Exemplo n.º 1
0
        // CSComponents can be instantiated from a serialized scene or from within managed code
        protected CSComponent()
        {
            if (nativeLoadOverrideValidate != IntPtr.Zero)
            {
                // When loading CSComponents from a scene, many issues circumvented by not allowing additional components
                // to be created (on the Node) during serialization, so this is an error state
                throw new InvalidOperationException($"CSComponent() - Recursive CSComponent instantiation in default constructor during load type: { GetType().Name} ");
            }

            // detect instantiation type
            InstantiationType itype = InstantiationType.INSTANTIATION_NATIVE;

            IntPtr ninstance = IntPtr.Zero;

            if (nativeLoadOverride == IntPtr.Zero)
            {
                // We are being "new'd" in managed code
                ninstance = csi_Atomic_CSComponent_Constructor();
                itype     = InstantiationType.INSTANTIATION_NET;
            }
            else
            {
                // We are loading from a serialized CSComponent
                ninstance = nativeInstance = nativeLoadOverride;

                // validation bookkeeping
                nativeLoadOverrideValidate = nativeLoadOverride;
                nativeLoadOverride         = IntPtr.Zero;
            }

            NativeCore.RegisterNative(ninstance, this, itype);
        }
Exemplo n.º 2
0
        // register a newly created native
        public static IntPtr RegisterNative(IntPtr native, RefCounted r, InstantiationType instantiationType = InstantiationType.INSTANTIATION_NET)
        {
            if (native == IntPtr.Zero || r == null)
            {
                throw new InvalidOperationException("NativeCore.RegisterNative - native == IntPtr.Zero || RefCounted instance == null");
            }

            if (instantiationType == InstantiationType.INSTANTIATION_NET)
            {
                if (r.nativeInstance != IntPtr.Zero)
                {
                    throw new InvalidOperationException("NativeCore.RegisterNative - NET Instantiated RefCounted with initialized nativeInstance");
                }

                r.nativeInstance = native;
            }

            r.InstantiationType = instantiationType;
            r.InternalInit();

            refCountedCache.Add(r);

            r.PostNativeUpdate();

            return(native);
        }
Exemplo n.º 3
0
 public static TypeMapping Create <TFrom, TTo>(string key, InstantiationType instantiate)
     where TTo : TFrom
 {
     return(new TypeMapping(typeof(TFrom), typeof(TTo), key)
     {
         InstantiationType = instantiate
     });
 }
        public virtual void RegisterTypeMapping <TFrom, TTo>(string key, InstantiationType instantiationType)
            where TTo : TFrom
        {
            var typeMappings   = GetConfigData();
            var newTypeMapping = TypeMapping.Create <TFrom, TTo>(key, instantiationType);

            RemovePreviousMappingsForFromType(typeMappings, newTypeMapping);
            typeMappings.Add(newTypeMapping);
            SetTypeMappingsList(typeMappings);
        }
        /// <summary>
        /// Bind an object to the object's type with specific initialization type and with supplied id as Key. This operation will ignore
        /// the [Singleton] or [Prototype] attributes that are declared in class attribute.
        /// </summary>
        /// <param name="type">Type of object to bind to.</param>
        /// <param name="obj">Target object.</param>
        /// <param name="instType">The initialization type.</param>
        /// <param name="id">Custom id of the object.</param>
        public void Bind <T>(T obj, InstantiationType instType, string id)
        {
            Type type = typeof(T);
            Dictionary <string, IoCObject> objectMap;

            if (!_objMap.TryGetValue(type, out objectMap))
            {
                objectMap = new Dictionary <string, IoCObject>();
            }

            objectMap[id] = new IoCObject(instType, obj);
            _objMap[type] = objectMap;
        }
Exemplo n.º 6
0
        public static Binding CreateForGeneric(IDIContext context, IList <Type> types, Type genericType,
                                               InstantiationType instantiationType, bool isDefault = true, string name = DEFAULT_BINDING)
        {
            var result = new Binding();

            result.context              = context;
            result.types                = types;
            result.instance             = genericType;
            result.instantiationType    = InstantiationType.None;
            result.genericInstantiation = instantiationType;
            result.factory              = null;
            result.instantiationFactory = null;
            result.name        = name;
            result.makeDefault = isDefault;
            return(result);
        }
Exemplo n.º 7
0
        protected IBinding Bind(InstantiationType inst, IList <Type> types, Func <object> create, string name = null, bool makeDefault = false)
        {
            Func <object> factory = null;

            if (customFactoryWrapper != null)
            {
                factory = () => customFactoryWrapper(types, create);
            }
            else
            {
                factory = create;
            }

            IBinding binding = CreateBinding(inst, types, factory, name, makeDefault);

            this.context.Register(binding);
            return(binding);
        }
Exemplo n.º 8
0
        private static void InstantiatePersistent(InstantiationType type, EntityManager mgr, Entity prefabEntity, ref int existingAmount, int extraAmount)
        {
            switch (type)
            {
            case InstantiationType.Manager:
                if (extraAmount == 1)
                {
                    mgr.InstantiatePersistent(prefabEntity, ref existingAmount);
                }
                else
                {
                    mgr.InstantiatePersistent(prefabEntity, ref existingAmount, extraAmount);
                }
                break;

            case InstantiationType.Command:
                EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp, PlaybackPolicy.SinglePlayback);
                ecb.InstantiatePersistent(prefabEntity, ref existingAmount, extraAmount);
                ecb.Playback(mgr);
                ecb.Dispose();
                break;

            case InstantiationType.ParallelCommand:
                EntityCommandBuffer ecbParallel = new EntityCommandBuffer(Allocator.TempJob, PlaybackPolicy.SinglePlayback);
                var job = new ParallelInstantiateJob()
                {
                    Ecb            = ecbParallel.AsParallelWriter(),
                    ExistingAmount = existingAmount,
                    ExtraAmount    = extraAmount,
                    PrefabEntity   = prefabEntity
                };
                existingAmount += extraAmount;
                job.Schedule().Complete();
                ecbParallel.Playback(mgr);
                ecbParallel.Dispose();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }
Exemplo n.º 9
0
        protected IBinding CreateBinding(InstantiationType inst, IList <Type> types, Func <object> create, string name, bool makeDefault)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = BindHelper.GetDefaultBindingName(context);
            }

            if (inst == InstantiationType.Abstract)
            {
                return(Binding.CreateForAbstract(this.context, types, create, makeDefault, name));
            }
            else if (inst == InstantiationType.Concrete)
            {
                return(Binding.CreateForConcrete(this.context, types, create, makeDefault, name));
            }
            else if (inst == InstantiationType.Instance)
            {
                return(Binding.CreateForInstance(this.context, types, create(), makeDefault, name));
            }
            else
            {
                throw new MindiException("Unhandled instantiation type: " + inst);
            }
        }
Exemplo n.º 10
0
        public void TestDynamicPoolApplyAndPersist([Values(InstantiationType.Manager, InstantiationType.Command, InstantiationType.ParallelCommand)] InstantiationType instantiationType,
                                                   [Values(1, 2, 3, 444, 5555)] int total, [Values(false, true)] bool groupedJobs)
        {
            // Prepare
            PersistencySettings settings = CreateTestSettings();

            settings.ForceUseGroupedJobsInEditor   = groupedJobs;
            settings.ForceUseNonGroupedJobsInBuild = !groupedJobs;
            Assert.True(groupedJobs == settings.UseGroupedJobs());
            PersistentSceneSystem       persistentSceneSystem       = World.GetOrCreateSystem <PersistentSceneSystem>();
            BeginFramePersistencySystem beginFramePersistencySystem = World.GetExistingSystem <BeginFramePersistencySystem>();

            beginFramePersistencySystem.ReplaceSettings(settings);
            EndFramePersistencySystem endFramePersistencySystem = World.GetOrCreateSystem <EndFramePersistencySystem>();

            endFramePersistencySystem.ReplaceSettings(settings);
            EndInitializationEntityCommandBufferSystem ecbSystem = World.GetOrCreateSystem <EndInitializationEntityCommandBufferSystem>();
            PersistentDataStorage dataStorage = persistentSceneSystem.PersistentDataStorage;
            Hash128 identifier = Hash128.Compute("DynamicPoolTests");

            NativeArray <PersistableTypeHandle> typeHandles = new NativeArray <PersistableTypeHandle>(Archetype.Length, Allocator.Persistent);

            for (int i = 0; i < typeHandles.Length; i++)
            {
                typeHandles[i] = settings.GetPersistableTypeHandleFromFullTypeName(Archetype[i].GetManagedType().FullName); // This is not advised in a game
            }

            // Action
            Entity prefabEntity = m_Manager.CreateEntity(Archetype);

            m_Manager.AddComponent <Prefab>(prefabEntity);
            persistentSceneSystem.InitializePool(prefabEntity, total, identifier, typeHandles);
            int amountSpawned = 0;

            InstantiatePersistent(instantiationType, m_Manager, prefabEntity, ref amountSpawned, total);
            persistentSceneSystem.InstantChangePoolCapacity(identifier, total * 2); // double amount
            InstantiatePersistent(instantiationType, m_Manager, prefabEntity, ref amountSpawned, total);

            m_Manager.RemoveComponent <EmptyEcsTestData>(m_Manager.CreateEntityQuery(typeof(PersistenceState)));
            Entities.ForEach((Entity e, ref EcsTestData testData, DynamicBuffer <DynamicBufferData1> buffer) =>
            {
                testData.Value = 1;
                buffer.Add(new DynamicBufferData1()
                {
                    Value = 1
                });
            });

            dataStorage.ToIndex(0);
            endFramePersistencySystem.RequestPersist(dataStorage.GetWriteContainerForCurrentIndex(identifier));
            endFramePersistencySystem.Update();
            m_Manager.CompleteAllJobs();
            beginFramePersistencySystem.RequestApply(dataStorage.GetInitialStateReadContainer(identifier));
            beginFramePersistencySystem.Update();
            ecbSystem.Update();

            // Test
            int amountSurvivingEntities = m_Manager.CreateEntityQuery(typeof(EcsTestData)).CalculateEntityCount();

            Assert.True(amountSurvivingEntities == total * 2, $"{instantiationType} didn't create the expected amount of entities({amountSurvivingEntities}vs{total*2})! (Or they were destroyed by Apply)");
            Entities.ForEach((Entity e, ref EcsTestData testData, DynamicBuffer <DynamicBufferData1> buffer) =>
            {
                Assert.True(testData.Value == 0, "The apply didn't restore the component value!");
                Assert.True(buffer.IsEmpty, "The apply didn't restore the buffer!");
                Assert.True(m_Manager.HasComponent <EmptyEcsTestData>(e), "The apply didn't restore the component!");
            });

            // Action
            dataStorage.ToIndex(0);
            beginFramePersistencySystem.RequestApply(dataStorage.GetWriteContainerForCurrentIndex(identifier));
            beginFramePersistencySystem.Update();
            ecbSystem.Update();

            // Test
            amountSurvivingEntities = m_Manager.CreateEntityQuery(typeof(EcsTestData)).CalculateEntityCount();
            Assert.True(amountSurvivingEntities == total * 2, $"Some entities were unexpectedly destroyed!");
            Entities.ForEach((Entity e, ref EcsTestData testData, DynamicBuffer <DynamicBufferData1> buffer) =>
            {
                Assert.True(testData.Value == 1, "The second apply didn't restore the component value!");
                Assert.True(buffer[0].Value == 1, "The second apply didn't restore the buffer!");
                Assert.False(m_Manager.HasComponent <EmptyEcsTestData>(e), "The second apply didn't restore the component!");
            });

            // Cleanup
            m_Manager.DestroyEntity(m_Manager.UniversalQuery);
        }
 public void IncrementCtor(InstantiationType type) => _access.WriteUsing("ctor", type);
Exemplo n.º 12
0
 /// <summary>
 /// Bind an object to its type and the supplied id.
 /// Object must have the supplied type.
 /// This object will ingore the [Singleton] or [Prototype] attribute.
 /// </summary>
 /// <param name="obj">Target object.</param>
 /// <param name="instType">Singleton or Prototype.</param>
 /// <param name="id">Custom id of the object.</param>
 public void Bind <T>(T obj, InstantiationType instType, string id)
 {
     _container.Bind <T>(obj, instType, id);
 }
Exemplo n.º 13
0
 public static TypeMapping Create <TFrom, TTo>(InstantiationType instantiate)
     where TTo : TFrom
 {
     return(Create <TFrom, TTo>(null, instantiate));
 }
 /// <summary>
 /// Register a type mapping between fromType and toType with specified key. When <see cref="IServiceLocator.GetInstance(System.Type)"/> with
 /// parameter TFrom is called, an instance of type TTO is returned.
 /// </summary>
 /// <param name="fromType">The type to register type mappings for. </param>
 /// <param name="toType">The type to create if <see cref="IServiceLocator.GetInstance(System.Type)"/> is called with fromType. </param>
 /// <param name="key">The key that's used to store the type mapping.</param>
 /// <param name="instantiationType">Determines how the type should be created. </param>
 /// <returns>The service locator to make it easier to add multiple type mappings</returns>
 public ActivatingServiceLocator RegisterTypeMapping(Type fromType, Type toType, string key, InstantiationType instantiationType)
 {
     Validation.ArgumentNotNull(fromType, "fromType");
     Validation.ArgumentNotNull(toType, "toType");
     return(RegisterTypeMapping(new TypeMapping(fromType, toType, key)
     {
         InstantiationType = instantiationType
     }));
 }
 public ActivatingServiceLocator RegisterTypeMapping <TFrom, TTo>(InstantiationType instantiationType)
     where TTo : TFrom, new()
 {
     return(RegisterTypeMapping(typeof(TFrom), typeof(TTo), null, instantiationType));
 }
        /// <summary>
        /// Bind an object to the object's type with supplied id as key. Object must have [Singleton] or [Prototype] declared as class attribute.
        /// </summary>
        /// <param name="type">Type of object to bind to.</param>
        /// <param name="obj">Target object.</param>
        /// <param name="id">Custom id of the object.</param>
        public void Bind <T>(T obj, string id)
        {
            InstantiationType instType = GetInstantiationType(obj.GetType());

            Bind <T>(obj, instType, id);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Register a type mapping between fromType and toType with specified key. When <see cref="IServiceLocator.GetInstance(System.Type)"/> with
 /// parameter TFrom is called, an instance of type TTO is returned.
 /// </summary>
 /// <param name="fromType">The type to register type mappings for. </param>
 /// <param name="toType">The type to create if <see cref="IServiceLocator.GetInstance(System.Type)"/> is called with fromType. </param>
 /// <param name="key">The key that's used to store the type mapping.</param>
 /// <param name="instantiationType">Determines how the type should be created. </param>
 /// <returns>The service locator to make it easier to add multiple type mappings</returns>
 public ActivatingServiceLocator RegisterTypeMapping(Type fromType, Type toType, string key, InstantiationType instantiationType)
 {
     return(RegisterTypeMapping(new TypeMapping(fromType, toType, key)
     {
         InstantiationType = instantiationType
     }));
 }
Exemplo n.º 18
0
 public IoCObject(InstantiationType instType, object obj)
 {
     this._instantiationType = instType;
     this._obj = obj;
 }
 public ActivatingServiceLocator RegisterTypeMapping <TFrom, TTo>(string key, InstantiationType instantiationType)
     where TTo : TFrom, new()
 {
     return(this.RegisterTypeMapping(typeof(TFrom), typeof(TTo), key, instantiationType));
 }
Exemplo n.º 20
0
 /// <summary>
 /// Bind an object to its type and the default id.
 /// Object must have the supplied type.
 /// This object will ingore the [Singleton] or [Prototype] attribute.
 /// </summary>
 /// <param name="instType">Singleton or Prototype.</param>
 /// <param name="obj">Target obj.</param>
 public static void Bind <T>(T obj, InstantiationType instType)
 {
     _injector.Bind <T>(obj, instType);
 }
Exemplo n.º 21
0
 /// <summary>
 /// Bind an object to its type and the supplied id.
 /// Object must have the supplied type.
 /// This object will ingore the [Singleton] or [Prototype] attribute.
 /// </summary>
 /// <param name="obj">Target object.</param>
 /// <param name="instType">Singleton or Prototype.</param>
 /// <param name="id">Custom id of the object.</param>
 public static void Bind <T>(T obj, InstantiationType instType, string id)
 {
     _injector.Bind <T>(obj, instType, id);
 }
Exemplo n.º 22
0
 /// <summary>
 /// Bind an object to its type and the default id.
 /// Object must have the supplied type.
 /// This object will ingore the [Singleton] or [Prototype] attribute.
 /// </summary>
 /// <param name="instType">Singleton or Prototype.</param>
 /// <param name="obj">Target obj.</param>
 public void Bind <T>(T obj, InstantiationType instType)
 {
     _container.Bind <T>(obj, instType, DEFAULT);
 }