コード例 #1
0
        private static object FromStringStruct(Type type, string src)
        {
            object objValue = Activator.CreateInstance(type);
            Dictionary <string, FieldInfo> structMembers = new Dictionary <string, FieldInfo>();

            FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            for (int i = 0; i < fields.Length; ++i)
            {
                FieldInfo f = fields[i];

                if (!f.IsLiteral)
                {
                    structMembers.Add(f.Name, f);
                }
            }

            if (string.IsNullOrEmpty(src))
            {
                return(objValue);
            }

            //{color=0;id=;type={bLive=false;name=0;weight=0;};}
            //the first char is '{'
            //the last char is '}'
            int posCloseBrackets = SkipPairedBrackets(src, 0);

            Debug.Check(posCloseBrackets != -1);

            //{color=0;id=;type={bLive=false;name=0;weight=0;};}
            int posBegin = 1;
            int posEnd   = src.IndexOf(';', posBegin);

            while (posEnd != -1)
            {
                Debug.Check(src[posEnd] == ';');

                //the last one might be empty
                if (posEnd > posBegin)
                {
                    int posEqual = src.IndexOf('=', posBegin);
                    Debug.Check(posEqual > posBegin);

                    int    length      = posEqual - posBegin;
                    string memmberName = src.Substring(posBegin, length);
                    string memberValueStr;
                    char   c = src[posEqual + 1];

                    if (c != '{')
                    {
                        length         = posEnd - posEqual - 1;
                        memberValueStr = src.Substring(posEqual + 1, length);
                    }
                    else
                    {
                        int pStructBegin = 0;
                        pStructBegin += posEqual + 1;
                        int posCloseBrackets_ = SkipPairedBrackets(src, pStructBegin);
                        length = posCloseBrackets_ - pStructBegin + 1;

                        memberValueStr = src.Substring(posEqual + 1, length);

                        posEnd = posEqual + 1 + length;
                    }

                    if (structMembers.ContainsKey(memmberName))
                    {
                        FieldInfo memberType = structMembers[memmberName];
                        Debug.Check(memberType != null);
                        object memberValue = FromString(memberType.FieldType, memberValueStr, false);
                        memberType.SetValue(objValue, memberValue);
                    }
                }

                //skip ';'
                posBegin = posEnd + 1;

                //{color=0;id=;type={bLive=false;name=0;weight=0;};}
                posEnd = src.IndexOf(';', posBegin);

                if (posEnd > posCloseBrackets)
                {
                    break;
                }
            }

            return(objValue);
        }
コード例 #2
0
ファイル: AgentProperties.cs プロジェクト: qipa/behaviac-1
            public override void Run(Agent self)
            {
                Debug.Check(_param0 != null);

                _returnValue.value = behaviac.Agent.VectorLength((System.Collections.IList)_param0.GetValueObject(self));
            }
コード例 #3
0
ファイル: Selector.cs プロジェクト: midgithub/notes
 protected override bool onenter(Agent pAgent)
 {
     Debug.Check(this.m_children.Count > 0);
     this.m_activeChildIndex = 0;
     return(true);
 }
コード例 #4
0
        public EBTStatus exec(Agent pAgent, EBTStatus childStatus)
        {
#if !BEHAVIAC_RELEASE
            Debug.Check(this.m_node == null || this.m_node.IsValid(pAgent, this),
                        string.Format("Agent In BT:{0} while the Agent used for: {1}", this.m_node.GetAgentType(), pAgent.GetClassTypeName()));

            string classStr    = (this.m_node != null ? this.m_node.GetClassNameString() : "BT");
            int    nodeId      = (this.m_node != null ? this.m_node.GetId() : -1);
            string taskClassid = string.Format("{0}[{1}]", classStr, nodeId);

            AutoProfileBlockSend profiler_block = new AutoProfileBlockSend(taskClassid, pAgent);
#endif//#if !BEHAVIAC_RELEASE
            bool bEnterResult = false;

            if (this.m_status == EBTStatus.BT_RUNNING)
            {
                bEnterResult = true;
            }
            else
            {
                //reset it to invalid when it was success/failure
                this.m_status = EBTStatus.BT_INVALID;
                bEnterResult  = this.onenter_action(pAgent);
            }

            if (bEnterResult)
            {
#if !BEHAVIAC_RELEASE
                if (Config.IsLoggingOrSocketing)
                {
                    string btStr = BehaviorTask.GetTickInfo(pAgent, this, "update");

                    //empty btStr is for internal BehaviorTreeTask
                    if (!string.IsNullOrEmpty(btStr))
                    {
                        LogManager.Instance.Log(pAgent, btStr, EActionResult.EAR_none, LogMode.ELM_tick);
                    }
                }
#endif
                bool bValid = this.CheckParentUpdatePreconditions(pAgent);

                if (bValid)
                {
                    this.m_status = this.update_current(pAgent, childStatus);
                }
                else
                {
                    this.m_status = EBTStatus.BT_FAILURE;

                    if (this.GetCurrentTask() != null)
                    {
                        this.update_current(pAgent, EBTStatus.BT_FAILURE);
                    }
                }

                if (this.m_status != EBTStatus.BT_RUNNING)
                {
                    //clear it

                    this.onexit_action(pAgent, this.m_status);

                    //this node is possibly ticked by its parent or by the topBranch who records it as currrent node
                    //so, we can't here reset the topBranch's current node
                }
                else
                {
                    BranchTask tree = this.GetTopManageBranchTask();

                    if (tree != null)
                    {
                        tree.SetCurrentTask(this);
                    }
                }
            }
            else
            {
                this.m_status = EBTStatus.BT_FAILURE;
            }

#if !BEHAVIAC_RELEASE
            profiler_block.Close();
#endif

            return(this.m_status);
        }
コード例 #5
0
 protected override void onexit(Agent pAgent, EBTStatus s)
 {
     Debug.Check(true);
     base.onexit(pAgent, s);
 }
コード例 #6
0
            protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
            {
                int idx = -1;

                if (childStatus != EBTStatus.BT_RUNNING)
                {
                    Debug.Check(this.m_activeChildIndex != CompositeTask.InvalidChildIndex);

                    if (childStatus == EBTStatus.BT_SUCCESS)
                    {
                        return(EBTStatus.BT_SUCCESS);
                    }
                    else if (childStatus == EBTStatus.BT_FAILURE)
                    {
                        //the next for starts from (idx + 1), so that it starts from next one after this failed one
                        idx = this.m_activeChildIndex;
                    }
                    else
                    {
                        Debug.Check(false);
                    }
                }

                //checking the preconditions and take the first action tree
                int index = (int)-1;

                for (int i = (idx + 1); i < this.m_children.Count; ++i)
                {
                    Debug.Check(this.m_children[i] is WithPreconditionTask);
                    WithPreconditionTask pSubTree = (WithPreconditionTask)this.m_children[i];

                    BehaviorTask pre = pSubTree.PreconditionNode;

                    EBTStatus status = pre.exec(pAgent);

                    if (status == EBTStatus.BT_SUCCESS)
                    {
                        index = i;
                        break;
                    }
                }

                //clean up the current ticking action tree
                if (index != (int)-1)
                {
                    if (this.m_activeChildIndex != CompositeTask.InvalidChildIndex &&
                        this.m_activeChildIndex != index)
                    {
                        WithPreconditionTask pCurrentSubTree = (WithPreconditionTask)this.m_children[this.m_activeChildIndex];
                        //BehaviorTask action = pCurrentSubTree.ActionNode;
                        pCurrentSubTree.abort(pAgent);

                        //don't set it here
                        //this.m_activeChildIndex = index;
                    }

                    for (int i = index; i < this.m_children.Count; ++i)
                    {
                        WithPreconditionTask pSubTree = (WithPreconditionTask)this.m_children[i];

                        if (i > index)
                        {
                            BehaviorTask pre    = pSubTree.PreconditionNode;
                            EBTStatus    status = pre.exec(pAgent);

                            //to search for the first one whose precondition is success
                            if (status != EBTStatus.BT_SUCCESS)
                            {
                                continue;
                            }
                        }

                        BehaviorTask action = pSubTree.ActionNode;
                        EBTStatus    s      = action.exec(pAgent);

                        if (s == EBTStatus.BT_RUNNING)
                        {
                            this.m_activeChildIndex = i;
                            pSubTree.m_status       = EBTStatus.BT_RUNNING;
                        }
                        else
                        {
                            pSubTree.m_status = s;

                            if (s == EBTStatus.BT_FAILURE)
                            {
                                //THE ACTION failed, to try the next one
                                continue;
                            }
                        }

                        Debug.Check(s == EBTStatus.BT_RUNNING || s == EBTStatus.BT_SUCCESS);

                        return(s);
                    }
                }

                return(EBTStatus.BT_FAILURE);
            }
コード例 #7
0
        public EBTStatus ParallelUpdate(Agent pAgent, List <BehaviorTask> children)
        {
            bool sawSuccess    = false;
            bool sawFail       = false;
            bool sawRunning    = false;
            bool sawAllFails   = true;
            bool sawAllSuccess = true;

            bool bLoop = (this.m_childFinishPolicy == CHILDFINISH_POLICY.CHILDFINISH_LOOP);

            // go through all m_children
            for (int i = 0; i < children.Count; ++i)
            {
                BehaviorTask pChild = children[i];

                EBTStatus treeStatus = pChild.GetStatus();

                if (bLoop || (treeStatus == EBTStatus.BT_RUNNING || treeStatus == EBTStatus.BT_INVALID))
                {
                    EBTStatus status = pChild.exec(pAgent);

                    if (status == EBTStatus.BT_FAILURE)
                    {
                        sawFail       = true;
                        sawAllSuccess = false;
                    }
                    else if (status == EBTStatus.BT_SUCCESS)
                    {
                        sawSuccess  = true;
                        sawAllFails = false;
                    }
                    else if (status == EBTStatus.BT_RUNNING)
                    {
                        sawRunning    = true;
                        sawAllFails   = false;
                        sawAllSuccess = false;
                    }
                }
                else if (treeStatus == EBTStatus.BT_SUCCESS)
                {
                    sawSuccess  = true;
                    sawAllFails = false;
                }
                else
                {
                    Debug.Check(treeStatus == EBTStatus.BT_FAILURE);

                    sawFail       = true;
                    sawAllSuccess = false;
                }
            }

            EBTStatus result = sawRunning ? EBTStatus.BT_RUNNING : EBTStatus.BT_FAILURE;

            if ((this.m_failPolicy == FAILURE_POLICY.FAIL_ON_ALL && sawAllFails) ||
                (this.m_failPolicy == FAILURE_POLICY.FAIL_ON_ONE && sawFail))
            {
                result = EBTStatus.BT_FAILURE;
            }
            else if ((this.m_succeedPolicy == SUCCESS_POLICY.SUCCEED_ON_ALL && sawAllSuccess) ||
                     (this.m_succeedPolicy == SUCCESS_POLICY.SUCCEED_ON_ONE && sawSuccess))
            {
                result = EBTStatus.BT_SUCCESS;
            }

            //else if (m_failPolicy == FAIL_ON_ALL && m_succeedPolicy == SUCCEED_ON_ALL && sawRunning)
            //{
            //  return EBTStatus.BT_RUNNING;
            //}

            if (this.m_exitPolicy == EXIT_POLICY.EXIT_ABORT_RUNNINGSIBLINGS && (result == EBTStatus.BT_FAILURE || result == EBTStatus.BT_SUCCESS))
            {
                for (int i = 0; i < children.Count; ++i)
                {
                    BehaviorTask pChild = children[i];
                    //Debug.Check(BehaviorTreeTask.DynamicCast(pChild));
                    EBTStatus treeStatus = pChild.GetStatus();

                    if (treeStatus == EBTStatus.BT_RUNNING)
                    {
                        pChild.abort(pAgent);
                    }
                }
            }

            return(result);
        }
コード例 #8
0
        public static IInstanceMember ParseProperty(string value)
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    return(null);
                }

                List <string> tokens   = StringUtils.SplitTokens(value);
                string        typeName = "";

                if (tokens[0] == "const")
                {
                    // const Int32 0
                    Debug.Check(tokens.Count == 3);

                    const int kConstLength = 5;
                    string    strRemaining = value.Substring(kConstLength + 1);
                    int       p            = StringUtils.FirstToken(strRemaining, ' ', ref typeName);

                    typeName = typeName.Replace("::", ".");

                    string strVale = strRemaining.Substring(p + 1);

                    // const
                    return(AgentMeta.CreateInstanceConst(typeName, strVale));
                }
                else
                {
                    string propStr      = "";
                    string indexPropStr = "";

                    if (tokens[0] == "static")
                    {
                        // static float Self.AgentNodeTest::s_float_type_0
                        // static float Self.AgentNodeTest::s_float_type_0[int Self.AgentNodeTest::par_int_type_2]
                        Debug.Check(tokens.Count == 3 || tokens.Count == 4);

                        typeName = tokens[1];
                        propStr  = tokens[2];
                        if (tokens.Count == 4) // array index
                        {
                            indexPropStr = tokens[3];
                        }
                    }
                    else
                    {
                        // float Self.AgentNodeTest::par_float_type_1
                        // float Self.AgentNodeTest::par_float_type_1[int Self.AgentNodeTest::par_int_type_2]
                        Debug.Check(tokens.Count == 2 || tokens.Count == 3);

                        typeName = tokens[0];
                        propStr  = tokens[1];
                        if (tokens.Count == 3) // array index
                        {
                            indexPropStr = tokens[2];
                        }
                    }

                    string          arrayItem   = "";
                    IInstanceMember indexMember = null;
                    if (!string.IsNullOrEmpty(indexPropStr))
                    {
                        arrayItem   = "[]";
                        indexMember = ParseProperty <int>(indexPropStr);
                    }

                    typeName = typeName.Replace("::", ".");
                    propStr  = propStr.Replace("::", ".");

                    string[] props = propStr.Split('.');
                    Debug.Check(props.Length >= 3);

                    string instantceName = props[0];
                    string propName      = props[props.Length - 1];
                    string className     = props[1];

                    for (int i = 2; i < props.Length - 1; ++i)
                    {
                        className += "." + props[i];
                    }

                    uint      classId = Utils.MakeVariableId(className);
                    AgentMeta meta    = AgentMeta.GetMeta(classId);
                    Debug.Check(meta != null);

                    uint propId = Utils.MakeVariableId(propName + arrayItem);

                    // property
                    IProperty p = meta.GetProperty(propId);
                    if (p != null)
                    {
                        return(p.CreateInstance(instantceName, indexMember));
                    }

                    // local var
                    return(AgentMeta.CreateInstanceProperty(typeName, instantceName, indexMember, propId));
                }
            }
            catch (System.Exception e)
            {
                Debug.Check(false, e.Message);
            }

            return(null);
        }
コード例 #9
0
 public static ulong ByteSwap64(ulong i)
 {
     //return (0xFF & i) << 24 | (0xFF00 & i) << 8 | (0xFF0000 & i) >> 8 | (0xFF000000 & i) >> 24;
     Debug.Check(false, "unimplemented");
     return(i);
 }
コード例 #10
0
        public static object FromStringPrimitive(Type type, string valueStr)
        {
            if (valueStr != null)
            {
                if (type == typeof(string) && !string.IsNullOrEmpty(valueStr) &&
                    valueStr.Length > 1 && valueStr[0] == '\"' && valueStr[valueStr.Length - 1] == '\"')
                {
                    valueStr = valueStr.Substring(1, valueStr.Length - 2);
                }

                try
                {
                    TypeConverter converter = TypeDescriptor.GetConverter(type);
                    return(converter.ConvertFromString(valueStr));
                }
                catch
                {
                    if (type == typeof(bool))
                    {
                        bool b;

                        if (bool.TryParse(valueStr, out b))
                        {
                            return(b);
                        }
                    }
                    else if (type == typeof(int))
                    {
                        int i;

                        if (int.TryParse(valueStr, out i))
                        {
                            return(i);
                        }
                    }
                    else if (type == typeof(uint))
                    {
                        uint ui;

                        if (uint.TryParse(valueStr, out ui))
                        {
                            return(ui);
                        }
                    }
                    else if (type == typeof(short))
                    {
                        short s;

                        if (short.TryParse(valueStr, out s))
                        {
                            return(s);
                        }
                    }
                    else if (type == typeof(ushort))
                    {
                        ushort us;

                        if (ushort.TryParse(valueStr, out us))
                        {
                            return(us);
                        }
                    }
                    else if (type == typeof(char))
                    {
                        char c;

                        if (char.TryParse(valueStr, out c))
                        {
                            return(c);
                        }
                    }
                    else if (type == typeof(sbyte))
                    {
                        sbyte sb;

                        if (sbyte.TryParse(valueStr, out sb))
                        {
                            return(sb);
                        }
                    }
                    else if (type == typeof(byte))
                    {
                        byte b;

                        if (byte.TryParse(valueStr, out b))
                        {
                            return(b);
                        }
                    }
                    else if (type == typeof(long))
                    {
                        long l;

                        if (long.TryParse(valueStr, out l))
                        {
                            return(l);
                        }
                    }
                    else if (type == typeof(ulong))
                    {
                        ulong ul;

                        if (ulong.TryParse(valueStr, out ul))
                        {
                            return(ul);
                        }
                    }
                    else if (type == typeof(float))
                    {
                        float f;

                        if (float.TryParse(valueStr, out f))
                        {
                            return(f);
                        }
                    }
                    else if (type == typeof(double))
                    {
                        double d;

                        if (double.TryParse(valueStr, out d))
                        {
                            return(d);
                        }
                    }
                    else if (type == typeof(string))
                    {
                        return(valueStr);
                    }
                    else if (type.IsEnum)
                    {
                        object ret = Enum.Parse(type, valueStr, true);

                        return(ret);
                    }
                    else
                    {
                        Debug.Check(false);
                    }
                }
            }

            return(GetDefaultValue(type));
        }
コード例 #11
0
 public static bool IsAgentType(Type type)
 {
     Debug.Check(type != null);
     return(type == typeof(Agent) || type.IsSubclassOf(typeof(Agent)));
 }
コード例 #12
0
        public static bool ParseForStruct(Type type, string str, ref string strT, Dictionary <string, IInstanceMember> props)
        {
            int pB = 0;
            int i  = 0;

            while (i < str.Length)
            {
                char c = str[i];

                if (c == ';' || c == '{' || c == '}')
                {
                    int p = pB;

                    while (p <= i)
                    {
                        strT += str[p++];
                    }

                    pB = i + 1;
                }
                else if (c == ' ')
                {
                    //par or property
                    string propName = "";
                    int    p        = pB;

                    while (str[p] != '=')
                    {
                        propName += str[p++];
                    }

                    //skip '='
                    Debug.Check(str[p] == '=');
                    p++;

                    string valueStr = str.Substring(p);

                    string typeStr = "";

                    while (str[p] != ' ')
                    {
                        typeStr += str[p++];
                    }

                    //bool bStatic = false;

                    if (typeStr == "static")
                    {
                        //skip ' '
                        Debug.Check(str[p] == ' ');
                        p++;

                        while (str[p] != ' ')
                        {
                            typeStr += str[p++];
                        }

                        //bStatic = true;
                    }

                    string parName = "";

                    //skip ' '
                    Debug.Check(str[i] == ' ');
                    i++;

                    while (str[i] != ';')
                    {
                        parName += str[i++];
                    }

                    props[propName] = AgentMeta.ParseProperty(valueStr);

                    //skip ';'
                    Debug.Check(str[i] == ';');

                    pB = i + 1;
                }

                i++;
            }

            return(true);
        }
コード例 #13
0
        public static List <string> SplitTokens(string str)
        {
            List <string> ret = new List <string>();

            // "const string \"test string\""
            // "const int 10"
            // "int Self.AgentArrayAccessTest::ListInts[int Self.AgentArrayAccessTest::l_index]"

            if (str.StartsWith("const string "))
            {
                ret.Add("const");
                ret.Add("string");
                ret.Add(str.Substring(13));

                return(ret);
            }

            int pB = 0;
            int i  = 0;

            bool bBeginIndex = false;

            while (i < str.Length)
            {
                bool bFound = false;
                char c      = str[i];

                if (c == ' ' && !bBeginIndex)
                {
                    bFound = true;
                }
                else if (c == '[')
                {
                    bBeginIndex = true;
                    bFound      = true;
                }
                else if (c == ']')
                {
                    bBeginIndex = false;
                    bFound      = true;
                }

                if (bFound)
                {
                    string strT = ReadToken(str, pB, i);
                    Debug.Check(strT.Length > 0);
                    ret.Add(strT);

                    pB = i + 1;
                }

                i++;
            }

            string t = ReadToken(str, pB, i);

            if (t.Length > 0)
            {
                ret.Add(t);
            }

            return(ret);
        }
コード例 #14
0
        private static object FromStringVector(Type type, string src)
        {
            Type  vectorType = typeof(List <>).MakeGenericType(type);
            IList objVector  = (IList)Activator.CreateInstance(vectorType);

            if (string.IsNullOrEmpty(src))
            {
                return(objVector);
            }

            int semiColon = src.IndexOf(':');

            Debug.Check(semiColon != -1);
            string countStr = src.Substring(0, semiColon);
            int    count    = int.Parse(countStr);

            int b   = semiColon + 1;
            int sep = b;

            if (b < src.Length && src[b] == '{')
            {
                sep = SkipPairedBrackets(src, b);
                Debug.Check(sep != -1);
            }

            sep = src.IndexOf('|', sep);

            while (sep != -1)
            {
                int    len        = sep - b;
                string elemStr    = src.Substring(b, len);
                object elemObject = FromString(type, elemStr, false);

                objVector.Add(elemObject);

                b = sep + 1;

                if (b < src.Length && src[b] == '{')
                {
                    sep = SkipPairedBrackets(src, b);
                    Debug.Check(b != -1);
                }
                else
                {
                    sep = b;
                }

                sep = src.IndexOf('|', sep);
            }

            if (b < src.Length)
            {
                int    len        = src.Length - b;
                string elemStr    = src.Substring(b, len);
                object elemObject = FromString(type, elemStr, false);

                objVector.Add(elemObject);
            }

            Debug.Check(objVector.Count == count);

            return(objVector);
        }
コード例 #15
0
        //private static bool MemberCompare(object left, object right)
        //{
        //    if (Object.ReferenceEquals(left, right))
        //        return true;

        //    if (left == null || right == null)
        //        return false;

        //    Type type = left.GetType();
        //    if (type != right.GetType())
        //        return false;

        //    if (left as ValueType != null)
        //        return left.Equals(right);

        //    if (left as IEnumerable != null)
        //    {
        //        IEnumerator rightEnumerator = (right as IEnumerable).GetEnumerator();
        //        rightEnumerator.Reset();
        //        foreach (object leftItem in left as IEnumerable)
        //        {
        //            if (!rightEnumerator.MoveNext())
        //            {
        //                return false;
        //            }
        //            else
        //            {
        //                if (!MemberCompare(leftItem, rightEnumerator.Current))
        //                    return false;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        Debug.Check(false);
        //    }

        //    return true;
        //}

        public static bool Compare <T>(T left, T right, EOperatorType comparisonType)
        {
            Type type = typeof(T);

            if (Utils.IsCustomStructType(type))
            {
                //bool bEqual = MemberCompare(left, right);
                bool bEqual = Operator <T> .MemberEqual(left, right);

                switch (comparisonType)
                {
                case EOperatorType.E_EQUAL: return(bEqual);

                case EOperatorType.E_NOTEQUAL: return(!bEqual);
                }
            }
            else if (Utils.IsArrayType(type))
            {
                //bool bEqual = MemberCompare(left, right);
                bool bEqual = Operator <T> .ItemEqual(left, right);

                switch (comparisonType)
                {
                case EOperatorType.E_EQUAL: return(bEqual);

                case EOperatorType.E_NOTEQUAL: return(!bEqual);
                }
            }
            else if (Utils.IsStringType(type) || type == typeof(bool))
            {
                switch (comparisonType)
                {
                case EOperatorType.E_EQUAL: return(Operator <T> .Equal(left, right));

                case EOperatorType.E_NOTEQUAL: return(Operator <T> .NotEqual(left, right));
                }
            }
            else if (Utils.IsEnumType(type) || type == typeof(char))
            {
                int iLeft  = Convert.ToInt32(left);
                int iRight = Convert.ToInt32(right);

                switch (comparisonType)
                {
                case EOperatorType.E_EQUAL: return(Operator <int> .Equal(iLeft, iRight));

                case EOperatorType.E_NOTEQUAL: return(Operator <int> .NotEqual(iLeft, iRight));

                case EOperatorType.E_GREATER: return(Operator <int> .GreaterThan(iLeft, iRight));

                case EOperatorType.E_GREATEREQUAL: return(Operator <int> .GreaterThanOrEqual(iLeft, iRight));

                case EOperatorType.E_LESS: return(Operator <int> .LessThan(iLeft, iRight));

                case EOperatorType.E_LESSEQUAL: return(Operator <int> .LessThanOrEqual(iLeft, iRight));
                }
            }
            else
            {
                switch (comparisonType)
                {
                case EOperatorType.E_EQUAL: return(Operator <T> .Equal(left, right));

                case EOperatorType.E_NOTEQUAL: return(Operator <T> .NotEqual(left, right));

                case EOperatorType.E_GREATER: return(Operator <T> .GreaterThan(left, right));

                case EOperatorType.E_GREATEREQUAL: return(Operator <T> .GreaterThanOrEqual(left, right));

                case EOperatorType.E_LESS: return(Operator <T> .LessThan(left, right));

                case EOperatorType.E_LESSEQUAL: return(Operator <T> .LessThanOrEqual(left, right));
                }
            }

            Debug.Check(false);
            return(false);
        }
コード例 #16
0
        private void ThreadFunc()
        {
            Log("behaviac: Socket Thread Starting\n");

            try
            {
                this.ReserveThreadPacketBuffer();
                int bufferIndex = t_packetBufferIndex;
                Debug.Check(bufferIndex > 0);

                bool   blockingSocket = true;
                Socket serverSocket   = null;

                try
                {
                    serverSocket = SocketBase.Create(blockingSocket);

                    if (serverSocket == null)
                    {
                        Log("behaviac: Couldn't create server socket.\n");
                        return;
                    }

                    string bufferTemp = string.Format("behaviac: Listening at port {0}...\n", m_port);
                    Log(bufferTemp);

                    // max connections: 1, don't allow multiple clients?
                    if (!SocketBase.Listen(serverSocket, m_port, 1))
                    {
                        Log("behaviac: Couldn't configure server socket.\n");
                        SocketBase.Close(ref serverSocket);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex.Message);
                }

                while (m_terminating.Get() == 0)
                {
                    //wait for connecting
                    while (m_terminating.Get() == 0)
                    {
                        if (SocketBase.TestConnection(serverSocket))
                        {
                            break;
                        }

                        System.Threading.Thread.Sleep(100);
                    }

                    if (m_terminating.Get() == 0)
                    {
                        Log("behaviac: accepting...\n");

                        try
                        {
                            m_writeSocket = SocketBase.Accept(serverSocket, SocketConnection.kSocketBufferSize);

                            if (m_writeSocket == null)
                            {
                                Log("behaviac: Couldn't create write socket.\n");
                                SocketBase.Close(ref serverSocket);
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.LogError(ex.Message);
                        }

                        try
                        {
                            m_isConnected.AtomicInc();
                            System.Threading.Thread.Sleep(1);

                            OnConnection();

                            m_isConnectedFinished.AtomicInc();
                            System.Threading.Thread.Sleep(1);

                            //this.OnConnectionFinished();

                            Log("behaviac: Connected. accepted\n");
                        }
                        catch (Exception ex)
                        {
                            Debug.LogError(ex.Message);
                        }

                        try
                        {
                            while (m_terminating.Get() == 0 && this.m_writeSocket != null)
                            {
                                System.Threading.Thread.Sleep(1);

                                this.SendAllPackets();
                                this.ReceivePackets("");
                            }

                            if (this.m_writeSocket != null && this.m_writeSocket.Connected)
                            {
                                // One last time, to send any outstanding packets out there.
                                this.SendAllPackets();
                            }

                            SocketBase.Close(ref this.m_writeSocket);
                            this.Clear();

                            Log("behaviac: disconnected. \n");
                        }
                        catch (Exception ex)
                        {
                            Debug.LogError(ex.Message + ex.StackTrace);
                        }
                    }
                }//while (!m_terminating)

                SocketBase.Close(ref serverSocket);

                this.Clear();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
            }

            Log("behaviac: ThreadFunc exited. \n");
        }
コード例 #17
0
 protected override BehaviorTask createTask()
 {
     Debug.Check(false);
     return(null);
 }
コード例 #18
0
ファイル: AgentState.cs プロジェクト: q3640850400/Dream1
        public virtual void AddVariable(uint varId, IInstantiatedVariable pVar, int stackIndex)
        {
            Debug.Check(!this.m_variables.ContainsKey(varId));

            this.m_variables[varId] = pVar;
        }
コード例 #19
0
            protected override void addChild(BehaviorTask pBehavior)
            {
                base.addChild(pBehavior);

                Debug.Check(pBehavior is WithPreconditionTask);
            }
コード例 #20
0
            protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
            {
                //checking the preconditions and take the first action tree
                int index = (int)-1;

                for (int i = 0; i < this.m_children.Count; ++i)
                {
                    WithPreconditionTask pSubTree = (WithPreconditionTask)this.m_children[i];
                    Debug.Check(pSubTree is WithPreconditionTask);

                    BehaviorTask pPrecondTree = pSubTree.PreconditionNode();

                    EBTStatus status = pPrecondTree.exec(pAgent);

                    if (status == EBTStatus.BT_SUCCESS)
                    {
                        index = i;
                        break;
                    }
                }

                //clean up the current ticking action tree
                if (index != (int)-1)
                {
                    if (this.m_activeChildIndex != CompositeTask.InvalidChildIndex)
                    {
                        WithPreconditionTask pCurrentSubTree = (WithPreconditionTask)this.m_children[this.m_activeChildIndex];
                        Debug.Check(pCurrentSubTree is WithPreconditionTask);
                        BehaviorTask pCurrentActionTree = pCurrentSubTree.Action();

                        WithPreconditionTask pSubTree = (WithPreconditionTask)this.m_children[index];
                        Debug.Check(pSubTree is WithPreconditionTask);

                        BehaviorTask pActionTree = pSubTree.Action();

                        if (pCurrentActionTree != pActionTree)
                        {
                            pCurrentActionTree.abort(pAgent);

                            pCurrentSubTree.abort(pAgent);

                            this.m_activeChildIndex = index;
                        }
                    }

                    for (int i = 0; i < this.m_children.Count; ++i)
                    {
                        WithPreconditionTask pSubTree = (WithPreconditionTask)this.m_children[i];
                        Debug.Check(pSubTree is WithPreconditionTask);

                        //dummy ticking so that the designer knows it is updating
                        EBTStatus statusDummy = pSubTree.exec(pAgent);
                        Debug.Check(statusDummy == EBTStatus.BT_RUNNING);

                        //when i < index, the precondition is failure, so to continue
                        if (i < index)
                        {
                            continue;
                        }

                        if (i > index)
                        {
                            BehaviorTask pPreconditionTree = pSubTree.PreconditionNode();

                            EBTStatus status = pPreconditionTree.exec(pAgent);

                            //to search for the first one whose precondition is success
                            if (status != EBTStatus.BT_SUCCESS)
                            {
                                continue;
                            }
                        }

                        BehaviorTask pActionTree = pSubTree.Action();

                        EBTStatus s = pActionTree.exec(pAgent);

                        if (s == EBTStatus.BT_RUNNING)
                        {
                            this.m_activeChildIndex = index;
                        }
                        else
                        {
                            pActionTree.reset(pAgent);

                            if (s == EBTStatus.BT_FAILURE || s == EBTStatus.BT_INVALID)
                            {
                                //THE ACTION failed, to try the next one
                                continue;
                            }
                        }

                        Debug.Check(s == EBTStatus.BT_RUNNING || s == EBTStatus.BT_SUCCESS);

                        return(s);
                    }
                }

                return(EBTStatus.BT_FAILURE);
            }
コード例 #21
0
        protected override void load(int version, string agentType, List <property_t> properties)
        {
            base.load(version, agentType, properties);

            for (int i = 0; i < properties.Count; ++i)
            {
                property_t p = properties[i];

                if (p.name == "FailurePolicy")
                {
                    if (p.value == "FAIL_ON_ONE")
                    {
                        this.m_failPolicy = FAILURE_POLICY.FAIL_ON_ONE;
                    }
                    else if (p.value == "FAIL_ON_ALL")
                    {
                        this.m_failPolicy = FAILURE_POLICY.FAIL_ON_ALL;
                    }
                    else
                    {
                        Debug.Check(false);
                    }
                }
                else if (p.name == "SuccessPolicy")
                {
                    if (p.value == "SUCCEED_ON_ONE")
                    {
                        this.m_succeedPolicy = SUCCESS_POLICY.SUCCEED_ON_ONE;
                    }
                    else if (p.value == "SUCCEED_ON_ALL")
                    {
                        this.m_succeedPolicy = SUCCESS_POLICY.SUCCEED_ON_ALL;
                    }
                    else
                    {
                        Debug.Check(false);
                    }
                }
                else if (p.name == "ExitPolicy")
                {
                    if (p.value == "EXIT_NONE")
                    {
                        this.m_exitPolicy = EXIT_POLICY.EXIT_NONE;
                    }
                    else if (p.value == "EXIT_ABORT_RUNNINGSIBLINGS")
                    {
                        this.m_exitPolicy = EXIT_POLICY.EXIT_ABORT_RUNNINGSIBLINGS;
                    }
                    else
                    {
                        Debug.Check(false);
                    }
                }
                else if (p.name == "ChildFinishPolicy")
                {
                    if (p.value == "CHILDFINISH_ONCE")
                    {
                        this.m_childFinishPolicy = CHILDFINISH_POLICY.CHILDFINISH_ONCE;
                    }
                    else if (p.value == "CHILDFINISH_LOOP")
                    {
                        this.m_childFinishPolicy = CHILDFINISH_POLICY.CHILDFINISH_LOOP;
                    }
                    else
                    {
                        Debug.Check(false);
                    }
                }
                else
                {
                    // todo: enter exit action failed here by mistake
                    //Debug.Check(false);
                }
            }
        }
コード例 #22
0
            private EBTStatus UpdateFSM(Agent pAgent, EBTStatus childStatus)
            {
                Debug.Check(this.m_node != null);
                Debug.Check(this.m_currentNodeId != -1);

#if !BEHAVIAC_RELEASE
                int kMaxCount = 10;
                Dictionary <int, int> state_update_count = new Dictionary <int, int>();
#endif//#if !BEHAVIAC_RELEASE

                EBTStatus status = childStatus;
                bool      bLoop  = true;

                while (bLoop)
                {
                    BehaviorTask currentState = this.GetChildById(this.m_currentNodeId);
                    currentState.exec(pAgent);

                    if (currentState is State.StateTask)
                    {
                        State.StateTask pStateTask = (State.StateTask)currentState;

                        if (pStateTask.IsEndState)
                        {
                            return(EBTStatus.BT_SUCCESS);
                        }
                    }

                    int nextStateId = currentState.GetNextStateId();

                    if (nextStateId < 0)
                    {
                        //if not transitioned, don't go on next state, to exit
                        bLoop = false;
                    }
                    else
                    {
#if !BEHAVIAC_RELEASE
                        if (state_update_count.ContainsKey(this.m_currentNodeId))
                        {
                            state_update_count[this.m_currentNodeId]++;
                        }
                        else
                        {
                            state_update_count.Add(this.m_currentNodeId, 1);
                        }

                        if (state_update_count[this.m_currentNodeId] > kMaxCount)
                        {
                            string treeName = BehaviorTask.GetParentTreeName(pAgent, this.GetNode());
                            Debug.LogError(string.Format("{0} might be updating an FSM('{1}') endlessly, possibly a dead loop, please redesign it!\n", pAgent.GetName(), treeName));
                            Debug.Check(false);
                        }
#endif

                        //if transitioned, go on next state
                        this.m_currentNodeId = nextStateId;
                    }
                }

                return(status);
            }
コード例 #23
0
 protected override bool onenter(Agent pAgent)
 {
     Debug.Check(true);
     return(true);
 }
コード例 #24
0
        public override bool decompose(BehaviorNode node, PlannerTaskComplex seqTask, int depth, Planner planner)
        {
            Debug.Check(false);

            return(false);
        }
コード例 #25
0
        public void RemoveChild(PlannerTask childTask)
        {
            Debug.Check(this.m_children.Count > 0 && this.m_children[this.m_children.Count - 1] == childTask);

            this.m_children.Remove(childTask);
        }
コード例 #26
0
ファイル: Planner.cs プロジェクト: q3640850400/Dream1
        public PlannerTask decomposeNode(BehaviorNode node, int depth)
        {
            try
            {
                // Ensure that the planner does not get stuck in an infinite loop
                if (depth >= 256)
                {
                    Debug.LogError("Exceeded task nesting depth. Does the graph contain an invalid cycle?");
                    return(null);
                }

                LogPlanNodeBegin(this.agent, node);

                int         depth1    = this.agent.Variables.Depth;
                PlannerTask taskAdded = null;

                bool isPreconditionOk = node.CheckPreconditions(this.agent, false);

                if (isPreconditionOk)
                {
                    bool bOk = true;
                    taskAdded = PlannerTask.Create(node, this.agent);

                    if (node is Action)
                    {
                        //nothing to do for action
                        Debug.Check(true);
                    }
                    else
                    {
                        Debug.Check(taskAdded is PlannerTaskComplex);
                        PlannerTaskComplex seqTask = taskAdded as PlannerTaskComplex;

                        bOk = this.decomposeComplex(node, seqTask, depth);
                    }

                    if (bOk)
                    {
                        node.ApplyEffects(this.agent, Effector.EPhase.E_SUCCESS);
                    }
                    else
                    {
                        BehaviorTask.DestroyTask(taskAdded);
                        taskAdded = null;
                    }
                }
                else
                {
                    //precondition failed
                    LogPlanNodePreconditionFailed(this.agent, node);
                }

                LogPlanNodeEnd(this.agent, node, taskAdded != null ? "success" : "failure");

                Debug.Check(this.agent.Variables.Depth == depth1);

                return(taskAdded);
            }
            catch (Exception ex)
            {
                Debug.Check(false, ex.Message);
            }

            return(null);
        }
コード例 #27
0
ファイル: AgentProperties.cs プロジェクト: qipa/behaviac-1
            public override void Run(Agent self)
            {
                Debug.Check(_param0 != null);

                behaviac.Agent.VectorClear((System.Collections.IList)_param0.GetValueObject(self));
            }
コード例 #28
0
        public static Func <TArg1, TArg2, bool> MakeMemberEqualsMethod <TArg1, TArg2>()
        {
            try
            {
                Type type1 = typeof(TArg1);
                Type type2 = typeof(TArg1);
                Debug.Check(Utils.IsCustomStructType(type1));

                ParameterExpression pThis = Expression.Parameter(type1, "lhs");
                ParameterExpression pThat = Expression.Parameter(type2, "rhs");

                // cast to the subclass type1
                UnaryExpression pCastThis = Expression.Convert(pThis, type1);
                UnaryExpression pCastThat = Expression.Convert(pThat, type2);

                // compound AND expression using short-circuit evaluation
                Expression   last         = null;
                BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
                foreach (FieldInfo field in type1.GetFields(bindingFlags))
                {
                    BinaryExpression equals = null;

                    if (field.FieldType == typeof(System.Char))
                    {
                        //Char needs to be checked before primitive
                        MethodInfo CharEquals = typeof(Extensions).GetMethod("CharEquals");
                        equals = Expression.Equal(
                            Expression.Field(pCastThis, field),
                            Expression.Field(pCastThat, field),
                            false,
                            CharEquals
                            );
                    }
                    else if (field.FieldType.IsPrimitive || field.FieldType == typeof(string) || field.FieldType.IsEnum)
                    {
                        equals = Expression.Equal(
                            Expression.Field(pCastThis, field),
                            Expression.Field(pCastThat, field)
                            );
                    }
                    else
                    {
                        MethodInfo TypesEquals = typeof(Extensions).GetMethod("TypesEquals").MakeGenericMethod(field.FieldType);;
                        equals = Expression.Equal(
                            Expression.Field(pCastThis, field),
                            Expression.Field(pCastThat, field),
                            false,
                            TypesEquals
                            );
                    }

                    if (last == null)
                    {
                        last = equals;
                    }
                    else
                    {
                        last = Expression.AndAlso(last, equals);
                    }
                }

                //Expression<Func<bool>> falsePredicate = () => false;
                Expression falsePredicate = Expression.Constant(false);
                // call Object.Equals if second parameter doesn't match type1
                last = Expression.Condition(
                    Expression.TypeIs(pThat, type1),
                    last,
                    falsePredicate
                    );

                // compile method
                return(Expression.Lambda <Func <TArg1, TArg2, bool> >(last, pThis, pThat).Compile());
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                return(delegate { throw new InvalidOperationException(msg); });
            }
        }
コード例 #29
0
ファイル: Compute.cs プロジェクト: yixiaoqingyuz/behaviac
        protected override void load(int version, string agentType, List <property_t> properties)
        {
            base.load(version, agentType, properties);

            for (int i = 0; i < properties.Count; ++i)
            {
                property_t p = properties[i];
                if (p.name == "Opl")
                {
                    this.m_opl = Condition.LoadLeft(p.value);
                }
                else if (p.name == "Operator")
                {
                    if (p.value == "Add")
                    {
                        this.m_operator = EComputeOperator.E_ADD;
                    }
                    else if (p.value == "Sub")
                    {
                        this.m_operator = EComputeOperator.E_SUB;
                    }
                    else if (p.value == "Mul")
                    {
                        this.m_operator = EComputeOperator.E_MUL;
                    }
                    else if (p.value == "Div")
                    {
                        this.m_operator = EComputeOperator.E_DIV;
                    }
                    else
                    {
                        Debug.Check(false);
                    }
                }
                else if (p.name == "Opr1")
                {
                    int pParenthesis = p.value.IndexOf('(');

                    if (pParenthesis == -1)
                    {
                        string typeName = null;
                        this.m_opr1 = Condition.LoadRight(p.value, ref typeName);
                    }
                    else
                    {
                        //method
                        this.m_opr1_m = Action.LoadMethod(p.value);
                    }
                }
                else if (p.name == "Opr2")
                {
                    int pParenthesis = p.value.IndexOf('(');

                    if (pParenthesis == -1)
                    {
                        string typeName = null;
                        this.m_opr2 = Condition.LoadRight(p.value, ref typeName);
                    }
                    else
                    {
                        //method
                        this.m_opr2_m = Action.LoadMethod(p.value);
                    }
                }
                else
                {
                    //Debug.Check(0, "unrecognised property %s", p.name);
                }
            }
        }
コード例 #30
0
        public static void Clone <T>(ref T o, T c)
        {
            if (c == null)
            {
                o = default(T);
                return;
            }

            //Type type = c.GetType();
            Type type = typeof(T);

            if (type.IsPrimitive || type.IsEnum || type.IsValueType)
            {
                //c is boxed, it needs to make a new copy
                //if (o == null)
                //{
                //    o =(T) Activator.CreateInstance(type);
                //}

                o = c;
            }
            else if (type == typeof(string))
            {
                //string is immutable, it doesn't need to make a new copy
                o = c;
            }
            else if (type.IsArray)
            {
                Type elementType = type.GetElementType();

                if (elementType == null)
                {
                    elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));
                }

                var   array  = c as Array;
                Array copied = Array.CreateInstance(elementType, array.Length);

                for (int i = 0; i < array.Length; i++)
                {
                    object item = null;
                    Utils.Clone(ref item, array.GetValue(i));
                    //object item = Utils.Clone(array.GetValue(i));

                    copied.SetValue(item, i);
                }

                if (o == null)
                {
                    o = (T)Convert.ChangeType(copied, type);
                }
            }
            else if (Utils.IsArrayType(type))
            {
                Type elementType = type.GetElementType();

                if (elementType == null)
                {
                    elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));
                }

                var array = c as IList;
                o = (T)Activator.CreateInstance(type);

                for (int i = 0; i < array.Count; i++)
                {
                    object item = null;
                    Utils.Clone(ref item, array[i]);

                    ((IList)o).Add(item);
                }
            }
            else
            {
                bool isClass = type.IsClass;

                if (isClass && Utils.IsRefNullType(type))
                {
                    o = c;
                }
                else
                {
                    Debug.Check(!type.IsPrimitive && !type.IsEnum);

                    bool isStruct = type.IsValueType;

                    if (o == null)
                    {
                        o = (T)Activator.CreateInstance(type);
                    }

                    if (isStruct || isClass)
                    {
                        FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

                        for (int i = 0; i < fields.Length; ++i)
                        {
                            FieldInfo f = fields[i];

                            if (!f.IsLiteral)
                            {
                                object fv  = f.GetValue(c);
                                object fv2 = null;
                                Utils.Clone(ref fv2, fv);

                                f.SetValue(o, fv2);
                            }
                        }
                    }
                    else
                    {
                        o = c;
                    }
                }
            }
        }