Exemplo n.º 1
0
 void EntitySelectionChanged(Entity entity, World _world, ComponentType type)
 {
     if (type.GetManagedType() == typeof(Entity))
     {
         if (_world.EntityManager != null)
         {
             selectionEntityProxy.SetEntity(_world, entity);
         }
         if (Selection.activeObject != selectionEntityProxy)
         {
             Selection.activeObject = selectionEntityProxy;
         }
     }
     else
     {
         if (_world.EntityManager == null)
         {
             return;
         }
         if (type.GetManagedType() == typeof(MonoBehaviour) &&
             type.GetManagedType() == typeof(ScriptableObject))
         {
             return;
         }
         var obj = _world.EntityManager.GetComponentFromType(entity, type);
         ObjectSelectionChanged(type, ref obj);
     }
 }
Exemplo n.º 2
0
        public void RegisterRpc(ComponentType type, PortableFunctionPointer <RpcExecutor.ExecuteDelegate> exec)
        {
            if (!exec.Ptr.IsCreated)
            {
                throw new InvalidOperationException(
                          $"不能注册Rpc类型 {type.GetManagedType()}: Ptr 属性没有创建 (null)" +
                          "Check CompileExecute() and verify you are initializing the PortableFunctionPointer with a valid static function delegate, decorated with [BurstCompile] attribute");
            }

            var hash = TypeManager.GetTypeInfo(type.TypeIndex).StableTypeHash;

            if (hash == 0)
            {
                throw new InvalidOperationException($"Unexpected 0 hash for type {type.GetManagedType()}");
            }

            if (_rpcTypeHashToIndex.TryGetValue(hash, out var index))
            {
                var rpcData = _rpcData[index];
                if (rpcData.TypeHash != 0)
                {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                    if (rpcData.RpcType == type)
                    {
                        throw new InvalidOperationException(
                                  String.Format("Registering RPC {0} multiple times is not allowed", type.GetManagedType()));
                    }
                    throw new InvalidOperationException(
                              String.Format("Type hash collision between types {0} and {1}", type.GetManagedType(),
                                            rpcData.RpcType.GetManagedType()));
#else
                    throw new InvalidOperationException(
                              String.Format("Hash collision or multiple registrations for {0}", type.GetManagedType()));
#endif
                }

                rpcData.TypeHash = hash;
                rpcData.Execute  = exec;
                _rpcData[index]  = rpcData;
            }
            else
            {
                _rpcTypeHashToIndex.Add(hash, _rpcData.Length);
                _rpcData.Add(new RpcData
                {
                    TypeHash = hash,
                    Execute  = exec,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                    RpcType = type
#endif
                });
            }

            // Debug.Log("注册Rpc:" + index + " " + World.Name);
        }
Exemplo n.º 3
0
        private IReactiveUpdateGroup CreateReactiveUpdateGroup(ComponentType componentType)
        {
            var group = GetComponentGroup(componentType, ComponentType.ReadOnly <ReactiveChanged>());

            var reactiveCompareType = typeof(ReactiveCompare <>).MakeGenericType(componentType.GetManagedType());

            var reactiveCompareSystem = typeof(ReactiveCompareSystem <,>).MakeGenericType(componentType.GetManagedType(), reactiveCompareType);

            World.CreateManager(reactiveCompareSystem);

            var makeme = typeof(ReactiveAddRemoveGroup <,>).MakeGenericType(componentType.GetManagedType(), reactiveCompareType);

            return((IReactiveUpdateGroup)Activator.CreateInstance(makeme, group));
        }
Exemplo n.º 4
0
    bool GetComponentData <T>(ref Entity entity, out NetworkComponent componentDataContainer) where T : struct, IComponentData
    {
        componentDataContainer = null;
        if (EntityManager.HasComponent <T>(entity))
        {
            ComponentType componentType   = ComponentType.Create <T>();
            int           numberOfMembers = reflectionUtility.GetFieldsCount(componentType.GetManagedType());

            T component = EntityManager.GetComponentData <T>(entity);
            NetworkField[]        networkMemberInfos   = reflectionUtility.GetFields(componentType);
            List <ComponentField> memberDataContainers = new List <ComponentField>();
            for (int i = 0; i < numberOfMembers; i++)
            {
                memberDataContainers.Add(new ComponentField()
                {
                    Id    = i,
                    Value = (networkMemberInfos[i] as NetworkField <T>).GetValue(component)
                });
            }


            componentDataContainer = new NetworkComponent()
            {
                TypeId = reflectionUtility.GetId(componentType),
                Fields = memberDataContainers
            };
            return(true);
        }
        return(false);
    }
Exemplo n.º 5
0
        protected override void OnUpdate()
        {
            Entities.WithStoreEntityQueryInField(ref m_query).WithStructuralChanges().ForEach((Entity entity, ref BlackboardEntityData globalEntityData) =>
            {
                var types        = EntityManager.GetComponentTypes(entity, Unity.Collections.Allocator.TempJob);
                var targetEntity = globalEntityData.blackboardScope == BlackboardScope.World ? worldBlackboardEntity : sceneBlackboardEntity;

                ComponentType errorType = default;
                bool error = false;
                foreach (var type in types)
                {
                    if (type.TypeIndex == ComponentType.ReadWrite <BlackboardEntityData>().TypeIndex)
                    {
                        continue;
                    }
                    if (globalEntityData.mergeMethod == MergeMethod.Overwrite || !targetEntity.HasComponent(type))
                    {
                        m_copyKit.CopyData(entity, targetEntity, type);
                    }
                    else if (globalEntityData.mergeMethod == MergeMethod.ErrorOnConflict)
                    {
                        errorType = type;
                        error     = true;
                    }
                }
                types.Dispose();
                if (error)
                {
                    throw new InvalidOperationException(
                        $"Entity {entity} could not copy component {errorType.GetManagedType()} onto {(globalEntityData.blackboardScope == BlackboardScope.World ? "world" : "scene")} entity because the component already exists and the MergeMethod was set to ErrorOnConflict.");
                }
            }).Run();
            EntityManager.DestroyEntity(m_query);
        }
Exemplo n.º 6
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            inputDeps.Complete();
            Entities.WithStructuralChanges().ForEach((Entity entity, ref GlobalEntityData globalEntityData) =>
            {
                var types        = EntityManager.GetComponentTypes(entity, Unity.Collections.Allocator.TempJob);
                var targetEntity = globalEntityData.globalScope == GlobalScope.World ? worldGlobalEntity : sceneGlobalEntity;

                ComponentType errorType = default;
                bool error = false;
                foreach (var type in types)
                {
                    if (globalEntityData.mergeMethod == MergeMethod.Overwrite || !targetEntity.HasComponent(type))
                    {
                        m_copyKit.CopyData(entity, targetEntity, type);
                    }
                    else if (globalEntityData.mergeMethod == MergeMethod.ErrorOnConflict)
                    {
                        errorType = type;
                        error     = true;
                    }
                }
                types.Dispose();
                if (error)
                {
                    throw new InvalidOperationException(
                        $"Entity {entity} could not copy component {errorType.GetManagedType()} onto {(globalEntityData.globalScope == GlobalScope.World ? "world" : "scene")} entity because the component already exists and the MergeMethod was set to ErrorOnConflict.");
                }
            }).Run();
            return(inputDeps);
        }
Exemplo n.º 7
0
    private bool AddComponentDataOnEntityAdded <T>(ref Entity entity, out NetworkComponent componentDataContainer) where T : struct, IComponentData
    {
        componentDataContainer = null;
        if (EntityManager.HasComponent <T>(entity))
        {
            ComponentType     componentType     = ComponentType.Create <T>();
            int               numberOfMembers   = reflectionUtility.GetFieldsCount(componentType.GetManagedType());
            Entity            networkDataEntity = networkFactory.CreateNetworkComponentData <T>(entity, numberOfMembers);
            NativeArray <int> values            = networkFactory.NetworkEntityManager.GetFixedArray <int>(networkDataEntity);
            PostUpdateCommands.AddComponent(entity, new NetworkComponentState <T>());

            T component = EntityManager.GetComponentData <T>(entity);
            NetworkField[]        networkMemberInfos   = reflectionUtility.GetFields(componentType);
            List <ComponentField> memberDataContainers = new List <ComponentField>();
            for (int i = 0; i < numberOfMembers; i++)
            {
                int value = (networkMemberInfos[i] as NetworkField <T>).GetValue(component);
                memberDataContainers.Add(new ComponentField()
                {
                    Id    = i,
                    Value = value
                });
                values[i] = value;
            }

            componentDataContainer = new NetworkComponent()
            {
                TypeId = reflectionUtility.GetId(componentType),
                Fields = memberDataContainers
            };
            return(true);
        }
        return(false);
    }
Exemplo n.º 8
0
    private bool GetComponentData <T>(ref Entity entity, out ComponentDataContainer componentDataContainer) where T : struct, IComponentData
    {
        componentDataContainer = null;
        if (EntityManager.HasComponent <T>(entity))
        {
            ComponentType componentType   = ComponentType.Create <T>();
            int           numberOfMembers = reflectionUtility.GetNumberOfMembers(componentType.GetManagedType());

            T component = EntityManager.GetComponentData <T>(entity);
            NetworkMemberInfo[]        networkMemberInfos   = reflectionUtility.GetNetworkMemberInfo(componentType);
            List <MemberDataContainer> memberDataContainers = new List <MemberDataContainer>();
            for (int i = 0; i < numberOfMembers; i++)
            {
                memberDataContainers.Add(new MemberDataContainer()
                {
                    MemberId = i,
                    Data     = (networkMemberInfos[i] as NetworkMemberInfo <T>).GetValue(component)
                });
            }


            componentDataContainer = new ComponentDataContainer()
            {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType),
                MemberData      = memberDataContainers
            };
            return(true);
        }
        return(false);
    }
Exemplo n.º 9
0
    private void AddedComponents <T>() where T : struct, IComponentData
    {
        ComponentType          componentType = ComponentType.Create <T>();
        ComponentGroup         group         = GetComponentGroup(ComponentType.Create <NetworkSyncState>(), componentType, ComponentType.Subtractive <NetworkComponentState <T> >(), ComponentType.Create <NetworktAuthority>());
        ComponentDataArray <T> components    = group.GetComponentDataArray <T>();
        ComponentDataArray <NetworkSyncState> networkSyncStateComponents = group.GetComponentDataArray <NetworkSyncState>();
        EntityArray entities = group.GetEntityArray();

        NetworkMemberInfo[] networkMemberInfos = reflectionUtility.GetNetworkMemberInfo(componentType);

        for (int i = 0; i < entities.Length; i++)
        {
            NetworkSyncState       networkSyncState = networkSyncStateComponents[i];
            ComponentDataContainer componentData    = new ComponentDataContainer {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType)
            };

            T component = components[i];
            for (int j = 0; j < networkMemberInfos.Length; j++)
            {
                componentData.MemberData.Add(new MemberDataContainer {
                    MemberId = j,
                    Data     = (networkMemberInfos[j] as NetworkMemberInfo <T>).GetValue(component),
                });
            }


            ownNetworkSendMessageUtility.AddComponent(entities[i], networkSyncState.actorId, networkSyncState.networkId, componentData);
            AllNetworkSendMessageUtility.AddComponent(entities[i], networkSyncState.actorId, networkSyncState.networkId, componentData);

            int numberOfMembers = reflectionUtility.GetNumberOfMembers(componentType.GetManagedType());
            networkFactory.CreateNetworkComponentData <T>(entities[i], numberOfMembers);
            PostUpdateCommands.AddComponent(entities[i], new NetworkComponentState <T>());
        }
    }
Exemplo n.º 10
0
        public static object GetComponentData(EntityManager entityManager, Entity entity, ComponentType componentType)
        {
            EntityDataAccess *    dataAccess           = entityManager.GetCheckedEntityDataAccess();
            EntityComponentStore *entityComponentStore = dataAccess->EntityComponentStore;
            byte *ptr = entityComponentStore->GetComponentDataWithTypeRO(entity, componentType.TypeIndex);

            return(Marshal.PtrToStructure((IntPtr)ptr, componentType.GetManagedType()));
        }
Exemplo n.º 11
0
            public static ComponentVisualElement Get(ComponentType componentType)
            {
                if (!cache.TryGetValue(componentType, out var element))
                {
                    throw new ArgumentException($"Unknown component type: '{componentType.GetManagedType().Name}'",
                                                nameof(componentType));
                }

                return(element);
            }
Exemplo n.º 12
0
        private static string Name(ComponentType type)
        {
            var str = $"{type.ToString()}";

            foreach (var @interface in type.GetManagedType().GetInterfaces())
            {
                str += $": {@interface.Name}";
            }
            return(str + " : " + type.TypeIndex);
        }
Exemplo n.º 13
0
        public void RegisterRpc(ComponentType type, PortableFunctionPointer <RpcExecutor.ExecuteDelegate> exec)
        {
            if (!m_CanRegister)
            {
                throw new InvalidOperationException("Cannot register new RPCs after the RpcSystem has started running");
            }

            if (!exec.Ptr.IsCreated)
            {
                throw new InvalidOperationException($"Cannot register RPC for type {type.GetManagedType()}: Ptr property is not created (null)" +
                                                    "Check CompileExecute() and verify you are initializing the PortableFunctionPointer with a valid static function delegate, decorated with [BurstCompile] attribute");
            }

            var hash = TypeManager.GetTypeInfo(type.TypeIndex).StableTypeHash;

            if (hash == 0)
            {
                throw new InvalidOperationException(String.Format("Unexpected 0 hash for type {0}", type.GetManagedType()));
            }
            if (m_RpcTypeHashToIndex.TryGetValue(hash, out var index))
            {
                var rpcData = m_RpcData[index];
                if (rpcData.TypeHash != 0)
                {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                    if (rpcData.RpcType == type)
                    {
                        throw new InvalidOperationException(
                                  String.Format("Registering RPC {0} multiple times is not allowed", type.GetManagedType()));
                    }
                    throw new InvalidOperationException(
                              String.Format("Type hash collision between types {0} and {1}", type.GetManagedType(), rpcData.RpcType.GetManagedType()));
#else
                    throw new InvalidOperationException(
                              String.Format("Hash collision or multiple registrations for {0}", type.GetManagedType()));
#endif
                }

                rpcData.TypeHash = hash;
                rpcData.Execute  = exec;
                m_RpcData[index] = rpcData;
            }
            else
            {
                m_RpcTypeHashToIndex.Add(hash, m_RpcData.Length);
                m_RpcData.Add(new RpcData
                {
                    TypeHash = hash,
                    Execute  = exec,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                    RpcType = type
#endif
                });
            }
        }
Exemplo n.º 14
0
 public void CopyData(Entity src, Entity dst, ComponentType componentType)
 {
     //Check to ensure dst has componentType
     if (!m_em.HasComponent(dst, componentType))
     {
         m_em.AddComponent(dst, componentType);
     }
     if (componentType.IsSharedComponent)
     {
         CopyScd(src, dst, componentType);
     }
     else if (componentType.IsBuffer)
     {
         CopyBuffer(src, dst, componentType);
     }
     else
     {
         bool handled = false;
         var  type    = componentType.GetManagedType();
         if (type.IsConstructedGenericType)
         {
             var genType = type.GetGenericTypeDefinition();
             if (genType == typeof(ManagedComponentTag <>))
             {
                 if (!m_typeTagsToTypesCache.TryGetValue(type, out Type managedType))
                 {
                     managedType = type.GenericTypeArguments[0];
                     m_typeTagsToTypesCache[type] = managedType;
                 }
                 LatiosWorld lw = m_em.World as LatiosWorld;
                 lw.ManagedStructStorage.CopyComponent(src, dst, managedType);
                 handled = true;
             }
             else if (genType == typeof(CollectionComponentTag <>))
             {
                 if (!m_typeTagsToTypesCache.TryGetValue(type, out Type managedType))
                 {
                     managedType = type.GenericTypeArguments[0];
                     m_typeTagsToTypesCache[type] = managedType;
                 }
                 LatiosWorld lw = m_em.World as LatiosWorld;
                 lw.CollectionComponentStorage.CopyComponent(src, dst, managedType);
                 handled = true;
             }
             else if (genType == typeof(ManagedComponentSystemStateTag <>) || genType == typeof(CollectionComponentSystemStateTag <>))
             {
                 handled = true;
             }
         }
         if (!handled)
         {
             CopyIcd(src, dst, componentType);
         }
     }
 }
Exemplo n.º 15
0
        public unsafe DebugComponent(EntityManager entityManager, Entity entity, ComponentType componentType)
        {
            Type = componentType.GetManagedType();
            Data = null;

            if (Type.IsClass)
            {
                Data = entityManager.GetComponentObject <object>(entity, componentType);
            }
            else if (typeof(IComponentData).IsAssignableFrom(Type))
            {
                if (componentType.IsZeroSized)
                {
                    Data = Activator.CreateInstance(Type);
                }
                else
                {
                    var dataPtr = entityManager.GetComponentDataRawRO(entity, componentType.TypeIndex);
                    // this doesn't work for structs that contain BlobAssetReferences
                    Data = Marshal.PtrToStructure((IntPtr)dataPtr, Type);
                }
            }
            else if (typeof(ISharedComponentData).IsAssignableFrom(Type))
            {
                try
                {
                    Data = entityManager.GetSharedComponentData(entity, componentType.TypeIndex);
                }
                catch (Exception x) // currently triggered in dots runtime (see GetAllEntities_WithSharedTagEntity)
                {
                    Data = x;
                }
            }
            else if (typeof(IBufferElementData).IsAssignableFrom(Type))
            {
                var bufferPtr   = (byte *)entityManager.GetBufferRawRO(entity, componentType.TypeIndex);
                var length      = entityManager.GetBufferLength(entity, componentType.TypeIndex);
                var elementSize = Marshal.SizeOf(Type);

                var array = Array.CreateInstance(Type, length);
                Data = array;

                for (var i = 0; i < length; ++i)
                {
                    var elementPtr = bufferPtr + (elementSize * i);
                    array.SetValue(Marshal.PtrToStructure((IntPtr)elementPtr, Type), i);
                }
            }
            else
            {
                throw new InvalidOperationException("Unsupported ECS data type");
            }
        }
Exemplo n.º 16
0
        public SharedComponentDataDiffer(ComponentType componentType)
        {
            if (!CanWatch(componentType))
            {
                throw new ArgumentException($"{nameof(SharedComponentDataDiffer)} only supports {nameof(ISharedComponentData)} components.", nameof(componentType));
            }

            WatchedComponentType = componentType;
            m_TypeIndex          = componentType.TypeIndex;
            m_ManagedComponentIndexInCopyByChunk = new NativeHashMap <ulong, int>(100, Allocator.Persistent);
            m_ShadowChunks = new NativeHashMap <ulong, ShadowChunk>(100, Allocator.Persistent);
            m_DefaultComponentDataValue = Activator.CreateInstance(componentType.GetManagedType());
        }
Exemplo n.º 17
0
        private void CacheCommandType(ComponentType command, int priority)
        {
            var commandCode = command.GetManagedType().GetHashCode();

            if (cachedCommandsPrio.ContainsKey(commandCode))
            {
                return;
            }

            var query = EntityManager.CreateEntityQuery(command);

            queries.Add(query);
            cachedCommandsPrio.Add(commandCode, priority);
            cachedCommandsIndex.Add(commandCode, queries.Count - 1);
        }
Exemplo n.º 18
0
        public unsafe DebugComponent(EntityManager entityManager, Entity entity, ComponentType componentType)
        {
            Type = componentType.GetManagedType();
            Data = null;

            if (Type.IsClass)
            {
                Data = entityManager.GetComponentObject <object>(entity, componentType);
            }
            else if (typeof(IComponentData).IsAssignableFrom(Type))
            {
                if (componentType.IsZeroSized)
                {
                    Data = Activator.CreateInstance(Type);
                }
                else
                {
                    var dataPtr = entityManager.GetComponentDataRawRO(entity, componentType.TypeIndex);
                    Data = Marshal.PtrToStructure((IntPtr)dataPtr, Type);
                }
            }
            else if (typeof(IBufferElementData).IsAssignableFrom(Type))
            {
                var bufferPtr   = (byte *)entityManager.GetBufferRawRO(entity, componentType.TypeIndex);
                var length      = entityManager.GetBufferLength(entity, componentType.TypeIndex);
                var elementSize = Marshal.SizeOf(Type);

                var array = Array.CreateInstance(Type, length);
                Data = array;

                for (var i = 0; i < length; ++i)
                {
                    var elementPtr = bufferPtr + (elementSize * i);
                    array.SetValue(Marshal.PtrToStructure((IntPtr)elementPtr, Type), i);
                }
            }
            else
            {
                throw new InvalidOperationException("Unsupported ECS data type");
            }
        }
        public static object GetComponentFromType(this EntityManager EntityManager, Entity entity, ComponentType type)
        {
            object componentData = new object();

            if (type.GetManagedType().GetInterface("IComponentData") != null)
            {
                if (!type.IsZeroSized)
                {
                    MethodInfo methodInfo        = typeof(EntityManager).GetMethod("GetComponentData");
                    MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(type.GetManagedType());
                    var        parameters        = new object[] { entity };
                    componentData = genericMethodInfo.Invoke(EntityManager, parameters);
                }
                //else if (type.IsZeroSized) //Zero sized components should not be passed
                //    return null;
            }
            else if (type.GetManagedType().GetInterface("ISharedComponentData", true) != null)
            {
                MethodInfo methodInfo =
                    typeof(EntityManager).GetMethod("GetSharedComponentData", new[] { typeof(Entity) });
                MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(type.GetManagedType());
                var        parameters        = new object[] { entity };
                componentData = genericMethodInfo.Invoke(EntityManager, parameters);
            }
            else if (type.GetManagedType() == typeof(Mesh) || type.GetManagedType() == typeof(Material))
            {
                MethodInfo methodInfo =
                    typeof(EntityManagerExtensions).GetMethod("GetComponentObject",
                                                              new[] { typeof(EntityManager), typeof(Entity) });
                MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(type.GetManagedType());
                var        parameters        = new object[] { EntityManager, entity };
                var        data = genericMethodInfo.Invoke(EntityManager, parameters);
                if (data != null)
                {
                    componentData = data;
                }
            }
            return(componentData);
        }
 public static bool SetComponentWithType(this EntityManager entityManager, Entity entity, ComponentType type, object obj)
 {
     if (type.IsZeroSized)
     {
         Debug.Assert(type.IsZeroSized, "Zero-sized Components can not be set only added or removed");
     }
     else if (type.GetManagedType().GetInterface("IComponentData") != null)
     {
         MethodInfo methodInfo        = typeof(EntityManager).GetMethod("SetComponentData");
         MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(type.GetManagedType());
         var        parameters        = new object[] { entity, obj };
         if (genericMethodInfo.Invoke(entityManager, parameters) != null)
         {
             return(true);
         }
     }
     else if (type.GetManagedType().GetInterface("ISharedComponentData", true) != null)
     {
         MethodInfo methodInfo =
             typeof(EntityManager).GetMethod("SetSharedComponentData", new[] { typeof(Entity) });
         MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(type.GetManagedType());
         var        parameters        = new object[] { entity, obj };
         if (genericMethodInfo.Invoke(entityManager, parameters) != null)
         {
             return(true);
         }
     }
     else if (!type.GetManagedType().IsValueType)
     {
         MethodInfo methodInfo        = typeof(EntityManager).GetMethod("GetComponentObject");
         MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(type.GetManagedType());
         var        parameters        = new object[] { entity };
         var        component         = genericMethodInfo.Invoke(entityManager, parameters);
         if (component != null)
         {
             component = obj;
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 21
0
        internal static int CompareTypes(ComponentType x, ComponentType y)
        {
            var accessModeOrder = SortOrderFromAccessMode(x.AccessModeType).CompareTo(SortOrderFromAccessMode(y.AccessModeType));

            return(accessModeOrder != 0 ? accessModeOrder : String.Compare(x.GetManagedType().Name, y.GetManagedType().Name, StringComparison.InvariantCulture));
        }
        public static void AddDependency(AssetImportContext ctx, ComponentType type)
        {
            var typeString = TypeString(type.GetManagedType());

            ctx.DependsOnCustomDependency(typeString);
        }
        public static bool CanWatch(ComponentType componentType)
        {
            var typeInfo = TypeManager.GetTypeInfo(componentType.TypeIndex);

            return(typeInfo.Category == TypeManager.TypeCategory.ComponentData && UnsafeUtility.IsUnmanaged(componentType.GetManagedType()));
        }
Exemplo n.º 24
0
        protected override IEnumerator ExecuteRoutine()
        {
            Log.Info("Start Sim Serialization Process...");

            Dictionary <uint, byte[]>        blobAssetsMap = new Dictionary <uint, byte[]>();
            Dictionary <ComponentType, Type> compToManaged = new Dictionary <ComponentType, Type>();
            Dictionary <ComponentType, DynamicComponentTypeHandle> compToHandle = new Dictionary <ComponentType, DynamicComponentTypeHandle>();
            NativeArray <ArchetypeChunk> chunks = _simulationWorld.EntityManager.GetAllChunks(Allocator.TempJob);

            foreach (var item in BlobAssetDataCollectors.Values)
            {
                item.BeginCollect(_simulationWorld);
            }

            // iterate over all chunks
            for (int i = 0; i < chunks.Length; i++)
            {
                ArchetypeChunk chunk = chunks[i];

                // iterate over all components in chunk
                foreach (ComponentType c in chunk.Archetype.GetComponentTypes())
                {
                    ComponentType componentType = c;
                    componentType.AccessModeType = ComponentType.AccessMode.ReadOnly;

                    // get managed type
                    if (!compToManaged.TryGetValue(componentType, out Type managedType))
                    {
                        managedType = componentType.GetManagedType();
                        compToManaged[componentType] = managedType;
                    }

                    // if collector exists for given component, invoke it
                    if (BlobAssetDataCollectors.TryGetValue(managedType, out IPtrObjectCollector collector))
                    {
                        // get componentTypeHandle (necessary for chunk data access)
                        if (!compToHandle.TryGetValue(componentType, out DynamicComponentTypeHandle typeHandle))
                        {
                            typeHandle = _simulationWorld.EntityManager.GetDynamicComponentTypeHandle(componentType);
                            compToHandle[componentType] = typeHandle;
                        }

                        // invoke!
                        collector.Collect(typeHandle, chunk, blobAssetsMap);
                    }
                }
            }
            chunks.Dispose();

            foreach (var item in BlobAssetDataCollectors.Values)
            {
                item.EndCollect();
            }

            SerializedWorld serializedWorld = new SerializedWorld();

            {
                serializedWorld.BlobAssets = new SerializedWorld.BlobAsset[blobAssetsMap.Count];
                int i = 0;
                foreach (var item in blobAssetsMap)
                {
                    serializedWorld.BlobAssets[i] = new SerializedWorld.BlobAsset()
                    {
                        Id   = item.Key,
                        Data = item.Value,
                    };
                    i++;
                }
            }

            serializedWorld.WorldData = SerializeUtilityX.SerializeWorld(_simulationWorld.EntityManager, out object[] referencedObjects);

            SerializationData = NetSerializer.Serialize(serializedWorld);

            foreach (var obj in referencedObjects)
            {
                Log.Warning($"The ECS simulation references {obj}, which is a managed object. " +
                            $"This is not allowed for now due to serialization");
            }

            Log.Info("Sim Serialization Complete!");
            TerminateWithSuccess();
            yield break;
        }
Exemplo n.º 25
0
 MethodInfo GetMethod(ComponentType componentType, Type type, string methodName) =>
 type
 .GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic)
 .MakeGenericMethod(componentType.GetManagedType());
Exemplo n.º 26
0
    private bool AddComponentDataOnEntityAdded <T>(ref Entity entity, out ComponentDataContainer componentDataContainer) where T : struct, IComponentData
    {
        componentDataContainer = null;
        ComponentDataFromEntity <NetworkSyncState> networkSyncStateEntities = EntityManager.GetComponentDataFromEntity <NetworkSyncState>();

        if (EntityManager.HasComponent <T>(entity))
        {
            ComponentType       componentType     = ComponentType.Create <T>();
            int                 numberOfMembers   = reflectionUtility.GetNumberOfMembers(componentType.GetManagedType());
            Entity              networkDataEntity = networkFactory.CreateNetworkComponentData <T>(entity, numberOfMembers);
            DynamicBuffer <int> values            = networkFactory.NetworkEntityManager.GetBuffer <NetworkValue>(networkDataEntity).Reinterpret <int>();
            PostUpdateCommands.AddComponent(entity, new NetworkComponentState <T>());

            T component = EntityManager.GetComponentData <T>(entity);
            NetworkMemberInfo[]        networkMemberInfos   = reflectionUtility.GetNetworkMemberInfo(componentType);
            List <MemberDataContainer> memberDataContainers = new List <MemberDataContainer>();
            for (int i = 0; i < numberOfMembers; i++)
            {
                int value = (networkMemberInfos[i] as NetworkMemberInfo <T>).GetValue(component, networkSyncStateEntities);
                memberDataContainers.Add(new MemberDataContainer()
                {
                    MemberId = i,
                    Data     = value
                });
                values[i] = value;
            }

            componentDataContainer = new ComponentDataContainer()
            {
                ComponentTypeId = reflectionUtility.GetComponentTypeID(componentType),
                MemberData      = memberDataContainers
            };
            return(true);
        }
        return(false);
    }