Exemplo n.º 1
0
        public void SetFilter <SharedComponent1, SharedComponent2>(SharedComponent1 sharedComponent1,
                                                                   SharedComponent2 sharedComponent2)
            where SharedComponent1 : struct, ISharedComponentData
            where SharedComponent2 : struct, ISharedComponentData
        {
            var sm = ArchetypeManager.GetSharedComponentDataManager();

            var filter = new ComponentGroupFilter();

            filter.Type         = FilterType.SharedComponent;
            filter.Shared.Count = 2;
            filter.Shared.IndexInComponentGroup[0] = GetIndexInComponentGroup(TypeManager.GetTypeIndex <SharedComponent1>());
            filter.Shared.SharedComponentIndex[0]  = sm.InsertSharedComponent(sharedComponent1);

            filter.Shared.IndexInComponentGroup[1] = GetIndexInComponentGroup(TypeManager.GetTypeIndex <SharedComponent2>());
            filter.Shared.SharedComponentIndex[1]  = sm.InsertSharedComponent(sharedComponent2);

            SetFilter(ref filter);
        }
Exemplo n.º 2
0
        internal void GetComponentDataArray <T>(ref ComponentChunkIterator iterator, int indexInComponentGroup,
                                                int length, out ComponentDataArray <T> output) where T : struct, IComponentData
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            var typeIndex     = TypeManager.GetTypeIndex <T>();
            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 <T>(iterator, length, GetSafetyHandle(indexInComponentGroup));
#else
            output = new ComponentDataArray <T>(iterator, length);
#endif
        }
Exemplo n.º 3
0
        /// <summary>
        /// Sets the value of a component of an entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="componentData">The data to set.</param>
        /// <typeparam name="T">The component type.</typeparam>
        /// <exception cref="ArgumentException">Thrown if the component type has no fields.</exception>
        public void SetComponentData <T>(Entity entity, T componentData) where T : struct, IComponentData
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();

            EntityComponentStore->AssertEntityHasComponent(entity, typeIndex);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            if (ComponentType.FromTypeIndex(typeIndex).IsZeroSized)
            {
                throw new System.ArgumentException(
                          $"SetComponentData<{typeof(T)}> can not be called with a zero sized component.");
            }
#endif

            ComponentJobSafetyManager->CompleteReadAndWriteDependency(typeIndex);

            var ptr = EntityComponentStore->GetComponentDataWithTypeRW(entity, typeIndex, EntityComponentStore->GlobalSystemVersion);
            UnsafeUtility.CopyStructureToPtr(ref componentData, ptr);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Filters this EntityQuery based on the values of two separate shared components.
        /// </summary>
        /// <remarks>
        /// The filter only selects entities for which both shared component values
        /// specified by the `sharedComponent1` and `sharedComponent2` parameters match.
        /// </remarks>
        /// <param name="sharedComponent1">Shared component values on which to filter.</param>
        /// <param name="sharedComponent2">Shared component values on which to filter.</param>
        /// <typeparam name="SharedComponent1">The type of shared component. (The type must also be
        /// one of the types used to create the EntityQuery.</typeparam>
        /// <typeparam name="SharedComponent2">The type of shared component. (The type must also be
        /// one of the types used to create the EntityQuery.</typeparam>
        public void SetFilter <SharedComponent1, SharedComponent2>(SharedComponent1 sharedComponent1,
                                                                   SharedComponent2 sharedComponent2)
            where SharedComponent1 : struct, ISharedComponentData
            where SharedComponent2 : struct, ISharedComponentData
        {
            var sm = ManagedComponentStore;

            var filter = new EntityQueryFilter();

            filter.Type         = FilterType.SharedComponent;
            filter.Shared.Count = 2;
            filter.Shared.IndexInEntityQuery[0]   = GetIndexInEntityQuery(TypeManager.GetTypeIndex <SharedComponent1>());
            filter.Shared.SharedComponentIndex[0] = sm.InsertSharedComponent(sharedComponent1);

            filter.Shared.IndexInEntityQuery[1]   = GetIndexInEntityQuery(TypeManager.GetTypeIndex <SharedComponent2>());
            filter.Shared.SharedComponentIndex[1] = sm.InsertSharedComponent(sharedComponent2);

            SetFilter(ref filter);
        }
Exemplo n.º 5
0
        private static unsafe void ApplyAddComponents(
            EntityManager entityManager,
            NativeArray <PackedComponent> addComponents,
            NativeArray <EntityGuid> packedEntityGuids,
            NativeMultiHashMap <int, Entity> packedEntities,
            NativeArray <ComponentType> packedTypes)
        {
            var linkedEntityGroupTypeIndex = TypeManager.GetTypeIndex <LinkedEntityGroup>();

            for (var i = 0; i < addComponents.Length; i++)
            {
                var packedComponent = addComponents[i];

                if (!packedEntities.TryGetFirstValue(packedComponent.PackedEntityIndex, out var entity, out var iterator))
                {
                    continue;
                }

                var component = packedTypes[packedComponent.PackedTypeIndex];

                do
                {
                    if (!entityManager.EntityComponentStore->HasComponent(entity, component))
                    {
                        entityManager.AddComponent(entity, component);

                        // 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 (component.TypeIndex == linkedEntityGroupTypeIndex)
                        {
                            var buffer = entityManager.GetBuffer <LinkedEntityGroup>(entity);
                            buffer.Add(entity);
                        }
                    }
                    else
                    {
                        Debug.LogWarning($"AddComponent({packedEntityGuids[packedComponent.PackedEntityIndex]}, {component}) but the component already exists.");
                    }
                }while (packedEntities.TryGetNextValue(out entity, ref iterator));
            }
        }
Exemplo n.º 6
0
        bool TestMatchingArchetypeAll(Archetype *archetype, ComponentType *allTypes, int allCount)
        {
            var componentTypes      = archetype->Types;
            var componentTypesCount = archetype->TypesCount;
            var foundCount          = 0;
            var disabledTypeIndex   = TypeManager.GetTypeIndex <Disabled>();
            var prefabTypeIndex     = TypeManager.GetTypeIndex <Prefab>();
            var requestedDisabled   = false;
            var requestedPrefab     = false;

            for (var i = 0; i < componentTypesCount; i++)
            {
                var componentTypeIndex = componentTypes[i].TypeIndex;
                for (var j = 0; j < allCount; j++)
                {
                    var allTypeIndex = allTypes[j].TypeIndex;
                    if (allTypeIndex == disabledTypeIndex)
                    {
                        requestedDisabled = true;
                    }
                    if (allTypeIndex == prefabTypeIndex)
                    {
                        requestedPrefab = true;
                    }
                    if (componentTypeIndex == allTypeIndex)
                    {
                        foundCount++;
                    }
                }
            }

            if (archetype->Disabled && (!requestedDisabled))
            {
                return(false);
            }
            if (archetype->Prefab && (!requestedPrefab))
            {
                return(false);
            }

            return(foundCount == allCount);
        }
Exemplo n.º 7
0
        public ComponentDataArray <T> GetComponentDataArray <T>() where T : struct, IComponentData
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();

#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 <T> res;
            GetComponentDataArray(ref iterator, indexInComponentGroup, length, out res);
            return(res);
        }
Exemplo n.º 8
0
        public int InsertSharedComponent <T>(T newData) where T : struct
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();
            var index     = FindSharedComponentIndex(TypeManager.GetTypeIndex <T>(), newData);

            if (index == 0)
            {
                return(0);
            }

            if (index != -1)
            {
                m_SharedComponentRefCount[index]++;
                return(index);
            }

            var hashcode = TypeManager.GetHashCode <T>(ref newData);

            return(Add(typeIndex, hashcode, newData));
        }
Exemplo n.º 9
0
        static SharedComponentDataManager()
        {
            TypeManager.Initialize();
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            ISharedComponentDataType = typeof(ISharedComponentData);
            for (int i = 0; i < assemblies.Length; ++i)
            {
                var types = assemblies[i].GetTypes();
                for (int j = 0; j < types.Length; ++j)
                {
                    if (!types[j].IsValueType || !ISharedComponentDataType.IsAssignableFrom(types[j]) || (types[j].IsGenericType && types[j].IsGenericTypeDefinition))
                    {
                        continue;
                    }
                    TypeManager.GetTypeIndex(types[j]);
                }
            }
            for (int i = 1, length = TypeManager.GetTypeCount(); i < length; ++i)
            {
                var type = TypeManager.GetType(i);
                if (!type.IsValueType || !ISharedComponentDataType.IsAssignableFrom(type) || (type.IsGenericType && type.IsGenericTypeDefinition))
                {
                    continue;
                }
#if REF_EQUATABLE
                var EqualsMethodInfo = type.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, CallingConventions.Any, EqualsTypeArray, null);
                if (EqualsMethodInfo == null || EqualsMethodInfo.DeclaringType != type)
                {
                    throw new Exception(type.FullName);
                }
                var GetHashCodeMethodInfo = type.GetMethod("GetHashCode", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, CallingConventions.Any, Array.Empty <Type>(), null);
                if (GetHashCodeMethodInfo == null || GetHashCodeMethodInfo.DeclaringType != type)
                {
                    throw new Exception(type.FullName);
                }
#endif
                SharedComponentTypeStart = i;
                break;
            }
        }
Exemplo n.º 10
0
        public int InsertSharedComponent <T>(T newData) where T : struct
        {
            int typeIndex = TypeManager.GetTypeIndex <T>();
            int index     = FindSharedComponentIndex(TypeManager.GetTypeIndex <T>(), newData);

            if (index == 0)
            {
                return(0);
            }
            else if (index != -1)
            {
                m_SharedComponentRefCount[index]++;
                return(index);
            }
            else
            {
                var fastLayout = TypeManager.GetComponentType(typeIndex).FastEqualityLayout;
                var hashcode   = FastEquality.GetHashCode(ref newData, fastLayout);
                return(Add(typeIndex, hashcode, newData));
            }
        }
Exemplo n.º 11
0
        public T GetComponentData <T>(Entity entity) where T : struct, IComponentData
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();

            Entities->AssertEntityHasComponent(entity, typeIndex);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            if (ComponentType.FromTypeIndex(typeIndex).IsZeroSized)
            {
                throw new System.ArgumentException($"GetComponentData<{typeof(T)}> can not be called with a zero sized component.");
            }
#endif

            ComponentJobSafetyManager.CompleteWriteDependency(typeIndex);

            var ptr = Entities->GetComponentDataWithTypeRO(entity, typeIndex);

            T value;
            UnsafeUtility.CopyPtrToStructure(ptr, out value);
            return(value);
        }
        public static T[] ToComponentArray <T>(this EntityQuery group) where T : Component
        {
            int entityCount = group.CalculateEntityCount();
            var arr         = new T[entityCount];

            var iterator           = group.GetArchetypeChunkIterator();
            var indexInEntityQuery = group.GetIndexInEntityQuery(TypeManager.GetTypeIndex <T>());

            var entityCounter = 0;

            while (iterator.MoveNext())
            {
                var chunk = iterator.CurrentArchetypeChunk;
                for (int entityIndex = 0; entityIndex < chunk.Count; ++entityIndex)
                {
                    arr[entityCounter++] = (T)iterator.GetManagedObject(group.ManagedComponentStore, indexInEntityQuery, entityIndex);
                }
            }

            return(arr);
        }
Exemplo n.º 13
0
        public void SetComponentData <T>(Entity entity, T componentData) where T : struct, IComponentData
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();

            Entities->AssertEntityHasComponent(entity, typeIndex);

            // If the user attempts to set a zero-sized type, we do nothing instead.
            // This is to prevent requiring users from checking for zero-size before calling this API.
            var componentType = ComponentType.FromTypeIndex(typeIndex);

            if (componentType.IsZeroSized)
            {
                return;
            }

            ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex);

            var ptr = Entities->GetComponentDataWithTypeRW(entity, typeIndex, Entities->GlobalSystemVersion);

            UnsafeUtility.CopyStructureToPtr(ref componentData, ptr);
        }
Exemplo n.º 14
0
        internal bool CompareComponents(ComponentType *componentTypes, int count)
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            for (var k = 0; k < count; ++k)
            {
                if (componentTypes[k].TypeIndex == TypeManager.GetTypeIndex <Entity>())
                {
                    throw new ArgumentException(
                              "ComponentGroup.CompareComponents may not include typeof(Entity), it is implicit");
                }
            }
#endif

            // ComponentGroups are constructed including the Entity ID
            var requiredCount = m_GroupData->RequiredComponentsCount;
            if (count != requiredCount - 1)
            {
                return(false);
            }

            for (var k = 0; k < count; ++k)
            {
                int i;
                for (i = 1; i < requiredCount; ++i)
                {
                    if (m_GroupData->RequiredComponents[i] == componentTypes[k])
                    {
                        break;
                    }
                }

                if (i == requiredCount)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 15
0
        internal unsafe void AddEntitySharedComponentCommand <T>(EntityCommandBufferChain *chain, int jobIndex, ECBCommand op, Entity e, int hashCode, object boxedObject) where T : struct
        {
            int size = Align(sizeof(EntitySharedComponentCommand), 8);
            EntitySharedComponentCommand *commandPtr = (EntitySharedComponentCommand *)ref this.Reserve(chain, jobIndex, size);

            commandPtr->Header.Header.CommandType = (int)op;
            commandPtr->Header.Header.TotalSize   = size;
            commandPtr->Header.Header.SortIndex   = chain.m_LastSortIndex;
            commandPtr->Header.Entity             = e;
            commandPtr->ComponentTypeIndex        = TypeManager.GetTypeIndex <T>();
            commandPtr->HashCode = hashCode;
            if (boxedObject == null)
            {
                commandPtr->BoxedObject = new GCHandle();
            }
            else
            {
                commandPtr->BoxedObject = GCHandle.Alloc(boxedObject);
                commandPtr->Prev        = chain.m_CleanupList;
                chain.m_CleanupList     = commandPtr;
            }
        }
Exemplo n.º 16
0
        private static unsafe void ApplyRemoveComponents(
            EntityManager entityManager,
            NativeArray <PackedComponent> removeComponents,
            NativeArray <EntityGuid> packedEntityGuids,
            NativeMultiHashMap <int, Entity> packedEntities,
            NativeArray <ComponentType> packedTypes)
        {
            var entityGuidTypeIndex = TypeManager.GetTypeIndex <EntityGuid>();

            for (var i = 0; i < removeComponents.Length; i++)
            {
                var packedComponent = removeComponents[i];

                if (!packedEntities.TryGetFirstValue(packedComponent.PackedEntityIndex, out var entity, out var iterator))
                {
                    continue;
                }

                var component = packedTypes[packedComponent.PackedTypeIndex];

                do
                {
                    if (component.TypeIndex == entityGuidTypeIndex)
                    {
                        // @TODO Add test cases around this.
                        // Should entityGuidToEntity be updated or should we throw and error.
                    }

                    if (entityManager.EntityComponentStore->HasComponent(entity, component))
                    {
                        entityManager.RemoveComponent(entity, component);
                    }
                    else
                    {
                        Debug.LogWarning($"RemoveComponent({packedEntityGuids[packedComponent.PackedEntityIndex]}, {component}) but the component already exists.");
                    }
                }while (packedEntities.TryGetNextValue(out entity, ref iterator));
            }
        }
Exemplo n.º 17
0
        public DynamicBuffer <T> GetBuffer <T>(Entity entity) where T : struct, IBufferElementData
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            Entities->AssertEntityHasComponent(entity, typeIndex);
            if (TypeManager.GetTypeInfo <T>().Category != TypeManager.TypeCategory.BufferData)
            {
                throw new ArgumentException(
                          $"GetBuffer<{typeof(T)}> may not be IComponentData or ISharedComponentData; currently {TypeManager.GetTypeInfo<T>().Category}");
            }
#endif

            ComponentJobSafetyManager.CompleteReadAndWriteDependency(typeIndex);

            BufferHeader *header = (BufferHeader *)Entities->GetComponentDataWithTypeRW(entity, typeIndex, Entities->GlobalSystemVersion);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            return(new DynamicBuffer <T>(header, ComponentJobSafetyManager.GetSafetyHandle(typeIndex, false), ComponentJobSafetyManager.GetBufferSafetyHandle(typeIndex), false));
#else
            return(new DynamicBuffer <T>(header));
#endif
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a NativeArray containing the components of type T for the selected entities.
        /// </summary>
        /// <param name="allocator">The type of memory to allocate.</param>
        /// <typeparam name="T">The component type.</typeparam>
        /// <returns>An array containing the specified component for all the entities selected
        /// by the EntityQuery.</returns>
        /// <exception cref="InvalidOperationException">Thrown if you ask for a component that is not part of
        /// the group.</exception>
        public NativeArray <T> ToComponentDataArray <T>(Allocator allocator)
            where T : struct, IComponentData
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            var componentType = new ArchetypeChunkComponentType <T>(m_SafetyManager->GetSafetyHandle(TypeManager.GetTypeIndex <T>(), true), true, EntityComponentStore->GlobalSystemVersion);
#else
            var componentType = new ArchetypeChunkComponentType <T>(true, EntityComponentStore->GlobalSystemVersion);
#endif

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            int typeIndex          = TypeManager.GetTypeIndex <T>();
            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

            JobHandle job;
            var       res = ComponentChunkIterator.CreateComponentDataArray(m_QueryData->MatchingArchetypes, allocator, componentType, this, ref m_Filter, out job, GetDependency());
            job.Complete();
            return(res);
        }
Exemplo n.º 19
0
        public static void AssertArchetypeComponents(ComponentTypeInArchetype *types, int count)
        {
            if (count < 1)
            {
                throw new ArgumentException($"Invalid component count");
            }
            if (types[0].TypeIndex != TypeManager.GetTypeIndex <Entity>())
            {
                throw new ArgumentException($"The Entity ID must always be the first component");
            }

            for (var i = 1; i < count; i++)
            {
                if (!TypeManager.IsValidComponentTypeForArchetype(types[i].TypeIndex, types[i].IsFixedArray))
                {
                    throw new ArgumentException($"{types[i]} is not a valid component type.");
                }
                if (types[i - 1].TypeIndex == types[i].TypeIndex)
                {
                    throw new ArgumentException($"It is not allowed to have two components of the same type on the same entity. ({types[i-1]} and {types[i]})");
                }
            }
        }
Exemplo n.º 20
0
        public ForEachComponentGroupFilter CreateForEachFilter <SharedComponent1>(
            List <SharedComponent1> sharedComponent1)
            where SharedComponent1 : struct, ISharedComponentData
        {
            var forEachFilter = new ForEachComponentGroupFilter();

            forEachFilter.TypeManager  = ArchetypeManager;
            forEachFilter.ItemIterator =
                new NativeArray <ComponentChunkIterator>(sharedComponent1.Count, Allocator.Temp);
            forEachFilter.ItemLength            = new NativeArray <int>(sharedComponent1.Count, Allocator.Temp);
            forEachFilter.SharedComponentIndex  = new NativeArray <int>(sharedComponent1.Count, Allocator.Temp);
            forEachFilter.IndexInComponentGroup =
                GetIndexInComponentGroup(TypeManager.GetTypeIndex <SharedComponent1>());
            for (var i = 0; i < sharedComponent1.Count; ++i)
            {
                forEachFilter.SharedComponentIndex[i] = ArchetypeManager.GetSharedComponentDataManager()
                                                        .InsertSharedComponent(sharedComponent1[i]);
            }

            m_ComponentGroupData.GetComponentChunkIterators(forEachFilter);

            return(forEachFilter);
        }
Exemplo n.º 21
0
        public static T[] ToComponentArray <T>(this ComponentGroup group) where T : Component
        {
            int length = group.CalculateLength();
            ComponentChunkIterator iterator = group.GetComponentChunkIterator();
            var indexInComponentGroup       = group.GetIndexInComponentGroup(TypeManager.GetTypeIndex <T>());

            iterator.IndexInComponentGroup = indexInComponentGroup;

            var arr   = new T[length];
            var cache = default(ComponentChunkCache);

            for (int i = 0; i < length; ++i)
            {
                if (i < cache.CachedBeginIndex || i >= cache.CachedEndIndex)
                {
                    iterator.MoveToEntityIndexAndUpdateCache(i, out cache, true);
                }

                arr[i] = (T)iterator.GetManagedObject(group.ArchetypeManager, cache.CachedBeginIndex, i);
            }

            return(arr);
        }
Exemplo n.º 22
0
        public int InsertSharedComponent <T>(T newData) where T : struct
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();
            var index     = FindSharedComponentIndex(TypeManager.GetTypeIndex <T>(), newData);

            if (index == 0)
            {
                return(0);
            }

            if (index != -1)
            {
                SharedComponentInfoPtr[index].RefCount++;
                return(index);
            }

            var hashcode = TypeManager.GetHashCode <T>(ref newData);

            object newDataObj = newData;

            (newDataObj as IRefCounted)?.Retain();
            return(Add(typeIndex, hashcode, newDataObj));
        }
Exemplo n.º 23
0
        public T GetComponentData <T>(Entity entity) where T : struct, IComponentData
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();

            Entities->AssertEntityHasComponent(entity, typeIndex);

            // If the user attempts to get a zero-sized type, we return a default-initialized value instead.
            // This is to prevent requiring users from checking for zero-size before calling this API.
            var componentType = ComponentType.FromTypeIndex(typeIndex);

            if (componentType.IsZeroSized)
            {
                return(default(T));
            }

            ComponentJobSafetyManager.CompleteWriteDependency(typeIndex);

            var ptr = Entities->GetComponentDataWithTypeRO(entity, typeIndex);

            T value;

            UnsafeUtility.CopyPtrToStructure(ptr, out value);
            return(value);
        }
Exemplo n.º 24
0
        IPropertyBag GetPropertyBag(object obj)
        {
            if (null == obj)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            var type     = obj.GetType();
            var typeInfo = TypeManager.GetTypeInfo(TypeManager.GetTypeIndex(type));

            if (typeInfo.Category == TypeManager.TypeCategory.UnityEngineObject)
            {
                throw new ArgumentException("Cannot remap hybrid components", nameof(obj));
            }

            var properties = PropertyBagStore.GetPropertyBag(type);

            if (null == properties)
            {
                throw new MissingPropertyBagException(type);
            }

            return(properties);
        }
        public DynamicBuffer <T> GetBuffer <T>(Entity entity) where T : struct, IBufferElementData
        {
            CheckAccess();

            var typeIndex = TypeManager.GetTypeIndex <T>();

            m_Entities->AssertEntityHasComponent(entity, typeIndex);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            if (!TypeManager.IsBuffer(typeIndex))
            {
                throw new ArgumentException(
                          $"GetBuffer<{typeof(T)}> may not be IComponentData or ISharedComponentData; currently {TypeManager.GetTypeInfo<T>().Category}");
            }
#endif

            BufferHeader *header = (BufferHeader *)m_Entities->GetComponentDataWithTypeRW(entity, typeIndex, m_Entities->GlobalSystemVersion);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            return(new DynamicBuffer <T>(header, m_Safety, m_Safety, false));
#else
            return(new DynamicBuffer <T>(header));
#endif
        }
Exemplo n.º 26
0
        public void SetSingleton <T>(T value)
            where T : struct, IComponentData
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            if (GetIndexInComponentGroup(TypeManager.GetTypeIndex <T>()) != 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}.");
            }
#endif

            CompleteDependency();

            var iterator = GetComponentChunkIterator();
            iterator.MoveToChunkWithoutFiltering(0);

            var array = iterator.GetCurrentChunkComponentDataPtr(true, 1);
            UnsafeUtility.CopyStructureToPtr(ref value, array);
        }
Exemplo n.º 27
0
        public int GetSharedComponentVersion <T>(T sharedData) where T : struct
        {
            var index = FindSharedComponentIndex(TypeManager.GetTypeIndex <T>(), sharedData);

            return(index == -1 ? 0 : m_SharedComponentVersion[index]);
        }
        // ----------------------------------------------------------------------------------------------------------
        // PUBLIC
        // ----------------------------------------------------------------------------------------------------------

        public static Archetype *GetOrCreateArchetype(ComponentTypeInArchetype *inTypesSorted, int count,
                                                      EntityComponentStore *entityComponentStore)
        {
            var srcArchetype = entityComponentStore->GetExistingArchetype(inTypesSorted, count);

            if (srcArchetype != null)
            {
                return(srcArchetype);
            }

            srcArchetype = entityComponentStore->CreateArchetype(inTypesSorted, count);
            var types = stackalloc ComponentTypeInArchetype[count + 1];

            // Setup Instantiable archetype
            {
                UnsafeUtility.MemCpy(types, inTypesSorted, sizeof(ComponentTypeInArchetype) * count);

                var hasCleanup       = false;
                var removedTypes     = 0;
                var prefabTypeIndex  = TypeManager.GetTypeIndex <Prefab>();
                var cleanupTypeIndex = TypeManager.GetTypeIndex <CleanupEntity>();
                for (var t = 0; t < srcArchetype->TypesCount; ++t)
                {
                    var type = srcArchetype->Types[t];

                    hasCleanup |= type.TypeIndex == cleanupTypeIndex;

                    var skip = type.IsSystemStateComponent || type.TypeIndex == prefabTypeIndex;
                    if (skip)
                    {
                        ++removedTypes;
                    }
                    else
                    {
                        types[t - removedTypes] = srcArchetype->Types[t];
                    }
                }

                // Entity has already been destroyed, so it shouldn't be instantiated anymore
                if (hasCleanup)
                {
                    srcArchetype->InstantiableArchetype = null;
                }
                else if (removedTypes > 0)
                {
                    var instantiableArchetype = GetOrCreateArchetype(types, count - removedTypes, entityComponentStore);

                    srcArchetype->InstantiableArchetype = instantiableArchetype;
                    Assert.IsTrue(instantiableArchetype->InstantiableArchetype == instantiableArchetype);
                    Assert.IsTrue(instantiableArchetype->SystemStateResidueArchetype == null);
                }
                else
                {
                    srcArchetype->InstantiableArchetype = srcArchetype;
                }
            }


            // Setup System state cleanup archetype
            if (srcArchetype->SystemStateCleanupNeeded)
            {
                var  cleanupEntityType = new ComponentTypeInArchetype(ComponentType.ReadWrite <CleanupEntity>());
                bool cleanupAdded      = false;

                types[0] = inTypesSorted[0];
                var newTypeCount = 1;

                for (var t = 1; t < srcArchetype->TypesCount; ++t)
                {
                    var type = srcArchetype->Types[t];

                    if (type.IsSystemStateComponent)
                    {
                        if (!cleanupAdded && (cleanupEntityType < srcArchetype->Types[t]))
                        {
                            types[newTypeCount++] = cleanupEntityType;
                            cleanupAdded          = true;
                        }

                        types[newTypeCount++] = srcArchetype->Types[t];
                    }
                }

                if (!cleanupAdded)
                {
                    types[newTypeCount++] = cleanupEntityType;
                }

                var systemStateResidueArchetype = GetOrCreateArchetype(types, newTypeCount, entityComponentStore);
                srcArchetype->SystemStateResidueArchetype = systemStateResidueArchetype;

                Assert.IsTrue(systemStateResidueArchetype->SystemStateResidueArchetype == systemStateResidueArchetype);
                Assert.IsTrue(systemStateResidueArchetype->InstantiableArchetype == null);
            }

            // Setup meta chunk archetype
            if (count > 1)
            {
                types[0] = new ComponentTypeInArchetype(typeof(Entity));
                int metaArchetypeTypeCount = 1;
                for (int i = 1; i < count; ++i)
                {
                    var           t = inTypesSorted[i];
                    ComponentType typeToInsert;
                    if (inTypesSorted[i].IsChunkComponent)
                    {
                        typeToInsert = new ComponentType
                        {
                            TypeIndex = TypeManager.ChunkComponentToNormalTypeIndex(t.TypeIndex)
                        };
                        SortingUtilities.InsertSorted(types, metaArchetypeTypeCount++, typeToInsert);
                    }
                }

                if (metaArchetypeTypeCount > 1)
                {
                    SortingUtilities.InsertSorted(types, metaArchetypeTypeCount++, new ComponentType(typeof(ChunkHeader)));
                    srcArchetype->MetaChunkArchetype = GetOrCreateArchetype(types, metaArchetypeTypeCount, entityComponentStore);
                }
            }

            return(srcArchetype);
        }
Exemplo n.º 29
0
 internal BufferFromEntity <T> GetBufferFromEntity <T>(bool isReadOnly = false)
     where T : struct, IBufferElementData
 {
     return(GetBufferFromEntity <T>(TypeManager.GetTypeIndex <T>(), isReadOnly));
 }
Exemplo n.º 30
0
        public static ComponentType ChunkComponentReadOnly <T>()
        {
            var typeIndex = TypeManager.MakeChunkComponentTypeIndex(TypeManager.GetTypeIndex <T>());

            return(ReadOnly(typeIndex));
        }