diff --git a/Documentation~/TableOfContents.md b/Documentation~/TableOfContents.md index 6fae25dd..ca3e83e2 100644 --- a/Documentation~/TableOfContents.md +++ b/Documentation~/TableOfContents.md @@ -1,27 +1,27 @@ * [Overview](index.md) * Core ECS -** [Entities](ecs_entities.md) -*** [Worlds](world.md) -** [Components](ecs_components.md) -*** [General Purpose Components](component_data.md) -*** [Shared Components](shared_component_data.md) -*** [System State Components](system_state_components.md) -*** [Dynamic Buffer Components](dynamic_buffers.md) -** [System](ecs_systems.md) -*** [Component Systems](component_system.md) -*** [Job Component Systems](job_component_system.md) -*** [Entity Command Buffers](entity_command_buffer.md) -*** [System Update Order](system_update_order.md) -** [Accessing Entity Data](chunk_iteration.md) -*** [Using IJobProcessComponentData](entity_iteration_job.md) -*** [Using IJobChunk](chunk_iteration_job.md) -*** [Using ComponentSystem and ForEach](entity_iteration_foreach.md) -*** [Manual iteration](manual_iteration.md) -*** [Component Groups](component_group.md) -** [Versions and Generations](version_numbers.md) -** [Jobs in ECS](ecs_job_overview.md) -*** [ECS Job System extensions](ecs_job_extensions.md) + * [Entities](ecs_entities.md) + * [Worlds](world.md) + * [Components](ecs_components.md) + * [General Purpose Components](component_data.md) + * [Shared Components](shared_component_data.md) + * [System State Components](system_state_components.md) + * [Dynamic Buffer Components](dynamic_buffers.md) + * [System](ecs_systems.md) + * [Component Systems](component_system.md) + * [Job Component Systems](job_component_system.md) + * [Entity Command Buffers](entity_command_buffer.md) + * [System Update Order](system_update_order.md) + * [Accessing Entity Data](chunk_iteration.md) + * [Using IJobForEach](entity_iteration_job.md) + * [Using IJobChunk](chunk_iteration_job.md) + * [Using ComponentSystem and ForEach](entity_iteration_foreach.md) + * [Manual iteration](manual_iteration.md) + * [Component Groups](component_group.md) + * [Versions and Generations](version_numbers.md) + * [Jobs in ECS](ecs_job_overview.md) + * [ECS Job System extensions](ecs_job_extensions.md) * Creating Gameplay -** [Transforms](transform_system.md) -** [Rendering](gp_rendering.md) + * [Transforms](transform_system.md) + * [Rendering](gp_rendering.md) diff --git a/Documentation~/chunk_iteration.md b/Documentation~/chunk_iteration.md index b43e186e..f9ed9db5 100644 --- a/Documentation~/chunk_iteration.md +++ b/Documentation~/chunk_iteration.md @@ -9,14 +9,14 @@ In general, the most efficient way to iterate over your entities and components The ECS API provides a number of ways to accomplish iteration, each with its own performance implications and restrictions. You can iterate over ECS data in the following ways: -* [IJobProcessComponentData](entity_iteration_job.md) — the simplest efficient way to process component data entity by entity. +* [IJobForEach](entity_iteration_job.md) — the simplest efficient way to process component data entity by entity. -* [IJobProcessComponentDataWithEntity](entity_iteration_job.md#with-entity) — slightly more complex than IJobProcessComponentData, giving you access to the entity handle and array index of the entity you are processing. +* [IJobForEachWithEntity](entity_iteration_job.md#with-entity) — slightly more complex than IJobForEach, giving you access to the entity handle and array index of the entity you are processing. -* [IJobChunk](chunk_iteration_job.md) — iterates over the eligible blocks of memory (called a *Chunk*) containing matching entities. Your Job Execute() function can iterate over the Elements inside each chunk using a for loop. You can use IJobChunk for more complex situations than supported by IJobProcessComponentData, while maintaining maximum efficiency. +* [IJobChunk](chunk_iteration_job.md) — iterates over the eligible blocks of memory (called a *Chunk*) containing matching entities. Your Job Execute() function can iterate over the Elements inside each chunk using a for loop. You can use IJobChunk for more complex situations than supported by IJobForEach, while maintaining maximum efficiency. * [ComponentSystem](entity_iteration_foreach.md) — the ComponentSystem offers the Entities.ForEach delegate functions to help iterate over your entities. However, ForEach runs on the main thread, so typically, you should only use ComponentSystem implementations for tasks that must be carried out on the main thread anyway. * [Manual iteration](manual_iteration.md) — if the previous methods are insufficient, you can manually iterate over entities or chunks. For example, you can get a NativeArray containing entities or the chunks of the entities that you want to process and iterate over them using a Job, such as IJobParallelFor. -The [ComponentGroup](component_group.md) class provides a way to construct a view of your data that contains only the specific data you need for a given algorithm or process. Many of the iteration methods in the list above use a ComponentGroup, either explicitly or internally. \ No newline at end of file +The [EntityQuery](component_group.md) class provides a way to construct a view of your data that contains only the specific data you need for a given algorithm or process. Many of the iteration methods in the list above use a EntityQuery, either explicitly or internally. \ No newline at end of file diff --git a/Documentation~/chunk_iteration_job.md b/Documentation~/chunk_iteration_job.md index 08d7e417..5622fe75 100644 --- a/Documentation~/chunk_iteration_job.md +++ b/Documentation~/chunk_iteration_job.md @@ -2,38 +2,38 @@ You can implement IJobChunk inside a JobComponentSystem to iterate through your data by chunk. The JobComponentSystem calls your Execute() function once for each chunk that contains the entities that you want the system to process. You can then process the data inside each chunk, entity by entity. -Iterating with IJobChunk requires more code setup than does IJobProcessComponentData, but is also more explicit and represents the most direct access to the data, as it is actually stored. +Iterating with IJobChunk requires more code setup than does IJobForEach, but is also more explicit and represents the most direct access to the data, as it is actually stored. Another benefit of using iterating by chunks is that you can check whether an optional component is present in each chunk (with Archetype.Has) and process all the entities in the chunk accordingly. The steps involved in implementing an IJobChunk Job include: -1. Identify the entities that you want to process by creating a ComponentGroup. +1. Identify the entities that you want to process by creating a EntityQuery. 2. Defining the Job struct, including fields for ArchetypeChunkComponentType objects to identifying the types of components the Job directly accesses, specifying whether the Job reads or writes to those components. 3. Instantiating the Job struct and scheduling the Job in the system OnUpdate() function. 4. In the Execute() function, getting the NativeArray instances for the components the Job reads or writes and, finally, iterating over the current chunk to perform the desired work. The [ECS samples repository](https://github.com/Unity-Technologies/EntityComponentSystemSamples) contains a simple example, HelloCube_03_IJobChunk, that uses IJobChunk. -## Query for data with a ComponentGroup +## Query for data with a EntityQuery -A ComponentGroup defines the set of component types that an archetype must contain for the system to process its associated chunks and entities. An archetype can have additional components as well, but it must have at least those defined by the ComponentGroup. You can also exclude archetypes that contain specific types of components. +A EntityQuery defines the set of component types that an archetype must contain for the system to process its associated chunks and entities. An archetype can have additional components as well, but it must have at least those defined by the EntityQuery. You can also exclude archetypes that contain specific types of components. -For simple queries, you can use the JobComponentSystem.GetComponentGroup() function, passing in the component types: +For simple queries, you can use the JobComponentSystem.GetEntityQuery() function, passing in the component types: ``` c# public class RotationSpeedSystem : JobComponentSystem { - private ComponentGroup m_Group; - protected override void OnCreateManager() + private EntityQuery m_Group; + protected override void OnCreate() { - m_Group = GetComponentGroup(typeof(RotationQuaternion), ComponentType.ReadOnly()); + m_Group = GetEntityQuery(typeof(RotationQuaternion), ComponentType.ReadOnly()); } //… } ```` -For more complex situations, you can use an EntityArchetypeQuery. An EntityArchetypeQuery provides a flexible query mechanism to specify the component types: +For more complex situations, you can use an EntityQueryDesc. An EntityQueryDesc provides a flexible query mechanism to specify the component types: * `All` = All component types in this array must exist in the archetype * `Any` = At least one of the component types in this array must exist in the archetype @@ -42,48 +42,48 @@ For more complex situations, you can use an EntityArchetypeQuery. An EntityArche For example, the following query includes archetypes containing the RotationQuaternion and RotationSpeed components, but excludes any archetypes containing the Frozen component: ``` c# -protected override void OnCreateManager() +protected override void OnCreate() { - var query = new EntityArchetypeQuery + var query = new EntityQueryDesc { None = new ComponentType[]{ typeof(Frozen) }, All = new ComponentType[]{ typeof(RotationQuaternion), ComponentType.ReadOnly() } } }; - m_Group = GetComponentGroup(query); + m_Group = GetEntityQuery(query); } ``` The query uses `ComponentType.ReadOnly` instead of the simpler `typeof` expression to designate that the system does not write to RotationSpeed. -You can also combine multiple queries by passing an array of EntityArchetypeQuery objects rather than a single instance. Each query is combined using a logical OR operation. The following example selects an archetypes that contain a RotationQuaternion component or a RotationSpeed component (or both): +You can also combine multiple queries by passing an array of EntityQueryDesc objects rather than a single instance. Each query is combined using a logical OR operation. The following example selects an archetypes that contain a RotationQuaternion component or a RotationSpeed component (or both): ``` c# -protected override void OnCreateManager() +protected override void OnCreate() { - var query0 = new EntityArchetypeQuery + var query0 = new EntityQueryDesc { All = new ComponentType[] {typeof(RotationQuaternion)} }; - var query1 = new EntityArchetypeQuery + var query1 = new EntityQueryDesc { All = new ComponentType[] {typeof(RotationSpeed)} }; - m_Group = GetComponentGroup(new EntityArchetypeQuery[] {query0, query1}); + m_Group = GetEntityQuery(new EntityQueryDesc[] {query0, query1}); } ``` -**Note:** Do not include completely optional components in the EntityArchetypeQuery. To handle optional components, use the `chunk.Has()` method inside `IJobChunk.Execute()` to determine whether the current ArchetypeChunk has the optional component or not. Since all entities within the same chunk have the same components, you only need to check whether an optional component exists once per chunk -- not once per entity. +**Note:** Do not include completely optional components in the EntityQueryDesc. To handle optional components, use the `chunk.Has()` method inside `IJobChunk.Execute()` to determine whether the current ArchetypeChunk has the optional component or not. Since all entities within the same chunk have the same components, you only need to check whether an optional component exists once per chunk -- not once per entity. -For efficiency and to avoid needless creation of garbage-collected reference types, you should create the ComponentGroups for a system in the system’s OnCreateManager() function and store the result in an instance variable. (In the above examples, the `m_Group` variable is used for this purpose.) +For efficiency and to avoid needless creation of garbage-collected reference types, you should create the EntityQueries for a system in the system’s OnCreate() function and store the result in an instance variable. (In the above examples, the `m_Group` variable is used for this purpose.) ### ## Define the IJobChunk struct The IJobChunk struct defines fields for the data the Job needs when it runs, as well as the Job’s Execute() method. -In order to access the component arrays inside the chunks that the system passes to your Execute() method, you must create an ArchetypeChunkComponentType object for each type of component that the Job reads or writes. These objects allow you to get instances of the NativeArrays providing access to the components of an entity. Include all the components referenced in the Job’s ComponentGroup that the Execute method reads or writes. You can also provide ArchetypeChunkComponentType variables for optional component types that you do not include in the ComponentGroup. (You must check to make sure that the current chunk has an optional component before trying to access it.) +In order to access the component arrays inside the chunks that the system passes to your Execute() method, you must create an ArchetypeChunkComponentType object for each type of component that the Job reads or writes. These objects allow you to get instances of the NativeArrays providing access to the components of an entity. Include all the components referenced in the Job’s EntityQuery that the Execute method reads or writes. You can also provide ArchetypeChunkComponentType variables for optional component types that you do not include in the EntityQuery. (You must check to make sure that the current chunk has an optional component before trying to access it.) For example, the HelloCube_03_IJobChunk example declares a Job struct that defines ArchetypeChunkComponentType variables for two components, RotationQuaternion and RotationSpeed: @@ -140,7 +140,7 @@ for (var i = 0; i < chunk.Count; i++) } ``` -If you the `Any` filter in your EntityArchetypeQuery or have completely optional components that don’t appear in the query at all, you can use the `ArchetypeChunk.Has` function to test whether the current chunk contains the one of those components before using it: +If you the `Any` filter in your EntityQueryDesc or have completely optional components that don’t appear in the query at all, you can use the `ArchetypeChunk.Has` function to test whether the current chunk contains the one of those components before using it: if (chunk.Has(OptionalCompType)) {//...} @@ -149,20 +149,20 @@ __Note:__ If you use a concurrent entity command buffer, pass the chunkIndex arg ## Skipping chunks with unchanged entities -If you only need to update entities when a component value has changed, you can add that component type to the change filter of the ComponentGroup used to select the entities and chunks for the job. For example, if you have a system that reads two components and only needs to update a third when one of the first two has changed, you could use a ComponentGroup as follows: +If you only need to update entities when a component value has changed, you can add that component type to the change filter of the EntityQuery used to select the entities and chunks for the job. For example, if you have a system that reads two components and only needs to update a third when one of the first two has changed, you could use a EntityQuery as follows: ``` c# -ComponentGroup m_Group; -protected override void OnCreateManager() +EntityQuery m_Group; +protected override void OnCreate() { - m_Group = GetComponentGroup(typeof(Output), + m_Group = GetEntityQuery(typeof(Output), ComponentType.ReadOnly(), ComponentType.ReadOnly()); m_Group.SetFilterChanged(new ComponentType{ typeof(InputA), typeof(InputB)}); } ``` -The ComponentGroup change filter supports up to two components. If you want to check more or aren't using a ComponentGroup, you can make the check manually. To make this check, compare the chunk’s change version for the component to the system’s LastSystemVersion using the `ArchetypeChunk.DidChange()` function. If this function returns false, you can skip the current chunk altogether since none of the components of that type have changed since the last time the system ran. +The EntityQuery change filter supports up to two components. If you want to check more or aren't using a EntityQuery, you can make the check manually. To make this check, compare the chunk’s change version for the component to the system’s LastSystemVersion using the `ArchetypeChunk.DidChange()` function. If this function returns false, you can skip the current chunk altogether since none of the components of that type have changed since the last time the system ran. The LastSystemVersion from the system must be passed into the Job using a struct field: @@ -214,6 +214,6 @@ protected override JobHandle OnUpdate(JobHandle inputDependencies) } ``` -When you call the GetArchetypeChunkComponentType function to set your component type variables, make sure that you set the isReadOnly to true for components that the Job reads, but doesn’t write. Setting these parameters correctly can have a significant impact on how efficiently the ECS framework can schedule your Jobs. These access mode settings must match their equivalents in both the struct definition, and the ComponentGroup. +When you call the GetArchetypeChunkComponentType function to set your component type variables, make sure that you set the isReadOnly to true for components that the Job reads, but doesn’t write. Setting these parameters correctly can have a significant impact on how efficiently the ECS framework can schedule your Jobs. These access mode settings must match their equivalents in both the struct definition, and the EntityQuery. Do not cache the return value of GetArchetypeChunkComponentType in a system class variable. The function must be called every time the system runs and the updated value passed to the Job. diff --git a/Documentation~/component_group.md b/Documentation~/component_group.md index 53bc3088..24649ad3 100644 --- a/Documentation~/component_group.md +++ b/Documentation~/component_group.md @@ -1,37 +1,37 @@ --- uid: ecs-component-group --- -# Querying for data using a ComponentGroup +# Querying for data using a EntityQuery -The first step to reading or writing data is finding that data. Data in the ECS framework is stored in components, which are grouped together in memory according to the archetype of the entity to which they belong. To define a view into your ECS data that contains only the specific data you need for a given algorithm or process, you can construct a ComponentGroup. +The first step to reading or writing data is finding that data. Data in the ECS framework is stored in components, which are grouped together in memory according to the archetype of the entity to which they belong. To define a view into your ECS data that contains only the specific data you need for a given algorithm or process, you can construct a EntityQuery. -After creating a ComponentGroup, you can +After creating a EntityQuery, you can * Run a Job to process the entities and components selected for the view * Get a NativeArray containing all the selected entities * Get NativeArrays of the selected components (by component type) -The entity and component arrays returned by a ComponentGroup are guaranteed to be "parallel", that is, the same index value always applies to the same entity in any array. +The entity and component arrays returned by a EntityQuery are guaranteed to be "parallel", that is, the same index value always applies to the same entity in any array. -**Note:** that the `ComponentSystem.Entites.ForEach` delegates and IJobProcessComponentData create internal ComponentGroups based on the component types and attributes you specify for these APIs. +**Note:** that the `ComponentSystem.Entites.ForEach` delegates and IJobForEach create internal EntityQueries based on the component types and attributes you specify for these APIs. - + ## Defining a query -A ComponentGroup query defines the set of component types that an archetype must contain in order for its chunks and entities to be included in the view. You can also exclude archetypes that contain specific types of components. +A EntityQuery query defines the set of component types that an archetype must contain in order for its chunks and entities to be included in the view. You can also exclude archetypes that contain specific types of components. -For simple queries, you can create a ComponentGroup based on an array of component types. The following example defines a ComponentGroup that finds all entities with both RotationQuaternion and RotationSpeed components. +For simple queries, you can create a EntityQuery based on an array of component types. The following example defines a EntityQuery that finds all entities with both RotationQuaternion and RotationSpeed components. ``` c# -ComponentGroup m_Group = GetComponentGroup(typeof(RotationQuaternion), ComponentType.ReadOnly()); +EntityQuery m_Group = GetEntityQuery(typeof(RotationQuaternion), ComponentType.ReadOnly()); ```` The query uses `ComponentType.ReadOnly` instead of the simpler `typeof` expression to designate that the system does not write to RotationSpeed. Always specify read only when possible, since there are fewer constraints on read access to data, which can help the Job scheduler execute your Jobs more efficiently. -### EntityArchetypeQuery +### EntityQueryDesc -For more complex queries, you can use an EntityArchetypeQuery to create the ComponentGroup. An EntityArchetypeQuery provides a flexible query mechanism to specify which archetypes to select based on the following sets of components: +For more complex queries, you can use an EntityQueryDesc to create the EntityQuery. An EntityQueryDesc provides a flexible query mechanism to specify which archetypes to select based on the following sets of components: * `All` = All component types in this array must exist in the archetype * `Any` = At least one of the component types in this array must exist in the archetype @@ -40,19 +40,19 @@ For more complex queries, you can use an EntityArchetypeQuery to create the Comp For example, the following query includes archetypes containing the RotationQuaternion and RotationSpeed components, but excludes any archetypes containing the Frozen component: ``` c# -var query = new EntityArchetypeQuery +var query = new EntityQueryDesc { None = new ComponentType[]{ typeof(Frozen) }, All = new ComponentType[]{ typeof(RotationQuaternion), ComponentType.ReadOnly() } } -ComponentGroup m_Group = GetComponentGroup(query); +EntityQuery m_Group = GetEntityQuery(query); ``` -**Note:** Do not include completely optional components in the EntityArchetypeQuery. To handle optional components, use the `ArchetypeChunk.Has()` method to determine whether a chunk contains the optional component or not. Since all entities within the same chunk have the same components, you only need to check whether an optional component exists once per chunk -- not once per entity. +**Note:** Do not include completely optional components in the EntityQueryDesc. To handle optional components, use the `ArchetypeChunk.Has()` method to determine whether a chunk contains the optional component or not. Since all entities within the same chunk have the same components, you only need to check whether an optional component exists once per chunk -- not once per entity. ### Query options -When you create an EntityArchetypeQuery, you can set its `Options` variable. The options allow for specialized queries (normally you do not need to set them): +When you create an EntityQueryDesc, you can set its `Options` variable. The options allow for specialized queries (normally you do not need to set them): * Default — no options set; the query behaves normally. * IncludePrefab — includes archetypes containing the special Prefab tag component. @@ -73,11 +73,11 @@ public struct C2: IComponentData{} public struct C3: IComponentData{} // ... In a system: -var query = new EntityArchetypeQuery{ +var query = new EntityQueryDesc{ All = new ComponentType{typeof(C1), ComponentType.ReadOnly()}, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryDescOptions.FilterWriteGroup }; -var m_group = GetComponentGroup(query); +var m_group = GetEntityQuery(query); ``` This query excludes any entities with both C2 and C3 because C2 is not explicitly included in the query. While you could design this into the query using `None`, doing it through a Write Group provides an important benefit: you don't need to alter the queries used by other systems (as long as these systems also use Write Groups). @@ -88,45 +88,45 @@ See [Write Groups](ecs_write_groups.md) for more information. ### Combining queries -You can combine multiple queries by passing an array of EntityArchetypeQuery objects rather than a single instance. Each query is combined using a logical OR operation. The following example selects an archetypes that contain a RotationQuaternion component or a RotationSpeed component (or both): +You can combine multiple queries by passing an array of EntityQueryDesc objects rather than a single instance. Each query is combined using a logical OR operation. The following example selects an archetypes that contain a RotationQuaternion component or a RotationSpeed component (or both): ``` c# -var query0 = new EntityArchetypeQuery +var query0 = new EntityQueryDesc { All = new ComponentType[] {typeof(RotationQuaternion)} }; -var query1 = new EntityArchetypeQuery +var query1 = new EntityQueryDesc { All = new ComponentType[] {typeof(RotationSpeed)} }; -ComponentGroup m_Group = GetComponentGroup(new EntityArchetypeQuery[] {query0, query1}); +EntityQuery m_Group = GetEntityQuery(new EntityQueryDesc[] {query0, query1}); ``` -## Creating a ComponentGroup +## Creating a EntityQuery -Outside a system class, you can create a ComponentGroup with the `EntityManager.CreateComponentGroup()` function: +Outside a system class, you can create a EntityQuery with the `EntityManager.CreateEntityQuery()` function: ``` c# -ComponentGroup m_Group = CreateComponentGroup(typeof(RotationQuaternion), ComponentType.ReadOnly()); +EntityQuery m_Group = CreateEntityQuery(typeof(RotationQuaternion), ComponentType.ReadOnly()); ``` -However, in a system class, you must use the `GetComponentGroup()` function: +However, in a system class, you must use the `GetEntityQuery()` function: ``` c# public class RotationSpeedSystem : JobComponentSystem { - private ComponentGroup m_Group; - protected override void OnCreateManager() + private EntityQuery m_Group; + protected override void OnCreate() { - m_Group = GetComponentGroup(typeof(RotationQuaternion), ComponentType.ReadOnly()); + m_Group = GetEntityQuery(typeof(RotationQuaternion), ComponentType.ReadOnly()); } //… } ``` -When you plan to reuse the same view, you should cache the ComponentGroup instance, if possible, instead of creating a new one for each use. For example, in a system, you can create the ComponentGroup in the system’s `OnCreateManager()` function and store the result in an instance variable. The `m_Group` variable in the above example is used for this purpose. +When you plan to reuse the same view, you should cache the EntityQuery instance, if possible, instead of creating a new one for each use. For example, in a system, you can create the EntityQuery in the system’s `OnCreate()` function and store the result in an instance variable. The `m_Group` variable in the above example is used for this purpose. ## Defining filters @@ -137,7 +137,7 @@ In addition to defining which components must be included or excluded from the q ### Shared component filters -To use a shared component filter, first include the shared component in the ComponentGroup (along with other needed components), and then call the `SetFilter()` function, passing in a struct of the same ISharedComponent type that contains the values to select. All values must match. You can add up to two different shared components to the filter. +To use a shared component filter, first include the shared component in the EntityQuery (along with other needed components), and then call the `SetFilter()` function, passing in a struct of the same ISharedComponent type that contains the values to select. All values must match. You can add up to two different shared components to the filter. You can change the filter at any time, but changing the filter does not change any existing arrays of entities or components that you received from the group `ToComponentDataArray()` or `ToEntityArray()` functions. You must recreate these arrays. @@ -151,11 +151,11 @@ struct SharedGrouping : ISharedComponentData class ImpulseSystem : ComponentSystem { - ComponentGroup m_Group; + EntityQuery m_Group; - protected override void OnCreateManager(int capacity) + protected override void OnCreate(int capacity) { - m_Group = GetComponentGroup(typeof(Position), typeof(Displacement), typeof(SharedGrouping)); + m_Group = GetEntityQuery(typeof(Position), typeof(Displacement), typeof(SharedGrouping)); } protected override void OnUpdate() @@ -174,12 +174,12 @@ class ImpulseSystem : ComponentSystem ### Change filters -If you only need to update entities when a component value has changed, you can add that component to the ComponentGroup filter using the `SetFilterChanged()` function. For example, the following ComponentGroup only includes entities from chunks in which another system has already written to the Translation component: +If you only need to update entities when a component value has changed, you can add that component to the EntityQuery filter using the `SetFilterChanged()` function. For example, the following EntityQuery only includes entities from chunks in which another system has already written to the Translation component: ``` c# -protected override void OnCreateManager(int capacity) +protected override void OnCreate(int capacity) { - m_Group = GetComponentGroup(typeof(LocalToWorld), ComponentType.ReadOnly()); + m_Group = GetEntityQuery(typeof(LocalToWorld), ComponentType.ReadOnly()); m_Group.SetFilterChanged(typeof(Translation)); } @@ -189,7 +189,7 @@ Note that for efficiency, the change filter applies to whole chunks not individu ## Executing the query -A ComponentGroup executes its query when you use the ComponentGroup in a Job or you call one of the ComponentGroup methods that returns arrays of entities, components, or chunks in the view: +A EntityQuery executes its query when you use the EntityQuery in a Job or you call one of the EntityQuery methods that returns arrays of entities, components, or chunks in the view: * `ToEntityArray()` returns an array of the selected entities. * `ToComponentDataArray` returns an array of the components of type T for the selected entities. @@ -199,7 +199,7 @@ A ComponentGroup executes its query when you use the ComponentGroup in a Job or ### In Jobs -In a JobComponentSystem, pass the ComponentGroup object to the system's `Schedule()` method. In the following example, from the HelloCube_03_IJobChunk sample, the `m_Group` argument is the ComponentGroup object +In a JobComponentSystem, pass the EntityQuery object to the system's `Schedule()` method. In the following example, from the HelloCube_03_IJobChunk sample, the `m_Group` argument is the EntityQuery object ``` c# // OnUpdate runs on the main thread. @@ -219,5 +219,5 @@ protected override JobHandle OnUpdate(JobHandle inputDependencies) } ``` -A ComponentGroup uses Jobs internally to create the required arrays. When you pass the group to the `Schedule()` method, the ComponentGroup Jobs are scheduled along with the system's own Jobs and can take advantage of parallel processing. +A EntityQuery uses Jobs internally to create the required arrays. When you pass the group to the `Schedule()` method, the EntityQuery Jobs are scheduled along with the system's own Jobs and can take advantage of parallel processing. diff --git a/Documentation~/component_system.md b/Documentation~/component_system.md index 3201680e..48602d23 100644 --- a/Documentation~/component_system.md +++ b/Documentation~/component_system.md @@ -3,7 +3,7 @@ uid: ecs-component-system --- # ComponentSystem -A `ComponentSystem` in Unity (also known as a system in standard ECS terms) performs operations on [entities](entity.md). A `ComponentSystem` cannot contain instance data. To put this in terms of the old Unity system, this is somewhat similar to an old [Component](https://docs.unity3d.com/Manual/Components.html) class, but one that **only contains methods**. One `ComponentSystem` is responsible for updating all entities with a matching set of components (that is defined within a struct called a [ComponentGroup](component_group.md)). +A `ComponentSystem` in Unity (also known as a system in standard ECS terms) performs operations on [entities](entity.md). A `ComponentSystem` cannot contain instance data. To put this in terms of the old Unity system, this is somewhat similar to an old [Component](https://docs.unity3d.com/Manual/Components.html) class, but one that **only contains methods**. One `ComponentSystem` is responsible for updating all entities with a matching set of components (that is defined within a struct called a [EntityQuery](component_group.md)). Unity ECS provides an abstract class called `ComponentSystem` that you can extend in your code. diff --git a/Documentation~/ecs_components.md b/Documentation~/ecs_components.md index 17f37556..f7951929 100644 --- a/Documentation~/ecs_components.md +++ b/Documentation~/ecs_components.md @@ -13,7 +13,7 @@ uid: ecs-components > BufferComponent > ChunkComponent > Prefab and Disabled IComponentData -> ComponentGroup and filtering +> EntityQuery and filtering --> Components are one of the three principle elements of an Entity Component System architecture. They represent the data of your game or program. [Entities](ecs_entities.md) are essentially identifiers that index your collections of components [Systems](ecs_systems.md) provide the behavior. diff --git a/Documentation~/ecs_in_detail.md b/Documentation~/ecs_in_detail.md index fd52bae7..49cc67e1 100644 --- a/Documentation~/ecs_in_detail.md +++ b/Documentation~/ecs_in_detail.md @@ -23,11 +23,11 @@ If you need to access `ComponentData` on another entity, the only stable way of For more information, see the [ComponentDataFromEntity](component_data_from_entity.md) reference page. -## ComponentGroup +## EntityQuery -The `ComponentGroup` is the foundation class on top of which all iteration methods are built `foreach`, `IJobProcessComponentData`, etc.). Essentially a `ComponentGroup` is constructed with a set of required components and or subtractive components. `ComponentGroup` lets you extract individual arrays of entities based on their components. +The `EntityQuery` is the foundation class on top of which all iteration methods are built `foreach`, `IJobForEach`, etc.). Essentially a `EntityQuery` is constructed with a set of required components and or subtractive components. `EntityQuery` lets you extract individual arrays of entities based on their components. -For more information, see the [ComponentGroup](component_group.md) reference page. +For more information, see the [EntityQuery](component_group.md) reference page. ## Entity diff --git a/Documentation~/ecs_job_overview.md b/Documentation~/ecs_job_overview.md index 14c7543c..bbfa4610 100644 --- a/Documentation~/ecs_job_overview.md +++ b/Documentation~/ecs_job_overview.md @@ -17,7 +17,7 @@ For example, the following system updates positions: public class MovementSpeedSystem : JobComponentSystem { [BurstCompile] - struct MovementSpeedJob : IJobProcessComponentData + struct MovementSpeedJob : IJobForEach { public float dT; diff --git a/Documentation~/ecs_project_status.md b/Documentation~/ecs_project_status.md index 02743642..97736a8f 100644 --- a/Documentation~/ecs_project_status.md +++ b/Documentation~/ecs_project_status.md @@ -8,7 +8,7 @@ uid: ecs-project-status As the ECS APIs change, so too will these best practices. For the time being, these are our best recommendations when using the ECS APIs. ### Do's -* Use IJobProcessComponentData for processing many entities' components in a job. +* Use IJobForEach for processing many entities' components in a job. * Use chunk iteration if you need finer-grained control. ### Don'ts diff --git a/Documentation~/entity_command_buffer.md b/Documentation~/entity_command_buffer.md index 50abb3d3..cc41a0e7 100644 --- a/Documentation~/entity_command_buffer.md +++ b/Documentation~/entity_command_buffer.md @@ -6,7 +6,7 @@ uid: ecs-entity-command-buffer The `EntityCommandBuffer` class solves two important problems: 1. When you're in a job, you can't access the `EntityManager`. -2. When you access the `EntityManager` (to say, create an entity) you invalidate all injected arrays and `ComponentGroup` objects. +2. When you access the `EntityManager` (to say, create an entity) you invalidate all injected arrays and `EntityQuery` objects. The `EntityCommandBuffer` abstraction allows you to queue up changes (from either a job or from the main thread) so that they can take effect later on the main thread. There are two ways to use a `EntityCommandBuffer`: diff --git a/Documentation~/entity_iteration_job.md b/Documentation~/entity_iteration_job.md index bd9b0944..c40290fa 100644 --- a/Documentation~/entity_iteration_job.md +++ b/Documentation~/entity_iteration_job.md @@ -1,17 +1,17 @@ -# Using IJobProcessComponentData +# Using IJobForEach -You can define an `IJobProcessComponentData` Job in a JobComponentSystem to read and write component data. +You can define an `IJobForEach` Job in a JobComponentSystem to read and write component data. -When the Job runs, the ECS framework finds all of the entities that have the required components and calls the Job’s Execute() function for each of them. The data is processed in the order it is laid out in memory and the Job runs in parallel, so a `IJobProcessComponentData` combines simplicity and efficiency. +When the Job runs, the ECS framework finds all of the entities that have the required components and calls the Job’s Execute() function for each of them. The data is processed in the order it is laid out in memory and the Job runs in parallel, so a `IJobForEach` combines simplicity and efficiency. -The following example illustrates a simple system that uses `IJobProcessComponentData`. The Job reads a `RotationSpeed` component and writes to a `RotationQuaternion` component. +The following example illustrates a simple system that uses `IJobForEach`. The Job reads a `RotationSpeed` component and writes to a `RotationQuaternion` component. ```c# public class RotationSpeedSystem : JobComponentSystem { // Use the [BurstCompile] attribute to compile a job with Burst. [BurstCompile] - struct RotationSpeedJob : IJobProcessComponentData + struct RotationSpeedJob : IJobForEach { public float DeltaTime; // The [ReadOnly] attribute tells the job scheduler that this job will not write to rotSpeed @@ -39,11 +39,11 @@ protected override JobHandle OnUpdate(JobHandle inputDependencies) Note: this system is part of the HelloCubes_02 example in the [ECS samples repository](https://github.com/Unity-Technologies/EntityComponentSystemSamples). -## Defining the IJobProcessComponentData signature +## Defining the IJobForEach signature -The `IJobProcessComponentData` struct signature identifies which components your system operates on: +The `IJobForEach` struct signature identifies which components your system operates on: - struct RotationSpeedJob : IJobProcessComponentData + struct RotationSpeedJob : IJobForEach You can also use the following attributes to modify which entities the Job selects: @@ -55,13 +55,13 @@ For example, the following Job definition selects entities that have archetypes [ExcludeComponent(typeof(Frozen))] [RequireComponentTag(typeof(Gravity))] [BurstCompile] - struct RotationSpeedJob : IJobProcessComponentData + struct RotationSpeedJob : IJobForEach -If you need a more complex query to select the entities to operate upon, you can use an IJobChunk Job instead of IJobProcessComponentData. +If you need a more complex query to select the entities to operate upon, you can use an IJobChunk Job instead of IJobForEach. ## Writing the Execute() method -The JobComponentSystem calls your Execute() method for each eligible entity, passing in the components identified by the IJobProcessComponentData signature. Thus, the parameters of your Execute() function must match the generic arguments you defined for the struct. +The JobComponentSystem calls your Execute() method for each eligible entity, passing in the components identified by the IJobForEach signature. Thus, the parameters of your Execute() function must match the generic arguments you defined for the struct. For example, the following Execute() method reads a RotationSpeed component and reads and writes a RotationQuaternion component. (Read/write is the default, so no attribute is needed.) @@ -78,9 +78,9 @@ Identifying read-only and write-only components allows the Job scheduler to sche Note that for efficiency, the change filter works on whole chunks of entities; it does not track individual entities. If a chunk has been accessed by another Job which had the ability to write to that type of component, then the ECS framework considers that chunk to have changed and includes all of the entities in the Job. Otherwise, the ECS framework excludes the entities in that chunk entirely. -## Using IJobProcessComponentDataWithEntity +## Using IJobForEachWithEntity -The Jobs implementing the IJobProcessComponentDataWithEntity interface behave much the same as those implementing IJobProcessComponentData. The difference is that the Execute() function signature in IJobProcessComponentDataWithEntity provides you with the Entity object for the current entity and the index into the extended, parallel arrays of components. +The Jobs implementing the IJobForEachWithEntity interface behave much the same as those implementing IJobForEach. The difference is that the Execute() function signature in IJobForEachWithEntity provides you with the Entity object for the current entity and the index into the extended, parallel arrays of components. ### Using the Entity parameter @@ -94,12 +94,12 @@ public class HelloSpawnerSystem : JobComponentSystem // EndFrameBarrier provides the CommandBuffer EndFrameBarrier m_EndFrameBarrier; - protected override void OnCreateManager() + protected override void OnCreate() { // Cache the EndFrameBarrier in a field, so we don't have to get it every frame - m_EndFrameBarrier = World.GetOrCreateManager(); + m_EndFrameBarrier = World.GetOrCreateSystem(); } - struct SpawnJob : IJobProcessComponentDataWithEntity + struct SpawnJob : IJobForEachWithEntity { public EntityCommandBuffer CommandBuffer; public void Execute(Entity entity, int index, [ReadOnly] ref HelloSpawner spawner, @@ -136,12 +136,12 @@ public class HelloSpawnerSystem : JobComponentSystem } ``` -__Note:__ this example uses IJobProcessComponentData.ScheduleSingle(), which performs the Job on a single thread. If you used the Schedule() method instead, the system uses parallel jobs to process the entities. In the parallel case, you must use a concurrent entity command buffer (EntityCommandBuffer.Concurrent). +__Note:__ this example uses IJobForEach.ScheduleSingle(), which performs the Job on a single thread. If you used the Schedule() method instead, the system uses parallel jobs to process the entities. In the parallel case, you must use a concurrent entity command buffer (EntityCommandBuffer.Concurrent). See the [ECS samples repository](https://github.com/Unity-Technologies/EntityComponentSystemSamples) for the full example source code. ### Using the index parameter -You can use the index when adding a command to a concurrent command buffer. You use concurrent command buffers when running Jobs that process entities in parallel. In an IJobProcessComponentDataWithEntity Job, the Job System process entities in parallel when you use the Schedule() method rather than the ScheduleSingle() method used in the example above. Concurrent command buffers should always be used for parallel Jobs to guarantee thread safety and deterministic execution of the buffer commands. +You can use the index when adding a command to a concurrent command buffer. You use concurrent command buffers when running Jobs that process entities in parallel. In an IJobForEachWithEntity Job, the Job System process entities in parallel when you use the Schedule() method rather than the ScheduleSingle() method used in the example above. Concurrent command buffers should always be used for parallel Jobs to guarantee thread safety and deterministic execution of the buffer commands. You can also use the index to reference the same entities across Jobs within the same system. For example, if you need to process a set of entities in multiple passes and collect temporary data along the way, you can use the index to insert the temporary data into a NativeArray in one Job and then use the index to access that data in a subsequent Job. (Naturally, you have to pass the same NativeArray to both Jobs.) diff --git a/Documentation~/entity_manager.md b/Documentation~/entity_manager.md index 0ae63575..b642796c 100644 --- a/Documentation~/entity_manager.md +++ b/Documentation~/entity_manager.md @@ -3,7 +3,7 @@ uid: ecs-entity-manager --- # EntityManager -The `EntityManager` owns `EntityData`, [EntityArchetypes](entity_archetype.md), [SharedComponentData](shared_component_data.md) and [ComponentGroup](component_group.md). +The `EntityManager` owns `EntityData`, [EntityArchetypes](entity_archetype.md), [SharedComponentData](shared_component_data.md) and [EntityQuery](component_group.md). `EntityManager` is where you find APIs to create entities, check if an entity is still alive, instantiate entities and add or remove components. diff --git a/Documentation~/filter.yml b/Documentation~/filter.yml new file mode 100644 index 00000000..d17fb0bd --- /dev/null +++ b/Documentation~/filter.yml @@ -0,0 +1,37 @@ +apiRules: + - exclude: + # inherited Object methods + uidRegex: ^System\.Object\..*$ + type: Method + - exclude: + # mentioning types from System.* namespace + uidRegex: ^System\..*$ + type: Type + - exclude: + hasAttribute: + uid: System.ObsoleteAttribute + type: Member + - exclude: + hasAttribute: + uid: System.ObsoleteAttribute + type: Type + - include: + uidRegex: IJobForEach`6 + type: Interface + - include: + uidRegex: IJobForEachWithEntity`6 + type: Interface + - exclude: + uidRegex: IJobForEach + type: Interface + - exclude: + uidRegex: Unity\.Entities\.JobForEachExtensions\.IBaseJobForEach_ + type: Interface + - exclude: + uidRegex: Unity\.Entities.EntityQueryBuilder + type: Delegate + - exclude: + uidRegex: Unity\.Entities.EntityQueryBuilder\.ForEach``\d + - exclude: + uidRegex: Tests$ + type: Namespace diff --git a/Documentation~/images/sec1-1.png b/Documentation~/images/sec1-1.png new file mode 100644 index 00000000..594d1c4c Binary files /dev/null and b/Documentation~/images/sec1-1.png differ diff --git a/Documentation~/images/sec1-2.png b/Documentation~/images/sec1-2.png new file mode 100644 index 00000000..a9c48e28 Binary files /dev/null and b/Documentation~/images/sec1-2.png differ diff --git a/Documentation~/images/sec2-1.png b/Documentation~/images/sec2-1.png new file mode 100644 index 00000000..a1eb4d43 Binary files /dev/null and b/Documentation~/images/sec2-1.png differ diff --git a/Documentation~/images/sec2-2.png b/Documentation~/images/sec2-2.png new file mode 100644 index 00000000..c510d2c7 Binary files /dev/null and b/Documentation~/images/sec2-2.png differ diff --git a/Documentation~/images/sec2-3.png b/Documentation~/images/sec2-3.png new file mode 100644 index 00000000..86df6178 Binary files /dev/null and b/Documentation~/images/sec2-3.png differ diff --git a/Documentation~/images/sec4-1.png b/Documentation~/images/sec4-1.png new file mode 100644 index 00000000..2afea0b7 Binary files /dev/null and b/Documentation~/images/sec4-1.png differ diff --git a/Documentation~/images/sec4-2.png b/Documentation~/images/sec4-2.png new file mode 100644 index 00000000..96e3a2d0 Binary files /dev/null and b/Documentation~/images/sec4-2.png differ diff --git a/Documentation~/images/sec4-3.png b/Documentation~/images/sec4-3.png new file mode 100644 index 00000000..46d70a21 Binary files /dev/null and b/Documentation~/images/sec4-3.png differ diff --git a/Documentation~/images/sec4-4.png b/Documentation~/images/sec4-4.png new file mode 100644 index 00000000..0f5d78db Binary files /dev/null and b/Documentation~/images/sec4-4.png differ diff --git a/Documentation~/images/sec4-5.png b/Documentation~/images/sec4-5.png new file mode 100644 index 00000000..aa61d923 Binary files /dev/null and b/Documentation~/images/sec4-5.png differ diff --git a/Documentation~/images/sec5-1.png b/Documentation~/images/sec5-1.png new file mode 100644 index 00000000..dc3a9ab1 Binary files /dev/null and b/Documentation~/images/sec5-1.png differ diff --git a/Documentation~/images/sec5-2.png b/Documentation~/images/sec5-2.png new file mode 100644 index 00000000..d1ee8635 Binary files /dev/null and b/Documentation~/images/sec5-2.png differ diff --git a/Documentation~/images/sec5-3.png b/Documentation~/images/sec5-3.png new file mode 100644 index 00000000..89690499 Binary files /dev/null and b/Documentation~/images/sec5-3.png differ diff --git a/Documentation~/images/sec5-4.png b/Documentation~/images/sec5-4.png new file mode 100644 index 00000000..248c0113 Binary files /dev/null and b/Documentation~/images/sec5-4.png differ diff --git a/Documentation~/images/sec5-5.png b/Documentation~/images/sec5-5.png new file mode 100644 index 00000000..98ceda02 Binary files /dev/null and b/Documentation~/images/sec5-5.png differ diff --git a/Documentation~/images/sec5-6.png b/Documentation~/images/sec5-6.png new file mode 100644 index 00000000..432f1007 Binary files /dev/null and b/Documentation~/images/sec5-6.png differ diff --git a/Documentation~/images/sec5-7.png b/Documentation~/images/sec5-7.png new file mode 100644 index 00000000..306c0657 Binary files /dev/null and b/Documentation~/images/sec5-7.png differ diff --git a/Documentation~/job_component_system.md b/Documentation~/job_component_system.md index 4b1651d1..4b32a22c 100644 --- a/Documentation~/job_component_system.md +++ b/Documentation~/job_component_system.md @@ -11,7 +11,7 @@ Managing dependencies is hard. This is why in `JobComponentSystem` we are doing public class RotationSpeedSystem : JobComponentSystem { [BurstCompile] - struct RotationSpeedRotation : IJobProcessComponentData + struct RotationSpeedRotation : IJobForEach { public float dt; @@ -41,10 +41,10 @@ Thus if a system writes to component `A`, and another system later on reads from ## Dependency management is conservative & deterministic -Dependency management is conservative. `ComponentSystem` simply tracks all `ComponentGroup`objects ever used and stores which types are being written or read based on that. +Dependency management is conservative. `ComponentSystem` simply tracks all `EntityQuery`objects ever used and stores which types are being written or read based on that. Also when scheduling multiple jobs in a single system, dependencies must be passed to all jobs even though different jobs may need less dependencies. If that proves to be a performance issue the best solution is to split a system into two. diff --git a/Documentation~/manual_iteration.md b/Documentation~/manual_iteration.md index a2f06f5b..87e7bc8c 100644 --- a/Documentation~/manual_iteration.md +++ b/Documentation~/manual_iteration.md @@ -1,6 +1,6 @@ # Manual iteration -You can also request all the chunks explicitly in a NativeArray and process them with a Job such as `IJobParallelFor`. This method is recommended if you need to manage chunks in some way that is not appropriate for the simplified model of simply iterating over all the Chunks in a ComponentGroup. As in: +You can also request all the chunks explicitly in a NativeArray and process them with a Job such as `IJobParallelFor`. This method is recommended if you need to manage chunks in some way that is not appropriate for the simplified model of simply iterating over all the Chunks in a EntityQuery. As in: ```c# public class RotationSpeedSystem : JobComponentSystem @@ -30,16 +30,16 @@ public class RotationSpeedSystem : JobComponentSystem } } - ComponentGroup m_group; + EntityQuery m_group; - protected override void OnCreateManager() + protected override void OnCreate() { - var query = new EntityArchetypeQuery + var query = new EntityQueryDesc { All = new ComponentType[]{ typeof(RotationQuaternion), ComponentType.ReadOnly() } }; - m_group = GetComponentGroup(query); + m_group = GetEntityQuery(query); } protected override JobHandle OnUpdate(JobHandle inputDeps) diff --git a/Documentation~/shared_component_data.md b/Documentation~/shared_component_data.md index d80a250c..d403ecfb 100644 --- a/Documentation~/shared_component_data.md +++ b/Documentation~/shared_component_data.md @@ -26,8 +26,8 @@ We use `ISharedComponentData` to group all entities using the same `InstanceRend ## Some important notes about SharedComponentData: - Entities with the same `SharedComponentData` are grouped together in the same [Chunks](chunk_iteration.md). The index to the `SharedComponentData` is stored once per `Chunk`, not per entity. As a result `SharedComponentData` have zero memory overhead on a per entity basis. -- Using `ComponentGroup` we can iterate over all entities with the same type. -- Additionally we can use `ComponentGroup.SetFilter()` to iterate specifically over entities that have a specific `SharedComponentData` value. Due to the data layout this iteration has low overhead. +- Using `EntityQuery` we can iterate over all entities with the same type. +- Additionally we can use `EntityQuery.SetFilter()` to iterate specifically over entities that have a specific `SharedComponentData` value. Due to the data layout this iteration has low overhead. - Using `EntityManager.GetAllUniqueSharedComponents` we can retrieve all unique `SharedComponentData` that is added to any alive entities. - `SharedComponentData` are automatically [reference counted](https://en.wikipedia.org/wiki/Reference_counting). - `SharedComponentData` should change rarely. Changing a `SharedComponentData` involves using [memcpy](https://msdn.microsoft.com/en-us/library/aa246468(v=vs.60).aspx) to copy all `ComponentData` for that entity into a different `Chunk`. diff --git a/Documentation~/system_update_order.md b/Documentation~/system_update_order.md index 580d7b5c..9ef8e5d0 100644 --- a/Documentation~/system_update_order.md +++ b/Documentation~/system_update_order.md @@ -89,6 +89,6 @@ For example, here’s the typical procedure of a custom `MyCustomBootstrap.Initi ## Tips and Best Practices * __Use [UpdateInGroup] to specify the system group for each system you write.__ If not specified, the implicit default group is SimulationSystemGroup. -* __Use manually-ticked ComponentSystemGroups to update systems elsewhere in the Unity player loop.__ Adding the [DisableAutoCreation] attribute to a component system (or system group) prevents it from being created or added to the default system groups. You can still manually create the system with World.GetOrCreateManager() and update it by calling manually calling MySystem.Update() from the main thread. This is an easy way to insert systems elsewhere in the Unity player loop (for example, if you have a system that should run later or earlier in the frame). +* __Use manually-ticked ComponentSystemGroups to update systems elsewhere in the Unity player loop.__ Adding the [DisableAutoCreation] attribute to a component system (or system group) prevents it from being created or added to the default system groups. You can still manually create the system with World.GetOrCreateSystem() and update it by calling manually calling MySystem.Update() from the main thread. This is an easy way to insert systems elsewhere in the Unity player loop (for example, if you have a system that should run later or earlier in the frame). * __Use the existing `EntityCommandBufferSystem`s instead of adding new ones, if possible.__ An `EntityCommandBufferSystem` represents a sync point where the main thread waits for worker threads to complete before processing any outstanding `EntityCommandBuffer`s. Reusing one of the predefined Begin/End systems in each root-level system group is less likely to introduce a new "bubble" into the frame pipeline than creating a new one. * __Avoid putting custom logic in `ComponentSystemGroup.OnUpdate()`__. Since `ComponentSystemGroup` is functionally a component system itself, it may be tempting to add custom processing to its OnUpdate() method, to perform some work, spawn some jobs, etc. We advise against this in general, as it’s not immediately clear from the outside whether the custom logic is executed before or after the group’s members are updated. It’s preferable to keep system groups limited to a grouping mechanism, and to implement the desired logic in a separate component system, explicitly ordered relative to the group. diff --git a/Documentation~/toc.yml b/Documentation~/toc.yml index 5f5d675b..90207383 100644 --- a/Documentation~/toc.yml +++ b/Documentation~/toc.yml @@ -41,7 +41,7 @@ - name: Accessing Entity Data href: chunk_iteration.md items: - - name: Using IJobProcessComponentData + - name: Using IJobForEach href: entity_iteration_job.md - name: Using IJobChunk href: chunk_iteration_job.md diff --git a/Documentation~/transform_system.md b/Documentation~/transform_system.md index 8258b483..61a9bb68 100644 --- a/Documentation~/transform_system.md +++ b/Documentation~/transform_system.md @@ -41,11 +41,8 @@ e.g. If the following components are present... - [TRSToLocalToWorldSystem] Write LocalToWorld <= Translation * Rotation -``` -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ -``` +![](images/sec1-1.png) + Or, if the following components are present... | (Entity) | @@ -59,17 +56,8 @@ Or, if the following components are present... - [TRSToLocalToWorldSystem] Write LocalToWorld <= Translation * Rotation * Scale -``` - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ -``` +![](images/sec1-2.png) + ------------------------------------------ Section 2: Hierarchical Transforms (Basic) ------------------------------------------ @@ -94,25 +82,7 @@ e.g. If the following components are present... 1. [TRSToLocalToWorldSystem] Parent: Write LocalToWorld as defined above in "Non-hierarchical Transforms (Basic)" 2. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ - ------- Child: ------ - -┌──────────────────────┐ ┌──────────────┐ ┌───────────────┐ -│ LocalToWorld[Parent] │ ──> │ LocalToWorld │ <── │ LocalToParent │ -└──────────────────────┘ └──────────────┘ └───────────────┘ -``` +![](images/sec2-1.png) LocalToWorld components associated with Parent Entity IDs are guaranteed to be computed before multiplies with LocalToParent associated with Child Entity ID. @@ -164,37 +134,7 @@ e.g. If the following components are present... 2. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * Rotation * Scale 3. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ - ------- Child: ------ - - ┌───────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └───────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌──────────┐ ┌───────────────┐ ┌──────────────────────┐ -│ Rotation │ ──> │ LocalToParent │ <── │ Translation │ -└──────────┘ └───────────────┘ └──────────────────────┘ - ∧ - │ - │ - ┌───────────────┐ - │ Scale │ - └───────────────┘ -``` +![](images/sec2-2.png) Parents may of course themselves be children of other LocalToWorld components. @@ -218,43 +158,7 @@ e.g. If the following components are present... 3. [LocalToParentSystem] Parent: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent 4. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌───────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └───────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌──────────┐ ┌───────────────┐ ┌──────────────────────┐ -│ Rotation │ ──> │ LocalToParent │ <── │ Translation │ -└──────────┘ └───────────────┘ └──────────────────────┘ - ∧ - │ - │ - ┌───────────────┐ - │ Scale │ - └───────────────┘ - ------- Child: ------ - - ┌───────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └───────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌──────────┐ ┌───────────────┐ ┌──────────────────────┐ -│ Rotation │ ──> │ LocalToParent │ <── │ Translation │ -└──────────┘ └───────────────┘ └──────────────────────┘ - ∧ - │ - │ - ┌───────────────┐ - │ Scale │ - └───────────────┘ -``` +![](images/sec2-3.png) ------------------------------------- Section 3: Default Conversion (Basic) @@ -304,17 +208,7 @@ e.g. If the following components are present... - [TRSToLocalToWorldSystem] Write LocalToWorld <= Translation * Rotation * NonUniformScale -``` - ┌──────────────┐ - │ Rotation │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌─────────────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ NonUniformScale │ -└─────────────┘ └──────────────┘ └─────────────────┘ -``` +![](images/sec4-1.png) The Rotation component may be written to directly as a quaternion by user code. However, if an Euler interface is preferred, components are available for each rotation order which will cause a write to the Rotation component if present. @@ -339,17 +233,7 @@ e.g. If the following components are present... 1. [RotationEulerSystem] Write Rotation <= RotationEulerXYZ 2. [TRSToLocalToWorldSystem] Write LocalToWorld <= Translation * Rotation * Scale -``` - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ ┌──────────────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ <── │ RotationEulerXYZ │ -└─────────────┘ └──────────────┘ └──────────┘ └──────────────────┘ -``` +![](images/sec4-2.png) It is a setup error to have more than one RotationEuler*** component is associated with the same Entity, however the result is defined. The first to be found in the order of precedence will be applied. That order is: @@ -417,26 +301,7 @@ e.g. If the following components are present... 1. [CompositeRotationSystem] Write CompositeRotation <= RotationPivotTranslation * RotationPivot * Rotation * PostRotation * RotationPivot^-1 2. [TRSToLocalToWorldSystem] Write LocalToWorld <= Translation * CompositeRotation * Scale -``` - ┌──────────────────────────┐ ┌───────────────────┐ - │ Scale │ │ RotationPivot │ - └──────────────────────────┘ └───────────────────┘ - │ │ - │ │ - ∨ ∨ -┌─────────────┐ ┌──────────────────────────┐ ┌───────────────────┐ ┌──────────────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ │ <── │ PostRotation │ -└─────────────┘ └──────────────────────────┘ │ CompositeRotation │ └──────────────────┘ - ┌──────────────────────────┐ │ │ ┌──────────────────┐ - │ RotationPivotTranslation │ ──> │ │ │ RotationEulerXYZ │ - └──────────────────────────┘ └───────────────────┘ └──────────────────┘ - ∧ │ - │ │ - │ ∨ - │ ┌──────────────────┐ - └────────────────────── │ Rotation │ - └──────────────────┘ -``` +![](images/sec4-3.png) The PostRotation component may be written to directly as a quaternion by user code. However, if an Euler interface is preferred, components are available for each rotation order which will cause a write to the PostRotation component if present. @@ -469,20 +334,7 @@ e.g. If the following components are present... 3. [CompositeRotationSystem] Write CompositeRotation <= RotationPivotTranslation * RotationPivot * Rotation * PostRotation * RotationPivot^-1 4. [TRSToLocalToWorldSystem] Write LocalToWorld <= Translation * CompositeRotation * Scale -``` - ┌──────────────────────────┐ ┌───────────────────┐ - │ Scale │ │ RotationPivot │ - └──────────────────────────┘ └───────────────────┘ - │ │ - │ │ - ∨ ∨ -┌─────────────┐ ┌──────────────────────────┐ ┌───────────────────┐ ┌──────────────┐ ┌──────────────────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ │ <── │ PostRotation │ <── │ PostRotationEulerXYZ │ -└─────────────┘ └──────────────────────────┘ │ CompositeRotation │ └──────────────┘ └──────────────────────┘ - ┌──────────────────────────┐ │ │ ┌──────────────┐ ┌──────────────────────┐ - │ RotationPivotTranslation │ ──> │ │ <── │ Rotation │ <── │ RotationEulerXYZ │ - └──────────────────────────┘ └───────────────────┘ └──────────────┘ └──────────────────────┘ -``` +![](images/sec4-4.png) For more complex Scale requirements, a CompositeScale (float4x4) component may be used as an alternative to Scale (or NonUniformScale). @@ -543,38 +395,7 @@ e.g. If the following components are present... 4. [CompositeRotationSystem] Write CompositeRotation <= RotationPivotTranslation * RotationPivot * Rotation * PostRotation * RotationPivot^-1 5. [TRSToLocalToWorldSystem] Write LocalToWorld <= Translation * CompositeRotation * CompositeScale -``` - ┌───────────────────┐ - │ RotationPivot │ - └───────────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────────────────┐ ┌───────────────────┐ ┌───────────────────────┐ ┌──────────────────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ │ <── │ PostRotation │ <── │ PostRotationEulerXYZ │ -└─────────────┘ └──────────────────────────┘ │ │ └───────────────────────┘ └──────────────────────┘ - ∧ │ │ - ┌────┘ │ CompositeRotation │ - │ │ │ - │ ┌──────────────────────────┐ │ │ ┌───────────────────────┐ ┌──────────────────────┐ - │ │ RotationPivotTranslation │ ──> │ │ <── │ Rotation │ <── │ RotationEulerXYZ │ - │ └──────────────────────────┘ └───────────────────┘ └───────────────────────┘ └──────────────────────┘ - │ - │ ┌─────────────────────────────────────────────────────┐ - │ ∨ │ - │ ┌───────────────────────┐ ┌──────────────────────┐ │ - └──────────────────────────────────────────────────────────── │ CompositeScale │ <── │ Scale │ │ - └───────────────────────┘ └──────────────────────┘ │ - ∧ │ - │ │ - │ │ - ┌───────────────────────┐ │ - │ ScalePivotTranslation │ │ - └───────────────────────┘ │ - ┌───────────────────────┐ │ - │ ScalePivot │ ──────────────────────────────┘ - └───────────────────────┘ -``` +![](images/sec4-5.png) --------------------------------------------- Section 5: Hierarchical Transforms (Advanced) @@ -613,37 +434,7 @@ e.g. If the following components are present... 2. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * Rotation * NonUniformScale 3. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ - ------- Child: ------ - - ┌───────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └───────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌─────────────────┐ ┌───────────────┐ ┌──────────────────────┐ -│ NonUniformScale │ ──> │ LocalToParent │ <── │ Translation │ -└─────────────────┘ └───────────────┘ └──────────────────────┘ - ∧ - │ - │ - ┌───────────────┐ - │ Rotation │ - └───────────────┘ -``` +![](images/sec5-1.png) Parent LocalToWorld is multiplied with the Child LocalToWorld, which includes any scaling. However, if removing Parent scale is preferred (AKA Scale Compensate), ParentScaleInverse is available for that purpose. @@ -693,37 +484,7 @@ e.g. If the following components are present... 3. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * ParentScaleInverse * Rotation 4. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ - ------- Child: ------ - - ┌────────────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └────────────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌──────────┐ ┌────────────────────┐ ┌──────────────────────┐ -│ Rotation │ ──> │ LocalToParent │ <── │ Translation │ -└──────────┘ └────────────────────┘ └──────────────────────┘ - ∧ - │ - │ - ┌────────────────────┐ ┌──────────────────────┐ - │ ParentScaleInverse │ <── │ Scale[Parent] │ - └────────────────────┘ └──────────────────────┘ -``` +![](images/sec5-2.png) The Rotation component may be written to directly as a quaternion by user code. However, if an Euler interface is preferred, components are available for each rotation order which will cause a write to the Rotation component if present. @@ -753,37 +514,7 @@ e.g. If the following components are present... 3. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * Rotation 4. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ - ------- Child: ------ - -┌───────────────┐ ┌──────────────────────┐ -│ LocalToWorld │ <── │ LocalToWorld[Parent] │ -└───────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌───────────────┐ ┌──────────────────────┐ -│ LocalToParent │ <── │ Translation │ -└───────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌───────────────┐ ┌──────────────────────┐ -│ Rotation │ <── │ RotationEulerXYZ │ -└───────────────┘ └──────────────────────┘ -``` +![](images/sec5-3.png) For more complex Rotation requirements, a CompositeRotation (float4x4) component may be used as an alternative to Rotation. @@ -856,51 +587,7 @@ e.g. If the following components are present... 4. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * CompositeRotation * Scale 5. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ - ------- Child: ------ - ┌───────────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └───────────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌──────────────────────────┐ ┌───────────────────┐ ┌──────────────────────┐ -│ Scale │ ──> │ │ <── │ Translation │ -└──────────────────────────┘ │ │ └──────────────────────┘ - │ │ - │ LocalToParent │ <─────────────────────────────┐ - │ │ │ - │ │ ┌──────────────────────┐ │ - │ │ │ RotationEulerXYZ │ │ - └───────────────────┘ └──────────────────────┘ │ - ∧ │ │ - │ │ │ - │ ∨ │ -┌──────────────────────────┐ ┌───────────────────┐ ┌──────────────────────┐ │ -│ RotationPivotTranslation │ ──> │ │ <── │ Rotation │ │ -└──────────────────────────┘ │ CompositeRotation │ └──────────────────────┘ │ -┌──────────────────────────┐ │ │ ┌──────────────────────┐ │ -│ PostRotation │ ──> │ │ │ Scale[Parent] │ │ -└──────────────────────────┘ └───────────────────┘ └──────────────────────┘ │ - ∧ │ │ - │ │ │ - │ ∨ │ - ┌───────────────────┐ ┌──────────────────────┐ │ - │ RotationPivot │ │ ParentScaleInverse │ ─┘ - └───────────────────┘ └──────────────────────┘ -``` +![](images/sec5-4.png) The PostRotation component may be written to directly as a quaternion by user code. However, if an Euler interface is preferred, components are available for each rotation order which will cause a write to the PostRotation component if present. @@ -938,58 +625,7 @@ e.g. If the following components are present... 5. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * CompositeRotation * Scale 6. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ - ------- Child: ------ - - ┌────────────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └────────────────────┘ └──────────────────────┘ - ∧ - │ - │ -┌──────────────────────────┐ ┌────────────────────┐ ┌──────────────────────┐ -│ Scale │ ──> │ │ <── │ Translation │ -└──────────────────────────┘ │ │ └──────────────────────┘ - │ │ - │ LocalToParent │ <─────────────────────────────┐ - │ │ │ - │ │ ┌──────────────────────┐ │ - │ │ │ PostRotationEulerXYZ │ │ - └────────────────────┘ └──────────────────────┘ │ - ∧ │ │ - │ │ │ - │ ∨ │ -┌──────────────────────────┐ ┌────────────────────┐ ┌──────────────────────┐ │ -│ RotationPivotTranslation │ ──> │ │ <── │ PostRotation │ │ -└──────────────────────────┘ │ CompositeRotation │ └──────────────────────┘ │ -┌──────────────────────────┐ │ │ ┌──────────────────────┐ │ -│ RotationPivot │ ──> │ │ │ RotationEulerXYZ │ │ -└──────────────────────────┘ └────────────────────┘ └──────────────────────┘ │ - ∧ │ │ - │ │ │ - │ ∨ │ - │ ┌──────────────────────┐ │ - └─────────────────────── │ Rotation │ │ - └──────────────────────┘ │ - │ - ┌──────────────────────────────────────────────────┘ - │ - ┌────────────────────┐ ┌──────────────────────┐ - │ ParentScaleInverse │ <── │ Scale[Parent] │ - └────────────────────┘ └──────────────────────┘ -``` +![](images/sec5-5.png) It is a setup error to have more than one PostRotationEuler*** component is associated with the same Entity, however the result is defined. The first to be found in the order of precedence will be applied. That order is: @@ -1068,19 +704,8 @@ e.g. If the following components are present... 4. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * CompositeRotation * Scale 5. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` ------- Parent: ------ - - ┌──────────────┐ - │ Scale │ - └──────────────┘ - │ - │ - ∨ -┌─────────────┐ ┌──────────────┐ ┌──────────┐ -│ Translation │ ──> │ LocalToWorld │ <── │ Rotation │ -└─────────────┘ └──────────────┘ └──────────┘ -``` +![](images/sec5-6.png) + ...then the transform system will: 1. [TRSToLocalToWorldSystem] Parent: Write LocalToWorld as defined above in "Non-hierarchical Transforms (Basic)" @@ -1091,56 +716,7 @@ e.g. If the following components are present... 6. [TRSToLocalToParentSystem] Child: Write LocalToParent <= Translation * CompositeRotation * Scale 7. [LocalToParentSystem] Child: Write LocalToWorld <= LocalToWorld[Parent] * LocalToParent -``` - ┌───────────────────┐ ┌──────────────────────┐ - │ LocalToWorld │ <── │ LocalToWorld[Parent] │ - └───────────────────┘ └──────────────────────┘ - ∧ - │ - │ - ┌───────────────────┐ ┌──────────────────────┐ - │ │ <── │ Translation │ - │ │ └──────────────────────┘ - │ │ - │ LocalToParent │ <─────────────────────────────┐ - │ │ │ - │ │ ┌──────────────────────┐ │ - ┌─────────────────────────────────> │ │ │ PostRotationEulerXYZ │ │ - │ └───────────────────┘ └──────────────────────┘ │ - │ ∧ │ │ - │ │ │ │ - │ │ ∨ │ - │ ┌──────────────────────────┐ ┌───────────────────┐ ┌──────────────────────┐ │ - │ │ RotationPivotTranslation │ ──> │ │ <── │ PostRotation │ │ - │ └──────────────────────────┘ │ CompositeRotation │ └──────────────────────┘ │ - │ ┌──────────────────────────┐ │ │ ┌──────────────────────┐ │ - │ │ RotationPivot │ ──> │ │ │ RotationEulerXYZ │ │ - │ └──────────────────────────┘ └───────────────────┘ └──────────────────────┘ │ - │ ∧ │ │ - │ │ │ │ - │ │ ∨ │ - │ │ ┌──────────────────────┐ │ - │ └────────────────────── │ Rotation │ │ - │ └──────────────────────┘ │ - │ │ - │ ┌─────────────────────────────────────────────────┘ - │ │ - │ ┌──────────────────────────┐ ┌───────────────────┐ ┌──────────────────────┐ - │ │ ScalePivotTranslation │ ──> │ CompositeScale │ <── │ Scale │ - │ └──────────────────────────┘ └───────────────────┘ └──────────────────────┘ - │ ∧ - │ │ - │ │ - │ ┌───────────────────┐ ┌──────────────────────┐ - │ │ ScalePivot │ │ Scale[Parent] │ - │ └───────────────────┘ └──────────────────────┘ - │ │ - │ │ - │ ∨ - │ ┌──────────────────────┐ - └──────────────────────────────────────────────────────────── │ ParentScaleInverse │ - └──────────────────────┘ -``` +![](images/sec5-7.png) --------------------------------------- Section 6: Custom Transforms (Advanced) @@ -1171,7 +747,7 @@ e.g. public class UserTransformSystem : JobComponentSystem { [BurstCompile] - struct UserTransform : IJobProcessComponentData + struct UserTransform : IJobForEach { public void Execute(ref LocalToWorld localToWorld, [ReadOnly] ref UserComponent userComponent) { @@ -1221,7 +797,7 @@ And the equivalent system: public class UserTransformSystem2 : JobComponentSystem { [BurstCompile] - struct UserTransform2 : IJobProcessComponentData + struct UserTransform2 : IJobForEach { public void Execute(ref LocalToWorld localToWorld, [ReadOnly] ref UserComponent2 userComponent2) { @@ -1269,23 +845,23 @@ And a system which filters based on the WriteGroup of LocalToWorld: public class UserTransformSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery() + m_Group = GetEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { ComponentType.ReadWrite(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryDescOptions.FilterWriteGroup }); } [BurstCompile] - struct UserTransform : IJobProcessComponentData + struct UserTransform : IJobForEach { public void Execute(ref LocalToWorld localToWorld, [ReadOnly] ref UserComponent userComponent) { @@ -1304,7 +880,7 @@ And a system which filters based on the WriteGroup of LocalToWorld: m_Group in UserTransformSystem will only match the explicitly mentioned components. -For instance, the following with match and be included in the ComponentGroup: +For instance, the following with match and be included in the EntityQuery: | (Entity) | | -------------- | @@ -1327,11 +903,11 @@ However, they may be explicitly supported by UserComponent systems by adding to public class UserTransformExtensionSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery() + m_Group = GetEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { @@ -1341,12 +917,12 @@ However, they may be explicitly supported by UserComponent systems by adding to ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryDescOptions.FilterWriteGroup }); } [BurstCompile] - struct UserTransform : IJobProcessComponentData + struct UserTransform : IJobForEach { public void Execute(ref LocalToWorld localToWorld, [ReadOnly] ref UserComponent userComponent, [ReadOnly] ref Translation translation, @@ -1388,11 +964,11 @@ However, an explicit query can be created which can resolve the case and ensure public class UserTransformComboSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery() + m_Group = GetEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { @@ -1400,12 +976,12 @@ However, an explicit query can be created which can resolve the case and ensure ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryDescOptions.FilterWriteGroup }); } [BurstCompile] - struct UserTransform : IJobProcessComponentData + struct UserTransform : IJobForEach { public void Execute(ref LocalToWorld localToWorld, [ReadOnly] ref UserComponent userComponent, diff --git a/Documentation~/version_numbers.md b/Documentation~/version_numbers.md index 927981c9..108e7813 100644 --- a/Documentation~/version_numbers.md +++ b/Documentation~/version_numbers.md @@ -48,7 +48,7 @@ For each component type in the archetype, this array contains the value of `Enti Shared components can never be accessed as writeable, even if there is technically a version number stored for those too, it serves no purpose. -When using the `[ChangedFilter]` attribute in an `IJobProcessComponentData`, the `Chunk.ChangeVersion` for that specific component is compared to `System.LastSystemVersion`, so only chunks whose component arrays have been accessed as writeable since after the system last started running will be processed. +When using the `[ChangedFilter]` attribute in an `IJobForEach`, the `Chunk.ChangeVersion` for that specific component is compared to `System.LastSystemVersion`, so only chunks whose component arrays have been accessed as writeable since after the system last started running will be processed. > If the amount of health points of a group of units is guaranteed not to have changed since the previous frame, checking if those units should update their damage model can be skipped altogether. diff --git a/Unity.Entities.BuildUtils/MonoExtensions.cs b/Unity.Entities.BuildUtils/MonoExtensions.cs index 54f13b09..e7fd5d48 100644 --- a/Unity.Entities.BuildUtils/MonoExtensions.cs +++ b/Unity.Entities.BuildUtils/MonoExtensions.cs @@ -91,6 +91,48 @@ public static bool IsEntityType(this TypeReference typeRef) return (typeRef.FullName == "Unity.Entities.Entity"); } + public static bool IsManagedType(this TypeReference typeRef) + { + // We must check this before calling Resolve() as cecil loses this property otherwise + if (typeRef.IsPointer) + return false; + + if (typeRef.IsArray) + return true; + + var type = typeRef.Resolve(); + + if (type.IsDynamicArray()) + return true; + + TypeDefinition fixedSpecialType = type.FixedSpecialType(); + if (fixedSpecialType != null) + { + if (fixedSpecialType.MetadataType == MetadataType.String) + return true; + return false; + } + + if (type.IsEnum) + return false; + + if (type.IsValueType) + { + // if none of the above check the type's fields + foreach (var field in type.Fields) + { + if (field.IsStatic) + continue; + + if (field.FieldType.IsManagedType()) + return true; + } + + return false; + } + + return true; + } public static bool IsComplex(this TypeReference typeRef) diff --git a/Unity.Entities.BuildUtils/TypeUtils.cs b/Unity.Entities.BuildUtils/TypeUtils.cs index 7825d14d..6231fc89 100644 --- a/Unity.Entities.BuildUtils/TypeUtils.cs +++ b/Unity.Entities.BuildUtils/TypeUtils.cs @@ -267,7 +267,7 @@ public static void PreprocessTypeFields(TypeDefinition valuetype, int bits) ValueTypeIsComplex[bits].Add(valuetype, isComplex); } - internal static void GetEntityFieldOffsets(int offset, TypeDefinition type, List l, int bits) + internal static void GetFieldOffsetsOfRecurse(string queryFullTypeName, int offset, TypeDefinition type, List l, int bits) { int in_type_offset = 0; foreach (var f in type.Fields) @@ -284,34 +284,51 @@ internal static void GetEntityFieldOffsets(int offset, TypeDefinition type, List var tinfo = resize(TypeUtils.AlignAndSizeOfType(f.FieldType, bits)); in_type_offset = (int)alignUp((uint)in_type_offset, (uint)tinfo.align); - if (f.FieldType.IsDynamicArray() && f.FieldType.DynamicArrayElementType().IsEntityType()) + if (f.FieldType.IsDynamicArray() && f.FieldType.DynamicArrayElementType().Resolve().FullName == queryFullTypeName) { // +1 so that we have a way to indicate an Array at position 0 // fixup code subtracts 1 l.Add(-(offset + in_type_offset + 1)); } - else if (f.FieldType.IsEntityType()) + else if (f.FieldType.Resolve().FullName == queryFullTypeName) { l.Add(offset + in_type_offset); } else if (f.FieldType.IsValueType && !f.FieldType.IsPrimitive) { - GetEntityFieldOffsets(offset + in_type_offset, f.FieldType.Resolve(), l, bits); + GetFieldOffsetsOfRecurse(queryFullTypeName, offset + in_type_offset, f.FieldType.Resolve(), l, bits); } in_type_offset += tinfo.size; } } - public static List GetEntityFieldOffsets(TypeDefinition type, int archBits) + public static List GetFieldOffsetsOf(TypeReference typeToFind, TypeDefinition typeToLookIn, int archBits) + { + var offsets = new List(); + + if (typeToLookIn != null) + { + GetFieldOffsetsOfRecurse(typeToFind.FullName, 0, typeToLookIn, offsets, archBits); + } + + return offsets; + } + + public static List GetFieldOffsetsOf(string queryFullTypeName, TypeDefinition typeToLookIn, int archBits) { var offsets = new List(); - if (type != null) + if (typeToLookIn != null) { - GetEntityFieldOffsets(0, type, offsets, archBits); + GetFieldOffsetsOfRecurse(queryFullTypeName, 0, typeToLookIn, offsets, archBits); } return offsets; } + + public static List GetEntityFieldOffsets(TypeDefinition type, int archBits) + { + return GetFieldOffsetsOf("Unity.Entities.Entity", type, archBits); + } } } diff --git a/Unity.Entities.Editor.Tests/ComponentGroupGUITests.cs b/Unity.Entities.Editor.Tests/ComponentGroupGUITests.cs index 5dd9c3d5..2ea12550 100644 --- a/Unity.Entities.Editor.Tests/ComponentGroupGUITests.cs +++ b/Unity.Entities.Editor.Tests/ComponentGroupGUITests.cs @@ -15,14 +15,14 @@ public class ComponentGroupGUITests [Test] public void ComponentGroupGUI_SpecifiedTypeName_NestedTypeInGeneric() { - var typeName = ComponentGroupGUI.SpecifiedTypeName(typeof(GenericClassTest.InternalClass)); + var typeName = EntityQueryGUI.SpecifiedTypeName(typeof(GenericClassTest.InternalClass)); Assert.AreEqual("GenericClassTest.InternalClass", typeName); } [Test] public void ComponentGroupGUI_SpecifiedTypeName_NestedGenericTypeInGeneric() { - var typeName = ComponentGroupGUI.SpecifiedTypeName(typeof(GenericClassTest.InternalGenericClass)); + var typeName = EntityQueryGUI.SpecifiedTypeName(typeof(GenericClassTest.InternalGenericClass)); Assert.AreEqual("GenericClassTest.InternalGenericClass", typeName); } } diff --git a/Unity.Entities.Editor.Tests/ComponentTypeFilterUITests.cs b/Unity.Entities.Editor.Tests/ComponentTypeFilterUITests.cs index d4e8af4c..e3763850 100644 --- a/Unity.Entities.Editor.Tests/ComponentTypeFilterUITests.cs +++ b/Unity.Entities.Editor.Tests/ComponentTypeFilterUITests.cs @@ -39,9 +39,9 @@ public void ComponentTypeFilterUI_ComponentGroupCaches() var filterUI = new ComponentTypeFilterUI(SetFilterDummy, WorldSelectionGetter); var types = new ComponentType[] {ComponentType.ReadWrite(), ComponentType.ReadOnly()}; - Assert.IsNull(filterUI.GetExistingGroup(types)); - var group = filterUI.GetComponentGroup(types); - Assert.AreEqual(group, filterUI.GetExistingGroup(types)); + Assert.IsNull(filterUI.GetExistingQuery(types)); + var group = filterUI.GetEntityQuery(types); + Assert.AreEqual(group, filterUI.GetExistingQuery(types)); } } } diff --git a/Unity.Entities.Editor.Tests/EntityArrayListAdapterTests.cs b/Unity.Entities.Editor.Tests/EntityArrayListAdapterTests.cs index f8363348..bd5fb09b 100644 --- a/Unity.Entities.Editor.Tests/EntityArrayListAdapterTests.cs +++ b/Unity.Entities.Editor.Tests/EntityArrayListAdapterTests.cs @@ -19,14 +19,14 @@ public override void Setup() m_Manager.CreateEntity(archetype, entities); } - var query = new EntityArchetypeQuery() + var query = new EntityQueryDesc() { Any = new ComponentType[0], All = new ComponentType[0], None = new ComponentType[0] }; - var group = m_Manager.CreateComponentGroup(query); + var group = m_Manager.CreateEntityQuery(query); m_ChunkArray = group.CreateArchetypeChunkArray(Allocator.TempJob); } diff --git a/Unity.Entities.Editor.Tests/EntityDebuggerTests.cs b/Unity.Entities.Editor.Tests/EntityDebuggerTests.cs index 462c87e8..721bd799 100644 --- a/Unity.Entities.Editor.Tests/EntityDebuggerTests.cs +++ b/Unity.Entities.Editor.Tests/EntityDebuggerTests.cs @@ -11,7 +11,7 @@ class EntityDebuggerTests : ECSTestsFixture private EntityDebugger m_Window; private ComponentSystem m_System; - private ComponentGroup m_ComponentGroup; + private EntityQuery entityQuery; private Entity m_Entity; [DisableAutoCreation] @@ -23,9 +23,9 @@ protected override void OnUpdate() throw new NotImplementedException(); } - protected override void OnCreateManager() + protected override void OnCreate() { - GetComponentGroup(typeof(EcsTestData)); + GetEntityQuery(typeof(EcsTestData)); } } @@ -48,18 +48,17 @@ public override void Setup() m_Window = EditorWindow.GetWindow(); - m_System = World.Active.GetOrCreateManager(); - World.Active.GetOrCreateManager().AddSystemToUpdateList(m_System); + m_System = World.Active.GetOrCreateSystem(); + World.Active.GetOrCreateSystem().AddSystemToUpdateList(m_System); ScriptBehaviourUpdateOrder.UpdatePlayerLoop(World.Active); World2 = new World(World2Name); - World2.GetOrCreateManager(); - var emptySys = World2.GetOrCreateManager(); - World.Active.GetOrCreateManager().AddSystemToUpdateList(emptySys); - World.Active.GetOrCreateManager().SortSystemUpdateList(); + var emptySys = World2.GetOrCreateSystem(); + World.Active.GetOrCreateSystem().AddSystemToUpdateList(emptySys); + World.Active.GetOrCreateSystem().SortSystemUpdateList(); - m_ComponentGroup = m_System.ComponentGroups[0]; + entityQuery = m_System.EntityQueries[0]; m_Entity = m_Manager.CreateEntity(typeof(EcsTestData)); } @@ -93,11 +92,14 @@ public void WorldPopup_RestorePreviousSelection() [Test] public void EntityDebugger_SetSystemSelection() { + // TODO EntityManager is no longer a system + /* m_Window.SetSystemSelection(m_Manager, World.Active, true, true); Assert.AreEqual(World.Active, m_Window.SystemSelectionWorld); Assert.Throws(() => m_Window.SetSystemSelection(m_Manager, null, true, true)); + */ } [Test] @@ -115,27 +117,27 @@ public void EntityDebugger_DestroySystem() { m_Window.SetWorldSelection(World2, true); Assert.IsFalse(m_Window.systemListView.NeedsReload); - var emptySystem = World2.GetExistingManager(); - World2.DestroyManager(emptySystem); + var emptySystem = World2.GetExistingSystem(); + World2.DestroySystem(emptySystem); Assert.IsTrue(m_Window.systemListView.NeedsReload); } [Test] public void EntityDebugger_SetAllSelections() { - var entityListQuery = new EntityListQuery(m_ComponentGroup); + var entityListQuery = new EntityListQuery(entityQuery); EntityDebugger.SetAllSelections(World.Active, m_System, entityListQuery, m_Entity); Assert.AreEqual(World.Active, m_Window.WorldSelection); Assert.AreEqual(m_System, m_Window.SystemSelection); - Assert.AreEqual(m_ComponentGroup, m_Window.EntityListQuerySelection.Group); + Assert.AreEqual(entityQuery, m_Window.EntityListQuerySelection.Group); Assert.AreEqual(m_Entity, m_Window.EntitySelection); } [Test] public void EntityDebugger_RememberSelections() { - var entityListQuery = new EntityListQuery(m_ComponentGroup); + var entityListQuery = new EntityListQuery(entityQuery); EntityDebugger.SetAllSelections(World.Active, m_System, entityListQuery, m_Entity); m_Window.SetWorldSelection(null, true); @@ -144,14 +146,14 @@ public void EntityDebugger_RememberSelections() Assert.AreEqual(World.Active, m_Window.WorldSelection); Assert.AreEqual(m_System, m_Window.SystemSelection); - Assert.AreEqual(m_ComponentGroup, m_Window.EntityListQuerySelection.Group); + Assert.AreEqual(entityQuery, m_Window.EntityListQuerySelection.Group); Assert.AreEqual(m_Entity, m_Window.EntitySelection); } [Test] public void EntityDebugger_SetAllEntitiesFilter() { - var query = new EntityArchetypeQuery() + var query = new EntityQueryDesc() { All = new ComponentType[] {ComponentType.ReadWrite() }, Any = new ComponentType[0], @@ -162,12 +164,12 @@ public void EntityDebugger_SetAllEntitiesFilter() m_Window.SetWorldSelection(World.Active, true); m_Window.SetSystemSelection(null, null, true, true); m_Window.SetAllEntitiesFilter(listQuery); - Assert.AreEqual(query, m_Window.EntityListQuerySelection.Query); + Assert.AreEqual(query, m_Window.EntityListQuerySelection.QueryDesc); m_Window.SetEntityListSelection(null, true, true); - m_Window.SetSystemSelection(World.Active.GetExistingManager(), World.Active, true, true); + m_Window.SetSystemSelection(null, World.Active, true, true); m_Window.SetAllEntitiesFilter(listQuery); - Assert.AreEqual(query, m_Window.EntityListQuerySelection.Query); + Assert.AreEqual(query, m_Window.EntityListQuerySelection.QueryDesc); m_Window.SetSystemSelection(m_System, World.Active, true, true); m_Window.SetAllEntitiesFilter(listQuery); diff --git a/Unity.Entities.Editor.Tests/ListViewTests.cs b/Unity.Entities.Editor.Tests/ListViewTests.cs index d70753f7..7fa111f8 100644 --- a/Unity.Entities.Editor.Tests/ListViewTests.cs +++ b/Unity.Entities.Editor.Tests/ListViewTests.cs @@ -21,11 +21,11 @@ private static void SetComponentGroupSelection(EntityListQuery query) { } - private static void SetSystemSelection(ScriptBehaviourManager system, World world) + private static void SetSystemSelection(ComponentSystemBase system, World world) { } - private EntityListQuery AllQuery => new EntityListQuery(new EntityArchetypeQuery(){All = new ComponentType[0], Any = new ComponentType[0], None = new ComponentType[0]}); + private EntityListQuery AllQuery => new EntityListQuery(new EntityQueryDesc(){All = new ComponentType[0], Any = new ComponentType[0], None = new ComponentType[0]}); private World World2; @@ -36,9 +36,9 @@ public override void Setup() ScriptBehaviourUpdateOrder.UpdatePlayerLoop(World.Active); World2 = new World("Test World 2"); - var emptySys = World2.GetOrCreateManager(); - World.Active.GetOrCreateManager().AddSystemToUpdateList(emptySys); - World.Active.GetOrCreateManager().SortSystemUpdateList(); + var emptySys = World2.GetOrCreateSystem(); + World.Active.GetOrCreateSystem().AddSystemToUpdateList(emptySys); + World.Active.GetOrCreateSystem().SortSystemUpdateList(); } public override void TearDown() @@ -55,16 +55,12 @@ public override void TearDown() public void EntityListView_ShowNothingWithoutWorld() { m_Manager.CreateEntity(); - var emptySystem = World.Active.GetOrCreateManager(); - ScriptBehaviourManager currentSystem = null; + var emptySystem = World.Active.GetOrCreateSystem(); + ComponentSystemBase currentSystem = null; using (var listView = new EntityListView(new TreeViewState(), null, SetEntitySelection, () => null, () => currentSystem, x => {})) { - currentSystem = World.Active.GetExistingManager(); - listView.SelectedEntityQuery = null; - Assert.IsFalse(listView.ShowingSomething); - currentSystem = emptySystem; listView.SelectedEntityQuery = null; Assert.IsFalse(listView.ShowingSomething); @@ -83,22 +79,25 @@ public void EntityListView_ShowNothingWithoutWorld() public void EntityListView_ShowEntitiesFromWorld() { m_Manager.CreateEntity(); - var emptySystem = World.Active.GetOrCreateManager(); + var emptySystem = World.Active.GetOrCreateSystem(); var selectedWorld = World.Active; - ScriptBehaviourManager currentSystem = null; + ComponentSystemBase currentSystem = null; using (var listView = new EntityListView(new TreeViewState(), null, SetEntitySelection, () => selectedWorld, () => currentSystem, x => {})) { - currentSystem = World.Active.GetExistingManager(); + // TODO EntityManager is no longer a system + /* + currentSystem = World.Active.EntityManager; listView.SelectedEntityQuery = AllQuery; Assert.IsTrue(listView.ShowingSomething); Assert.AreEqual(1, listView.GetRows().Count); - currentSystem = World.Active.GetExistingManager(); + currentSystem = World.Active.EntityManager; listView.SelectedEntityQuery = null; Assert.IsTrue(listView.ShowingSomething); Assert.AreEqual(1, listView.GetRows().Count); + */ currentSystem = emptySystem; listView.SelectedEntityQuery = null; @@ -106,10 +105,24 @@ public void EntityListView_ShowEntitiesFromWorld() } } + [Test] + public void EntityListView_ShowNothingWithNoEntityManager() + { + using (var incompleteWorld = new World("test 2")) + { + using (var listView = new EntityListView(new TreeViewState(), null, SetEntitySelection, () => incompleteWorld, + () => null, x => {})) + { + listView.SelectedEntityQuery = null; + Assert.AreEqual(0, listView.GetRows().Count); + } + } + } + [Test] public void ComponentGroupListView_CanSetNullSystem() { - var listView = new ComponentGroupListView(new TreeViewState(), EmptySystem, SetComponentGroupSelection, GetWorldSelection); + var listView = new EntityQueryListView(new TreeViewState(), EmptySystem, SetComponentGroupSelection, GetWorldSelection); Assert.DoesNotThrow(() => listView.SelectedSystem = null); } @@ -125,7 +138,7 @@ public void ComponentGroupListView_SortOrderExpected() typeList.Add(subtractive); typeList.Add(readOnly); typeList.Add(readWrite); - typeList.Sort(ComponentGroupGUI.CompareTypes); + typeList.Sort(EntityQueryGUI.CompareTypes); Assert.AreEqual(readOnly, typeList[0]); Assert.AreEqual(readWrite, typeList[1]); @@ -156,7 +169,7 @@ public void SystemListView_ShowExactlyWorldSystems() () => true); var managerItems = listView.GetRows().Where(x => listView.managersById.ContainsKey(x.id)).Select(x => listView.managersById[x.id]); var managerList = managerItems.ToList(); - Assert.AreEqual(World2.BehaviourManagers.Count(x => !(x is EntityManager)), managerList.Intersect(World2.BehaviourManagers).Count()); + Assert.AreEqual(World2.Systems.Count(), managerList.Intersect(World2.Systems).Count()); } [Test] @@ -169,11 +182,11 @@ public void SystemListView_NullWorldShowsAllSystems() () => null, () => true); var managerItems = listView.GetRows().Where(x => listView.managersById.ContainsKey(x.id)).Select(x => listView.managersById[x.id]); - var allManagers = new List(); - allManagers.AddRange(World.Active.BehaviourManagers); - allManagers.AddRange(World2.BehaviourManagers); + var allManagers = new List(); + allManagers.AddRange(World.Active.Systems); + allManagers.AddRange(World2.Systems); var managerList = managerItems.ToList(); - Assert.AreEqual(allManagers.Count(x => !(x is EntityManager || x is ComponentSystemGroup) ), allManagers.Intersect(managerList).Count()); + Assert.AreEqual(allManagers.Count(x => !(x is ComponentSystemGroup) ), allManagers.Intersect(managerList).Count()); } } diff --git a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUI.cs b/Unity.Entities.Editor/CommonGUI/EntityQueryGUI.cs similarity index 96% rename from Unity.Entities.Editor/CommonGUI/ComponentGroupGUI.cs rename to Unity.Entities.Editor/CommonGUI/EntityQueryGUI.cs index c5e670df..e5ff40ae 100644 --- a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUI.cs +++ b/Unity.Entities.Editor/CommonGUI/EntityQueryGUI.cs @@ -6,7 +6,7 @@ namespace Unity.Entities.Editor { - internal static class ComponentGroupGUI + internal static class EntityQueryGUI { internal static int CompareTypes(ComponentType x, ComponentType y) @@ -42,7 +42,7 @@ static string SpecifiedTypeName(Type type, Queue args) if (type.IsGenericParameter) { return name; - } + } if (type.IsNested) { name = $"{SpecifiedTypeName(type.DeclaringType, args)}.{name}"; @@ -62,7 +62,7 @@ static string SpecifiedTypeName(Type type, Queue args) genericTypeNames.Append(SpecifiedTypeName(args.Dequeue())); } - if (genericTypeNames.Length > 0) + if (genericTypeNames.Length > 0) { name = $"{name}<{genericTypeNames}>"; } diff --git a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUIControl.cs.meta b/Unity.Entities.Editor/CommonGUI/EntityQueryGUI.cs.meta similarity index 83% rename from Unity.Entities.Editor/CommonGUI/ComponentGroupGUIControl.cs.meta rename to Unity.Entities.Editor/CommonGUI/EntityQueryGUI.cs.meta index 0dc703dd..aa066e65 100644 --- a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUIControl.cs.meta +++ b/Unity.Entities.Editor/CommonGUI/EntityQueryGUI.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 910d2d0d5f8554bc5a32518b8fdcfee6 +guid: a2599509af17e8a4881f190635eea7a9 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUIControl.cs b/Unity.Entities.Editor/CommonGUI/EntityQueryGUIControl.cs similarity index 82% rename from Unity.Entities.Editor/CommonGUI/ComponentGroupGUIControl.cs rename to Unity.Entities.Editor/CommonGUI/EntityQueryGUIControl.cs index 60690f82..c0c30c1c 100644 --- a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUIControl.cs +++ b/Unity.Entities.Editor/CommonGUI/EntityQueryGUIControl.cs @@ -6,7 +6,7 @@ namespace Unity.Entities.Editor { - internal class ComponentGroupGUIControl + internal class EntityQueryGUIControl { private List styles; private List names; @@ -19,12 +19,12 @@ public float Height get { return height; } } - public ComponentGroupGUIControl(IEnumerable types, bool archetypeQueryMode) + public EntityQueryGUIControl(IEnumerable types, bool archetypeQueryMode) { CalculateDrawingParts(types, null, archetypeQueryMode); } - public ComponentGroupGUIControl(IEnumerable types, IEnumerable readWriteTypes, bool archetypeQueryMode) + public EntityQueryGUIControl(IEnumerable types, IEnumerable readWriteTypes, bool archetypeQueryMode) { CalculateDrawingParts(types, readWriteTypes, archetypeQueryMode); } @@ -32,7 +32,7 @@ public ComponentGroupGUIControl(IEnumerable types, IEnumerable types, IEnumerable readWriteTypes, bool archetypeQueryMode) { var typeList = types.ToList(); - typeList.Sort((Comparison) ComponentGroupGUI.CompareTypes); + typeList.Sort((Comparison) EntityQueryGUI.CompareTypes); styles = new List(typeList.Count); names = new List(typeList.Count); rects = new List(typeList.Count); @@ -45,7 +45,7 @@ void CalculateDrawingParts(IEnumerable types, IEnumerable types, IEnumerable>> cachedMatches = new List>>(); - private readonly Dictionary cachedControls = new Dictionary(); + private readonly List>> cachedMatches = new List>>(); + private readonly Dictionary cachedControls = new Dictionary(); private bool repainted = true; [SerializeField] private bool showSystems; @@ -26,14 +26,14 @@ public void OnGUI(World world, Entity entity) if (repainted == true) { cachedMatches.Clear(); - WorldDebuggingTools.MatchEntityInComponentGroups(world, entity, cachedMatches); + WorldDebuggingTools.MatchEntityInEntityQueries(world, entity, cachedMatches); foreach (var pair in cachedMatches) { foreach (var componentGroup in pair.Item2) { if (!cachedControls.ContainsKey(componentGroup)) { - cachedControls.Add(componentGroup, new ComponentGroupGUIControl(componentGroup.GetQueryTypes(), false)); + cachedControls.Add(componentGroup, new EntityQueryGUIControl(componentGroup.GetQueryTypes(), false)); } } } diff --git a/Unity.Entities.Editor/EntityDebugger/ChunkInfoListView.cs b/Unity.Entities.Editor/EntityDebugger/ChunkInfoListView.cs index 9b4d6a94..3a6aef97 100644 --- a/Unity.Entities.Editor/EntityDebugger/ChunkInfoListView.cs +++ b/Unity.Entities.Editor/EntityDebugger/ChunkInfoListView.cs @@ -77,7 +77,7 @@ static Styles() } public EntityArchetype archetype; - public ComponentGroupGUIControl control; + public EntityQueryGUIControl control; public int[] counts; public int maxCount; public int firstChunkIndex; @@ -225,7 +225,7 @@ protected override TreeViewItem BuildRoot() var stats = new ArchetypeInfo() { archetype = currentArchetype, - control = new ComponentGroupGUIControl(currentArchetype.GetComponentTypes(), true), + control = new EntityQueryGUIControl(currentArchetype.GetComponentTypes(), true), counts = new int[currentArchetype.ChunkCapacity], firstChunkIndex = currentChunkIndex }; diff --git a/Unity.Entities.Editor/EntityDebugger/ComponentTypeFilterUI.cs b/Unity.Entities.Editor/EntityDebugger/ComponentTypeFilterUI.cs index 9bef2cdb..1ceb6288 100644 --- a/Unity.Entities.Editor/EntityDebugger/ComponentTypeFilterUI.cs +++ b/Unity.Entities.Editor/EntityDebugger/ComponentTypeFilterUI.cs @@ -13,7 +13,7 @@ internal class ComponentTypeFilterUI private readonly List selectedFilterTypes = new List(); private readonly List filterTypes = new List(); - private readonly List entityQueries = new List(); + private readonly List entityQueries = new List(); public ComponentTypeFilterUI(SetFilterAction setFilter, WorldSelectionGetter worldSelectionGetter) { @@ -53,8 +53,8 @@ internal void GetTypes() filterTypes.AddRange(requiredTypes); filterTypes.AddRange(subtractiveTypes); - - filterTypes.Sort(ComponentGroupGUI.CompareTypes); + + filterTypes.Sort(EntityQueryGUI.CompareTypes); } } @@ -68,7 +68,7 @@ public void OnGUI() { ++filterCount; var style = filterTypes[i].AccessModeType == ComponentType.AccessMode.Exclude ? EntityDebuggerStyles.ComponentExclude : EntityDebuggerStyles.ComponentRequired; - GUILayout.Label(ComponentGroupGUI.SpecifiedTypeName(filterTypes[i].GetManagedType()), style); + GUILayout.Label(EntityQueryGUI.SpecifiedTypeName(filterTypes[i].GetManagedType()), style); } } if (filterCount == 0) @@ -90,7 +90,7 @@ public void OnGUI() } } - internal ComponentGroup GetExistingGroup(ComponentType[] components) + internal EntityQuery GetExistingQuery(ComponentType[] components) { foreach (var existingGroup in entityQueries) { @@ -101,12 +101,12 @@ internal ComponentGroup GetExistingGroup(ComponentType[] components) return null; } - internal ComponentGroup GetComponentGroup(ComponentType[] components) + internal EntityQuery GetEntityQuery(ComponentType[] components) { - var group = GetExistingGroup(components); + var group = GetExistingQuery(components); if (group != null) return group; - group = getWorldSelection().GetExistingManager().CreateComponentGroup(components); + group = getWorldSelection().EntityManager.CreateEntityQuery(components); entityQueries.Add(group); return group; @@ -120,7 +120,7 @@ private void ComponentFilterChanged() if (selectedFilterTypes[i]) selectedTypes.Add(filterTypes[i]); } - var group = GetComponentGroup(selectedTypes.ToArray()); + var group = GetEntityQuery(selectedTypes.ToArray()); setFilter(new EntityListQuery(group)); } } diff --git a/Unity.Entities.Editor/EntityDebugger/ComponentTypeListView.cs b/Unity.Entities.Editor/EntityDebugger/ComponentTypeListView.cs index 0b23ee6e..8f347aca 100644 --- a/Unity.Entities.Editor/EntityDebugger/ComponentTypeListView.cs +++ b/Unity.Entities.Editor/EntityDebugger/ComponentTypeListView.cs @@ -21,7 +21,7 @@ public ComponentTypeListView(TreeViewState state, List types, Lis this.typeSelections = typeSelections; typeNames = new List(types.Count); for (var i = 0; i < types.Count; ++i) - typeNames.Add(new GUIContent(ComponentGroupGUI.SpecifiedTypeName(types[i].GetManagedType()))); + typeNames.Add(new GUIContent(EntityQueryGUI.SpecifiedTypeName(types[i].GetManagedType()))); Reload(); } diff --git a/Unity.Entities.Editor/EntityDebugger/EntityDebugger.cs b/Unity.Entities.Editor/EntityDebugger/EntityDebugger.cs index 957caa14..ead0d351 100644 --- a/Unity.Entities.Editor/EntityDebugger/EntityDebugger.cs +++ b/Unity.Entities.Editor/EntityDebugger/EntityDebugger.cs @@ -3,6 +3,7 @@ using UnityEditor; using UnityEngine; using UnityEditor.IMGUI.Controls; +using UnityEngine.Serialization; namespace Unity.Entities.Editor { @@ -66,7 +67,7 @@ private static GUIStyle BoxStyle private static GUIStyle boxStyle; - public ScriptBehaviourManager SystemSelection { get; private set; } + public ComponentSystemBase SystemSelection { get; private set; } public World SystemSelectionWorld { @@ -74,7 +75,7 @@ public World SystemSelectionWorld private set { systemSelectionWorld = value; } } - public void SetSystemSelection(ScriptBehaviourManager manager, World world, bool updateList, bool propagate) + public void SetSystemSelection(ComponentSystemBase manager, World world, bool updateList, bool propagate) { if (manager != null && world == null) throw new ArgumentNullException("System cannot have null world"); @@ -82,11 +83,11 @@ public void SetSystemSelection(ScriptBehaviourManager manager, World world, bool SystemSelectionWorld = world; if (updateList) systemListView.SetSystemSelection(manager, world); - CreateComponentGroupListView(); + CreateEntityQueryListView(); if (propagate) { if (SystemSelection is ComponentSystemBase) - componentGroupListView.TouchSelection(); + entityQueryListView.TouchSelection(); else ApplyAllEntitiesFilter(); } @@ -99,7 +100,7 @@ public void SetEntityListSelection(EntityListQuery newSelection, bool updateList chunkInfoListView.ClearSelection(); EntityListQuerySelection = newSelection; if (updateList) - componentGroupListView.SetEntityListSelection(newSelection); + entityQueryListView.SetEntityListSelection(newSelection); entityListView.SelectedEntityQuery = newSelection; if (propagate) entityListView.TouchSelection(); @@ -112,7 +113,7 @@ internal void SetEntitySelection(Entity newSelection, bool updateList) if (updateList) entityListView.SetEntitySelection(newSelection); - var world = WorldSelection ?? (SystemSelection as ComponentSystemBase)?.World ?? (SystemSelection as EntityManager)?.World; + var world = WorldSelection ?? (SystemSelection as ComponentSystemBase)?.World; if (world != null && newSelection != Entity.Null) { selectionProxy.SetEntity(world, newSelection); @@ -139,25 +140,27 @@ internal static void SetAllSelections(World world, ComponentSystemBase system, E private static EntityDebugger Instance { get; set; } private EntitySelectionProxy selectionProxy; - - [SerializeField] private List componentGroupListStates = new List(); - [SerializeField] private List componentGroupListStateNames = new List(); - private ComponentGroupListView componentGroupListView; - + + [FormerlySerializedAs("componentGroupListStates")] + [SerializeField] private List entityQueryListStates = new List(); + [FormerlySerializedAs("componentGroupListStateNames")] + [SerializeField] private List entityQueryListStateNames = new List(); + private EntityQueryListView entityQueryListView; + [SerializeField] private List systemListStates = new List(); [SerializeField] private List systemListStateNames = new List(); internal SystemListView systemListView; [SerializeField] private TreeViewState entityListState = new TreeViewState(); private EntityListView entityListView; - + [SerializeField] private ChunkInfoListView.State chunkInfoListState = new ChunkInfoListView.State(); private ChunkInfoListView chunkInfoListView; internal WorldPopup m_WorldPopup; - + private ComponentTypeFilterUI filterUI; - + public World WorldSelection { get @@ -167,7 +170,7 @@ public World WorldSelection return null; } } - + [SerializeField] private string lastEditModeWorldSelection = WorldPopup.kNoWorldName; [SerializeField] private string lastPlayModeWorldSelection = WorldPopup.kNoWorldName; [SerializeField] private bool showingPlayerLoop; @@ -185,7 +188,7 @@ public void SetWorldSelection(World selection, bool propagate) else lastEditModeWorldSelection = worldSelection.Name; } - + CreateSystemListView(); if (propagate) systemListView.TouchSelection(); @@ -217,9 +220,9 @@ private void CreateSystemListView() systemListView.multiColumnHeader.ResizeToFit(); } - private void CreateComponentGroupListView() + private void CreateEntityQueryListView() { - componentGroupListView = ComponentGroupListView.CreateList(SystemSelection as ComponentSystemBase, componentGroupListStates, componentGroupListStateNames, x => SetEntityListSelection(x, false, true), () => SystemSelectionWorld); + entityQueryListView = EntityQueryListView.CreateList(SystemSelection as ComponentSystemBase, entityQueryListStates, entityQueryListStateNames, x => SetEntityListSelection(x, false, true), () => SystemSelectionWorld); } [SerializeField] private bool ShowInactiveSystems; @@ -253,7 +256,7 @@ private void OnEnable() CreateEntitySelectionProxy(); CreateWorldPopup(); CreateSystemListView(); - CreateComponentGroupListView(); + CreateEntityQueryListView(); CreateEntityListView(); CreateChunkInfoListView(); systemListView.TouchSelection(); @@ -285,7 +288,7 @@ private void OnDisable() Instance = null; if (selectionProxy) DestroyImmediate(selectionProxy); - + EditorApplication.playModeStateChanged -= OnPlayModeStateChange; } @@ -302,8 +305,8 @@ private void OnPlayModeStateChange(PlayModeStateChange change) private void Update() { systemListView.UpdateTimings(); - - + + if (repaintLimiter.SimulationAdvanced()) { @@ -311,7 +314,7 @@ private void Update() } else if (!Application.isPlaying) { - if (systemListView.NeedsReload || componentGroupListView.NeedsReload || entityListView.NeedsReload || !filterUI.TypeListValid()) + if (systemListView.NeedsReload || entityQueryListView.NeedsReload || entityListView.NeedsReload || !filterUI.TypeListValid()) Repaint(); } } @@ -342,7 +345,7 @@ private void SystemHeader() ShowWorldPopup(); GUILayout.EndHorizontal(); } - + const float kChunkInfoButtonWidth = 60f; private void EntityHeader() @@ -371,15 +374,15 @@ private void ChunkInfoToggle(Rect rect) ShowingChunkInfoView = GUI.Toggle(rect, ShowingChunkInfoView, "Chunk Info", EditorStyles.miniButton); } - private void ComponentGroupList() + private void EntityQueryList() { - if (SystemSelection is ComponentSystemBase) + if (SystemSelection != null) { - componentGroupListView.SetWidth(CurrentEntityViewWidth); - var height = Mathf.Min(componentGroupListView.Height + BoxStyle.padding.vertical, position.height*0.5f); + entityQueryListView.SetWidth(CurrentEntityViewWidth); + var height = Mathf.Min(entityQueryListView.Height + BoxStyle.padding.vertical, position.height*0.5f); GUILayout.BeginVertical(BoxStyle, GUILayout.Height(height)); - - componentGroupListView.OnGUI(GUIHelpers.GetExpandingRect()); + + entityQueryListView.OnGUI(GUIHelpers.GetExpandingRect()); GUILayout.EndVertical(); } else if (WorldSelection != null) @@ -399,11 +402,11 @@ private void ComponentGroupList() public void SetAllEntitiesFilter(EntityListQuery entityQuery) { filterQuery = entityQuery; - if (WorldSelection == null || SystemSelection is ComponentSystemBase) + if (WorldSelection == null || SystemSelection != null) return; ApplyAllEntitiesFilter(); } - + private void ApplyAllEntitiesFilter() { SetEntityListSelection(filterQuery, false, true); @@ -415,7 +418,7 @@ void EntityList() entityListView.OnGUI(GUIHelpers.GetExpandingRect()); GUILayout.EndVertical(); } - + private void ChunkInfoView() { GUILayout.BeginHorizontal(BoxStyle); @@ -459,10 +462,10 @@ private void OnGUI() { systemListView.ReloadIfNecessary(); filterUI.GetTypes(); - componentGroupListView.ReloadIfNecessary(); + entityQueryListView.ReloadIfNecessary(); entityListView.ReloadIfNecessary(); } - + if (Selection.activeObject == selectionProxy) { if (!selectionProxy.Exists) @@ -473,17 +476,17 @@ private void OnGUI() } GUILayout.BeginArea(new Rect(0f, 0f, kSystemListWidth, position.height)); // begin System side SystemHeader(); - + GUILayout.BeginVertical(BoxStyle); SystemList(); GUILayout.EndVertical(); - + GUILayout.EndArea(); // end System side - + EntityHeader(); - + GUILayout.BeginArea(new Rect(kSystemListWidth, kLineHeight, CurrentEntityViewWidth, position.height - kLineHeight)); - ComponentGroupList(); + EntityQueryList(); EntityList(); GUILayout.EndArea(); @@ -493,8 +496,8 @@ private void OnGUI() ChunkInfoView(); GUILayout.EndArea(); } - + repaintLimiter.RecordRepaint(); } } -} \ No newline at end of file +} diff --git a/Unity.Entities.Editor/EntityDebugger/EntityListQuery.cs b/Unity.Entities.Editor/EntityDebugger/EntityListQuery.cs index f5f439d0..d7728d43 100644 --- a/Unity.Entities.Editor/EntityDebugger/EntityListQuery.cs +++ b/Unity.Entities.Editor/EntityDebugger/EntityListQuery.cs @@ -5,18 +5,18 @@ namespace Unity.Entities.Editor internal class EntityListQuery { - public ComponentGroup Group { get; } + public EntityQuery Group { get; } - public EntityArchetypeQuery Query { get; } + public EntityQueryDesc QueryDesc { get; } - public EntityListQuery(ComponentGroup group) + public EntityListQuery(EntityQuery group) { this.Group = group; } - public EntityListQuery(EntityArchetypeQuery query) + public EntityListQuery(EntityQueryDesc queryDesc) { - this.Query = query; + this.QueryDesc = queryDesc; } } diff --git a/Unity.Entities.Editor/EntityDebugger/EntityListView.cs b/Unity.Entities.Editor/EntityDebugger/EntityListView.cs index 1054c787..5707beac 100644 --- a/Unity.Entities.Editor/EntityDebugger/EntityListView.cs +++ b/Unity.Entities.Editor/EntityDebugger/EntityListView.cs @@ -6,12 +6,12 @@ namespace Unity.Entities.Editor { - + internal delegate void EntitySelectionCallback(Entity selection); internal delegate World WorldSelectionGetter(); - internal delegate ScriptBehaviourManager SystemSelectionGetter(); + internal delegate ComponentSystemBase SystemSelectionGetter(); internal delegate void ChunkArrayAssignmentCallback(NativeArray chunkArray); - + internal class EntityListView : TreeView, IDisposable { public EntityListQuery SelectedEntityQuery @@ -41,7 +41,7 @@ public void SetFilter(ChunkFilter filter) private readonly WorldSelectionGetter getWorldSelection; private readonly SystemSelectionGetter getSystemSelection; private readonly ChunkArrayAssignmentCallback setChunkArray; - + private readonly EntityArrayListAdapter rows; public NativeArray ChunkArray => chunkArray; @@ -64,7 +64,7 @@ public EntityListView(TreeViewState state, EntityListQuery entityQuery, EntitySe private int lastVersion = -1; - public bool NeedsReload => ShowingSomething && getWorldSelection().GetExistingManager().Version != lastVersion; + public bool NeedsReload => ShowingSomething && getWorldSelection().EntityManager.Version != lastVersion; public void ReloadIfNecessary() { @@ -77,42 +77,42 @@ public void ReloadIfNecessary() protected override TreeViewItem BuildRoot() { var root = new TreeViewItem { id = 0, depth = -1, displayName = "Root" }; - + return root; } - + protected override IList BuildRows(TreeViewItem root) { if (!ShowingSomething) return new List(); - var entityManager = getWorldSelection().GetExistingManager(); + var entityManager = getWorldSelection().EntityManager; if (chunkArray.IsCreated) chunkArray.Dispose(); - + entityManager.CompleteAllJobs(); var group = SelectedEntityQuery?.Group; - + if (group == null) { - var query = SelectedEntityQuery?.Query; + var query = SelectedEntityQuery?.QueryDesc; if (query == null) - group = entityManager.UniversalGroup; + group = entityManager.UniversalQuery; else { - group = entityManager.CreateComponentGroup(query); + group = entityManager.CreateEntityQuery(query); } } - + chunkArray = group.CreateArchetypeChunkArray(Allocator.Persistent); rows.SetSource(chunkArray, entityManager, chunkFilter); setChunkArray(chunkArray); lastVersion = entityManager.Version; - + return rows; } @@ -128,7 +128,7 @@ protected override IList GetDescendantsThatHaveChildren(int id) public override void OnGUI(Rect rect) { - if (getWorldSelection()?.GetExistingManager()?.IsCreated == true) + if (getWorldSelection()?.EntityManager.IsCreated == true) base.OnGUI(rect); } @@ -165,7 +165,7 @@ protected override void RenameEnded(RenameEndedArgs args) { if (args.acceptedRename) { - var manager = getWorldSelection()?.GetExistingManager(); + var manager = getWorldSelection()?.EntityManager; if (manager != null) { Entity entity; @@ -184,7 +184,7 @@ public void SelectNothing() public void SetEntitySelection(Entity entitySelection) { - if (entitySelection != Entity.Null && getWorldSelection().GetExistingManager().Exists(entitySelection)) + if (entitySelection != Entity.Null && getWorldSelection().EntityManager.Exists(entitySelection)) SetSelection(new List{EntityArrayListAdapter.IndexToItemId(entitySelection.Index)}); } diff --git a/Unity.Entities.Editor/EntityDebugger/ComponentGroupListView.cs b/Unity.Entities.Editor/EntityDebugger/EntityQueryListView.cs similarity index 76% rename from Unity.Entities.Editor/EntityDebugger/ComponentGroupListView.cs rename to Unity.Entities.Editor/EntityDebugger/EntityQueryListView.cs index 157ce81a..3a24ee06 100644 --- a/Unity.Entities.Editor/EntityDebugger/ComponentGroupListView.cs +++ b/Unity.Entities.Editor/EntityDebugger/EntityQueryListView.cs @@ -9,15 +9,15 @@ namespace Unity.Entities.Editor { internal delegate void SetEntityListSelection(EntityListQuery query); - internal class ComponentGroupListView : TreeView { - private static Dictionary> queriesBySystem = new Dictionary>(); - private static readonly Dictionary queriesByGroup = new Dictionary(); + internal class EntityQueryListView : TreeView { + private static Dictionary> queriesBySystem = new Dictionary>(); + private static readonly Dictionary queriesByGroup = new Dictionary(); - private static EntityArchetypeQuery GetQueryForGroup(ComponentGroup group) + private static EntityQueryDesc GetQueryForGroup(EntityQuery group) { if (!queriesByGroup.ContainsKey(group)) { - var query = new EntityArchetypeQuery() + var query = new EntityQueryDesc() { All = group.GetQueryTypes().Where(x => x.AccessModeType != ComponentType.AccessMode.Exclude).ToArray(), Any = new ComponentType[0], @@ -29,9 +29,9 @@ private static EntityArchetypeQuery GetQueryForGroup(ComponentGroup group) return queriesByGroup[group]; } - private readonly Dictionary componentGroupsById = new Dictionary(); - private readonly Dictionary queriesById = new Dictionary(); - private readonly Dictionary controlsById = new Dictionary(); + private readonly Dictionary componentGroupsById = new Dictionary(); + private readonly Dictionary queriesById = new Dictionary(); + private readonly Dictionary controlsById = new Dictionary(); public ComponentSystemBase SelectedSystem { @@ -62,21 +62,21 @@ private static TreeViewState GetStateForSystem(ComponentSystemBase system, List< return stateForCurrentSystem; stateForCurrentSystem = new TreeViewState(); - if (system.ComponentGroups != null && system.ComponentGroups.Length > 0) + if (system.EntityQueries != null && system.EntityQueries.Length > 0) stateForCurrentSystem.expandedIDs = new List {1}; states.Add(stateForCurrentSystem); stateNames.Add(currentSystemName); return stateForCurrentSystem; } - public static ComponentGroupListView CreateList(ComponentSystemBase system, List states, List stateNames, + public static EntityQueryListView CreateList(ComponentSystemBase system, List states, List stateNames, SetEntityListSelection entityQuerySelectionCallback, WorldSelectionGetter worldSelectionGetter) { var state = GetStateForSystem(system, states, stateNames); - return new ComponentGroupListView(state, system, entityQuerySelectionCallback, worldSelectionGetter); + return new EntityQueryListView(state, system, entityQuerySelectionCallback, worldSelectionGetter); } - public ComponentGroupListView(TreeViewState state, ComponentSystemBase system, SetEntityListSelection entityListSelectionCallback, WorldSelectionGetter worldSelectionGetter) : base(state) + public EntityQueryListView(TreeViewState state, ComponentSystemBase system, SetEntityListSelection entityListSelectionCallback, WorldSelectionGetter worldSelectionGetter) : base(state) { this.getWorldSelection = worldSelectionGetter; this.entityListSelectionCallback = entityListSelectionCallback; @@ -93,13 +93,13 @@ protected override float GetCustomRowHeight(int row, TreeViewItem item) return controlsById.ContainsKey(item.id) ? controlsById[item.id].Height + 2 : rowHeight; } - private static List GetQueriesForSystem(ComponentSystemBase system) + private static List GetQueriesForSystem(ComponentSystemBase system) { - List queries; + List queries; if (queriesBySystem.TryGetValue(system, out queries)) return queries; - queries = new List(); + queries = new List(); var currentType = system.GetType(); @@ -107,8 +107,8 @@ private static List GetQueriesForSystem(ComponentSystemBas { foreach (var field in currentType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { - if (field.FieldType == typeof(EntityArchetypeQuery)) - queries.Add(field.GetValue(system) as EntityArchetypeQuery); + if (field.FieldType == typeof(EntityQueryDesc)) + queries.Add(field.GetValue(system) as EntityQueryDesc); } currentType = currentType.BaseType; @@ -135,20 +135,20 @@ protected override TreeViewItem BuildRoot() else { var queries = GetQueriesForSystem(SelectedSystem); - var entityManager = getWorldSelection().GetExistingManager(); + var entityManager = getWorldSelection().EntityManager; foreach (var query in queries) { - var group = entityManager.CreateComponentGroup(query); + var group = entityManager.CreateEntityQuery(query); queriesById.Add(currentId, query); componentGroupsById.Add(currentId, group); var groupItem = new TreeViewItem { id = currentId++ }; root.AddChild(groupItem); } - if (SelectedSystem.ComponentGroups != null) + if (SelectedSystem.EntityQueries != null) { - foreach (var group in SelectedSystem.ComponentGroups) + foreach (var group in SelectedSystem.EntityQueries) { componentGroupsById.Add(currentId, group); @@ -166,7 +166,7 @@ protected override TreeViewItem BuildRoot() foreach (var idGroupPair in componentGroupsById) { - var newControl = new ComponentGroupGUIControl(idGroupPair.Value.GetQueryTypes(), idGroupPair.Value.GetReadAndWriteTypes(), true); + var newControl = new EntityQueryGUIControl(idGroupPair.Value.GetQueryTypes(), idGroupPair.Value.GetReadAndWriteTypes(), true); controlsById.Add(idGroupPair.Key, newControl); } } @@ -195,7 +195,7 @@ public void SetWidth(float newWidth) public override void OnGUI(Rect rect) { - if (getWorldSelection()?.GetExistingManager()?.IsCreated == true) + if (getWorldSelection()?.EntityManager.IsCreated == true) { if (Event.current.type == EventType.Repaint) { @@ -207,10 +207,10 @@ public override void OnGUI(Rect rect) protected void DrawCount(RowGUIArgs args) { - ComponentGroup componentGroup; - if (componentGroupsById.TryGetValue(args.item.id, out componentGroup)) + EntityQuery entityQuery; + if (componentGroupsById.TryGetValue(args.item.id, out entityQuery)) { - var countString = componentGroup.CalculateLength().ToString(); + var countString = entityQuery.CalculateLength().ToString(); DefaultGUI.LabelRightAligned(args.rowRect, countString, args.selected, args.focused); } } @@ -234,9 +234,9 @@ protected override void SelectionChanged(IList selectedIds) { if (selectedIds.Count > 0) { - ComponentGroup componentGroup; - if (componentGroupsById.TryGetValue(selectedIds[0], out componentGroup)) - entityListSelectionCallback(new EntityListQuery(componentGroup)); + EntityQuery entityQuery; + if (componentGroupsById.TryGetValue(selectedIds[0], out entityQuery)) + entityListSelectionCallback(new EntityListQuery(entityQuery)); } else { @@ -271,7 +271,7 @@ public void SetEntityListSelection(EntityListQuery newListQuery) { foreach (var pair in queriesById) { - if (pair.Value == newListQuery.Query) + if (pair.Value == newListQuery.QueryDesc) { SetSelection(new List {pair.Key}); return; @@ -281,7 +281,7 @@ public void SetEntityListSelection(EntityListQuery newListQuery) SetSelection(new List()); } - public void SetComponentGroupSelection(ComponentGroup group) + public void SetEntityQuerySelection(EntityQuery group) { SetSelection(new List()); } @@ -295,7 +295,7 @@ public bool NeedsReload { get { - var expectedGroupCount = SelectedSystem?.ComponentGroups?.Length ?? 0; + var expectedGroupCount = SelectedSystem?.EntityQueries?.Length ?? 0; return expectedGroupCount != componentGroupsById.Count; } diff --git a/Unity.Entities.Editor/IJobProcessComponentDataGenerator.cs.meta b/Unity.Entities.Editor/EntityDebugger/EntityQueryListView.cs.meta similarity index 83% rename from Unity.Entities.Editor/IJobProcessComponentDataGenerator.cs.meta rename to Unity.Entities.Editor/EntityDebugger/EntityQueryListView.cs.meta index 216c4e00..ce66e690 100644 --- a/Unity.Entities.Editor/IJobProcessComponentDataGenerator.cs.meta +++ b/Unity.Entities.Editor/EntityDebugger/EntityQueryListView.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 102f0b713c27d488c87e97a3506bd2d9 +guid: ef7ed95af4a49594e977be31384c6908 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Unity.Entities.Editor/EntityDebugger/SystemListView.cs b/Unity.Entities.Editor/EntityDebugger/SystemListView.cs index 13809355..8a0b250c 100644 --- a/Unity.Entities.Editor/EntityDebugger/SystemListView.cs +++ b/Unity.Entities.Editor/EntityDebugger/SystemListView.cs @@ -8,7 +8,7 @@ namespace Unity.Entities.Editor { - internal delegate void SystemSelectionCallback(ScriptBehaviourManager manager, World world); + internal delegate void SystemSelectionCallback(ComponentSystemBase manager, World world); internal class SystemListView : TreeView { @@ -43,7 +43,7 @@ public float ReadMilliseconds() } internal readonly Dictionary managersById = new Dictionary(); private readonly Dictionary worldsById = new Dictionary(); - private readonly Dictionary recordersByManager = new Dictionary(); + private readonly Dictionary recordersByManager = new Dictionary(); private readonly Dictionary hideNodesById = new Dictionary(); private const float kToggleWidth = 22f; @@ -249,7 +249,7 @@ private HideNode BuildNodesForPlayerLoopSystem(PlayerLoopSystem system, ref int if (executionDelegate != null && (dummy = executionDelegate.Target as ScriptBehaviourUpdateOrder.DummyDelegateWrapper) != null) { - var rootSystem = dummy.Manager; + var rootSystem = dummy.System; return BuildNodesForComponentSystem(rootSystem, ref currentId); } } @@ -264,7 +264,7 @@ private HideNode BuildNodesForPlayerLoopSystem(PlayerLoopSystem system, ref int return null; } - private HideNode BuildNodesForComponentSystem(ScriptBehaviourManager manager, ref int currentId) + private HideNode BuildNodesForComponentSystem(ComponentSystemBase manager, ref int currentId) { switch (manager) { @@ -497,7 +497,7 @@ public bool NeedsReload { if (manager is ComponentSystemBase system) { - if (system.World == null || !system.World.BehaviourManagers.Contains(manager)) + if (system.World == null || !system.World.Systems.Contains(manager)) return true; } } @@ -527,7 +527,7 @@ public void UpdateTimings() lastTimedFrame = Time.frameCount; } - public void SetSystemSelection(ScriptBehaviourManager manager, World world) + public void SetSystemSelection(ComponentSystemBase manager, World world) { foreach (var pair in managersById) { diff --git a/Unity.Entities.Editor/EntityInspector/EntitySelectionProxy.cs b/Unity.Entities.Editor/EntityInspector/EntitySelectionProxy.cs index 1ed2f124..5aece152 100644 --- a/Unity.Entities.Editor/EntityInspector/EntitySelectionProxy.cs +++ b/Unity.Entities.Editor/EntityInspector/EntitySelectionProxy.cs @@ -35,7 +35,7 @@ public void SetEntity(World world, Entity entity) { this.World = world; this.Entity = entity; - this.EntityManager = world.GetExistingManager(); + this.EntityManager = world.EntityManager; this.Container = new EntityContainer(EntityManager, Entity); EditorUtility.SetDirty(this); } diff --git a/Unity.Entities.Editor/EntityInspector/EntitySelectionProxyEditor.cs b/Unity.Entities.Editor/EntityInspector/EntitySelectionProxyEditor.cs index 0e0ddcf8..252f3b66 100644 --- a/Unity.Entities.Editor/EntityInspector/EntitySelectionProxyEditor.cs +++ b/Unity.Entities.Editor/EntityInspector/EntitySelectionProxyEditor.cs @@ -13,7 +13,7 @@ internal class EntitySelectionProxyEditor : UnityEditor.Editor private readonly RepaintLimiter repaintLimiter = new RepaintLimiter(); [SerializeField] private SystemInclusionList inclusionList; - + void OnEnable() { visitor = new EntityIMGUIVisitor((entity) => @@ -32,7 +32,7 @@ void OnEnable() private uint GetVersion() { var container = target as EntitySelectionProxy; - return container.World.GetExistingManager().GetChunkVersionHash(container.Entity); + return container.World.EntityManager.GetChunkVersionHash(container.Entity); } public override void OnInspectorGUI() @@ -46,9 +46,9 @@ public override void OnInspectorGUI() (targetProxy.Container.PropertyBag as StructPropertyBag)?.Visit(ref container, visitor); GUI.enabled = true; - + inclusionList.OnGUI(targetProxy.World, targetProxy.Entity); - + repaintLimiter.RecordRepaint(); lastVersion = GetVersion(); } diff --git a/Unity.Entities.Editor/ExtraTypesProvider.cs b/Unity.Entities.Editor/ExtraTypesProvider.cs index 7b6951f6..770c6775 100644 --- a/Unity.Entities.Editor/ExtraTypesProvider.cs +++ b/Unity.Entities.Editor/ExtraTypesProvider.cs @@ -11,11 +11,11 @@ namespace Unity.Entities.Editor [InitializeOnLoad] public sealed class ExtraTypesProvider { - static void AddIJobProcessComponentData(Type type, HashSet extraTypes) + static void AddIJobForEach(Type type, HashSet extraTypes) { foreach (var typeInterface in type.GetInterfaces()) { - if (typeInterface.Name.StartsWith("IJobProcessComponentData")) + if (typeInterface.Name.StartsWith("IJobForEach")) { var genericArgumentList = new List { type }; genericArgumentList.AddRange(typeInterface.GetGenericArguments()); @@ -23,7 +23,7 @@ static void AddIJobProcessComponentData(Type type, HashSet extraTypes) var producerAttribute = (JobProducerTypeAttribute) typeInterface.GetCustomAttribute(typeof(JobProducerTypeAttribute), true); if (producerAttribute == null) - throw new System.ArgumentException("IJobProcessComponentData interface must have [JobProducerType]"); + throw new System.ArgumentException("IJobForEach interface must have [JobProducerType]"); var generatedType = producerAttribute.ProducerType.MakeGenericType(genericArgumentList.ToArray()); extraTypes.Add(generatedType.ToString()); @@ -35,7 +35,7 @@ static void AddIJobProcessComponentData(Type type, HashSet extraTypes) static ExtraTypesProvider() { - //@TODO: Only produce JobProcessComponentDataExtensions.JobStruct_Process1 + //@TODO: Only produce JobForEachExtensions.JobStruct_Process1 // if there is any use of that specific type in deployed code. PlayerBuildInterface.ExtraTypesProvider += () => @@ -49,9 +49,9 @@ static ExtraTypesProvider() foreach (var type in assembly.GetTypes()) { - if (typeof(JobProcessComponentDataExtensions.IBaseJobProcessComponentData).IsAssignableFrom(type) && !type.IsAbstract) + if (typeof(JobForEachExtensions.IBaseJobForEach).IsAssignableFrom(type) && !type.IsAbstract) { - AddIJobProcessComponentData(type, extraTypes); + AddIJobForEach(type, extraTypes); } } } diff --git a/Unity.Entities.Editor/IJobProcessComponentDataGenerator.cs b/Unity.Entities.Editor/IJobProcessComponentDataGenerator.cs deleted file mode 100644 index 82d27b69..00000000 --- a/Unity.Entities.Editor/IJobProcessComponentDataGenerator.cs +++ /dev/null @@ -1,358 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using UnityEditor; - -#if false -namespace Unity.Entities -{ - public static class IJobProcessComponentDataGenerator - { - enum Combination - { - D - } - - [MenuItem("Tools/Gen IJobProcessComponentData")] - static void GenTest() - { - var combinations = new List(); - for (int count = 1; count <= 6; count++) - { - var array = new Combination[count]; - for (var c = 0; c != array.Length; c++) - array[c] = Combination.D; - - combinations.Add(array); - } - - var res = GenerateFile(combinations); - - File.WriteAllText("Packages/com.unity.entities/Unity.Entities/IJobProcessComponentData.generated.cs", res); - AssetDatabase.Refresh(); - - } - - static string GetComboString(bool withEntity, Combination[] combinations) - { - var baseType = new StringBuilder(); - - if (withEntity) - baseType.Append("E"); - foreach (var c in combinations) - baseType.Append(Enum.GetName(typeof(Combination), c)); - return baseType.ToString(); - } - - static void GenerateScheduleFunc(List combinations, string funcName, int forEach, - string scheduleMode, StringBuilder gen) - { - gen.Append - ( - $@" - public static JobHandle {funcName}(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - {{ - var typeT = typeof(T);" - ); - - foreach (var combination in combinations) - { - string comboString; - comboString = GetComboString(false, combination); - gen.Append( - $@" - if (typeof(IBaseJobProcessComponentData_{comboString}).IsAssignableFrom(typeT)) - return ScheduleInternal_{comboString}(ref jobData, system, null, {forEach}, dependsOn, {scheduleMode});" - ); - - comboString = GetComboString(true, combination); - gen.Append( - $@" - if (typeof(IBaseJobProcessComponentData_{comboString}).IsAssignableFrom(typeT)) - return ScheduleInternal_{comboString}(ref jobData, system, null, {forEach}, dependsOn, {scheduleMode});" - ); - } - - gen.Append - ( - $@" - throw new System.ArgumentException({'"'}Not supported{'"'}); - }} -" - ); - } - - static void GenerateScheduleGroupFunc(List combinations, string funcName, int forEach, - string scheduleMode, StringBuilder gen) - { - gen.Append - ( - $@" - public static JobHandle {funcName}(this T jobData, ComponentGroup componentGroup, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - {{ - var typeT = typeof(T);" - ); - - foreach (var combination in combinations) - { - string comboString; - comboString = GetComboString(false, combination); - gen.Append( - $@" - if (typeof(IBaseJobProcessComponentData_{comboString}).IsAssignableFrom(typeT)) - return ScheduleInternal_{comboString}(ref jobData, null, componentGroup, {forEach}, dependsOn, {scheduleMode});" - ); - - comboString = GetComboString(true, combination); - gen.Append( - $@" - if (typeof(IBaseJobProcessComponentData_{comboString}).IsAssignableFrom(typeT)) - return ScheduleInternal_{comboString}(ref jobData, null, componentGroup, {forEach}, dependsOn, {scheduleMode});" - ); - } - - gen.Append - ( - $@" - throw new System.ArgumentException({'"'}Not supported{'"'}); - }} -" - ); - } - - static string GenerateFile(List combinations) - { - var gen = new StringBuilder(); - var igen = new StringBuilder(); - - GenerateScheduleFunc(combinations, "Schedule", 1, "ScheduleMode.Batched", gen); - GenerateScheduleFunc(combinations, "ScheduleSingle", -1, "ScheduleMode.Batched", gen); - GenerateScheduleFunc(combinations, "Run", -1, "ScheduleMode.Run", gen); - - GenerateScheduleGroupFunc(combinations, "ScheduleGroup", 1, "ScheduleMode.Batched", gen); - GenerateScheduleGroupFunc(combinations, "ScheduleGroupSingle", -1, "ScheduleMode.Batched", gen); - GenerateScheduleGroupFunc(combinations, "RunGroup", -1, "ScheduleMode.Run", gen); - - foreach (var combination in combinations) - { - Generate(false, combination, gen, igen); - Generate(true, combination, gen, igen); - } - - var res = - ( - $@"// Generated by IJobProcessComponentDataGenerator.cs -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ -#if !UNITY_ZEROPLAYER - -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; -using Unity.Jobs; -using Unity.Jobs.LowLevel.Unsafe; -using System.Runtime.InteropServices; -using UnityEngine.Scripting; -using System; - - -namespace Unity.Entities -{{ - -{igen} - - public static partial class JobProcessComponentDataExtensions - {{ -{gen} - }} -}} - -#endif -" - ); - - return res; - } - - - static string Generate(bool withEntity, Combination[] combination, StringBuilder gen, StringBuilder igen) - { - var comboString = GetComboString(withEntity, combination); - var untypedGenericParams = new StringBuilder(); - var genericParams = new StringBuilder(); - var genericConstraints = new StringBuilder(); - - var executeParams = new StringBuilder(); - var executeCallParams = new StringBuilder(); - var ptrs = new StringBuilder(); - var typeLookupCache = new StringBuilder(); - - var interfaceName = withEntity ? "IJobProcessComponentDataWithEntity" : "IJobProcessComponentData"; - - if (withEntity) - { - executeCallParams.Append("ptrE[i], i + beginIndex, "); - executeParams.Append("Entity entity, int index, "); - ptrs.AppendLine - ( -$" var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion));" - ); - } - - for (int i = 0; i != combination.Length; i++) - { - ptrs.AppendLine - ( - -$@" ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex{i}, ref typeLookupCache{i}); - var ptr{i} = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly{i} == 0, typeLookupCache{i}, jobData.Iterator.GlobalSystemVersion));" - ); - - typeLookupCache.AppendLine - ( - -$@" var typeLookupCache{i} = 0; " - ); - - genericConstraints.Append($" where U{i} : struct, IComponentData"); - if (i != combination.Length - 1) - genericConstraints.AppendLine(); - untypedGenericParams.Append(","); - - genericParams.Append($"U{i}"); - if (i != combination.Length - 1) - genericParams.Append(", "); - - executeCallParams.Append($"ref UnsafeUtilityEx.ArrayElementAsRef(ptr{i}, i)"); - if (i != combination.Length - 1) - executeCallParams.Append(", "); - - executeParams.Append($"ref U{i} c{i}"); - if (i != combination.Length - 1) - executeParams.Append(", "); - } - - - igen.Append - ( - $@" - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_{comboString}<{untypedGenericParams}>))] - public interface {interfaceName}<{genericParams}> : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_{comboString} -{genericConstraints} - {{ - void Execute({executeParams}); - }}" - ); - - - gen.Append - ( - $@" - internal static unsafe JobHandle ScheduleInternal_{comboString}(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - {{ - JobStruct_ProcessInfer_{comboString} fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_{comboString}<{untypedGenericParams}>), isParallelFor, ref JobStruct_ProcessInfer_{comboString}.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_{comboString}.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_{comboString}.Cache, deferredCountData, prefilterHandle, mode); - }} - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_{comboString} : IBaseJobProcessComponentData {{ }} - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_{comboString} where T : struct - {{ - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - }} - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_{comboString} - where T : struct, {interfaceName}<{genericParams}> -{genericConstraints} - {{ - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - {{ - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_{comboString}), typeof(T), jobType, (ExecuteJobFunction) Execute); - }} - - delegate void ExecuteJobFunction(ref JobStruct_Process_{comboString} data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_{comboString} jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - {{ - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - {{ - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - }} - else - {{ - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - }} - }} - - static unsafe void ExecuteChunk(ref JobStruct_Process_{comboString} jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - {{ -{typeLookupCache} - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - {{ - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif -{ptrs} - - for (var i = 0; i != count; i++) - {{ - jobData.Data.Execute({executeCallParams}); - }} - }} - }} - }} -" - ); - - return gen.ToString(); - } - } -} -#endif diff --git a/ScriptTemplates.meta b/Unity.Entities.Editor/ScriptTemplates.meta similarity index 100% rename from ScriptTemplates.meta rename to Unity.Entities.Editor/ScriptTemplates.meta diff --git a/Unity.Entities.Editor/ScriptTemplates/AuthoringComponent.txt b/Unity.Entities.Editor/ScriptTemplates/AuthoringComponent.txt new file mode 100644 index 00000000..9eb2e86b --- /dev/null +++ b/Unity.Entities.Editor/ScriptTemplates/AuthoringComponent.txt @@ -0,0 +1,36 @@ +using Unity.Entities; +using Unity.Mathematics; +using UnityEngine; + +[DisallowMultipleComponent] +[RequiresEntityConversion] +public class #SCRIPTNAME# : MonoBehaviour, IConvertGameObjectToEntity +{ + // Add fields to your component here. Remember that: + // + // * The purpose of this class is to store data for authoring purposes - it is not for use while the game is + // running. + // + // * Traditional Unity serialization rules apply: fields must be public or marked with [SerializeField], and + // must be one of the supported types. + // + // For example, + // public float scale; + #NOTRIM# + #NOTRIM# + + public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) + { + // Call methods on 'dstManager' to create runtime components on 'entity' here. Remember that: + // + // * You can add more than one component to the entity. It's also OK to not add any at all. + // + // * If you want to create more than one entity from the data in this class, use the 'conversionSystem' + // to do it, instead of adding entities through 'dstManager' directly. + // + // For example, + // dstManager.AddComponentData(entity, new Unity.Transforms.Scale { Value = scale }); + #NOTRIM# + #NOTRIM# + } +} diff --git a/Unity.Entities.Editor/ScriptTemplates/AuthoringComponent.txt.meta b/Unity.Entities.Editor/ScriptTemplates/AuthoringComponent.txt.meta new file mode 100644 index 00000000..305e310e --- /dev/null +++ b/Unity.Entities.Editor/ScriptTemplates/AuthoringComponent.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d47db0d26b3754ceca18d8e1a04f577a +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/ScriptTemplates/ECS__Component Type-NewComponentType.cs.txt b/Unity.Entities.Editor/ScriptTemplates/RunTimeComponent.txt similarity index 67% rename from ScriptTemplates/ECS__Component Type-NewComponentType.cs.txt rename to Unity.Entities.Editor/ScriptTemplates/RunTimeComponent.txt index fa08bab0..a96e461a 100644 --- a/ScriptTemplates/ECS__Component Type-NewComponentType.cs.txt +++ b/Unity.Entities.Editor/ScriptTemplates/RunTimeComponent.txt @@ -8,13 +8,17 @@ public struct #SCRIPTNAME# : IComponentData { // Add fields to your component here. Remember that: // - // * A component itself is for storing data and doesn't 'do' anything + // * A component itself is for storing data and doesn't 'do' anything. // - // * To act on the data, you will need a System + // * To act on the data, you will need a System. // // * Data in a component must be blittable, which means a component can // only contain fields which are primitive types or other blittable // structs; they cannot contain references to classes. + // + // * You should focus on the data structure that makes the most sense + // for runtime use here. Authoring Components will be used for + // authoring the data in the Editor. #NOTRIM# #NOTRIM# } diff --git a/ScriptTemplates/ECS__Component Type-NewComponentType.cs.txt.meta b/Unity.Entities.Editor/ScriptTemplates/RunTimeComponent.txt.meta similarity index 100% rename from ScriptTemplates/ECS__Component Type-NewComponentType.cs.txt.meta rename to Unity.Entities.Editor/ScriptTemplates/RunTimeComponent.txt.meta diff --git a/Unity.Entities.Editor/ScriptTemplates/ScriptTemplates.cs b/Unity.Entities.Editor/ScriptTemplates/ScriptTemplates.cs new file mode 100644 index 00000000..dbb875c3 --- /dev/null +++ b/Unity.Entities.Editor/ScriptTemplates/ScriptTemplates.cs @@ -0,0 +1,37 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; + +namespace Unity.Entities.Editor +{ + + internal class ScriptTemplates + { + public const string TemplatesRoot = "Packages/com.unity.entities/Unity.Entities.Editor/ScriptTemplates"; + + [MenuItem("Assets/Create/ECS/Runtime Component Type")] + public static void CreateRuntimeComponentType() + { + ProjectWindowUtil.CreateScriptAssetFromTemplateFile( + $"{TemplatesRoot}/RunTimeComponent.txt", + "NewComponent.cs"); + } + + [MenuItem("Assets/Create/ECS/Authoring Component Type")] + public static void CreateAuthoringComponentType() + { + ProjectWindowUtil.CreateScriptAssetFromTemplateFile( + $"{TemplatesRoot}/AuthoringComponent.txt", + "NewComponent.cs"); + } + + [MenuItem("Assets/Create/ECS/System")] + public static void CreateSystem() + { + ProjectWindowUtil.CreateScriptAssetFromTemplateFile( + $"{TemplatesRoot}/System.txt", + "NewSystem.cs"); + } + } + +} \ No newline at end of file diff --git a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUI.cs.meta b/Unity.Entities.Editor/ScriptTemplates/ScriptTemplates.cs.meta similarity index 83% rename from Unity.Entities.Editor/CommonGUI/ComponentGroupGUI.cs.meta rename to Unity.Entities.Editor/ScriptTemplates/ScriptTemplates.cs.meta index 79798205..b803356e 100644 --- a/Unity.Entities.Editor/CommonGUI/ComponentGroupGUI.cs.meta +++ b/Unity.Entities.Editor/ScriptTemplates/ScriptTemplates.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 01aaabedd6a3443f1b0702e31df8e517 +guid: 3db8275d04ea14fd9a69331827c45292 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/ScriptTemplates/ECS__System-NewSystem.cs.txt b/Unity.Entities.Editor/ScriptTemplates/System.txt similarity index 81% rename from ScriptTemplates/ECS__System-NewSystem.cs.txt rename to Unity.Entities.Editor/ScriptTemplates/System.txt index 78bc761f..63199072 100644 --- a/ScriptTemplates/ECS__System-NewSystem.cs.txt +++ b/Unity.Entities.Editor/ScriptTemplates/System.txt @@ -9,15 +9,15 @@ using static Unity.Mathematics.math; public class #SCRIPTNAME# : JobComponentSystem { // This declares a new kind of job, which is a unit of work to do. - // The job is declared as an IJobProcessComponentData, + // The job is declared as an IJobForEach, // meaning it will process all entities in the world that have both - // Position and Rotation components. Change it to process the component + // Translation and Rotation components. Change it to process the component // types you want. // // The job is also tagged with the BurstCompile attribute, which means // that the Burst compiler will optimize it for the best performance. [BurstCompile] - struct #SCRIPTNAME#Job : IJobProcessComponentData + struct #SCRIPTNAME#Job : IJobForEach { // Add fields here that your job needs to do its work. // For example, @@ -25,7 +25,7 @@ public class #SCRIPTNAME# : JobComponentSystem #NOTRIM# #NOTRIM# #NOTRIM# - public void Execute(ref Position position, [ReadOnly] ref Rotation rotation) + public void Execute(ref Translation translation, [ReadOnly] ref Rotation rotation) { // Implement the work to perform for each entity here. // You should only access data that is local or that is a @@ -34,7 +34,7 @@ public class #SCRIPTNAME# : JobComponentSystem // but allows this job to run in parallel with other jobs // that want to read Rotation component data. // For example, - // position.Value += mul(rotation.Value, new float3(0, 0, 1)) * deltaTime; + // translation.Value += mul(rotation.Value, new float3(0, 0, 1)) * deltaTime; #NOTRIM# #NOTRIM# } diff --git a/ScriptTemplates/ECS__System-NewSystem.cs.txt.meta b/Unity.Entities.Editor/ScriptTemplates/System.txt.meta similarity index 100% rename from ScriptTemplates/ECS__System-NewSystem.cs.txt.meta rename to Unity.Entities.Editor/ScriptTemplates/System.txt.meta diff --git a/Unity.Entities.Hybrid.Tests/ComponentDataProxy_EntityManager_IntegrationTests.cs b/Unity.Entities.Hybrid.Tests/ComponentDataProxy_EntityManager_IntegrationTests.cs index 573cf071..30f41fa9 100644 --- a/Unity.Entities.Hybrid.Tests/ComponentDataProxy_EntityManager_IntegrationTests.cs +++ b/Unity.Entities.Hybrid.Tests/ComponentDataProxy_EntityManager_IntegrationTests.cs @@ -125,7 +125,7 @@ public void ComponentDataProxy_WhenEntityManagerIsInvalid_SynchronizesWithEntity Type proxyType, object expectedValue, MockSetter setValue, MockGetter getValue ) { - var entityManager = new EntityManager(); + var entityManager = EntityManager.CreateEntityManagerInUninitializedState(); k_EntityManagerBackingField.SetValue(m_GameObjectEntity, entityManager); Assume.That(entityManager.IsCreated, Is.False, "EntityManager was not in correct state in test arrangement"); var proxy = m_GameObjectEntity.gameObject.AddComponent(proxyType) as ComponentDataProxyBase; diff --git a/Unity.Entities.Hybrid.Tests/ComponentGroupTransformAccessArrayTests.cs b/Unity.Entities.Hybrid.Tests/ComponentGroupTransformAccessArrayTests.cs index fec5c1da..7cf2d6c0 100644 --- a/Unity.Entities.Hybrid.Tests/ComponentGroupTransformAccessArrayTests.cs +++ b/Unity.Entities.Hybrid.Tests/ComponentGroupTransformAccessArrayTests.cs @@ -7,24 +7,6 @@ namespace Unity.Entities.Tests { class ComponentGroupTransformAccessArrayTests : ECSTestsFixture { -#pragma warning disable 618 - TransformAccessArrayInjectionHook m_TransformAccessArrayInjectionHook = new TransformAccessArrayInjectionHook(); - ComponentArrayInjectionHook m_ComponentArrayInjectionHook = new ComponentArrayInjectionHook(); -#pragma warning restore 618 - [OneTimeSetUp] - public void Init() - { - InjectionHookSupport.RegisterHook(m_ComponentArrayInjectionHook); - InjectionHookSupport.RegisterHook(m_TransformAccessArrayInjectionHook); - } - - [OneTimeTearDown] - public void Cleanup() - { - InjectionHookSupport.RegisterHook(m_TransformAccessArrayInjectionHook); - InjectionHookSupport.UnregisterHook(m_ComponentArrayInjectionHook); - } - public ComponentGroupTransformAccessArrayTests() { Assert.IsTrue(Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled, "JobDebugger must be enabled for these tests"); @@ -40,7 +22,7 @@ public class TransformAccessArrayTestTagProxy : ComponentDataProxy(); - var group = EmptySystem.GetComponentGroup(typeof(Transform), typeof(TransformAccessArrayTestTag)); + var group = EmptySystem.GetEntityQuery(typeof(Transform), typeof(TransformAccessArrayTestTag)); var ta = group.GetTransformAccessArray(); Assert.AreEqual(1, ta.length); @@ -60,7 +42,7 @@ public void AddAndGetNewTransformAccessArrayUpdatesContent() { var go = new GameObject(); go.AddComponent(); - var group = EmptySystem.GetComponentGroup(typeof(Transform), typeof(TransformAccessArrayTestTag)); + var group = EmptySystem.GetEntityQuery(typeof(Transform), typeof(TransformAccessArrayTestTag)); var ta = group.GetTransformAccessArray(); Assert.AreEqual(1, ta.length); @@ -78,7 +60,7 @@ public void AddAndUseOldTransformAccessArrayDoesNotUpdateContent() { var go = new GameObject(); go.AddComponent(); - var group = EmptySystem.GetComponentGroup(typeof(Transform), typeof(TransformAccessArrayTestTag)); + var group = EmptySystem.GetEntityQuery(typeof(Transform), typeof(TransformAccessArrayTestTag)); var ta = group.GetTransformAccessArray(); Assert.AreEqual(1, ta.length); @@ -97,7 +79,7 @@ public void DestroyAndGetNewTransformAccessArrayUpdatesContent() var go2 = new GameObject(); go2.AddComponent(); - var group = EmptySystem.GetComponentGroup(typeof(Transform), typeof(TransformAccessArrayTestTag)); + var group = EmptySystem.GetEntityQuery(typeof(Transform), typeof(TransformAccessArrayTestTag)); var ta = group.GetTransformAccessArray(); Assert.AreEqual(2, ta.length); @@ -117,7 +99,7 @@ public void DestroyAndUseOldTransformAccessArrayDoesNotUpdateContent() var go2 = new GameObject(); go2.AddComponent(); - var group = EmptySystem.GetComponentGroup(typeof(Transform), typeof(TransformAccessArrayTestTag)); + var group = EmptySystem.GetEntityQuery(typeof(Transform), typeof(TransformAccessArrayTestTag)); var ta = group.GetTransformAccessArray(); Assert.AreEqual(2, ta.length); @@ -127,89 +109,5 @@ public void DestroyAndUseOldTransformAccessArrayDoesNotUpdateContent() Object.DestroyImmediate(go2); } - - [DisableAutoCreation] - public class GameObjectArrayWithTransformAccessSystem : ComponentSystem - { - public ComponentGroup group; - protected override void OnUpdate() - { - } - - public new void UpdateInjectedComponentGroups() - { - base.UpdateInjectedComponentGroups(); - } - - protected override void OnCreateManager() - { - group = GetComponentGroup(typeof(Transform)); - } - } - - #pragma warning disable 618 - [Test] - public void GameObjectArrayWorksWithTransformAccessArray() - { - var hook = new GameObjectArrayInjectionHook(); - InjectionHookSupport.RegisterHook(hook); - - var go = new GameObject("test"); - GameObjectEntity.AddToEntityManager(m_Manager, go); - - var manager = World.GetOrCreateManager(); - - manager.UpdateInjectedComponentGroups(); - - Assert.AreEqual(1, manager.group.CalculateLength()); - Assert.AreEqual(go, manager.group.GetGameObjectArray()[0]); - Assert.AreEqual(go, manager.group.GetTransformAccessArray()[0].gameObject); - - Object.DestroyImmediate (go); - - InjectionHookSupport.UnregisterHook(hook); - - TearDown(); - } - #pragma warning restore 618 - - [DisableAutoCreation] - public class TransformWithTransformAccessSystem : ComponentSystem - { - public ComponentGroup group; - - protected override void OnUpdate() - { - } - - public new void UpdateInjectedComponentGroups() - { - base.UpdateInjectedComponentGroups(); - } - - protected override void OnCreateManager() - { - group = GetComponentGroup(typeof(Transform)); - } - } - - #pragma warning disable 618 - [Test] - public void TransformArrayWorksWithTransformAccessArray() - { - var go = new GameObject("test"); - GameObjectEntity.AddToEntityManager(m_Manager, go); - - var manager = World.GetOrCreateManager(); - - manager.UpdateInjectedComponentGroups(); - - Assert.AreEqual(1, manager.group.CalculateLength()); - Assert.AreEqual(manager.group.GetComponentArray()[0].gameObject, manager.group.GetTransformAccessArray()[0].gameObject); - - Object.DestroyImmediate (go); - TearDown(); - } - #pragma warning restore 618 } } diff --git a/Unity.Entities.Hybrid.Tests/ComponentSystem_GameObject_IntegrationTests.cs b/Unity.Entities.Hybrid.Tests/ComponentSystem_GameObject_IntegrationTests.cs deleted file mode 100644 index 5fba114d..00000000 --- a/Unity.Entities.Hybrid.Tests/ComponentSystem_GameObject_IntegrationTests.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using NUnit.Framework; -using Unity.Entities; -using Unity.Entities.Tests; -#pragma warning disable 649 -#pragma warning disable 618 - -namespace UnityEngine.Entities.Tests -{ - class ComponentSystem_GameObject_IntegrationTests : ECSTestsFixture - { - ComponentArrayInjectionHook m_ComponentArrayInjectionHook = new ComponentArrayInjectionHook(); - GameObjectArrayInjectionHook m_GameObjectArrayInjectionHook = new GameObjectArrayInjectionHook(); - - [OneTimeSetUp] - public void Init() - { - InjectionHookSupport.RegisterHook(m_ComponentArrayInjectionHook); - InjectionHookSupport.RegisterHook(m_GameObjectArrayInjectionHook); - } - - [OneTimeTearDown] - public void Cleanup() - { - InjectionHookSupport.UnregisterHook(m_GameObjectArrayInjectionHook); - InjectionHookSupport.RegisterHook(m_ComponentArrayInjectionHook); - } - - GameObject m_GameObject; - - [SetUp] - public override void Setup() - { - base.Setup(); - m_GameObject = new GameObject(TestContext.CurrentContext.Test.Name); - } - - [TearDown] - public override void TearDown() - { - base.TearDown(); - if (m_GameObject != null) - GameObject.DestroyImmediate(m_GameObject); - } - - [DisableAutoCreation] - public class GameObjectArraySystem : ComponentSystem - { - public struct Group - { - public readonly int Length; - public GameObjectArray gameObjects; - - public ComponentArray colliders; - } - - [Inject] - public Group group; - - protected override void OnUpdate() - { - } - - public new void UpdateInjectedComponentGroups() - { - base.UpdateInjectedComponentGroups(); - } - } - - [Test] - public void UpdateInjectedComponentGroups_WhenObjectWithMatchingComponentExists_GameObjectArrayIsPopulated() - { - m_GameObject.AddComponent(); - GameObjectEntity.AddToEntityManager(m_Manager, m_GameObject); - var manager = World.GetOrCreateManager(); - - manager.UpdateInjectedComponentGroups(); - - Assert.That(manager.group.gameObjects.ToArray(), Is.EqualTo(new[] { m_GameObject })); - } - - [Test] - public void UpdateInjectedComponentGroups_WhenObjectWithMatchingComponentExists_ComponentArrayIsPopulated() - { - var c = m_GameObject.AddComponent(); - GameObjectEntity.AddToEntityManager(m_Manager, m_GameObject); - var manager = World.GetOrCreateManager(); - - manager.UpdateInjectedComponentGroups(); - - Assert.That(manager.group.colliders.ToArray(), Is.EqualTo(new[] { c })); - } - - [Test] - public void GetComponentGroup_WhenObjectWithMatchingComponentExists_ComponentArrayIsPopulated() - { - var rb = m_GameObject.AddComponent(); - GameObjectEntity.AddToEntityManager(m_Manager, m_GameObject); - - var grp = EmptySystem.GetComponentGroup(typeof(Rigidbody)); - - var array = grp.GetComponentArray(); - Assert.That(array.ToArray(), Is.EqualTo(new[] { rb })); - } - - [Test] - public void GetComponentGroup_WhenObjectWithMatchingComponentAndECSDataExists_ComponentArraysArePopulated() - { - var goe = m_GameObject.AddComponent().GetComponent(); - var expectedTestData = new EcsTestData(5); - m_Manager.SetComponentData(goe.Entity, expectedTestData); - - var grp = EmptySystem.GetComponentGroup(typeof(Transform), typeof(EcsTestData)); - - var transformArray = grp.GetComponentArray(); - Assert.That(transformArray.ToArray(), Is.EqualTo(new[] { goe.transform })); - var ecsDataArray = grp.GetComponentDataArray(); - Assert.That(ecsDataArray.Length, Is.EqualTo(1)); - Assert.That(ecsDataArray[0], Is.EqualTo(expectedTestData)); - } - } -} diff --git a/Unity.Entities.Hybrid.Tests/ComponentSystem_GameObject_IntegrationTests.cs.meta b/Unity.Entities.Hybrid.Tests/ComponentSystem_GameObject_IntegrationTests.cs.meta deleted file mode 100644 index ce578ad6..00000000 --- a/Unity.Entities.Hybrid.Tests/ComponentSystem_GameObject_IntegrationTests.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f12b2ef99b3ca499b9c97e13baf3c0a3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities.Hybrid.Tests/ConversionMappingTests.cs b/Unity.Entities.Hybrid.Tests/ConversionMappingTests.cs index f132c2b7..db0fc478 100644 --- a/Unity.Entities.Hybrid.Tests/ConversionMappingTests.cs +++ b/Unity.Entities.Hybrid.Tests/ConversionMappingTests.cs @@ -15,7 +15,7 @@ public override void Setup() { base.Setup(); dstWorld = new World("Test dst world"); - mappingSystem = World.CreateManager(dstWorld, default(Unity.Entities.Hash128), GameObjectConversionUtility.ConversionFlags.None); + mappingSystem = World.CreateSystem(dstWorld, default(Unity.Entities.Hash128), GameObjectConversionUtility.ConversionFlags.None); } [TearDown] diff --git a/Unity.Entities.Hybrid.Tests/Runtime/GameObjectEntityTests.cs b/Unity.Entities.Hybrid.Tests/Runtime/GameObjectEntityTests.cs index 83a8d215..ba2ff279 100644 --- a/Unity.Entities.Hybrid.Tests/Runtime/GameObjectEntityTests.cs +++ b/Unity.Entities.Hybrid.Tests/Runtime/GameObjectEntityTests.cs @@ -52,28 +52,6 @@ public void AddComponentDuringForeachProtection() { //* Check for string in MyEntity and other illegal constructs... } - [Test] - unsafe public void ComponentEnumerator() - { - var go = new GameObject("test", typeof(Rigidbody), typeof(Light)); - var entity = GameObjectEntity.AddToEntityManager(m_Manager, go); - - m_Manager.AddComponentData(entity, new EcsTestData(5)); - m_Manager.AddComponentData(entity, new EcsTestData2(6)); - - int iterations = 0; - foreach (var e in EmptySystem.GetEntities() ) - { - Assert.AreEqual(5, e.testData->value); - Assert.AreEqual(6, e.testData2->value0); - Assert.AreEqual(go.GetComponent(), e.light); - Assert.AreEqual(go.GetComponent(), e.rigidbody); - iterations++; - } - Assert.AreEqual(1, iterations); - - Object.DestroyImmediate(go); - } [Test] public void AddRemoveGetComponentObject() diff --git a/Unity.Entities.Hybrid.Tests/Runtime/InjectComponentGroupTestsHybrid.cs b/Unity.Entities.Hybrid.Tests/Runtime/InjectComponentGroupTestsHybrid.cs deleted file mode 100644 index 337bcb3a..00000000 --- a/Unity.Entities.Hybrid.Tests/Runtime/InjectComponentGroupTestsHybrid.cs +++ /dev/null @@ -1,58 +0,0 @@ -using NUnit.Framework; -using UnityEngine; -#pragma warning disable 649 -#pragma warning disable 618 - -namespace Unity.Entities.Tests -{ - class InjectComponentGroupTestsHybrid : ECSTestsFixture - { - [DisableAutoCreation] - [AlwaysUpdateSystem] - public class ExcludeSystem : ComponentSystem - { - public struct Datas - { - public ComponentDataArray Data; - public ExcludeComponent Data2; - public ExcludeComponent Rigidbody; - } - - [Inject] - public Datas Group; - - protected override void OnUpdate() - { - } - } - - [Test] - public void ExcludeComponent() - { - var subtractiveSystem = World.GetOrCreateManager (); - - var entity = m_Manager.CreateEntity (typeof(EcsTestData)); - - var go = new GameObject("Test", typeof(EcsTestProxy)); - - // Ensure entities without the subtractive components are present - subtractiveSystem.Update (); - Assert.AreEqual (2, subtractiveSystem.Group.Data.Length); - Assert.AreEqual (0, subtractiveSystem.Group.Data[0].value); - Assert.AreEqual (0, subtractiveSystem.Group.Data[1].value); - - // Ensure adding the subtractive components, removes them from the injection - m_Manager.AddComponentData (entity, new EcsTestData2()); - - // TODO: This should be automatic... - go.AddComponent(); - go.GetComponent().enabled = false; - go.GetComponent().enabled = true; - - subtractiveSystem.Update (); - Assert.AreEqual (0, subtractiveSystem.Group.Data.Length); - - Object.DestroyImmediate(go); - } - } -} diff --git a/Unity.Entities.Hybrid.Tests/Runtime/InjectComponentGroupTestsHybrid.cs.meta b/Unity.Entities.Hybrid.Tests/Runtime/InjectComponentGroupTestsHybrid.cs.meta deleted file mode 100644 index e9f18fe8..00000000 --- a/Unity.Entities.Hybrid.Tests/Runtime/InjectComponentGroupTestsHybrid.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 241a4da0c00ab408d84c63e4dd20a864 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities.Hybrid.Tests/Runtime/SharedComponentSerializeTests.cs b/Unity.Entities.Hybrid.Tests/Runtime/SharedComponentSerializeTests.cs index 95075ddd..1b3a2db7 100644 --- a/Unity.Entities.Hybrid.Tests/Runtime/SharedComponentSerializeTests.cs +++ b/Unity.Entities.Hybrid.Tests/Runtime/SharedComponentSerializeTests.cs @@ -61,9 +61,9 @@ public void SharedComponentSerialize() var reader = new TestBinaryReader(writer); var world = new World("temp"); - SerializeUtilityHybrid.Deserialize (world.GetOrCreateManager(), reader, sharedComponents); + SerializeUtilityHybrid.Deserialize (world.EntityManager, reader, sharedComponents); - var newWorldEntities = world.GetOrCreateManager(); + var newWorldEntities = world.EntityManager; { var entities = newWorldEntities.GetAllEntities(); diff --git a/Unity.Entities.Hybrid/Components/GameObjectEntity.cs b/Unity.Entities.Hybrid/Components/GameObjectEntity.cs index b79d4742..b40f64ec 100644 --- a/Unity.Entities.Hybrid/Components/GameObjectEntity.cs +++ b/Unity.Entities.Hybrid/Components/GameObjectEntity.cs @@ -154,7 +154,7 @@ void Initialize() DefaultWorldInitialization.DefaultLazyEditModeInitialize(); if (World.Active != null) { - m_EntityManager = World.Active.GetOrCreateManager(); + m_EntityManager = World.Active.EntityManager; m_Entity = AddToEntityManager(m_EntityManager, gameObject); } } diff --git a/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionMappingSystem.cs b/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionMappingSystem.cs index c84085b7..4e8a6370 100644 --- a/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionMappingSystem.cs +++ b/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionMappingSystem.cs @@ -76,7 +76,6 @@ public void Dispose() } [DisableAutoCreation] -[Preserve] class GameObjectConversionMappingSystem : ComponentSystem { NativeHashMap m_GameObjectToEntity = new NativeHashMap(100 * 1000, Allocator.Persistent); @@ -103,14 +102,14 @@ public GameObjectConversionMappingSystem(World DstWorld, Hash128 sceneGUID, Conv m_DstWorld = DstWorld; m_SceneGUID = sceneGUID; m_ConversionFlags = conversionFlags; - m_DstManager = DstWorld.GetOrCreateManager(); + m_DstManager = DstWorld.EntityManager; m_Entities = new Entity[128]; m_Next = new int[128]; m_EntitiesCount = 0; } - protected override void OnDestroyManager() + protected override void OnDestroy() { m_GameObjectToEntity.Dispose(); } @@ -354,7 +353,7 @@ internal static void CreateEntitiesForGameObjectsRecurse(Transform transform, En internal static void CreateEntitiesForGameObjects(Scene scene, World gameObjectWorld) { - var entityManager = gameObjectWorld.GetOrCreateManager(); + var entityManager = gameObjectWorld.EntityManager; var gameObjects = scene.GetRootGameObjects(); foreach (var go in gameObjects) @@ -365,4 +364,4 @@ protected override void OnUpdate() { } -} \ No newline at end of file +} diff --git a/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionSystem.cs b/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionSystem.cs index 06d8fc48..d9a2d815 100644 --- a/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionSystem.cs +++ b/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionSystem.cs @@ -11,13 +11,13 @@ public abstract class GameObjectConversionSystem : ComponentSystem GameObjectConversionMappingSystem m_MappingSystem; - protected override void OnCreateManager() + protected override void OnCreate() { - base.OnCreateManager(); + base.OnCreate(); - m_MappingSystem = World.GetOrCreateManager(); + m_MappingSystem = World.GetOrCreateSystem(); DstWorld = m_MappingSystem.DstWorld; - DstEntityManager = DstWorld.GetOrCreateManager(); + DstEntityManager = DstWorld.EntityManager; } public Entity GetPrimaryEntity(Component component) diff --git a/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionUtility.cs b/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionUtility.cs index 15e1c5e2..bb28ae6b 100644 --- a/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionUtility.cs +++ b/Unity.Entities.Hybrid/GameObjectConversion/GameObjectConversionUtility.cs @@ -56,7 +56,7 @@ internal static World CreateConversionWorld(World dstEntityWorld, Hash128 scene m_CreateConversionWorld.Begin(); var gameObjectWorld = new World("GameObject World"); - gameObjectWorld.CreateManager(dstEntityWorld, sceneGUID, conversionFlags); + gameObjectWorld.CreateSystem(dstEntityWorld, sceneGUID, conversionFlags); AddConversionSystems(gameObjectWorld); @@ -68,14 +68,14 @@ internal static World CreateConversionWorld(World dstEntityWorld, Hash128 scene internal static void Convert(World gameObjectWorld, World dstEntityWorld) { - var mappingSystem = gameObjectWorld.GetExistingManager(); + var mappingSystem = gameObjectWorld.GetExistingSystem(); using (m_UpdateSystems.Auto()) { // Convert all the data into dstEntityWorld - gameObjectWorld.GetExistingManager().Update(); - gameObjectWorld.GetExistingManager().Update(); - gameObjectWorld.GetExistingManager().Update(); + gameObjectWorld.GetExistingSystem().Update(); + gameObjectWorld.GetExistingSystem().Update(); + gameObjectWorld.GetExistingSystem().Update(); } using (m_AddPrefabComponentDataTag.Auto()) @@ -86,7 +86,7 @@ internal static void Convert(World gameObjectWorld, World dstEntityWorld) internal static Entity GameObjectToConvertedEntity(World gameObjectWorld, GameObject gameObject) { - var mappingSystem = gameObjectWorld.GetExistingManager(); + var mappingSystem = gameObjectWorld.GetExistingSystem(); return mappingSystem.GetPrimaryEntity(gameObject); } @@ -98,7 +98,7 @@ public static Entity ConvertGameObjectHierarchy(GameObject root, World dstEntity Entity convertedEntity; using (var gameObjectWorld = CreateConversionWorld(dstEntityWorld, default(Hash128), 0)) { - var mappingSystem = gameObjectWorld.GetExistingManager(); + var mappingSystem = gameObjectWorld.GetExistingSystem(); using (m_CreateEntitiesForGameObjects.Auto()) { @@ -139,13 +139,13 @@ public static void ConvertScene(Scene scene, Hash128 sceneHash, World dstEntityW static void AddConversionSystems(World gameObjectWorld) { - var init = gameObjectWorld.GetOrCreateManager(); - var convert = gameObjectWorld.GetOrCreateManager(); - var afterConvert = gameObjectWorld.GetOrCreateManager(); + var init = gameObjectWorld.GetOrCreateSystem(); + var convert = gameObjectWorld.GetOrCreateSystem(); + var afterConvert = gameObjectWorld.GetOrCreateSystem(); // Ensure the following systems run first in this order... - init.AddSystemToUpdateList(gameObjectWorld.GetOrCreateManager()); - init.AddSystemToUpdateList(gameObjectWorld.GetOrCreateManager()); + init.AddSystemToUpdateList(gameObjectWorld.GetOrCreateSystem()); + init.AddSystemToUpdateList(gameObjectWorld.GetOrCreateSystem()); var systems = DefaultWorldInitialization.GetAllSystems(WorldSystemFilterFlags.GameObjectConversion); foreach (var system in systems) @@ -185,7 +185,7 @@ static void AddSystemAndLogException(World world, ComponentSystemGroup group, Ty { try { - group.AddSystemToUpdateList(world.GetOrCreateManager(type) as ComponentSystemBase); + group.AddSystemToUpdateList(world.GetOrCreateSystem(type) as ComponentSystemBase); } catch (Exception e) { diff --git a/Unity.Entities.Hybrid/Injection/DefaultWorldInitialization.cs b/Unity.Entities.Hybrid/Injection/DefaultWorldInitialization.cs index 7235162c..9cba197e 100644 --- a/Unity.Entities.Hybrid/Injection/DefaultWorldInitialization.cs +++ b/Unity.Entities.Hybrid/Injection/DefaultWorldInitialization.cs @@ -26,11 +26,11 @@ static void DomainUnloadShutdown() ScriptBehaviourUpdateOrder.UpdatePlayerLoop(null); } - static ScriptBehaviourManager GetOrCreateManagerAndLogException(World world, Type type) + static ComponentSystemBase GetOrCreateManagerAndLogException(World world, Type type) { try { - return world.GetOrCreateManager(type); + return world.GetOrCreateSystem(type); } catch (Exception e) { @@ -41,13 +41,6 @@ static ScriptBehaviourManager GetOrCreateManagerAndLogException(World world, Typ public static void Initialize(string worldName, bool editorWorld) { - // Register hybrid injection hooks - #pragma warning disable 0618 - InjectionHookSupport.RegisterHook(new GameObjectArrayInjectionHook()); - InjectionHookSupport.RegisterHook(new TransformAccessArrayInjectionHook()); - InjectionHookSupport.RegisterHook(new ComponentArrayInjectionHook()); - #pragma warning restore 0618 - PlayerLoopManager.RegisterDomainUnload(DomainUnloadShutdown, 10000); var world = new World(worldName); @@ -64,9 +57,9 @@ public static void Initialize(string worldName, bool editorWorld) } // create presentation system and simulation system - InitializationSystemGroup initializationSystemGroup = world.GetOrCreateManager(); - SimulationSystemGroup simulationSystemGroup = world.GetOrCreateManager(); - PresentationSystemGroup presentationSystemGroup = world.GetOrCreateManager(); + InitializationSystemGroup initializationSystemGroup = world.GetOrCreateSystem(); + SimulationSystemGroup simulationSystemGroup = world.GetOrCreateSystem(); + PresentationSystemGroup presentationSystemGroup = world.GetOrCreateSystem(); // Add systems to their groups, based on the [UpdateInGroup] attribute. foreach (var type in systems) { diff --git a/Unity.Entities.Hybrid/Iterators/ComponentArray.cs b/Unity.Entities.Hybrid/Iterators/ComponentArray.cs index 8602e784..0663b66c 100644 --- a/Unity.Entities.Hybrid/Iterators/ComponentArray.cs +++ b/Unity.Entities.Hybrid/Iterators/ComponentArray.cs @@ -7,26 +7,15 @@ namespace Unity.Entities { - public static class ComponentGroupExtensionsForComponentArray + public static class EntityQueryExtensionsForComponentArray { - [Obsolete("GetComponentArray has been deprecated. Use ComponentSystem.ForEach to access managed components.")] - public static ComponentArray GetComponentArray(this ComponentGroup group) where T : Component + public static T[] ToComponentArray(this EntityQuery group) where T : Component { int length = group.CalculateLength(); ComponentChunkIterator iterator = group.GetComponentChunkIterator(); - var indexInComponentGroup = group.GetIndexInComponentGroup(TypeManager.GetTypeIndex()); + var indexInComponentGroup = group.GetIndexInEntityQuery(TypeManager.GetTypeIndex()); - iterator.IndexInComponentGroup = indexInComponentGroup; - return new ComponentArray(iterator, length, group.ArchetypeManager); - } - - public static T[] ToComponentArray(this ComponentGroup group) where T : Component - { - int length = group.CalculateLength(); - ComponentChunkIterator iterator = group.GetComponentChunkIterator(); - var indexInComponentGroup = group.GetIndexInComponentGroup(TypeManager.GetTypeIndex()); - - iterator.IndexInComponentGroup = indexInComponentGroup; + iterator.IndexInEntityQuery = indexInComponentGroup; var arr = new T[length]; var cache = default(ComponentChunkCache); @@ -34,7 +23,7 @@ public static T[] ToComponentArray(this ComponentGroup group) where T : Compo { if (i < cache.CachedBeginIndex || i >= cache.CachedEndIndex) iterator.MoveToEntityIndexAndUpdateCache(i, out cache, true); - + arr[i] = (T)iterator.GetManagedObject(group.ArchetypeManager, cache.CachedBeginIndex, i); } @@ -42,116 +31,3 @@ public static T[] ToComponentArray(this ComponentGroup group) where T : Compo } } } - -namespace Unity.Entities -{ - [Obsolete("ComponentArray has been deprecated. Use ComponentSystem.ForEach to access managed components.")] - public struct ComponentArray where T: Component - { - ComponentChunkIterator m_Iterator; - ComponentChunkCache m_Cache; - readonly int m_Length; - readonly ArchetypeManager m_ArchetypeManager; - - internal ComponentArray(ComponentChunkIterator iterator, int length, ArchetypeManager typeMan) - { - m_Length = length; - m_Cache = default(ComponentChunkCache); - m_Iterator = iterator; - m_ArchetypeManager = typeMan; - } - - public T this[int index] - { - get - { - //@TODO: Unnecessary.. integrate into cache instead... - if ((uint)index >= (uint)m_Length) - FailOutOfRangeError(index); - - if (index < m_Cache.CachedBeginIndex || index >= m_Cache.CachedEndIndex) - m_Iterator.MoveToEntityIndexAndUpdateCache(index, out m_Cache, true); - - return (T)m_Iterator.GetManagedObject(m_ArchetypeManager, m_Cache.CachedBeginIndex, index); - } - } - - public T[] ToArray() - { - var arr = new T[m_Length]; - var i = 0; - while (i < m_Length) - { - m_Iterator.MoveToEntityIndexAndUpdateCache(i, out m_Cache, true); - int start, length; - var objs = m_Iterator.GetManagedObjectRange(m_ArchetypeManager, m_Cache.CachedBeginIndex, i, out start, out length); - for (var obj = 0; obj < length; ++obj) - arr[i+obj] = (T)objs[start+obj]; - i += length; - } - return arr; - } - - void FailOutOfRangeError(int index) - { - throw new IndexOutOfRangeException($"Index {index} is out of range of '{Length}' Length."); - } - - public int Length => m_Length; - } - - [Preserve] - [CustomInjectionHook] - [Obsolete("ComponentArray and injection have been deprecated. Use ComponentSystem.ForEach to access managed components.")] - sealed class ComponentArrayInjectionHook : InjectionHook - { - public override Type FieldTypeOfInterest => typeof(ComponentArray<>); - - public override bool IsInterestedInField(FieldInfo fieldInfo) - { - return fieldInfo.FieldType.IsGenericType && fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(ComponentArray<>); - } - - public override string ValidateField(FieldInfo field, bool isReadOnly, InjectionContext injectionInfo) - { - if (field.FieldType != typeof(ComponentArray<>)) - return null; - - if (isReadOnly) - return "[ReadOnly] may not be used on ComponentArray<>, it can only be used on ComponentDataArray<>"; - - return null; - } - - public override InjectionContext.Entry CreateInjectionInfoFor(FieldInfo field, bool isReadOnly) - { - var componentType = field.FieldType.GetGenericArguments()[0]; - var accessMode = isReadOnly ? ComponentType.AccessMode.ReadOnly : ComponentType.AccessMode.ReadWrite; - return new InjectionContext.Entry - { - Hook = this, - FieldInfo = field, - IsReadOnly = false /* isReadOnly */, - AccessMode = accessMode, - IndexInComponentGroup = -1, - FieldOffset = UnsafeUtility.GetFieldOffset(field), - ComponentType = new ComponentType(componentType, accessMode), - ComponentRequirements = componentType == typeof(Transform) - ? new[] { typeof(Transform), componentType } - : new []{ componentType } - }; - } - - public override void PrepareEntry(ref InjectionContext.Entry entry, ComponentGroup entityGroup) - { - entry.IndexInComponentGroup = entityGroup.GetIndexInComponentGroup(entry.ComponentType.TypeIndex); - } - - internal override unsafe void InjectEntry(InjectionContext.Entry entry, ComponentGroup entityGroup, ref ComponentChunkIterator iterator, int length, byte* groupStructPtr) - { - iterator.IndexInComponentGroup = entry.IndexInComponentGroup; - var data = new ComponentArray(iterator, length, entityGroup.ArchetypeManager); - UnsafeUtility.CopyStructureToPtr(ref data, groupStructPtr + entry.FieldOffset); - } - } -} diff --git a/Unity.Entities.Hybrid/Iterators/GameObjectArray.cs b/Unity.Entities.Hybrid/Iterators/GameObjectArray.cs deleted file mode 100644 index 20141d8f..00000000 --- a/Unity.Entities.Hybrid/Iterators/GameObjectArray.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; - -using Unity.Collections.LowLevel.Unsafe; -using UnityEngine; -using UnityEngine.Scripting; - -namespace Unity.Entities -{ - public static class ComponentGroupExtensionsForGameObjectArray - { - [Obsolete("GetGameObjectArray has been deprecated. Use ComponentSystem.ForEach or ToTransformArray()[index].gameObject to access entity GameObjects.")] - public static GameObjectArray GetGameObjectArray(this ComponentGroup group) - { - int length = group.CalculateLength(); - ComponentChunkIterator iterator = group.GetComponentChunkIterator(); - iterator.IndexInComponentGroup = group.GetIndexInComponentGroup(TypeManager.GetTypeIndex()); - return new GameObjectArray(iterator, length, group.ArchetypeManager); - } - } -} - -namespace Unity.Entities -{ - [Obsolete("GameObjectArray has been deprecated. Use ComponentSystem.ForEach or ToTransformArray()[index].gameObject to access entity GameObjects.")] - public struct GameObjectArray - { - ComponentChunkIterator m_Iterator; - ComponentChunkCache m_Cache; - readonly int m_Length; - readonly ArchetypeManager m_ArchetypeManager; - - internal GameObjectArray(ComponentChunkIterator iterator, int length, ArchetypeManager typeMan) - { - m_Length = length; - m_Cache = default(ComponentChunkCache); - m_Iterator = iterator; - m_ArchetypeManager = typeMan; - } - - public GameObject this[int index] - { - get - { - //@TODO: Unnecessary.. integrate into cache instead... - if ((uint)index >= (uint)m_Length) - FailOutOfRangeError(index); - - if (index < m_Cache.CachedBeginIndex || index >= m_Cache.CachedEndIndex) - m_Iterator.MoveToEntityIndexAndUpdateCache(index, out m_Cache, true); - - var transform = (Transform) m_Iterator.GetManagedObject(m_ArchetypeManager, m_Cache.CachedBeginIndex, index); - - return transform.gameObject; - } - } - - public GameObject[] ToArray() - { - var arr = new GameObject[m_Length]; - var i = 0; - while (i < m_Length) - { - m_Iterator.MoveToEntityIndexAndUpdateCache(i, out m_Cache, true); - int start, length; - var objs = m_Iterator.GetManagedObjectRange(m_ArchetypeManager, m_Cache.CachedBeginIndex, i, out start, out length); - for (var obj = 0; obj < length; ++obj) - arr[i+obj] = ((Transform) objs[start + obj]).gameObject; - i += length; - } - return arr; - } - - void FailOutOfRangeError(int index) - { - throw new IndexOutOfRangeException($"Index {index} is out of range of '{Length}' Length."); - } - - public int Length => m_Length; - } - - [Preserve] - [CustomInjectionHook] - [Obsolete("GameObjectArray and injection have been deprecated. Use ComponentSystem.ForEach or ToTransformArray()[index].gameObject to access entity GameObjects.")] - sealed class GameObjectArrayInjectionHook : InjectionHook - { - public override Type FieldTypeOfInterest => typeof(GameObjectArray); - - public override bool IsInterestedInField(FieldInfo fieldInfo) - { - return fieldInfo.FieldType == typeof(GameObjectArray); - } - - public override string ValidateField(FieldInfo field, bool isReadOnly, InjectionContext injectionInfo) - { - if (field.FieldType != typeof(GameObjectArray)) - return null; - - if (isReadOnly) - return "[ReadOnly] may not be used on GameObjectArray, it can only be used on ComponentDataArray<>"; - - // Error on multiple GameObjectArray - if (injectionInfo.Entries.Any(i => i.FieldInfo.FieldType == typeof(GameObjectArray))) - return "A [Inject] struct, may only contain a single GameObjectArray"; - - return null; - } - - public override InjectionContext.Entry CreateInjectionInfoFor(FieldInfo field, bool isReadOnly) - { - return new InjectionContext.Entry - { - Hook = this, - FieldInfo = field, - IsReadOnly = isReadOnly, - AccessMode = isReadOnly ? ComponentType.AccessMode.ReadOnly : ComponentType.AccessMode.ReadWrite, - IndexInComponentGroup = -1, - FieldOffset = UnsafeUtility.GetFieldOffset(field), - ComponentRequirements = new[] { typeof(Transform) } - }; - } - - internal override unsafe void InjectEntry(InjectionContext.Entry entry, ComponentGroup entityGroup, ref ComponentChunkIterator iterator, int length, byte* groupStructPtr) - { - var gameObjectArray = entityGroup.GetGameObjectArray(); - UnsafeUtility.CopyStructureToPtr(ref gameObjectArray, groupStructPtr + entry.FieldOffset); - } - } -} diff --git a/Unity.Entities.Hybrid/Iterators/GameObjectArray.cs.meta b/Unity.Entities.Hybrid/Iterators/GameObjectArray.cs.meta deleted file mode 100644 index 3fca4764..00000000 --- a/Unity.Entities.Hybrid/Iterators/GameObjectArray.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5558e38bbc5c843679c87e532e532994 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities.Hybrid/Iterators/TransformAccessArrayIterator.cs b/Unity.Entities.Hybrid/Iterators/TransformAccessArrayIterator.cs index 13d19933..d1062b5f 100644 --- a/Unity.Entities.Hybrid/Iterators/TransformAccessArrayIterator.cs +++ b/Unity.Entities.Hybrid/Iterators/TransformAccessArrayIterator.cs @@ -21,9 +21,9 @@ public void Dispose() } } - public static class ComponentGroupExtensionsForTransformAccessArray + public static class EntityQueryExtensionsForTransformAccessArray { - public static unsafe TransformAccessArray GetTransformAccessArray(this ComponentGroup group) + public static unsafe TransformAccessArray GetTransformAccessArray(this EntityQuery group) { var state = (TransformAccessArrayState?)group.m_CachedState ?? new TransformAccessArrayState(); var orderVersion = group.EntityDataManager->GetComponentTypeOrderVersion(TypeManager.GetTypeIndex()); @@ -47,51 +47,3 @@ public static unsafe TransformAccessArray GetTransformAccessArray(this Component } } } - -namespace Unity.Entities -{ - [Preserve] - [CustomInjectionHook] - [Obsolete("Injection has been deprecated. Use ComponentGroup.GetTransformAccessArray instead.")] - sealed class TransformAccessArrayInjectionHook : InjectionHook - { - public override Type FieldTypeOfInterest => typeof(TransformAccessArray); - - public override bool IsInterestedInField(FieldInfo fieldInfo) - { - return fieldInfo.FieldType == typeof(TransformAccessArray); - } - - public override string ValidateField(FieldInfo field, bool isReadOnly, InjectionContext injectionInfo) - { - if (isReadOnly) - return "[ReadOnly] may not be used on a TransformAccessArray only on ComponentDataArray<>"; - - // Error on multiple TransformAccessArray - if (injectionInfo.Entries.Any(i => i.FieldInfo.FieldType == typeof(TransformAccessArray))) - return "A [Inject] struct, may only contain a single TransformAccessArray"; - - return null; - } - - public override InjectionContext.Entry CreateInjectionInfoFor(FieldInfo field, bool isReadOnly) - { - return new InjectionContext.Entry - { - Hook = this, - FieldInfo = field, - IsReadOnly = isReadOnly, - AccessMode = isReadOnly ? ComponentType.AccessMode.ReadOnly : ComponentType.AccessMode.ReadWrite, - IndexInComponentGroup = -1, - FieldOffset = UnsafeUtility.GetFieldOffset(field), - ComponentRequirements = new[] { typeof(Transform) } - }; - } - - internal override unsafe void InjectEntry(InjectionContext.Entry entry, ComponentGroup entityGroup, ref ComponentChunkIterator iterator, int length, byte* groupStructPtr) - { - var transformsArray = entityGroup.GetTransformAccessArray(); - UnsafeUtility.CopyStructureToPtr(ref transformsArray, groupStructPtr + entry.FieldOffset); - } - } -} diff --git a/Unity.Entities.PerformanceTests/EntityCommandBufferPerformanceTests.cs b/Unity.Entities.PerformanceTests/EntityCommandBufferPerformanceTests.cs index a87b83b4..260efdaf 100644 --- a/Unity.Entities.PerformanceTests/EntityCommandBufferPerformanceTests.cs +++ b/Unity.Entities.PerformanceTests/EntityCommandBufferPerformanceTests.cs @@ -23,7 +23,7 @@ public void Setup() { m_PreviousWorld = World.Active; m_World = World.Active = new World("Test World"); - m_Manager = m_World.GetOrCreateManager(); + m_Manager = m_World.EntityManager; } public struct EcsTestData : IComponentData diff --git a/Unity.Entities.PerformanceTests/EntityManagerPerformanceTests.cs b/Unity.Entities.PerformanceTests/EntityManagerPerformanceTests.cs index 88fef9fe..f48010f5 100644 --- a/Unity.Entities.PerformanceTests/EntityManagerPerformanceTests.cs +++ b/Unity.Entities.PerformanceTests/EntityManagerPerformanceTests.cs @@ -16,7 +16,7 @@ public sealed unsafe class EntityManagerPerformanceTests NativeArray entities1; NativeArray entities2; NativeArray entities3; - ComponentGroup group; + EntityQuery group; const int count = 1024 * 128; @@ -25,14 +25,14 @@ public void Setup() { m_PreviousWorld = World.Active; m_World = World.Active = new World("Test World"); - m_Manager = m_World.GetOrCreateManager(); + m_Manager = m_World.EntityManager; archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3)); archetype2 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); archetype3 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData3)); entities1 = new NativeArray(count, Allocator.Persistent); entities2 = new NativeArray(count, Allocator.Persistent); entities3 = new NativeArray(count, Allocator.Persistent); - group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); } [TearDown] diff --git a/Unity.Entities.PerformanceTests/EntitySerializationPerformanceTests.cs b/Unity.Entities.PerformanceTests/EntitySerializationPerformanceTests.cs index de478d21..683bf65c 100644 --- a/Unity.Entities.PerformanceTests/EntitySerializationPerformanceTests.cs +++ b/Unity.Entities.PerformanceTests/EntitySerializationPerformanceTests.cs @@ -22,7 +22,7 @@ public void Setup() { m_PreviousWorld = World.Active; m_World = World.Active = new World("Test World"); - m_Manager = m_World.GetOrCreateManager(); + m_Manager = m_World.EntityManager; } [TearDown] @@ -104,7 +104,7 @@ private struct SerializationJob : IJobParallelForBatch public void Execute(int startIndex, int count) { // @HACK need a reliable way having the entity manage for the given entities - var manager = World.Active.GetExistingManager(); + var manager = World.Active.EntityManager; var buffer = new StringBuffer(4096); var visitor = new JsonVisitor { StringBuffer = buffer }; diff --git a/Unity.Entities.PerformanceTests/JobProcessComponentDataPrefilteringPerformanceTests.cs b/Unity.Entities.PerformanceTests/JobForEachPrefilteringPerformanceTests.cs similarity index 78% rename from Unity.Entities.PerformanceTests/JobProcessComponentDataPrefilteringPerformanceTests.cs rename to Unity.Entities.PerformanceTests/JobForEachPrefilteringPerformanceTests.cs index 91c0abbf..543d5736 100644 --- a/Unity.Entities.PerformanceTests/JobProcessComponentDataPrefilteringPerformanceTests.cs +++ b/Unity.Entities.PerformanceTests/JobForEachPrefilteringPerformanceTests.cs @@ -13,13 +13,13 @@ namespace Unity.Entities.PerformanceTests { [TestFixture] [NUnit.Framework.Category("Performance")] - public sealed class JobProcessComponentDataPrefilteringPerformanceTests + public sealed class JobForEachPrefilteringPerformanceTests { private World m_PreviousWorld; private World m_World; private EntityManager m_Manager; - private struct ProcessJob : IJobProcessComponentData + private struct ProcessJob : IJobForEach { public void Execute(ref EcsTestData c0) { @@ -32,7 +32,7 @@ public void Setup() { m_PreviousWorld = World.Active; m_World = World.Active = new World("Test World"); - m_Manager = m_World.GetOrCreateManager(); + m_Manager = m_World.EntityManager; } #if UNITY_2019_2_OR_NEWER @@ -43,36 +43,36 @@ public void Setup() public void Prefiltering_SingleArchetype_SingleChunk_Unfiltered() { const int kEntityCount = 10; - + var archetype = m_Manager.CreateArchetype(ComponentType.ReadWrite(), ComponentType.ReadWrite()); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite(),ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite(),ComponentType.ReadWrite()); var entities = new NativeArray(kEntityCount, Allocator.TempJob); m_Manager.CreateEntity(archetype, entities); - + var dependsOn = new JobHandle(); - + Measure.Method( () => { - dependsOn = new ProcessJob().ScheduleGroup(group, dependsOn); + dependsOn = new ProcessJob().Schedule(group, dependsOn); }) .Definition("Scheduling") .Run(); - + dependsOn.Complete(); - + Measure.Method( () => { - var job = new ProcessJob().ScheduleGroup(group); + var job = new ProcessJob().Schedule(group); job.Complete(); }) .Definition("ScheduleAndRun") .Run(); - + entities.Dispose(); } - + #if UNITY_2019_2_OR_NEWER [Test, Performance] #else @@ -81,49 +81,49 @@ public void Prefiltering_SingleArchetype_SingleChunk_Unfiltered() public void Prefiltering_SingleArchetype_TwoChunks_Filtered() { const int kEntityCount = 10; - + var archetype = m_Manager.CreateArchetype( - ComponentType.ReadWrite(), - ComponentType.ReadWrite(), + ComponentType.ReadWrite(), + ComponentType.ReadWrite(), ComponentType.ReadWrite()); - - var group = m_Manager.CreateComponentGroup( - ComponentType.ReadWrite(), + + var group = m_Manager.CreateEntityQuery( + ComponentType.ReadWrite(), ComponentType.ReadWrite(), ComponentType.ReadWrite()); - + var entities = new NativeArray(kEntityCount, Allocator.TempJob); m_Manager.CreateEntity(archetype, entities); for (int i = kEntityCount / 2; i < kEntityCount; ++i) { m_Manager.SetSharedComponentData(entities[i], new EcsTestSharedComp{value = 10}); } - + var dependsOn = new JobHandle(); group.SetFilter(new EcsTestSharedComp {value = 10}); Measure.Method( () => { - dependsOn = new ProcessJob().ScheduleGroup(group, dependsOn); + dependsOn = new ProcessJob().Schedule(group, dependsOn); }) .Definition("Scheduling") .Run(); - + dependsOn.Complete(); - + Measure.Method( () => { - var job = new ProcessJob().ScheduleGroup(group); + var job = new ProcessJob().Schedule(group); job.Complete(); }) .Definition("ScheduleAndRun") .Run(); - + entities.Dispose(); } - + #if UNITY_2019_2_OR_NEWER [Test, Performance] #else @@ -134,15 +134,15 @@ public void Prefiltering_SingleArchetype_MultipleChunks_Filtered() const int kEntityCount = 10000; var archetype = m_Manager.CreateArchetype( - ComponentType.ReadWrite(), - ComponentType.ReadWrite(), + ComponentType.ReadWrite(), + ComponentType.ReadWrite(), ComponentType.ReadWrite()); - - var group = m_Manager.CreateComponentGroup( - ComponentType.ReadWrite(), + + var group = m_Manager.CreateEntityQuery( + ComponentType.ReadWrite(), ComponentType.ReadWrite(), ComponentType.ReadWrite()); - + var entities = new NativeArray(kEntityCount, Allocator.TempJob); m_Manager.CreateEntity(archetype, entities); @@ -150,32 +150,32 @@ public void Prefiltering_SingleArchetype_MultipleChunks_Filtered() { m_Manager.SetSharedComponentData(entities[i], new EcsTestSharedComp {value = i % 10 } ); } - + var dependsOn = new JobHandle(); group.SetFilter(new EcsTestSharedComp{value = 0}); Measure.Method( () => { - dependsOn = new ProcessJob().ScheduleGroup(group, dependsOn); + dependsOn = new ProcessJob().Schedule(group, dependsOn); }) .Definition("Scheduling") .Run(); - + dependsOn.Complete(); - + Measure.Method( () => { - var job = new ProcessJob().ScheduleGroup(group); + var job = new ProcessJob().Schedule(group); job.Complete(); }) .Definition("ScheduleAndRun") .Run(); - + entities.Dispose(); } - + #if UNITY_2019_2_OR_NEWER [Test, Performance] #else @@ -198,7 +198,7 @@ public void Prefiltering_MultipleArchetype_MultipleChunks_Filtered() allArchetypes[4] = m_Manager.CreateArchetype(allTypes[0], allTypes[1], allTypes[2], allTypes[3]); allArchetypes[5] = m_Manager.CreateArchetype(allTypes[0], allTypes[1], allTypes[2], allTypes[4]); allArchetypes[6] = m_Manager.CreateArchetype(allTypes[0], allTypes[1], allTypes[3], allTypes[4]); - allArchetypes[7] = m_Manager.CreateArchetype(allTypes); + allArchetypes[7] = m_Manager.CreateArchetype(allTypes); const int kEntityCountPerArchetype = 1000; for (int i = 0; i < 8; ++i) @@ -209,36 +209,36 @@ public void Prefiltering_MultipleArchetype_MultipleChunks_Filtered() for (int j = 0; j < kEntityCountPerArchetype; ++j) { m_Manager.SetSharedComponentData(entities[i], new EcsTestSharedComp {value = i % 10 } ); - } - + } + entities.Dispose(); } - + var dependsOn = new JobHandle(); - var group = m_Manager.CreateComponentGroup( - ComponentType.ReadWrite(), + var group = m_Manager.CreateEntityQuery( + ComponentType.ReadWrite(), ComponentType.ReadWrite()); group.SetFilter(new EcsTestSharedComp{value = 0}); Measure.Method( () => { - dependsOn = new ProcessJob().ScheduleGroup(group, dependsOn); + dependsOn = new ProcessJob().Schedule(group, dependsOn); }) .Definition("Scheduling") .Run(); - + dependsOn.Complete(); - + Measure.Method( () => { - var job = new ProcessJob().ScheduleGroup(group); + var job = new ProcessJob().Schedule(group); job.Complete(); }) .Definition("ScheduleAndRun") .Run(); - + } } } diff --git a/Unity.Entities.PerformanceTests/JobProcessComponentDataPrefilteringPerformanceTests.cs.meta b/Unity.Entities.PerformanceTests/JobForEachPrefilteringPerformanceTests.cs.meta similarity index 100% rename from Unity.Entities.PerformanceTests/JobProcessComponentDataPrefilteringPerformanceTests.cs.meta rename to Unity.Entities.PerformanceTests/JobForEachPrefilteringPerformanceTests.cs.meta diff --git a/Unity.Entities.PerformanceTests/SharedComponentPerformanceTests.cs b/Unity.Entities.PerformanceTests/SharedComponentPerformanceTests.cs index d3edb6a3..238362e0 100644 --- a/Unity.Entities.PerformanceTests/SharedComponentPerformanceTests.cs +++ b/Unity.Entities.PerformanceTests/SharedComponentPerformanceTests.cs @@ -15,7 +15,7 @@ public void Setup() { m_PreviousWorld = World.Active; m_World = World.Active = new World("Test World"); - m_Manager = m_World.GetOrCreateManager(); + m_Manager = m_World.EntityManager; } [TearDown] diff --git a/Unity.Entities.Properties.Tests/EntitySerializationTests.cs b/Unity.Entities.Properties.Tests/EntitySerializationTests.cs index 3ca27dec..3bd371bc 100644 --- a/Unity.Entities.Properties.Tests/EntitySerializationTests.cs +++ b/Unity.Entities.Properties.Tests/EntitySerializationTests.cs @@ -19,7 +19,7 @@ public void Setup() { m_PreviousWorld = World.Active; m_World = World.Active = new World ("Test World"); - m_Manager = m_World.GetOrCreateManager (); + m_Manager = m_World.EntityManager; } [TearDown] diff --git a/Unity.Entities.StaticTypeRegistry/StaticTypeRegistry.cs b/Unity.Entities.StaticTypeRegistry/StaticTypeRegistry.cs index 1ffff332..d3bfc530 100644 --- a/Unity.Entities.StaticTypeRegistry/StaticTypeRegistry.cs +++ b/Unity.Entities.StaticTypeRegistry/StaticTypeRegistry.cs @@ -10,6 +10,8 @@ static internal unsafe class StaticTypeRegistry static public readonly bool[] SystemIsGroup; static public readonly string[] SystemName; // Debugging. And a reason to have a TinyReflectionSystem static public readonly int[] EntityOffsets; + static public readonly int[] BlobAssetReferenceOffsets; + static public readonly int[] WriteGroups; // This field will be generated in the replacement assembly //static public readonly TypeManager.TypeInfo[] TypeInfos; #pragma warning restore 0649 @@ -35,6 +37,20 @@ public static bool Equals(void* lhs, void* rhs, int typeIndex) throw new NotImplementedException("This function should have been replaced by the TypeRegGen build step. Ensure TypeRegGen.exe is generating a new Unity.Entities.StaticTypeRegistry assembly."); } + public static bool Equals(object lhs, object rhs, int typeIndex) + { + // empty -- dynamic reg is used. TypeRegGen will generate + // a replacement assembly + throw new NotImplementedException("This function should have been replaced by the TypeRegGen build step. Ensure TypeRegGen.exe is generating a new Unity.Entities.StaticTypeRegistry assembly."); + } + + public static bool Equals(object lhs, void* rhs, int typeIndex) + { + // empty -- dynamic reg is used. TypeRegGen will generate + // a replacement assembly + throw new NotImplementedException("This function should have been replaced by the TypeRegGen build step. Ensure TypeRegGen.exe is generating a new Unity.Entities.StaticTypeRegistry assembly."); + } + public static int GetHashCode(void* val, int typeIndex) { // empty -- dynamic reg is used. TypeRegGen will generate @@ -42,5 +58,11 @@ public static int GetHashCode(void* val, int typeIndex) throw new NotImplementedException("This function should have been replaced by the TypeRegGen build step. Ensure TypeRegGen.exe is generating a new Unity.Entities.StaticTypeRegistry assembly."); } + public static int BoxedGetHashCode(object val, int typeIndex) + { + // empty -- dynamic reg is used. TypeRegGen will generate + // a replacement assembly + throw new NotImplementedException("This function should have been replaced by the TypeRegGen build step. Ensure TypeRegGen.exe is generating a new Unity.Entities.StaticTypeRegistry assembly."); + } } } diff --git a/Unity.Entities.Tests/ArchetypeChunkArrayTests.cs b/Unity.Entities.Tests/ArchetypeChunkArrayTests.cs index 476c8c69..51314888 100644 --- a/Unity.Entities.Tests/ArchetypeChunkArrayTests.cs +++ b/Unity.Entities.Tests/ArchetypeChunkArrayTests.cs @@ -85,13 +85,13 @@ public void ACS_WriteMixed() { CreateMixedEntities(64); - var query = new EntityArchetypeQuery + var query = new EntityQueryDesc { Any = new ComponentType[] {typeof(EcsTestData2), typeof(EcsTestData)}, // any None = Array.Empty(), // none All = Array.Empty(), // all }; - var group = m_Manager.CreateComponentGroup(query); + var group = m_Manager.CreateEntityQuery(query); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); @@ -199,7 +199,7 @@ public void ACS_WriteMixedFilterShared() } } - var group = m_Manager.CreateComponentGroup(new EntityArchetypeQuery + var group = m_Manager.CreateEntityQuery(new EntityQueryDesc { Any = new ComponentType[] {typeof(EcsTestData2), typeof(EcsTestData)}, // any None = Array.Empty(), // none @@ -287,7 +287,7 @@ public void ACS_Buffers() { CreateEntities(128); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); @@ -336,11 +336,11 @@ public void Execute(int chunkIndex) } } - ComponentGroup m_Group; + EntityQuery m_Group; - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(typeof(EcsIntElement)); + m_Group = GetEntityQuery(typeof(EcsIntElement)); } protected override void OnUpdate() @@ -365,7 +365,7 @@ public void ACS_BufferHas() { CreateEntities(128); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); @@ -392,7 +392,7 @@ public void ACS_BufferVersions() { CreateEntities(128); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); @@ -412,7 +412,7 @@ public void ACS_BufferVersions() } // Run system to bump chunk versions - var bumpChunkBufferTypeVersionSystem = World.CreateManager(); + var bumpChunkBufferTypeVersionSystem = World.CreateSystem(); bumpChunkBufferTypeVersionSystem.Update(); // Check versions after modifications @@ -430,12 +430,12 @@ public void ACS_BufferVersions() } [Test] - [StandaloneFixme] // ISharedComponentData + [StandaloneFixme] // don't know why this fails public void ACS_BuffersRO() { CreateEntities(128); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); var intElements = m_Manager.GetArchetypeChunkBufferType(true); @@ -450,14 +450,14 @@ public void ACS_BuffersRO() } [Test] - [StandaloneFixme] // ISharedComponentData + [StandaloneFixme] // don't know why this fails public void ACS_ChunkArchetypeTypesMatch() { var entityTypes = new ComponentType[] {typeof(EcsTestData), typeof(EcsTestSharedComp), typeof(EcsIntElement)}; CreateEntities(128); - var group = m_Manager.CreateComponentGroup(entityTypes); + var group = m_Manager.CreateEntityQuery(entityTypes); using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) @@ -481,13 +481,12 @@ public void ACS_ChunkArchetypeTypesMatch() struct Max3Capacity : IComponentData { } [Test] - [StandaloneFixme] // MaximumChunkCapacityAttribute not supported in Tiny? public void MaximumChunkCapacityIsRespected() { for (int i = 0; i != 4; i++) m_Manager.CreateEntity(typeof(Max3Capacity)); - var group = m_Manager.CreateComponentGroup(typeof(Max3Capacity)); + var group = m_Manager.CreateEntityQuery(typeof(Max3Capacity)); using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) { Assert.AreEqual(2, chunks.Length); diff --git a/Unity.Entities.Tests/BlobificationTests.cs b/Unity.Entities.Tests/BlobificationTests.cs index b681d77b..582f3766 100644 --- a/Unity.Entities.Tests/BlobificationTests.cs +++ b/Unity.Entities.Tests/BlobificationTests.cs @@ -7,7 +7,6 @@ using Unity.Entities; using Unity.Entities.Tests; -[StandaloneFixme] // Should this work for Tiny? public class BlobTests : ECSTestsFixture { //@TODO: Test Prevent NativeArray and other containers inside of Blob data @@ -122,7 +121,7 @@ public void ReadBlobDataFromJob() } - struct ValidateBlobInComponentJob : IJobProcessComponentData + struct ValidateBlobInComponentJob : IJobForEach { public bool ExpectException; @@ -156,7 +155,7 @@ public unsafe void ParallelBlobAccessFromEntityJob() var jobData = new ValidateBlobInComponentJob(); - var system = World.Active.GetOrCreateManager(); + var system = World.Active.GetOrCreateSystem(); var jobHandle = jobData.Schedule(system); ValidateBlobData(ref blob.Value); @@ -175,7 +174,7 @@ public void DestroyedBlobAccessFromEntityJobThrows() var jobData = new ValidateBlobInComponentJob(); jobData.ExpectException = true; - var system = World.Active.GetOrCreateManager(); + var system = World.Active.GetOrCreateSystem(); var jobHandle = jobData.Schedule(system); jobHandle.Complete (); diff --git a/Unity.Entities.Tests/BufferElementDataInstantiateTests.cs b/Unity.Entities.Tests/BufferElementDataInstantiateTests.cs index b00d5fa0..4d6e5c6a 100644 --- a/Unity.Entities.Tests/BufferElementDataInstantiateTests.cs +++ b/Unity.Entities.Tests/BufferElementDataInstantiateTests.cs @@ -5,7 +5,6 @@ using Unity.Collections; #pragma warning disable 0649 -#pragma warning disable 0618 #pragma warning disable 0219 // assigned but its value is never used namespace Unity.Entities.Tests @@ -144,7 +143,6 @@ public void DuplicatingEntity_WhenPrototypeHasDynamicBuffer_DoesNotWriteOutOfBou } #pragma warning restore 0649 -#pragma warning restore 0618 #pragma warning restore 0219 // assigned but its value is never used diff --git a/Unity.Entities.Tests/BufferElementDataSystemStateInstantiateTests.cs b/Unity.Entities.Tests/BufferElementDataSystemStateInstantiateTests.cs index 9dc84222..e8d23d61 100644 --- a/Unity.Entities.Tests/BufferElementDataSystemStateInstantiateTests.cs +++ b/Unity.Entities.Tests/BufferElementDataSystemStateInstantiateTests.cs @@ -5,7 +5,6 @@ namespace Unity.Entities.Tests public class BufferElementDataSystemStateInstantiateTests : ECSTestsFixture { [Test] - [StandaloneFixme] // Real issue public unsafe void InstantiateDoesNotCreatesCopy() { var original = m_Manager.CreateEntity(typeof(EcsIntStateElement)); diff --git a/Unity.Entities.Tests/BufferElementDataSystemStateTests.cs b/Unity.Entities.Tests/BufferElementDataSystemStateTests.cs index 4a683be9..7b1ce534 100644 --- a/Unity.Entities.Tests/BufferElementDataSystemStateTests.cs +++ b/Unity.Entities.Tests/BufferElementDataSystemStateTests.cs @@ -1,5 +1,6 @@ using NUnit.Framework; using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; using System; using System.Collections.Generic; using System.Linq; @@ -16,7 +17,6 @@ // ******* COPY AND PASTE WARNING ************* #pragma warning disable 0649 -#pragma warning disable 0618 #pragma warning disable 0219 // assigned but its value is never used namespace Unity.Entities.Tests @@ -282,34 +282,6 @@ public void MutateBufferData() } } - [Test] - public void BufferArrayComponentGroupIteration() - { - /*var entity64 =*/ - m_Manager.CreateEntity(typeof(EcsIntStateElement)); - /*var entity10 =*/ - m_Manager.CreateEntity(typeof(EcsIntStateElement)); - - var group = m_Manager.CreateComponentGroup(typeof(EcsIntStateElement)); - - var buffers = group.GetBufferArray(); - - Assert.AreEqual(2, buffers.Length); - Assert.AreEqual(0, buffers[0].Length); - Assert.AreEqual(8, buffers[0].Capacity); - Assert.AreEqual(0, buffers[1].Length); - Assert.AreEqual(8, buffers[1].Capacity); - - buffers[0].Add(12); - buffers[0].Add(13); - - Assert.AreEqual(2, buffers[0].Length); - Assert.AreEqual(12, buffers[0][0].Value); - Assert.AreEqual(13, buffers[0][1].Value); - - Assert.AreEqual(0, buffers[1].Length); - } - [Test] public void BufferComponentGroupChunkIteration() { @@ -318,7 +290,7 @@ public void BufferComponentGroupChunkIteration() /*var entity10 =*/ m_Manager.CreateEntity(typeof(EcsIntStateElement)); - var group = m_Manager.CreateComponentGroup(typeof(EcsIntStateElement)); + var group = m_Manager.CreateEntityQuery(typeof(EcsIntStateElement)); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); var buffers = chunks[0].GetBufferAccessor(m_Manager.GetArchetypeChunkBufferType(false)); @@ -355,7 +327,6 @@ public void BufferFromEntityWorks() } [Test] - [StandaloneFixme] // Real issue - Safety & Sentinel should be invalid after Destroy public void OutOfBoundsAccessThrows() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntStateElement)); @@ -370,7 +341,6 @@ public void OutOfBoundsAccessThrows() } [Test] - [StandaloneFixme] // Real issue - Safety & Sentinel should be invalid after Destroy public void UseAfterStructuralChangeThrows() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntStateElement)); @@ -384,7 +354,6 @@ public void UseAfterStructuralChangeThrows() } [Test] - [StandaloneFixme] // Real issue - Safety & Sentinel should be invalid after Destroy public void UseAfterStructuralChangeThrows2() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntStateElement)); @@ -399,19 +368,19 @@ public void UseAfterStructuralChangeThrows2() } [Test] - [StandaloneFixme] // Real issue - Safety & Sentinel should be invalid after Add on structural change public void UseAfterStructuralChangeThrows3() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntStateElement)); var buffer = m_Manager.GetBuffer(entityInt); buffer.CopyFrom(new EcsIntStateElement[] { 1, 2, 3 }); m_Manager.AddComponentData(entityInt, new EcsTestData() { value = 20 }); - Assert.Throws(() => { buffer.Add(4); }); + Assert.Throws(() => { + buffer.Add(4); + }); } [Test] - [StandaloneFixme] // Real issue - Safety & Sentinel should be invalid after Add on structural change public void WritingReadOnlyThrows() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntStateElement)); @@ -453,57 +422,6 @@ public void ReinterpretWrongSizeThrows() }); } -// Injection is obsolete - [DisableAutoCreation] - public class InjectionTestSystem : JobComponentSystem - { - public struct Data - { - public readonly int Length; - public BufferArray Buffers; - } - - [Inject] Data m_Data; - - public struct MyJob : IJobParallelFor - { - public BufferArray Buffers; - - public void Execute(int i) - { - Buffers[i].Add(i * 3); - } - } - - protected override JobHandle OnUpdate(JobHandle inputDeps) - { - new MyJob { Buffers = m_Data.Buffers }.Schedule(m_Data.Length, 32, inputDeps).Complete(); - return default(JobHandle); - } - } - - [Test] - [StandaloneFixme] // IJob - InjectionTestSystem : JobComponentSystem - public void Injection() - { - var system = World.Active.GetOrCreateManager(); - - using (var entities = new NativeArray(320, Allocator.Temp)) - { - var arch = m_Manager.CreateArchetype(typeof(EcsIntStateElement)); - m_Manager.CreateEntity(arch, entities); - - system.Update(); - system.Update(); - - for (var i = 0; i < entities.Length; ++i) - { - var buf = m_Manager.GetBuffer(entities[i]); - Assert.AreEqual(2, buf.Length); - } - } - } - [Test] public void TrimExcessWorks() { @@ -566,7 +484,6 @@ public void NoCapacitySpecifiedWorks() } [Test] - [StandaloneFixme] // Real issue : buffer.AsNativeArray should invalidate the Safety public void ArrayInvalidationWorks() { var original = m_Manager.CreateEntity(typeof(EcsIntStateElement)); @@ -587,7 +504,6 @@ public void ArrayInvalidationWorks() } [Test] - [StandaloneFixme] // Real issue : buffer.AsNativeArray should invalidate the Safety public void ArrayInvalidationHappensForAllInstances() { var e0 = m_Manager.CreateEntity(typeof(EcsIntStateElement)); @@ -680,7 +596,7 @@ public void ReadWriteDynamicBuffer() var buffer = m_Manager.GetBuffer(original); buffer.Add(5); - var group = EmptySystem.GetComponentGroup(new EntityArchetypeQuery {All = new ComponentType[] {typeof(EcsIntStateElement)}}); + var group = EmptySystem.GetEntityQuery(new EntityQueryDesc {All = new ComponentType[] {typeof(EcsIntStateElement)}}); var job = new WriteJob { //@TODO: Throw exception when read only flag is not accurately passed to job for buffers... @@ -720,7 +636,7 @@ public void ReadOnlyDynamicBufferImpl(bool readOnlyType) var buffer = m_Manager.GetBuffer(original); buffer.Add(5); - var group = EmptySystem.GetComponentGroup(new EntityArchetypeQuery {All = new ComponentType[] {typeof(EcsIntStateElement)}}); + var group = EmptySystem.GetEntityQuery(new EntityQueryDesc {All = new ComponentType[] {typeof(EcsIntStateElement)}}); var job = new ReadOnlyJob { Int = EmptySystem.GetArchetypeChunkBufferType(readOnlyType) @@ -823,10 +739,99 @@ public void DynamicBuffer_FromEntity_IsCreated_IsTrue() var buffer = m_Manager.GetBuffer(entity); Assert.IsTrue(buffer.IsCreated); } + + [Test] + public void DynamicBuffer_AllocateBufferWithLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntStateElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + Assert.DoesNotThrow(() => buffer.ResizeUninitialized(capacity)); + Assert.AreEqual(capacity, buffer.Length); + } + + [Test] + public void DynamicBuffer_Insert_BufferHasLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntStateElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + buffer.ResizeUninitialized(capacity); + + Assert.DoesNotThrow(() => buffer.Insert(0, new EcsIntStateElement { Value = 99 })); + Assert.AreEqual(capacity + 1, buffer.Length); + } + + [Test] + public void DynamicBuffer_AddRange_NewBufferHasLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + buffer.ResizeUninitialized(capacity); + + NativeArray array = new NativeArray(10, Allocator.Temp); + Assert.DoesNotThrow(() => buffer.AddRange(array)); + Assert.AreEqual(capacity + 10, buffer.Length); + } + + [Test] + public void DynamicBuffer_RemoveRange_MovedBufferHasLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 2); + buffer.ResizeUninitialized(capacity); + + Assert.AreEqual(536870914, buffer.Length); + Assert.DoesNotThrow(() => buffer.RemoveRange(0, 1)); + Assert.AreEqual(536870913, buffer.Length); + } + + [Test] + public void DynamicBuffer_Add_NewBufferHasLongSize_DoesNotThrow() + { + var arrayType = ComponentType.ReadWrite(); + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + + buffer.ResizeUninitialized(capacity); + + Assert.DoesNotThrow(() => buffer.Add(1)); + } + + [Test] + public void DynamicBuffer_TrimExcess_NewBufferHasLongSize_DoesNotThrow() + { + var arrayType = ComponentType.ReadWrite(); + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + + buffer.ResizeUninitialized(capacity); + // cause the capacity to double + buffer.Add(1); + + Assert.DoesNotThrow(() => buffer.TrimExcess()); + Assert.AreEqual(capacity + 1, buffer.Length); + } + + [Test] + public void DynamicBuffer_Reserve_IncreasesCapacity() + { + var arrayType = ComponentType.ReadWrite(); + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + + buffer.Reserve(100); + + Assert.AreEqual(100, buffer.Capacity); + Assert.AreEqual(0, buffer.Length); + } } } #pragma warning restore 0649 -#pragma warning restore 0618 #pragma warning restore 0219 // assigned but its value is never used diff --git a/Unity.Entities.Tests/BufferElementDataTests.cs b/Unity.Entities.Tests/BufferElementDataTests.cs index 7f5ecd9b..e78665d8 100644 --- a/Unity.Entities.Tests/BufferElementDataTests.cs +++ b/Unity.Entities.Tests/BufferElementDataTests.cs @@ -1,5 +1,6 @@ using NUnit.Framework; using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; using System; using System.Collections.Generic; using System.Linq; @@ -16,7 +17,6 @@ // ******* COPY AND PASTE WARNING ************* #pragma warning disable 0649 -#pragma warning disable 0618 #pragma warning disable 0219 // assigned but its value is never used namespace Unity.Entities.Tests @@ -282,34 +282,6 @@ public void MutateBufferData() } } - [Test] - public void BufferArrayComponentGroupIteration() - { - /*var entity64 =*/ - m_Manager.CreateEntity(typeof(EcsIntElement)); - /*var entity10 =*/ - m_Manager.CreateEntity(typeof(EcsIntElement)); - - var group = m_Manager.CreateComponentGroup(typeof(EcsIntElement)); - - var buffers = group.GetBufferArray(); - - Assert.AreEqual(2, buffers.Length); - Assert.AreEqual(0, buffers[0].Length); - Assert.AreEqual(8, buffers[0].Capacity); - Assert.AreEqual(0, buffers[1].Length); - Assert.AreEqual(8, buffers[1].Capacity); - - buffers[0].Add(12); - buffers[0].Add(13); - - Assert.AreEqual(2, buffers[0].Length); - Assert.AreEqual(12, buffers[0][0].Value); - Assert.AreEqual(13, buffers[0][1].Value); - - Assert.AreEqual(0, buffers[1].Length); - } - [Test] public void BufferComponentGroupChunkIteration() { @@ -318,7 +290,7 @@ public void BufferComponentGroupChunkIteration() /*var entity10 =*/ m_Manager.CreateEntity(typeof(EcsIntElement)); - var group = m_Manager.CreateComponentGroup(typeof(EcsIntElement)); + var group = m_Manager.CreateEntityQuery(typeof(EcsIntElement)); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); var buffers = chunks[0].GetBufferAccessor(m_Manager.GetArchetypeChunkBufferType(false)); @@ -355,7 +327,6 @@ public void BufferFromEntityWorks() } [Test] - [StandaloneFixme] // Real problem DestroyEntity should invalidate the buffers. Not sure about array bounds checking in this test public void OutOfBoundsAccessThrows() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -370,7 +341,6 @@ public void OutOfBoundsAccessThrows() } [Test] - [StandaloneFixme] // Real problem DestroyEntity should invalidate the buffers public void UseAfterStructuralChangeThrows() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -384,7 +354,6 @@ public void UseAfterStructuralChangeThrows() } [Test] - [StandaloneFixme] // Real problem DestroyEntity should invalidate the buffers public void UseAfterStructuralChangeThrows2() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -399,7 +368,6 @@ public void UseAfterStructuralChangeThrows2() } [Test] - [StandaloneFixme] // Real problem structural change should invalidate the buffers public void UseAfterStructuralChangeThrows3() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -411,7 +379,6 @@ public void UseAfterStructuralChangeThrows3() [Test] - [StandaloneFixme] // Real problem structural change should invalidate the buffers public void WritingReadOnlyThrows() { var entityInt = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -453,57 +420,6 @@ public void ReinterpretWrongSizeThrows() }); } -// Injection is obsolete - [DisableAutoCreation] - public class InjectionTestSystem : JobComponentSystem - { - public struct Data - { - public readonly int Length; - public BufferArray Buffers; - } - - [Inject] Data m_Data; - - public struct MyJob : IJobParallelFor - { - public BufferArray Buffers; - - public void Execute(int i) - { - Buffers[i].Add(i * 3); - } - } - - protected override JobHandle OnUpdate(JobHandle inputDeps) - { - new MyJob { Buffers = m_Data.Buffers }.Schedule(m_Data.Length, 32, inputDeps).Complete(); - return default(JobHandle); - } - } - - [Test] - [StandaloneFixme] // IJob - public void Injection() - { - var system = World.Active.GetOrCreateManager(); - - using (var entities = new NativeArray(320, Allocator.Temp)) - { - var arch = m_Manager.CreateArchetype(typeof(EcsIntElement)); - m_Manager.CreateEntity(arch, entities); - - system.Update(); - system.Update(); - - for (var i = 0; i < entities.Length; ++i) - { - var buf = m_Manager.GetBuffer(entities[i]); - Assert.AreEqual(2, buf.Length); - } - } - } - [Test] public void TrimExcessWorks() { @@ -566,7 +482,6 @@ public void NoCapacitySpecifiedWorks() } [Test] - [StandaloneFixme] // Real problem structural change should invalidate the buffers public void ArrayInvalidationWorks() { var original = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -588,7 +503,6 @@ public void ArrayInvalidationWorks() } [Test] - [StandaloneFixme] // Real problem structural change should invalidate the buffers public void ArrayInvalidationHappensForAllInstances() { var e0 = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -639,7 +553,7 @@ public void Execute() } [Test] - [StandaloneFixme] // Real problem structural change should invalidate the buffers && IJob + [StandaloneFixme] // IJob public void BufferInvalidationNotPossibleWhenArraysAreGivenToJobs() { var original = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -674,14 +588,13 @@ public void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset) } [Test] - [StandaloneFixme] // IJob public void ReadWriteDynamicBuffer() { var original = m_Manager.CreateEntity(typeof(EcsIntElement)); var buffer = m_Manager.GetBuffer(original); buffer.Add(5); - var group = EmptySystem.GetComponentGroup(new EntityArchetypeQuery {All = new ComponentType[] {typeof(EcsIntElement)}}); + var group = EmptySystem.GetEntityQuery(new EntityQueryDesc {All = new ComponentType[] {typeof(EcsIntElement)}}); var job = new WriteJob { //@TODO: Throw exception when read only flag is not accurately passed to job for buffers... @@ -721,7 +634,7 @@ public void ReadOnlyDynamicBufferImpl(bool readOnlyType) var buffer = m_Manager.GetBuffer(original); buffer.Add(5); - var group = EmptySystem.GetComponentGroup(new EntityArchetypeQuery {All = new ComponentType[] {typeof(EcsIntElement)}}); + var group = EmptySystem.GetEntityQuery(new EntityQueryDesc {All = new ComponentType[] {typeof(EcsIntElement)}}); var job = new ReadOnlyJob { Int = EmptySystem.GetArchetypeChunkBufferType(readOnlyType) @@ -786,7 +699,7 @@ public void Execute() } [Test] - [StandaloneFixme] // IJob + Safety Handles + [StandaloneFixme] // IJob public void NativeArrayInJobReadOnly() { var original = m_Manager.CreateEntity(typeof(EcsIntElement)); @@ -824,10 +737,99 @@ public void DynamicBuffer_FromEntity_IsCreated_IsTrue() var buffer = m_Manager.GetBuffer(entity); Assert.IsTrue(buffer.IsCreated); } - } + + [Test] + public void DynamicBuffer_AllocateBufferWithLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + Assert.DoesNotThrow(() => buffer.ResizeUninitialized(capacity)); + Assert.AreEqual(capacity, buffer.Length); + } + + [Test] + public void DynamicBuffer_Insert_BufferHasLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + buffer.ResizeUninitialized(capacity); + + Assert.DoesNotThrow(() => buffer.Insert(0, new EcsIntElement { Value = 99 })); + Assert.AreEqual(capacity + 1, buffer.Length); + } + + [Test] + public void DynamicBuffer_AddRange_NewBufferHasLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + buffer.ResizeUninitialized(capacity); + + NativeArray array = new NativeArray(10, Allocator.Temp); + Assert.DoesNotThrow(() => buffer.AddRange(array)); + Assert.AreEqual(capacity + 10, buffer.Length); + } + + [Test] + public void DynamicBuffer_RemoveRange_MovedBufferHasLongSize_DoesNotThrow() + { + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 2); + buffer.ResizeUninitialized(capacity); + + Assert.AreEqual(536870914, buffer.Length); + Assert.DoesNotThrow(() => buffer.RemoveRange(0, 1)); + Assert.AreEqual(536870913, buffer.Length); + } + + [Test] + public void DynamicBuffer_Add_NewBufferHasLongSize_DoesNotThrow() + { + var arrayType = ComponentType.ReadWrite(); + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + + buffer.ResizeUninitialized(capacity); + + Assert.DoesNotThrow(() => buffer.Add(1)); + } + + [Test] + public void DynamicBuffer_TrimExcess_NewBufferHasLongSize_DoesNotThrow() + { + var arrayType = ComponentType.ReadWrite(); + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + int capacity = (int)(((long)int.MaxValue + 1) / UnsafeUtility.SizeOf() + 1); //536870913 + + buffer.ResizeUninitialized(capacity); + // cause the capacity to double + buffer.Add(1); + + Assert.DoesNotThrow(() => buffer.TrimExcess()); + Assert.AreEqual(capacity + 1, buffer.Length); + } + + [Test] + public void DynamicBuffer_Reserve_IncreasesCapacity() + { + var arrayType = ComponentType.ReadWrite(); + var entity = m_Manager.CreateEntity(typeof(EcsIntElement)); + var buffer = m_Manager.GetBuffer(entity); + + buffer.Reserve(100); + + Assert.AreEqual(100, buffer.Capacity); + Assert.AreEqual(0, buffer.Length); + } + } } #pragma warning restore 0649 -#pragma warning restore 0618 #pragma warning restore 0219 // assigned but its value is never used diff --git a/Unity.Entities.Tests/ChangeVersionTests.cs b/Unity.Entities.Tests/ChangeVersionTests.cs index 108f8319..78b7dbf1 100644 --- a/Unity.Entities.Tests/ChangeVersionTests.cs +++ b/Unity.Entities.Tests/ChangeVersionTests.cs @@ -2,79 +2,67 @@ using Unity.Collections; using Unity.Jobs; -#pragma warning disable 618 - namespace Unity.Entities.Tests { class ChangeVersionTests : ECSTestsFixture { +#if !UNITY_ZEROPLAYER [DisableAutoCreation] class BumpVersionSystemInJob : ComponentSystem { -#pragma warning disable 649 - struct MyStruct - { - public readonly int Length; - public ComponentDataArray Data; - public ComponentDataArray Data2; - } - - [Inject] - MyStruct DataStruct; -#pragma warning restore 649 + public EntityQuery m_Group; - struct UpdateData : IJob + struct UpdateData : IJobForEach { - public int Length; - public ComponentDataArray Data; - public ComponentDataArray Data2; - - public void Execute() + public void Execute(ref EcsTestData data, ref EcsTestData2 data2) { - for (int i = 0; i < Length; ++i) - { - var d2 = Data2[i]; - d2.value0 = 10; - Data2[i] = d2; - } + data2 = new EcsTestData2 {value0 = 10}; } } protected override void OnUpdate() { - var updateDataJob = new UpdateData - { - Length = DataStruct.Length, - Data = DataStruct.Data, - Data2 = DataStruct.Data2 - }; - var updateDataJobHandle = updateDataJob.Schedule(); + var updateDataJob = new UpdateData{}; + var updateDataJobHandle = updateDataJob.Schedule(m_Group); updateDataJobHandle.Complete(); } + + protected override void OnCreate() + { + m_Group = GetEntityQuery(ComponentType.ReadWrite(), + ComponentType.ReadWrite()); + } } +#endif [DisableAutoCreation] class BumpVersionSystem : ComponentSystem { - struct MyStruct - { -#pragma warning disable 649 - public readonly int Length; - public ComponentDataArray Data; - public ComponentDataArray Data2; - } - - [Inject] - MyStruct DataStruct; -#pragma warning restore 649 + public EntityQuery m_Group; protected override void OnUpdate() { - for (int i = 0; i < DataStruct.Length; ++i) { - var d2 = DataStruct.Data2[i]; + var data = m_Group.ToComponentDataArray(Allocator.TempJob); + var data2 = m_Group.ToComponentDataArray(Allocator.TempJob); + + for (int i = 0; i < data.Length; ++i) + { + var d2 = data2[i]; d2.value0 = 10; - DataStruct.Data2[i] = d2; + data2[i] = d2; } + + m_Group.CopyFromComponentDataArray(data); + m_Group.CopyFromComponentDataArray(data2); + + data.Dispose(); + data2.Dispose(); + } + + protected override void OnCreate() + { + m_Group = GetEntityQuery(ComponentType.ReadWrite(), + ComponentType.ReadWrite()); } } @@ -97,12 +85,12 @@ public void Execute(int chunkIndex) } } - ComponentGroup m_Group; + EntityQuery m_Group; private bool m_LastAllChanged; - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(typeof(EcsTestData)); + m_Group = GetEntityQuery(typeof(EcsTestData)); m_LastAllChanged = false; } @@ -135,60 +123,12 @@ public bool AllEcsTestDataChunksChanged() } } - [Test] - [StandaloneFixme] // IJob - public void CHG_IncrementedOnInjectionInJob() - { - var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var bumpSystem = World.CreateManager(); - - var oldGlobalVersion = m_Manager.GlobalSystemVersion; - - bumpSystem.Update(); - - var value0 = m_Manager.GetComponentData(entity0).value0; - Assert.AreEqual(10, value0); - - Assert.That(m_Manager.GlobalSystemVersion > oldGlobalVersion); - - unsafe { - // a system ran, the version should match the global - var chunk0 = m_Manager.Entities->GetComponentChunk(entity0); - var td2index0 = ChunkDataUtility.GetIndexInTypeArray(chunk0->Archetype, TypeManager.GetTypeIndex()); - Assert.AreEqual(m_Manager.GlobalSystemVersion, chunk0->GetChangeVersion(td2index0)); - } - } - - [Test] - [StandaloneFixme] // IJob - public void CHG_IncrementedOnInjection() - { - var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var bumpSystem = World.CreateManager(); - - var oldGlobalVersion = m_Manager.GlobalSystemVersion; - - bumpSystem.Update(); - - var value0 = m_Manager.GetComponentData(entity0).value0; - Assert.AreEqual(10, value0); - - Assert.That(m_Manager.GlobalSystemVersion > oldGlobalVersion); - - unsafe { - // a system ran, the version should match the global - var chunk0 = m_Manager.Entities->GetComponentChunk(entity0); - var td2index0 = ChunkDataUtility.GetIndexInTypeArray(chunk0->Archetype, TypeManager.GetTypeIndex()); - Assert.AreEqual(m_Manager.GlobalSystemVersion, chunk0->GetChangeVersion(td2index0)); - } - } - [Test] public void CHG_BumpValueChangesChunkTypeVersion() { m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var bumpChunkTypeVersionSystem = World.CreateManager(); + var bumpChunkTypeVersionSystem = World.CreateSystem(); bumpChunkTypeVersionSystem.Update(); Assert.AreEqual(true, bumpChunkTypeVersionSystem.AllEcsTestDataChunksChanged()); @@ -201,10 +141,22 @@ public void CHG_BumpValueChangesChunkTypeVersion() public void CHG_SystemVersionZeroWhenNotRun() { m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var system = World.CreateManager(); + var system = World.CreateSystem(); + Assert.AreEqual(0, system.LastSystemVersion); + system.Update(); + Assert.AreNotEqual(0, system.LastSystemVersion); + } + +#if !UNITY_ZEROPLAYER + [Test] + public void CHG_SystemVersionJob() + { + m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); + var system = World.CreateSystem(); Assert.AreEqual(0, system.LastSystemVersion); system.Update(); Assert.AreNotEqual(0, system.LastSystemVersion); } +#endif } } diff --git a/Unity.Entities.Tests/ChunkChangeVersionTests.cs b/Unity.Entities.Tests/ChunkChangeVersionTests.cs index f91e88ef..23e565b2 100644 --- a/Unity.Entities.Tests/ChunkChangeVersionTests.cs +++ b/Unity.Entities.Tests/ChunkChangeVersionTests.cs @@ -143,7 +143,6 @@ public void ModifyingBufferComponentMarksOnlySetTypeAsChanged() } [Test] - [StandaloneFixme] // ISharedComponentData public void AddSharedComponentMarksSrcAndDestChunkAsChanged() { var e0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); @@ -158,7 +157,6 @@ public void AddSharedComponentMarksSrcAndDestChunkAsChanged() } [Test] - [StandaloneFixme] // ISharedComponentData public void SetSharedComponentMarksSrcAndDestChunkAsChanged() { var e0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestSharedComp)); @@ -172,7 +170,6 @@ public void SetSharedComponentMarksSrcAndDestChunkAsChanged() } [Test] - [StandaloneFixme] // ISharedComponentData public void SwapComponentsMarksSrcAndDestChunkAsChanged() { var e0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestSharedComp)); diff --git a/Unity.Entities.Tests/ChunkComponentTests.cs b/Unity.Entities.Tests/ChunkComponentTests.cs index f35f67a5..c83b2dd6 100644 --- a/Unity.Entities.Tests/ChunkComponentTests.cs +++ b/Unity.Entities.Tests/ChunkComponentTests.cs @@ -91,7 +91,7 @@ public void RemoveChunkComponent() public void UpdateChunkComponent() { var arch0 = m_Manager.CreateArchetype(ComponentType.ChunkComponent(), typeof(EcsTestData2)); - ComponentGroup group0 = m_Manager.CreateComponentGroup(typeof(ChunkHeader), typeof(EcsTestData)); + EntityQuery group0 = m_Manager.CreateEntityQuery(typeof(ChunkHeader), typeof(EcsTestData)); var entity0 = m_Manager.CreateEntity(arch0); var chunk0 = m_Manager.GetChunk(entity0); @@ -136,7 +136,7 @@ public void ProcessMetaChunkComponent() m_Manager.SetComponentData(entity0, new BoundsComponent{boundsMin = new float3(-10,-10,-10), boundsMax = new float3(0,0,0)}); var entity1 = m_Manager.CreateEntity(typeof(BoundsComponent), ComponentType.ChunkComponent()); m_Manager.SetComponentData(entity1, new BoundsComponent{boundsMin = new float3(0,0,0), boundsMax = new float3(10,10,10)}); - var metaGroup = m_Manager.CreateComponentGroup(typeof(ChunkBoundsComponent), typeof(ChunkHeader)); + var metaGroup = m_Manager.CreateEntityQuery(typeof(ChunkBoundsComponent), typeof(ChunkHeader)); var metaBoundsCount = metaGroup.CalculateLength(); var metaChunkHeaders = metaGroup.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(1, metaBoundsCount); @@ -166,10 +166,9 @@ public void ProcessMetaChunkComponent() #if !UNITY_ZEROPLAYER [DisableAutoCreation] [UpdateInGroup(typeof(PresentationSystemGroup))] - [StandaloneFixme] private class ChunkBoundsUpdateSystem : JobComponentSystem { - struct UpdateChunkBoundsJob : IJobProcessComponentData + struct UpdateChunkBoundsJob : IJobForEach { [ReadOnly] public ArchetypeChunkComponentType chunkComponentType; public void Execute(ref ChunkBoundsComponent chunkBounds, [ReadOnly] ref ChunkHeader chunkHeader) @@ -194,10 +193,9 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) } [Test] - [StandaloneFixme] public void SystemProcessMetaChunkComponent() { - var chunkBoundsUpdateSystem = World.GetOrCreateManager (); + var chunkBoundsUpdateSystem = World.GetOrCreateSystem (); var entity0 = m_Manager.CreateEntity(typeof(BoundsComponent), ComponentType.ChunkComponent()); m_Manager.SetComponentData(entity0, new BoundsComponent{boundsMin = new float3(-10,-10,-10), boundsMax = new float3(0,0,0)}); @@ -219,8 +217,8 @@ public void ChunkHeaderMustBeQueriedExplicitly() var arch0 = m_Manager.CreateArchetype(ComponentType.ChunkComponent(), typeof(EcsTestData2)); var entity0 = m_Manager.CreateEntity(arch0); - ComponentGroup group0 = m_Manager.CreateComponentGroup(typeof(ChunkHeader), typeof(EcsTestData)); - ComponentGroup group1 = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + EntityQuery group0 = m_Manager.CreateEntityQuery(typeof(ChunkHeader), typeof(EcsTestData)); + EntityQuery group1 = m_Manager.CreateEntityQuery(typeof(EcsTestData)); Assert.AreEqual(1, group0.CalculateLength()); Assert.AreEqual(0, group1.CalculateLength()); diff --git a/Unity.Entities.Tests/ComponentGroupArrayTests.cs b/Unity.Entities.Tests/ComponentGroupArrayTests.cs deleted file mode 100644 index 2caa057a..00000000 --- a/Unity.Entities.Tests/ComponentGroupArrayTests.cs +++ /dev/null @@ -1,130 +0,0 @@ -#if !UNITY_ZEROPLAYER -using NUnit.Framework; -using Unity.Jobs; -using Unity.Collections; - -#pragma warning disable 618 - -namespace Unity.Entities.Tests -{ - class ComponentGroupArrayTests : ECSTestsFixture - { - public ComponentGroupArrayTests() - { - Assert.IsTrue(Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled, "JobDebugger must be enabled for these tests"); - } - - struct TestCopy1To2Job : IJob - { - public ComponentGroupArray entities; - unsafe public void Execute() - { - foreach (var e in entities) - e.testData2->value0 = e.testData->value; - } - } - - struct TestReadOnlyJob : IJob - { - public ComponentGroupArray entities; - public void Execute() - { - foreach (var e in entities) - ; - } - } - - - //@TODO: Test for Entity setup with same component twice... - //@TODO: Test for subtractive components - //@TODO: Test for process ComponentGroupArray in job - - unsafe struct TestEntity - { -#pragma warning disable 649 - [ReadOnly] - - public EcsTestData* testData; - - public EcsTestData2* testData2; - } - - unsafe struct TestEntityReadOnly - { - [ReadOnly] - public EcsTestData* testData; - [ReadOnly] - public EcsTestData2* testData2; - } -#pragma warning restore 649 - - [Test] - [StandaloneFixme] - public void ComponentAccessAfterScheduledJobThrowsEntityArray() - { - m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - - var job = new TestCopy1To2Job(); - job.entities = EmptySystem.GetEntities(); - - var fence = job.Schedule(); - - var entityArray = EmptySystem.GetEntities(); - Assert.Throws(() => { var temp = entityArray[0]; }); - - fence.Complete(); - } - - [Test] - [StandaloneFixme] - public void ComponentGroupArrayJobScheduleDetectsWriteDependency() - { - var entity = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - m_Manager.SetComponentData(entity, new EcsTestData(42)); - - var job = new TestCopy1To2Job(); - job.entities = EmptySystem.GetEntities(); - - var fence = job.Schedule(); - Assert.Throws(() => { job.Schedule(); }); - - fence.Complete(); - } - - [Test] - [StandaloneFixme] - public void ComponentGroupArrayJobScheduleReadOnlyParallelIsAllowed() - { - var entity = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - m_Manager.SetComponentData(entity, new EcsTestData(42)); - - var job = new TestReadOnlyJob(); - job.entities = EmptySystem.GetEntities(); - - var fence = job.Schedule(); - var fence2 = job.Schedule(); - - JobHandle.CompleteAll(ref fence, ref fence2); - } - - unsafe struct TestEntitySub2 - { -#pragma warning disable 649 - public EcsTestData* testData; - public ExcludeComponent testData2; -#pragma warning restore 649 - } - - [Test] - [StandaloneFixme] - public void ComponentGroupArrayExclude() - { - m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - m_Manager.CreateEntity(typeof(EcsTestData)); - - var entities = EmptySystem.GetEntities(); - Assert.AreEqual(1, entities.Length); - } - } -} -#endif diff --git a/Unity.Entities.Tests/ComponentGroupArrayTests.cs.meta b/Unity.Entities.Tests/ComponentGroupArrayTests.cs.meta deleted file mode 100644 index 8e6b5fce..00000000 --- a/Unity.Entities.Tests/ComponentGroupArrayTests.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 41659abe70864cfdbd0d142215cf0cd9 -timeCreated: 1512497553 \ No newline at end of file diff --git a/Unity.Entities.Tests/ComponentGroupDelta.cs b/Unity.Entities.Tests/ComponentGroupDelta.cs index 2d2249f4..ba163e2b 100644 --- a/Unity.Entities.Tests/ComponentGroupDelta.cs +++ b/Unity.Entities.Tests/ComponentGroupDelta.cs @@ -4,8 +4,6 @@ using Unity.Collections; using Unity.Jobs; -#pragma warning disable 618 - namespace Unity.Entities.Tests { [TestFixture] @@ -28,14 +26,15 @@ public class DeltaCheckSystem : ComponentSystem protected override void OnUpdate() { - var group = GetComponentGroup(typeof(EcsTestData)); + var group = GetEntityQuery(typeof(EcsTestData)); group.SetFilterChanged(typeof(EcsTestData)); - var actualEntityArray = group.GetEntityArray().ToArray(); + var actualEntityArray = group.ToEntityArray(Allocator.TempJob); var systemVersion = GlobalSystemVersion; var lastSystemVersion = LastSystemVersion; CollectionAssert.AreEqual(Expected, actualEntityArray); + actualEntityArray.Dispose(); } public void UpdateExpectedResults(Entity[] expected) @@ -47,11 +46,10 @@ public void UpdateExpectedResults(Entity[] expected) [Test] - [StandaloneFixme] public void CreateEntityTriggersChange() { Entity[] entity = new Entity[] { m_Manager.CreateEntity(typeof(EcsTestData)) }; - var deltaCheckSystem = World.CreateManager(); + var deltaCheckSystem = World.CreateSystem(); deltaCheckSystem.UpdateExpectedResults(entity); } @@ -59,8 +57,6 @@ public enum ChangeMode { SetComponentData, SetComponentDataFromEntity, - ComponentDataArray, - ComponentGroupArray } #pragma warning disable 649 @@ -80,15 +76,10 @@ unsafe struct GroupRO unsafe void SetValue(int index, int value, ChangeMode mode) { EmptySystem.Update(); - var entityArray = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetEntityArray(); + var entityArray = EmptySystem.GetEntityQuery(typeof(EcsTestData)).ToEntityArray(Allocator.TempJob); var entity = entityArray[index]; - if (mode == ChangeMode.ComponentDataArray) - { - var array = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetComponentDataArray(); - array[index] = new EcsTestData(value); - } - else if (mode == ChangeMode.SetComponentData) + if (mode == ChangeMode.SetComponentData) { m_Manager.SetComponentData(entity, new EcsTestData(value)); } @@ -98,27 +89,17 @@ unsafe void SetValue(int index, int value, ChangeMode mode) var array = EmptySystem.GetComponentDataFromEntity(false); array[entity] = new EcsTestData(value); } - else if (mode == ChangeMode.ComponentGroupArray) - { - *(EmptySystem.GetEntities()[index].Data) = new EcsTestData(value); - } + + entityArray.Dispose(); } // Running GetValue should not trigger any changes to chunk version. void GetValue(ChangeMode mode) { EmptySystem.Update(); - var entityArray = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetEntityArray(); + var entityArray = EmptySystem.GetEntityQuery(typeof(EcsTestData)).ToEntityArray(Allocator.TempJob); - if (mode == ChangeMode.ComponentDataArray) - { - var array = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetComponentDataArray(); - for (int i = 0; i != array.Length; i++) - { - var val = array[i]; - } - } - else if (mode == ChangeMode.SetComponentData) + if (mode == ChangeMode.SetComponentData) { for(int i = 0;i != entityArray.Length;i++) m_Manager.GetComponentData(entityArray[i]); @@ -128,22 +109,17 @@ void GetValue(ChangeMode mode) for(int i = 0;i != entityArray.Length;i++) m_Manager.GetComponentData(entityArray[i]); } - else if (mode == ChangeMode.ComponentGroupArray) - { - foreach (var e in EmptySystem.GetEntities()) - ; - } + entityArray.Dispose(); } [Test] - [StandaloneFixme] public void ChangeEntity([Values]ChangeMode mode) { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var deltaCheckSystem0 = World.CreateManager(); - var deltaCheckSystem1 = World.CreateManager(); + var deltaCheckSystem0 = World.CreateSystem(); + var deltaCheckSystem1 = World.CreateSystem(); // Chunk versions are considered changed upon creation and until after they're first updated. deltaCheckSystem0.UpdateExpectedResults(new Entity[] { entity0, entity1 }); @@ -172,12 +148,11 @@ public void ChangeEntity([Values]ChangeMode mode) } [Test] - [StandaloneFixme] public void GetEntityDataDoesNotChange([Values]ChangeMode mode) { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var deltaCheckSystem = World.CreateManager(); + var deltaCheckSystem = World.CreateSystem(); // First update of chunks after creation. SetValue(0, 2, mode); @@ -185,20 +160,19 @@ public void GetEntityDataDoesNotChange([Values]ChangeMode mode) deltaCheckSystem.UpdateExpectedResults(new Entity[] { entity0, entity1 }); deltaCheckSystem.UpdateExpectedResults(nothing); - // Now ensure that GetValue does not trigger a change on the ComponentGroup. + // Now ensure that GetValue does not trigger a change on the EntityQuery. GetValue(mode); deltaCheckSystem.UpdateExpectedResults(nothing); } [Test] - [StandaloneFixme] public void ChangeEntityWrap() { m_Manager.Debug.SetGlobalSystemVersion(uint.MaxValue-3); var entity = m_Manager.CreateEntity(typeof(EcsTestData)); - var deltaCheckSystem = World.CreateManager(); + var deltaCheckSystem = World.CreateSystem(); for (int i = 0; i != 7; i++) { @@ -210,7 +184,6 @@ public void ChangeEntityWrap() } [Test] - [StandaloneFixme] public void NoChangeEntityWrap() { m_Manager.Debug.SetGlobalSystemVersion(uint.MaxValue - 3); @@ -218,7 +191,7 @@ public void NoChangeEntityWrap() var entity = m_Manager.CreateEntity(typeof(EcsTestData)); SetValue(0, 2, ChangeMode.SetComponentData); - var deltaCheckSystem = World.CreateManager(); + var deltaCheckSystem = World.CreateSystem(); deltaCheckSystem.UpdateExpectedResults(new Entity[] { entity }); for (int i = 0; i != 7; i++) @@ -228,7 +201,7 @@ public void NoChangeEntityWrap() [DisableAutoCreation] public class DeltaProcessComponentSystem : JobComponentSystem { - struct DeltaJob : IJobProcessComponentData + struct DeltaJob : IJobForEach { public void Execute([ChangedFilter][ReadOnly]ref EcsTestData input, ref EcsTestData2 output) { @@ -244,13 +217,12 @@ protected override JobHandle OnUpdate(JobHandle deps) [Test] - [StandaloneFixme] public void IJobProcessComponentDeltaWorks() { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var deltaSystem = World.CreateManager(); + var deltaSystem = World.CreateSystem(); // First update of chunks after creation. SetValue(0, -100, ChangeMode.SetComponentData); @@ -276,7 +248,7 @@ public void IJobProcessComponentDeltaWorks() [DisableAutoCreation] public class DeltaProcessComponentSystemUsingRun : ComponentSystem { - struct DeltaJob : IJobProcessComponentData + struct DeltaJob : IJobForEach { public void Execute([ChangedFilter][ReadOnly]ref EcsTestData input, ref EcsTestData2 output) { @@ -291,13 +263,12 @@ protected override void OnUpdate() } [Test] - [StandaloneFixme] public void IJobProcessComponentDeltaWorksWhenUsingRun() { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var deltaSystem = World.CreateManager(); + var deltaSystem = World.CreateSystem(); // First update of chunks after creation. SetValue(0, -100, ChangeMode.SetComponentData); @@ -320,7 +291,6 @@ public void IJobProcessComponentDeltaWorksWhenUsingRun() #if false [Test] - [StandaloneFixme] public void IJobProcessComponentDeltaWorksWhenSetSharedComponent() { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3), typeof(EcsTestSharedComp)); @@ -341,10 +311,10 @@ public void IJobProcessComponentDeltaWorksWhenSetSharedComponent() [DisableAutoCreation] public class ModifyComponentSystem1Comp : JobComponentSystem { - public ComponentGroup m_Group; + public EntityQuery m_Group; public EcsTestSharedComp m_sharedComp; - struct DeltaJob : IJobProcessComponentData + struct DeltaJob : IJobForEach { public void Execute(ref EcsTestData data) { @@ -354,28 +324,28 @@ public void Execute(ref EcsTestData data) protected override JobHandle OnUpdate(JobHandle deps) { - m_Group = GetComponentGroup( + m_Group = GetEntityQuery( typeof(EcsTestData), ComponentType.ReadOnly(typeof(EcsTestSharedComp))); m_Group.SetFilter(m_sharedComp); DeltaJob job = new DeltaJob(); - return job.ScheduleGroup(m_Group, deps); + return job.Schedule(m_Group, deps); } } [DisableAutoCreation] public class DeltaModifyComponentSystem1Comp : JobComponentSystem { - struct DeltaJobFirstRunAfterCreation : IJobProcessComponentData + struct DeltaJobFirstRunAfterCreation : IJobForEach { public void Execute([ChangedFilter]ref EcsTestData output) { output.value = 0; } } - struct DeltaJob : IJobProcessComponentData + struct DeltaJob : IJobForEach { public void Execute([ChangedFilter]ref EcsTestData output) { @@ -394,15 +364,14 @@ protected override JobHandle OnUpdate(JobHandle deps) } [Test] - [StandaloneFixme] public void ChangedFilterJobAfterAnotherJob1Comp() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); var entities = new NativeArray(10000, Allocator.Persistent); m_Manager.CreateEntity(archetype, entities); - var modifSystem = World.CreateManager(); - var deltaSystem = World.CreateManager(); + var modifSystem = World.CreateSystem(); + var deltaSystem = World.CreateSystem(); // First update of chunks after creation. modifSystem.Update(); @@ -435,10 +404,10 @@ public void ChangedFilterJobAfterAnotherJob1Comp() [DisableAutoCreation] public class ModifyComponentSystem2Comp : JobComponentSystem { - public ComponentGroup m_Group; + public EntityQuery m_Group; public EcsTestSharedComp m_sharedComp; - struct DeltaJob : IJobProcessComponentData + struct DeltaJob : IJobForEach { public void Execute(ref EcsTestData data, ref EcsTestData2 data2) { @@ -448,7 +417,7 @@ public void Execute(ref EcsTestData data, ref EcsTestData2 data2) protected override JobHandle OnUpdate(JobHandle deps) { - m_Group = GetComponentGroup( + m_Group = GetEntityQuery( typeof(EcsTestData), typeof(EcsTestData2), ComponentType.ReadOnly(typeof(EcsTestSharedComp))); @@ -456,14 +425,14 @@ protected override JobHandle OnUpdate(JobHandle deps) m_Group.SetFilter(m_sharedComp); DeltaJob job = new DeltaJob(); - return job.ScheduleGroup(m_Group, deps); + return job.Schedule(m_Group, deps); } } [DisableAutoCreation] public class DeltaModifyComponentSystem2Comp : JobComponentSystem { - struct DeltaJobFirstRunAfterCreation : IJobProcessComponentData + struct DeltaJobFirstRunAfterCreation : IJobForEach { public void Execute(ref EcsTestData output, ref EcsTestData2 output2) { @@ -472,7 +441,7 @@ public void Execute(ref EcsTestData output, ref EcsTestData2 output2) } } - struct DeltaJobChanged0 : IJobProcessComponentData + struct DeltaJobChanged0 : IJobForEach { public void Execute([ChangedFilter]ref EcsTestData output, ref EcsTestData2 output2) { @@ -481,7 +450,7 @@ public void Execute([ChangedFilter]ref EcsTestData output, ref EcsTestData2 outp } } - struct DeltaJobChanged1 : IJobProcessComponentData + struct DeltaJobChanged1 : IJobForEach { public void Execute(ref EcsTestData output, [ChangedFilter]ref EcsTestData2 output2) { @@ -517,7 +486,6 @@ protected override JobHandle OnUpdate(JobHandle deps) } [Test] - [StandaloneFixme] public void ChangedFilterJobAfterAnotherJob2Comp([Values]DeltaModifyComponentSystem2Comp.Variant variant) { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestSharedComp)); @@ -525,8 +493,8 @@ public void ChangedFilterJobAfterAnotherJob2Comp([Values]DeltaModifyComponentSys m_Manager.CreateEntity(archetype, entities); // All entities have just been created, so they're all technically "changed". - var modifSystem = World.CreateManager(); - var deltaSystem = World.CreateManager(); + var modifSystem = World.CreateSystem(); + var deltaSystem = World.CreateSystem(); // First update of chunks after creation. modifSystem.Update(); @@ -562,10 +530,10 @@ public void ChangedFilterJobAfterAnotherJob2Comp([Values]DeltaModifyComponentSys [DisableAutoCreation] public class ModifyComponentSystem3Comp : JobComponentSystem { - public ComponentGroup m_Group; + public EntityQuery m_Group; public EcsTestSharedComp m_sharedComp; - struct DeltaJob : IJobProcessComponentData + struct DeltaJob : IJobForEach { public void Execute(ref EcsTestData data, ref EcsTestData2 data2, ref EcsTestData3 data3) { @@ -576,7 +544,7 @@ public void Execute(ref EcsTestData data, ref EcsTestData2 data2, ref EcsTestDat protected override JobHandle OnUpdate(JobHandle deps) { - m_Group = GetComponentGroup( + m_Group = GetEntityQuery( typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3), @@ -585,14 +553,14 @@ protected override JobHandle OnUpdate(JobHandle deps) m_Group.SetFilter(m_sharedComp); DeltaJob job = new DeltaJob(); - return job.ScheduleGroup(m_Group, deps); + return job.Schedule(m_Group, deps); } } [DisableAutoCreation] public class DeltaModifyComponentSystem3Comp : JobComponentSystem { - struct DeltaJobChanged0 : IJobProcessComponentData + struct DeltaJobChanged0 : IJobForEach { public void Execute([ChangedFilter]ref EcsTestData output, ref EcsTestData2 output2, ref EcsTestData3 output3) { @@ -602,7 +570,7 @@ public void Execute([ChangedFilter]ref EcsTestData output, ref EcsTestData2 outp } } - struct DeltaJobChanged1 : IJobProcessComponentData + struct DeltaJobChanged1 : IJobForEach { public void Execute(ref EcsTestData output, [ChangedFilter]ref EcsTestData2 output2, ref EcsTestData3 output3) { @@ -612,7 +580,7 @@ public void Execute(ref EcsTestData output, [ChangedFilter]ref EcsTestData2 outp } } - struct DeltaJobChanged2 : IJobProcessComponentData + struct DeltaJobChanged2 : IJobForEach { public void Execute(ref EcsTestData output, ref EcsTestData2 output2, [ChangedFilter]ref EcsTestData3 output3) { @@ -653,8 +621,8 @@ public void ChangedFilterJobAfterAnotherJob3Comp([Values]DeltaModifyComponentSys var entities = new NativeArray(10000, Allocator.Persistent); m_Manager.CreateEntity(archetype, entities); - var modifSystem = World.CreateManager(); - var deltaSystem = World.CreateManager(); + var modifSystem = World.CreateSystem(); + var deltaSystem = World.CreateSystem(); deltaSystem.variant = variant; @@ -687,7 +655,7 @@ public void ChangedFilterJobAfterAnotherJob3Comp([Values]DeltaModifyComponentSys [DisableAutoCreation] class ChangeFilter1TestSystem : JobComponentSystem { - struct ChangedFilterJob : IJobProcessComponentData + struct ChangedFilterJob : IJobForEach { public void Execute(ref EcsTestData output, [ChangedFilter]ref EcsTestData2 output2) { @@ -706,7 +674,7 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) public void ChangeFilterWorksWithOneTypes() { var e = m_Manager.CreateEntity(); - var system = World.GetOrCreateManager(); + var system = World.GetOrCreateSystem(); m_Manager.AddComponentData(e, new EcsTestData(0)); m_Manager.AddComponentData(e, new EcsTestData2(1)); @@ -733,7 +701,7 @@ public void ChangeFilterWorksWithOneTypes() [DisableAutoCreation] class ChangeFilter2TestSystem : JobComponentSystem { - struct ChangedFilterJob : IJobProcessComponentData + struct ChangedFilterJob : IJobForEach { public void Execute(ref EcsTestData output, [ChangedFilter]ref EcsTestData2 output2, [ChangedFilter]ref EcsTestData3 output3) { @@ -752,7 +720,7 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) public void ChangeFilterWorksWithTwoTypes() { var e = m_Manager.CreateEntity(); - var system = World.GetOrCreateManager(); + var system = World.GetOrCreateSystem(); m_Manager.AddComponentData(e, new EcsTestData(0)); m_Manager.AddComponentData(e, new EcsTestData2(1)); m_Manager.AddComponentData(e, new EcsTestData3(2)); diff --git a/Unity.Entities.Tests/ComponentGroupTests.cs b/Unity.Entities.Tests/ComponentGroupTests.cs index fde05527..1a3242a4 100644 --- a/Unity.Entities.Tests/ComponentGroupTests.cs +++ b/Unity.Entities.Tests/ComponentGroupTests.cs @@ -14,7 +14,7 @@ ArchetypeChunk[] CreateEntitiesAndReturnChunks(EntityArchetype archetype, int en { var entities = new NativeArray(entityCount, Allocator.Temp); m_Manager.CreateEntity(archetype, entities); -#if UNITY_CSHARP_TINY +#if NET_DOTS var managedEntities = new Entity[entities.Length]; for (int i = 0; i < entities.Length; i++) { @@ -45,8 +45,8 @@ public void CreateArchetypeChunkArray() var allCreatedChunks = createdChunks1.Concat(createdChunks2).Concat(createdChunks12); - var group1 = m_Manager.CreateComponentGroup(typeof(EcsTestData)); - var group12 = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2)); + var group1 = m_Manager.CreateEntityQuery(typeof(EcsTestData)); + var group12 = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2)); var queriedChunks1 = group1.CreateArchetypeChunkArray(Allocator.TempJob); var queriedChunks12 = group12.CreateArchetypeChunkArray(Allocator.TempJob); @@ -67,7 +67,6 @@ void SetShared(Entity e, int i) } [Test] - [StandaloneFixme] // ISharedComponentData public void CreateArchetypeChunkArray_FiltersSharedComponents() { var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); @@ -78,7 +77,7 @@ public void CreateArchetypeChunkArray_FiltersSharedComponents() var createdChunks3 = CreateEntitiesAndReturnChunks(archetype1, 5000, e => SetShared(e, 2)); var createdChunks4 = CreateEntitiesAndReturnChunks(archetype2, 5000, e => SetShared(e, 2)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestSharedComp)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestSharedComp)); group.SetFilter(new EcsTestSharedComp(1)); @@ -103,7 +102,6 @@ void SetShared(Entity e, int i, int j) } [Test] - [StandaloneFixme] // ISharedComponentData public void CreateArchetypeChunkArray_FiltersTwoSharedComponents() { var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp), typeof(EcsTestSharedComp2)); @@ -118,7 +116,7 @@ public void CreateArchetypeChunkArray_FiltersTwoSharedComponents() var createdChunks7 = CreateEntitiesAndReturnChunks(archetype1, 5000, e => SetShared(e, 2,8)); var createdChunks8 = CreateEntitiesAndReturnChunks(archetype2, 5000, e => SetShared(e, 2,8)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestSharedComp), typeof(EcsTestSharedComp2)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestSharedComp), typeof(EcsTestSharedComp2)); group.SetFilter(new EcsTestSharedComp(1), new EcsTestSharedComp2(7)); var queriedChunks1 = group.CreateArchetypeChunkArray(Allocator.TempJob); @@ -164,7 +162,7 @@ public void CreateArchetypeChunkArray_FiltersChangeVersions() m_ManagerDebug.SetGlobalSystemVersion(40); var createdChunks3 = CreateEntitiesAndReturnChunks(archetype3, 5000, e => SetData(e, 3)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); group.SetFilterChanged(typeof(EcsTestData)); @@ -213,7 +211,7 @@ public void CreateArchetypeChunkArray_FiltersTwoChangeVersions() m_ManagerDebug.SetGlobalSystemVersion(40); var createdChunks3 = CreateEntitiesAndReturnChunks(archetype3, 5000, e => SetData(e, 3, 6)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2)); group.SetFilterChanged(new ComponentType[]{typeof(EcsTestData), typeof(EcsTestData2)}); @@ -258,9 +256,9 @@ public void TestIssue1098() using ( - var group = m_Manager.CreateComponentGroup + var group = m_Manager.CreateEntityQuery ( - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EcsTestData)} } @@ -276,7 +274,7 @@ public void TestIssue1098() [AlwaysUpdateSystem] public class WriteEcsTestDataSystem : JobComponentSystem { - private struct WriteJob : IJobProcessComponentData + private struct WriteJob : IJobForEach { public void Execute(ref EcsTestData c0) {} } @@ -289,13 +287,13 @@ protected override JobHandle OnUpdate(JobHandle input) } [Test] - public void CreateArchetypeChunkArray_SyncsChangeFilterTypes() + public unsafe void CreateArchetypeChunkArray_SyncsChangeFilterTypes() { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); group.SetFilterChanged(typeof(EcsTestData)); - var ws1 = World.GetOrCreateManager(); + var ws1 = World.GetOrCreateSystem(); ws1.Update(); - var safetyHandle = m_Manager.ComponentJobSafetyManager.GetSafetyHandle(TypeManager.GetTypeIndex(), false); + var safetyHandle = m_Manager.ComponentJobSafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex(), false); Assert.Throws(() => AtomicSafetyHandle.CheckWriteAndThrow(safetyHandle)); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); @@ -306,13 +304,13 @@ public void CreateArchetypeChunkArray_SyncsChangeFilterTypes() } [Test] - public void CalculateLength_SyncsChangeFilterTypes() + public unsafe void CalculateLength_SyncsChangeFilterTypes() { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); group.SetFilterChanged(typeof(EcsTestData)); - var ws1 = World.GetOrCreateManager(); + var ws1 = World.GetOrCreateSystem(); ws1.Update(); - var safetyHandle = m_Manager.ComponentJobSafetyManager.GetSafetyHandle(TypeManager.GetTypeIndex(), false); + var safetyHandle = m_Manager.ComponentJobSafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex(), false); Assert.Throws(() => AtomicSafetyHandle.CheckWriteAndThrow(safetyHandle)); group.CalculateLength(); @@ -323,7 +321,6 @@ public void CalculateLength_SyncsChangeFilterTypes() #endif [Test] - [StandaloneFixme] // ISharedComponentData public void ToEntityArrayOnFilteredGroup() { // Note - test is setup so that each entity is in its own chunk, this checks that entity indices are correct @@ -335,7 +332,7 @@ public void ToEntityArrayOnFilteredGroup() m_Manager.SetSharedComponentData(b, new EcsTestSharedComp {value = 456}); m_Manager.SetSharedComponentData(c, new EcsTestSharedComp {value = 123}); - using (var group = m_Manager.CreateComponentGroup(typeof(EcsTestSharedComp))) + using (var group = m_Manager.CreateEntityQuery(typeof(EcsTestSharedComp))) { group.SetFilter(new EcsTestSharedComp {value = 123}); using (var entities = group.ToEntityArray(Allocator.TempJob)) @@ -344,7 +341,7 @@ public void ToEntityArrayOnFilteredGroup() } } - using (var group = m_Manager.CreateComponentGroup(typeof(EcsTestSharedComp))) + using (var group = m_Manager.CreateEntityQuery(typeof(EcsTestSharedComp))) { group.SetFilter(new EcsTestSharedComp {value = 456}); using (var entities = group.ToEntityArray(Allocator.TempJob)) diff --git a/Unity.Entities.Tests/ComponentOrderVersionTests.cs b/Unity.Entities.Tests/ComponentOrderVersionTests.cs index 1918ccda..4fce6690 100644 --- a/Unity.Entities.Tests/ComponentOrderVersionTests.cs +++ b/Unity.Entities.Tests/ComponentOrderVersionTests.cs @@ -32,10 +32,10 @@ void AddEvenOddTestData() } } - void ActionEvenOdd(Action even, Action odd) + void ActionEvenOdd(Action even, Action odd) { var uniqueTypes = new List(10); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); group.CompleteDependency(); m_Manager.GetAllUniqueSharedComponentData(uniqueTypes); @@ -61,7 +61,6 @@ void ActionEvenOdd(Action even, Action } [Test] - [StandaloneFixme] // ISharedComponentData public void SharedComponentNoChangeVersionUnchanged() { AddEvenOddTestData(); @@ -69,7 +68,7 @@ public void SharedComponentNoChangeVersionUnchanged() (version, group) => { Assert.AreEqual(version, 1); }); } - void TestSourceEvenValues(int version, ComponentGroup group) + void TestSourceEvenValues(int version, EntityQuery group) { var testData = group.ToComponentDataArray(Allocator.TempJob); @@ -83,7 +82,7 @@ void TestSourceEvenValues(int version, ComponentGroup group) testData.Dispose(); } - void TestSourceOddValues(int version, ComponentGroup group) + void TestSourceOddValues(int version, EntityQuery group) { var testData = group.ToComponentDataArray(Allocator.TempJob); @@ -98,14 +97,13 @@ void TestSourceOddValues(int version, ComponentGroup group) } [Test] - [StandaloneFixme] // ISharedComponentData public void SharedComponentNoChangeValuesUnchanged() { AddEvenOddTestData(); ActionEvenOdd(TestSourceEvenValues, TestSourceOddValues); } - void ChangeGroupOrder(int version, ComponentGroup group) + void ChangeGroupOrder(int version, EntityQuery group) { var entities = group.ToEntityArray(Allocator.TempJob); @@ -123,7 +121,6 @@ void ChangeGroupOrder(int version, ComponentGroup group) } [Test] - [StandaloneFixme] // ISharedComponentData public void SharedComponentChangeOddGroupOrderOnlyOddVersionChanged() { AddEvenOddTestData(); @@ -134,7 +131,6 @@ public void SharedComponentChangeOddGroupOrderOnlyOddVersionChanged() } [Test] - [StandaloneFixme] // ISharedComponentData public void SharedComponentChangeOddGroupOrderEvenValuesUnchanged() { AddEvenOddTestData(); @@ -143,7 +139,7 @@ public void SharedComponentChangeOddGroupOrderEvenValuesUnchanged() ActionEvenOdd(TestSourceEvenValues, (version, group) => { }); } - void DestroyAllButOneEntityInGroup(int version, ComponentGroup group) + void DestroyAllButOneEntityInGroup(int version, EntityQuery group) { var entities = group.ToEntityArray(Allocator.TempJob); @@ -157,7 +153,6 @@ void DestroyAllButOneEntityInGroup(int version, ComponentGroup group) } [Test] - [StandaloneFixme] // ISharedComponentData public void SharedComponentDestroyAllButOneEntityInOddGroupOnlyOddVersionChanged() { AddEvenOddTestData(); @@ -168,7 +163,6 @@ public void SharedComponentDestroyAllButOneEntityInOddGroupOnlyOddVersionChanged } [Test] - [StandaloneFixme] // ISharedComponentData public void SharedComponentDestroyAllButOneEntityInOddGroupEvenValuesUnchanged() { AddEvenOddTestData(); @@ -228,7 +222,6 @@ public void ChangedOnlyAffectedArchetype() } [Test] - [StandaloneFixme] // ISharedComponentData public void SetSharedComponent() { var entity = m_Manager.CreateEntity(typeof(SharedData1), typeof(SharedData2)); @@ -241,7 +234,6 @@ public void SetSharedComponent() } [Test] - [StandaloneFixme] // ISharedComponentData public void DestroySharedComponentEntity() { var sharedData = new SharedData1(1); @@ -258,7 +250,6 @@ public void DestroySharedComponentEntity() } [Test] - [StandaloneFixme] // ISharedComponentData public void DestroySharedComponentDataSetsOrderVersionToZero() { var sharedData = new SharedData1(1); diff --git a/Unity.Entities.Tests/ComponentSystemGroupTests.cs b/Unity.Entities.Tests/ComponentSystemGroupTests.cs index b34b2a1f..cf931688 100644 --- a/Unity.Entities.Tests/ComponentSystemGroupTests.cs +++ b/Unity.Entities.Tests/ComponentSystemGroupTests.cs @@ -18,7 +18,7 @@ class TestGroup : ComponentSystemGroup } [DisableAutoCreation] -#if UNITY_CSHARP_TINY +#if NET_DOTS private class TestSystemBase :ComponentSystem { protected override void OnUpdate() => throw new System.NotImplementedException(); @@ -46,8 +46,8 @@ class TestSystem : TestSystemBase [Test] public void SortOneChildSystem() { - var parent = World.CreateManager(); - var child = World.CreateManager(); + var parent = World.CreateSystem(); + var child = World.CreateSystem(); parent.AddSystemToUpdateList(child); parent.SortSystemUpdateList(); CollectionAssert.AreEqual(new[] {child}, parent.Systems); @@ -66,9 +66,9 @@ class Sibling2System : TestSystemBase [Test] public void SortTwoChildSystems_CorrectOrder() { - var parent = World.CreateManager(); - var child1 = World.CreateManager(); - var child2 = World.CreateManager(); + var parent = World.CreateSystem(); + var child1 = World.CreateSystem(); + var child2 = World.CreateSystem(); parent.AddSystemToUpdateList(child1); parent.AddSystemToUpdateList(child2); parent.SortSystemUpdateList(); @@ -114,18 +114,18 @@ class Circle6System : TestSystemBase } [Test] -#if UNITY_CSHARP_TINY +#if NET_DOTS [Ignore("Tiny pre-compiles systems. Many tests will fail if they exist, not just this one.")] #endif public void DetectCircularDependency_Throws() { - var parent = World.CreateManager(); - var child1 = World.CreateManager(); - var child2 = World.CreateManager(); - var child3 = World.CreateManager(); - var child4 = World.CreateManager(); - var child5 = World.CreateManager(); - var child6 = World.CreateManager(); + var parent = World.CreateSystem(); + var child1 = World.CreateSystem(); + var child2 = World.CreateSystem(); + var child3 = World.CreateSystem(); + var child4 = World.CreateSystem(); + var child5 = World.CreateSystem(); + var child6 = World.CreateSystem(); parent.AddSystemToUpdateList(child3); parent.AddSystemToUpdateList(child6); parent.AddSystemToUpdateList(child2); @@ -175,11 +175,11 @@ class Unconstrained4System : TestSystemBase [Test] public void SortUnconstrainedSystems_IsDeterministic() { - var parent = World.CreateManager(); - var child1 = World.CreateManager(); - var child2 = World.CreateManager(); - var child3 = World.CreateManager(); - var child4 = World.CreateManager(); + var parent = World.CreateSystem(); + var child1 = World.CreateSystem(); + var child2 = World.CreateSystem(); + var child3 = World.CreateSystem(); + var child4 = World.CreateSystem(); parent.AddSystemToUpdateList(child2); parent.AddSystemToUpdateList(child4); parent.AddSystemToUpdateList(child3); @@ -219,14 +219,14 @@ protected override void OnUpdate() } } -#if !UNITY_CSHARP_TINY // Tiny precompiles systems, and lacks a Regex overload for LogAssert.Expect() +#if !NET_DOTS // Tiny precompiles systems, and lacks a Regex overload for LogAssert.Expect() [Test] public void SystemInGroupThrows_LaterSystemsRun() { - var parent = World.CreateManager(); - var child1 = World.CreateManager(); - var child2 = World.CreateManager(); - var child3 = World.CreateManager(); + var parent = World.CreateSystem(); + var child1 = World.CreateSystem(); + var child2 = World.CreateSystem(); + var child3 = World.CreateSystem(); parent.AddSystemToUpdateList(child1); parent.AddSystemToUpdateList(child2); parent.AddSystemToUpdateList(child3); diff --git a/Unity.Entities.Tests/ComponentSystemInjectionTests.cs b/Unity.Entities.Tests/ComponentSystemInjectionTests.cs deleted file mode 100644 index fe4df969..00000000 --- a/Unity.Entities.Tests/ComponentSystemInjectionTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#if !UNITY_ZEROPLAYER -using NUnit.Framework; - -// Injection is deprecated -#pragma warning disable 618 - -namespace Unity.Entities.Tests -{ - class ComponentSystemInjectionTests : ECSTestsFixture - { - [DisableAutoCreation] - class TestSystem : ComponentSystem - { - protected override void OnUpdate() - { - } - } - - [DisableAutoCreation] - class AttributeInjectionSystem : ComponentSystem - { - [Inject] -#pragma warning disable 649 - public TestSystem test; -#pragma warning restore 649 - - protected override void OnUpdate() - { - } - } - - [DisableAutoCreation] - class ConstructorInjectionSystem : ComponentSystem - { - public string test; - - public ConstructorInjectionSystem(string value) - { - this.test = value; - } - - protected override void OnUpdate() - { - } - } - - [Test] - public void ConstructorInjection() - { - var hello = "HelloWorld"; - var system = World.CreateManager(hello); - Assert.AreEqual(hello, system.test); - } - - [Test] - public void AttributeInjectionCreates() - { - var system = World.CreateManager(); - Assert.AreEqual(World.GetOrCreateManager(), system.test); - } - - [Test] - public void AttributeInjectionAlreadyCreated() - { - var test = World.CreateManager(); - var system = World.CreateManager(); - Assert.AreEqual(test, system.test); - } - } -} -#endif \ No newline at end of file diff --git a/Unity.Entities.Tests/ComponentSystemInjectionTests.cs.meta b/Unity.Entities.Tests/ComponentSystemInjectionTests.cs.meta deleted file mode 100644 index ab977e91..00000000 --- a/Unity.Entities.Tests/ComponentSystemInjectionTests.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 83110af8b51c435eb9e2d0a50d4ae5de -timeCreated: 1512086766 \ No newline at end of file diff --git a/Unity.Entities.Tests/ComponentSystemStartStopRunningTests.cs b/Unity.Entities.Tests/ComponentSystemStartStopRunningTests.cs index 53239666..5f329284 100644 --- a/Unity.Entities.Tests/ComponentSystemStartStopRunningTests.cs +++ b/Unity.Entities.Tests/ComponentSystemStartStopRunningTests.cs @@ -10,7 +10,7 @@ class ComponentSystemStartStopRunningTests : ECSTestsFixture [DisableAutoCreation] class TestSystem : ComponentSystem { - public ComponentGroup m_TestGroup; + public EntityQuery m_TestGroup; public const string OnStartRunningString = nameof(TestSystem) + ".OnStartRunning()"; @@ -45,9 +45,9 @@ protected override void OnStopRunning() base.OnStopRunning(); } - protected override void OnCreateManager() + protected override void OnCreate() { - m_TestGroup = GetComponentGroup(ComponentType.ReadWrite()); + m_TestGroup = GetEntityQuery(ComponentType.ReadWrite()); } } @@ -71,7 +71,7 @@ public void ShouldRunSystem(bool shouldRun) public override void Setup() { base.Setup(); - system = World.Active.GetOrCreateManager(); + system = World.Active.GetOrCreateSystem(); ShouldRunSystem(true); } @@ -84,7 +84,7 @@ public override void TearDown() } if (system != null) { - World.Active.DestroyManager(system); + World.Active.DestroySystem(system); system = null; } @@ -282,7 +282,7 @@ public void OnStopRunning_WhenDestroyingActiveManager_CalledOnce() system.Update(); LogAssert.Expect(LogType.Log, TestSystem.OnStopRunningString); - World.Active.DestroyManager(system); + World.Active.DestroySystem(system); system = null; LogAssert.NoUnexpectedReceived(); @@ -294,7 +294,7 @@ public void OnStopRunning_WhenDestroyingInactiveManager_NotCalled() system.Enabled = false; system.Update(); - World.Active.DestroyManager(system); + World.Active.DestroySystem(system); system = null; LogAssert.NoUnexpectedReceived(); diff --git a/Unity.Entities.Tests/ComponentSystemTests.cs b/Unity.Entities.Tests/ComponentSystemTests.cs index cdd80ec4..6670c9af 100644 --- a/Unity.Entities.Tests/ComponentSystemTests.cs +++ b/Unity.Entities.Tests/ComponentSystemTests.cs @@ -17,12 +17,12 @@ protected override void OnUpdate() { } - protected override void OnCreateManager() + protected override void OnCreate() { Created = true; } - protected override void OnDestroyManager() + protected override void OnDestroy() { Created = false; } @@ -39,7 +39,7 @@ protected override void OnUpdate() [DisableAutoCreation] class ThrowExceptionSystem : TestSystem { - protected override void OnCreateManager() + protected override void OnCreate() { throw new System.Exception(); } @@ -65,7 +65,7 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) return new Job(){ test = test }.Schedule(inputDeps); } - protected override void OnDestroyManager() + protected override void OnDestroy() { // We expect this to not throw an exception since the jobs scheduled // by this system should be synced before the system is destroyed @@ -76,38 +76,38 @@ protected override void OnDestroyManager() [Test] public void Create() { - var system = World.CreateManager(); - Assert.AreEqual(system, World.GetExistingManager()); + var system = World.CreateSystem(); + Assert.AreEqual(system, World.GetExistingSystem()); Assert.IsTrue(system.Created); } [Test] public void CreateAndDestroy() { - var system = World.CreateManager(); - World.DestroyManager(system); - Assert.AreEqual(null, World.GetExistingManager()); + var system = World.CreateSystem(); + World.DestroySystem(system); + Assert.AreEqual(null, World.GetExistingSystem()); Assert.IsFalse(system.Created); } [Test] - public void GetOrCreateManagerReturnsSameSystem() + public void GetOrCreateSystemReturnsSameSystem() { - var system = World.GetOrCreateManager(); - Assert.AreEqual(system, World.GetOrCreateManager()); + var system = World.GetOrCreateSystem(); + Assert.AreEqual(system, World.GetOrCreateSystem()); } [Test] public void InheritedSystem() { - var system = World.CreateManager(); - Assert.AreEqual(system, World.GetExistingManager()); - Assert.AreEqual(system, World.GetExistingManager()); + var system = World.CreateSystem(); + Assert.AreEqual(system, World.GetExistingSystem()); + Assert.AreEqual(system, World.GetExistingSystem()); - World.DestroyManager(system); + World.DestroySystem(system); - Assert.AreEqual(null, World.GetExistingManager()); - Assert.AreEqual(null, World.GetExistingManager()); + Assert.AreEqual(null, World.GetExistingSystem()); + Assert.AreEqual(null, World.GetExistingSystem()); Assert.IsFalse(system.Created); } @@ -116,142 +116,142 @@ public void InheritedSystem() [Test] public void CreateNonSystemThrows() { - Assert.Throws(() => { World.CreateManager(typeof(Entity)); }); + Assert.Throws(() => { World.CreateSystem(typeof(Entity)); }); } [Test] public void GetOrCreateNonSystemThrows() { - Assert.Throws(() => { World.GetOrCreateManager(typeof(Entity)); }); + Assert.Throws(() => { World.GetOrCreateSystem(typeof(Entity)); }); } #endif [Test] public void OnCreateThrowRemovesSystem() { - Assert.Throws(() => { World.CreateManager(); }); - Assert.AreEqual(null, World.GetExistingManager()); + Assert.Throws(() => { World.CreateSystem(); }); + Assert.AreEqual(null, World.GetExistingSystem()); } [Test] [StandaloneFixme] // IJob public void DestroySystemWhileJobUsingArrayIsRunningWorks() { - var system = World.CreateManager(); + var system = World.CreateSystem(); system.Update(); - World.DestroyManager(system); + World.DestroySystem(system); } [Test] public void DisposeSystemComponentGroupThrows() { - var system = World.CreateManager(); - var group = system.GetComponentGroup(typeof(EcsTestData)); + var system = World.CreateSystem(); + var group = system.GetEntityQuery(typeof(EcsTestData)); Assert.Throws(() => group.Dispose()); } [Test] - public void DestroyManagerTwiceThrows() + public void DestroySystemTwiceThrows() { - var system = World.CreateManager(); - World.DestroyManager(system); - Assert.Throws(() => World.DestroyManager(system) ); + var system = World.CreateSystem(); + World.DestroySystem(system); + Assert.Throws(() => World.DestroySystem(system) ); } [Test] public void CreateTwoSystemsOfSameType() { - var systemA = World.CreateManager(); - var systemB = World.CreateManager(); - // CreateManager makes a new manager + var systemA = World.CreateSystem(); + var systemB = World.CreateSystem(); + // CreateSystem makes a new system Assert.AreNotEqual(systemA, systemB); // Return first system - Assert.AreEqual(systemA, World.GetOrCreateManager()); + Assert.AreEqual(systemA, World.GetOrCreateSystem()); } [Test] public void CreateTwoSystemsAfterDestroyReturnSecond() { - var systemA = World.CreateManager(); - var systemB = World.CreateManager(); - World.DestroyManager(systemA); + var systemA = World.CreateSystem(); + var systemB = World.CreateSystem(); + World.DestroySystem(systemA); - Assert.AreEqual(systemB, World.GetExistingManager());; + Assert.AreEqual(systemB, World.GetExistingSystem());; } [Test] public void CreateTwoSystemsAfterDestroyReturnFirst() { - var systemA = World.CreateManager(); - var systemB = World.CreateManager(); - World.DestroyManager(systemB); + var systemA = World.CreateSystem(); + var systemB = World.CreateSystem(); + World.DestroySystem(systemB); - Assert.AreEqual(systemA, World.GetExistingManager());; + Assert.AreEqual(systemA, World.GetExistingSystem());; } [Test] - public void GetComponentGroup() + public void GetEntityQuery() { ComponentType[] ro_rw = { ComponentType.ReadOnly(), typeof(EcsTestData2) }; ComponentType[] rw_rw = { typeof(EcsTestData), typeof(EcsTestData2) }; ComponentType[] rw = { typeof(EcsTestData) }; - var ro_rw0_system = EmptySystem.GetComponentGroup(ro_rw); - var rw_rw_system = EmptySystem.GetComponentGroup(rw_rw); - var rw_system = EmptySystem.GetComponentGroup(rw); + var ro_rw0_system = EmptySystem.GetEntityQuery(ro_rw); + var rw_rw_system = EmptySystem.GetEntityQuery(rw_rw); + var rw_system = EmptySystem.GetEntityQuery(rw); - Assert.AreEqual(ro_rw0_system, EmptySystem.GetComponentGroup(ro_rw)); - Assert.AreEqual(rw_rw_system, EmptySystem.GetComponentGroup(rw_rw)); - Assert.AreEqual(rw_system, EmptySystem.GetComponentGroup(rw)); + Assert.AreEqual(ro_rw0_system, EmptySystem.GetEntityQuery(ro_rw)); + Assert.AreEqual(rw_rw_system, EmptySystem.GetEntityQuery(rw_rw)); + Assert.AreEqual(rw_system, EmptySystem.GetEntityQuery(rw)); - Assert.AreEqual(3, EmptySystem.ComponentGroups.Length); + Assert.AreEqual(3, EmptySystem.EntityQueries.Length); } [Test] public void GetComponentGroupArchetypeQuery() { var query1 = new ComponentType[] { typeof(EcsTestData) }; - var query2 = new EntityArchetypeQuery { All = new ComponentType[] {typeof(EcsTestData)} }; - var query3 = new EntityArchetypeQuery { All = new ComponentType[] {typeof(EcsTestData), typeof(EcsTestData2)} }; + var query2 = new EntityQueryDesc { All = new ComponentType[] {typeof(EcsTestData)} }; + var query3 = new EntityQueryDesc { All = new ComponentType[] {typeof(EcsTestData), typeof(EcsTestData2)} }; - var group1 = EmptySystem.GetComponentGroup(query1); - var group2 = EmptySystem.GetComponentGroup(query2); - var group3 = EmptySystem.GetComponentGroup(query3); + var group1 = EmptySystem.GetEntityQuery(query1); + var group2 = EmptySystem.GetEntityQuery(query2); + var group3 = EmptySystem.GetEntityQuery(query3); - Assert.AreEqual(group1, EmptySystem.GetComponentGroup(query1)); - Assert.AreEqual(group2, EmptySystem.GetComponentGroup(query2)); - Assert.AreEqual(group3, EmptySystem.GetComponentGroup(query3)); + Assert.AreEqual(group1, EmptySystem.GetEntityQuery(query1)); + Assert.AreEqual(group2, EmptySystem.GetEntityQuery(query2)); + Assert.AreEqual(group3, EmptySystem.GetEntityQuery(query3)); - Assert.AreEqual(2, EmptySystem.ComponentGroups.Length); + Assert.AreEqual(2, EmptySystem.EntityQueries.Length); } [Test] public void GetComponentGroupComponentTypeArchetypeQueryEquality() { var query1 = new ComponentType[] { typeof(EcsTestData) }; - var query2 = new EntityArchetypeQuery { All = new ComponentType[] {typeof(EcsTestData)} }; - var query3 = new EntityArchetypeQuery { All = new [] {ComponentType.ReadWrite()} }; + var query2 = new EntityQueryDesc { All = new ComponentType[] {typeof(EcsTestData)} }; + var query3 = new EntityQueryDesc { All = new [] {ComponentType.ReadWrite()} }; - var group1 = EmptySystem.GetComponentGroup(query1); - var group2 = EmptySystem.GetComponentGroup(query2); - var group3 = EmptySystem.GetComponentGroup(query3); + var group1 = EmptySystem.GetEntityQuery(query1); + var group2 = EmptySystem.GetEntityQuery(query2); + var group3 = EmptySystem.GetEntityQuery(query3); Assert.AreEqual(group1, group2); Assert.AreEqual(group2, group3); - Assert.AreEqual(1, EmptySystem.ComponentGroups.Length); + Assert.AreEqual(1, EmptySystem.EntityQueries.Length); } [Test] public void GetComponentGroupRespectsRWAccessInequality() { - var query1 = new EntityArchetypeQuery { All = new [] {ComponentType.ReadOnly(), ComponentType.ReadWrite()} }; - var query2 = new EntityArchetypeQuery { All = new [] {ComponentType.ReadOnly(), ComponentType.ReadOnly()} }; + var query1 = new EntityQueryDesc { All = new [] {ComponentType.ReadOnly(), ComponentType.ReadWrite()} }; + var query2 = new EntityQueryDesc { All = new [] {ComponentType.ReadOnly(), ComponentType.ReadOnly()} }; - var group1 = EmptySystem.GetComponentGroup(query1); - var group2 = EmptySystem.GetComponentGroup(query2); + var group1 = EmptySystem.GetEntityQuery(query1); + var group2 = EmptySystem.GetEntityQuery(query2); Assert.AreNotEqual(group1, group2); - Assert.AreEqual(2, EmptySystem.ComponentGroups.Length); + Assert.AreEqual(2, EmptySystem.EntityQueries.Length); } [Test] @@ -260,20 +260,20 @@ public void GetComponentGroupOrderIndependent() var query1 = new ComponentType[] { typeof(EcsTestData), typeof(EcsTestData2) }; var query2 = new ComponentType[] { typeof(EcsTestData2), typeof(EcsTestData) }; - var group1 = EmptySystem.GetComponentGroup(query1); - var group2 = EmptySystem.GetComponentGroup(query2); + var group1 = EmptySystem.GetEntityQuery(query1); + var group2 = EmptySystem.GetEntityQuery(query2); Assert.AreEqual(group1, group2); - Assert.AreEqual(1, EmptySystem.ComponentGroups.Length); + Assert.AreEqual(1, EmptySystem.EntityQueries.Length); - var query3 = new EntityArchetypeQuery { All = new ComponentType[] {typeof(EcsTestData2), typeof(EcsTestData3)} }; - var query4 = new EntityArchetypeQuery { All = new ComponentType[] {typeof(EcsTestData3), typeof(EcsTestData2)} }; + var query3 = new EntityQueryDesc { All = new ComponentType[] {typeof(EcsTestData2), typeof(EcsTestData3)} }; + var query4 = new EntityQueryDesc { All = new ComponentType[] {typeof(EcsTestData3), typeof(EcsTestData2)} }; - var group3 = EmptySystem.GetComponentGroup(query3); - var group4 = EmptySystem.GetComponentGroup(query4); + var group3 = EmptySystem.GetEntityQuery(query3); + var group4 = EmptySystem.GetEntityQuery(query4); Assert.AreEqual(group3, group4); - Assert.AreEqual(2, EmptySystem.ComponentGroups.Length); + Assert.AreEqual(2, EmptySystem.EntityQueries.Length); } //@TODO: Behaviour is a slightly dodgy... Should probably just ignore and return same as single typeof(EcsTestData) @@ -281,8 +281,8 @@ public void GetComponentGroupOrderIndependent() public void GetComponentGroupWithEntityThrows() { ComponentType[] e = { typeof(Entity), typeof(EcsTestData) }; - EmptySystem.GetComponentGroup(e); - Assert.Throws(() => EmptySystem.GetComponentGroup(e)); + EmptySystem.GetEntityQuery(e); + Assert.Throws(() => EmptySystem.GetEntityQuery(e)); } [Test] @@ -290,22 +290,22 @@ public void GetComponentGroupWithDuplicates() { // Currently duplicates will create two seperate groups doing the same thing... ComponentType[] dup_1 = { typeof(EcsTestData2) }; - ComponentType[] dup_2 = { typeof(EcsTestData2), typeof(EcsTestData2) }; + ComponentType[] dup_2 = { typeof(EcsTestData2), typeof(EcsTestData3) }; - var dup1_system = EmptySystem.GetComponentGroup(dup_1); - var dup2_system = EmptySystem.GetComponentGroup(dup_2); + var dup1_system = EmptySystem.GetEntityQuery(dup_1); + var dup2_system = EmptySystem.GetEntityQuery(dup_2); - Assert.AreEqual(dup1_system, EmptySystem.GetComponentGroup(dup_1)); - Assert.AreEqual(dup2_system, EmptySystem.GetComponentGroup(dup_2)); + Assert.AreEqual(dup1_system, EmptySystem.GetEntityQuery(dup_1)); + Assert.AreEqual(dup2_system, EmptySystem.GetEntityQuery(dup_2)); - Assert.AreEqual(2, EmptySystem.ComponentGroups.Length); + Assert.AreEqual(2, EmptySystem.EntityQueries.Length); } [Test] public void UpdateDestroyedSystemThrows() { var system = EmptySystem; - World.DestroyManager(system); + World.DestroySystem(system); Assert.Throws(system.Update); } } diff --git a/Unity.Entities.Tests/CreateAndDestroyTests.cs b/Unity.Entities.Tests/CreateAndDestroyTests.cs index 426daf0d..1d0cb764 100644 --- a/Unity.Entities.Tests/CreateAndDestroyTests.cs +++ b/Unity.Entities.Tests/CreateAndDestroyTests.cs @@ -1,3 +1,4 @@ +using System; using NUnit.Framework; using Unity.Collections; @@ -215,7 +216,7 @@ public void ReadOnlyAndNonReadOnlyArchetypeAreEqual() [Test] public void ExcludeArchetypeReactToAddRemoveComponent() { - var subtractiveArch = m_Manager.CreateComponentGroup(ComponentType.Exclude(typeof(EcsTestData)), typeof(EcsTestData2)); + var subtractiveArch = m_Manager.CreateEntityQuery(ComponentType.Exclude(typeof(EcsTestData)), typeof(EcsTestData2)); var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); @@ -345,7 +346,6 @@ public void AddComponentsWithTypeIndicesWorks() } [Test] - [StandaloneFixme] // ISharedComponentData public void AddComponentsWithSharedComponentsWorks() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); @@ -415,7 +415,6 @@ public EcsSharedStateForcedOrder(int value) } [Test] - [StandaloneFixme] // ISharedComponentData public void InstantiateWithSharedSystemStateComponent() { var srcEntity = m_Manager.CreateEntity(); @@ -443,5 +442,80 @@ public void InstantiateWithSharedSystemStateComponent() Assert.AreNotEqual(versionSharedBefore, versionSharedAfter); Assert.AreEqual(versionSystemBefore, versionSystemAfter); } + + [Test] + public void AddTagComponentTwiceByValue() + { + var entity = m_Manager.CreateEntity(); + + m_Manager.AddComponentData(entity, new EcsTestTag()); + m_Manager.AddComponentData(entity, new EcsTestTag()); + } + + [Test] + public void AddTagComponentTwiceByType() + { + var entity = m_Manager.CreateEntity(); + + m_Manager.AddComponent(entity, ComponentType.ReadWrite()); + m_Manager.AddComponent(entity, ComponentType.ReadWrite()); + } + + [Test] + public void AddTagComponentTwiceToGroup() + { + m_Manager.CreateEntity(); + + m_Manager.AddComponent(m_Manager.UniversalQuery, ComponentType.ReadWrite()); + Assert.Throws(() => m_Manager.AddComponent(m_Manager.UniversalQuery, ComponentType.ReadWrite())); + + // Failure because the component type is expected to be explicitly excluded from the group. + } + + [Test] + public void AddTagComponentTwiceByTypeArray() + { + var entity = m_Manager.CreateEntity(); + + m_Manager.AddComponents(entity, new ComponentTypes(ComponentType.ReadWrite())); + m_Manager.AddComponents(entity, new ComponentTypes(ComponentType.ReadWrite())); + + m_Manager.AddComponents(entity, new ComponentTypes(ComponentType.ReadWrite())); + Assert.Throws(() => m_Manager.AddComponents(entity, new ComponentTypes(ComponentType.ReadWrite()))); + } + + [Test] + public void AddChunkComponentTwice() + { + var entity = m_Manager.CreateEntity(); + + m_Manager.AddChunkComponentData(entity); + m_Manager.AddChunkComponentData(entity); + + m_Manager.AddChunkComponentData(entity); + m_Manager.AddChunkComponentData(entity); + } + + [Test] + public void AddChunkComponentToGroupTwice() + { + m_Manager.CreateEntity(); + + m_Manager.AddChunkComponentData(m_Manager.UniversalQuery, new EcsTestTag()); + Assert.Throws(() => m_Manager.AddChunkComponentData(m_Manager.UniversalQuery, new EcsTestTag())); + + m_Manager.AddChunkComponentData(m_Manager.UniversalQuery, new EcsTestData{value = 123}); + Assert.Throws(() => m_Manager.AddChunkComponentData(m_Manager.UniversalQuery, new EcsTestData{value = 123})); + Assert.Throws(() => m_Manager.AddChunkComponentData(m_Manager.UniversalQuery, new EcsTestData{value = 456})); + } + + [Test] + public void AddSharedComponentTwice() + { + var entity = m_Manager.CreateEntity(); + + m_Manager.AddSharedComponentData(entity, new EcsTestSharedComp()); + Assert.Throws(() => m_Manager.AddSharedComponentData(entity, new EcsTestSharedComp())); + } } } diff --git a/Unity.Entities.Tests/DisableComponentTests.cs b/Unity.Entities.Tests/DisableComponentTests.cs index 6abb82d2..66122542 100644 --- a/Unity.Entities.Tests/DisableComponentTests.cs +++ b/Unity.Entities.Tests/DisableComponentTests.cs @@ -7,12 +7,12 @@ namespace Unity.Entities.Tests class DisableComponentTests : ECSTestsFixture { [Test] - public void DIS_DontFindDisabledInComponentGroup() + public void DIS_DontFindDisabledInEntityQuery() { var archetype0 = m_Manager.CreateArchetype(typeof(EcsTestData)); var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(Disabled)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var entity0 = m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); @@ -33,7 +33,7 @@ public void DIS_DontFindDisabledInChunkIterator() var entity0 = m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); var count = ArchetypeChunkArray.CalculateEntityCount(chunks); @@ -46,12 +46,12 @@ public void DIS_DontFindDisabledInChunkIterator() } [Test] - public void DIS_FindDisabledIfRequestedInComponentGroup() + public void DIS_FindDisabledIfRequestedInEntityQuery() { var archetype0 = m_Manager.CreateArchetype(typeof(EcsTestData)); var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(Disabled)); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite(), ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite(), ComponentType.ReadWrite()); var entity0 = m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); @@ -75,7 +75,7 @@ public void DIS_FindDisabledIfRequestedInChunkIterator() var entity1 = m_Manager.CreateEntity(archetype1); var entity2 = m_Manager.CreateEntity(archetype1); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite(), ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite(), ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); var count = ArchetypeChunkArray.CalculateEntityCount(chunks); @@ -115,15 +115,15 @@ public void PrefabAndDisabledQueryOptions() m_Manager.CreateEntity(typeof(EcsTestData), typeof(Disabled)); m_Manager.CreateEntity(typeof(EcsTestData), typeof(Disabled), typeof(Prefab)); - CheckPrefabAndDisabledQueryOptions(EntityArchetypeQueryOptions.Default, 0); - CheckPrefabAndDisabledQueryOptions(EntityArchetypeQueryOptions.IncludePrefab, 1); - CheckPrefabAndDisabledQueryOptions(EntityArchetypeQueryOptions.IncludeDisabled, 1); - CheckPrefabAndDisabledQueryOptions(EntityArchetypeQueryOptions.IncludeDisabled | EntityArchetypeQueryOptions.IncludePrefab, 3); + CheckPrefabAndDisabledQueryOptions(EntityQueryOptions.Default, 0); + CheckPrefabAndDisabledQueryOptions(EntityQueryOptions.IncludePrefab, 1); + CheckPrefabAndDisabledQueryOptions(EntityQueryOptions.IncludeDisabled, 1); + CheckPrefabAndDisabledQueryOptions(EntityQueryOptions.IncludeDisabled | EntityQueryOptions.IncludePrefab, 3); } - void CheckPrefabAndDisabledQueryOptions(EntityArchetypeQueryOptions options, int expected) + void CheckPrefabAndDisabledQueryOptions(EntityQueryOptions options, int expected) { - var group = m_Manager.CreateComponentGroup(new EntityArchetypeQuery { All = new[] {ComponentType.ReadWrite()}, Options = options }); + var group = m_Manager.CreateEntityQuery(new EntityQueryDesc { All = new[] {ComponentType.ReadWrite()}, Options = options }); Assert.AreEqual(expected, group.CalculateLength()); group.Dispose(); } diff --git a/Unity.Entities.Tests/ECSTestsFixture.cs b/Unity.Entities.Tests/ECSTestsFixture.cs index ea4ef8df..8f88c040 100644 --- a/Unity.Entities.Tests/ECSTestsFixture.cs +++ b/Unity.Entities.Tests/ECSTestsFixture.cs @@ -1,3 +1,4 @@ +using System.Linq; using NUnit.Framework; using Unity.Collections; using Unity.Jobs; @@ -6,25 +7,25 @@ namespace Unity.Entities.Tests { [DisableAutoCreation] -#if UNITY_CSHARP_TINY +#if NET_DOTS public class EmptySystem : ComponentSystem { protected override void OnUpdate() { } - public new ComponentGroup GetComponentGroup(params EntityArchetypeQuery[] queries) + public new EntityQuery GetEntityQuery(params EntityQueryDesc[] queriesDesc) { - return base.GetComponentGroup(queries); + return base.GetEntityQuery(queriesDesc); } - public new ComponentGroup GetComponentGroup(params ComponentType[] componentTypes) + public new EntityQuery GetEntityQuery(params ComponentType[] componentTypes) { - return base.GetComponentGroup(componentTypes); + return base.GetEntityQuery(componentTypes); } - public new ComponentGroup GetComponentGroup(NativeArray componentTypes) + public new EntityQuery GetEntityQuery(NativeArray componentTypes) { - return base.GetComponentGroup(componentTypes); + return base.GetEntityQuery(componentTypes); } public BufferFromEntity GetBufferFromEntity(bool isReadOnly = false) where T : struct, IBufferElementData { @@ -38,27 +39,19 @@ public class EmptySystem : JobComponentSystem protected override JobHandle OnUpdate(JobHandle dep) { return dep; } - new public ComponentGroup GetComponentGroup(params EntityArchetypeQuery[] queries) + new public EntityQuery GetEntityQuery(params EntityQueryDesc[] queriesDesc) { - return base.GetComponentGroup(queries); + return base.GetEntityQuery(queriesDesc); } - new public ComponentGroup GetComponentGroup(params ComponentType[] componentTypes) + new public EntityQuery GetEntityQuery(params ComponentType[] componentTypes) { - return base.GetComponentGroup(componentTypes); + return base.GetEntityQuery(componentTypes); } - new public ComponentGroup GetComponentGroup(NativeArray componentTypes) + new public EntityQuery GetEntityQuery(NativeArray componentTypes) { - return base.GetComponentGroup(componentTypes); + return base.GetEntityQuery(componentTypes); } -#if !UNITY_ZEROPLAYER - #pragma warning disable 618 - new public ComponentGroupArray GetEntities() where T : struct - { - return base.GetEntities(); - } - #pragma warning restore 618 -#endif } #endif public class ECSTestsFixture @@ -80,7 +73,7 @@ public virtual void Setup() World = DefaultTinyWorldInitialization.Initialize("Test World"); #endif - m_Manager = World.GetOrCreateManager(); + m_Manager = World.EntityManager; m_ManagerDebug = new EntityManager.EntityManagerDebug(m_Manager); #if !UNITY_ZEROPLAYER @@ -100,11 +93,9 @@ public virtual void TearDown() { // Clean up systems before calling CheckInternalConsistency because we might have filters etc // holding on SharedComponentData making checks fail - var system = World.GetExistingManager(); - while (system != null) + while (World.Systems.Any()) { - World.DestroyManager(system); - system = World.GetExistingManager(); + World.DestroySystem(World.Systems.First()); } m_ManagerDebug.CheckInternalConsistency(); @@ -166,7 +157,7 @@ public EmptySystem EmptySystem { get { - return World.Active.GetOrCreateManager(); + return World.Active.GetOrCreateSystem(); } } } diff --git a/Unity.Entities.Tests/EntityArchetypeQueryTests.cs b/Unity.Entities.Tests/EntityArchetypeQueryTests.cs new file mode 100644 index 00000000..cb2bedcf --- /dev/null +++ b/Unity.Entities.Tests/EntityArchetypeQueryTests.cs @@ -0,0 +1,112 @@ +using System; +using NUnit.Framework; + +namespace Unity.Entities.Tests +{ + class EntityArchetypeQueryTests : ECSTestsFixture + { + [Test] + public void EntityQueryFilter_IdenticalIds_InDifferentFilters_Throws() + { + var query = new EntityQueryDesc + { + All = new ComponentType[] {typeof(EcsTestData)}, + None = new ComponentType[] {typeof(EcsTestData)} + }; + + Assert.Throws(() => + { + query.Validate(); + }); + } + + [Test] + public void EntityQueryFilter_IdenticalIds_InSameFilter_Throws() + { + var query = new EntityQueryDesc + { + All = new ComponentType[] {typeof(EcsTestData), typeof(EcsTestData)} + }; + + Assert.Throws(() => + { + query.Validate(); + }); + } + + [Test] + public void EntityQueryFilter_MultipleIdenticalIds_Throws() + { + var query = new EntityQueryDesc + { + All = new ComponentType[] {typeof(EcsTestData), typeof(EcsTestData2)}, + None = new ComponentType[] {typeof(EcsTestData3), typeof(EcsTestData)}, + Any = new ComponentType[] {typeof(EcsTestData), typeof(EcsTestData4)}, + }; + + Assert.Throws(() => + { + query.Validate(); + }); + } + + [Test] + public void EntityQueryFilter_SeparatedIds() + { + var query = new EntityQueryDesc + { + All = new ComponentType[] {typeof(EcsTestData), typeof(EcsTestData2)}, + None = new ComponentType[] {typeof(EcsTestData3), typeof(EcsTestData4)}, + Any = new ComponentType[] {typeof(EcsTestData5)}, + }; + + Assert.DoesNotThrow(() => + { + query.Validate(); + }); + } + + [Test] + public void EntityQueryFilter_CannotContainExcludeComponentType_All_Throws() + { + var query = new EntityQueryDesc + { + All = new ComponentType[] {typeof(EcsTestData), ComponentType.Exclude() }, + }; + + Assert.Throws(() => + { + query.Validate(); + }); + } + + [Test] + public void EntityQueryFilterCannotContainExcludeComponentType_Any_Throws() + { + var query = new EntityQueryDesc + { + Any = new ComponentType[] {typeof(EcsTestData), ComponentType.Exclude() }, + }; + + Assert.Throws(() => + { + query.Validate(); + }); + } + + [Test] + public void EntityQueryFilterCannotContainExcludeComponentType_None_Throws() + { + var query = new EntityQueryDesc + { + All = new ComponentType[] {typeof(EcsTestData) }, + None = new ComponentType[] {typeof(EcsTestData3), ComponentType.Exclude() }, + }; + + Assert.Throws(() => + { + query.Validate(); + }); + } + } +} diff --git a/Unity.Entities.Tests/EntityArchetypeQueryTests.cs.meta b/Unity.Entities.Tests/EntityArchetypeQueryTests.cs.meta new file mode 100644 index 00000000..9594c267 --- /dev/null +++ b/Unity.Entities.Tests/EntityArchetypeQueryTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 64c6e77bc4a4d6346b0b1a89c7fa09ff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities.Tests/EntityCommandBufferTests.cs b/Unity.Entities.Tests/EntityCommandBufferTests.cs index ea5cbcec..5b3d562e 100644 --- a/Unity.Entities.Tests/EntityCommandBufferTests.cs +++ b/Unity.Entities.Tests/EntityCommandBufferTests.cs @@ -47,7 +47,7 @@ public void SingleWriterEnforced() cmds.Playback(m_Manager); cmds.Dispose(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var arr = group.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(2, arr.Length); Assert.AreEqual(42, arr[0].value); @@ -153,7 +153,7 @@ public void CreateEntity() cmds.Playback(m_Manager); cmds.Dispose(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var arr = group.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(1, arr.Length); Assert.AreEqual(12, arr[0].value); @@ -172,7 +172,7 @@ public void CreateEntityWithArchetype() cmds.Playback(m_Manager); cmds.Dispose(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var arr = group.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(1, arr.Length); Assert.AreEqual(12, arr[0].value); @@ -191,7 +191,7 @@ public void CreateTwoComponents() cmds.Dispose(); { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var arr = group.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(1, arr.Length); Assert.AreEqual(12, arr[0].value); @@ -200,7 +200,7 @@ public void CreateTwoComponents() } { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData2)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData2)); var arr = group.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(1, arr.Length); Assert.AreEqual(1, arr[0].value0); @@ -229,7 +229,7 @@ public void TestMultiChunks() cmds.Dispose(); { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2)); var arr = group.ToComponentDataArray(Allocator.TempJob); var arr2 = group.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(count, arr.Length); @@ -246,7 +246,6 @@ public void TestMultiChunks() } [Test] - [StandaloneFixme] // ISharedComponentData public void AddSharedComponent() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -264,7 +263,6 @@ public void AddSharedComponent() } [Test] - [StandaloneFixme] // ISharedComponentData public void AddSharedComponentDefault() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -292,7 +290,6 @@ public void AddSharedComponentDefault() } [Test] - [StandaloneFixme] // ISharedComponentData public void SetSharedComponent() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -313,7 +310,6 @@ public void SetSharedComponent() } [Test] - [StandaloneFixme] // ISharedComponentData public void SetSharedComponentDefault() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -334,7 +330,6 @@ public void SetSharedComponentDefault() } [Test] - [StandaloneFixme] // ISharedComponentData public void RemoveSharedComponent() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -700,7 +695,6 @@ public void ConcurrentRecordInstantiate() } [Test] - [StandaloneFixme] // // Real problem: Atomic Safety public void PlaybackInvalidatesBuffers() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -718,7 +712,6 @@ public void PlaybackInvalidatesBuffers() } [Test] - [StandaloneFixme] // Real problem: Atomic Safety public void ArrayAliasesOfPendingBuffersAreInvalidateOnResize() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -925,10 +918,9 @@ public void BufferCopyFromDoesNotThrowInJob() #if ENABLE_UNITY_COLLECTIONS_CHECKS [Test] - [StandaloneFixme] public void EntityCommandBufferSystemPlaybackExceptionIsolation() { - var entityCommandBufferSystem = World.GetOrCreateManager(); + var entityCommandBufferSystem = World.GetOrCreateSystem(); var buf1 = entityCommandBufferSystem.CreateCommandBuffer(); var buf2 = entityCommandBufferSystem.CreateCommandBuffer(); @@ -944,13 +936,13 @@ public void EntityCommandBufferSystemPlaybackExceptionIsolation() // We exp both command buffers to execute, and an exception thrown afterwards // Essentially we want isolation of two systems that might fail independently. Assert.Throws(() => { entityCommandBufferSystem.Update(); }); - Assert.AreEqual(2, EmptySystem.GetComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(2, EmptySystem.GetEntityQuery(typeof(EcsTestData)).CalculateLength()); // On second run, we expect all buffers to be removed... // So no more exceptions thrown. entityCommandBufferSystem.Update(); - Assert.AreEqual(2, EmptySystem.GetComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(2, EmptySystem.GetEntityQuery(typeof(EcsTestData)).CalculateLength()); } #endif @@ -959,7 +951,7 @@ public void EntityCommandBufferSystemPlaybackExceptionIsolation() [StandaloneFixme] // IJob public void EntityCommandBufferSystem_OmitAddJobHandleForProducer_ThrowArgumentException() { - var barrier = World.GetOrCreateManager(); + var barrier = World.GetOrCreateSystem(); var cmds = barrier.CreateCommandBuffer(); const int kCreateCount = 10000; var job = new TestParallelJob @@ -974,7 +966,6 @@ public void EntityCommandBufferSystem_OmitAddJobHandleForProducer_ThrowArgumentE #endif [Test] - [StandaloneFixme] // ISharedComponentData public void AddSharedComponent_WhenComponentHasEntityField_ThrowsArgumentException() { var cmds = new EntityCommandBuffer(Allocator.TempJob); @@ -1000,7 +991,7 @@ public void AddComponent_WhenDataContainsDeferredEntity_DeferredEntityIsResolved cmds.Playback(m_Manager); cmds.Dispose(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestDataEntity)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestDataEntity)); var arr = group.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(1, arr.Length); @@ -1052,6 +1043,63 @@ public void InstantiateEntity_BatchMode_DisabledIfEntityDirty() Assert.AreEqual(12, m_Manager.GetComponentData(realDst1).value1); } + [Test] + public void UninitializedEntityCommandBufferThrows() + { + EntityCommandBuffer cmds = new EntityCommandBuffer(); + var exception = Assert.Throws(() => cmds.CreateEntity()); + Assert.AreEqual(exception.Message, "The EntityCommandBuffer has not been initialized!"); + } + + [Test] + public void UninitializedConcurrentEntityCommandBufferThrows() + { + EntityCommandBuffer.Concurrent cmds = new EntityCommandBuffer.Concurrent(); + var exception = Assert.Throws(() => cmds.CreateEntity(0)); + Assert.AreEqual(exception.Message, "The EntityCommandBuffer has not been initialized!"); + } + + [Test] + public void AddOrSetBufferWithEntity_NeedsFixup_Works([Values(true,false)] bool setBuffer) + { + EntityCommandBuffer cmds = new EntityCommandBuffer(Allocator.TempJob); + + Entity e0 = m_Manager.CreateEntity(); + Entity e1 = m_Manager.CreateEntity(); + Entity e2 = m_Manager.CreateEntity(); + + if (setBuffer) + m_Manager.AddComponent(e1, typeof(EcsComplexEntityRefElement)); + + { + var deferred0 = cmds.CreateEntity(); + var deferred1 = cmds.CreateEntity(); + var deferred2 = cmds.CreateEntity(); + + cmds.AddComponent(e0, new EcsTestDataEntity() { value1 = deferred0 }); + cmds.AddComponent(e1, new EcsTestDataEntity() { value1 = deferred1 }); + cmds.AddComponent(e2, new EcsTestDataEntity() { value1 = deferred2 }); + + var buf = setBuffer ? cmds.SetBuffer(e1) : cmds.AddBuffer(e1); + buf.Add(new EcsComplexEntityRefElement() {Entity = e0}); + buf.Add(new EcsComplexEntityRefElement() {Entity = deferred1}); + buf.Add(new EcsComplexEntityRefElement() {Entity = deferred2}); + buf.Add(new EcsComplexEntityRefElement() {Entity = deferred0}); + cmds.Playback(m_Manager); + cmds.Dispose(); + } + { + var outbuf = m_Manager.GetBuffer(e1); + Assert.AreEqual(4, outbuf.Length); + var expect0 = m_Manager.GetComponentData(e0).value1; + var expect1 = m_Manager.GetComponentData(e1).value1; + var expect2 = m_Manager.GetComponentData(e2).value1; + Assert.AreEqual(e0, outbuf[0].Entity); + Assert.AreEqual(expect1, outbuf[1].Entity); + Assert.AreEqual(expect2, outbuf[2].Entity); + Assert.AreEqual(expect0, outbuf[3].Entity); + } + } } } diff --git a/Unity.Entities.Tests/EntityManagerBugTests.cs b/Unity.Entities.Tests/EntityManagerBugTests.cs index 70c255d0..9720128e 100644 --- a/Unity.Entities.Tests/EntityManagerBugTests.cs +++ b/Unity.Entities.Tests/EntityManagerBugTests.cs @@ -34,6 +34,8 @@ class EntityBag [Test] public void TestIssue149() { + m_OurTypes = new ComponentType[] {typeof(Issue149Data)}; + m_Archetype = m_Manager.CreateArchetype(typeof(Issue149Data)); for (int i = 0; i < Bags.Length; ++i) @@ -91,19 +93,17 @@ void RecycleEntities(EntityBag bag) } } - private static readonly ComponentType[] s_OurTypes = new ComponentType[] { - typeof(Issue149Data) - }; + private ComponentType[] m_OurTypes; // Walk all accessible entity data and check that the versions match what we // believe the generation numbers should be. private void SanityCheckVersions() { - var group = m_Manager.CreateComponentGroup(new EntityArchetypeQuery + var group = m_Manager.CreateEntityQuery(new EntityQueryDesc { Any = Array.Empty(), None = Array.Empty(), - All = s_OurTypes, + All = m_OurTypes, }); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); @@ -138,7 +138,7 @@ class Bug476 : ECSTestsFixture public void EntityArchetypeQueryMembersHaveSensibleDefaults() { ComponentType[] types = {typeof(Issue476Data)}; - var group = m_Manager.CreateComponentGroup(types); + var group = m_Manager.CreateEntityQuery(types); var temp = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); temp.Dispose(); @@ -156,7 +156,7 @@ public void Test1() World w = DefaultTinyWorldInitialization.Initialize("TestWorld"); #endif World.Active = w; - EntityManager em = World.Active.GetOrCreateManager(); + EntityManager em = World.Active.EntityManager; List remember = new List(); for (int i = 0; i < 5; i++) { @@ -185,7 +185,7 @@ public void Test2() World w = DefaultTinyWorldInitialization.Initialize("TestWorld"); #endif World.Active = w; - EntityManager em = World.Active.GetOrCreateManager(); + EntityManager em = World.Active.EntityManager; List remember = new List(); for (int i = 0; i < 5; i++) @@ -202,7 +202,7 @@ public void Test2() w = DefaultTinyWorldInitialization.Initialize("TestWorld"); #endif World.Active = w; - em = World.Active.GetOrCreateManager(); + em = World.Active.EntityManager; var allEnt = em.GetAllEntities(Allocator.Temp); Assert.AreEqual(0, allEnt.Length); allEnt.Dispose(); diff --git a/Unity.Entities.Tests/EntityManagerComponentGroupOperationsTests.cs b/Unity.Entities.Tests/EntityManagerComponentGroupOperationsTests.cs index 004a2bed..91af710e 100644 --- a/Unity.Entities.Tests/EntityManagerComponentGroupOperationsTests.cs +++ b/Unity.Entities.Tests/EntityManagerComponentGroupOperationsTests.cs @@ -8,13 +8,13 @@ class EntityManagerComponentGroupOperationsTests : ECSTestsFixture [Test] public void AddRemoveChunkComponentWithGroupWorks() { - var metaChunkGroup = m_Manager.CreateComponentGroup(typeof(ChunkHeader)); + var metaChunkGroup = m_Manager.CreateEntityQuery(typeof(ChunkHeader)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData)); var entity2 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); var entity3 = m_Manager.CreateEntity(typeof(EcsTestData2)); - var group1 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group1 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); m_Manager.AddChunkComponentData(group1, new EcsTestData3(7)); @@ -32,7 +32,7 @@ public void AddRemoveChunkComponentWithGroupWorks() m_ManagerDebug.CheckInternalConsistency(); - var group2 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite(), ComponentType.ChunkComponent()); + var group2 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite(), ComponentType.ChunkComponent()); m_Manager.RemoveChunkComponentData(group2); @@ -49,7 +49,7 @@ public void AddRemoveSharedComponentWithGroupWorks() var entity2 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); var entity3 = m_Manager.CreateEntity(typeof(EcsTestData2)); - var group1 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group1 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); m_Manager.AddSharedComponentData(group1, new EcsTestSharedComp(7)); @@ -65,90 +65,106 @@ public void AddRemoveSharedComponentWithGroupWorks() m_ManagerDebug.CheckInternalConsistency(); - var group2 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite(), ComponentType.ReadWrite()); + var group2 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite(), ComponentType.ReadWrite()); m_Manager.RemoveComponent(group2, typeof(EcsTestSharedComp)); Assert.IsFalse(m_Manager.HasComponent(entity2, typeof(EcsTestSharedComp))); } - public static ComponentType[] GetTestTypes() - { - TypeManager.Initialize(); - return new ComponentType[] { typeof(EcsTestTag), typeof(EcsTestData4), ComponentType.ChunkComponent(), typeof(EcsTestSharedComp) }; - } - [Test] [StandaloneFixme] // ISharedComponentData - public void AddRemoveAnyComponentWithGroupWorksWith([ValueSource(nameof(GetTestTypes))] ComponentType type) + public void AddRemoveAnyComponentWithGroupWorksWithVariousTypes() { - var metaChunkGroup = m_Manager.CreateComponentGroup(typeof(ChunkHeader)); + TypeManager.Initialize(); + var componentTypes = new ComponentType[] { typeof(EcsTestTag), typeof(EcsTestData4), ComponentType.ChunkComponent(), typeof(EcsTestSharedComp) }; - var entity1 = m_Manager.CreateEntity(typeof(EcsTestData)); - var entity2 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var entity3 = m_Manager.CreateEntity(typeof(EcsTestData2)); + foreach (var type in componentTypes) + { + // We want a clean slate for the m_manager so teardown and setup before the test + TearDown(); + Setup(); - var group1 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var metaChunkGroup = m_Manager.CreateEntityQuery(typeof(ChunkHeader)); - m_Manager.AddComponent(group1, type); + var entity1 = m_Manager.CreateEntity(typeof(EcsTestData)); + var entity2 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); + var entity3 = m_Manager.CreateEntity(typeof(EcsTestData2)); - Assert.IsTrue(m_Manager.HasComponent(entity1, type)); - Assert.IsTrue(m_Manager.HasComponent(entity2, type)); - Assert.IsFalse(m_Manager.HasComponent(entity3, type)); + var group1 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); - if(type.IsChunkComponent) - Assert.AreEqual(2, metaChunkGroup.CalculateLength()); + m_Manager.AddComponent(group1, type); - if (type == ComponentType.ReadWrite()) - { - m_Manager.SetSharedComponentData(entity1, new EcsTestSharedComp(1)); - m_Manager.SetSharedComponentData(entity2, new EcsTestSharedComp(2)); - } + Assert.IsTrue(m_Manager.HasComponent(entity1, type)); + Assert.IsTrue(m_Manager.HasComponent(entity2, type)); + Assert.IsFalse(m_Manager.HasComponent(entity3, type)); - m_ManagerDebug.CheckInternalConsistency(); + if (type.IsChunkComponent) + Assert.AreEqual(2, metaChunkGroup.CalculateLength()); - var group2 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite(), type); + if (type == ComponentType.ReadWrite()) + { + m_Manager.SetSharedComponentData(entity1, new EcsTestSharedComp(1)); + m_Manager.SetSharedComponentData(entity2, new EcsTestSharedComp(2)); + } - m_Manager.RemoveComponent(group2, type); + m_ManagerDebug.CheckInternalConsistency(); - Assert.IsFalse(m_Manager.HasComponent(entity2, ComponentType.ChunkComponent())); + var group2 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite(), type); + + m_Manager.RemoveComponent(group2, type); - if(type.IsChunkComponent) - Assert.AreEqual(1, metaChunkGroup.CalculateLength()); + Assert.IsFalse(m_Manager.HasComponent(entity2, ComponentType.ChunkComponent())); + + if (type.IsChunkComponent) + Assert.AreEqual(1, metaChunkGroup.CalculateLength()); + } + TypeManager.Shutdown(); } [Test] [StandaloneFixme] // ISharedComponentData - public void RemoveAnyComponentWithGroupIgnoresChunksThatDontHaveTheComponent([ValueSource(nameof(GetTestTypes))] ComponentType type) + public void RemoveAnyComponentWithGroupIgnoresChunksThatDontHaveTheComponent() { - var metaChunkGroup = m_Manager.CreateComponentGroup(typeof(ChunkHeader)); + TypeManager.Initialize(); + var componentTypes = new ComponentType[] { typeof(EcsTestTag), typeof(EcsTestData4), ComponentType.ChunkComponent(), typeof(EcsTestSharedComp) }; - var entity1 = m_Manager.CreateEntity(typeof(EcsTestData)); - var entity2 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var entity3 = m_Manager.CreateEntity(typeof(EcsTestData2)); + foreach (var type in componentTypes) + { + // We want a clean slate for the m_manager so teardown and setup before the test + TearDown(); + Setup(); - var group1 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var metaChunkGroup = m_Manager.CreateEntityQuery(typeof(ChunkHeader)); - m_Manager.AddComponent(group1, type); + var entity1 = m_Manager.CreateEntity(typeof(EcsTestData)); + var entity2 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); + var entity3 = m_Manager.CreateEntity(typeof(EcsTestData2)); - Assert.IsTrue(m_Manager.HasComponent(entity1, type)); - Assert.IsTrue(m_Manager.HasComponent(entity2, type)); - Assert.IsFalse(m_Manager.HasComponent(entity3, type)); + var group1 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); - if(type.IsChunkComponent) - Assert.AreEqual(2, metaChunkGroup.CalculateLength()); + m_Manager.AddComponent(group1, type); - if (type == ComponentType.ReadWrite()) - { - m_Manager.SetSharedComponentData(entity1, new EcsTestSharedComp(1)); - m_Manager.SetSharedComponentData(entity2, new EcsTestSharedComp(2)); - } + Assert.IsTrue(m_Manager.HasComponent(entity1, type)); + Assert.IsTrue(m_Manager.HasComponent(entity2, type)); + Assert.IsFalse(m_Manager.HasComponent(entity3, type)); - m_ManagerDebug.CheckInternalConsistency(); + if (type.IsChunkComponent) + Assert.AreEqual(2, metaChunkGroup.CalculateLength()); + + if (type == ComponentType.ReadWrite()) + { + m_Manager.SetSharedComponentData(entity1, new EcsTestSharedComp(1)); + m_Manager.SetSharedComponentData(entity2, new EcsTestSharedComp(2)); + } - m_Manager.RemoveComponent(m_Manager.UniversalGroup, type); + m_ManagerDebug.CheckInternalConsistency(); - Assert.AreEqual(0, m_Manager.CreateComponentGroup(type).CalculateLength()); + m_Manager.RemoveComponent(m_Manager.UniversalQuery, type); + + Assert.AreEqual(0, m_Manager.CreateEntityQuery(type).CalculateLength()); + } + TypeManager.Shutdown(); } uint GetComponentDataVersion(Entity e) where T : struct, IComponentData @@ -162,7 +178,7 @@ uint GetSharedComponentDataVersion(Entity e) where T : struct, ISharedCompone } [Test] - [StandaloneFixme] // ISharedComponentData + [StandaloneFixme] // Don't know why fails? public void AddRemoveComponentWithGroupPreservesChangeVersions() { m_ManagerDebug.SetGlobalSystemVersion(10); @@ -182,11 +198,11 @@ public void AddRemoveComponentWithGroupPreservesChangeVersions() m_ManagerDebug.SetGlobalSystemVersion(30); - m_Manager.AddSharedComponentData(m_Manager.UniversalGroup, new EcsTestSharedComp(1)); + m_Manager.AddSharedComponentData(m_Manager.UniversalQuery, new EcsTestSharedComp(1)); m_ManagerDebug.SetGlobalSystemVersion(40); - m_Manager.AddComponent(m_Manager.UniversalGroup, typeof(EcsTestTag)); + m_Manager.AddComponent(m_Manager.UniversalQuery, typeof(EcsTestTag)); Assert.AreEqual(30, GetSharedComponentDataVersion(entity1)); Assert.AreEqual(30, GetSharedComponentDataVersion(entity2)); @@ -198,7 +214,7 @@ public void AddRemoveComponentWithGroupPreservesChangeVersions() m_ManagerDebug.SetGlobalSystemVersion(50); - m_Manager.RemoveComponent(m_Manager.UniversalGroup, typeof(EcsTestSharedComp2)); + m_Manager.RemoveComponent(m_Manager.UniversalQuery, typeof(EcsTestSharedComp2)); Assert.AreEqual(30, GetSharedComponentDataVersion(entity1)); Assert.AreEqual(30, GetSharedComponentDataVersion(entity2)); @@ -206,7 +222,7 @@ public void AddRemoveComponentWithGroupPreservesChangeVersions() m_ManagerDebug.SetGlobalSystemVersion(60); - m_Manager.RemoveComponent(m_Manager.UniversalGroup, typeof(EcsTestSharedComp)); + m_Manager.RemoveComponent(m_Manager.UniversalQuery, typeof(EcsTestSharedComp)); Assert.AreEqual(10, GetComponentDataVersion(entity1)); Assert.AreEqual(10, GetComponentDataVersion(entity2)); diff --git a/Unity.Entities.Tests/EntityManagerPrefabTests.cs b/Unity.Entities.Tests/EntityManagerPrefabTests.cs index 535d3002..a0150152 100644 --- a/Unity.Entities.Tests/EntityManagerPrefabTests.cs +++ b/Unity.Entities.Tests/EntityManagerPrefabTests.cs @@ -70,7 +70,7 @@ public void InstantiateLinkedGroup() CheckLinkedGroup(clone, srcLinked, external); // Make sure that instantiated objects are found by component group (They are no longer prefabs) - Assert.AreEqual(4, m_Manager.CreateComponentGroup(typeof(EcsTestDataEntity)).CalculateLength()); + Assert.AreEqual(4, m_Manager.CreateEntityQuery(typeof(EcsTestDataEntity)).CalculateLength()); srcLinked.Dispose(); } @@ -91,7 +91,7 @@ public void InstantiateLinkedGroupStressTest([Values(1, 1023)]int count) } // Make sure that instantiated objects are found by component group (They are no longer prefabs) - Assert.AreEqual(3 * 4 * count, m_Manager.CreateComponentGroup(typeof(EcsTestDataEntity)).CalculateLength()); + Assert.AreEqual(3 * 4 * count, m_Manager.CreateEntityQuery(typeof(EcsTestDataEntity)).CalculateLength()); clones.Dispose(); srcLinked.Dispose(); diff --git a/Unity.Entities.Tests/EntityManagerTests.cs b/Unity.Entities.Tests/EntityManagerTests.cs index 27876954..43177a79 100644 --- a/Unity.Entities.Tests/EntityManagerTests.cs +++ b/Unity.Entities.Tests/EntityManagerTests.cs @@ -138,7 +138,7 @@ public unsafe void ComponentsWithBool() var hash = new NativeHashMap(count, Allocator.Temp); - var cg = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var cg = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); using (var chunks = cg.CreateArchetypeChunkArray(Allocator.TempJob)) { var boolsType = m_Manager.GetArchetypeChunkComponentType(false); @@ -166,5 +166,56 @@ public unsafe void ComponentsWithBool() array.Dispose(); hash.Dispose(); } + + + struct BigComponentWithAlign1A : IComponentData + { + NativeString4096 bs; + unsafe fixed byte val[3]; + } + + struct ComponentWithAlign8 : IComponentData { + double val; + } + + struct BigComponentWithAlign1B : IComponentData { + NativeString4096 bs; + unsafe fixed byte val[3]; + } + + [Test] + public unsafe void ChunkComponentRunIsAligned() + { + // We need to make sure that the stricter-alignment component (WithAlign8) comes after the simpler one + Type oneByteAlignmentType = typeof(BigComponentWithAlign1A); + int bigTypeIndex = TypeManager.GetTypeIndex(); + if ((TypeManager.GetTypeIndex() & TypeManager.ClearFlagsMask) > + (bigTypeIndex & TypeManager.ClearFlagsMask)) + { + // must be the other one + oneByteAlignmentType = typeof(BigComponentWithAlign1B); + } + + var oneByteInfo = TypeManager.GetTypeInfo(TypeManager.GetTypeIndex(oneByteAlignmentType)); + int bigAlignment = TypeManager.GetTypeInfo().AlignmentInBytes; + + //Assert.AreEqual(4, TypeManager.GetTypeInfo(TypeManager.GetTypeIndex(oneByteAlignmentType)).AlignmentInBytes); + Assert.AreEqual(8, bigAlignment); + + // Create an entity + var archetype = m_Manager.CreateArchetype(oneByteAlignmentType, typeof(ComponentWithAlign8)); + var entity = m_Manager.CreateEntity(archetype); + // Get a pointer to the first bigger-aligned component + var p2 = m_Manager.GetComponentDataRawRW(entity, bigTypeIndex); + + // p2 needs to be aligned properly + Assert.AreEqual(0, (long)p2 & (bigAlignment - 1)); + + // But let's verify that we didn't get lucky. If you see this assertion fire due to a change, + // it's because chunk layout chanked such that the 8-byte-aligned chunk would naturally fall + // on its proper alignment. Play with the BigComponent sizes (by adding/removing members) above + // until you get this to pass. + Assert.AreNotEqual(0, (archetype.Archetype->ChunkCapacity * oneByteInfo.SizeInChunk) % 8); + } } } diff --git a/Unity.Entities.Tests/EntityQueryBuilderTests.cs b/Unity.Entities.Tests/EntityQueryBuilderTests.cs index 97f9f68d..65e508b1 100644 --- a/Unity.Entities.Tests/EntityQueryBuilderTests.cs +++ b/Unity.Entities.Tests/EntityQueryBuilderTests.cs @@ -11,7 +11,7 @@ class EntityQueryBuilderTestFixture : ECSTestsFixture protected class TestComponentSystem : ComponentSystem { protected override void OnUpdate() { } } - protected static TestComponentSystem TestSystem => World.Active.GetOrCreateManager(); + protected static TestComponentSystem TestSystem => World.Active.GetOrCreateSystem(); } class EntityQueryBuilderTests : EntityQueryBuilderTestFixture @@ -20,7 +20,7 @@ class EntityQueryBuilderTests : EntityQueryBuilderTestFixture class TestComponentSystem2 : ComponentSystem { protected override void OnUpdate() { } } - static TestComponentSystem2 TestSystem2 => World.Active.GetOrCreateManager(); + static TestComponentSystem2 TestSystem2 => World.Active.GetOrCreateSystem(); [Test] public void WithGroup_WithNullGroup_Throws() => @@ -29,8 +29,8 @@ public void WithGroup_WithNullGroup_Throws() => [Test] public void WithGroup_WithExistingGroup_Throws() { - var group0 = TestSystem.GetComponentGroup(ComponentType.ReadWrite()); - var group1 = TestSystem.GetComponentGroup(ComponentType.ReadOnly()); + var group0 = TestSystem.GetEntityQuery(ComponentType.ReadWrite()); + var group1 = TestSystem.GetEntityQuery(ComponentType.ReadOnly()); var query = TestSystem.Entities.With(group0); @@ -40,7 +40,7 @@ public void WithGroup_WithExistingGroup_Throws() [Test] public void WithGroup_WithExistingSpec_Throws() { - var group = TestSystem.GetComponentGroup(ComponentType.ReadWrite()); + var group = TestSystem.GetEntityQuery(ComponentType.ReadWrite()); Assert.Throws(() => TestSystem.Entities.WithAny().With(group)); Assert.Throws(() => TestSystem.Entities.WithNone().With(group)); @@ -50,7 +50,7 @@ public void WithGroup_WithExistingSpec_Throws() [Test] public void WithSpec_WithExistingGroup_Throws() { - var group = TestSystem.GetComponentGroup(ComponentType.ReadWrite()); + var group = TestSystem.GetEntityQuery(ComponentType.ReadWrite()); Assert.Throws(() => TestSystem.Entities.With(group).WithAny()); Assert.Throws(() => TestSystem.Entities.With(group).WithNone()); @@ -91,8 +91,8 @@ public void Equals_WithSlightlyDifferentlyConstructedBuilders_ReturnsFalse() [Test] public void Equals_WithDifferentGroups_ReturnsFalse() { - var group0 = TestSystem.GetComponentGroup(ComponentType.ReadWrite()); - var group1 = TestSystem.GetComponentGroup(ComponentType.ReadOnly()); + var group0 = TestSystem.GetEntityQuery(ComponentType.ReadWrite()); + var group1 = TestSystem.GetEntityQuery(ComponentType.ReadOnly()); var builder0 = TestSystem.Entities.With(group0); var builder1 = TestSystem.Entities.With(group1); @@ -145,7 +145,7 @@ public void Equals_WithMismatchedBuilders_ReturnsFalse() } { - var group = TestSystem.GetComponentGroup(ComponentType.ReadWrite()); + var group = TestSystem.GetEntityQuery(ComponentType.ReadWrite()); var builder0 = TestSystem.Entities.With(group); var builder1 = TestSystem.Entities; Assert.IsFalse(builder0.ShallowEquals(ref builder1)); @@ -159,7 +159,7 @@ public void ToEntityArchetypeQuery_WithFluentSpec_ReturnsQueryAsSpecified() .WithAll() .WithAny() .WithNone() - .ToEntityArchetypeQuery(); + .ToEntityQueryDesc(); CollectionAssert.AreEqual( new[] { ComponentType.ReadWrite() }, @@ -177,7 +177,7 @@ public void ToComponentGroup_OnceCached_StaysCached() { // this will cause the group to get cached in the query var query = TestSystem.Entities.WithAll(); - query.ToComponentGroup(); + query.ToEntityQuery(); // this will throw because we're trying to modify the spec, yet we already have a group cached Assert.Throws(() => query.WithNone()); @@ -203,7 +203,7 @@ public void ForEach_WithReusedQueryButDifferentDelegateParams_Throws() Assert.IsTrue(oldQuery.ShallowEquals(ref query)); - var eaq = query.ToEntityArchetypeQuery(); + var eaq = query.ToEntityQueryDesc(); CollectionAssert.AreEqual( new[] { ComponentType.ReadWrite(), ComponentType.ReadWrite() }, eaq.All); diff --git a/Unity.Entities.Tests/EntityQueryCacheTests.cs b/Unity.Entities.Tests/EntityQueryCacheTests.cs index aad117cb..f0a13f87 100644 --- a/Unity.Entities.Tests/EntityQueryCacheTests.cs +++ b/Unity.Entities.Tests/EntityQueryCacheTests.cs @@ -8,6 +8,18 @@ namespace Unity.Entities.Tests { unsafe class EntityQueryCacheTests { + [SetUp] + public void Setup() + { + TypeManager.Initialize(); + } + + [TearDown] + public void TearDown() + { + TypeManager.Shutdown(); + } + [Test] public void Ctor_WithCacheSize0_Throws() { @@ -17,7 +29,7 @@ public void Ctor_WithCacheSize0_Throws() // ReSharper restore ObjectCreationAsStatement } - static void SimpleWrapCreateCachedQuery(EntityQueryCache cache, uint hash, ComponentGroup group) + static void SimpleWrapCreateCachedQuery(EntityQueryCache cache, uint hash, EntityQuery group) { #if ENABLE_UNITY_COLLECTIONS_CHECKS var builder = new EntityQueryBuilder(); @@ -27,6 +39,32 @@ static void SimpleWrapCreateCachedQuery(EntityQueryCache cache, uint hash, Compo #endif } + [Test] + public void CalcUsedCacheCount_WithEmptyCache_ReturnsZero() + { + var cache = new EntityQueryCache(1); + + Assert.AreEqual(0, cache.CalcUsedCacheCount()); + } + + [Test] + public void CalcUsedCacheCount_WithSomeInCache_ReturnsCorrectNumber() + { + var cache = new EntityQueryCache(2); + SimpleWrapCreateCachedQuery(cache, 0, k_DummyGroup); + + Assert.AreEqual(1, cache.CalcUsedCacheCount()); + } + + [Test] + public void CalcUsedCacheCount_WithFullCache_ReturnsCorrectNumber() + { + var cache = new EntityQueryCache(1); + SimpleWrapCreateCachedQuery(cache, 0, k_DummyGroup); + + Assert.AreEqual(1, cache.CalcUsedCacheCount()); + } + [Test] public void FindQueryInCache_WithEmptyCache_ReturnsErrorIndex() { @@ -61,7 +99,7 @@ public void FindQueryInCache_WithHashFound_ReturnsFoundIndex() } readonly Regex k_ResizeError = new Regex(".*is too small to hold the current number of queries.*"); - readonly ComponentGroup k_DummyGroup = new ComponentGroup(null, null, null, null); + readonly EntityQuery k_DummyGroup = new EntityQuery(null, null, null, null); [Test] public void CreateCachedQuery_WithNullGroup_Throws() @@ -127,6 +165,7 @@ public void GetCachedQuery_WithInvalidIndex_Throws() Assert.Throws(() => cache.GetCachedQuery(1)); } +#if ENABLE_UNITY_COLLECTIONS_CHECKS [Test] public void ValidateMatchesCache_WithValidMatch_DoesNotThrow() @@ -191,5 +230,6 @@ public void ValidateMatchesCache_WithMismatchedDelegateTypeIndices_Throws() catch (InvalidOperationException x) { testException1 = x; } Assert.NotNull(testException1); } +#endif } } diff --git a/Unity.Entities.Tests/EntityRemapUtilityTests.cs b/Unity.Entities.Tests/EntityRemapUtilityTests.cs index 0376bb27..fef0936e 100644 --- a/Unity.Entities.Tests/EntityRemapUtilityTests.cs +++ b/Unity.Entities.Tests/EntityRemapUtilityTests.cs @@ -10,6 +10,7 @@ public class EntityRemapUtilityTests [SetUp] public void Setup() { + TypeManager.Initialize(); m_Remapping = new NativeArray(100, Allocator.Persistent); } @@ -17,6 +18,7 @@ public void Setup() public void TearDown() { m_Remapping.Dispose(); + TypeManager.Shutdown(); } [Test] diff --git a/Unity.Entities.Tests/EntityTransactionTests.cs b/Unity.Entities.Tests/EntityTransactionTests.cs index a661d6ed..397c7cdf 100644 --- a/Unity.Entities.Tests/EntityTransactionTests.cs +++ b/Unity.Entities.Tests/EntityTransactionTests.cs @@ -13,7 +13,7 @@ namespace Unity.Entities.Tests [StandaloneFixme] // Asserts on JobDebugger in constructor class EntityTransactionTests : ECSTestsFixture { - ComponentGroup m_Group; + EntityQuery m_Group; public EntityTransactionTests() { @@ -25,7 +25,7 @@ public override void Setup() { base.Setup(); - m_Group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + m_Group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); // Archetypes can't be created on a job m_Manager.CreateArchetype(typeof(EcsTestData)); @@ -84,7 +84,6 @@ public void CreateEntitiesChainedJob() [Test] - [StandaloneFixme] public void CommitAfterNotRegisteredTransactionJobLogsError() { var job = new CreateEntityJob(); diff --git a/Unity.Entities/Injection.meta b/Unity.Entities.Tests/ForEach.meta similarity index 77% rename from Unity.Entities/Injection.meta rename to Unity.Entities.Tests/ForEach.meta index 0b6e859b..ed678d6a 100644 --- a/Unity.Entities/Injection.meta +++ b/Unity.Entities.Tests/ForEach.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8bf694bfa86dd41fa8c549c11468bc71 +guid: e118a56a80e4c6749bc6caeb2ff6a56a folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Unity.Entities.Tests/ForEach/ForEachBasicMemoryTests.cs b/Unity.Entities.Tests/ForEach/ForEachBasicMemoryTests.cs new file mode 100644 index 00000000..e95c91d2 --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachBasicMemoryTests.cs @@ -0,0 +1,41 @@ +#if !UNITY_ZEROPLAYER +using System; +using NUnit.Framework; + +// ReSharper disable MemberCanBeMadeStatic.Local + +namespace Unity.Entities.Tests.ForEach +{ + // these tests are intended to confirm that compiled code allocs exactly how we expect + + class ForEachBasicMemoryTests : ForEachMemoryTestFixtureBase + { + // SANITY + + [Test] + public void StackAllocValueType_ShouldRecordNoGCAllocs() + { + AllocRecorder.enabled = true; + + // ReSharper disable once NotAccessedVariable + var i = 0; + ++i; + + AllocRecorder.enabled = false; + Assert.Zero(AllocRecorder.sampleBlockCount); + } + + [Test] + public void NewArray_ShouldRecordOneGCAlloc() + { + AllocRecorder.enabled = true; + + var t = new int[1]; + t[0] = 1; + + AllocRecorder.enabled = false; + Assert.AreEqual(1, AllocRecorder.sampleBlockCount); + } + } +} +#endif // !UNITY_ZEROPLAYER diff --git a/Unity.Entities.Tests/ForEach/ForEachBasicMemoryTests.cs.meta b/Unity.Entities.Tests/ForEach/ForEachBasicMemoryTests.cs.meta new file mode 100644 index 00000000..13e52c7f --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachBasicMemoryTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 047b97d3d30df7241bf8322367a2edc4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.gen.cs b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.gen.cs new file mode 100644 index 00000000..0e80c806 --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.gen.cs @@ -0,0 +1,729 @@ +#if !UNITY_ZEROPLAYER +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +// Generated by ForEachDelegateMemoryTests.tt + +using NUnit.Framework; + +/* +The purpose of these tests is to validate and make invariant assumptions about +compiler codegen. ForEach needs to receive a delegate, and there are many ways +to implicitly construct one, which are tested below. What we want is to ensure +that we understand the scenarios that generate garbage every frame so we can +detect and warn about them in user code, or replace with our own codegen. + +There are two paths to garbage: + +1. ForEach needs to receive a delegate to do its work, which is represented in + the runtime as a MulticastDelegate. This needs to be allocated from the + gc, and it is not done statically, but on-demand. + + The result of this `newobj` may always be cached manually, and sometimes is + cached automatically. That's one of the things the below tests validate. + +2. In a closure, something needs to associate all captured non-global + variables (including `this`) with the delegate, typically a codegen'd class + with captures as members. This will involve a gc alloc per-call. + + Note that local functions use a struct for their captures when called in + the containing method, but this optimization does not apply if the local is + converted to a delegate. + +Categories: (each has a fixture) + + Lambda: Using the () => {} syntax. Current C# compilers (at least Mono and + Roslyn) will + + This is the key scenario we care about, + because it's the most natural to use with ForEach. (The other scenarios we + include because users may adopt them as workarounds.) + + LocalFunction: Using a local function defined in the same function where the + ForEach is called. + + (Static)Method: An ordinary (static) class method. Aside from lack of access + to locals (and `this` for statics), these should behave identically to local + functions. + + "Cached": Because the compilers don't currently cache delegates auto-created + for anything except lambdas, we'll generate garbage every frame for all + operations. So we manually cache in order to test just the closure alloc + behavior. + +Tests: (some combos that are impossible are left out) + + Empty: just an empty code block + + WithLocal: a closure that captures a local + + WithThis: a closure that captures `this` + + WithStatic: a method that uses a static +*/ + +namespace Unity.Entities.Tests.ForEach +{ + class ForEachLambdaMemoryTests : ForEachMemoryTestFixtureBase + { + int InvokeEmpty() + { + TestInvoke(v => { }); + return 0; + } + + [Test] + public void Empty_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + int InvokeWithLocal() + { + int local = 2; + TestInvoke(v => { local += v; }); + return local; + } + + [Test] + public void WithLocal_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithLocal(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal += InvokeWithLocal(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(4, firstCallTotal); + Assert.AreEqual(20, loopedCallTotal); + } + + int InvokeWithThis() + { + TestInvoke(v => { m_Field += v; }); + return m_Field; + } + + [Test] + public void WithThis_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(5, firstCallTotal); + Assert.AreEqual(15, loopedCallTotal); + } + + int InvokeWithStatic() + { + TestInvoke(v => { s_Static += v; }); + return s_Static; + } + + [Test] + public void WithStatic_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(6, firstCallTotal); + Assert.AreEqual(16, loopedCallTotal); + } + + } + + class ForEachLocalFunctionMemoryTests : ForEachMemoryTestFixtureBase + { + int InvokeEmpty() + { + void Empty(int v) { } + TestInvoke(Empty); + return 0; + } + + [Test] + [Ignore("Unstable")] + public void Empty_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + int InvokeWithLocal() + { + int local = 2; + void WithLocal(int v) { local += v; } + TestInvoke(WithLocal); + return local; + } + + [Test] + [Ignore("Unstable")] + public void WithLocal_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithLocal(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal += InvokeWithLocal(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + int InvokeWithThis() + { + void WithThis(int v) { m_Field += v; } + TestInvoke(WithThis); + return m_Field; + } + + [Test] + public void WithThis_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(5, firstCallTotal); + Assert.AreEqual(15, loopedCallTotal); + } + + int InvokeWithStatic() + { + void WithStatic(int v) { s_Static += v; } + TestInvoke(WithStatic); + return s_Static; + } + + [Test] + [Ignore("Unstable")] + public void WithStatic_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(6, firstCallTotal); + Assert.AreEqual(16, loopedCallTotal); + } + + } + + class ForEachLocalFunctionCachedMemoryTests : ForEachMemoryTestFixtureBase + { + TestDelegate m_EmptyDelegate; + int InvokeEmpty() + { + void Empty(int v) { } + TestInvoke(m_EmptyDelegate = m_EmptyDelegate ?? Empty); + return 0; + } + + [Test] + public void Empty_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + TestDelegate m_WithThisDelegate; + int InvokeWithThis() + { + void WithThis(int v) { m_Field += v; } + TestInvoke(m_WithThisDelegate = m_WithThisDelegate ?? WithThis); + return m_Field; + } + + [Test] + public void WithThis_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(5, firstCallTotal); + Assert.AreEqual(15, loopedCallTotal); + } + + TestDelegate m_WithStaticDelegate; + int InvokeWithStatic() + { + void WithStatic(int v) { s_Static += v; } + TestInvoke(m_WithStaticDelegate = m_WithStaticDelegate ?? WithStatic); + return s_Static; + } + + [Test] + public void WithStatic_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(6, firstCallTotal); + Assert.AreEqual(16, loopedCallTotal); + } + + } + + class ForEachMethodMemoryTests : ForEachMemoryTestFixtureBase + { + void MethodEmpty(int v) { } + + int InvokeEmpty() + { + TestInvoke(MethodEmpty); + return 0; + } + + [Test] + public void Empty_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + void MethodWithThis(int v) { m_Field += v; } + + int InvokeWithThis() + { + TestInvoke(MethodWithThis); + return m_Field; + } + + [Test] + public void WithThis_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(5, firstCallTotal); + Assert.AreEqual(15, loopedCallTotal); + } + + void MethodWithStatic(int v) { s_Static += v; } + + int InvokeWithStatic() + { + TestInvoke(MethodWithStatic); + return s_Static; + } + + [Test] + public void WithStatic_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(6, firstCallTotal); + Assert.AreEqual(16, loopedCallTotal); + } + + } + + class ForEachMethodCachedMemoryTests : ForEachMemoryTestFixtureBase + { + TestDelegate m_EmptyDelegate; + void MethodEmpty(int v) { } + + int InvokeEmpty() + { + TestInvoke(m_EmptyDelegate = m_EmptyDelegate ?? MethodEmpty); + return 0; + } + + [Test] + public void Empty_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + TestDelegate m_WithThisDelegate; + void MethodWithThis(int v) { m_Field += v; } + + int InvokeWithThis() + { + TestInvoke(m_WithThisDelegate = m_WithThisDelegate ?? MethodWithThis); + return m_Field; + } + + [Test] + public void WithThis_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithThis(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(5, firstCallTotal); + Assert.AreEqual(15, loopedCallTotal); + } + + TestDelegate m_WithStaticDelegate; + void MethodWithStatic(int v) { s_Static += v; } + + int InvokeWithStatic() + { + TestInvoke(m_WithStaticDelegate = m_WithStaticDelegate ?? MethodWithStatic); + return s_Static; + } + + [Test] + public void WithStatic_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(6, firstCallTotal); + Assert.AreEqual(16, loopedCallTotal); + } + + } + + class ForEachStaticMethodMemoryTests : ForEachMemoryTestFixtureBase + { + static void StaticMethodEmpty(int v) { } + + int InvokeEmpty() + { + TestInvoke(StaticMethodEmpty); + return 0; + } + + [Test] + public void Empty_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + static void StaticMethodWithStatic(int v) { s_Static += v; } + + int InvokeWithStatic() + { + TestInvoke(StaticMethodWithStatic); + return s_Static; + } + + [Test] + public void WithStatic_ShouldAllocEveryCall() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.AreEqual(firstCallAllocCount * 5, loopedCallAllocCount); + + Assert.AreEqual(6, firstCallTotal); + Assert.AreEqual(16, loopedCallTotal); + } + + } + + class ForEachStaticMethodCachedMemoryTests : ForEachMemoryTestFixtureBase + { + TestDelegate m_EmptyDelegate; + static void StaticMethodEmpty(int v) { } + + int InvokeEmpty() + { + TestInvoke(m_EmptyDelegate = m_EmptyDelegate ?? StaticMethodEmpty); + return 0; + } + + [Test] + public void Empty_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeEmpty(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(0, firstCallTotal); + Assert.AreEqual(0, loopedCallTotal); + } + + TestDelegate m_WithStaticDelegate; + static void StaticMethodWithStatic(int v) { s_Static += v; } + + int InvokeWithStatic() + { + TestInvoke(m_WithStaticDelegate = m_WithStaticDelegate ?? StaticMethodWithStatic); + return s_Static; + } + + [Test] + public void WithStatic_ShouldAllocFirstCallOnly() + { + AllocRecorder.enabled = true; + var firstCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < 5; ++i) + loopedCallTotal = InvokeWithStatic(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); + Assert.Zero(loopedCallAllocCount); + + Assert.AreEqual(6, firstCallTotal); + Assert.AreEqual(16, loopedCallTotal); + } + + } + +} +#endif // !UNITY_ZEROPLAYER diff --git a/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.gen.cs.meta b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.gen.cs.meta new file mode 100644 index 00000000..ea41a907 --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.gen.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b99fa878950225049b0139e443740796 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.tt b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.tt new file mode 100644 index 00000000..d78a315b --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.tt @@ -0,0 +1,214 @@ +<#/*THIS IS A T4 FILE - see HACKING.md for what it is and how to run codegen*/#> +<#@ assembly name="System.Collections" #> +<#@ assembly name="System.Core" #> +<#@ assembly name="System.Linq" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Linq" #> +<#@ output extension=".gen.cs" #> +#if !UNITY_ZEROPLAYER +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +// Generated by ForEachDelegateMemoryTests.tt + +using NUnit.Framework; + +/* +The purpose of these tests is to validate and make invariant assumptions about +compiler codegen. ForEach needs to receive a delegate, and there are many ways +to implicitly construct one, which are tested below. What we want is to ensure +that we understand the scenarios that generate garbage every frame so we can +detect and warn about them in user code, or replace with our own codegen. + +There are two paths to garbage: + +1. ForEach needs to receive a delegate to do its work, which is represented in + the runtime as a MulticastDelegate. This needs to be allocated from the + gc, and it is not done statically, but on-demand. + + The result of this `newobj` may always be cached manually, and sometimes is + cached automatically. That's one of the things the below tests validate. + +2. In a closure, something needs to associate all captured non-global + variables (including `this`) with the delegate, typically a codegen'd class + with captures as members. This will involve a gc alloc per-call. + + Note that local functions use a struct for their captures when called in + the containing method, but this optimization does not apply if the local is + converted to a delegate. + +Categories: (each has a fixture) + + Lambda: Using the () => {} syntax. Current C# compilers (at least Mono and + Roslyn) will + + This is the key scenario we care about, + because it's the most natural to use with ForEach. (The other scenarios we + include because users may adopt them as workarounds.) + + LocalFunction: Using a local function defined in the same function where the + ForEach is called. + + (Static)Method: An ordinary (static) class method. Aside from lack of access + to locals (and `this` for statics), these should behave identically to local + functions. + + "Cached": Because the compilers don't currently cache delegates auto-created + for anything except lambdas, we'll generate garbage every frame for all + operations. So we manually cache in order to test just the closure alloc + behavior. + +Tests: (some combos that are impossible are left out) + + Empty: just an empty code block + + WithLocal: a closure that captures a local + + WithThis: a closure that captures `this` + + WithStatic: a method that uses a static +*/ + +namespace Unity.Entities.Tests.ForEach +{ +<# +const int k_Loops = 5; + +foreach (var fixture in new[] { + // spec: bool allocEveryCall, int firstCallTotal, int loopedCallTotal + // invoke: 0 = test.name, 1 = test.code + (type: "Lambda", invoke: "v => {1}", + empty: new Spec(false, 0, 0), + local: new Spec( true, 4, 20), + thiz: new Spec( true, 5, 15), + statik: new Spec(false, 6, 16)), + (type: "LocalFunction", invoke: "{0}", + empty: new Spec(false, 0, 0) { Disabled = "Unstable" }, + local: new Spec( true, 0, 0) { Disabled = "Unstable" }, + thiz: new Spec( true, 5, 15), + statik: new Spec( true, 6, 16) { Disabled = "Unstable" }), // << loopedCallAllocCount doesn't match expected + (type: "LocalFunctionCached", invoke: "m_{0}Delegate = m_{0}Delegate ?? {0}", + empty: new Spec(false, 0, 0), + local: null, // new Spec( true, 0, 0), + thiz: new Spec(false, 5, 15), + statik: new Spec(false, 6, 16)), + (type: "Method", invoke: "Method{0}", + empty: new Spec( true, 0, 0), + local: null, + thiz: new Spec( true, 5, 15), + statik: new Spec( true, 6, 16)), + (type: "MethodCached", invoke: "m_{0}Delegate = m_{0}Delegate ?? Method{0}", + empty: new Spec(false, 0, 0), + local: null, + thiz: new Spec(false, 5, 15), + statik: new Spec(false, 6, 16)), + (type: "StaticMethod", invoke: "StaticMethod{0}", + empty: new Spec( true, 0, 0), + local: null, + thiz: null, + statik: new Spec( true, 6, 16)), + (type: "StaticMethodCached", invoke: "m_{0}Delegate = m_{0}Delegate ?? StaticMethod{0}", + empty: new Spec(false, 0, 0), + local: null, + thiz: null, + statik: new Spec(false, 6, 16)) }) { + + // TODO: fix unstable commented-out Spec stuff above + + var tests = new[] { + (name: "Empty", spec: fixture.empty, code: "{ }", retval: "0"), + (name: "WithLocal", spec: fixture.local, code: "{ local += v; }", retval: "local"), + (name: "WithThis", spec: fixture.thiz, code: "{ m_Field += v; }", retval: "m_Field"), + (name: "WithStatic", spec: fixture.statik, code: "{ s_Static += v; }", retval: "s_Static") }; +#> + class ForEach<#=fixture.type#>MemoryTests : ForEachMemoryTestFixtureBase + { +<# + foreach (var test in tests) { + if (test.spec == null) + continue; + string member = null; + if (fixture.type.StartsWith("Method")) + member = $"void Method{test.name}(int v) {test.code}"; + else if (fixture.type.StartsWith("StaticMethod")) + member = $"static void StaticMethod{test.name}(int v) {test.code}"; + if (fixture.type.EndsWith("Cached")) {#> + TestDelegate m_<#=test.name#>Delegate; +<# } + if (member != null) {#> + <#=member#> + +<# }#> + int Invoke<#=test.name#>() + { +<# if (test.name == "WithLocal") {#> + int local = 2; +<# }#> +<# if (fixture.type.StartsWith("LocalFunction")) {#> + void <#=test.name#>(int v) <#=test.code#> +<# }#> + TestInvoke(<#=string.Format(fixture.invoke, test.name, test.code)#>); + return <#=test.retval#>; + } + + [Test] +<# if (test.spec.Disabled != null) {#> + [Ignore("<#=test.spec.Disabled#>")] +<# }#> + public void <#=test.name#>_ShouldAlloc<#=test.spec.AllocEveryCall ? "EveryCall" : "FirstCallOnly"#>() + { + AllocRecorder.enabled = true; + var firstCallTotal = Invoke<#=test.name#>(); + AllocRecorder.enabled = false; + var firstCallAllocCount = AllocRecorder.sampleBlockCount; + + AllocRecorder.enabled = true; + var loopedCallTotal = 0; + for (var i = 0; i < <#=k_Loops#>; ++i) + loopedCallTotal <#=test.name == "WithLocal" ? "+=" : "="#> Invoke<#=test.name#>(); + AllocRecorder.enabled = false; + var loopedCallAllocCount = AllocRecorder.sampleBlockCount; + + Assert.Greater(firstCallAllocCount, 0); +<# if (test.spec.AllocEveryCall) {#> + Assert.AreEqual(firstCallAllocCount * <#=k_Loops#>, loopedCallAllocCount); +<# } else {#> + Assert.Zero(loopedCallAllocCount); +<# }#> + + Assert.AreEqual(<#=test.spec.FirstCallTotal#>, firstCallTotal); + Assert.AreEqual(<#=test.spec.LoopedCallTotal#>, loopedCallTotal); + } + +<# }#> + } + +<#}#> +} +#endif // !UNITY_ZEROPLAYER +<#+ + +class Spec +{ + public bool AllocEveryCall; + + // these counts are just used to validate that the delegates are called the expected number of times + public int FirstCallTotal; + public int LoopedCallTotal; + + public string Disabled; + + public Spec(bool allocEveryCall, int firstCallTotal, int loopedCallTotal) + { + AllocEveryCall = allocEveryCall; + FirstCallTotal = firstCallTotal; + LoopedCallTotal = loopedCallTotal; + } +} + +#> diff --git a/Unity.Entities/EntityQueryBuilder.tt.meta b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.tt.meta similarity index 74% rename from Unity.Entities/EntityQueryBuilder.tt.meta rename to Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.tt.meta index ec9bb529..3a692fd5 100644 --- a/Unity.Entities/EntityQueryBuilder.tt.meta +++ b/Unity.Entities.Tests/ForEach/ForEachDelegateMemoryTests.tt.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: df0a5c4fe61ce2c42bcab398bb71d5ce +guid: 2593083696dc6c341b5525d68f1597bc DefaultImporter: externalObjects: {} userData: diff --git a/Unity.Entities.Tests/ForEachTests.cs b/Unity.Entities.Tests/ForEach/ForEachGeneralTests.cs similarity index 55% rename from Unity.Entities.Tests/ForEachTests.cs rename to Unity.Entities.Tests/ForEach/ForEachGeneralTests.cs index 0156601e..21d0e92f 100644 --- a/Unity.Entities.Tests/ForEachTests.cs +++ b/Unity.Entities.Tests/ForEach/ForEachGeneralTests.cs @@ -1,7 +1,7 @@ using System; using NUnit.Framework; -namespace Unity.Entities.Tests +namespace Unity.Entities.Tests.ForEach { class ForEachBasicTests : EntityQueryBuilderTestFixture { @@ -9,10 +9,47 @@ class ForEachBasicTests : EntityQueryBuilderTestFixture public void CreateTestEntities() { m_Manager.AddComponentData(m_Manager.CreateEntity(), new EcsTestData(5)); + m_Manager.CreateEntity(typeof(EcsTestTag)); m_Manager.AddSharedComponentData(m_Manager.CreateEntity(), new SharedData1(7)); m_Manager.CreateEntity(typeof(EcsIntElement)); } + [Test, Repeat(2)] + public void Ensure_CacheClearedBetweenTests() // sanity check + { + Assert.IsNull(TestSystem.EntityQueryCache); + + var counter = 0; + TestSystem.Entities.ForEach(e => ++counter); + Assert.AreEqual(4, counter); + } + + [Test] + public void Ensure_EachElementOfEntityQueryBuilder_UsedInHashing() + { + // re-run should not change hash + for (var i = 0; i < 2; ++i) + { + // variance in 'all' should change hash + TestSystem.Entities.WithAll().ForEach(e => { }); + TestSystem.Entities.WithAll().ForEach(e => { }); + + // variance in 'any' should change hash + TestSystem.Entities.WithAny().ForEach(e => { }); + TestSystem.Entities.WithAny().ForEach(e => { }); + + // variance in 'none' should change hash + TestSystem.Entities.WithNone().ForEach(e => { }); + TestSystem.Entities.WithNone().ForEach(e => { }); + + // variance in delegate params should change hash + TestSystem.Entities.WithNone().ForEach((ref EcsTestData2 d) => { }); + TestSystem.Entities.WithNone().ForEach((ref EcsTestData3 d) => { }); + + Assert.AreEqual(8, TestSystem.EntityQueryCache.CalcUsedCacheCount()); + } + } + [Test] public void All() { @@ -22,7 +59,7 @@ public void All() Assert.IsTrue(m_Manager.Exists(entity)); counter++; }); - Assert.AreEqual(3, counter); + Assert.AreEqual(4, counter); } [Test] @@ -78,6 +115,14 @@ public void DynamicBuffer() }); Assert.AreEqual(1, counter); } + + [Test] + public void EmptyComponentData() // "tag" + { + var counter = 0; + TestSystem.Entities.WithAll().ForEach(entity => ++counter); + Assert.AreEqual(1, counter); + } } class ForEachTests : EntityQueryBuilderTestFixture @@ -106,6 +151,57 @@ public void Many() Assert.AreEqual(1, counter); } + [Test] + public void MixingWithAllAndForEach_Throws() + { + Assert.Throws(() => + { + TestSystem.Entities.WithAll().ForEach((Entity e, ref EcsTestData2 t1) => + { + Assert.Fail(); + }); + }); + } + + [Test] + public void MixingNoneAndAll_Throws() + { + Assert.Throws(() => + { + TestSystem.Entities.WithNone().ForEach((Entity e, ref EcsTestData2 t1) => + { + Assert.Fail(); + }); + }); + } + + [Test] + public void UsingAnyInForEach_Matches() + { + m_Manager.CreateEntity(typeof(EcsTestData)); + m_Manager.CreateEntity(typeof(EcsTestData2)); + m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); + + var counter = 0; + TestSystem.Entities + .WithAny() + .ForEach(e => ++counter); + Assert.AreEqual(counter, 3); + + } + + [Test] + public void MixingAnyWithForEachDelegateParams_Throws() + { + Assert.Throws(() => + { + TestSystem.Entities.WithAny().ForEach((ref EcsTestData t1) => + { + Assert.Fail(); + }); + }); + } + [Test] public void Safety() { @@ -127,8 +223,9 @@ public void Safety() { TestSystem.Entities.ForEach((Entity e, ref EcsTestData t0) => throw new ArgumentException()); }); - +#if ENABLE_UNITY_COLLECTIONS_CHECKS Assert.IsFalse(m_Manager.IsInsideForEach); +#endif } //@TODO: Class iterator test coverage... diff --git a/Unity.Entities.Tests/ForEach/ForEachGeneralTests.cs.meta b/Unity.Entities.Tests/ForEach/ForEachGeneralTests.cs.meta new file mode 100644 index 00000000..3e8abc4c --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachGeneralTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9723439e4511f2a4aa9aa750e04775cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities.Tests/ForEach/ForEachMemoryTestFixtureBase.cs b/Unity.Entities.Tests/ForEach/ForEachMemoryTestFixtureBase.cs new file mode 100644 index 00000000..02508a26 --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachMemoryTestFixtureBase.cs @@ -0,0 +1,62 @@ +#if !UNITY_ZEROPLAYER +using System; +using System.Linq; +using System.Reflection; +using NUnit.Framework; +using UnityEngine.Profiling; + +namespace Unity.Entities.Tests.ForEach +{ + class ForEachMemoryTestFixtureBase : EntityQueryBuilderTestFixture + { + // TODO: implement equivalent in DOTS runtime and remove #if !UNITY_ZEROPLAYER from all ForEach memory tests + Recorder m_AllocRecorder; + + protected int m_Field; + protected static int s_Static; + + [SetUp] + public void SetUp() + { + m_AllocRecorder = Recorder.Get("GC.Alloc"); + m_AllocRecorder.FilterToCurrentThread(); + m_AllocRecorder.enabled = false; + + m_Field = 3; + s_Static = 4; + } + + [TearDown] + public new void TearDown() + { + // this code is necessary to make our tests re-runnable without requiring a domain reload. + // lambdas only provide code, and we're operating with delegates in ForEach, which require + // an alloc to create. the c# compiler generates code to alloc the delegate on first use, + // and then stores it in a static for later reuse. we need to clear those statics in order + // to rerun the tests. + + var cache = GetType().GetNestedType("<>c", BindingFlags.NonPublic); + if (cache != null) + { + foreach (var field in cache + .GetFields(BindingFlags.Static | BindingFlags.Public) + .Where(f => typeof(MulticastDelegate).IsAssignableFrom(f.FieldType))) + { + field.SetValue(null, null); + } + } + } + + protected Recorder AllocRecorder => m_AllocRecorder; + + protected delegate void TestDelegate(int i); + + protected void TestInvoke(TestDelegate op) + { + // simulate more than one iteration + op(1); + op(1); + } + } +} +#endif // !UNITY_ZEROPLAYER diff --git a/Unity.Entities.Tests/ForEach/ForEachMemoryTestFixtureBase.cs.meta b/Unity.Entities.Tests/ForEach/ForEachMemoryTestFixtureBase.cs.meta new file mode 100644 index 00000000..fe51948f --- /dev/null +++ b/Unity.Entities.Tests/ForEach/ForEachMemoryTestFixtureBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 60f00a90d39638042a2984d05e17c25e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities.Tests/ForEachTests.cs.meta b/Unity.Entities.Tests/ForEachTests.cs.meta deleted file mode 100644 index a5567c60..00000000 --- a/Unity.Entities.Tests/ForEachTests.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fbe615a9e67b4d049bdc94d3655cf536 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities.Tests/IJobChunkTests.cs b/Unity.Entities.Tests/IJobChunkTests.cs index 37987ee2..a0cb2ea7 100644 --- a/Unity.Entities.Tests/IJobChunkTests.cs +++ b/Unity.Entities.Tests/IJobChunkTests.cs @@ -25,7 +25,7 @@ public void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset) public void IJobChunkProcess() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); - var group = m_Manager.CreateComponentGroup(new EntityArchetypeQuery + var group = m_Manager.CreateEntityQuery(new EntityQueryDesc { Any = Array.Empty(), None = Array.Empty(), @@ -47,7 +47,7 @@ public void IJobChunkProcess() public void IJobChunkProcessFiltered() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); var entity1 = m_Manager.CreateEntity(archetype); var entity2 = m_Manager.CreateEntity(archetype); @@ -76,7 +76,7 @@ public void IJobChunkProcessFiltered() public void IJobChunkWithEntityOffsetCopy() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2)); var entities = new NativeArray(50000, Allocator.Temp); m_Manager.CreateEntity(archetype, entities); @@ -127,7 +127,7 @@ public void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset) public void IJobChunkProcessChunkIndex() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); var entity1 = m_Manager.CreateEntity(archetype); var entity2 = m_Manager.CreateEntity(archetype); @@ -160,7 +160,7 @@ public void IJobChunkProcessChunkIndex() public void IJobChunkProcessEntityOffset() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); var entity1 = m_Manager.CreateEntity(archetype); var entity2 = m_Manager.CreateEntity(archetype); @@ -203,7 +203,7 @@ public void IJobChunkProcessChunkMultiArchetype() var entityC = m_Manager.CreateEntity(archetypeC); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); m_Manager.SetComponentData(entity1A, new EcsTestData { value = -1 }); m_Manager.SetComponentData(entity2A, new EcsTestData { value = -1 }); @@ -222,5 +222,75 @@ public void IJobChunkProcessChunkMultiArchetype() group.Dispose(); } + + #if !UNITY_ZEROPLAYER + struct ProcessChunkWriteIndex : IJobChunk + { + public ArchetypeChunkComponentType ecsTestType; + + public void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset) + { + var testDataArray = chunk.GetNativeArray(ecsTestType); + for (int i = 0; i < chunk.Count; ++i) + { + testDataArray[i] = new EcsTestData + { + value = entityOffset + i + }; + } + } + } + + struct ForEachComponentData : IJobForEachWithEntity + { + public void Execute(Entity entity, int index, ref EcsTestData c0) + { + c0 = new EcsTestData { value = index }; + } + } + + [Test] + public void FilteredIJobChunkProcessesSameChunksAsFilteredJobForEach() + { + var archetypeA = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); + var archetypeB = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestSharedComp)); + + var entitiesA = new NativeArray(5000, Allocator.Temp); + m_Manager.CreateEntity(archetypeA, entitiesA); + + var entitiesB = new NativeArray(5000, Allocator.Temp); + m_Manager.CreateEntity(archetypeA, entitiesB); + + for (int i = 0; i < 5000; ++i) + { + m_Manager.SetSharedComponentData(entitiesA[i], new EcsTestSharedComp { value = i % 8 }); + m_Manager.SetSharedComponentData(entitiesB[i], new EcsTestSharedComp { value = i % 8 }); + } + + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestSharedComp)); + + group.SetFilter(new EcsTestSharedComp { value = 1 }); + + var jobChunk = new ProcessChunkWriteIndex + { + ecsTestType = m_Manager.GetArchetypeChunkComponentType(false) + }; + jobChunk.Schedule(group).Complete(); + + var componentArrayA = group.ToComponentDataArray(Allocator.TempJob); + + var jobProcess = new ForEachComponentData + {}; + jobProcess.Schedule(group).Complete(); + + var componentArrayB = group.ToComponentDataArray(Allocator.TempJob); + + CollectionAssert.AreEqual(componentArrayA.ToArray(), componentArrayB.ToArray()); + + componentArrayA.Dispose(); + componentArrayB.Dispose(); + group.Dispose(); + } +#endif } } diff --git a/Unity.Entities.Tests/IJobProcessComponentDataCombinationsTests.cs b/Unity.Entities.Tests/IJobForEachCombinationsTests.cs similarity index 83% rename from Unity.Entities.Tests/IJobProcessComponentDataCombinationsTests.cs rename to Unity.Entities.Tests/IJobForEachCombinationsTests.cs index 15658523..f4c4c298 100644 --- a/Unity.Entities.Tests/IJobProcessComponentDataCombinationsTests.cs +++ b/Unity.Entities.Tests/IJobForEachCombinationsTests.cs @@ -1,12 +1,11 @@ -#if !UNITY_ZEROPLAYER -using NUnit.Framework; +using NUnit.Framework; using Unity.Collections; namespace Unity.Entities.Tests { - class IJobProcessComponentDataCombinationsTests : ECSTestsFixture + class IJobForEachCombinationsTests : ECSTestsFixture { - struct Process1 : IJobProcessComponentData + struct Process1 : IJobForEach { public void Execute(ref EcsTestData value) { @@ -14,7 +13,7 @@ public void Execute(ref EcsTestData value) } } - struct Process2 : IJobProcessComponentData + struct Process2 : IJobForEach { public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst) { @@ -22,7 +21,7 @@ public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst) } } - struct Process3 : IJobProcessComponentData + struct Process3 : IJobForEach { public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst1, ref EcsTestData3 dst2) { @@ -30,7 +29,7 @@ public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst1, ref Ec } } - struct Process4 : IJobProcessComponentData + struct Process4 : IJobForEach { public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst1, ref EcsTestData3 dst2, ref EcsTestData4 dst3) { @@ -38,7 +37,7 @@ public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst1, ref Ec } } - struct Process1Entity : IJobProcessComponentDataWithEntity + struct Process1Entity : IJobForEachWithEntity { public void Execute(Entity entity, int index, ref EcsTestData value) { @@ -46,7 +45,7 @@ public void Execute(Entity entity, int index, ref EcsTestData value) } } - struct Process2Entity : IJobProcessComponentDataWithEntity + struct Process2Entity : IJobForEachWithEntity { public void Execute(Entity entity, int index, [ReadOnly]ref EcsTestData src, ref EcsTestData2 dst) { @@ -54,7 +53,7 @@ public void Execute(Entity entity, int index, [ReadOnly]ref EcsTestData src, ref } } - struct Process3Entity : IJobProcessComponentDataWithEntity + struct Process3Entity : IJobForEachWithEntity { public void Execute(Entity entity, int index, [ReadOnly]ref EcsTestData src, ref EcsTestData2 dst1, ref EcsTestData3 dst2) { @@ -62,7 +61,7 @@ public void Execute(Entity entity, int index, [ReadOnly]ref EcsTestData src, ref } } - struct Process4Entity : IJobProcessComponentDataWithEntity + struct Process4Entity : IJobForEachWithEntity { public void Execute(Entity entity, int index, [ReadOnly]ref EcsTestData src, ref EcsTestData2 dst1, ref EcsTestData3 dst2, ref EcsTestData4 dst3) { @@ -77,14 +76,16 @@ public enum ProcessMode Run } - void Schedule(ProcessMode mode) where T : struct, JobProcessComponentDataExtensions.IBaseJobProcessComponentData + void Schedule(ProcessMode mode) where T : struct, JobForEachExtensions.IBaseJobForEach { +#if !UNITY_ZEROPLAYER if (mode == ProcessMode.Parallel) new T().Schedule(EmptySystem).Complete(); else if (mode == ProcessMode.Run) new T().Run(EmptySystem); else new T().ScheduleSingle(EmptySystem).Complete(); +#endif } NativeArray PrepareData(int entityCount) @@ -138,14 +139,17 @@ public void JobProcessStress_1([Values]ProcessMode mode, [Values(0, 1, 1000)]int var entities = new NativeArray(entityCount, Allocator.Temp); m_Manager.CreateEntity(archetype, entities); +#if UNITY_ZEROPLAYER + (new Process1()).Schedule(EmptySystem); +#else Schedule(mode); - +#endif for (int i = 0; i < entities.Length; i++) Assert.AreEqual(1, m_Manager.GetComponentData(entities[i]).value); entities.Dispose(); } - + [Test] public void JobProcessStress_1_WithEntity([Values]ProcessMode mode, [Values(0, 1, 1000)]int entityCount) { @@ -153,7 +157,11 @@ public void JobProcessStress_1_WithEntity([Values]ProcessMode mode, [Values(0, 1 var entities = new NativeArray(entityCount, Allocator.Temp); m_Manager.CreateEntity(archetype, entities); +#if UNITY_ZEROPLAYER + (new Process1Entity()).Schedule(EmptySystem); +#else Schedule(mode); +#endif for (int i = 0; i < entities.Length; i++) Assert.AreEqual(i + entities[i].Index, m_Manager.GetComponentData(entities[i]).value); @@ -166,8 +174,11 @@ public void JobProcessStress_2([Values]ProcessMode mode, [Values(0, 1, 1000)]int { var entities = PrepareData(entityCount); +#if UNITY_ZEROPLAYER + (new Process2()).Schedule(EmptySystem); +#else Schedule(mode); - +#endif CheckResultsAndDispose(entities, 2, false); } @@ -176,7 +187,11 @@ public void JobProcessStress_2_WithEntity([Values]ProcessMode mode, [Values(0, 1 { var entities = PrepareData(entityCount); +#if UNITY_ZEROPLAYER + (new Process2Entity()).Schedule(EmptySystem); +#else Schedule(mode); +#endif CheckResultsAndDispose(entities, 2, true); @@ -187,7 +202,11 @@ public void JobProcessStress_3([Values]ProcessMode mode, [Values(0, 1, 1000)]int { var entities = PrepareData(entityCount); +#if UNITY_ZEROPLAYER + (new Process3()).Schedule(EmptySystem); +#else Schedule(mode); +#endif CheckResultsAndDispose(entities, 3, false); } @@ -197,8 +216,11 @@ public void JobProcessStress_3_WithEntity([Values]ProcessMode mode, [Values(0, 1 { var entities = PrepareData(entityCount); +#if UNITY_ZEROPLAYER + (new Process3Entity()).Schedule(EmptySystem); +#else Schedule(mode); - +#endif CheckResultsAndDispose(entities, 3, true); } @@ -207,8 +229,11 @@ public void JobProcessStress_4([Values]ProcessMode mode, [Values(0, 1, 1000)]int { var entities = PrepareData(entityCount); +#if UNITY_ZEROPLAYER + (new Process4()).Schedule(EmptySystem); +#else Schedule(mode); - +#endif CheckResultsAndDispose(entities, 4, false); } @@ -217,10 +242,12 @@ public void JobProcessStress_4_WithEntity([Values]ProcessMode mode, [Values(0, 1 { var entities = PrepareData(entityCount); +#if UNITY_ZEROPLAYER + (new Process4Entity()).Schedule(EmptySystem); +#else Schedule(mode); - +#endif CheckResultsAndDispose(entities, 4, true); } } } -#endif \ No newline at end of file diff --git a/Unity.Entities.Tests/IJobProcessComponentDataCombinationsTests.cs.meta b/Unity.Entities.Tests/IJobForEachCombinationsTests.cs.meta similarity index 100% rename from Unity.Entities.Tests/IJobProcessComponentDataCombinationsTests.cs.meta rename to Unity.Entities.Tests/IJobForEachCombinationsTests.cs.meta diff --git a/Unity.Entities.Tests/IJobProcessComponentDataTests.cs b/Unity.Entities.Tests/IJobForEachTests.cs similarity index 78% rename from Unity.Entities.Tests/IJobProcessComponentDataTests.cs rename to Unity.Entities.Tests/IJobForEachTests.cs index d2298ef7..20fd6f15 100644 --- a/Unity.Entities.Tests/IJobProcessComponentDataTests.cs +++ b/Unity.Entities.Tests/IJobForEachTests.cs @@ -6,9 +6,9 @@ namespace Unity.Entities.Tests { - public class IJobProcessComponentDataTests :ECSTestsFixture + public class IJobForEachTests :ECSTestsFixture { - struct Process1 : IJobProcessComponentData + struct Process1 : IJobForEach { public void Execute(ref EcsTestData dst) { @@ -16,7 +16,7 @@ public void Execute(ref EcsTestData dst) } } - struct Process2 : IJobProcessComponentData + struct Process2 : IJobForEach { public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst) { @@ -24,14 +24,14 @@ public void Execute([ReadOnly]ref EcsTestData src, ref EcsTestData2 dst) } } - struct Process3Entity : IJobProcessComponentDataWithEntity + struct Process3Entity : IJobForEachWithEntity { public void Execute(Entity entity, int index, [ReadOnly]ref EcsTestData src, ref EcsTestData2 dst1, ref EcsTestData3 dst2) { dst1.value1 = dst2.value2 = src.value + index + entity.Index; } } - + [Test] public void JobProcessSimple() { @@ -49,11 +49,11 @@ public void JobProcessComponentGroupCorrect() ComponentType[] expectedTypes = { ComponentType.ReadOnly(), ComponentType.ReadWrite() }; new Process2().Run(EmptySystem); - var group = EmptySystem.GetComponentGroup(expectedTypes); + var group = EmptySystem.GetEntityQuery(expectedTypes); - Assert.AreEqual(1, EmptySystem.ComponentGroups.Length); - Assert.IsTrue(EmptySystem.ComponentGroups[0].CompareComponents(expectedTypes)); - Assert.AreEqual(group, EmptySystem.ComponentGroups[0]); + Assert.AreEqual(1, EmptySystem.EntityQueries.Length); + Assert.IsTrue(EmptySystem.EntityQueries[0].CompareComponents(expectedTypes)); + Assert.AreEqual(group, EmptySystem.EntityQueries[0]); } @@ -72,11 +72,11 @@ public void JobProcessComponentGroupCorrectNativeArrayOfComponentTypes() componentTypes[0] = ComponentType.ReadOnly(componentTypes[0].TypeIndex); - var group = EmptySystem.GetComponentGroup(componentTypes); + var group = EmptySystem.GetEntityQuery(componentTypes); - Assert.AreEqual(1, EmptySystem.ComponentGroups.Length); - Assert.IsTrue(EmptySystem.ComponentGroups[0].CompareComponents(componentTypes)); - Assert.AreEqual(group, EmptySystem.ComponentGroups[0]); + Assert.AreEqual(1, EmptySystem.EntityQueries.Length); + Assert.IsTrue(EmptySystem.EntityQueries[0].CompareComponents(componentTypes)); + Assert.AreEqual(group, EmptySystem.EntityQueries[0]); componentTypes.Dispose(); } @@ -87,11 +87,11 @@ public void JobProcessComponentWithEntityGroupCorrect() ComponentType[] expectedTypes = { ComponentType.ReadOnly(), ComponentType.ReadWrite(), ComponentType.ReadWrite() }; new Process3Entity().Run(EmptySystem); - var group = EmptySystem.GetComponentGroup(expectedTypes); + var group = EmptySystem.GetEntityQuery(expectedTypes); - Assert.AreEqual(1, EmptySystem.ComponentGroups.Length); - Assert.IsTrue(EmptySystem.ComponentGroups[0].CompareComponents(expectedTypes)); - Assert.AreEqual(group, EmptySystem.ComponentGroups[0]); + Assert.AreEqual(1, EmptySystem.EntityQueries.Length); + Assert.IsTrue(EmptySystem.EntityQueries[0].CompareComponents(expectedTypes)); + Assert.AreEqual(group, EmptySystem.EntityQueries[0]); } @@ -106,10 +106,10 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) } } [Test] - public void MultipleJobProcessComponentDataCanChain() + public void MultipleJobForEachCanChain() { var entity = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var system = World.GetOrCreateManager(); + var system = World.GetOrCreateSystem(); system.Update(); Assert.AreEqual(7, m_Manager.GetComponentData(entity).value1); } @@ -133,7 +133,7 @@ public void JobWithMissingDependency() [ExcludeComponent(typeof(EcsTestData3))] [RequireComponentTag(typeof(EcsTestData4))] - struct ProcessTagged : IJobProcessComponentData + struct ProcessTagged : IJobForEach { public void Execute(ref EcsTestData src, ref EcsTestData2 dst) { @@ -165,7 +165,7 @@ public void JobProcessAdditionalRequirements() var entityProcess = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData4)); Test(true, entityProcess); } - struct ProcessFilteredData : IJobProcessComponentData + struct ProcessFilteredData : IJobForEach { public void Execute(ref EcsTestData c0) { @@ -174,7 +174,7 @@ public void Execute(ref EcsTestData c0) } [Test] - public void JobProcessWithFilteredComponentGroup() + public void JobProcessWithFilteredEntityQuery() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); @@ -186,11 +186,11 @@ public void JobProcessWithFilteredComponentGroup() m_Manager.SetSharedComponentData(entityInGroupA, new EcsTestSharedComp { value = 1} ); m_Manager.SetSharedComponentData(entityInGroupB, new EcsTestSharedComp { value = 2} ); - var group = EmptySystem.GetComponentGroup(typeof(EcsTestData), typeof(EcsTestSharedComp)); + var group = EmptySystem.GetEntityQuery(typeof(EcsTestData), typeof(EcsTestSharedComp)); group.SetFilter(new EcsTestSharedComp { value = 1}); var processJob = new ProcessFilteredData(); - processJob.ScheduleGroup(group).Complete(); + processJob.Schedule(group).Complete(); Assert.AreEqual(10, m_Manager.GetComponentData(entityInGroupA).value); Assert.AreEqual(5, m_Manager.GetComponentData(entityInGroupB).value); @@ -214,9 +214,19 @@ public void JobCalculateEntityCount() job2.Schedule(EmptySystem).Complete(); } + [Test] + public void JobExcludedComponentExplicitQuery() + { + var group = EmptySystem.GetEntityQuery(ComponentType.Exclude()); + + var handle = new JobHandle(); + Assert.Throws(() => handle = new Process1().Schedule(group)); + handle.Complete(); + } + [Test] [Ignore("TODO")] - public void TestCoverageFor_ComponentSystemBase_InjectNestedIJobProcessComponentDataJobs() + public void TestCoverageFor_ComponentSystemBase_InjectNestedIJobForEachJobs() { } @@ -227,4 +237,4 @@ public void DuplicateComponentTypeParametersThrows() } } } -#endif \ No newline at end of file +#endif diff --git a/Unity.Entities.Tests/IJobProcessComponentDataTests.cs.meta b/Unity.Entities.Tests/IJobForEachTests.cs.meta similarity index 100% rename from Unity.Entities.Tests/IJobProcessComponentDataTests.cs.meta rename to Unity.Entities.Tests/IJobForEachTests.cs.meta diff --git a/Unity.Entities.Tests/IJobProcessComponentInjection.cs b/Unity.Entities.Tests/IJobProcessComponentInjection.cs index 14ca80ff..49f50358 100644 --- a/Unity.Entities.Tests/IJobProcessComponentInjection.cs +++ b/Unity.Entities.Tests/IJobProcessComponentInjection.cs @@ -9,7 +9,7 @@ class IJobProcessComponentInjection : ECSTestsFixture [DisableAutoCreation] class TestSystem : JobComponentSystem { - private struct Process1 : IJobProcessComponentData + private struct Process1 : IJobForEach { public void Execute(ref EcsTestData value) { @@ -17,14 +17,14 @@ public void Execute(ref EcsTestData value) } } - public struct Process2 : IJobProcessComponentData + public struct Process2 : IJobForEach { public void Execute(ref EcsTestData src, ref EcsTestData2 dst) { dst.value1 = src.value; } } - + protected override JobHandle OnUpdate(JobHandle inputDeps) { inputDeps = new Process1().Schedule(this, inputDeps); @@ -34,12 +34,12 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) } [Test] - public void NestedIJobProcessComponentDataAreInjectedDuringOnCreateManager() + public void NestedIJobForEachAreInjectedDuringOnCreate() { m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var system = World.GetOrCreateManager(); - Assert.AreEqual(2, system.ComponentGroups.Length); + var system = World.GetOrCreateSystem(); + Assert.AreEqual(2, system.EntityQueries.Length); } } } -#endif \ No newline at end of file +#endif diff --git a/Unity.Entities.Tests/InjectComponentGroupTests.cs b/Unity.Entities.Tests/InjectComponentGroupTests.cs deleted file mode 100644 index 5182d26e..00000000 --- a/Unity.Entities.Tests/InjectComponentGroupTests.cs +++ /dev/null @@ -1,339 +0,0 @@ -using NUnit.Framework; -using System; -using Unity.Collections; -using Unity.Jobs; - -#pragma warning disable 649 -// Injection is deprecated -#pragma warning disable 618 - -namespace Unity.Entities.Tests -{ - class InjectComponentGroupTests : ECSTestsFixture - { - [DisableAutoCreation] - [AlwaysUpdateSystem] - public class PureEcsTestSystem : ComponentSystem - { - public struct DataAndEntites - { - public ComponentDataArray Data; - public EntityArray Entities; - public readonly int Length; - } - - [Inject] - public DataAndEntites Group; - - protected override void OnUpdate() - { - } - } - - [DisableAutoCreation] - [AlwaysUpdateSystem] - public class PureReadOnlySystem : ComponentSystem - { - public struct Datas - { - [ReadOnly] - public ComponentDataArray Data; - } - - [Inject] - public Datas Group; - - protected override void OnUpdate() - { - } - } - - - - public struct SharedData : ISharedComponentData - { - public int value; - - public SharedData(int val) { value = val; } - } - - [DisableAutoCreation] - [AlwaysUpdateSystem] - public class SharedComponentSystem : ComponentSystem - { - public struct Datas - { - public ComponentDataArray Data; - [ReadOnly] public SharedComponentDataArray SharedData; - } - - [Inject] - public Datas Group; - - protected override void OnUpdate() - { - } - } - - [DisableAutoCreation] - [AlwaysUpdateSystem] - public class ComponentGroupAsPartOfInjectedGroupSystem : ComponentSystem - { - public struct GroupStruct0 - { - public ComponentDataArray Data; - public ComponentDataArray Data2; - public readonly int GroupIndex; - } - - public struct GroupStruct1 - { - public ComponentDataArray Data; - [ReadOnly] public SharedComponentDataArray Shared; - public readonly int GroupIndex; - } - - [Inject] - public GroupStruct0 Group0; - [Inject] - public GroupStruct1 Group1; - - protected override void OnCreateManager() - { - ComponentGroups[Group1.GroupIndex].SetFilter(new EcsTestSharedComp(123)); - } - - protected override void OnUpdate() - { - } - } - - [Test] - [StandaloneFixme] // ISharedComponentData - public void ComponentGroupFromInjectedGroup() - { - var system = World.GetOrCreateManager(); - - var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestSharedComp), typeof(EcsTestData2)); - var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestSharedComp)); - var entity2 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestSharedComp)); - - m_Manager.SetSharedComponentData(entity0, new EcsTestSharedComp(123)); - m_Manager.SetSharedComponentData(entity1, new EcsTestSharedComp(456)); - m_Manager.SetSharedComponentData(entity2, new EcsTestSharedComp(123)); - - var group0 = system.ComponentGroups[system.Group0.GroupIndex]; - var group1 = system.ComponentGroups[system.Group1.GroupIndex]; - - var data0 = group0.GetComponentDataArray(); - var data1 = group1.GetComponentDataArray(); - - Assert.AreEqual(1, data0.Length); - Assert.AreEqual(2, data1.Length); - } - - [Test] - [StandaloneFixme] // AtomicSafety - public void ReadOnlyComponentDataArray() - { - var readOnlySystem = World.GetOrCreateManager (); - - var go = m_Manager.CreateEntity (new ComponentType[0]); - m_Manager.AddComponentData (go, new EcsTestData(2)); - - readOnlySystem.Update (); - Assert.AreEqual (2, readOnlySystem.Group.Data[0].value); - Assert.Throws(()=> { readOnlySystem.Group.Data[0] = new EcsTestData(); }); - } - - - - [Test] - [StandaloneFixme] // ISharedComponentData - public void SharedComponentDataArray() - { - var sharedComponentSystem = World.GetOrCreateManager (); - - var go = m_Manager.CreateEntity(new ComponentType[0]); - m_Manager.AddComponentData (go, new EcsTestData(2)); - m_Manager.AddSharedComponentData(go, new SharedData(3)); - - sharedComponentSystem.Update (); - Assert.AreEqual (1, sharedComponentSystem.Group.Data.Length); - Assert.AreEqual (2, sharedComponentSystem.Group.Data[0].value); - Assert.AreEqual (3, sharedComponentSystem.Group.SharedData[0].value); - } - - - [Test] - [StandaloneFixme] // Real problem - Test failure - public void RemoveComponentGroupTracking() - { - var pureSystem = World.GetOrCreateManager (); - - var go0 = m_Manager.CreateEntity (new ComponentType[0]); - m_Manager.AddComponentData (go0, new EcsTestData(10)); - - var go1 = m_Manager.CreateEntity (); - m_Manager.AddComponentData (go1, new EcsTestData(20)); - - pureSystem.Update (); - Assert.AreEqual (2, pureSystem.Group.Length); - Assert.AreEqual (10, pureSystem.Group.Data[0].value); - Assert.AreEqual (20, pureSystem.Group.Data[1].value); - - m_Manager.RemoveComponent (go0); - - pureSystem.Update (); - Assert.AreEqual (1, pureSystem.Group.Length); - Assert.AreEqual (20, pureSystem.Group.Data[0].value); - - m_Manager.RemoveComponent (go1); - pureSystem.Update (); - Assert.AreEqual (0, pureSystem.Group.Length); - } - - [Test] - [StandaloneFixme] // Real problem - Test failure - public void EntityGroupTracking() - { - var pureSystem = World.GetOrCreateManager (); - - var go = m_Manager.CreateEntity (new ComponentType[0]); - m_Manager.AddComponentData (go, new EcsTestData(2)); - - pureSystem.Update (); - Assert.AreEqual (1, pureSystem.Group.Length); - Assert.AreEqual (1, pureSystem.Group.Data.Length); - Assert.AreEqual (1, pureSystem.Group.Entities.Length); - Assert.AreEqual (2, pureSystem.Group.Data[0].value); - Assert.AreEqual (go, pureSystem.Group.Entities[0]); - } - - [DisableAutoCreation] - public class FromEntitySystemIncrementInJob : JobComponentSystem - { - public struct IncrementValueJob : IJob - { - public Entity entity; - - public ComponentDataFromEntity ecsTestDataFromEntity; - public BufferFromEntity intArrayFromEntity; - - public void Execute() - { - DynamicBuffer array = intArrayFromEntity[entity]; - for (int i = 0; i < array.Length; i++) - array[i] = new EcsIntElement { Value = array[i].Value + 1 }; - - var value = ecsTestDataFromEntity[entity]; - value.value++; - ecsTestDataFromEntity[entity] = value; - } - } - -#pragma warning disable 649 - [Inject] - BufferFromEntity intArrayFromEntity; - - [Inject] - ComponentDataFromEntity ecsTestDataFromEntity; -#pragma warning restore 649 - - public Entity entity; - - protected override JobHandle OnUpdate(JobHandle inputDeps) - { - var job = new IncrementValueJob(); - job.entity = entity; - job.ecsTestDataFromEntity = ecsTestDataFromEntity; - job.intArrayFromEntity = intArrayFromEntity; - - return job.Schedule(inputDeps); - } - } - - [Test] - [StandaloneFixme] // IJob - public void FromEntitySystemIncrementInJobWorks() - { - var system = World.GetOrCreateManager(); - - var entity = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsIntElement)); - - m_Manager.GetBuffer(entity).CopyFrom(new EcsIntElement[] { 0, -1, Int32.MinValue }); - - system.entity = entity; - system.Update(); - system.Update(); - - Assert.AreEqual(2, m_Manager.GetComponentData(entity).value); - Assert.AreEqual(2, m_Manager.GetBuffer(entity)[0].Value); - } - - [DisableAutoCreation] - public class OnCreateManagerComponentGroupInjectionSystem : JobComponentSystem - { - public struct Group - { - public ComponentDataArray Data; - } - - [Inject] - public Group group; - - protected override void OnCreateManager() - { - Assert.AreEqual(1, group.Data.Length); - Assert.AreEqual(42, group.Data[0].value); - } - - protected override JobHandle OnUpdate(JobHandle inputDeps) - { - return inputDeps; - } - } - - [Test] - [StandaloneFixme] // IJob - public void OnCreateManagerComponentGroupInjectionWorks() - { - var entity = m_Manager.CreateEntity (typeof(EcsTestData)); - m_Manager.SetComponentData(entity, new EcsTestData(42)); - World.GetOrCreateManager(); - } - - [DisableAutoCreation] - public class OnDestroyManagerComponentGroupInjectionSystem : JobComponentSystem - { - public struct Group - { - public ComponentDataArray Data; - } - - [Inject] - public Group group; - - protected override void OnDestroyManager() - { - Assert.AreEqual(1, group.Data.Length); - Assert.AreEqual(42, group.Data[0].value); - } - - protected override JobHandle OnUpdate(JobHandle inputDeps) - { - return inputDeps; - } - } - - [Test] - [StandaloneFixme] // IJob - public void OnDestroyManagerComponentGroupInjectionWorks() - { - var system = World.GetOrCreateManager(); - var entity = m_Manager.CreateEntity (typeof(EcsTestData)); - m_Manager.SetComponentData(entity, new EcsTestData(42)); - World.DestroyManager(system); - } - } -} diff --git a/Unity.Entities.Tests/IterationTests.cs b/Unity.Entities.Tests/IterationTests.cs index 20dff2bf..d5950d41 100644 --- a/Unity.Entities.Tests/IterationTests.cs +++ b/Unity.Entities.Tests/IterationTests.cs @@ -8,11 +8,11 @@ namespace Unity.Entities.Tests class IterationTests : ECSTestsFixture { [Test] - public void CreateComponentGroup() + public void CreateEntityQuery() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2)); Assert.AreEqual(0, group.CalculateLength()); var entity = m_Manager.CreateEntity(archetype); @@ -33,7 +33,7 @@ struct TempComponentNeverInstantiated : IComponentData [Test] public void IterateEmptyArchetype() { - var group = m_Manager.CreateComponentGroup(typeof(TempComponentNeverInstantiated)); + var group = m_Manager.CreateEntityQuery(typeof(TempComponentNeverInstantiated)); Assert.AreEqual(0, group.CalculateLength()); var archetype = m_Manager.CreateArchetype(typeof(TempComponentNeverInstantiated)); @@ -45,12 +45,12 @@ public void IterateEmptyArchetype() Assert.AreEqual(0, group.CalculateLength()); } [Test] - public void IterateChunkedComponentGroup() + public void IterateChunkedEntityQuery() { var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData)); var archetype2 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); Assert.AreEqual(0, group.CalculateLength()); Entity[] entities = new Entity[10000]; @@ -87,7 +87,7 @@ public void IterateChunkedComponentGroupBackwards() var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData)); var archetype2 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); Assert.AreEqual(0, group.CalculateLength()); Entity[] entities = new Entity[10000]; @@ -127,7 +127,7 @@ public void IterateChunkedComponentGroupAfterDestroy() var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData)); var archetype2 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); Assert.AreEqual(0, group.CalculateLength()); Entity[] entities = new Entity[10000]; @@ -188,70 +188,6 @@ public void IterateChunkedComponentGroupAfterDestroy() } arr.Dispose(); } - -#pragma warning disable 618 - [Test] - public void IterateEntityArray() - { - var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData)); - var archetype2 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); - - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); - var arr = group.GetEntityArray(); - Assert.AreEqual(0, arr.Length); - - Entity[] entities = new Entity[10000]; - for (int i = 0; i < entities.Length/2;i++) - { - entities[i] = m_Manager.CreateEntity(archetype1); - m_Manager.SetComponentData(entities[i], new EcsTestData(i)); - } - for (int i = entities.Length/2; i < entities.Length;i++) - { - entities[i] = m_Manager.CreateEntity(archetype2); - m_Manager.SetComponentData(entities[i], new EcsTestData(i)); - } - - arr = group.GetEntityArray(); - Assert.AreEqual(entities.Length, arr.Length); - var values = new HashSet(); - for (int i = 0; i < arr.Length;i++) - { - Entity val = arr[i]; - Assert.IsFalse(values.Contains(val)); - values.Add(val); - } - - for (int i = 0; i < entities.Length;i++) - m_Manager.DestroyEntity(entities[i]); - } - - [Test] - public void ComponentDataArrayCopy() - { - var entity = m_Manager.CreateEntity(typeof(EcsTestData)); - - var entities = new NativeArray(20000, Allocator.Persistent); - m_Manager.Instantiate(entity, entities); - - var ecsArray = m_Manager.CreateComponentGroup(typeof(EcsTestData)).GetComponentDataArray(); - - for (int i = 0; i < ecsArray.Length; i++) - ecsArray[i] = new EcsTestData(i); - - var copied = new NativeArray(entities.Length - 11 + 1, Allocator.Persistent); - ecsArray.CopyTo(copied, 11); - - for (int i = 0; i < copied.Length; i++) - { - if (copied[i].value != i) - Assert.AreEqual(i + 11, copied[i].value); - } - - copied.Dispose(); - entities.Dispose(); - } -#pragma warning restore 618 [Test] public void GroupCopyFromNativeArray() @@ -274,7 +210,7 @@ public void GroupCopyFromNativeArray() } - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); group.CopyFromComponentDataArray(dataToCopyA); for (int i = 0; i < dataToCopyA.Length; ++i) @@ -297,7 +233,7 @@ public void ComponentGroupFilteredEntityIndexWithMultipleArchetypes() var archetypeA = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestSharedComp)); var archetypeB = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestSharedComp)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestSharedComp)); var entity1A = m_Manager.CreateEntity(archetypeA); var entity2A = m_Manager.CreateEntity(archetypeA); @@ -314,7 +250,7 @@ public void ComponentGroupFilteredEntityIndexWithMultipleArchetypes() iterator.MoveToChunkWithoutFiltering(2); // 2 is index of chunk iterator.GetCurrentChunkRange(out var begin, out var end ); - Assert.AreEqual(1, begin); // 1 is index of entity in filtered ComponentGroup + Assert.AreEqual(1, begin); // 1 is index of entity in filtered EntityQuery group.Dispose(); } @@ -325,7 +261,7 @@ public void ComponentGroupFilteredChunkCount() { var archetypeA = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestSharedComp)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestSharedComp)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestSharedComp)); for (int i = 0; i < archetypeA.ChunkCapacity * 2; ++i) { diff --git a/Unity.Entities.Tests/JobComponentSystemDependencyTests.cs b/Unity.Entities.Tests/JobComponentSystemDependencyTests.cs index 99bd0d8da..8658cb86 100644 --- a/Unity.Entities.Tests/JobComponentSystemDependencyTests.cs +++ b/Unity.Entities.Tests/JobComponentSystemDependencyTests.cs @@ -11,9 +11,9 @@ class JobComponentSystemDependencyTests : ECSTestsFixture [DisableAutoCreation] public class ReadSystem1 : JobComponentSystem { - public ComponentGroup m_ReadGroup; + public EntityQuery m_ReadGroup; - struct ReadJob : IJobProcessComponentData + struct ReadJob : IJobForEach { public void Execute([ReadOnly]ref EcsTestData c0) { @@ -23,24 +23,24 @@ public void Execute([ReadOnly]ref EcsTestData c0) protected override JobHandle OnUpdate(JobHandle input) { var job = new ReadJob() {}; - return job.ScheduleGroup(m_ReadGroup); + return job.Schedule(m_ReadGroup); } - protected override void OnCreateManager() + protected override void OnCreate() { - m_ReadGroup = GetComponentGroup(ComponentType.ReadOnly()); + m_ReadGroup = GetEntityQuery(ComponentType.ReadOnly()); } } [DisableAutoCreation] public class ReadSystem2 : JobComponentSystem { - public ComponentGroup m_ReadGroup; + public EntityQuery m_ReadGroup; public bool returnWrongJob = false; public bool ignoreInputDeps = false; - private struct ReadJob : IJobProcessComponentData + private struct ReadJob : IJobForEach { public void Execute([ReadOnly]ref EcsTestData c0) { @@ -55,46 +55,46 @@ protected override JobHandle OnUpdate(JobHandle input) if (ignoreInputDeps) { - h = job.ScheduleGroup(m_ReadGroup); + h = job.Schedule(m_ReadGroup); } else { - h = job.ScheduleGroup(m_ReadGroup, input); + h = job.Schedule(m_ReadGroup, input); } return returnWrongJob ? input : h; } - protected override void OnCreateManager() + protected override void OnCreate() { - m_ReadGroup = GetComponentGroup(ComponentType.ReadOnly()); + m_ReadGroup = GetEntityQuery(ComponentType.ReadOnly()); } } [DisableAutoCreation] public class ReadSystem3 : JobComponentSystem { - public ComponentGroup m_ReadGroup; + public EntityQuery m_ReadGroup; protected override JobHandle OnUpdate(JobHandle input) { return input; } - protected override void OnCreateManager() + protected override void OnCreate() { - m_ReadGroup = GetComponentGroup(ComponentType.ReadOnly()); + m_ReadGroup = GetEntityQuery(ComponentType.ReadOnly()); } } [DisableAutoCreation] public class WriteSystem : JobComponentSystem { - public ComponentGroup m_WriteGroup; + public EntityQuery m_WriteGroup; public bool SkipJob = false; - private struct WriteJob : IJobProcessComponentData + private struct WriteJob : IJobForEach { public void Execute(ref EcsTestData c0) { @@ -106,7 +106,7 @@ protected override JobHandle OnUpdate(JobHandle input) if (!SkipJob) { var job = new WriteJob() {}; - return job.ScheduleGroup(m_WriteGroup); + return job.Schedule(m_WriteGroup); } else { @@ -114,9 +114,9 @@ protected override JobHandle OnUpdate(JobHandle input) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_WriteGroup = GetComponentGroup(ComponentType.ReadWrite()); + m_WriteGroup = GetEntityQuery(ComponentType.ReadWrite()); } } @@ -125,8 +125,8 @@ public void ReturningWrongJobThrowsInCorrectSystemUpdate() { var entity = m_Manager.CreateEntity (typeof(EcsTestData)); m_Manager.SetComponentData(entity, new EcsTestData(42)); - ReadSystem1 rs1 = World.GetOrCreateManager(); - ReadSystem2 rs2 = World.GetOrCreateManager(); + ReadSystem1 rs1 = World.GetOrCreateSystem(); + ReadSystem2 rs2 = World.GetOrCreateSystem(); rs2.returnWrongJob = true; @@ -139,8 +139,8 @@ public void IgnoredInputDepsThrowsInCorrectSystemUpdate() { var entity = m_Manager.CreateEntity (typeof(EcsTestData)); m_Manager.SetComponentData(entity, new EcsTestData(42)); - WriteSystem ws1 = World.GetOrCreateManager(); - ReadSystem2 rs2 = World.GetOrCreateManager(); + WriteSystem ws1 = World.GetOrCreateSystem(); + ReadSystem2 rs2 = World.GetOrCreateSystem(); rs2.ignoreInputDeps = true; @@ -153,7 +153,7 @@ public void NotSchedulingWriteJobIsHarmless() { var entity = m_Manager.CreateEntity (typeof(EcsTestData)); m_Manager.SetComponentData(entity, new EcsTestData(42)); - WriteSystem ws1 = World.GetOrCreateManager(); + WriteSystem ws1 = World.GetOrCreateSystem(); ws1.Update(); ws1.SkipJob = true; @@ -165,20 +165,20 @@ public void NotUsingDataIsHarmless() { var entity = m_Manager.CreateEntity (typeof(EcsTestData)); m_Manager.SetComponentData(entity, new EcsTestData(42)); - ReadSystem1 rs1 = World.GetOrCreateManager(); - ReadSystem3 rs3 = World.GetOrCreateManager(); + ReadSystem1 rs1 = World.GetOrCreateSystem(); + ReadSystem3 rs3 = World.GetOrCreateSystem(); rs1.Update(); rs3.Update(); } [Test] - public void ReadAfterWrite_JobProcessComponentDataGroup_Works() + public void ReadAfterWrite_JobForEachGroup_Works() { var entity = m_Manager.CreateEntity (typeof(EcsTestData)); m_Manager.SetComponentData(entity, new EcsTestData(42)); - var ws = World.GetOrCreateManager(); - var rs = World.GetOrCreateManager(); + var ws = World.GetOrCreateSystem(); + var rs = World.GetOrCreateSystem(); ws.Update(); rs.Update(); @@ -205,13 +205,13 @@ protected override JobHandle OnUpdate(JobHandle dep) } // The writer dependency on EcsTestData is not predeclared during - // OnCreateManager, but we still expect the code to work correctly. + // OnCreate, but we still expect the code to work correctly. // This should result in a sync point when adding the dependency for the first time. [Test] public void AddingDependencyTypeDuringOnUpdateSyncsDependency() { - var systemA = World.CreateManager(); - var systemB = World.CreateManager(); + var systemA = World.CreateSystem(); + var systemB = World.CreateSystem(); systemA.Update(); systemB.Update(); @@ -241,7 +241,7 @@ protected override JobHandle OnUpdate(JobHandle dep) var handle = new EmptyJob { TestDataType = GetArchetypeChunkComponentType() - }.Schedule(m_EntityManager.UniversalGroup, dep); + }.Schedule(m_EntityManager.UniversalQuery, dep); return handle; } } @@ -251,8 +251,8 @@ public void EmptySystemAfterNonEmptySystemDoesntThrow() { m_Manager.CreateEntity(typeof(EcsTestData)); - var systemA = World.CreateManager(); - var systemB = World.CreateManager(); + var systemA = World.CreateSystem(); + var systemB = World.CreateSystem(); systemA.Update(); systemB.Update(); diff --git a/Unity.Entities.Tests/JobSafetyTests.cs b/Unity.Entities.Tests/JobSafetyTests.cs index 202057ec..c2b9980f 100644 --- a/Unity.Entities.Tests/JobSafetyTests.cs +++ b/Unity.Entities.Tests/JobSafetyTests.cs @@ -35,7 +35,7 @@ public void Execute() [Test] public void ComponentAccessAfterScheduledJobThrows() { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var entity = m_Manager.CreateEntity(typeof(EcsTestData)); m_Manager.SetComponentData(entity, new EcsTestData(42)); @@ -64,7 +64,7 @@ public void ComponentAccessAfterScheduledJobThrows() public void GetComponentCompletesJob() { var entity = m_Manager.CreateEntity(typeof(EcsTestData)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var job = new TestIncrementJob(); job.entities = group.ToEntityArray(Allocator.TempJob); @@ -82,7 +82,7 @@ public void DestroyEntityCompletesScheduledJobs() { var entity = m_Manager.CreateEntity(typeof(EcsTestData)); /*var entity2 =*/ m_Manager.CreateEntity(typeof(EcsTestData)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var job = new TestIncrementJob(); job.entities = group.ToEntityArray(Allocator.TempJob); @@ -110,7 +110,7 @@ public void EntityManagerDestructionDetectsUnregisteredJob() #endif /*var entity =*/ m_Manager.CreateEntity(typeof(EcsTestData)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var job = new TestIncrementJob(); job.entities = group.ToEntityArray(Allocator.TempJob); @@ -126,7 +126,7 @@ public void EntityManagerDestructionDetectsUnregisteredJob() public void DestroyEntityDetectsUnregisteredJob() { var entity = m_Manager.CreateEntity(typeof(EcsTestData)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var job = new TestIncrementJob(); job.entities = group.ToEntityArray(Allocator.TempJob); @@ -143,7 +143,7 @@ public void DestroyEntityDetectsUnregisteredJob() public void GetComponentDetectsUnregisteredJob() { var entity = m_Manager.CreateEntity(typeof(EcsTestData)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var job = new TestIncrementJob(); job.entities = group.ToEntityArray(Allocator.TempJob); @@ -185,7 +185,7 @@ class EntityOnlyDependencySystem : JobComponentSystem protected override JobHandle OnUpdate(JobHandle inputDeps) { EntityManager.CreateEntity(typeof(EcsTestData)); - var group = GetComponentGroup(new ComponentType[]{}); + var group = GetEntityQuery(new ComponentType[]{}); var job = new EntityOnlyDependencyJob { entityType = m_EntityManager.GetArchetypeChunkEntityType() @@ -202,7 +202,7 @@ class NoComponentDependenciesSystem : JobComponentSystem protected override JobHandle OnUpdate(JobHandle inputDeps) { EntityManager.CreateEntity(typeof(EcsTestData)); - var group = GetComponentGroup(new ComponentType[]{}); + var group = GetEntityQuery(new ComponentType[]{}); var job = new NoDependenciesJob{}; JobHandle = job.Schedule(group, inputDeps); @@ -225,18 +225,18 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) [Test] public void StructuralChangeCompletesEntityOnlyDependencyJob() { - var system = World.GetOrCreateManager(); + var system = World.GetOrCreateSystem(); system.Update(); - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); Assert.IsTrue(JobHandle.CheckFenceIsDependencyOrDidSyncFence(system.JobHandle, new JobHandle())); } [Test] public void StructuralChangeCompletesNoComponentDependenciesJob() { - var system = World.GetOrCreateManager(); + var system = World.GetOrCreateSystem(); system.Update(); - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); Assert.IsTrue(JobHandle.CheckFenceIsDependencyOrDidSyncFence(system.JobHandle, new JobHandle())); } @@ -245,7 +245,7 @@ public void StructuralChangeAfterSchedulingNoDependenciesJobThrows() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData)); var entity = m_Manager.CreateEntity(archetype); - var group = EmptySystem.GetComponentGroup(typeof(EcsTestData)); + var group = EmptySystem.GetEntityQuery(typeof(EcsTestData)); var handle = new NoDependenciesJob().Schedule(group); Assert.Throws(() => m_Manager.DestroyEntity(entity)); handle.Complete(); @@ -256,7 +256,7 @@ public void StructuralChangeAfterSchedulingEntityOnlyDependencyJobThrows() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData)); var entity = m_Manager.CreateEntity(archetype); - var group = EmptySystem.GetComponentGroup(typeof(EcsTestData)); + var group = EmptySystem.GetEntityQuery(typeof(EcsTestData)); var handle = new EntityOnlyDependencyJob{entityType = m_Manager.GetArchetypeChunkEntityType()}.Schedule(group); Assert.Throws(() => m_Manager.DestroyEntity(entity)); handle.Complete(); @@ -265,9 +265,9 @@ public void StructuralChangeAfterSchedulingEntityOnlyDependencyJobThrows() [DisableAutoCreation] class SharedComponentSystem : JobComponentSystem { - ComponentGroup group; - protected override void OnCreateManager() { - group = GetComponentGroup(ComponentType.ReadOnly()); + EntityQuery group; + protected override void OnCreate() { + group = GetEntityQuery(ComponentType.ReadOnly()); } struct SharedComponentJobChunk : IJobChunk { @@ -292,7 +292,7 @@ public void JobsUsingArchetypeChunkSharedComponentTypeSyncOnStructuralChange() var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); var entity = m_Manager.CreateEntity(archetype); - var sharedComponentSystem = World.CreateManager(); + var sharedComponentSystem = World.CreateSystem(); sharedComponentSystem.Update(); // DestroyEntity should sync the job and not cause any safety error diff --git a/Unity.Entities.Tests/LockedEntityTests.cs b/Unity.Entities.Tests/LockedEntityTests.cs index 8cdf4524..cb5f6f9a 100644 --- a/Unity.Entities.Tests/LockedEntityTests.cs +++ b/Unity.Entities.Tests/LockedEntityTests.cs @@ -73,13 +73,13 @@ public void LockedEntityRestrictions() m_Manager.LockChunk(chunk); Assert.Throws(() => m_Manager.AddComponentData(entity, new EcsTestTag()) ); - Assert.Throws(() => m_Manager.AddComponent(m_Manager.UniversalGroup, typeof(EcsTestTag)) ); + Assert.Throws(() => m_Manager.AddComponent(m_Manager.UniversalQuery, typeof(EcsTestTag)) ); Assert.Throws(() => m_Manager.RemoveComponent(entity) ); - Assert.Throws(() => m_Manager.RemoveComponent(m_Manager.UniversalGroup, typeof(EcsTestData))); + Assert.Throws(() => m_Manager.RemoveComponent(m_Manager.UniversalQuery, typeof(EcsTestData))); Assert.Throws(() => m_Manager.DestroyEntity(entity)); - Assert.Throws(() => m_Manager.DestroyEntity(m_Manager.UniversalGroup)); + Assert.Throws(() => m_Manager.DestroyEntity(m_Manager.UniversalQuery)); } [Test] @@ -90,10 +90,10 @@ public void LockedEntityOrderRestrictions() m_Manager.LockChunkOrder(chunk); Assert.Throws(() => m_Manager.AddComponentData(entity, new EcsFooTest())); - Assert.Throws(() => m_Manager.AddComponent(m_Manager.UniversalGroup, typeof(EcsFooTest))); + Assert.Throws(() => m_Manager.AddComponent(m_Manager.UniversalQuery, typeof(EcsFooTest))); Assert.Throws(() => m_Manager.RemoveComponent(entity) ); - Assert.Throws(() => m_Manager.RemoveComponent(m_Manager.UniversalGroup, typeof(EcsTestData))); + Assert.Throws(() => m_Manager.RemoveComponent(m_Manager.UniversalQuery, typeof(EcsTestData))); Assert.Throws(() => m_Manager.DestroyEntity(entity)); } @@ -105,10 +105,10 @@ public void LockedEntityOrderAllowsNonMovingOperations() var chunk = m_Manager.GetChunk(entity); m_Manager.LockChunkOrder(chunk); - m_Manager.AddComponent(m_Manager.UniversalGroup, typeof(EcsTestTag)); - m_Manager.RemoveComponent(m_Manager.UniversalGroup, typeof(EcsTestTag)); - m_Manager.AddChunkComponentData(m_Manager.UniversalGroup, new EcsFooTest()); - m_Manager.DestroyEntity(m_Manager.UniversalGroup); + m_Manager.AddComponent(m_Manager.UniversalQuery, typeof(EcsTestTag)); + m_Manager.RemoveComponent(m_Manager.UniversalQuery, typeof(EcsTestTag)); + m_Manager.AddChunkComponentData(m_Manager.UniversalQuery, new EcsFooTest()); + m_Manager.DestroyEntity(m_Manager.UniversalQuery); } [Test] diff --git a/Unity.Entities.Tests/MoveEntitiesFromTests.cs b/Unity.Entities.Tests/MoveEntitiesFromTests.cs index 2ea4f833..9aedf9a0 100644 --- a/Unity.Entities.Tests/MoveEntitiesFromTests.cs +++ b/Unity.Entities.Tests/MoveEntitiesFromTests.cs @@ -19,7 +19,7 @@ public void MoveEntitiesToSameEntityManagerThrows() public void MoveEntities() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); @@ -39,9 +39,9 @@ public void MoveEntities() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); Assert.AreEqual(entities.Length, group.CalculateLength()); - Assert.AreEqual(0, creationManager.CreateComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(0, creationManager.CreateEntityQuery(typeof(EcsTestData)).CalculateLength()); // We expect that the order of the crated entities is the same as in the creation scene var testDataArray = group.ToComponentDataArray(Allocator.TempJob); @@ -54,11 +54,10 @@ public void MoveEntities() } [Test] - [StandaloneFixme] // ISharedComponentData public void MoveEntitiesWithSharedComponentData() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); @@ -78,9 +77,9 @@ public void MoveEntitiesWithSharedComponentData() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); Assert.AreEqual(entities.Length, group.CalculateLength()); - Assert.AreEqual(0, creationManager.CreateComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(0, creationManager.CreateEntityQuery(typeof(EcsTestData)).CalculateLength()); // We expect that the shared component data matches the correct entities var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); @@ -104,7 +103,7 @@ public void MoveEntitiesWithSharedComponentData() public void MoveEntitiesWithChunkComponents() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), ComponentType.ChunkComponent()); @@ -130,9 +129,9 @@ public void MoveEntitiesWithChunkComponents() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), ComponentType.ChunkComponent()); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), ComponentType.ChunkComponent()); Assert.AreEqual(entities.Length, group.CalculateLength()); - Assert.AreEqual(0, creationManager.CreateComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(0, creationManager.CreateEntityQuery(typeof(EcsTestData)).CalculateLength()); var movedEntities = group.ToEntityArray(Allocator.TempJob); for (int i = 0; i < movedEntities.Length; ++i) @@ -149,10 +148,10 @@ public void MoveEntitiesWithChunkComponents() } [Test] - public void MoveEntitiesWithComponentGroup() + public void MoveEntitiesWithEntityQuery() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(SharedData1)); @@ -167,7 +166,7 @@ public void MoveEntitiesWithComponentGroup() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var filteredComponentGroup = creationManager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); + var filteredComponentGroup = creationManager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); filteredComponentGroup.SetFilter(new SharedData1(2)); var entityRemapping = creationManager.CreateEntityRemapArray(Allocator.TempJob); @@ -179,9 +178,9 @@ public void MoveEntitiesWithComponentGroup() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); Assert.AreEqual(2000, group.CalculateLength()); - Assert.AreEqual(8000, creationManager.CreateComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(8000, creationManager.CreateEntityQuery(typeof(EcsTestData)).CalculateLength()); // We expect that the shared component data matches the correct entities var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); @@ -206,11 +205,10 @@ public void MoveEntitiesWithComponentGroup() } [Test] - [StandaloneFixme] // ISharedComponentData public void MoveEntitiesWithComponentGroupMovesChunkComponents() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), ComponentType.ChunkComponent(), typeof(SharedData1)); var entities = new NativeArray(10000, Allocator.Temp); @@ -221,7 +219,7 @@ public void MoveEntitiesWithComponentGroupMovesChunkComponents() creationManager.SetSharedComponentData(entities[i], new SharedData1(i % 5)); } - var srcGroup = creationManager.CreateComponentGroup(typeof(EcsTestData), ComponentType.ChunkComponent(), typeof(SharedData1)); + var srcGroup = creationManager.CreateEntityQuery(typeof(EcsTestData), ComponentType.ChunkComponent(), typeof(SharedData1)); var chunksPerValue = new int[5]; var chunks = srcGroup.CreateArchetypeChunkArray(Allocator.TempJob); @@ -241,7 +239,7 @@ public void MoveEntitiesWithComponentGroupMovesChunkComponents() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var filteredComponentGroup = creationManager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); + var filteredComponentGroup = creationManager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); filteredComponentGroup.SetFilter(new SharedData1(2)); var entityRemapping = creationManager.CreateEntityRemapArray(Allocator.TempJob); @@ -253,15 +251,15 @@ public void MoveEntitiesWithComponentGroupMovesChunkComponents() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var dstGroup = m_Manager.CreateComponentGroup(typeof(EcsTestData), ComponentType.ChunkComponent(), typeof(SharedData1)); + var dstGroup = m_Manager.CreateEntityQuery(typeof(EcsTestData), ComponentType.ChunkComponent(), typeof(SharedData1)); Assert.AreEqual(2000, dstGroup.CalculateLength()); - Assert.AreEqual(8000, creationManager.CreateComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(8000, creationManager.CreateEntityQuery(typeof(EcsTestData)).CalculateLength()); int expectedMovedChunkCount = chunksPerValue[2]; int expectedRemainingChunkCount = chunksPerValue.Sum() - expectedMovedChunkCount; - var movedChunkHeaderGroup = m_Manager.CreateComponentGroup(typeof(EcsTestData2), typeof(ChunkHeader)); - var remainingChunkHeaderGroup = creationManager.CreateComponentGroup(typeof(EcsTestData2), typeof(ChunkHeader)); + var movedChunkHeaderGroup = m_Manager.CreateEntityQuery(typeof(EcsTestData2), typeof(ChunkHeader)); + var remainingChunkHeaderGroup = creationManager.CreateEntityQuery(typeof(EcsTestData2), typeof(ChunkHeader)); Assert.AreEqual(expectedMovedChunkCount, movedChunkHeaderGroup.CalculateLength()); Assert.AreEqual(expectedRemainingChunkCount, remainingChunkHeaderGroup.CalculateLength()); @@ -303,7 +301,7 @@ public void MoveEntitiesWithComponentGroupMovesChunkComponents() public void MoveEntitiesWithChunkHeaderChunksThrows() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), ComponentType.ChunkComponent()); @@ -314,7 +312,7 @@ public void MoveEntitiesWithChunkHeaderChunksThrows() m_Manager.Debug.CheckInternalConsistency(); creationManager.Debug.CheckInternalConsistency(); - var componentGroupToMove = creationManager.CreateComponentGroup(typeof(EcsTestData2), typeof(ChunkHeader)); + var componentGroupToMove = creationManager.CreateEntityQuery(typeof(EcsTestData2), typeof(ChunkHeader)); var entityRemapping = creationManager.CreateEntityRemapArray(Allocator.TempJob); Assert.Throws(() => m_Manager.MoveEntitiesFrom(creationManager, componentGroupToMove, entityRemapping)); @@ -337,7 +335,7 @@ public void MoveEntitiesAppendsToExistingEntities() m_Manager.SetComponentData(targetEntities[i], new EcsTestData(i)); var sourceWorld = new World("SourceWorld"); - var sourceManager = sourceWorld.GetOrCreateManager(); + var sourceManager = sourceWorld.EntityManager; var sourceArchetype = sourceManager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); var sourceEntities = new NativeArray(numberOfEntitiesPerManager, Allocator.Temp); sourceManager.CreateEntity(sourceArchetype, sourceEntities); @@ -352,9 +350,9 @@ public void MoveEntitiesAppendsToExistingEntities() m_Manager.Debug.CheckInternalConsistency(); sourceManager.Debug.CheckInternalConsistency(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); Assert.AreEqual(numberOfEntitiesPerManager * 2, group.CalculateLength()); - Assert.AreEqual(0, sourceManager.CreateComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(0, sourceManager.CreateEntityQuery(typeof(EcsTestData)).CalculateLength()); // We expect that the order of the crated entities is the same as in the creation scene var testDataArray = group.ToComponentDataArray(Allocator.TempJob); @@ -379,7 +377,7 @@ public void MoveEntitiesPatchesEntityReferences() m_Manager.SetComponentData(targetEntities[i], new EcsTestDataEntity(i, targetEntities[i])); var sourceWorld = new World("SourceWorld"); - var sourceManager = sourceWorld.GetOrCreateManager(); + var sourceManager = sourceWorld.EntityManager; var sourceArchetype = sourceManager.CreateArchetype(typeof(EcsTestDataEntity)); var sourceEntities = new NativeArray(numberOfEntitiesPerManager, Allocator.Temp); sourceManager.CreateEntity(sourceArchetype, sourceEntities); @@ -394,9 +392,9 @@ public void MoveEntitiesPatchesEntityReferences() m_Manager.Debug.CheckInternalConsistency(); sourceManager.Debug.CheckInternalConsistency(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestDataEntity)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestDataEntity)); Assert.AreEqual(numberOfEntitiesPerManager * 2, group.CalculateLength()); - Assert.AreEqual(0, sourceManager.CreateComponentGroup(typeof(EcsTestDataEntity)).CalculateLength()); + Assert.AreEqual(0, sourceManager.CreateEntityQuery(typeof(EcsTestDataEntity)).CalculateLength()); var testDataArray = group.ToComponentDataArray(Allocator.TempJob); for (int i = 0; i != testDataArray.Length; i++) @@ -409,7 +407,6 @@ public void MoveEntitiesPatchesEntityReferences() } [Test] - [StandaloneFixme] // ISharedComponentData [Ignore("This behaviour is currently not intended. It prevents streaming efficiently.")] public void MoveEntitiesPatchesEntityReferencesInSharedComponentData() { @@ -426,7 +423,7 @@ public void MoveEntitiesPatchesEntityReferencesInSharedComponentData() } var sourceWorld = new World("SourceWorld"); - var sourceManager = sourceWorld.GetOrCreateManager(); + var sourceManager = sourceWorld.EntityManager; var sourceArchetype = sourceManager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedCompEntity)); var sourceEntities = new NativeArray(numberOfEntitiesPerManager, Allocator.Temp); sourceManager.CreateEntity(sourceArchetype, sourceEntities); @@ -444,9 +441,9 @@ public void MoveEntitiesPatchesEntityReferencesInSharedComponentData() m_Manager.Debug.CheckInternalConsistency(); sourceManager.Debug.CheckInternalConsistency(); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestSharedCompEntity)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestSharedCompEntity)); Assert.AreEqual(numberOfEntitiesPerManager * 2, group.CalculateLength()); - Assert.AreEqual(0, sourceManager.CreateComponentGroup(typeof(EcsTestData)).CalculateLength()); + Assert.AreEqual(0, sourceManager.CreateEntityQuery(typeof(EcsTestData)).CalculateLength()); var testDataArray = group.ToComponentDataArray(Allocator.TempJob); var entities = group.ToEntityArray(Allocator.TempJob); @@ -469,7 +466,7 @@ public void MoveEntitiesPatchesEntityReferencesInSharedComponentData() public void MoveEntitiesFromCanReturnEntities() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); @@ -513,7 +510,7 @@ public void MoveEntitiesFromCanReturnEntities() public unsafe void MoveEntitiesArchetypeChunkCountMatches() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var archetype = creationManager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2)); @@ -549,11 +546,11 @@ public unsafe void MoveEntitiesArchetypeChunkCountMatches() public void MoveEntitiesFromChunksAreConsideredChangedOnlyOnce() { var creationWorld = new World("CreationWorld"); - var creationManager = creationWorld.GetOrCreateManager(); + var creationManager = creationWorld.EntityManager; var entity = creationManager.CreateEntity(); creationManager.AddComponentData(entity, new EcsTestData(42)); - var system = World.GetOrCreateManager(); + var system = World.GetOrCreateSystem(); system.Update(); Assert.AreEqual(0, system.NumChanged); diff --git a/Unity.Entities.Tests/PrefabComponentTests.cs b/Unity.Entities.Tests/PrefabComponentTests.cs index 554e0969..04693c7b 100644 --- a/Unity.Entities.Tests/PrefabComponentTests.cs +++ b/Unity.Entities.Tests/PrefabComponentTests.cs @@ -7,12 +7,12 @@ namespace Unity.Entities.Tests class PrefabComponentTests : ECSTestsFixture { [Test] - public void PFB_DontFindPrefabInComponentGroup() + public void PFB_DontFindPrefabInEntityQuery() { var archetype0 = m_Manager.CreateArchetype(typeof(EcsTestData)); var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(Prefab)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData)); var entity0 = m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); @@ -32,7 +32,7 @@ public void PFB_DontFindPrefabInChunkIterator() var entity0 = m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); var count = ArchetypeChunkArray.CalculateEntityCount(chunks); @@ -45,12 +45,12 @@ public void PFB_DontFindPrefabInChunkIterator() } [Test] - public void PFB_FindPrefabIfRequestedInComponentGroup() + public void PFB_FindPrefabIfRequestedInEntityQuery() { var archetype0 = m_Manager.CreateArchetype(typeof(EcsTestData)); var archetype1 = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(Prefab)); - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(Prefab)); + var group = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(Prefab)); var entity0 = m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); @@ -73,7 +73,7 @@ public void PFB_FindPrefabIfRequestedInChunkIterator() var entity1 = m_Manager.CreateEntity(archetype1); var entity2 = m_Manager.CreateEntity(archetype1); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite(), + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite(), ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); @@ -117,7 +117,7 @@ public void PFB_InstantiatedWithoutPrefab() Assert.AreEqual(true, m_Manager.HasComponent(entity0)); Assert.AreEqual(false, m_Manager.HasComponent(entity1)); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); var count = ArchetypeChunkArray.CalculateEntityCount(chunks); diff --git a/Unity.Entities.Tests/SafetyTests.cs b/Unity.Entities.Tests/SafetyTests.cs index c49ba7ad..719fb465 100644 --- a/Unity.Entities.Tests/SafetyTests.cs +++ b/Unity.Entities.Tests/SafetyTests.cs @@ -20,77 +20,6 @@ public void RemoveEntityComponentThrows() Assert.IsTrue(m_Manager.HasComponent(entity)); } -#pragma warning disable 618 - [Test] - public void ComponentArrayChunkSliceOutOfBoundsThrowsException() - { - for (int i = 0;i<10;i++) - m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); - var testData = group.GetComponentDataArray(); - - Assert.AreEqual(0, testData.GetChunkArray(5, 0).Length); - Assert.AreEqual(10, testData.GetChunkArray(0, 10).Length); - - Assert.Throws(() => { testData.GetChunkArray(-1, 1); }); - Assert.Throws(() => { testData.GetChunkArray(5, 6); }); - Assert.Throws(() => { testData.GetChunkArray(10, 1); }); - } - - - [Test] - [StandaloneFixme] // Real problem : Atomic Safety - public void ReadOnlyComponentDataArray() - { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData2), ComponentType.ReadOnly(typeof(EcsTestData))); - - var entity = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - m_Manager.SetComponentData(entity, new EcsTestData(42)); - - // EcsTestData is read only - var arr = group.GetComponentDataArray(); - Assert.AreEqual(1, arr.Length); - Assert.AreEqual(42, arr[0].value); - Assert.Throws(() => { arr[0] = new EcsTestData(0); }); - - // EcsTestData2 can be written to - var arr2 = group.GetComponentDataArray(); - Assert.AreEqual(1, arr2.Length); - arr2[0] = new EcsTestData2(55); - Assert.AreEqual(55, arr2[0].value0); - } - - [Test] - [StandaloneFixme] // Real problem : Atomic Safety - public void AccessComponentArrayAfterCreationThrowsException() - { - CreateEntityWithDefaultData(0); - - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); - var arr = group.GetComponentDataArray(); - - CreateEntityWithDefaultData(1); - - Assert.Throws(() => { var value = arr[0]; }); - } - - [Test] - [StandaloneFixme] // Real problem : Atomic Safety - public void CreateEntityInvalidatesArray() - { - CreateEntityWithDefaultData(0); - - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData)); - var arr = group.GetComponentDataArray(); - - CreateEntityWithDefaultData(1); - - Assert.Throws(() => { var value = arr[0]; }); - } - - #pragma warning restore 618 - [Test] public void GetSetComponentThrowsIfNotExist() { @@ -106,7 +35,6 @@ public void GetSetComponentThrowsIfNotExist() } [Test] - [StandaloneFixme] // Real problem : Atomic Safety public void ComponentDataArrayFromEntityThrowsIfNotExist() { var entity = m_Manager.CreateEntity(typeof(EcsTestData)); @@ -131,15 +59,6 @@ public void AddComponentTwiceThrows() Assert.Throws(() => { m_Manager.AddComponentData(entity, new EcsTestData(1)); }); } - [Test] - public void AddChunkComponentTwiceOnEntityThrows() - { - var entity = m_Manager.CreateEntity(); - - m_Manager.AddChunkComponentData(entity); - Assert.Throws(() => { m_Manager.AddChunkComponentData(entity); }); - } - [Test] public void AddComponentOnDestroyedEntityThrows() { @@ -210,7 +129,6 @@ unsafe struct BigComponentData2 : IComponentData } [Test] - [StandaloneFixme] // Real problem - sizeof(BigComponentData1) = 4 vs 40000 expected public void CreateTooBigArchetypeThrows() { Assert.Throws(() => diff --git a/Unity.Entities.Tests/SerializeTests.cs b/Unity.Entities.Tests/SerializeTests.cs index 5ccd1497..3afc0c3b 100644 --- a/Unity.Entities.Tests/SerializeTests.cs +++ b/Unity.Entities.Tests/SerializeTests.cs @@ -121,7 +121,7 @@ public unsafe void SerializeEntities() var reader = new TestBinaryReader(writer); var deserializedWorld = new World("SerializeEntities Test World 3"); - var entityManager = deserializedWorld.GetOrCreateManager(); + var entityManager = deserializedWorld.EntityManager; SerializeUtility.DeserializeWorld(entityManager.BeginExclusiveEntityTransaction(), reader, 0); entityManager.EndExclusiveEntityTransaction(); @@ -134,20 +134,20 @@ public unsafe void SerializeEntities() Assert.AreEqual(4, count); - var group1 = entityManager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2), + var group1 = entityManager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2), typeof(TestComponentData1)); - var group2 = entityManager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2), + var group2 = entityManager.CreateEntityQuery(typeof(EcsTestData), typeof(EcsTestData2), typeof(TestComponentData2)); - var group3 = entityManager.CreateComponentGroup(typeof(EcsTestData), + var group3 = entityManager.CreateEntityQuery(typeof(EcsTestData), typeof(TestComponentData1), typeof(TestComponentData2)); - var group4 = entityManager.CreateComponentGroup(typeof(EcsComplexEntityRefElement)); + var group4 = entityManager.CreateEntityQuery(typeof(EcsComplexEntityRefElement)); Assert.AreEqual(1, group1.CalculateLength()); Assert.AreEqual(1, group2.CalculateLength()); Assert.AreEqual(1, group3.CalculateLength()); Assert.AreEqual(1, group4.CalculateLength()); - var everythingGroup = entityManager.CreateComponentGroup(Array.Empty()); + var everythingGroup = entityManager.CreateEntityQuery(Array.Empty()); var chunks = everythingGroup.CreateArchetypeChunkArray(Allocator.TempJob); Assert.AreEqual(4, chunks.Length); everythingGroup.Dispose(); @@ -249,7 +249,7 @@ public void SerializeEntitiesSupportsNonASCIIComponentTypeNames() var reader = new TestBinaryReader(writer); var deserializedWorld = new World("SerializeEntitiesSupportsNonASCIIComponentTypeNames Test World"); - var entityManager = deserializedWorld.GetOrCreateManager(); + var entityManager = deserializedWorld.EntityManager; SerializeUtility.DeserializeWorld(entityManager.BeginExclusiveEntityTransaction(), reader, 0); entityManager.EndExclusiveEntityTransaction(); @@ -262,7 +262,7 @@ public void SerializeEntitiesSupportsNonASCIIComponentTypeNames() Assert.AreEqual(1, count); - var group1 = entityManager.CreateComponentGroup(typeof(测试)); + var group1 = entityManager.CreateEntityQuery(typeof(测试)); Assert.AreEqual(1, group1.CalculateLength()); @@ -308,7 +308,7 @@ public unsafe void SerializeEntitiesRemapsEntitiesInBuffers() var reader = new TestBinaryReader(writer); var deserializedWorld = new World("SerializeEntities Test World 3"); - var entityManager = deserializedWorld.GetOrCreateManager(); + var entityManager = deserializedWorld.EntityManager; SerializeUtility.DeserializeWorld(entityManager.BeginExclusiveEntityTransaction(), reader, 0); entityManager.EndExclusiveEntityTransaction(); @@ -316,8 +316,8 @@ public unsafe void SerializeEntitiesRemapsEntitiesInBuffers() try { - var group1 = entityManager.CreateComponentGroup(typeof(EcsTestData), typeof(TestBufferElement)); - var group2 = entityManager.CreateComponentGroup(typeof(EcsTestData2), typeof(TestBufferElement)); + var group1 = entityManager.CreateEntityQuery(typeof(EcsTestData), typeof(TestBufferElement)); + var group2 = entityManager.CreateEntityQuery(typeof(EcsTestData2), typeof(TestBufferElement)); Assert.AreEqual(1, group1.CalculateLength()); Assert.AreEqual(1, group2.CalculateLength()); @@ -376,15 +376,15 @@ public unsafe void SerializeEntitiesWorksWithChunkComponents() var reader = new TestBinaryReader(writer); var deserializedWorld = new World("SerializeEntities Test World 3"); - var entityManager = deserializedWorld.GetOrCreateManager(); + var entityManager = deserializedWorld.EntityManager; SerializeUtility.DeserializeWorld(entityManager.BeginExclusiveEntityTransaction(), reader, 0); entityManager.EndExclusiveEntityTransaction(); try { - var group1 = entityManager.CreateComponentGroup(typeof(EcsTestData)); - var group2 = entityManager.CreateComponentGroup(typeof(EcsTestData2)); + var group1 = entityManager.CreateEntityQuery(typeof(EcsTestData)); + var group2 = entityManager.CreateEntityQuery(typeof(EcsTestData2)); Assert.AreEqual(1, group1.CalculateLength()); Assert.AreEqual(1, group2.CalculateLength()); @@ -468,7 +468,7 @@ ExternalSharedComponentValue[] ExtractSharedComponentValues(int[] indices, Entit { object value = manager.m_SharedComponentManager.GetSharedComponentDataNonDefaultBoxed(indices[i]); int typeIndex = TypeManager.GetTypeIndex(value.GetType()); - int hash = SharedComponentDataManager.GetHashCodeFast(value, typeIndex); + int hash = TypeManager.GetHashCode(value, typeIndex); values[i] = new ExternalSharedComponentValue {obj = value, hashcode = hash, typeIndex = typeIndex}; } return values; @@ -536,7 +536,7 @@ public unsafe void SerializeEntitiesWorksWithBlobAssetReferences() var sharedComponents = ExtractSharedComponentValues(sharedData, m_Manager); - m_Manager.DestroyEntity(m_Manager.UniversalGroup); + m_Manager.DestroyEntity(m_Manager.UniversalQuery); arrayComponent.array.Release(); for(int i=0; i(); + var entityManager = deserializedWorld.EntityManager; InsertSharedComponentValues(sharedComponents, entityManager); @@ -558,8 +558,8 @@ public unsafe void SerializeEntitiesWorksWithBlobAssetReferences() try { - var group1 = entityManager.CreateComponentGroup(typeof(EcsTestDataBlobAssetArray)); - var group2 = entityManager.CreateComponentGroup(typeof(EcsTestDataBlobAssetRef)); + var group1 = entityManager.CreateEntityQuery(typeof(EcsTestDataBlobAssetArray)); + var group2 = entityManager.CreateEntityQuery(typeof(EcsTestDataBlobAssetRef)); var entities1 = group1.ToEntityArray(Allocator.TempJob); Assert.AreEqual(entityCount, entities1.Length); @@ -598,7 +598,7 @@ public void DeserializedChunksAreConsideredChangedOnlyOnce() TestBinaryReader CreateSerializedData() { var world = new World("DeserializedChunksAreConsideredChangedOnlyOnce World"); - var manager = world.GetOrCreateManager(); + var manager = world.EntityManager; var entity = manager.CreateEntity(); manager.AddComponentData(entity, new EcsTestData(42)); var writer = new TestBinaryWriter(); @@ -610,8 +610,8 @@ TestBinaryReader CreateSerializedData() var reader = CreateSerializedData(); var deserializedWorld = new World("DeserializedChunksAreConsideredChangedOnlyOnce World 2"); - var deserializedManager = deserializedWorld.GetOrCreateManager(); - var system = deserializedWorld.GetOrCreateManager(); + var deserializedManager = deserializedWorld.EntityManager; + var system = deserializedWorld.GetOrCreateSystem(); system.Update(); Assert.AreEqual(0, system.NumChanged); diff --git a/Unity.Entities.Tests/SharedComponentDataTests.cs b/Unity.Entities.Tests/SharedComponentDataTests.cs index 47f5be08..757eb246 100644 --- a/Unity.Entities.Tests/SharedComponentDataTests.cs +++ b/Unity.Entities.Tests/SharedComponentDataTests.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; using Unity.Collections; -#pragma warning disable 618 - namespace Unity.Entities.Tests { struct SharedData1 : ISharedComponentData @@ -20,7 +18,7 @@ struct SharedData2 : ISharedComponentData public SharedData2(int val) { value = val; } } - [StandaloneFixme] // ISharedComponentData + class SharedComponentDataTests : ECSTestsFixture { //@TODO: No tests for invalid shared components / destroyed shared component data @@ -32,13 +30,13 @@ public void SetSharedComponent() { var archetype = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData), typeof(SharedData2)); - var group1 = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); - var group2 = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData2)); - var group12 = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData2), typeof(SharedData1)); + var group1 = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); + var group2 = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData2)); + var group12 = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData2), typeof(SharedData1)); - var group1_filter_0 = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); + var group1_filter_0 = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); group1_filter_0.SetFilter(new SharedData1(0)); - var group1_filter_20 = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); + var group1_filter_20 = m_Manager.CreateEntityQuery(typeof(EcsTestData), typeof(SharedData1)); group1_filter_20.SetFilter(new SharedData1(20)); Assert.AreEqual(0, group1.CalculateLength()); @@ -53,65 +51,42 @@ public void SetSharedComponent() Entity e2 = m_Manager.CreateEntity(archetype); m_Manager.SetComponentData(e2, new EcsTestData(243)); + var group1_filter0_data = group1_filter_0.ToComponentDataArray(Allocator.TempJob); + Assert.AreEqual(2, group1_filter_0.CalculateLength()); Assert.AreEqual(0, group1_filter_20.CalculateLength()); - Assert.AreEqual(117, group1_filter_0.GetComponentDataArray()[0].value); - Assert.AreEqual(243, group1_filter_0.GetComponentDataArray()[1].value); + Assert.AreEqual(117, group1_filter0_data[0].value); + Assert.AreEqual(243, group1_filter0_data[1].value); m_Manager.SetSharedComponentData(e1, new SharedData1(20)); + + group1_filter0_data.Dispose(); + group1_filter0_data = group1_filter_0.ToComponentDataArray(Allocator.TempJob); + var group1_filter20_data = group1_filter_20.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(1, group1_filter_0.CalculateLength()); Assert.AreEqual(1, group1_filter_20.CalculateLength()); - Assert.AreEqual(117, group1_filter_20.GetComponentDataArray()[0].value); - Assert.AreEqual(243, group1_filter_0.GetComponentDataArray()[0].value); + Assert.AreEqual(117, group1_filter20_data[0].value); + Assert.AreEqual(243, group1_filter0_data[0].value); m_Manager.SetSharedComponentData(e2, new SharedData1(20)); + + group1_filter20_data.Dispose(); + group1_filter20_data = group1_filter_20.ToComponentDataArray(Allocator.TempJob); Assert.AreEqual(0, group1_filter_0.CalculateLength()); Assert.AreEqual(2, group1_filter_20.CalculateLength()); - Assert.AreEqual(117, group1_filter_20.GetComponentDataArray()[0].value); - Assert.AreEqual(243, group1_filter_20.GetComponentDataArray()[1].value); + Assert.AreEqual(117, group1_filter20_data[0].value); + Assert.AreEqual(243, group1_filter20_data[1].value); group1.Dispose(); group2.Dispose(); group12.Dispose(); group1_filter_0.Dispose(); group1_filter_20.Dispose(); - } - - - [Test] - public void GetComponentArray() - { - var archetype1 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData)); - var archetype2 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData), typeof(SharedData2)); - - const int entitiesPerValue = 5000; - for (int i = 0; i < entitiesPerValue*8; ++i) - { - Entity e = m_Manager.CreateEntity((i % 2 == 0) ? archetype1 : archetype2); - m_Manager.SetComponentData(e, new EcsTestData(i)); - m_Manager.SetSharedComponentData(e, new SharedData1(i%8)); - } - - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); - - for (int sharedValue = 0; sharedValue < 8; ++sharedValue) - { - bool[] foundEntities = new bool[entitiesPerValue]; - group.SetFilter(new SharedData1(sharedValue)); - var componentArray = group.GetComponentDataArray(); - Assert.AreEqual(entitiesPerValue, componentArray.Length); - for (int i = 0; i < entitiesPerValue; ++i) - { - int index = componentArray[i].value; - Assert.AreEqual(sharedValue, index % 8); - Assert.IsFalse(foundEntities[index/8]); - foundEntities[index/8] = true; - } - } - - group.Dispose(); + + group1_filter0_data.Dispose(); + group1_filter20_data.Dispose(); } [Test] @@ -235,50 +210,13 @@ public void RemoveSharedComponent() } [Test] - public void GetSharedComponentArray() - { - var archetype1 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData)); - var archetype2 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData), typeof(SharedData2)); - - const int entitiesPerValue = 5000; - for (int i = 0; i < entitiesPerValue*8; ++i) - { - Entity e = m_Manager.CreateEntity((i % 2 == 0) ? archetype1 : archetype2); - m_Manager.SetComponentData(e, new EcsTestData(i)); - m_Manager.SetSharedComponentData(e, new SharedData1(i%8)); - } - - var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(SharedData1)); - - var foundEntities = new bool[8, entitiesPerValue]; - - - var sharedComponentDataArray = group.GetSharedComponentDataArray(); - var componentArray = group.GetComponentDataArray(); - - Assert.AreEqual(entitiesPerValue*8, sharedComponentDataArray.Length); - Assert.AreEqual(entitiesPerValue*8, componentArray.Length); - - for (int i = 0; i < entitiesPerValue*8; ++i) - { - var sharedValue = sharedComponentDataArray[i].value; - int index = componentArray[i].value; - Assert.AreEqual(sharedValue, index % 8); - Assert.IsFalse(foundEntities[sharedValue, index/8]); - foundEntities[sharedValue, index/8] = true; - } - - group.Dispose(); - } - - [Test] - public void SCG_DoesNotMatchRemovedSharedComponentInComponentGroup() + public void SCG_DoesNotMatchRemovedSharedComponentInEntityQuery() { var archetype0 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData)); var archetype1 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData), typeof(SharedData2)); - var group0 = m_Manager.CreateComponentGroup(typeof(SharedData1)); - var group1 = m_Manager.CreateComponentGroup(typeof(SharedData2)); + var group0 = m_Manager.CreateEntityQuery(typeof(SharedData1)); + var group1 = m_Manager.CreateEntityQuery(typeof(SharedData2)); m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); @@ -301,8 +239,8 @@ public void SCG_DoesNotMatchRemovedSharedComponentInChunkQuery() var archetype0 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData)); var archetype1 = m_Manager.CreateArchetype(typeof(SharedData1), typeof(EcsTestData), typeof(SharedData2)); - var group0 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); - var group1 = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group0 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); + var group1 = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); m_Manager.CreateEntity(archetype0); var entity1 = m_Manager.CreateEntity(archetype1); @@ -329,6 +267,7 @@ public void SCG_DoesNotMatchRemovedSharedComponentInChunkQuery() postChunks1.Dispose(); } +#if !NET_DOTS [Test] public void GetSharedComponentDataWithTypeIndex() { @@ -347,5 +286,6 @@ public void GetSharedComponentDataWithTypeIndex() Assert.AreEqual(typeof(SharedData1), sharedComponentValue.GetType()); Assert.AreEqual(17, ((SharedData1)sharedComponentValue).value); } +#endif } } diff --git a/Unity.Entities.Tests/SingletonTests.cs b/Unity.Entities.Tests/SingletonTests.cs index a919687f..b098c7c8 100644 --- a/Unity.Entities.Tests/SingletonTests.cs +++ b/Unity.Entities.Tests/SingletonTests.cs @@ -6,7 +6,6 @@ namespace Unity.Entities.Tests class SingletonTests : ECSTestsFixture { [Test] - [StandaloneFixme] public void GetSetSingleton() { var entity = m_Manager.CreateEntity(typeof(EcsTestData)); @@ -16,7 +15,6 @@ public void GetSetSingleton() } [Test] - [StandaloneFixme] public void GetSetSingletonZeroThrows() { Assert.Throws(() => EmptySystem.SetSingleton(new EcsTestData())); @@ -24,7 +22,6 @@ public void GetSetSingletonZeroThrows() } [Test] - [StandaloneFixme] public void GetSetSingletonMultipleThrows() { m_Manager.CreateEntity(typeof(EcsTestData)); @@ -35,11 +32,11 @@ public void GetSetSingletonMultipleThrows() } [Test] - [StandaloneFixme] + [StandaloneFixme] // EmptySystem.ShouldRunSystem is always true in ZeroPlayer public void RequireSingletonWorks() { EmptySystem.RequireSingletonForUpdate(); - EmptySystem.GetComponentGroup(typeof(EcsTestData2)); + EmptySystem.GetEntityQuery(typeof(EcsTestData2)); m_Manager.CreateEntity(typeof(EcsTestData2)); Assert.IsFalse(EmptySystem.ShouldRunSystem()); @@ -48,7 +45,6 @@ public void RequireSingletonWorks() } [Test] - [StandaloneFixme] public void HasSingletonWorks() { Assert.IsFalse(EmptySystem.HasSingleton()); diff --git a/Unity.Entities.Tests/SizeTests.cs b/Unity.Entities.Tests/SizeTests.cs index 4f433c9a..631a5408 100644 --- a/Unity.Entities.Tests/SizeTests.cs +++ b/Unity.Entities.Tests/SizeTests.cs @@ -80,17 +80,6 @@ public void SIZ_TagCanAddComponentData() Assert.IsTrue(m_Manager.HasComponent(entity)); } - #pragma warning disable 618 - [Test] - public void SIZ_TagCannotGetComponentDataArray() - { - var group = m_Manager.CreateComponentGroup(typeof(EcsTestTag)); - var entity0 = m_Manager.CreateEntity(typeof(EcsTestTag)); - - Assert.Throws(() => { group.GetComponentDataArray(); }); - } - #pragma warning restore 618 - [Test] public void SIZ_TagThrowsOnComponentDataFromEntity() { @@ -104,7 +93,7 @@ public void SIZ_TagThrowsOnComponentDataFromEntity() public void SIZ_TagCannotGetNativeArrayFromArchetypeChunk() { m_Manager.CreateEntity(typeof(EcsTestTag)); - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); diff --git a/Unity.Entities.Tests/StandaloneFixme.cs b/Unity.Entities.Tests/StandaloneFixme.cs index 6be96359..e26c3db2 100644 --- a/Unity.Entities.Tests/StandaloneFixme.cs +++ b/Unity.Entities.Tests/StandaloneFixme.cs @@ -3,7 +3,7 @@ namespace Unity.Entities.Tests { -#if UNITY_CSHARP_TINY +#if NET_DOTS public class StandaloneFixmeAttribute : IgnoreAttribute { public StandaloneFixmeAttribute() : base("Need to fix for Tiny.") diff --git a/Unity.Entities.Tests/SystemStateBufferElementTests.cs b/Unity.Entities.Tests/SystemStateBufferElementTests.cs index 34eed534..07a2d5ed 100644 --- a/Unity.Entities.Tests/SystemStateBufferElementTests.cs +++ b/Unity.Entities.Tests/SystemStateBufferElementTests.cs @@ -26,7 +26,7 @@ class SystemStateBufferElementTests : ECSTestsFixture void VerifyComponentCount(int expectedCount) where T : IComponentData { - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); Assert.AreEqual(expectedCount, ArchetypeChunkArray.CalculateEntityCount(chunks)); @@ -36,14 +36,14 @@ void VerifyComponentCount(int expectedCount) void VerifyBufferCount(int expectedCount) where T : ISystemStateBufferElementData { - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); Assert.AreEqual(expectedCount, ArchetypeChunkArray.CalculateEntityCount(chunks)); chunks.Dispose(); } - void VerifyQueryCount(ComponentGroup group, int expectedCount) + void VerifyQueryCount(EntityQuery group, int expectedCount) { var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); Assert.AreEqual(expectedCount, ArchetypeChunkArray.CalculateEntityCount(chunks)); @@ -51,7 +51,7 @@ void VerifyQueryCount(ComponentGroup group, int expectedCount) } [Test] - [StandaloneFixme] + [StandaloneFixme] // ISharedComponentData public void DeleteWhenEmpty() { var entity = m_Manager.CreateEntity( @@ -80,7 +80,7 @@ public void DeleteWhenEmpty() } [Test] - [StandaloneFixme] + [StandaloneFixme] // ISharedComponentData public void DeleteWhenEmptyArray() { var entities = new Entity[512]; @@ -110,7 +110,7 @@ public void DeleteWhenEmptyArray() VerifyComponentCount(256); VerifyBufferCount(512); - VerifyQueryCount(m_Manager.CreateComponentGroup( + VerifyQueryCount(m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()), 256); @@ -136,7 +136,7 @@ public void DeleteWhenEmptyArray() } [Test] - [StandaloneFixme] + [StandaloneFixme] // ISharedComponentData public void DeleteWhenEmptyArray2() { var entities = new Entity[512]; @@ -166,7 +166,7 @@ public void DeleteWhenEmptyArray2() VerifyComponentCount(256); VerifyBufferCount(512); - VerifyQueryCount(m_Manager.CreateComponentGroup( + VerifyQueryCount(m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()), 256); @@ -192,7 +192,7 @@ public void DeleteWhenEmptyArray2() } [Test] - [StandaloneFixme] + [StandaloneFixme] // ISharedComponentData public void DoNotInstantiateSystemState() { var entity0 = m_Manager.CreateEntity( @@ -219,7 +219,7 @@ public void InstantiateResidueEntityThrows() } [Test] - [StandaloneFixme] + [StandaloneFixme] // Test Error public void DeleteFromEntity() { var entities = new Entity[512]; @@ -247,7 +247,7 @@ public void DeleteFromEntity() VerifyComponentCount(0); VerifyBufferCount(512); - var group = m_Manager.CreateComponentGroup( + var group = m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()); @@ -267,8 +267,7 @@ public void DeleteFromEntity() } [Test] - [StandaloneFixme] - public void DeleteFromComponentGroup() + public void DeleteFromEntityQuery() { var entities = new Entity[512]; @@ -296,7 +295,7 @@ public void DeleteFromComponentGroup() VerifyComponentCount(0); VerifyBufferCount(512); - var group = m_Manager.CreateComponentGroup( + var group = m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()); @@ -312,8 +311,7 @@ public void DeleteFromComponentGroup() } [Test] - [StandaloneFixme] - public void DeleteTagFromComponentGroup() + public void DeleteTagFromEntityQuery() { var entities = new Entity[512]; @@ -339,7 +337,7 @@ public void DeleteTagFromComponentGroup() VerifyComponentCount(0); VerifyBufferCount(512); - var group = m_Manager.CreateComponentGroup( + var group = m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()); diff --git a/Unity.Entities.Tests/SystemStateComponentTests.cs b/Unity.Entities.Tests/SystemStateComponentTests.cs index cdf4740b..197044c8 100644 --- a/Unity.Entities.Tests/SystemStateComponentTests.cs +++ b/Unity.Entities.Tests/SystemStateComponentTests.cs @@ -26,14 +26,14 @@ class SystemStateComponentTests : ECSTestsFixture void VerifyComponentCount(int expectedCount) where T : IComponentData { - var group = m_Manager.CreateComponentGroup(ComponentType.ReadWrite()); + var group = m_Manager.CreateEntityQuery(ComponentType.ReadWrite()); var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); group.Dispose(); Assert.AreEqual(expectedCount, ArchetypeChunkArray.CalculateEntityCount(chunks)); chunks.Dispose(); } - void VerifyQueryCount(ComponentGroup group, int expectedCount) + void VerifyQueryCount(EntityQuery group, int expectedCount) { var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); Assert.AreEqual(expectedCount, ArchetypeChunkArray.CalculateEntityCount(chunks)); @@ -41,7 +41,7 @@ void VerifyQueryCount(ComponentGroup group, int expectedCount) } [Test] - [StandaloneFixme] + [StandaloneFixme] // ISharedComponentData public void DeleteWhenEmpty() { var entity = m_Manager.CreateEntity( @@ -69,7 +69,7 @@ public void DeleteWhenEmpty() } [Test] - [StandaloneFixme] + [StandaloneFixme] // ISharedComponentData public void DeleteWhenEmptyArray() { var entities = new Entity[512]; @@ -98,7 +98,7 @@ public void DeleteWhenEmptyArray() VerifyComponentCount(256); VerifyComponentCount(512); - VerifyQueryCount(m_Manager.CreateComponentGroup( + VerifyQueryCount(m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()), 256); @@ -124,7 +124,7 @@ public void DeleteWhenEmptyArray() } [Test] - [StandaloneFixme] + [StandaloneFixme] // ISharedComponentData public void DeleteWhenEmptyArray2() { var entities = new Entity[512]; @@ -153,7 +153,7 @@ public void DeleteWhenEmptyArray2() VerifyComponentCount(256); VerifyComponentCount(512); - VerifyQueryCount(m_Manager.CreateComponentGroup( + VerifyQueryCount(m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()), 256); @@ -232,7 +232,7 @@ public void DeleteFromEntity() VerifyComponentCount(0); VerifyComponentCount(512); - var group = m_Manager.CreateComponentGroup( + var group = m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()); @@ -252,7 +252,7 @@ public void DeleteFromEntity() } [Test] - public void DeleteFromComponentGroup() + public void DeleteFromEntityQuery() { var entities = new Entity[512]; @@ -279,7 +279,7 @@ public void DeleteFromComponentGroup() VerifyComponentCount(0); VerifyComponentCount(512); - var group = m_Manager.CreateComponentGroup( + var group = m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()); @@ -295,7 +295,7 @@ public void DeleteFromComponentGroup() } [Test] - public void DeleteTagFromComponentGroup() + public void DeleteTagFromEntityQuery() { var entities = new Entity[512]; @@ -321,7 +321,7 @@ public void DeleteTagFromComponentGroup() VerifyComponentCount(0); VerifyComponentCount(512); - var group = m_Manager.CreateComponentGroup( + var group = m_Manager.CreateEntityQuery( ComponentType.Exclude(), ComponentType.ReadWrite()); diff --git a/Unity.Entities.Tests/TestComponentSystems.cs b/Unity.Entities.Tests/TestComponentSystems.cs index a3b473c0..78e50654 100644 --- a/Unity.Entities.Tests/TestComponentSystems.cs +++ b/Unity.Entities.Tests/TestComponentSystems.cs @@ -6,10 +6,10 @@ namespace Unity.Entities.Tests public class TestEcsChangeSystem : JobComponentSystem { public int NumChanged; - ComponentGroup ChangeGroup; - protected override void OnCreateManager() + EntityQuery ChangeGroup; + protected override void OnCreate() { - ChangeGroup = GetComponentGroup(typeof(EcsTestData)); + ChangeGroup = GetEntityQuery(typeof(EcsTestData)); ChangeGroup.SetFilterChanged(typeof(EcsTestData)); } diff --git a/Unity.Entities.Tests/TypeIndexOrderTests.cs b/Unity.Entities.Tests/TypeIndexOrderTests.cs index f3a735f8..c81a1bc5 100644 --- a/Unity.Entities.Tests/TypeIndexOrderTests.cs +++ b/Unity.Entities.Tests/TypeIndexOrderTests.cs @@ -113,7 +113,6 @@ void MatchesChunkTypes(params ComponentTypeInArchetype[] types) } [Test] - [StandaloneFixme] public unsafe void TypesInArchetypeAreOrderedAsExpected() { var archetype = m_Manager.CreateArchetype( diff --git a/Unity.Entities.Tests/WorldDebuggingToolsTests.cs b/Unity.Entities.Tests/WorldDebuggingToolsTests.cs index 721030d4..097e8e09 100644 --- a/Unity.Entities.Tests/WorldDebuggingToolsTests.cs +++ b/Unity.Entities.Tests/WorldDebuggingToolsTests.cs @@ -11,33 +11,33 @@ class WorldDebuggingToolsTests : ECSTestsFixture [DisableAutoCreation] class RegularSystem : ComponentSystem { - public ComponentGroup entities; - + public EntityQuery entities; + protected override void OnUpdate() { throw new NotImplementedException(); } - protected override void OnCreateManager() + protected override void OnCreate() { - entities = GetComponentGroup(ComponentType.ReadWrite()); + entities = GetEntityQuery(ComponentType.ReadWrite()); } } [DisableAutoCreation] class ExcludeSystem : ComponentSystem { - public ComponentGroup entities; - + public EntityQuery entities; + protected override void OnUpdate() { throw new NotImplementedException(); } - - protected override void OnCreateManager() + + protected override void OnCreate() { - entities = GetComponentGroup( - ComponentType.ReadWrite(), + entities = GetEntityQuery( + ComponentType.ReadWrite(), ComponentType.Exclude()); } } @@ -45,33 +45,33 @@ protected override void OnCreateManager() [Test] public void SystemInclusionList_MatchesComponents() { - var system = World.Active.GetOrCreateManager(); - + var system = World.Active.GetOrCreateSystem(); + var entity = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var matchList = new List>>(); - - WorldDebuggingTools.MatchEntityInComponentGroups(World.Active, entity, matchList); - + var matchList = new List>>(); + + WorldDebuggingTools.MatchEntityInEntityQueries(World.Active, entity, matchList); + Assert.AreEqual(1, matchList.Count); Assert.AreEqual(system, matchList[0].Item1); - Assert.AreEqual(system.ComponentGroups[0], matchList[0].Item2[0]); + Assert.AreEqual(system.EntityQueries[0], matchList[0].Item2[0]); } [Test] public void SystemInclusionList_IgnoresSubtractedComponents() { - World.Active.GetOrCreateManager(); - + World.Active.GetOrCreateSystem(); + var entity = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); - var matchList = new List>>(); - - WorldDebuggingTools.MatchEntityInComponentGroups(World.Active, entity, matchList); - + var matchList = new List>>(); + + WorldDebuggingTools.MatchEntityInEntityQueries(World.Active, entity, matchList); + Assert.AreEqual(0, matchList.Count); } - + } } #endif \ No newline at end of file diff --git a/Unity.Entities.Tests/WorldDiffTests.cs b/Unity.Entities.Tests/WorldDiffTests.cs index 2f434d14..d6535bbf 100644 --- a/Unity.Entities.Tests/WorldDiffTests.cs +++ b/Unity.Entities.Tests/WorldDiffTests.cs @@ -29,8 +29,8 @@ public void SetUp() m_After = new World("After"); m_DstWorld = new World("DstWorld"); - m_Manager = m_After.GetOrCreateManager(); - m_DstManager = m_DstWorld.GetOrCreateManager(); + m_Manager = m_After.EntityManager; + m_DstManager = m_DstWorld.EntityManager; } @@ -39,9 +39,9 @@ public void TearDown() { World.Active = m_PreviousWorld; - m_Shadow.GetOrCreateManager().Debug.CheckInternalConsistency(); - m_After.GetOrCreateManager().Debug.CheckInternalConsistency(); - m_DstWorld.GetOrCreateManager().Debug.CheckInternalConsistency(); + m_Shadow.EntityManager.Debug.CheckInternalConsistency(); + m_After.EntityManager.Debug.CheckInternalConsistency(); + m_DstWorld.EntityManager.Debug.CheckInternalConsistency(); m_Shadow.Dispose(); m_After.Dispose(); diff --git a/Unity.Entities.Tests/WorldTests.cs b/Unity.Entities.Tests/WorldTests.cs index 39d5cff7..eff0b9e7 100644 --- a/Unity.Entities.Tests/WorldTests.cs +++ b/Unity.Entities.Tests/WorldTests.cs @@ -21,7 +21,7 @@ public virtual void TearDown() World.Active = m_PreviousWorld; } - + [Test] [StandaloneFixme] public void ActiveWorldResets() @@ -30,21 +30,21 @@ public void ActiveWorldResets() var worldA = new World("WorldA"); var worldB = new World("WorldB"); - World.Active = worldB; - + World.Active = worldB; + Assert.AreEqual(worldB, World.Active); Assert.AreEqual(count + 2, World.AllWorlds.Count()); Assert.AreEqual(worldA, World.AllWorlds[World.AllWorlds.Count()-2]); Assert.AreEqual(worldB, World.AllWorlds[World.AllWorlds.Count()-1]); - + worldB.Dispose(); - + Assert.IsFalse(worldB.IsCreated); Assert.IsTrue(worldA.IsCreated); Assert.AreEqual(null, World.Active); - + worldA.Dispose(); - + Assert.AreEqual(count, World.AllWorlds.Count()); } @@ -63,20 +63,20 @@ public void WorldVersionIsConsistent() Assert.AreEqual(0, world.Version); var version = world.Version; - world.GetOrCreateManager(); + world.GetOrCreateSystem(); Assert.AreNotEqual(version, world.Version); version = world.Version; - var manager = world.GetOrCreateManager(); + var manager = world.GetOrCreateSystem(); Assert.AreEqual(version, world.Version); version = world.Version; - world.DestroyManager(manager); + world.DestroySystem(manager); Assert.AreNotEqual(version, world.Version); - + world.Dispose(); } - + [Test] [StandaloneFixme] public void UsingDisposedWorldThrows() @@ -84,16 +84,16 @@ public void UsingDisposedWorldThrows() var world = new World("WorldX"); world.Dispose(); - Assert.Throws(() => world.GetExistingManager()); + Assert.Throws(() => world.GetExistingSystem()); } - + [DisableAutoCreation] class AddWorldDuringConstructorThrowsSystem : ComponentSystem { public AddWorldDuringConstructorThrowsSystem() { Assert.AreEqual(null, World); - World.Active.AddManager(this); + World.Active.AddSystem(this); } protected override void OnUpdate() { } @@ -105,18 +105,18 @@ public void AddWorldDuringConstructorThrows () var world = new World("WorldX"); World.Active = world; // Adding a manager during construction is not allowed - Assert.Throws(() => world.CreateManager()); + Assert.Throws(() => world.CreateSystem()); // The manager will not be added to the list of managers if throws - Assert.AreEqual(0, world.BehaviourManagers.Count()); - + Assert.AreEqual(0, world.Systems.Count()); + world.Dispose(); } - - + + [DisableAutoCreation] - class SystemThrowingInOnCreateManagerIsRemovedSystem : ComponentSystem + class SystemThrowingInOnCreateIsRemovedSystem : ComponentSystem { - protected override void OnCreateManager() + protected override void OnCreate() { throw new AssertionException(""); } @@ -125,28 +125,27 @@ protected override void OnUpdate() { } } [Test] [StandaloneFixme] - public void SystemThrowingInOnCreateManagerIsRemoved() + public void SystemThrowingInOnCreateIsRemoved() { var world = new World("WorldX"); - world.GetOrCreateManager(); - Assert.AreEqual(1, world.BehaviourManagers.Count()); + Assert.AreEqual(0, world.Systems.Count()); - Assert.Throws(() => world.GetOrCreateManager()); + Assert.Throws(() => world.GetOrCreateSystem()); // throwing during OnCreateManager does not add the manager to the behaviour manager list - Assert.AreEqual(1, world.BehaviourManagers.Count()); - + Assert.AreEqual(0, world.Systems.Count()); + world.Dispose(); } [DisableAutoCreation] class SystemIsAccessibleDuringOnCreateManagerSystem : ComponentSystem { - protected override void OnCreateManager() + protected override void OnCreate() { - Assert.AreEqual(this, World.GetOrCreateManager()); + Assert.AreEqual(this, World.GetOrCreateSystem()); } - + protected override void OnUpdate() { } } [Test] @@ -154,14 +153,13 @@ protected override void OnUpdate() { } public void SystemIsAccessibleDuringOnCreateManager () { var world = new World("WorldX"); - world.GetOrCreateManager(); - Assert.AreEqual(1, world.BehaviourManagers.Count()); - world.CreateManager(); - Assert.AreEqual(2, world.BehaviourManagers.Count()); - + Assert.AreEqual(0, world.Systems.Count()); + world.CreateSystem(); + Assert.AreEqual(1, world.Systems.Count()); + world.Dispose(); } - - //@TODO: Test for adding a manager from one world to another. + + //@TODO: Test for adding a manager from one world to another. } } diff --git a/Unity.Entities.Tests/WriteGroupTests.cs b/Unity.Entities.Tests/WriteGroupTests.cs index e4dffe55..525eff75 100644 --- a/Unity.Entities.Tests/WriteGroupTests.cs +++ b/Unity.Entities.Tests/WriteGroupTests.cs @@ -47,13 +47,12 @@ struct TestInputD : IComponentData [Test] - [StandaloneFixme] public void WG_AllOnlyMatchesExplicit() { var archetype0 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { @@ -61,7 +60,7 @@ public void WG_AllOnlyMatchesExplicit() ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); m_Manager.CreateEntity(archetype0); @@ -75,10 +74,9 @@ public void WG_AllOnlyMatchesExplicit() } [Test] - [StandaloneFixme] public void WG_AllOnlyMatchesExplicitLateDefinition() { - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { @@ -86,7 +84,7 @@ public void WG_AllOnlyMatchesExplicitLateDefinition() ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); var archetype0 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC)); @@ -109,7 +107,7 @@ public void WG_AllOnlyMatchesExtended() var archetype0 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { @@ -118,7 +116,7 @@ public void WG_AllOnlyMatchesExtended() ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); m_Manager.CreateEntity(archetype0); @@ -132,13 +130,12 @@ public void WG_AllOnlyMatchesExtended() } [Test] - [StandaloneFixme] public void WG_AnyOnlyMatchesExplicit() { var archetype0 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { Any = new ComponentType[] { @@ -146,7 +143,7 @@ public void WG_AnyOnlyMatchesExplicit() ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); m_Manager.CreateEntity(archetype0); @@ -165,7 +162,7 @@ public void WG_AnyMatchesAll() var archetype0 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { Any = new ComponentType[] { @@ -174,7 +171,7 @@ public void WG_AnyMatchesAll() ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); m_Manager.CreateEntity(archetype0); @@ -193,7 +190,7 @@ public void WG_AnyExplicitlyExcludesExtension() var archetype0 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { Any = new ComponentType[] { @@ -205,7 +202,7 @@ public void WG_AnyExplicitlyExcludesExtension() { ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); m_Manager.CreateEntity(archetype0); @@ -225,14 +222,14 @@ public void WG_AllAllowsDependentWriteGroups() typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestOutputB), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { typeof(TestOutputA), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); m_Manager.CreateEntity(archetype0); @@ -246,21 +243,20 @@ public void WG_AllAllowsDependentWriteGroups() } [Test] - [StandaloneFixme] public void WG_AllExcludesFromDependentWriteGroup() { var archetype0 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestOutputB), typeof(TestInputB), typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestOutputB), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { typeof(TestOutputA), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); m_Manager.CreateEntity(archetype0); @@ -280,8 +276,8 @@ public void WG_NotExcludesWhenOverrideWriteGroup() typeof(TestInputC)); var archetype1 = m_Manager.CreateArchetype(typeof(TestOutputA), typeof(TestOutputB), typeof(TestInputB), typeof(TestInputC), typeof(TestInputD)); - // Not specified Options = EntityArchetypeQueryOptions.FilterWriteGroup means that WriteGroup is being overridden (ignored) - var group0 = m_Manager.CreateComponentGroup(new EntityArchetypeQuery() + // Not specified Options = EntityQueryOptions.FilterWriteGroup means that WriteGroup is being overridden (ignored) + var group0 = m_Manager.CreateEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { diff --git a/Unity.Entities.Tests/ZeroPlayerTests.cs b/Unity.Entities.Tests/ZeroPlayerTests.cs new file mode 100644 index 00000000..fcd68fea --- /dev/null +++ b/Unity.Entities.Tests/ZeroPlayerTests.cs @@ -0,0 +1,56 @@ +using System; +using System.Diagnostics; +using Unity.Jobs; +using NUnit.Framework; +using NUnit.Framework.Constraints; +using Unity.Collections.LowLevel.Unsafe; + +namespace Unity.Entities.Tests +{ + + class ZeroPlayerTests + { +#if ENABLE_UNITY_COLLECTIONS_CHECKS + [Test] + public void AllowSecondaryWriting() + { + AtomicSafetyHandle handle = AtomicSafetyHandle.Create(); + AtomicSafetyHandle.SetAllowSecondaryVersionWriting(handle, false); + AtomicSafetyHandle.UseSecondaryVersion(ref handle); + AtomicSafetyHandle.CheckReadAndThrow(handle); + Assert.Throws(() => AtomicSafetyHandle.CheckWriteAndThrow(handle)); + } + + [Test] + public void ReleaseShouldThrow() + { + AtomicSafetyHandle handle = AtomicSafetyHandle.Create(); + AtomicSafetyHandle.Release(handle); + Assert.Throws(() => AtomicSafetyHandle.CheckReadAndThrow(handle)); + Assert.Throws(() => AtomicSafetyHandle.CheckWriteAndThrow(handle)); + Assert.Throws(() => AtomicSafetyHandle.CheckExistsAndThrow(handle)); + + } + + [Test] + public void CloneAndReleaseOriginalShouldThrow() + { + AtomicSafetyHandle handle = AtomicSafetyHandle.Create(); + AtomicSafetyHandle clone = handle; + AtomicSafetyHandle.Release(handle); + Assert.Throws(() => AtomicSafetyHandle.CheckReadAndThrow(clone)); + Assert.Throws(() => AtomicSafetyHandle.CheckWriteAndThrow(clone)); + } + + [Test] + public void CheckDeallocateShouldThrow() + { + AtomicSafetyHandle handle = AtomicSafetyHandle.Create(); + AtomicSafetyHandle clone = handle; + AtomicSafetyHandle.CheckDeallocateAndThrow(clone); + AtomicSafetyHandle.Release(handle); + Assert.Throws(() => AtomicSafetyHandle.CheckDeallocateAndThrow(clone)); + } +#endif + } +} diff --git a/Unity.Entities.Tests/ZeroPlayerTests.cs.meta b/Unity.Entities.Tests/ZeroPlayerTests.cs.meta new file mode 100644 index 00000000..c75d6b03 --- /dev/null +++ b/Unity.Entities.Tests/ZeroPlayerTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 52cee78bb878f224daba76919fd06a82 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/ArchetypeManager.cs b/Unity.Entities/ArchetypeManager.cs index dcb62765..39441ad0 100644 --- a/Unity.Entities/ArchetypeManager.cs +++ b/Unity.Entities/ArchetypeManager.cs @@ -45,7 +45,7 @@ internal struct ComponentTypeInArchetype public bool IsSystemStateComponent => (TypeIndex & TypeManager.SystemStateTypeFlag) != 0; public bool IsSystemStateSharedComponent => (TypeIndex & TypeManager.SystemStateSharedComponentTypeFlag) == TypeManager.SystemStateSharedComponentTypeFlag; public bool IsSharedComponent => (TypeIndex & TypeManager.SharedComponentTypeFlag) != 0; - public bool IsZeroSized => (TypeIndex & TypeManager.ZeroSizeTypeFlag) != 0; + public bool IsZeroSized => (TypeIndex & TypeManager.ZeroSizeInChunkTypeFlag) != 0; public bool IsChunkComponent => (TypeIndex & TypeManager.ChunkComponentTypeFlag) != 0; public bool HasEntityReferences => (TypeIndex & TypeManager.HasNoEntityReferencesFlag) == 0; @@ -146,45 +146,53 @@ internal enum ChunkFlags LockedEntityOrder = 1 << 1 } - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Explicit)] internal unsafe struct Chunk { - // offset of field in architecture with // 64 / 32 bits // Chunk header START - public Archetype* Archetype; // 0 / 0 - public Entity metaChunkEntity; // 8 / 4 + [FieldOffset(0)] + public Archetype* Archetype; + // 4-byte padding on 32-bit architectures here + + [FieldOffset(8)] + public Entity metaChunkEntity; // This is meant as read-only. // ArchetypeManager.SetChunkCount should be used to change the count. - public int Count; // 16 / 12 - public int Capacity; // 20 / 16 + [FieldOffset(16)] + public int Count; + [FieldOffset(20)] + public int Capacity; // In hybrid mode, archetypes can contain non-ECS-type components which are managed objects. // In order to access them without a lot of overhead we conceptually store an Object[] in each chunk which contains the managed components. // The chunk does not really own the array though since we cannot store managed references in unmanaged memory, // so instead the ArchetypeManager has a list of Object[]s and the chunk just has an int to reference an Object[] by index in that list. - public int ManagedArrayIndex; // 24 / 20 + [FieldOffset(24)] + public int ManagedArrayIndex; - public int ListIndex; // 28 / 24 - public int ListWithEmptySlotsIndex; // 32 / 28 + [FieldOffset(28)] + public int ListIndex; + [FieldOffset(32)] + public int ListWithEmptySlotsIndex; // Incrementing automatically for each chunk - public uint SequenceNumber; // 36 / 32 + [FieldOffset(36)] + public uint SequenceNumber; // Special chunk behaviors - public uint Flags; // 40 / 36 + [FieldOffset(40)] + public uint Flags; - public int Padding1; // 44 / 40 + // 4-byte padding here, available for an int -#if UNITY_32 - public int Padding2; // * / 44 -#endif // Chunk header END // Component data buffer // This is where the actual chunk data starts. // It's declared like this so we can skip the header part of the chunk and just get to the data. - public fixed byte Buffer[4]; // 48 / 48 (must be multiple of 16) + [FieldOffset(48)] // (must be multiple of 16) + public fixed byte Buffer[4]; public const int kChunkSize = 16 * 1024 - 256; // allocate a bit less to allow for header overhead public const int kMaximumEntitiesPerChunk = kChunkSize / 8; @@ -216,21 +224,21 @@ public static int GetChunkBufferSize() return kChunkSize - (sizeof(Chunk) - 4); } - public bool MatchesFilter(MatchingArchetype* match, ref ComponentGroupFilter filter) + public bool MatchesFilter(MatchingArchetype* match, ref EntityQueryFilter filter) { if ((filter.Type & FilterType.SharedComponent) != 0) { var sharedComponentsInChunk = SharedComponentValues; var filteredCount = filter.Shared.Count; - fixed (int* indexInComponentGroupPtr = filter.Shared.IndexInComponentGroup, sharedComponentIndexPtr = + fixed (int* indexInEntityQueryPtr = filter.Shared.IndexInEntityQuery, sharedComponentIndexPtr = filter.Shared.SharedComponentIndex) { for (var i = 0; i < filteredCount; ++i) { - var indexInComponentGroup = indexInComponentGroupPtr[i]; + var indexInEntityQuery = indexInEntityQueryPtr[i]; var sharedComponentIndex = sharedComponentIndexPtr[i]; - var componentIndexInArcheType = match->IndexInArchetype[indexInComponentGroup]; + var componentIndexInArcheType = match->IndexInArchetype[indexInEntityQuery]; var componentIndexInChunk = componentIndexInArcheType - match->Archetype->FirstSharedComponent; if (sharedComponentsInChunk[componentIndexInChunk] != sharedComponentIndex) return false; @@ -245,11 +253,11 @@ public bool MatchesFilter(MatchingArchetype* match, ref ComponentGroupFilter fil var changedCount = filter.Changed.Count; var requiredVersion = filter.RequiredChangeVersion; - fixed (int* indexInComponentGroupPtr = filter.Changed.IndexInComponentGroup) + fixed (int* indexInEntityQueryPtr = filter.Changed.IndexInEntityQuery) { for (var i = 0; i < changedCount; ++i) { - var indexInArchetype = match->IndexInArchetype[indexInComponentGroupPtr[i]]; + var indexInArchetype = match->IndexInArchetype[indexInEntityQueryPtr[i]]; var changeVersion = GetChangeVersion(indexInArchetype); if (ChangeVersionUtility.DidChange(changeVersion, requiredVersion)) @@ -263,9 +271,9 @@ public bool MatchesFilter(MatchingArchetype* match, ref ComponentGroupFilter fil return true; } - public int GetSharedComponentIndex(MatchingArchetype* match, int indexInComponentGroup) + public int GetSharedComponentIndex(MatchingArchetype* match, int indexInEntityQuery) { - var componentIndexInArcheType = match->IndexInArchetype[indexInComponentGroup]; + var componentIndexInArcheType = match->IndexInArchetype[indexInEntityQuery]; var componentIndexInChunk = componentIndexInArcheType - match->Archetype->FirstSharedComponent; return GetSharedComponentValue(componentIndexInChunk); } @@ -601,10 +609,18 @@ public ArchetypeManager(SharedComponentDataManager sharedComponentManager, Entit m_ChunksBySequenceNumber = new NativeHashMap(4096, Allocator.Persistent); m_EmptyChunks = new ChunkList(); m_Archetypes = new ArchetypeList(); + + // Sanity check a few alignments #if UNITY_ASSERTIONS // Buffer should be 16 byte aligned to ensure component data layout itself can gurantee being aligned var offset = UnsafeUtility.GetFieldOffset(typeof(Chunk).GetField("Buffer")); - Assert.IsTrue(offset % 16 == 0, "Chunk buffer must be 16 byte aligned"); + Assert.IsTrue(offset % TypeManager.MaximumSupportedAlignment == 0, $"Chunk buffer must be {TypeManager.MaximumSupportedAlignment} byte aligned (buffer offset at {offset})"); + Assert.IsTrue(sizeof(Entity) == 8, $"Unity.Entities.Entity is expected to be 8 bytes in size (is {sizeof(Entity)}); if this changes, update Chunk explicit layout"); +#endif +#if ENABLE_UNITY_COLLECTIONS_CHECKS + var bufHeaderSize = UnsafeUtility.SizeOf(); + Assert.IsTrue(bufHeaderSize % TypeManager.MaximumSupportedAlignment == 0, + $"BufferHeader total struct size must be a multiple of the max supported alignment ({TypeManager.MaximumSupportedAlignment})"); #endif } @@ -714,6 +730,14 @@ public static void AssertArchetypeComponents(ComponentTypeInArchetype* types, in if(indexInTypeArray != null) *indexInTypeArray = t; + + if(archetype->Types[t] == componentType) + { + Assert.IsTrue(addedComponentType.IgnoreDuplicateAdd, $"{addedComponentType} is already part of the archetype."); + // Tag component type is already there, no new archetype required. + return null; + } + newTypes[t] = componentType; while (t < archetype->TypesCount) { @@ -956,7 +980,11 @@ void ChunkAllocate(void* pointer, int count = 1) where T : struct type->BytesPerInstance = 0; - int maxCapacity = int.MaxValue; + // number of bytes we'll reserve for potential alignment + int alignExtraSpace = 0; + var alignments = stackalloc int[count]; + + int maxCapacity = TypeManager.MaximumChunkCapacity; for (var i = 0; i < count; ++i) { var cType = TypeManager.GetTypeInfo(types[i].TypeIndex); @@ -969,15 +997,17 @@ void ChunkAllocate(void* pointer, int count = 1) where T : struct type->BufferCapacities[i] = cType.BufferCapacity; type->BytesPerInstance += sizeOf; - #if !UNITY_CSHARP_TINY - //@TODO: not supported in tiny type manager maxCapacity = math.min(cType.MaximumChunkCapacity, maxCapacity); - #endif + + // explicitly 0 here for sizeof == 0, so that the usedBytes + // calculation below properly ignores 0-sized components + alignments[i] = sizeOf == 0 ? 0 : cType.AlignmentInChunkInBytes; + alignExtraSpace += alignments[i]; } Assert.IsTrue(maxCapacity >= 1, "MaximumChunkCapacity must be larger than 1"); - type->ChunkCapacity = math.min(chunkDataSize / type->BytesPerInstance, maxCapacity); + type->ChunkCapacity = math.min((chunkDataSize - alignExtraSpace) / type->BytesPerInstance, maxCapacity); #if ENABLE_UNITY_COLLECTIONS_CHECKS if (type->BytesPerInstance > chunkDataSize) @@ -1012,6 +1042,11 @@ void ChunkAllocate(void* pointer, int count = 1) where T : struct var index = type->TypeMemoryOrder[i]; var sizeOf = type->SizeOfs[index]; + // align usedBytes upwards (eating into alignExtraSpace) so that + // this component actually starts at its required alignment. + // Assumption is that the start of the entire data segment is at the + // maximum possible alignment. + usedBytes = TypeManager.AlignUp(usedBytes, alignments[index]); type->Offsets[index] = usedBytes; usedBytes += sizeOf * type->ChunkCapacity; @@ -1048,7 +1083,7 @@ void ChunkAllocate(void* pointer, int count = 1) where T : struct for (var i = 0; i != count; i++) { var ct = TypeManager.GetTypeInfo(types[i].TypeIndex); - #if !UNITY_CSHARP_TINY + #if !NET_DOTS ulong handle = ~0UL; var offsets = ct.EntityOffsets == null ? null : (TypeManager.EntityOffsetInfo*) UnsafeUtility.PinGCArrayAndGetDataAddress(ct.EntityOffsets, out handle); var offsetCount = ct.EntityOffsetCount; @@ -1066,7 +1101,7 @@ void ChunkAllocate(void* pointer, int count = 1) where T : struct scalarPatchInfo = EntityRemapUtility.AppendEntityPatches(scalarPatchInfo, offsets, offsetCount, type->Offsets[i], type->SizeOfs[i]); } - #if !UNITY_CSHARP_TINY + #if !NET_DOTS if(offsets != null) UnsafeUtility.ReleaseGCObject(handle); #endif @@ -1507,7 +1542,7 @@ public void Execute(int index) dstArray[i] = globalSystemVersion; } } - + // Copy chunk count array var dstCountArray = dstArchetype->Chunks.GetChunkEntityCountArray() + dstChunkCount; UnsafeUtility.MemCpy(dstCountArray, srcArchetype->Chunks.GetChunkEntityCountArray(), sizeof(int) * srcChunkCount); diff --git a/Unity.Entities/AssemblyInfo.cs b/Unity.Entities/AssemblyInfo.cs index acde701d..d1b9addc 100644 --- a/Unity.Entities/AssemblyInfo.cs +++ b/Unity.Entities/AssemblyInfo.cs @@ -3,5 +3,6 @@ [assembly: InternalsVisibleTo("Unity.Entities.Editor")] [assembly: InternalsVisibleTo("Unity.Entities.Editor.Tests")] [assembly: InternalsVisibleTo("Unity.Entities.Hybrid")] +[assembly: InternalsVisibleTo("Unity.Entities.Hybrid.Tests")] [assembly: InternalsVisibleTo("Unity.Entities.StaticTypeRegistry")] [assembly: InternalsVisibleTo("Unity.Entities.CPlusPlus")] diff --git a/Unity.Entities/BinarySerialization.cs b/Unity.Entities/BinarySerialization.cs index 4b9b6a64..e3a303c0 100644 --- a/Unity.Entities/BinarySerialization.cs +++ b/Unity.Entities/BinarySerialization.cs @@ -79,7 +79,7 @@ public static void ReadArray(this BinaryReader reader, NativeArray element } } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS public unsafe class StreamBinaryReader : BinaryReader { private Stream stream; diff --git a/Unity.Entities/ComponentJobManager.cs b/Unity.Entities/ComponentJobManager.cs index ea346b5c..563c1ba8 100644 --- a/Unity.Entities/ComponentJobManager.cs +++ b/Unity.Entities/ComponentJobManager.cs @@ -22,13 +22,13 @@ namespace Unity.Entities /// Job component systems that have no other type dependencies have their JobHandles registered on the Entity type /// to ensure that they are completed by CompleteAllJobsAndInvalidateArrays /// - internal unsafe class ComponentJobSafetyManager + internal unsafe struct ComponentJobSafetyManager { private const int kMaxReadJobHandles = 17; private const int kMaxTypes = TypeManager.MaximumTypesCount; - private readonly JobHandle* m_JobDependencyCombineBuffer; - private readonly int m_JobDependencyCombineBufferCount; + private JobHandle* m_JobDependencyCombineBuffer; + private int m_JobDependencyCombineBufferCount; private ComponentSafetyHandle* m_ComponentSafetyHandles; private JobHandle m_ExclusiveTransactionDependency; @@ -40,7 +40,7 @@ internal unsafe class ComponentJobSafetyManager private const int EntityTypeIndex = 1; - public ComponentJobSafetyManager() + public void OnCreate() { #if ENABLE_UNITY_COLLECTIONS_CHECKS m_TempSafety = AtomicSafetyHandle.Create(); @@ -63,6 +63,8 @@ public ComponentJobSafetyManager() #endif m_HasCleanHandles = true; + IsInTransaction = false; + m_ExclusiveTransactionDependency = default(JobHandle); } public bool IsInTransaction { get; private set; } @@ -489,7 +491,7 @@ private struct ComponentSafetyHandle } #if ENABLE_UNITY_COLLECTIONS_CHECKS - private readonly AtomicSafetyHandle m_TempSafety; + private AtomicSafetyHandle m_TempSafety; #endif } } diff --git a/Unity.Entities/ComponentSystem.cs b/Unity.Entities/ComponentSystem.cs index da8b45d5..cfc4a94a 100644 --- a/Unity.Entities/ComponentSystem.cs +++ b/Unity.Entities/ComponentSystem.cs @@ -8,6 +8,7 @@ using System.ComponentModel; using System.Diagnostics; using System.Linq; +using UnityEngine; namespace Unity.Entities { @@ -20,36 +21,159 @@ internal unsafe struct IntList public int Capacity; } - - public unsafe abstract class ComponentSystemBase : ScriptBehaviourManager + public unsafe abstract partial class ComponentSystemBase { -#if !UNITY_ZEROPLAYER - InjectComponentGroupData[] m_InjectedComponentGroups; - InjectFromEntityData m_InjectFromEntityData; -#endif -#if !UNITY_CSHARP_TINY - ComponentGroupArrayStaticCache[] m_CachedComponentGroupArrays; -#endif - ComponentGroup[] m_ComponentGroups; - ComponentGroup[] m_RequiredComponentGroups; + EntityQuery[] m_EntityQueries; + EntityQuery[] m_RequiredEntityQueries; - internal IntList m_JobDependencyForReadingManagers; - internal IntList m_JobDependencyForWritingManagers; + internal IntList m_JobDependencyForReadingSystems; + internal IntList m_JobDependencyForWritingSystems; - uint m_LastSystemVersion; + uint m_LastSystemVersion; - internal ComponentJobSafetyManager m_SafetyManager; - internal EntityManager m_EntityManager; - World m_World; + internal ComponentJobSafetyManager* m_SafetyManager; + internal EntityManager m_EntityManager; + World m_World; - bool m_AlwaysUpdateSystem; - internal bool m_PreviouslyEnabled; + bool m_AlwaysUpdateSystem; + internal bool m_PreviouslyEnabled; public bool Enabled { get; set; } = true; - public ComponentGroup[] ComponentGroups => m_ComponentGroups; + public EntityQuery[] EntityQueries => m_EntityQueries; public uint GlobalSystemVersion => m_EntityManager.GlobalSystemVersion; - public uint LastSystemVersion => m_LastSystemVersion; + public uint LastSystemVersion => m_LastSystemVersion; + + // ============ + +#if UNITY_EDITOR + private UnityEngine.Profiling.CustomSampler m_Sampler; +#endif + +#if !NET_DOTS +#if ENABLE_UNITY_COLLECTIONS_CHECKS + private static HashSet s_ObsoleteAPICheckedTypes = new HashSet(); + + void CheckForObsoleteAPI() + { + var type = this.GetType(); + while (type != typeof(ComponentSystemBase)) + { + if (s_ObsoleteAPICheckedTypes.Contains(type)) + break; + + if (type.GetMethod("OnCreateManager", BindingFlags.DeclaredOnly | BindingFlags.Instance) != null) + { + Debug.LogWarning($"The OnCreateManager overload in {type} is obsolete; please rename it to OnCreate. OnCreateManager will stop being called in a future release."); + } + + if (type.GetMethod("OnDestroyManager", BindingFlags.DeclaredOnly | BindingFlags.Instance) != null) + { + Debug.LogWarning($"The OnDestroyManager overload in {type} is obsolete; please rename it to OnDestroy. OnDestroyManager will stop being called in a future release."); + } + + s_ObsoleteAPICheckedTypes.Add(type); + + type = type.BaseType; + } + } + + protected ComponentSystemBase() + { + CheckForObsoleteAPI(); + } +#endif +#endif + + internal void CreateInstance(World world) + { + OnBeforeCreateInternal(world); + try + { + OnCreateManager(); // DELETE after obsolete period! + OnCreate(); +#if UNITY_EDITOR + var type = GetType(); + m_Sampler = UnityEngine.Profiling.CustomSampler.Create($"{world.Name} {type.FullName}"); +#endif + } + catch + { + OnBeforeDestroyInternal(); + OnAfterDestroyInternal(); + throw; + } + } + + internal void DestroyInstance() + { + OnBeforeDestroyInternal(); + OnDestroy(); + OnDestroyManager(); // DELETE after obsolete period! + OnAfterDestroyInternal(); + } + + protected virtual void OnCreateManager() + { + } + + protected virtual void OnDestroyManager() + { + } + + /// + /// Called when the ComponentSystem/JobComponentSystem is created. + /// When scripts are reloaded, OnCreate will be invoked before the + /// ComponentSystems receives its first OnUpdate call. + /// + protected virtual void OnCreate() + { + } + + /// + /// OnStartRunning is called when the ComponentSystem starts running + /// for the first time, and every time after it was disabled due to no matching entities. + /// + protected virtual void OnStartRunning() + { + } + + /// + /// OnStopRunning is called when no entities would match the system's + /// EntityQueries (and OnStartRunning was executed before). + /// + protected virtual void OnStopRunning() + { + } + + /// + /// Called when the ComponentSystem/JobComponentSystem is destroyed. + /// Will be called when scripts are reloaded or before Play Mode exits before + /// the system is destroyed. + /// + protected virtual void OnDestroy() + { + } + + /// + /// Execute the system immediately. + /// + public void Update() + { +#if UNITY_EDITOR + m_Sampler?.Begin(); +#endif + InternalUpdate(); + +#if UNITY_EDITOR + m_Sampler?.End(); +#endif + } + + protected internal EntityManager EntityManager => m_EntityManager; + protected internal World World => m_World; + + // =================== #if ENABLE_UNITY_COLLECTIONS_CHECKS internal int m_SystemID; @@ -57,7 +181,7 @@ public unsafe abstract class ComponentSystemBase : ScriptBehaviourManager internal ComponentSystemBase GetSystemFromSystemID(World world, int systemID) { - foreach(var m in world.BehaviourManagers) + foreach(var m in world.Systems) { var system = m as ComponentSystemBase; if (system == null) @@ -70,8 +194,11 @@ internal ComponentSystemBase GetSystemFromSystemID(World world, int systemID) } #endif - ref UnsafeList JobDependencyForReadingManagersUnsafeList => ref *(UnsafeList*)UnsafeUtility.AddressOf(ref m_JobDependencyForReadingManagers); - ref UnsafeList JobDependencyForWritingManagersUnsafeList => ref *(UnsafeList*)UnsafeUtility.AddressOf(ref m_JobDependencyForWritingManagers); + ref UnsafeList JobDependencyForReadingSystemsUnsafeList => + ref *(UnsafeList*) UnsafeUtility.AddressOf(ref m_JobDependencyForReadingSystems); + + ref UnsafeList JobDependencyForWritingSystemsUnsafeList => + ref *(UnsafeList*) UnsafeUtility.AddressOf(ref m_JobDependencyForWritingSystems); [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal void CheckExists() @@ -89,11 +216,11 @@ public bool ShouldRunSystem() if (m_AlwaysUpdateSystem) return true; - if (m_RequiredComponentGroups != null) + if (m_RequiredEntityQueries != null) { - for (int i = 0;i != m_RequiredComponentGroups.Length;i++) + for (int i = 0; i != m_RequiredEntityQueries.Length; i++) { - if (m_RequiredComponentGroups[i].IsEmptyIgnoreFilter) + if (m_RequiredEntityQueries[i].IsEmptyIgnoreFilter) return false; } @@ -101,17 +228,17 @@ public bool ShouldRunSystem() } else { - // Systems without component groups should always run. Specifically, - // IJobProcessComponentData adds its component group the first time it's run. - var length = m_ComponentGroups != null ? m_ComponentGroups.Length : 0; + // Systems without queriesDesc should always run. Specifically, + // IJobForEach adds its queriesDesc the first time it's run. + var length = m_EntityQueries != null ? m_EntityQueries.Length : 0; if (length == 0) return true; - // If all the groups are empty, skip it. + // If all the queriesDesc are empty, skip it. // (There’s no way to know what they key value is without other markup) - for (int i = 0;i != length;i++) + for (int i = 0; i != length; i++) { - if (!m_ComponentGroups[i].IsEmptyIgnoreFilter) + if (!m_EntityQueries[i].IsEmptyIgnoreFilter) return true; } @@ -119,106 +246,77 @@ public bool ShouldRunSystem() } } - protected override void OnBeforeCreateManagerInternal(World world) + internal virtual void OnBeforeCreateInternal(World world) { #if ENABLE_UNITY_COLLECTIONS_CHECKS m_SystemID = World.AllocateSystemID(); #endif m_World = world; - m_EntityManager = world.GetOrCreateManager(); + m_EntityManager = world.EntityManager; m_SafetyManager = m_EntityManager.ComponentJobSafetyManager; - m_ComponentGroups = new ComponentGroup[0]; -#if !UNITY_CSHARP_TINY - m_CachedComponentGroupArrays = new ComponentGroupArrayStaticCache[0]; + m_EntityQueries = new EntityQuery[0]; +#if !NET_DOTS m_AlwaysUpdateSystem = GetType().GetCustomAttributes(typeof(AlwaysUpdateSystemAttribute), true).Length != 0; #else m_AlwaysUpdateSystem = true; #endif -#if !UNITY_ZEROPLAYER - ComponentSystemInjection.Inject(this, world, m_EntityManager, out m_InjectedComponentGroups, out m_InjectFromEntityData); - m_InjectFromEntityData.ExtractJobDependencyTypes(this); -#endif - InjectNestedIJobProcessComponentDataJobs(); - - UpdateInjectedComponentGroups(); + InjectNestedIJobForEachJobs(); } - void InjectNestedIJobProcessComponentDataJobs() + void InjectNestedIJobForEachJobs() { #if !UNITY_ZEROPLAYER - // Create ComponentGroup for all nested IJobProcessComponentData jobs - foreach (var nestedType in GetType().GetNestedTypes(BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public)) - JobProcessComponentDataExtensions.GetComponentGroupForIJobProcessComponentData(this, nestedType); + // Create EntityQuery for all nested IJobForEach jobs + foreach (var nestedType in GetType() + .GetNestedTypes(BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public)) + JobForEachExtensions.GetEntityQueryForIJobForEach(this, nestedType); #endif } - protected sealed override void OnAfterDestroyManagerInternal() + internal void OnAfterDestroyInternal() { - foreach (var group in m_ComponentGroups) + foreach (var query in m_EntityQueries) { - #if ENABLE_UNITY_COLLECTIONS_CHECKS - group.DisallowDisposing = null; - #endif - group.Dispose(); +#if ENABLE_UNITY_COLLECTIONS_CHECKS + query.DisallowDisposing = null; +#endif + query.Dispose(); } - m_ComponentGroups = null; + + m_EntityQueries = null; m_EntityManager = null; m_World = null; m_SafetyManager = null; -#if !UNITY_ZEROPLAYER - m_InjectedComponentGroups = null; -#endif -#if !UNITY_CSHARP_TINY - m_CachedComponentGroupArrays = null; -#endif - JobDependencyForReadingManagersUnsafeList.Dispose(); - JobDependencyForWritingManagersUnsafeList.Dispose(); + JobDependencyForReadingSystemsUnsafeList.Dispose(); + JobDependencyForWritingSystemsUnsafeList.Dispose(); } - internal override void InternalUpdate() - { - throw new NotImplementedException(); - } + internal abstract void InternalUpdate(); - protected override void OnBeforeDestroyManagerInternal() + internal virtual void OnBeforeDestroyInternal() { if (m_PreviouslyEnabled) { m_PreviouslyEnabled = false; OnStopRunning(); } - CompleteDependencyInternal(); - UpdateInjectedComponentGroups(); } - protected virtual void OnStartRunning() - { - - } - - protected virtual void OnStopRunning() - { - - } - - protected internal void BeforeUpdateVersioning() + internal void BeforeUpdateVersioning() { m_EntityManager.Entities->IncrementGlobalSystemVersion(); - foreach (var group in m_ComponentGroups) - group.SetFilterChangedRequiredVersion(m_LastSystemVersion); + foreach (var query in m_EntityQueries) + query.SetFilterChangedRequiredVersion(m_LastSystemVersion); } - protected internal void AfterUpdateVersioning() + internal void AfterUpdateVersioning() { m_LastSystemVersion = EntityManager.Entities->GlobalSystemVersion; } - protected internal EntityManager EntityManager => m_EntityManager; - protected internal World World => m_World; - // TODO: this should be made part of UnityEngine? static void ArrayUtilityAdd(ref T[] array, T item) { @@ -257,180 +355,150 @@ public ComponentDataFromEntity GetComponentDataFromEntity(bool isReadOnly return EntityManager.GetComponentDataFromEntity(isReadOnly); } - public void RequireForUpdate(ComponentGroup group) + public void RequireForUpdate(EntityQuery query) { - if (m_RequiredComponentGroups == null) - m_RequiredComponentGroups =new ComponentGroup[1] { group }; + if (m_RequiredEntityQueries == null) + m_RequiredEntityQueries = new EntityQuery[1] {query}; else - ArrayUtilityAdd(ref m_RequiredComponentGroups, group); + ArrayUtilityAdd(ref m_RequiredEntityQueries, query); } public void RequireSingletonForUpdate() { var type = ComponentType.ReadOnly(); - var group = GetComponentGroupInternal(&type, 1); - RequireForUpdate(group); + var query = GetEntityQueryInternal(&type, 1); + RequireForUpdate(query); } public bool HasSingleton() where T : struct, IComponentData { var type = ComponentType.ReadOnly(); - var group = GetComponentGroupInternal(&type, 1); - return !group.IsEmptyIgnoreFilter; + var query = GetEntityQueryInternal(&type, 1); + return !query.IsEmptyIgnoreFilter; } public T GetSingleton() where T : struct, IComponentData { var type = ComponentType.ReadOnly(); - var group = GetComponentGroupInternal(&type, 1); + var query = GetEntityQueryInternal(&type, 1); - return group.GetSingleton(); + return query.GetSingleton(); } public void SetSingleton(T value) where T : struct, IComponentData { var type = ComponentType.ReadWrite(); - var group = GetComponentGroupInternal(&type, 1); - group.SetSingleton(value); + var query = GetEntityQueryInternal(&type, 1); + query.SetSingleton(value); } public Entity GetSingletonEntity() where T : struct, IComponentData { var type = ComponentType.ReadOnly(); - var group = GetComponentGroupInternal(&type, 1); + var query = GetEntityQueryInternal(&type, 1); - return group.GetSingletonEntity(); + return query.GetSingletonEntity(); } internal void AddReaderWriter(ComponentType componentType) { - if (CalculateReaderWriterDependency.Add(componentType, ref JobDependencyForReadingManagersUnsafeList, ref JobDependencyForWritingManagersUnsafeList)) + if (CalculateReaderWriterDependency.Add(componentType, ref JobDependencyForReadingSystemsUnsafeList, + ref JobDependencyForWritingSystemsUnsafeList)) { CompleteDependencyInternal(); } } - internal void AddReaderWriters(ComponentGroup group) + internal void AddReaderWriters(EntityQuery query) { - if (group.AddReaderWritersToLists(ref JobDependencyForReadingManagersUnsafeList, ref JobDependencyForWritingManagersUnsafeList)) + if (query.AddReaderWritersToLists(ref JobDependencyForReadingSystemsUnsafeList, + ref JobDependencyForWritingSystemsUnsafeList)) { CompleteDependencyInternal(); } } - internal ComponentGroup GetComponentGroupInternal(ComponentType* componentTypes, int count) + internal EntityQuery GetEntityQueryInternal(ComponentType* componentTypes, int count) { - for (var i = 0; i != m_ComponentGroups.Length; i++) + for (var i = 0; i != m_EntityQueries.Length; i++) { - if (m_ComponentGroups[i].CompareComponents(componentTypes, count)) - return m_ComponentGroups[i]; + if (m_EntityQueries[i].CompareComponents(componentTypes, count)) + return m_EntityQueries[i]; } - var group = EntityManager.CreateComponentGroup(componentTypes, count); + var query = EntityManager.CreateEntityQuery(componentTypes, count); - AddReaderWriters(group); - AfterGroupCreated(group); + AddReaderWriters(query); + AfterQueryCreated(query); - return group; + return query; } - internal ComponentGroup GetComponentGroupInternal(ComponentType[] componentTypes) + internal EntityQuery GetEntityQueryInternal(ComponentType[] componentTypes) { fixed (ComponentType* componentTypesPtr = componentTypes) { - return GetComponentGroupInternal(componentTypesPtr, componentTypes.Length); + return GetEntityQueryInternal(componentTypesPtr, componentTypes.Length); } } - internal ComponentGroup GetComponentGroupInternal(EntityArchetypeQuery[] query) + internal EntityQuery GetEntityQueryInternal(EntityQueryDesc[] desc) { - for (var i = 0; i != m_ComponentGroups.Length; i++) + for (var i = 0; i != m_EntityQueries.Length; i++) { - if (m_ComponentGroups[i].CompareQuery(query)) - return m_ComponentGroups[i]; + if (m_EntityQueries[i].CompareQuery(desc)) + return m_EntityQueries[i]; } - var group = EntityManager.CreateComponentGroup(query); + var query = EntityManager.CreateEntityQuery(desc); - AddReaderWriters(group); - AfterGroupCreated(group); + AddReaderWriters(query); + AfterQueryCreated(query); - return group; + return query; } - void AfterGroupCreated(ComponentGroup group) + void AfterQueryCreated(EntityQuery query) { - group.SetFilterChangedRequiredVersion(m_LastSystemVersion); + query.SetFilterChangedRequiredVersion(m_LastSystemVersion); #if ENABLE_UNITY_COLLECTIONS_CHECKS - group.DisallowDisposing = "ComponentGroup.Dispose() may not be called on a ComponentGroup created with ComponentSystem.GetComponentGroup. The ComponentGroup will automatically be disposed by the ComponentSystem."; + query.DisallowDisposing = + "EntityQuery.Dispose() may not be called on a EntityQuery created with ComponentSystem.GetEntityQuery. The EntityQuery will automatically be disposed by the ComponentSystem."; #endif - ArrayUtilityAdd(ref m_ComponentGroups, group); + ArrayUtilityAdd(ref m_EntityQueries, query); } - protected internal ComponentGroup GetComponentGroup(params ComponentType[] componentTypes) + protected internal EntityQuery GetEntityQuery(params ComponentType[] componentTypes) { - return GetComponentGroupInternal(componentTypes); - } - protected ComponentGroup GetComponentGroup(NativeArray componentTypes) - { - return GetComponentGroupInternal((ComponentType*)componentTypes.GetUnsafeReadOnlyPtr(), componentTypes.Length); + return GetEntityQueryInternal(componentTypes); } - protected internal ComponentGroup GetComponentGroup(params EntityArchetypeQuery[] query) + protected EntityQuery GetEntityQuery(NativeArray componentTypes) { - return GetComponentGroupInternal(query); + return GetEntityQueryInternal((ComponentType*) componentTypes.GetUnsafeReadOnlyPtr(), + componentTypes.Length); } -#if !UNITY_CSHARP_TINY - [Obsolete("GetEntities has been deprecated. Use ComponentSystem.ForEach to access managed components.")] - protected ComponentGroupArray GetEntities() where T : struct + protected internal EntityQuery GetEntityQuery(params EntityQueryDesc[] queryDesc) { - for (var i = 0; i != m_CachedComponentGroupArrays.Length; i++) - { - if (m_CachedComponentGroupArrays[i].CachedType == typeof(T)) - return new ComponentGroupArray(m_CachedComponentGroupArrays[i]); - } - - var cache = new ComponentGroupArrayStaticCache(typeof(T), EntityManager, this); - ArrayUtilityAdd(ref m_CachedComponentGroupArrays, cache); - return new ComponentGroupArray(cache); - } -#endif - - protected void UpdateInjectedComponentGroups() - { -#if !UNITY_ZEROPLAYER - if (null == m_InjectedComponentGroups) - return; - - ulong gchandle; - var pinnedSystemPtr = (byte*)UnsafeUtility.PinGCObjectAndGetAddress(this, out gchandle); - - try - { - foreach (var group in m_InjectedComponentGroups) - group.UpdateInjection (pinnedSystemPtr); - - m_InjectFromEntityData.UpdateInjection(pinnedSystemPtr, EntityManager); - } - catch - { - UnsafeUtility.ReleaseGCObject(gchandle); - throw; - } - UnsafeUtility.ReleaseGCObject(gchandle); -#endif + return GetEntityQueryInternal(queryDesc); } internal void CompleteDependencyInternal() { - m_SafetyManager.CompleteDependenciesNoChecks(m_JobDependencyForReadingManagers.p, m_JobDependencyForReadingManagers.Count, m_JobDependencyForWritingManagers.p, m_JobDependencyForWritingManagers.Count); + m_SafetyManager->CompleteDependenciesNoChecks(m_JobDependencyForReadingSystems.p, + m_JobDependencyForReadingSystems.Count, m_JobDependencyForWritingSystems.p, + m_JobDependencyForWritingSystems.Count); } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GetEntities has been deprecated. Use Entities.ForEach to access managed components. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + protected void GetEntities() where T : struct { } } public abstract partial class ComponentSystem : ComponentSystemBase @@ -443,6 +511,8 @@ public abstract partial class ComponentSystem : ComponentSystemBase protected internal void InitEntityQueryCache(int cacheSize) => m_EntityQueryCache = new EntityQueryCache(cacheSize); + internal EntityQueryCache EntityQueryCache => m_EntityQueryCache; + internal EntityQueryCache GetOrCreateEntityQueryCache() => m_EntityQueryCache ?? (m_EntityQueryCache = new EntityQueryCache()); @@ -452,7 +522,6 @@ unsafe void BeforeOnUpdate() { BeforeUpdateVersioning(); CompleteDependencyInternal(); - UpdateInjectedComponentGroups(); m_DeferredEntities = new EntityCommandBuffer(Allocator.TempJob, -1); } @@ -516,18 +585,20 @@ internal sealed override void InternalUpdate() } } - protected sealed override void OnBeforeCreateManagerInternal(World world) + internal sealed override void OnBeforeCreateInternal(World world) { - base.OnBeforeCreateManagerInternal(world); + base.OnBeforeCreateInternal(world); } - protected sealed override void OnBeforeDestroyManagerInternal() + internal sealed override void OnBeforeDestroyInternal() { - base.OnBeforeDestroyManagerInternal(); + base.OnBeforeDestroyInternal(); } /// - /// Called once per frame on the main thread. + /// Called once per frame on the main thread when any of this system's + /// EntityQueries would match, or if the system has the AlwaysUpdate + /// attribute. /// protected abstract void OnUpdate(); } @@ -535,14 +606,11 @@ protected sealed override void OnBeforeDestroyManagerInternal() public abstract class JobComponentSystem : ComponentSystemBase { JobHandle m_PreviousFrameDependency; - EntityCommandBufferSystem[] m_EntityCommandBufferSystemList; unsafe JobHandle BeforeOnUpdate() { BeforeUpdateVersioning(); - UpdateInjectedComponentGroups(); - // We need to wait on all previous frame dependencies, otherwise it is possible that we create infinitely long dependency chains // without anyone ever waiting on it m_PreviousFrameDependency.Complete(); @@ -558,13 +626,6 @@ unsafe void AfterOnUpdate(JobHandle outputJob, bool throwException) AddDependencyInternal(outputJob); - // Notify all injected barrier systems that they will need to sync on any jobs we spawned. - // This is conservative currently - the barriers will sync on too much if we use more than one. - for (int i = 0; i < m_EntityCommandBufferSystemList.Length; ++i) - { - m_EntityCommandBufferSystemList[i].AddJobHandleForProducer(outputJob); - } - #if ENABLE_UNITY_COLLECTIONS_CHECKS if (!JobsUtility.JobDebuggerEnabled) @@ -582,15 +643,15 @@ unsafe void AfterOnUpdate(JobHandle outputJob, bool throwException) // Which seems like debug code might have side-effects string dependencyError = null; - for (var index = 0; index < m_JobDependencyForReadingManagers.Count && dependencyError == null; index++) + for (var index = 0; index < m_JobDependencyForReadingSystems.Count && dependencyError == null; index++) { - var type = m_JobDependencyForReadingManagers.p[index]; + var type = m_JobDependencyForReadingSystems.p[index]; dependencyError = CheckJobDependencies(type); } - for (var index = 0; index < m_JobDependencyForWritingManagers.Count && dependencyError == null; index++) + for (var index = 0; index < m_JobDependencyForWritingSystems.Count && dependencyError == null; index++) { - var type = m_JobDependencyForWritingManagers.p[index]; + var type = m_JobDependencyForWritingSystems.p[index]; dependencyError = CheckJobDependencies(type); } @@ -644,17 +705,9 @@ internal sealed override void InternalUpdate() } } -#if !UNITY_ZEROPLAYER - protected sealed override void OnBeforeCreateManagerInternal(World world) - { - base.OnBeforeCreateManagerInternal(world); - - m_EntityCommandBufferSystemList = ComponentSystemInjection.GetAllInjectedManagers(this, world); - } -#endif - protected sealed override void OnBeforeDestroyManagerInternal() + internal sealed override void OnBeforeDestroyInternal() { - base.OnBeforeDestroyManagerInternal(); + base.OnBeforeDestroyInternal(); m_PreviousFrameDependency.Complete(); } @@ -669,7 +722,7 @@ public BufferFromEntity GetBufferFromEntity(bool isReadOnly = false) where #if ENABLE_UNITY_COLLECTIONS_CHECKS unsafe string CheckJobDependencies(int type) { - var h = m_SafetyManager.GetSafetyHandle(type, true); + var h = m_SafetyManager->GetSafetyHandle(type, true); var readerCount = AtomicSafetyHandle.GetReaderArray(h, 0, IntPtr.Zero); JobHandle* readers = stackalloc JobHandle[readerCount]; @@ -677,11 +730,11 @@ unsafe string CheckJobDependencies(int type) for (var i = 0; i < readerCount; ++i) { - if (!m_SafetyManager.HasReaderOrWriterDependency(type, readers[i])) + if (!m_SafetyManager->HasReaderOrWriterDependency(type, readers[i])) return $"The system {GetType()} reads {TypeManager.GetType(type)} via {AtomicSafetyHandle.GetReaderName(h, i)} but that type was not returned as a job dependency. To ensure correct behavior of other systems, the job or a dependency of it must be returned from the OnUpdate method."; } - if (!m_SafetyManager.HasReaderOrWriterDependency(type, AtomicSafetyHandle.GetWriter(h))) + if (!m_SafetyManager->HasReaderOrWriterDependency(type, AtomicSafetyHandle.GetWriter(h))) return $"The system {GetType()} writes {TypeManager.GetType(type)} via {AtomicSafetyHandle.GetWriterName(h)} but that was not returned as a job dependency. To ensure correct behavior of other systems, the job or a dependency of it must be returned from the OnUpdate method."; return null; @@ -689,28 +742,28 @@ unsafe string CheckJobDependencies(int type) unsafe void EmergencySyncAllJobs() { - for (int i = 0;i != m_JobDependencyForReadingManagers.Count;i++) + for (int i = 0;i != m_JobDependencyForReadingSystems.Count;i++) { - int type = m_JobDependencyForReadingManagers.p[i]; - AtomicSafetyHandle.EnforceAllBufferJobsHaveCompleted(m_SafetyManager.GetSafetyHandle(type, true)); + int type = m_JobDependencyForReadingSystems.p[i]; + AtomicSafetyHandle.EnforceAllBufferJobsHaveCompleted(m_SafetyManager->GetSafetyHandle(type, true)); } - for (int i = 0;i != m_JobDependencyForWritingManagers.Count;i++) + for (int i = 0;i != m_JobDependencyForWritingSystems.Count;i++) { - int type = m_JobDependencyForWritingManagers.p[i]; - AtomicSafetyHandle.EnforceAllBufferJobsHaveCompleted(m_SafetyManager.GetSafetyHandle(type, true)); + int type = m_JobDependencyForWritingSystems.p[i]; + AtomicSafetyHandle.EnforceAllBufferJobsHaveCompleted(m_SafetyManager->GetSafetyHandle(type, true)); } } #endif unsafe JobHandle GetDependency () { - return m_SafetyManager.GetDependency(m_JobDependencyForReadingManagers.p, m_JobDependencyForReadingManagers.Count, m_JobDependencyForWritingManagers.p, m_JobDependencyForWritingManagers.Count); + return m_SafetyManager->GetDependency(m_JobDependencyForReadingSystems.p, m_JobDependencyForReadingSystems.Count, m_JobDependencyForWritingSystems.p, m_JobDependencyForWritingSystems.Count); } unsafe void AddDependencyInternal(JobHandle dependency) { - m_PreviousFrameDependency = m_SafetyManager.AddDependency(m_JobDependencyForReadingManagers.p, m_JobDependencyForReadingManagers.Count, m_JobDependencyForWritingManagers.p, m_JobDependencyForWritingManagers.Count, dependency); + m_PreviousFrameDependency = m_SafetyManager->AddDependency(m_JobDependencyForReadingSystems.p, m_JobDependencyForReadingSystems.Count, m_JobDependencyForWritingSystems.p, m_JobDependencyForWritingSystems.Count, dependency); } } @@ -753,7 +806,7 @@ public EntityCommandBuffer CreateCommandBuffer() /// by this EntityCommandBufferSystem, to prevent the command buffer from being played back before /// it's complete. The general usage looks like: /// MyEntityCommandBufferSystem _barrier; - /// // in OnCreateManager(): + /// // in OnCreate(): /// _barrier = World.GetOrCreateManager(); /// // in OnUpdate(): /// EntityCommandBuffer cmd = _barrier.CreateCommandBuffer(); @@ -769,9 +822,9 @@ public void AddJobHandleForProducer(JobHandle producerJob) m_ProducerHandle = JobHandle.CombineDependencies(m_ProducerHandle, producerJob); } - protected override void OnCreateManager() + protected override void OnCreate() { - base.OnCreateManager(); + base.OnCreate(); #if ENABLE_UNITY_COLLECTIONS_CHECKS m_PendingBuffers = new List(); @@ -780,7 +833,7 @@ protected override void OnCreateManager() #endif } - protected override void OnDestroyManager() + protected override void OnDestroy() { FlushBuffers(false); @@ -788,7 +841,7 @@ protected override void OnDestroyManager() m_PendingBuffers.Dispose(); #endif - base.OnDestroyManager(); + base.OnDestroy(); } protected override void OnUpdate() @@ -861,7 +914,7 @@ private void FlushBuffers(bool playBack) #if ENABLE_UNITY_COLLECTIONS_CHECKS if (playbackErrorLog != null) { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS string exceptionMessage = playbackErrorLog.Aggregate((str1, str2) => str1 + "\n" + str2); #else foreach (var err in playbackErrorLog) diff --git a/Unity.Entities/ComponentSystemGroup.cs b/Unity.Entities/ComponentSystemGroup.cs index eddd2780..55a2af9b 100644 --- a/Unity.Entities/ComponentSystemGroup.cs +++ b/Unity.Entities/ComponentSystemGroup.cs @@ -9,7 +9,7 @@ public class CircularSystemDependencyException : Exception public CircularSystemDependencyException(IEnumerable chain) { Chain = chain; -#if UNITY_CSHARP_TINY +#if NET_DOTS var lines = new List(); Console.WriteLine($"The following systems form a circular dependency cycle (check their [UpdateBefore]/[UpdateAfter] attributes):"); foreach (var s in Chain) @@ -23,7 +23,7 @@ public CircularSystemDependencyException(IEnumerable chain) public IEnumerable Chain { get; } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS public override string Message { get @@ -147,7 +147,7 @@ public TypeHeapElement(int index, Type t) } public int CompareTo(TypeHeapElement other) { -#if UNITY_CSHARP_TINY +#if NET_DOTS // Workaround for missing string.CompareTo() in HPC#. This is not a fully compatible substitute, // but should be suitable for comparing system names. if (typeName.Length < other.typeName.Length) @@ -170,7 +170,7 @@ public int CompareTo(TypeHeapElement other) // Tiny doesn't have a data structure that can take Type as a key. // For now, this gives Tiny a linear search. Would like to do better. -#if !UNITY_CSHARP_TINY +#if !NET_DOTS private Dictionary lookupDictionary = null; private int LookupSysAndDep(Type t, SysAndDep[] array) { @@ -200,7 +200,7 @@ private int LookupSysAndDep(Type t, SysAndDep[] array) public virtual void SortSystemUpdateList() { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS lookupDictionary = null; #endif // Populate dictionary mapping systemType to system-and-before/after-types. @@ -238,7 +238,7 @@ public virtual void SortSystemUpdateList() int depIndex = LookupSysAndDep(dep.SystemType, sysAndDep); if (depIndex < 0) { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS Debug.LogWarning("Ignoring invalid [UpdateBefore] dependency for " + sys.GetType() + ": " + dep.SystemType + " must be a member of the same ComponentSystemGroup."); #else Debug.LogWarning("WARNING: invalid [UpdateBefore] dependency:"); @@ -257,7 +257,7 @@ public virtual void SortSystemUpdateList() int depIndex = LookupSysAndDep(dep.SystemType, sysAndDep); if (depIndex < 0) { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS Debug.LogWarning("Ignoring invalid [UpdateAfter] dependency for " + sys.GetType() + ": " + dep.SystemType + " must be a member of the same ComponentSystemGroup."); #else Debug.LogWarning("WARNING: invalid [UpdateAfter] dependency:"); @@ -333,7 +333,7 @@ public virtual void SortSystemUpdateList() } -#if UNITY_CSHARP_TINY +#if NET_DOTS public void RecursiveLogToConsole() { foreach (var sys in m_systemsToUpdate) diff --git a/Unity.Entities/CopyUtility.cs b/Unity.Entities/CopyUtility.cs index 23192741..aadb4834 100644 --- a/Unity.Entities/CopyUtility.cs +++ b/Unity.Entities/CopyUtility.cs @@ -4,24 +4,6 @@ namespace Unity.Entities { - /// - /// Copy ComponentDataArray to NativeArray Job. - /// - /// Component data type stored in ComponentDataArray to be copied to NativeArray - [BurstCompile] - [System.Obsolete("CopyComponentData is deprecated. Use ComponentGroup.ToComponentDataArray instead.")] - public struct CopyComponentData : IJobParallelFor - where T : struct, IComponentData - { - [ReadOnly] public ComponentDataArray Source; - public NativeArray Results; - - public void Execute(int index) - { - Results[index] = Source[index]; - } - } - /// /// Assign Value to each element of NativeArray /// @@ -39,20 +21,4 @@ public void Execute(int index) Source[index] = Value; } } - - /// - /// Copy Entities from EntityArray to NativeArray - /// - [BurstCompile] - [System.Obsolete("CopyEntities is deprecated. Use ComponentGroup.ToEntityArray instead.")] - public struct CopyEntities : IJobParallelFor - { - [ReadOnly] public EntityArray Source; - public NativeArray Results; - - public void Execute(int index) - { - Results[index] = Source[index]; - } - } } diff --git a/Unity.Entities/DebugView.cs b/Unity.Entities/DebugView.cs index cf659784..a0cbb2c4 100644 --- a/Unity.Entities/DebugView.cs +++ b/Unity.Entities/DebugView.cs @@ -140,7 +140,7 @@ public unsafe EntityGroupData*[] Items } } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS sealed unsafe class DebugViewUtility { [DebuggerDisplay("{name} {entity} Components: {components.Count}")] @@ -212,7 +212,7 @@ public static Components GetComponents(EntityManager m, Entity e) } #endif -#if !UNITY_CSHARP_TINY +#if !NET_DOTS sealed class EntityManagerDebugView { private EntityManager m_target; @@ -372,7 +372,7 @@ sealed class ArchetypeChunkDebugView } #endif -#if !UNITY_CSHARP_TINY +#if !NET_DOTS sealed class EntityArchetypeDebugView { private EntityArchetype m_EntityArchetype; diff --git a/Unity.Entities/Injection/DefaultTinyWorldInitialization.cs b/Unity.Entities/DefaultTinyWorldInitialization.cs similarity index 84% rename from Unity.Entities/Injection/DefaultTinyWorldInitialization.cs rename to Unity.Entities/DefaultTinyWorldInitialization.cs index 288434ea..e09f4800 100644 --- a/Unity.Entities/Injection/DefaultTinyWorldInitialization.cs +++ b/Unity.Entities/DefaultTinyWorldInitialization.cs @@ -29,8 +29,6 @@ public static World InitializeWorld(string worldName) { var world = new World(worldName); World.Active = world; - // Entity manager must be first so that other things can find it. - world.AddManager(new EntityManager()); return world; } @@ -46,13 +44,13 @@ public static void InitializeSystems(World world) // Create top level presentation system and simulation systems. InitializationSystemGroup initializationSystemGroup = new InitializationSystemGroup(); - world.AddManager(initializationSystemGroup); + world.AddSystem(initializationSystemGroup); SimulationSystemGroup simulationSystemGroup = new SimulationSystemGroup(); - world.AddManager(simulationSystemGroup); + world.AddSystem(simulationSystemGroup); PresentationSystemGroup presentationSystemGroup = new PresentationSystemGroup(); - world.AddManager(presentationSystemGroup); + world.AddSystem(presentationSystemGroup); // Create the working set of systems. int nSystems = 0; @@ -74,14 +72,14 @@ public static void InitializeSystems(World world) continue; } - if (world.GetExistingManager(allSystemTypes[i]) != null) + if (world.GetExistingSystem(allSystemTypes[i]) != null) continue; #if WRITE_LOG Console.WriteLine(allSystemNames[i]); #endif systemTypes[nSystems] = allSystemTypes[i]; systems[nSystems] = TypeManager.ConstructSystem(allSystemTypes[i]); - world.AddManager(systems[nSystems]); + world.AddSystem(systems[nSystems]); nSystems++; } #if WRITE_LOG @@ -102,7 +100,7 @@ public static void InitializeSystems(World world) for (int g = 0; g < groups.Length; ++g) { var groupType = groups[g] as UpdateInGroupAttribute; - var groupSystem = world.GetExistingManager(groupType.GroupType) as ComponentSystemGroup; + var groupSystem = world.GetExistingSystem(groupType.GroupType) as ComponentSystemGroup; if (groupSystem == null) throw new Exception("DefaultTinyWorldInitialization failed to find existing SystemGroup."); @@ -113,9 +111,9 @@ public static void InitializeSystems(World world) public static void SortSystems(World world) { - var initializationSystemGroup = world.GetExistingManager(); - var simulationSystemGroup = world.GetExistingManager(); - var presentationSystemGroup = world.GetExistingManager(); + var initializationSystemGroup = world.GetExistingSystem(); + var simulationSystemGroup = world.GetExistingSystem(); + var presentationSystemGroup = world.GetExistingSystem(); initializationSystemGroup.SortSystemUpdateList(); simulationSystemGroup.SortSystemUpdateList(); diff --git a/Unity.Entities/Injection/DefaultTinyWorldInitialization.cs.meta b/Unity.Entities/DefaultTinyWorldInitialization.cs.meta similarity index 100% rename from Unity.Entities/Injection/DefaultTinyWorldInitialization.cs.meta rename to Unity.Entities/DefaultTinyWorldInitialization.cs.meta diff --git a/Unity.Entities/DefaultWorld.cs b/Unity.Entities/DefaultWorld.cs index ba0eb855..eb796219 100644 --- a/Unity.Entities/DefaultWorld.cs +++ b/Unity.Entities/DefaultWorld.cs @@ -5,12 +5,10 @@ namespace Unity.Entities { [DisableAutoCreation] - [Preserve] [UnityEngine.ExecuteAlways] public class BeginInitializationEntityCommandBufferSystem : EntityCommandBufferSystem {} [DisableAutoCreation] - [Preserve] [UnityEngine.ExecuteAlways] public class EndInitializationEntityCommandBufferSystem : EntityCommandBufferSystem {} @@ -19,10 +17,10 @@ public class InitializationSystemGroup : ComponentSystemGroup private BeginInitializationEntityCommandBufferSystem m_BeginEntityCommandBufferSystem; private EndInitializationEntityCommandBufferSystem m_EndEntityCommandBufferSystem; - protected override void OnCreateManager() + protected override void OnCreate() { - m_BeginEntityCommandBufferSystem = World.GetOrCreateManager(); - m_EndEntityCommandBufferSystem = World.GetOrCreateManager(); + m_BeginEntityCommandBufferSystem = World.GetOrCreateSystem(); + m_EndEntityCommandBufferSystem = World.GetOrCreateSystem(); m_systemsToUpdate.Add(m_BeginEntityCommandBufferSystem); m_systemsToUpdate.Add(m_EndEntityCommandBufferSystem); } @@ -53,12 +51,10 @@ public override void SortSystemUpdateList() } [DisableAutoCreation] - [Preserve] [UnityEngine.ExecuteAlways] public class BeginSimulationEntityCommandBufferSystem : EntityCommandBufferSystem {} [DisableAutoCreation] - [Preserve] [UnityEngine.ExecuteAlways] public class EndSimulationEntityCommandBufferSystem : EntityCommandBufferSystem {} @@ -70,11 +66,11 @@ public class SimulationSystemGroup : ComponentSystemGroup private BeginSimulationEntityCommandBufferSystem m_BeginEntityCommandBufferSystem; private LateSimulationSystemGroup m_lateSimulationGroup; private EndSimulationEntityCommandBufferSystem m_EndEntityCommandBufferSystem; - protected override void OnCreateManager() + protected override void OnCreate() { - m_BeginEntityCommandBufferSystem = World.GetOrCreateManager(); - m_lateSimulationGroup = World.GetOrCreateManager(); - m_EndEntityCommandBufferSystem = World.GetOrCreateManager(); + m_BeginEntityCommandBufferSystem = World.GetOrCreateSystem(); + m_lateSimulationGroup = World.GetOrCreateSystem(); + m_EndEntityCommandBufferSystem = World.GetOrCreateSystem(); m_systemsToUpdate.Add(m_BeginEntityCommandBufferSystem); m_systemsToUpdate.Add(m_lateSimulationGroup); m_systemsToUpdate.Add(m_EndEntityCommandBufferSystem); @@ -109,12 +105,10 @@ s is LateSimulationSystemGroup || } [DisableAutoCreation] - [Preserve] [UnityEngine.ExecuteAlways] public class BeginPresentationEntityCommandBufferSystem : EntityCommandBufferSystem {} [DisableAutoCreation] - [Preserve] [UnityEngine.ExecuteAlways] public class EndPresentationEntityCommandBufferSystem : EntityCommandBufferSystem {} @@ -123,10 +117,10 @@ public class PresentationSystemGroup : ComponentSystemGroup private BeginPresentationEntityCommandBufferSystem m_BeginEntityCommandBufferSystem; private EndPresentationEntityCommandBufferSystem m_EndEntityCommandBufferSystem; - protected override void OnCreateManager() + protected override void OnCreate() { - m_BeginEntityCommandBufferSystem = World.GetOrCreateManager(); - m_EndEntityCommandBufferSystem = World.GetOrCreateManager(); + m_BeginEntityCommandBufferSystem = World.GetOrCreateSystem(); + m_EndEntityCommandBufferSystem = World.GetOrCreateSystem(); m_systemsToUpdate.Add(m_BeginEntityCommandBufferSystem); m_systemsToUpdate.Add(m_EndEntityCommandBufferSystem); } diff --git a/Unity.Entities/DeprecatedAPIStubs.cs b/Unity.Entities/DeprecatedAPIStubs.cs new file mode 100644 index 00000000..c8188fb9 --- /dev/null +++ b/Unity.Entities/DeprecatedAPIStubs.cs @@ -0,0 +1,54 @@ +using System; +using System.ComponentModel; + +namespace Unity.Entities +{ + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("ComponentDataArray is deprecated. Use IJobForEach or EntityQuery ToComponentDataArray/CopyFromComponentDataArray APIs instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public unsafe struct ComponentDataArray where T : struct, IComponentData { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("SharedComponentDataArray is deprecated. Use ArchetypeChunk.GetSharedComponentData. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public struct SharedComponentDataArray where T : struct, ISharedComponentData { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("BufferArray is deprecated. Use ArchetypeChunk.GetBufferAccessor() instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public unsafe struct BufferArray where T : struct, IBufferElementData { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("EntityArray is deprecated. Use IJobForEachWithEntity or EntityQuery.ToEntityArray(...) instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public unsafe struct EntityArray { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("ComponentGroupArray has been deprecated. Use Entities.ForEach instead to access managed components. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public struct ComponentGroupArray where T : struct { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [AttributeUsage(AttributeTargets.Field)] + [Obsolete("Injection API is deprecated. For struct injection, use the EntityQuery API instead. For ComponentDataFromEntity injection use (Job)ComponentSystem.GetComponentDataFromEntity. For system injection, use World.GetOrCreateManager(). More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public class InjectAttribute : Attribute { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("CopyComponentData is deprecated. Use EntityQuery.ToComponentDataArray instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public struct CopyComponentData + where T : struct, IComponentData { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("CopyEntities is deprecated. Use EntityQuery.ToEntityArray instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public struct CopyEntities { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GameObjectArray has been deprecated. Use ComponentSystem.ForEach or ToTransformArray()[index].gameObject to access entity GameObjects. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public struct GameObjectArray { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("ComponentArray has been deprecated. Use ComponentSystem.ForEach to access managed components. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public struct ComponentArray where T: UnityEngine.Component { } + + public static class ComponentGroupExtensionsForGameObjectArray + { + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GetGameObjectArray has been deprecated. Use ComponentSystem.ForEach or ToTransformArray()[index].gameObject to access entity GameObjects. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public static void GetGameObjectArray(this ComponentGroup group) { } + } +} diff --git a/Unity.Entities.Tests/InjectComponentGroupTests.cs.meta b/Unity.Entities/DeprecatedAPIStubs.cs.meta similarity index 77% rename from Unity.Entities.Tests/InjectComponentGroupTests.cs.meta rename to Unity.Entities/DeprecatedAPIStubs.cs.meta index 111ecf8a..a3843d43 100644 --- a/Unity.Entities.Tests/InjectComponentGroupTests.cs.meta +++ b/Unity.Entities/DeprecatedAPIStubs.cs.meta @@ -1,6 +1,6 @@ fileFormatVersion: 2 -guid: 31ecd4b002f954cbfb4ca96c1a1b9d20 -timeCreated: 1505216351 +guid: bd6e9dca1b719403b9b6246585da9981 +timeCreated: 1504790404 licenseType: Pro MonoImporter: externalObjects: {} diff --git a/Unity.Entities/EntityCommandBuffer.cs b/Unity.Entities/EntityCommandBuffer.cs index 0bced056..8968f8a0 100644 --- a/Unity.Entities/EntityCommandBuffer.cs +++ b/Unity.Entities/EntityCommandBuffer.cs @@ -199,7 +199,9 @@ internal enum ECBCommand SetComponentWithEntityFixUp, AddBuffer, + AddBufferWithEntityFixUp, SetBuffer, + SetBufferWithEntityFixUp, AddSharedComponentData, SetSharedComponentData @@ -393,25 +395,36 @@ internal void AddEntityComponentCommand(EntityCommandBufferChain* chain, int } } - internal BufferHeader* AddEntityBufferCommand(EntityCommandBufferChain* chain, int jobIndex, ECBCommand op, Entity e) where T : struct, IBufferElementData + internal BufferHeader* AddEntityBufferCommand(EntityCommandBufferChain* chain, int jobIndex, ECBCommand op, + Entity e) where T : struct, IBufferElementData { var typeIndex = TypeManager.GetTypeIndex(); var type = TypeManager.GetTypeInfo(); var sizeNeeded = Align(sizeof(EntityBufferCommand) + type.SizeInChunk, 8); ResetCommandBatching(chain); - var data = (EntityBufferCommand*)Reserve(chain, jobIndex, sizeNeeded); + var cmd = (EntityBufferCommand*) Reserve(chain, jobIndex, sizeNeeded); - data->Header.Header.CommandType = (int)op; - data->Header.Header.TotalSize = sizeNeeded; - data->Header.Header.SortIndex = chain->m_LastSortIndex; - data->Header.Entity = e; - data->ComponentTypeIndex = typeIndex; - data->ComponentSize = type.SizeInChunk; + cmd->Header.Header.CommandType = (int) op; + cmd->Header.Header.TotalSize = sizeNeeded; + cmd->Header.Header.SortIndex = chain->m_LastSortIndex; + cmd->Header.Entity = e; + cmd->ComponentTypeIndex = typeIndex; + cmd->ComponentSize = type.SizeInChunk; - BufferHeader.Initialize(&data->TempBuffer, type.BufferCapacity); + BufferHeader* header = &cmd->TempBuffer; + BufferHeader.Initialize(header, type.BufferCapacity); - return &data->TempBuffer; + if (TypeManager.HasEntityReferences(typeIndex)) + { + + if (op == ECBCommand.AddBuffer) + cmd->Header.Header.CommandType = (int) ECBCommand.AddBufferWithEntityFixUp; + else if (op == ECBCommand.SetBuffer) + cmd->Header.Header.CommandType = (int) ECBCommand.SetBufferWithEntityFixUp; + } + + return header; } internal static int Align(int size, int alignmentPowerOfTwo) @@ -586,6 +599,8 @@ public bool ShouldPlayback private void EnforceSingleThreadOwnership() { #if ENABLE_UNITY_COLLECTIONS_CHECKS + if (m_Data == null) + throw new NullReferenceException("The EntityCommandBuffer has not been initialized!"); AtomicSafetyHandle.CheckWriteAndThrow(m_Safety0); #endif } @@ -808,7 +823,7 @@ private static bool IsDefaultObject(ref T component, out int hashCode) where { var defaultValue = default(T); - #if !UNITY_CSHARP_TINY + #if !NET_DOTS var typeIndex = TypeManager.GetTypeIndex(); var typeInfo = TypeManager.GetTypeInfo(typeIndex).FastEqualityTypeInfo; hashCode = FastEquality.GetHashCode(ref component, typeInfo); @@ -976,23 +991,30 @@ private static unsafe Entity SelectEntity(Entity cmdEntity, ECBSharedPlaybackSta } private static void FixupComponentData(byte* data, int typeIndex, ECBSharedPlaybackState playbackState) + { + FixupComponentData(data, 1, typeIndex, playbackState); + } + private static void FixupComponentData(byte* data, int count, int typeIndex, ECBSharedPlaybackState playbackState) { var componentTypeInfo = TypeManager.GetTypeInfo(typeIndex); Assert.IsTrue(componentTypeInfo.EntityOffsets != null); var offsets = componentTypeInfo.EntityOffsets; var offsetCount = componentTypeInfo.EntityOffsetCount; - - for (int i=0; i < offsetCount; i++) + for (var componentCount = 0; componentCount < count; componentCount++, data += componentTypeInfo.ElementSize) { - // Need fix ups - Entity* e = (Entity*) (data + offsets[i].Offset); - if (e->Index < 0) + for (int i=0; i < offsetCount; i++) { - var index = -e->Index - 1; - Entity real = *(playbackState.CreateEntityBatch + index); - *e = real; + // Need fix ups + Entity* e = (Entity*) (data + offsets[i].Offset); + if (e->Index < 0) + { + var index = -e->Index - 1; + Entity real = *(playbackState.CreateEntityBatch + index); + *e = real; + } } + } } @@ -1006,6 +1028,17 @@ private static unsafe void SetCommandDataWithFixup( playbackState); } + private static unsafe void SetBufferWithFixup( + EntityManager mgr, EntityBufferCommand* cmd, Entity entity, + ECBSharedPlaybackState playbackState) + { + byte* data = (byte*) BufferHeader.GetElementPointer(&cmd->TempBuffer); + FixupComponentData(data, cmd->TempBuffer.Length, + cmd->ComponentTypeIndex, playbackState); + + mgr.SetBufferRaw(entity, cmd->ComponentTypeIndex, &cmd->TempBuffer, cmd->ComponentSize); + } + private static unsafe void PlaybackChain(EntityManager mgr, ref ECBSharedPlaybackState playbackState, NativeArray chainStates, int currentChain, int nextChain) { int nextChainSortIndex = (nextChain != -1) ? chainStates[nextChain].NextSortIndex : -1; @@ -1123,6 +1156,15 @@ private static unsafe void PlaybackChain(EntityManager mgr, ref ECBSharedPlaybac } break; + case ECBCommand.AddBufferWithEntityFixUp: + { + var cmd = (EntityBufferCommand*) header; + var entity = SelectEntity(cmd->Header.Entity, playbackState); + mgr.AddComponent(entity, ComponentType.FromTypeIndex(cmd->ComponentTypeIndex)); + SetBufferWithFixup(mgr, cmd, entity, playbackState); + } + break; + case ECBCommand.SetBuffer: { var cmd = (EntityBufferCommand*)header; @@ -1131,6 +1173,14 @@ private static unsafe void PlaybackChain(EntityManager mgr, ref ECBSharedPlaybac } break; + case ECBCommand.SetBufferWithEntityFixUp: + { + var cmd = (EntityBufferCommand*)header; + var entity = SelectEntity(cmd->Header.Entity, playbackState); + SetBufferWithFixup(mgr, cmd, entity, playbackState); + } + break; + case ECBCommand.AddSharedComponentData: { var cmd = (EntitySharedComponentCommand*)header; @@ -1231,6 +1281,8 @@ unsafe public struct Concurrent private void CheckWriteAccess() { #if ENABLE_UNITY_COLLECTIONS_CHECKS + if (m_Data == null) + throw new NullReferenceException("The EntityCommandBuffer has not been initialized!"); AtomicSafetyHandle.CheckWriteAndThrow(m_Safety0); #endif } diff --git a/Unity.Entities/EntityDataManager.cs b/Unity.Entities/EntityDataManager.cs index abe1e146..406505e5 100644 --- a/Unity.Entities/EntityDataManager.cs +++ b/Unity.Entities/EntityDataManager.cs @@ -384,7 +384,7 @@ public void AssertCanAddComponent(Entity entity, ComponentType componentType) if (!Exists(entity)) throw new ArgumentException("The entity does not exist"); - if (HasComponent(entity, componentType)) + if (!componentType.IgnoreDuplicateAdd && HasComponent(entity, componentType)) throw new ArgumentException($"The component of type:{componentType} has already been added to the entity."); var chunk = GetComponentChunk(entity); @@ -1003,6 +1003,7 @@ public void AddComponents(Entity entity, ComponentTypes types, ArchetypeManager // zipper the two sorted arrays "type" and "componentTypeInArchetype" into "componentTypeInArchetype" // because this is done in-place, it must be done backwards so as not to disturb the existing contents. + var unusedIndices = 0; { var oldThings = oldArchetype->TypesCount; var newThings = types.Length; @@ -1018,30 +1019,27 @@ public void AddComponents(Entity entity, ComponentTypes types, ArchetypeManager } else { + if (oldThing.TypeIndex == newThing.TypeIndex && newThing.IgnoreDuplicateAdd) + --oldThings; + var componentTypeInArchetype = new ComponentTypeInArchetype(newThing); newTypes[--mixedThings] = componentTypeInArchetype; --newThings; indexOfNewTypeInNewArchetype[newThings] = mixedThings; // "this new thing ended up HERE" } } - while (newThings > 0) // if smallest new things < smallest old things, copy them here - { - var newThing = types.GetComponentType(newThings - 1); - var componentTypeInArchetype = new ComponentTypeInArchetype(newThing); - newTypes[--mixedThings] = componentTypeInArchetype; - --newThings; - indexOfNewTypeInNewArchetype[newThings] = mixedThings; // "this new thing ended up HERE" - } + + Assert.AreEqual(0, newThings); // must not be any new things to copy remaining, oldThings contain entity + while (oldThings > 0) // if there are remaining old things, copy them here { newTypes[--mixedThings] = oldTypes[--oldThings]; } - Assert.AreEqual(newThings, 0); // must not be any new things to copy remaining - Assert.AreEqual(oldThings, mixedThings); // all things we didn't copy must be old + unusedIndices = mixedThings; // In case we ignored duplicated types, this will be > 0 } - var newArchetype = archetypeManager.GetOrCreateArchetype(newTypes, newTypesCount, groupManager); + var newArchetype = archetypeManager.GetOrCreateArchetype(newTypes + unusedIndices, newTypesCount, groupManager); var sharedComponentValues = GetComponentChunk(entity)->SharedComponentValues; if (types.m_masks.m_SharedComponentMask != 0) @@ -1066,6 +1064,12 @@ public void AddComponent(Entity entity, ComponentType type, ArchetypeManager arc int indexInTypeArray=0; var newType = archetypeManager.GetArchetypeWithAddedComponentType(archetype, type, groupManager, &indexInTypeArray); + if (newType == null) + { + // This can happen if we are adding a tag component to an entity that already has it. + return; + } + var sharedComponentValues = GetComponentChunk(entity)->SharedComponentValues; if (type.IsSharedComponent) { diff --git a/Unity.Entities/EntityManager.cs b/Unity.Entities/EntityManager.cs index 97a6964c..81533673 100644 --- a/Unity.Entities/EntityManager.cs +++ b/Unity.Entities/EntityManager.cs @@ -244,7 +244,7 @@ public bool Equals(Entity entity) /// A string containing the entity index and generational version. public override string ToString() { - return $"Entity Index: {Index} Version: {Version}"; + return Equals(Entity.Null) ? "Entity.Null" : $"Entity({Index}:{Version})"; } } @@ -267,9 +267,10 @@ public override string ToString() /// [Preserve] [DebuggerTypeProxy(typeof(EntityManagerDebugView))] - public sealed unsafe class EntityManager : ScriptBehaviourManager + public sealed unsafe partial class EntityManager { EntityDataManager* m_Entities; + ComponentJobSafetyManager* m_ComponentJobSafetyManager; ArchetypeManager m_ArchetypeManager; EntityGroupManager m_GroupManager; @@ -279,11 +280,11 @@ public sealed unsafe class EntityManager : ScriptBehaviourManager ExclusiveEntityTransaction m_ExclusiveEntityTransaction; World m_World; - private ComponentGroup m_UniversalGroup; // matches all components + private EntityQuery m_UniversalQuery; // matches all components /// - /// A ComponentGroup instance that matches all components. + /// A EntityQuery instance that matches all components. /// - public ComponentGroup UniversalGroup => m_UniversalGroup; + public EntityQuery UniversalQuery => m_UniversalQuery; #if ENABLE_UNITY_COLLECTIONS_CHECKS int m_InsideForEach; @@ -308,6 +309,11 @@ internal EntityDataManager* Entities { get { return m_Entities; } } + + internal ComponentJobSafetyManager* ComponentJobSafetyManager + { + get { return m_ComponentJobSafetyManager; } + } internal EntityGroupManager GroupManager { @@ -364,16 +370,14 @@ public int EntityCapacity } } - internal ComponentJobSafetyManager ComponentJobSafetyManager { get; private set; } - /// /// The Job dependencies of the exclusive entity transaction. /// /// public JobHandle ExclusiveEntityTransactionDependency { - get { return ComponentJobSafetyManager.ExclusiveTransactionDependency; } - set { ComponentJobSafetyManager.ExclusiveTransactionDependency = value; } + get { return ComponentJobSafetyManager->ExclusiveTransactionDependency; } + set { ComponentJobSafetyManager->ExclusiveTransactionDependency = value; } } EntityManagerDebug m_Debug; @@ -383,55 +387,47 @@ public JobHandle ExclusiveEntityTransactionDependency /// public EntityManagerDebug Debug => m_Debug ?? (m_Debug = new EntityManagerDebug(this)); - protected override void OnBeforeCreateManagerInternal(World world) - { - m_World = world; - } - - protected override void OnBeforeDestroyManagerInternal() - { - } - - protected override void OnAfterDestroyManagerInternal() - { - } - - protected override void OnCreateManager() + internal EntityManager(World world) { TypeManager.Initialize(); + m_World = world; + m_Entities = (EntityDataManager*) UnsafeUtility.Malloc(sizeof(EntityDataManager), 64, Allocator.Persistent); - m_Entities->OnCreate(); + m_Entities->OnCreate(); m_SharedComponentManager = new SharedComponentDataManager(); + + m_ComponentJobSafetyManager = (ComponentJobSafetyManager*) UnsafeUtility.Malloc(sizeof(ComponentJobSafetyManager), 64, Allocator.Persistent); + m_ComponentJobSafetyManager->OnCreate(); - ComponentJobSafetyManager = new ComponentJobSafetyManager(); - m_GroupManager = new EntityGroupManager(ComponentJobSafetyManager); + m_GroupManager = new EntityGroupManager(m_ComponentJobSafetyManager); m_ArchetypeManager = new ArchetypeManager(m_SharedComponentManager, m_Entities, m_GroupManager); m_ExclusiveEntityTransaction = new ExclusiveEntityTransaction(ArchetypeManager, m_GroupManager, m_SharedComponentManager, Entities); - m_UniversalGroup = CreateComponentGroup( - new EntityArchetypeQuery + m_UniversalQuery = CreateEntityQuery( + new EntityQueryDesc { - Options = EntityArchetypeQueryOptions.IncludePrefab | EntityArchetypeQueryOptions.IncludeDisabled + Options = EntityQueryOptions.IncludePrefab | EntityQueryOptions.IncludeDisabled } ); } - protected override void OnDestroyManager() + internal void DestroyInstance() { EndExclusiveEntityTransaction(); - ComponentJobSafetyManager.PreDisposeCheck(); + m_ComponentJobSafetyManager->PreDisposeCheck(); - m_UniversalGroup.Dispose(); - m_UniversalGroup = null; + m_UniversalQuery.Dispose(); + m_UniversalQuery = null; - ComponentJobSafetyManager.Dispose(); - ComponentJobSafetyManager = null; + m_ComponentJobSafetyManager->Dispose(); + UnsafeUtility.Free(m_ComponentJobSafetyManager, Allocator.Persistent); + m_ComponentJobSafetyManager = null; m_Entities->OnDestroy(); UnsafeUtility.Free(m_Entities, Allocator.Persistent); @@ -440,16 +436,24 @@ protected override void OnDestroyManager() m_ArchetypeManager = null; m_GroupManager.Dispose(); m_GroupManager = null; - m_ExclusiveEntityTransaction.OnDestroyManager(); + m_ExclusiveEntityTransaction.OnDestroy(); m_SharedComponentManager.Dispose(); m_World = null; m_Debug = null; + + TypeManager.Shutdown(); } - internal override void InternalUpdate() + private EntityManager() { + // for tests only + } + + internal static EntityManager CreateEntityManagerInUninitializedState() + { + return new EntityManager(); } internal static int FillSortedArchetypeArray(ComponentTypeInArchetype* dst, ComponentType* requiredComponents, int count) @@ -466,30 +470,30 @@ internal static int FillSortedArchetypeArray(ComponentTypeInArchetype* dst, Comp } /// - /// Creates a ComponentGroup from an array of component types. + /// Creates a EntityQuery from an array of component types. /// /// An array containing the component types. - /// The ComponentGroup derived from the specified array of component types. - /// - public ComponentGroup CreateComponentGroup(params ComponentType[] requiredComponents) + /// The EntityQuery derived from the specified array of component types. + /// + public EntityQuery CreateEntityQuery(params ComponentType[] requiredComponents) { fixed (ComponentType* requiredComponentsPtr = requiredComponents) { return m_GroupManager.CreateEntityGroup(ArchetypeManager, Entities, requiredComponentsPtr, requiredComponents.Length); } } - internal ComponentGroup CreateComponentGroup(ComponentType* requiredComponents, int count) + internal EntityQuery CreateEntityQuery(ComponentType* requiredComponents, int count) { return m_GroupManager.CreateEntityGroup(ArchetypeManager, Entities, requiredComponents, count); } /// - /// Creates a ComponentGroup from an EntityArchetypeQuery. + /// Creates a EntityQuery from an EntityQueryDesc. /// - /// A query identifying a set of component types. - /// The ComponentGroup corresponding to the query. - public ComponentGroup CreateComponentGroup(params EntityArchetypeQuery[] queries) + /// A queryDesc identifying a set of component types. + /// The EntityQuery corresponding to the queryDesc. + public EntityQuery CreateEntityQuery(params EntityQueryDesc[] queriesDesc) { - return m_GroupManager.CreateEntityGroup(ArchetypeManager, Entities, queries); + return m_GroupManager.CreateEntityGroup(ArchetypeManager, Entities, queriesDesc); } internal EntityArchetype CreateArchetype(ComponentType* types, int count) @@ -597,28 +601,28 @@ public void UnlockChunk(NativeArray chunks) } - public void LockChunkOrder(ComponentGroup group) + public void LockChunkOrder(EntityQuery query) { - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { LockChunksInternal(chunks.GetUnsafePtr(), chunks.Length, ChunkFlags.LockedEntityOrder); } } - + public void LockChunkOrder(ArchetypeChunk chunk) { LockChunksInternal(&chunk, 1, ChunkFlags.LockedEntityOrder); } - - public void UnlockChunkOrder(ComponentGroup group) + + public void UnlockChunkOrder(EntityQuery query) { - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { UnlockChunksInternal(chunks.GetUnsafePtr(), chunks.Length, ChunkFlags.LockedEntityOrder); } } - + public void UnlockChunkOrder(ArchetypeChunk chunk) { UnlockChunksInternal(&chunk, 1, ChunkFlags.LockedEntityOrder); @@ -628,7 +632,7 @@ internal void UnlockChunksInternal(void* chunks, int count, ChunkFlags flags) { Entities->UnlockChunks((Chunk**)chunks, count, flags); } - + internal void LockChunksInternal(void* chunks, int count, ChunkFlags flags) { Entities->LockChunks((Chunk**)chunks, count, flags); @@ -711,7 +715,7 @@ public Entity CreateEntity() Entities->CreateEntities(ArchetypeManager, ArchetypeManager.GetEntityOnlyArchetype(GroupManager), &entity, 1); return entity; } - + internal void CreateEntityInternal(EntityArchetype archetype, Entity* entities, int count) { BeforeStructuralChange(); @@ -724,10 +728,10 @@ internal void CreateChunkInternal(EntityArchetype archetype, ArchetypeChunk* chu Entities->CreateChunks(ArchetypeManager, archetype.Archetype, chunks, entityCount); } - NativeArray GetTempEntityArray(ComponentGroup group) + NativeArray GetTempEntityArray(EntityQuery query) { //@TODO: Using Allocator.Temp here throws an exception... - var entityArray = group.ToEntityArray(Allocator.TempJob); + var entityArray = query.ToEntityArray(Allocator.TempJob); return entityArray; } @@ -735,19 +739,19 @@ NativeArray GetTempEntityArray(ComponentGroup group) /// Destroy all entities having a common set of component types. /// /// Since entities in the same chunk share the same component structure, this function effectively destroys - /// the chunks holding any entities identified by the `componentGroupFilter` parameter. - /// Defines the components an entity must have to qualify for destruction. - public void DestroyEntity(ComponentGroup componentGroupFilter) + /// the chunks holding any entities identified by the `entityQueryFilter` parameter. + /// Defines the components an entity must have to qualify for destruction. + public void DestroyEntity(EntityQuery entityQueryFilter) { - //@TODO: When destroying entities with componentGroupFilter we assume that any LinkedEntityGroup also get destroyed + //@TODO: When destroying entities with entityQueryFilter we assume that any LinkedEntityGroup also get destroyed // We should have some sort of validation that everything is included, and either give an error message or have a fast enough path to handle it... //@TODO: Locked checks... - - Profiler.BeginSample("DestroyEntity(ComponentGroup componentGroupFilter)"); + + Profiler.BeginSample("DestroyEntity(EntityQuery entityQueryFilter)"); Profiler.BeginSample("GetAllMatchingChunks"); - using (var chunks = componentGroupFilter.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = entityQueryFilter.CreateArchetypeChunkArray(Allocator.TempJob)) { Profiler.EndSample(); @@ -971,13 +975,16 @@ internal void InstantiateInternal(Entity srcEntity, Entity* outputEntities, int /// The type of component to add. public void AddComponent(Entity entity, ComponentType componentType) { + if (componentType.IgnoreDuplicateAdd && HasComponent(entity, componentType)) + return; + BeforeStructuralChange(); Entities->AssertCanAddComponent(entity, componentType); Entities->AddComponent(entity, componentType, ArchetypeManager, m_SharedComponentManager, m_GroupManager); } /// - /// Adds a component to a set of entities defined by a ComponentGroup. + /// Adds a component to a set of entities defined by a EntityQuery. /// /// /// Adding a component changes an entity's archetype and results in the entity being moved to a different @@ -990,11 +997,11 @@ public void AddComponent(Entity entity, ComponentType componentType) /// the function is finished. A sync point can cause a drop in performance because the ECS framework may not /// be able to make use of the processing power of all available cores. /// - /// The ComponentGroup defining the entities to modify. + /// The EntityQuery defining the entities to modify. /// The type of component to add. - public void AddComponent(ComponentGroup componentGroup, ComponentType componentType) + public void AddComponent(EntityQuery entityQuery, ComponentType componentType) { - using (var chunks = componentGroup.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = entityQuery.CreateArchetypeChunkArray(Allocator.TempJob)) { if (chunks.Length == 0) return; @@ -1077,7 +1084,7 @@ public void RemoveComponent(Entity entity, ComponentType type) } /// - /// Removes a component from a set of entities defined by a ComponentGroup. + /// Removes a component from a set of entities defined by a EntityQuery. /// /// /// Removing a component changes an entity's archetype and results in the entity being moved to a different @@ -1088,11 +1095,11 @@ public void RemoveComponent(Entity entity, ComponentType type) /// the function is finished. A sync point can cause a drop in performance because the ECS framework may not /// be able to make use of the processing power of all available cores. /// - /// The ComponentGroup defining the entities to modify. + /// The EntityQuery defining the entities to modify. /// The type of component to remove. - public void RemoveComponent(ComponentGroup componentGroup, ComponentType componentType) + public void RemoveComponent(EntityQuery entityQuery, ComponentType componentType) { - using (var chunks = componentGroup.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = entityQuery.CreateArchetypeChunkArray(Allocator.TempJob)) { if (chunks.Length == 0) return; @@ -1101,15 +1108,15 @@ public void RemoveComponent(ComponentGroup componentGroup, ComponentType compone Entities->RemoveComponent(chunks, componentType, ArchetypeManager, m_GroupManager, m_SharedComponentManager); } } - - public void RemoveComponent(ComponentGroup componentGroupFilter, ComponentTypes types) + + public void RemoveComponent(EntityQuery entityQueryFilter, ComponentTypes types) { - if (componentGroupFilter.CalculateLength() == 0) + if (entityQueryFilter.CalculateLength() == 0) return; // @TODO: Opportunity to do all components in batch on a per chunk basis. for (int i = 0; i != types.Length; i++) - RemoveComponent(componentGroupFilter, types.GetComponentType(i)); + RemoveComponent(entityQueryFilter, types.GetComponentType(i)); } //@TODO: optimize for batch @@ -1220,10 +1227,10 @@ public void AddChunkComponentData(Entity entity) where T : struct, IComponent } /// - /// Adds a component to each of the chunks identified by a ComponentGroup and set the component values. + /// Adds a component to each of the chunks identified by a EntityQuery and set the component values. /// /// - /// This function finds all chunks whose archetype satisfies the ComponentGroup and adds the specified + /// This function finds all chunks whose archetype satisfies the EntityQuery and adds the specified /// component to them. /// /// A chunk component is common to all entities in a chunk. You can access a chunk @@ -1234,12 +1241,12 @@ public void AddChunkComponentData(Entity entity) where T : struct, IComponent /// the function is finished. A sync point can cause a drop in performance because the ECS framework may not /// be able to make use of the processing power of all available cores. /// - /// The ComponentGroup identifying the chunks to modify. + /// The EntityQuery identifying the chunks to modify. /// The data to set. /// The type of component, which must implement IComponentData. - public void AddChunkComponentData(ComponentGroup componentGroup, T componentData) where T : struct, IComponentData + public void AddChunkComponentData(EntityQuery entityQuery, T componentData) where T : struct, IComponentData { - using (var chunks = componentGroup.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = entityQuery.CreateArchetypeChunkArray(Allocator.TempJob)) { if (chunks.Length == 0) return; @@ -1250,7 +1257,7 @@ public void AddChunkComponentData(ComponentGroup componentGroup, T componentD } /// - /// Removes a component from the chunks identified by a ComponentGroup. + /// Removes a component from the chunks identified by a EntityQuery. /// /// /// A chunk component is common to all entities in a chunk. You can access a chunk @@ -1261,11 +1268,11 @@ public void AddChunkComponentData(ComponentGroup componentGroup, T componentD /// the function is finished. A sync point can cause a drop in performance because the ECS framework may not /// be able to make use of the processing power of all available cores. /// - /// The ComponentGroup identifying the chunks to modify. + /// The EntityQuery identifying the chunks to modify. /// The type of component to remove. - public void RemoveChunkComponentData(ComponentGroup componentGroup) + public void RemoveChunkComponentData(EntityQuery entityQuery) { - using (var chunks = componentGroup.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = entityQuery.CreateArchetypeChunkArray(Allocator.TempJob)) { if (chunks.Length == 0) return; @@ -1312,7 +1319,7 @@ internal ComponentDataFromEntity GetComponentDataFromEntity(int typeIndex, { #if ENABLE_UNITY_COLLECTIONS_CHECKS return new ComponentDataFromEntity(typeIndex, Entities, - ComponentJobSafetyManager.GetSafetyHandle(typeIndex, isReadOnly)); + ComponentJobSafetyManager->GetSafetyHandle(typeIndex, isReadOnly)); #else return new ComponentDataFromEntity(typeIndex, m_Entities); #endif @@ -1329,8 +1336,8 @@ internal BufferFromEntity GetBufferFromEntity(int typeIndex, bool isReadOn { #if ENABLE_UNITY_COLLECTIONS_CHECKS return new BufferFromEntity(typeIndex, Entities, isReadOnly, - ComponentJobSafetyManager.GetSafetyHandle(typeIndex, isReadOnly), - ComponentJobSafetyManager.GetBufferSafetyHandle(typeIndex)); + ComponentJobSafetyManager->GetSafetyHandle(typeIndex, isReadOnly), + ComponentJobSafetyManager->GetBufferSafetyHandle(typeIndex)); #else return new BufferFromEntity(typeIndex, m_Entities, isReadOnly); #endif @@ -1354,7 +1361,7 @@ public T GetComponentData(Entity entity) where T : struct, IComponentData throw new System.ArgumentException($"GetComponentData<{typeof(T)}> can not be called with a zero sized component."); #endif - ComponentJobSafetyManager.CompleteWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteWriteDependency(typeIndex); var ptr = Entities->GetComponentDataWithTypeRO(entity, typeIndex); @@ -1381,7 +1388,7 @@ public void SetComponentData(Entity entity, T componentData) where T : struct throw new System.ArgumentException($"SetComponentData<{typeof(T)}> can not be called with a zero sized component."); #endif - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); var ptr = Entities->GetComponentDataWithTypeRW(entity, typeIndex, Entities->GlobalSystemVersion); UnsafeUtility.CopyStructureToPtr(ref componentData, ptr); @@ -1617,7 +1624,7 @@ public void AddSharedComponentData(Entity entity, T componentData) where T : } /// - /// Adds a shared component to a set of entities defined by a ComponentGroup. + /// Adds a shared component to a set of entities defined by a EntityQuery. /// /// /// The fields of the `componentData` parameter are assigned to all of the added shared components. @@ -1631,13 +1638,13 @@ public void AddSharedComponentData(Entity entity, T componentData) where T : /// the function is finished. A sync point can cause a drop in performance because the ECS framework may not /// be able to make use of the processing power of all available cores. /// - /// The ComponentGroup defining a set of entities to modify. + /// The EntityQuery defining a set of entities to modify. /// The data to set. /// The data type of the shared component. - public void AddSharedComponentData(ComponentGroup componentGroup, T componentData) where T : struct, ISharedComponentData + public void AddSharedComponentData(EntityQuery entityQuery, T componentData) where T : struct, ISharedComponentData { var componentType = ComponentType.ReadWrite(); - using (var chunks = componentGroup.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = entityQuery.CreateArchetypeChunkArray(Allocator.TempJob)) { if (chunks.Length == 0) return; @@ -1687,7 +1694,7 @@ public void SetSharedComponentData(Entity entity, T componentData) where T : internal void SetSharedComponentDataBoxed(Entity entity, int typeIndex, object componentData) { - var hashCode = SharedComponentDataManager.GetHashCodeFast(componentData, typeIndex); + var hashCode = TypeManager.GetHashCode(componentData, typeIndex); SetSharedComponentDataBoxed(entity, typeIndex, hashCode, componentData); } @@ -1725,12 +1732,12 @@ public DynamicBuffer GetBuffer(Entity entity) where T : struct, IBufferEle $"GetBuffer<{typeof(T)}> may not be IComponentData or ISharedComponentData; currently {TypeManager.GetTypeInfo().Category}"); #endif - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); BufferHeader* header = (BufferHeader*) Entities->GetComponentDataWithTypeRW(entity, typeIndex, Entities->GlobalSystemVersion); #if ENABLE_UNITY_COLLECTIONS_CHECKS - return new DynamicBuffer(header, ComponentJobSafetyManager.GetSafetyHandle(typeIndex, false), ComponentJobSafetyManager.GetBufferSafetyHandle(typeIndex), false); + return new DynamicBuffer(header, ComponentJobSafetyManager->GetSafetyHandle(typeIndex, false), ComponentJobSafetyManager->GetBufferSafetyHandle(typeIndex), false); #else return new DynamicBuffer(header); #endif @@ -1740,7 +1747,7 @@ public DynamicBuffer GetBuffer(Entity entity) where T : struct, IBufferEle { Entities->AssertEntityHasComponent(entity, typeIndex); - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); BufferHeader* header = (BufferHeader*)Entities->GetComponentDataWithTypeRW(entity, typeIndex, Entities->GlobalSystemVersion); @@ -1751,7 +1758,7 @@ public DynamicBuffer GetBuffer(Entity entity) where T : struct, IBufferEle { Entities->AssertEntityHasComponent(entity, typeIndex); - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); BufferHeader* header = (BufferHeader*)Entities->GetComponentDataWithTypeRO(entity, typeIndex); @@ -1762,7 +1769,7 @@ internal int GetBufferLength(Entity entity, int typeIndex) { Entities->AssertEntityHasComponent(entity, typeIndex); - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); BufferHeader* header = (BufferHeader*)Entities->GetComponentDataWithTypeRO(entity, typeIndex); @@ -1832,7 +1839,7 @@ public NativeArray GetAllChunks(Allocator allocator = Allocator. { BeforeStructuralChange(); - return m_UniversalGroup.CreateArchetypeChunkArray(allocator); + return m_UniversalQuery.CreateArchetypeChunkArray(allocator); } /// @@ -1860,7 +1867,7 @@ internal void SetBufferRaw(Entity entity, int componentTypeIndex, BufferHeader* { Entities->AssertEntityHasComponent(entity, componentTypeIndex); - ComponentJobSafetyManager.CompleteReadAndWriteDependency(componentTypeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(componentTypeIndex); var ptr = Entities->GetComponentDataWithTypeRW(entity, componentTypeIndex, Entities->GlobalSystemVersion); @@ -1895,7 +1902,7 @@ internal void SetComponentDataRaw(Entity entity, int typeIndex, void* data, int { Entities->AssertEntityHasComponent(entity, typeIndex); - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); #if ENABLE_UNITY_COLLECTIONS_CHECKS if (TypeManager.GetTypeInfo(typeIndex).SizeInChunk != size) @@ -1910,7 +1917,7 @@ internal void SetComponentDataRaw(Entity entity, int typeIndex, void* data, int { Entities->AssertEntityHasComponent(entity, typeIndex); - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); #if ENABLE_UNITY_COLLECTIONS_CHECKS if (TypeManager.GetTypeInfo(typeIndex).IsZeroSized) @@ -1926,7 +1933,7 @@ internal void SetComponentDataRaw(Entity entity, int typeIndex, void* data, int { Entities->AssertEntityHasComponent(entity, typeIndex); - ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex); + ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex); #if ENABLE_UNITY_COLLECTIONS_CHECKS if (TypeManager.GetTypeInfo(typeIndex).IsZeroSized) @@ -2006,9 +2013,9 @@ public int GetSharedComponentOrderVersion(T sharedComponent) where T : struct /// A transaction object that provides an functions for making structural changes. public ExclusiveEntityTransaction BeginExclusiveEntityTransaction() { - ComponentJobSafetyManager.BeginExclusiveTransaction(); + ComponentJobSafetyManager->BeginExclusiveTransaction(); #if ENABLE_UNITY_COLLECTIONS_CHECKS - m_ExclusiveEntityTransaction.SetAtomicSafetyHandle(ComponentJobSafetyManager.ExclusiveTransactionSafety); + m_ExclusiveEntityTransaction.SetAtomicSafetyHandle(ComponentJobSafetyManager->ExclusiveTransactionSafety); #endif return m_ExclusiveEntityTransaction; } @@ -2020,13 +2027,13 @@ public ExclusiveEntityTransaction BeginExclusiveEntityTransaction() /// public void EndExclusiveEntityTransaction() { - ComponentJobSafetyManager.EndExclusiveTransaction(); + ComponentJobSafetyManager->EndExclusiveTransaction(); } private void BeforeStructuralChange() { #if ENABLE_UNITY_COLLECTIONS_CHECKS - if (ComponentJobSafetyManager.IsInTransaction) + if (ComponentJobSafetyManager->IsInTransaction) throw new InvalidOperationException( "Access to EntityManager is not allowed after EntityManager.BeginExclusiveEntityTransaction(); has been called."); @@ -2034,7 +2041,7 @@ private void BeforeStructuralChange() throw new InvalidOperationException("EntityManager.AddComponent/RemoveComponent/CreateEntity/DestroyEntity are not allowed during Entities.ForEach. Please use PostUpdateCommandBuffer to delay applying those changes until after ForEach."); #endif - ComponentJobSafetyManager.CompleteAllJobsAndInvalidateArrays(); + ComponentJobSafetyManager->CompleteAllJobsAndInvalidateArrays(); } //@TODO: Not clear to me what this method is really for... @@ -2044,7 +2051,7 @@ private void BeforeStructuralChange() /// Calling CompleteAllJobs() blocks the main thread until all currently running Jobs finish. public void CompleteAllJobs() { - ComponentJobSafetyManager.CompleteAllJobsAndInvalidateArrays(); + ComponentJobSafetyManager->CompleteAllJobsAndInvalidateArrays(); } /// @@ -2099,8 +2106,11 @@ public void MoveEntitiesFrom(EntityManager srcEntities, NativeArrayCapacity) + throw new ArgumentException("entityRemapping.Length isn't large enough, use srcEntities.CreateEntityRemapArray"); + if (!srcEntities.m_SharedComponentManager.AllSharedComponentReferencesAreFromChunks(srcEntities.ArchetypeManager)) - throw new ArgumentException("EntityManager.MoveEntitiesFrom failed - All ISharedComponentData references must be from EntityManager. (For example ComponentGroup.SetFilter with a shared component type is not allowed during EntityManager.MoveEntitiesFrom)"); + throw new ArgumentException("EntityManager.MoveEntitiesFrom failed - All ISharedComponentData references must be from EntityManager. (For example EntityQuery.SetFilter with a shared component type is not allowed during EntityManager.MoveEntitiesFrom)"); #endif BeforeStructuralChange(); @@ -2136,12 +2146,12 @@ public void MoveEntitiesFrom(EntityManager srcEntities, NativeArray /// The EntityManager whose entities are appropriated. - /// A ComponentGroup that defines the entities to move. Must be part of the source + /// A EntityQuery that defines the entities to move. Must be part of the source /// World. /// A set of entity transformations to make during the transfer. - /// Thrown if the ComponentGroup object used as the `filter` comes + /// Thrown if the EntityQuery object used as the `filter` comes /// from a different world than the `srcEntities` EntityManager. - public void MoveEntitiesFrom(EntityManager srcEntities, ComponentGroup filter, NativeArray entityRemapping) + public void MoveEntitiesFrom(EntityManager srcEntities, EntityQuery filter, NativeArray entityRemapping) { #if ENABLE_UNITY_COLLECTIONS_CHECKS if(filter.ArchetypeManager != srcEntities.ArchetypeManager) @@ -2158,6 +2168,10 @@ internal void MoveEntitiesFrom(EntityManager srcEntities, NativeArrayCapacity) + throw new ArgumentException("entityRemapping.Length isn't large enough, use srcEntities.CreateEntityRemapArray"); + for(int i=0;iArchetype->HasChunkHeader) throw new ArgumentException("MoveEntitiesFrom can not move chunks that contain ChunkHeader components."); @@ -2226,7 +2240,7 @@ public void MoveEntitiesFrom(out NativeArray output, EntityManager srcEn throw new ArgumentException("srcEntities must not be the same as this EntityManager."); if (!srcEntities.m_SharedComponentManager.AllSharedComponentReferencesAreFromChunks(srcEntities.ArchetypeManager)) - throw new ArgumentException("EntityManager.MoveEntitiesFrom failed - All ISharedComponentData references must be from EntityManager. (For example ComponentGroup.SetFilter with a shared component type is not allowed during EntityManager.MoveEntitiesFrom)"); + throw new ArgumentException("EntityManager.MoveEntitiesFrom failed - All ISharedComponentData references must be from EntityManager. (For example EntityQuery.SetFilter with a shared component type is not allowed during EntityManager.MoveEntitiesFrom)"); #endif BeforeStructuralChange(); @@ -2255,11 +2269,11 @@ public void MoveEntitiesFrom(out NativeArray output, EntityManager srcEn /// /// An array to receive the Entity objects of the transferred entities. /// The EntityManager whose entities are appropriated. - /// A ComponentGroup that defines the entities to move. Must be part of the source + /// A EntityQuery that defines the entities to move. Must be part of the source /// World. /// A set of entity transformations to make during the transfer. /// - public void MoveEntitiesFrom(out NativeArray output, EntityManager srcEntities, ComponentGroup filter, NativeArray entityRemapping) + public void MoveEntitiesFrom(out NativeArray output, EntityManager srcEntities, EntityQuery filter, NativeArray entityRemapping) { #if ENABLE_UNITY_COLLECTIONS_CHECKS if(filter.ArchetypeManager != srcEntities.ArchetypeManager) @@ -2377,17 +2391,17 @@ private bool TestMatchingArchetypeAll(Archetype* archetype, ComponentType* allTy } [Obsolete("This function is deprecated and will be removed in a future release.")] - public void AddMatchingArchetypes(EntityArchetypeQuery query, NativeList foundArchetypes) + public void AddMatchingArchetypes(EntityQueryDesc queryDesc, NativeList foundArchetypes) { - var anyCount = query.Any.Length; - var noneCount = query.None.Length; - var allCount = query.All.Length; + var anyCount = queryDesc.Any.Length; + var noneCount = queryDesc.None.Length; + var allCount = queryDesc.All.Length; - fixed (ComponentType* any = query.Any) + fixed (ComponentType* any = queryDesc.Any) { - fixed (ComponentType* none = query.None) + fixed (ComponentType* none = queryDesc.None) { - fixed (ComponentType* all = query.All) + fixed (ComponentType* all = queryDesc.All) { for (var i = ArchetypeManager.m_Archetypes.Count - 1; i >= 0; --i) { @@ -2427,7 +2441,7 @@ public void GetAllArchetypes(NativeList allArchetypes) } } - [Obsolete("Please use ComponentGroup APIs instead.")] + [Obsolete("Please use EntityQuery APIs instead.")] public NativeArray CreateArchetypeChunkArray(NativeList archetypes, Allocator allocator) { @@ -2439,11 +2453,11 @@ public NativeArray CreateArchetypeChunkArray(NativeList CreateArchetypeChunkArray(EntityArchetypeQuery query, Allocator allocator) + [Obsolete("Please use EntityQuery APIs instead.")] + public NativeArray CreateArchetypeChunkArray(EntityQueryDesc queryDesc, Allocator allocator) { var foundArchetypes = new NativeList(Allocator.TempJob); - AddMatchingArchetypes(query, foundArchetypes); + AddMatchingArchetypes(queryDesc, foundArchetypes); var chunkStream = CreateArchetypeChunkArray(foundArchetypes, allocator); foundArchetypes.Dispose(); return chunkStream; @@ -2467,7 +2481,7 @@ public ArchetypeChunkComponentType GetArchetypeChunkComponentType(bool isR #if ENABLE_UNITY_COLLECTIONS_CHECKS var typeIndex = TypeManager.GetTypeIndex(); return new ArchetypeChunkComponentType( - ComponentJobSafetyManager.GetSafetyHandle(typeIndex, isReadOnly), isReadOnly, + ComponentJobSafetyManager->GetSafetyHandle(typeIndex, isReadOnly), isReadOnly, GlobalSystemVersion); #else return new ArchetypeChunkComponentType(isReadOnly, GlobalSystemVersion); @@ -2493,8 +2507,8 @@ public ArchetypeChunkBufferType GetArchetypeChunkBufferType(bool isReadOnl #if ENABLE_UNITY_COLLECTIONS_CHECKS var typeIndex = TypeManager.GetTypeIndex(); return new ArchetypeChunkBufferType( - ComponentJobSafetyManager.GetSafetyHandle(typeIndex, isReadOnly), - ComponentJobSafetyManager.GetBufferSafetyHandle(typeIndex), + ComponentJobSafetyManager->GetSafetyHandle(typeIndex, isReadOnly), + ComponentJobSafetyManager->GetBufferSafetyHandle(typeIndex), isReadOnly, GlobalSystemVersion); #else return new ArchetypeChunkBufferType(isReadOnly,GlobalSystemVersion); @@ -2517,7 +2531,7 @@ public ArchetypeChunkSharedComponentType GetArchetypeChunkSharedComponentType { #if ENABLE_UNITY_COLLECTIONS_CHECKS return new ArchetypeChunkSharedComponentType( - ComponentJobSafetyManager.GetEntityManagerSafetyHandle()); + ComponentJobSafetyManager->GetEntityManagerSafetyHandle()); #else return new ArchetypeChunkSharedComponentType(false); #endif @@ -2539,7 +2553,7 @@ public ArchetypeChunkEntityType GetArchetypeChunkEntityType() { #if ENABLE_UNITY_COLLECTIONS_CHECKS return new ArchetypeChunkEntityType( - ComponentJobSafetyManager.GetSafetyHandle(TypeManager.GetTypeIndex(), true)); + ComponentJobSafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex(), true)); #else return new ArchetypeChunkEntityType(false); #endif @@ -2617,7 +2631,7 @@ public bool IsSharedComponentManagerEmpty() return m_Manager.m_SharedComponentManager.IsEmpty(); } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS internal static string GetArchetypeDebugString(Archetype* a) { var buf = new System.Text.StringBuilder(); @@ -2660,12 +2674,16 @@ public void LogEntityInfo(Entity entity) public string GetEntityInfo(Entity entity) { var archetype = m_Manager.Entities->GetArchetype(entity); - #if !UNITY_CSHARP_TINY + #if !NET_DOTS var str = new System.Text.StringBuilder(); str.Append(entity.ToString()); #if UNITY_EDITOR - str.Append($" (name '{m_Manager.GetName(entity)}')"); - #endif + { + var name = m_Manager.GetName(entity); + if(!string.IsNullOrEmpty(name)) + str.Append($" (name '{name}')"); + } +#endif for (var i = 0; i < archetype->TypesCount; i++) { var componentTypeInArchetype = archetype->Types[i]; @@ -2686,7 +2704,7 @@ public string GetEntityInfo(Entity entity) #endif } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS public object GetComponentBoxed(Entity entity, ComponentType type) { m_Manager.Entities->AssertEntityHasComponent(entity, type); @@ -2727,7 +2745,7 @@ public void CheckInternalConsistency() { #if ENABLE_UNITY_COLLECTIONS_CHECKS - //@TODO: Validate from perspective of componentgroup... + //@TODO: Validate from perspective of chunkquery... var entityCountEntityData = m_Manager.Entities->CheckInternalConsistency(); var entityCountArchetypeManager = m_Manager.ArchetypeManager.CheckInternalConsistency(m_Manager.Entities); Assert.AreEqual(entityCountEntityData, entityCountArchetypeManager); diff --git a/Unity.Entities/EntityQueryBuilder.cs b/Unity.Entities/EntityQueryBuilder.cs index 92a070b2..e9b99bee 100644 --- a/Unity.Entities/EntityQueryBuilder.cs +++ b/Unity.Entities/EntityQueryBuilder.cs @@ -11,7 +11,7 @@ public partial struct EntityQueryBuilder ComponentSystem m_System; ResizableArray64Byte m_Any, m_None, m_All; - ComponentGroup m_Group; + EntityQuery m_Query; internal EntityQueryBuilder(ComponentSystem system) { @@ -19,7 +19,7 @@ internal EntityQueryBuilder(ComponentSystem system) m_Any = new ResizableArray64Byte(); m_None = new ResizableArray64Byte(); m_All = new ResizableArray64Byte(); - m_Group = null; + m_Query = null; } // this is a specialized function intended only for validation that builders are hashing and getting cached @@ -36,7 +36,7 @@ internal bool ShallowEquals(ref EntityQueryBuilder other) m_Any .Equals(ref other.m_Any) && m_None.Equals(ref other.m_None) && m_All .Equals(ref other.m_All) && - ReferenceEquals(m_Group, other.m_Group); + ReferenceEquals(m_Query, other.m_Query); } public override int GetHashCode() => @@ -45,7 +45,7 @@ public override bool Equals(object obj) => throw new InvalidOperationException("Calling this function is a sign of inadvertent boxing"); [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] - void ValidateHasNoGroup() => ThrowIfInvalidMixing(m_Group != null); + void ValidateHasNoQuery() => ThrowIfInvalidMixing(m_Query != null); [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] void ValidateHasNoSpec() => ThrowIfInvalidMixing(m_Any.Length != 0 || m_None.Length != 0 || m_All.Length != 0); @@ -54,24 +54,24 @@ public override bool Equals(object obj) => void ThrowIfInvalidMixing(bool throwIfTrue) { if (throwIfTrue) - throw new InvalidOperationException($"Cannot mix {nameof(WithAny)}/{nameof(WithNone)}/{nameof(WithAll)} and {nameof(With)}({nameof(ComponentGroup)})"); + throw new InvalidOperationException($"Cannot mix {nameof(WithAny)}/{nameof(WithNone)}/{nameof(WithAll)} and {nameof(With)}({nameof(EntityQuery)})"); } - public EntityQueryBuilder With(ComponentGroup componentGroup) + public EntityQueryBuilder With(EntityQuery entityQuery) { #if ENABLE_UNITY_COLLECTIONS_CHECKS - if (componentGroup == null) - throw new ArgumentNullException(nameof(componentGroup)); - if (m_Group != null) - throw new InvalidOperationException($"{nameof(ComponentGroup)} has already been set"); + if (entityQuery == null) + throw new ArgumentNullException(nameof(entityQuery)); + if (m_Query != null) + throw new InvalidOperationException($"{nameof(EntityQuery)} has already been set"); ValidateHasNoSpec(); #endif - m_Group = componentGroup; + m_Query = entityQuery; return this; } - EntityArchetypeQuery ToEntityArchetypeQuery(int delegateTypeCount) + EntityQueryDesc ToEntityQueryDesc(int delegateTypeCount) { ComponentType[] ToComponentTypes(ref ResizableArray64Byte typeIndices, ComponentType.AccessMode mode, int extraCapacity = 0) { @@ -86,7 +86,7 @@ ComponentType[] ToComponentTypes(ref ResizableArray64Byte typeIndices, Comp return types; } - return new EntityArchetypeQuery + return new EntityQueryDesc { Any = ToComponentTypes(ref m_Any, ComponentType.AccessMode.ReadWrite), None = ToComponentTypes(ref m_None, ComponentType.AccessMode.ReadOnly), @@ -94,11 +94,11 @@ ComponentType[] ToComponentTypes(ref ResizableArray64Byte typeIndices, Comp }; } - public EntityArchetypeQuery ToEntityArchetypeQuery() => - ToEntityArchetypeQuery(0); + public EntityQueryDesc ToEntityQueryDesc() => + ToEntityQueryDesc(0); - public ComponentGroup ToComponentGroup() => - m_Group ?? (m_Group = m_System.GetComponentGroup(ToEntityArchetypeQuery())); + public EntityQuery ToEntityQuery() => + m_Query ?? (m_Query = m_System.GetEntityQuery(ToEntityQueryDesc())); // see EntityQueryBuilder.tt for the template that is converted into EntityQueryBuilder.gen.cs, // which contains ForEach and other generated methods. @@ -108,7 +108,7 @@ EntityManager.InsideForEach InsideForEach() => new EntityManager.InsideForEach(m_System.EntityManager); #endif - unsafe ComponentGroup ResolveComponentGroup(int* delegateTypeIndices, int delegateTypeCount) + unsafe EntityQuery ResolveEntityQuery(int* delegateTypeIndices, int delegateTypeCount) { var hash = (uint)m_Any .GetHashCode() * 0xEA928FF9 @@ -122,18 +122,18 @@ var hash if (found < 0) { // base query from builder spec, but reserve some extra room for the types detected from the delegate - var eaq = ToEntityArchetypeQuery(delegateTypeCount); + var eaq = ToEntityQueryDesc(delegateTypeCount); // now fill out the extra types for (var i = 0 ; i < delegateTypeCount; ++i) eaq.All[i + m_All.Length] = ComponentType.FromTypeIndex(delegateTypeIndices[i]); - var group = m_System.GetComponentGroup(eaq); + var query = m_System.GetEntityQuery(eaq); #if ENABLE_UNITY_COLLECTIONS_CHECKS - found = cache.CreateCachedQuery(hash, group, ref this, delegateTypeIndices, delegateTypeCount); + found = cache.CreateCachedQuery(hash, query, ref this, delegateTypeIndices, delegateTypeCount); #else - found = cache.CreateCachedQuery(hash, group); + found = cache.CreateCachedQuery(hash, query); #endif } #if ENABLE_UNITY_COLLECTIONS_CHECKS @@ -141,7 +141,7 @@ var hash { cache.ValidateMatchesCache(found, ref this, delegateTypeIndices, delegateTypeCount); - // TODO: also validate that m_Group spec matches m_Any/All/None and delegateTypeIndices + // TODO: also validate that m_Query spec matches m_Any/All/None and delegateTypeIndices } #endif diff --git a/Unity.Entities/EntityQueryBuilder.gen.cs.meta b/Unity.Entities/EntityQueryBuilder.gen.cs.meta deleted file mode 100644 index 5ee87395..00000000 --- a/Unity.Entities/EntityQueryBuilder.gen.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 71b6bf888bcea364696d5cc546629b7a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/EntityQueryBuilder.gen.cs b/Unity.Entities/EntityQueryBuilder_ForEach.gen.cs similarity index 73% rename from Unity.Entities/EntityQueryBuilder.gen.cs rename to Unity.Entities/EntityQueryBuilder_ForEach.gen.cs index 9bdc229e..cba956b0 100644 --- a/Unity.Entities/EntityQueryBuilder.gen.cs +++ b/Unity.Entities/EntityQueryBuilder_ForEach.gen.cs @@ -8,151 +8,16 @@ //------------------------------------------------------------------------------ // Generated by EntityQueryBuilder.tt (129 `foreach` combinations) +using System; +using System.ComponentModel; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; +using Unity.Jobs; namespace Unity.Entities { public partial struct EntityQueryBuilder { - // ** FLUENT QUERY ** - - public EntityQueryBuilder WithAny() - { - ValidateHasNoGroup(); - m_Any.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAny() - { - ValidateHasNoGroup(); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAny() - { - ValidateHasNoGroup(); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAny() - { - ValidateHasNoGroup(); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAny() - { - ValidateHasNoGroup(); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - m_Any.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithNone() - { - ValidateHasNoGroup(); - m_None.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithNone() - { - ValidateHasNoGroup(); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithNone() - { - ValidateHasNoGroup(); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithNone() - { - ValidateHasNoGroup(); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithNone() - { - ValidateHasNoGroup(); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - m_None.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAll() - { - ValidateHasNoGroup(); - m_All.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAll() - { - ValidateHasNoGroup(); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAll() - { - ValidateHasNoGroup(); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAll() - { - ValidateHasNoGroup(); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - return this; - } - - public EntityQueryBuilder WithAll() - { - ValidateHasNoGroup(); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - m_All.Add(TypeManager.GetTypeIndex()); - return this; - } - - // ** FOREACH ** public delegate void F_E(Entity entity); @@ -162,15 +27,15 @@ public unsafe void ForEach(F_E action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { - group = ResolveComponentGroup(null, 0); + query = ResolveEntityQuery(null, 0); } var entityType = m_System.GetArchetypeChunkEntityType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -183,6 +48,7 @@ public unsafe void ForEach(F_E action) } } + public delegate void F_ED(Entity entity, ref T0 c0) where T0 : struct, IComponentData; @@ -193,19 +59,19 @@ public unsafe void ForEach(F_ED action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -219,6 +85,7 @@ public unsafe void ForEach(F_ED action) } } + public delegate void F_D(ref T0 c0) where T0 : struct, IComponentData; @@ -229,18 +96,18 @@ public unsafe void ForEach(F_D action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -253,6 +120,7 @@ public unsafe void ForEach(F_D action) } } + public delegate void F_EC(Entity entity, T0 c0) where T0 : class; @@ -263,19 +131,19 @@ public unsafe void ForEach(F_EC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -289,6 +157,7 @@ public unsafe void ForEach(F_EC action) } } + public delegate void F_C(T0 c0) where T0 : class; @@ -299,18 +168,18 @@ public unsafe void ForEach(F_C action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -323,6 +192,7 @@ public unsafe void ForEach(F_C action) } } + public delegate void F_EB(Entity entity, DynamicBuffer c0) where T0 : struct, IBufferElementData; @@ -333,19 +203,19 @@ public unsafe void ForEach(F_EB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -359,6 +229,7 @@ public unsafe void ForEach(F_EB action) } } + public delegate void F_B(DynamicBuffer c0) where T0 : struct, IBufferElementData; @@ -369,18 +240,18 @@ public unsafe void ForEach(F_B action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -393,6 +264,7 @@ public unsafe void ForEach(F_B action) } } + public delegate void F_ES(Entity entity, T0 c0) where T0 : struct, ISharedComponentData; @@ -403,19 +275,19 @@ public unsafe void ForEach(F_ES action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -429,6 +301,7 @@ public unsafe void ForEach(F_ES action) } } + public delegate void F_S(T0 c0) where T0 : struct, ISharedComponentData; @@ -439,18 +312,18 @@ public unsafe void ForEach(F_S action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[1]; delegateTypes[0] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 1); + query = ResolveEntityQuery(delegateTypes, 1); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -463,6 +336,7 @@ public unsafe void ForEach(F_S action) } } + public delegate void F_EDD(Entity entity, ref T0 c0, ref T1 c1) where T0 : struct, IComponentData where T1 : struct, IComponentData; @@ -475,21 +349,21 @@ public unsafe void ForEach(F_EDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -504,6 +378,7 @@ public unsafe void ForEach(F_EDD action) } } + public delegate void F_DD(ref T0 c0, ref T1 c1) where T0 : struct, IComponentData where T1 : struct, IComponentData; @@ -516,20 +391,20 @@ public unsafe void ForEach(F_DD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -543,6 +418,7 @@ public unsafe void ForEach(F_DD action) } } + public delegate void F_EDDD(Entity entity, ref T0 c0, ref T1 c1, ref T2 c2) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -557,15 +433,15 @@ public unsafe void ForEach(F_EDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -573,7 +449,7 @@ public unsafe void ForEach(F_EDDD action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -589,6 +465,7 @@ public unsafe void ForEach(F_EDDD action) } } + public delegate void F_DDD(ref T0 c0, ref T1 c1, ref T2 c2) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -603,22 +480,22 @@ public unsafe void ForEach(F_DDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -633,6 +510,7 @@ public unsafe void ForEach(F_DDD action) } } + public delegate void F_EDDDD(Entity entity, ref T0 c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -649,8 +527,8 @@ public unsafe void ForEach(F_EDDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -658,7 +536,7 @@ public unsafe void ForEach(F_EDDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -667,7 +545,7 @@ public unsafe void ForEach(F_EDDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -684,6 +562,7 @@ public unsafe void ForEach(F_EDDDD action) } } + public delegate void F_DDDD(ref T0 c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -700,8 +579,8 @@ public unsafe void ForEach(F_DDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -709,7 +588,7 @@ public unsafe void ForEach(F_DDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -717,7 +596,7 @@ public unsafe void ForEach(F_DDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -733,6 +612,7 @@ public unsafe void ForEach(F_DDDD action) } } + public delegate void F_EDDDDD(Entity entity, ref T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -751,8 +631,8 @@ public unsafe void ForEach(F_EDDDDD acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -761,7 +641,7 @@ public unsafe void ForEach(F_EDDDDD acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -771,7 +651,7 @@ public unsafe void ForEach(F_EDDDDD acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -789,6 +669,7 @@ public unsafe void ForEach(F_EDDDDD acti } } + public delegate void F_DDDDD(ref T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -807,8 +688,8 @@ public unsafe void ForEach(F_DDDDD actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -817,7 +698,7 @@ public unsafe void ForEach(F_DDDDD actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -826,7 +707,7 @@ public unsafe void ForEach(F_DDDDD actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -843,6 +724,7 @@ public unsafe void ForEach(F_DDDDD actio } } + public delegate void F_EDDDDDD(Entity entity, ref T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -863,8 +745,8 @@ public unsafe void ForEach(F_EDDDDDD(); @@ -874,7 +756,7 @@ public unsafe void ForEach(F_EDDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -885,7 +767,7 @@ public unsafe void ForEach(F_EDDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -904,6 +786,7 @@ public unsafe void ForEach(F_EDDDDDD(ref T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : struct, IComponentData where T1 : struct, IComponentData @@ -924,8 +807,8 @@ public unsafe void ForEach(F_DDDDDD(); @@ -935,7 +818,7 @@ public unsafe void ForEach(F_DDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -945,7 +828,7 @@ public unsafe void ForEach(F_DDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -963,6 +846,7 @@ public unsafe void ForEach(F_DDDDDD(Entity entity, T0 c0, ref T1 c1) where T0 : class where T1 : struct, IComponentData; @@ -975,21 +859,21 @@ public unsafe void ForEach(F_ECD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1004,6 +888,7 @@ public unsafe void ForEach(F_ECD action) } } + public delegate void F_CD(T0 c0, ref T1 c1) where T0 : class where T1 : struct, IComponentData; @@ -1016,20 +901,20 @@ public unsafe void ForEach(F_CD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1043,6 +928,7 @@ public unsafe void ForEach(F_CD action) } } + public delegate void F_ECDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2) where T0 : class where T1 : struct, IComponentData @@ -1057,15 +943,15 @@ public unsafe void ForEach(F_ECDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1073,7 +959,7 @@ public unsafe void ForEach(F_ECDD action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1089,6 +975,7 @@ public unsafe void ForEach(F_ECDD action) } } + public delegate void F_CDD(T0 c0, ref T1 c1, ref T2 c2) where T0 : class where T1 : struct, IComponentData @@ -1103,22 +990,22 @@ public unsafe void ForEach(F_CDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1133,6 +1020,7 @@ public unsafe void ForEach(F_CDD action) } } + public delegate void F_ECDDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : class where T1 : struct, IComponentData @@ -1149,8 +1037,8 @@ public unsafe void ForEach(F_ECDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1158,7 +1046,7 @@ public unsafe void ForEach(F_ECDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1167,7 +1055,7 @@ public unsafe void ForEach(F_ECDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1184,6 +1072,7 @@ public unsafe void ForEach(F_ECDDD action) } } + public delegate void F_CDDD(T0 c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : class where T1 : struct, IComponentData @@ -1200,8 +1089,8 @@ public unsafe void ForEach(F_CDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1209,7 +1098,7 @@ public unsafe void ForEach(F_CDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -1217,7 +1106,7 @@ public unsafe void ForEach(F_CDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1233,6 +1122,7 @@ public unsafe void ForEach(F_CDDD action) } } + public delegate void F_ECDDDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : class where T1 : struct, IComponentData @@ -1251,8 +1141,8 @@ public unsafe void ForEach(F_ECDDDD acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1261,7 +1151,7 @@ public unsafe void ForEach(F_ECDDDD acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1271,7 +1161,7 @@ public unsafe void ForEach(F_ECDDDD acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1289,6 +1179,7 @@ public unsafe void ForEach(F_ECDDDD acti } } + public delegate void F_CDDDD(T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : class where T1 : struct, IComponentData @@ -1307,8 +1198,8 @@ public unsafe void ForEach(F_CDDDD actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1317,7 +1208,7 @@ public unsafe void ForEach(F_CDDDD actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -1326,7 +1217,7 @@ public unsafe void ForEach(F_CDDDD actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1343,6 +1234,7 @@ public unsafe void ForEach(F_CDDDD actio } } + public delegate void F_ECDDDDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : class where T1 : struct, IComponentData @@ -1363,8 +1255,8 @@ public unsafe void ForEach(F_ECDDDDD(); @@ -1374,7 +1266,7 @@ public unsafe void ForEach(F_ECDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1385,7 +1277,7 @@ public unsafe void ForEach(F_ECDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1404,6 +1296,7 @@ public unsafe void ForEach(F_ECDDDDD(T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : class where T1 : struct, IComponentData @@ -1424,8 +1317,8 @@ public unsafe void ForEach(F_CDDDDD(); @@ -1435,7 +1328,7 @@ public unsafe void ForEach(F_CDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -1445,7 +1338,7 @@ public unsafe void ForEach(F_CDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1463,6 +1356,7 @@ public unsafe void ForEach(F_CDDDDD(Entity entity, DynamicBuffer c0, ref T1 c1) where T0 : struct, IBufferElementData where T1 : struct, IComponentData; @@ -1475,21 +1369,21 @@ public unsafe void ForEach(F_EBD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1504,6 +1398,7 @@ public unsafe void ForEach(F_EBD action) } } + public delegate void F_BD(DynamicBuffer c0, ref T1 c1) where T0 : struct, IBufferElementData where T1 : struct, IComponentData; @@ -1516,20 +1411,20 @@ public unsafe void ForEach(F_BD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1543,6 +1438,7 @@ public unsafe void ForEach(F_BD action) } } + public delegate void F_EBDD(Entity entity, DynamicBuffer c0, ref T1 c1, ref T2 c2) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1557,15 +1453,15 @@ public unsafe void ForEach(F_EBDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1573,7 +1469,7 @@ public unsafe void ForEach(F_EBDD action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1589,6 +1485,7 @@ public unsafe void ForEach(F_EBDD action) } } + public delegate void F_BDD(DynamicBuffer c0, ref T1 c1, ref T2 c2) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1603,22 +1500,22 @@ public unsafe void ForEach(F_BDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1633,6 +1530,7 @@ public unsafe void ForEach(F_BDD action) } } + public delegate void F_EBDDD(Entity entity, DynamicBuffer c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1649,8 +1547,8 @@ public unsafe void ForEach(F_EBDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1658,7 +1556,7 @@ public unsafe void ForEach(F_EBDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1667,7 +1565,7 @@ public unsafe void ForEach(F_EBDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1684,6 +1582,7 @@ public unsafe void ForEach(F_EBDDD action) } } + public delegate void F_BDDD(DynamicBuffer c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1700,8 +1599,8 @@ public unsafe void ForEach(F_BDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1709,7 +1608,7 @@ public unsafe void ForEach(F_BDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -1717,7 +1616,7 @@ public unsafe void ForEach(F_BDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1733,6 +1632,7 @@ public unsafe void ForEach(F_BDDD action) } } + public delegate void F_EBDDDD(Entity entity, DynamicBuffer c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1751,8 +1651,8 @@ public unsafe void ForEach(F_EBDDDD acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1761,7 +1661,7 @@ public unsafe void ForEach(F_EBDDDD acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1771,7 +1671,7 @@ public unsafe void ForEach(F_EBDDDD acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1789,6 +1689,7 @@ public unsafe void ForEach(F_EBDDDD acti } } + public delegate void F_BDDDD(DynamicBuffer c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1807,8 +1708,8 @@ public unsafe void ForEach(F_BDDDD actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -1817,7 +1718,7 @@ public unsafe void ForEach(F_BDDDD actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -1826,7 +1727,7 @@ public unsafe void ForEach(F_BDDDD actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1843,6 +1744,7 @@ public unsafe void ForEach(F_BDDDD actio } } + public delegate void F_EBDDDDD(Entity entity, DynamicBuffer c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1863,8 +1765,8 @@ public unsafe void ForEach(F_EBDDDDD(); @@ -1874,7 +1776,7 @@ public unsafe void ForEach(F_EBDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -1885,7 +1787,7 @@ public unsafe void ForEach(F_EBDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1904,6 +1806,7 @@ public unsafe void ForEach(F_EBDDDDD(DynamicBuffer c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : struct, IBufferElementData where T1 : struct, IComponentData @@ -1924,8 +1827,8 @@ public unsafe void ForEach(F_BDDDDD(); @@ -1935,7 +1838,7 @@ public unsafe void ForEach(F_BDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -1945,7 +1848,7 @@ public unsafe void ForEach(F_BDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -1963,6 +1866,7 @@ public unsafe void ForEach(F_BDDDDD(Entity entity, T0 c0, ref T1 c1) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData; @@ -1975,21 +1879,21 @@ public unsafe void ForEach(F_ESD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2004,6 +1908,7 @@ public unsafe void ForEach(F_ESD action) } } + public delegate void F_SD(T0 c0, ref T1 c1) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData; @@ -2016,20 +1921,20 @@ public unsafe void ForEach(F_SD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2043,6 +1948,7 @@ public unsafe void ForEach(F_SD action) } } + public delegate void F_ESDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2057,15 +1963,15 @@ public unsafe void ForEach(F_ESDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2073,7 +1979,7 @@ public unsafe void ForEach(F_ESDD action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2089,6 +1995,7 @@ public unsafe void ForEach(F_ESDD action) } } + public delegate void F_SDD(T0 c0, ref T1 c1, ref T2 c2) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2103,22 +2010,22 @@ public unsafe void ForEach(F_SDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2133,6 +2040,7 @@ public unsafe void ForEach(F_SDD action) } } + public delegate void F_ESDDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2149,8 +2057,8 @@ public unsafe void ForEach(F_ESDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2158,7 +2066,7 @@ public unsafe void ForEach(F_ESDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2167,7 +2075,7 @@ public unsafe void ForEach(F_ESDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2184,6 +2092,7 @@ public unsafe void ForEach(F_ESDDD action) } } + public delegate void F_SDDD(T0 c0, ref T1 c1, ref T2 c2, ref T3 c3) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2200,8 +2109,8 @@ public unsafe void ForEach(F_SDDD action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2209,7 +2118,7 @@ public unsafe void ForEach(F_SDDD action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -2217,7 +2126,7 @@ public unsafe void ForEach(F_SDDD action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2233,6 +2142,7 @@ public unsafe void ForEach(F_SDDD action) } } + public delegate void F_ESDDDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2251,8 +2161,8 @@ public unsafe void ForEach(F_ESDDDD acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2261,7 +2171,7 @@ public unsafe void ForEach(F_ESDDDD acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2271,7 +2181,7 @@ public unsafe void ForEach(F_ESDDDD acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2289,6 +2199,7 @@ public unsafe void ForEach(F_ESDDDD acti } } + public delegate void F_SDDDD(T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2307,8 +2218,8 @@ public unsafe void ForEach(F_SDDDD actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2317,7 +2228,7 @@ public unsafe void ForEach(F_SDDDD actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -2326,7 +2237,7 @@ public unsafe void ForEach(F_SDDDD actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2343,6 +2254,7 @@ public unsafe void ForEach(F_SDDDD actio } } + public delegate void F_ESDDDDD(Entity entity, T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2363,8 +2275,8 @@ public unsafe void ForEach(F_ESDDDDD(); @@ -2374,7 +2286,7 @@ public unsafe void ForEach(F_ESDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2385,7 +2297,7 @@ public unsafe void ForEach(F_ESDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2404,6 +2316,7 @@ public unsafe void ForEach(F_ESDDDDD(T0 c0, ref T1 c1, ref T2 c2, ref T3 c3, ref T4 c4, ref T5 c5) where T0 : struct, ISharedComponentData where T1 : struct, IComponentData @@ -2424,8 +2337,8 @@ public unsafe void ForEach(F_SDDDDD(); @@ -2435,7 +2348,7 @@ public unsafe void ForEach(F_SDDDDD(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -2445,7 +2358,7 @@ public unsafe void ForEach(F_SDDDDD(false); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2463,6 +2376,7 @@ public unsafe void ForEach(F_SDDDDD(Entity entity, ref T0 c0, T1 c1) where T0 : struct, IComponentData where T1 : class; @@ -2475,21 +2389,21 @@ public unsafe void ForEach(F_EDC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2504,6 +2418,7 @@ public unsafe void ForEach(F_EDC action) } } + public delegate void F_DC(ref T0 c0, T1 c1) where T0 : struct, IComponentData where T1 : class; @@ -2516,20 +2431,20 @@ public unsafe void ForEach(F_DC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2543,6 +2458,7 @@ public unsafe void ForEach(F_DC action) } } + public delegate void F_EDCC(Entity entity, ref T0 c0, T1 c1, T2 c2) where T0 : struct, IComponentData where T1 : class @@ -2557,15 +2473,15 @@ public unsafe void ForEach(F_EDCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2573,7 +2489,7 @@ public unsafe void ForEach(F_EDCC action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2589,6 +2505,7 @@ public unsafe void ForEach(F_EDCC action) } } + public delegate void F_DCC(ref T0 c0, T1 c1, T2 c2) where T0 : struct, IComponentData where T1 : class @@ -2603,22 +2520,22 @@ public unsafe void ForEach(F_DCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2633,6 +2550,7 @@ public unsafe void ForEach(F_DCC action) } } + public delegate void F_EDCCC(Entity entity, ref T0 c0, T1 c1, T2 c2, T3 c3) where T0 : struct, IComponentData where T1 : class @@ -2649,8 +2567,8 @@ public unsafe void ForEach(F_EDCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2658,7 +2576,7 @@ public unsafe void ForEach(F_EDCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2667,7 +2585,7 @@ public unsafe void ForEach(F_EDCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2684,6 +2602,7 @@ public unsafe void ForEach(F_EDCCC action) } } + public delegate void F_DCCC(ref T0 c0, T1 c1, T2 c2, T3 c3) where T0 : struct, IComponentData where T1 : class @@ -2700,8 +2619,8 @@ public unsafe void ForEach(F_DCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2709,7 +2628,7 @@ public unsafe void ForEach(F_DCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -2717,7 +2636,7 @@ public unsafe void ForEach(F_DCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2733,6 +2652,7 @@ public unsafe void ForEach(F_DCCC action) } } + public delegate void F_EDCCCC(Entity entity, ref T0 c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : struct, IComponentData where T1 : class @@ -2751,8 +2671,8 @@ public unsafe void ForEach(F_EDCCCC acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2761,7 +2681,7 @@ public unsafe void ForEach(F_EDCCCC acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2771,7 +2691,7 @@ public unsafe void ForEach(F_EDCCCC acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2789,6 +2709,7 @@ public unsafe void ForEach(F_EDCCCC acti } } + public delegate void F_DCCCC(ref T0 c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : struct, IComponentData where T1 : class @@ -2807,8 +2728,8 @@ public unsafe void ForEach(F_DCCCC actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -2817,7 +2738,7 @@ public unsafe void ForEach(F_DCCCC actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -2826,7 +2747,7 @@ public unsafe void ForEach(F_DCCCC actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2843,6 +2764,7 @@ public unsafe void ForEach(F_DCCCC actio } } + public delegate void F_EDCCCCC(Entity entity, ref T0 c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : struct, IComponentData where T1 : class @@ -2863,8 +2785,8 @@ public unsafe void ForEach(F_EDCCCCC(); @@ -2874,7 +2796,7 @@ public unsafe void ForEach(F_EDCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -2885,7 +2807,7 @@ public unsafe void ForEach(F_EDCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2904,6 +2826,7 @@ public unsafe void ForEach(F_EDCCCCC(ref T0 c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : struct, IComponentData where T1 : class @@ -2924,8 +2847,8 @@ public unsafe void ForEach(F_DCCCCC(); @@ -2935,7 +2858,7 @@ public unsafe void ForEach(F_DCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -2945,7 +2868,7 @@ public unsafe void ForEach(F_DCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -2963,6 +2886,7 @@ public unsafe void ForEach(F_DCCCCC(Entity entity, T0 c0, T1 c1) where T0 : class where T1 : class; @@ -2975,21 +2899,21 @@ public unsafe void ForEach(F_ECC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3004,6 +2928,7 @@ public unsafe void ForEach(F_ECC action) } } + public delegate void F_CC(T0 c0, T1 c1) where T0 : class where T1 : class; @@ -3016,20 +2941,20 @@ public unsafe void ForEach(F_CC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3043,6 +2968,7 @@ public unsafe void ForEach(F_CC action) } } + public delegate void F_ECCC(Entity entity, T0 c0, T1 c1, T2 c2) where T0 : class where T1 : class @@ -3057,15 +2983,15 @@ public unsafe void ForEach(F_ECCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3073,7 +2999,7 @@ public unsafe void ForEach(F_ECCC action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3089,6 +3015,7 @@ public unsafe void ForEach(F_ECCC action) } } + public delegate void F_CCC(T0 c0, T1 c1, T2 c2) where T0 : class where T1 : class @@ -3103,22 +3030,22 @@ public unsafe void ForEach(F_CCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3133,6 +3060,7 @@ public unsafe void ForEach(F_CCC action) } } + public delegate void F_ECCCC(Entity entity, T0 c0, T1 c1, T2 c2, T3 c3) where T0 : class where T1 : class @@ -3149,8 +3077,8 @@ public unsafe void ForEach(F_ECCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3158,7 +3086,7 @@ public unsafe void ForEach(F_ECCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3167,7 +3095,7 @@ public unsafe void ForEach(F_ECCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3184,6 +3112,7 @@ public unsafe void ForEach(F_ECCCC action) } } + public delegate void F_CCCC(T0 c0, T1 c1, T2 c2, T3 c3) where T0 : class where T1 : class @@ -3200,8 +3129,8 @@ public unsafe void ForEach(F_CCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3209,7 +3138,7 @@ public unsafe void ForEach(F_CCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -3217,7 +3146,7 @@ public unsafe void ForEach(F_CCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3233,6 +3162,7 @@ public unsafe void ForEach(F_CCCC action) } } + public delegate void F_ECCCCC(Entity entity, T0 c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : class where T1 : class @@ -3251,8 +3181,8 @@ public unsafe void ForEach(F_ECCCCC acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3261,7 +3191,7 @@ public unsafe void ForEach(F_ECCCCC acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3271,7 +3201,7 @@ public unsafe void ForEach(F_ECCCCC acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3289,6 +3219,7 @@ public unsafe void ForEach(F_ECCCCC acti } } + public delegate void F_CCCCC(T0 c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : class where T1 : class @@ -3307,8 +3238,8 @@ public unsafe void ForEach(F_CCCCC actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3317,7 +3248,7 @@ public unsafe void ForEach(F_CCCCC actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -3326,7 +3257,7 @@ public unsafe void ForEach(F_CCCCC actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3343,6 +3274,7 @@ public unsafe void ForEach(F_CCCCC actio } } + public delegate void F_ECCCCCC(Entity entity, T0 c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : class where T1 : class @@ -3363,8 +3295,8 @@ public unsafe void ForEach(F_ECCCCCC(); @@ -3374,7 +3306,7 @@ public unsafe void ForEach(F_ECCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3385,7 +3317,7 @@ public unsafe void ForEach(F_ECCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3404,6 +3336,7 @@ public unsafe void ForEach(F_ECCCCCC(T0 c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : class where T1 : class @@ -3424,8 +3357,8 @@ public unsafe void ForEach(F_CCCCCC(); @@ -3435,7 +3368,7 @@ public unsafe void ForEach(F_CCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -3445,7 +3378,7 @@ public unsafe void ForEach(F_CCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3463,6 +3396,7 @@ public unsafe void ForEach(F_CCCCCC(Entity entity, DynamicBuffer c0, T1 c1) where T0 : struct, IBufferElementData where T1 : class; @@ -3475,21 +3409,21 @@ public unsafe void ForEach(F_EBC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3504,6 +3438,7 @@ public unsafe void ForEach(F_EBC action) } } + public delegate void F_BC(DynamicBuffer c0, T1 c1) where T0 : struct, IBufferElementData where T1 : class; @@ -3516,20 +3451,20 @@ public unsafe void ForEach(F_BC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3543,6 +3478,7 @@ public unsafe void ForEach(F_BC action) } } + public delegate void F_EBCC(Entity entity, DynamicBuffer c0, T1 c1, T2 c2) where T0 : struct, IBufferElementData where T1 : class @@ -3557,15 +3493,15 @@ public unsafe void ForEach(F_EBCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3573,7 +3509,7 @@ public unsafe void ForEach(F_EBCC action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3589,6 +3525,7 @@ public unsafe void ForEach(F_EBCC action) } } + public delegate void F_BCC(DynamicBuffer c0, T1 c1, T2 c2) where T0 : struct, IBufferElementData where T1 : class @@ -3603,22 +3540,22 @@ public unsafe void ForEach(F_BCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3633,6 +3570,7 @@ public unsafe void ForEach(F_BCC action) } } + public delegate void F_EBCCC(Entity entity, DynamicBuffer c0, T1 c1, T2 c2, T3 c3) where T0 : struct, IBufferElementData where T1 : class @@ -3649,8 +3587,8 @@ public unsafe void ForEach(F_EBCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3658,7 +3596,7 @@ public unsafe void ForEach(F_EBCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3667,7 +3605,7 @@ public unsafe void ForEach(F_EBCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3684,6 +3622,7 @@ public unsafe void ForEach(F_EBCCC action) } } + public delegate void F_BCCC(DynamicBuffer c0, T1 c1, T2 c2, T3 c3) where T0 : struct, IBufferElementData where T1 : class @@ -3700,8 +3639,8 @@ public unsafe void ForEach(F_BCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3709,7 +3648,7 @@ public unsafe void ForEach(F_BCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -3717,7 +3656,7 @@ public unsafe void ForEach(F_BCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3733,6 +3672,7 @@ public unsafe void ForEach(F_BCCC action) } } + public delegate void F_EBCCCC(Entity entity, DynamicBuffer c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : struct, IBufferElementData where T1 : class @@ -3751,8 +3691,8 @@ public unsafe void ForEach(F_EBCCCC acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3761,7 +3701,7 @@ public unsafe void ForEach(F_EBCCCC acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3771,7 +3711,7 @@ public unsafe void ForEach(F_EBCCCC acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3789,6 +3729,7 @@ public unsafe void ForEach(F_EBCCCC acti } } + public delegate void F_BCCCC(DynamicBuffer c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : struct, IBufferElementData where T1 : class @@ -3807,8 +3748,8 @@ public unsafe void ForEach(F_BCCCC actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -3817,7 +3758,7 @@ public unsafe void ForEach(F_BCCCC actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -3826,7 +3767,7 @@ public unsafe void ForEach(F_BCCCC actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3843,6 +3784,7 @@ public unsafe void ForEach(F_BCCCC actio } } + public delegate void F_EBCCCCC(Entity entity, DynamicBuffer c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : struct, IBufferElementData where T1 : class @@ -3863,8 +3805,8 @@ public unsafe void ForEach(F_EBCCCCC(); @@ -3874,7 +3816,7 @@ public unsafe void ForEach(F_EBCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -3885,7 +3827,7 @@ public unsafe void ForEach(F_EBCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3904,6 +3846,7 @@ public unsafe void ForEach(F_EBCCCCC(DynamicBuffer c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : struct, IBufferElementData where T1 : class @@ -3924,8 +3867,8 @@ public unsafe void ForEach(F_BCCCCC(); @@ -3935,7 +3878,7 @@ public unsafe void ForEach(F_BCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -3945,7 +3888,7 @@ public unsafe void ForEach(F_BCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -3963,6 +3906,7 @@ public unsafe void ForEach(F_BCCCCC(Entity entity, T0 c0, T1 c1) where T0 : struct, ISharedComponentData where T1 : class; @@ -3975,21 +3919,21 @@ public unsafe void ForEach(F_ESC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4004,6 +3948,7 @@ public unsafe void ForEach(F_ESC action) } } + public delegate void F_SC(T0 c0, T1 c1) where T0 : struct, ISharedComponentData where T1 : class; @@ -4016,20 +3961,20 @@ public unsafe void ForEach(F_SC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4043,6 +3988,7 @@ public unsafe void ForEach(F_SC action) } } + public delegate void F_ESCC(Entity entity, T0 c0, T1 c1, T2 c2) where T0 : struct, ISharedComponentData where T1 : class @@ -4057,15 +4003,15 @@ public unsafe void ForEach(F_ESCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4073,7 +4019,7 @@ public unsafe void ForEach(F_ESCC action) var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4089,6 +4035,7 @@ public unsafe void ForEach(F_ESCC action) } } + public delegate void F_SCC(T0 c0, T1 c1, T2 c2) where T0 : struct, ISharedComponentData where T1 : class @@ -4103,22 +4050,22 @@ public unsafe void ForEach(F_SCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4133,6 +4080,7 @@ public unsafe void ForEach(F_SCC action) } } + public delegate void F_ESCCC(Entity entity, T0 c0, T1 c1, T2 c2, T3 c3) where T0 : struct, ISharedComponentData where T1 : class @@ -4149,8 +4097,8 @@ public unsafe void ForEach(F_ESCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4158,7 +4106,7 @@ public unsafe void ForEach(F_ESCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4167,7 +4115,7 @@ public unsafe void ForEach(F_ESCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4184,6 +4132,7 @@ public unsafe void ForEach(F_ESCCC action) } } + public delegate void F_SCCC(T0 c0, T1 c1, T2 c2, T3 c3) where T0 : struct, ISharedComponentData where T1 : class @@ -4200,8 +4149,8 @@ public unsafe void ForEach(F_SCCC action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4209,7 +4158,7 @@ public unsafe void ForEach(F_SCCC action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -4217,7 +4166,7 @@ public unsafe void ForEach(F_SCCC action) var chunkComponentType2 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4233,6 +4182,7 @@ public unsafe void ForEach(F_SCCC action) } } + public delegate void F_ESCCCC(Entity entity, T0 c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : struct, ISharedComponentData where T1 : class @@ -4251,8 +4201,8 @@ public unsafe void ForEach(F_ESCCCC acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4261,7 +4211,7 @@ public unsafe void ForEach(F_ESCCCC acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4271,7 +4221,7 @@ public unsafe void ForEach(F_ESCCCC acti var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4289,6 +4239,7 @@ public unsafe void ForEach(F_ESCCCC acti } } + public delegate void F_SCCCC(T0 c0, T1 c1, T2 c2, T3 c3, T4 c4) where T0 : struct, ISharedComponentData where T1 : class @@ -4307,8 +4258,8 @@ public unsafe void ForEach(F_SCCCC actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4317,7 +4268,7 @@ public unsafe void ForEach(F_SCCCC actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -4326,7 +4277,7 @@ public unsafe void ForEach(F_SCCCC actio var chunkComponentType3 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType4 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4343,6 +4294,7 @@ public unsafe void ForEach(F_SCCCC actio } } + public delegate void F_ESCCCCC(Entity entity, T0 c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : struct, ISharedComponentData where T1 : class @@ -4363,8 +4315,8 @@ public unsafe void ForEach(F_ESCCCCC(); @@ -4374,7 +4326,7 @@ public unsafe void ForEach(F_ESCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4385,7 +4337,7 @@ public unsafe void ForEach(F_ESCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4404,6 +4356,7 @@ public unsafe void ForEach(F_ESCCCCC(T0 c0, T1 c1, T2 c2, T3 c3, T4 c4, T5 c5) where T0 : struct, ISharedComponentData where T1 : class @@ -4424,8 +4377,8 @@ public unsafe void ForEach(F_SCCCCC(); @@ -4435,7 +4388,7 @@ public unsafe void ForEach(F_SCCCCC(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -4445,7 +4398,7 @@ public unsafe void ForEach(F_SCCCCC(); var chunkComponentType5 = m_System.GetArchetypeChunkComponentType(); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4463,6 +4416,7 @@ public unsafe void ForEach(F_SCCCCC(Entity entity, ref T0 c0, DynamicBuffer c1) where T0 : struct, IComponentData where T1 : struct, IBufferElementData; @@ -4475,21 +4429,21 @@ public unsafe void ForEach(F_EDB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4504,6 +4458,7 @@ public unsafe void ForEach(F_EDB action) } } + public delegate void F_DB(ref T0 c0, DynamicBuffer c1) where T0 : struct, IComponentData where T1 : struct, IBufferElementData; @@ -4516,20 +4471,20 @@ public unsafe void ForEach(F_DB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4543,6 +4498,7 @@ public unsafe void ForEach(F_DB action) } } + public delegate void F_EDBB(Entity entity, ref T0 c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4557,15 +4513,15 @@ public unsafe void ForEach(F_EDBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4573,7 +4529,7 @@ public unsafe void ForEach(F_EDBB action) var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4589,6 +4545,7 @@ public unsafe void ForEach(F_EDBB action) } } + public delegate void F_DBB(ref T0 c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4603,22 +4560,22 @@ public unsafe void ForEach(F_DBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4633,6 +4590,7 @@ public unsafe void ForEach(F_DBB action) } } + public delegate void F_EDBBB(Entity entity, ref T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4649,8 +4607,8 @@ public unsafe void ForEach(F_EDBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4658,7 +4616,7 @@ public unsafe void ForEach(F_EDBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4667,7 +4625,7 @@ public unsafe void ForEach(F_EDBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4684,6 +4642,7 @@ public unsafe void ForEach(F_EDBBB action) } } + public delegate void F_DBBB(ref T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4700,8 +4659,8 @@ public unsafe void ForEach(F_DBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4709,7 +4668,7 @@ public unsafe void ForEach(F_DBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -4717,7 +4676,7 @@ public unsafe void ForEach(F_DBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4733,6 +4692,7 @@ public unsafe void ForEach(F_DBBB action) } } + public delegate void F_EDBBBB(Entity entity, ref T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4751,8 +4711,8 @@ public unsafe void ForEach(F_EDBBBB acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4761,7 +4721,7 @@ public unsafe void ForEach(F_EDBBBB acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4771,7 +4731,7 @@ public unsafe void ForEach(F_EDBBBB acti var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4789,6 +4749,7 @@ public unsafe void ForEach(F_EDBBBB acti } } + public delegate void F_DBBBB(ref T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4807,8 +4768,8 @@ public unsafe void ForEach(F_DBBBB actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -4817,7 +4778,7 @@ public unsafe void ForEach(F_DBBBB actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -4826,7 +4787,7 @@ public unsafe void ForEach(F_DBBBB actio var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4843,6 +4804,7 @@ public unsafe void ForEach(F_DBBBB actio } } + public delegate void F_EDBBBBB(Entity entity, ref T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4863,8 +4825,8 @@ public unsafe void ForEach(F_EDBBBBB(); @@ -4874,7 +4836,7 @@ public unsafe void ForEach(F_EDBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -4885,7 +4847,7 @@ public unsafe void ForEach(F_EDBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4904,6 +4866,7 @@ public unsafe void ForEach(F_EDBBBBB(ref T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : struct, IComponentData where T1 : struct, IBufferElementData @@ -4924,8 +4887,8 @@ public unsafe void ForEach(F_DBBBBB(); @@ -4935,7 +4898,7 @@ public unsafe void ForEach(F_DBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(false); @@ -4945,7 +4908,7 @@ public unsafe void ForEach(F_DBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -4963,6 +4926,7 @@ public unsafe void ForEach(F_DBBBBB(Entity entity, T0 c0, DynamicBuffer c1) where T0 : class where T1 : struct, IBufferElementData; @@ -4975,21 +4939,21 @@ public unsafe void ForEach(F_ECB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5004,6 +4968,7 @@ public unsafe void ForEach(F_ECB action) } } + public delegate void F_CB(T0 c0, DynamicBuffer c1) where T0 : class where T1 : struct, IBufferElementData; @@ -5016,20 +4981,20 @@ public unsafe void ForEach(F_CB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5043,6 +5008,7 @@ public unsafe void ForEach(F_CB action) } } + public delegate void F_ECBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : class where T1 : struct, IBufferElementData @@ -5057,15 +5023,15 @@ public unsafe void ForEach(F_ECBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5073,7 +5039,7 @@ public unsafe void ForEach(F_ECBB action) var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5089,6 +5055,7 @@ public unsafe void ForEach(F_ECBB action) } } + public delegate void F_CBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : class where T1 : struct, IBufferElementData @@ -5103,22 +5070,22 @@ public unsafe void ForEach(F_CBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5133,6 +5100,7 @@ public unsafe void ForEach(F_CBB action) } } + public delegate void F_ECBBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : class where T1 : struct, IBufferElementData @@ -5149,8 +5117,8 @@ public unsafe void ForEach(F_ECBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5158,7 +5126,7 @@ public unsafe void ForEach(F_ECBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5167,7 +5135,7 @@ public unsafe void ForEach(F_ECBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5184,6 +5152,7 @@ public unsafe void ForEach(F_ECBBB action) } } + public delegate void F_CBBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : class where T1 : struct, IBufferElementData @@ -5200,8 +5169,8 @@ public unsafe void ForEach(F_CBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5209,7 +5178,7 @@ public unsafe void ForEach(F_CBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -5217,7 +5186,7 @@ public unsafe void ForEach(F_CBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5233,6 +5202,7 @@ public unsafe void ForEach(F_CBBB action) } } + public delegate void F_ECBBBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : class where T1 : struct, IBufferElementData @@ -5251,8 +5221,8 @@ public unsafe void ForEach(F_ECBBBB acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5261,7 +5231,7 @@ public unsafe void ForEach(F_ECBBBB acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5271,7 +5241,7 @@ public unsafe void ForEach(F_ECBBBB acti var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5289,6 +5259,7 @@ public unsafe void ForEach(F_ECBBBB acti } } + public delegate void F_CBBBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : class where T1 : struct, IBufferElementData @@ -5307,8 +5278,8 @@ public unsafe void ForEach(F_CBBBB actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5317,7 +5288,7 @@ public unsafe void ForEach(F_CBBBB actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -5326,7 +5297,7 @@ public unsafe void ForEach(F_CBBBB actio var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5343,6 +5314,7 @@ public unsafe void ForEach(F_CBBBB actio } } + public delegate void F_ECBBBBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : class where T1 : struct, IBufferElementData @@ -5363,8 +5335,8 @@ public unsafe void ForEach(F_ECBBBBB(); @@ -5374,7 +5346,7 @@ public unsafe void ForEach(F_ECBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5385,7 +5357,7 @@ public unsafe void ForEach(F_ECBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5404,6 +5376,7 @@ public unsafe void ForEach(F_ECBBBBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : class where T1 : struct, IBufferElementData @@ -5424,8 +5397,8 @@ public unsafe void ForEach(F_CBBBBB(); @@ -5435,7 +5408,7 @@ public unsafe void ForEach(F_CBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkComponentType(); @@ -5445,7 +5418,7 @@ public unsafe void ForEach(F_CBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5463,6 +5436,7 @@ public unsafe void ForEach(F_CBBBBB(Entity entity, DynamicBuffer c0, DynamicBuffer c1) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData; @@ -5475,21 +5449,21 @@ public unsafe void ForEach(F_EBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5504,6 +5478,7 @@ public unsafe void ForEach(F_EBB action) } } + public delegate void F_BB(DynamicBuffer c0, DynamicBuffer c1) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData; @@ -5516,20 +5491,20 @@ public unsafe void ForEach(F_BB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5543,6 +5518,7 @@ public unsafe void ForEach(F_BB action) } } + public delegate void F_EBBB(Entity entity, DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5557,15 +5533,15 @@ public unsafe void ForEach(F_EBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5573,7 +5549,7 @@ public unsafe void ForEach(F_EBBB action) var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5589,6 +5565,7 @@ public unsafe void ForEach(F_EBBB action) } } + public delegate void F_BBB(DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5603,22 +5580,22 @@ public unsafe void ForEach(F_BBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5633,6 +5610,7 @@ public unsafe void ForEach(F_BBB action) } } + public delegate void F_EBBBB(Entity entity, DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5649,8 +5627,8 @@ public unsafe void ForEach(F_EBBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5658,7 +5636,7 @@ public unsafe void ForEach(F_EBBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5667,7 +5645,7 @@ public unsafe void ForEach(F_EBBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5684,6 +5662,7 @@ public unsafe void ForEach(F_EBBBB action) } } + public delegate void F_BBBB(DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5700,8 +5679,8 @@ public unsafe void ForEach(F_BBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5709,7 +5688,7 @@ public unsafe void ForEach(F_BBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -5717,7 +5696,7 @@ public unsafe void ForEach(F_BBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5733,6 +5712,7 @@ public unsafe void ForEach(F_BBBB action) } } + public delegate void F_EBBBBB(Entity entity, DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5751,8 +5731,8 @@ public unsafe void ForEach(F_EBBBBB acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5761,7 +5741,7 @@ public unsafe void ForEach(F_EBBBBB acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5771,7 +5751,7 @@ public unsafe void ForEach(F_EBBBBB acti var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5789,6 +5769,7 @@ public unsafe void ForEach(F_EBBBBB acti } } + public delegate void F_BBBBB(DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5807,8 +5788,8 @@ public unsafe void ForEach(F_BBBBB actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -5817,7 +5798,7 @@ public unsafe void ForEach(F_BBBBB actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -5826,7 +5807,7 @@ public unsafe void ForEach(F_BBBBB actio var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5843,6 +5824,7 @@ public unsafe void ForEach(F_BBBBB actio } } + public delegate void F_EBBBBBB(Entity entity, DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5863,8 +5845,8 @@ public unsafe void ForEach(F_EBBBBBB(); @@ -5874,7 +5856,7 @@ public unsafe void ForEach(F_EBBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -5885,7 +5867,7 @@ public unsafe void ForEach(F_EBBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5904,6 +5886,7 @@ public unsafe void ForEach(F_EBBBBBB(DynamicBuffer c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData @@ -5924,8 +5907,8 @@ public unsafe void ForEach(F_BBBBBB(); @@ -5935,7 +5918,7 @@ public unsafe void ForEach(F_BBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkBufferType(false); @@ -5945,7 +5928,7 @@ public unsafe void ForEach(F_BBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -5963,6 +5946,7 @@ public unsafe void ForEach(F_BBBBBB(Entity entity, T0 c0, DynamicBuffer c1) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData; @@ -5975,21 +5959,21 @@ public unsafe void ForEach(F_ESB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var entityType = m_System.GetArchetypeChunkEntityType(); var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6004,6 +5988,7 @@ public unsafe void ForEach(F_ESB action) } } + public delegate void F_SB(T0 c0, DynamicBuffer c1) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData; @@ -6016,20 +6001,20 @@ public unsafe void ForEach(F_SB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[2]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 2); + query = ResolveEntityQuery(delegateTypes, 2); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6043,6 +6028,7 @@ public unsafe void ForEach(F_SB action) } } + public delegate void F_ESBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6057,15 +6043,15 @@ public unsafe void ForEach(F_ESBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -6073,7 +6059,7 @@ public unsafe void ForEach(F_ESBB action) var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6089,6 +6075,7 @@ public unsafe void ForEach(F_ESBB action) } } + public delegate void F_SBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6103,22 +6090,22 @@ public unsafe void ForEach(F_SBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[3]; delegateTypes[0] = TypeManager.GetTypeIndex(); delegateTypes[1] = TypeManager.GetTypeIndex(); delegateTypes[2] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 3); + query = ResolveEntityQuery(delegateTypes, 3); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); var chunkComponentType1 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6133,6 +6120,7 @@ public unsafe void ForEach(F_SBB action) } } + public delegate void F_ESBBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6149,8 +6137,8 @@ public unsafe void ForEach(F_ESBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -6158,7 +6146,7 @@ public unsafe void ForEach(F_ESBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -6167,7 +6155,7 @@ public unsafe void ForEach(F_ESBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6184,6 +6172,7 @@ public unsafe void ForEach(F_ESBBB action) } } + public delegate void F_SBBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6200,8 +6189,8 @@ public unsafe void ForEach(F_SBBB action) using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[4]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -6209,7 +6198,7 @@ public unsafe void ForEach(F_SBBB action) delegateTypes[2] = TypeManager.GetTypeIndex(); delegateTypes[3] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 4); + query = ResolveEntityQuery(delegateTypes, 4); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -6217,7 +6206,7 @@ public unsafe void ForEach(F_SBBB action) var chunkComponentType2 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6233,6 +6222,7 @@ public unsafe void ForEach(F_SBBB action) } } + public delegate void F_ESBBBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6251,8 +6241,8 @@ public unsafe void ForEach(F_ESBBBB acti using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -6261,7 +6251,7 @@ public unsafe void ForEach(F_ESBBBB acti delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -6271,7 +6261,7 @@ public unsafe void ForEach(F_ESBBBB acti var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6289,6 +6279,7 @@ public unsafe void ForEach(F_ESBBBB acti } } + public delegate void F_SBBBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6307,8 +6298,8 @@ public unsafe void ForEach(F_SBBBB actio using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { var delegateTypes = stackalloc int[5]; delegateTypes[0] = TypeManager.GetTypeIndex(); @@ -6317,7 +6308,7 @@ public unsafe void ForEach(F_SBBBB actio delegateTypes[3] = TypeManager.GetTypeIndex(); delegateTypes[4] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 5); + query = ResolveEntityQuery(delegateTypes, 5); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -6326,7 +6317,7 @@ public unsafe void ForEach(F_SBBBB actio var chunkComponentType3 = m_System.GetArchetypeChunkBufferType(false); var chunkComponentType4 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6343,6 +6334,7 @@ public unsafe void ForEach(F_SBBBB actio } } + public delegate void F_ESBBBBB(Entity entity, T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6363,8 +6355,8 @@ public unsafe void ForEach(F_ESBBBBB(); @@ -6374,7 +6366,7 @@ public unsafe void ForEach(F_ESBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var entityType = m_System.GetArchetypeChunkEntityType(); @@ -6385,7 +6377,7 @@ public unsafe void ForEach(F_ESBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6404,6 +6396,7 @@ public unsafe void ForEach(F_ESBBBBB(T0 c0, DynamicBuffer c1, DynamicBuffer c2, DynamicBuffer c3, DynamicBuffer c4, DynamicBuffer c5) where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData @@ -6424,8 +6417,8 @@ public unsafe void ForEach(F_SBBBBB(); @@ -6435,7 +6428,7 @@ public unsafe void ForEach(F_SBBBBB(); delegateTypes[5] = TypeManager.GetTypeIndex(); - group = ResolveComponentGroup(delegateTypes, 6); + query = ResolveEntityQuery(delegateTypes, 6); } var chunkComponentType0 = m_System.GetArchetypeChunkSharedComponentType(); @@ -6445,7 +6438,7 @@ public unsafe void ForEach(F_SBBBBB(false); var chunkComponentType5 = m_System.GetArchetypeChunkBufferType(false); - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -6465,1429 +6458,539 @@ public unsafe void ForEach(F_SBBBBB(EntityQueryBuilder.F_ED action, ComponentGroup group = null) - where T0 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_D action, ComponentGroup group = null) - where T0 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EC action, ComponentGroup group = null) - where T0 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_C action, ComponentGroup group = null) - where T0 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_B action, ComponentGroup group = null) - where T0 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ES action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_S action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDDDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DDDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDDDDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DDDDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDDDDDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DDDDDD action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECDDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CDDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECDDDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CDDDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECDDDDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CDDDDD action, ComponentGroup group = null) - where T0 : class where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBDDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BDDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBDDDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BDDDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBDDDDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BDDDDD action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESDDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SDDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESDDDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SDDDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESDDDDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SDDDDD action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IComponentData where T2 : struct, IComponentData where T3 : struct, IComponentData where T4 : struct, IComponentData where T5 : struct, IComponentData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDCCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DCCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDCCCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DCCCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDCCCCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DCCCCC action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECC action, ComponentGroup group = null) - where T0 : class where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CC action, ComponentGroup group = null) - where T0 : class where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECCCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CCCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECCCCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CCCCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECCCCCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CCCCCC action, ComponentGroup group = null) - where T0 : class where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBCCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BCCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBCCCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BCCCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBCCCCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BCCCCC action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESCCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SCCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class where T3 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESCCCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SCCCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class where T3 : class where T4 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESCCCCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SCCCCC action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDBBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DBBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDBBBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DBBBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EDBBBBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_DBBBBB action, ComponentGroup group = null) - where T0 : struct, IComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECBBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CBBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECBBBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CBBBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ECBBBBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_CBBBBB action, ComponentGroup group = null) - where T0 : class where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBBBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BBBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBBBBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BBBBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_EBBBBBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_BBBBBB action, ComponentGroup group = null) - where T0 : struct, IBufferElementData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESBBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SBBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESBBBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SBBBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_ESBBBBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach(EntityQueryBuilder.F_SBBBBB action, ComponentGroup group = null) - where T0 : struct, ISharedComponentData where T1 : struct, IBufferElementData where T2 : struct, IBufferElementData where T3 : struct, IBufferElementData where T4 : struct, IBufferElementData where T5 : struct, IBufferElementData - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } - - } -} + + // Schedule() implementation for DOTS-standalone. + // The IDE calls Schedule(), and then code-gen is used to + // replace the call to the correct Schedule_D method, With + // known types. + +#if UNITY_ZEROPLAYER + public static partial class JobForEachExtensions { + + // This method is used by the IDE, and is what will be replaced by one of the Schedule_D methods below. + public unsafe static JobHandle Schedule(this TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IBaseJobForEach + { + throw new NotImplementedException("Schedule() should have been replaced by code-gen."); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_D(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEach + where T0 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[1]; + delegateTypes[0] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 1); + } + + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(array0, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_ED(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEachWithEntity + where T0 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[1]; + delegateTypes[0] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 1); + } + + var entityType = system.GetArchetypeChunkEntityType(); + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var entityArray = (Entity*)chunk.GetNativeArray(entityType).GetUnsafeReadOnlyPtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(entityArray[i], entityArray[i].Index, ref UnsafeUtilityEx.ArrayElementAsRef(array0, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_DD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEach + where T0 : struct, IComponentData + where T1 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[2]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 2); + } + + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_EDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEachWithEntity + where T0 : struct, IComponentData + where T1 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[2]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 2); + } + + var entityType = system.GetArchetypeChunkEntityType(); + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var entityArray = (Entity*)chunk.GetNativeArray(entityType).GetUnsafeReadOnlyPtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(entityArray[i], entityArray[i].Index, ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_DDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEach + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[3]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 3); + } + + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_EDDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEachWithEntity + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[3]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 3); + } + + var entityType = system.GetArchetypeChunkEntityType(); + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + var entityArray = (Entity*)chunk.GetNativeArray(entityType).GetUnsafeReadOnlyPtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(entityArray[i], entityArray[i].Index, ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_DDDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEach + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + where T3 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[4]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + delegateTypes[3] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 4); + } + + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType3 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + var array3 = chunk.GetNativeArray(chunkComponentType3).GetUnsafePtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i), ref UnsafeUtilityEx.ArrayElementAsRef(array3, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_EDDDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEachWithEntity + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + where T3 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[4]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + delegateTypes[3] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 4); + } + + var entityType = system.GetArchetypeChunkEntityType(); + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType3 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + var array3 = chunk.GetNativeArray(chunkComponentType3).GetUnsafePtr(); + var entityArray = (Entity*)chunk.GetNativeArray(entityType).GetUnsafeReadOnlyPtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(entityArray[i], entityArray[i].Index, ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i), ref UnsafeUtilityEx.ArrayElementAsRef(array3, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_DDDDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEach + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + where T3 : struct, IComponentData + where T4 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[5]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + delegateTypes[3] = ComponentType.ReadWrite(); + delegateTypes[4] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 5); + } + + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType3 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType4 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + var array3 = chunk.GetNativeArray(chunkComponentType3).GetUnsafePtr(); + var array4 = chunk.GetNativeArray(chunkComponentType4).GetUnsafePtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i), ref UnsafeUtilityEx.ArrayElementAsRef(array3, i), ref UnsafeUtilityEx.ArrayElementAsRef(array4, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_EDDDDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEachWithEntity + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + where T3 : struct, IComponentData + where T4 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[5]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + delegateTypes[3] = ComponentType.ReadWrite(); + delegateTypes[4] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 5); + } + + var entityType = system.GetArchetypeChunkEntityType(); + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType3 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType4 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + var array3 = chunk.GetNativeArray(chunkComponentType3).GetUnsafePtr(); + var array4 = chunk.GetNativeArray(chunkComponentType4).GetUnsafePtr(); + var entityArray = (Entity*)chunk.GetNativeArray(entityType).GetUnsafeReadOnlyPtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(entityArray[i], entityArray[i].Index, ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i), ref UnsafeUtilityEx.ArrayElementAsRef(array3, i), ref UnsafeUtilityEx.ArrayElementAsRef(array4, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_DDDDDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEach + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + where T3 : struct, IComponentData + where T4 : struct, IComponentData + where T5 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[6]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + delegateTypes[3] = ComponentType.ReadWrite(); + delegateTypes[4] = ComponentType.ReadWrite(); + delegateTypes[5] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 6); + } + + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType3 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType4 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType5 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + var array3 = chunk.GetNativeArray(chunkComponentType3).GetUnsafePtr(); + var array4 = chunk.GetNativeArray(chunkComponentType4).GetUnsafePtr(); + var array5 = chunk.GetNativeArray(chunkComponentType5).GetUnsafePtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i), ref UnsafeUtilityEx.ArrayElementAsRef(array3, i), ref UnsafeUtilityEx.ArrayElementAsRef(array4, i), ref UnsafeUtilityEx.ArrayElementAsRef(array5, i)); + } + } + } + return new JobHandle(); + } + + + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_EDDDDDD(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IJobForEachWithEntity + where T0 : struct, IComponentData + where T1 : struct, IComponentData + where T2 : struct, IComponentData + where T3 : struct, IComponentData + where T4 : struct, IComponentData + where T5 : struct, IComponentData + { + { + EntityQuery query = null; + if (query== null) + { + var delegateTypes = stackalloc ComponentType[6]; + delegateTypes[0] = ComponentType.ReadWrite(); + delegateTypes[1] = ComponentType.ReadWrite(); + delegateTypes[2] = ComponentType.ReadWrite(); + delegateTypes[3] = ComponentType.ReadWrite(); + delegateTypes[4] = ComponentType.ReadWrite(); + delegateTypes[5] = ComponentType.ReadWrite(); + + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(delegateTypes, 6); + } + + var entityType = system.GetArchetypeChunkEntityType(); + var chunkComponentType0 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType1 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType2 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType3 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType4 = system.GetArchetypeChunkComponentType(false); + var chunkComponentType5 = system.GetArchetypeChunkComponentType(false); + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { + var array0 = chunk.GetNativeArray(chunkComponentType0).GetUnsafePtr(); + var array1 = chunk.GetNativeArray(chunkComponentType1).GetUnsafePtr(); + var array2 = chunk.GetNativeArray(chunkComponentType2).GetUnsafePtr(); + var array3 = chunk.GetNativeArray(chunkComponentType3).GetUnsafePtr(); + var array4 = chunk.GetNativeArray(chunkComponentType4).GetUnsafePtr(); + var array5 = chunk.GetNativeArray(chunkComponentType5).GetUnsafePtr(); + var entityArray = (Entity*)chunk.GetNativeArray(entityType).GetUnsafeReadOnlyPtr(); + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(entityArray[i], entityArray[i].Index, ref UnsafeUtilityEx.ArrayElementAsRef(array0, i), ref UnsafeUtilityEx.ArrayElementAsRef(array1, i), ref UnsafeUtilityEx.ArrayElementAsRef(array2, i), ref UnsafeUtilityEx.ArrayElementAsRef(array3, i), ref UnsafeUtilityEx.ArrayElementAsRef(array4, i), ref UnsafeUtilityEx.ArrayElementAsRef(array5, i)); + } + } + } + return new JobHandle(); + } + + } +#endif // UNITY_ZEROPLAYER + +} // namespace Unity.Entities diff --git a/Unity.Entities/EntityQueryBuilder_ForEach.gen.cs.meta b/Unity.Entities/EntityQueryBuilder_ForEach.gen.cs.meta new file mode 100644 index 00000000..0413c1b2 --- /dev/null +++ b/Unity.Entities/EntityQueryBuilder_ForEach.gen.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 118db93182504784ea2d31aeef050909 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/EntityQueryBuilder.tt b/Unity.Entities/EntityQueryBuilder_ForEach.tt similarity index 69% rename from Unity.Entities/EntityQueryBuilder.tt rename to Unity.Entities/EntityQueryBuilder_ForEach.tt index f203b40e..c5ea83b8 100644 --- a/Unity.Entities/EntityQueryBuilder.tt +++ b/Unity.Entities/EntityQueryBuilder_ForEach.tt @@ -16,31 +16,16 @@ <# var combinations = InitCombinations(); #> // Generated by EntityQueryBuilder.tt (<#=combinations.Count * 2 - 1#> `foreach` combinations) +using System; +using System.ComponentModel; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; +using Unity.Jobs; namespace Unity.Entities { public partial struct EntityQueryBuilder { - // ** FLUENT QUERY ** - -<# -foreach (var (name, count) in new[] { ("Any", 5), ( "None", 5), ("All", 5) }) { - for (var it = 1; it <= count; ++it) { -#> - public EntityQueryBuilder With<#=name#><<#=Series("T{0}", it, ", ")#>>() - { - ValidateHasNoGroup(); -<# for (var ia = 0; ia < it; ++ia) {#> - m_<#=name#>.Add(TypeManager.GetTypeIndex>()); -<# }#> - return this; - } - -<#}}#> - // ** FOREACH ** - <# foreach (var categories in combinations) { foreach (var hasEntity in new[] { true, false }) { @@ -50,9 +35,11 @@ foreach (var categories in combinations) { var delegateName = GetDelegateName(categories, hasEntity); var delegateParameters = GetDelegateParameters(categories, hasEntity); var genericTypes = categories.Any() ? ("<" + Series("T{0}", categories.Length, ", ") + ">") : ""; + var genericTypesWithJob = ""; var genericConstraints = GetGenericConstraints(categories); var actionParams = GetActionParams(categories, hasEntity); #> + public delegate void <#=delegateName#><#=genericTypes#>(<#=delegateParameters#>)<#=categories.Any() ? "" : ";"#> <# foreach (var constraint in Smart(genericConstraints)) {#> <#=constraint.Value#><#=constraint.IfLast(";")#> @@ -67,8 +54,8 @@ foreach (var categories in combinations) { using (InsideForEach()) #endif { - var group = m_Group; - if (group == null) + var query = m_Query; + if (query == null) { <# if (categories.Any()) {#> var delegateTypes = stackalloc int[<#=categories.Length#>]; @@ -77,7 +64,7 @@ foreach (var categories in combinations) { <# }#> <# }#> - group = ResolveComponentGroup(<#=categories.Any() ? "delegateTypes" : "null"#>, <#=categories.Length#>); + query = ResolveEntityQuery(<#=categories.Any() ? "delegateTypes" : "null"#>, <#=categories.Length#>); } <# if (hasEntity) {#> @@ -87,7 +74,7 @@ foreach (var categories in combinations) { var chunkComponentType<#=i#> = m_System.<#=AccessFunction[c]#>>(<#=IsReadOnly[c]#>); <# }#> - using (var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) { foreach (var chunk in chunks) { @@ -108,33 +95,102 @@ foreach (var categories in combinations) { <#}}#> } - // BACK-COMPAT - TO BE REMOVED - public partial class ComponentSystem - { + // Schedule() implementation for DOTS-standalone. + // The IDE calls Schedule(), and then code-gen is used to + // replace the call to the correct Schedule_D method, With + // known types. + +#if UNITY_ZEROPLAYER + public static partial class JobForEachExtensions { + + // This method is used by the IDE, and is what will be replaced by one of the Schedule_D methods below. + public unsafe static JobHandle Schedule(this TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, IBaseJobForEach + { + throw new NotImplementedException("Schedule() should have been replaced by code-gen."); + } <# + +string GetScheduleParams(Category[] categories, bool hasEntity) +{ + var parts = categories.Select((c, i) => string.Format(ArrayAccess[(int)c], i)); + if (hasEntity) { + parts = parts.Prepend("entityArray[i].Index"); + parts = parts.Prepend("entityArray[i]"); + } + return string.Join(", ", parts); +} + foreach (var categories in combinations) { - foreach (var hasEntity in new[] { true, false }) { - if (!categories.Any() && !hasEntity) + foreach (var hasEntity in new[] { false, true }) { + if (!categories.Any()) continue; + var mappedCategories = categories.Select((c, i) => (c: (int)c, i: i)); var delegateName = GetDelegateName(categories, hasEntity); + var delegateParameters = GetDelegateParameters(categories, hasEntity); var genericTypes = categories.Any() ? ("<" + Series("T{0}", categories.Length, ", ") + ">") : ""; + var genericTypesWithJob = ""; var genericConstraints = GetGenericConstraints(categories); + var actionParams = GetScheduleParams(categories, hasEntity); + var dName = (hasEntity ? "E" : "") + Series("D", categories.Length, ""); + var jobInterface = hasEntity ? "IJobForEachWithEntity" : "IJobForEach"; #> - [System.Obsolete("Call Entities.ForEach() or Entities.With(group).ForEach() instead")] - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public unsafe void ForEach<#=genericTypes#>(EntityQueryBuilder.<#=delegateName#><#=genericTypes#> action, ComponentGroup group = null) - <#=string.Join(" ", genericConstraints)#> - { - var q = Entities; - if (group != null) - q = q.With(group); - q.ForEach(action); - } +<# if (categories.Any() && !categories.Any(c => c != Category.D)) { #> + [EditorBrowsable(EditorBrowsableState.Never)] + public unsafe static JobHandle Schedule_<#=dName#><#=genericTypesWithJob#>(TJob job, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where TJob : struct, <#=jobInterface#><#=genericTypes#> +<# foreach (var constraint in genericConstraints) {#> + <#=constraint#> +<# }#> + { + { + EntityQuery query = null; + if (query== null) + { +<# if (categories.Any()) {#> + var delegateTypes = stackalloc ComponentType[<#=categories.Length#>]; +<# foreach (var (c, i) in mappedCategories) { /*TODO: when tiny on c# 7.3 switch to initializer syntax */#> + delegateTypes[<#=i#>] = ComponentType.ReadWrite>(); +<# }#> + +<# }#> + query = /*ResolveEntityQuery*/system.GetEntityQueryInternal(<#=categories.Any() ? "delegateTypes" : "null"#>, <#=categories.Length#>); + } + +<# if (hasEntity) {#> + var entityType = system.GetArchetypeChunkEntityType(); +<# }#> +<# foreach (var (c, i) in mappedCategories) {#> + var chunkComponentType<#=i#> = system.<#=AccessFunction[c]#>>(<#=IsReadOnly[c]#>); +<# }#> + + using (var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob)) + { + foreach (var chunk in chunks) + { +<# foreach (var (c, i) in mappedCategories) {#> + var array<#=i#> = chunk.<#=string.Format(ChunkGetArray[c], i)#>; +<# }#> +<# if (hasEntity) {#> + var entityArray = (Entity*)chunk.GetNativeArray(entityType).GetUnsafeReadOnlyPtr(); +<# }#> + + for (int i = 0, count = chunk.Count; i < count; ++i) + job.Execute(<#=actionParams#>); + } + } + } + return new JobHandle(); + } + +<# } #> <#}}#> - } -} + } +#endif // UNITY_ZEROPLAYER + +} // namespace Unity.Entities <#+ enum Category diff --git a/Unity.Entities/EntityQueryBuilder_ForEach.tt.meta b/Unity.Entities/EntityQueryBuilder_ForEach.tt.meta new file mode 100644 index 00000000..ff7f7df3 --- /dev/null +++ b/Unity.Entities/EntityQueryBuilder_ForEach.tt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 389ff16d82330834188334e010bd0923 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/EntityQueryBuilder_With.gen.cs b/Unity.Entities/EntityQueryBuilder_With.gen.cs new file mode 100644 index 00000000..95a0e751 --- /dev/null +++ b/Unity.Entities/EntityQueryBuilder_With.gen.cs @@ -0,0 +1,156 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +// Generated by EntityQueryBuilder_With.tt + +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; + +namespace Unity.Entities +{ + public partial struct EntityQueryBuilder + { + // ** FLUENT QUERY ** + + public EntityQueryBuilder WithAny() + { + ValidateHasNoQuery(); + m_Any.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAny() + { + ValidateHasNoQuery(); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAny() + { + ValidateHasNoQuery(); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAny() + { + ValidateHasNoQuery(); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAny() + { + ValidateHasNoQuery(); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + m_Any.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithNone() + { + ValidateHasNoQuery(); + m_None.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithNone() + { + ValidateHasNoQuery(); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithNone() + { + ValidateHasNoQuery(); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithNone() + { + ValidateHasNoQuery(); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithNone() + { + ValidateHasNoQuery(); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + m_None.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAll() + { + ValidateHasNoQuery(); + m_All.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAll() + { + ValidateHasNoQuery(); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAll() + { + ValidateHasNoQuery(); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAll() + { + ValidateHasNoQuery(); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + return this; + } + + public EntityQueryBuilder WithAll() + { + ValidateHasNoQuery(); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + m_All.Add(TypeManager.GetTypeIndex()); + return this; + } + + } +} diff --git a/Unity.Entities/EntityQueryBuilder_With.gen.cs.meta b/Unity.Entities/EntityQueryBuilder_With.gen.cs.meta new file mode 100644 index 00000000..05b4d4b4 --- /dev/null +++ b/Unity.Entities/EntityQueryBuilder_With.gen.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35b8234d1cdce984490dca58bf2c083c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/EntityQueryBuilder_With.tt b/Unity.Entities/EntityQueryBuilder_With.tt new file mode 100644 index 00000000..0e494265 --- /dev/null +++ b/Unity.Entities/EntityQueryBuilder_With.tt @@ -0,0 +1,49 @@ +<#/*THIS IS A T4 FILE - see HACKING.md for what it is and how to run codegen*/#> +<#@ assembly name="System.Collections" #> +<#@ assembly name="System.Core" #> +<#@ assembly name="System.Linq" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Linq" #> +<#@ output extension=".gen.cs" #> +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +// Generated by EntityQueryBuilder_With.tt + +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; + +namespace Unity.Entities +{ + public partial struct EntityQueryBuilder + { + // ** FLUENT QUERY ** + +<# +foreach (var (name, count) in new[] { ("Any", 5), ( "None", 5), ("All", 5) }) { + for (var it = 1; it <= count; ++it) { +#> + public EntityQueryBuilder With<#=name#><<#=Series("T{0}", it, ", ")#>>() + { + ValidateHasNoQuery(); +<# for (var ia = 0; ia < it; ++ia) {#> + m_<#=name#>.Add(TypeManager.GetTypeIndex>()); +<# }#> + return this; + } + +<#}}#> + } +} +<#+ + +// misc support utils + +static string Series(string formatString, int count, string separator) => + string.Join(separator, Enumerable.Range(0, count).Select(i => string.Format(formatString, i))); +#> diff --git a/Unity.Entities/EntityQueryBuilder_With.tt.meta b/Unity.Entities/EntityQueryBuilder_With.tt.meta new file mode 100644 index 00000000..9dfe94d4 --- /dev/null +++ b/Unity.Entities/EntityQueryBuilder_With.tt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d43583fb8d51c0e479ff1df8ae774905 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/EntityQueryCache.cs b/Unity.Entities/EntityQueryCache.cs index 4a1e501a..f28cd24c 100644 --- a/Unity.Entities/EntityQueryCache.cs +++ b/Unity.Entities/EntityQueryCache.cs @@ -4,11 +4,11 @@ namespace Unity.Entities { class EntityQueryCache { - uint[] m_CacheHashes; // combined hash of QueryComponentBuilder and delegate types - ComponentGroup[] m_CacheComponentGroups; + uint[] m_CacheHashes; // combined hash of QueryComponentBuilder and delegate types + EntityQuery[] m_CachedEntityQueries; #if ENABLE_UNITY_COLLECTIONS_CHECKS - EntityQueryBuilder[] m_CacheCheckQueryBuilders; - int[][] m_CacheCheckDelegateTypeIndices; + EntityQueryBuilder[] m_CacheCheckQueryBuilders; + int[][] m_CacheCheckDelegateTypeIndices; #endif public EntityQueryCache(int cacheSize = 10) @@ -19,7 +19,7 @@ public EntityQueryCache(int cacheSize = 10) #endif m_CacheHashes = new uint[cacheSize]; - m_CacheComponentGroups = new ComponentGroup[cacheSize]; + m_CachedEntityQueries = new EntityQuery[cacheSize]; // we use these for an additional equality check to avoid accidental hash collisions #if ENABLE_UNITY_COLLECTIONS_CHECKS @@ -28,9 +28,18 @@ public EntityQueryCache(int cacheSize = 10) #endif } + public int CalcUsedCacheCount() + { + var used = 0; + while (used < m_CacheHashes.Length && m_CachedEntityQueries[used] != null) + ++used; + + return used; + } + public int FindQueryInCache(uint hash) { - for (var i = 0; i < m_CacheHashes.Length && m_CacheComponentGroups[i] != null; ++i) + for (var i = 0; i < m_CacheHashes.Length && m_CachedEntityQueries[i] != null; ++i) { if (m_CacheHashes[i] == hash) return i; @@ -39,15 +48,15 @@ public int FindQueryInCache(uint hash) return -1; } - public unsafe int CreateCachedQuery(uint hash, ComponentGroup group + public unsafe int CreateCachedQuery(uint hash, EntityQuery query #if ENABLE_UNITY_COLLECTIONS_CHECKS , ref EntityQueryBuilder builder, int* delegateTypeIndices, int delegateTypeCount #endif ) { #if ENABLE_UNITY_COLLECTIONS_CHECKS - if (group == null) - throw new ArgumentNullException(nameof(group)); + if (query == null) + throw new ArgumentNullException(nameof(query)); #endif var index = 0; @@ -65,7 +74,7 @@ public unsafe int CreateCachedQuery(uint hash, ComponentGroup group $"but this may cause a GC. Set cache size at init time via {nameof(ComponentSystem.InitEntityQueryCache)}() to a large enough number to ensure no allocations are required at run time."); Array.Resize(ref m_CacheHashes, newSize); - Array.Resize(ref m_CacheComponentGroups, newSize); + Array.Resize(ref m_CachedEntityQueries, newSize); #if ENABLE_UNITY_COLLECTIONS_CHECKS Array.Resize(ref m_CacheCheckQueryBuilders, newSize); @@ -74,7 +83,7 @@ public unsafe int CreateCachedQuery(uint hash, ComponentGroup group break; } - if (m_CacheComponentGroups[index] == null) + if (m_CachedEntityQueries[index] == null) break; #if ENABLE_UNITY_COLLECTIONS_CHECKS @@ -88,7 +97,7 @@ public unsafe int CreateCachedQuery(uint hash, ComponentGroup group // store in cache m_CacheHashes[index] = hash; - m_CacheComponentGroups[index] = group; + m_CachedEntityQueries[index] = query; #if ENABLE_UNITY_COLLECTIONS_CHECKS m_CacheCheckQueryBuilders[index] = builder; @@ -101,8 +110,8 @@ public unsafe int CreateCachedQuery(uint hash, ComponentGroup group return index; } - public ComponentGroup GetCachedQuery(int cacheIndex) - => m_CacheComponentGroups[cacheIndex]; + public EntityQuery GetCachedQuery(int cacheIndex) + => m_CachedEntityQueries[cacheIndex]; #if ENABLE_UNITY_COLLECTIONS_CHECKS public unsafe void ValidateMatchesCache(int foundCacheIndex, ref EntityQueryBuilder builder, int* delegateTypeIndices, int delegateTypeCount) diff --git a/Unity.Entities/EntityRemapUtility.cs b/Unity.Entities/EntityRemapUtility.cs index d6533a8b..0aa9565e 100644 --- a/Unity.Entities/EntityRemapUtility.cs +++ b/Unity.Entities/EntityRemapUtility.cs @@ -82,7 +82,7 @@ public struct BufferEntityPatchInfo public int ElementStride; } -#if UNITY_CSHARP_TINY +#if NET_DOTS // @TODO TINY -- Need to use UnsafeArray to provide a view of the data in sEntityOffsetArray in the static type manager public static EntityOffsetInfo[] CalculateEntityOffsets() { diff --git a/Unity.Entities/ExclusiveEntityTransaction.cs b/Unity.Entities/ExclusiveEntityTransaction.cs index 46a3c13f..808ead66 100644 --- a/Unity.Entities/ExclusiveEntityTransaction.cs +++ b/Unity.Entities/ExclusiveEntityTransaction.cs @@ -39,7 +39,7 @@ internal ExclusiveEntityTransaction(ArchetypeManager archetypes, EntityGroupMana m_SharedComponentDataManager = GCHandle.Alloc(sharedComponentDataManager, GCHandleType.Weak); } - internal void OnDestroyManager() + internal void OnDestroy() { m_ArchetypeManager.Free(); m_EntityGroupManager.Free(); diff --git a/Unity.Entities/IJobChunk.cs b/Unity.Entities/IJobChunk.cs index 79aaaba4..09884a7a 100644 --- a/Unity.Entities/IJobChunk.cs +++ b/Unity.Entities/IJobChunk.cs @@ -11,7 +11,7 @@ namespace Unity.Entities #endif public interface IJobChunk { - // firstEntityIndex refers to the index of the first entity in the current chunk within the ComponentGroup the job was scheduled with + // firstEntityIndex refers to the index of the first entity in the current chunk within the EntityQuery the job was scheduled with // For example, if the job operates on 3 chunks with 20 entities each, then the firstEntityIndices will be [0, 20, 40] respectively void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex); } @@ -40,25 +40,25 @@ internal struct JobChunkData where T : struct public NativeArray PrefilterData; } - public static unsafe JobHandle Schedule(this T jobData, ComponentGroup group, JobHandle dependsOn = default(JobHandle)) + public static unsafe JobHandle Schedule(this T jobData, EntityQuery query, JobHandle dependsOn = default(JobHandle)) where T : struct, IJobChunk { - return ScheduleInternal(ref jobData, group, dependsOn, ScheduleMode.Batched); + return ScheduleInternal(ref jobData, query, dependsOn, ScheduleMode.Batched); } - public static void Run(this T jobData, ComponentGroup group) + public static void Run(this T jobData, EntityQuery query) where T : struct, IJobChunk { - ScheduleInternal(ref jobData, group, default(JobHandle), ScheduleMode.Run); + ScheduleInternal(ref jobData, query, default(JobHandle), ScheduleMode.Run); } #if !UNITY_ZEROPLAYER - internal static unsafe JobHandle ScheduleInternal(ref T jobData, ComponentGroup group, JobHandle dependsOn, ScheduleMode mode) + internal static unsafe JobHandle ScheduleInternal(ref T jobData, EntityQuery query, JobHandle dependsOn, ScheduleMode mode) where T : struct, IJobChunk { - ComponentChunkIterator iterator = group.GetComponentChunkIterator(); + ComponentChunkIterator iterator = query.GetComponentChunkIterator(); - var unfilteredChunkCount = group.CalculateNumberOfChunksWithoutFiltering(); + var unfilteredChunkCount = query.CalculateNumberOfChunksWithoutFiltering(); var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out var prefilterData, @@ -69,7 +69,7 @@ internal static unsafe JobHandle ScheduleInternal(ref T jobData, ComponentGro #if ENABLE_UNITY_COLLECTIONS_CHECKS // All IJobChunk jobs have a EntityManager safety handle to ensure that BeforeStructuralChange throws an error if // jobs without any other safety handles are still running (haven't been synced). - safety = new EntitySafetyHandle{m_Safety = group.SafetyManager.GetEntityManagerSafetyHandle()}, + safety = new EntitySafetyHandle{m_Safety = query.SafetyManager->GetEntityManagerSafetyHandle()}, #endif Data = jobData, PrefilterData = prefilterData, @@ -124,8 +124,7 @@ public unsafe static void Execute(ref JobChunkData jobData, System.IntPtr add internal unsafe static void ExecuteInternal(ref JobChunkData jobData, ref JobRanges ranges, int jobIndex) { - var filteredChunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (filteredChunks + ranges.TotalIterationCount); + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var filteredChunks, out var entityIndices, out var chunkCount); int chunkIndex, end; while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out chunkIndex, out end)) @@ -138,10 +137,10 @@ internal unsafe static void ExecuteInternal(ref JobChunkData jobData, ref Job } } #else - internal static unsafe JobHandle ScheduleInternal(ref T jobData, ComponentGroup group, JobHandle dependsOn, ScheduleMode mode) + internal static unsafe JobHandle ScheduleInternal(ref T jobData, EntityQuery query, JobHandle dependsOn, ScheduleMode mode) where T : struct, IJobChunk { - using (var chunks = group.CreateArchetypeChunkArray(Allocator.Temp)) + using (var chunks = query.CreateArchetypeChunkArray(Allocator.Temp)) { int currentChunk = 0; int currentEntity = 0; @@ -153,8 +152,15 @@ internal static unsafe JobHandle ScheduleInternal(ref T jobData, ComponentGro } } + DoDeallocateOnJobCompletion(jobData); + return new JobHandle(); } + + static internal void DoDeallocateOnJobCompletion(object jobData) + { + throw new NotImplementedException("This function should have been replaced by codegen"); + } #endif } } diff --git a/Unity.Entities/IJobProcessComponentData.cs b/Unity.Entities/IJobForEach.cs similarity index 79% rename from Unity.Entities/IJobProcessComponentData.cs rename to Unity.Entities/IJobForEach.cs index 3e3f6323..fc42f2bd 100644 --- a/Unity.Entities/IJobProcessComponentData.cs +++ b/Unity.Entities/IJobForEach.cs @@ -10,8 +10,6 @@ using Unity.Jobs.LowLevel.Unsafe; using ReadOnlyAttribute = Unity.Collections.ReadOnlyAttribute; -#if !UNITY_ZEROPLAYER - namespace Unity.Entities { //@TODO: What about change or add? @@ -19,7 +17,7 @@ namespace Unity.Entities public class ChangedFilterAttribute : Attribute { } - + [AttributeUsage(AttributeTargets.Struct)] public class RequireComponentTagAttribute : Attribute { @@ -42,11 +40,17 @@ public ExcludeComponentAttribute(params Type[] subtractiveComponents) } } - public static partial class JobProcessComponentDataExtensions + public static partial class JobForEachExtensions { + [EditorBrowsable(EditorBrowsableState.Never)] + public interface IBaseJobForEach + { + } + +#if !UNITY_ZEROPLAYER static ComponentType[] GetComponentTypes(Type jobType) { - var interfaceType = GetIJobProcessComponentDataInterface(jobType); + var interfaceType = GetIJobForEachInterface(jobType); if (interfaceType != null) { int temp; @@ -63,19 +67,19 @@ static ComponentType[] GetComponentTypes(Type jobType, Type interfaceType, out i var genericArgs = interfaceType.GetGenericArguments(); var executeMethodParameters = jobType.GetMethod("Execute").GetParameters(); - + var componentTypes = new List(); var changedFilterTypes = new List(); - + // void Execute(Entity entity, int index, ref T0 data0, ref T1 data1, ref T2 data2); // First two parameters are optional, depending on the interface name used. var methodParameterOffset = genericArgs.Length != executeMethodParameters.Length ? 2 : 0; - + for (var i = 0; i < genericArgs.Length; i++) { var isReadonly = executeMethodParameters[i + methodParameterOffset].GetCustomAttribute(typeof(ReadOnlyAttribute)) != null; - + var type = new ComponentType(genericArgs[i], isReadonly ? ComponentType.AccessMode.ReadOnly : ComponentType.AccessMode.ReadWrite); componentTypes.Add(type); @@ -99,16 +103,16 @@ static ComponentType[] GetComponentTypes(Type jobType, Type interfaceType, out i changedFilter = changedFilterTypes.ToArray(); return componentTypes.ToArray(); } - + static int CalculateEntityCount(ComponentSystemBase system, Type jobType) { - var componentGroup = GetComponentGroupForIJobProcessComponentData(system, jobType); + var query = GetEntityQueryForIJobForEach(system, jobType); - int entityCount = componentGroup.CalculateLength(); + int entityCount = query.CalculateLength(); return entityCount; } - + static IntPtr GetJobReflection(Type jobType, Type wrapperJobType, Type interfaceType, bool isIJobParallelFor) { @@ -127,34 +131,34 @@ static IntPtr GetJobReflection(Type jobType, Type wrapperJobType, Type interface return (IntPtr) reflectionDataRes; } - static Type GetIJobProcessComponentDataInterface(Type jobType) + static Type GetIJobForEachInterface(Type jobType) { foreach (var iType in jobType.GetInterfaces()) - if (iType.Assembly == typeof(IBaseJobProcessComponentData).Assembly && - iType.Name.StartsWith("IJobProcessComponentData")) + if (iType.Assembly == typeof(IBaseJobForEach).Assembly && + iType.Name.StartsWith("IJobForEach")) return iType; return null; } - static void PrepareComponentGroup(ComponentSystemBase system, Type jobType) + static void PrepareEntityQuery(ComponentSystemBase system, Type jobType) { - var iType = GetIJobProcessComponentDataInterface(jobType); - + var iType = GetIJobForEachInterface(jobType); + ComponentType[] filterChanged; int processTypesCount; var types = GetComponentTypes(jobType, iType, out processTypesCount, out filterChanged); - system.GetComponentGroupInternal(types); + system.GetEntityQueryInternal(types); } - static unsafe void Initialize(ComponentSystemBase system, ComponentGroup componentGroup, Type jobType, Type wrapperJobType, - bool isParallelFor, ref JobProcessComponentDataCache cache, out ProcessIterationData iterator) + static unsafe void Initialize(ComponentSystemBase system, EntityQuery entityQuery, Type jobType, Type wrapperJobType, + bool isParallelFor, ref JobForEachCache cache, out ProcessIterationData iterator) { // Get the job reflection data and cache it if we don't already have it cached. if (isParallelFor && cache.JobReflectionDataParallelFor == IntPtr.Zero || !isParallelFor && cache.JobReflectionData == IntPtr.Zero) { - var iType = GetIJobProcessComponentDataInterface(jobType); + var iType = GetIJobForEachInterface(jobType); if (cache.Types == null) cache.Types = GetComponentTypes(jobType, iType, out cache.ProcessTypesCount, out cache.FilterChanged); @@ -167,43 +171,43 @@ static unsafe void Initialize(ComponentSystemBase system, ComponentGroup compone cache.JobReflectionData = res; } - // Update cached ComponentGroup and ComponentSystem data. + // Update cached EntityQuery and ComponentSystem data. if (system != null) { if (cache.ComponentSystem != system) { - cache.ComponentGroup = system.GetComponentGroupInternal(cache.Types); + cache.EntityQuery = system.GetEntityQueryInternal(cache.Types); - // If the cached filter has changed, update the newly cached ComponentGroup with those changes. + // If the cached filter has changed, update the newly cached EntityQuery with those changes. if (cache.FilterChanged.Length != 0) - cache.ComponentGroup.SetFilterChanged(cache.FilterChanged); + cache.EntityQuery.SetFilterChanged(cache.FilterChanged); - // Otherwise, just reset our newly cached ComponentGroup's filter. + // Otherwise, just reset our newly cached EntityQuery's filter. else - cache.ComponentGroup.ResetFilter(); + cache.EntityQuery.ResetFilter(); cache.ComponentSystem = system; } } - else if (componentGroup != null) + else if (entityQuery != null) { - if (cache.ComponentGroup != componentGroup) + if (cache.EntityQuery != entityQuery) { - // Cache the new ComponentGroup and cache that our system is null. - cache.ComponentGroup = componentGroup; + // Cache the new EntityQuery and cache that our system is null. + cache.EntityQuery = entityQuery; cache.ComponentSystem = null; } } - var group = cache.ComponentGroup; - + var query = cache.EntityQuery; + iterator.IsReadOnly0 = iterator.IsReadOnly1 = iterator.IsReadOnly2 = iterator.IsReadOnly3 = iterator.IsReadOnly4 = iterator.IsReadOnly5= 0; fixed (int* isReadOnly = &iterator.IsReadOnly0) { for (var i = 0; i != cache.ProcessTypesCount; i++) isReadOnly[i] = cache.Types[i].AccessModeType == ComponentType.AccessMode.ReadOnly ? 1 : 0; } - + iterator.TypeIndex0 = iterator.TypeIndex1 = iterator.TypeIndex2 = iterator.TypeIndex3 = iterator.TypeIndex4 = iterator.TypeIndex5 = -1; fixed (int* typeIndices = &iterator.TypeIndex0) { @@ -212,14 +216,14 @@ static unsafe void Initialize(ComponentSystemBase system, ComponentGroup compone } iterator.m_IsParallelFor = isParallelFor; - iterator.m_Length = group.CalculateNumberOfChunksWithoutFiltering(); + iterator.m_Length = query.CalculateNumberOfChunksWithoutFiltering(); - iterator.GlobalSystemVersion = group.GetComponentChunkIterator().m_GlobalSystemVersion; + iterator.GlobalSystemVersion = query.GetComponentChunkIterator().m_GlobalSystemVersion; #if ENABLE_UNITY_COLLECTIONS_CHECKS iterator.m_MaxIndex = iterator.m_Length - 1; iterator.m_MinIndex = 0; - + iterator.m_Safety0 = iterator.m_Safety1 = iterator.m_Safety2 = iterator.m_Safety3 = iterator.m_Safety4 = iterator.m_Safety5 = default(AtomicSafetyHandle); @@ -230,7 +234,7 @@ static unsafe void Initialize(ComponentSystemBase system, ComponentGroup compone if (cache.Types[i].AccessModeType == ComponentType.AccessMode.ReadOnly) { safety[iterator.m_SafetyReadOnlyCount] = - group.GetSafetyHandle(group.GetIndexInComponentGroup(cache.Types[i].TypeIndex)); + query.GetSafetyHandle(query.GetIndexInEntityQuery(cache.Types[i].TypeIndex)); iterator.m_SafetyReadOnlyCount++; } } @@ -242,7 +246,7 @@ static unsafe void Initialize(ComponentSystemBase system, ComponentGroup compone if (cache.Types[i].AccessModeType == ComponentType.AccessMode.ReadWrite) { safety[iterator.m_SafetyReadOnlyCount + iterator.m_SafetyReadWriteCount] = - group.GetSafetyHandle(group.GetIndexInComponentGroup(cache.Types[i].TypeIndex)); + query.GetSafetyHandle(query.GetIndexInEntityQuery(cache.Types[i].TypeIndex)); iterator.m_SafetyReadWriteCount++; } } @@ -250,13 +254,8 @@ static unsafe void Initialize(ComponentSystemBase system, ComponentGroup compone Assert.AreEqual(cache.ProcessTypesCount, iterator.m_SafetyReadWriteCount + iterator.m_SafetyReadOnlyCount); #endif } - - [EditorBrowsable(EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData - { - } - internal struct JobProcessComponentDataCache + internal struct JobForEachCache { public IntPtr JobReflectionData; public IntPtr JobReflectionDataParallelFor; @@ -265,7 +264,7 @@ internal struct JobProcessComponentDataCache public int ProcessTypesCount; - public ComponentGroup ComponentGroup; + public EntityQuery EntityQuery; public ComponentSystemBase ComponentSystem; } @@ -275,7 +274,7 @@ internal struct JobProcessComponentDataCache internal struct ProcessIterationData { public uint GlobalSystemVersion; - + public int TypeIndex0; public int TypeIndex1; public int TypeIndex2; @@ -289,7 +288,7 @@ internal struct ProcessIterationData public int IsReadOnly3; public int IsReadOnly4; public int IsReadOnly5; - + public bool m_IsParallelFor; public int m_Length; @@ -311,35 +310,36 @@ internal struct ProcessIterationData #pragma warning restore #endif } - public static ComponentGroup GetComponentGroupForIJobProcessComponentData(this ComponentSystemBase system, + + public static EntityQuery GetEntityQueryForIJobForEach(this ComponentSystemBase system, Type jobType) { var types = GetComponentTypes(jobType); if (types != null) - return system.GetComponentGroupInternal(types); + return system.GetEntityQueryInternal(types); else return null; } - + //NOTE: It would be much better if C# could resolve the branch with generic resolving, // but apparently the interface constraint is not enough.. - public static void PrepareComponentGroup(this T jobData, ComponentSystemBase system) - where T : struct, IBaseJobProcessComponentData + public static void PrepareEntityQuery(this T jobData, ComponentSystemBase system) + where T : struct, IBaseJobForEach { - PrepareComponentGroup(system, typeof(T)); + PrepareEntityQuery(system, typeof(T)); } - + public static int CalculateEntityCount(this T jobData, ComponentSystemBase system) - where T : struct, IBaseJobProcessComponentData + where T : struct, IBaseJobForEach { return CalculateEntityCount(system, typeof(T)); } - static unsafe JobHandle Schedule(void* fullData, NativeArray prefilterData, int unfilteredLength, int innerloopBatchCount, - bool isParallelFor, bool isFiltered, ref JobProcessComponentDataCache cache, void* deferredCountData, JobHandle dependsOn, ScheduleMode mode) + static unsafe JobHandle Schedule(void* fullData, NativeArray prefilterData, int unfilteredLength, int innerloopBatchCount, + bool isParallelFor, bool isFiltered, ref JobForEachCache cache, void* deferredCountData, JobHandle dependsOn, ScheduleMode mode) { -#if ENABLE_UNITY_COLLECTIONS_CHECKS +#if ENABLE_UNITY_COLLECTIONS_CHECKS try { #endif @@ -356,15 +356,15 @@ static unsafe JobHandle Schedule(void* fullData, NativeArray prefilterData var scheduleParams = new JobsUtility.JobScheduleParameters(fullData, cache.JobReflectionData, dependsOn, mode); return JobsUtility.Schedule(ref scheduleParams); } -#if ENABLE_UNITY_COLLECTIONS_CHECKS +#if ENABLE_UNITY_COLLECTIONS_CHECKS } catch (InvalidOperationException e) { prefilterData.Dispose(); throw e; } -#endif +#endif } +#endif } } -#endif \ No newline at end of file diff --git a/Unity.Entities/IJobProcessComponentData.cs.meta b/Unity.Entities/IJobForEach.cs.meta similarity index 100% rename from Unity.Entities/IJobProcessComponentData.cs.meta rename to Unity.Entities/IJobForEach.cs.meta diff --git a/Unity.Entities/IJobForEach.gen.cs b/Unity.Entities/IJobForEach.gen.cs new file mode 100644 index 00000000..a3392406 --- /dev/null +++ b/Unity.Entities/IJobForEach.gen.cs @@ -0,0 +1,1649 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +// Generated by T4 (TextTransform.exe) from the file IJobForEach.tt +// + +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Jobs; +using Unity.Jobs.LowLevel.Unsafe; +using System.Runtime.InteropServices; +using UnityEngine.Scripting; +using System; + +namespace Unity.Entities +{ + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_D<,>))] +#endif + public interface IJobForEach : JobForEachExtensions.IBaseJobForEach_D + where U0 : struct, IComponentData + { + void Execute(ref U0 c0); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_ED<,>))] +#endif + public interface IJobForEachWithEntity : JobForEachExtensions.IBaseJobForEach_ED + where U0 : struct, IComponentData + { + void Execute(Entity entity, int index, ref U0 c0); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_DD<,,>))] +#endif + public interface IJobForEach : JobForEachExtensions.IBaseJobForEach_DD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + { + void Execute(ref U0 c0, ref U1 c1); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_EDD<,,>))] +#endif + public interface IJobForEachWithEntity : JobForEachExtensions.IBaseJobForEach_EDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + { + void Execute(Entity entity, int index, ref U0 c0, ref U1 c1); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_DDD<,,,>))] +#endif + public interface IJobForEach : JobForEachExtensions.IBaseJobForEach_DDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + { + void Execute(ref U0 c0, ref U1 c1, ref U2 c2); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_EDDD<,,,>))] +#endif + public interface IJobForEachWithEntity : JobForEachExtensions.IBaseJobForEach_EDDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + { + void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_DDDD<,,,,>))] +#endif + public interface IJobForEach : JobForEachExtensions.IBaseJobForEach_DDDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + { + void Execute(ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_EDDDD<,,,,>))] +#endif + public interface IJobForEachWithEntity : JobForEachExtensions.IBaseJobForEach_EDDDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + { + void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_DDDDD<,,,,,>))] +#endif + public interface IJobForEach : JobForEachExtensions.IBaseJobForEach_DDDDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + { + void Execute(ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_EDDDDD<,,,,,>))] +#endif + public interface IJobForEachWithEntity : JobForEachExtensions.IBaseJobForEach_EDDDDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + { + void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_DDDDDD<,,,,,,>))] +#endif + public interface IJobForEach : JobForEachExtensions.IBaseJobForEach_DDDDDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + where U5 : struct, IComponentData + { + void Execute(ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4, ref U5 c5); + } + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_EDDDDDD<,,,,,,>))] +#endif + public interface IJobForEachWithEntity : JobForEachExtensions.IBaseJobForEach_EDDDDDD + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + where U5 : struct, IComponentData + { + void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4, ref U5 c5); + } + + public static partial class JobForEachExtensions + { +#if !UNITY_ZEROPLAYER + public static JobHandle Schedule(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); + if (typeof(IBaseJobForEach_D).IsAssignableFrom(typeT)) + return ScheduleInternal_D(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_ED).IsAssignableFrom(typeT)) + return ScheduleInternal_ED(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DD).IsAssignableFrom(typeT)) + return ScheduleInternal_DD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); + throw new System.ArgumentException("Not supported"); + } +#endif +#if !UNITY_ZEROPLAYER + public static JobHandle ScheduleSingle(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); + if (typeof(IBaseJobForEach_D).IsAssignableFrom(typeT)) + return ScheduleInternal_D(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_ED).IsAssignableFrom(typeT)) + return ScheduleInternal_ED(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DD).IsAssignableFrom(typeT)) + return ScheduleInternal_DD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); + throw new System.ArgumentException("Not supported"); + } +#endif +#if !UNITY_ZEROPLAYER + public static JobHandle Run(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); + if (typeof(IBaseJobForEach_D).IsAssignableFrom(typeT)) + return ScheduleInternal_D(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_ED).IsAssignableFrom(typeT)) + return ScheduleInternal_ED(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DD).IsAssignableFrom(typeT)) + return ScheduleInternal_DD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); + throw new System.ArgumentException("Not supported"); + } +#endif + +#if !UNITY_ZEROPLAYER + public static JobHandle Schedule(this T jobData, EntityQuery query, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); + if (typeof(IBaseJobForEach_D).IsAssignableFrom(typeT)) + return ScheduleInternal_D(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_ED).IsAssignableFrom(typeT)) + return ScheduleInternal_ED(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DD).IsAssignableFrom(typeT)) + return ScheduleInternal_DD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDDD(ref jobData, null, query, 1, dependsOn, ScheduleMode.Batched); + throw new System.ArgumentException("Not supported"); + } +#endif +#if !UNITY_ZEROPLAYER + public static JobHandle ScheduleSingle(this T jobData, EntityQuery query, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); + if (typeof(IBaseJobForEach_D).IsAssignableFrom(typeT)) + return ScheduleInternal_D(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_ED).IsAssignableFrom(typeT)) + return ScheduleInternal_ED(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DD).IsAssignableFrom(typeT)) + return ScheduleInternal_DD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_DDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + if (typeof(IBaseJobForEach_EDDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Batched); + throw new System.ArgumentException("Not supported"); + } +#endif +#if !UNITY_ZEROPLAYER + public static JobHandle Run(this T jobData, EntityQuery query, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); + if (typeof(IBaseJobForEach_D).IsAssignableFrom(typeT)) + return ScheduleInternal_D(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_ED).IsAssignableFrom(typeT)) + return ScheduleInternal_ED(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DD).IsAssignableFrom(typeT)) + return ScheduleInternal_DD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_DDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_DDDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + if (typeof(IBaseJobForEach_EDDDDDD).IsAssignableFrom(typeT)) + return ScheduleInternal_EDDDDDD(ref jobData, null, query, -1, dependsOn, ScheduleMode.Run); + throw new System.ArgumentException("Not supported"); + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_D(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_D fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_D<,>), isParallelFor, ref JobStruct_ProcessInfer_D.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_D.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_D.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_D : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_D where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_D + where T : struct, IJobForEach + where U0 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_D), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_D data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_D jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_D jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_ED(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_ED fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_ED<,>), isParallelFor, ref JobStruct_ProcessInfer_ED.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_ED.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_ED.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_ED : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_ED where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_ED + where T : struct, IJobForEachWithEntity + where U0 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_ED), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_ED data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_ED jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_ED jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_DD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_DD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_DD<,,>), isParallelFor, ref JobStruct_ProcessInfer_DD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_DD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_DD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_DD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_DD + where T : struct, IJobForEach + where U0 : struct, IComponentData + where U1 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_DD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_DD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_DD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_EDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_EDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_EDD<,,>), isParallelFor, ref JobStruct_ProcessInfer_EDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_EDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_EDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_EDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_EDD + where T : struct, IJobForEachWithEntity + where U0 : struct, IComponentData + where U1 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_EDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_EDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_EDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_DDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_DDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_DDD<,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_DDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_DDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_DDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_DDD + where T : struct, IJobForEach + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_DDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_DDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_DDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_EDDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_EDDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_EDDD<,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_EDDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_EDDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_EDDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_EDDD + where T : struct, IJobForEachWithEntity + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_EDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_EDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_EDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_DDDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_DDDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_DDDD<,,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_DDDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_DDDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_DDDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_DDDD + where T : struct, IJobForEach + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_DDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_DDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_DDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + var typeLookupCache3 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); + var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_EDDDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_EDDDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_EDDDD<,,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_EDDDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_EDDDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_EDDDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_EDDDD + where T : struct, IJobForEachWithEntity + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_EDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_EDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_EDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + var typeLookupCache3 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); + var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_DDDDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_DDDDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_DDDDD<,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDDDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_DDDDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDDDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_DDDDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_DDDDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_DDDDD + where T : struct, IJobForEach + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_DDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_DDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_DDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + var typeLookupCache3 = 0; + var typeLookupCache4 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); + var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); + var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_EDDDDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_EDDDDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_EDDDDD<,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDDDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_EDDDDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDDDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_EDDDDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_EDDDDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_EDDDDD + where T : struct, IJobForEachWithEntity + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_EDDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_EDDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_EDDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + var typeLookupCache3 = 0; + var typeLookupCache4 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); + var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); + var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_DDDDDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_DDDDDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_DDDDDD<,,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDDDDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_DDDDDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDDDDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_DDDDDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_DDDDDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_DDDDDD + where T : struct, IJobForEach + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + where U5 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_DDDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_DDDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_DDDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + var typeLookupCache3 = 0; + var typeLookupCache4 = 0; + var typeLookupCache5 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); + var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); + var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex5, ref typeLookupCache5); + var ptr5 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly5 == 0, typeLookupCache5, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr5, i)); + } + } + } + } +#endif + +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_EDDDDDD(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_EDDDDDD fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_EDDDDDD<,,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDDDDD.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_EDDDDDD.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDDDDD.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_EDDDDDD : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_EDDDDDD where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_EDDDDDD + where T : struct, IJobForEachWithEntity + where U0 : struct, IComponentData + where U1 : struct, IComponentData + where U2 : struct, IComponentData + where U3 : struct, IComponentData + where U4 : struct, IComponentData + where U5 : struct, IComponentData + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_EDDDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_EDDDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_EDDDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { + var typeLookupCache0 = 0; + var typeLookupCache1 = 0; + var typeLookupCache2 = 0; + var typeLookupCache3 = 0; + var typeLookupCache4 = 0; + var typeLookupCache5 = 0; + + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif + var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); + var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); + var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); + var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); + var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); + var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); + ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex5, ref typeLookupCache5); + var ptr5 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly5 == 0, typeLookupCache5, jobData.Iterator.GlobalSystemVersion)); + + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr5, i)); + } + } + } + } +#endif + + } +} + diff --git a/Unity.Entities/IJobForEach.gen.cs.meta b/Unity.Entities/IJobForEach.gen.cs.meta new file mode 100644 index 00000000..ce849e68 --- /dev/null +++ b/Unity.Entities/IJobForEach.gen.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6e655e914344af458054023f1d180eb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/IJobForEach.tt b/Unity.Entities/IJobForEach.tt new file mode 100644 index 00000000..5c92fa7f --- /dev/null +++ b/Unity.Entities/IJobForEach.tt @@ -0,0 +1,337 @@ +<#/*THIS IS A T4 FILE - see HACKING.md for what it is and how to run codegen*/#> +<#@ assembly name="System.Collections" #> +<#@ assembly name="System.Core" #> +<#@ assembly name="System.Linq" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ output extension=".gen.cs" #> +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +// Generated by T4 (TextTransform.exe) from the file IJobForEach.tt +// + +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Jobs; +using Unity.Jobs.LowLevel.Unsafe; +using System.Runtime.InteropServices; +using UnityEngine.Scripting; +using System; + +namespace Unity.Entities +{ +<# +var combinations = GenCombinations(); +foreach(var combination in combinations) { + foreach (var withEntity in new[] { false, true }) { + var comboString = GetComboString(withEntity, combination); + var name = withEntity ? "IJobForEachWithEntity" : "IJobForEach"; +#> + +#if !UNITY_ZEROPLAYER + [JobProducerType(typeof(JobForEachExtensions.JobStruct_Process_<#=comboString#><<#=GetUntypedGenericParams(combination)#>>))] +#endif + public interface <#=name#><<#=GenericParams(combination)#>> : JobForEachExtensions.IBaseJobForEach_<#=GetComboString(withEntity, combination)#> +<#=GenericConstraints(combination)#> + { + void Execute(<#=ExecuteParams(withEntity, combination)#>); + } +<# + } +} +#> + + public static partial class JobForEachExtensions + { +<# +string[] funcNames = new string[]{"Schedule", "ScheduleSingle", "Run"}; +int [] forEachVals = new int[]{1, -1, -1}; +string[] scheduleMode = new string[]{"ScheduleMode.Batched", "ScheduleMode.Batched", "ScheduleMode.Run"}; +for(int i=0; i +#if !UNITY_ZEROPLAYER + public static JobHandle <#=funcNames[i]#>(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); +<# + foreach(var combination in combinations) { + var comboStringD = GetComboString(false, combination); + var comboStringE = GetComboString(true, combination); +#> + if (typeof(IBaseJobForEach_<#=comboStringD#>).IsAssignableFrom(typeT)) + return ScheduleInternal_<#=comboStringD#>(ref jobData, system, null, <#=forEachVals[i]#>, dependsOn, <#=scheduleMode[i]#>); + if (typeof(IBaseJobForEach_<#=comboStringE#>).IsAssignableFrom(typeT)) + return ScheduleInternal_<#=comboStringE#>(ref jobData, system, null, <#=forEachVals[i]#>, dependsOn, <#=scheduleMode[i]#>); +<# + } +#> + throw new System.ArgumentException("Not supported"); + } +#endif +<# +} +#> + +<# +string[] groupFuncNames = new string[]{"Schedule", "ScheduleSingle", "Run"}; +for(int i=0; i +#if !UNITY_ZEROPLAYER + public static JobHandle <#=groupFuncNames[i]#>(this T jobData, EntityQuery query, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + var typeT = typeof(T); +<# + foreach(var combination in combinations) { + var comboStringD = GetComboString(false, combination); + var comboStringE = GetComboString(true, combination); +#> + if (typeof(IBaseJobForEach_<#=comboStringD#>).IsAssignableFrom(typeT)) + return ScheduleInternal_<#=comboStringD#>(ref jobData, null, query, <#=forEachVals[i]#>, dependsOn, <#=scheduleMode[i]#>); + if (typeof(IBaseJobForEach_<#=comboStringE#>).IsAssignableFrom(typeT)) + return ScheduleInternal_<#=comboStringE#>(ref jobData, null, query, <#=forEachVals[i]#>, dependsOn, <#=scheduleMode[i]#>); +<# + } +#> + throw new System.ArgumentException("Not supported"); + } +#endif +<# +} +#> + +<# +foreach(var combination in combinations) { + foreach (var withEntity in new[] { false, true }) { + var comboString = GetComboString(withEntity, combination); + var untypedGenericParams = new StringBuilder(); + var genericParams = new StringBuilder(); + var genericConstraints = new StringBuilder(); + + var executeParams = new StringBuilder(); + var executeCallParams = new StringBuilder(); + var ptrs = new StringBuilder(); + var typeLookupCache = new StringBuilder(); + + var interfaceName = withEntity ? "IJobForEachWithEntity" : "IJobForEach"; + if (withEntity) + { + executeCallParams.Append("ptrE[i], i + beginIndex, "); + executeParams.Append("Entity entity, int index, "); + ptrs.AppendLine + ( +$" var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion));" + ); + } + for (int i = 0; i != combination.Length; i++) + { + ptrs.AppendLine + ( + +$@" ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex{i}, ref typeLookupCache{i}); + var ptr{i} = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly{i} == 0, typeLookupCache{i}, jobData.Iterator.GlobalSystemVersion));" + ); + + typeLookupCache.AppendLine + ( + +$@" var typeLookupCache{i} = 0; " + ); + + genericConstraints.Append($" where U{i} : struct, IComponentData"); + if (i != combination.Length - 1) + genericConstraints.AppendLine(); + untypedGenericParams.Append(","); + + genericParams.Append($"U{i}"); + if (i != combination.Length - 1) + genericParams.Append(", "); + + executeCallParams.Append($"ref UnsafeUtilityEx.ArrayElementAsRef(ptr{i}, i)"); + if (i != combination.Length - 1) + executeCallParams.Append(", "); + + executeParams.Append($"ref U{i} c{i}"); + if (i != combination.Length - 1) + executeParams.Append(", "); + } +#> +#if !UNITY_ZEROPLAYER + internal static unsafe JobHandle ScheduleInternal_<#=comboString#>(ref T jobData, ComponentSystemBase system, EntityQuery query, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) + where T : struct + { + JobStruct_ProcessInfer_<#=comboString#> fullData; + fullData.Data = jobData; + + var isParallelFor = innerloopBatchCount != -1; + Initialize(system, query, typeof(T), typeof(JobStruct_Process_<#=comboString#><<#=untypedGenericParams#>>), isParallelFor, ref JobStruct_ProcessInfer_<#=comboString#>.Cache, out fullData.Iterator); + + var unfilteredChunkCount = fullData.Iterator.m_Length; + var iterator = JobStruct_ProcessInfer_<#=comboString#>.Cache.EntityQuery.GetComponentChunkIterator(); + + var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); + + return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_<#=comboString#>.Cache, deferredCountData, prefilterHandle, mode); + } +#endif + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public interface IBaseJobForEach_<#=comboString#> : IBaseJobForEach {} + +#if !UNITY_ZEROPLAYER + [StructLayout(LayoutKind.Sequential)] + private struct JobStruct_ProcessInfer_<#=comboString#> where T : struct + { + public static JobForEachCache Cache; + + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct JobStruct_Process_<#=comboString#>> + where T : struct, <#=interfaceName#><<#=genericParams#>> +<#=genericConstraints#> + { + public ProcessIterationData Iterator; + public T Data; + + [DeallocateOnJobCompletion] + [NativeDisableContainerSafetyRestriction] + public NativeArray PrefilterData; + + [Preserve] + public static IntPtr Initialize(JobType jobType) + { + return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_<#=comboString#>>), typeof(T), jobType, (ExecuteJobFunction) Execute); + } + + delegate void ExecuteJobFunction(ref JobStruct_Process_<#=comboString#>> data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); + + public static unsafe void Execute(ref JobStruct_Process_<#=comboString#>> jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) + { + ComponentChunkIterator.UnpackPrefilterData(jobData.PrefilterData, out var chunks, out var entityIndices, out var chunkCount); + + if (jobData.Iterator.m_IsParallelFor) + { + int begin, end; + while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) + ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); + } + else + { + ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); + } + } + + static unsafe void ExecuteChunk(ref JobStruct_Process_<#=comboString#>> jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) + { +<#=typeLookupCache#> + for (var blockIndex = begin; blockIndex != end; ++blockIndex) + { + var chunk = chunks[blockIndex]; + int beginIndex = entityIndices[blockIndex]; + var count = chunk.Count; +#if ENABLE_UNITY_COLLECTIONS_CHECKS + JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); +#endif +<#=ptrs#> + + for (var i = 0; i != count; i++) + { + jobData.Data.Execute(<#=executeCallParams#>); + } + } + } + } +#endif + +<# + } +} +#> + } +} + +<#+ +enum Combination +{ + D +} + +List GenCombinations() +{ + var combinations = new List(); + for (int count = 1; count <= 6; count++) + { + var array = new Combination[count]; + for (var c = 0; c != array.Length; c++) + array[c] = Combination.D; + + combinations.Add(array); + } + return combinations; +} + +string GetComboString(bool withEntity, Combination[] combination) +{ + var baseType = new StringBuilder(); + + if (withEntity) + baseType.Append("E"); + foreach (var c in combination) + baseType.Append(Enum.GetName(typeof(Combination), c)); + return baseType.ToString(); +} + +string GetUntypedGenericParams(Combination[] combination) { + return new String(',', combination.Length); +} + +string GenericParams(Combination[] combination) { + StringBuilder genericParams = new StringBuilder(); + for(int i=0; i \ No newline at end of file diff --git a/Unity.Entities/IJobForEach.tt.meta b/Unity.Entities/IJobForEach.tt.meta new file mode 100644 index 00000000..35e42f6d --- /dev/null +++ b/Unity.Entities/IJobForEach.tt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: dd1f79449e827b643bc786b747ca5fa3 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/IJobProcessComponentData.generated.cs b/Unity.Entities/IJobProcessComponentData.generated.cs deleted file mode 100644 index ff16e4d1..00000000 --- a/Unity.Entities/IJobProcessComponentData.generated.cs +++ /dev/null @@ -1,1598 +0,0 @@ -// Generated by IJobProcessComponentDataGenerator.cs -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ -#if !UNITY_ZEROPLAYER - -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; -using Unity.Jobs; -using Unity.Jobs.LowLevel.Unsafe; -using System.Runtime.InteropServices; -using UnityEngine.Scripting; -using System; - - -namespace Unity.Entities -{ - - - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_D<,>))] - public interface IJobProcessComponentData : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_D - where U0 : struct, IComponentData - { - void Execute(ref U0 c0); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_ED<,>))] - public interface IJobProcessComponentDataWithEntity : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_ED - where U0 : struct, IComponentData - { - void Execute(Entity entity, int index, ref U0 c0); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_DD<,,>))] - public interface IJobProcessComponentData : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_DD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - { - void Execute(ref U0 c0, ref U1 c1); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_EDD<,,>))] - public interface IJobProcessComponentDataWithEntity : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_EDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - { - void Execute(Entity entity, int index, ref U0 c0, ref U1 c1); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_DDD<,,,>))] - public interface IJobProcessComponentData : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_DDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - { - void Execute(ref U0 c0, ref U1 c1, ref U2 c2); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_EDDD<,,,>))] - public interface IJobProcessComponentDataWithEntity : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_EDDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - { - void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_DDDD<,,,,>))] - public interface IJobProcessComponentData : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_DDDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - { - void Execute(ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_EDDDD<,,,,>))] - public interface IJobProcessComponentDataWithEntity : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_EDDDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - { - void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_DDDDD<,,,,,>))] - public interface IJobProcessComponentData : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_DDDDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - { - void Execute(ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_EDDDDD<,,,,,>))] - public interface IJobProcessComponentDataWithEntity : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_EDDDDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - { - void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_DDDDDD<,,,,,,>))] - public interface IJobProcessComponentData : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_DDDDDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - where U5 : struct, IComponentData - { - void Execute(ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4, ref U5 c5); - } - - [JobProducerType(typeof(JobProcessComponentDataExtensions.JobStruct_Process_EDDDDDD<,,,,,,>))] - public interface IJobProcessComponentDataWithEntity : JobProcessComponentDataExtensions.IBaseJobProcessComponentData_EDDDDDD - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - where U5 : struct, IComponentData - { - void Execute(Entity entity, int index, ref U0 c0, ref U1 c1, ref U2 c2, ref U3 c3, ref U4 c4, ref U5 c5); - } - - public static partial class JobProcessComponentDataExtensions - { - - public static JobHandle Schedule(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - { - var typeT = typeof(T); - if (typeof(IBaseJobProcessComponentData_D).IsAssignableFrom(typeT)) - return ScheduleInternal_D(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_ED).IsAssignableFrom(typeT)) - return ScheduleInternal_ED(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DD).IsAssignableFrom(typeT)) - return ScheduleInternal_DD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDDD(ref jobData, system, null, 1, dependsOn, ScheduleMode.Batched); - throw new System.ArgumentException("Not supported"); - } - - public static JobHandle ScheduleSingle(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - { - var typeT = typeof(T); - if (typeof(IBaseJobProcessComponentData_D).IsAssignableFrom(typeT)) - return ScheduleInternal_D(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_ED).IsAssignableFrom(typeT)) - return ScheduleInternal_ED(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DD).IsAssignableFrom(typeT)) - return ScheduleInternal_DD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Batched); - throw new System.ArgumentException("Not supported"); - } - - public static JobHandle Run(this T jobData, ComponentSystemBase system, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - { - var typeT = typeof(T); - if (typeof(IBaseJobProcessComponentData_D).IsAssignableFrom(typeT)) - return ScheduleInternal_D(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_ED).IsAssignableFrom(typeT)) - return ScheduleInternal_ED(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DD).IsAssignableFrom(typeT)) - return ScheduleInternal_DD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDDD(ref jobData, system, null, -1, dependsOn, ScheduleMode.Run); - throw new System.ArgumentException("Not supported"); - } - - public static JobHandle ScheduleGroup(this T jobData, ComponentGroup componentGroup, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - { - var typeT = typeof(T); - if (typeof(IBaseJobProcessComponentData_D).IsAssignableFrom(typeT)) - return ScheduleInternal_D(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_ED).IsAssignableFrom(typeT)) - return ScheduleInternal_ED(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DD).IsAssignableFrom(typeT)) - return ScheduleInternal_DD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDDD(ref jobData, null, componentGroup, 1, dependsOn, ScheduleMode.Batched); - throw new System.ArgumentException("Not supported"); - } - - public static JobHandle ScheduleGroupSingle(this T jobData, ComponentGroup componentGroup, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - { - var typeT = typeof(T); - if (typeof(IBaseJobProcessComponentData_D).IsAssignableFrom(typeT)) - return ScheduleInternal_D(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_ED).IsAssignableFrom(typeT)) - return ScheduleInternal_ED(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DD).IsAssignableFrom(typeT)) - return ScheduleInternal_DD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_DDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - if (typeof(IBaseJobProcessComponentData_EDDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Batched); - throw new System.ArgumentException("Not supported"); - } - - public static JobHandle RunGroup(this T jobData, ComponentGroup componentGroup, JobHandle dependsOn = default(JobHandle)) - where T : struct, IBaseJobProcessComponentData - { - var typeT = typeof(T); - if (typeof(IBaseJobProcessComponentData_D).IsAssignableFrom(typeT)) - return ScheduleInternal_D(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_ED).IsAssignableFrom(typeT)) - return ScheduleInternal_ED(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DD).IsAssignableFrom(typeT)) - return ScheduleInternal_DD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_DDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_DDDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - if (typeof(IBaseJobProcessComponentData_EDDDDDD).IsAssignableFrom(typeT)) - return ScheduleInternal_EDDDDDD(ref jobData, null, componentGroup, -1, dependsOn, ScheduleMode.Run); - throw new System.ArgumentException("Not supported"); - } - - internal static unsafe JobHandle ScheduleInternal_D(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_D fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_D<,>), isParallelFor, ref JobStruct_ProcessInfer_D.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_D.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_D.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_D : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_D where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_D - where T : struct, IJobProcessComponentData - where U0 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_D), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_D data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_D jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_D jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_ED(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_ED fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_ED<,>), isParallelFor, ref JobStruct_ProcessInfer_ED.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_ED.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_ED.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_ED : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_ED where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_ED - where T : struct, IJobProcessComponentDataWithEntity - where U0 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_ED), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_ED data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_ED jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_ED jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_DD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_DD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_DD<,,>), isParallelFor, ref JobStruct_ProcessInfer_DD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_DD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_DD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_DD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_DD - where T : struct, IJobProcessComponentData - where U0 : struct, IComponentData - where U1 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_DD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_DD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_DD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_EDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_EDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_EDD<,,>), isParallelFor, ref JobStruct_ProcessInfer_EDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_EDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_EDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_EDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_EDD - where T : struct, IJobProcessComponentDataWithEntity - where U0 : struct, IComponentData - where U1 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_EDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_EDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_EDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_DDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_DDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_DDD<,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_DDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_DDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_DDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_DDD - where T : struct, IJobProcessComponentData - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_DDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_DDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_DDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_EDDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_EDDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_EDDD<,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_EDDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_EDDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_EDDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_EDDD - where T : struct, IJobProcessComponentDataWithEntity - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_EDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_EDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_EDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_DDDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_DDDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_DDDD<,,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_DDDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_DDDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_DDDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_DDDD - where T : struct, IJobProcessComponentData - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_DDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_DDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_DDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - var typeLookupCache3 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); - var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_EDDDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_EDDDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_EDDDD<,,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_EDDDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_EDDDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_EDDDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_EDDDD - where T : struct, IJobProcessComponentDataWithEntity - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_EDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_EDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_EDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - var typeLookupCache3 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); - var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_DDDDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_DDDDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_DDDDD<,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDDDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_DDDDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDDDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_DDDDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_DDDDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_DDDDD - where T : struct, IJobProcessComponentData - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_DDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_DDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_DDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - var typeLookupCache3 = 0; - var typeLookupCache4 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); - var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); - var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_EDDDDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_EDDDDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_EDDDDD<,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDDDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_EDDDDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDDDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_EDDDDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_EDDDDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_EDDDDD - where T : struct, IJobProcessComponentDataWithEntity - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_EDDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_EDDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_EDDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - var typeLookupCache3 = 0; - var typeLookupCache4 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); - var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); - var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_DDDDDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_DDDDDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_DDDDDD<,,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_DDDDDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_DDDDDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_DDDDDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_DDDDDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_DDDDDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_DDDDDD - where T : struct, IJobProcessComponentData - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - where U5 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_DDDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_DDDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_DDDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_DDDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - var typeLookupCache3 = 0; - var typeLookupCache4 = 0; - var typeLookupCache5 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); - var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); - var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex5, ref typeLookupCache5); - var ptr5 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly5 == 0, typeLookupCache5, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr5, i)); - } - } - } - } - - internal static unsafe JobHandle ScheduleInternal_EDDDDDD(ref T jobData, ComponentSystemBase system, ComponentGroup componentGroup, int innerloopBatchCount, JobHandle dependsOn, ScheduleMode mode) - where T : struct - { - JobStruct_ProcessInfer_EDDDDDD fullData; - fullData.Data = jobData; - - var isParallelFor = innerloopBatchCount != -1; - Initialize(system, componentGroup, typeof(T), typeof(JobStruct_Process_EDDDDDD<,,,,,,>), isParallelFor, ref JobStruct_ProcessInfer_EDDDDDD.Cache, out fullData.Iterator); - - var unfilteredChunkCount = fullData.Iterator.m_Length; - var iterator = JobStruct_ProcessInfer_EDDDDDD.Cache.ComponentGroup.GetComponentChunkIterator(); - - var prefilterHandle = ComponentChunkIterator.PreparePrefilteredChunkLists(unfilteredChunkCount, iterator.m_MatchingArchetypeList, iterator.m_Filter, dependsOn, mode, out fullData.PrefilterData, out var deferredCountData); - - return Schedule(UnsafeUtility.AddressOf(ref fullData), fullData.PrefilterData, fullData.Iterator.m_Length, innerloopBatchCount, isParallelFor, iterator.RequiresFilter(), ref JobStruct_ProcessInfer_EDDDDDD.Cache, deferredCountData, prefilterHandle, mode); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public interface IBaseJobProcessComponentData_EDDDDDD : IBaseJobProcessComponentData { } - - [StructLayout(LayoutKind.Sequential)] - private struct JobStruct_ProcessInfer_EDDDDDD where T : struct - { - public static JobProcessComponentDataCache Cache; - - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct JobStruct_Process_EDDDDDD - where T : struct, IJobProcessComponentDataWithEntity - where U0 : struct, IComponentData - where U1 : struct, IComponentData - where U2 : struct, IComponentData - where U3 : struct, IComponentData - where U4 : struct, IComponentData - where U5 : struct, IComponentData - { - public ProcessIterationData Iterator; - public T Data; - - [DeallocateOnJobCompletion] - [NativeDisableContainerSafetyRestriction] - public NativeArray PrefilterData; - - [Preserve] - public static IntPtr Initialize(JobType jobType) - { - return JobsUtility.CreateJobReflectionData(typeof(JobStruct_Process_EDDDDDD), typeof(T), jobType, (ExecuteJobFunction) Execute); - } - - delegate void ExecuteJobFunction(ref JobStruct_Process_EDDDDDD data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); - - public static unsafe void Execute(ref JobStruct_Process_EDDDDDD jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) - { - var chunks = (ArchetypeChunk*)NativeArrayUnsafeUtility.GetUnsafePtr(jobData.PrefilterData); - var entityIndices = (int*) (chunks + jobData.Iterator.m_Length); - var chunkCount = *(entityIndices + jobData.Iterator.m_Length); - - if (jobData.Iterator.m_IsParallelFor) - { - int begin, end; - while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) - ExecuteChunk(ref jobData, bufferRangePatchData, begin, end, chunks, entityIndices); - } - else - { - ExecuteChunk(ref jobData, bufferRangePatchData, 0, chunkCount, chunks, entityIndices); - } - } - - static unsafe void ExecuteChunk(ref JobStruct_Process_EDDDDDD jobData, IntPtr bufferRangePatchData, int begin, int end, ArchetypeChunk* chunks, int* entityIndices) - { - var typeLookupCache0 = 0; - var typeLookupCache1 = 0; - var typeLookupCache2 = 0; - var typeLookupCache3 = 0; - var typeLookupCache4 = 0; - var typeLookupCache5 = 0; - - for (var blockIndex = begin; blockIndex != end; ++blockIndex) - { - var chunk = chunks[blockIndex]; - int beginIndex = entityIndices[blockIndex]; - var count = chunk.Count; - #if ENABLE_UNITY_COLLECTIONS_CHECKS - JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), beginIndex, beginIndex + count); - #endif - var ptrE = (Entity*)UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, false, 0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex0, ref typeLookupCache0); - var ptr0 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly0 == 0, typeLookupCache0, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex1, ref typeLookupCache1); - var ptr1 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly1 == 0, typeLookupCache1, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex2, ref typeLookupCache2); - var ptr2 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly2 == 0, typeLookupCache2, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex3, ref typeLookupCache3); - var ptr3 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly3 == 0, typeLookupCache3, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex4, ref typeLookupCache4); - var ptr4 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly4 == 0, typeLookupCache4, jobData.Iterator.GlobalSystemVersion)); - ChunkDataUtility.GetIndexInTypeArray(chunk.m_Chunk->Archetype, jobData.Iterator.TypeIndex5, ref typeLookupCache5); - var ptr5 = UnsafeUtilityEx.RestrictNoAlias(ComponentChunkIterator.GetChunkComponentDataPtr(chunk.m_Chunk, jobData.Iterator.IsReadOnly5 == 0, typeLookupCache5, jobData.Iterator.GlobalSystemVersion)); - - - for (var i = 0; i != count; i++) - { - jobData.Data.Execute(ptrE[i], i + beginIndex, ref UnsafeUtilityEx.ArrayElementAsRef(ptr0, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr1, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr2, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr3, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr4, i), ref UnsafeUtilityEx.ArrayElementAsRef(ptr5, i)); - } - } - } - } - - } -} - -#endif diff --git a/Unity.Entities/IJobProcessComponentData.generated.cs.meta b/Unity.Entities/IJobProcessComponentData.generated.cs.meta deleted file mode 100644 index be44c35c..00000000 --- a/Unity.Entities/IJobProcessComponentData.generated.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a0728d3be945c4afb91aa33feaef01a8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Injection/ComponentSystemInjection.cs b/Unity.Entities/Injection/ComponentSystemInjection.cs deleted file mode 100644 index 5f5c60a1..00000000 --- a/Unity.Entities/Injection/ComponentSystemInjection.cs +++ /dev/null @@ -1,115 +0,0 @@ -#if !UNITY_ZEROPLAYER -using System; -using System.Collections.Generic; -using System.Reflection; - -#pragma warning disable 618 - -namespace Unity.Entities -{ - internal static class ComponentSystemInjection - { - public static string GetFieldString(FieldInfo info) - { - return $"{info.DeclaringType.Name}.{info.Name}"; - } - - public static void Inject(ComponentSystemBase componentSystem, World world, EntityManager entityManager, - out InjectComponentGroupData[] outInjectGroups, out InjectFromEntityData outInjectFromEntityData) - { - var componentSystemType = componentSystem.GetType(); - - ValidateNoStaticInjectDependencies(componentSystemType); - - InjectFields(componentSystem, world, entityManager, out outInjectGroups, out outInjectFromEntityData); - } - - static void InjectFields(ComponentSystemBase componentSystem, World world, EntityManager entityManager, - out InjectComponentGroupData[] outInjectGroups, out InjectFromEntityData outInjectFromEntityData) - { - var componentSystemType = componentSystem.GetType(); - var fields = componentSystemType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); - var injectGroups = new List(); - - var injectFromEntity = new List(); - var injectFromFixedArray = new List(); - - foreach (var field in fields) - { - var attr = field.GetCustomAttributes(typeof(InjectAttribute), true); - if (attr.Length == 0) - continue; - - if (field.FieldType.IsClass) - { - InjectConstructorDependencies(componentSystem, world, field); - } - else - { - if (InjectFromEntityData.SupportsInjections(field)) - InjectFromEntityData.CreateInjection(field, entityManager, injectFromEntity, - injectFromFixedArray); - else - injectGroups.Add( - InjectComponentGroupData.CreateInjection(field.FieldType, field, componentSystem)); - } - } - - - outInjectGroups = injectGroups.ToArray(); - - outInjectFromEntityData = new InjectFromEntityData(injectFromEntity.ToArray(), injectFromFixedArray.ToArray()); - } - - private static void ValidateNoStaticInjectDependencies(Type type) - { -#if UNITY_EDITOR - var fields = type.GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic); - - foreach (var field in fields) - if (field.GetCustomAttributes(typeof(InjectAttribute), true).Length != 0) - throw new ArgumentException( - $"[Inject] may not be used on static variables: {GetFieldString(field)}"); -#endif - } - - private static void InjectConstructorDependencies(ScriptBehaviourManager manager, World world, FieldInfo field) - { - if (field.FieldType.IsSubclassOf(typeof(ScriptBehaviourManager))) - field.SetValue(manager, world.GetOrCreateManager(field.FieldType)); - else - ThrowUnsupportedInjectException(field); - } - - public static void ThrowUnsupportedInjectException(FieldInfo field) - { - throw new ArgumentException( - $"[Inject] is not supported for type '{field.FieldType}'. At: {GetFieldString(field)}"); - } - - internal static T[] GetAllInjectedManagers(ScriptBehaviourManager host, World world) - where T : ScriptBehaviourManager - { - var result = new List(); - var fields = host.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); - - foreach (var field in fields) - { - var attr = field.GetCustomAttributes(typeof(InjectAttribute), true); - if (attr.Length == 0) - continue; - - if (!field.FieldType.IsClass) - continue; - - if (!field.FieldType.IsSubclassOf(typeof(T))) - continue; - - result.Add((T) world.GetOrCreateManager(field.FieldType)); - } - - return result.ToArray(); - } - } -} -#endif \ No newline at end of file diff --git a/Unity.Entities/Injection/ComponentSystemInjection.cs.meta b/Unity.Entities/Injection/ComponentSystemInjection.cs.meta deleted file mode 100644 index 365a26b7..00000000 --- a/Unity.Entities/Injection/ComponentSystemInjection.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 15f0c9e8418343e09f1835b588049d8b -timeCreated: 1511049156 \ No newline at end of file diff --git a/Unity.Entities/Injection/InjectAttribute.cs b/Unity.Entities/Injection/InjectAttribute.cs deleted file mode 100644 index f92055ff..00000000 --- a/Unity.Entities/Injection/InjectAttribute.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace Unity.Entities -{ - [AttributeUsage(AttributeTargets.Field)] - [Obsolete("Injection API is deprecated. Use ComponentGroup API instead.")] - public class InjectAttribute : Attribute - { - } -} diff --git a/Unity.Entities/Injection/InjectAttribute.cs.meta b/Unity.Entities/Injection/InjectAttribute.cs.meta deleted file mode 100644 index 35f0db95..00000000 --- a/Unity.Entities/Injection/InjectAttribute.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 0cd570c938a441eb828ce5faca7c5418 -timeCreated: 1512064623 \ No newline at end of file diff --git a/Unity.Entities/Injection/InjectComponentFromEntity.cs b/Unity.Entities/Injection/InjectComponentFromEntity.cs deleted file mode 100644 index ad9b3d83..00000000 --- a/Unity.Entities/Injection/InjectComponentFromEntity.cs +++ /dev/null @@ -1,87 +0,0 @@ -#if !UNITY_ZEROPLAYER -using System.Collections.Generic; -using System.Reflection; -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; - -namespace Unity.Entities -{ - internal struct InjectFromEntityData - { - private readonly InjectionData[] m_InjectComponentDataFromEntity; - private readonly InjectionData[] m_InjectBufferFromEntity; - - public InjectFromEntityData(InjectionData[] componentDataFromEntity, InjectionData[] bufferFromEntity) - { - m_InjectComponentDataFromEntity = componentDataFromEntity; - m_InjectBufferFromEntity = bufferFromEntity; - } - - public static bool SupportsInjections(FieldInfo field) - { - if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(ComponentDataFromEntity<>)) - return true; - if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(BufferFromEntity<>)) - return true; - return false; - } - - public static void CreateInjection(FieldInfo field, EntityManager entityManager, - List componentDataFromEntity, List bufferFromEntity) - { - var isReadOnly = field.GetCustomAttributes(typeof(ReadOnlyAttribute), true).Length != 0; - - if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(ComponentDataFromEntity<>)) - { - var injection = new InjectionData(field, field.FieldType.GetGenericArguments()[0], isReadOnly); - componentDataFromEntity.Add(injection); - } - else if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(BufferFromEntity<>)) - { - var injection = new InjectionData(field, field.FieldType.GetGenericArguments()[0], isReadOnly); - bufferFromEntity.Add(injection); - } - else - { - ComponentSystemInjection.ThrowUnsupportedInjectException(field); - } - } - - public unsafe void UpdateInjection(byte* pinnedSystemPtr, EntityManager entityManager) - { - for (var i = 0; i != m_InjectComponentDataFromEntity.Length; i++) - { - var array = entityManager.GetComponentDataFromEntity( - m_InjectComponentDataFromEntity[i].ComponentType.TypeIndex, - m_InjectComponentDataFromEntity[i].IsReadOnly); - UnsafeUtility.CopyStructureToPtr(ref array, - pinnedSystemPtr + m_InjectComponentDataFromEntity[i].FieldOffset); - } - - for (var i = 0; i != m_InjectBufferFromEntity.Length; i++) - { - var array = entityManager.GetBufferFromEntity( - m_InjectBufferFromEntity[i].ComponentType.TypeIndex, - m_InjectBufferFromEntity[i].IsReadOnly); - UnsafeUtility.CopyStructureToPtr(ref array, - pinnedSystemPtr + m_InjectBufferFromEntity[i].FieldOffset); - } - } - - public void ExtractJobDependencyTypes(ComponentSystemBase system) - { - if (m_InjectComponentDataFromEntity != null) - foreach (var injection in m_InjectComponentDataFromEntity) - system.AddReaderWriter(injection.ComponentType); - - if (m_InjectBufferFromEntity != null) - foreach (var injection in m_InjectBufferFromEntity) - system.AddReaderWriter(injection.ComponentType); - } - } -} -#endif \ No newline at end of file diff --git a/Unity.Entities/Injection/InjectComponentFromEntity.cs.meta b/Unity.Entities/Injection/InjectComponentFromEntity.cs.meta deleted file mode 100644 index 3676195f..00000000 --- a/Unity.Entities/Injection/InjectComponentFromEntity.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 1be2212180ea46758457f3d63f4aabf5 -timeCreated: 1511048217 \ No newline at end of file diff --git a/Unity.Entities/Injection/InjectComponentGroup.cs b/Unity.Entities/Injection/InjectComponentGroup.cs deleted file mode 100644 index c753ef56..00000000 --- a/Unity.Entities/Injection/InjectComponentGroup.cs +++ /dev/null @@ -1,264 +0,0 @@ -#if !UNITY_ZEROPLAYER - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; - -// Injection marked Obsolete -#pragma warning disable 618 - -namespace Unity.Entities -{ - internal struct ProxyComponentData : IComponentData - { - private byte m_Internal; - } - - internal struct ProxyBufferElementData : IBufferElementData - { - private byte m_Internal; - } - - internal struct ProxySharedComponentData : ISharedComponentData - { - private byte m_Internal; - } - - internal class InjectComponentGroupData - { - private readonly InjectionData[] m_ComponentDataInjections; - - private readonly int m_EntityArrayOffset; - private readonly InjectionData[] m_BufferArrayInjections; - private readonly int m_GroupFieldOffset; - - private readonly InjectionContext m_InjectionContext; - private readonly int m_LengthOffset; - private readonly InjectionData[] m_SharedComponentInjections; - private readonly ComponentGroup m_EntityGroup; - - private readonly int m_ComponentGroupIndex; - - private unsafe InjectComponentGroupData(ComponentSystemBase system, FieldInfo groupField, - InjectionData[] componentDataInjections, InjectionData[] bufferArrayInjections, - InjectionData[] sharedComponentInjections, - FieldInfo entityArrayInjection, FieldInfo indexFromEntityInjection, InjectionContext injectionContext, - FieldInfo lengthInjection, FieldInfo componentGroupIndexField, ComponentType[] componentRequirements) - { - m_EntityGroup = system.GetComponentGroupInternal(componentRequirements); - - m_ComponentGroupIndex = Array.IndexOf(system.ComponentGroups, m_EntityGroup); - - m_ComponentDataInjections = componentDataInjections; - m_BufferArrayInjections = bufferArrayInjections; - m_SharedComponentInjections = sharedComponentInjections; - m_InjectionContext = injectionContext; - - PatchGetIndexInComponentGroup(m_ComponentDataInjections); - PatchGetIndexInComponentGroup(m_BufferArrayInjections); - PatchGetIndexInComponentGroup(m_SharedComponentInjections); - - injectionContext.PrepareEntries(m_EntityGroup); - - if (entityArrayInjection != null) - m_EntityArrayOffset = UnsafeUtility.GetFieldOffset(entityArrayInjection); - else - m_EntityArrayOffset = -1; - - if (lengthInjection != null) - m_LengthOffset = UnsafeUtility.GetFieldOffset(lengthInjection); - else - m_LengthOffset = -1; - - m_GroupFieldOffset = UnsafeUtility.GetFieldOffset(groupField); - - if (componentGroupIndexField != null) - { - ulong gchandle; - var pinnedSystemPtr = (byte*)UnsafeUtility.PinGCObjectAndGetAddress(system, out gchandle); - var groupIndexPtr = pinnedSystemPtr + m_GroupFieldOffset + UnsafeUtility.GetFieldOffset(componentGroupIndexField); - - int groupIndex = m_ComponentGroupIndex; - UnsafeUtility.CopyStructureToPtr(ref groupIndex, groupIndexPtr); - - UnsafeUtility.ReleaseGCObject(gchandle); - } - } - - private void PatchGetIndexInComponentGroup(InjectionData[] componentInjections) - { - for (var i = 0; i != componentInjections.Length; i++) - componentInjections[i].IndexInComponentGroup = - m_EntityGroup.GetIndexInComponentGroup(componentInjections[i].ComponentType.TypeIndex); - } - - public unsafe void UpdateInjection(byte* systemPtr) - { - var groupStructPtr = systemPtr + m_GroupFieldOffset; - - int length = m_EntityGroup.CalculateLength(); - ComponentChunkIterator iterator = m_EntityGroup.GetComponentChunkIterator(); - - for (var i = 0; i != m_ComponentDataInjections.Length; i++) - { - ComponentDataArray data; - m_EntityGroup.GetComponentDataArray(ref iterator, m_ComponentDataInjections[i].IndexInComponentGroup, - length, out data); - UnsafeUtility.CopyStructureToPtr(ref data, groupStructPtr + m_ComponentDataInjections[i].FieldOffset); - } - - for (var i = 0; i != m_SharedComponentInjections.Length; i++) - { - SharedComponentDataArray data; - m_EntityGroup.GetSharedComponentDataArray(ref iterator, - m_SharedComponentInjections[i].IndexInComponentGroup, length, out data); - UnsafeUtility.CopyStructureToPtr(ref data, groupStructPtr + m_SharedComponentInjections[i].FieldOffset); - } - - for (var i = 0; i != m_BufferArrayInjections.Length; i++) - { - BufferArray data; - m_EntityGroup.GetBufferArray(ref iterator, m_BufferArrayInjections[i].IndexInComponentGroup, length, - out data); - UnsafeUtility.CopyStructureToPtr(ref data, groupStructPtr + m_BufferArrayInjections[i].FieldOffset); - } - - if (m_EntityArrayOffset != -1) - { - EntityArray entityArray = m_EntityGroup.GetEntityArray(); - UnsafeUtility.CopyStructureToPtr(ref entityArray, groupStructPtr + m_EntityArrayOffset); - } - - if (m_InjectionContext.HasEntries) - m_InjectionContext.UpdateEntries(m_EntityGroup, ref iterator, length, groupStructPtr); - - if (m_LengthOffset != -1) UnsafeUtility.CopyStructureToPtr(ref length, groupStructPtr + m_LengthOffset); - } - - public static InjectComponentGroupData CreateInjection(Type injectedGroupType, FieldInfo groupField, - ComponentSystemBase system) - { - FieldInfo entityArrayField; - FieldInfo indexFromEntityField; - FieldInfo lengthField; - FieldInfo componentGroupIndexField; - - var injectionContext = new InjectionContext(); - var componentDataInjections = new List(); - var bufferDataInjections = new List(); - var sharedComponentInjections = new List(); - - var componentRequirements = new HashSet(); - var error = CollectInjectedGroup(system, groupField, injectedGroupType, out entityArrayField, - out indexFromEntityField, injectionContext, out lengthField, out componentGroupIndexField, - componentRequirements, componentDataInjections, bufferDataInjections, sharedComponentInjections); - if (error != null) - throw new ArgumentException(error); - - return new InjectComponentGroupData(system, groupField, componentDataInjections.ToArray(), - bufferDataInjections.ToArray(), sharedComponentInjections.ToArray(), entityArrayField, - indexFromEntityField, injectionContext, lengthField, componentGroupIndexField, - componentRequirements.ToArray()); - } - - private static string CollectInjectedGroup(ComponentSystemBase system, FieldInfo groupField, - Type injectedGroupType, out FieldInfo entityArrayField, out FieldInfo indexFromEntityField, - InjectionContext injectionContext, out FieldInfo lengthField, out FieldInfo componentGroupIndexField, - ISet componentRequirements, ICollection componentDataInjections, - ICollection bufferDataInjections, ICollection sharedComponentInjections) - { - //@TODO: Improve error messages... - var fields = - injectedGroupType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); - entityArrayField = null; - indexFromEntityField = null; - lengthField = null; - componentGroupIndexField = null; - - foreach (var field in fields) - { - var isReadOnly = field.GetCustomAttributes(typeof(ReadOnlyAttribute), true).Length != 0; - //@TODO: Prevent using GameObjectEntity, it will never show up. Point to GameObjectArray instead... - - if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(ComponentDataArray<>)) - { - var injection = new InjectionData(field, field.FieldType.GetGenericArguments()[0], isReadOnly); - componentDataInjections.Add(injection); - componentRequirements.Add(injection.ComponentType); - } - else if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(ExcludeComponent<>)) - { - componentRequirements.Add(ComponentType.Exclude(field.FieldType.GetGenericArguments()[0])); - } - else if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(BufferArray<>)) - { - var injection = new InjectionData(field, field.FieldType.GetGenericArguments()[0], isReadOnly); - - bufferDataInjections.Add(injection); - componentRequirements.Add(injection.ComponentType); - } - else if (field.FieldType.IsGenericType && - field.FieldType.GetGenericTypeDefinition() == typeof(SharedComponentDataArray<>)) - { - if (!isReadOnly) - return - $"{system.GetType().Name}:{groupField.Name} SharedComponentDataArray<> must always be injected as [ReadOnly]"; - var injection = new InjectionData(field, field.FieldType.GetGenericArguments()[0], true); - - sharedComponentInjections.Add(injection); - componentRequirements.Add(injection.ComponentType); - } - else if (field.FieldType == typeof(EntityArray)) - { - // Error on multiple EntityArray - if (entityArrayField != null) - return - $"{system.GetType().Name}:{groupField.Name} An [Inject] struct, may only contain a single EntityArray"; - - entityArrayField = field; - } - else if (field.FieldType == typeof(int)) - { - if (field.Name != "Length" && field.Name != "GroupIndex") - return - $"{system.GetType().Name}:{groupField.Name} Int in an [Inject] struct should be named \"Length\" (group length) or \"GroupIndex\" (index in ComponentGroup[])"; - - if (!field.IsInitOnly) - return - $"{system.GetType().Name}:{groupField.Name} {field.Name} must use the \"readonly\" keyword"; - - if(field.Name == "Length") - lengthField = field; - - if (field.Name == "GroupIndex") - componentGroupIndexField = field; - } - else - { - var hook = InjectionHookSupport.HookFor(field); - if (hook == null) - return - $"{system.GetType().Name}:{groupField.Name} [Inject] may only be used on ComponentDataArray<>, ComponentArray<>, TransformAccessArray, EntityArray, {string.Join(",", InjectionHookSupport.Hooks.Select(h => h.FieldTypeOfInterest.Name))} and int Length."; - - var error = hook.ValidateField(field, isReadOnly, injectionContext); - if (error != null) return error; - - injectionContext.AddEntry(hook.CreateInjectionInfoFor(field, isReadOnly)); - } - } - - if (injectionContext.HasComponentRequirements) - foreach (var requirement in injectionContext.ComponentRequirements) - componentRequirements.Add(requirement); - - return null; - } - } -} -#endif \ No newline at end of file diff --git a/Unity.Entities/Injection/InjectComponentGroup.cs.meta b/Unity.Entities/Injection/InjectComponentGroup.cs.meta deleted file mode 100644 index beb0080a..00000000 --- a/Unity.Entities/Injection/InjectComponentGroup.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: e808dc4ed0eb648f1a15659b3a73fc32 -timeCreated: 1491948448 -licenseType: Pro -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Injection/InjectionData.cs b/Unity.Entities/Injection/InjectionData.cs deleted file mode 100644 index cb2462b8..00000000 --- a/Unity.Entities/Injection/InjectionData.cs +++ /dev/null @@ -1,26 +0,0 @@ -#if !UNITY_ZEROPLAYER -using System; -using System.Reflection; -using Unity.Collections.LowLevel.Unsafe; - -namespace Unity.Entities -{ - internal struct InjectionData - { - public ComponentType ComponentType; - public int IndexInComponentGroup; - public readonly bool IsReadOnly; - public readonly int FieldOffset; - - public InjectionData(FieldInfo field, Type genericType, bool isReadOnly) - { - IndexInComponentGroup = -1; - FieldOffset = UnsafeUtility.GetFieldOffset(field); - - var accessMode = isReadOnly ? ComponentType.AccessMode.ReadOnly : ComponentType.AccessMode.ReadWrite; - ComponentType = new ComponentType(genericType, accessMode); - IsReadOnly = isReadOnly; - } - } -} -#endif \ No newline at end of file diff --git a/Unity.Entities/Injection/InjectionData.cs.meta b/Unity.Entities/Injection/InjectionData.cs.meta deleted file mode 100644 index d1d20a95..00000000 --- a/Unity.Entities/Injection/InjectionData.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 8f94d591047f4a7cae2b25c92134da90 -timeCreated: 1511048294 \ No newline at end of file diff --git a/Unity.Entities/Injection/InjectionHook.cs b/Unity.Entities/Injection/InjectionHook.cs deleted file mode 100644 index 5d39ba2a..00000000 --- a/Unity.Entities/Injection/InjectionHook.cs +++ /dev/null @@ -1,134 +0,0 @@ -#if !UNITY_ZEROPLAYER -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Unity.Entities -{ - internal sealed class CustomInjectionHookAttribute : Attribute - { - } - - public sealed class InjectionContext - { - private readonly List m_Entries = new List(); - - public bool HasComponentRequirements { get; private set; } - - public bool HasEntries => m_Entries.Count != 0; - - public IReadOnlyCollection Entries => m_Entries; - - public IEnumerable ComponentRequirements - { - get - { - foreach (var info in m_Entries) - foreach (var requirement in info.ComponentRequirements) - yield return requirement; - } - } - - internal void AddEntry(Entry entry) - { - HasComponentRequirements = HasComponentRequirements || entry.ComponentRequirements.Length > 0; - m_Entries.Add(entry); - } - - public void PrepareEntries(ComponentGroup entityGroup) - { - if (!HasEntries) - return; - - for (var index = 0; index < m_Entries.Count; index++) - { - var entry = m_Entries[index]; - entry.Hook.PrepareEntry(ref entry, entityGroup); - m_Entries[index] = entry; - } - } - - internal unsafe void UpdateEntries(ComponentGroup entityGroup, ref ComponentChunkIterator iterator, int length, - byte* groupStructPtr) - { - if (!HasEntries) - return; - - foreach (var info in m_Entries) - info.Hook.InjectEntry(info, entityGroup, ref iterator, length, groupStructPtr); - } - - public struct Entry - { - public int FieldOffset; - public FieldInfo FieldInfo; - public Type[] ComponentRequirements; - public InjectionHook Hook; - public ComponentType.AccessMode AccessMode; - public int IndexInComponentGroup; - public bool IsReadOnly; - public ComponentType ComponentType; - } - } - - public abstract unsafe class InjectionHook - { - public abstract Type FieldTypeOfInterest { get; } - public abstract bool IsInterestedInField(FieldInfo fieldInfo); - public abstract InjectionContext.Entry CreateInjectionInfoFor(FieldInfo field, bool isReadOnly); - - internal abstract void InjectEntry(InjectionContext.Entry entry, ComponentGroup entityGroup, - ref ComponentChunkIterator iterator, int length, byte* groupStructPtr); - - public abstract string ValidateField(FieldInfo field, bool isReadOnly, InjectionContext injectionInfo); - - public virtual void PrepareEntry(ref InjectionContext.Entry entry, ComponentGroup entityGroup) - { - } - } - - public static class InjectionHookSupport - { - private static bool s_HasHooks; - private static readonly List k_Hooks = new List(); - - internal static IReadOnlyCollection Hooks => k_Hooks; - - public static void RegisterHook(InjectionHook hook) - { - s_HasHooks = true; - k_Hooks.Add(hook); - } - - public static void UnregisterHook(InjectionHook hook) - { - k_Hooks.Remove(hook); - s_HasHooks = k_Hooks.Count != 0; - } - - internal static InjectionHook HookFor(FieldInfo fieldInfo) - { - if (!s_HasHooks) - return null; - - // TODO: in case of multiple hooks interested in a single field type, we should drop an error (in Editor) - foreach (var hook in k_Hooks) - if (hook.IsInterestedInField(fieldInfo)) - return hook; - - return null; - } - - public static bool IsValidHook(Type type) - { - if (type.IsAbstract) - return false; - if (type.ContainsGenericParameters) - return false; - if (!typeof(InjectionHook).IsAssignableFrom(type)) - return false; - return type.GetCustomAttributes(typeof(CustomInjectionHookAttribute), true).Length != 0; - } - } -} -#endif diff --git a/Unity.Entities/Injection/InjectionHook.cs.meta b/Unity.Entities/Injection/InjectionHook.cs.meta deleted file mode 100644 index a0bbf3a1..00000000 --- a/Unity.Entities/Injection/InjectionHook.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ebb4176a338ea4d3aaed1f846062468e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Injection/World.cs b/Unity.Entities/Injection/World.cs deleted file mode 100644 index af3cbfac..00000000 --- a/Unity.Entities/Injection/World.cs +++ /dev/null @@ -1,543 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Reflection; - -namespace Unity.Entities -{ -#if !UNITY_ZEROPLAYER - public class World : IDisposable - { - static readonly List allWorlds = new List(); -#if ENABLE_UNITY_COLLECTIONS_CHECKS - bool m_AllowGetManager = true; -#endif - - //@TODO: What about multiple managers of the same type... - Dictionary m_BehaviourManagerLookup = - new Dictionary(); - - List m_BehaviourManagers = new List(); - static int ms_SystemIDAllocator = 0; - - public World(string name) - { - // Debug.LogError("Create World "+ name + " - " + GetHashCode()); - Name = name; - allWorlds.Add(this); - } - - public IEnumerable BehaviourManagers => - new ReadOnlyCollection(m_BehaviourManagers); - - public string Name { get; } - - public override string ToString() - { - return Name; - } - - public int Version { get; private set; } - - public static World Active { get; set; } - - public EntityManager EntityManager - { - get { return GetOrCreateManager(); } - } - - public static ReadOnlyCollection AllWorlds => new ReadOnlyCollection(allWorlds); - - public bool IsCreated => m_BehaviourManagers != null; - - public void Dispose() - { - if (!IsCreated) - throw new ArgumentException("The World has already been Disposed."); - // Debug.LogError("Dispose World "+ Name + " - " + GetHashCode()); - - if (allWorlds.Contains(this)) - allWorlds.Remove(this); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_AllowGetManager = false; -#endif - // Destruction should happen in reverse order to construction - ScriptBehaviourManager em = null; - for (int i = m_BehaviourManagers.Count - 1; i >= 0; --i) - { - var mgr = m_BehaviourManagers[i]; - if (mgr is EntityManager) - { - em = mgr; - continue; - } - try - { - mgr.DestroyInstance(); - } - catch (Exception e) - { - Debug.LogException(e); - } - } - - // Destroy EntityManager last - if (em != null) - { - try - { - em.DestroyInstance(); - } - catch (Exception e) - { - Debug.LogException(e); - } - } - - if (Active == this) - Active = null; - - m_BehaviourManagers.Clear(); - m_BehaviourManagerLookup.Clear(); - - m_BehaviourManagers = null; - m_BehaviourManagerLookup = null; - } - - public static void DisposeAllWorlds() - { - while (allWorlds.Count != 0) - allWorlds[0].Dispose(); - } - - ScriptBehaviourManager CreateManagerInternal(Type type, object[] constructorArguments) - { - if (!typeof(ScriptBehaviourManager).IsAssignableFrom(type)) - { - throw new ArgumentException($"Type {type} must be derived from ScriptBehaviourManager."); - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - - if (constructorArguments != null && constructorArguments.Length != 0) - { - var constructors = - type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); - if (constructors.Length == 1 && constructors[0].IsPrivate) - throw new MissingMethodException( - $"Constructing {type} failed because the constructor was private, it must be public."); - } - - m_AllowGetManager = false; -#endif - ScriptBehaviourManager manager; - try - { - manager = Activator.CreateInstance(type, constructorArguments) as ScriptBehaviourManager; - } - catch (MissingMethodException) - { - Debug.LogError($"System/Manager {type} must be mentioned in a link.xml file, or annotated " + - "with a [Preserve] attribute to prevent its constructor from being stripped. " + - "See https://docs.unity3d.com/Manual/ManagedCodeStripping.html for more information."); - throw; - } - finally - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_AllowGetManager = true; -#endif - } - - return AddManager(manager); - } - - ScriptBehaviourManager GetExistingManagerInternal(Type type) - { - ScriptBehaviourManager manager; - if (m_BehaviourManagerLookup.TryGetValue(type, out manager)) - return manager; - - return null; - } - - ScriptBehaviourManager GetOrCreateManagerInternal(Type type) - { - var manager = GetExistingManagerInternal(type); - - return manager ?? CreateManagerInternal(type, null); - } - - void AddTypeLookup(Type type, ScriptBehaviourManager manager) - { - while (type != typeof(ScriptBehaviourManager)) - { - if (!m_BehaviourManagerLookup.ContainsKey(type)) - m_BehaviourManagerLookup.Add(type, manager); - - type = type.BaseType; - } - } - - void RemoveManagerInternal(ScriptBehaviourManager manager) - { - if (!m_BehaviourManagers.Remove(manager)) - throw new ArgumentException($"manager does not exist in the world"); - ++Version; - - var type = manager.GetType(); - while (type != typeof(ScriptBehaviourManager)) - { - if (m_BehaviourManagerLookup[type] == manager) - { - m_BehaviourManagerLookup.Remove(type); - - foreach (var otherManager in m_BehaviourManagers) - if (otherManager.GetType().IsSubclassOf(type)) - AddTypeLookup(otherManager.GetType(), otherManager); - } - - type = type.BaseType; - } - } - - void CheckGetOrCreateManager() - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (!IsCreated) - throw new ArgumentException("The World has already been Disposed."); - if (!m_AllowGetManager) - throw new ArgumentException( - "During destruction and constructor of a system you are not allowed to get or create more systems."); -#endif - } - - void CheckCreated() - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (!IsCreated) - throw new ArgumentException("The World has already been Disposed."); -#endif - } - - public ScriptBehaviourManager CreateManager(Type type, params object[] constructorArguments) - { - CheckGetOrCreateManager(); - - return CreateManagerInternal(type, constructorArguments); - } - - public T CreateManager(params object[] constructorArguments) where T : ScriptBehaviourManager - { - CheckGetOrCreateManager(); - - return (T) CreateManagerInternal(typeof(T), constructorArguments); - } - - public T GetOrCreateManager() where T : ScriptBehaviourManager - { - CheckGetOrCreateManager(); - - return (T) GetOrCreateManagerInternal(typeof(T)); - } - - public ScriptBehaviourManager GetOrCreateManager(Type type) - { - CheckGetOrCreateManager(); - - return GetOrCreateManagerInternal(type); - } - - public T AddManager(T manager) where T : ScriptBehaviourManager - { - CheckGetOrCreateManager(); - - m_BehaviourManagers.Add(manager); - AddTypeLookup(manager.GetType(), manager); - - try - { - manager.CreateInstance(this); - } - catch - { - RemoveManagerInternal(manager); - throw; - } - ++Version; - return manager; - } - - public T GetExistingManager() where T : ScriptBehaviourManager - { - CheckGetOrCreateManager(); - - return (T) GetExistingManagerInternal(typeof(T)); - } - - public ScriptBehaviourManager GetExistingManager(Type type) - { - CheckGetOrCreateManager(); - - return GetExistingManagerInternal(type); - } - - public void DestroyManager(ScriptBehaviourManager manager) - { - CheckGetOrCreateManager(); - - RemoveManagerInternal(manager); - manager.DestroyInstance(); - } - - public bool QuitUpdate { get; set; } - - internal static int AllocateSystemID() - { - return ++ms_SystemIDAllocator; - } - } -#else - public class World : IDisposable - { - static readonly List allWorlds = new List(); -#if ENABLE_UNITY_COLLECTIONS_CHECKS - bool m_AllowGetManager = true; -#endif - - //@TODO: What about multiple managers of the same type... - List m_BehaviourManagers = new List(); - - int m_SystemIDAllocator = 0; - - public World(string name) - { - // Debug.LogError("Create World "+ name + " - " + GetHashCode()); - Name = name; - allWorlds.Add(this); - } - - // XXX fix me -- we need a readonly wrapper - public ScriptBehaviourManager[] BehaviourManagers => m_BehaviourManagers.ToArray(); - - public string Name { get; } - - public override string ToString() - { - return Name; - } - - public int Version { get; private set; } - - public static World Active { get; set; } - - public static World[] AllWorlds => allWorlds.ToArray(); - - public bool IsCreated => true; - - public void Dispose() - { - if (!IsCreated) - throw new ArgumentException("World is already disposed"); - // Debug.LogError("Dispose World "+ Name + " - " + GetHashCode()); - - if (allWorlds.Contains(this)) - allWorlds.Remove(this); - - // Destruction should happen in reverse order to construction - ScriptBehaviourManager em = null; - for (int i = m_BehaviourManagers.Count - 1; i >= 0; --i) - { - var mgr = m_BehaviourManagers[i]; - if (mgr is EntityManager) - { - em = mgr; - continue; - } - try - { - mgr.DestroyInstance(); - } - catch (Exception e) - { - Debug.LogException(e); - } - } - - // Destroy EntityManager last - if (em != null) - { - try - { - em.DestroyInstance(); - } - catch (Exception e) - { - Debug.LogException(e); - } - } - - if (Active == this) - Active = null; - - m_BehaviourManagers.Clear(); - m_BehaviourManagers = null; - } - - public static void DisposeAllWorlds() - { - while (allWorlds.Count != 0) - allWorlds[0].Dispose(); - } - - private ScriptBehaviourManager CreateManagerInternal() where T : new() - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (!m_AllowGetManager) - throw new ArgumentException( - "During destruction of a system you are not allowed to create more systems."); - - m_AllowGetManager = true; -#endif - ScriptBehaviourManager manager; - try - { -#if !UNITY_CSHARP_TINY - manager = new T() as ScriptBehaviourManager; -#else - manager = TypeManager.ConstructSystem(typeof(T)); -#endif - } - catch - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_AllowGetManager = false; -#endif - throw; - } - - return AddManager(manager); - } - - private ScriptBehaviourManager GetExistingManagerInternal() - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (!IsCreated) - throw new ArgumentException("During destruction "); - if (!m_AllowGetManager) - throw new ArgumentException( - "During destruction of a system you are not allowed to get or create more systems."); -#endif - - ScriptBehaviourManager manager; - for (int i = 0; i < m_BehaviourManagers.Count; ++i) { - var mgr = m_BehaviourManagers[i]; - if (mgr is T) - return mgr; - } - - return null; - } - - private ScriptBehaviourManager GetExistingManagerInternal(Type type) - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (!IsCreated) - throw new ArgumentException("During destruction "); - if (!m_AllowGetManager) - throw new ArgumentException( - "During destruction of a system you are not allowed to get or create more systems."); -#endif - - ScriptBehaviourManager manager; - for (int i = 0; i < m_BehaviourManagers.Count; ++i) { - var mgr = m_BehaviourManagers[i]; - if (type.IsAssignableFrom(mgr.GetType())) - return mgr; - } - - return null; - } - - private ScriptBehaviourManager GetOrCreateManagerInternal() where T : new() - { - var manager = GetExistingManagerInternal(); - return manager ?? CreateManagerInternal(); - } - - private void RemoveManagerInternal(ScriptBehaviourManager manager) - { - if (!m_BehaviourManagers.Remove(manager)) - throw new ArgumentException($"manager does not exist in the world"); - ++Version; - } - - public T CreateManager() where T : ScriptBehaviourManager, new() - { - return (T) CreateManagerInternal(); - } - - public T GetOrCreateManager() where T : ScriptBehaviourManager, new() - { - return (T) GetOrCreateManagerInternal(); - } - - public T AddManager(T manager) where T : ScriptBehaviourManager - { - m_BehaviourManagers.Add(manager); - try - { - manager.CreateInstance(this); - } - catch - { - RemoveManagerInternal(manager); - throw; - } - - ++Version; - return manager; - } - - public T GetExistingManager() where T : ScriptBehaviourManager - { - return (T) GetExistingManagerInternal(typeof(T)); - } - - public ScriptBehaviourManager GetExistingManager(Type type) - { - return GetExistingManagerInternal(type); - } - - public void DestroyManager(ScriptBehaviourManager manager) - { - RemoveManagerInternal(manager); - manager.DestroyInstance(); - } - - static int ms_SystemIDAllocator = 0; - internal static int AllocateSystemID() - { - return ++ms_SystemIDAllocator; - } - - public bool QuitUpdate { get; set; } - - public void Update() - { - InitializationSystemGroup initializationSystemGroup = - GetExistingManager(typeof(InitializationSystemGroup)) as InitializationSystemGroup; - SimulationSystemGroup simulationSystemGroup = - GetExistingManager(typeof(SimulationSystemGroup)) as SimulationSystemGroup; - PresentationSystemGroup presentationSystemGroup = - GetExistingManager(typeof(PresentationSystemGroup)) as PresentationSystemGroup; - - initializationSystemGroup?.Update(); - simulationSystemGroup?.Update(); - presentationSystemGroup?.Update(); - } - - } -#endif -} diff --git a/Unity.Entities/Injection/WorldDebuggingTools.cs b/Unity.Entities/Injection/WorldDebuggingTools.cs deleted file mode 100644 index cdbe1849..00000000 --- a/Unity.Entities/Injection/WorldDebuggingTools.cs +++ /dev/null @@ -1,54 +0,0 @@ -#if UNITY_EDITOR -using System; -using System.Collections.Generic; -using System.Linq; -using Unity.Collections; - -namespace Unity.Entities -{ - internal class WorldDebuggingTools - { - internal static void MatchEntityInComponentGroups(World world, Entity entity, - List>> matchList) - { - using (var entityComponentTypes = - world.GetExistingManager().GetComponentTypes(entity, Allocator.Temp)) - { - foreach (var manager in World.Active.BehaviourManagers) - { - var componentGroupList = new List(); - var system = manager as ComponentSystemBase; - if (system == null) continue; - foreach (var componentGroup in system.ComponentGroups) - if (Match(componentGroup, entityComponentTypes)) - componentGroupList.Add(componentGroup); - - if (componentGroupList.Count > 0) - matchList.Add( - new Tuple>(manager, componentGroupList)); - } - } - } - - private static bool Match(ComponentGroup group, NativeArray entityComponentTypes) - { - foreach (var groupType in group.GetQueryTypes().Skip(1)) - { - var found = false; - foreach (var type in entityComponentTypes) - { - if (type.TypeIndex != groupType.TypeIndex) - continue; - found = true; - break; - } - - if (found == (groupType.AccessModeType == ComponentType.AccessMode.Exclude)) - return false; - } - - return true; - } - } -} -#endif \ No newline at end of file diff --git a/Unity.Entities/Iterators/BufferArray.cs b/Unity.Entities/Iterators/BufferArray.cs deleted file mode 100644 index 693fe9aa..00000000 --- a/Unity.Entities/Iterators/BufferArray.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using Unity.Collections.LowLevel.Unsafe; - -namespace Unity.Entities -{ - [NativeContainer] - [NativeContainerSupportsMinMaxWriteRestriction] - [Obsolete("BufferArray is deprecated. Use ComponentGroup APIs instead.")] - public unsafe struct BufferArray where T : struct, IBufferElementData - { - private ComponentChunkCache m_Cache; - private ComponentChunkIterator m_Iterator; - private readonly bool m_IsReadOnly; - - - private readonly int m_Length; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private readonly int m_MinIndex; - private readonly int m_MaxIndex; - private readonly AtomicSafetyHandle m_Safety0; - private readonly AtomicSafetyHandle m_ArrayInvalidationSafety; -#pragma warning disable 0414 // assigned but its value is never used - private int m_SafetyReadOnlyCount; - private int m_SafetyReadWriteCount; -#pragma warning restore 0414 -#endif - public int Length => m_Length; - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - internal BufferArray(ComponentChunkIterator iterator, int length, bool isReadOnly, - AtomicSafetyHandle safety, AtomicSafetyHandle arrayInvalidationSafety) -#else - internal BufferArray(ComponentChunkIterator iterator, int length, bool isReadOnly) -#endif - { - m_Length = length; - m_IsReadOnly = isReadOnly; - m_Iterator = iterator; - m_Cache = default(ComponentChunkCache); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_MinIndex = 0; - m_MaxIndex = length - 1; - m_Safety0 = safety; - m_ArrayInvalidationSafety = arrayInvalidationSafety; - m_SafetyReadOnlyCount = isReadOnly ? 2 : 0; - m_SafetyReadWriteCount = isReadOnly ? 0 : 2; -#endif - } - - public DynamicBuffer this[int index] - { - get - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - AtomicSafetyHandle.CheckReadAndThrow(m_Safety0); - if (index < m_MinIndex || index > m_MaxIndex) - FailOutOfRangeError(index); -#endif - - if (index < m_Cache.CachedBeginIndex || index >= m_Cache.CachedEndIndex) - { - m_Iterator.MoveToEntityIndexAndUpdateCache(index, out m_Cache, !m_IsReadOnly); -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (m_Cache.CachedSizeOf < sizeof(BufferHeader)) - throw new InvalidOperationException("size cache info is broken"); -#endif - } - - BufferHeader* header = (BufferHeader*) ((byte*)m_Cache.CachedPtr + index * m_Cache.CachedSizeOf); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - return new DynamicBuffer(header, m_Safety0, m_ArrayInvalidationSafety, m_IsReadOnly); -#else - return new DynamicBuffer(header); -#endif - } - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private void FailOutOfRangeError(int index) - { - //@TODO: Make error message utility and share with NativeArray... - if (index < Length && (m_MinIndex != 0 || m_MaxIndex != Length - 1)) - throw new IndexOutOfRangeException( - $"Index {index} is out of restricted IJobParallelFor range [{m_MinIndex}...{m_MaxIndex}] in ReadWriteBuffer.\nReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job."); - - throw new IndexOutOfRangeException($"Index {index} is out of range of '{Length}' Length."); - } -#endif - } -} diff --git a/Unity.Entities/Iterators/BufferArray.cs.meta b/Unity.Entities/Iterators/BufferArray.cs.meta deleted file mode 100644 index 3e91ca74..00000000 --- a/Unity.Entities/Iterators/BufferArray.cs.meta +++ /dev/null @@ -1,13 +0,0 @@ -fileFormatVersion: 2 -guid: 24ee6c53bdd9546d0982af7d8b40e84d -timeCreated: 1504713176 -licenseType: Pro -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Iterators/ChunkDataGatherJobs.cs b/Unity.Entities/Iterators/ChunkDataGatherJobs.cs index d696a347..8160541c 100644 --- a/Unity.Entities/Iterators/ChunkDataGatherJobs.cs +++ b/Unity.Entities/Iterators/ChunkDataGatherJobs.cs @@ -69,7 +69,7 @@ public void Execute() unsafe struct GatherChunksWithFiltering : IJobParallelFor { [NativeDisableUnsafePtrRestriction] public MatchingArchetype** MatchingArchetypes; - public ComponentGroupFilter Filter; + public EntityQueryFilter Filter; [ReadOnly] public NativeArray Offsets; public NativeArray FilteredCounts; @@ -88,9 +88,9 @@ public void Execute(int index) if (filter.Type == FilterType.SharedComponent) { - var indexInComponentGroup1 = filter.Shared.IndexInComponentGroup[0]; + var indexInEntityQuery1 = filter.Shared.IndexInEntityQuery[0]; var sharedComponentIndex1 = filter.Shared.SharedComponentIndex[0]; - var componentIndexInChunk1 = match->IndexInArchetype[indexInComponentGroup1] - archetype->FirstSharedComponent; + var componentIndexInChunk1 = match->IndexInArchetype[indexInEntityQuery1] - archetype->FirstSharedComponent; var sharedComponents1 = archetype->Chunks.GetSharedComponentValueArrayForType(componentIndexInChunk1); if (filter.Shared.Count == 1) @@ -103,9 +103,9 @@ public void Execute(int index) } else { - var indexInComponentGroup2 = filter.Shared.IndexInComponentGroup[1]; + var indexInEntityQuery2 = filter.Shared.IndexInEntityQuery[1]; var sharedComponentIndex2 = filter.Shared.SharedComponentIndex[1]; - var componentIndexInChunk2 = match->IndexInArchetype[indexInComponentGroup2] - archetype->FirstSharedComponent; + var componentIndexInChunk2 = match->IndexInArchetype[indexInEntityQuery2] - archetype->FirstSharedComponent; var sharedComponents2 = archetype->Chunks.GetSharedComponentValueArrayForType(componentIndexInChunk2); for (var i = 0; i < chunkCount; ++i) @@ -118,8 +118,8 @@ public void Execute(int index) } else { - var indexInComponentGroup1 = filter.Changed.IndexInComponentGroup[0]; - var componentIndexInChunk1 = match->IndexInArchetype[indexInComponentGroup1]; + var indexInEntityQuery1 = filter.Changed.IndexInEntityQuery[0]; + var componentIndexInChunk1 = match->IndexInArchetype[indexInEntityQuery1]; var changeVersions1 = archetype->Chunks.GetChangeVersionArrayForType(componentIndexInChunk1); var requiredVersion = filter.RequiredChangeVersion; @@ -133,8 +133,8 @@ public void Execute(int index) } else { - var indexInComponentGroup2 = filter.Changed.IndexInComponentGroup[1]; - var componentIndexInChunk2 = match->IndexInArchetype[indexInComponentGroup2]; + var indexInEntityQuery2 = filter.Changed.IndexInEntityQuery[1]; + var componentIndexInChunk2 = match->IndexInArchetype[indexInEntityQuery2]; var changeVersions2 = archetype->Chunks.GetChangeVersionArrayForType(componentIndexInChunk2); for (var i = 0; i < chunkCount; ++i) @@ -154,7 +154,7 @@ public void Execute(int index) internal unsafe struct GatherChunksAndOffsetsWithFilteringJob : IJob { public MatchingArchetypeList Archetypes; - public ComponentGroupFilter Filter; + public EntityQueryFilter Filter; [NativeDisableUnsafePtrRestriction] public void* PrefilterData; @@ -181,10 +181,10 @@ public void Execute() if (filter.Type == FilterType.SharedComponent) { - var indexInComponentGroup0 = filter.Shared.IndexInComponentGroup[0]; + var indexInEntityQuery0 = filter.Shared.IndexInEntityQuery[0]; var sharedComponentIndex0 = filter.Shared.SharedComponentIndex[0]; var componentIndexInChunk0 = - match->IndexInArchetype[indexInComponentGroup0] - archetype->FirstSharedComponent; + match->IndexInArchetype[indexInEntityQuery0] - archetype->FirstSharedComponent; var sharedComponents0 = archetype->Chunks.GetSharedComponentValueArrayForType(componentIndexInChunk0); @@ -203,10 +203,10 @@ public void Execute() } else { - var indexInComponentGroup1 = filter.Shared.IndexInComponentGroup[1]; + var indexInEntityQuery1 = filter.Shared.IndexInEntityQuery[1]; var sharedComponentIndex1 = filter.Shared.SharedComponentIndex[1]; var componentIndexInChunk1 = - match->IndexInArchetype[indexInComponentGroup1] - archetype->FirstSharedComponent; + match->IndexInArchetype[indexInEntityQuery1] - archetype->FirstSharedComponent; var sharedComponents1 = archetype->Chunks.GetSharedComponentValueArrayForType(componentIndexInChunk1); @@ -225,8 +225,8 @@ public void Execute() } else { - var indexInComponentGroup0 = filter.Changed.IndexInComponentGroup[0]; - var componentIndexInChunk0 = match->IndexInArchetype[indexInComponentGroup0]; + var indexInEntityQuery0 = filter.Changed.IndexInEntityQuery[0]; + var componentIndexInChunk0 = match->IndexInArchetype[indexInEntityQuery0]; var changeVersions0 = archetype->Chunks.GetChangeVersionArrayForType(componentIndexInChunk0); var requiredVersion = filter.RequiredChangeVersion; @@ -245,8 +245,8 @@ public void Execute() } else { - var indexInComponentGroup1 = filter.Changed.IndexInComponentGroup[1]; - var componentIndexInChunk1 = match->IndexInArchetype[indexInComponentGroup1]; + var indexInEntityQuery1 = filter.Changed.IndexInEntityQuery[1]; + var componentIndexInChunk1 = match->IndexInArchetype[indexInEntityQuery1]; var changeVersions1 = archetype->Chunks.GetChangeVersionArrayForType(componentIndexInChunk1); diff --git a/Unity.Entities/Iterators/ComponentChunkIterator.cs b/Unity.Entities/Iterators/ComponentChunkIterator.cs index d84658f2..1be96e21 100644 --- a/Unity.Entities/Iterators/ComponentChunkIterator.cs +++ b/Unity.Entities/Iterators/ComponentChunkIterator.cs @@ -18,12 +18,12 @@ internal enum FilterType } //@TODO: Use field offset / union here... There seems to be an issue in mono preventing it... - internal unsafe struct ComponentGroupFilter + internal unsafe struct EntityQueryFilter { public struct SharedComponentData { public int Count; - public fixed int IndexInComponentGroup[2]; + public fixed int IndexInEntityQuery[2]; public fixed int SharedComponentIndex[2]; } @@ -33,7 +33,7 @@ public struct ChangedFilter public const int Capacity = 2; public int Count; - public fixed int IndexInComponentGroup[2]; + public fixed int IndexInEntityQuery[2]; } public FilterType Type; @@ -91,11 +91,11 @@ internal unsafe struct ComponentChunkIterator private int m_CurrentArchetypeIndex; private int m_CurrentChunkIndex; - internal ComponentGroupFilter m_Filter; + internal EntityQueryFilter m_Filter; internal readonly uint m_GlobalSystemVersion; - public int IndexInComponentGroup; + public int IndexInEntityQuery; internal int GetSharedComponentFromCurrentChunk(int sharedComponentIndex) { @@ -106,11 +106,11 @@ internal int GetSharedComponentFromCurrentChunk(int sharedComponentIndex) } public ComponentChunkIterator(MatchingArchetypeList match, uint globalSystemVersion, - ref ComponentGroupFilter filter) + ref EntityQueryFilter filter) { m_MatchingArchetypeList = match; m_CurrentMatchingArchetypeIndex = match.Count - 1; - IndexInComponentGroup = -1; + IndexInEntityQuery = -1; m_CurrentChunk = null; m_CurrentArchetypeIndex = m_CurrentArchetypeEntityIndex = @@ -129,14 +129,14 @@ public object GetManagedObject(ArchetypeManager typeMan, int typeIndexInArchetyp public object GetManagedObject(ArchetypeManager typeMan, int cachedBeginIndex, int index) { return typeMan.GetManagedObject(*m_CurrentChunk, - m_CurrentMatchingArchetype->IndexInArchetype[IndexInComponentGroup], index - cachedBeginIndex); + m_CurrentMatchingArchetype->IndexInArchetype[IndexInEntityQuery], index - cachedBeginIndex); } public object[] GetManagedObjectRange(ArchetypeManager typeMan, int cachedBeginIndex, int index, out int rangeStart, out int rangeLength) { var objs = typeMan.GetManagedObjectRange(*m_CurrentChunk, - m_CurrentMatchingArchetype->IndexInArchetype[IndexInComponentGroup], out rangeStart, + m_CurrentMatchingArchetype->IndexInArchetype[IndexInEntityQuery], out rangeStart, out rangeLength); rangeStart += index - cachedBeginIndex; rangeLength -= index - cachedBeginIndex; @@ -169,7 +169,7 @@ internal static int CalculateNumberOfChunksWithoutFiltering(MatchingArchetypeLis /// Handle to the GatherChunks job used to fill the output array. /// NativeArray of all the chunks in the matchingArchetypes list. public static NativeArray CreateArchetypeChunkArray(MatchingArchetypeList matchingArchetypes, - Allocator allocator, out JobHandle jobHandle, ref ComponentGroupFilter filter, + Allocator allocator, out JobHandle jobHandle, ref EntityQueryFilter filter, JobHandle dependsOn = default(JobHandle)) { var archetypeCount = matchingArchetypes.Count; @@ -239,21 +239,21 @@ public static NativeArray CreateArchetypeChunkArray(MatchingArch } /// - /// Creates a NativeArray containing the entities in a given ComponentGroup. + /// Creates a NativeArray containing the entities in a given EntityQuery. /// /// List of matching archetypes. /// Allocator to use for the array. /// An atomic safety handle required by GatherEntitiesJob so it can call GetNativeArray() on chunks. - /// ComponentGroup to gather entities from. - /// ComponentGroupFilter for calculating the length of the output array. + /// EntityQuery to gather entities from. + /// EntityQueryFilter for calculating the length of the output array. /// Handle to the GatherEntitiesJob job used to fill the output array. /// Handle to a job this GatherEntitiesJob must wait on. - /// NativeArray of the entities in a given ComponentGroup. + /// NativeArray of the entities in a given EntityQuery. public static NativeArray CreateEntityArray(MatchingArchetypeList matchingArchetypes, Allocator allocator, ArchetypeChunkEntityType type, - ComponentGroup componentGroup, - ref ComponentGroupFilter filter, + EntityQuery entityQuery, + ref EntityQueryFilter filter, out JobHandle jobHandle, JobHandle dependsOn) @@ -265,7 +265,7 @@ public static NativeArray CreateEntityArray(MatchingArchetypeList matchi EntityType = type, Entities = new NativeArray(entityCount, allocator) }; - jobHandle = job.Schedule(componentGroup, dependsOn); + jobHandle = job.Schedule(entityQuery, dependsOn); return job.Entities; } @@ -273,8 +273,8 @@ public static NativeArray CreateEntityArray(MatchingArchetypeList matchi public static NativeArray CreateComponentDataArray(MatchingArchetypeList matchingArchetypes, Allocator allocator, ArchetypeChunkComponentType type, - ComponentGroup componentGroup, - ref ComponentGroupFilter filter, + EntityQuery entityQuery, + ref EntityQueryFilter filter, out JobHandle jobHandle, JobHandle dependsOn) where T :struct, IComponentData @@ -286,7 +286,7 @@ public static NativeArray CreateComponentDataArray(MatchingArchetypeList m ComponentData = new NativeArray(entityCount, allocator), ComponentType = type }; - jobHandle = job.Schedule(componentGroup, dependsOn); + jobHandle = job.Schedule(entityQuery, dependsOn); return job.ComponentData; } @@ -294,8 +294,8 @@ public static NativeArray CreateComponentDataArray(MatchingArchetypeList m public static void CopyFromComponentDataArray(MatchingArchetypeList matchingArchetypes, NativeArray componentDataArray, ArchetypeChunkComponentType type, - ComponentGroup componentGroup, - ref ComponentGroupFilter filter, + EntityQuery entityQuery, + ref EntityQueryFilter filter, out JobHandle jobHandle, JobHandle dependsOn) where T :struct, IComponentData @@ -305,16 +305,16 @@ public static void CopyFromComponentDataArray(MatchingArchetypeList matchingA ComponentData = componentDataArray, ComponentType = type }; - jobHandle = job.Schedule(componentGroup, dependsOn); + jobHandle = job.Schedule(entityQuery, dependsOn); } /// /// Total number of entities contained in a given MatchingArchetype list. /// /// List of matching archetypes. - /// ComponentGroupFilter to use when calculating total number of entities. + /// EntityQueryFilter to use when calculating total number of entities. /// Number of entities - public static int CalculateLength(MatchingArchetypeList matchingArchetypes, ref ComponentGroupFilter filter) + public static int CalculateLength(MatchingArchetypeList matchingArchetypes, ref EntityQueryFilter filter) { var filterCopy = filter; // Necessary to avoid a nasty compiler error cause by fixed buffer types @@ -342,10 +342,10 @@ public static int CalculateLength(MatchingArchetypeList matchingArchetypes, ref if (filter.Type == FilterType.SharedComponent) { - var indexInComponentGroup0 = filterCopy.Shared.IndexInComponentGroup[0]; + var indexInEntityQuery0 = filterCopy.Shared.IndexInEntityQuery[0]; var sharedComponentIndex0 = filterCopy.Shared.SharedComponentIndex[0]; var componentIndexInChunk0 = - match->IndexInArchetype[indexInComponentGroup0] - archetype->FirstSharedComponent; + match->IndexInArchetype[indexInEntityQuery0] - archetype->FirstSharedComponent; var sharedComponents0 = archetype->Chunks.GetSharedComponentValueArrayForType(componentIndexInChunk0); @@ -359,10 +359,10 @@ public static int CalculateLength(MatchingArchetypeList matchingArchetypes, ref } else { - var indexInComponentGroup1 = filterCopy.Shared.IndexInComponentGroup[1]; + var indexInEntityQuery1 = filterCopy.Shared.IndexInEntityQuery[1]; var sharedComponentIndex1 = filterCopy.Shared.SharedComponentIndex[1]; var componentIndexInChunk1 = - match->IndexInArchetype[indexInComponentGroup1] - archetype->FirstSharedComponent; + match->IndexInArchetype[indexInEntityQuery1] - archetype->FirstSharedComponent; var sharedComponents1 = archetype->Chunks.GetSharedComponentValueArrayForType(componentIndexInChunk1); @@ -376,8 +376,8 @@ public static int CalculateLength(MatchingArchetypeList matchingArchetypes, ref } else { - var indexInComponentGroup0 = filterCopy.Changed.IndexInComponentGroup[0]; - var componentIndexInChunk0 = match->IndexInArchetype[indexInComponentGroup0]; + var indexInEntityQuery0 = filterCopy.Changed.IndexInEntityQuery[0]; + var componentIndexInChunk0 = match->IndexInArchetype[indexInEntityQuery0]; var changeVersions0 = archetype->Chunks.GetChangeVersionArrayForType(componentIndexInChunk0); var requiredVersion = filter.RequiredChangeVersion; @@ -391,8 +391,8 @@ public static int CalculateLength(MatchingArchetypeList matchingArchetypes, ref } else { - var indexInComponentGroup1 = filterCopy.Changed.IndexInComponentGroup[1]; - var componentIndexInChunk1 = match->IndexInArchetype[indexInComponentGroup1]; + var indexInEntityQuery1 = filterCopy.Changed.IndexInEntityQuery[1]; + var componentIndexInChunk1 = match->IndexInArchetype[indexInEntityQuery1]; var changeVersions1 = archetype->Chunks.GetChangeVersionArrayForType(componentIndexInChunk1); @@ -550,16 +550,16 @@ public bool RequiresFilter() return m_Filter.RequiresMatchesFilter; } - public int GetIndexInArchetypeFromCurrentChunk(int indexInComponentGroup) + public int GetIndexInArchetypeFromCurrentChunk(int indexInEntityQuery) { - return m_CurrentMatchingArchetype->IndexInArchetype[indexInComponentGroup]; + return m_CurrentMatchingArchetype->IndexInArchetype[indexInEntityQuery]; } - public void UpdateCacheToCurrentChunk(out ComponentChunkCache cache, bool isWriting, int indexInComponentGroup) + public void UpdateCacheToCurrentChunk(out ComponentChunkCache cache, bool isWriting, int indexInEntityQuery) { var archetype = m_CurrentMatchingArchetype->Archetype; - int indexInArchetype = m_CurrentMatchingArchetype->IndexInArchetype[indexInComponentGroup]; + int indexInArchetype = m_CurrentMatchingArchetype->IndexInArchetype[indexInEntityQuery]; cache.CachedBeginIndex = m_CurrentChunkEntityIndex + m_CurrentArchetypeEntityIndex; cache.CachedEndIndex = cache.CachedBeginIndex + (*m_CurrentChunk)->Count; @@ -601,23 +601,23 @@ public void GetCurrentChunkRange(out int beginIndex, out int endIndex) return chunk->Buffer + archetype->Offsets[indexInArchetype]; } - public void* GetCurrentChunkComponentDataPtr(bool isWriting, int indexInComponentGroup) + public void* GetCurrentChunkComponentDataPtr(bool isWriting, int indexInEntityQuery) { - int indexInArchetype = m_CurrentMatchingArchetype->IndexInArchetype[indexInComponentGroup]; + int indexInArchetype = m_CurrentMatchingArchetype->IndexInArchetype[indexInEntityQuery]; return GetChunkComponentDataPtr(*m_CurrentChunk, isWriting, indexInArchetype, m_GlobalSystemVersion); } public void UpdateChangeVersion() { - int indexInArchetype = m_CurrentMatchingArchetype->IndexInArchetype[IndexInComponentGroup]; + int indexInArchetype = m_CurrentMatchingArchetype->IndexInArchetype[IndexInEntityQuery]; (*m_CurrentChunk)->SetChangeVersion(indexInArchetype, m_GlobalSystemVersion); } public void MoveToEntityIndexAndUpdateCache(int index, out ComponentChunkCache cache, bool isWriting) { - Assert.IsTrue(-1 != IndexInComponentGroup); + Assert.IsTrue(-1 != IndexInEntityQuery); MoveToEntityIndex(index); - UpdateCacheToCurrentChunk(out cache, isWriting, IndexInComponentGroup); + UpdateCacheToCurrentChunk(out cache, isWriting, IndexInEntityQuery); } internal ArchetypeChunk GetCurrentChunk() @@ -712,7 +712,7 @@ internal int GetIndexOfFirstEntityInCurrentChunk() return index; } - internal static JobHandle PreparePrefilteredChunkLists(int unfilteredChunkCount, MatchingArchetypeList archetypes, ComponentGroupFilter filter, JobHandle dependsOn, ScheduleMode mode, out NativeArray prefilterDataArray, out void* deferredCountData) + internal static JobHandle PreparePrefilteredChunkLists(int unfilteredChunkCount, MatchingArchetypeList archetypes, EntityQueryFilter filter, JobHandle dependsOn, ScheduleMode mode, out NativeArray prefilterDataArray, out void* deferredCountData) { // Allocate one buffer for all prefilter data and distribute it // We keep the full buffer as a "dummy array" so we can deallocate it later with [DeallocateOnJobCompletion] @@ -764,5 +764,13 @@ internal static JobHandle PreparePrefilteredChunkLists(int unfilteredChunkCount, return prefilterHandle; } + + internal static void UnpackPrefilterData(NativeArray prefilterData, out ArchetypeChunk* chunks, out int* entityOffsets, out int filteredChunkCount) + { + chunks = (ArchetypeChunk*) prefilterData.GetUnsafePtr(); + + filteredChunkCount = *(int*)((byte*) prefilterData.GetUnsafePtr() + prefilterData.Length - sizeof(int)); + entityOffsets = (int*) (chunks + filteredChunkCount); + } } } diff --git a/Unity.Entities/Iterators/ComponentDataArray.cs b/Unity.Entities/Iterators/ComponentDataArray.cs deleted file mode 100644 index ac3fbcfe..00000000 --- a/Unity.Entities/Iterators/ComponentDataArray.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System; -using System.Diagnostics; -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; - -namespace Unity.Entities -{ - [NativeContainer] - [NativeContainerSupportsMinMaxWriteRestriction] - [Obsolete("ComponentDataArray is deprecated. Use IJobProcessComponentData or ComponentGroup ToComponentDataArray/CopyFromComponentDataArray APIs instead.")] - public unsafe struct ComponentDataArray where T : struct, IComponentData - { - private ComponentChunkIterator m_Iterator; - private ComponentChunkCache m_Cache; - - private readonly int m_Length; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private readonly int m_MinIndex; - private readonly int m_MaxIndex; - private readonly AtomicSafetyHandle m_Safety; -#endif - public int Length => m_Length; - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - internal ComponentDataArray(ComponentChunkIterator iterator, int length, AtomicSafetyHandle safety) -#else - internal ComponentDataArray(ComponentChunkIterator iterator, int length) -#endif - { - m_Iterator = iterator; - m_Cache = default(ComponentChunkCache); - - m_Length = length; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_MinIndex = 0; - m_MaxIndex = length - 1; - m_Safety = safety; -#endif - } - - internal void* GetUnsafeChunkPtr(int startIndex, int maxCount, out int actualCount, bool isWriting) - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - GetUnsafeChunkPtrCheck(startIndex, maxCount); -#endif - - m_Iterator.MoveToEntityIndexAndUpdateCache(startIndex, out m_Cache, isWriting); - - void* ptr = (byte*) m_Cache.CachedPtr + startIndex * m_Cache.CachedSizeOf; - actualCount = Math.Min(maxCount, m_Cache.CachedEndIndex - startIndex); - - return ptr; - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] - private void GetUnsafeChunkPtrCheck(int startIndex, int maxCount) - { - AtomicSafetyHandle.CheckReadAndThrow(m_Safety); - - if (startIndex < m_MinIndex) - FailOutOfRangeError(startIndex); - else if (startIndex + maxCount > m_MaxIndex + 1) - FailOutOfRangeError(startIndex + maxCount); - } -#endif - - public NativeArray GetChunkArray(int startIndex, int maxCount) - { - int count; - //@TODO: How should we declare read / write here? - var ptr = GetUnsafeChunkPtr(startIndex, maxCount, out count, true); - - var arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(ptr, count, Allocator.Invalid); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref arr, m_Safety); -#endif - - return arr; - } - - public void CopyTo(NativeSlice dst, int startIndex = 0) - { - var copiedCount = 0; - while (copiedCount < dst.Length) - { - var chunkArray = GetChunkArray(startIndex + copiedCount, dst.Length - copiedCount); - dst.Slice(copiedCount, chunkArray.Length).CopyFrom(chunkArray); - - copiedCount += chunkArray.Length; - } - } - - public T this[int index] - { - get - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - GetValueCheck(index); -#endif - - if (index < m_Cache.CachedBeginIndex || index >= m_Cache.CachedEndIndex) - m_Iterator.MoveToEntityIndexAndUpdateCache(index, out m_Cache, false); - - return UnsafeUtility.ReadArrayElement(m_Cache.CachedPtr, index); - } - - set - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - SetValueCheck(index); -#endif - - if (index < m_Cache.CachedBeginIndex || index >= m_Cache.CachedEndIndex) - m_Iterator.MoveToEntityIndexAndUpdateCache(index, out m_Cache, true); - else if (!m_Cache.IsWriting) - { - m_Cache.IsWriting = true; - m_Iterator.UpdateChangeVersion(); - } - - UnsafeUtility.WriteArrayElement(m_Cache.CachedPtr, index, value); - } - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] - private void SetValueCheck(int index) - { - AtomicSafetyHandle.CheckWriteAndThrow(m_Safety); - if (index < m_MinIndex || index > m_MaxIndex) - FailOutOfRangeError(index); - } -#endif - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] - private void GetValueCheck(int index) - { - AtomicSafetyHandle.CheckReadAndThrow(m_Safety); - if (index < m_MinIndex || index > m_MaxIndex) - FailOutOfRangeError(index); - } -#endif - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] - private void FailOutOfRangeError(int index) - { - //@TODO: Make error message utility and share with NativeArray... - if (index < Length && (m_MinIndex != 0 || m_MaxIndex != Length - 1)) - throw new IndexOutOfRangeException( - $"Index {index} is out of restricted IJobParallelFor range [{m_MinIndex}...{m_MaxIndex}] in ReadWriteBuffer.\n" + - "ReadWriteBuffers are restricted to only read & write the element at the job index. " + - "You can use double buffering strategies to avoid race conditions due to " + - "reading & writing in parallel to the same elements from a job."); - - throw new IndexOutOfRangeException($"Index {index} is out of range of '{Length}' Length."); - } -#endif - } -} diff --git a/Unity.Entities/Iterators/ComponentDataArray.cs.meta b/Unity.Entities/Iterators/ComponentDataArray.cs.meta deleted file mode 100644 index 85a8eb73..00000000 --- a/Unity.Entities/Iterators/ComponentDataArray.cs.meta +++ /dev/null @@ -1,13 +0,0 @@ -fileFormatVersion: 2 -guid: e899c8ac6ed7b40afacf51d570844e48 -timeCreated: 1504713176 -licenseType: Pro -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Iterators/ComponentGroup.cs.meta b/Unity.Entities/Iterators/ComponentGroup.cs.meta deleted file mode 100644 index 08a41540..00000000 --- a/Unity.Entities/Iterators/ComponentGroup.cs.meta +++ /dev/null @@ -1,13 +0,0 @@ -fileFormatVersion: 2 -guid: e5e6e5c15d4a044a699fce82fa67186b -timeCreated: 1506266985 -licenseType: Pro -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Iterators/ComponentGroup.obsolete.cs b/Unity.Entities/Iterators/ComponentGroup.obsolete.cs new file mode 100644 index 00000000..0f717a23 --- /dev/null +++ b/Unity.Entities/Iterators/ComponentGroup.obsolete.cs @@ -0,0 +1,275 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using Unity.Burst; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Jobs; + +namespace Unity.Entities +{ + public sealed unsafe partial class EntityManager + { + // The script updater has some bugs that make it unable to handle these as automatic updates + [Obsolete("CreateComponentGroup has been renamed to CreateEntityQuery.", true)] + public ComponentGroup CreateComponentGroup(params ComponentType[] requiredComponents) + { + throw new NotImplementedException(); + } + + [Obsolete("CreateComponentGroup has been renamed to CreateEntityQuery.", true)] + public ComponentGroup CreateComponentGroup(params EntityArchetypeQuery[] queriesDesc) + { + throw new NotImplementedException(); + } + + [Obsolete("UniversalGroup has been renamed to UniversalQuery. (UnityUpgradable) -> UniversalQuery", true)] + public EntityQuery UniversalGroup => null; + } + + [Obsolete("EntityArchetypeQuery has been renamed to EntityQueryDesc. (UnityUpgradable) -> EntityQueryDesc", true)] + public class EntityArchetypeQuery + { + public ComponentType[] Any = null; + public ComponentType[] None = null; + public ComponentType[] All = null; + public EntityArchetypeQueryOptions Options = EntityArchetypeQueryOptions.Default; + } + + [Flags] + [Obsolete("EntityArchetypeQueryOptions has been renamed to EntityQueryOptions. (UnityUpgradable) -> EntityQueryOptions", true)] + public enum EntityArchetypeQueryOptions + { + Default = 0, + IncludePrefab = 1, + IncludeDisabled = 2, + FilterWriteGroup = 4, + } + + [Obsolete("ComponentGroupExtensionsForComponentArray has been renamed to EntityQueryExtensionsForComponentArray. (UnityUpgradable) -> EntityQueryExtensionsForComponentArray", true)] + public static class ComponentGroupExtensionsForComponentArray + { + } + + [Obsolete("ComponentGroupExtensionsForTransformAccessArray has been renamed to EntityQueryExtensionsForTransformAccessArray. (UnityUpgradable) -> EntityQueryExtensionsForTransformAccessArray", true)] + public static class ComponentGroupExtensionsForTransformAccessArray + { + } + + public unsafe abstract partial class ComponentSystemBase + { + //[Obsolete("GetComponentGroup has been renamed to GetEntityQuery. (UnityUpgradable) -> GetEntityQuery(*)", true)] + [Obsolete("GetComponentGroup has been renamed to GetEntityQuery.", true)] + protected internal ComponentGroup GetComponentGroup(params ComponentType[] componentTypes) + { + throw new NotImplementedException(); + } + + //[Obsolete("GetComponentGroup has been renamed to GetEntityQuery. (UnityUpgradable) -> GetEntityQuery(*)", true)] + [Obsolete("GetComponentGroup has been renamed to GetEntityQuery.", true)] + protected ComponentGroup GetComponentGroup(NativeArray componentTypes) + { + throw new NotImplementedException(); + } + + //[Obsolete("GetComponentGroup has been renamed to GetEntityQuery. (UnityUpgradable) -> GetEntityQuery(*)", true)] + [Obsolete("GetComponentGroup has been renamed to GetEntityQuery.", true)] + protected internal ComponentGroup GetComponentGroup(params EntityArchetypeQuery[] queryDesc) + { + throw new NotImplementedException(); + } + + [Obsolete("GetComponentGroup has been renamed to GetEntityQuery.", true)] + protected internal ComponentGroup GetComponentGroup(params EntityQueryDesc[] queryDesc) + { + throw new NotImplementedException(); + } + } + +#if !UNITY_CSHARP_TINY + public static partial class JobForEachExtensions + { + [Obsolete("GetComponentGroupForIJobForEach has been renamed to GetEntityQueryForIJobForEach. (UnityUpgradable) -> GetEntityQueryForIJobForEach(*)", true)] + public static ComponentGroup GetComponentGroupForIJobForEach(this ComponentSystemBase system, + Type jobType) + { + throw new NotImplementedException(); + } + + [Obsolete("PrepareComponentGroup has been renamed to PrepareEntityQuery. (UnityUpgradable) -> PrepareEntityQuery(*)", true)] + public static void PrepareComponentGroup(this T jobData, ComponentSystemBase system) + where T : struct, JobForEachExtensions.IBaseJobForEach + { + throw new NotImplementedException(); + } + + [Obsolete("ScheduleGroup has been renamed to Schedule. (UnityUpgradable) -> Schedule(*)", true)] + public static JobHandle ScheduleGroup(this T jobData, ComponentGroup cg, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + throw new NotImplementedException(); + } + + [Obsolete("ScheduleGroupSingle has been renamed to ScheduleSingle. (UnityUpgradable) -> ScheduleSingle(*)", true)] + public static JobHandle ScheduleGroupSingle(this T jobData, ComponentGroup cg, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + throw new NotImplementedException(); + } + + [Obsolete("RunGroup has been renamed to Run. (UnityUpgradable) -> Run(*)", true)] + public static JobHandle Run(this T jobData, ComponentGroup cg, JobHandle dependsOn = default(JobHandle)) + where T : struct, IBaseJobForEach + { + throw new NotImplementedException(); + } + } +#endif + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("ComponentGroup has been renamed to EntityQuery. (UnityUpgradable) -> EntityQuery", true)] + public class ComponentGroup : IDisposable + { + public bool IsEmptyIgnoreFilter + { + get { throw new NotImplementedException(); } + } + + public int CalculateLength() + { + throw new NotImplementedException(); + } + + public NativeArray CreateArchetypeChunkArray(Allocator allocator, out JobHandle jobhandle) + { + throw new NotImplementedException(); + } + + public NativeArray CreateArchetypeChunkArray(Allocator allocator) + { + throw new NotImplementedException(); + } + + + public NativeArray ToEntityArray(Allocator allocator, out JobHandle jobhandle) + { + throw new NotImplementedException(); + } + + public NativeArray ToEntityArray(Allocator allocator) + { + throw new NotImplementedException(); + } + + public NativeArray ToComponentDataArray(Allocator allocator, out JobHandle jobhandle) + where T : struct, IComponentData + { + throw new NotImplementedException(); + } + + public NativeArray ToComponentDataArray(Allocator allocator) + where T : struct, IComponentData + { + throw new NotImplementedException(); + } + + public void CopyFromComponentDataArray(NativeArray componentDataArray) + where T : struct, IComponentData + { + throw new NotImplementedException(); + } + + public void CopyFromComponentDataArray(NativeArray componentDataArray, out JobHandle jobhandle) + where T : struct, IComponentData + { + throw new NotImplementedException(); + } + + public Entity GetSingletonEntity() + { + throw new NotImplementedException(); + } + + public T GetSingleton() + where T : struct, IComponentData + { + throw new NotImplementedException(); + } + + public void SetSingleton(T value) + where T : struct, IComponentData + { + throw new NotImplementedException(); + } + + public bool CompareComponents(ComponentType[] componentTypes) + { + throw new NotImplementedException(); + } + + public bool CompareComponents(NativeArray componentTypes) + { + throw new NotImplementedException(); + } + + public bool CompareQuery(EntityArchetypeQuery[] queryDesc) + { + throw new NotImplementedException(); + } + + public void ResetFilter() + { + throw new NotImplementedException(); + } + + public void SetFilter(SharedComponent1 sharedComponent1) + where SharedComponent1 : struct, ISharedComponentData + { + throw new NotImplementedException(); + } + + public void SetFilter(SharedComponent1 sharedComponent1, + SharedComponent2 sharedComponent2) + where SharedComponent1 : struct, ISharedComponentData + where SharedComponent2 : struct, ISharedComponentData + { + throw new NotImplementedException(); + } + + public void SetFilterChanged(ComponentType componentType) + { + throw new NotImplementedException(); + } + + public void SetFilterChanged(ComponentType[] componentType) + { + throw new NotImplementedException(); + } + + public void CompleteDependency() + { + throw new NotImplementedException(); + } + + public JobHandle GetDependency() + { + throw new NotImplementedException(); + } + + public void AddDependency(JobHandle job) + { + throw new NotImplementedException(); + } + + public int GetCombinedComponentOrderVersion() + { + throw new NotImplementedException(); + } + + public void Dispose() + { + throw new NotImplementedException(); + } + } +} diff --git a/Unity.Entities/Iterators/ComponentGroup.obsolete.cs.meta b/Unity.Entities/Iterators/ComponentGroup.obsolete.cs.meta new file mode 100644 index 00000000..bf03362b --- /dev/null +++ b/Unity.Entities/Iterators/ComponentGroup.obsolete.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f44190df1d8f7846866e1f2cce00448 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/Iterators/ComponentGroupArray.cs b/Unity.Entities/Iterators/ComponentGroupArray.cs deleted file mode 100644 index 414d48b6..00000000 --- a/Unity.Entities/Iterators/ComponentGroupArray.cs +++ /dev/null @@ -1,417 +0,0 @@ -#if !UNITY_CSHARP_TINY -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using Unity.Assertions; -using Unity.Burst; -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; - -namespace Unity.Entities -{ - internal class ComponentGroupArrayStaticCache - { - public readonly Type CachedType; - internal readonly int ComponentCount; - internal readonly int ComponentDataCount; - internal readonly int[] ComponentFieldOffsets; - internal readonly ComponentGroup ComponentGroup; - - internal readonly ComponentType[] ComponentTypes; - internal readonly ComponentJobSafetyManager SafetyManager; - - public ComponentGroupArrayStaticCache(Type type, EntityManager entityManager, ComponentSystemBase system) - { - var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); - - var componentFieldOffsetsBuilder = new List(); - var componentTypesBuilder = new List(); - - var componentDataFieldOffsetsBuilder = new List(); - var componentDataTypesBuilder = new List(); - - var subtractiveComponentTypesBuilder = new List(); - - foreach (var field in fields) - { - var fieldType = field.FieldType; - var offset = UnsafeUtility.GetFieldOffset(field); - - if (fieldType.IsPointer) - { - var isReadOnly = field.GetCustomAttributes(typeof(ReadOnlyAttribute), true).Length != 0; - var accessMode = - isReadOnly ? ComponentType.AccessMode.ReadOnly : ComponentType.AccessMode.ReadWrite; - - var elementType = fieldType.GetElementType(); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (!typeof(IComponentData).IsAssignableFrom(elementType) && elementType != typeof(Entity)) - throw new ArgumentException( - $"{type}.{field.Name} is a pointer type but not a IComponentData. Only IComponentData or Entity may be a pointer type for enumeration."); -#endif - componentDataFieldOffsetsBuilder.Add(offset); - componentDataTypesBuilder.Add(new ComponentType(elementType, accessMode)); - } - else if (TypeManager.UnityEngineComponentType?.IsAssignableFrom(fieldType) ?? false) - { - componentFieldOffsetsBuilder.Add(offset); - componentTypesBuilder.Add(fieldType); - } - else if (fieldType.IsGenericType && - fieldType.GetGenericTypeDefinition() == typeof(ExcludeComponent<>)) - { - subtractiveComponentTypesBuilder.Add(ComponentType.Exclude(fieldType.GetGenericArguments()[0])); - } -#if ENABLE_UNITY_COLLECTIONS_CHECKS - else if (typeof(IComponentData).IsAssignableFrom(fieldType)) - { - throw new ArgumentException( - $"{type}.{field.Name} must be an unsafe pointer to the {fieldType}. Like this: {fieldType}* {field.Name};"); - } - else - { - throw new ArgumentException($"{type}.{field.Name} can not be used in a component enumerator"); - } -#endif - } -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (componentTypesBuilder.Count + componentDataTypesBuilder.Count > ComponentGroupArrayData.kMaxStream) - throw new ArgumentException( - $"{type} has too many component references. A ComponentGroup Array can have up to {ComponentGroupArrayData.kMaxStream}."); -#endif - - ComponentDataCount = componentDataTypesBuilder.Count; - ComponentCount = componentTypesBuilder.Count; - - componentDataTypesBuilder.AddRange(componentTypesBuilder); - componentDataTypesBuilder.AddRange(subtractiveComponentTypesBuilder); - ComponentTypes = componentDataTypesBuilder.ToArray(); - - componentDataFieldOffsetsBuilder.AddRange(componentFieldOffsetsBuilder); - ComponentFieldOffsets = componentDataFieldOffsetsBuilder.ToArray(); - - ComponentGroup = system.GetComponentGroupInternal(ComponentTypes); - SafetyManager = entityManager.ComponentJobSafetyManager; - - CachedType = type; - } - } - - [NativeContainer] - [NativeContainerSupportsMinMaxWriteRestriction] - internal unsafe struct ComponentGroupArrayData - { - public const int kMaxStream = 6; - - private struct ComponentGroupStream - { - public byte* CachedPtr; - public int SizeOf; - public ushort FieldOffset; - public ushort TypeIndexInArchetype; - } - - private fixed byte m_Caches[16 * kMaxStream]; - - private readonly int m_ComponentDataCount; - private readonly int m_ComponentCount; - - // The following 3 fields must not be renamed, unless JobReflectionData.cpp is changed accordingly. - // TODO: make JobDebugger logic more solid, either by using codegen proxies or attributes. - public readonly int m_Length; - public readonly int m_MinIndex; - public readonly int m_MaxIndex; - - public int CacheBeginIndex; - public int CacheEndIndex; - - private ComponentChunkIterator m_ChunkIterator; - private fixed int m_IndexInComponentGroup[kMaxStream]; - private fixed bool m_IsWriting[kMaxStream]; - - // The following fields must not be renamed, unless JobReflectionData.cpp is changed accordingly. - // TODO: make JobDebugger logic more solid, either by using codegen proxies or attributes. -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private readonly int m_SafetyReadOnlyCount; - private readonly int m_SafetyReadWriteCount; -#pragma warning disable 414 - private AtomicSafetyHandle m_Safety0; - private AtomicSafetyHandle m_Safety1; - private AtomicSafetyHandle m_Safety2; - private AtomicSafetyHandle m_Safety3; - private AtomicSafetyHandle m_Safety4; - private AtomicSafetyHandle m_Safety5; -#pragma warning restore -#endif - - [NativeSetClassTypeToNullOnSchedule] private readonly ArchetypeManager m_ArchetypeManager; - - public ComponentGroupArrayData(ComponentGroupArrayStaticCache staticCache) - { - var length = staticCache.ComponentGroup.CalculateLength(); - m_ChunkIterator = staticCache.ComponentGroup.GetComponentChunkIterator(); - m_ChunkIterator.IndexInComponentGroup = 0; - - m_Length = length; - m_MinIndex = 0; - m_MaxIndex = length - 1; - - CacheBeginIndex = 0; - CacheEndIndex = 0; - m_ArchetypeManager = staticCache.ComponentGroup.ArchetypeManager; - - m_ComponentDataCount = staticCache.ComponentDataCount; - m_ComponentCount = staticCache.ComponentCount; - - fixed (int* indexInComponentGroup = m_IndexInComponentGroup) - fixed (byte* cacheBytes = m_Caches) - fixed (bool* isWriting = m_IsWriting) - { - var streams = (ComponentGroupStream*) cacheBytes; - - for (var i = 0; i < staticCache.ComponentDataCount + staticCache.ComponentCount; i++) - { - indexInComponentGroup[i] = staticCache.ComponentGroup.GetIndexInComponentGroup(staticCache.ComponentTypes[i].TypeIndex); - streams[i].FieldOffset = (ushort) staticCache.ComponentFieldOffsets[i]; - isWriting[i] = staticCache.ComponentTypes[i].AccessModeType == ComponentType.AccessMode.ReadWrite; - } - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_Safety0 = new AtomicSafetyHandle(); - m_Safety1 = new AtomicSafetyHandle(); - m_Safety2 = new AtomicSafetyHandle(); - m_Safety3 = new AtomicSafetyHandle(); - m_Safety4 = new AtomicSafetyHandle(); - m_Safety5 = new AtomicSafetyHandle(); - Assert.AreEqual(6, kMaxStream); - - m_SafetyReadWriteCount = 0; - m_SafetyReadOnlyCount = 0; - var safetyManager = staticCache.SafetyManager; - fixed (AtomicSafetyHandle* safety = &m_Safety0) - { - for (var i = 0; i != staticCache.ComponentTypes.Length; i++) - { - var type = staticCache.ComponentTypes[i]; - if (type.IsZeroSized || type.AccessModeType != ComponentType.AccessMode.ReadOnly) - continue; - - safety[m_SafetyReadOnlyCount] = safetyManager.GetSafetyHandle(type.TypeIndex, true); - m_SafetyReadOnlyCount++; - } - - for (var i = 0; i != staticCache.ComponentTypes.Length; i++) - { - var type = staticCache.ComponentTypes[i]; - if (type.IsZeroSized || type.AccessModeType != ComponentType.AccessMode.ReadWrite) - continue; - - safety[m_SafetyReadOnlyCount + m_SafetyReadWriteCount] = - safetyManager.GetSafetyHandle(type.TypeIndex, false); - m_SafetyReadWriteCount++; - } - } -#endif - } - - public void UpdateCache(int index) - { - ComponentChunkCache cache; - - m_ChunkIterator.MoveToEntityIndex(index); - - fixed (int* indexInComponentGroup = m_IndexInComponentGroup) - fixed (byte* cacheBytes = m_Caches) - fixed (bool* isWriting = m_IsWriting) - { - var streams = (ComponentGroupStream*) cacheBytes; - var totalCount = m_ComponentDataCount + m_ComponentCount; - for (var i = 0; i < totalCount; i++) - { - m_ChunkIterator.UpdateCacheToCurrentChunk(out cache, isWriting[i], indexInComponentGroup[i]); - CacheBeginIndex = cache.CachedBeginIndex; - CacheEndIndex = cache.CachedEndIndex; - - int indexInArcheType = m_ChunkIterator.GetIndexInArchetypeFromCurrentChunk(indexInComponentGroup[i]); - - streams[i].SizeOf = cache.CachedSizeOf; - streams[i].CachedPtr = (byte*) cache.CachedPtr; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (indexInArcheType > ushort.MaxValue) - throw new ArgumentException( - $"There is a maximum of {ushort.MaxValue} components on one entity."); -#endif - streams[i].TypeIndexInArchetype = (ushort) indexInArcheType; - } - } - } - - public void CheckAccess() - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - fixed (AtomicSafetyHandle* safety = &m_Safety0) - { - for (var i = 0; i < m_SafetyReadOnlyCount; i++) - AtomicSafetyHandle.CheckReadAndThrow(safety[i]); - - for (var i = m_SafetyReadOnlyCount; i < m_SafetyReadOnlyCount + m_SafetyReadWriteCount; i++) - AtomicSafetyHandle.CheckWriteAndThrow(safety[i]); - } -#endif - } - - public void PatchPtrs(int index, byte* valuePtr) - { - fixed (byte* cacheBytes = m_Caches) - { - var streams = (ComponentGroupStream*) cacheBytes; - for (var i = 0; i != m_ComponentDataCount; i++) - { - var componentPtr = (void*) (streams[i].CachedPtr + streams[i].SizeOf * index); - var valuePtrOffsetted = (void**) (valuePtr + streams[i].FieldOffset); - - *valuePtrOffsetted = componentPtr; - } - } - } - - [BurstDiscard] - public void PatchManagedPtrs(int index, byte* valuePtr) - { - fixed (byte* cacheBytes = m_Caches) - { - var streams = (ComponentGroupStream*) cacheBytes; - for (var i = m_ComponentDataCount; i != m_ComponentDataCount + m_ComponentCount; i++) - { - var component = m_ChunkIterator.GetManagedObject(m_ArchetypeManager, - streams[i].TypeIndexInArchetype, CacheBeginIndex, index); - var valuePtrOffsetted = valuePtr + streams[i].FieldOffset; - UnsafeUtility.CopyObjectAddressToPtr(component, valuePtrOffsetted); - } - } - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - [BurstDiscard] - public void FailOutOfRangeError(int index) - { - /* - //@TODO: Make error message utility and share with NativeArray... - if (index < Length && (m_MinIndex != 0 || m_MaxIndex != Length - 1)) - throw new IndexOutOfRangeException(string.Format( - "Index {0} is out of restricted component group array range [{1}...{2}] in ReadWriteBuffer.\n" + - "ReadWriteBuffers are restricted to only read & write the element at the job index. " + - "You can use double buffering strategies to avoid race conditions due to " + - "reading & writing in parallel to the same elements from a job.", - index, m_MinIndex, m_MaxIndex)); -*/ - throw new IndexOutOfRangeException($"Index {index} is out of range of '{m_Length}' Length."); - } -#endif - } - - [Obsolete("ComponentGroupArray has been deprecated. Use ComponentSystem.ForEach to access managed components.")] - public struct ComponentGroupArray : IDisposable where T : struct - { - internal ComponentGroupArrayData m_Data; - - internal ComponentGroupArray(ComponentGroupArrayStaticCache cache) - { - m_Data = new ComponentGroupArrayData(cache); - } - - public void Dispose() - { - } - - public int Length => m_Data.m_Length; - - public unsafe T this[int index] - { - get - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_Data.CheckAccess(); - if (index < m_Data.m_MinIndex || index > m_Data.m_MaxIndex) - m_Data.FailOutOfRangeError(index); -#endif - - if (index < m_Data.CacheBeginIndex || index >= m_Data.CacheEndIndex) - m_Data.UpdateCache(index); - - var value = default(T); - var valuePtr = (byte*) UnsafeUtility.AddressOf(ref value); - m_Data.PatchPtrs(index, valuePtr); - m_Data.PatchManagedPtrs(index, valuePtr); - return value; - } - } - - public ComponentGroupEnumerator GetEnumerator() - { - return new ComponentGroupEnumerator(m_Data); - } - - public unsafe struct ComponentGroupEnumerator : IEnumerator where U : struct - { - private ComponentGroupArrayData m_Data; - private int m_Index; - - internal ComponentGroupEnumerator(ComponentGroupArrayData arrayData) - { - m_Data = arrayData; - m_Index = -1; - } - - public void Dispose() - { - } - - public bool MoveNext() - { - m_Index++; - - if (m_Index >= m_Data.CacheBeginIndex && m_Index < m_Data.CacheEndIndex) - return true; - - if (m_Index >= m_Data.m_Length) - return false; - - m_Data.CheckAccess(); - m_Data.UpdateCache(m_Index); - - return true; - } - - public void Reset() - { - m_Index = -1; - } - - public U Current - { - get - { - m_Data.CheckAccess(); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - if (m_Index < m_Data.m_MinIndex || m_Index > m_Data.m_MaxIndex) - m_Data.FailOutOfRangeError(m_Index); -#endif - - var value = default(U); - var valuePtr = (byte*) UnsafeUtility.AddressOf(ref value); - m_Data.PatchPtrs(m_Index, valuePtr); - m_Data.PatchManagedPtrs(m_Index, valuePtr); - return value; - } - } - - object IEnumerator.Current => Current; - } - } -} -#endif diff --git a/Unity.Entities/Iterators/ComponentGroupArray.cs.meta b/Unity.Entities/Iterators/ComponentGroupArray.cs.meta deleted file mode 100644 index e3bcd5e2..00000000 --- a/Unity.Entities/Iterators/ComponentGroupArray.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b2149666441034bd2be2b403b9bc5dbd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Iterators/DynamicBuffer.cs b/Unity.Entities/Iterators/DynamicBuffer.cs index 99b1081b..d99e5981 100644 --- a/Unity.Entities/Iterators/DynamicBuffer.cs +++ b/Unity.Entities/Iterators/DynamicBuffer.cs @@ -38,6 +38,9 @@ internal DynamicBuffer(BufferHeader* header) } #endif + /// + /// The number of elements the buffer holds. + /// public int Length { get @@ -47,6 +50,9 @@ public int Length } } + /// + /// The number of elements the buffer can hold. + /// public int Capacity { get @@ -116,11 +122,24 @@ public T this [int index] } } + /// + /// Increases the buffer capacity and length. + /// + /// The new length of the buffer. public void ResizeUninitialized(int length) + { + Reserve(length); + m_Buffer->Length = length; + } + + /// + /// Increases the buffer capacity without increasing its length. + /// + /// The new buffer capacity. + public void Reserve(int length) { CheckWriteAccessAndInvalidateArrayAliases(); BufferHeader.EnsureCapacity(m_Buffer, length, UnsafeUtility.SizeOf(), UnsafeUtility.AlignOf(), BufferHeader.TrashMode.RetainOldData); - m_Buffer->Length = length; } public void Clear() @@ -143,8 +162,8 @@ public void TrimExcess() int elemSize = UnsafeUtility.SizeOf(); int elemAlign = UnsafeUtility.AlignOf(); - byte* newPtr = (byte*) UnsafeUtility.Malloc(elemSize * length, elemAlign, Allocator.Persistent); - UnsafeUtility.MemCpy(newPtr, oldPtr, elemSize * length); + byte* newPtr = (byte*) UnsafeUtility.Malloc((long)elemSize * length, elemAlign, Allocator.Persistent); + UnsafeUtility.MemCpy(newPtr, oldPtr, (long)elemSize * length); m_Buffer->Capacity = length; m_Buffer->Pointer = newPtr; @@ -168,7 +187,7 @@ public void Insert(int index, T elem) CheckBounds(index); //CheckBounds after ResizeUninitialized since index == length is allowed int elemSize = UnsafeUtility.SizeOf(); byte* basePtr = BufferHeader.GetElementPointer(m_Buffer); - UnsafeUtility.MemMove(basePtr + (index + 1) * elemSize, basePtr + index * elemSize, elemSize * (length - index)); + UnsafeUtility.MemMove(basePtr + (index + 1) * elemSize, basePtr + index * elemSize, (long)elemSize * (length - index)); this[index] = elem; } @@ -180,7 +199,7 @@ public void AddRange(NativeArray newElems) ResizeUninitialized(oldLength + newElems.Length); byte* basePtr = BufferHeader.GetElementPointer(m_Buffer); - UnsafeUtility.MemCpy(basePtr + oldLength * elemSize, newElems.GetUnsafeReadOnlyPtr(), elemSize * newElems.Length); + UnsafeUtility.MemCpy(basePtr + (long)oldLength * elemSize, newElems.GetUnsafeReadOnlyPtr(), (long)elemSize * newElems.Length); } public void RemoveRange(int index, int count) @@ -191,7 +210,7 @@ public void RemoveRange(int index, int count) int elemSize = UnsafeUtility.SizeOf(); byte* basePtr = BufferHeader.GetElementPointer(m_Buffer); - UnsafeUtility.MemMove(basePtr + index * elemSize, basePtr + (index + count) * elemSize, elemSize * (Length - count - index)); + UnsafeUtility.MemMove(basePtr + index * elemSize, basePtr + (index + count) * elemSize, (long)elemSize * (Length - count - index)); m_Buffer->Length -= count; } @@ -243,7 +262,11 @@ public NativeArray ToNativeArray() return AsNativeArray(); } - + public NativeArray ToNativeArray(Allocator allocator) + { + return new NativeArray(AsNativeArray(), allocator); + } + public void CopyFrom(NativeArray v) { ResizeUninitialized(v.Length); @@ -252,7 +275,7 @@ public void CopyFrom(NativeArray v) public void CopyFrom(T[] v) { -#if UNITY_CSHARP_TINY +#if NET_DOTS Clear(); foreach (var d in v) { diff --git a/Unity.Entities/Iterators/EntityArray.cs b/Unity.Entities/Iterators/EntityArray.cs deleted file mode 100644 index 1423a473..00000000 --- a/Unity.Entities/Iterators/EntityArray.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; - -namespace Unity.Entities -{ - /// - /// Enables array-like iteration over entities in a set of chunks. - /// - [NativeContainer] - [NativeContainerIsReadOnly] - [Obsolete("EntityArray is deprecated. Use IJobProcessComponentDataWithEntity or ComponentGroup.ToEntityArray(...) instead.")] - public unsafe struct EntityArray - { - private ComponentChunkIterator m_Iterator; - private ComponentChunkCache m_Cache; - - private readonly int m_Length; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private readonly AtomicSafetyHandle m_Safety; -#endif - public int Length => m_Length; - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - internal EntityArray(ComponentChunkIterator iterator, int length, AtomicSafetyHandle safety) -#else - internal unsafe EntityArray(ComponentChunkIterator iterator, int length) -#endif - { - m_Length = length; - m_Iterator = iterator; - m_Cache = default(ComponentChunkCache); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_Safety = safety; -#endif - } - - public Entity this[int index] - { - get - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - AtomicSafetyHandle.CheckReadAndThrow(m_Safety); - if ((uint)index >= (uint)m_Length) - FailOutOfRangeError(index); -#endif - - if (index < m_Cache.CachedBeginIndex || index >= m_Cache.CachedEndIndex) - m_Iterator.MoveToEntityIndexAndUpdateCache(index, out m_Cache, false); - - return UnsafeUtility.ReadArrayElement(m_Cache.CachedPtr, index); - } - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private void FailOutOfRangeError(int index) - { - throw new IndexOutOfRangeException($"Index {index} is out of range of '{Length}' Length."); - } -#endif - - public NativeArray GetChunkArray(int startIndex, int maxCount) - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - AtomicSafetyHandle.CheckReadAndThrow(m_Safety); - - if (startIndex < 0) - FailOutOfRangeError(startIndex); - else if (startIndex + maxCount > m_Length) - FailOutOfRangeError(startIndex + maxCount); -#endif - - - m_Iterator.MoveToEntityIndexAndUpdateCache(startIndex, out m_Cache, false); - - void* ptr = (byte*) m_Cache.CachedPtr + startIndex * m_Cache.CachedSizeOf; - var count = Math.Min(maxCount, m_Cache.CachedEndIndex - startIndex); - - var arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(ptr, count, Allocator.Invalid); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref arr, m_Safety); -#endif - - return arr; - } - - public void CopyTo(NativeSlice dst, int startIndex = 0) - { - var copiedCount = 0; - while (copiedCount < dst.Length) - { - var chunkArray = GetChunkArray(startIndex + copiedCount, dst.Length - copiedCount); - dst.Slice(copiedCount, chunkArray.Length).CopyFrom(chunkArray); - - copiedCount += chunkArray.Length; - } - } - - public Entity[] ToArray() - { - var array = new Entity[Length]; - for (var i = 0; i != array.Length; i++) - array[i] = this[i]; - return array; - } - } -} diff --git a/Unity.Entities/Iterators/EntityArray.cs.meta b/Unity.Entities/Iterators/EntityArray.cs.meta deleted file mode 100644 index 3c408a56..00000000 --- a/Unity.Entities/Iterators/EntityArray.cs.meta +++ /dev/null @@ -1,13 +0,0 @@ -fileFormatVersion: 2 -guid: 5e10ee0838de946aca61081698f37214 -timeCreated: 1504806398 -licenseType: Pro -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/Iterators/EntityGroupManager.cs b/Unity.Entities/Iterators/EntityGroupManager.cs index b11ea029..c0e9f505 100644 --- a/Unity.Entities/Iterators/EntityGroupManager.cs +++ b/Unity.Entities/Iterators/EntityGroupManager.cs @@ -11,7 +11,7 @@ namespace Unity.Entities { internal unsafe class EntityGroupManager : IDisposable { - private readonly ComponentJobSafetyManager m_JobSafetyManager; + private readonly ComponentJobSafetyManager* m_JobSafetyManager; private ChunkAllocator m_GroupDataChunkAllocator; private EntityGroupDataList m_EntityGroupDatas; private NativeMultiHashMap m_EntityGroupDataCache; @@ -20,12 +20,12 @@ ref UnsafePtrList m_EntityGroupDatasUnsafePtrList { get { return ref *(UnsafePtrList*)UnsafeUtility.AddressOf(ref m_EntityGroupDatas); } } - - public EntityGroupManager(ComponentJobSafetyManager safetyManager) + + public EntityGroupManager(ComponentJobSafetyManager* safetyManager) { m_JobSafetyManager = safetyManager; m_GroupDataChunkAllocator = new ChunkAllocator(); - m_EntityGroupDataCache = new NativeMultiHashMap(1024, Allocator.Persistent); + m_EntityGroupDataCache = new NativeMultiHashMap(1024, Allocator.Persistent); } public void Dispose() @@ -49,7 +49,7 @@ public void Dispose() else allList.Add(requiredTypes[i]); } - + // NativeList.ToArray requires GC Pinning, not supported in Tiny var allCount = allList.Length; var noneCount = noneList.Length; @@ -60,16 +60,16 @@ public void Dispose() for (int i = 0; i < noneCount; i++) noneTypes[i] = noneList[i]; - var query = new EntityArchetypeQuery + var query = new EntityQueryDesc { All = allTypes, None = noneTypes }; - + allList.Dispose(); noneList.Dispose(); - return CreateQuery(ref scratchAllocator, new EntityArchetypeQuery[] { query }); + return CreateQuery(ref scratchAllocator, new EntityQueryDesc[] { query }); } void ConstructTypeArray(ref ScratchAllocator scratchAllocator, ComponentType[] types, out int* outTypes, out byte* outAccessModes, out int outLength) @@ -85,7 +85,7 @@ void ConstructTypeArray(ref ScratchAllocator scratchAllocator, ComponentType[] t outLength = types.Length; outTypes = (int*)scratchAllocator.Allocate(types.Length); outAccessModes = (byte*)scratchAllocator.Allocate(types.Length); - + var sortedTypes = stackalloc ComponentType[types.Length]; for (var i = 0; i < types.Length; ++i) SortingUtilities.InsertSorted(sortedTypes, i, types[i]); @@ -102,14 +102,14 @@ void IncludeDependentWriteGroups(ComponentType type, NativeList e { if (type.AccessModeType != ComponentType.AccessMode.ReadOnly) return; - + var writeGroupTypes = TypeManager.GetWriteGroupTypes(type.TypeIndex); for (int i = 0; i < writeGroupTypes.Length; i++) { var excludedComponentType = GetWriteGroupReadOnlyComponentType(writeGroupTypes, i); if (explicitList.Contains(excludedComponentType)) continue; - + explicitList.Add(excludedComponentType); IncludeDependentWriteGroups(excludedComponentType, explicitList); } @@ -128,7 +128,7 @@ void ExcludeWriteGroups(ComponentType type, NativeList noneList, { if (type.AccessModeType == ComponentType.AccessMode.ReadOnly) return; - + var writeGroupTypes = TypeManager.GetWriteGroupTypes(type.TypeIndex); for (int i = 0; i < writeGroupTypes.Length; i++) { @@ -137,7 +137,7 @@ void ExcludeWriteGroups(ComponentType type, NativeList noneList, continue; if (explicitList.Contains(excludedComponentType)) continue; - + noneList.Add(excludedComponentType); } } @@ -154,30 +154,18 @@ NativeList CreateExplicitTypeList(ComponentType[] typesNone, Comp return explicitList; } - ArchetypeQuery* CreateQuery(ref ScratchAllocator scratchAllocator, EntityArchetypeQuery[] query) + ArchetypeQuery* CreateQuery(ref ScratchAllocator scratchAllocator, EntityQueryDesc[] queryDesc) { - var outQuery = (ArchetypeQuery*)scratchAllocator.Allocate(sizeof(ArchetypeQuery) * query.Length, UnsafeUtility.AlignOf()); - for (int q = 0; q != query.Length; q++) + var outQuery = (ArchetypeQuery*)scratchAllocator.Allocate(sizeof(ArchetypeQuery) * queryDesc.Length, UnsafeUtility.AlignOf()); + for (int q = 0; q != queryDesc.Length; q++) { - var typesNone = query[q].None; - var typesAll = query[q].All; - var typesAny = query[q].Any; - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - // Check that query doesn't contain any ExcludeComponent... - { - for (int i=0;i CreateExplicitTypeList(ComponentType[] typesNone, Comp typesNone[i] = ComponentType.ReadOnly(typesNone[i].TypeIndex); } - var isFilterWriteGroup = (query[q].Options & EntityArchetypeQueryOptions.FilterWriteGroup) != 0; + var isFilterWriteGroup = (queryDesc[q].Options & EntityQueryOptions.FilterWriteGroup) != 0; if (isFilterWriteGroup) { // Each ReadOnly in any or all @@ -201,7 +189,7 @@ NativeList CreateExplicitTypeList(ComponentType[] typesNone, Comp // Each ReadWrite in any or all // if has WriteGroup types, - // Add to none (if not exist in any or all or none) + // Add to none (if not exist in any or all or none) var noneList = new NativeList(typesNone.Length, Allocator.Temp); for (int i = 0; i < typesNone.Length; i++) noneList.Add(typesNone[i]); @@ -219,7 +207,7 @@ NativeList CreateExplicitTypeList(ComponentType[] typesNone, Comp ConstructTypeArray(ref scratchAllocator, typesNone, out outQuery[q].None, out outQuery[q].NoneAccessMode, out outQuery[q].NoneCount); ConstructTypeArray(ref scratchAllocator, typesAll, out outQuery[q].All, out outQuery[q].AllAccessMode, out outQuery[q].AllCount); ConstructTypeArray(ref scratchAllocator, typesAny, out outQuery[q].Any, out outQuery[q].AnyAccessMode, out outQuery[q].AnyCount); - outQuery[q].Options = query[q].Options; + outQuery[q].Options = queryDesc[q].Options; } return outQuery; @@ -246,18 +234,18 @@ public static bool CompareQueryArray(ComponentType[] filter, int* typeArray, byt return true; } - public static bool CompareQuery(EntityArchetypeQuery[] query, EntityGroupData* groupData) + public static bool CompareQuery(EntityQueryDesc[] queryDesc, EntityGroupData* groupData) { - if (groupData->ArchetypeQueryCount != query.Length) + if (groupData->ArchetypeQueryCount != queryDesc.Length) return false; - for (int i = 0; i != query.Length; i++) + for (int i = 0; i != queryDesc.Length; i++) { - if (!CompareQueryArray(query[i].All, groupData->ArchetypeQuery[i].All, groupData->ArchetypeQuery[i].AllAccessMode, groupData->ArchetypeQuery[i].AllCount)) + if (!CompareQueryArray(queryDesc[i].All, groupData->ArchetypeQuery[i].All, groupData->ArchetypeQuery[i].AllAccessMode, groupData->ArchetypeQuery[i].AllCount)) return false; - if (!CompareQueryArray(query[i].None, groupData->ArchetypeQuery[i].None, groupData->ArchetypeQuery[i].NoneAccessMode, groupData->ArchetypeQuery[i].NoneCount)) + if (!CompareQueryArray(queryDesc[i].None, groupData->ArchetypeQuery[i].None, groupData->ArchetypeQuery[i].NoneAccessMode, groupData->ArchetypeQuery[i].NoneCount)) return false; - if (!CompareQueryArray(query[i].Any, groupData->ArchetypeQuery[i].Any, groupData->ArchetypeQuery[i].AnyAccessMode, groupData->ArchetypeQuery[i].AnyCount)) + if (!CompareQueryArray(queryDesc[i].Any, groupData->ArchetypeQuery[i].Any, groupData->ArchetypeQuery[i].AnyAccessMode, groupData->ArchetypeQuery[i].AnyCount)) return false; } @@ -270,7 +258,7 @@ public static bool CompareComponents(ComponentType* componentTypes, int componen for (var k = 0; k < componentTypesCount; ++k) if (componentTypes[k].TypeIndex == TypeManager.GetTypeIndex()) throw new ArgumentException( - "ComponentGroup.CompareComponents may not include typeof(Entity), it is implicit"); + "EntityQuery.CompareComponents may not include typeof(Entity), it is implicit"); #endif var sortedTypes = stackalloc ComponentType[componentTypesCount]; @@ -278,8 +266,8 @@ public static bool CompareComponents(ComponentType* componentTypes, int componen { SortingUtilities.InsertSorted(sortedTypes, i, componentTypes[i]); } - - // ComponentGroups are constructed including the Entity ID + + // EntityQueries are constructed including the Entity ID if (componentTypesCount + 1 != groupData->RequiredComponentsCount) return false; @@ -327,31 +315,31 @@ private int IntersectSortedComponentIndexArrays(int* arrayA, int arrayACount, in var intersectionCount = 0; var i = 0; - var j = 0; - while (i < arrayACount && j < arrayBCount) - { - if (arrayA[i] < arrayB[j]) - i++; - else if (arrayB[j] < arrayA[i]) - j++; + var j = 0; + while (i < arrayACount && j < arrayBCount) + { + if (arrayA[i] < arrayB[j]) + i++; + else if (arrayB[j] < arrayA[i]) + j++; else { outArray[intersectionCount++] = arrayB[j]; - i++; - j++; - } + i++; + j++; + } } return intersectionCount; } - // Calculates the intersection of "All" queries + // Calculates the intersection of "All" queriesDesc private ComponentType* CalculateRequiredComponentsFromQuery(ref ScratchAllocator allocator, ArchetypeQuery* queries, int queryCount, out int outRequiredComponentsCount) { var maxIntersectionCount = 0; for (int queryIndex = 0; queryIndex < queryCount; ++queryIndex) - maxIntersectionCount = math.max(maxIntersectionCount, queries[queryIndex].AllCount); - + maxIntersectionCount = math.max(maxIntersectionCount, queries[queryIndex].AllCount); + var intersection = (int*)allocator.Allocate(maxIntersectionCount); UnsafeUtility.MemCpy(intersection, queries[0].All, sizeof(int) * queries[0].AllCount); @@ -361,31 +349,31 @@ private int IntersectSortedComponentIndexArrays(int* arrayA, int arrayACount, in intersectionCount = IntersectSortedComponentIndexArrays(intersection, intersectionCount, queries[i].All, queries[i].AllCount, intersection); } - + var outRequiredComponents = (ComponentType*)allocator.Allocate(intersectionCount + 1); outRequiredComponents[0] = ComponentType.ReadWrite(); for (int i = 0; i < intersectionCount; ++i) { outRequiredComponents[i + 1] = ComponentType.FromTypeIndex(intersection[i]); } - + outRequiredComponentsCount = intersectionCount + 1; return outRequiredComponents; } - public ComponentGroup CreateEntityGroup(ArchetypeManager typeMan, EntityDataManager* entityDataManager, EntityArchetypeQuery[] query) + public EntityQuery CreateEntityGroup(ArchetypeManager typeMan, EntityDataManager* entityDataManager, EntityQueryDesc[] queryDesc) { - //@TODO: Support for CreateEntityGroup with query but using ComponentDataArray etc + //@TODO: Support for CreateEntityGroup with queryDesc but using ComponentDataArray etc var buffer = stackalloc byte[1024]; var scratchAllocator = new ScratchAllocator(buffer, 1024); - var archetypeQuery = CreateQuery(ref scratchAllocator, query); + var archetypeQuery = CreateQuery(ref scratchAllocator, queryDesc); - var outRequiredComponents = CalculateRequiredComponentsFromQuery(ref scratchAllocator, archetypeQuery, query.Length, out var outRequiredComponentsCount); - - return CreateEntityGroup(typeMan, entityDataManager, archetypeQuery, query.Length, outRequiredComponents, outRequiredComponentsCount); + var outRequiredComponents = CalculateRequiredComponentsFromQuery(ref scratchAllocator, archetypeQuery, queryDesc.Length, out var outRequiredComponentsCount); + + return CreateEntityGroup(typeMan, entityDataManager, archetypeQuery, queryDesc.Length, outRequiredComponents, outRequiredComponentsCount); } - public ComponentGroup CreateEntityGroup(ArchetypeManager typeMan, EntityDataManager* entityDataManager, ComponentType* inRequiredComponents, int inRequiredComponentsCount) + public EntityQuery CreateEntityGroup(ArchetypeManager typeMan, EntityDataManager* entityDataManager, ComponentType* inRequiredComponents, int inRequiredComponentsCount) { var buffer = stackalloc byte[1024]; var scratchAllocator = new ScratchAllocator(buffer, 1024); @@ -423,10 +411,10 @@ bool Matches(EntityGroupData* grp, ArchetypeQuery* archetypeQueries, int archety UnsafeUtility.MemCpy(pointer, source, bytes); return pointer; } - - public ComponentGroup CreateEntityGroup(ArchetypeManager typeMan, EntityDataManager* entityDataManager, + + public EntityQuery CreateEntityGroup(ArchetypeManager typeMan, EntityDataManager* entityDataManager, ArchetypeQuery* query, int queryCount, ComponentType* component, int componentCount) - { + { //@TODO: Validate that required types is subset of archetype filters all... int hash = (int)math.hash(component, componentCount * sizeof(ComponentType)); @@ -474,7 +462,7 @@ public ComponentGroup CreateEntityGroup(ArchetypeManager typeMan, EntityDataMana m_EntityGroupDatasUnsafePtrList.Add(cachedGroup); } - return new ComponentGroup(cachedGroup, m_JobSafetyManager, typeMan, entityDataManager); + return new EntityQuery(cachedGroup, m_JobSafetyManager, typeMan, entityDataManager); } void InitializeReaderWriter(EntityGroupData* grp, ComponentType* requiredTypes, int requiredCount) @@ -620,7 +608,7 @@ static bool TestMatchingArchetypeNone(Archetype* archetype, int* noneTypes, int return true; } - static bool TestMatchingArchetypeAll(Archetype* archetype, int* allTypes, int allCount, EntityArchetypeQueryOptions options) + static bool TestMatchingArchetypeAll(Archetype* archetype, int* allTypes, int allCount, EntityQueryOptions options) { var componentTypes = archetype->Types; var componentTypesCount = archetype->TypesCount; @@ -628,8 +616,8 @@ static bool TestMatchingArchetypeAll(Archetype* archetype, int* allTypes, int al var disabledTypeIndex = TypeManager.GetTypeIndex(); var prefabTypeIndex = TypeManager.GetTypeIndex(); var chunkHeaderTypeIndex = TypeManager.GetTypeIndex(); - var includeInactive = (options & EntityArchetypeQueryOptions.IncludeDisabled) != 0; - var includePrefab = (options & EntityArchetypeQueryOptions.IncludePrefab) != 0; + var includeInactive = (options & EntityQueryOptions.IncludeDisabled) != 0; + var includePrefab = (options & EntityQueryOptions.IncludePrefab) != 0; var includeChunkHeader = false; for (var i = 0; i < componentTypesCount; i++) @@ -644,7 +632,7 @@ static bool TestMatchingArchetypeAll(Archetype* archetype, int* allTypes, int al includePrefab = true; if (allTypeIndex == chunkHeaderTypeIndex) includeChunkHeader = true; - + if (componentTypeIndex == allTypeIndex) foundCount++; } } @@ -681,7 +669,7 @@ unsafe struct MatchingArchetypeList public int Count; public int Capacity; } - + unsafe struct ArchetypeQuery : IEquatable { public int* Any; @@ -695,9 +683,9 @@ unsafe struct ArchetypeQuery : IEquatable public int* None; public byte* NoneAccessMode; public int NoneCount; - - public EntityArchetypeQueryOptions Options; - + + public EntityQueryOptions Options; + public bool Equals(ArchetypeQuery other) { if (AnyCount != other.AnyCount) @@ -706,7 +694,7 @@ public bool Equals(ArchetypeQuery other) return false; if (NoneCount != other.NoneCount) return false; - if (AnyCount > 0 && UnsafeUtility.MemCmp(Any, other.Any, sizeof(int) * AnyCount) != 0 && + if (AnyCount > 0 && UnsafeUtility.MemCmp(Any, other.Any, sizeof(int) * AnyCount) != 0 && UnsafeUtility.MemCmp(AnyAccessMode, other.AnyAccessMode, sizeof(byte) * AnyCount) != 0) return false; if (AllCount > 0 && UnsafeUtility.MemCmp(All, other.All, sizeof(int) * AllCount) != 0 && @@ -717,9 +705,9 @@ public bool Equals(ArchetypeQuery other) return false; if (Options != other.Options) return false; - + return true; - } + } public override int GetHashCode() { unchecked @@ -745,7 +733,7 @@ unsafe struct EntityGroupDataList public int Count; public int Capacity; } - + unsafe struct EntityGroupData : IDisposable { //@TODO: better name or remove entirely... @@ -767,7 +755,7 @@ public ref UnsafePtrList MatchingArchetypesUnsafePtrList { get { return ref *(UnsafePtrList*)UnsafeUtility.AddressOf(ref MatchingArchetypes); } } - + public void Dispose() { MatchingArchetypesUnsafePtrList.Dispose(); diff --git a/Unity.Entities/Iterators/ComponentGroup.cs b/Unity.Entities/Iterators/EntityQuery.cs similarity index 65% rename from Unity.Entities/Iterators/ComponentGroup.cs rename to Unity.Entities/Iterators/EntityQuery.cs index b0c50b64..82735a59 100644 --- a/Unity.Entities/Iterators/ComponentGroup.cs +++ b/Unity.Entities/Iterators/EntityQuery.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; @@ -7,11 +9,19 @@ namespace Unity.Entities { + public class EntityQueryDescValidationException : Exception + { + public EntityQueryDescValidationException(string message) : base(message) + { + + } + } + /// - /// Defines a query to find archetypes with specific components. + /// Defines a queryDesc to find archetypes with specific components. /// /// - /// A query combines components in the All, Any, and None sets according to the + /// A queryDesc combines components in the All, Any, and None sets according to the /// following rules: /// /// * All - Includes archetypes that have every component in this set @@ -24,106 +34,165 @@ namespace Unity.Entities /// * Enemy1 has components: Position, Rotation, Melee /// * Enemy2 has components: Position, Rotation, Ranger /// - /// The query below would give you all of the archetypes that: + /// The queryDesc below would give you all of the archetypes that: /// have any of [Melee or Ranger], AND have none of [Player], AND have all of [Position and Rotation] /// - /// new EntityArchetypeQuery { + /// new EntityQueryDesc { /// Any = new ComponentType[] {typeof(Melee), typeof(Ranger)}, /// None = new ComponentType[] {typeof(Player)}, /// All = new ComponentType[] {typeof(Position), typeof(Rotation)} /// } /// /// - /// In other words, the query selects the Enemy1 and Enemy2 entities, but not the Player entity. + /// In other words, the queryDesc selects the Enemy1 and Enemy2 entities, but not the Player entity. /// - public class EntityArchetypeQuery + public class EntityQueryDesc { /// - /// The query includes archetypes that contain at least one (but possibly more) of the + /// The queryDesc includes archetypes that contain at least one (but possibly more) of the /// components in the Any list. /// public ComponentType[] Any = Array.Empty(); /// - /// The query excludes archetypes that contain any of the + /// The queryDesc excludes archetypes that contain any of the /// components in the None list. /// public ComponentType[] None = Array.Empty(); /// - /// The query includes archetypes that contain all of the + /// The queryDesc includes archetypes that contain all of the /// components in the All list. /// public ComponentType[] All = Array.Empty(); /// - /// Specialized query options. + /// Specialized queryDesc options. /// /// - /// You should not need to set these options for most queries. + /// You should not need to set these options for most queriesDesc. /// /// Options is a bit mask; use the bitwise OR operator to combine multiple options. /// - public EntityArchetypeQueryOptions Options = EntityArchetypeQueryOptions.Default; + public EntityQueryOptions Options = EntityQueryOptions.Default; + + [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] + public void Validate() + { + // Determine the number of ComponentTypes contained in the filters + var itemCount = None.Length + All.Length + Any.Length; + + // Project all the ComponentType Ids of None, All, Any queryDesc filters into the same array to identify duplicated later on + // Also, check that queryDesc doesn't contain any ExcludeComponent... + + var allComponentTypeIds = new NativeArray(itemCount, Allocator.Temp); + var curComponentTypeIndex = 0; + + for (int i = 0; i < None.Length; i++) + { + var componentType = None[i]; + allComponentTypeIds[curComponentTypeIndex++] = componentType.TypeIndex; + if (componentType.AccessModeType == ComponentType.AccessMode.Exclude) + throw new ArgumentException("EntityQueryDesc cannot contain Exclude Component types"); + } + for (int i = 0; i < All.Length; i++) + { + var componentType = All[i]; + allComponentTypeIds[curComponentTypeIndex++] = componentType.TypeIndex; + if (componentType.AccessModeType == ComponentType.AccessMode.Exclude) + throw new ArgumentException("EntityQueryDesc cannot contain Exclude Component types"); + } + for (int i = 0; i < Any.Length; i++) + { + var componentType = Any[i]; + allComponentTypeIds[curComponentTypeIndex++] = componentType.TypeIndex; + if (componentType.AccessModeType == ComponentType.AccessMode.Exclude) + throw new ArgumentException("EntityQueryDesc cannot contain Exclude Component types"); + } + + // Check for duplicate, only if necessary + if (itemCount > 1) + { + // Sort the Ids to have identical value adjacent + allComponentTypeIds.Sort(); + + // Check for identical values + var refId = allComponentTypeIds[0]; + for (int i = 1; i < allComponentTypeIds.Length; i++) + { + var curId = allComponentTypeIds[i]; + if (curId == refId) + { +#if NET_DOTS + throw new EntityQueryDescValidationException($"Cannot create a queryDesc with more than one filter containing the same component type, type index {curId}"); +#else + var compType = TypeManager.GetType(curId); + throw new EntityQueryDescValidationException($"Cannot create a queryDesc with more than one filter containing the same component type, type name {compType.Name}"); +#endif + } + + refId = curId; + } + } + } } /// - /// The bit flags to use for the field. + /// The bit flags to use for the field. /// [Flags] - public enum EntityArchetypeQueryOptions + public enum EntityQueryOptions { /// /// No options specified. /// Default = 0, /// - /// The query includes the special component. + /// The queryDesc includes the special component. /// IncludePrefab = 1, /// - /// The query includes the special component. + /// The queryDesc includes the special component. /// IncludeDisabled = 2, /// - /// The query should filter selected entities based on the - /// settings of the components specified in the query. + /// The queryDesc should filter selected entities based on the + /// settings of the components specified in the queryDesc. /// FilterWriteGroup = 4, } - //@TODO: Rename to EntityView /// - /// A ComponentGroup provides a query-based view of your component data. + /// A EntityQuery provides a queryDesc-based view of your component data. /// /// - /// A ComponentGroup defines a view of your data based on a query for the set of + /// A EntityQuery defines a view of your data based on a queryDesc for the set of /// component types that an archetype must contain in order for its chunks and entities /// to be included in the view. You can also exclude archetypes that contain specific types - /// of components. For simple queries, you can create a ComponentGroup based on an array of - /// component types. The following example defines a ComponentGroup that finds all entities + /// of components. For simple queriesDesc, you can create a EntityQuery based on an array of + /// component types. The following example defines a EntityQuery that finds all entities /// with both RotationQuaternion and RotationSpeed components. /// /// - /// ComponentGroup m_Group = GetComponentGroup(typeof(RotationQuaternion), + /// EntityQuery m_Group = GetEntityQuery(typeof(RotationQuaternion), /// ComponentType.ReadOnly{RotationSpeed}()); /// /// - /// The query uses `ComponentType.ReadOnly` instead of the simpler `typeof` expression + /// The queryDesc uses `ComponentType.ReadOnly` instead of the simpler `typeof` expression /// to designate that the system does not write to RotationSpeed. Always specify read only /// when possible, since there are fewer constraints on read access to data, which can help /// the Job scheduler execute your Jobs more efficiently. /// - /// For more complex queries, you can use an instead of a + /// For more complex queriesDesc, you can use an instead of a /// simple list of component types. /// - /// Use the or - /// functions - /// to get a ComponentGroup instance. + /// Use the or + /// functions + /// to get a EntityQuery instance. /// - public unsafe class ComponentGroup : IDisposable + public unsafe class EntityQuery : IDisposable { - readonly ComponentJobSafetyManager m_SafetyManager; - readonly EntityGroupData* m_GroupData; - readonly EntityDataManager* m_EntityDataManager; - ComponentGroupFilter m_Filter; + readonly ComponentJobSafetyManager* m_SafetyManager; + readonly EntityGroupData* m_GroupData; + readonly EntityDataManager* m_EntityDataManager; + EntityQueryFilter m_Filter; #if ENABLE_UNITY_COLLECTIONS_CHECKS internal string DisallowDisposing = null; @@ -132,23 +201,23 @@ public unsafe class ComponentGroup : IDisposable // TODO: this is temporary, used to cache some state to avoid recomputing the TransformAccessArray. We need to improve this. internal IDisposable m_CachedState; - internal ComponentGroup(EntityGroupData* groupData, ComponentJobSafetyManager safetyManager, ArchetypeManager typeManager, EntityDataManager* entityDataManager) + internal EntityQuery(EntityGroupData* groupData, ComponentJobSafetyManager* safetyManager, ArchetypeManager typeManager, EntityDataManager* entityDataManager) { m_GroupData = groupData; m_EntityDataManager = entityDataManager; - m_Filter = default(ComponentGroupFilter); + m_Filter = default(EntityQueryFilter); m_SafetyManager = safetyManager; ArchetypeManager = typeManager; EntityDataManager = entityDataManager; } internal EntityDataManager* EntityDataManager { get; } - internal ComponentJobSafetyManager SafetyManager => m_SafetyManager; + internal ComponentJobSafetyManager* SafetyManager => m_SafetyManager; /// - /// Ignore this ComponentGroup if it has no entities in any of its archetypes. + /// Ignore this EntityQuery if it has no entities in any of its archetypes. /// - /// True if this ComponentGroup has no entities. False if it has 1 or more entities. + /// True if this EntityQuery has no entities. False if it has 1 or more entities. public bool IsEmptyIgnoreFilter { get @@ -163,7 +232,7 @@ public bool IsEmptyIgnoreFilter return true; } } -#if UNITY_CSHARP_TINY +#if NET_DOTS internal class SlowListSet { internal List items; @@ -188,12 +257,12 @@ internal T[] ToArray() #endif /// - /// Gets the array of objects included in this ComponentGroup. + /// Gets the array of objects included in this EntityQuery. /// /// Array of ComponentTypes internal ComponentType[] GetQueryTypes() { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS var types = new HashSet(); #else var types = new SlowListSet(); @@ -215,7 +284,7 @@ internal ComponentType[] GetQueryTypes() } } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS var array = new ComponentType[types.Count]; var t = 0; foreach (var type in types) @@ -227,7 +296,7 @@ internal ComponentType[] GetQueryTypes() } /// - /// Packed array of this ComponentGroup's ReadOnly and writable ComponentTypes. + /// Packed array of this EntityQuery's ReadOnly and writable ComponentTypes. /// ReadOnly ComponentTypes come before writable types in this array. /// /// Array of ComponentTypes @@ -264,43 +333,43 @@ public void Dispose() #if ENABLE_UNITY_COLLECTIONS_CHECKS /// - /// Gets safety handle to a ComponentType required by this ComponentGroup. + /// Gets safety handle to a ComponentType required by this EntityQuery. /// - /// Index of a ComponentType in this ComponentGroup's RequiredComponents list./param> + /// Index of a ComponentType in this EntityQuery's RequiredComponents list./param> /// AtomicSafetyHandle for a ComponentType - internal AtomicSafetyHandle GetSafetyHandle(int indexInComponentGroup) + internal AtomicSafetyHandle GetSafetyHandle(int indexInEntityQuery) { - var type = m_GroupData->RequiredComponents + indexInComponentGroup; + var type = m_GroupData->RequiredComponents + indexInEntityQuery; var isReadOnly = type->AccessModeType == ComponentType.AccessMode.ReadOnly; - return m_SafetyManager.GetSafetyHandle(type->TypeIndex, isReadOnly); + return m_SafetyManager->GetSafetyHandle(type->TypeIndex, isReadOnly); } /// - /// Gets buffer safety handle to a ComponentType required by this ComponentGroup. + /// Gets buffer safety handle to a ComponentType required by this EntityQuery. /// - /// Index of a ComponentType in this ComponentGroup's RequiredComponents list./param> + /// Index of a ComponentType in this EntityQuery's RequiredComponents list./param> /// AtomicSafetyHandle for a buffer - internal AtomicSafetyHandle GetBufferSafetyHandle(int indexInComponentGroup) + internal AtomicSafetyHandle GetBufferSafetyHandle(int indexInEntityQuery) { - var type = m_GroupData->RequiredComponents + indexInComponentGroup; - return m_SafetyManager.GetBufferSafetyHandle(type->TypeIndex); + var type = m_GroupData->RequiredComponents + indexInEntityQuery; + return m_SafetyManager->GetBufferSafetyHandle(type->TypeIndex); } #endif - bool GetIsReadOnly(int indexInComponentGroup) + bool GetIsReadOnly(int indexInEntityQuery) { - var type = m_GroupData->RequiredComponents + indexInComponentGroup; + var type = m_GroupData->RequiredComponents + indexInEntityQuery; var isReadOnly = type->AccessModeType == ComponentType.AccessMode.ReadOnly; return isReadOnly; } /// - /// Calculates the number of entities selected by this ComponentGroup. + /// Calculates the number of entities selected by this EntityQuery. /// /// - /// The ComponentGroup must run the query and apply any filters to calculate the entity count. + /// The EntityQuery must run the queryDesc and apply any filters to calculate the entity count. /// - /// The number of entities based on the current ComponentGroup properties. + /// The number of entities based on the current EntityQuery properties. public int CalculateLength() { SyncFilterTypes(); @@ -308,17 +377,17 @@ public int CalculateLength() } /// - /// Gets iterator to chunks associated with this ComponentGroup. + /// Gets iterator to chunks associated with this EntityQuery. /// - /// ComponentChunkIterator for this ComponentGroup + /// ComponentChunkIterator for this EntityQuery internal ComponentChunkIterator GetComponentChunkIterator() { return new ComponentChunkIterator(m_GroupData->MatchingArchetypes, m_EntityDataManager->GlobalSystemVersion, ref m_Filter); } /// - /// Index of a ComponentType in this ComponentGroup's RequiredComponents list. - /// For example, you have a ComponentGroup that requires these ComponentTypes: Position, Velocity, and Color. + /// Index of a ComponentType in this EntityQuery's RequiredComponents list. + /// For example, you have a EntityQuery that requires these ComponentTypes: Position, Velocity, and Color. /// /// These are their type indices (according to the TypeManager): /// Position.TypeIndex == 3 @@ -330,119 +399,22 @@ internal ComponentChunkIterator GetComponentChunkIterator() /// /// Index of a ComponentType in the TypeManager /// An index into RequiredComponents. - internal int GetIndexInComponentGroup(int componentType) + internal int GetIndexInEntityQuery(int componentType) { - // Go through all the required component types in this ComponentGroup until you find the matching component type index. + // Go through all the required component types in this EntityQuery until you find the matching component type index. var componentIndex = 0; while (componentIndex < m_GroupData->RequiredComponentsCount && m_GroupData->RequiredComponents[componentIndex].TypeIndex != componentType) ++componentIndex; #if ENABLE_UNITY_COLLECTIONS_CHECKS - if (componentIndex >= m_GroupData->RequiredComponentsCount) + if (componentIndex >= m_GroupData->RequiredComponentsCount || m_GroupData->RequiredComponents[componentIndex].AccessModeType == ComponentType.AccessMode.Exclude) throw new InvalidOperationException( $"Trying to get iterator for {TypeManager.GetType(componentType)} but the required component type was not declared in the EntityGroup."); #endif return componentIndex; } - [Obsolete("GetComponentDataArray is deprecated. Use IJobProcessComponentData or ToComponentDataArray/CopyFromComponentDataArray instead.")] - internal void GetComponentDataArray(ref ComponentChunkIterator iterator, int indexInComponentGroup, - int length, out ComponentDataArray output) where T : struct, IComponentData - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - var typeIndex = TypeManager.GetTypeIndex(); - var componentType = ComponentType.FromTypeIndex(typeIndex); - if (componentType.IsZeroSized) - throw new ArgumentException($"GetComponentDataArray<{typeof(T)}> cannot be called on zero-sized IComponentData"); -#endif - - iterator.IndexInComponentGroup = indexInComponentGroup; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - output = new ComponentDataArray(iterator, length, GetSafetyHandle(indexInComponentGroup)); -#else - output = new ComponentDataArray(iterator, length); -#endif - } - - [Obsolete("GetComponentDataArray is deprecated. Use IJobProcessComponentData or ToComponentDataArray/CopyFromComponentDataArray instead.")] - public ComponentDataArray GetComponentDataArray() where T : struct, IComponentData - { - var typeIndex = TypeManager.GetTypeIndex(); - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - var componentType = ComponentType.FromTypeIndex(typeIndex); - if (componentType.IsZeroSized) - throw new ArgumentException($"GetComponentDataArray<{typeof(T)}> cannot be called on zero-sized IComponentData"); -#endif - - int length = CalculateLength(); - ComponentChunkIterator iterator = GetComponentChunkIterator(); - var indexInComponentGroup = GetIndexInComponentGroup(typeIndex); - - ComponentDataArray res; - GetComponentDataArray(ref iterator, indexInComponentGroup, length, out res); - return res; - } - - [Obsolete("GetSharedComponentDataArray is deprecated.")] - internal void GetSharedComponentDataArray(ref ComponentChunkIterator iterator, int indexInComponentGroup, - int length, out SharedComponentDataArray output) where T : struct, ISharedComponentData - { - iterator.IndexInComponentGroup = indexInComponentGroup; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - var componentTypeIndex = m_GroupData->RequiredComponents[indexInComponentGroup].TypeIndex; - output = new SharedComponentDataArray(ArchetypeManager.GetSharedComponentDataManager(), - indexInComponentGroup, iterator, length, m_SafetyManager.GetSafetyHandle(componentTypeIndex, true)); -#else - output = new SharedComponentDataArray(ArchetypeManager.GetSharedComponentDataManager(), - indexInComponentGroup, iterator, length); -#endif - } - - /// - /// Creates an array containing ISharedComponentData of a given type T. - /// - /// NativeArray of ISharedComponentData in this ComponentGroup. - [Obsolete("GetSharedComponentDataArray is deprecated.")] - public SharedComponentDataArray GetSharedComponentDataArray() where T : struct, ISharedComponentData - { - int length = CalculateLength(); - ComponentChunkIterator iterator = GetComponentChunkIterator(); - var indexInComponentGroup = GetIndexInComponentGroup(TypeManager.GetTypeIndex()); - - SharedComponentDataArray res; - GetSharedComponentDataArray(ref iterator, indexInComponentGroup, length, out res); - return res; - } - - [Obsolete("GetBufferArray is deprecated.")] - internal void GetBufferArray(ref ComponentChunkIterator iterator, int indexInComponentGroup, int length, - out BufferArray output) where T : struct, IBufferElementData - { - iterator.IndexInComponentGroup = indexInComponentGroup; - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - output = new BufferArray(iterator, length, GetIsReadOnly(indexInComponentGroup), - GetSafetyHandle(indexInComponentGroup), - GetBufferSafetyHandle(indexInComponentGroup)); -#else - output = new BufferArray(iterator, length, GetIsReadOnly(indexInComponentGroup)); -#endif - } - - [Obsolete("GetBufferArray is deprecated.")] - public BufferArray GetBufferArray() where T : struct, IBufferElementData - { - int length = CalculateLength(); - ComponentChunkIterator iterator = GetComponentChunkIterator(); - var indexInComponentGroup = GetIndexInComponentGroup(TypeManager.GetTypeIndex()); - - BufferArray res; - GetBufferArray(ref iterator, indexInComponentGroup, length, out res); - return res; - } - /// - /// Creates an array with all the chunks in this ComponentGroup. + /// Creates an array with all the chunks in this EntityQuery. /// Gives the caller a job handle so it can wait for GatherChunks to finish. /// /// Allocator to use for the array. @@ -456,18 +428,18 @@ public NativeArray CreateArchetypeChunkArray(Allocator allocator { var filterCount = m_Filter.Changed.Count; var readerTypes = stackalloc int[filterCount]; - fixed (int* indexInComponentGroupPtr = m_Filter.Changed.IndexInComponentGroup) + fixed (int* indexInEntityQueryPtr = m_Filter.Changed.IndexInEntityQuery) for (int i = 0; i < filterCount; ++i) - readerTypes[i] = m_GroupData->RequiredComponents[indexInComponentGroupPtr[i]].TypeIndex; + readerTypes[i] = m_GroupData->RequiredComponents[indexInEntityQueryPtr[i]].TypeIndex; - dependency = m_SafetyManager.GetDependency(readerTypes, filterCount,null, 0); + dependency = m_SafetyManager->GetDependency(readerTypes, filterCount,null, 0); } return ComponentChunkIterator.CreateArchetypeChunkArray(m_GroupData->MatchingArchetypes, allocator, out jobhandle, ref m_Filter, dependency); } /// - /// Creates an array with all the chunks in this ComponentGroup. + /// Creates an array with all the chunks in this EntityQuery. /// Waits for the GatherChunks job to complete here. /// /// Allocator to use for the array. @@ -488,11 +460,11 @@ public NativeArray CreateArchetypeChunkArray(Allocator allocator /// The type of memory to allocate. /// A handle that you can use as a dependency for a Job /// that uses the NativeArray. - /// An array containing all the entities selected by the ComponentGroup. + /// An array containing all the entities selected by the EntityQuery. public NativeArray ToEntityArray(Allocator allocator, out JobHandle jobhandle) { #if ENABLE_UNITY_COLLECTIONS_CHECKS - var entityType = new ArchetypeChunkEntityType(m_SafetyManager.GetEntityManagerSafetyHandle()); + var entityType = new ArchetypeChunkEntityType(m_SafetyManager->GetEntityManagerSafetyHandle()); #else var entityType = new ArchetypeChunkEntityType(); #endif @@ -505,11 +477,11 @@ public NativeArray ToEntityArray(Allocator allocator, out JobHandle jobh /// /// This version of the function blocks until the Job used to fill the array is complete. /// The type of memory to allocate. - /// An array containing all the entities selected by the ComponentGroup. + /// An array containing all the entities selected by the EntityQuery. public NativeArray ToEntityArray(Allocator allocator) { #if ENABLE_UNITY_COLLECTIONS_CHECKS - var entityType = new ArchetypeChunkEntityType(m_SafetyManager.GetEntityManagerSafetyHandle()); + var entityType = new ArchetypeChunkEntityType(m_SafetyManager->GetEntityManagerSafetyHandle()); #else var entityType = new ArchetypeChunkEntityType(); #endif @@ -527,12 +499,12 @@ public NativeArray ToEntityArray(Allocator allocator) /// that uses the NativeArray. /// The component type. /// An array containing the specified component for all the entities selected - /// by the ComponentGroup. + /// by the EntityQuery. public NativeArray ToComponentDataArray(Allocator allocator, out JobHandle jobhandle) where T : struct,IComponentData { #if ENABLE_UNITY_COLLECTIONS_CHECKS - var componentType = new ArchetypeChunkComponentType(m_SafetyManager.GetSafetyHandle(TypeManager.GetTypeIndex(), true), true, EntityDataManager->GlobalSystemVersion); + var componentType = new ArchetypeChunkComponentType(m_SafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex(), true), true, EntityDataManager->GlobalSystemVersion); #else var componentType = new ArchetypeChunkComponentType(true, EntityDataManager->GlobalSystemVersion); #endif @@ -545,22 +517,22 @@ public NativeArray ToComponentDataArray(Allocator allocator, out JobHandle /// The type of memory to allocate. /// The component type. /// An array containing the specified component for all the entities selected - /// by the ComponentGroup. + /// by the EntityQuery. /// Thrown if you ask for a component that is not part of /// the group. public NativeArray ToComponentDataArray(Allocator allocator) where T : struct, IComponentData { #if ENABLE_UNITY_COLLECTIONS_CHECKS - var componentType = new ArchetypeChunkComponentType(m_SafetyManager.GetSafetyHandle(TypeManager.GetTypeIndex(), true), true, EntityDataManager->GlobalSystemVersion); + var componentType = new ArchetypeChunkComponentType(m_SafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex(), true), true, EntityDataManager->GlobalSystemVersion); #else var componentType = new ArchetypeChunkComponentType(true, EntityDataManager->GlobalSystemVersion); #endif #if ENABLE_UNITY_COLLECTIONS_CHECKS int typeIndex = TypeManager.GetTypeIndex(); - int indexInComponentGroup = GetIndexInComponentGroup(typeIndex); - if (indexInComponentGroup == -1) + int indexInEntityQuery = GetIndexInEntityQuery(typeIndex); + if (indexInEntityQuery == -1) throw new InvalidOperationException( $"Trying ToComponentDataArray of {TypeManager.GetType(typeIndex)} but the required component type was not declared in the EntityGroup."); #endif @@ -575,10 +547,10 @@ public void CopyFromComponentDataArray(NativeArray componentDataArray) { // throw if non equal size #if ENABLE_UNITY_COLLECTIONS_CHECKS - var groupLength = CalculateLength(); - if(groupLength != componentDataArray.Length) - throw new ArgumentException($"Length of input array ({componentDataArray.Length}) does not match length of ComponentGroup ({groupLength})"); - var componentType = new ArchetypeChunkComponentType(m_SafetyManager.GetSafetyHandle(TypeManager.GetTypeIndex(), false), false, EntityDataManager->GlobalSystemVersion); + var entityCount = CalculateLength(); + if (entityCount != componentDataArray.Length) + throw new ArgumentException($"Length of input array ({componentDataArray.Length}) does not match length of EntityQuery ({entityCount})"); + var componentType = new ArchetypeChunkComponentType(m_SafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex(), false), false, EntityDataManager->GlobalSystemVersion); #else var componentType = new ArchetypeChunkComponentType(false, EntityDataManager->GlobalSystemVersion); #endif @@ -592,13 +564,13 @@ public void CopyFromComponentDataArray(NativeArray componentDataArray, out { // throw if non equal size #if ENABLE_UNITY_COLLECTIONS_CHECKS - var groupLength = CalculateLength(); - if(groupLength != componentDataArray.Length) - throw new ArgumentException($"Length of input array ({componentDataArray.Length}) does not match length of ComponentGroup ({groupLength})"); + var entityCount = CalculateLength(); + if(entityCount != componentDataArray.Length) + throw new ArgumentException($"Length of input array ({componentDataArray.Length}) does not match length of EntityQuery ({entityCount})"); #endif #if ENABLE_UNITY_COLLECTIONS_CHECKS - var componentType = new ArchetypeChunkComponentType(m_SafetyManager.GetSafetyHandle(TypeManager.GetTypeIndex(), false), false, EntityDataManager->GlobalSystemVersion); + var componentType = new ArchetypeChunkComponentType(m_SafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex(), false), false, EntityDataManager->GlobalSystemVersion); #else var componentType = new ArchetypeChunkComponentType(false, EntityDataManager->GlobalSystemVersion); #endif @@ -606,36 +578,12 @@ public void CopyFromComponentDataArray(NativeArray componentDataArray, out ComponentChunkIterator.CopyFromComponentDataArray(m_GroupData->MatchingArchetypes, componentDataArray, componentType, this, ref m_Filter, out jobhandle, GetDependency()); } - /// - /// Creates an EntityArray that gives you access to the entities in this ComponentGroup. - /// - /// EntityArray of all the entities in this ComponentGroup. - [Obsolete("GetEntityArray is deprecated. Use IJobProcessComponentDataWithEntity or ToEntityArray instead.")] - public EntityArray GetEntityArray() - { - int length = CalculateLength(); - ComponentChunkIterator iterator = GetComponentChunkIterator(); - - EntityArray output; - iterator.IndexInComponentGroup = 0; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - - if (m_GroupData->RequiredComponentsCount == 0) - throw new InvalidOperationException( $"GetEntityArray() is currently not supported from a ComponentGroup created with EntityArchetypeQuery."); - - output = new EntityArray(iterator, length, m_SafetyManager.GetEntityManagerSafetyHandle()); -#else - output = new EntityArray(iterator, length); -#endif - return output; - } - public Entity GetSingletonEntity() { #if ENABLE_UNITY_COLLECTIONS_CHECKS - var groupLength = CalculateLength(); - if (groupLength != 1) - throw new System.InvalidOperationException($"GetSingletonEntity() requires that exactly one exists but there are {groupLength}."); + var entityCount = CalculateLength(); + if (entityCount != 1) + throw new System.InvalidOperationException($"GetSingletonEntity() requires that exactly one exists but there are {entityCount}."); #endif @@ -660,12 +608,12 @@ public T GetSingleton() where T : struct, IComponentData { #if ENABLE_UNITY_COLLECTIONS_CHECKS - if(GetIndexInComponentGroup(TypeManager.GetTypeIndex()) != 1) + if(GetIndexInEntityQuery(TypeManager.GetTypeIndex()) != 1) throw new System.InvalidOperationException($"GetSingleton<{typeof(T)}>() requires that {typeof(T)} is the only component type in its archetype."); - var groupLength = CalculateLength(); - if (groupLength != 1) - throw new System.InvalidOperationException($"GetSingleton<{typeof(T)}>() requires that exactly one {typeof(T)} exists but there are {groupLength}."); + var entityCount = CalculateLength(); + if (entityCount != 1) + throw new System.InvalidOperationException($"GetSingleton<{typeof(T)}>() requires that exactly one {typeof(T)} exists but there are {entityCount}."); #endif CompleteDependency(); @@ -699,11 +647,11 @@ public T GetSingleton() /// /// var entityManager = World.Active.EntityManager; /// var singletonEntity = entityManager.CreateEntity(typeof(Singlet)); - /// var singletonGroup = entityManager.CreateComponentGroup(typeof(Singlet)); + /// var singletonGroup = entityManager.CreateEntityQuery(typeof(Singlet)); /// singletonGroup.SetSingleton<Singlet>(new Singlet {Value = 1}); /// /// - /// You can set and get the singleton value from a ComponentGroup or a ComponentSystem. + /// You can set and get the singleton value from a EntityQuery or a ComponentSystem. /// /// An instance of type T containing the values to set. /// The component type. @@ -713,12 +661,12 @@ public void SetSingleton(T value) where T : struct, IComponentData { #if ENABLE_UNITY_COLLECTIONS_CHECKS - if(GetIndexInComponentGroup(TypeManager.GetTypeIndex()) != 1) + if(GetIndexInEntityQuery(TypeManager.GetTypeIndex()) != 1) throw new System.InvalidOperationException($"GetSingleton<{typeof(T)}>() requires that {typeof(T)} is the only component type in its archetype."); - var groupLength = CalculateLength(); - if (groupLength != 1) - throw new System.InvalidOperationException($"SetSingleton<{typeof(T)}>() requires that exactly one {typeof(T)} exists but there are {groupLength}."); + var entityCount = CalculateLength(); + if (entityCount != 1) + throw new System.InvalidOperationException($"SetSingleton<{typeof(T)}>() requires that exactly one {typeof(T)} exists but there are {entityCount}."); #endif CompleteDependency(); @@ -762,15 +710,15 @@ public bool CompareComponents(NativeArray componentTypes) /// /// /// - /// + /// /// - public bool CompareQuery(EntityArchetypeQuery[] query) + public bool CompareQuery(EntityQueryDesc[] queryDesc) { - return EntityGroupManager.CompareQuery(query, m_GroupData); + return EntityGroupManager.CompareQuery(queryDesc, m_GroupData); } /// - /// Resets this ComponentGroup's filter. + /// Resets this EntityQuery's filter. /// /// /// Removes references to shared component data, if applicable, then resets the filter type to None. @@ -793,10 +741,10 @@ public void ResetFilter() } /// - /// Sets this ComponentGroup's filter while preserving its version number. + /// Sets this EntityQuery's filter while preserving its version number. /// - /// ComponentGroupFilter to use all data but RequiredChangeVersion from. - void SetFilter(ref ComponentGroupFilter filter) + /// EntityQueryFilter to use all data but RequiredChangeVersion from. + void SetFilter(ref EntityQueryFilter filter) { #if ENABLE_UNITY_COLLECTIONS_CHECKS filter.AssertValid(); @@ -808,28 +756,28 @@ void SetFilter(ref ComponentGroupFilter filter) } /// - /// Filters this ComponentGroup so that it only selects entities with shared component values + /// Filters this EntityQuery so that it only selects entities with shared component values /// matching the values specified by the `sharedComponent1` parameter. /// /// The shared component values on which to filter. /// The type of shared component. (The type must also be - /// one of the types used to create the ComponentGroup. + /// one of the types used to create the EntityQuery. public void SetFilter(SharedComponent1 sharedComponent1) where SharedComponent1 : struct, ISharedComponentData { var sm = ArchetypeManager.GetSharedComponentDataManager(); - var filter = new ComponentGroupFilter(); + var filter = new EntityQueryFilter(); filter.Type = FilterType.SharedComponent; filter.Shared.Count = 1; - filter.Shared.IndexInComponentGroup[0] = GetIndexInComponentGroup(TypeManager.GetTypeIndex()); + filter.Shared.IndexInEntityQuery[0] = GetIndexInEntityQuery(TypeManager.GetTypeIndex()); filter.Shared.SharedComponentIndex[0] = sm.InsertSharedComponent(sharedComponent1); SetFilter(ref filter); } /// - /// Filters this ComponentGroup based on the values of two separate shared components. + /// Filters this EntityQuery based on the values of two separate shared components. /// /// /// The filter only selects entities for which both shared component values @@ -838,9 +786,9 @@ public void SetFilter(SharedComponent1 sharedComponent1) /// Shared component values on which to filter. /// Shared component values on which to filter. /// The type of shared component. (The type must also be - /// one of the types used to create the ComponentGroup. + /// one of the types used to create the EntityQuery. /// The type of shared component. (The type must also be - /// one of the types used to create the ComponentGroup. + /// one of the types used to create the EntityQuery. public void SetFilter(SharedComponent1 sharedComponent1, SharedComponent2 sharedComponent2) where SharedComponent1 : struct, ISharedComponentData @@ -848,13 +796,13 @@ public void SetFilter(SharedComponent1 share { var sm = ArchetypeManager.GetSharedComponentDataManager(); - var filter = new ComponentGroupFilter(); + var filter = new EntityQueryFilter(); filter.Type = FilterType.SharedComponent; filter.Shared.Count = 2; - filter.Shared.IndexInComponentGroup[0] = GetIndexInComponentGroup(TypeManager.GetTypeIndex()); + filter.Shared.IndexInEntityQuery[0] = GetIndexInEntityQuery(TypeManager.GetTypeIndex()); filter.Shared.SharedComponentIndex[0] = sm .InsertSharedComponent(sharedComponent1); - filter.Shared.IndexInComponentGroup[1] = GetIndexInComponentGroup(TypeManager.GetTypeIndex()); + filter.Shared.IndexInEntityQuery[1] = GetIndexInEntityQuery(TypeManager.GetTypeIndex()); filter.Shared.SharedComponentIndex[1] = sm.InsertSharedComponent(sharedComponent2); SetFilter(ref filter); @@ -866,13 +814,13 @@ public void SetFilter(SharedComponent1 share /// /// Saves a given ComponentType's index in RequiredComponents in this group's Changed filter. /// - /// ComponentType to mark as changed on this ComponentGroup's filter. + /// ComponentType to mark as changed on this EntityQuery's filter. public void SetFilterChanged(ComponentType componentType) { - var filter = new ComponentGroupFilter(); + var filter = new EntityQueryFilter(); filter.Type = FilterType.Changed; filter.Changed.Count = 1; - filter.Changed.IndexInComponentGroup[0] = GetIndexInComponentGroup(componentType.TypeIndex); + filter.Changed.IndexInEntityQuery[0] = GetIndexInEntityQuery(componentType.TypeIndex); SetFilter(ref filter); } @@ -888,50 +836,50 @@ internal void SetFilterChangedRequiredVersion(uint requiredVersion) /// /// Saves given ComponentTypes' indices in RequiredComponents in this group's Changed filter. /// - /// Array of up to two ComponentTypes to mark as changed on this ComponentGroup's filter. + /// Array of up to two ComponentTypes to mark as changed on this EntityQuery's filter. public void SetFilterChanged(ComponentType[] componentType) { - if (componentType.Length > ComponentGroupFilter.ChangedFilter.Capacity) + if (componentType.Length > EntityQueryFilter.ChangedFilter.Capacity) throw new ArgumentException( - $"ComponentGroup.SetFilterChanged accepts a maximum of {ComponentGroupFilter.ChangedFilter.Capacity} component array length"); + $"EntityQuery.SetFilterChanged accepts a maximum of {EntityQueryFilter.ChangedFilter.Capacity} component array length"); if (componentType.Length <= 0) throw new ArgumentException( - $"ComponentGroup.SetFilterChanged component array length must be larger than 0"); + $"EntityQuery.SetFilterChanged component array length must be larger than 0"); - var filter = new ComponentGroupFilter(); + var filter = new EntityQueryFilter(); filter.Type = FilterType.Changed; filter.Changed.Count = componentType.Length; for (var i = 0; i != componentType.Length; i++) - filter.Changed.IndexInComponentGroup[i] = GetIndexInComponentGroup(componentType[i].TypeIndex); + filter.Changed.IndexInEntityQuery[i] = GetIndexInEntityQuery(componentType[i].TypeIndex); SetFilter(ref filter); } /// - /// Ensures all jobs running on this ComponentGroup complete. + /// Ensures all jobs running on this EntityQuery complete. /// public void CompleteDependency() { - m_SafetyManager.CompleteDependenciesNoChecks(m_GroupData->ReaderTypes, m_GroupData->ReaderTypesCount, + m_SafetyManager->CompleteDependenciesNoChecks(m_GroupData->ReaderTypes, m_GroupData->ReaderTypesCount, m_GroupData->WriterTypes, m_GroupData->WriterTypesCount); } /// - /// Combines all dependencies in this ComponentGroup into a single JobHandle. + /// Combines all dependencies in this EntityQuery into a single JobHandle. /// - /// JobHandle that represents the combined dependencies of this ComponentGroup + /// JobHandle that represents the combined dependencies of this EntityQuery public JobHandle GetDependency() { - return m_SafetyManager.GetDependency(m_GroupData->ReaderTypes, m_GroupData->ReaderTypesCount, + return m_SafetyManager->GetDependency(m_GroupData->ReaderTypes, m_GroupData->ReaderTypesCount, m_GroupData->WriterTypes, m_GroupData->WriterTypesCount); } /// - /// Adds another job handle to this ComponentGroup's dependencies. + /// Adds another job handle to this EntityQuery's dependencies. /// public void AddDependency(JobHandle job) { - m_SafetyManager.AddDependency(m_GroupData->ReaderTypes, m_GroupData->ReaderTypesCount, + m_SafetyManager->AddDependency(m_GroupData->ReaderTypes, m_GroupData->ReaderTypesCount, m_GroupData->WriterTypes, m_GroupData->WriterTypesCount, job); } @@ -950,10 +898,10 @@ public int GetCombinedComponentOrderVersion() } /// - /// Total number of chunks in this ComponentGroup's MatchingArchetypes list. + /// Total number of chunks in this EntityQuery's MatchingArchetypes list. /// /// First node of MatchingArchetypes linked list. - /// Number of chunks in this ComponentGroup. + /// Number of chunks in this EntityQuery. internal int CalculateNumberOfChunksWithoutFiltering() { return ComponentChunkIterator.CalculateNumberOfChunksWithoutFiltering(m_GroupData->MatchingArchetypes); @@ -964,7 +912,7 @@ internal bool AddReaderWritersToLists(ref UnsafeList reading, ref UnsafeList wri bool anyAdded = false; for (int i = 0; i < m_GroupData->ReaderTypesCount; ++i) anyAdded |= CalculateReaderWriterDependency.AddReaderTypeIndex(m_GroupData->ReaderTypes[i], ref reading, ref writing); - + for (int i = 0; i < m_GroupData->WriterTypesCount; ++i) anyAdded |=CalculateReaderWriterDependency.AddWriterTypeIndex(m_GroupData->WriterTypes[i], ref reading, ref writing); return anyAdded; @@ -979,13 +927,33 @@ internal void SyncFilterTypes() { if (m_Filter.Type == FilterType.Changed) { - fixed (int* indexInComponentGroupPtr = m_Filter.Changed.IndexInComponentGroup) + fixed (int* indexInEntityQueryPtr = m_Filter.Changed.IndexInEntityQuery) for (int i = 0; i < m_Filter.Changed.Count; ++i) { - var type = m_GroupData->RequiredComponents[indexInComponentGroupPtr[i]]; - SafetyManager.CompleteWriteDependency(type.TypeIndex); + var type = m_GroupData->RequiredComponents[indexInEntityQueryPtr[i]]; + SafetyManager->CompleteWriteDependency(type.TypeIndex); } } } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GetComponentDataArray is deprecated. Use IJobForEach or ToComponentDataArray/CopyFromComponentDataArray instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public void GetComponentDataArray() where T : struct, IComponentData + { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GetSharedComponentDataArray is deprecated. Use ArchetypeChunk.GetSharedComponentData. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public void GetSharedComponentDataArray() where T : struct, ISharedComponentData + { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GetBufferArray is deprecated. Use ArchetypeChunk.GetBufferAccessor() instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public void GetBufferArray() where T : struct, IBufferElementData + { } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("GetEntityArray is deprecated. Use IJobForEachWithEntity or ToEntityArray instead. More information: https://forum.unity.com/threads/api-deprecation-faq-0-0-23.636994/", true)] + public void GetEntityArray() + { } } } diff --git a/Unity.Entities/Iterators/EntityQuery.cs.meta b/Unity.Entities/Iterators/EntityQuery.cs.meta new file mode 100644 index 00000000..454d2f5d --- /dev/null +++ b/Unity.Entities/Iterators/EntityQuery.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f749f9fbe6d422c4799fc5957dc3f912 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity.Entities/Iterators/SharedComponentDataArray.cs b/Unity.Entities/Iterators/SharedComponentDataArray.cs deleted file mode 100644 index 93e55559..00000000 --- a/Unity.Entities/Iterators/SharedComponentDataArray.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using Unity.Collections.LowLevel.Unsafe; - -namespace Unity.Entities -{ - [Obsolete("SharedComponentDataArray is deprecated. Use chunk API instead.")] - public struct SharedComponentDataArray where T : struct, ISharedComponentData - { - private ComponentChunkIterator m_Iterator; - private ComponentChunkCache m_Cache; - private readonly SharedComponentDataManager m_sharedComponentDataManager; - private readonly int m_sharedComponentIndex; - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private readonly AtomicSafetyHandle m_Safety; -#endif - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - internal SharedComponentDataArray(SharedComponentDataManager sharedComponentDataManager, - int sharedComponentIndex, ComponentChunkIterator iterator, int length, AtomicSafetyHandle safety) -#else - internal unsafe SharedComponentDataArray(SharedComponentDataManager sharedComponentDataManager, int sharedComponentIndex, ComponentChunkIterator iterator, int length) -#endif - { - m_sharedComponentDataManager = sharedComponentDataManager; - m_sharedComponentIndex = sharedComponentIndex; - m_Iterator = iterator; - m_Cache = default(ComponentChunkCache); - - Length = length; -#if ENABLE_UNITY_COLLECTIONS_CHECKS - m_Safety = safety; -#endif - } - - public T this[int index] - { - get - { -#if ENABLE_UNITY_COLLECTIONS_CHECKS - AtomicSafetyHandle.CheckReadAndThrow(m_Safety); - if ((uint) index >= (uint) Length) - FailOutOfRangeError(index); -#endif - - if (index < m_Cache.CachedBeginIndex || index >= m_Cache.CachedEndIndex) - m_Iterator.MoveToEntityIndexAndUpdateCache(index, out m_Cache, false); - - var sharedComponent = m_Iterator.GetSharedComponentFromCurrentChunk(m_sharedComponentIndex); - return m_sharedComponentDataManager.GetSharedComponentData(sharedComponent); - } - } - -#if ENABLE_UNITY_COLLECTIONS_CHECKS - private void FailOutOfRangeError(int index) - { - throw new IndexOutOfRangeException($"Index {index} is out of range of '{Length}' Length."); - } -#endif - - public int Length { get; } - } -} diff --git a/Unity.Entities/Iterators/SharedComponentDataArray.cs.meta b/Unity.Entities/Iterators/SharedComponentDataArray.cs.meta deleted file mode 100644 index 98380507..00000000 --- a/Unity.Entities/Iterators/SharedComponentDataArray.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 36d1b790446ccf84e8be1845686c0c98 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Unity.Entities/ScriptBehaviourManager.cs b/Unity.Entities/ScriptBehaviourManager.cs index c89cf50f..bf665782 100644 --- a/Unity.Entities/ScriptBehaviourManager.cs +++ b/Unity.Entities/ScriptBehaviourManager.cs @@ -29,76 +29,4 @@ public WorldSystemFilterAttribute(WorldSystemFilterFlags flags) FilterFlags = flags; } } - - - public abstract class ScriptBehaviourManager - { -#if UNITY_EDITOR - private CustomSampler m_Sampler; -#endif - internal void CreateInstance(World world) - { - OnBeforeCreateManagerInternal(world); - try - { - OnCreateManager(); -#if UNITY_EDITOR - var type = GetType(); - m_Sampler = CustomSampler.Create($"{world.Name} {type.FullName}"); -#endif - } - catch - { - OnBeforeDestroyManagerInternal(); - OnAfterDestroyManagerInternal(); - throw; - } - } - - internal void DestroyInstance() - { - OnBeforeDestroyManagerInternal(); - OnDestroyManager(); - OnAfterDestroyManagerInternal(); - } - - protected abstract void OnBeforeCreateManagerInternal(World world); - - protected abstract void OnBeforeDestroyManagerInternal(); - protected abstract void OnAfterDestroyManagerInternal(); - - /// - /// Called when the ScriptBehaviourManager is created. - /// When a new domain is loaded, OnCreate on the necessary manager will be invoked - /// before the ScriptBehaviour will receive its first OnCreate() call. - /// - protected virtual void OnCreateManager() - { - } - - /// - /// Called when the ScriptBehaviourManager is destroyed. - /// Before Playmode exits or scripts are reloaded OnDestroy will be called on all created ScriptBehaviourManagers. - /// - protected virtual void OnDestroyManager() - { - } - - internal abstract void InternalUpdate(); - - /// - /// Execute the manager immediately. - /// - public void Update() - { -#if UNITY_EDITOR - m_Sampler?.Begin(); -#endif - InternalUpdate(); - -#if UNITY_EDITOR - m_Sampler?.End(); -#endif - } - } } diff --git a/Unity.Entities/ScriptBehaviourUpdateOrder.cs b/Unity.Entities/ScriptBehaviourUpdateOrder.cs index e7b20d7d..323f3ee7 100644 --- a/Unity.Entities/ScriptBehaviourUpdateOrder.cs +++ b/Unity.Entities/ScriptBehaviourUpdateOrder.cs @@ -53,7 +53,7 @@ public UpdateInGroupAttribute(Type groupType) public static class ScriptBehaviourUpdateOrder { private static void InsertManagerIntoSubsystemList(PlayerLoopSystem[] subsystemList, int insertIndex, T mgr) - where T : ScriptBehaviourManager + where T : ComponentSystemBase { var del = new DummyDelegateWrapper(mgr); subsystemList[insertIndex].type = typeof(T); @@ -75,7 +75,7 @@ public static void UpdatePlayerLoop(World world) for (var j = 0; j < subsystemListLength; ++j) newSubsystemList[j] = playerLoop.subSystemList[i].subSystemList[j]; InsertManagerIntoSubsystemList(newSubsystemList, - subsystemListLength + 0, world.GetOrCreateManager()); + subsystemListLength + 0, world.GetOrCreateSystem()); playerLoop.subSystemList[i].subSystemList = newSubsystemList; } else if (playerLoop.subSystemList[i].type == typeof(PreLateUpdate)) @@ -84,7 +84,7 @@ public static void UpdatePlayerLoop(World world) for (var j = 0; j < subsystemListLength; ++j) newSubsystemList[j] = playerLoop.subSystemList[i].subSystemList[j]; InsertManagerIntoSubsystemList(newSubsystemList, - subsystemListLength + 0, world.GetOrCreateManager()); + subsystemListLength + 0, world.GetOrCreateSystem()); playerLoop.subSystemList[i].subSystemList = newSubsystemList; } else if (playerLoop.subSystemList[i].type == typeof(Initialization)) @@ -93,7 +93,7 @@ public static void UpdatePlayerLoop(World world) for (var j = 0; j < subsystemListLength; ++j) newSubsystemList[j] = playerLoop.subSystemList[i].subSystemList[j]; InsertManagerIntoSubsystemList(newSubsystemList, - subsystemListLength + 0, world.GetOrCreateManager()); + subsystemListLength + 0, world.GetOrCreateSystem()); playerLoop.subSystemList[i].subSystemList = newSubsystemList; } } @@ -116,17 +116,17 @@ public static void SetPlayerLoop(PlayerLoopSystem playerLoop) internal class DummyDelegateWrapper { - internal ScriptBehaviourManager Manager => m_Manager; - private readonly ScriptBehaviourManager m_Manager; + internal ComponentSystemBase System => m_System; + private readonly ComponentSystemBase m_System; - public DummyDelegateWrapper(ScriptBehaviourManager man) + public DummyDelegateWrapper(ComponentSystemBase sys) { - m_Manager = man; + m_System = sys; } public void TriggerUpdate() { - m_Manager.Update(); + m_System.Update(); } } } diff --git a/Unity.Entities/SerializeUtility.cs b/Unity.Entities/SerializeUtility.cs index 9dc8b85d..b99b9c06 100644 --- a/Unity.Entities/SerializeUtility.cs +++ b/Unity.Entities/SerializeUtility.cs @@ -1,4 +1,4 @@ -#if !UNITY_CSHARP_TINY +#if !NET_DOTS using System; using System.Collections.Generic; using System.Linq; diff --git a/Unity.Entities/SharedComponentManager.cs b/Unity.Entities/SharedComponentManager.cs index eeb1e114..33dff445 100644 --- a/Unity.Entities/SharedComponentManager.cs +++ b/Unity.Entities/SharedComponentManager.cs @@ -112,12 +112,7 @@ private unsafe int FindNonDefaultSharedComponentIndex(int typeIndex, int hashCod var data = m_SharedComponentData[itemIndex]; if (data != null && m_SharedComponentType[itemIndex] == typeIndex) { - ulong handle; - var value = PinGCObjectAndGetAddress(data, out handle); - var res = TypeManager.Equals(newData, value, typeIndex); - UnsafeUtility.ReleaseGCObject(handle); - - if (res) + if (TypeManager.Equals(data, newData, typeIndex)) return itemIndex; } } while (m_HashLookup.TryGetNextValue(out itemIndex, ref iter)); @@ -125,14 +120,30 @@ private unsafe int FindNonDefaultSharedComponentIndex(int typeIndex, int hashCod return -1; } - internal unsafe int InsertSharedComponentAssumeNonDefault(int typeIndex, int hashCode, object newData) + private unsafe int FindNonDefaultSharedComponentIndex(int typeIndex, int hashCode, object newData) { - ulong handle; - var newDataPtr = PinGCObjectAndGetAddress(newData, out handle); + int itemIndex; + NativeMultiHashMapIterator iter; - var index = FindNonDefaultSharedComponentIndex(typeIndex, hashCode, newDataPtr); + if (!m_HashLookup.TryGetFirstValue(hashCode, out itemIndex, out iter)) + return -1; - UnsafeUtility.ReleaseGCObject(handle); + do + { + var data = m_SharedComponentData[itemIndex]; + if (data != null && m_SharedComponentType[itemIndex] == typeIndex) + { + if (TypeManager.Equals(data, newData, typeIndex)) + return itemIndex; + } + } while (m_HashLookup.TryGetNextValue(out itemIndex, ref iter)); + + return -1; + } + + internal unsafe int InsertSharedComponentAssumeNonDefault(int typeIndex, int hashCode, object newData) + { + var index = FindNonDefaultSharedComponentIndex(typeIndex, hashCode, newData); if (-1 == index) index = Add(typeIndex, hashCode, newData); @@ -194,13 +205,12 @@ public T GetSharedComponentData(int index) where T : struct public object GetSharedComponentDataBoxed(int index, int typeIndex) { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS if (index == 0) return Activator.CreateInstance(TypeManager.GetType(typeIndex)); #else if (index == 0) throw new InvalidOperationException("Implement TypeManager.GetType(typeIndex).DefaultValue"); - throw new NotImplementedException("SharedComponents not supported (yet) in Tiny"); #endif return m_SharedComponentData[index]; } @@ -219,23 +229,6 @@ public void AddReference(int index, int numRefs = 1) m_SharedComponentRefCount[index] += numRefs; } - public static unsafe int GetHashCodeFast(object target, int typeIndex) - { - ulong handle; - var ptr = PinGCObjectAndGetAddress(target, out handle); - var hashCode = TypeManager.GetHashCode(ptr, typeIndex); - UnsafeUtility.ReleaseGCObject(handle); - - return hashCode; - } - - private static unsafe void* PinGCObjectAndGetAddress(object target, out ulong handle) - { - var ptr = UnsafeUtility.PinGCObjectAndGetAddress(target, out handle); - return (byte*) ptr + TypeManager.ObjectOffset; - } - - public void RemoveReference(int index, int numRefs = 1) { if (index == 0) @@ -248,7 +241,7 @@ public void RemoveReference(int index, int numRefs = 1) return; var typeIndex = m_SharedComponentType[index]; - var hashCode = GetHashCodeFast(m_SharedComponentData[index], typeIndex); + var hashCode = TypeManager.GetHashCode(m_SharedComponentData[index], typeIndex); object sharedComponent = m_SharedComponentData[index]; (sharedComponent as IDisposable)?.Dispose(); @@ -327,7 +320,7 @@ public unsafe void MoveSharedComponents(SharedComponentDataManager srcSharedComp var srcData = srcSharedComponents.m_SharedComponentData[srcIndex]; var typeIndex = srcSharedComponents.m_SharedComponentType[srcIndex]; - var hashCode = GetHashCodeFast(srcData, typeIndex); + var hashCode = TypeManager.GetHashCode(srcData, typeIndex); var dstIndex = InsertSharedComponentAssumeNonDefault(typeIndex, hashCode, srcData); srcSharedComponents.RemoveReference(srcIndex); @@ -346,7 +339,7 @@ public unsafe void CopySharedComponents(SharedComponentDataManager srcSharedComp var srcData = srcSharedComponents.m_SharedComponentData[srcIndex]; var typeIndex = srcSharedComponents.m_SharedComponentType[srcIndex]; - var hashCode = GetHashCodeFast(srcData, typeIndex); + var hashCode = TypeManager.GetHashCode(srcData, typeIndex); var dstIndex = InsertSharedComponentAssumeNonDefault(typeIndex, hashCode, srcData); sharedComponentIndices[i] = dstIndex; @@ -375,26 +368,6 @@ public unsafe bool AllSharedComponentReferencesAreFromChunks(ArchetypeManager ar return cmp == 0; } - public static unsafe bool FastEquality_CompareBoxed(object lhs, object rhs, int typeIndex) - { - ulong lhsHandle, rhsHandle; - var valueLHS = PinGCObjectAndGetAddress(lhs, out lhsHandle); - var valueRHS = PinGCObjectAndGetAddress(rhs, out rhsHandle); - - var res = TypeManager.Equals(valueLHS, valueRHS, typeIndex); - - UnsafeUtility.ReleaseGCObject(lhsHandle); - UnsafeUtility.ReleaseGCObject(rhsHandle); - - return res; - } - - public static unsafe bool FastEquality_ComparePtr(void* lhs, void* rhs, int typeIndex) - { - var res = TypeManager.Equals(lhs, rhs, typeIndex); - return res; - } - public static unsafe bool FastEquality_CompareElements(void* lhs, void* rhs, int count, int typeIndex) { var typeInfo = TypeManager.GetTypeInfo(typeIndex); @@ -420,7 +393,7 @@ public unsafe NativeArray MoveAllSharedComponents(SharedComponentDataManage var typeIndex = srcSharedComponents.m_SharedComponentType[srcIndex]; - var hashCode = GetHashCodeFast(srcData, typeIndex); + var hashCode = TypeManager.GetHashCode(srcData, typeIndex); var dstIndex = InsertSharedComponentAssumeNonDefault(typeIndex, hashCode, srcData); m_SharedComponentRefCount[dstIndex] += srcSharedComponents.m_SharedComponentRefCount[srcIndex] - 1; @@ -465,7 +438,7 @@ public unsafe NativeArray MoveSharedComponents(SharedComponentDataManager s var srcData = srcSharedComponents.m_SharedComponentData[srcIndex]; var typeIndex = srcSharedComponents.m_SharedComponentType[srcIndex]; - var hashCode = GetHashCodeFast(srcData, typeIndex); + var hashCode = TypeManager.GetHashCode(srcData, typeIndex); var dstIndex = InsertSharedComponentAssumeNonDefault(typeIndex, hashCode, srcData); m_SharedComponentRefCount[dstIndex] += remap[srcIndex] - 1; diff --git a/Unity.Entities/Types/BufferHeader.cs b/Unity.Entities/Types/BufferHeader.cs index 4e06cf39..6554da29 100644 --- a/Unity.Entities/Types/BufferHeader.cs +++ b/Unity.Entities/Types/BufferHeader.cs @@ -34,14 +34,14 @@ public static void EnsureCapacity(BufferHeader* header, int count, int typeSize, return; int newCapacity = Math.Max(Math.Max(2 * header->Capacity, count), kMinimumCapacity); - long newBlockSize = newCapacity * typeSize; + long newBlockSize = (long)newCapacity * typeSize; byte* oldData = GetElementPointer(header); byte* newData = (byte*) UnsafeUtility.Malloc(newBlockSize, alignment, Allocator.Persistent); if (trashMode == TrashMode.RetainOldData) { - long oldBlockSize = header->Capacity * typeSize; + long oldBlockSize = (long)header->Capacity * typeSize; UnsafeUtility.MemCpy(newData, oldData, oldBlockSize); } @@ -62,7 +62,7 @@ public static void Assign(BufferHeader* header, byte* source, int count, int typ // Select between internal capacity buffer and heap buffer. byte* elementPtr = GetElementPointer(header); - UnsafeUtility.MemCpy(elementPtr, source, typeSize * count); + UnsafeUtility.MemCpy(elementPtr, source, (long)typeSize * count); header->Length = count; } @@ -103,9 +103,9 @@ public static void PatchAfterCloningChunk(Chunk* chunk) if (header->Pointer != null) // hoo boy, it's a malloc { BufferHeader newHeader = *header; - var bytesToAllocate = header->Capacity * ti.ElementSize; - var bytesToCopy = header->Length * ti.ElementSize; - newHeader.Pointer = (byte*)UnsafeUtility.Malloc(bytesToAllocate, 16, Allocator.Persistent); + long bytesToAllocate = (long)header->Capacity * ti.ElementSize; + long bytesToCopy = (long)header->Length * ti.ElementSize; + newHeader.Pointer = (byte*)UnsafeUtility.Malloc(bytesToAllocate, TypeManager.MaximumSupportedAlignment, Allocator.Persistent); UnsafeUtility.MemCpy(newHeader.Pointer, header->Pointer, bytesToCopy); *header = newHeader; } diff --git a/Unity.Entities/Types/ComponentType.cs b/Unity.Entities/Types/ComponentType.cs index 3e7f0382..d1128fca 100644 --- a/Unity.Entities/Types/ComponentType.cs +++ b/Unity.Entities/Types/ComponentType.cs @@ -30,6 +30,8 @@ public enum AccessMode public bool IsChunkComponent => TypeManager.IsChunkComponent(TypeIndex); public bool HasEntityReferences => TypeManager.HasEntityReferences(TypeIndex); + public bool IgnoreDuplicateAdd => TypeManager.IgnoreDuplicateAdd(TypeIndex); + [Obsolete("Create has been renamed. Use ReadWrite instead.", false)] [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] public static ComponentType Create() @@ -160,7 +162,7 @@ internal static unsafe bool CompareArray(ComponentType* type1, int typeCount1, C #if ENABLE_UNITY_COLLECTIONS_CHECKS public override string ToString() { -#if UNITY_CSHARP_TINY +#if NET_DOTS var name = TypeManager.GetTypeInfo(TypeIndex).StableTypeHash.ToString(); #else var name = GetManagedType().Name; diff --git a/Unity.Entities/Types/FastEquality.cs b/Unity.Entities/Types/FastEquality.cs index ead82cd2..bf70a1e6 100644 --- a/Unity.Entities/Types/FastEquality.cs +++ b/Unity.Entities/Types/FastEquality.cs @@ -11,7 +11,7 @@ namespace Unity.Entities { public static class FastEquality { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS internal static TypeInfo CreateTypeInfo() where T : struct { return CreateTypeInfo(typeof(T)); @@ -67,7 +67,7 @@ private unsafe struct PointerSize { private void* pter; } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS struct FieldData { public int Offset; diff --git a/Unity.Entities/Types/Hash128.cs b/Unity.Entities/Types/Hash128.cs index 85e46784..f8f47129 100644 --- a/Unity.Entities/Types/Hash128.cs +++ b/Unity.Entities/Types/Hash128.cs @@ -12,7 +12,7 @@ public struct Hash128 : IEquatable public unsafe override string ToString() { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS var str = new string('0', 32); fixed (char* buf = str) { diff --git a/Unity.Entities/Types/TypeManager.cs b/Unity.Entities/Types/TypeManager.cs index 093c2951..51419a3d 100644 --- a/Unity.Entities/Types/TypeManager.cs +++ b/Unity.Entities/Types/TypeManager.cs @@ -3,6 +3,8 @@ using System.Diagnostics; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Threading; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; @@ -71,26 +73,38 @@ public enum TypeCategory public const int BufferComponentTypeFlag = 1 << 27; public const int SharedComponentTypeFlag = 1 << 28; public const int ChunkComponentTypeFlag = 1<<29; - public const int ZeroSizeTypeFlag = 1<<30; + public const int ZeroSizeInChunkTypeFlag = 1<<30; public const int ClearFlagsMask = 0x00FFFFFF; public const int SystemStateSharedComponentTypeFlag = SystemStateTypeFlag | SharedComponentTypeFlag; - + public const int MaximumChunkCapacity = int.MaxValue; + public const int MaximumSupportedAlignment = 16; public const int MaximumTypesCount = 1024 * 10; + private static volatile int s_Count; -#if !UNITY_CSHARP_TINY + private static int s_InitCount = 0; +#if !NET_DOTS private static SpinLock s_CreateTypeLock; #endif public static int ObjectOffset; -#if !UNITY_CSHARP_TINY - public static IEnumerable AllTypes { get { return Enumerable.Take(s_Types, s_Count); } } - private static Dictionary s_StableTypeHashToTypeIndex; +#if !NET_DOTS + public static IEnumerable AllTypes { get { return Enumerable.Take(s_TypeInfos, s_Count); } } private static Dictionary s_ManagedTypeToIndex; #endif - static TypeInfo[] s_Types; - static Type[] s_Systems; + private static TypeInfo[] s_TypeInfos; + private static Type[] s_Systems; + private static NativeHashMap s_StableTypeHashToTypeIndex; + +#if NET_DOTS + private static List s_FastEqualityTypeInfoList; + private static List s_DynamicTypeList; + private static NativeList s_WriteGroupList; + private static NativeList s_EntityOffsetList; + private static NativeList s_BlobAssetRefOffsetList; +#endif + #if !UNITY_ZEROPLAYER internal static Type UnityEngineComponentType; @@ -101,26 +115,26 @@ public static void RegisterUnityEngineComponentType(Type type) UnityEngineComponentType = type; } #endif - private struct StaticTypeLookup + public struct EntityOffsetInfo { - public static int typeIndex; + public int Offset; } - public struct EntityOffsetInfo + public struct StaticTypeLookup { - public int Offset; + public static int typeIndex; } public struct EqualityHelper { - public delegate bool EqualsFn(T left, T right); - public delegate int HashFn(T value); + public delegate bool EqualsFn(ref T left, ref T right); + public delegate int HashFn(ref T value); public static new EqualsFn Equals; public static HashFn Hash; } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS // https://stackoverflow.com/a/27851610 static bool IsZeroSizeStruct(Type t) { @@ -129,10 +143,10 @@ static bool IsZeroSizeStruct(Type t) } #endif - // NOTE: This type will be moved into Unity.Entities.StaticTypeRegistry once Static Type Registry generation is hooked into #!UNITY_CSHARP_TINY builds + // NOTE: This type will be moved into Unity.Entities.StaticTypeRegistry once Static Type Registry generation is hooked into #!NET_DOTS builds public readonly struct TypeInfo { -#if !UNITY_CSHARP_TINY +#if !NET_DOTS public TypeInfo(Type type, int typeIndex, int size, TypeCategory category, FastEquality.TypeInfo typeInfo, EntityOffsetInfo[] entityOffsets, EntityOffsetInfo[] blobAssetRefOffsets, ulong memoryOrdering, int bufferCapacity, int elementSize, int alignmentInBytes, ulong stableTypeHash, int* writeGroups, int writeGroupCount, int maximumChunkCapacity) { Type = type; @@ -160,7 +174,7 @@ public TypeInfo(Type type, int typeIndex, int size, TypeCategory category, FastE if (typeIndex != 0) { if (SizeInChunk == 0) - TypeIndex |= ZeroSizeTypeFlag; + TypeIndex |= ZeroSizeInChunkTypeFlag; if(Category == TypeCategory.ISharedComponentData) TypeIndex |= SharedComponentTypeFlag; @@ -185,7 +199,8 @@ public TypeInfo(Type type, int typeIndex, int size, TypeCategory category, FastE public readonly int SizeInChunk; // Normally the same as SizeInChunk (for components), but for buffers means size of an individual element. public readonly int ElementSize; - // Sometimes we need to know not only the size, but the alignment. + // Sometimes we need to know not only the size, but the alignment. For buffers this is the alignment + // of an individual element. public readonly int AlignmentInBytes; public readonly int BufferCapacity; public readonly FastEquality.TypeInfo FastEqualityTypeInfo; @@ -201,53 +216,65 @@ public TypeInfo(Type type, int typeIndex, int size, TypeCategory category, FastE public readonly int WriteGroupCount; public readonly int MaximumChunkCapacity; + // Alignment of this type in a chunk. Normally the same + // as AlignmentInBytes, but that might be less than this + // for buffer elements, whereas the buffer itself must + // be aligned to the maximum. + public int AlignmentInChunkInBytes { + get { + if (Category == TypeCategory.BufferData) + return MaximumSupportedAlignment; + return AlignmentInBytes; + } + } + public bool IsZeroSized => SizeInChunk == 0; public bool HasWriteGroups => WriteGroupCount > 0; #else - public TypeInfo(int typeIndex, TypeCategory category, int entityOffsetCount, int entityOffsetStartIndex, ulong memoryOrdering, ulong stableTypeHash, int bufferCapacity, int typeSize, int elementSize, int alignmentInBytes, bool isSystemStateComponent, bool isSystemStateSharedComponent) + // NOTE: Any change to this constructor prototype requires a change in the TypeRegGen to match + public TypeInfo(int typeIndex, TypeCategory category, int entityOffsetCount, int entityOffsetStartIndex, + ulong memoryOrdering, ulong stableTypeHash, int bufferCapacity, int typeSize, int elementSize, + int alignmentInBytes, int maxChunkCapacity, int writeGroupCount, int writeGroupStartIndex, + int blobAssetRefOffsetCount, int blobAssetRefOffsetStartIndex, int fastEqualityIndex, bool usesDynamicInfo) { TypeIndex = typeIndex; Category = category; EntityOffsetCount = entityOffsetCount; EntityOffsetStartIndex = entityOffsetStartIndex; - //TODO: add BlobAssetRefOffset support to the static type registry - BlobAssetRefOffsetCount = 0; - BlobAssetRefOffsetStartIndex = 0; MemoryOrdering = memoryOrdering; StableTypeHash = stableTypeHash; BufferCapacity = bufferCapacity; SizeInChunk = typeSize; - AlignmentInBytes = alignmentInBytes; ElementSize = elementSize; - - if (typeIndex != 0) - { - if (SizeInChunk == 0) - TypeIndex |= ZeroSizeTypeFlag; - - if(Category == TypeCategory.ISharedComponentData) - TypeIndex |= SharedComponentTypeFlag; - - //System state shared components are also considered system state components - if (isSystemStateComponent || isSystemStateSharedComponent) - TypeIndex |= SystemStateTypeFlag; - - if (isSystemStateSharedComponent) - TypeIndex |= SystemStateSharedComponentTypeFlag; - - if (Category == TypeCategory.BufferData) - TypeIndex |= BufferComponentTypeFlag; - - if (EntityOffsetCount == 0) - TypeIndex |= HasNoEntityReferencesFlag; - } + AlignmentInBytes = alignmentInBytes; + MaximumChunkCapacity = maxChunkCapacity; + WriteGroupCount = writeGroupCount; + WriteGroupStartIndex = writeGroupStartIndex; + BlobAssetRefOffsetCount = blobAssetRefOffsetCount; + BlobAssetRefOffsetStartIndex = blobAssetRefOffsetStartIndex; + FastEqualityIndex = fastEqualityIndex; // Only used for Hybrid types (should be removed once we code gen all equality cases) + UsesDynamicInfo = usesDynamicInfo; } public readonly int TypeIndex; // Note that this includes internal capacity and header overhead for buffers. public readonly int SizeInChunk; - // Sometimes we need to know not only the size, but the alignment. + // Sometimes we need to know not only the size, but the alignment. For buffers this is the alignment + // of an individual element. public readonly int AlignmentInBytes; + // Alignment of this type in a chunk. Normally the same + // as AlignmentInBytes, but that might be less than this + // for buffer elements, whereas the buffer itself must + // be aligned to the maximum. + public int AlignmentInChunkInBytes + { + get + { + if (Category == TypeCategory.BufferData) + return MaximumSupportedAlignment; + return AlignmentInBytes; + } + } // Normally the same as SizeInChunk (for components), but for buffers means size of an individual element. public readonly int ElementSize; public readonly int BufferCapacity; @@ -255,33 +282,74 @@ public TypeInfo(int typeIndex, TypeCategory category, int entityOffsetCount, int public readonly ulong MemoryOrdering; public readonly ulong StableTypeHash; public readonly int EntityOffsetCount; - public readonly int EntityOffsetStartIndex; + internal readonly int EntityOffsetStartIndex; public readonly int BlobAssetRefOffsetCount; - public readonly int BlobAssetRefOffsetStartIndex; + internal readonly int BlobAssetRefOffsetStartIndex; + public readonly int WriteGroupCount; + internal readonly int WriteGroupStartIndex; + public readonly int MaximumChunkCapacity; + internal readonly int FastEqualityIndex; + internal readonly bool UsesDynamicInfo; + + public bool IsZeroSized => !UsesDynamicInfo && SizeInChunk == 0; + public bool HasWriteGroups => WriteGroupCount > 0; + + // NOTE: We explictly exclude Type as a member of TypeInfo so the type can remain a ValueType + public Type Type => StaticTypeRegistry.StaticTypeRegistry.Types[TypeIndex & ClearFlagsMask]; + + // To consider: pinning the static array ptr and storing the correct offset pinned ptr for TypeInfo and the nremove these getters + public EntityOffsetInfo* EntityOffsets + { + get + { + if (EntityOffsetCount > 0) + { + return ((EntityOffsetInfo*)UnsafeUtility.AddressOf(ref StaticTypeRegistry.StaticTypeRegistry.EntityOffsets[0])) + EntityOffsetStartIndex; + } - public bool IsZeroSized => SizeInChunk == 0; - public EntityOffsetInfo* EntityOffsets => EntityOffsetCount > 0 ? ((EntityOffsetInfo*) UnsafeUtility.AddressOf(ref StaticTypeRegistry.StaticTypeRegistry.EntityOffsets[0])) + EntityOffsetStartIndex : null; - public EntityOffsetInfo* BlobAssetRefOffsets => BlobAssetRefOffsetCount > 0 ? ((EntityOffsetInfo*) UnsafeUtility.AddressOf(ref StaticTypeRegistry.StaticTypeRegistry.EntityOffsets[0])) + BlobAssetRefOffsetStartIndex : null; + return null; + } + } + public EntityOffsetInfo* BlobAssetRefOffsets + { + get + { + if (BlobAssetRefOffsetCount > 0) + { + return ((EntityOffsetInfo*)UnsafeUtility.AddressOf(ref StaticTypeRegistry.StaticTypeRegistry.BlobAssetReferenceOffsets[0])) + BlobAssetRefOffsetStartIndex; + } + + return null; + } + } + public int* WriteGroups + { + get + { + if (WriteGroupCount> 0) + { + return ((int*)UnsafeUtility.AddressOf(ref StaticTypeRegistry.StaticTypeRegistry.WriteGroups[0])) + WriteGroupStartIndex; + } + + return null; + } + } #endif } public static unsafe TypeInfo GetTypeInfo(int typeIndex) { - return s_Types[typeIndex & ClearFlagsMask]; + return s_TypeInfos[typeIndex & ClearFlagsMask]; } public static TypeInfo GetTypeInfo() where T : struct { - return s_Types[GetTypeIndex() & ClearFlagsMask]; + return s_TypeInfos[GetTypeIndex() & ClearFlagsMask]; } public static Type GetType(int typeIndex) { - #if !UNITY_CSHARP_TINY - return s_Types[typeIndex & ClearFlagsMask].Type; - #else - return StaticTypeRegistry.StaticTypeRegistry.Types[typeIndex & ClearFlagsMask]; - #endif + return s_TypeInfos[typeIndex & ClearFlagsMask].Type; } public static int GetTypeCount() @@ -293,12 +361,14 @@ public static int GetTypeCount() public static bool IsSystemStateComponent(int typeIndex) => (typeIndex & SystemStateTypeFlag) != 0; public static bool IsSystemStateSharedComponent(int typeIndex) => (typeIndex & SystemStateSharedComponentTypeFlag) == SystemStateSharedComponentTypeFlag; public static bool IsSharedComponent(int typeIndex) => (typeIndex & SharedComponentTypeFlag) != 0; - public static bool IsZeroSized(int typeIndex) => (typeIndex & ZeroSizeTypeFlag) != 0; + public static bool IsZeroSized(int typeIndex) => (typeIndex & ZeroSizeInChunkTypeFlag) != 0; public static bool IsChunkComponent(int typeIndex) => (typeIndex & ChunkComponentTypeFlag) != 0; public static bool HasEntityReferences(int typeIndex) => (typeIndex & HasNoEntityReferencesFlag) == 0; - public static int MakeChunkComponentTypeIndex(int typeIndex) => (typeIndex | ChunkComponentTypeFlag | ZeroSizeTypeFlag); - public static int ChunkComponentToNormalTypeIndex(int typeIndex) => s_Types[typeIndex & ClearFlagsMask].TypeIndex; + public static bool IgnoreDuplicateAdd(int typeIndex) => (typeIndex & ZeroSizeInChunkTypeFlag) != 0 && (typeIndex & SharedComponentTypeFlag) == 0; + + public static int MakeChunkComponentTypeIndex(int typeIndex) => (typeIndex | ChunkComponentTypeFlag | ZeroSizeInChunkTypeFlag); + public static int ChunkComponentToNormalTypeIndex(int typeIndex) => s_TypeInfos[typeIndex & ClearFlagsMask].TypeIndex; // TODO: this creates a dependency on UnityEngine, but makes splitting code in separate assemblies easier. We need to remove it during the biggere refactor. private struct ObjectOffsetType @@ -307,100 +377,185 @@ private struct ObjectOffsetType private void* v1; } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS private static void AddTypeInfoToTables(TypeInfo typeInfo) { - s_Types[typeInfo.TypeIndex & ClearFlagsMask] = typeInfo; - s_StableTypeHashToTypeIndex.Add(typeInfo.StableTypeHash, typeInfo.TypeIndex); + s_TypeInfos[typeInfo.TypeIndex & ClearFlagsMask] = typeInfo; + s_StableTypeHashToTypeIndex.TryAdd(typeInfo.StableTypeHash, typeInfo.TypeIndex); s_ManagedTypeToIndex.Add(typeInfo.Type, typeInfo.TypeIndex); ++s_Count; } #endif - public static void Initialize() + /// + /// Initializes the TypeManager with all ECS type information. Additional calls without a matching Shutdown() simply increment the TypeManager ref-count and return + /// + /// Returns the TypeManager ref-count. It is expected for each Initialize() call to be matched by a Shutdown() call. + public static int Initialize() { - if (s_Types != null) - return; + int initVal = Interlocked.Increment(ref s_InitCount); + if (initVal != 1) + return initVal; ObjectOffset = UnsafeUtility.SizeOf(); -#if !UNITY_CSHARP_TINY - s_CreateTypeLock = new SpinLock(); - s_ManagedTypeToIndex = new Dictionary(1000); -#endif - s_Types = new TypeInfo[MaximumTypesCount]; - - #if !UNITY_CSHARP_TINY - s_StableTypeHashToTypeIndex = new Dictionary(); + #if !NET_DOTS + s_CreateTypeLock = new SpinLock(); + s_ManagedTypeToIndex = new Dictionary(1000); #endif - s_Count = 0; - - #if !UNITY_CSHARP_TINY - s_Types[s_Count++] = new TypeInfo(null, 0, 0, TypeCategory.ComponentData, FastEquality.TypeInfo.Null, null, null, 0, -1, 0, 1, 0, null, 0, int.MaxValue); + s_TypeInfos = new TypeInfo[MaximumTypesCount]; - // This must always be first so that Entity is always index 0 in the archetype - AddTypeInfoToTables(new TypeInfo(typeof(Entity), 1, sizeof(Entity), TypeCategory.EntityData, - FastEquality.CreateTypeInfo(), EntityRemapUtility.CalculateEntityOffsets(), null, 0, -1, sizeof(Entity), UnsafeUtility.AlignOf(), CalculateStableTypeHash(typeof(Entity)), null, 0, int.MaxValue)); + s_Count = 0; + #if !NET_DOTS + s_TypeInfos[s_Count++] = new TypeInfo(null, 0, 0, TypeCategory.ComponentData, FastEquality.TypeInfo.Null, null, null, 0, -1, 0, 1, 0, null, 0, int.MaxValue); InitializeAllComponentTypes(); #else + s_FastEqualityTypeInfoList = new List(); + s_DynamicTypeList = new List(); + s_EntityOffsetList = new NativeList(Allocator.Persistent); + s_BlobAssetRefOffsetList = new NativeList(Allocator.Persistent); + s_WriteGroupList = new NativeList(Allocator.Persistent); + + // Registers all types and their static info from the static type rgistry + // Note: this will call AddStaticTypesToRegistry which will initialize s_StableTypeHashToTypeIndex StaticTypeRegistry.StaticTypeRegistry.RegisterStaticTypes(); #endif + + return initVal; + } + + /// + /// Removes all ECS type information and any allocated memory when the TypeManager ref-count == 1. That is, + /// the TypeManager will shutdown on the last call to Shutdown() matching the number of invocations of Initialize(). + /// + /// Returns the TypeManager ref-count. It is expected for each Shutdown() call to match a previous Initialize() call. + public static int Shutdown() + { + int initVal = Interlocked.Decrement(ref s_InitCount); + + if (initVal < 0) + throw new Exception("Calling TypeManager.Shutdown() before TypeManager.Initialize() has ever been called"); + + if (initVal == 0) + { + #if !NET_DOTS + ClearStaticTypeLookup(); + #endif + + s_TypeInfos = null; + s_Count = 0; + s_StableTypeHashToTypeIndex.Dispose(); + #if NET_DOTS + s_Systems = null; + s_EntityOffsetList.Dispose(); + s_BlobAssetRefOffsetList.Dispose(); + s_WriteGroupList.Dispose(); + #else + s_ManagedTypeToIndex.Clear(); + #endif + } + + return initVal; } -#if UNITY_CSHARP_TINY +#if !NET_DOTS + static void ClearStaticTypeLookup() + { + var staticLookupGenericType = Type.GetType("Unity.Entities.TypeManager+StaticTypeLookup`1"); + for (int i = 1; i < s_Count; ++i) + { + var type = s_TypeInfos[i].Type; + var staticLookupType = staticLookupGenericType.MakeGenericType(type); + var typeIndexField = staticLookupType.GetField("typeIndex", BindingFlags.Static | BindingFlags.Public); + typeIndexField.SetValue(null, 0); + } + } +#endif + +#if NET_DOTS // Called by the StaticTypeRegistry - internal static void AddStaticTypesFromRegistry(ref TypeInfo[] typeArray, int count) + internal static void AddStaticTypesFromRegistry(in TypeInfo[] typeInfoArray/*, int count*/) { - if (count >= MaximumTypesCount) + if (typeInfoArray.Length >= MaximumTypesCount) throw new Exception("More types detected than MaximumTypesCount. Increase the static buffer size."); s_Count = 0; - for (int i = 0; i < count; ++i) + + if (s_StableTypeHashToTypeIndex.IsCreated) + s_StableTypeHashToTypeIndex.Dispose(); + + s_StableTypeHashToTypeIndex = new NativeHashMap(typeInfoArray.Length * 2, Allocator.Persistent); // Extra room added for dynamically added types + + for (int i = 0; i < typeInfoArray.Length; ++i) { - s_Types[s_Count++] = typeArray[i]; + TypeInfo typeInfo = typeInfoArray[i]; + s_TypeInfos[s_Count++] = typeInfo; + + if (!s_StableTypeHashToTypeIndex.TryAdd(typeInfo.StableTypeHash, typeInfo.TypeIndex)) + throw new Exception("Failed to add hash to StableTypeHash -> typeIndex dictionary."); } } // Called by the StaticTypeRegistry - internal static void AddStaticSystemsFromRegistry(ref Type[] systemArray) + internal static void AddStaticSystemsFromRegistry(in Type[] systemArray) { s_Systems = systemArray; } #endif -#if !UNITY_CSHARP_TINY +#if !NET_DOTS static void InitializeAllComponentTypes() { - var componentTypeSet = new HashSet(); - - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + var lockTaken = false; + try { - if (!IsAssemblyReferencingEntities(assembly)) - continue; + s_CreateTypeLock.Enter(ref lockTaken); - foreach (var type in assembly.GetTypes()) + var componentTypeSet = new HashSet(); + + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { - if (type.IsAbstract || !type.IsValueType) - continue; - if (!UnsafeUtility.IsUnmanaged(type)) + if (!IsAssemblyReferencingEntities(assembly)) continue; - if (typeof(IComponentData).IsAssignableFrom(type) || - typeof(ISharedComponentData).IsAssignableFrom(type) || - typeof(IBufferElementData).IsAssignableFrom(type)) + foreach (var type in assembly.GetTypes()) { - componentTypeSet.Add(type); + if (type.IsAbstract || !type.IsValueType) + continue; + + // XXX There's a bug in the Unity Mono scripting backend where if the + // Mono type hasn't been initialized, the IsUnmanaged result is wrong. + // We force it to be fully initialized by creating an instance until + // that bug is fixed. + try + { + var inst = Activator.CreateInstance(type); + } catch (Exception) + { + // ignored + } + + if (!UnsafeUtility.IsUnmanaged(type)) + continue; + + if (typeof(IComponentData).IsAssignableFrom(type) || + typeof(ISharedComponentData).IsAssignableFrom(type) || + typeof(IBufferElementData).IsAssignableFrom(type)) + { + componentTypeSet.Add(type); + } } } - } - var lockTaken = false; - try - { - s_CreateTypeLock.Enter(ref lockTaken); + s_StableTypeHashToTypeIndex = new NativeHashMap(componentTypeSet.Count * 2, Allocator.Persistent); // Extra room added for dynamically added types + + // This must always be first so that Entity is always first in the archetype + AddTypeInfoToTables(new TypeInfo(typeof(Entity), 1, sizeof(Entity), TypeCategory.EntityData, + FastEquality.CreateTypeInfo(), EntityRemapUtility.CalculateEntityOffsets(), null, 0, -1, + sizeof(Entity), UnsafeUtility.AlignOf(), CalculateStableTypeHash(typeof(Entity)), null, 0, int.MaxValue)); var componentTypeCount = componentTypeSet.Count; var componentTypes = new Type[componentTypeCount]; @@ -411,7 +566,9 @@ static void InitializeAllComponentTypes() var startTypeIndex = s_Count; for (int i = 0; i < componentTypes.Length; i++) + { typeIndexByType[componentTypes[i]] = startTypeIndex + i; + } GatherWriteGroups(componentTypes, startTypeIndex, typeIndexByType, writeGroupByType); AddAllComponentTypes(componentTypes, startTypeIndex, writeGroupByType); @@ -472,6 +629,11 @@ private static void GatherWriteGroups(Type[] componentTypes, int startTypeIndex, foreach (var attribute in type.GetCustomAttributes(typeof(WriteGroupAttribute))) { var attr = (WriteGroupAttribute) attribute; + if (!typeIndexByType.ContainsKey(attr.TargetType)) + { + Debug.LogError($"GatherWriteGroups: looking for {attr.TargetType} but it hasn't been set up yet"); + } + int targetTypeIndex = typeIndexByType[attr.TargetType]; if (!writeGroupByType.ContainsKey(targetTypeIndex)) @@ -501,8 +663,8 @@ private static int FindTypeIndex(Type type) { for (var i = 0; i != s_Count; i++) { - var c = s_Types[i]; - if (StaticTypeRegistry.StaticTypeRegistry.Types[c.TypeIndex & ClearFlagsMask] == type) + var c = s_TypeInfos[i]; + if (c.Type == type) return c.TypeIndex; } @@ -513,6 +675,8 @@ private static int FindTypeIndex(Type type) public static int GetTypeIndex() { var typeIndex = StaticTypeLookup.typeIndex; + // with NET_DOTS, this could be a straight return without a 0 check, + // if the static typereg code were to set the generic field during init if (typeIndex != 0) return typeIndex; @@ -530,17 +694,17 @@ public static int GetTypeIndex(Type type) public static bool Equals(ref T left, ref T right) where T : struct { - #if !UNITY_CSHARP_TINY + #if !NET_DOTS var typeInfo = TypeManager.GetTypeInfo().FastEqualityTypeInfo; return FastEquality.Equals(ref left, ref right, typeInfo); #else - return EqualityHelper.Equals(left, right); + return EqualityHelper.Equals(ref left, ref right); #endif } public static bool Equals(void* left, void* right, int typeIndex) { - #if !UNITY_CSHARP_TINY + #if !NET_DOTS var typeInfo = TypeManager.GetTypeInfo(typeIndex).FastEqualityTypeInfo; return FastEquality.Equals(left, right, typeInfo); #else @@ -548,19 +712,51 @@ public static bool Equals(void* left, void* right, int typeIndex) #endif } + public static bool Equals(object left, object right, int typeIndex) + { + #if !NET_DOTS + var leftptr = (byte*) UnsafeUtility.PinGCObjectAndGetAddress(left, out var lhandle) + ObjectOffset; + var rightptr = (byte*) UnsafeUtility.PinGCObjectAndGetAddress(right, out var rhandle) + ObjectOffset; + + var typeInfo = GetTypeInfo(typeIndex).FastEqualityTypeInfo; + var result = FastEquality.Equals(leftptr, rightptr, typeInfo); + + UnsafeUtility.ReleaseGCObject(lhandle); + UnsafeUtility.ReleaseGCObject(rhandle); + return result; + #else + return StaticTypeRegistry.StaticTypeRegistry.Equals(left, right, typeIndex & ClearFlagsMask); + #endif + } + + public static bool Equals(object left, void* right, int typeIndex) + { + #if !NET_DOTS + var leftptr = (byte*) UnsafeUtility.PinGCObjectAndGetAddress(left, out var lhandle) + ObjectOffset; + + var typeInfo = GetTypeInfo(typeIndex).FastEqualityTypeInfo; + var result = FastEquality.Equals(leftptr, right, typeInfo); + + UnsafeUtility.ReleaseGCObject(lhandle); + return result; + #else + return StaticTypeRegistry.StaticTypeRegistry.Equals(left, right, typeIndex & ClearFlagsMask); + #endif + } + public static int GetHashCode(ref T val) where T : struct { - #if !UNITY_CSHARP_TINY + #if !NET_DOTS var typeInfo = TypeManager.GetTypeInfo().FastEqualityTypeInfo; return FastEquality.GetHashCode(ref val, typeInfo); #else - return EqualityHelper.Hash(val); + return EqualityHelper.Hash(ref val); #endif } public static int GetHashCode(void* val, int typeIndex) { - #if !UNITY_CSHARP_TINY + #if !NET_DOTS var typeInfo = TypeManager.GetTypeInfo(typeIndex).FastEqualityTypeInfo; return FastEquality.GetHashCode(val, typeInfo); #else @@ -568,18 +764,33 @@ public static int GetHashCode(void* val, int typeIndex) #endif } + public static int GetHashCode(object val, int typeIndex) + { + #if !NET_DOTS + var ptr = (byte*) UnsafeUtility.PinGCObjectAndGetAddress(val, out var handle) + ObjectOffset; + + var typeInfo = GetTypeInfo(typeIndex).FastEqualityTypeInfo; + var result = FastEquality.GetHashCode(ptr, typeInfo); + + UnsafeUtility.ReleaseGCObject(handle); + return result; + #else + return StaticTypeRegistry.StaticTypeRegistry.BoxedGetHashCode(val, typeIndex & ClearFlagsMask); + #endif + } + public static int GetTypeIndexFromStableTypeHash(ulong stableTypeHash) { -#if !UNITY_CSHARP_TINY - if(s_StableTypeHashToTypeIndex.TryGetValue(stableTypeHash, out var typeIndex)) - return typeIndex; - return -1; -#else - throw new InvalidOperationException("Not allowed in Project Tiny"); -#endif + #if !NET_DOTS + if(s_StableTypeHashToTypeIndex.TryGetValue(stableTypeHash, out var typeIndex)) + return typeIndex; + return -1; + #else + throw new InvalidOperationException("Not allowed in Project Tiny"); + #endif } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS public static bool IsAssemblyReferencingEntities(Assembly assembly) { const string entitiesAssemblyName = "Unity.Entities"; @@ -610,13 +821,13 @@ public static string[] SystemNames public static string SystemName(Type t) { -#if UNITY_CSHARP_TINY - int index = GetSystemTypeIndex(t); - if (index < 0 || index >= SystemNames.Length) return "null"; - return SystemNames[index]; -#else - return t.FullName; -#endif + #if NET_DOTS + int index = GetSystemTypeIndex(t); + if (index < 0 || index >= SystemNames.Length) return "null"; + return SystemNames[index]; + #else + return t.FullName; + #endif } public static int GetSystemTypeIndex(Type t) @@ -631,13 +842,13 @@ public static int GetSystemTypeIndex(Type t) public static bool IsSystemAGroup(Type t) { -#if !UNITY_CSHARP_TINY - return t.IsSubclassOf(typeof(ComponentSystemGroup)); -#else - int index = GetSystemTypeIndex(t); - var isGroup = StaticTypeRegistry.StaticTypeRegistry.SystemIsGroup[index]; - return isGroup; -#endif + #if !NET_DOTS + return t.IsSubclassOf(typeof(ComponentSystemGroup)); + #else + int index = GetSystemTypeIndex(t); + var isGroup = StaticTypeRegistry.StaticTypeRegistry.SystemIsGroup[index]; + return isGroup; + #endif } /// @@ -665,34 +876,34 @@ public static Attribute[] GetSystemAttributes(Type systemType) /// public static Attribute[] GetSystemAttributes(Type systemType, Type attributeType) { -#if !UNITY_CSHARP_TINY - var objArr = systemType.GetCustomAttributes(attributeType, true); - var attr = new Attribute[objArr.Length]; - for (int i = 0; i < objArr.Length; i++) { - attr[i] = objArr[i] as Attribute; - } - return attr; -#else - Attribute[] attr = StaticTypeRegistry.StaticTypeRegistry.GetSystemAttributes(systemType); - int count = 0; - for (int i = 0; i < attr.Length; ++i) - { - if (attr[i].GetType() == attributeType) + #if !NET_DOTS + var objArr = systemType.GetCustomAttributes(attributeType, true); + var attr = new Attribute[objArr.Length]; + for (int i = 0; i < objArr.Length; i++) { + attr[i] = objArr[i] as Attribute; + } + return attr; + #else + Attribute[] attr = StaticTypeRegistry.StaticTypeRegistry.GetSystemAttributes(systemType); + int count = 0; + for (int i = 0; i < attr.Length; ++i) { - ++count; + if (attr[i].GetType() == attributeType) + { + ++count; + } } - } - Attribute[] result = new Attribute[count]; - count = 0; - for (int i = 0; i < attr.Length; ++i) - { - if (attr[i].GetType() == attributeType) + Attribute[] result = new Attribute[count]; + count = 0; + for (int i = 0; i < attr.Length; ++i) { - result[count++] = attr[i]; + if (attr[i].GetType() == attributeType) + { + result[count++] = attr[i]; + } } - } - return result; -#endif + return result; + #endif } #if ENABLE_UNITY_COLLECTIONS_CHECKS @@ -719,21 +930,43 @@ internal static void CheckComponentType(Type type) public static NativeArray GetWriteGroupTypes(int typeIndex) { -#if UNITY_CSHARP_TINY - var arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(null, 0, Allocator.None); -#else var type = GetTypeInfo(typeIndex); var writeGroups = type.WriteGroups; var writeGroupCount = type.WriteGroupCount; var arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(writeGroups, writeGroupCount, Allocator.None); -#endif #if ENABLE_UNITY_COLLECTIONS_CHECKS NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref arr, AtomicSafetyHandle.Create()); #endif return arr; } -#if !UNITY_CSHARP_TINY + internal static int NextPowerOfTwo(int n) + { + if (n == 0) + return 1; + n--; + n |= n >> 1; + n |= n >> 2; + n |= n >> 4; + n |= n >> 8; + n |= n >> 16; + return n + 1; + } + + internal static int AlignUp(int value, int alignment) + { + int mask = alignment - 1; + if ((value & ~mask) == 0) + return value; + return (value + mask) & ~mask; + } + + internal static bool IsPowerOfTwo(int value) + { + return (value & (value - 1)) == 0; + } + +#if !NET_DOTS // // The reflection-based type registration path that we can't support with tiny csharp profile. // A generics compile-time path is temporarily used (see later in the file) until we have @@ -766,6 +999,7 @@ static void CalculatBlobAssetRefOffsetsRecurse(ref List offset } } + // Todo: Replace with code in Entities.BuildUtils static ulong CalculateMemoryOrdering(Type type) { if (type == typeof(Entity)) @@ -823,6 +1057,7 @@ private static ulong HashStringWithFNV1A64(string text) return result; } + // Todo: Replace with code in Entities.BuildUtils static ulong CalculateStableTypeHash(Type type) { return HashStringWithFNV1A64(type.AssemblyQualifiedName); @@ -881,7 +1116,7 @@ internal static TypeInfo BuildComponentType(Type type, int* writeGroups, int wri int bufferCapacity = -1; var memoryOrdering = CalculateMemoryOrdering(type); var stableTypeHash = CalculateStableTypeHash(type); - var maxChunkCapacity = int.MaxValue; + var maxChunkCapacity = MaximumChunkCapacity; var maxCapacityAttribute = type.GetCustomAttribute(); if (maxCapacityAttribute != null) @@ -898,27 +1133,37 @@ internal static TypeInfo BuildComponentType(Type type, int* writeGroups, int wri CheckIsAllowedAsComponentData(type, nameof(IComponentData)); category = TypeCategory.ComponentData; + + int sizeInBytes = UnsafeUtility.SizeOf(type); + // TODO: Implement UnsafeUtility.AlignOf(type) + // Assume an alignment of 16, unless the type itself is smaller and a power of two + alignmentInBytes = MaximumSupportedAlignment; + if (sizeInBytes < alignmentInBytes && IsPowerOfTwo(sizeInBytes)) + alignmentInBytes = sizeInBytes; + if (TypeManager.IsZeroSizeStruct(type)) componentSize = 0; else - componentSize = UnsafeUtility.SizeOf(type); + componentSize = sizeInBytes; typeInfo = FastEquality.CreateTypeInfo(type); entityOffsets = EntityRemapUtility.CalculateEntityOffsets(type); blobAssetRefOffsets = CalculatBlobAssetRefOffsets(type); - - int sizeInBytes = UnsafeUtility.SizeOf(type); - // TODO: Implement UnsafeUtility.AlignOf(type) - alignmentInBytes = 16; - if(sizeInBytes < 16 && (sizeInBytes & (sizeInBytes-1))==0) - alignmentInBytes = sizeInBytes; } else if (typeof(IBufferElementData).IsAssignableFrom(type)) { CheckIsAllowedAsComponentData(type, nameof(IBufferElementData)); category = TypeCategory.BufferData; - elementSize = UnsafeUtility.SizeOf(type); + + int sizeInBytes = UnsafeUtility.SizeOf(type); + // TODO: Implement UnsafeUtility.AlignOf(type) + // Assume an alignment of 16, unless the type itself is smaller + alignmentInBytes = MaximumSupportedAlignment; + if (sizeInBytes < alignmentInBytes && IsPowerOfTwo(sizeInBytes)) + alignmentInBytes = sizeInBytes; + + elementSize = sizeInBytes; var capacityAttribute = (InternalBufferCapacityAttribute) type.GetCustomAttribute(typeof(InternalBufferCapacityAttribute)); if (capacityAttribute != null) @@ -930,12 +1175,6 @@ internal static TypeInfo BuildComponentType(Type type, int* writeGroups, int wri typeInfo = FastEquality.CreateTypeInfo(type); entityOffsets = EntityRemapUtility.CalculateEntityOffsets(type); blobAssetRefOffsets = CalculatBlobAssetRefOffsets(type); - - int sizeInBytes = UnsafeUtility.SizeOf(type); - // TODO: Implement UnsafeUtility.AlignOf(type) - alignmentInBytes = 16; - if(sizeInBytes < 16 && (sizeInBytes & (sizeInBytes-1))==0) - alignmentInBytes = sizeInBytes; } else if (typeof(ISharedComponentData).IsAssignableFrom(type)) { diff --git a/Unity.Entities/World.cs b/Unity.Entities/World.cs new file mode 100644 index 00000000..045a5870 --- /dev/null +++ b/Unity.Entities/World.cs @@ -0,0 +1,562 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Reflection; + +namespace Unity.Entities +{ + // Obsolete + public partial class World + { + [Obsolete("BehaviourManagers have been renamed to Systems. (UnityUpgradable) -> Systems", true)] + public IEnumerable BehaviourManagers => null; + + [Obsolete("CreateManager has been renamed to CreateSystem. (UnityUpgradable) -> CreateSystem(*)", true)] + public ComponentSystemBase CreateManager(Type type, params object[] constructorArgumnents) + { + throw new NotImplementedException(); + } + + [Obsolete("GetOrCreateManager has been renamed to GetOrCreateSystem. (UnityUpgradable) -> GetOrCreateSystem(*)", true)] + public ComponentSystemBase GetOrCreateManager(Type type) + { + throw new NotImplementedException(); + } + + [Obsolete("AddManager has been renamed to AddSystem. (UnityUpgradable) -> AddSystem(*)", true)] + public T AddManager(T manager) where T : ComponentSystemBase + { + throw new NotImplementedException(); + } + + [Obsolete("GetExistingManager has been renamed to GetExistingSystem. (UnityUpgradable) -> GetExistingSystem(*)", true)] + public ComponentSystemBase GetExistingManager(Type type) + { + throw new NotImplementedException(); + } + + [Obsolete("DestroyManager has been renamed to DestroySystem. (UnityUpgradable) -> DestroySystem(*)", true)] + public void DestroyManager(ComponentSystemBase manager) + { + throw new NotImplementedException(); + } + + // These updates can not be configured automatically inline, due to the generic type param. + [Obsolete("CreateManager has been renamed to CreateSystem. (UnityUpgradable) -> CreateSystem(*)", true)] + public T CreateManager(params object[] constructorArgumnents) where T : ComponentSystemBase + { + throw new NotImplementedException(); + } + + [Obsolete("GetOrCreateManager has been renamed to GetOrCreateSystem. (UnityUpgradable) -> GetOrCreateSystem()", true)] + public T GetOrCreateManager() where T : ComponentSystemBase + { + throw new NotImplementedException(); + } + + [Obsolete("GetExistingManager has been renamed to GetExistingSystem. (UnityUpgradable) -> GetExistingSystem()", true)] + public T GetExistingManager() where T : ComponentSystemBase + { + throw new NotImplementedException(); + } + } + +#if !UNITY_ZEROPLAYER + public partial class World : IDisposable + { + public static World Active { get; set; } + + static readonly List allWorlds = new List(); + + public static ReadOnlyCollection AllWorlds => new ReadOnlyCollection(allWorlds); + +#if ENABLE_UNITY_COLLECTIONS_CHECKS + bool m_AllowGetSystem = true; +#endif + + //@TODO: What about multiple managers of the same type... + Dictionary m_SystemLookup = + new Dictionary(); + + List m_Systems = new List(); + private EntityManager m_EntityManager; + + static int ms_SystemIDAllocator = 0; + + public IEnumerable Systems => + new ReadOnlyCollection(m_Systems); + + public string Name { get; } + + public override string ToString() + { + return Name; + } + + public int Version { get; private set; } + + public EntityManager EntityManager => m_EntityManager; + + public bool IsCreated => m_Systems != null; + + public World(string name) + { + // Debug.LogError("Create World "+ name + " - " + GetHashCode()); + Name = name; + allWorlds.Add(this); + + m_EntityManager = new EntityManager(this); + } + + public void Dispose() + { + if (!IsCreated) + throw new ArgumentException("The World has already been Disposed."); + // Debug.LogError("Dispose World "+ Name + " - " + GetHashCode()); + + if (allWorlds.Contains(this)) + allWorlds.Remove(this); + +#if ENABLE_UNITY_COLLECTIONS_CHECKS + m_AllowGetSystem = false; +#endif + // Destruction should happen in reverse order to construction + for (int i = m_Systems.Count - 1; i >= 0; --i) + { + try + { + m_Systems[i].DestroyInstance(); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + // Destroy EntityManager last + m_EntityManager.DestroyInstance(); + m_EntityManager = null; + + m_Systems.Clear(); + m_SystemLookup.Clear(); + + m_Systems = null; + m_SystemLookup = null; + + if (Active == this) + Active = null; + } + + public static void DisposeAllWorlds() + { + while (allWorlds.Count != 0) + allWorlds[0].Dispose(); + } + + ComponentSystemBase CreateSystemInternal(Type type, object[] constructorArguments) + { + if (!typeof(ComponentSystemBase).IsAssignableFrom(type)) + { + throw new ArgumentException($"Type {type} must be derived from ComponentSystem or JobComponentSystem."); + } + +#if ENABLE_UNITY_COLLECTIONS_CHECKS + + if (constructorArguments != null && constructorArguments.Length != 0) + { + var constructors = + type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + if (constructors.Length == 1 && constructors[0].IsPrivate) + throw new MissingMethodException( + $"Constructing {type} failed because the constructor was private, it must be public."); + } + + m_AllowGetSystem = false; +#endif + ComponentSystemBase system; + try + { + system = Activator.CreateInstance(type, constructorArguments) as ComponentSystemBase; + } + catch (MissingMethodException) + { + Debug.LogError($"[Job]ComponentSystem {type} must be mentioned in a link.xml file, or annotated " + + "with a [Preserve] attribute to prevent its constructor from being stripped. " + + "See https://docs.unity3d.com/Manual/ManagedCodeStripping.html for more information."); + throw; + } + finally + { +#if ENABLE_UNITY_COLLECTIONS_CHECKS + m_AllowGetSystem = true; +#endif + } + + return AddSystem(system); + } + + ComponentSystemBase GetExistingSystemInternal(Type type) + { + ComponentSystemBase manager; + if (m_SystemLookup.TryGetValue(type, out manager)) + return manager; + + return null; + } + + ComponentSystemBase GetOrCreateSystemInternal(Type type) + { + var manager = GetExistingSystemInternal(type); + + return manager ?? CreateSystemInternal(type, null); + } + + void AddTypeLookup(Type type, ComponentSystemBase manager) + { + while (type != typeof(ComponentSystemBase)) + { + if (!m_SystemLookup.ContainsKey(type)) + m_SystemLookup.Add(type, manager); + + type = type.BaseType; + } + } + + void RemoveSystemInternal(ComponentSystemBase manager) + { + if (!m_Systems.Remove(manager)) + throw new ArgumentException($"manager does not exist in the world"); + ++Version; + + var type = manager.GetType(); + while (type != typeof(ComponentSystemBase)) + { + if (m_SystemLookup[type] == manager) + { + m_SystemLookup.Remove(type); + + foreach (var otherManager in m_Systems) + if (otherManager.GetType().IsSubclassOf(type)) + AddTypeLookup(otherManager.GetType(), otherManager); + } + + type = type.BaseType; + } + } + + void CheckGetOrCreateSystem() + { +#if ENABLE_UNITY_COLLECTIONS_CHECKS + if (!IsCreated) + throw new ArgumentException("The World has already been Disposed."); + if (!m_AllowGetSystem) + throw new ArgumentException( + "You are not allowed to get or create more systems during destruction and constructor of a system."); +#endif + } + + void CheckCreated() + { +#if ENABLE_UNITY_COLLECTIONS_CHECKS + if (!IsCreated) + throw new ArgumentException("The World has already been Disposed."); +#endif + } + + public ComponentSystemBase CreateSystem(Type type, params object[] constructorArgumnents) + { + CheckGetOrCreateSystem(); + + return CreateSystemInternal(type, constructorArgumnents); + } + + public T CreateSystem(params object[] constructorArgumnents) where T : ComponentSystemBase + { + CheckGetOrCreateSystem(); + + return (T) CreateSystemInternal(typeof(T), constructorArgumnents); + } + + public T GetOrCreateSystem() where T : ComponentSystemBase + { + CheckGetOrCreateSystem(); + + return (T) GetOrCreateSystemInternal(typeof(T)); + } + + public ComponentSystemBase GetOrCreateSystem(Type type) + { + CheckGetOrCreateSystem(); + + return GetOrCreateSystemInternal(type); + } + + public T AddSystem(T system) where T : ComponentSystemBase + { + CheckGetOrCreateSystem(); + + m_Systems.Add(system); + AddTypeLookup(system.GetType(), system); + + try + { + system.CreateInstance(this); + } + catch + { + RemoveSystemInternal(system); + throw; + } + ++Version; + return system; + } + + public T GetExistingSystem() where T : ComponentSystemBase + { + CheckGetOrCreateSystem(); + + return (T) GetExistingSystemInternal(typeof(T)); + } + + public ComponentSystemBase GetExistingSystem(Type type) + { + CheckGetOrCreateSystem(); + + return GetExistingSystemInternal(type); + } + + public void DestroySystem(ComponentSystemBase system) + { + CheckGetOrCreateSystem(); + + RemoveSystemInternal(system); + system.DestroyInstance(); + } + + public bool QuitUpdate { get; set; } + + internal static int AllocateSystemID() + { + return ++ms_SystemIDAllocator; + } + } +#else + public partial class World : IDisposable + { + public static World Active { get; set; } + + static readonly List allWorlds = new List(); + + public static World[] AllWorlds => allWorlds.ToArray(); + +#if ENABLE_UNITY_COLLECTIONS_CHECKS + bool m_AllowGetSystem = true; +#endif + + //@TODO: What about multiple managers of the same type... + List m_Systems = new List(); + private EntityManager m_EntityManager; + + int m_SystemIDAllocator = 0; + + public ComponentSystemBase[] Systems => m_Systems.ToArray(); + + public string Name { get; } + + public override string ToString() + { + return Name; + } + + public int Version { get; private set; } + + public EntityManager EntityManager => m_EntityManager; + + public bool IsCreated => true; + + public World(string name) + { + // Debug.LogError("Create World "+ name + " - " + GetHashCode()); + Name = name; + allWorlds.Add(this); + + m_EntityManager = new EntityManager(this); + Version++; + } + + public void Dispose() + { + if (!IsCreated) + throw new ArgumentException("World is already disposed"); + // Debug.LogError("Dispose World "+ Name + " - " + GetHashCode()); + + if (allWorlds.Contains(this)) + allWorlds.Remove(this); + +#if ENABLE_UNITY_COLLECTIONS_CHECKS + m_AllowGetSystem = false; +#endif + + // Destruction should happen in reverse order to construction + for (int i = m_Systems.Count - 1; i >= 0; --i) + { + try + { + m_Systems[i].DestroyInstance(); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + // Destroy EntityManager last + m_EntityManager.DestroyInstance(); + m_EntityManager = null; + + m_Systems.Clear(); + m_Systems = null; + + if (Active == this) + Active = null; + } + + public static void DisposeAllWorlds() + { + while (allWorlds.Count != 0) + allWorlds[0].Dispose(); + } + + private ComponentSystemBase CreateSystemInternal() where T : new() + { +#if ENABLE_UNITY_COLLECTIONS_CHECKS + if (!m_AllowGetSystem) + throw new ArgumentException( + "During destruction of a system you are not allowed to create more systems."); + + m_AllowGetSystem = true; +#endif + ComponentSystemBase system; + try + { +#if !NET_DOTS + system = new T() as ComponentSystemBase; +#else + system = TypeManager.ConstructSystem(typeof(T)); +#endif + } + catch + { +#if ENABLE_UNITY_COLLECTIONS_CHECKS + m_AllowGetSystem = false; +#endif + throw; + } + + return AddSystem(system); + } + + private ComponentSystemBase GetExistingSystemInternal() + { + return GetExistingSystem(typeof(T)); + } + + private ComponentSystemBase GetExistingSystemInternal(Type type) + { +#if ENABLE_UNITY_COLLECTIONS_CHECKS + if (!IsCreated) + throw new ArgumentException("During destruction "); + if (!m_AllowGetSystem) + throw new ArgumentException( + "During destruction of a system you are not allowed to get or create more systems."); +#endif + + for (int i = 0; i < m_Systems.Count; ++i) { + var mgr = m_Systems[i]; + if (type.IsAssignableFrom(mgr.GetType())) + return mgr; + } + + return null; + } + + private ComponentSystemBase GetOrCreateSystemInternal() where T : new() + { + var manager = GetExistingSystemInternal(); + return manager ?? CreateSystemInternal(); + } + + private void RemoveSystemInternal(ComponentSystemBase system) + { + if (!m_Systems.Remove(system)) + throw new ArgumentException($"manager does not exist in the world"); + ++Version; + } + + public T CreateSystem() where T : ComponentSystemBase, new() + { + return (T) CreateSystemInternal(); + } + + public T GetOrCreateSystem() where T : ComponentSystemBase, new() + { + return (T) GetOrCreateSystemInternal(); + } + + public T AddSystem(T system) where T : ComponentSystemBase + { + m_Systems.Add(system); + try + { + system.CreateInstance(this); + } + catch + { + RemoveSystemInternal(system); + throw; + } + + ++Version; + return system; + } + + public T GetExistingSystem() where T : ComponentSystemBase + { + return (T) GetExistingSystemInternal(typeof(T)); + } + + public ComponentSystemBase GetExistingSystem(Type type) + { + return GetExistingSystemInternal(type); + } + + public void DestroySystem(ComponentSystemBase system) + { + RemoveSystemInternal(system); + system.DestroyInstance(); + } + + static int ms_SystemIDAllocator = 0; + internal static int AllocateSystemID() + { + return ++ms_SystemIDAllocator; + } + + public bool QuitUpdate { get; set; } + + public void Update() + { + InitializationSystemGroup initializationSystemGroup = + GetExistingSystem(typeof(InitializationSystemGroup)) as InitializationSystemGroup; + SimulationSystemGroup simulationSystemGroup = + GetExistingSystem(typeof(SimulationSystemGroup)) as SimulationSystemGroup; + PresentationSystemGroup presentationSystemGroup = + GetExistingSystem(typeof(PresentationSystemGroup)) as PresentationSystemGroup; + + initializationSystemGroup?.Update(); + simulationSystemGroup?.Update(); + presentationSystemGroup?.Update(); + } + } +#endif +} diff --git a/Unity.Entities/Injection/World.cs.meta b/Unity.Entities/World.cs.meta similarity index 100% rename from Unity.Entities/Injection/World.cs.meta rename to Unity.Entities/World.cs.meta diff --git a/Unity.Entities/WorldDebuggingTools.cs b/Unity.Entities/WorldDebuggingTools.cs new file mode 100644 index 00000000..5e7c1000 --- /dev/null +++ b/Unity.Entities/WorldDebuggingTools.cs @@ -0,0 +1,53 @@ +#if UNITY_EDITOR +using System; +using System.Collections.Generic; +using System.Linq; +using Unity.Collections; + +namespace Unity.Entities +{ + internal class WorldDebuggingTools + { + internal static void MatchEntityInEntityQueries(World world, Entity entity, + List>> matchList) + { + using (var entityComponentTypes = + world.EntityManager.GetComponentTypes(entity, Allocator.Temp)) + { + foreach (var system in World.Active.Systems) + { + var queryList = new List(); + if (system == null) continue; + foreach (var query in system.EntityQueries) + if (Match(query, entityComponentTypes)) + queryList.Add(query); + + if (queryList.Count > 0) + matchList.Add( + new Tuple>(system, queryList)); + } + } + } + + private static bool Match(EntityQuery query, NativeArray entityComponentTypes) + { + foreach (var groupType in query.GetQueryTypes().Skip(1)) + { + var found = false; + foreach (var type in entityComponentTypes) + { + if (type.TypeIndex != groupType.TypeIndex) + continue; + found = true; + break; + } + + if (found == (groupType.AccessModeType == ComponentType.AccessMode.Exclude)) + return false; + } + + return true; + } + } +} +#endif diff --git a/Unity.Entities/Injection/WorldDebuggingTools.cs.meta b/Unity.Entities/WorldDebuggingTools.cs.meta similarity index 100% rename from Unity.Entities/Injection/WorldDebuggingTools.cs.meta rename to Unity.Entities/WorldDebuggingTools.cs.meta diff --git a/Unity.Entities/WorldDiff.cs b/Unity.Entities/WorldDiff.cs index d62ec2a5..4f963d64 100644 --- a/Unity.Entities/WorldDiff.cs +++ b/Unity.Entities/WorldDiff.cs @@ -11,7 +11,7 @@ using Unity.Profiling; namespace Unity.Entities -{ +{ public static class HashMapUtility { public static bool TryRemove(this NativeMultiHashMap h, K k, V v) where K : struct, IEquatable where V : struct, IEquatable @@ -130,38 +130,38 @@ public struct SetSharedComponentDiff } public static class DiffUtil - { - public static ComponentGroup CreateAllChunksGroup(EntityManager manager) + { + public static EntityQuery CreateAllChunksQuery(EntityManager manager) { var guidQuery = new[] { - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid)}, }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Disabled)}, }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Prefab)}, }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Prefab), typeof(Disabled)}, } }; - return manager.CreateComponentGroup(guidQuery); + return manager.CreateEntityQuery(guidQuery); } public static NativeArray GetAllChunks(EntityManager manager) { - var group = CreateAllChunksGroup(manager); + var query = CreateAllChunksQuery(manager); - var chunks = group.CreateArchetypeChunkArray(Allocator.TempJob); + var chunks = query.CreateArchetypeChunkArray(Allocator.TempJob); - group.Dispose(); + query.Dispose(); return chunks; } @@ -246,13 +246,13 @@ public static void DiffAndApply(World newState, World previousStateShadowWorld, using (var diff = WorldDiffer.UpdateDiff(newState, previousStateShadowWorld, Allocator.TempJob)) { m_Diff.End(); - + m_ApplyDiff.Begin(); ApplyDiff(dstEntityWorld, diff); m_ApplyDiff.End(); } } - + public static WorldDiff UpdateDiff(World Source, World ShadowWorld, Allocator resultAllocator) { if (Source == null) @@ -264,8 +264,8 @@ public static WorldDiff UpdateDiff(World Source, World ShadowWorld, Allocator re if (resultAllocator == Allocator.Temp) throw new ArgumentException("Allocator can not be Allocator.Temp. Use Allocator.TempJob instead."); - var smgr = Source.GetOrCreateManager(); - var dmgr = ShadowWorld.GetOrCreateManager(); + var smgr = Source.EntityManager; + var dmgr = ShadowWorld.EntityManager; var schunks = DiffUtil.GetAllChunks(smgr); var dchunks = DiffUtil.GetAllChunks(dmgr); @@ -553,7 +553,7 @@ static void BuildComponentDiff(NativeList modifiedEntities byte* beforeAddress = mod.BeforeChunk->Buffer + beforeArch->Offsets[beforeType] + beforeArch->SizeOfs[beforeType] * mod.BeforeIndex; byte* afterAddress = mod.AfterChunk->Buffer + afterArch->Offsets[afterType] + afterArch->SizeOfs[afterType] * mod.AfterIndex; - if (!SharedComponentDataManager.FastEquality_ComparePtr(beforeAddress, afterAddress, targetTypeIndex)) + if (!TypeManager.Equals(beforeAddress, afterAddress, targetTypeIndex)) { // For now do full component replacement, because we need to dig into field information to make this work. dataDiffs.Add(new DataDiff @@ -577,7 +577,7 @@ static void BuildComponentDiff(NativeList modifiedEntities object beforeObject = GetSharedComponentObject(dsharedComponentDataManager, mod.BeforeChunk, beforeType, targetTypeIndex); object afterObject = GetSharedComponentObject(ssharedComponentDataManager, mod.AfterChunk, afterType, targetTypeIndex); - if (!SharedComponentDataManager.FastEquality_CompareBoxed(beforeObject, afterObject, targetTypeIndex)) + if (!TypeManager.Equals(beforeObject, afterObject, targetTypeIndex)) { sharedComponentDiffs.Add(new SetSharedComponentDiff { @@ -694,7 +694,7 @@ private static void ExtractGuidPatches(NativeList entityPatches int elementOffset = 0; for (var element = 0; element < elementCount; ++element) { - #if !UNITY_CSHARP_TINY + #if !NET_DOTS foreach (var eo in ft.EntityOffsets) { #else @@ -723,7 +723,7 @@ private static void ExtractGuidPatches(NativeList entityPatches } -#if !UNITY_CSHARP_TINY +#if !NET_DOTS static object GetSharedComponentObject(SharedComponentDataManager sharedComponentDataManager, Chunk* chunk, int typeIndexInArchetype, int targetTypeIndex) { int off = typeIndexInArchetype - chunk->Archetype->FirstSharedComponent; @@ -1071,7 +1071,7 @@ public void Execute(ArchetypeChunk chunk, int entityIndex, int chunkIndex) var entities = chunk.GetNativeArray(Entity); for (int i = 0; i != entities.Length; i++) GuidToDestWorldPrefabEntity.TryAdd(guids[i], entities[i]); - } + } } struct BuildEntityToRootEntityLookup : IJobChunk @@ -1097,8 +1097,8 @@ public void Execute(ArchetypeChunk chunk, int entityIndex, int chunkIndex) internal struct DiffApplier : IDisposable { static ProfilerMarker s_AllocateLookups = new ProfilerMarker("DiffApplier.AllocateLookups"); - static ProfilerMarker s_BuildDestWorldLookups = new ProfilerMarker("DiffApplier.BuildDestWorldLookups"); - static ProfilerMarker s_BuildDiffToDestWorldLookups = new ProfilerMarker("DiffApplier.BuildDiffToDestWorldLookups"); + static ProfilerMarker s_BuildDestWorldLookups = new ProfilerMarker("DiffApplier.BuildDestWorldLookups"); + static ProfilerMarker s_BuildDiffToDestWorldLookups = new ProfilerMarker("DiffApplier.BuildDiffToDestWorldLookups"); static ProfilerMarker s_CreateEntities = new ProfilerMarker("DiffApplier.CreateEntities"); static ProfilerMarker s_DestroyEntities = new ProfilerMarker("DiffApplier.DestroyEntities"); static ProfilerMarker s_AddComponents = new ProfilerMarker("DiffApplier.AddComponents"); @@ -1108,7 +1108,7 @@ internal struct DiffApplier : IDisposable static ProfilerMarker s_ApplyLinkedEntityGroupAdds = new ProfilerMarker("DiffApplier.ApplyLinkedEntityGroupAdds"); static ProfilerMarker s_ApplyLinkedEntityGroupRemoves = new ProfilerMarker("DiffApplier.ApplyLinkedEntityGroupRemoves"); static ProfilerMarker s_PatchEntities = new ProfilerMarker("DiffApplier.PatchEntities"); - + // World to which we apply the diff internal World destWorld; @@ -1153,7 +1153,7 @@ public DiffApplier(World dest_, WorldDiff diff_) { destWorld = dest_; diff = diff_; - DestWorldManager = destWorld.GetOrCreateManager(); + DestWorldManager = destWorld.EntityManager; DestWorldManager.CompleteAllJobs(); DiffIndexToDestWorldEntities = default; DiffIndexToDestWorldTypes = default; @@ -1209,19 +1209,19 @@ void BuildDestWorldLookups() // we need to ask for guids, guids and disabled, guids and prefab, and guids/prefab/disabled. var guidQuery = new[] { - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid)} }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Disabled)} }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Prefab)} }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Prefab), typeof(Disabled)} } @@ -1230,19 +1230,19 @@ void BuildDestWorldLookups() // we need to ask for linkedentitygroups, linkedentitygroups and disabled, linkedentitygroups and prefab, and linkedentitygroups/prefab/disabled. var linkedEntityGroupQuery = new[] { - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(LinkedEntityGroup)} }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(LinkedEntityGroup), typeof(Disabled)} }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(LinkedEntityGroup), typeof(Prefab)} }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(LinkedEntityGroup), typeof(Prefab), typeof(Disabled)} } @@ -1250,18 +1250,18 @@ void BuildDestWorldLookups() // this is for finding entities that have GUIDs, and which are Prefabs. var guidPrefabQuery = new[] { - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Prefab)} }, - new EntityArchetypeQuery + new EntityQueryDesc { All = new ComponentType[] {typeof(EntityGuid), typeof(Prefab), typeof(Disabled)} } }; - using(ComponentGroup DestChunksWithGuids = DestWorldManager.CreateComponentGroup(guidQuery)) - using (ComponentGroup DestChunksWithLinkedEntityGroups = DestWorldManager.CreateComponentGroup(linkedEntityGroupQuery)) - using(ComponentGroup DestchunksWithGuidAndPrefab = DestWorldManager.CreateComponentGroup(guidPrefabQuery)) + using (EntityQuery DestChunksWithGuids = DestWorldManager.CreateEntityQuery(guidQuery)) + using (EntityQuery DestChunksWithLinkedEntityGroups = DestWorldManager.CreateEntityQuery(linkedEntityGroupQuery)) + using (EntityQuery DestchunksWithGuidAndPrefab = DestWorldManager.CreateEntityQuery(guidPrefabQuery)) { DestWorldEntitiesWithGuids = DestChunksWithGuids.CalculateLength(); DestWorldEntitiesWithLinkedEntityGroups = DestChunksWithLinkedEntityGroups.CalculateLength(); @@ -1293,7 +1293,7 @@ void BuildDestWorldLookups() { GuidToDestWorldPrefabEntity = GuidToDestWorldPrefabEntity.ToConcurrent(), Entity = DestWorldManager.GetArchetypeChunkEntityType(), - EntityGUID = DestWorldManager.GetArchetypeChunkComponentType(true) + EntityGUID = DestWorldManager.GetArchetypeChunkComponentType(true) }; handle = buildDestWorldGuidPrefabLookups.Schedule(DestchunksWithGuidAndPrefab); handle.Complete(); @@ -1362,14 +1362,14 @@ void SetDebugNames() { do { -#if UNITY_EDITOR +#if UNITY_EDITOR DestWorldManager.SetName(entity, diff.EntityNames[i].ToString()); #endif } while (DiffIndexToDestWorldEntities.TryGetNextValue(out entity, ref it)); } } } - + void DestroyEntities() { s_DestroyEntities.Begin(); @@ -1399,7 +1399,7 @@ void DestroyEntities() void AddComponents() { s_AddComponents.Begin(); - var linkedEntityGroupTypeIndex = TypeManager.GetTypeIndex(); + var linkedEntityGroupTypeIndex = TypeManager.GetTypeIndex(); foreach (var addition in diff.AddComponents) { @@ -1414,7 +1414,7 @@ void AddComponents() // magic is required to force the first entity in the LinkedEntityGroup to be the entity // that owns the component. this magic doesn't seem to exist at a lower level, so let's // shim it in here. we'll probably need to move the magic lower someday. - if (componentType.TypeIndex == linkedEntityGroupTypeIndex) + if (componentType.TypeIndex == linkedEntityGroupTypeIndex) { var buffer = DestWorldManager.GetBuffer(entity); buffer.Add(entity); @@ -1680,12 +1680,12 @@ void ApplyLinkedEntityGroupAdds() } else { - Debug.LogWarning($"Tried to add a child to a linked entity group, but root entity didn't exist in destination world."); + Debug.LogWarning($"Tried to add a child to a linked entity group, but root entity didn't exist in destination world."); } } else { - Debug.LogWarning($"Tried to add a child to a linked entity group, but no such prefab exists in destination world."); + Debug.LogWarning($"Tried to add a child to a linked entity group, but no such prefab exists in destination world."); } } for (var a = 0; a < instanceChildren.Length; ++a) @@ -1731,7 +1731,7 @@ void ApplyLinkedEntityGroupRemoves() for (var a = 0; a < pending.Length; ++a) RemoveChildFromTables(pending[a]); } - s_ApplyLinkedEntityGroupRemoves.End(); + s_ApplyLinkedEntityGroupRemoves.End(); } } diff --git a/Unity.Scenes.Editor/ConversionWarningsEditor.cs b/Unity.Scenes.Editor/ConversionWarningsEditor.cs index 184212b3..05adff75 100644 --- a/Unity.Scenes.Editor/ConversionWarningsEditor.cs +++ b/Unity.Scenes.Editor/ConversionWarningsEditor.cs @@ -49,7 +49,7 @@ public static string GetWarnings(GameObject gameobject) Type convertType = null; foreach (var behaviour in gameobject.GetComponents()) { - if (behaviour.GetType().GetCustomAttribute(true) != null) + if (behaviour != null && behaviour.GetType().GetCustomAttribute(true) != null) { convertType = behaviour.GetType(); break; diff --git a/Unity.Scenes.Editor/EditorEntityScenes.cs b/Unity.Scenes.Editor/EditorEntityScenes.cs index fee1efc0..08896f75 100644 --- a/Unity.Scenes.Editor/EditorEntityScenes.cs +++ b/Unity.Scenes.Editor/EditorEntityScenes.cs @@ -8,6 +8,7 @@ using Unity.Profiling; using UnityEditor; using UnityEngine; +using UnityEngine.Assertions; using UnityEngine.SceneManagement; using static Unity.Entities.GameObjectConversionUtility; using Hash128 = Unity.Entities.Hash128; @@ -44,7 +45,7 @@ public static bool HasEntitySceneCache(Hash128 sceneGUID) public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, ConversionFlags conversionFlags) { var world = new World("ConversionWorld"); - var entityManager = world.GetOrCreateManager(); + var entityManager = world.EntityManager; var boundsEntity = entityManager.CreateEntity(typeof(SceneBoundingVolume)); entityManager.SetComponentData(boundsEntity, new SceneBoundingVolume { Value = MinMaxAABB.Empty } ); @@ -63,11 +64,11 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve NativeArray entitiesInMainSection; - var sectionGrp = entityManager.CreateComponentGroup( - new EntityArchetypeQuery + var sectionGrp = entityManager.CreateEntityQuery( + new EntityQueryDesc { All = new[] {ComponentType.ReadWrite()}, - Options = EntityArchetypeQueryOptions.IncludePrefab | EntityArchetypeQueryOptions.IncludeDisabled + Options = EntityQueryOptions.IncludePrefab | EntityQueryOptions.IncludeDisabled } ); @@ -82,6 +83,10 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve // otherwise they would reuse entities that have been moved and mess up the remapping tables. for(int sectionIndex = 1; sectionIndex < subSectionList.Count; ++sectionIndex) { + if (subSectionList[sectionIndex].Section == 0) + // Main section, the only one that doesn't need an external ref array + continue; + var extRefInfoEntity = entityManager.CreateEntity(); entityManager.AddSharedComponentData(extRefInfoEntity, subSectionList[sectionIndex]); extRefInfoEntities[sectionIndex] = extRefInfoEntity; @@ -106,7 +111,7 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve // Save main section var sectionWorld = new World("SectionWorld"); - var sectionManager = sectionWorld.GetOrCreateManager(); + var sectionManager = sectionWorld.EntityManager; var entityRemapping = entityManager.CreateEntityRemapArray(Allocator.TempJob); sectionManager.MoveEntitiesFrom(entityManager, sectionGrp, entityRemapping); @@ -114,8 +119,8 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve // The section component is only there to break the conversion world into different sections // We don't want to store that on the disk //@TODO: Component should be removed but currently leads to corrupt data file. Figure out why. - //sectionManager.RemoveComponent(sectionManager.UniversalGroup, typeof(SceneSection)); - + //sectionManager.RemoveComponent(sectionManager.UniversalQuery, typeof(SceneSection)); + var sectionFileSize = WriteEntityScene(sectionManager, sceneGUID, "0"); sceneSections.Add(new SceneData { @@ -137,7 +142,7 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve var subSection = subSectionList[subSectionIndex]; if (subSection.Section == 0) continue; - + sectionGrp.SetFilter(subSection); var entitiesInSection = sectionGrp.ToEntityArray(Allocator.TempJob); @@ -155,10 +160,13 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve ExternalEntityRef.Add(ref externRefs, new ExternalEntityRef{entityIndex = i}); } - // Entities will be remapped to a contiguous range in the section world, - // so any range after that is fine for the external references - //@TODO why are we not mapping anything to entity 0? we use the range [1;count], hence +1 - var externEntityIndexStart = entitiesInSection.Length + 1; + var entityRemapping = entityManager.CreateEntityRemapArray(Allocator.TempJob); + + // Entities will be remapped to a contiguous range in the section world, but they will + // also come with an unpredictable amount of meta entities. We have the guarantee that + // the entities in the main section won't be moved over, so there's a free range of that + // size at the end of the remapping table. So we use that range for external references. + var externEntityIndexStart = entityRemapping.Length - entitiesInMainSection.Length; entityManager.AddComponentData(refInfoEntity, new ExternalEntityRefInfo @@ -168,9 +176,7 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve }); var sectionWorld = new World("SectionWorld"); - var sectionManager = sectionWorld.GetOrCreateManager(); - - var entityRemapping = entityManager.CreateEntityRemapArray(Allocator.TempJob); + var sectionManager = sectionWorld.EntityManager; // Insert mapping for external references, conversion world entity to virtual index in section for (int i = 0; i < entitiesInMainSection.Length; ++i) @@ -180,19 +186,47 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve } sectionManager.MoveEntitiesFrom(entityManager, sectionGrp, entityRemapping); - + + // Now that all the required entities have been moved over, we can get rid of the gap between + // real entities and external references. This allows remapping during load to deal with a + // smaller remap table, containing only useful entries. + + int highestEntityIndexInUse = 0; + for (int i = 0; i < externEntityIndexStart; ++i) + { + var targetIndex = entityRemapping[i].Target.Index; + if (targetIndex < externEntityIndexStart && targetIndex > highestEntityIndexInUse) + highestEntityIndexInUse = targetIndex; + } + + var oldExternEntityIndexStart = externEntityIndexStart; + externEntityIndexStart = highestEntityIndexInUse + 1; + + sectionManager.SetComponentData + ( + EntityRemapUtility.RemapEntity(ref entityRemapping, refInfoEntity), + new ExternalEntityRefInfo + { + SceneGUID = sceneGUID, + EntityIndexStart = externEntityIndexStart + } + ); + // When writing the scene, references to missing entities are set to Entity.Null by default + // (but only if they have been used, otherwise they remain untouched) // We obviously don't want that to happen to our external references, so we add explicit mapping + // And at the same time, we put them back at the end of the effective range of real entities. for (int i = 0; i < entitiesInMainSection.Length; ++i) { - var entity = new Entity {Index = i + externEntityIndexStart, Version = 1}; - EntityRemapUtility.AddEntityRemapping(ref entityRemapping, entity, entity); + var src = new Entity {Index = i + oldExternEntityIndexStart, Version = 1}; + var dst = new Entity {Index = i + externEntityIndexStart, Version = 1}; + EntityRemapUtility.AddEntityRemapping(ref entityRemapping, src, dst); } // The section component is only there to break the conversion world into different sections // We don't want to store that on the disk //@TODO: Component should be removed but currently leads to corrupt data file. Figure out why. - //sectionManager.RemoveComponent(sectionManager.UniversalGroup, typeof(SceneSection)); + //sectionManager.RemoveComponent(sectionManager.UniversalQuery, typeof(SceneSection)); var fileSize = WriteEntityScene(sectionManager, sceneGUID, subSection.Section.ToString(), entityRemapping); sceneSections.Add(new SceneData @@ -213,11 +247,11 @@ public static SceneData[] WriteEntityScene(Scene scene, Hash128 sceneGUID, Conve } { - var noSectionGrp = entityManager.CreateComponentGroup( - new EntityArchetypeQuery + var noSectionGrp = entityManager.CreateEntityQuery( + new EntityQueryDesc { None = new[] {ComponentType.ReadWrite()}, - Options = EntityArchetypeQueryOptions.IncludePrefab | EntityArchetypeQueryOptions.IncludeDisabled + Options = EntityQueryOptions.IncludePrefab | EntityQueryOptions.IncludeDisabled } ); if (noSectionGrp.CalculateLength() != 0) diff --git a/Unity.Scenes.Editor/SubSceneInspector.cs b/Unity.Scenes.Editor/SubSceneInspector.cs index 0d0d37f5..b8c158ac 100644 --- a/Unity.Scenes.Editor/SubSceneInspector.cs +++ b/Unity.Scenes.Editor/SubSceneInspector.cs @@ -88,7 +88,7 @@ public override void OnInspectorGUI() if (World.Active != null) { - var entityManager = World.Active.GetOrCreateManager(); + var entityManager = World.Active.EntityManager; foreach (var scene in scenes) { diff --git a/Unity.Scenes.Editor/SubSceneLiveLinkSystem.cs b/Unity.Scenes.Editor/SubSceneLiveLinkSystem.cs index 0710e81c..a28d5328 100644 --- a/Unity.Scenes.Editor/SubSceneLiveLinkSystem.cs +++ b/Unity.Scenes.Editor/SubSceneLiveLinkSystem.cs @@ -27,14 +27,14 @@ static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAsse } } } - + static int GlobalDirtyID = 0; static int PreviousGlobalDirtyID = 0; MethodInfo m_GetDirtyIDMethod = typeof(Scene).GetProperty("dirtyID", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetMethod; - + UInt64 m_LiveLinkEditSceneViewMask = 1UL << 60; UInt64 m_LiveLinkEditGameViewMask = 1UL << 58; - HashSet m_EditingSceneAssets = new HashSet(); + HashSet m_EditingSceneAssets = new HashSet(); static void AddUnique(ref List list, SubScene scene) { @@ -51,9 +51,9 @@ protected override void OnUpdate() List markSceneLoadedFromLiveLink = null; List removeSceneLoadedFromLiveLink = null; m_EditingSceneAssets.Clear(); - + var liveLinkEnabled = SubSceneInspectorUtility.LiveLinkEnabled; - + // By default all scenes need to have m_GameObjectSceneCullingMask, otherwise they won't show up in game view for (int i = 0; i != EditorSceneManager.sceneCount; i++) { @@ -67,10 +67,10 @@ protected override void OnUpdate() var sceneAsset = AssetDatabase.LoadAssetAtPath(scene.path); if (scene.isLoaded && sceneAsset != null) - m_EditingSceneAssets.Add(sceneAsset); + m_EditingSceneAssets.Add(sceneAsset); } - } - + } + if (PreviousGlobalDirtyID != GlobalDirtyID) { Entities.ForEach((SubScene subScene) => @@ -79,7 +79,7 @@ protected override void OnUpdate() }); PreviousGlobalDirtyID = GlobalDirtyID; } - + Entities.ForEach((SubScene subScene) => { var isLoaded = m_EditingSceneAssets.Contains(subScene.SceneAsset); @@ -171,9 +171,9 @@ void CleanupScene(SubScene scene) { // Debug.Log("CleanupScene: " + scene.SceneName); scene.CleanupLiveLink(); - - var streamingSystem = World.GetExistingManager(); - + + var streamingSystem = World.GetExistingSystem(); + foreach (var sceneEntity in scene._SceneEntities) { streamingSystem.UnloadSceneImmediate(sceneEntity); @@ -187,17 +187,17 @@ void CleanupScene(SubScene scene) void ApplyLiveLink(SubScene scene) { //Debug.Log("ApplyLiveLink: " + scene.SceneName); - - var streamingSystem = World.GetExistingManager(); + + var streamingSystem = World.GetExistingSystem(); var isFirstTime = scene.LiveLinkShadowWorld == null; if (scene.LiveLinkShadowWorld == null) scene.LiveLinkShadowWorld = new World("LiveLink"); - - + + using (var cleanConvertedEntityWorld = new World("Clean Entity Conversion World")) { - // Unload scene + // Unload scene //@TODO: We optimally shouldn't be unloading the scene here. We should simply prime the shadow world with the scene that we originally loaded into the player (Including Entity GUIDs) // This way we can continue the live link, compared to exactly what we loaded into the player. if (isFirstTime) @@ -207,46 +207,46 @@ void ApplyLiveLink(SubScene scene) streamingSystem.UnloadSceneImmediate(s); EntityManager.DestroyEntity(s); } - + var sceneEntity = EntityManager.CreateEntity(); EntityManager.SetName(sceneEntity, "Scene (LiveLink): " + scene.SceneName); EntityManager.AddComponentObject(sceneEntity, scene); EntityManager.AddComponentData(sceneEntity, new SubSceneStreamingSystem.StreamingState { Status = SubSceneStreamingSystem.StreamingStatus.Loaded}); EntityManager.AddComponentData(sceneEntity, new SubSceneStreamingSystem.IgnoreTag( )); - + scene._SceneEntities = new List(); scene._SceneEntities.Add(sceneEntity); } - + // Convert scene GameObjectConversionUtility.ConvertScene(scene.LoadedScene, scene.SceneGUID, cleanConvertedEntityWorld, GameObjectConversionUtility.ConversionFlags.AddEntityGUID | GameObjectConversionUtility.ConversionFlags.AssignName); - var convertedEntityManager = cleanConvertedEntityWorld.GetOrCreateManager(); + var convertedEntityManager = cleanConvertedEntityWorld.EntityManager; var liveLinkSceneEntity = scene._SceneEntities[0]; - - /// We want to let the live linked scene be able to reference the already existing Scene Entity (Specifically SceneTag should point to the scene Entity after live link completes) + + /// We want to let the live linked scene be able to reference the already existing Scene Entity (Specifically SceneTag should point to the scene Entity after live link completes) // Add Scene tag to all entities using the convertedSceneEntity that will map to the already existing scene entity. - convertedEntityManager.AddSharedComponentData(convertedEntityManager.UniversalGroup, new SceneTag { SceneEntity = liveLinkSceneEntity }); + convertedEntityManager.AddSharedComponentData(convertedEntityManager.UniversalQuery, new SceneTag { SceneEntity = liveLinkSceneEntity }); WorldDiffer.DiffAndApply(cleanConvertedEntityWorld, scene.LiveLinkShadowWorld, World); convertedEntityManager.Debug.CheckInternalConsistency(); - scene.LiveLinkShadowWorld.GetOrCreateManager().Debug.CheckInternalConsistency(); + scene.LiveLinkShadowWorld.EntityManager.Debug.CheckInternalConsistency(); - var group = EntityManager.CreateComponentGroup(typeof(SceneTag), ComponentType.Exclude()); + var group = EntityManager.CreateEntityQuery(typeof(SceneTag), ComponentType.Exclude()); group.SetFilter(new SceneTag {SceneEntity = liveLinkSceneEntity}); - + EntityManager.AddSharedComponentData(group, new EditorRenderData() { SceneCullingMask = m_LiveLinkEditGameViewMask, PickableObject = scene.gameObject }); group.Dispose(); - + scene.LiveLinkDirtyID = GetSceneDirtyID(scene.LoadedScene); EditorUpdateUtility.EditModeQueuePlayerLoopUpdate(); } } - - + + static GameObject GetGameObjectFromAny(Object target) { Component component = target as Component; @@ -254,13 +254,13 @@ static GameObject GetGameObjectFromAny(Object target) return component.gameObject; return target as GameObject; } - + internal static bool IsHotControlActive() { return GUIUtility.hotControl != 0; } - - + + UndoPropertyModification[] PostprocessModifications(UndoPropertyModification[] modifications) { foreach (var mod in modifications) @@ -273,15 +273,15 @@ UndoPropertyModification[] PostprocessModifications(UndoPropertyModification[] m { if (scene.IsLoaded && scene.LoadedScene == targetScene) { - scene.LiveLinkDirtyID = -1; + scene.LiveLinkDirtyID = -1; } }); } } - + return modifications; } - + int GetSceneDirtyID(Scene scene) { if (scene.IsValid()) @@ -291,17 +291,17 @@ int GetSceneDirtyID(Scene scene) else return -1; } - + static void GlobalDirtyLiveLink() { GlobalDirtyID++; } - - protected override void OnCreateManager() - { + + protected override void OnCreate() + { Undo.postprocessModifications += PostprocessModifications; Undo.undoRedoPerformed += GlobalDirtyLiveLink; - + Camera.onPreCull += OnPreCull; RenderPipeline.beginCameraRendering += OnPreCull; } @@ -326,14 +326,14 @@ void OnPreCull(Camera camera) camera.overrideSceneCullingMask = EditorSceneManager.DefaultSceneCullingMask | m_LiveLinkEditSceneViewMask; } } - + } - protected override void OnDestroyManager() - { + protected override void OnDestroy() + { Undo.postprocessModifications -= PostprocessModifications; Undo.undoRedoPerformed -= GlobalDirtyLiveLink; - + Camera.onPreCull -= OnPreCull; RenderPipeline.beginCameraRendering -= OnPreCull; } diff --git a/Unity.Scenes.Hybrid.Tests/SaveAndLoadEndToEnd.cs b/Unity.Scenes.Hybrid.Tests/SaveAndLoadEndToEnd.cs index d3c9f0a8..e4d42630 100644 --- a/Unity.Scenes.Hybrid.Tests/SaveAndLoadEndToEnd.cs +++ b/Unity.Scenes.Hybrid.Tests/SaveAndLoadEndToEnd.cs @@ -38,17 +38,20 @@ public IEnumerator EndToEnd() for (int w = 0; w != 1000; w++) { - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); if (1 != m_Manager.Debug.EntityCount) break; yield return null; } - Assert.AreEqual(4, m_Manager.Debug.EntityCount); + // 1. Scene entity + // 2. Public ref array + // 3. Mesh Renderer + Assert.AreEqual(3, m_Manager.Debug.EntityCount); m_Manager.RemoveComponent(sceneEntity); - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); Assert.AreEqual(1, m_Manager.Debug.EntityCount); } @@ -56,4 +59,3 @@ public IEnumerator EndToEnd() } } } - diff --git a/Unity.Scenes.Hybrid/EntitySceneOptimization.cs b/Unity.Scenes.Hybrid/EntitySceneOptimization.cs index 95fc6980..38c1bdca 100644 --- a/Unity.Scenes.Hybrid/EntitySceneOptimization.cs +++ b/Unity.Scenes.Hybrid/EntitySceneOptimization.cs @@ -14,7 +14,7 @@ public static class EntitySceneOptimization { static void MarkStaticFrozen(EntityManager entityManager) { - var staticGroup = entityManager.CreateComponentGroup(typeof(Static)); + var staticGroup = entityManager.CreateEntityQuery(typeof(Static)); entityManager.AddComponent(staticGroup, ComponentType.ReadWrite()); staticGroup.Dispose(); } @@ -26,7 +26,7 @@ static void RemoveSystemState(EntityManager entityManager) if (TypeManager.IsSystemStateComponent(s.TypeIndex)) { //@TODO: Make query instead of this crazy slow shit - entityManager.RemoveComponent(entityManager.UniversalGroup, ComponentType.FromTypeIndex(s.TypeIndex)); + entityManager.RemoveComponent(entityManager.UniversalQuery, ComponentType.FromTypeIndex(s.TypeIndex)); } } } @@ -35,7 +35,7 @@ public static void Optimize(World world) { var entityManager = world.EntityManager; - var group = world.GetOrCreateManager(); + var group = world.GetOrCreateSystem(); var systemTypes = DefaultWorldInitialization.GetAllSystems(WorldSystemFilterFlags.EntitySceneOptimizations); foreach (var systemType in systemTypes) @@ -50,7 +50,7 @@ public static void Optimize(World world) // Freeze static objects. // After this no more reordering is allowed - var staticGroup = entityManager.CreateComponentGroup(typeof(Static)); + var staticGroup = entityManager.CreateEntityQuery(typeof(Static)); entityManager.LockChunkOrder(staticGroup); staticGroup.Dispose(); @@ -66,7 +66,7 @@ static void AddSystemAndLogException(World world, ComponentSystemGroup group, Ty { try { - group.AddSystemToUpdateList(world.GetOrCreateManager(type) as ComponentSystemBase); + group.AddSystemToUpdateList(world.GetOrCreateSystem(type) as ComponentSystemBase); } catch (Exception e) { @@ -74,4 +74,4 @@ static void AddSystemAndLogException(World world, ComponentSystemGroup group, Ty } } } -} \ No newline at end of file +} diff --git a/Unity.Scenes.Hybrid/SubScene.cs b/Unity.Scenes.Hybrid/SubScene.cs index 8bc2a2b5..e26431dd 100644 --- a/Unity.Scenes.Hybrid/SubScene.cs +++ b/Unity.Scenes.Hybrid/SubScene.cs @@ -168,7 +168,7 @@ public void UpdateSceneEntities() DefaultWorldInitialization.DefaultLazyEditModeInitialize(); if (World.Active != null && m_SubSceneHeader != null) { - _SceneEntityManager = World.Active.GetOrCreateManager(); + _SceneEntityManager = World.Active.EntityManager; for (int i = 0; i < m_SubSceneHeader.Sections.Length; ++i) { diff --git a/Unity.Scenes.Hybrid/SubSceneStreamingSystem.cs b/Unity.Scenes.Hybrid/SubSceneStreamingSystem.cs index 06013af8..a3a4d60f 100644 --- a/Unity.Scenes.Hybrid/SubSceneStreamingSystem.cs +++ b/Unity.Scenes.Hybrid/SubSceneStreamingSystem.cs @@ -45,54 +45,54 @@ struct Stream int MaximumMoveEntitiesFromPerFrame = 1; Stream[] m_Streams = new Stream[LoadScenesPerFrame]; - ComponentGroup m_PendingStreamRequests; - ComponentGroup m_UnloadStreamRequests; - ComponentGroup m_SceneFilter; - ComponentGroup m_PublicRefFilter; - ComponentGroup m_SectionData; + EntityQuery m_PendingStreamRequests; + EntityQuery m_UnloadStreamRequests; + EntityQuery m_SceneFilter; + EntityQuery m_PublicRefFilter; + EntityQuery m_SectionData; ProfilerMarker m_MoveEntitiesFrom = new ProfilerMarker("SceneStreaming.MoveEntitiesFrom"); ProfilerMarker m_ExtractEntityRemapRefs = new ProfilerMarker("SceneStreaming.ExtractEntityRemapRefs"); ProfilerMarker m_AddSceneSharedComponents = new ProfilerMarker("SceneStreaming.AddSceneSharedComponents"); - protected override void OnCreateManager() + protected override void OnCreate() { for (int i = 0; i < LoadScenesPerFrame; ++i) CreateStreamWorld(i); - m_PendingStreamRequests = GetComponentGroup(new EntityArchetypeQuery() + m_PendingStreamRequests = GetEntityQuery(new EntityQueryDesc() { All = new[] {ComponentType.ReadWrite(), ComponentType.ReadWrite()}, None = new[] {ComponentType.ReadWrite(), ComponentType.ReadWrite() } }); - m_UnloadStreamRequests = GetComponentGroup(new EntityArchetypeQuery() + m_UnloadStreamRequests = GetEntityQuery(new EntityQueryDesc() { All = new[] {ComponentType.ReadWrite()}, None = new[] {ComponentType.ReadWrite(), ComponentType.ReadWrite()} }); - m_PublicRefFilter = GetComponentGroup + m_PublicRefFilter = GetEntityQuery ( ComponentType.ReadWrite(), ComponentType.ReadWrite() ); - m_SectionData = GetComponentGroup + m_SectionData = GetEntityQuery ( ComponentType.ReadWrite() ); - m_SceneFilter = GetComponentGroup( - new EntityArchetypeQuery + m_SceneFilter = GetEntityQuery( + new EntityQueryDesc { All = new [] {ComponentType.ReadWrite() }, - Options = EntityArchetypeQueryOptions.IncludeDisabled | EntityArchetypeQueryOptions.IncludePrefab + Options = EntityQueryOptions.IncludeDisabled | EntityQueryOptions.IncludePrefab } ); } - protected override void OnDestroyManager() + protected override void OnDestroy() { for (int i = 0; i != m_Streams.Length; i++) { @@ -100,7 +100,7 @@ protected override void OnDestroyManager() DestroyStreamWorld(i); } } - + void DestroyStreamWorld(int index) { m_Streams[index].World.Dispose(); @@ -111,12 +111,11 @@ void DestroyStreamWorld(int index) void CreateStreamWorld(int index) { m_Streams[index].World = new World("LoadingWorld" + index); - m_Streams[index].World.CreateManager(); } static NativeArray GetExternalRefEntities(EntityManager manager, Allocator allocator) { - using (var group = manager.CreateComponentGroup(typeof(ExternalEntityRefInfo))) + using (var group = manager.CreateEntityQuery(typeof(ExternalEntityRefInfo))) { return group.ToEntityArray(allocator); } @@ -125,7 +124,7 @@ static NativeArray GetExternalRefEntities(EntityManager manager, Allocat //@TODO There must be a more efficient way static Entity GetPublicRefEntity(EntityManager manager, Entities.Hash128 guid) { - using (var sceneDataGrp = manager.CreateComponentGroup(typeof(SceneData))) + using (var sceneDataGrp = manager.CreateEntityQuery(typeof(SceneData))) { using (var sceneEntities = sceneDataGrp.ToEntityArray(Allocator.TempJob)) { @@ -134,7 +133,7 @@ static Entity GetPublicRefEntity(EntityManager manager, Entities.Hash128 guid) var scenedata = manager.GetComponentData(sceneEntity); if (scenedata.SceneGUID == guid && scenedata.SubSectionIndex == 0) { - using(var group = manager.CreateComponentGroup(typeof(SceneTag), typeof(PublicEntityRef))) + using(var group = manager.CreateEntityQuery(typeof(SceneTag), typeof(PublicEntityRef))) { group.SetFilter(new SceneTag {SceneEntity = sceneEntity}); using (var entities = group.ToEntityArray(Allocator.TempJob)) @@ -196,10 +195,10 @@ bool MoveEntities(EntityManager srcManager, Entity sceneEntity) SceneCullingMask = UnityEditor.SceneManagement.EditorSceneManager.DefaultSceneCullingMask | (1UL << 59), PickableObject = EntityManager.HasComponent(sceneEntity) ? EntityManager.GetComponentObject(sceneEntity).gameObject : null }; - srcManager.AddSharedComponentData(srcManager.UniversalGroup, data); + srcManager.AddSharedComponentData(srcManager.UniversalQuery, data); #endif - srcManager.AddSharedComponentData(srcManager.UniversalGroup, new SceneTag { SceneEntity = sceneEntity}); + srcManager.AddSharedComponentData(srcManager.UniversalQuery, new SceneTag { SceneEntity = sceneEntity}); } @@ -289,8 +288,8 @@ bool ProcessActiveStreams() { var operation = m_Streams[i].Operation; var streamingWorld = m_Streams[i].World; - var streamingManager = streamingWorld.GetOrCreateManager(); - + var streamingManager = streamingWorld.EntityManager; + if (operation != null) { operation.Update(); @@ -328,7 +327,7 @@ bool ProcessActiveStreams() EntityManager.RemoveComponent(m_Streams[i].SceneEntity); - streamingManager.DestroyEntity(streamingManager.UniversalGroup); + streamingManager.DestroyEntity(streamingManager.UniversalQuery); streamingManager.PrepareForDeserialize(); moveEntitiesFromProcessed++; } @@ -408,17 +407,17 @@ protected override void OnUpdate() public void UnloadSceneImmediate(Entity scene) { if (EntityManager.HasComponent(scene)) - { + { m_SceneFilter.SetFilter(new SceneTag {SceneEntity = scene }); - + EntityManager.DestroyEntity(m_SceneFilter); - + m_SceneFilter.ResetFilter(); - + EntityManager.RemoveComponent(scene); } } - + int CreateAsyncLoadScene(Entity entity) { for (int i = 0; i != m_Streams.Length; i++) @@ -427,10 +426,10 @@ int CreateAsyncLoadScene(Entity entity) continue; var sceneData = EntityManager.GetComponentData(entity); - + var entitiesBinaryPath = EntityScenesPaths.GetLoadPath(sceneData.SceneGUID, EntityScenesPaths.PathType.EntitiesBinary, sceneData.SubSectionIndex); var resourcesPath = EntityScenesPaths.GetLoadPath(sceneData.SceneGUID, EntityScenesPaths.PathType.EntitiesSharedComponents, sceneData.SubSectionIndex); - var entityManager = m_Streams[i].World.GetOrCreateManager(); + var entityManager = m_Streams[i].World.EntityManager; m_Streams[i].Operation = new AsyncLoadSceneOperation(entitiesBinaryPath, sceneData.FileSize, sceneData.SharedComponentCount, resourcesPath, entityManager); m_Streams[i].SceneEntity = entity; diff --git a/Unity.Transforms.Hybrid/CopyInitialTransformFromGameObjectSystem.cs b/Unity.Transforms.Hybrid/CopyInitialTransformFromGameObjectSystem.cs index b30e532f..bfae21a9 100644 --- a/Unity.Transforms.Hybrid/CopyInitialTransformFromGameObjectSystem.cs +++ b/Unity.Transforms.Hybrid/CopyInitialTransformFromGameObjectSystem.cs @@ -33,7 +33,7 @@ public void Execute(int index, TransformAccess transform) } [BurstCompile] - struct CopyTransforms : IJobProcessComponentDataWithEntity + struct CopyTransforms : IJobForEachWithEntity { [DeallocateOnJobCompletion] public NativeArray transformStashes; @@ -69,12 +69,12 @@ public void Execute() EndInitializationEntityCommandBufferSystem m_EntityCommandBufferSystem; - ComponentGroup m_InitialTransformGroup; + EntityQuery m_InitialTransformGroup; - protected override void OnCreateManager() + protected override void OnCreate() { - m_EntityCommandBufferSystem = World.GetOrCreateManager(); - m_InitialTransformGroup = GetComponentGroup( + m_EntityCommandBufferSystem = World.GetOrCreateSystem(); + m_InitialTransformGroup = GetEntityQuery( ComponentType.ReadOnly(typeof(CopyInitialTransformFromGameObject)), typeof(UnityEngine.Transform), ComponentType.ReadWrite()); @@ -98,7 +98,7 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) transformStashes = transformStashes, }; - var copyTransformsJobHandle = copyTransformsJob.ScheduleGroup(m_InitialTransformGroup, stashTransformsJobHandle); + var copyTransformsJobHandle = copyTransformsJob.Schedule(m_InitialTransformGroup, stashTransformsJobHandle); var removeComponentsJob = new RemoveCopyInitialTransformFromGameObjectComponent { diff --git a/Unity.Transforms.Hybrid/CopyTransformFromGameObjectSystem.cs b/Unity.Transforms.Hybrid/CopyTransformFromGameObjectSystem.cs index 5ad748b4..30c9326a 100644 --- a/Unity.Transforms.Hybrid/CopyTransformFromGameObjectSystem.cs +++ b/Unity.Transforms.Hybrid/CopyTransformFromGameObjectSystem.cs @@ -34,7 +34,7 @@ public void Execute(int index, TransformAccess transform) } [BurstCompile] - struct CopyTransforms : IJobProcessComponentDataWithEntity + struct CopyTransforms : IJobForEachWithEntity { [DeallocateOnJobCompletion] public NativeArray transformStashes; @@ -52,11 +52,11 @@ public void Execute(Entity entity, int index, ref LocalToWorld localToWorld) } } - ComponentGroup m_TransformGroup; + EntityQuery m_TransformGroup; - protected override void OnCreateManager() + protected override void OnCreate() { - m_TransformGroup = GetComponentGroup( + m_TransformGroup = GetEntityQuery( ComponentType.ReadOnly(typeof(CopyTransformFromGameObject)), typeof(UnityEngine.Transform), ComponentType.ReadWrite()); @@ -81,7 +81,7 @@ protected override JobHandle OnUpdate(JobHandle inputDeps) transformStashes = transformStashes, }; - return copyTransformsJob.ScheduleGroup(m_TransformGroup, stashTransformsJobHandle); + return copyTransformsJob.Schedule(m_TransformGroup, stashTransformsJobHandle); } } } diff --git a/Unity.Transforms.Hybrid/CopyTransformToGameObjectSystem.cs b/Unity.Transforms.Hybrid/CopyTransformToGameObjectSystem.cs index 2fe32d73..f64ae105 100644 --- a/Unity.Transforms.Hybrid/CopyTransformToGameObjectSystem.cs +++ b/Unity.Transforms.Hybrid/CopyTransformToGameObjectSystem.cs @@ -16,41 +16,33 @@ public class CopyTransformToGameObjectSystem : JobComponentSystem [BurstCompile] struct CopyTransforms : IJobParallelForTransform { - [ReadOnly] public ComponentDataFromEntity LocalToWorlds; - - [ReadOnly] [DeallocateOnJobCompletion] - public NativeArray entities; + [ReadOnly] public NativeArray LocalToWorlds; public void Execute(int index, TransformAccess transform) { - var entity = entities[index]; - - var value = LocalToWorlds[entity]; - transform.position = math.transform(value.Value, float3.zero); + var value = LocalToWorlds[index]; + transform.position = value.Position; transform.rotation = new quaternion(value.Value); } } - ComponentGroup m_TransformGroup; + EntityQuery m_TransformGroup; - protected override void OnCreateManager() + protected override void OnCreate() { - m_TransformGroup = GetComponentGroup(ComponentType.ReadOnly(typeof(CopyTransformToGameObject)), ComponentType.ReadOnly(), typeof(UnityEngine.Transform)); + m_TransformGroup = GetEntityQuery(ComponentType.ReadOnly(typeof(CopyTransformToGameObject)), ComponentType.ReadOnly(), typeof(UnityEngine.Transform)); } protected override JobHandle OnUpdate(JobHandle inputDeps) { var transforms = m_TransformGroup.GetTransformAccessArray(); - var entities = m_TransformGroup.ToEntityArray(Allocator.TempJob); - var copyTransformsJob = new CopyTransforms { - LocalToWorlds = GetComponentDataFromEntity(true), - entities = entities + LocalToWorlds = m_TransformGroup.ToComponentDataArray(Allocator.TempJob, out inputDeps), }; - return copyTransformsJob.Schedule(transforms,inputDeps); + return copyTransformsJob.Schedule(transforms, inputDeps); } } } \ No newline at end of file diff --git a/Unity.Transforms.Tests/TransformTests.cs b/Unity.Transforms.Tests/TransformTests.cs index 6da88e78..65945c81 100644 --- a/Unity.Transforms.Tests/TransformTests.cs +++ b/Unity.Transforms.Tests/TransformTests.cs @@ -25,8 +25,8 @@ public void TRS_ChildPosition() Value = math.mul( float4x4.RotateY((float)math.PI), float4x4.Translate( new float3(0.0f, 0.0f, 1.0f))) }); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); m_Manager.CompleteAllJobs(); var childWorldPosition = m_Manager.GetComponentData(child).Position; @@ -49,8 +49,8 @@ public void TRS_RemovedParentDoesNotAffectChildPosition() Value = math.mul( float4x4.RotateY((float)math.PI), float4x4.Translate( new float3(0.0f, 0.0f, 1.0f))) }); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); m_Manager.CompleteAllJobs(); var expectedChildWorldPosition = m_Manager.GetComponentData(child).Position; @@ -62,8 +62,8 @@ public void TRS_RemovedParentDoesNotAffectChildPosition() Value = math.mul( float4x4.RotateY((float)math.PI), float4x4.Translate( new float3(0.0f, 0.0f, 1.0f))) }); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); var childWorldPosition = m_Manager.GetComponentData(child).Position; @@ -251,14 +251,14 @@ public void CreateWithCompositeScaleParentScaleInverse() public void Update() { - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); - World.GetOrCreateManager().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); + World.GetOrCreateSystem().Update(); // Force complete so that main thread (tests) can have access to direct editing. m_Manager.CompleteAllJobs(); diff --git a/Unity.Transforms/CompositeRotation.cs b/Unity.Transforms/CompositeRotation.cs index 803b67d3..ddfd7aa2 100644 --- a/Unity.Transforms/CompositeRotation.cs +++ b/Unity.Transforms/CompositeRotation.cs @@ -39,7 +39,7 @@ public struct RotationPivotTranslation : IComponentData // CompositeRotation = RotationPivotTranslation * RotationPivot * Rotation * PostRotation * RotationPivot^-1 public abstract class CompositeRotationSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; [BurstCompile] struct ToCompositeRotation : IJobChunk @@ -357,9 +357,9 @@ public void Execute(ArchetypeChunk chunk, int index, int entityOffset) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery + m_Group = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -372,7 +372,7 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/CompositeScale.cs b/Unity.Transforms/CompositeScale.cs index c1c17438..a6346f11 100644 --- a/Unity.Transforms/CompositeScale.cs +++ b/Unity.Transforms/CompositeScale.cs @@ -35,7 +35,7 @@ public struct ScalePivotTranslation : IComponentData // (or) CompositeScale = ScalePivotTranslation * ScalePivot * NonUniformScale * ScalePivot^-1 public abstract class CompositeScaleSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; [BurstCompile] struct ToCompositeScale : IJobChunk @@ -272,9 +272,9 @@ public void Execute(ArchetypeChunk chunk, int index, int entityOffset) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery + m_Group = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -287,7 +287,7 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/LocalToParentSystem.cs b/Unity.Transforms/LocalToParentSystem.cs index 86406ede..8f8e4715 100644 --- a/Unity.Transforms/LocalToParentSystem.cs +++ b/Unity.Transforms/LocalToParentSystem.cs @@ -10,7 +10,7 @@ namespace Unity.Transforms { public abstract class LocalToParentSystem : JobComponentSystem { - private ComponentGroup m_RootsGroup; + private EntityQuery m_RootsGroup; // LocalToWorld = Parent.LocalToWorld * LocalToParent [BurstCompile] @@ -56,9 +56,9 @@ public void Execute(ArchetypeChunk chunk, int index, int entityOffset) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_RootsGroup = GetComponentGroup(new EntityArchetypeQuery + m_RootsGroup = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -69,7 +69,7 @@ protected override void OnCreateManager() { typeof(Parent) }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/ParentScaleInverse.cs b/Unity.Transforms/ParentScaleInverse.cs index 332d4369..cafce220 100644 --- a/Unity.Transforms/ParentScaleInverse.cs +++ b/Unity.Transforms/ParentScaleInverse.cs @@ -25,7 +25,7 @@ public struct ParentScaleInverse : IComponentData // (or) ParentScaleInverse = Parent.NonUniformScale^-1 public abstract class ParentScaleInverseSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; [BurstCompile] struct ToChildParentScaleInverse : IJobChunk @@ -115,9 +115,9 @@ public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery + m_Group = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -129,7 +129,7 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/ParentSystem.cs b/Unity.Transforms/ParentSystem.cs index bae1cf79..9b17ba26 100644 --- a/Unity.Transforms/ParentSystem.cs +++ b/Unity.Transforms/ParentSystem.cs @@ -8,10 +8,10 @@ namespace Unity.Transforms { public abstract class ParentSystem : ComponentSystem { - private ComponentGroup m_NewParentsGroup; - private ComponentGroup m_RemovedParentsGroup; - private ComponentGroup m_ExistingParentsGroup; - private ComponentGroup m_DeletedParentsGroup; + private EntityQuery m_NewParentsGroup; + private EntityQuery m_RemovedParentsGroup; + private EntityQuery m_ExistingParentsGroup; + private EntityQuery m_DeletedParentsGroup; void AddChildToParent(Entity childEntity, Entity parentEntity) { @@ -96,9 +96,9 @@ public void Execute() } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_NewParentsGroup = GetComponentGroup(new EntityArchetypeQuery + m_NewParentsGroup = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -110,9 +110,9 @@ protected override void OnCreateManager() { typeof(PreviousParent) }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); - m_RemovedParentsGroup = GetComponentGroup(new EntityArchetypeQuery + m_RemovedParentsGroup = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -122,9 +122,9 @@ protected override void OnCreateManager() { typeof(Parent) }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); - m_ExistingParentsGroup = GetComponentGroup(new EntityArchetypeQuery + m_ExistingParentsGroup = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -133,9 +133,9 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), typeof(PreviousParent) }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); - m_DeletedParentsGroup = GetComponentGroup(new EntityArchetypeQuery + m_DeletedParentsGroup = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -145,7 +145,7 @@ protected override void OnCreateManager() { typeof(LocalToWorld) }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/PostRotationEuler.cs b/Unity.Transforms/PostRotationEuler.cs index 2fd36304..ecdddad4 100644 --- a/Unity.Transforms/PostRotationEuler.cs +++ b/Unity.Transforms/PostRotationEuler.cs @@ -66,11 +66,11 @@ public struct PostRotationEulerZYX : IComponentData // (or) PostRotation = PostRotationEulerZYX public abstract class PostRotationEulerSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery + m_Group = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -85,7 +85,7 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/RotationEuler.cs b/Unity.Transforms/RotationEuler.cs index f9f85047..716b3ac7 100644 --- a/Unity.Transforms/RotationEuler.cs +++ b/Unity.Transforms/RotationEuler.cs @@ -66,11 +66,11 @@ public struct RotationEulerZYX : IComponentData // (or) Rotation = RotationEulerZYX public abstract class RotationEulerSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery + m_Group = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { @@ -85,7 +85,7 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/TRSToLocalToParentSystem.cs b/Unity.Transforms/TRSToLocalToParentSystem.cs index 5036df92..9fe32113 100644 --- a/Unity.Transforms/TRSToLocalToParentSystem.cs +++ b/Unity.Transforms/TRSToLocalToParentSystem.cs @@ -31,7 +31,7 @@ namespace Unity.Transforms public abstract class TRSToLocalToParentSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; [BurstCompile] struct TRSToLocalToParent : IJobChunk @@ -468,9 +468,9 @@ public void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery() + m_Group = GetEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { @@ -486,7 +486,7 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/TRSToLocalToWorldSystem.cs b/Unity.Transforms/TRSToLocalToWorldSystem.cs index 6c5b4029..292f9fe3 100644 --- a/Unity.Transforms/TRSToLocalToWorldSystem.cs +++ b/Unity.Transforms/TRSToLocalToWorldSystem.cs @@ -24,7 +24,7 @@ namespace Unity.Transforms // (or) LocalToWorld = Translation * CompositeRotation * CompositeScale public abstract class TRSToLocalToWorldSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; [BurstCompile] struct TRSToLocalToWorld : IJobChunk @@ -223,9 +223,9 @@ public void Execute(ArchetypeChunk chunk, int chunkIndex, int entityOffset) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery() + m_Group = GetEntityQuery(new EntityQueryDesc() { All = new ComponentType[] { @@ -239,7 +239,7 @@ protected override void OnCreateManager() ComponentType.ReadOnly(), ComponentType.ReadOnly() }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/Unity.Transforms/WorldToLocal.cs b/Unity.Transforms/WorldToLocal.cs index 75947577..9c5f3d75 100644 --- a/Unity.Transforms/WorldToLocal.cs +++ b/Unity.Transforms/WorldToLocal.cs @@ -19,7 +19,7 @@ public struct WorldToLocal : IComponentData public abstract class WorldToLocalSystem : JobComponentSystem { - private ComponentGroup m_Group; + private EntityQuery m_Group; struct ToWorldToLocal : IJobChunk { @@ -43,16 +43,16 @@ public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex) } } - protected override void OnCreateManager() + protected override void OnCreate() { - m_Group = GetComponentGroup(new EntityArchetypeQuery + m_Group = GetEntityQuery(new EntityQueryDesc { All = new ComponentType[] { typeof(WorldToLocal), ComponentType.ReadOnly(), }, - Options = EntityArchetypeQueryOptions.FilterWriteGroup + Options = EntityQueryOptions.FilterWriteGroup }); } diff --git a/package.json b/package.json index 72973ec2..6f5bb73e 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,16 @@ { + "displayName": "Entities", "name": "com.unity.entities", "unity": "2019.1", - "version": "0.0.12-preview.29", + "version": "0.0.12-preview.30", "dependencies": { "nuget.mono-cecil": "0.1.6-preview", "com.unity.test-framework.performance": "1.0.6-preview", "com.unity.properties": "0.4.0-preview", "com.unity.mathematics": "1.0.0-preview.1", - "com.unity.collections": "0.0.9-preview.16", - "com.unity.burst": "1.0.0-preview.4", - "com.unity.jobs": "0.0.7-preview.9" + "com.unity.collections": "0.0.9-preview.17", + "com.unity.burst": "1.0.0-preview.8", + "com.unity.jobs": "0.0.7-preview.10" }, "keywords": [ "entities",