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);
            }
        }
        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;
            }
        }
        public bool QueueInput(Command cmd)
        {
            if (canQueueCommands)
            {
                NetAssert.True(HasControl);

                if (CommandQueue.Count < Core.Config.commandQueueSize)
                {
                    cmd.ServerFrame = Core.ServerFrame;
                    cmd.Sequence    = CommandSequence = NetMath.SeqNext(CommandSequence, Command.SEQ_MASK);
                }
                else
                {
                    NetLog.Error("Input queue for {0} is full", this);
                    return(false);
                }

                CommandQueue.AddLast(cmd);
                return(true);
            }
            else
            {
                NetLog.Error("You can only queue commands to the host in the 'SimulateController' callback");
                return(false);
            }
        }
        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);
            }
        }
Beispiel #5
0
        public void SetIdle(Connection connection, bool idle)
        {
            if (idle && IsController(connection))
            {
                NetLog.Error("You can not idle {0} on {1}, as it is the controller for this entity", this, connection);
                return;
            }

            connection.entityChannel.SetIdle(this, idle);
        }
Beispiel #6
0
        public override void SetDynamic(NetworkObj obj, object value)
        {
            if (MecanimDirection == MecanimDirection.UsingAnimatorMethods)
            {
                NetLog.Error("Can't call SetDynamic on a trigger in 'UsingAnimatorMethods' mode");
                return;
            }

            obj.Storage.Values[obj[this]].TriggerLocal.Update(Core.Frame, true);
        }
Beispiel #7
0
        bool VerifyCallbackPath(string path)
        {
            if (Meta.CallbackPaths.Contains(path))
            {
                return(true);
            }

            NetLog.Error("No callback path '{0}' available on {1}", path, this);
            return(false);
        }
        /// <summary>
        /// Get the state if this entity
        /// </summary>
        public TState GetState <TState>()
        {
            if (AEntity.Serializer is TState)
            {
                return((TState)(object)AEntity.Serializer);
            }

            NetLog.Error("You are trying to access the state of {0} as '{1}'", AEntity, typeof(TState));
            return(default(TState));
        }
Beispiel #9
0
        static object Create(UniqueId id)
        {
#if DEBUG
            if (_factoriesByKey.ContainsKey(id) == false)
            {
                NetLog.Error("Unknown {0}", id);
            }
#endif

            return(_factoriesByKey[id].Create());
        }
Beispiel #10
0
 public void SetParent(Entity entity)
 {
     if (IsOwner || HasPredictedControl)
     {
         SetParentInternal(entity);
     }
     else
     {
         NetLog.Error("You are not allowed to assign the parent of this entity, only the owner or a controller with local prediction can");
     }
 }
Beispiel #11
0
        public void InvokeRepeating(Command command, CommandCallback callback, int period)
        {
            NetAssert.True(period > 0);

            if (!canQueueCallbacks)
            {
                NetLog.Error("Can only queue callbacks when commands with 'IsFirstExecution' set to true are executing");
                return;
            }

            //CommandCallbacks.Add(new CommandCallbackItem { Command = command, Callback = callback, Start = command.Number + 1, End = command.Number + period, Mode = CommandCallbackModes.InvokeRepeating });
        }
Beispiel #12
0
        public void InvokeOnce(Command command, CommandCallback callback, int delay)
        {
            NetAssert.True(delay > 0);

            if (!canQueueCallbacks)
            {
                NetLog.Error("Can only queue callbacks when commands with 'IsFirstExecution' set to true are executing");
                return;
            }

            //CommandCallbacks.Add(new CommandCallbackItem { Command = command, Callback = callback, Start = -1, End = command.Number + delay, Mode = CommandCallbackModes.InvokeOnce });
        }
Beispiel #13
0
        public static IFactory GetFactory(UniqueId id)
        {
#if DEBUG
            if (!_factoriesByKey.ContainsKey(id))
            {
                NetLog.Error("Unknown factory {0}", id);
                return(null);
            }
#endif

            return(_factoriesByKey[id]);
        }
        public void SetScope(Entity entity, bool inScope)
        {
            if (Core.Config.scopeMode == ScopeMode.Automatic)
            {
                NetLog.Error("SetScope has no effect when Scope Mode is set to Automatic");
                return;
            }

            if (ReferenceEquals(entity.Source, connection))
            {
                return;
            }

            if (inScope)
            {
                if (_incommingDict.ContainsKey(entity.NetworkId))
                {
                    return;
                }

                EntityProxy proxy;

                if (_outgoingDict.TryGetValue(entity.NetworkId, out proxy))
                {
                    if (proxy.Flags & ProxyFlags.DESTROY_REQUESTED)
                    {
                        if (proxy.Flags & ProxyFlags.DESTROY_PENDING)
                        {
                            proxy.Flags |= ProxyFlags.DESTROY_IGNORE;
                        }
                        else
                        {
                            proxy.Flags &= ~ProxyFlags.DESTROY_IGNORE;
                            proxy.Flags &= ~ProxyFlags.DESTROY_REQUESTED;
                        }
                    }
                }
                else
                {
                    CreateOnRemote(entity);
                }
            }
            else
            {
                if (_outgoingDict.ContainsKey(entity.NetworkId))
                {
                    DestroyOnRemote(entity);
                }
            }
        }
Beispiel #15
0
 public override bool Write(Connection connection, NetworkObj obj, NetworkStorage storage, Packet packet)
 {
     try
     {
         packet.WriteToken(storage.Values[obj[this]].ProtocolToken);
         return(true);
     }
     catch (Exception exn)
     {
         NetLog.Error("User code threw exception while serializing protocol token");
         NetLog.Exception(exn);
         return(false);
     }
 }
Beispiel #16
0
 public void PacketDelivered(Packet packet)
 {
     try
     {
         for (int i = 0; i < channels.Length; ++i)
         {
             channels[i].Delivered(packet);
         }
     }
     catch (Exception exn)
     {
         NetLog.Exception(exn);
         NetLog.Error("exception thrown while handling delivered packet to {0}", sockConn.RemoteEndPoint);
     }
 }
Beispiel #17
0
 public void PacketLost(Packet packet)
 {
     for (int i = 0; i < channels.Length; ++i)
     {
         channels[i].Lost(packet);
     }
     try
     {
     }
     catch (Exception exn)
     {
         NetLog.Exception(exn);
         NetLog.Error("exception thrown while handling lost packet to {0}", sockConn.RemoteEndPoint);
     }
 }
Beispiel #18
0
        public override void SetDynamic(NetworkObj obj, object value)
        {
            if (MecanimDirection == MecanimDirection.UsingAnimatorMethods)
            {
                NetLog.Error("Can't call SetDynamic on a float in 'UsingAnimatorMethods' mode");
                return;
            }

            var v = (float)value;

            if (NetworkValue.Diff(obj.Storage.Values[obj[this]].Float0, v))
            {
                obj.Storage.Values[obj[this]].Float0 = v;
                obj.Storage.PropertyChanged(obj.OffsetProperties + this.OffsetProperties);
            }
        }
Beispiel #19
0
        public void PacketReceived(Packet Packet)
        {
            try
            {
                using (Packet packet = Core.AllocatePacket())
                {
                    packet.Set(Packet); //This copies the values into the newly acquired packet
                    //Read signature & frame
                    packet.Type  = packet.ReadByte();
                    packet.Frame = packet.ReadIntVB();

                    if (packet.Frame > remoteFrameActual)
                    {
                        remoteFrameAdjust = true;
                        remoteFrameActual = packet.Frame;
                    }

                    //OLD method
                    //bitsSecondInAcc += packet.ActualSize;
                    bitsSecondInAcc += packet.Position;
                    packetsReceived += 1;

                    for (int i = 0; i < channels.Length; ++i)
                    {
                        channels[i].Read(packet);
                    }
                    //for (int i = 0; i < channels.Length; ++i)
                    //{
                    //    channels[i].ReadDone();
                    //}

                    packetStatsIn.Enqueue(packet.Stats);

                    NetAssert.False(Packet.Overflowing);

                    //SocketLog.Info("Received packet of length {0}", packet.ActualSize);
                }
            }
            catch (Exception exn)
            {
                NetLog.Exception(exn);
                NetLog.Error("exception thrown while unpacking data from {0}, disconnecting", sockConn.RemoteEndPoint);
                Disconnect();
            }
        }
        void OnDestroy()
        {
            if (entity && entity.IsAttached && Application.isPlaying)
            {
                if (entity.IsOwner)
                {
                    NetLog.Warn("{0} is being destroyed/disabled without being detached, forcing detach", AEntity);
                }
                else
                {
                    NetLog.Error("{0} is being destroyed/disabled without being detached by the owner, this will cause this peer to disconnect the next time it receives an update for this entity", AEntity);
                }

                // force detach
                entity.Detach();
                entity = null;
            }
        }
Beispiel #21
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));
        }
Beispiel #22
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);
        }
        public static GameObject Find(PrefabId id)
        {
            if (lookup == null || instance == null)
            {
                LoadInstance();
                UpdateLookup();
            }

            GameObject prefab;

            if (lookup.TryGetValue(id, out prefab))
            {
                return(prefab);
            }
            else
            {
                NetLog.Error("Could not find game object for {0}", id);
                return(null);
            }
        }
Beispiel #24
0
        Vector3 CalculateVelocity(NetworkTransform nt, Vector3 position)
        {
            switch (Extrapolation.VelocityMode)
            {
            case ExtrapolationVelocityModes.CalculateFromPosition:
                return((GetPosition(nt.Simulate) - position) * Core.Config.framesPerSecond);

            case ExtrapolationVelocityModes.CopyFromRigidbody:
                return(nt.Simulate.GetComponent <Rigidbody>().velocity);

            case ExtrapolationVelocityModes.CopyFromRigidbody2D:
                return(nt.Simulate.GetComponent <Rigidbody2D>().velocity);

            case ExtrapolationVelocityModes.CopyFromCharacterController:
                return(nt.Simulate.GetComponent <CharacterController>().velocity);

            default:
                NetLog.Error("Unknown velocity extrapolation mode {0}", Extrapolation.VelocityMode);
                return((GetPosition(nt.Simulate) - position) * Core.Config.framesPerSecond);
            }
        }
Beispiel #25
0
        void Update()
        {
            try
            {
                if ((Time.timeScale != 1f) && RuntimeSettings.Instance.overrideTimeScale)
                {
                    // log this error
                    NetLog.Error("Time.timeScale value is incorrect: {0}f", Time.timeScale);

                    // force this
                    Time.timeScale = 1f;

                    // log that we forced timescale to 1
                    NetLog.Error("Time.timeScale has been set to 1.0f by Ascension");
                }
            }
            finally
            {
                Core.Update();
            }
        }
        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);
            }
        }
Beispiel #27
0
        public void SetParentInternal(Entity entity)
        {
            if (entity != Parent)
            {
                if ((entity != null) && (entity.IsAttached == false))
                {
                    NetLog.Error("You can't assign a detached entity as the parent of another entity");
                    return;
                }

                try
                {
                    // notify serializer
                    Serializer.OnParentChanging(entity, Parent);
                }
                finally
                {
                    // set parent
                    Parent = entity;
                }
            }
        }
Beispiel #28
0
 public NetAssertFailedException(string msg)
     : base(msg)
 {
     NetLog.Error("ASSERT FAILED: " + msg);
 }
Beispiel #29
0
 public NetAssertFailedException()
 {
     NetLog.Error("ASSERT FAILED");
 }
        public void Raise(Event ev)
        {
            IEventFactory factory = Factory.GetEventFactory(ev.Meta.TypeId);

            List <CallbackWrapper> newCallbacks;

            if (callbacks.TryGetValue(ev.GetType(), out newCallbacks))
            {
                for (int i = 0; i < callbacks.Count; ++i)
                {
                    newCallbacks[i].Wrapper(ev);
                }
            }

            for (int i = 0; i < targets.Count; ++i)
            {
                EventListener mb = targets[i];

                if (mb.Behaviour)
                {
                    // dont call on disabled behaviours
                    if (mb.Behaviour.enabled == false)
                    {
                        if ((mb.Listener == null) || (mb.Listener.InvokeIfDisabled == false))
                        {
                            continue;
                        }
                    }

                    // dont call on behaviours attached to inactive game objects
                    if (mb.GameObject.activeInHierarchy == false)
                    {
                        if ((mb.Listener == null) || (mb.Listener.InvokeIfGameObjectIsInactive == false))
                        {
                            continue;
                        }
                    }

                    // invoke event
                    try
                    {
                        factory.Dispatch(ev, mb.Behaviour);
                    }
                    catch (Exception exn)
                    {
                        NetLog.Error("User code threw exception when invoking {0}", ev);
                        NetLog.Exception(exn);
                    }
                }
                else
                {
                    // remove callback if this behaviour is destroyed
                    targets.RemoveAt(i);

                    //
                    --i;

                    continue;
                }
            }
        }