Exemple #1
0
        /// <summary>
        ///   Per frame update.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after this update. </returns>
        public override ExecutionStatus Update(IAgentData agentData)
        {
            Data data = agentData.GetTaskData <Data>();

            if (data.Status == ExecutionStatus.Running)
            {
                // Update.
                data.Status = this.UpdateChild(agentData);
            }
            else
            {
                // Restart if still possible.
                IDecisionData decisionData = null;
                ++agentData.CurrentDeciderLevel;
                float decisionValue = this.Task.Decide(agentData, ref decisionData);
                --agentData.CurrentDeciderLevel;
                if (decisionValue > 0.0f)
                {
                    data.Status = this.ActivateChild(agentData, decisionData);
                    if (data.Status == ExecutionStatus.Running)
                    {
                        data.Status = this.UpdateChild(agentData);
                    }
                }
                else
                {
                    data.Status = ExecutionStatus.Failed;
                }
            }

            return(ExecutionStatus.Running);
        }
Exemple #2
0
	public override IState CreateNewState(IAgentData data)
	{
		int machineResult = GetKeyByData(data);
		IState newState = new GuessState(machineResult);

		return newState;
	}
Exemple #3
0
        /// <summary>
        ///   Per frame update.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after this update. </returns>
        public override ExecutionStatus Update(IAgentData agentData)
        {
            Data data = agentData.CurrentTaskData as Data;

            if (data.Status == ExecutionStatus.Running)
            {
                data.Status = this.UpdateChild(agentData);
            }
            else
            {
                // Restart if still possible.
                IDecisionData decisionData  = null;
                float         decisionValue = this.Task.Decide(agentData, ref decisionData);
                if (decisionValue > 0.0f)
                {
                    data.Status = this.ActivateChild(agentData, decisionData);
                    if (data.Status == ExecutionStatus.Running)
                    {
                        data.Status = this.UpdateChild(agentData);
                    }
                }
            }

            return(data.Status == ExecutionStatus.Failed ? ExecutionStatus.Failed : ExecutionStatus.Running);
        }
Exemple #4
0
        /// <summary>
        /// Create an uninitialized LSAgent
        /// </summary>
        /// <returns>The raw agent.</returns>
        /// <param name="agentCode">Agent code.</param>
        /// <param name="isBare">If set to <c>true</c> is bare.</param>
        public static LSAgent CreateRawAgent(string agentCode)
        {
            if (!ResourceManager.IsValidAgentCode(agentCode))
            {
                throw new System.ArgumentException(string.Format("Agent code '{0}' not found.", agentCode));
            }
            FastStack <LSAgent> cache    = CachedAgents[agentCode];
            LSAgent             curAgent = null;

            if (cache.IsNotNull() && cache.Count > 0)
            {
                curAgent = cache.Pop();
                ushort agentCodeID = ResourceManager.GetAgentCodeIndex(agentCode);
                Debug.Log(curAgent.TypeIndex);
                TypeAgentsActive[agentCodeID][curAgent.TypeIndex] = true;
            }
            else
            {
                IAgentData interfacer = ResourceManager.AgentCodeInterfacerMap[agentCode];

                curAgent = GameObject.Instantiate(ResourceManager.GetAgentTemplate(agentCode).gameObject).GetComponent <LSAgent>();
                curAgent.Setup(interfacer);

                RegisterRawAgent(curAgent);
            }
            return(curAgent);
        }
        /// <summary>
        /// Not sure what sequence causes this function to be invoked. The only calling
        /// path is through the GET method
        /// </summary>
        public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
        {
            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: RetrieveAgent start");

            agent = null;

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + id + "/" + destination.RegionID.ToString() + "/";

            try
            {
                OSDMap result = WebUtil.GetFromService(uri);
                if (result["Success"].AsBoolean())
                {
                    // OSDMap args = Util.GetOSDMap(result["_RawResult"].AsString());
                    OSDMap args = (OSDMap)result["_Result"];
                    if (args != null)
                    {
                        agent = new CompleteAgentData();
                        agent.Unpack(args, null);
                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
            }

            return(false);
        }
Exemple #6
0
        public int Excute(IAgentData data, IAgent agent)
        {
            int key = GetKeyByData(data);

            if (states.ContainsKey(key) == false)
            {
                IState newState = CreateNewState(data);
                newState.Init(data);
                states.Add(key, newState);

                if (newState.IsEndNode())
                {
                    newState.WorldIndex    = agent.AddEndNodeState(newState);
                    newState.ActionMonitor = agent.CreateActionMonitor(data);
                }
            }

            if (states[key].IsEndNode())
            {
                agent.curAction = states[key].ActionMonitor.ConfirmAndExcuteAction(data);
                agent.curState  = states[key].WorldIndex;
                return(states[key].WorldIndex);
            }
            else
            {
                return(states[key].SubStateMonitor.Excute(data, agent));
            }
        }
Exemple #7
0
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Execution status after activation. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            DecisionData taskDecisionData = (DecisionData)decisionData;

            // Create child blackboard.
            Data data = new Data {
                Blackboard = taskDecisionData.Blackboard, PreviousBlackboard = agentData.Blackboard
            };

            agentData.CurrentTaskData = data;

            // Setup blackboard.
            Setup(agentData, data);

            // Activate child.
            ExecutionStatus result = this.ActivateChild(agentData, taskDecisionData.ChildDecisionData);

            if (result != ExecutionStatus.Running)
            {
                // Tear down.
                TearDown(agentData, data);
            }

            return(result);
        }
Exemple #8
0
        /// <summary>
        ///   Tries to get the task parameter value.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="value"> Parameter value. </param>
        /// <returns> True if value was determined; otherwise, false. </returns>
        public bool TryGetValue(IAgentData agentData, out object value)
        {
            switch (this.Location)
            {
            case TaskParameterLocation.UserValue:
            {
                // Use user value.
                value = this.UserValue;
                return(true);
            }

            case TaskParameterLocation.Blackboard:
            {
                // Try to get from blackboard.
                if (agentData.Blackboard != null && this.BlackboardAttribute != null &&
                    agentData.Blackboard.TryGetValue(this.BlackboardAttribute, out value))
                {
                    return(true);
                }

                // Use user value as fallback/default.
                if (this.UserValue != null)
                {
                    value = this.UserValue;
                    return(true);
                }
            }

            break;
            }

            // Not found.
            value = null;
            return(false);
        }
Exemple #9
0
        public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
        {
            agent = null;
            // Try local first
            if (m_localBackend.RetrieveAgent(destination, id, out agent))
            {
                return(true);
            }

            // else do the remote thing
            if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
            {
                // Eventually, we want to use a caps url instead of the agentID
                string uri = MakeUri(destination, true) + id + "/" + destination.RegionID.ToString() + "/";

                try
                {
                    OSDMap result = WebUtils.GetFromService(uri);
                    if (result["Success"].AsBoolean())
                    {
                        agent = new AgentData();
                        agent.Unpack(result);
                        return(true);
                    }
                }
                catch (Exception e)
                {
                    m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
                }

                return(false);
            }

            return(false);
        }
        /// <summary>
        /// Create an uninitialized RTSAgent
        /// </summary>
        /// <returns>The raw agent.</returns>
        /// <param name="agentCode">Agent code.</param>
        /// <param name="isBare">If set to <c>true</c> is bare.</param>
        public static RTSAgent CreateRawAgent(string agentCode, Vector2d startPosition = default(Vector2d), Vector2d startRotation = default(Vector2d))
        {
            if (!GameResourceManager.IsValidAgentCode(agentCode))
            {
                throw new System.ArgumentException(string.Format("Agent code '{0}' not found.", agentCode));
            }
            FastStack <RTSAgent> cache    = CachedAgents[agentCode];
            RTSAgent             curAgent = null;

            if (cache.IsNotNull() && cache.Count > 0)
            {
                curAgent = cache.Pop();
                ushort agentCodeID = GameResourceManager.GetAgentCodeIndex(agentCode);
                Debug.Log(curAgent.TypeIndex);
                TypeAgentsActive[agentCodeID][curAgent.TypeIndex] = true;
            }
            else
            {
                IAgentData interfacer = GameResourceManager.AgentCodeInterfacerMap[agentCode];

                Vector3    pos = startPosition.ToVector3();
                Quaternion rot = new Quaternion(0, startRotation.y, 0, startRotation.x);

                curAgent = GameObject.Instantiate(GameResourceManager.GetAgentTemplate(agentCode).gameObject, pos, rot).GetComponent <RTSAgent>();
                curAgent.Setup(interfacer);

                RegisterRawAgent(curAgent);
            }
            return(curAgent);
        }
Exemple #11
0
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the task will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the task will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            if (this.Children.Count == 0)
            {
                return(0.0f);
            }

            // Check if all children want to run.
            float maxChildDecisionValue = 0.0f;

            for (int index = 0; index < this.Children.Count; index++)
            {
                ITask         child              = this.Children[index];
                IDecisionData childDecisionData  = null;
                float         childDecisionValue = child.Decide(agentData, ref childDecisionData);
                maxChildDecisionValue = Math.Max(maxChildDecisionValue, childDecisionValue);

                // If one doesn't want to run, we don't run the whole task.
                if (childDecisionValue <= 0.0f)
                {
                    return(0.0f);
                }

                // Store decision data of first child to pass it to it in Activate.
                if (index == 0)
                {
                    decisionData = childDecisionData;
                }
            }

            return(maxChildDecisionValue);
        }
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the decider will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the decider will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            // Create blackboard.
            Blackboard blackboard = new Blackboard();

            // Add parent blackboards.
            if (this.Blackboard != null)
            {
                blackboard.Parents.Add(this.Blackboard);
            }

            blackboard.Parents.Add(agentData.Blackboard);

            // Setup blackboard.
            Blackboard previousBlackboard = agentData.Blackboard;
            agentData.Blackboard = blackboard;

            // Deactivate child.
            IDecisionData childDecisionData = null;
            float decisionValue = this.DecideChild(agentData, ref childDecisionData);

            // Tear down.
            agentData.Blackboard = previousBlackboard;

            // Create decision data.
            if (decisionValue > 0.0f)
            {
                decisionData = new DecisionData { Blackboard = blackboard, ChildDecisionData = childDecisionData };
            }

            return decisionValue;
        }
Exemple #13
0
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the decider will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the decider will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            // Create blackboard.
            Blackboard blackboard = new Blackboard();

            // Add parent blackboards.
            if (this.Blackboard != null)
            {
                blackboard.Parents.Add(this.Blackboard);
            }

            blackboard.Parents.Add(agentData.Blackboard);

            // Setup blackboard.
            Blackboard previousBlackboard = agentData.Blackboard;

            agentData.Blackboard = blackboard;

            // Deactivate child.
            IDecisionData childDecisionData = null;
            float         decisionValue     = this.DecideChild(agentData, ref childDecisionData);

            // Tear down.
            agentData.Blackboard = previousBlackboard;

            // Create decision data.
            if (decisionValue > 0.0f)
            {
                decisionData = new DecisionData {
                    Blackboard = blackboard, ChildDecisionData = childDecisionData
                };
            }

            return(decisionValue);
        }
Exemple #14
0
        /// <summary>
        ///   Generates a collection of active task nodes under this task. Used for debugging only.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="taskNode"> Task node this task is located in. </param>
        /// <param name="activeTasks"> Collection of active task nodes. </param>
        public override void GetActiveTasks(
            IAgentData agentData, TaskNode taskNode, ref ICollection <TaskNode> activeTasks)
        {
            Data data = agentData.CurrentTaskData as Data;

            if (data == null)
            {
                throw new ArgumentException(string.Format("Expected parallel data for task '{0}'.", this.Name));
            }

            // Check if selector has an active child.
            if (data.RunningChildren.Count == 0)
            {
                return;
            }

            // Add task to active tasks and collect active tasks of active child.
            ++agentData.CurrentDeciderLevel;
            foreach (int childIdx in data.RunningChildren)
            {
                TaskNode childTaskNode = taskNode.CreateChildNode(this.Children[childIdx], childIdx);
                activeTasks.Add(childTaskNode);

                agentData.CurrentTaskData = data.ChildrenData[childIdx];
                this.Children[childIdx].GetActiveTasks(agentData, childTaskNode, ref activeTasks);
            }

            --agentData.CurrentDeciderLevel;
        }
Exemple #15
0
        public LSAgent CreateAgent(
            string agentCode,
            Vector2d?position = null,  //nullable position
            Vector2d?rotation = null   //Nullable rotation for default parametrz
            )
        {
            Vector2d pos = position != null ? position.Value : new Vector2d(0, 0);
            Vector2d rot = rotation != null ? rotation.Value : Vector2d.radian0;


            if (!IsValidAgentCode(agentCode))
            {
                throw new System.ArgumentException(string.Format("Agent code '{0}' not found.", agentCode));
            }


            FastStack <LSAgent> cache    = CachedAgents [agentCode];
            LSAgent             curAgent = null;

            if (cache.IsNotNull() && cache.Count > 0)
            {
                curAgent = cache.Pop();
            }
            else
            {
                IAgentData interfacer = AgentController.CodeInterfacerMap [agentCode];

                curAgent = GameObject.Instantiate(interfacer.GetAgent().gameObject).GetComponent <LSAgent>();
                curAgent.Setup(interfacer);
            }
            InitializeAgent(curAgent, pos, rot);
            return(curAgent);
        }
        /// <summary>
        ///   Per frame update.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after this update. </returns>
        public override ExecutionStatus Update(IAgentData agentData)
        {
            Data data = agentData.GetTaskData<Data>();
            if (data.Status == ExecutionStatus.Running)
            {
                // Update.
                data.Status = this.UpdateChild(agentData);
            }
            else
            {
                // Restart if still possible.
                IDecisionData decisionData = null;
                ++agentData.CurrentDeciderLevel;
                float decisionValue = this.Task.Decide(agentData, ref decisionData);
                --agentData.CurrentDeciderLevel;
                if (decisionValue > 0.0f)
                {
                    data.Status = this.ActivateChild(agentData, decisionData);
                    if (data.Status == ExecutionStatus.Running)
                    {
                        data.Status = this.UpdateChild(agentData);
                    }
                }
                else
                {
                    data.Status = ExecutionStatus.Failed;
                }
            }

            return ExecutionStatus.Running;
        }
        public static void Setup()
        {
            IAgentDataProvider database;

            if (LSDatabaseManager.TryGetDatabase <IAgentDataProvider>(out database))
            {
                AgentData = database.AgentData;

                //AgentInterfacer[] agentInters = (LSDatabaseManager.CurrentDatabase as DefaultLSDatabase).AgentData;
                AgentCodes = new string[AgentData.Length];

                CachedAgents = new Dictionary <string, FastStack <LSAgent> >(AgentData.Length);

                for (int i = 0; i < AgentData.Length; i++)
                {
                    IAgentData interfacer = AgentData [i];
                    string     agentCode  = interfacer.Name;
                    AgentCodes [i] = agentCode;

                    CachedAgents.Add(agentCode, new FastStack <LSAgent>(2));
                    CodeInterfacerMap.Add(agentCode, interfacer);
                    CodeIndexMap.Add(agentCode, (ushort)i);
                }
            }
            else
            {
                Debug.Log("Database does no provide AgentData. Make sure it implements IAgentDataProvider.");
            }
        }
Exemple #18
0
        /// <summary>
        /// This is the worker function to send AgentData to a neighbor region
        /// </summary>
        private bool UpdateAgent(GridRegion destination, IAgentData cAgentData, int timeout)
        {
            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: UpdateAgent in {0}", destination.ServerURI);

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + cAgentData.AgentID + "/";

            try
            {
                OSDMap args = cAgentData.Pack();

                args["destination_x"]    = OSD.FromString(destination.RegionLocX.ToString());
                args["destination_y"]    = OSD.FromString(destination.RegionLocY.ToString());
                args["destination_name"] = OSD.FromString(destination.RegionName);
                args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());

                OSDMap result = WebUtil.PutToServiceCompressed(uri, args, timeout);
                if (result["Success"].AsBoolean())
                {
                    return(true);
                }

                result = WebUtil.PutToService(uri, args, timeout);

                return(result["Success"].AsBoolean());
            }
            catch (Exception e)
            {
                m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
            }

            return(false);
        }
        public static void Setup()
        {
            IAgentDataProvider database;

            if (LSDatabaseManager.TryGetDatabase <IAgentDataProvider> (out database))
            {
                AgentData = database.AgentData;

                //AgentInterfacer[] agentInters = (LSDatabaseManager.CurrentDatabase as DefaultLSDatabase).AgentData;
                AgentCodes = new string[AgentData.Length];

                CachedAgents = new Dictionary <string, FastStack <LSAgent> > (AgentData.Length);

                OrganizerObject = LSUtility.CreateEmpty().transform;
                OrganizerObject.gameObject.name = "OrganizerObject";
                OrganizerObject.gameObject.SetActive(false);

                GameObject.DontDestroyOnLoad(OrganizerObject);
                for (int i = 0; i < AgentData.Length; i++)
                {
                    IAgentData interfacer = AgentData [i];
                    string     agentCode  = interfacer.Name;
                    AgentCodes [i] = agentCode;

                    CachedAgents.Add(agentCode, new FastStack <LSAgent> (2));
                    CodeInterfacerMap.Add(agentCode, interfacer);
                    CodeIndexMap.Add(agentCode, (ushort)i);
                }
            }
            else
            {
                Debug.Log("Database does no provide AgentData. Make sure it implements IAgentDataProvider.");
            }
        }
Exemple #20
0
 /// <summary>
 ///   Gets the active tasks of the passed child. Does no index range checking.
 /// </summary>
 /// <param name="childIdx"> Child index. Has to be in correct range. </param>
 /// <param name="agentData"> Agent data. </param>
 /// <param name="childTaskNode"> Task node of child. </param>
 /// <param name="activeTasks"> Collection of active tasks. </param>
 protected void GetActiveChildTasks(
     int childIdx, IAgentData agentData, TaskNode childTaskNode, ref ICollection <TaskNode> activeTasks)
 {
     ++agentData.CurrentDeciderLevel;
     this.children[childIdx].GetActiveTasks(agentData, childTaskNode, ref activeTasks);
     --agentData.CurrentDeciderLevel;
 }
Exemple #21
0
        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the task will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the task will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            List <IDecisionData> childrenDecisionData = new List <IDecisionData>();

            // Check if all children want to run.
            float maxChildDecisionValue = 0.0f;

            foreach (ITask child in this.Children)
            {
                IDecisionData childDecisionData  = null;
                float         childDecisionValue = child.Decide(agentData, ref childDecisionData);
                maxChildDecisionValue = Math.Max(maxChildDecisionValue, childDecisionValue);

                // If one doesn't want to run, we don't run the whole task.
                if (childDecisionValue <= 0.0f)
                {
                    return(0.0f);
                }

                childrenDecisionData.Add(childDecisionData);
            }

            decisionData = new DecisionData {
                ChildrenDecisionData = childrenDecisionData
            };

            return(maxChildDecisionValue);
        }
Exemple #22
0
        /// <summary>
        ///   Activates the passed child. Does no index range checking.
        /// </summary>
        /// <param name="childIdx"> Child index. Has to be in correct range. </param>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data from the decide function. </param>
        /// <returns> Execution status after the activation. </returns>
        protected ExecutionStatus ActivateChild(int childIdx, IAgentData agentData, IDecisionData decisionData)
        {
            ++agentData.CurrentDeciderLevel;
            ExecutionStatus executionStatus = this.children[childIdx].Activate(agentData, decisionData);

            --agentData.CurrentDeciderLevel;
            return(executionStatus);
        }
 /// <summary>
 ///   Deactivation.
 /// </summary>
 /// <param name="agentData"> Agent data. </param>
 public override void Deactivate(IAgentData agentData)
 {
     ITask task = this.GetTask(agentData);
     if (task != null)
     {
         task.Deactivate(agentData);
     }
 }
Exemple #24
0
        /// <summary>
        ///   Updates the child of the decorator.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after update. </returns>
        protected ExecutionStatus UpdateChild(IAgentData agentData)
        {
            ++agentData.CurrentDeciderLevel;
            ExecutionStatus result = this.Task.Update(agentData);

            --agentData.CurrentDeciderLevel;
            return(result);
        }
Exemple #25
0
        /// <summary>
        ///   Let's the child decide.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the task will be activated. </returns>
        protected float DecideChild(IAgentData agentData, ref IDecisionData decisionData)
        {
            ++agentData.CurrentDeciderLevel;
            float decisionValue = this.Task.Decide(agentData, ref decisionData);

            --agentData.CurrentDeciderLevel;
            return(decisionValue);
        }
Exemple #26
0
        /// <summary>
        ///   Activates the child of the decorator.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data. </param>
        /// <returns> Execution status after activation. </returns>
        protected ExecutionStatus ActivateChild(IAgentData agentData, IDecisionData decisionData)
        {
            ++agentData.CurrentDeciderLevel;
            ExecutionStatus result = this.Task.Activate(agentData, decisionData);

            --agentData.CurrentDeciderLevel;
            return(result);
        }
Exemple #27
0
        /*
         * /// <summary>
         * ///   Called when the configuration should be read from xml. Can be overridden in derived classes to read
         * ///   additional attributes from xml.
         * /// </summary>
         * /// <param name = "reader">Xml reader.</param>
         * protected override void OnReadXml(XmlReader reader)
         * {
         *  int numChildren = Convert.ToInt32(reader.GetValue("Count"));
         *  reader.ReadStartElement("Children");
         *  for (int idx = 0; idx < numChildren; ++idx)
         *  {
         *      // Read child.
         *      ITask task;
         *      BehaviorTreeHelpers.ReadXml(reader, out task, "Child");
         *
         *      this.children.Add(task);
         *  }
         *
         *  reader.ReadEndElement();
         * }
         *
         * /// <summary>
         * ///   Called when the configuration should be write to xml. Can be overridden in derived classes to write
         * ///   additional attributes to xml.
         * /// </summary>
         * /// <param name = "writer">Xml writer.</param>
         * protected override void OnWriteXml(XmlWriter writer)
         * {
         *  writer.WriteStartElement("Children");
         *  writer.WriteAttributeString("Count", this.children.Count.ToString());
         *  foreach (ITask task in this.children)
         *  {
         *      BehaviorTreeHelpers.WriteXml(writer, task, "Child");
         *  }
         *
         *  writer.WriteEndElement();
         * }*/

        /// <summary>
        ///   Updates the passed child. Does no index range checking.
        /// </summary>
        /// <param name="childIdx"> Child index. Has to be in correct range. </param>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> New execution status. </returns>
        protected ExecutionStatus UpdateChild(int childIdx, IAgentData agentData)
        {
            ++agentData.CurrentDeciderLevel;
            ExecutionStatus executionStatus = this.children[childIdx].Update(agentData);

            --agentData.CurrentDeciderLevel;
            return(executionStatus);
        }
        /// <summary>
        ///   Deactivation.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        public override void Deactivate(IAgentData agentData)
        {
            ITask task = this.GetTask(agentData);

            if (task != null)
            {
                task.Deactivate(agentData);
            }
        }
Exemple #29
0
        public bool DoRetrieveRootAgentCall(RegionInfo region, UUID id, out IAgentData agent)
        {
            agent = null;
            // Eventually, we want to use a caps url instead of the agentID
            string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
            //Console.WriteLine("   >>> DoRetrieveRootAgentCall <<< " + uri);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Method  = "GET";
            request.Timeout = 10000;
            //request.Headers.Add("authorization", String.Empty); // coming soon
            request.Headers["authorization"] = GenerateAuthorization();

            HttpWebResponse webResponse = null;
            string          reply       = String.Empty;

            try
            {
                webResponse = (HttpWebResponse)request.GetResponse();
                if (webResponse == null)
                {
                    m_log.Info("[REST COMMS]: Null reply on agent get ");
                    return(false);
                }

                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                reply = sr.ReadToEnd().Trim();
                sr.Close();
                //Console.WriteLine("[REST COMMS]: ChildAgentUpdate reply was " + reply);
            }
            catch (WebException ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message);
                // ignore, really
                return(false);
            }

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                // we know it's jason
                OSDMap args = GetOSDMap(reply);
                if (args == null)
                {
                    //Console.WriteLine("[REST COMMS]: Error getting OSDMap from reply");
                    return(false);
                }

                agent = new CompleteAgentData();
                agent.Unpack(args);
                return(true);
            }

            //Console.WriteLine("[REST COMMS]: DoRetrieveRootAgentCall returned status " + webResponse.StatusCode);
            return(false);
        }
Exemple #30
0
 /// <summary>
 ///   Checks for an interrupting task. Only checks higher prioritized deciders as they are the only ones which can interrupt the running task.
 /// </summary>
 /// <param name="agentData"> Agent data. </param>
 /// <param name="data"> task data. </param>
 /// <param name="childIdx"> Index of child which will be activated. </param>
 /// <param name="childDecideValue"> Decide value of child which will be activated. </param>
 /// <param name="childDecisionData"> Decision data of child to be used in activate method. </param>
 /// <returns> True if there's a child which wants to be activated, else false. </returns>
 private bool CheckForInterruptingDecider(
     IAgentData agentData,
     Data data,
     ref int childIdx,
     ref float childDecideValue,
     ref IDecisionData childDecisionData)
 {
     return(this.DecideForFirstPossible(
                agentData, 0, data.ActiveChildIdx, ref childIdx, ref childDecideValue, ref childDecisionData));
 }
        /// <summary>
        ///   Decision function for a boolean condition.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Returns true if the condition is forfilled, else false. </returns>
        protected override bool Decide(IAgentData agentData)
        {
            object attribute = null;
            if (!agentData.Blackboard.TryGetValue(this.BlackboardAttributeKey, out attribute))
            {
                return false;
            }

            // Check that not null.
            return attribute != null;
        }
        public LSAgent CreateAgent(
            string agentCode,
            Vector2d?position = null,  //nullable position
            Vector2d?rotation = null   //Nullable rotation for default parametrz
            )
        {
            Vector2d pos = position != null ? position.Value : new Vector2d(0, 0);
            Vector2d rot = rotation != null ? rotation.Value : Vector2d.radian0;


            if (!IsValidAgentCode(agentCode))
            {
                throw new System.ArgumentException(string.Format("Agent code '{0}' not found.", agentCode));
            }


            FastStack <LSAgent> cache    = CachedAgents [agentCode];
            LSAgent             curAgent = null;
            ushort agentCodeID           = AgentController.GetAgentCodeIndex(agentCode);

            if (cache.IsNotNull() && cache.Count > 0)
            {
                curAgent = cache.Pop();

                TypeAgentsActive[agentCodeID][curAgent.TypeIndex] = true;
            }
            else
            {
                IAgentData interfacer = AgentController.CodeInterfacerMap [agentCode];

                curAgent = GameObject.Instantiate(interfacer.GetAgent().gameObject).GetComponent <LSAgent>();
                curAgent.Setup(interfacer);


                FastList <bool> typeActive;
                if (!AgentController.TypeAgentsActive.TryGetValue(agentCodeID, out typeActive))
                {
                    typeActive = new FastList <bool>();
                    TypeAgentsActive.Add(agentCodeID, typeActive);
                }
                FastList <LSAgent> typeAgents;
                if (!TypeAgents.TryGetValue(agentCodeID, out typeAgents))
                {
                    typeAgents = new FastList <LSAgent>();
                    TypeAgents.Add(agentCodeID, typeAgents);
                }

                curAgent.TypeIndex = (ushort)typeAgents.Count;
                typeAgents.Add(curAgent);
                typeActive.Add(true);
            }
            InitializeAgent(curAgent, pos, rot);
            return(curAgent);
        }
Exemple #33
0
        protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID)
        {
            if (m_SimulationService == null)
            {
                m_log.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless.");
                responsedata["content_type"]        = "application/json";
                responsedata["int_response_code"]   = HttpStatusCode.NotImplemented;
                responsedata["str_response_string"] = string.Empty;

                return;
            }

            GridRegion destination = new GridRegion();

            destination.RegionID = regionID;

            IAgentData agent     = null;
            bool       result    = m_SimulationService.RetrieveAgent(destination, id, out agent);
            OSDMap     map       = null;
            string     strBuffer = "";

            if (result)
            {
                if (agent != null) // just to make sure
                {
                    map = agent.Pack();
                    try
                    {
                        strBuffer = OSDParser.SerializeJsonString(map);
                    }
                    catch (Exception e)
                    {
                        m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.ToString());
                        responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
                        // ignore. buffer will be empty, caller should check.
                    }
                }
                else
                {
                    map           = new OSDMap();
                    map["Result"] = "Internal error";
                }
            }
            else
            {
                map           = new OSDMap();
                map["Result"] = "Not Found";
            }
            strBuffer = OSDParser.SerializeJsonString(map);

            responsedata["content_type"]        = "application/json";
            responsedata["int_response_code"]   = HttpStatusCode.OK;
            responsedata["str_response_string"] = strBuffer;
        }
Exemple #34
0
        public void Excute(IAgentData data)
        {
            if (root == null)
            {
                return;
            }

            lastState  = curState;
            lastAction = curAction;
            root.Excute(data, this);
        }
        /// <summary>
        ///   Per frame update.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after this update. </returns>
        public override ExecutionStatus Update(IAgentData agentData)
        {
            // Get key of attribute to remove.
            object key = this.GetBlackboardAttributeKey(agentData);
            if (key != null)
            {
                // Remove attribute.
                agentData.Blackboard.RemoveValue(key);
            }

            return ExecutionStatus.Success;
        }
        /// <summary>
        ///   Deactivation.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        public override void Deactivate(IAgentData agentData)
        {
            Data data = agentData.GetTaskData<Data>();

            // Deactivate child if running.
            if (data.Status == ExecutionStatus.Running)
            {
                this.DeactivateChild(agentData);
            }

            agentData.CurrentTaskData = null;
        }
        /// <summary>
        ///   Deactivation.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        public override void Deactivate(IAgentData agentData)
        {
            Data data = agentData.GetTaskData<Data>();

            // Setup blackboard.
            Setup(agentData, data);

            // Deactivate child.
            this.DeactivateChild(agentData);

            // Tear down.
            TearDown(agentData, data);
        }
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Execution status after activation. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            Data data = new Data();
            data.Status = this.ActivateChild(agentData, decisionData);
            if (data.Status == ExecutionStatus.Failed)
            {
                return ExecutionStatus.Failed;
            }

            agentData.CurrentTaskData = data;

            return ExecutionStatus.Running;
        }
        /// <summary>
        ///   Per frame update.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after this update. </returns>
        public override ExecutionStatus Update(IAgentData agentData)
        {
            // Get value from blackboard.
            object attribute = null;
            if (!agentData.Blackboard.TryGetValue(this.SourceAttributeKey, out attribute))
            {
                return ExecutionStatus.Failed;
            }

            // Set value to target key.
            agentData.Blackboard.SetValue(this.TargetAttributeKey, attribute);

            return ExecutionStatus.Success;
        }
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Execution status after activation. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            Data data = new Data { Status = ExecutionStatus.Failed };

            // Check if child wants to run.
            float childDecisionValue = this.DecideChild(agentData, ref decisionData);
            if (childDecisionValue > 0.0f)
            {
                data.Status = this.ActivateChild(agentData, decisionData);
            }

            agentData.CurrentTaskData = data;

            return ExecutionStatus.Running;
        }
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Execution status after activation. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            DecisionData taskDecisionData = (DecisionData)decisionData;

            // Create child blackboard.
            Data data = new Data { Blackboard = taskDecisionData.Blackboard, PreviousBlackboard = agentData.Blackboard };
            agentData.CurrentTaskData = data;

            // Setup blackboard.
            Setup(agentData, data);

            // Activate child.
            ExecutionStatus result = this.ActivateChild(agentData, taskDecisionData.ChildDecisionData);
            if (result != ExecutionStatus.Running)
            {
                // Tear down.
                TearDown(agentData, data);
            }

            return result;
        }
        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Execution status after activation. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            Blackboard blackboard = agentData.Blackboard;
            if (blackboard.Parents == null)
            {
                return ExecutionStatus.Failed;
            }

            // Find attribute on parent blackboard.
            foreach (Blackboard parent in blackboard.Parents)
            {
                object attribute = null;
                if (parent.TryGetValue(this.AttributeKey, out attribute))
                {
                    // Set attribute on blackboard.
                    blackboard.SetValue(this.AttributeKey, attribute);

                    return ExecutionStatus.Success;
                }
            }

            return ExecutionStatus.Failed;
        }
        /// <summary>
        ///   Per frame update.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after this update. </returns>
        public override ExecutionStatus Update(IAgentData agentData)
        {
            Data data = agentData.CurrentTaskData as Data;
            if (data.Status == ExecutionStatus.Running)
            {
                data.Status = this.UpdateChild(agentData);
            }
            else
            {
                // Restart if still possible.
                IDecisionData decisionData = null;
                float decisionValue = this.Task.Decide(agentData, ref decisionData);
                if (decisionValue > 0.0f)
                {
                    data.Status = this.ActivateChild(agentData, decisionData);
                    if (data.Status == ExecutionStatus.Running)
                    {
                        data.Status = this.UpdateChild(agentData);
                    }
                }
            }

            return data.Status == ExecutionStatus.Failed ? ExecutionStatus.Failed : ExecutionStatus.Running;
        }
Exemple #44
0
        public bool DoChildAgentUpdateCall(RegionInfo region, IAgentData cAgentData)
        {
            // Eventually, we want to use a caps url instead of the agentID
            string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + cAgentData.AgentID + "/";
            //Console.WriteLine("   >>> DoChildAgentUpdateCall <<< " + uri);

            HttpWebRequest ChildUpdateRequest = (HttpWebRequest)WebRequest.Create(uri);
            ChildUpdateRequest.Method = "PUT";
            ChildUpdateRequest.ContentType = "application/json";
            ChildUpdateRequest.Timeout = AGENT_UPDATE_TIMEOUT;
            //ChildUpdateRequest.KeepAlive = false;
            ChildUpdateRequest.Headers["authorization"] = GenerateAuthorization();

            // Fill it in
            OSDMap args = null;
            try
            {
                args = cAgentData.Pack();
            }
            catch (Exception e)
            {
                m_log.Error("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message);
                return false;
            }

            // Add the regionhandle of the destination region
            ulong regionHandle = GetRegionHandle(region.RegionHandle);
            args["destination_handle"] = OSD.FromString(regionHandle.ToString());

            string strBuffer = "";
            byte[] buffer = new byte[1];
            try
            {
                strBuffer = OSDParser.SerializeJsonString(args);
                UTF8Encoding str = new UTF8Encoding();
                buffer = str.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[REST COMMS]: Exception thrown on serialization of ChildUpdate: {0}", e.Message);
                // ignore. buffer will be empty, caller should check.
            }

            Stream os = null;
            try
            { // send the Post
                ChildUpdateRequest.ContentLength = buffer.Length;   //Count bytes to send
                os = ChildUpdateRequest.GetRequestStream();
                os.Write(buffer, 0, strBuffer.Length);         //Send it
                os.Close();
                //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
            }
            catch (WebException)
            {
                // Normal case of network error connecting to a region (e.g. a down one)
                return false;
            }
            catch (Exception ex)
            {
                m_log.ErrorFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
                return false;
            }

            // Let's wait for the response
//            m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
            try
            {
                WebResponse webResponse = ChildUpdateRequest.GetResponse();
                if (webResponse != null)
                {
                    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                    string reply = sr.ReadToEnd().Trim();
                    sr.Close();
                    //m_log.InfoFormat("[REST COMMS]: ChildAgentUpdate reply was {0} ", reply);
                    bool rc = false;
                    if (!bool.TryParse(reply, out rc))
                        rc = false;
                    return rc;
                }
                m_log.Info("[REST COMMS]: Null reply on ChildAgentUpdate post");
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on reply of ChildAgentUpdate {0}", ex.Message);
            }
            return false;
        }
        /// <summary>
        /// Not sure what sequence causes this function to be invoked. The only calling
        /// path is through the GET method 
        /// </summary>
        public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
        {
            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: RetrieveAgent start");

            agent = null;

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + id + "/" + destination.RegionID.ToString() + "/";

            try
            {
                OSDMap result = WebUtil.GetFromService(uri, 10000);
                if (result["Success"].AsBoolean())
                {
                    // OSDMap args = Util.GetOSDMap(result["_RawResult"].AsString());
                    OSDMap args = (OSDMap)result["_Result"];
                    if (args != null)
                    {
                        agent = new CompleteAgentData();
                        agent.Unpack(args, null);
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
            }

            return false;
        }
        /// <summary>
        /// This is the worker function to send AgentData to a neighbor region
        /// </summary>
        private bool UpdateAgent(GridRegion destination, IAgentData cAgentData, int timeout)
        {
            // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: UpdateAgent start");

            // Eventually, we want to use a caps url instead of the agentID
            string uri = destination.ServerURI + AgentPath() + cAgentData.AgentID + "/";

            try
            {
                OSDMap args = cAgentData.Pack();

                args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
                args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
                args["destination_name"] = OSD.FromString(destination.RegionName);
                args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());

                OSDMap result = WebUtil.PutToServiceCompressed(uri, args, timeout);
                if (result["Success"].AsBoolean())
                    return true;

                result = WebUtil.PutToService(uri, args, timeout);

                return result["Success"].AsBoolean();
            }
            catch (Exception e)
            {
                m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
            }

            return false;
        }
Exemple #47
0
        public virtual bool IncomingRetrieveRootAgent(UUID id, out IAgentData agent)
        {
            agent = null;
            ScenePresence sp = GetScenePresence(id);
            if ((sp != null) && (!sp.IsChildAgent))
            {
                sp.IsChildAgent = true;
                return sp.CopyAgent(out agent);
            }

            return false;
        }
        public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
        {
            agent = null;

            if (destination == null)
                return false;

            foreach (Scene s in m_sceneList)
            {
                if (s.RegionInfo.RegionID == destination.RegionID)
                {
                    //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
                    IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule> ();
                    if (transferModule != null)
                        return transferModule.IncomingRetrieveRootAgent (s, id, out agent);
                }
            }
            //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
            return false;
        }
 public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent)
 {
     agent = null;
     foreach (Scene s in m_sceneList)
     {
         if (s.RegionInfo.RegionHandle == regionHandle)
         {
             //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
             return s.IncomingRetrieveRootAgent(id, out agent);
         }
     }
     //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
     return false;
 }
 /// <summary>
 ///   Depending on the group policy of its parent, the floating point return value indicates whether the decider will be activated.
 /// </summary>
 /// <param name="agentData"> Agent data. </param>
 /// <param name="decisionData"> Decision data to use in activate method. </param>
 /// <returns> Floating point value used to decide if the decider will be activated. </returns>
 public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
 {
     return this.Decide(agentData) ? 1.0f : 0.0f;
 }
        public void SendChildAgentUpdate(IAgentData childAgentUpdate, UUID regionID)
        {
            if (!m_KnownNeighbors.ContainsKey(regionID))
                return;

            Util.FireAndForget(delegate(object o)
            {
                //Send the updates to all known neighbors
                foreach (GridRegion region in m_KnownNeighbors[regionID])
                {
                    if (childAgentUpdate is AgentData)
                        m_simService.UpdateAgent(region, (AgentData)childAgentUpdate);
                    else
                        m_simService.UpdateAgent(region, (AgentPosition)childAgentUpdate);
                }
            });
        }
        private bool UpdateAgent(GridRegion destination, IAgentData cAgentData)
        {
            // Try local first
            if (cAgentData is AgentData)
            {
                if (m_localBackend.UpdateAgent(destination, (AgentData) cAgentData))
                    return true;
            }
            else if (cAgentData is AgentPosition)
            {
                if (m_localBackend.UpdateAgent(destination, (AgentPosition) cAgentData))
                    return true;
            }

            // else do the remote thing
            if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
            {
                // Eventually, we want to use a caps url instead of the agentID
                string uri = MakeUri(destination, true) + cAgentData.AgentID + "/";

                if (m_blackListedRegions.ContainsKey(uri))
                {
                    //Check against time
                    if (m_blackListedRegions[uri] > 3 &&
                        Util.EnvironmentTickCountSubtract(m_blackListedRegions[uri]) > 0)
                    {
                        MainConsole.Instance.Warn("[SimServiceConnector]: Blacklisted region " + destination.RegionName + " requested");
                        //Still blacklisted
                        return false;
                    }
                }
                try
                {
                    OSDMap args = cAgentData.Pack();

                    args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
                    args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
                    args["destination_name"] = OSD.FromString(destination.RegionName);
                    args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());

                    OSDMap result = WebUtils.PutToService(uri, args, true, true, false);
                    if (!result["Success"].AsBoolean())
                    {
                        if (m_blackListedRegions.ContainsKey(uri))
                        {
                            if (m_blackListedRegions[uri] == 3)
                            {
                                //add it to the blacklist as the request completely failed 3 times
                                m_blackListedRegions[uri] = Util.EnvironmentTickCount() + 60*1000; //60 seconds
                            }
                            else if (m_blackListedRegions[uri] == 0)
                                m_blackListedRegions[uri]++;
                        }
                        else
                            m_blackListedRegions[uri] = 0;
                        return result["Success"].AsBoolean();
                    }
                    //Clear out the blacklist if it went through
                    m_blackListedRegions.Remove(uri);

                    OSDMap innerResult = (OSDMap) result["_Result"];
                    return innerResult["Updated"].AsBoolean();
                }
                catch (Exception e)
                {
                    MainConsole.Instance.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e);
                }

                return false;
            }

            return false;
        }
 /// <summary>
 ///   Should return the key of the blackboard attribute to remove.
 /// </summary>
 /// <param name="agentData"> Agent data. </param>
 /// <returns> Key of the blackboard attribute to remove. </returns>
 protected abstract object GetBlackboardAttributeKey(IAgentData agentData);
 /// <summary>
 ///   Decision function for a boolean condition.
 /// </summary>
 /// <param name="agentData"> Agent data. </param>
 /// <returns> Returns true if the condition is forfilled, else false. </returns>
 protected abstract bool Decide(IAgentData agentData);
Exemple #55
0
        public bool DoRetrieveRootAgentCall(RegionInfo region, UUID id, out IAgentData agent)
        {
            agent = null;
            // Eventually, we want to use a caps url instead of the agentID
            string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
            //Console.WriteLine("   >>> DoRetrieveRootAgentCall <<< " + uri);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "GET";
            request.Timeout = 10000;
            //request.Headers.Add("authorization", ""); // coming soon
            request.Headers["authorization"] = GenerateAuthorization();

            HttpWebResponse webResponse = null;
            string reply = string.Empty;
            try
            {
                webResponse = (HttpWebResponse)request.GetResponse();
                if (webResponse == null)
                {
                    m_log.Info("[REST COMMS]: Null reply on agent get ");
                    return false;
                }

                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                reply = sr.ReadToEnd().Trim();
                sr.Close();
                //Console.WriteLine("[REST COMMS]: ChildAgentUpdate reply was " + reply);
            }
            catch (WebException ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message);
                // ignore, really
                return false;
            }

            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                // we know it's jason
                OSDMap args = GetOSDMap(reply);
                if (args == null)
                {
                    //Console.WriteLine("[REST COMMS]: Error getting OSDMap from reply");
                    return false;
                }

                agent = new CompleteAgentData();
                agent.Unpack(args);
                return true;
            }

            //Console.WriteLine("[REST COMMS]: DoRetrieveRootAgentCall returned status " + webResponse.StatusCode);
            return false;
        }
 /// <summary>
 ///   Depending on the group policy of its parent, the floating point return value indicates whether the decider will be activated.
 /// </summary>
 /// <param name="agentData"> Agent data. </param>
 /// <param name="decisionData"> Decision data to use in activate method. </param>
 /// <returns> Floating point value used to decide if the decider will be activated. </returns>
 public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
 {
     ITask task = this.GetTask(agentData);
     return task == null ? 0.0f : task.Decide(agentData, ref decisionData);
 }
Exemple #57
0
 public bool CopyAgent(out IAgentData agent)
 {
     agent = new CompleteAgentData();
     CopyTo((AgentData)agent);
     return true;
 }
        public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
        {
            agent = null;

            if (destination == null)
                return false;

            // Try local first
            if (m_localBackend.RetrieveAgent(destination, id, out agent))
                return true;

            // else do the remote thing
            if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
                return m_remoteConnector.RetrieveAgent(destination, id, out agent);

            return false;

        }
        public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent)
        {
            // Try local first
            if (m_localBackend.SendRetrieveRootAgent(regionHandle, id, out agent))
                return true;

            // else do the remote thing
            if (!m_localBackend.IsLocalRegion(regionHandle))
            {
                RegionInfo regInfo = m_commsManager.GridService.RequestNeighbourInfo(regionHandle);
                if (regInfo != null)
                {
                    return m_regionClient.DoRetrieveRootAgentCall(regInfo, id, out agent);
                }
                //else
                //    m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
            }
            return false;

        }
        public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
        {
            agent = null;
            // Try local first
            if (m_localBackend.RetrieveAgent(destination, id, out agent))
                return true;

            // else do the remote thing
            if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
            {
                // Eventually, we want to use a caps url instead of the agentID
                string uri = MakeUri(destination, true) + id + "/" + destination.RegionID.ToString() + "/";

                try
                {
                    OSDMap result = WebUtils.GetFromService(uri, true, false, false);
                    if (result["Success"].AsBoolean())
                    {
                        OSDMap r = (OSDMap)OSDParser.DeserializeJson (result["_RawResult"]);
                        if (r["Result"] == "Not Found")
                            return false;
                        agent = new AgentData();
                        agent.Unpack(r);
                        return true;
                    }
                }
                catch (Exception e)
                {
                    m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
                }

                return false;
            }

            return false;
        }