Ejemplo n.º 1
0
        public void AssignControl(Connection connection, IMessageRider token)
        {
            if (IsOwner)
            {
                if (HasControl)
                {
                    ReleaseControl(token);
                }

                EntityProxy proxy;

                CommandLastExecuted = null;
                CommandSequence     = 0;
                CommandQueue.Clear();

                Controller = connection;
                Controller.controlling.Add(this);
                Controller.entityChannel.CreateOnRemote(this, out proxy);
                Controller.entityChannel.ForceSync(this);

                // set token
                proxy.ControlTokenLost   = null;
                proxy.ControlTokenGained = token;

                Freeze(false);
            }
            else
            {
                NetLog.Error("You can not assign control of {0}, you are not the owner", this);
            }
        }
Ejemplo n.º 2
0
        public static byte[] ToByteArray(this IMessageRider token)
        {
            if (token == null)
            {
                return(null);
            }

            if ((tempBytes == null) || (tempBytes.Length != (Core.Config.packetSize - 256)))
            {
                tempBytes = new byte[Core.Config.packetSize - 256];
            }

            if (tempPacket == null)
            {
                tempPacket = new Packet();
            }

            // clear data
            Array.Clear(tempBytes, 0, tempBytes.Length);

            // setup packet
            tempPacket.Position   = 0;
            tempPacket.ByteBuffer = tempBytes;
            tempPacket.Size       = tempBytes.Length << 3;
            tempPacket.WriteByte(Factory.GetTokenId(token));

            // write token
            token.Write(tempPacket);

            return(tempPacket.DuplicateData());
        }
Ejemplo n.º 3
0
        void HandleToken(NetworkMsg type, IMessageRider token)
        {
            byte[] data = token.ToByteArray();

            switch (type)
            {
            case NetworkMsg.Connect:
                ConnectToken = data;
                break;

            case NetworkMsg.Accept:
                AcceptToken = data;
                break;

            case NetworkMsg.Disconnect:
                DisconnectToken = data;
                break;

            case NetworkMsg.Refuse:
                RefuseToken = data;
                break;

            default:
                break;
            }
        }
Ejemplo n.º 4
0
        public bool ReceiveToken(byte[] data, int dataSize, out IMessageRider riderToken, out NetworkMsg type)
        {
            byte tokType;
            int  size;

            riderToken = socketInterface.ReadToken(dataSize, data, out tokType, out size);

            //Null token received
            if (size == 0)
            {
                //NetLog.Info("<color=green> GOT A NULL TOKEN </color>");
            }

            type = (NetworkMsg)tokType;

            if (type != NetworkMsg.Unknown)
            {
                //Handle null tokens
                if (size == 0)
                {
                    return(true);
                }
                if (riderToken != null)
                {
                    SocketLog.Info("{0} token successfully received from host", type);
                    return(true);
                }
            }
            SocketLog.Error("Failed to unpack {0} token from host", type);
            return(false);
        }
Ejemplo n.º 5
0
        public void TakeControl(IMessageRider token)
        {
            if (IsOwner)
            {
                if (HasControl)
                {
                    NetLog.Warn("You already have control of {0}", this);
                }
                else
                {
                    // revoke any existing control
                    RevokeControl(token);

                    // take control locally
                    TakeControlInternal(token);


                    // de-freeze
                    Freeze(false);
                }
            }
            else
            {
                NetLog.Error("Only the owner of {0} can take control of it", this);
            }
        }
Ejemplo n.º 6
0
        public void ReleaseControlInternal(IMessageRider token)
        {
            NetAssert.True(Flags & EntityFlags.HAS_CONTROL);

            Flags &= ~EntityFlags.HAS_CONTROL;
            CommandQueue.Clear();
            CommandSequence     = 0;
            CommandLastExecuted = null;

            ControlLostToken   = token;
            ControlGainedToken = null;

            // call to serializer
            Serializer.OnControlLost();

            // call to user behaviours
            foreach (IEntityBehaviour eb in Behaviours)
            {
                if (ReferenceEquals(eb.entity, this.UnityObject))
                {
                    eb.ControlLost();
                }
            }

            // call user event
            GlobalEventListenerBase.ControlOfEntityLostInvoke(UnityObject);

            // de-freeze
            Freeze(false);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Remove a gameObject from the Ascension simulation.
        /// </summary>
        public static void Destroy(GameObject gameObject, IMessageRider token)
        {
            if (IsRunning)
            {
                AscensionEntity entity = gameObject.GetComponent <AscensionEntity>();

                if (entity)
                {
                    Core.Destroy(entity, token);
                }
                else
                {
                    if (token != null)
                    {
                        UnityEngine.Debug.LogWarning("Passing protocol token to destroy call for gameobject without ascension entity, token will be ignored");
                    }

                    UnityEngine.Object.Destroy(gameObject);
                }
            }
            else
            {
                if (token != null)
                {
                    UnityEngine.Debug.LogWarning("Passing protocol token to destroy call for gameobject when ascension is not running, token will be ignored");
                }

                UnityEngine.Object.Destroy(gameObject);
            }
        }
Ejemplo n.º 8
0
        public void RevokeControl(IMessageRider token)
        {
            if (IsOwner)
            {
                if (Controller)
                {
                    EntityProxy proxy;

                    // force a replication of this
                    Controller.controlling.Remove(this);
                    Controller.entityChannel.ForceSync(this, out proxy);
                    Controller = null;

                    // clear out everything
                    CommandLastExecuted = null;
                    CommandSequence     = 0;
                    CommandQueue.Clear();

                    // set token
                    if (proxy != null)
                    {
                        proxy.ControlTokenLost   = token;
                        proxy.ControlTokenGained = null;
                    }
                }

                Freeze(false);
            }
            else
            {
                NetLog.Error("You can not revoke control of {0}, you are not the owner", this);
                return;
            }
        }
Ejemplo n.º 9
0
        private void DestroyIncommingProxy(EntityProxy proxy, IMessageRider token)
        {
            // remove incomming proxy
            _incommingDict.Remove(proxy.NetworkId);

            // destroy entity
            proxy.Entity.DetachToken = token;

            // destroy entity
            Core.DestroyForce(proxy.Entity);
        }
Ejemplo n.º 10
0
        public static void WriteToken(this Packet packet, IMessageRider token)
        {
            if (packet.WriteBool(token != null))
            {
                // write header byte
                packet.WriteByte(Factory.GetTokenId(token));

                // write token
                token.Write(packet);
            }
        }
Ejemplo n.º 11
0
        public static byte GetTokenId(IMessageRider obj)
        {
#if DEBUG
            if (_token2id.ContainsKey(obj.GetType()) == false)
            {
                throw new AscensionException("Unknown token type {0}", obj.GetType());
            }
#endif

            return(_token2id[obj.GetType()]);
        }
Ejemplo n.º 12
0
 public static void SerializeToken(this Packet packet, ref IMessageRider token)
 {
     if (packet.Write)
     {
         packet.WriteToken(token);
     }
     else
     {
         token = packet.ReadToken();
     }
 }
Ejemplo n.º 13
0
        public static IMessageRider ReadToken(this Packet packet)
        {
            IMessageRider token = null;

            if (packet.ReadBool())
            {
                token = Factory.NewToken(packet.ReadByte());
                token.Read(packet);
            }

            return(token);
        }
Ejemplo n.º 14
0
 public bool RefuseConnection(SocketConnection conn, IMessageRider token)
 {
     if (AscensionNetwork.IsClient)
     {
         SocketLog.Error("Client cannot refuse!");
         return(false);
     }
     //COnstruct byte array of the token
     byte[] tokenBytes = WriteToken(token, NetworkMsg.Refuse);
     //Send Token
     conn.SendToken(tokenBytes, tokenBytes.Length, NetworkMsg.Refuse);
     //Disconnect
     server.DisconnectPeer(conn.ConnectionInfo.Peer);
     return(true);
 }
Ejemplo n.º 15
0
        public void SetToken(int dataSize, byte[] data)
        {
            //Initialization
            NetworkMsg msgType = NetworkMsg.Unknown;
            byte       type;
            int        size;
            //Read the packet and convert it to a byte array
            IMessageRider token = SockInterface.ReadToken(dataSize, data, out type, out size);

            //Convert the type into a enum readable type
            msgType = (NetworkMsg)type;
            //Handle the token
            HandleToken(msgType, token);
            SocketLog.Info("Set token type {0} for connection {1}", msgType, ConnectionInfo.Peer.ConnectId);
        }
Ejemplo n.º 16
0
 public void Disconnect(SocketConnection conn, IMessageRider token)
 {
     if (AscensionNetwork.IsClient && !connected)
     {
         SocketLog.Error("Cannot disconnect if we are not connected!");
         return;
     }
     //Construct byte array of the token
     byte[] tokenBytes = WriteToken(token, NetworkMsg.Disconnect);
     //Send Token
     conn.SendToken(tokenBytes, tokenBytes.Length, NetworkMsg.Disconnect);
     //Disconnect
     if (server != null)
     {
         server.DisconnectPeer(conn.ConnectionInfo.Peer);
     }
 }
Ejemplo n.º 17
0
        public bool Refuse(IPEndPoint endPoint, IMessageRider token)
        {
            bool refused = false;

            SocketConnection conn = GetPendingConnection(endPoint);

            if (conn != null)
            {
                refused = RefuseConnection(conn, token);
            }
            else
            {
                SocketLog.Error("Refuse failed! No connection with the endpoint: {0} found.", endPoint);
                return(false);
            }
            return(refused);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Load a scene based on name, only possible on the Server
        /// </summary>
        /// <param name="scene">The scene to load</param>
        /// <param name="token">A data token from the server</param>
        public static void LoadScene(string scene, IMessageRider token)
        {
            VerifyIsRunning();

            int sceneIndex = -1;

            try
            {
                sceneIndex = AscensionNetworkInternal.GetSceneIndex(scene);
            }
            catch (Exception exn)
            {
                NetLog.Error("Exception thrown while trying to find index of scene '{0}'", scene);
                NetLog.Exception(exn);
                return;
            }

            Core.LoadScene(sceneIndex, token);
        }
Ejemplo n.º 19
0
        public byte[] WriteToken(IMessageRider token, NetworkMsg type)
        {
            byte[] tokenArray = token.ToByteArray();
            //Handle null tokens
            int tokenSize = 0;

            if (tokenArray != null)
            {
                tokenSize = tokenArray.Length;
            }
            //The size is a byte in bits (8) + the size of the token to transmit
            Packet p = new Packet(8 + tokenSize);

            p.WriteByte((byte)type);
            p.WriteToken(token);
            p.FinishWriting(); // Not necessary as our defination of this packet was precise, but still good form

            return(p.ByteBuffer);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Create a new entity in the simuation from a prefab
        /// </summary>
        public static AscensionEntity Instantiate(GameObject prefab, IMessageRider token, Vector3 position, Quaternion rotation)
        {
            VerifyIsRunning();
            AscensionEntity ae = prefab.GetComponent <AscensionEntity>();

            if (!ae)
            {
                NetLog.Error("Prefab '{0}' does not have a Ascension Entity component attached", prefab.name);
                return(null);
            }

            if (ae.SerializerGuid == UniqueId.None)
            {
                NetLog.Error("Prefab '{0}' does not have a serializer assigned", prefab.name);
                return(null);
            }

            return(Core.Instantiate(new PrefabId(ae.prefabId), Factory.GetFactory(ae.SerializerGuid).TypeId, position, rotation, InstantiateFlags.ZERO, null, token));
        }
Ejemplo n.º 21
0
        public bool Accept(IPEndPoint endPoint, IMessageRider acceptToken, IMessageRider connectToken)
        {
            SocketConnection conn = GetPendingConnection(endPoint);

            if (conn != null)
            {
                //Remove from pending
                RemovePendingConnection(conn);
                //Add to current
                AddConnection(conn);
                //Send Tokens
                SendToken(conn.ConnectionInfo.Peer, acceptToken, NetworkMsg.Accept);
                SendToken(conn.ConnectionInfo.Peer, connectToken, NetworkMsg.Connect);
                SocketLog.Info("Accepted connection from {0}:{1}", endPoint.Address, endPoint.Port);
                return(true);
            }
            SocketLog.Error("Failed to accept connection {0}:{1}", endPoint.Address, endPoint.Port);
            return(false);
        }
Ejemplo n.º 22
0
        public bool Connect(SocketEndPoint endPoint, IMessageRider token)
        {
            //Checks before preceeding
            if (IsHost)
            {
                SocketLog.Error("Cannot connect when we are a host!");
                return(false);
            }
            if (connected)
            {
                SocketLog.Error("Cannot connect when we are already connected!");
                return(false);
            }
            if (connecting)
            {
                SocketLog.Error("Cannot connect when we are already connecting!");
                return(false);
            }

            client.Connect(endPoint.address, endPoint.port);

            //Set Address and Port
            address = endPoint.address;
            port    = endPoint.port;
            //Set the values of this connection
            SetConnectionValues(endPoint.address, endPoint.port);
            //Create a new instance of connection info
            SocketConnectionInfo info = new SocketConnectionInfo(address, port);
            //Initialize a new connection
            SocketConnection conn;

            //Add a connection
            AddConnection(info, out conn);
            //Cache our connect token to be sent once the communication lines have been established
            conn.ConnectToken = WriteToken(token, NetworkMsg.Connect);
            //Log our succeeded attempt
            SocketLog.Info("Connection Attempt to: {0} : {1}", endPoint.address, endPoint.port);
            //Set connecting
            connecting = true;

            return(true);
        }
Ejemplo n.º 23
0
        public void ReleaseControl(IMessageRider token)
        {
            if (IsOwner)
            {
                if (HasControl)
                {
                    ReleaseControlInternal(token);

                    // un-freeze
                    Freeze(false);
                }
                else
                {
                    NetLog.Warn("You are not controlling {0}", this);
                }
            }
            else
            {
                NetLog.Error("You can not release control of {0}, you are not the owner", this);
            }
        }
Ejemplo n.º 24
0
        void HandleReceivedToken(NetworkMsg type, IMessageRider riderToken)
        {
            switch (type)
            {
            case NetworkMsg.Accept:
                HandleAccepted(riderToken);
                break;

            case NetworkMsg.Connect:
                break;

            case NetworkMsg.Disconnect:
                break;

            case NetworkMsg.Ready:
                break;

            case NetworkMsg.Refuse:
                break;

            default:
                break;
            }
        }
Ejemplo n.º 25
0
        private void ReadResult(Packet packet)
        {
            while (packet.CanRead())
            {
                if (packet.ReadBool() == false)
                {
                    break;
                }

                NetworkId   netId  = packet.ReadNetworkId();
                EntityProxy proxy  = IncommingProxiesByNetworkId[netId];
                Entity      entity = proxy.Entity;

                while (packet.CanRead())
                {
                    if (packet.ReadBool() == false)
                    {
                        break;
                    }

                    TypeId        typeId      = packet.ReadTypeId();
                    ushort        sequence    = packet.ReadUShort(Command.SEQ_BITS);
                    IMessageRider resultToken = packet.ReadToken();

                    Command cmd = null;

                    if (entity != null)
                    {
                        var it = entity.CommandQueue.GetIterator();

                        while (it.Next())
                        {
                            int dist = NetMath.SeqDistance(it.val.Sequence, sequence, Command.SEQ_SHIFT);
                            if (dist > 0)
                            {
                                break;
                            }
                            if (dist < 0)
                            {
                                it.val.Flags |= CommandFlags.DISPOSE;
                            }
                            if (dist == 0)
                            {
                                cmd = it.val;
                                break;
                            }
                        }
                    }

                    if (cmd)
                    {
                        cmd.ResultObject.Token = resultToken;
                        cmd.Flags |= CommandFlags.CORRECTION_RECEIVED;

                        if (cmd.Meta.SmoothFrames > 0)
                        {
                            cmd.BeginSmoothing();
                        }

                        cmd.ReadResult(connection, packet);
                    }
                    else
                    {
                        cmd = Factory.NewCommand(typeId);
                        cmd.ReadResult(connection, packet);
                        cmd.Free();
                    }
                }
                // remove all disposable commands
                if (entity != null)
                {
                    while ((entity.CommandQueue.Count > 1) && (entity.CommandQueue.First.Flags & CommandFlags.DISPOSE))
                    {
                        entity.CommandQueue.RemoveFirst().Free();
                    }
                }
            }
        }
Ejemplo n.º 26
0
        private bool ReadUpdate(Packet packet)
        {
            if (packet.ReadBool() == false)
            {
                return(false);
            }
            // grab networkid
            NetworkId     networkId        = packet.ReadNetworkId();
            bool          isController     = packet.ReadBool();
            IMessageRider controlToken     = packet.ReadToken();
            bool          destroyRequested = packet.ReadBool();

            // we're destroying this proxy
            if (destroyRequested)
            {
                EntityProxy   proxy;
                IMessageRider detachToken = packet.ReadToken();

                if (_incommingDict.TryGetValue(networkId, out proxy))
                {
                    if (proxy.Entity.HasControl)
                    {
                        proxy.Entity.ReleaseControlInternal(controlToken);
                    }

                    DestroyIncommingProxy(proxy, detachToken);
                }
                else
                {
                    NetLog.Warn("Received destroy of {0} but no such proxy was found", networkId);
                }
            }
            else
            {
                IMessageRider attachToken = null;

                bool isSceneObject   = false;
                bool createRequested = packet.ReadBool();

                UniqueId   sceneId       = UniqueId.None;
                PrefabId   prefabId      = new PrefabId();
                TypeId     serializerId  = new TypeId();
                Vector3    spawnPosition = new Vector3();
                Quaternion spawnRotation = new Quaternion();

                if (createRequested)
                {
                    attachToken = packet.ReadToken();

                    prefabId      = packet.ReadPrefabId();
                    serializerId  = packet.ReadTypeId();
                    spawnPosition = packet.ReadVector3();
                    spawnRotation = packet.ReadQuaternion();
                    isSceneObject = packet.ReadBool();

                    if (isSceneObject)
                    {
                        sceneId = packet.ReadUniqueId();
                    }
                }

                Entity      entity = null;
                EntityProxy proxy  = null;

                if (createRequested && (_incommingDict.ContainsKey(networkId) == false))
                {
                    // create entity
                    if (isSceneObject)
                    {
                        GameObject go = Core.FindSceneObject(sceneId);

                        if (!go)
                        {
                            NetLog.Warn("Could not find scene object with {0}", sceneId);
                            go = Core.PrefabPool.Instantiate(prefabId, spawnPosition, spawnRotation);
                        }

                        entity = Entity.CreateFor(go, prefabId, serializerId, EntityFlags.SCENE_OBJECT);
                    }
                    else
                    {
                        GameObject go = Core.PrefabPool.LoadPrefab(prefabId);

                        // prefab checks (if applicable)
                        if (go)
                        {
                            if (Core.IsServer && !go.GetComponent <AscensionEntity>().allowInstantiateOnClient)
                            {
                                throw new AscensionException(
                                          "Received entity of prefab {0} from client at {1}, but this entity is not allowed to be instantiated from clients",
                                          go.name, connection.RemoteEndPoint);
                            }
                        }

                        NetLog.Warn("Creating instance of {0}", prefabId);
                        entity = Entity.CreateFor(prefabId, serializerId, spawnPosition, spawnRotation);
                    }

                    entity.Source    = connection;
                    entity.SceneId   = sceneId;
                    entity.NetworkId = networkId;

                    // handle case where we are given control (it needs to be true during the initialize, read and attached callbacks)
                    if (isController)
                    {
                        entity.Flags |= EntityFlags.HAS_CONTROL;
                    }

                    // initialize entity
                    entity.Initialize();

                    // create proxy
                    proxy            = entity.CreateProxy();
                    proxy.NetworkId  = networkId;
                    proxy.Connection = connection;

                    // register proxy
                    _incommingDict.Add(proxy.NetworkId, proxy);

                    // read packet
                    entity.Serializer.Read(connection, packet, packet.Frame);

                    // attach entity
                    proxy.Entity.AttachToken = attachToken;
                    proxy.Entity.Attach();

                    // assign control properly
                    if (isController)
                    {
                        proxy.Entity.Flags &= ~EntityFlags.HAS_CONTROL;
                        proxy.Entity.TakeControlInternal(controlToken);
                    }

                    // log debug info
                    NetLog.Debug("Received {0} from {1}", entity, connection);

                    // update last received frame
                    proxy.Entity.LastFrameReceived = AscensionNetwork.Frame;
                    proxy.Entity.Freeze(false);

                    // notify user
                    GlobalEventListenerBase.EntityReceivedInvoke(proxy.Entity.UnityObject);
                }
                else
                {
                    // find proxy
                    proxy = _incommingDict[networkId];

                    if (proxy == null)
                    {
                        throw new AscensionException("Couldn't find entity for {0}", networkId);
                    }

                    // update control state yes/no
                    if (proxy.Entity.HasControl ^ isController)
                    {
                        if (isController)
                        {
                            proxy.Entity.TakeControlInternal(controlToken);
                        }
                        else
                        {
                            proxy.Entity.ReleaseControlInternal(controlToken);
                        }
                    }

                    // read update
                    proxy.Entity.Serializer.Read(connection, packet, packet.Frame);
                    proxy.Entity.LastFrameReceived = AscensionNetwork.Frame;
                    proxy.Entity.Freeze(false);
                }
            }

            return(true);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Signal Ascension to refuse an incoming connection request
 /// </summary>
 /// <param name="endpoint">The UDP address of incoming client connection</param>
 /// <param name="acceptToken">A data token from the server</param>
 public static void Refuse(IPEndPoint endpoint, IMessageRider token)
 {
     VerifyIsRunning();
     Core.RefuseConnection(endpoint, token);
 }
Ejemplo n.º 28
0
 public static void Connect(string ip, int port, IMessageRider token)
 {
     VerifyIsRunning();
     Core.Connect(ip, port, token);
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Connect to a server
 /// </summary>
 /// <param name="endpoint">Server end point to connect to</param>
 public static void Connect(IPEndPoint endpoint, IMessageRider token)
 {
     VerifyIsRunning();
     Core.Connect(endpoint, token);
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Disconnect this connection with custom data
 /// </summary>
 /// <param name="token">A data token</param>
 public void Disconnect(IMessageRider token)
 {
     SockConn.Disconnect(token);
 }