public void LoadActionPlanStep(string actionName, OCAction.OCActionArgs arguments)
            {
                TreeType         treeType       = _ActionNameDictionary[actionName];
                Tree             tree           = _TreeTypeDictionary[treeType];
                OCActionPlanStep actionPlanStep = new OCActionPlanStep();

                actionPlanStep.Behaviour = tree;
                actionPlanStep.Arguments = arguments;
                _ActionPlanQueue.Enqueue(actionPlanStep);
                Debug.Log("Enqueued Action Step: " + actionPlanStep.Arguments.ActionName);
            }
Example #2
0
            public void LoadActionPlanStep(string actionName, OCAction.OCActionArgs arguments)
            {
                Debug.Log("OCActionController::LoadActionPlanStep: " + actionName);
                TreeType         treeType       = _ActionNameDictionary[actionName];
                Tree             tree           = _TreeTypeDictionary[treeType];
                OCActionPlanStep actionPlanStep = OCScriptableObject.CreateInstance <OCActionPlanStep>();

                actionPlanStep.Behaviour = tree;
                actionPlanStep.Arguments = arguments;
                _ActionPlanQueue.AddLast(actionPlanStep);
                Debug.Log("Enqueued Action Step: " + actionPlanStep.Arguments.ActionName);
            }
Example #3
0
            public void LoadActionPlanStep(string actionName, OCAction.OCActionArgs arguments)
            {
                //Debug.Log("OCActionController::LoadActionPlanStep: " + actionName);
                TreeType         treeType       = _ActionNameDictionary[actionName];
                Tree             tree           = _TreeTypeDictionary[treeType];
                OCActionPlanStep actionPlanStep = OCScriptableObject.CreateInstance <OCActionPlanStep>();

                actionPlanStep.Behaviour = tree;
                actionPlanStep.Arguments = arguments;
                _ActionPlanQueue.AddLast(actionPlanStep);
                System.Console.WriteLine(OCLogSymbol.DETAILEDINFO + "Enqueued Action Step: " + actionPlanStep.Arguments.ActionName);
            }
            //---------------------------------------------------------------------------

            #endregion

            //---------------------------------------------------------------------------

            #region Public Member Functions

            //---------------------------------------------------------------------------

            public IEnumerator Start()
            {
                _TreeTypeDictionary = new Dictionary <TreeType, Tree>();
                _ActionPlanQueue    = new Queue <OCActionPlanStep>();

                foreach (TreeType type in Enum.GetValues(typeof(TreeType)).Cast <TreeType>())
                {
                    _TreeTypeDictionary.Add(type, BLOCBehaviours.InstantiateTree(type, this));
                }

                OCAction[] actions = gameObject.GetComponentsInChildren <OCAction>(true);

                foreach (Tree tree in _TreeTypeDictionary.Values)
                {
                    if (tree == null)
                    {
                        continue;
                    }
                    int index = tree.Name.LastIndexOf(".") + 1;
                    if (index < 0 || index > tree.Name.Count())
                    {
                        index = 0;
                    }
                    string treeName = tree.Name.Substring(index);

                    foreach (OCAction action in actions)
                    {
                        if (action.FullName.Contains(treeName) || treeName.Contains("Behaviour"))
                        {
                            int actionTypeID = (int)Enum.Parse(typeof(BLOCBehaviours.ActionType), action.FullName);

                            tree.SetTickForward(actionTypeID, action.ExecuteBehave);
                        }
                    }
                }

                OCActionPlanStep firstStep = new OCActionPlanStep();

                firstStep.Behaviour = _TreeTypeDictionary[_TreeType];
                firstStep.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget);

                _ActionPlanQueue.Enqueue(firstStep);

                RunningActions = new List <string>();
                //RunningActions.Add("StandIdleShow");

                while (Application.isPlaying)
                {
                    yield return(new WaitForSeconds(1.0f / 240.0f));

                    UpdateAI();
                }
            }
	public void UpdateAI()
	{
		_ActionPlanList = _ActionPlanQueue.ToList();		
				
		if(_step == null && _ActionPlanQueue.Count != 0)
		{
			_step = _ActionPlanQueue.First();
			_ActionPlanQueue.RemoveFirst();
			Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry);
		} else if(_step == null && _ActionPlanQueue.Count == 0)
		{
			_PlanSucceeded = true;
			OCActionPlanStep step = OCScriptableObject.CreateInstance<OCActionPlanStep>();
			step.Behaviour = _TreeTypeDictionary[_TreeType];
			step.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget);
					KeyValuePair<string, TreeType> keyValuePair = _ActionNameDictionary.First(s => s.Value == _TreeType);
					step.Arguments.ActionName = keyValuePair.Key;
			_step = step;
		}
				
		BehaveResult result = _step.Behaviour.Tick();
				
//		if((_step.Behaviour.Name == _TreeTypeDictionary[TreeType.Character_IdleShow].Name) && result == BehaveResult.Success)
//		{
//			//iTween itween = _step.Arguments.Source.GetComponent<iTween>();
//			iTween.Stop(_step.Arguments.Source);
//		}		
				
		if(result != BehaveResult.Running)
		{
			OCAction.OCActionArgs args = _step.Arguments; 	
					
//			if((_step.Behaviour.Name != _TreeTypeDictionary[_TreeType].Name) 
//				|| ((_step.Behaviour.Name == _TreeTypeDictionary[_TreeType].Name) 
//					&& (GameObject.Find("EndPointStub").transform.position != Vector3.zero)))
			{
				// if we have a goal...
				if(_step.Arguments.EndTarget != null)
				{
					if(_step.Arguments.EndTarget.transform.position != Vector3.zero)
					{
						_PlanSucceeded &= result == BehaveResult.Success;
					}
							
					Vector3 startPosition = _step.Arguments.StartTarget.transform.position;
					Vector3 endPosition = _step.Arguments.EndTarget.transform.position;
					Vector3 sourcePosition = _step.Arguments.Source.transform.position;
							sourcePosition.y = sourcePosition.y - 0.5f;
								
					Vector3 startToEnd = endPosition - startPosition;
					Vector3 sourceToEnd = endPosition - sourcePosition;		
							
					float startToEndManDist = Math.Abs(endPosition.x - startPosition.x) + Math.Abs(endPosition.y - startPosition.y) + Math.Abs(endPosition.z - startPosition.z);
					float sourceToEndManDist = Math.Abs(endPosition.x - sourcePosition.x) + Math.Abs(endPosition.y - sourcePosition.y) + Math.Abs(endPosition.z - sourcePosition.z);		
							
					if(_step.Behaviour.Name == "Character.Move" || _step.Arguments.ActionName == "walk" || _step.Arguments.ActionName == "jump_toward")
					{
						// don't use euclideon distance
						//_PlanSucceeded |= sourceToEnd.sqrMagnitude < startToEnd.sqrMagnitude;
								
						// use manhattan distance
						//_PlanSucceeded = sourceToEndManDist <= startToEndManDist;

						if(VectorUtil.AreVectorsEqual(sourcePosition, endPosition))
						{
							_PlanSucceeded = true;
						} else
						{
							_PlanSucceeded = false;
						}
					}
							
					if(_step.Behaviour.Name == "Character.Destroy" || _step.Arguments.ActionName == "eat")
					{
						_PlanSucceeded = (endPosition == Vector3.zero || _step.Arguments.EndTarget == null);
					}

					if(_step.Arguments.ActionName == "grab")
					{
						_PlanSucceeded = OCAction.IsEndTargetCloseForward(null, _step.Arguments);
					}
							
//					if(_step.Arguments.ActionName == "grab")
//					{
//						_PlanSucceeded = endPosition != startPosition && endPosition != null;
//					}
							
					if(_step.Arguments.ActionPlanID != null && (_PlanSucceeded || _step.Retry > OCActionPlanStep.MaxRetries))
					{
						OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, _PlanSucceeded);

						if(_step.Behaviour.Name != "Character.IdleShow" && !_step.Behaviour.Name.Contains("Behaviour"))
						{
							Debug.LogWarning("In OCActionController.UpdateAI, Result: " + (_PlanSucceeded ? "Success" : "Failure") + " for Action: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : (_step.Arguments.ActionName + " & Sequence: " + _step.Arguments.SequenceID)));
						}		
					}
//							else if(_step.Arguments.ActionPlanID == null && (_PlanSucceeded || _step.Retry > OCActionPlanStep.MaxRetries) && OCConnectorSingleton.Instance.IsEstablished )
//					{
//								OCConnectorSingleton.Instance.HandleOtherAgentActionResult(_step, _PlanSucceeded);
//					}
				}
						
//				if(!_PlanSucceeded)
//					Debug.LogWarning(" -- Step Failed: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : _step.Arguments.ActionName));						
					

				
				_step.Behaviour.Reset();

				// if we failed, retry last step
				if(_PlanSucceeded == false && OCActionPlanStep.MaxRetries > _step.Retry)
				{
					_ActionPlanQueue.AddFirst(_step);
					_step.Retry += 1;
				} else if(_PlanSucceeded == false && OCActionPlanStep.MaxRetries <= _step.Retry)
				{
					_ActionPlanQueue.Clear();
					_step = null;
				} else if(_step.Arguments.EndTarget)
				{
					OCFadeOutGameObject fadeOut = _step.Arguments.EndTarget.GetComponent<OCFadeOutGameObject>();
					
					if(fadeOut != null)
					{
						fadeOut.enabled = true;
					}
				}
						
				if(_ActionPlanQueue.Count == 0)
				{
					if(_LastPlanID != null)
					{
							
								
//						if(result == BehaveResult.Failure)
//							OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, true);			
								
						OCConnectorSingleton.Instance.SendActionPlanStatus(_LastPlanID, _PlanSucceeded);

						if(_step != null && _step.Arguments.EndTarget != null)
						{
							OCFadeOutGameObject fadeOut = _step.Arguments.EndTarget.GetComponent<OCFadeOutGameObject>();
						
							if(fadeOut != null)
							{
								fadeOut.enabled = true;
							}
						}

						_LastPlanID = null;		
					}
					_step = null;	
				} else if(_LastPlanID != null)
				{
					_step = _ActionPlanQueue.First();
					_ActionPlanQueue.RemoveFirst();
					Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry);
					if(_LastPlanID != _step.Arguments.ActionPlanID)
					{
						Debug.LogError("We've changed plans without reporting back to OpenCog!");
					}
				} else
				{	
					_LastPlanID = _step.Arguments.ActionPlanID;
					_step = _ActionPlanQueue.First();
					_ActionPlanQueue.RemoveFirst();
					Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry);
				}
			}
					
			
		}
		
	}
Example #6
0
            public void UpdateAI()
            {
                _ActionPlanList = _ActionPlanQueue.ToList();

                if (_step == null && _ActionPlanQueue.Count != 0)
                {
                    _step = _ActionPlanQueue.First();
                    _ActionPlanQueue.RemoveFirst();
                    Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry);
                }
                else if (_step == null && _ActionPlanQueue.Count == 0)
                {
                    _PlanSucceeded = true;
                    OCActionPlanStep step = OCScriptableObject.CreateInstance <OCActionPlanStep>();
                    step.Behaviour = _TreeTypeDictionary[_TreeType];
                    step.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget);
                    KeyValuePair <string, TreeType> keyValuePair = _ActionNameDictionary.First(s => s.Value == _TreeType);
                    step.Arguments.ActionName = keyValuePair.Key;
                    _step = step;
                }

                BehaveResult result = _step.Behaviour.Tick();

//		if((_step.Behaviour.Name == _TreeTypeDictionary[TreeType.Character_IdleShow].Name) && result == BehaveResult.Success)
//		{
//			//iTween itween = _step.Arguments.Source.GetComponent<iTween>();
//			iTween.Stop(_step.Arguments.Source);
//		}

                if (result != BehaveResult.Running)
                {
                    OCAction.OCActionArgs args = _step.Arguments;

//			if((_step.Behaviour.Name != _TreeTypeDictionary[_TreeType].Name)
//				|| ((_step.Behaviour.Name == _TreeTypeDictionary[_TreeType].Name)
//					&& (GameObject.Find("EndPointStub").transform.position != Vector3.zero)))
                    {
                        // if we have a goal...
                        if (_step.Arguments.EndTarget != null)
                        {
                            if (_step.Arguments.EndTarget.transform.position != Vector3.zero)
                            {
                                _PlanSucceeded &= result == BehaveResult.Success;
                            }

                            Vector3 startPosition  = _step.Arguments.StartTarget.transform.position;
                            Vector3 endPosition    = _step.Arguments.EndTarget.transform.position;
                            Vector3 sourcePosition = _step.Arguments.Source.transform.position;
                            sourcePosition.y = sourcePosition.y - 0.5f;

                            Vector3 startToEnd  = endPosition - startPosition;
                            Vector3 sourceToEnd = endPosition - sourcePosition;

                            float startToEndManDist  = Math.Abs(endPosition.x - startPosition.x) + Math.Abs(endPosition.y - startPosition.y) + Math.Abs(endPosition.z - startPosition.z);
                            float sourceToEndManDist = Math.Abs(endPosition.x - sourcePosition.x) + Math.Abs(endPosition.y - sourcePosition.y) + Math.Abs(endPosition.z - sourcePosition.z);

                            if (_step.Behaviour.Name == "Character.Move" || _step.Arguments.ActionName == "walk" || _step.Arguments.ActionName == "jump_toward")
                            {
                                // don't use euclideon distance
                                //_PlanSucceeded |= sourceToEnd.sqrMagnitude < startToEnd.sqrMagnitude;

                                // use manhattan distance
                                //_PlanSucceeded = sourceToEndManDist <= startToEndManDist;

                                if (VectorUtil.AreVectorsEqual(sourcePosition, endPosition))
                                {
                                    _PlanSucceeded = true;
                                }
                                else
                                {
                                    _PlanSucceeded = false;
                                }
                            }

                            if (_step.Behaviour.Name == "Character.Destroy" || _step.Arguments.ActionName == "eat")
                            {
                                _PlanSucceeded = (endPosition == Vector3.zero || _step.Arguments.EndTarget == null);
                            }

                            if (_step.Arguments.ActionName == "grab")
                            {
                                _PlanSucceeded = OCAction.IsEndTargetCloseForward(null, _step.Arguments);
                            }

//					if(_step.Arguments.ActionName == "grab")
//					{
//						_PlanSucceeded = endPosition != startPosition && endPosition != null;
//					}

                            if (_step.Arguments.ActionPlanID != null && (_PlanSucceeded || _step.Retry > OCActionPlanStep.MaxRetries))
                            {
                                OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, _PlanSucceeded);

                                if (_step.Behaviour.Name != "Character.IdleShow" && !_step.Behaviour.Name.Contains("Behaviour"))
                                {
                                    Debug.LogWarning("In OCActionController.UpdateAI, Result: " + (_PlanSucceeded ? "Success" : "Failure") + " for Action: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : (_step.Arguments.ActionName + " & Sequence: " + _step.Arguments.SequenceID)));
                                }
                            }
                            else if (_step.Arguments.ActionPlanID == null && (_PlanSucceeded || _step.Retry > OCActionPlanStep.MaxRetries) && OCConnectorSingleton.Instance.IsEstablished)
                            {
                                OCConnectorSingleton.Instance.HandleOtherAgentActionResult(_step, _PlanSucceeded);
                            }
                        }

//				if(!_PlanSucceeded)
//					Debug.LogWarning(" -- Step Failed: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : _step.Arguments.ActionName));



                        _step.Behaviour.Reset();

                        // if we failed, retry last step
                        if (_PlanSucceeded == false && OCActionPlanStep.MaxRetries > _step.Retry)
                        {
                            _ActionPlanQueue.AddFirst(_step);
                            _step.Retry += 1;
                        }
                        else if (_PlanSucceeded == false && OCActionPlanStep.MaxRetries <= _step.Retry)
                        {
                            _ActionPlanQueue.Clear();
                            _step = null;
                        }
                        else if (_step.Arguments.EndTarget)
                        {
                            OCFadeOutGameObject fadeOut = _step.Arguments.EndTarget.GetComponent <OCFadeOutGameObject>();

                            if (fadeOut != null)
                            {
                                fadeOut.enabled = true;
                            }
                        }

                        if (_ActionPlanQueue.Count == 0)
                        {
                            if (_LastPlanID != null)
                            {
//						if(result == BehaveResult.Failure)
//							OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, true);

                                OCConnectorSingleton.Instance.SendActionPlanStatus(_LastPlanID, _PlanSucceeded);

                                if (_step != null && _step.Arguments.EndTarget != null)
                                {
                                    OCFadeOutGameObject fadeOut = _step.Arguments.EndTarget.GetComponent <OCFadeOutGameObject>();

                                    if (fadeOut != null)
                                    {
                                        fadeOut.enabled = true;
                                    }
                                }

                                _LastPlanID = null;
                            }
                            _step = null;
                        }
                        else if (_LastPlanID != null)
                        {
                            _step = _ActionPlanQueue.First();
                            _ActionPlanQueue.RemoveFirst();
                            Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry);
                            if (_LastPlanID != _step.Arguments.ActionPlanID)
                            {
                                Debug.LogError("We've changed plans without reporting back to OpenCog!");
                            }
                        }
                        else
                        {
                            _LastPlanID = _step.Arguments.ActionPlanID;
                            _step       = _ActionPlanQueue.First();
                            _ActionPlanQueue.RemoveFirst();
                            Debug.LogWarning("In OCActionController.UpdateAI, starting action step: " + _step.Arguments.ActionName + ", retry: " + _step.Retry);
                        }
                    }
                }
            }
Example #7
0
            //---------------------------------------------------------------------------

            #endregion

            //---------------------------------------------------------------------------

            #region Public Member Functions

            //---------------------------------------------------------------------------

            public IEnumerator Start()
            {
                _TreeTypeDictionary = new Dictionary <TreeType, Tree>();
                _ActionPlanQueue    = new LinkedList <OCActionPlanStep>();

                foreach (TreeType type in Enum.GetValues(typeof(TreeType)).Cast <TreeType>())
                {
                    _TreeTypeDictionary.Add(type, BLOCBehaviours.InstantiateTree(type, this));
                }

                OCAction[] actions = gameObject.GetComponentsInChildren <OCAction>(true);

                foreach (Tree tree in _TreeTypeDictionary.Values)
                {
                    if (tree == null)
                    {
                        continue;
                    }
                    int index = tree.Name.LastIndexOf(".") + 1;
                    if (index < 0 || index > tree.Name.Count())
                    {
                        index = 0;
                    }
                    string treeName = tree.Name.Substring(index);

                    foreach (OCAction action in actions)
                    {
                        if (((action.FullName.Contains(treeName) || treeName.Contains("Behaviour")) &&
                             !(treeName == "GhostBehaviour" && action.name.Contains("Create")) &&
                             !(treeName == "GhostBehaviour" && action.name.Contains("Destroy"))) ||
                            (treeName == "TurnAndCreate" && action.FullName == "HoldRightHandCreate") ||
                            (treeName == "TurnAndCreate" && action.FullName == "HoldRightHandCreateBelow") ||
                            (treeName == "TurnAndCreate" && action.FullName == "StandTurnLeftMove") ||
                            (treeName == "TurnAndCreate" && action.FullName == "StandTurnRightMove") ||
                            (treeName == "TurnAndCreate" && action.FullName == "StandIdleShow") ||
                            (treeName == "TurnAndCreate" && action.FullName == "FallIdleShow") ||
                            (treeName == "TurnLeftOrRight" && action.FullName == "StandTurnLeftMove") ||
                            (treeName == "TurnLeftOrRight" && action.FullName == "StandTurnRightMove") ||
                            (treeName == "TurnLeftOrRight" && action.FullName == "StandIdleShow") ||
                            (treeName == "TurnLeftOrRight" && action.FullName == "FallIdleShow") ||
                            (treeName == "BothHandsTransfer" && action.FullName == "HoldBothHandsTransfer")
                            )
                        {
                            int actionTypeID = (int)Enum.Parse(typeof(BLOCBehaviours.ActionType), action.FullName);

                            tree.SetTickForward(actionTypeID, action.ExecuteBehave);
                        }
                    }
                }

                OCActionPlanStep firstStep = OCScriptableObject.CreateInstance <OCActionPlanStep>();

                firstStep.Behaviour = _TreeTypeDictionary[_TreeType];
                firstStep.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget);
                KeyValuePair <string, TreeType> keyValuePair = _ActionNameDictionary.First(s => s.Value == _TreeType);

                firstStep.Arguments.ActionName = keyValuePair.Key;

                _ActionPlanQueue.AddLast(firstStep);

                RunningActions = new List <string>();
                //RunningActions.Add("StandIdleShow");

                // vvvv Testing Nil's action for the SantaFe problem vvvv
                /////////////////////////////////////////////////////////////////////////////////

//		XmlDocument doc = new XmlDocument();
//		doc.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n<oc:action-plan xmlns:oc=\"http://www.opencog.org/brain\" demand=\"\" entity-id=\"OAC_AGI_Robot\" id=\"0\">\n<action name=\"step_forward\" sequence=\"1\"/>\n</oc:action-plan>");
//
//		XmlNodeList list = doc.GetElementsByTagName(OCEmbodimentXMLTags.ACTION_PLAN_ELEMENT);
//		XmlElement root = (XmlElement)list.Item(0);//MakeXMLElementRoot(doc);
//
//		CharacterController charControl = gameObject.GetComponent<CharacterController>();
//		bool tryParse = true;

                /////////////////////////////////////////////////////////////////////////////////

                while (Application.isPlaying)
                {
                    yield return(new WaitForSeconds(1.0f / 100.0f));

                    UpdateAI();

//			if(tryParse && charControl.isGrounded)
//			{
//				OCConnectorSingleton.Instance.ParseActionPlanElement(root);
//				tryParse = false;
//			}
                }
            }
            public void UpdateAI()
            {
                _ActionPlanList = _ActionPlanQueue.ToList();

                if (_step == null && _ActionPlanQueue.Count != 0)
                {
                    _step = _ActionPlanQueue.Dequeue();
                }
                else if (_step == null && _ActionPlanQueue.Count == 0)
                {
                    _PlanSucceeded = true;
                    OCActionPlanStep step = new OCActionPlanStep();
                    step.Behaviour = _TreeTypeDictionary[_TreeType];
                    step.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget);
                    _step          = step;
                }

                BehaveResult result = _step.Behaviour.Tick();

//		if((_step.Behaviour.Name == _TreeTypeDictionary[TreeType.Character_IdleShow].Name) && result == BehaveResult.Success)
//		{
//			//iTween itween = _step.Arguments.Source.GetComponent<iTween>();
//			iTween.Stop(_step.Arguments.Source);
//		}

                if (result != BehaveResult.Running)
                {
                    OCAction.OCActionArgs args = _step.Arguments;

//			if((_step.Behaviour.Name != _TreeTypeDictionary[_TreeType].Name)
//				|| ((_step.Behaviour.Name == _TreeTypeDictionary[_TreeType].Name)
//					&& (GameObject.Find("EndPointStub").transform.position != Vector3.zero)))
                    {
                        // if we have a goal...
                        if (_step.Arguments.EndTarget != null)
                        {
                            if (_step.Arguments.EndTarget.transform.position != Vector3.zero)
                            {
                                _PlanSucceeded &= result == BehaveResult.Success;
                            }

                            Vector3 startPosition  = _step.Arguments.StartTarget.transform.position;
                            Vector3 endPosition    = _step.Arguments.EndTarget.transform.position;
                            Vector3 sourcePosition = _step.Arguments.Source.transform.position;

                            Vector3 startToEnd  = endPosition - startPosition;
                            Vector3 sourceToEnd = endPosition - sourcePosition;

                            float startToEndManDist  = Math.Abs(endPosition.x - startPosition.x) + Math.Abs(endPosition.y - startPosition.y) + Math.Abs(endPosition.z - startPosition.z);
                            float sourceToEndManDist = Math.Abs(endPosition.x - sourcePosition.x) + Math.Abs(endPosition.y - sourcePosition.y) + Math.Abs(endPosition.z - sourcePosition.z);

                            if (_step.Behaviour.Name == "Character.Move" || _step.Arguments.ActionName == "walk" || _step.Arguments.ActionName == "jump_toward")
                            {
                                // don't use euclideon distance
                                //_PlanSucceeded |= sourceToEnd.sqrMagnitude < startToEnd.sqrMagnitude;

                                // use manhattan distance
                                _PlanSucceeded = sourceToEndManDist <= startToEndManDist;

                                if (sourcePosition == endPosition)
                                {
                                    _PlanSucceeded = true;
                                }
                            }

                            if (_step.Behaviour.Name == "Character.Destroy" || _step.Arguments.ActionName == "eat")
                            {
                                _PlanSucceeded = endPosition == Vector3.zero;
                            }

                            if (_step.Arguments.ActionName == "grab")
                            {
                                _PlanSucceeded = endPosition != startPosition && endPosition != null;
                            }

                            if (_step.Arguments.ActionPlanID != null)
                            {
                                OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, _PlanSucceeded);
                            }
                        }

//				if(!_PlanSucceeded)
//					Debug.LogWarning(" -- Step Failed: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : _step.Arguments.ActionName));

                        if (_step.Behaviour.Name != "Character.IdleShow" && !_step.Behaviour.Name.Contains("Behaviour"))
                        {
                            Debug.LogWarning("In OCActionController.UpdateAI, Result: " + (_PlanSucceeded ? "Success" : "Failure") + " for Action: " + (_step.Arguments.ActionName == null ? _step.Behaviour.Name : (_step.Arguments.ActionName + " & Sequence: " + _step.Arguments.SequenceID)));
                        }

                        _step.Behaviour.Reset();

                        if (_ActionPlanQueue.Count == 0)
                        {
                            if (_LastPlanID != null)
                            {
//						if(result == BehaveResult.Failure)
//							OCConnectorSingleton.Instance.SendActionStatus(args.ActionPlanID, args.SequenceID, args.ActionName, true);

                                OCConnectorSingleton.Instance.SendActionPlanStatus(_LastPlanID, _PlanSucceeded);
                                _LastPlanID = null;
                            }
                            _step = null;
                        }
                        else if (_LastPlanID != null)
                        {
                            _step = _ActionPlanQueue.Dequeue();
                            if (_LastPlanID != _step.Arguments.ActionPlanID)
                            {
                                Debug.LogError("We've changed plans without reporting back to OpenCog!");
                            }
                        }
                        else
                        {
                            _LastPlanID = _step.Arguments.ActionPlanID;
                            _step       = _ActionPlanQueue.Dequeue();
                        }
                    }
                }
            }
  public void HandleOtherAgentActionResult(OCActionPlanStep step, bool status)
  {
    // don't report actions that game from us.
    // don't report actions without an action summary (these are from trying
    // to do non-existant actions).
		///TODO: Find a different way to check for this...
//    if (ar.avatar == gameObject.GetComponent<Avatar>() || ar.action == null) {
//        //Debug.LogWarning("skipping action result from " + ar.avatar);
//        return;
//    }

    // the corresponding process within OpenCog's embodiment system is in PAI::processAgentActionWithParameters

    string timestamp = GetCurrentTimestamp();
    XmlDocument doc = new XmlDocument();
    XmlElement root = MakeXMLElementRoot(doc);

    XmlElement agentSignal = (XmlElement) root.AppendChild(doc.CreateElement("agent-signal"));
    agentSignal.SetAttribute("id", gameObject.GetInstanceID().ToString());
	agentSignal.SetAttribute("type", OCEmbodimentXMLTags.AVATAR_OBJECT_TYPE);
    agentSignal.SetAttribute("timestamp", timestamp);
    XmlElement actionElement = (XmlElement)agentSignal.AppendChild(doc.CreateElement(OCEmbodimentXMLTags.ACTION_ELEMENT));

		// note that the name and the action-instance-name are different
		// ie: name = kick , while action-instance-name = kick2342
		actionElement.SetAttribute("name", step.Arguments.ActionName);
		actionElement.SetAttribute("action-instance-name", step.Arguments.ActionName + step.ID);
		
		//bool result = (status == ActionResult.Status.SUCCESS ? true : false);
		actionElement.SetAttribute("result-state", status.ToString().ToLower()); //successful or failed
		if (step.Arguments.Source.GetInstanceID() == step.Arguments.StartTarget.GetInstanceID()) {
			actionElement.SetAttribute("target", _brainID);
		} else {
			actionElement.SetAttribute("target", step.Arguments.StartTarget.GetInstanceID().ToString());
		}

		// currently we only process the avatar and ocobject type, other types in EmbodimentXMLTages can is to be added when needed.
		// if you add other types such as BLOCK_OBJECT_TYPE, you should also modify PAI::processAgentActionWithParameters in opencog
		string targetType = step.Arguments.StartTarget.tag;
		if (targetType == "OCA" || targetType == "Player" || targetType == "OCAGI")// it's an avatar
			actionElement.SetAttribute("target-type", OCEmbodimentXMLTags.AVATAR_OBJECT_TYPE);
		else if (targetType == "OCObject") // it's an object
			actionElement.SetAttribute("target-type",OCEmbodimentXMLTags.ORDINARY_OBJECT_TYPE);
		else
			Debug.LogWarning("Error target type: " + targetType + " in action: " + step.Arguments.ActionName);
				 
		XmlElement param = (XmlElement)actionElement.AppendChild(doc.CreateElement("param"));

		if(step.Arguments.EndTarget != null)
		{
			if(step.Arguments.EndTarget.tag == "OCObject" || step.Arguments.EndTarget.tag == "Player")
			{
				param.SetAttribute("type", "entity");
				param.SetAttribute("name", step.Arguments.EndTarget.name);
				XmlElement entityElement = (XmlElement)param.AppendChild(doc.CreateElement(OCEmbodimentXMLTags.ENTITY_ELEMENT));
				entityElement.SetAttribute(OCEmbodimentXMLTags.ID_ATTRIBUTE, step.Arguments.EndTarget.GetInstanceID().ToString());

				if(step.Arguments.EndTarget.tag == "OCObject")
					entityElement.SetAttribute(OCEmbodimentXMLTags.TYPE_ATTRIBUTE, OCEmbodimentXMLTags.ORDINARY_OBJECT_TYPE);
				else
					entityElement.SetAttribute(OCEmbodimentXMLTags.TYPE_ATTRIBUTE, OCEmbodimentXMLTags.AVATAR_OBJECT_TYPE);
			}
			else
			{
				UnityEngine.Vector3 vec = step.Arguments.EndTarget.transform.position;
				param.SetAttribute("type", "vector");
				param.SetAttribute("name", "position");
				XmlElement vectorElement = (XmlElement)param.AppendChild(doc.CreateElement(OCEmbodimentXMLTags.VECTOR_ELEMENT));
				vectorElement.SetAttribute(OCEmbodimentXMLTags.X_ATTRIBUTE, vec.x.ToString());
				vectorElement.SetAttribute(OCEmbodimentXMLTags.Y_ATTRIBUTE, vec.y.ToString());
				vectorElement.SetAttribute(OCEmbodimentXMLTags.Z_ATTRIBUTE, vec.z.ToString());
			}
		}





//		// we can only process the parameter type defined in class ActionParamType both in opencog and unity
//		// currently they are : boolean, int, float, string, vector, rotation, entity
//		// also see opencog/opencog/embodiment/control/perceptionActionInterface/BrainProxyAxon.xsd
//    ArrayList paramList = ar.parameters;
//      
//    if (paramList != null) 
//		{
//		
//			int i;
//			if (targetType == "OCA" || targetType == "Player")
//			{
//				if (ar.action.objectID == ar.avatar.gameObject.GetInstanceID())
//					i = -1;
//				else 
//					i = 0;
//			}
//	    else
//			{
//				i = 0;
//			}
//				
//     foreach (System.Object obj in paramList)
//    	{
//      	XmlElement param = (XmlElement)actionElement.AppendChild(doc.CreateElement("param"));
//			
//				// the first param in pinfo is usually the avator does this action, so we just skip it
//				string paratype = obj.GetType().ToString();
//				if (paratype == "System.Int32") // it's a int
//				{
//					param.SetAttribute("type", "int");
//					param.SetAttribute("name", ar.action.pinfo[i+1].Name);
//					param.SetAttribute("value", obj.ToString());
//				}
//				else if (paratype == "System.Single") // it's a float
//				{
//					param.SetAttribute("type", "float");
//					param.SetAttribute("name", ar.action.pinfo[i+1].Name);
//					param.SetAttribute("value", obj.ToString());
//				}
//				else if (paratype == "System.Boolean") // it's a bool
//				{
//					param.SetAttribute("type", "boolean");
//					param.SetAttribute("name", ar.action.pinfo[i+1].Name);
//				
//					param.SetAttribute("value", obj.ToString().ToLower());
//				}
//				else if (paratype == "System.String")// it's a string
//				{
//					param.SetAttribute("type", "string");
//					param.SetAttribute("name", ar.action.pinfo[i+1].Name);
//					param.SetAttribute("value", obj.ToString());
//				}
//				// it's an entity, we only process the ActionTarget, 
//				// if your parameter is an Entiy, please change it into ActionTarget type first
//				else if (paratype == "ActionTarget") 
//				{
//					param.SetAttribute("type", "entity");
//					param.SetAttribute("name", ar.action.pinfo[i+1].Name);
//					XmlElement entityElement = (XmlElement)param.AppendChild(doc.CreateElement(OCEmbodimentXMLTags.ENTITY_ELEMENT));
//					OCAction.Target entity = obj as OCAction.Target;
//					entityElement.SetAttribute(OCEmbodimentXMLTags.ID_ATTRIBUTE, entity.id.ToString());
//					entityElement.SetAttribute(OCEmbodimentXMLTags.TYPE_ATTRIBUTE, entity.type);
//					
//					// currently it seems not use of OWNER_ID_ATTRIBUTE and OWNER_NAME_ATTRIBUTE, we just skip them
//				}
//				else if ( paratype == "UnityEngine.Vector3") // it's an vector
//				{   
//					UnityEngine.Vector3 vec = (Vector3)obj ;
//					param.SetAttribute("type", "vector");
//					param.SetAttribute("name", ar.action.pinfo[i+1].Name);
//					XmlElement vectorElement = (XmlElement)param.AppendChild(doc.CreateElement(OCEmbodimentXMLTags.VECTOR_ELEMENT));
//					vectorElement.SetAttribute(OCEmbodimentXMLTags.X_ATTRIBUTE, vec.x.ToString());
//					vectorElement.SetAttribute(OCEmbodimentXMLTags.Y_ATTRIBUTE, vec.y.ToString());
//					vectorElement.SetAttribute(OCEmbodimentXMLTags.Z_ATTRIBUTE, vec.z.ToString());
//					
//				}
//				else if ( paratype ==  "IntVect") // it's an vector
//				{   
//					Vector3i vec = (Vector3i)obj ;
//					param.SetAttribute("type", "vector");
//					param.SetAttribute("name", ar.action.pinfo[i+1].Name);
//					XmlElement vectorElement = (XmlElement)param.AppendChild(doc.CreateElement(OCEmbodimentXMLTags.VECTOR_ELEMENT));
//					vectorElement.SetAttribute(OCEmbodimentXMLTags.X_ATTRIBUTE, (vec.X + 0.5f).ToString());
//					vectorElement.SetAttribute(OCEmbodimentXMLTags.Y_ATTRIBUTE, (vec.Y + 0.5f).ToString());
//					vectorElement.SetAttribute(OCEmbodimentXMLTags.Z_ATTRIBUTE, (vec.Z + 0.5f).ToString());
//					
//				}
//				// todo: we don't have a rotation type
//				else 
//				{
//					// we can only process the type define in ActionParamType
//					continue;
//				}
//				              
//	      i++;                
//	    }
//    }

		OCMessage message = new OCMessage(_ID, _brainID, OCMessage.MessageType.STRING, BeautifyXmlText(doc));

    OCLogger.Warn("sending action result from " + _ID + "\n" + BeautifyXmlText(doc));

    lock (_messageSendingLock)
    {
        _messagesToSend.Add(message);
    }
  }
	public void LoadActionPlanStep(string actionName, OCAction.OCActionArgs arguments)
	{
		TreeType treeType = _ActionNameDictionary[actionName];
		Tree tree = _TreeTypeDictionary[treeType];
		OCActionPlanStep actionPlanStep = new OCActionPlanStep();
		actionPlanStep.Behaviour = tree;
		actionPlanStep.Arguments = arguments;
		_ActionPlanQueue.AddLast(actionPlanStep);
		Debug.Log("Enqueued Action Step: " + actionPlanStep.Arguments.ActionName);
	}
	//---------------------------------------------------------------------------

	#endregion

	//---------------------------------------------------------------------------

	#region Public Member Functions

	//---------------------------------------------------------------------------

	public IEnumerator Start()
	{
		_TreeTypeDictionary = new Dictionary<TreeType, Tree>();
		_ActionPlanQueue = new LinkedList<OCActionPlanStep>();
				
		foreach(TreeType type in Enum.GetValues( typeof(TreeType) ).Cast<TreeType>())
		{
			_TreeTypeDictionary.Add(type, BLOCBehaviours.InstantiateTree(type, this));
		}
				
		OCAction[] actions = gameObject.GetComponentsInChildren<OCAction>(true);
				
		foreach(Tree tree in _TreeTypeDictionary.Values)
		{
			if(tree == null)
			{
				continue;
			}
			int index = tree.Name.LastIndexOf(".") + 1;
			if(index < 0 || index > tree.Name.Count())
			{
				index = 0;
			}
			string treeName = tree.Name.Substring(index);					
					
			foreach(OCAction action in actions)
			{
				if(((action.FullName.Contains(treeName) || treeName.Contains("Behaviour")) 
						&& !(treeName == "GhostBehaviour" && action.name.Contains("Create"))
						&& !(treeName == "GhostBehaviour" && action.name.Contains("Destroy")))
					|| (treeName == "TurnAndCreate" && action.FullName == "HoldRightHandCreate")
					|| (treeName == "TurnAndCreate" && action.FullName == "HoldRightHandCreateBelow")
					|| (treeName == "TurnAndCreate" && action.FullName == "StandTurnLeftMove")
					|| (treeName == "TurnAndCreate" && action.FullName == "StandTurnRightMove")
					|| (treeName == "TurnAndCreate" && action.FullName == "StandIdleShow")
					|| (treeName == "TurnAndCreate" && action.FullName == "FallIdleShow")
				  || (treeName == "TurnLeftOrRight" && action.FullName == "StandTurnLeftMove")
					|| (treeName == "TurnLeftOrRight" && action.FullName == "StandTurnRightMove")
					|| (treeName == "TurnLeftOrRight" && action.FullName == "StandIdleShow")
					|| (treeName == "TurnLeftOrRight" && action.FullName == "FallIdleShow")
					|| (treeName == "BothHandsTransfer" && action.FullName == "HoldBothHandsTransfer")
				  )
				{
					int actionTypeID = (int)Enum.Parse(typeof(BLOCBehaviours.ActionType), action.FullName);
							
					tree.SetTickForward(actionTypeID, action.ExecuteBehave);
				}
			}
		}
				
		OCActionPlanStep firstStep = new OCActionPlanStep();
		firstStep.Behaviour = _TreeTypeDictionary[_TreeType];
		firstStep.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget);

		_ActionPlanQueue.AddLast(firstStep);		

		RunningActions = new List<string>();
		//RunningActions.Add("StandIdleShow");

		while(Application.isPlaying)
		{
			yield return new WaitForSeconds(1.0f / 100.0f);
			UpdateAI();
		}
	}
	//---------------------------------------------------------------------------

	#endregion

	//---------------------------------------------------------------------------

	#region Public Member Functions

	//---------------------------------------------------------------------------

	public IEnumerator Start()
	{
		_TreeTypeDictionary = new Dictionary<TreeType, Tree>();
		_ActionPlanQueue = new LinkedList<OCActionPlanStep>();
				
		foreach(TreeType type in Enum.GetValues( typeof(TreeType) ).Cast<TreeType>())
		{
			_TreeTypeDictionary.Add(type, BLOCBehaviours.InstantiateTree(type, this));
		}
				
		OCAction[] actions = gameObject.GetComponentsInChildren<OCAction>(true);
				
		foreach(Tree tree in _TreeTypeDictionary.Values)
		{
			if(tree == null)
			{
				continue;
			}
			int index = tree.Name.LastIndexOf(".") + 1;
			if(index < 0 || index > tree.Name.Count())
			{
				index = 0;
			}
			string treeName = tree.Name.Substring(index);					
					
			foreach(OCAction action in actions)
			{
				if(((action.FullName.Contains(treeName) || treeName.Contains("Behaviour")) 
						&& !(treeName == "GhostBehaviour" && action.name.Contains("Create"))
						&& !(treeName == "GhostBehaviour" && action.name.Contains("Destroy")))
					|| (treeName == "TurnAndCreate" && action.FullName == "HoldRightHandCreate")
					|| (treeName == "TurnAndCreate" && action.FullName == "HoldRightHandCreateBelow")
					|| (treeName == "TurnAndCreate" && action.FullName == "StandTurnLeftMove")
					|| (treeName == "TurnAndCreate" && action.FullName == "StandTurnRightMove")
					|| (treeName == "TurnAndCreate" && action.FullName == "StandIdleShow")
					|| (treeName == "TurnAndCreate" && action.FullName == "FallIdleShow")
				  || (treeName == "TurnLeftOrRight" && action.FullName == "StandTurnLeftMove")
					|| (treeName == "TurnLeftOrRight" && action.FullName == "StandTurnRightMove")
					|| (treeName == "TurnLeftOrRight" && action.FullName == "StandIdleShow")
					|| (treeName == "TurnLeftOrRight" && action.FullName == "FallIdleShow")
					|| (treeName == "BothHandsTransfer" && action.FullName == "HoldBothHandsTransfer")
				  )
				{
					int actionTypeID = (int)Enum.Parse(typeof(BLOCBehaviours.ActionType), action.FullName);
							
					tree.SetTickForward(actionTypeID, action.ExecuteBehave);
				}
			}
		}
				
		OCActionPlanStep firstStep = new OCActionPlanStep();
		firstStep.Behaviour = _TreeTypeDictionary[_TreeType];
		firstStep.Arguments = new OCAction.OCActionArgs(_defaultSource, _defaultStartTarget, _defaultEndTarget);

		_ActionPlanQueue.AddLast(firstStep);		

		RunningActions = new List<string>();
		//RunningActions.Add("StandIdleShow");

		// vvvv Testing Nil's action for the SantaFe problem vvvv
		/////////////////////////////////////////////////////////////////////////////////

//		XmlDocument doc = new XmlDocument();
//		doc.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n<oc:action-plan xmlns:oc=\"http://www.opencog.org/brain\" demand=\"\" entity-id=\"OAC_AGI_Robot\" id=\"0\">\n<action name=\"step_forward\" sequence=\"1\"/>\n</oc:action-plan>");
//		
//		XmlNodeList list = doc.GetElementsByTagName(OCEmbodimentXMLTags.ACTION_PLAN_ELEMENT);
//		XmlElement root = (XmlElement)list.Item(0);//MakeXMLElementRoot(doc);
//
//		CharacterController charControl = gameObject.GetComponent<CharacterController>();
//		bool tryParse = true;

		/////////////////////////////////////////////////////////////////////////////////

		while(Application.isPlaying)
		{
			yield return new WaitForSeconds(1.0f / 100.0f);
			UpdateAI();

//			if(tryParse && charControl.isGrounded)
//			{
//				OCConnectorSingleton.Instance.ParseActionPlanElement(root);
//				tryParse = false;
//			}
		}
	}