Exemplo n.º 1
0
        protected Agent FindNearestMessenger(AgentPosition agentPosition, AgentPosition destPosition, Message message)
        {
            double minDist = 10000;
            Agent  nAgent  = null;

            foreach (var mAgent in Container.MessengerList)
            {
                if (mAgent != this)
                {
                    var foundAgent = message.RoutingList.Find(messengerAg => messengerAg == mAgent);

                    if (foundAgent == null)
                    {
                        if (agentPosition.Position.CalculateDistance(mAgent.Position.Position) <= RadioRange &&
                            agentPosition.Position.CalculateDistance(mAgent.Position.Position) +
                            destPosition.Position.CalculateDistance(mAgent.Position.Position) < minDist)
                        {
                            minDist = agentPosition.Position.CalculateDistance(mAgent.Position.Position) +
                                      destPosition.Position.CalculateDistance(mAgent.Position.Position);
                            nAgent = mAgent;
                        }
                    }
                }
            }
            return(nAgent);
        }
Exemplo n.º 2
0
 public void SendChildAgentUpdate(AgentPosition agentpos, IRegionClientCapsService regionCaps)
 {
     Util.FireAndForget(delegate(object o)
     {
         SendChildAgentUpdateAsync(agentpos, regionCaps);
     });
 }
        /// <summary>
        ///     We've got an update about an agent that sees into this region,
        ///     send it to ScenePresence for processing  It's only positional data
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
        /// <returns>true if we handled it.</returns>
        public virtual bool IncomingChildAgentDataUpdate(IScene scene, AgentPosition cAgentData)
        {
            // MainConsole.Instance.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
            IScenePresence presence = scene.GetScenePresence(cAgentData.AgentID);

            if (presence != null)
            {
                // I can't imagine *yet* why we would get an update if the agent is a root agent..
                // however to avoid a race condition crossing borders..
                if (presence.IsChildAgent)
                {
                    uint rRegionX = 0;
                    uint rRegionY = 0;
                    //In meters
                    Utils.LongToUInts(cAgentData.RegionHandle, out rRegionX, out rRegionY);
                    //In meters
                    int tRegionX = scene.RegionInfo.RegionLocX;
                    int tRegionY = scene.RegionInfo.RegionLocY;
                    //Send Data to ScenePresence
                    presence.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, (int)rRegionX, (int)rRegionY);
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 4
0
        /**
         * Constructor.
         *
         * @param currentPosition
         *
         */
        public Forward(AgentPosition currentPosition)
            : base(FORWARD_ACTION_NAME)
        {
            int x = currentPosition.getX();
            int y = currentPosition.getY();

            AgentPosition.Orientation orientation = currentPosition.getOrientation();
            if (orientation.Equals(AgentPosition.Orientation.FACING_NORTH))
            {
                toPosition = new AgentPosition(x, y + 1, orientation);
            }
            else if (orientation.Equals(AgentPosition.Orientation.FACING_SOUTH))
            {
                toPosition = new AgentPosition(x, y - 1, orientation);
            }
            else if (orientation.Equals(AgentPosition.Orientation.FACING_EAST))
            {
                toPosition = new AgentPosition(x + 1, y, orientation);
            }
            else if (orientation.Equals(AgentPosition.Orientation.FACING_WEST))
            {
                toPosition = new AgentPosition(x - 1, y, orientation);
            }
            SetAttribute(ATTRIBUTE_TO_POSITION, toPosition);
        }
Exemplo n.º 5
0
        public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
        {
            if (destination == null)
            {
                return(false);
            }

            bool retVal = false;

            foreach (Scene s in m_sceneList)
            {
                //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
                IEntityTransferModule transferModule = s.RequestModuleInterface <IEntityTransferModule> ();
                if (transferModule != null)
                {
                    if (retVal)
                    {
                        transferModule.IncomingChildAgentDataUpdate(s, cAgentData);
                    }
                    else
                    {
                        retVal = transferModule.IncomingChildAgentDataUpdate(s, cAgentData);
                    }
                }
            }
            //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
            return(retVal);
        }
        /// <summary>
        /// This informs all neighboring regions about the settings of it's child agent.
        /// Calls an asynchronous method to do so..  so it doesn't lag the sim.
        ///
        /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
        ///
        /// </summary>
        private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, ulong regionHandle)
        {
            //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
            try
            {
                //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
                uint x = 0, y = 0;
                Utils.LongToUInts(regionHandle, out x, out y);
                GridRegion destination = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
                m_scene.SimulationService.UpdateAgent(destination, cAgentData);
            }
            catch
            {
                // Ignore; we did our best
            }

            //if (regionAccepted)
            //{
            //    //m_log.Info("[INTERGRID]: Completed sending a neighbor an update about my agent");
            //}
            //else
            //{
            //    //m_log.Info("[INTERGRID]: Failed sending a neighbor an update about my agent");
            //}
        }
Exemplo n.º 7
0
 public override void FromOSD(OSDMap map)
 {
     Destination = new GridRegion();
     Destination.FromOSD((OSDMap)map["Destination"]);
     Update = new AgentPosition();
     Update.FromOSD((OSDMap)map["Update"]);
 }
Exemplo n.º 8
0
 public Messenger(Configuration config, AgentPosition pos, string id, Container cont, Area area)
     : base(config, pos, id, cont)
 {
     MessengerArea       = area;
     ReplyWaitingList    = new List <Message>();
     AdaptingWaitingList = new List <Message>();
 }
Exemplo n.º 9
0
        public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence)
        {
            // This assumes that we know what our neighbors are.
            try
            {
                uint          x = 0, y = 0;
                List <string> simulatorList = new List <string>();
                foreach (ulong regionHandle in presence.KnownChildRegionHandles)
                {
                    if (regionHandle != m_regionInfo.RegionHandle)
                    {
                        // we only want to send one update to each simulator; the simulator will
                        // hand it off to the regions where a child agent exists, this does assume
                        // that the region position is cached or performance will degrade
                        Utils.LongToUInts(regionHandle, out x, out y);
                        GridRegion dest = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
                        if (!simulatorList.Contains(dest.ServerURI))
                        {
                            // we havent seen this simulator before, add it to the list
                            // and send it an update
                            simulatorList.Add(dest.ServerURI);

                            SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
                            d.BeginInvoke(cAgentData, m_regionInfo.ScopeID, dest,
                                          SendChildAgentDataUpdateCompleted,
                                          d);
                        }
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // We're ignoring a collection was modified error because this data gets old and outdated fast.
            }
        }
        public static OSDMap SendChildAgentUpdate(AgentPosition agentpos, UUID requestingRegion)
        {
            OSDMap llsdBody = new OSDMap {
                { "AgentPos", agentpos.ToOSD() }
            };

            return(buildEvent("SendChildAgentUpdate", llsdBody, agentpos.AgentID, requestingRegion));
        }
Exemplo n.º 11
0
 public Worker(Configuration config, AgentPosition pos, string id,
               OrganizationBoundries orgBoundary, Container cont)
     : base(config, pos, id, cont)
 {
     TeamBoundary     = orgBoundary;
     ReplyWaitingList = new List <Message>();
     MaxPingDelay     = 10000;
 }
Exemplo n.º 12
0
 protected Agent(Configuration config, AgentPosition position, string id, Container cont)
 {
     Config     = config;
     Container  = cont;
     Position   = position;
     AgentId    = id;
     RadioRange = Config.MaxRadioRange;
     Status     = State.Stable;
 }
Exemplo n.º 13
0
        public bool UpdateAgent(GridRegion destination, AgentPosition data)
        {
            if (m_blackListedRegions.ContainsKey(destination.ServerURI))
            {
                //Check against time
                if (m_blackListedRegions[destination.ServerURI] > 3 &&
                    Util.EnvironmentTickCountSubtract(m_blackListedRegions[destination.ServerURI]) > 0)
                {
                    MainConsole.Instance.Warn("[Sim Service Connector]: Blacklisted region " + destination.RegionName +
                                              " requested");
                    //Still blacklisted
                    return(false);
                }
            }

            UpdateAgentPositionRequest request = new UpdateAgentPositionRequest();

            request.Update      = data;
            request.Destination = destination;

            AutoResetEvent resetEvent = new AutoResetEvent(false);
            OSDMap         result     = null;

            m_syncMessagePoster.Get(destination.ServerURI, request.ToOSD(), (response) =>
            {
                result = response;
                resetEvent.Set();
            });
            bool success = resetEvent.WaitOne(10000) && result != null;

            if (!success)
            {
                if (m_blackListedRegions.ContainsKey(destination.ServerURI))
                {
                    if (m_blackListedRegions[destination.ServerURI] == 3)
                    {
                        //add it to the blacklist as the request completely failed 3 times
                        m_blackListedRegions[destination.ServerURI] = Util.EnvironmentTickCount() + 60 * 1000; //60 seconds
                    }
                    else if (m_blackListedRegions[destination.ServerURI] == 0)
                    {
                        m_blackListedRegions[destination.ServerURI]++;
                    }
                }
                else
                {
                    m_blackListedRegions[destination.ServerURI] = 0;
                }
                return(false);
            }

            //Clear out the blacklist if it went through
            m_blackListedRegions.Remove(destination.ServerURI);

            return(result["Success"].AsBoolean());
        }
Exemplo n.º 14
0
        private void SetAgentVelocity(AgentPosition agentPosition)
        {
            var v = Config.MaxSpeed / 2;

            v = v + (Config.Rnd.NextDouble() - 0.5) * Config.MaxSpeed;
            var degree = Config.Rnd.NextDouble() * 360;

            agentPosition.Velocity.Y = v * Math.Sin(degree);
            agentPosition.Velocity.X = v * Math.Cos(degree);
        }
Exemplo n.º 15
0
        private Agent createNode(int ID)
        {
            Agent         tempAgent;
            AgentPosition tempAgentPosition = new AgentPosition();

            setAgentPosition(tempAgentPosition);
            setAgentVelocity(tempAgentPosition);
            // tempAgent = new Agent(tempAgentPosition,ID,Role.RolesName.Worker,new organizationBoundries(),);
            return(tempAgent);
        }
Exemplo n.º 16
0
        private AgentPosition SetAgentPosition()
        {
            var    tempAgentPosition = new AgentPosition();
            var    randomRadius      = Config.Rnd.NextDouble() * OrganizationBoundries.Radius;
            double randomDegree      = Config.Rnd.Next(0, 360);

            tempAgentPosition.Position.X = randomRadius * Math.Sin(randomDegree) + OrganizationBoundries.OrgCenter.X;
            tempAgentPosition.Position.Y = randomRadius * Math.Cos(randomDegree) + OrganizationBoundries.OrgCenter.Y;
            return(tempAgentPosition);
        }
        /// <summary>
        /// Send updated position information about an agent in this region to a neighbor
        /// This operation may be called very frequently if an avatar is moving about in
        /// the region.
        /// </summary>
        public bool UpdateAgent(GridRegion destination, AgentPosition data)
        {
            // The basic idea of this code is that the first thread that needs to
            // send an update for a specific avatar becomes the worker for any subsequent
            // requests until there are no more outstanding requests. Further, only send the most
            // recent update; this *should* never be needed but some requests get
            // slowed down and once that happens the problem with service end point
            // limits kicks in and nothing proceeds
            string uri = destination.ServerURI + AgentPath() + data.AgentID + "/";

            lock (m_updateAgentQueue)
            {
                if (m_updateAgentQueue.ContainsKey(uri))
                {
                    // Another thread is already handling
                    // updates for this simulator, just update
                    // the position and return, overwrites are
                    // not a problem since we only care about the
                    // last update anyway
                    m_updateAgentQueue[uri] = data;
                    return(true);
                }

                // Otherwise update the reference and start processing
                m_updateAgentQueue[uri] = data;
            }

            AgentPosition pos = null;

            while (true)
            {
                lock (m_updateAgentQueue)
                {
                    // save the position
                    AgentPosition lastpos = pos;

                    pos = m_updateAgentQueue[uri];

                    // this is true if no one put a new
                    // update in the map since the last
                    // one we processed, if thats the
                    // case then we are done
                    if (pos == lastpos)
                    {
                        m_updateAgentQueue.Remove(uri);
                        return(true);
                    }
                }

                UpdateAgent(destination, (IAgentData)pos);
            }

            // unreachable
//            return true;
        }
        public static OSDMap AgentLoggedOut(UUID AgentID, UUID requestingRegion, AgentPosition agentpos)
        {
            OSDMap llsdBody = new OSDMap
            {
                { "AgentID", AgentID },
                { "AgentPos", agentpos.ToOSD() },
                { "RequestingRegion", requestingRegion }
            };

            return(buildEvent("AgentLoggedOut", llsdBody, AgentID, requestingRegion));
        }
Exemplo n.º 19
0
 /// <summary>
 /// This informs all neighboring regions about the settings of it's child agent.
 /// Calls an asynchronous method to do so..  so it doesn't lag the sim.
 ///
 /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
 ///
 /// </summary>
 private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, UUID scopeID, GridRegion dest)
 {
     //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
     try
     {
         m_scene.SimulationService.UpdateAgent(dest, cAgentData);
     }
     catch
     {
         // Ignore; we did our best
     }
 }
Exemplo n.º 20
0
        public Ruler(Configuration config, AgentPosition pos, string id, Area area, Container cont)
            : base(config, pos, id, cont)
        {
            RulerArea  = area;
            LeaderList = InitialLeaderList();
            Status     = State.Stable;

            foreach (var leader in LeaderList)
            {
                leader.RulerAgent = this;
            }
        }
Exemplo n.º 21
0
        private AgentPosition SetAgentPosition()
        {
            var tempAgentPosition = new AgentPosition
            {
                Position =
                {
                    X = Config.Rnd.NextDouble() * (Config.UpperBoarder.X - Config.LowerBoarder.X) + Config.LowerBoarder.X,
                    Y = Config.Rnd.NextDouble() * (Config.UpperBoarder.Y - Config.LowerBoarder.Y) + Config.LowerBoarder.Y
                }
            };

            return(tempAgentPosition);
        }
 public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence)
 {
     foreach (ulong regionHandle in presence.KnownChildRegionHandles)
     {
         if (regionHandle != m_regionInfo.RegionHandle)
         {
             SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
             d.BeginInvoke(cAgentData, regionHandle,
                           SendChildAgentDataUpdateCompleted,
                           d);
         }
     }
 }
Exemplo n.º 23
0
 public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
 {
     foreach (Scene s in m_sceneList)
     {
         if (s.RegionInfo.RegionHandle == regionHandle)
         {
             //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
             s.IncomingChildAgentDataUpdate(cAgentData);
             return(true);
         }
     }
     //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
     return(false);
 }
 /// <summary>
 /// This informs all neighboring regions about the settings of it's child agent.
 /// Calls an asynchronous method to do so..  so it doesn't lag the sim.
 ///
 /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
 ///
 /// </summary>
 private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, ulong regionHandle)
 {
     //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
     try
     {
         //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
         m_interregionCommsOut.SendChildAgentUpdate(regionHandle, cAgentData);
     }
     catch (Exception e)
     {
         m_log.ErrorFormat("[INTERGRID]: Exception in SendChildAgentDataUpdateAsync. {0}", e);
         // Ignore; we did our best
     }
 }
        public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
        {
            if (destination == null)
            {
                return(false);
            }

            // Try local first
            if (m_localBackend.IsLocalRegion(destination.RegionID))
            {
                return(m_localBackend.UpdateAgent(destination, cAgentData));
            }

            return(m_remoteConnector.UpdateAgent(destination, cAgentData));
        }
Exemplo n.º 26
0
        public void testSuccessors()
        {
            ICollection <AgentPosition>             succPositions   = CollectionFactory.CreateQueue <AgentPosition>();
            ICollection <AgentPosition.Orientation> succOrientation = CollectionFactory.CreateQueue <AgentPosition.Orientation>();

            // From every position the possible actions are:
            //    - Turn right (change orientation, not position)
            //    - Turn left (change orientation, not position)
            //    - Forward (change position, not orientation)
            AgentPosition P11U = new AgentPosition(1, 1, AgentPosition.Orientation.FACING_NORTH);

            succPositions.Add(new AgentPosition(1, 2, AgentPosition.Orientation.FACING_NORTH));
            succOrientation.Add(AgentPosition.Orientation.FACING_EAST);
            succOrientation.Add(AgentPosition.Orientation.FACING_WEST);
            foreach (IAction a in actionFn.apply(P11U))
            {
                if (a is Forward)
                {
                    Assert.IsTrue(succPositions.Contains(((Forward)a).getToPosition()));
                    Assert.IsTrue(succPositions.Contains(resultFn.apply(P11U, a)));
                }
                else if (a is TurnLeft)
                {
                    Assert.IsTrue(succOrientation.Contains(((TurnLeft)a).getToOrientation()));
                    Assert.AreEqual("[1,1]->FacingWest", resultFn.apply(P11U, a).ToString());
                }
                else if (a is TurnRight)
                {
                    Assert.IsTrue(succOrientation.Contains(((TurnRight)a).getToOrientation()));
                    Assert.AreEqual("[1,1]->FacingEast", resultFn.apply(P11U, a).ToString());
                }
            }


            //If you are in front of a wall forward action is not possible
            AgentPosition P31D = new AgentPosition(3, 1, AgentPosition.Orientation.FACING_SOUTH);
            AgentPosition P41R = new AgentPosition(4, 1, AgentPosition.Orientation.FACING_EAST);

            foreach (IAction a in actionFn.apply(P31D))
            {
                Assert.IsFalse(a is Forward);
            }

            foreach (IAction a in actionFn.apply(P41R))
            {
                Assert.IsFalse(a is Forward);
            }
        }
Exemplo n.º 27
0
        public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence)
        {
//            m_log.DebugFormat(
//                "[SCENE COMMUNICATION SERVICE]: Sending child agent position updates for {0} in {1}",
//                presence.Name, m_scene.Name);

            // This assumes that we know what our neighbors are.
            try
            {
                uint          x = 0, y = 0;
                List <string> simulatorList = new List <string>();
                foreach (ulong regionHandle in presence.KnownRegionHandles)
                {
                    if (regionHandle != m_regionInfo.RegionHandle)
                    {
                        // we only want to send one update to each simulator; the simulator will
                        // hand it off to the regions where a child agent exists, this does assume
                        // that the region position is cached or performance will degrade
                        Util.RegionHandleToWorldLoc(regionHandle, out x, out y);
                        GridRegion dest = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
                        if (dest == null)
                        {
                            continue;
                        }

                        if (!simulatorList.Contains(dest.ServerURI))
                        {
                            // we havent seen this simulator before, add it to the list
                            // and send it an update
                            simulatorList.Add(dest.ServerURI);
                            // Let move this to sync. Mono definitely does not like async networking.
                            m_scene.SimulationService.UpdateAgent(dest, cAgentData);

                            // Leaving this here as a reminder that we tried, and it sucks.
                            //SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
                            //d.BeginInvoke(cAgentData, m_regionInfo.ScopeID, dest,
                            //              SendChildAgentDataUpdateCompleted,
                            //              d);
                        }
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // We're ignoring a collection was modified error because this data gets old and outdated fast.
            }
        }
        public bool UpdateAgent(GridRegion destination, AgentPosition agentData)
        {
            if (Scene == null || destination == null)
            {
                return(false);
            }

            //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
            IEntityTransferModule transferModule = Scene.RequestModuleInterface <IEntityTransferModule>();

            if (transferModule != null)
            {
                return(transferModule.IncomingChildAgentDataUpdate(Scene, agentData));
            }

            return(false);
        }
Exemplo n.º 29
0
        protected void UpdateVelocity(AgentPosition position)
        {
            var t1 = Config.Rnd.NextDouble();

            t1 = (t1 - 0.5) * 2;
            var t2 = Config.Rnd.NextDouble();

            t2 = (t2 - 0.5) * 2;

            if ((position.Velocity.X * position.Velocity.X) + (position.Velocity.Y * position.Velocity.Y) > (Config.MaxSpeed * Config.MaxSpeed))
            {
                position.Velocity.X /= 2;
                position.Velocity.Y /= 2;
            }

            position.Velocity.X += t1;
            position.Velocity.Y += t2;
        }
Exemplo n.º 30
0
        protected Messenger FindNearestMessenger(AgentPosition destPosition)
        {
            double    minMessengerDistance = 10000;
            Messenger messenger            = null;

            foreach (var mAgent in Container.MessengerList)
            {
                if (Position.Position.CalculateDistance(mAgent.Position.Position) <= RadioRange &&
                    Position.Position.CalculateDistance(mAgent.Position.Position) +
                    destPosition.Position.CalculateDistance(mAgent.Position.Position) < minMessengerDistance)
                {
                    minMessengerDistance = Position.Position.CalculateDistance(mAgent.Position.Position) +
                                           destPosition.Position.CalculateDistance(mAgent.Position.Position);
                    messenger = mAgent;
                }
            }
            return(messenger);
        }
Exemplo n.º 31
0
 public virtual void SendChildAgentUpdate(AgentPosition agentpos, IRegionClientCapsService regionCaps)
 {
     Util.FireAndForget(delegate { SendChildAgentUpdateAsync(agentpos, regionCaps); });
 }
Exemplo n.º 32
0
        /// <summary>
        /// We've got an update about an agent that sees into this region, 
        /// send it to ScenePresence for processing  It's only positional data
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
        /// <returns>true if we handled it.</returns>
        public virtual bool IncomingChildAgentDataUpdate (IScene scene, AgentPosition cAgentData)
        {
            //MainConsole.Instance.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
            IScenePresence presence = scene.GetScenePresence (cAgentData.AgentID);
            if (presence != null)
            {
                // I can't imagine *yet* why we would get an update if the agent is a root agent..
                // however to avoid a race condition crossing borders..
                if (presence.IsChildAgent)
                {
                    uint rRegionX = 0;
                    uint rRegionY = 0;
                    //In meters
                    Utils.LongToUInts (cAgentData.RegionHandle, out rRegionX, out rRegionY);
                    //In meters
                    int tRegionX = scene.RegionInfo.RegionLocX;
                    int tRegionY = scene.RegionInfo.RegionLocY;
                    //Send Data to ScenePresence
                    presence.ChildAgentDataUpdate (cAgentData, tRegionX, tRegionY, (int)rRegionX, (int)rRegionY);
                }

                return true;
            }

            return false;
        }
Exemplo n.º 33
0
        //private void TestThread(object arg)
        //{
        //    int x = 0;
        //    int y = 0;
        //    char Object1 = '1';
        //    char Object2 = '2';
        //    while (!this.Terminate)
        //    {
        //        this.occupiedPositionList.Enqueue(new AgentPosition(Object1, (x + 1)%this.XSize, y));
        //        this.occupiedPositionList.Enqueue(new AgentPosition(Object2, x, y));
        //        x++;
        //        if (x == this.XSize)
        //        {
        //            x = 0;
        //            y++;
        //            if (y == this.YSize)
        //            {
        //                y = 0;
        //            }
        //        }
        //        Thread.Sleep(500);
        //    }
        //}
        private void AddObject(AgentPosition newObject)
        {
            char[] tempRow = this.AgentCollection[newObject.YPos].Column;
            tempRow[newObject.XPos] = (char)newObject.Object;

            this.AgentCollection[newObject.YPos].Column = tempRow;
        }
Exemplo n.º 34
0
        /// <summary>
        /// This updates important decision making data about a child agent
        /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
        /// </summary>
        public void ChildAgentDataUpdate(AgentPosition cAgentData, int tRegionX, int tRegionY, int rRegionX, int rRegionY)
        {
            if (!IsChildAgent)
                return;

            //MainConsole.Instance.Debug("   >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
            int shiftx = rRegionX - tRegionX;
            int shifty = rRegionY - tRegionY;

            Vector3 offset = new Vector3(shiftx, shifty, 0f);

            DrawDistance = cAgentData.Far;
            m_pos = cAgentData.Position + offset;

            m_CameraCenter = cAgentData.Center + offset;

            m_avHeight = cAgentData.Size.Z;

            TriggerSignificantClientMovement();

            m_savedVelocity = cAgentData.Velocity;
        }
Exemplo n.º 35
0
        public void Update()
        {
            if ((Taints & PresenceTaint.ObjectUpdates) == PresenceTaint.ObjectUpdates)
            {
                Taints &= ~PresenceTaint.ObjectUpdates;

                lock (m_terseUpdates)
                {
                    foreach (OUpdates update in m_terseUpdates)
                        SceneViewer.QueuePartForUpdate(update.Child, update.Flags);
                    m_terseUpdates.Clear();
                }
            }
            if (!IsChildAgent && m_parentID != UUID.Zero)
            {
                SceneObjectPart part = (SceneObjectPart)Scene.GetSceneObjectPart(m_parentID);
                if (part != null)
                {
                    part.SetPhysActorCameraPos((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) ==
                                               AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK
                                                   ? CameraRotation
                                                   : Quaternion.Identity);
                }
            }
            if ((Taints & PresenceTaint.SignificantMovement) == PresenceTaint.SignificantMovement)
            {
                Taints &= ~PresenceTaint.SignificantMovement;
                //Trigger the movement now
                TriggerSignificantClientMovement();
            }
            if ((Taints & PresenceTaint.TerseUpdate) == PresenceTaint.TerseUpdate)
            {
                Taints &= ~PresenceTaint.TerseUpdate;
                //Send the terse update
                SendTerseUpdateToAllClients();
            }
            if ((Taints & PresenceTaint.Movement) == PresenceTaint.Movement)
            {
                Taints &= ~PresenceTaint.Movement;
                //Finish out the event
                UpdatePosAndVelocity();
            }
            if (m_enqueueSendChildAgentUpdate &&
                m_enqueueSendChildAgentUpdateTime != new DateTime())
            {
                if (DateTime.Now > m_enqueueSendChildAgentUpdateTime)
                {
                    Taints &= ~PresenceTaint.Other;
                    //Reset it now
                    m_enqueueSendChildAgentUpdateTime = new DateTime();
                    m_enqueueSendChildAgentUpdate = false;

                    AgentPosition agentpos = new AgentPosition
                                                 {
                                                     AgentID = UUID,
                                                     AtAxis = CameraAtAxis,
                                                     Center = m_lastChildAgentUpdateCamPosition,
                                                     Far = DrawDistance,
                                                     LeftAxis = CameraLeftAxis,
                                                     Position = m_lastChildAgentUpdatePosition,
                                                     RegionHandle = Scene.RegionInfo.RegionHandle,
                                                     Size =
                                                         PhysicsActor != null
                                                             ? PhysicsActor.Size
                                                             : new Vector3(0, 0, m_avHeight),
                                                     UpAxis = CameraUpAxis,
                                                     Velocity = Velocity
                                                 };

                    //Send the child agent data update
                    ISyncMessagePosterService syncPoster = Scene.RequestModuleInterface<ISyncMessagePosterService>();
                    if (syncPoster != null)
                        syncPoster.Post(SyncMessageHelper.SendChildAgentUpdate(agentpos, m_scene.RegionInfo.RegionHandle), m_scene.RegionInfo.RegionHandle);
                }
                else
                    Scene.SceneGraph.TaintPresenceForUpdate(this, PresenceTaint.Other);//We havn't sent the update yet, keep tainting
            }
        }
Exemplo n.º 36
0
        private void CleanerThread(object arg)
        {
            AgentPosition newPos = null;
            AgentPosition goalPos = null;

            while (!this.Terminate)
            {
                newPos = this.availablePositionList.Dequeue();

                if (newPos != null)
                {
                    if (newPos.Object != 'B')
                    {
                        lock (this.mutex)
                        {
                            for (int i = 0; i < this.YSize; i++)
                            {
                                for (int j = 0; j < this.XSize; j++)
                                {
                                    if (newPos.Object == this.AgentCollection[i].Column[j])//this.charMap[i][j])
                                    {
                                        if ((i == newPos.YPos) && (j == newPos.XPos))
                                        {
                                        }
                                        else
                                        {
                                            goalPos = this.goalList.Find(pos => ((pos.YPos == i) && (pos.XPos == j)));

                                            if (goalPos != null)
                                            {
                                                AddObject(goalPos);
                                            }
                                            else
                                            {
                                                goalPos = new AgentPosition();
                                                goalPos.Object = (sbyte)'O';
                                                goalPos.XPos = j;
                                                goalPos.YPos = i;

                                                AddObject(goalPos);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 37
0
 public bool UpdateAgent(GridRegion destination, AgentPosition data)
 {
     return UpdateAgent(destination, (IAgentData) data);
 }
Exemplo n.º 38
0
        public void OnConnectionClose(IClientAPI client)
        {
            IScenePresence sp = null;
            client.Scene.TryGetScenePresence(client.AgentId, out sp);
            if (client.IsLoggingOut && sp != null & !sp.IsChildAgent)
            {
                MainConsole.Instance.InfoFormat("[ActivityDetector]: Detected logout of user {0} in region {1}", client.Name,
                                 client.Scene.RegionInfo.RegionName);

                //Inform the grid service about it

                if (m_zombieAgents.Contains(client.AgentId))
                {
                    m_zombieAgents.Remove(client.AgentId);
                    return; //They are a known zombie, just clear them out and go on with life!
                }
                AgentPosition agentpos = new AgentPosition
                                             {
                                                 AgentID = sp.UUID,
                                                 AtAxis = sp.CameraAtAxis,
                                                 Center = sp.CameraPosition,
                                                 Far = sp.DrawDistance,
                                                 LeftAxis = Vector3.Zero,
                                                 Position = sp.AbsolutePosition
                                             };
                if (agentpos.Position.X > sp.Scene.RegionInfo.RegionSizeX)
                    agentpos.Position.X = sp.Scene.RegionInfo.RegionSizeX;
                if (agentpos.Position.Y > sp.Scene.RegionInfo.RegionSizeY)
                    agentpos.Position.Y = sp.Scene.RegionInfo.RegionSizeY;
                if (agentpos.Position.Z > sp.Scene.RegionInfo.RegionSizeZ)
                    agentpos.Position.Z = sp.Scene.RegionInfo.RegionSizeZ;
                if (agentpos.Position.X < 0)
                    agentpos.Position.X = 0;
                if (agentpos.Position.Y < 0)
                    agentpos.Position.Y = 0;
                if (agentpos.Position.Z < 0)
                    agentpos.Position.Z = 0;
                agentpos.RegionHandle = sp.Scene.RegionInfo.RegionHandle;
                agentpos.Size = sp.PhysicsActor != null ? sp.PhysicsActor.Size : new Vector3(0, 0, 1.8f);
                agentpos.UpAxis = Vector3.Zero;
                agentpos.Velocity = sp.Velocity;
                agentpos.UserGoingOffline = true; //Don't attempt to add us into other regions

                //Send the child agent data update
                ISyncMessagePosterService syncPoster = sp.Scene.RequestModuleInterface<ISyncMessagePosterService>();
                if (syncPoster != null)
                {
                    syncPoster.PostToServer(SyncMessageHelper.SendChildAgentUpdate(agentpos, sp.Scene.RegionInfo.RegionHandle));
                    syncPoster.PostToServer(
                        SyncMessageHelper.AgentLoggedOut(client.AgentId, client.Scene.RegionInfo.RegionHandle));
                }
            }
        }
        public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
        {
            if (destination == null)
                return false;

            bool retVal = false;
            foreach (IScene s in m_sceneList)
            {
                //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
                IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>();
                if (transferModule != null)
                    if (retVal)
                        transferModule.IncomingChildAgentDataUpdate(s, cAgentData);
                    else
                        retVal = transferModule.IncomingChildAgentDataUpdate(s, cAgentData);
            }
            //MainConsole.Instance.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
            return retVal;
        }
Exemplo n.º 40
0
        public static OSDMap SendChildAgentUpdate(AgentPosition agentpos, ulong requestingRegion)
        {
            OSDMap llsdBody = new OSDMap {{"AgentPos", agentpos.Pack()}};

            return buildEvent("SendChildAgentUpdate", llsdBody, agentpos.AgentID, requestingRegion);
        }
Exemplo n.º 41
0
        protected void DoAgentPut(Hashtable request, Hashtable responsedata)
        {
            OSDMap args = WebUtils.GetOSDMap((string) request["body"]);
            if (args == null)
            {
                responsedata["int_response_code"] = HttpStatusCode.BadRequest;
                responsedata["str_response_string"] = "Bad request";
                return;
            }

            // retrieve the input arguments
            int x = 0, y = 0;
            UUID uuid = UUID.Zero;
            string regionname = string.Empty;
            if (args.ContainsKey("destination_x") && args["destination_x"] != null)
                Int32.TryParse(args["destination_x"].AsString(), out x);
            if (args.ContainsKey("destination_y") && args["destination_y"] != null)
                Int32.TryParse(args["destination_y"].AsString(), out y);
            if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
                UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
            if (args.ContainsKey("destination_name") && args["destination_name"] != null)
                regionname = args["destination_name"].ToString();

            GridRegion destination = new GridRegion
                                         {RegionID = uuid, RegionLocX = x, RegionLocY = y, RegionName = regionname};

            string messageType;
            if (args["message_type"] != null)
                messageType = args["message_type"].AsString();
            else
            {
                MainConsole.Instance.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
                messageType = "AgentData";
            }

            bool result = true;
            if ("AgentData".Equals(messageType))
            {
                AgentData agent = new AgentData();
                try
                {
                    agent.Unpack(args);
                }
                catch (Exception ex)
                {
                    MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex);
                    responsedata["int_response_code"] = HttpStatusCode.BadRequest;
                    responsedata["str_response_string"] = "Bad request";
                    return;
                }

                //agent.Dump();
                // This is one of the meanings of PUT agent
                result = UpdateAgent(destination, agent);
            }
            else if ("AgentPosition".Equals(messageType))
            {
                AgentPosition agent = new AgentPosition();
                try
                {
                    agent.Unpack(args);
                }
                catch (Exception ex)
                {
                    MainConsole.Instance.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex);
                    return;
                }
                //agent.Dump();
                // This is one of the meanings of PUT agent
                result = m_SimulationService.UpdateAgent(destination, agent);
            }
            OSDMap resp = new OSDMap();
            resp["Updated"] = result;
            responsedata["int_response_code"] = HttpStatusCode.OK;
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
        }
Exemplo n.º 42
0
        public virtual void SendChildAgentUpdateAsync(AgentPosition agentpos, IRegionClientCapsService regionCaps)
        {
            //We need to send this update out to all the child agents this region has
            IGridService service = m_registry.RequestModuleInterface<IGridService>();
            if (service != null)
            {
                ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
                if (SimulationService != null)
                {
                    //Set the last location in the database
                    IAgentInfoService agentInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
                    if (agentInfoService != null)
                    {
                        //Find the lookAt vector
                        Vector3 lookAt = new Vector3(agentpos.AtAxis.X, agentpos.AtAxis.Y, 0);

                        if (lookAt != Vector3.Zero)
                            lookAt = Util.GetNormalizedVector(lookAt);
                        //Update the database
                        agentInfoService.SetLastPosition(regionCaps.AgentID.ToString(), regionCaps.Region.RegionID,
                                                         agentpos.Position, lookAt);
                    }

                    //Also update the service itself
                    regionCaps.LastPosition = agentpos.Position;
                    if (agentpos.UserGoingOffline)
                        return; //It just needed a last pos update

                    //Tell all neighbor regions about the new position as well
                    List<GridRegion> ourNeighbors = GetRegions(regionCaps.ClientCaps);
                    foreach (GridRegion region in ourNeighbors.Where(region => region != null && !SimulationService.UpdateAgent(region, agentpos)))
                    {
                        MainConsole.Instance.Info("[AgentProcessing]: Failed to inform " + region.RegionName +
                                   " about updating agent. ");
                    }

                    EnableChildAgentsForPosition(regionCaps, agentpos.Position);
                }
            }
        }
Exemplo n.º 43
0
        protected virtual OSDMap OnMessageReceived(OSDMap message)
        {
            if (!message.ContainsKey("Method"))
                return null;

            UUID AgentID = message["AgentID"].AsUUID();
            ulong requestingRegion = message["RequestingRegion"].AsULong();
            ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
            if (capsService == null)
                return new OSDMap();

            IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID);

            IRegionClientCapsService regionCaps = null;
            if (clientCaps != null)
                regionCaps = clientCaps.GetCapsService(requestingRegion);
            if (message["Method"] == "LogoutRegionAgents")
            {
                LogOutAllAgentsForRegion(requestingRegion);
            }
            else if (message["Method"] == "RegionIsOnline")
                //This gets fired when the scene is fully finished starting up
            {
                //Log out all the agents first, then add any child agents that should be in this region
                LogOutAllAgentsForRegion(requestingRegion);
                IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
                if (GridService != null)
                {
                    int x, y;
                    Util.UlongToInts(requestingRegion, out x, out y);
                    GridRegion requestingGridRegion = GridService.GetRegionByPosition(null, x, y);
                    if (requestingGridRegion != null)
                        Util.FireAndForget((o) => EnableChildAgentsForRegion(requestingGridRegion));
                }
            }
            else if (message["Method"] == "DisableSimulator")
            {
                //KILL IT!
                if (regionCaps == null || clientCaps == null)
                    return null;
                IEventQueueService eventQueue = m_registry.RequestModuleInterface<IEventQueueService>();
                eventQueue.DisableSimulator(regionCaps.AgentID, regionCaps.RegionHandle);
                //regionCaps.Close();
                //clientCaps.RemoveCAPS(requestingRegion);
                regionCaps.Disabled = true;
            }
            else if (message["Method"] == "ArrivedAtDestination")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                //Recieved a callback
                if (clientCaps.InTeleport) //Only set this if we are in a teleport, 
                    //  otherwise (such as on login), this won't check after the first tp!
                    clientCaps.CallbackHasCome = true;

                regionCaps.Disabled = false;

                //The agent is getting here for the first time (eg. login)
                OSDMap body = ((OSDMap) message["Message"]);

                //Parse the OSDMap
                int DrawDistance = body["DrawDistance"].AsInteger();

                AgentCircuitData circuitData = new AgentCircuitData();
                circuitData.UnpackAgentCircuitData((OSDMap) body["Circuit"]);

                //Now do the creation
                EnableChildAgents(AgentID, requestingRegion, DrawDistance, circuitData);
            }
            else if (message["Method"] == "CancelTeleport")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                //Only the region the client is root in can do this
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle)
                {
                    //The user has requested to cancel the teleport, stop them.
                    clientCaps.RequestToCancelTeleport = true;
                    regionCaps.Disabled = false;
                }
            }
            else if (message["Method"] == "AgentLoggedOut")
            {
                //ONLY if the agent is root do we even consider it
                if (regionCaps != null)
                {
                    if (regionCaps.RootAgent)
                    {
                        LogoutAgent(regionCaps, false); //The root is killing itself
                    }
                }
            }
            else if (message["Method"] == "SendChildAgentUpdate")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle) //Has to be root
                {
                    OSDMap body = ((OSDMap) message["Message"]);

                    AgentPosition pos = new AgentPosition();
                    pos.Unpack((OSDMap) body["AgentPos"]);

                    SendChildAgentUpdate(pos, regionCaps);
                    regionCaps.Disabled = false;
                }
            }
            else if (message["Method"] == "TeleportAgent")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle)
                {
                    OSDMap body = ((OSDMap) message["Message"]);

                    GridRegion destination = new GridRegion();
                    destination.FromOSD((OSDMap) body["Region"]);

                    uint TeleportFlags = body["TeleportFlags"].AsUInteger();
                    int DrawDistance = body["DrawDistance"].AsInteger();

                    AgentCircuitData Circuit = new AgentCircuitData();
                    Circuit.UnpackAgentCircuitData((OSDMap) body["Circuit"]);

                    AgentData AgentData = new AgentData();
                    AgentData.Unpack((OSDMap) body["AgentData"]);
                    regionCaps.Disabled = false;
                    string ResponseURL = message["ResponseURL"].AsString();
                    if (ResponseURL == "")
                    {
                        OSDMap result = new OSDMap();
                        string reason = "";
                        result["success"] = TeleportAgent(ref destination, TeleportFlags, DrawDistance,
                                                          Circuit, AgentData, AgentID, requestingRegion, out reason);
                        result["Reason"] = reason;
                        //Remove the region flags, not the regions problem
                        destination.Flags = 0;
                        result["Destination"] = destination.ToOSD(); //Send back the new destination
                        return result;
                    }
                    else
                    {
                        Util.FireAndForget(delegate
                        {
                            OSDMap result = new OSDMap();
                            string reason = "";
                            result["success"] = TeleportAgent(ref destination, TeleportFlags, DrawDistance,
                                                              Circuit, AgentData, AgentID, requestingRegion, out reason);
                            result["Reason"] = reason;
                            //Remove the region flags, not the regions problem
                            destination.Flags = 0;
                            result["Destination"] = destination.ToOSD(); //Send back the new destination
                            WebUtils.PostToService(ResponseURL, result);
                        });
                        return new OSDMap() { new KeyValuePair<string, OSD>("WillHaveResponse", true) };
                    }
                }
            }
            else if (message["Method"] == "CrossAgent")
            {
                if (regionCaps == null || clientCaps == null)
                    return null;
                IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
                if (rootCaps == null || rootCaps.RegionHandle == regionCaps.RegionHandle)
                {
                    //This is a simulator message that tells us to cross the agent
                    OSDMap body = ((OSDMap) message["Message"]);

                    Vector3 pos = body["Pos"].AsVector3();
                    Vector3 Vel = body["Vel"].AsVector3();
                    GridRegion Region = new GridRegion();
                    Region.FromOSD((OSDMap) body["Region"]);
                    AgentCircuitData Circuit = new AgentCircuitData();
                    Circuit.UnpackAgentCircuitData((OSDMap) body["Circuit"]);
                    AgentData AgentData = new AgentData();
                    AgentData.Unpack((OSDMap) body["AgentData"]);
                    regionCaps.Disabled = false;

                    string ResponseURL = message["ResponseURL"].AsString();
                    if (ResponseURL == "")
                    {
                        OSDMap result = new OSDMap();
                        string reason = "";
                        result["success"] = CrossAgent(Region, pos, Vel, Circuit, AgentData,
                                                       AgentID, requestingRegion, out reason);
                        result["reason"] = reason;
                        return result;
                    }
                    else
                    {
                        Util.FireAndForget(delegate
                        {
                            OSDMap result = new OSDMap();
                            string reason = "";
                            result["success"] = CrossAgent(Region, pos, Vel, Circuit, AgentData,
                                                           AgentID, requestingRegion, out reason);
                            result["reason"] = reason;
                            if (ResponseURL != null)
                                WebUtils.PostToService(ResponseURL, result);
                        });
                        return new OSDMap() { new KeyValuePair<string, OSD>("WillHaveResponse", true) };
                    }
                }
                else if (clientCaps.InTeleport)
                {
                    OSDMap result = new OSDMap();
                    result["success"] = false;
                    result["Note"] = false;
                    return result;
                }
                else
                {
                    OSDMap result = new OSDMap();
                    result["success"] = false;
                    result["Note"] = false;
                    return result;
                }
            }
            return null;
        }
Exemplo n.º 44
0
 private void Update(object sender, AgentPosition pos)
 {
     this.occupiedPositionList.Enqueue(pos);
 }