Example #1
0
 void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
Example #2
0
        public QuConnPool()
        {
            Func <IConnSource, QuConn> method = (connSource) => { return(new QuConn(connSource)); };

            connPool = new SmartPool <IConnSource, QuConn>(method, threadShareResource: true);
            connPool.PoolMaxCount = 1;
        }
Example #3
0
 void MakeInstance()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
Example #4
0
    public static void Despawn(GameObject item, float t)
    {
        if (item)
        {
            SmartPool P = GetPoolByItem(item);
            if (P != null)
            {
                bool bFind = false;
                P.mDealyDespawn.Find(objItem =>
                {
                    if (objItem._obj == item)
                    {
                        objItem._ft = Mathf.Min(objItem._ft, Time.time + t);
                        bFind       = true;
                        return(true);
                    }
                    return(false);
                });

                if (!bFind)
                {
                    delayDespawn delayItem = new delayDespawn();
                    delayItem._ft  = Time.time + t;
                    delayItem._obj = item;
                    P.mDealyDespawn.Add(delayItem);
                }
            }
            else
            {
                GameObject.Destroy(item, t);
            }
        }
    }
Example #5
0
    /// <summary>
    /// create a pool by it's name
    /// </summary>
    /// <param name="poolName">name of the pool</param>
    ///  <param name="prefab">name of the prefab</param>
    /// <returns>a pool or null</returns>
    public static SmartPool CreatePool(string poolName, GameObject prefab = null, string strParentName = "BattleParent")
    {
        SmartPool pool;

        _Pools.TryGetValue(poolName, out pool);
        if (pool == null)
        {
            GameObject parent = GameObject.Find(strParentName);
            if (parent == null)
            {
                parent      = new GameObject();
                parent.name = strParentName;
            }
            GameObject go = new GameObject();
            go.name             = poolName;
            go.transform.parent = parent.transform;
            pool = go.AddComponent <SmartPool>();
            if (pool != null)
            {
                pool.setPoolName(poolName);
            }
        }

        if (prefab)
        {
            SmartPool.setPrefabByPoolName(poolName, prefab);
        }


        return(pool);
    }
        public static GameObject PoolSpawnPrefab(string prefab, Vector3 point, Quaternion rotation, int maxSize)
        {
            GameObject prefabObj = null;

            if (AssetBundles.Instance != null)
            {
                prefabObj = AssetBundles.Instance.GetPrefab(prefab) as GameObject;
            }
#if UNITY_EDITOR
            if (prefabObj == null)
            {
                prefabObj = Resources.Load(prefab) as GameObject;
            }
#endif
            if (prefabObj != null)
            {
                SmartPool pool = SmartPool.GetPoolByName(prefab + "_pool");
                if (pool == null)
                {
                    pool             = SmartPool.CreatePool(prefab + "_pool", prefabObj);
                    pool.MaxPoolSize = maxSize;
                }
                return(pool.SpawnItem(point, rotation));
            }
            return(null);
        }
    void OnGUI()
    {
        if (GUILayout.Button("Spawn brick (click them to despawn)"))
        {
            var go = SmartPool.Spawn("Brick");
            if (go)
            {
                go.transform.localPosition = Random.insideUnitSphere * 10;
            }
        }
        if (GUILayout.Button("Despawn all bricks (and see them cull automatically)"))
        {
            SmartPool.DespawnAllItems("Brick");
        }


        if (GUILayout.Button("Spawn bullet (click them to despawn)"))
        {
            var go = SmartPool.Spawn("Bullet");
            if (go)
            {
                go.transform.localPosition = Random.insideUnitSphere * 10;
            }
        }
        if (GUILayout.Button("Despawn all bullets"))
        {
            SmartPool.DespawnAllItems("Bullet");
        }
        GUILayout.Label("Please add Example and Example2ndScene as levels to the build settings!");
        if (GUILayout.Button("Switch Scene"))
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene(1);
        }
    }
Example #8
0
    /// <summary>
    /// Despawn all items of a certain pool
    /// </summary>
    /// <param name="poolName">name of the pool</param>
    public static void DespawnAllItems(string poolName)
    {
        SmartPool P = GetPoolByName(poolName);

        if (P != null)
        {
            P.DespawnAllItems();
        }
    }
Example #9
0
    /// <summary>
    /// Shrink a stock to match MaxPoolSize
    /// </summary>
    /// <param name="smartCull">if true a maximum of AllocationBlockSize items are culled</param>
    public static void Cull(string poolName, bool smartCull)
    {
        SmartPool P = GetPoolByName(poolName);

        if (P)
        {
            P.Cull();
        }
    }
Example #10
0
    /// <summary>
    /// Clear all instances and repopulate a pool to match MinPoolSize
    /// </summary>
    public static void Prepare(string poolName)
    {
        SmartPool P = GetPoolByName(poolName);

        if (P != null)
        {
            P.Prepare();
        }
    }
Example #11
0
    /// <summary>
    /// Reset the prefab
    /// </summary>
    /// <param name="poolName">the pool's name</param>
    /// <param name="bIngore">if the prefab alerady exist ,don`t clear</param>
    /// <returns>a gameobject or null if spawning failed</returns>
    public static void setPrefabByPoolName(string poolName, GameObject prefab)
    {
        SmartPool p = SmartPool.GetPoolByName(poolName);

        if (p)
        {
            p.Clear();
            p.Prefab = prefab;
        }
    }
Example #12
0
 private void Init(IConnSource connSrc)
 {
     if (connSrc == null)
     {
         throw new NullReferenceException(nameof(Init));
     }
     conn        = connSrc.TakeCache <ConnectionFactory>().CreateConnection();
     ChannelPool = new SmartPool <string, IModel>(rckey => conn.CreateModel(), threadShareResource: false);
     ChannelPool.PoolMaxCount = 1;
 }
    public GameObject Instantiate(string prefabId, Vector3 position, Quaternion rotation)
    {
        Debug.LogWarning("Instantiate Prefab: " + prefabId);

        GameObject go = SmartPool.Spawn(prefabId);

        go.transform.position = position;
        go.transform.rotation = rotation;

        return(go);
    }
Example #14
0
        public virtual bool Start()
        {
            IsStopped = false;

            ILog log = AppServer.Logger;

            var config = AppServer.Config;

            var sendingQueuePool = new SmartPool <SendingQueue>();

            sendingQueuePool.Initialize(Math.Max(config.MaxConnectionNumber / 6, 256),
                                        Math.Max(config.MaxConnectionNumber * 2, 256),
                                        new SendingQueueSourceCreator(config.SendingQueueSize));

            SendingQueuePool = sendingQueuePool;

            for (var i = 0; i < ListenerInfos.Length; i++)
            {
                var listener = CreateListener(ListenerInfos[i]);
                listener.Error             += new ErrorHandler(OnListenerError);
                listener.Stopped           += new EventHandler(OnListenerStopped);
                listener.NewClientAccepted += new NewClientAcceptHandler(OnNewClientAccepted);

                if (listener.Start(AppServer.Config))
                {
                    Listeners.Add(listener);

                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Listener ({0}) was started", listener.EndPoint);
                    }
                }
                else //If one listener failed to start, stop started listeners
                {
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Listener ({0}) failed to start", listener.EndPoint);
                    }

                    for (var j = 0; j < Listeners.Count; j++)
                    {
                        Listeners[j].Stop();
                    }

                    Listeners.Clear();
                    return(false);
                }
            }

            IsRunning = true;
            return(true);
        }
Example #15
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        SmartPool pool = target as SmartPool;

        if (pool != null)
        {
            GUILayout.Label("In Stock: " + pool.InStock.ToString());
            GUILayout.Label("Spawned: " + pool.Spawned.ToString());
            Repaint();
        }
    }
Example #16
0
    /// <summary>
    /// Find the pool an item belongs to
    /// </summary>
    /// <param name="item">an item</param>
    /// <returns>the corresponding pool or null if the item is unmanaged</returns>
    public static SmartPool GetPoolByItem(GameObject item)
    {
        var       e = _Pools.GetEnumerator();
        SmartPool P = null;

        while (e.MoveNext())
        {
            P = e.Current.Value;
            if (P.IsManagedObject(item))
            {
                return(P);
            }
        }
        return(null);
    }
Example #17
0
 /// <summary>
 /// Kill a spawned item instead of despawning it
 /// </summary>
 /// <param name="item">the spawned item to kill</param>
 /// <remarks>If the item is unmanaged, it will be destroyed anyway</remarks>
 public static void Kill(GameObject item)
 {
     if (item)
     {
         SmartPool P = GetPoolByItem(item);
         if (P != null)
         {
             P.KillItem(item);
         }
         else
         {
             GameObject.Destroy(item);
         }
     }
 }
        /// <summary>
        /// 清算通知检查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void DoReckonCommitCheck(object sender, EventArgs args)
        {
            if (isDoReckonCommitChecking)
            {
                return;
            }

            try
            {
                SmartPool.QueueWorkItem(InternalDoReckonCommitCheck);
            }
            catch (Exception ex)
            {
                LogHelper.WriteError(ex.Message, ex);
                Thread t = new Thread(InternalDoReckonCommitCheck);
                t.Start();
                //InternalDoReckonCommitCheck();
            }
        }
Example #19
0
        public virtual bool Start()
        {
            IsStopped = false;

            ILog log = AppServer.Logger;

            var config = AppServer.Config;

            var sendingQueuePool = new SmartPool<SendingQueue>();
            sendingQueuePool.Initialize(Math.Max(config.MaxConnectionNumber / 6, 256),
                    Math.Max(config.MaxConnectionNumber * 2, 256),
                    new SendingQueueSourceCreator(config.SendingQueueSize));

            SendingQueuePool = sendingQueuePool;

            for (var i = 0; i < ListenerInfos.Length; i++)
            {
                var listener = CreateListener(ListenerInfos[i]);
                listener.Error += new ErrorHandler(OnListenerError);
                listener.Stopped += new EventHandler(OnListenerStopped);
                listener.NewClientAccepted += new NewClientAcceptHandler(OnNewClientAccepted);

                if (listener.Start(AppServer.Config))
                {
                    Listeners.Add(listener);

                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Listener ({0}) was started", listener.EndPoint);
                    }
                }
                else //If one listener failed to start, stop started listeners
                {
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Listener ({0}) failed to start", listener.EndPoint);
                    }

                    for (var j = 0; j < Listeners.Count; j++)
                    {
                        Listeners[j].Stop();
                    }

                    Listeners.Clear();
                    return false;
                }
            }

            IsRunning = true;
            return true;
        }
Example #20
0
 void OnDisable()
 {
     instance = null;
 }
Example #21
0
        public bool Start()
        {
            int bufferSize = 0;//AppServer.Config.ReceiveBufferSize;

            int maxConnection = Desc.MaxConnect;

            if (bufferSize <= 0)
            {
                bufferSize = 1024 * 4;
            }

            _bufferManager = new BufferManager(bufferSize * maxConnection, bufferSize);

            try
            {
                _bufferManager.InitBuffer();
            }
            catch (Exception e)
            {
                throw e;
                //AppServer.Logger.Error("Failed to allocate buffer for async socket communication, may because there is no enough memory, please decrease maxConnectionNumber in configuration!", e);
                //return false;
            }

            var sendingQueuePool = new SmartPool <SendingQueue>();

            sendingQueuePool.Initialize(Math.Max(maxConnection / 6, 256),
                                        Math.Max(maxConnection * 2, 256),
                                        new SendingQueueSourceCreator(5));

            SendingQueuePool = sendingQueuePool;

            // preallocate pool of SocketAsyncEventArgs objects
            SocketAsyncEventArgs socketEventArg;

            var socketArgsProxyList = new List <SocketAsyncEventArgsProxy>(maxConnection);

            for (int i = 0; i < maxConnection; i++)
            {
                //Pre-allocate a set of reusable SocketAsyncEventArgs
                socketEventArg = new SocketAsyncEventArgs();
                _bufferManager.SetBuffer(socketEventArg);

                socketArgsProxyList.Add(new SocketAsyncEventArgsProxy(socketEventArg));
            }

            _readWritePool = new ConcurrentStack <SocketAsyncEventArgsProxy>(socketArgsProxyList);



            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();

            //m_AcceptSAE = acceptEventArg;
            acceptEventArg.Completed += AcceptEventArg_Completed;
            _socket.Listen(100);

            if (!_socket.AcceptAsync(acceptEventArg))
            {
                ProcessAccept(acceptEventArg);
            }

            IsRunning = true;
            return(true);
        }
 public void Destroy(GameObject gameObject)
 {
     SmartPool.Despawn(gameObject);
 }
Example #23
0
 void OnMouseDown()
 {
     SmartPool.Despawn(gameObject);
 }
Example #24
0
        private void InitializePools()
        {
            var config = AppServer.Config;

            int bufferSize = config.ReceiveBufferSize;

            if (bufferSize <= 0)
                bufferSize = 1024 * 4;

            m_BufferManager = AppServer.BufferManager;

            var initialCount = Math.Min(Math.Max(config.MaxConnectionNumber / 15, 100), config.MaxConnectionNumber);
            m_SaePool = new IntelliPool<SocketAsyncEventArgs>(initialCount, new SaeCreator(m_BufferManager, bufferSize, this), (e) => e.UserToken = null);

            var sendingQueuePool = new SmartPool<SendingQueue>();
            sendingQueuePool.Initialize(Math.Max(config.MaxConnectionNumber / 6, 256),
                    Math.Max(config.MaxConnectionNumber * 2, 256),
                    new SendingQueueSourceCreator(config.SendingQueueSize));

            SendingQueuePool = sendingQueuePool;
        }