Exemple #1
0
        /** Look-up table to relate polygon key with the vertices that should be used for
         *  the sub polygon in marching squares
         **/

        /** Perform a single celled marching square for for the given cell defined by (x0,y0) (x1,y1)
         *  using the function f for recursive interpolation, given the look-up table 'fs' of
         *  the values of 'f' at cell vertices with the result to be stored in 'poly' given the actual
         *  coordinates of 'ax' 'ay' in the marching squares mesh.
         **/

        private static int MarchSquare(sbyte[,] f, sbyte[,] fs, ref GeomPoly poly, int ax, int ay, float x0, float y0,
                                       float x1, float y1, int bin)
        {
            //key lookup
            int   key = 0;
            sbyte v0  = fs[ax, ay];

            if (v0 < 0)
            {
                key |= 8;
            }
            sbyte v1 = fs[ax + 1, ay];

            if (v1 < 0)
            {
                key |= 4;
            }
            sbyte v2 = fs[ax + 1, ay + 1];

            if (v2 < 0)
            {
                key |= 2;
            }
            sbyte v3 = fs[ax, ay + 1];

            if (v3 < 0)
            {
                key |= 1;
            }

            int val = _lookMarch[key];

            if (val != 0)
            {
                CxFastListNode <Vector2> pi = null;
                for (int i = 0; i < 8; i++)
                {
                    Vector2 p;
                    if ((val & (1 << i)) != 0)
                    {
                        if (i == 7 && (val & 1) == 0)
                        {
                            poly.Points.Add(p = new Vector2(x0, Ylerp(y0, y1, x0, v0, v3, f, bin)));
                        }
                        else
                        {
                            if (i == 0)
                            {
                                p = new Vector2(x0, y0);
                            }
                            else if (i == 2)
                            {
                                p = new Vector2(x1, y0);
                            }
                            else if (i == 4)
                            {
                                p = new Vector2(x1, y1);
                            }
                            else if (i == 6)
                            {
                                p = new Vector2(x0, y1);
                            }

                            else if (i == 1)
                            {
                                p = new Vector2(Xlerp(x0, x1, y0, v0, v1, f, bin), y0);
                            }
                            else if (i == 5)
                            {
                                p = new Vector2(Xlerp(x0, x1, y1, v3, v2, f, bin), y1);
                            }

                            else if (i == 3)
                            {
                                p = new Vector2(x1, Ylerp(y0, y1, x1, v1, v2, f, bin));
                            }
                            else
                            {
                                p = new Vector2(x0, Ylerp(y0, y1, x0, v0, v3, f, bin));
                            }

                            pi = poly.Points.Insert(pi, p);
                        }
                        poly.Length++;
                    }
                }
                //poly.simplify(float.Epsilon,float.Epsilon);
            }
            return(key);
        }
 internal ByteMatrix(int width, int height)
 {
     M_Bytes = new sbyte[height, width];
 }
Exemple #3
0
        //遷移順を決める.  「この関数においては」MeBoard…手番プレイヤのボード, Me…手番プレイヤ、とします。
        //引数: stateは手番プレイヤが手を打つ前の探索状態、(way1[i], way2[i])はi番目の合法手(移動量)です。
        //以下のルールで優先順を決めます.
        //ルール1. Killer手(優先したい手)があれば、それを優先する
        //ルール2. 次のmoveで得られる「タイルポイント」の合計値が大きい移動(の組み合わせ)を優先する。
        //ルール2では, タイル除去によっても「タイルポイント」が得られるとして計算する。
        private void SortMoves(sbyte[,] ScoreBoard, SearchState state, SmallWays ways, int deep, Decision ngMove)
        {
            Unsafe16Array <Point> Killer = new Unsafe16Array <Point>();

            if (ngMove is null)
            {
                if (dp1[deep].Score == int.MinValue)
                {
                    for (int i = 0; i < AgentsCount; ++i)
                    {
                        Killer[i] = new Point(114, 191);
                    }
                }
                else
                {
                    for (int i = 0; i < AgentsCount; ++i)
                    {
                        Killer[i] = state.Me[i] + dp1[deep].Ways[i].Direction;
                    }
                }
            }
            else
            {
                if (dp2[deep].Score == int.MinValue)
                {
                    for (int i = 0; i < AgentsCount; ++i)
                    {
                        Killer[i] = new Point(114, 191);
                    }
                }
                else
                {
                    for (int i = 0; i < AgentsCount; ++i)
                    {
                        Killer[i] = state.Me[i] + dp2[deep].Ways[i].Direction;
                    }
                }
            }

            for (int i = 0; i < ways.Count; ++i)
            {
                sbyte score = 0;
                Unsafe16Array <Point> next = new Unsafe16Array <Point>();
                for (int j = 0; j < AgentsCount; ++j)
                {
                    next[j] = state.Me[j] + ways[i].AgentsWay[j].Direction;
                }

                for (int j = 0; j < AgentsCount; ++j)
                {
                    if (Killer[j] != next[j])
                    {
                        break;
                    }
                    if (j == AgentsCount - 1)
                    {
                        score = 100;
                    }
                }

                for (int j = 0; j < AgentsCount; ++j)
                {
                    if (state.EnemyBoard[next[j]])
                    {
                        score += ScoreBoard[next[j].X, next[j].Y];                               //タイル除去によって有利になる
                    }
                    else if (!state.MeBoard[next[j]])
                    {
                        score += ScoreBoard[next[j].X, next[j].Y];                               //移動でMeの陣地が増えて有利になる
                    }
                }
            }
            ways.Sort();
        }
        /// <summary>
        ///   Creates a matrix with uniformly distributed random data.
        /// </summary>
        ///
        public static sbyte[,] Random(int size, sbyte min, sbyte max, bool symmetric = false, sbyte[,] result = null)
        {
            if (result == null)
            {
                result = new sbyte[size, size];
            }

            var random = Accord.Math.Random.Generator.Random;

            if (symmetric)
            {
                for (int i = 0; i < size; i++)
                {
                    for (int j = i; j < size; j++)
                    {
                        result[i, j] = result[j, i] = (sbyte)random.Next((int)min, (int)max);
                    }
                }
            }
            else
            {
                for (int i = 0; i < size; i++)
                {
                    for (int j = i; j < size; j++)
                    {
                        result[i, j] = (sbyte)random.Next((int)min, (int)max);
                    }
                }
            }
            return(result);
        }
 static uint M2(sbyte[, ] arg0, short arg1, char arg2, ushort arg3)
 {
     arg0[0, 0] = -19;
     arg1       = arg1++;
     return(3532469096U);
 }
        private static int MarchSquare(sbyte[,] f, sbyte[,] fs, ref MarchingSquares.GeomPoly poly, int ax, int ay, FP x0, FP y0, FP x1, FP y1, int bin)
        {
            int   num  = 0;
            sbyte b    = fs[ax, ay];
            bool  flag = b < 0;

            if (flag)
            {
                num |= 8;
            }
            sbyte b2    = fs[ax + 1, ay];
            bool  flag2 = b2 < 0;

            if (flag2)
            {
                num |= 4;
            }
            sbyte b3    = fs[ax + 1, ay + 1];
            bool  flag3 = b3 < 0;

            if (flag3)
            {
                num |= 2;
            }
            sbyte b4    = fs[ax, ay + 1];
            bool  flag4 = b4 < 0;

            if (flag4)
            {
                num |= 1;
            }
            int  num2  = MarchingSquares._lookMarch[num];
            bool flag5 = num2 != 0;

            if (flag5)
            {
                MarchingSquares.CxFastListNode <TSVector2> node = null;
                for (int i = 0; i < 8; i++)
                {
                    bool flag6 = (num2 & 1 << i) != 0;
                    if (flag6)
                    {
                        bool flag7 = i == 7 && (num2 & 1) == 0;
                        if (flag7)
                        {
                            MarchingSquares.CxFastList <TSVector2> arg_EA_0 = poly.Points;
                            TSVector2 value = new TSVector2(x0, MarchingSquares.Ylerp(y0, y1, x0, (int)b, (int)b4, f, bin));
                            arg_EA_0.Add(value);
                        }
                        else
                        {
                            bool      flag8 = i == 0;
                            TSVector2 value;
                            if (flag8)
                            {
                                value = new TSVector2(x0, y0);
                            }
                            else
                            {
                                bool flag9 = i == 2;
                                if (flag9)
                                {
                                    value = new TSVector2(x1, y0);
                                }
                                else
                                {
                                    bool flag10 = i == 4;
                                    if (flag10)
                                    {
                                        value = new TSVector2(x1, y1);
                                    }
                                    else
                                    {
                                        bool flag11 = i == 6;
                                        if (flag11)
                                        {
                                            value = new TSVector2(x0, y1);
                                        }
                                        else
                                        {
                                            bool flag12 = i == 1;
                                            if (flag12)
                                            {
                                                value = new TSVector2(MarchingSquares.Xlerp(x0, x1, y0, (int)b, (int)b2, f, bin), y0);
                                            }
                                            else
                                            {
                                                bool flag13 = i == 5;
                                                if (flag13)
                                                {
                                                    value = new TSVector2(MarchingSquares.Xlerp(x0, x1, y1, (int)b4, (int)b3, f, bin), y1);
                                                }
                                                else
                                                {
                                                    bool flag14 = i == 3;
                                                    if (flag14)
                                                    {
                                                        value = new TSVector2(x1, MarchingSquares.Ylerp(y0, y1, x1, (int)b2, (int)b3, f, bin));
                                                    }
                                                    else
                                                    {
                                                        value = new TSVector2(x0, MarchingSquares.Ylerp(y0, y1, x0, (int)b, (int)b4, f, bin));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            node = poly.Points.Insert(node, value);
                        }
                        poly.Length++;
                    }
                }
            }
            return(num);
        }
Exemple #7
0
 public abstract int Calculate(sbyte[,] ScoreBoard, in Boards.ColoredBoardSmallBigger Painted, int Turn);
Exemple #8
0
 public void ChangeMapTileInfos(Vector3Int startPos, sbyte[,] info)
 {
     _MapProxy.ChangeMapInfos(startPos, info);
 }
        //On FormLoad generate randomlly the mines onto the playBoard
        public void Generate(sbyte mines, sbyte rows, sbyte cols)
        {
            sbyte[,] matrix = new sbyte[rows, cols];
            Random generateBomb = new Random();

            //Iterate through the Play Board until all mines are positioned(when mines = 0)
            while (mines > 0)
            {
                for (int row = 1; row < matrix.GetLength(0) - 1; row++)
                {
                    for (int col = 1; col < matrix.GetLength(1) - 1; col++)
                    {
                        //If the current cell has a mine skip it
                        if (matrix[row, col] != 1 && generateBomb.Next(0, 6) == 1)
                        {
                            matrix[row, col] = 1;
                            mines--;
                            if (mines == 0)
                            {
                                break;
                            }
                        }
                    }
                    if (mines == 0)
                    {
                        break;
                    }
                }
            }
            playBoardMatrix = matrix;
        }
Exemple #10
0
    /// <summary>
    /// 反向產生。holeArray[,]=2D陣列產生方式,spawnTime=老鼠間隔時間,intervalTime=產生間隔
    /// </summary>
    /// <param name="miceName">老鼠ID</param>
    /// <param name="holeArray">產生陣列</param>
    /// <param name="spawnTime">產生老鼠間隔</param>
    /// <param name="intervalTime">間隔時間</param>
    /// <param name="lerpTime">加速度</param>
    /// <param name="spawnCount">產生數量</param>
    /// <param name="randomPos1">1D陣列隨機值</param>
    /// <param name="randomPos2">2D陣列隨機值</param>
    /// <returns></returns>
    public IEnumerator ReSpawnBy2D(string miceName, sbyte[,] holeArray, float spawnTime, float intervalTime, float lerpTime, int spawnCount, int randomPos1, int randomPos2, bool isSkill)
    {
        int _tmpCount = 0;

        if (holeArray.GetLength(0) >= 4)
        {
            intervalTime /= 3;
            lerpTime     *= 2;
            spawnTime    /= 2;
        }

        for (int i = randomPos1; i > 0; i--)     // 1D陣列
        {
            for (int j = randomPos2; j > 0; j--) // 2D陣列
            {
                yield return(new WaitForSeconds(spawnTime));

                if (hole[holeArray[i - 1, j - 1] - 1].GetComponent <HoleState>().holeState == HoleState.State.Open)
                {
                    if (spawnCount > 0)
                    {
                        GameObject clone = poolManager.ActiveObject(miceName);
                        if (clone != null)
                        {
                            clone.transform.gameObject.SetActive(false);
                            hole[holeArray[i - 1, j - 1] - 1].GetComponent <HoleState>().holeState = HoleState.State.Closed;
                            Debug.Log(hole[holeArray[i - 1, j - 1] - 1].GetComponent <HoleState>().holeState);
                            _miceSize = hole[holeArray[i - 1, j - 1] - 1].transform.GetChild(0).localScale / 10 * miceSize;
                            clone.transform.parent        = hole[holeArray[i - 1, j - 1] - 1].transform;                // hole[-1] 和 holeArray[-1,-1]是因為起始值是0
                            clone.transform.localPosition = Vector2.zero;
                            clone.transform.localScale    = hole[holeArray[i - 1, j - 1] - 1].transform.GetChild(0).localScale - _miceSize;
                            clone.transform.gameObject.SetActive(true);
                            clone.transform.GetChild(0).SendMessage("Play");
                            _tmpCount++;

                            if (_tmpCount - spawnCount == 0)
                            {
                                goto Finish;
                            }
                            else if (_tmpCount == holeArray.Length || i == 1 && j == 1)
                            {
                                spawnCount -= _tmpCount;
                                _tmpCount   = 0;
                                i           = holeArray.GetLength(0);
                                j           = holeArray.GetLength(1) + 1; // 因為 j--是迴圈跑完才會-1 所以在跑一次會變 holeArray.GetLength(1)-1 不是 holeArray.GetLength(1) 0 所以要+1
                            }
                        }
                        else
                        {
                            Debug.Log("Object Pool hasn't Object");
                        }
                    }
                }
            }
            intervalTime = Mathf.Lerp(intervalTime, 0f, lerpTime);
            yield return(new WaitForSeconds(intervalTime / 3));
        }
        Finish :;
        if (!isSkill)
        {
            Global.spawnFlag = true;
        }
    }
 //遷移順を決める.  「この関数においては」MeBoard…手番プレイヤのボード, Me…手番プレイヤ、とします。
 //(この関数におけるMeは、Maxi関数におけるMe, Mini関数におけるEnemyです)
 //newMe[0]が最初に探索したい行き先、nextMe[1]が次に探索したい行き先…として、nextMeに「次の行き先」を入れていきます。
 //以下のルールで優先順を決めます。
 //ルール1. Killer手があれば、それを優先する。(Killer手がなければ、Killer.Agent1 = (514, 514), Killer.Agent2 = (514, 514)のように範囲外の移動先を設定すること。)
 //ルール2. 次のmoveで得られる「タイルポイント」の合計値、が大きい移動(の組み合わせ)を優先する。
 //なお、ルールはMovableChecker.csに準ずるため、現在は、「タイル除去先にもう一方のエージェントが移動することはできない」として計算しています。
 private List <KeyValuePair <int, (VelocityPoint Agent1, VelocityPoint Agent2)> > MoveOrderling(sbyte[,] ScoreBoard, in ColoredBoardSmallBigger MeBoard, in ColoredBoardSmallBigger EnemyBoard, in Player Me, in Player Enemy)
Exemple #12
0
        private unsafe void Copy(byte[] src, T[,] dst)
        {
            fixed(byte *s = src)
            {
                switch (DataType.TypeCode)
                {
                case TypeCode.Byte:   { byte[,]   d = dst as byte[, ];   byte *p = (byte *)s;   for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.SByte:  { sbyte[,]  d = dst as sbyte[, ];  sbyte *p = (sbyte *)s;  for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.Int16:  { short[,]  d = dst as short[, ];  short *p = (short *)s;  for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.UInt16: { ushort[,] d = dst as ushort[, ]; ushort *p = (ushort *)s; for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.Int32:  { int[,]    d = dst as int[, ];    int *p = (int *)s;    for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.UInt32: { uint[,]   d = dst as uint[, ];   uint *p = (uint *)s;   for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.Int64:  { long[,]   d = dst as long[, ];   long *p = (long *)s;   for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.UInt64: { ulong[,]  d = dst as ulong[, ];  ulong *p = (ulong *)s;  for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.Single: { float[,]  d = dst as float[, ];  float *p = (float *)s;  for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                case TypeCode.Double: { double[,] d = dst as double[, ]; double *p = (double *)s; for (int x = 0; x < TileSizeX; x++)
                                        {
                                            for (int y = 0; y < TileSizeY; y++)
                                            {
                                                d[x, y] = *p; ++p;
                                            }
                                        }
                }; break;

                default:
                    throw new NotSupportedException();
                }
            }
        }
Exemple #13
0
 public Board(sbyte[,] state) //creates a new board in the state specified
 {
     boardState = state;
 }
        /*********
        ** Public methods
        *********/
        public static List <Point> FindPath(Map location, Point start, Point end)
        {
            Layer           backLayer      = location.GetLayer("Back");
            Layer           buildingsLayer = location.GetLayer("Buildings");
            List <PathNode> nodes          = new List <PathNode>();

            sbyte[,] array =
            {
                { -1,  0 },
                {  1,  0 },
                {  0,  1 },
                {  0, -1 }
            };

            bool IsOccupied(int x, int y)
            {
                return(x < 0 || x >= buildingsLayer.LayerWidth || y < 0 || y > buildingsLayer.DisplayHeight || buildingsLayer.Tiles[x, y] != null || backLayer.Tiles[x, y]?.TileIndex != 138);
            }

            List <Point> ReconstructPath(PathNode node)
            {
                List <Point> myp = new List <Point>
                {
                    new Point(node.x, node.y)
                };

                while (node.parent != null)
                {
                    node = node.parent;
                    myp.Add(new Point(node.x, node.y));
                }

                return(myp);
            }

            PriorityQueue queue = new PriorityQueue();
            int           limit = buildingsLayer.LayerWidth * buildingsLayer.LayerHeight / 2;

            queue.Enqueue(new PathNode(start.X, start.Y, null), Math.Abs(end.X - start.X) + Math.Abs(end.Y - start.Y));
            while (!queue.IsEmpty())
            {
                PathNode node = queue.Dequeue();
                if (node.x == end.X && node.y == end.Y)
                {
                    return(ReconstructPath(node));
                }
                if (nodes.Contains(node))
                {
                    continue;
                }
                nodes.Add(node);
                for (int i = 0; i < 4; i++)
                {
                    PathNode node2 = new PathNode(node.x + array[i, 0], node.y + array[i, 1], node)
                    {
                        g = (byte)(node.g + 1)
                    };
                    int priority = node2.g + Math.Abs(end.X - node2.x) + Math.Abs(end.Y - node.y);
                    if (!IsOccupied(node2.x, node2.y) && !queue.Contains(node2, priority))
                    {
                        queue.Enqueue(node2, priority);
                    }
                }

                limit--;
                if (limit < 1)
                {
                    return(null);
                }
            }

            return(null);
        }
Exemple #15
0
    static ushort M9(sbyte arg0, long arg1)
    {
        s_1 = s_1;
        if (true)
        {
            M10(s_2, 65534);
        }
        else
        {
            ushort var0 = M11(new short[] { -29808, 1, 0 }, 65535, (short)M12(true, new byte[] { 21, 197, 212, 53, 125, 0, 254, 87, 0, 255 }), true, 10, M12(false, new byte[] { 1, 54, 180, 1, 206, 0 }), (ulong)(127 & (ushort)(0UL + (char)M12(false, new byte[] { 10, 255, 1, 84, 0, 224, 201, 131, 124 }))), 1, s_4);
            s_1 = new long[] { -6818683472497580245L, 2L };
            {
                ushort var1 = 7041;
                if ('b' > arg0)
                {
                    arg0 = arg0;
                    var0 = M11(new short[] { 25178, -32768, 0, 0, -32768, 6211, -23413 }, (ushort)M12(true, new byte[] { 1, 0, 37 }), s_4--, true, var0, arg0, (ulong)(1U - (uint)M11(new short[] { -22798, -32768, 8747, 19711, 28990 }, var1--, s_4, false, var1, -74, (ulong)M12(true, new byte[] { 160, 150 }), s_4, M10(s_2, (ushort)M12(false, new byte[] { 209, 254, 0 })))), s_4--, s_4--);
                    s_3  = s_3;
                    arg0 = arg0;
                }
                else
                {
                    M12(true, new byte[] { 1 });
                    {
                        s_3 = (byte)M12(false, new byte[] { 1 });
                        s_3 = s_3--;
                    }

                    var0 = var1;
                    {
                        {
                            arg1 = arg1--;
                            s_2  = s_2;
                        }

                        ulong[] var2 = new ulong[] { 5273692436403518283UL, 18446744073709551615UL, 10UL, 0UL, 18446744073709551615UL, 3107373517351959132UL };
                    }

                    s_2 = s_2;
                    uint var3 = 1U;
                    s_1 = s_1;
                    short var4 = s_4;
                }

                byte var5 = s_3;
            }

            {
                s_1[0] = s_1[0];
                s_1    = s_1;
            }

            arg0 >>= s_2;
            arg0  &= arg0;
            var0   = var0;
        }

        if (M13())
        {
            s_1[0] = s_1[0];
        }
        else
        {
            s_2  = s_2--;
            s_5  = s_5;
            arg1 = s_1[0];
        }

        s_5 = s_5;
        ++s_5[0, 0];
        return(1);
    }
        public Bitmap convertInterFrame(Bitmap bit)
        {
            interFrame = new Bitmap(bit.Width, bit.Height);
            width      = intraFrame.Width;
            height     = intraFrame.Height;
            YInter     = new byte[width, height];
            CbInter    = new byte[width, height];
            CrInter    = new byte[width, height];


            RGBtoYCbCr(bit, YInter, CbInter, CrInter);
            subSampling(ref CbInter, ref CrInter);
            subSampling(ref Cb, ref Cr);

            YDif  = calcDifference(Y, YInter, out YMoVec);
            CbDif = calcDifference(Cb, CbInter, out CbMoVec);
            CrDif = calcDifference(Cr, CrInter, out CrMoVec);

            YDCTInter  = new double[width, height];
            CbDCTInter = new double[CbInter.GetLength(0), CbInter.GetLength(1)];
            CrDCTInter = new double[CrInter.GetLength(0), CrInter.GetLength(1)];

            YQuantInter  = new sbyte[width, height];
            CbQuantInter = new sbyte[CbInter.GetLength(0), CbInter.GetLength(1)];
            CrQuantInter = new sbyte[CrInter.GetLength(0), CrInter.GetLength(1)];

            YEncodeInter  = new List <byte>();
            CbEncodeInter = new List <byte>();
            CrEncodeInter = new List <byte>();

            YDCTInter  = DCT(YDif);
            CbDCTInter = DCT(CbDif);
            CrDCTInter = DCT(CrDif);

            YQuantInter  = quantization(YDCTInter);
            CbQuantInter = quantization(CbDCTInter);
            CrQuantInter = quantization(CrDCTInter);

            YEncodeInter  = encoding(YQuantInter);
            CbEncodeInter = encoding(CbQuantInter);
            CrEncodeInter = encoding(CrQuantInter);

            YQuantInter  = decoding(YEncodeInter, YQuantInter.GetLength(0), YQuantInter.GetLength(1));
            CbQuantInter = decoding(CbEncodeInter, CbQuantInter.GetLength(0), CbQuantInter.GetLength(1));
            CrQuantInter = decoding(CrEncodeInter, CrQuantInter.GetLength(0), CrQuantInter.GetLength(1));

            YDCTInter  = invQuantization(YQuantInter);
            CbDCTInter = invQuantization(CbQuantInter);
            CrDCTInter = invQuantization(CrQuantInter);

            YDif  = inverseDCTInter(YDCTInter, width, height);
            CbDif = inverseDCTInter(CbDCTInter, CbInter.GetLength(0), CbInter.GetLength(1));
            CrDif = inverseDCTInter(CrDCTInter, CrInter.GetLength(0), CrInter.GetLength(1));

            YInter  = unCalcDifference(Y, YMoVec, YDif);
            CbInter = unCalcDifference(Cb, CbMoVec, CbDif);
            CrInter = unCalcDifference(Cr, CrMoVec, CrDif);



            unsubSampling(ref CbInter, ref CrInter);
            YCbCrtoRGB(interFrame, YInter, CbInter, CrInter);

            return(interFrame);
        }
Exemple #17
0
        public static List <Vertices> DetectSquares(AABB domain, FP cellWidth, FP cellHeight, sbyte[,] f, int lerpCount, bool combine)
        {
            MarchingSquares.CxFastList <MarchingSquares.GeomPoly> cxFastList = new MarchingSquares.CxFastList <MarchingSquares.GeomPoly>();
            List <Vertices> list  = new List <Vertices>();
            int             num   = (int)((long)(domain.Extents.x * 2 / cellWidth));
            bool            flag  = num == domain.Extents.x * 2 / cellWidth;
            int             num2  = (int)((long)(domain.Extents.y * 2 / cellHeight));
            bool            flag2 = num2 == domain.Extents.y * 2 / cellHeight;
            bool            flag3 = !flag;

            if (flag3)
            {
                num++;
            }
            bool flag4 = !flag2;

            if (flag4)
            {
                num2++;
            }
            sbyte[,] array = new sbyte[num + 1, num2 + 1];
            MarchingSquares.GeomPolyVal[,] array2 = new MarchingSquares.GeomPolyVal[num + 1, num2 + 1];
            for (int i = 0; i < num + 1; i++)
            {
                bool flag5 = i == num;
                int  num3;
                if (flag5)
                {
                    num3 = (int)((long)domain.UpperBound.x);
                }
                else
                {
                    num3 = (int)((long)(i * cellWidth + domain.LowerBound.x));
                }
                for (int j = 0; j < num2 + 1; j++)
                {
                    bool flag6 = j == num2;
                    int  num4;
                    if (flag6)
                    {
                        num4 = (int)((long)domain.UpperBound.y);
                    }
                    else
                    {
                        num4 = (int)((long)(j * cellHeight + domain.LowerBound.y));
                    }
                    array[i, j] = f[num3, num4];
                }
            }
            for (int k = 0; k < num2; k++)
            {
                FP   fP    = k * cellHeight + domain.LowerBound.y;
                bool flag7 = k == num2 - 1;
                FP   y;
                if (flag7)
                {
                    y = domain.UpperBound.y;
                }
                else
                {
                    y = fP + cellHeight;
                }
                MarchingSquares.GeomPoly geomPoly = null;
                for (int l = 0; l < num; l++)
                {
                    FP   fP2   = l * cellWidth + domain.LowerBound.x;
                    bool flag8 = l == num - 1;
                    FP   x;
                    if (flag8)
                    {
                        x = domain.UpperBound.x;
                    }
                    else
                    {
                        x = fP2 + cellWidth;
                    }
                    MarchingSquares.GeomPoly geomPoly2 = new MarchingSquares.GeomPoly();
                    int  num5  = MarchingSquares.MarchSquare(f, array, ref geomPoly2, l, k, fP2, fP, x, y, lerpCount);
                    bool flag9 = geomPoly2.Length != 0;
                    if (flag9)
                    {
                        bool flag10 = combine && geomPoly != null && (num5 & 9) != 0;
                        if (flag10)
                        {
                            MarchingSquares.combLeft(ref geomPoly, ref geomPoly2);
                            geomPoly2 = geomPoly;
                        }
                        else
                        {
                            cxFastList.Add(geomPoly2);
                        }
                        array2[l, k] = new MarchingSquares.GeomPolyVal(geomPoly2, num5);
                    }
                    else
                    {
                        geomPoly2 = null;
                    }
                    geomPoly = geomPoly2;
                }
            }
            bool            flag11 = !combine;
            List <Vertices> result;

            if (flag11)
            {
                List <MarchingSquares.GeomPoly> listOfElements = cxFastList.GetListOfElements();
                foreach (MarchingSquares.GeomPoly current in listOfElements)
                {
                    list.Add(new Vertices(current.Points.GetListOfElements()));
                }
                result = list;
            }
            else
            {
                for (int m = 1; m < num2; m++)
                {
                    int n = 0;
                    while (n < num)
                    {
                        MarchingSquares.GeomPolyVal geomPolyVal = array2[n, m];
                        bool flag12 = geomPolyVal == null;
                        if (flag12)
                        {
                            n++;
                        }
                        else
                        {
                            bool flag13 = (geomPolyVal.Key & 12) == 0;
                            if (flag13)
                            {
                                n++;
                            }
                            else
                            {
                                MarchingSquares.GeomPolyVal geomPolyVal2 = array2[n, m - 1];
                                bool flag14 = geomPolyVal2 == null;
                                if (flag14)
                                {
                                    n++;
                                }
                                else
                                {
                                    bool flag15 = (geomPolyVal2.Key & 3) == 0;
                                    if (flag15)
                                    {
                                        n++;
                                    }
                                    else
                                    {
                                        FP fP3 = n * cellWidth + domain.LowerBound.x;
                                        FP y2  = m * cellHeight + domain.LowerBound.y;
                                        MarchingSquares.CxFastList <TSVector2> points  = geomPolyVal.GeomP.Points;
                                        MarchingSquares.CxFastList <TSVector2> points2 = geomPolyVal2.GeomP.Points;
                                        bool flag16 = geomPolyVal2.GeomP == geomPolyVal.GeomP;
                                        if (flag16)
                                        {
                                            n++;
                                        }
                                        else
                                        {
                                            MarchingSquares.CxFastListNode <TSVector2> cxFastListNode = points.Begin();
                                            while (MarchingSquares.Square(cxFastListNode.Elem().y - y2) > Settings.Epsilon || cxFastListNode.Elem().x < fP3)
                                            {
                                                cxFastListNode = cxFastListNode.Next();
                                            }
                                            TSVector2 tSVector = cxFastListNode.Next().Elem();
                                            bool      flag17   = MarchingSquares.Square(tSVector.y - y2) > Settings.Epsilon;
                                            if (flag17)
                                            {
                                                n++;
                                            }
                                            else
                                            {
                                                bool flag18 = true;
                                                MarchingSquares.CxFastListNode <TSVector2> cxFastListNode2;
                                                for (cxFastListNode2 = points2.Begin(); cxFastListNode2 != points2.End(); cxFastListNode2 = cxFastListNode2.Next())
                                                {
                                                    bool flag19 = MarchingSquares.VecDsq(cxFastListNode2.Elem(), tSVector) < Settings.Epsilon;
                                                    if (flag19)
                                                    {
                                                        flag18 = false;
                                                        break;
                                                    }
                                                }
                                                bool flag20 = flag18;
                                                if (flag20)
                                                {
                                                    n++;
                                                }
                                                else
                                                {
                                                    MarchingSquares.CxFastListNode <TSVector2> cxFastListNode3 = cxFastListNode.Next().Next();
                                                    bool flag21 = cxFastListNode3 == points.End();
                                                    if (flag21)
                                                    {
                                                        cxFastListNode3 = points.Begin();
                                                    }
                                                    while (cxFastListNode3 != cxFastListNode)
                                                    {
                                                        cxFastListNode2 = points2.Insert(cxFastListNode2, cxFastListNode3.Elem());
                                                        cxFastListNode3 = cxFastListNode3.Next();
                                                        bool flag22 = cxFastListNode3 == points.End();
                                                        if (flag22)
                                                        {
                                                            cxFastListNode3 = points.Begin();
                                                        }
                                                        geomPolyVal2.GeomP.Length++;
                                                    }
                                                    fP3 = n + 1;
                                                    while (fP3 < num)
                                                    {
                                                        MarchingSquares.GeomPolyVal geomPolyVal3 = array2[(int)((long)fP3), m];
                                                        bool flag23 = geomPolyVal3 == null || geomPolyVal3.GeomP != geomPolyVal.GeomP;
                                                        if (flag23)
                                                        {
                                                            fP3 += 1;
                                                        }
                                                        else
                                                        {
                                                            geomPolyVal3.GeomP = geomPolyVal2.GeomP;
                                                            fP3 += 1;
                                                        }
                                                    }
                                                    fP3 = n - 1;
                                                    while (fP3 >= 0)
                                                    {
                                                        MarchingSquares.GeomPolyVal geomPolyVal4 = array2[(int)((long)fP3), m];
                                                        bool flag24 = geomPolyVal4 == null || geomPolyVal4.GeomP != geomPolyVal.GeomP;
                                                        if (flag24)
                                                        {
                                                            fP3 -= 1;
                                                        }
                                                        else
                                                        {
                                                            geomPolyVal4.GeomP = geomPolyVal2.GeomP;
                                                            fP3 -= 1;
                                                        }
                                                    }
                                                    cxFastList.Remove(geomPolyVal.GeomP);
                                                    geomPolyVal.GeomP = geomPolyVal2.GeomP;
                                                    n = (int)((long)((cxFastListNode.Next().Elem().x - domain.LowerBound.x) / cellWidth)) + 1;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                List <MarchingSquares.GeomPoly> listOfElements = cxFastList.GetListOfElements();
                foreach (MarchingSquares.GeomPoly current2 in listOfElements)
                {
                    list.Add(new Vertices(current2.Points.GetListOfElements()));
                }
                result = list;
            }
            return(result);
        }
        public Bitmap[] load(Stream stream)
        {
            BinaryReader binaryReader = new BinaryReader(stream);

            if (binaryReader.ReadChar() != id)
            {
                //
            }

            width  = binaryReader.ReadInt32();
            height = binaryReader.ReadInt32();

            //intra frame
            int count = binaryReader.ReadInt32();

            YEncode = new List <byte>(binaryReader.ReadBytes(count));

            count    = binaryReader.ReadInt32();
            CbEncode = new List <byte>(binaryReader.ReadBytes(count));

            count    = binaryReader.ReadInt32();
            CrEncode = new List <byte>(binaryReader.ReadBytes(count));

            //inter frame
            count         = binaryReader.ReadInt32();
            YEncodeInter  = new List <byte>(binaryReader.ReadBytes(count));
            count         = binaryReader.ReadInt32();
            CbEncodeInter = new List <byte>(binaryReader.ReadBytes(count));
            count         = binaryReader.ReadInt32();
            CrEncodeInter = new List <byte>(binaryReader.ReadBytes(count));

            //motion vector
            int x = binaryReader.ReadInt32();
            int y = binaryReader.ReadInt32();

            YMoVec = new Point[x, y];
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    YMoVec[i, j].X = binaryReader.ReadSByte();
                    YMoVec[i, j].Y = binaryReader.ReadSByte();
                }
            }

            x       = binaryReader.ReadInt32();
            y       = binaryReader.ReadInt32();
            CbMoVec = new Point[x, y];
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    CbMoVec[i, j].X = binaryReader.ReadSByte();
                    CbMoVec[i, j].Y = binaryReader.ReadSByte();
                }
            }

            x       = binaryReader.ReadInt32();
            y       = binaryReader.ReadInt32();
            CrMoVec = new Point[x, y];
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    CrMoVec[i, j].X = binaryReader.ReadSByte();
                    CrMoVec[i, j].Y = binaryReader.ReadSByte();
                }
            }



            Bitmap[] ret = new Bitmap[2];

            ret[0] = new Bitmap(width, height);
            ret[1] = new Bitmap(width, height);

            //decode intra frame
            YQuant  = decoding(YEncode, width, height);
            CbQuant = decoding(CbEncode, width / 2, height / 2);
            CrQuant = decoding(CrEncode, width / 2, height / 2);

            YDCT  = invQuantization(YQuant);
            CbDCT = invQuantization(CbQuant);
            CrDCT = invQuantization(CrQuant);

            Y  = inverseDCT(YDCT, width, height);
            Cb = inverseDCT(CbDCT, Cb.GetLength(0), Cb.GetLength(1));
            Cr = inverseDCT(CrDCT, Cr.GetLength(0), Cr.GetLength(1));


            unsubSampling(ref Cb, ref Cr);
            YCbCrtoRGB(ret[0], Y, Cb, Cr);

            //decode inter frame
            subSampling(ref Cb, ref Cr);
            YQuantInter  = decoding(YEncodeInter, width, height);
            CbQuantInter = decoding(CbEncodeInter, width / 2, height / 2);
            CrQuantInter = decoding(CrEncodeInter, width / 2, height / 2);

            YDCTInter  = invQuantization(YQuantInter);
            CbDCTInter = invQuantization(CbQuantInter);
            CrDCTInter = invQuantization(CrQuantInter);

            YDif  = inverseDCTInter(YDCTInter, width, height);
            CbDif = inverseDCTInter(CbDCTInter, CbInter.GetLength(0), CbInter.GetLength(1));
            CrDif = inverseDCTInter(CrDCTInter, CrInter.GetLength(0), CrInter.GetLength(1));

            YInter  = unCalcDifference(Y, YMoVec, YDif);
            CbInter = unCalcDifference(Cb, CbMoVec, CbDif);
            CrInter = unCalcDifference(Cr, CrMoVec, CrDif);

            unsubSampling(ref CbInter, ref CrInter);
            YCbCrtoRGB(ret[1], YInter, CbInter, CrInter);


            return(ret);
        }
Exemple #19
0
 public BoardSetting(sbyte[,] ScoreBoard, int Width, int Height)
 {
     this.ScoreBoard = ScoreBoard;
     this.Width      = Width;
     this.Height     = Height;
 }
 //Meが動く
 public int Max(int deepness, sbyte[,] ScoreBoard, in ColoredBoardSmallBigger MeBoard, in ColoredBoardSmallBigger EnemyBoard, in Player Me, in Player Enemy, int alpha, int beta, int count)
Exemple #21
0
        public bool RemoveMatches()
        {
            List <Line> lines = new List <Line>();

            //поиск горизонтальных линий
            sbyte[,] tmpMatrix = (sbyte[, ])m_matrix.Clone();
            for (int y = 0; y < FieldHeight; ++y)
            {
                for (int x = 0; x < FieldWidth; ++x)
                {
                    if (tmpMatrix[y, x] == -1)
                    {
                        continue;
                    }
                    int count = 1;
                    for (int i = x + 1; i < FieldWidth; ++i)
                    {
                        if (tmpMatrix[y, i] == tmpMatrix[y, x])
                        {
                            count++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (count >= 3)
                    {
                        for (int i = x; i < x + count; ++i)
                        {
                            tmpMatrix[y, i] = -1;
                        }
                        lines.Add(new Line(new Index(x, y), new Index(x + count - 1, y)));
                    }
                }
            }

            //поиск вертикальных линий
            tmpMatrix = (sbyte[, ])m_matrix.Clone();
            for (int y = 0; y < FieldHeight; ++y)
            {
                for (int x = 0; x < FieldWidth; ++x)
                {
                    if (tmpMatrix[y, x] == -1)
                    {
                        continue;
                    }
                    int count = 1;
                    for (int i = y + 1; i < FieldHeight; ++i)
                    {
                        if (tmpMatrix[i, x] == tmpMatrix[y, x])
                        {
                            count++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (count >= 3)
                    {
                        for (int i = y; i < y + count; ++i)
                        {
                            tmpMatrix[i, x] = -1;
                        }
                        lines.Add(new Line(new Index(x, y), new Index(x, y + count - 1)));
                    }
                }
            }

            if (lines.Count == 0)
            {
                return(false);
            }

            int baseValue = 10;

            foreach (Line line in lines)
            {
                int count = 0;
                //горизонтальная линия
                if (line.Start.Y == line.Finish.Y)
                {
                    for (int i = line.Start.X; i <= line.Finish.X; ++i)
                    {
                        m_matrix[line.Start.Y, i] = -1;
                        if (ElementRemoved != null)
                        {
                            ElementRemoved(i, line.Start.Y);
                        }
                        count++;
                    }
                }
                //вертикальная линия
                else
                {
                    for (int i = line.Start.Y; i <= line.Finish.Y; ++i)
                    {
                        m_matrix[i, line.Start.X] = -1;
                        if (ElementRemoved != null)
                        {
                            ElementRemoved(line.Start.X, i);
                        }
                        count++;
                    }
                }
                int value = (count - 2) * baseValue;
                m_score += count * value;
            }
            if (MatchesRemoved != null)
            {
                MatchesRemoved();
            }
            return(true);
        }
Exemple #22
0
        /// <summary>
        /// Get all possible moves from the simplified grid
        /// </summary>
        public List <AIMove> GetMoves(int level, sbyte[,] g, int minX, int maxX, AIMove parent)
        {
            // Explore the grid!
            int width  = g.GetUpperBound(0) + 1;
            int height = g.GetUpperBound(1) + 1;

            // Find the moves
            var moves        = new List <AIMove>();
            int currentCount = 0;
            int limit        = settings.movesLimits.Length > level ? settings.movesLimits[level] : int.MaxValue;

            // Look left only on the first step. Then right only.
            int start = minX + 1;

            for (int x = start;
                 x < maxX;
                 x++)
            {
                // Be sure we're in the grid
                if (x < 0 || x >= width)
                {
                    continue;
                }

                for (int y = 0; y < height; y++)
                {
                    int block = g[x, y];
                    if (block >= 0 && block < 99) // Not empty & not garbage
                    {
                        // Check left
                        if (x > 0 && x == start)
                        {
                            if (block != 0 || g[x - 1, y] != 0)
                            {
                                if (parent == null || (parent.x != (x - 1) && parent.y != y && parent.direction != -1))
                                {
                                    moves.Add(new AIMove(x, y, -1, parent));
                                    currentCount++;
                                }
                            }
                        }

                        // Check right
                        if (x < width - 1)
                        {
                            if (block != 0 || g[x + 1, y] != 0)
                            {
                                if (parent == null || (parent.x != (x + 1) && parent.y != y && parent.direction != 1))
                                {
                                    moves.Add(new AIMove(x, y, 1, parent));
                                    currentCount++;
                                }
                            }
                        }
                    }

                    if (level > 0 && currentCount > limit)
                    {
                        return(moves);
                    }
                }
            }

            // First depth = randomize please
            if (level == 0 && limit > 0)
            {
                return(moves.OrderBy(m => Random.Range(0f, 1f)).Take(limit).ToList());
            }

            return(moves);
        }
Exemple #23
0
        public List <Vector2Int> PathFind(Vector2Int start, Vector2Int end)
        {
            bool found = false;

            mOpenTable.Clear();
            mResultPath.Clear();
            mOpenStatusValue  += 2;
            mCloseStatusValue += 2;
            int    closeNodeCounter = 0;
            ushort location         = (ushort)((start[1] << mGridXLog2) + start[0]);
            ushort endLocation      = (ushort)((end[1] << mGridXLog2) + end[0]);

            mGridNode[location].G      = 0;
            mGridNode[location].F      = mHEstimate;
            mGridNode[location].PX     = (ushort)start[0];
            mGridNode[location].PY     = (ushort)start[1];
            mGridNode[location].Status = mOpenStatusValue;
            mOpenTable.Enqueue(location, location, mGridNode[location].F);
            ushort locationX;
            ushort locationY;
            ushort mHoriz = 0;

            sbyte[,] direction = UseDiagonal ? AStarDirection.DiagonalDirection : AStarDirection.NormalDirection;
            int directionCount = UseDiagonal ? 8 : 4;

            while (mOpenTable.Size > 0)
            {
                location = mOpenTable.Dequeue();
                if (mGridNode[location].Status == mCloseStatusValue)
                {
                    continue;
                }
                if (location == endLocation)
                {
                    mGridNode[location].Status = mCloseStatusValue;
                    found = true;
                    break;
                }
                if (closeNodeCounter > mSearchLimit)
                {
                    break;
                }
                locationX = (ushort)(location & mGridXMod);
                locationY = (ushort)(location >> mGridXLog2);
                if (UsePunish)
                {
                    mHoriz = (ushort)(locationX - mGridNode[location].PX);
                }
                int newG = 0;
                for (int i = 0; i < directionCount; i++)
                {
                    ushort newLocationX = (ushort)(locationX + direction[i, 0]);
                    ushort newLocationY = (ushort)(locationY + direction[i, 1]);
                    ushort newLocation  = (ushort)((newLocationY << mGridXLog2) + newLocationX);
                    if (newLocationX >= mGridX || newLocationY >= mGridY)
                    {
                        continue;
                    }
                    if (mGridNode[newLocation].Status == mCloseStatusValue && !ReuseClose)
                    {
                        continue;
                    }
                    if (mGrid[newLocationX, newLocationY] == 0)
                    {
                        continue;
                    }
                    if (UseDiagonal && i > 3)
                    {
                        newG = mGridNode[location].G + (int)(mGrid[newLocationX, newLocationY] * 2.41);
                    }
                    else
                    {
                        newG = mGridNode[location].G + mGrid[newLocationX, newLocationY];
                    }
                    if (UsePunish)
                    {
                        if ((newLocationX - locationX) != 0)
                        {
                            if (mHoriz == 0)
                            {
                                newG += Math.Abs(newLocationX - end[0]) + Math.Abs(newLocationY - end[1]);
                            }
                        }
                        if ((newLocationY - locationY) != 0)
                        {
                            if (mHoriz != 0)
                            {
                                newG += Math.Abs(newLocationX - end[0]) + Math.Abs(newLocationY - end[1]);
                            }
                        }
                    }
                    if (mGridNode[newLocation].Status == mOpenStatusValue || mGridNode[newLocation].Status == mCloseStatusValue)
                    {
                        if (mGridNode[newLocation].G <= newG)
                        {
                            continue;
                        }
                    }
                    mGridNode[newLocation].PX = locationX;
                    mGridNode[newLocation].PY = locationY;
                    mGridNode[newLocation].G  = newG;

                    int newH = 0;
                    switch (Formula)
                    {
                    case AStarFormula.Manhattan:
                        newH = mHEstimate * (Math.Abs(newLocationX - end[0]) + Math.Abs(newLocationY - end[1]));
                        break;

                    case AStarFormula.MaxDXDY:
                        newH = mHEstimate * (Math.Max(Math.Abs(newLocationX - end[0]), Math.Abs(newLocationY - end[1])));
                        break;

                    case AStarFormula.DiagonalShortCut:
                        int h_diagonal = Math.Min(Math.Abs(newLocationX - end[0]), Math.Abs(newLocationY - end[1]));
                        int h_straight = (Math.Abs(newLocationX - end[0]) + Math.Abs(newLocationY - end[1]));
                        newH = (mHEstimate * 2) * h_diagonal + mHEstimate * (h_straight - 2 * h_diagonal);
                        break;

                    case AStarFormula.Euclidean:
                        newH = (int)(mHEstimate * Math.Sqrt(Math.Pow((newLocationY - end[0]), 2) + Math.Pow((newLocationY - end[1]), 2)));
                        break;

                    case AStarFormula.EuclideanNoSQR:
                        newH = (int)(mHEstimate * (Math.Pow((newLocationX - end[0]), 2) + Math.Pow((newLocationY - end[1]), 2)));
                        break;

                    case AStarFormula.Custom:
                        Vector2Int dxy        = new Vector2Int(Math.Abs(end[0] - newLocationX), Math.Abs(end[1] - newLocationY));
                        int        Orthogonal = Math.Abs(dxy[0] - dxy[1]);
                        int        Diagonal   = Math.Abs(((dxy[0] + dxy[1]) - Orthogonal) / 2);
                        newH = mHEstimate * (Diagonal + Orthogonal + dxy[0] + dxy[1]);
                        break;
                    }
                    if (UseTieBreaker)
                    {
                        int dx1   = locationX - end[0];
                        int dy1   = locationY - end[1];
                        int dx2   = start[0] - end[0];
                        int dy2   = start[1] - end[1];
                        int cross = Math.Abs(dx1 * dy2 - dx2 * dy1);
                        newH = (int)(newH + cross * mMultiple);
                    }
                    mGridNode[newLocation].F = newG + newH;
                    mOpenTable.Enqueue(newLocation, newLocation, mGridNode[newLocation].F);
                    mGridNode[newLocation].Status = mOpenStatusValue;
                }
                closeNodeCounter++;
                mGridNode[location].Status = mCloseStatusValue;
            }
            if (found)
            {
                mResultPath.Clear();
                PathNode       tmp  = mGridNode[(end[1] << mGridXLog2) + end[0]];
                PathNodeResult node = new PathNodeResult();
                node.F  = tmp.F;
                node.G  = tmp.G;
                node.H  = 0;
                node.PX = tmp.PX;
                node.PY = tmp.PY;
                node.X  = end[0];
                node.Y  = end[1];
                while (node.X != node.PX || node.Y != node.PY)
                {
                    mResultPath.Add(node);
                    ushort posX = node.PX;
                    ushort posY = node.PY;
                    tmp     = mGridNode[(posY << mGridXLog2) + posX];
                    node    = new PathNodeResult();
                    node.F  = tmp.F;
                    node.G  = tmp.G;
                    node.H  = 0;
                    node.PX = tmp.PX;
                    node.PY = tmp.PY;
                    node.X  = posX;
                    node.Y  = posY;
                }
                mResultPath.Add(node);
                mResultPath.Reverse(0, mResultPath.Count);
                List <Vector2Int> res = new List <Vector2Int>();
                foreach (PathNodeResult n in mResultPath)
                {
                    res.Add(new Vector2Int(n.X, n.Y));
                }
                return(res);
            }
            return(null);
        }
 public ChessBoard()
 {
     // Code Review: Неіменована константа
     height  = 8;
     squares = new sbyte[height, height];
 }
Exemple #25
0
 public override int Calculate(sbyte[,] ScoreBoard, in ColoredBoardNormalSmaller Painted, int Turn, Unsafe8Array <Point> Me, Unsafe8Array <Point> Enemy)
 public ChessBoard(ChessBoard other)
 {
     this.height  = other.height;
     this.squares = (sbyte[, ])other.squares.Clone();
 }
Exemple #27
0
 public override int Calculate(sbyte[,] ScoreBoard, in ColoredBoardSmallBigger Painted, int Turn)
Exemple #28
0
 public mxNumericArray(sbyte[,] values)
     : this(BitConverterExtesions.GetBytes(values), values.GetLength(0), values.GetLength(1), mxNumericType.INT8)
 {
 }
        static void Main(string[] args)
        {
            // ---------------------------------------- Initializing variables  ----------------------------------------------------------------------
            DateTime      foreDate         = DateTime.Today.Date;
            DateTime      bndstarthindDate = foreDate.AddDays(-7);
            StringBuilder tracker          = new StringBuilder();

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("Boundary generator of Altimetry based Flood Forecasting System of SASWE.");
            Console.WriteLine("Forecast Date for generating boundary: " + foreDate.ToString("yyyy-MM-dd"));
            Console.WriteLine("Boundary generation started at: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            tracker.AppendLine("Boundary generator of Altimetry based Flood Forecasting System of SASWE.");
            tracker.AppendLine("Forecast Date for generating boundary: " + foreDate.ToString("yyyy-MM-dd"));
            tracker.AppendLine("Boundary generation started at: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.ResetColor();

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Initializing variables and checking for necessary files ...");
            tracker.AppendLine("Initializing variables and checking for necessary files ...");
            Console.ResetColor();

            string rootdirectory      = @"C:\Users\nbiswas\Desktop\Nishan\SASWE\FFWC_Flood\NewDesign\";
            string binDir             = rootdirectory + @"Bin\";
            string logDir             = rootdirectory + @"\Logs\";
            string preprocessdir      = rootdirectory + @"Preprocess\";
            string granuledir         = preprocessdir + @"GranuleData\";
            string virtualHdir        = preprocessdir + @"VSHeight\";
            string forecastHDir       = preprocessdir + @"ForecastHeights\";
            string correctHDir        = preprocessdir + @"CorrectForecasts\";
            string latloninfofilepath = binDir + "Minmaxlat.txt";
            string frcCurvepath       = binDir + "FRCInfo.txt";
            string logfilepath        = logDir + "ForecastInfo_" + foreDate.ToString("yyyy-MM-dd") + ".log";
            string selectedGanges     = "";
            string selectedBrahma     = "";

            string[] gangesBnds = new string[] { "Faridpur", "Rohanpur" };
            string[] brahmaBnds = new string[] { "Gaibandha", "Kurigram", "Badarganj", "Panchagarh", "Dalia", "Comilla", "Dinajpur" };

            SQLiteConnection sqlconn = new SQLiteConnection(@"Data Source=C:\Users\nbiswas\Desktop\Nishan\SASWE\FFWC_Flood\NewDesign\Database\Insituwaterlevel.db;Version=3;");

            sqlconn.Open();
            string        sql;
            SQLiteCommand command;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Necessary files and folders checked and variables initiated successfully.");
            tracker.AppendLine("Necessary files and folders checked and variables initiated successfully.");
            Console.ResetColor();

            try
            {
                //-------------------------------------- Creating directory if not exists --------------------------------------------------------------
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Checking for latest Virtual Station file ...");
                tracker.AppendLine("Checking for latest Virtual Station file ...");
                Console.ResetColor();

                if (Directory.Exists(granuledir) != true)
                {
                    Directory.CreateDirectory(granuledir);
                }
                //-------------------------------------- Getting Latest JASON 3 Files from AVISO FTP Server ---------------------------------------------
                List <string> jason3Files = new List <string>();
                FtpWebRequest ftpRequest  = (FtpWebRequest)WebRequest.Create("ftp://avisoftp.cnes.fr/AVISO/pub/jason-3/igdr/latest_data/");
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                FtpWebResponse response     = (FtpWebResponse)ftpRequest.GetResponse();
                StreamReader   streamReader = new StreamReader(response.GetResponseStream());
                string         line         = streamReader.ReadLine();
                while (!string.IsNullOrEmpty(line))
                {
                    jason3Files.Add(line);
                    line = streamReader.ReadLine();
                }
                streamReader.Close();

                //-------------------------------------- Getting Latest JASON 2 Files from AVISO FTP Server ---------------------------------------------
                List <string> jason2Files = new List <string>();
                ftpRequest        = (FtpWebRequest)WebRequest.Create("ftp://avisoftp.cnes.fr/AVISO/pub/jason-2/igdr/latest_data/");
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                response          = (FtpWebResponse)ftpRequest.GetResponse();
                streamReader      = new StreamReader(response.GetResponseStream());
                line = streamReader.ReadLine();
                while (!string.IsNullOrEmpty(line))
                {
                    jason2Files.Add(line);
                    line = streamReader.ReadLine();
                }
                streamReader.Close();

                //// ---------------------------------------------- Comparing JASON 3 and JASON 2 Data to get the latest File ----------------------------------
                //------------------------------------------ Selection of JASON 3 File ------------------------------------------------------
                string j3GangFile = "";
                for (int i = jason3Files.Count - 1; i >= 0; i--)
                {
                    if (jason3Files[i].Substring(16, 3) == "014" || jason3Files[i].Substring(16, 3) == "079" || jason3Files[i].Substring(16, 3) == "155" || jason3Files[i].Substring(16, 3) == "192")
                    {
                        j3GangFile = jason3Files[i];
                        Console.WriteLine("Latest JASON 3 Altimeter data available for Ganges River: " + j3GangFile);
                        tracker.AppendLine("Latest JASON 3 Altimeter data available for Ganges River: " + j3GangFile);
                        break;
                    }
                }

                string j3BrahmaFile = "";
                for (int i = jason3Files.Count - 1; i >= 0; i--)
                {
                    if (jason3Files[i].Substring(16, 3) == "053" || jason3Files[i].Substring(16, 3) == "166" || jason3Files[i].Substring(16, 3) == "242")
                    {
                        j3BrahmaFile = jason3Files[i];
                        Console.WriteLine("Latest JASON 3 Altimeter data available for Brahmaputra River: " + j3BrahmaFile);
                        tracker.AppendLine("Latest JASON 3 Altimeter data available for Brahmaputra River: " + j3BrahmaFile);
                        break;
                    }
                }

                //------------------------------------------ Selection of JASON 2 File ------------------------------------------------------
                string j2GangFile = "";
                for (int i = jason2Files.Count - 1; i >= 0; i--)
                {
                    if (jason2Files[i].Substring(16, 3) == "014" || jason2Files[i].Substring(16, 3) == "079" || jason2Files[i].Substring(16, 3) == "155" || jason2Files[i].Substring(16, 3) == "192")
                    {
                        j2GangFile = jason2Files[i];
                        Console.WriteLine("Latest JASON 2 Altimeter data available for Ganges River: " + j2GangFile);
                        tracker.AppendLine("Latest JASON 2 Altimeter data available for Ganges River: " + j2GangFile);
                        break;
                    }
                }

                string j2BrahmaFile = "";
                for (int i = jason2Files.Count - 1; i >= 0; i--)
                {
                    if (jason2Files[i].Substring(16, 3) == "053" || jason2Files[i].Substring(16, 3) == "166" || jason2Files[i].Substring(16, 3) == "242")
                    {
                        j2BrahmaFile = jason2Files[i];
                        Console.WriteLine("Latest JASON 2 Altimeter data available for Brahmaputra River: " + j2BrahmaFile);
                        tracker.AppendLine("Latest JASON 2 Altimeter data available for Brahmaputra River: " + j2BrahmaFile);
                        break;
                    }
                }
                // -------------------------------------------- Comapring the latest File -------------------------------------------------------------------
                DateTime gangesJA2Date = DateTime.ParseExact(j2GangFile.Substring(20, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
                DateTime gangesJA3Date = DateTime.ParseExact(j3GangFile.Substring(20, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
                DateTime brahmaJA2Date = DateTime.ParseExact(j2BrahmaFile.Substring(20, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
                DateTime brahmaJA3Date = DateTime.ParseExact(j3BrahmaFile.Substring(20, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
                string   gangesFile    = "";
                string   brahmaFile    = "";

                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Latest Virtual Station file Selected. Downloading the selected file ...");
                tracker.AppendLine("Latest Virtual Station file Selected. Downloading the selected file ...");
                Console.ResetColor();

                // -------------------------------------------- Downloading the latest File from AVISO FTP Server ----------------------------------
                WebClient ftpClient = new WebClient();
                if (gangesJA2Date > gangesJA3Date)
                {
                    gangesFile = j2GangFile;
                    string gangesftp = "ftp://avisoftp.cnes.fr/AVISO/pub/jason-2/igdr/latest_data/" + gangesFile;
                    selectedGanges = gangesFile;
                    string gangesfilepath = granuledir + gangesFile;
                    if (!File.Exists(gangesfilepath))
                    {
                        ftpClient.DownloadFile(gangesftp, gangesfilepath);
                    }
                }
                else
                {
                    gangesFile = j3GangFile;
                    string gangesftp = "ftp://avisoftp.cnes.fr/AVISO/pub/jason-3/igdr/latest_data/" + gangesFile;
                    selectedGanges = gangesFile;
                    string gangesfilepath = granuledir + gangesFile;
                    if (!File.Exists(gangesfilepath))
                    {
                        ftpClient.DownloadFile(gangesftp, gangesfilepath);
                    }
                }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Latest downloaded file for Ganges: " + selectedGanges);
                tracker.AppendLine("Latest downloaded file for Ganges: " + selectedGanges);
                Console.ResetColor();

                if (brahmaJA2Date > brahmaJA3Date)
                {
                    brahmaFile = j2BrahmaFile;
                    string brahmaftp = "ftp://avisoftp.cnes.fr/AVISO/pub/jason-2/igdr/latest_data/" + brahmaFile;
                    selectedBrahma = brahmaFile;
                    string brahmafilepath = granuledir + brahmaFile;
                    if (!File.Exists(brahmafilepath))
                    {
                        ftpClient.DownloadFile(brahmaftp, brahmafilepath);
                    }
                }
                else
                {
                    brahmaFile = j3BrahmaFile;
                    string brahmaftp = "ftp://avisoftp.cnes.fr/AVISO/pub/jason-3/igdr/latest_data/" + brahmaFile;
                    selectedBrahma = brahmaFile;
                    string brahmafilepath = granuledir + brahmaFile;
                    if (!File.Exists(brahmafilepath))
                    {
                        ftpClient.DownloadFile(brahmaftp, brahmafilepath);
                    }
                }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Latest downloaded file for Brahmaputra: " + selectedBrahma);
                tracker.AppendLine("Latest downloaded file for Brahmaputra: " + selectedBrahma);
                Console.ResetColor();
            }
            catch (Exception Error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Latest Virtual Station file cannot be downloaded due to an error. Error: " + Error);
                tracker.AppendLine("Latest Virtual Station file cannot be downloaded due to an error. Error: " + Error);
                Console.ResetColor();
            }

            // ------------------------------Unzipping Files ---------------------------------------------------
            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Unzipping the latest virtual station files for both basins ...");
                tracker.AppendLine("Unzipping the latest virtual station files for both basins ...");
                Console.ResetColor();

                string gangesfilepath = granuledir + selectedGanges;
                string brahmafilepath = granuledir + selectedBrahma;
                if (!File.Exists(gangesfilepath.Substring(0, gangesfilepath.Length - 4) + ".nc"))
                {
                    ZipFile.ExtractToDirectory(gangesfilepath, granuledir);
                }
                if (!File.Exists(brahmafilepath.Substring(0, brahmafilepath.Length - 4) + ".nc"))
                {
                    ZipFile.ExtractToDirectory(brahmafilepath, granuledir);
                }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("The selected virtual station file unzipped successfully.");
                tracker.AppendLine("The selected virtual station file unzipped successfully.");
                Console.ResetColor();
            }
            catch (Exception error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error in unzipping downloaded File. Error: " + error);
                tracker.AppendLine("Error in unzipping downloaded File. Error: " + error);
                Console.ResetColor();
            }

            //------------------------------------ Extracting Heights and Forecasted Rating Curves ----------------------------------------------------------
            string gangesVSfile = "";
            string brahmaVSfile = "";

            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Virtual Station files are processing to get NC files ...");
                tracker.AppendLine("Virtual Station files are processing to get NC files ...");
                Console.ResetColor();

                string   gangesNCFile = selectedGanges.Substring(0, selectedGanges.Length - 4) + ".nc";
                string   brahmaNCFile = selectedBrahma.Substring(0, selectedBrahma.Length - 4) + ".nc";
                string[] files        = new string[] { gangesNCFile, brahmaNCFile };
                //-------------------------------- Minimum and Maximum Latitude Searcing --------------------------------------------------------------------
                string[] allTxt = File.ReadAllLines(latloninfofilepath);
                Dictionary <string, float> minlats = new Dictionary <string, float>();
                Dictionary <string, float> maxlats = new Dictionary <string, float>();
                Dictionary <string, float> hcorrs  = new Dictionary <string, float>();

                for (int i = 0; i < allTxt.Length - 1; i++)
                {
                    var elements = allTxt[i + 1].Split('\t');
                    minlats.Add(elements[0], float.Parse(elements[1]));
                    maxlats.Add(elements[0], float.Parse(elements[2]));
                    hcorrs.Add(elements[0], float.Parse(elements[3]));
                }
                foreach (string element in files)
                {
                    string passID   = element.Substring(0, 3) + element.Substring(16, 3);
                    string filename = virtualHdir + passID;
                    double minlat   = minlats[passID];
                    double maxlat   = maxlats[passID];
                    double hcorr    = hcorrs[passID];
                    Console.WriteLine(minlat.ToString("0.00") + " " + maxlat.ToString("0.00") + hcorr.ToString("0.00"));

                    var      dataset                       = Microsoft.Research.Science.Data.DataSet.Open(granuledir + element + "?openMode=readOnly");
                    int[]    lat                           = dataset.GetData <int[]>("lat");
                    int[]    lon                           = dataset.GetData <int[]>("lon");
                    sbyte[]  meas_ind                      = dataset.GetData <sbyte[]>("meas_ind");
                    double[] time                          = dataset.GetData <double[]>("time");
                    short[]  model_dry_tropo_corr          = dataset.GetData <short[]>("model_dry_tropo_corr");
                    short[]  model_wet_tropo_corr          = dataset.GetData <short[]>("model_wet_tropo_corr");
                    short[]  iono_corr_gim_ku              = dataset.GetData <short[]>("iono_corr_gim_ku");
                    short[]  solid_earth_tide              = dataset.GetData <short[]>("solid_earth_tide");
                    short[]  pole_tide                     = dataset.GetData <short[]>("pole_tide");
                    sbyte[]  alt_state_flag_ku_band_status = dataset.GetData <sbyte[]>("alt_state_flag_ku_band_status");
                    int[,] lon_20hz = dataset.GetData <int[, ]>("lon_20hz");
                    int[,] lat_20hz = dataset.GetData <int[, ]>("lat_20hz");
                    sbyte[,] ice_qual_flag_20hz_ku = dataset.GetData <sbyte[, ]>("ice_qual_flag_20hz_ku");
                    double[,] time_20hz            = dataset.GetData <double[, ]>("time_20hz");
                    int[,] alt_20hz           = dataset.GetData <int[, ]>("alt_20hz");
                    int[,] ice_range_20hz_ku  = dataset.GetData <int[, ]>("ice_range_20hz_ku");
                    short[,] ice_sig0_20hz_ku = dataset.GetData <short[, ]>("ice_sig0_20hz_ku");

                    string   datetime = dataset.GetAttr(1, "units").ToString();
                    DateTime refDate  = DateTime.ParseExact(datetime.Substring(14, 19), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);

                    double s_latlon           = 0.000001;
                    double s_model_wet        = 0.0001;
                    double s_model_dry        = 0.0001;
                    double s_iono_corr        = 0.0001;
                    double s_pole_tide        = 0.0001;
                    double s_solid_earth_tide = 0.0001;
                    double s_alt           = 0.0001;
                    double s_icerange_ku   = 0.0001;
                    double s_ice_sig0_20hz = 0.01;

                    double media_corr;
                    double bsValue;
                    double height;
                    double latitude;
                    double longitude;

                    List <double> heights  = new List <double>();
                    List <double> bsValues = new List <double>();

                    DateTime      dataDate = new DateTime();
                    StringBuilder sob      = new StringBuilder();
                    sob.AppendLine("Lat(D)\tLon(D)\tH(m)\tBS(dB)");
                    for (int i = 0; i < lat.Length; i++)
                    {
                        if (model_dry_tropo_corr[i] != 32767 && model_wet_tropo_corr[i] != 32767 && iono_corr_gim_ku[i] != 32767 && solid_earth_tide[i] != 32767 && pole_tide[i] != 32767 && alt_state_flag_ku_band_status[i] == 0)
                        {
                            media_corr = model_dry_tropo_corr[i] * s_model_dry + model_wet_tropo_corr[i] * s_model_wet + iono_corr_gim_ku[i] * s_iono_corr + solid_earth_tide[i] * s_solid_earth_tide + pole_tide[i] * s_pole_tide;
                            for (int j = 0; j < meas_ind.Length; j++)
                            {
                                if (ice_qual_flag_20hz_ku[i, j] != 1 && lat_20hz[i, j] != 2147483647 && lat_20hz[i, j] * s_latlon >= minlat && lat_20hz[i, j] * s_latlon <= maxlat)
                                {
                                    height  = alt_20hz[i, j] * s_alt - (media_corr + ice_range_20hz_ku[i, j] * s_icerange_ku) - 0.7 + hcorr;
                                    bsValue = ice_sig0_20hz_ku[i, j] * s_ice_sig0_20hz;
                                    heights.Add(height);
                                    bsValues.Add(bsValue);

                                    longitude = lon_20hz[i, j] * s_latlon;
                                    latitude  = lat_20hz[i, j] * s_latlon;
                                    dataDate  = refDate.AddSeconds(time_20hz[i, j]);
                                    sob.AppendLine(latitude.ToString("0.000") + "\t" + longitude.ToString("0.000") + "\t" + Math.Round(height, 2).ToString("0.00") + "\t" + bsValue.ToString("0.00"));
                                }
                            }
                        }
                    }
                    File.WriteAllText(filename + "_" + dataDate.ToString("yyyy-MM-dd") + ".txt", sob.ToString());
                    if (element.Substring(0, 3) + element.Substring(16, 3) == selectedGanges.Substring(0, 3) + selectedGanges.Substring(16, 3))
                    {
                        gangesVSfile = passID + "_" + dataDate.ToString("yyyy-MM-dd") + ".txt";
                    }
                    else
                    {
                        brahmaVSfile = passID + "_" + dataDate.ToString("yyyy-MM-dd") + ".txt";
                    }
                    sob.Clear();
                    bsValues.Clear();
                    heights.Clear();
                }
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("Virtual Station selected for Ganges River: " + gangesVSfile);
                tracker.AppendLine("Virtual Station selected for Ganges River: " + gangesVSfile);
                Console.WriteLine("Virtual Station selected for Brahmaputra River: " + brahmaVSfile);
                tracker.AppendLine("Virtual Station selected for Brahmaputra River: " + brahmaVSfile);
                Console.ResetColor();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Virtual Station files are processed successfully.");
                tracker.AppendLine("Virtual Station files are processed successfully.");
                Console.ResetColor();
            }

            catch (Exception error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Virtual Station files cannot be processed due to an error. Error: " + error);
                tracker.AppendLine("Virtual Station files cannot be processed due to an error. Error: " + error);
                Console.ResetColor();
            }

            // ----------------------------------------------------------------------- Forecasting Boundary at Bahadurabad and Hardinge Bridge  ------------------------------------------------------------
            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Generating forecasted Water Heights at Bahadurabad and Hardinge Bridge ...");
                tracker.AppendLine("Generating forecasted Water Heights at Bahadurabad and Hardinge Bridge ...");
                Console.ResetColor();

                // ------------------------------------------------------------------- Reading Forecast Rating Curve File ----------------------------------------------------------------------------------
                string[] frcInfo = File.ReadAllLines(frcCurvepath);
                Dictionary <Tuple <string, int>, float> mvalue = new Dictionary <Tuple <string, int>, float>();
                Dictionary <Tuple <string, int>, float> cvalue = new Dictionary <Tuple <string, int>, float>();

                for (int i = 0; i < frcInfo.Length - 1; i++)
                {
                    var elements = frcInfo[i + 1].Split('\t');
                    mvalue.Add(Tuple.Create(elements[0], int.Parse(elements[1])), float.Parse(elements[2]));
                    cvalue.Add(Tuple.Create(elements[0], int.Parse(elements[1])), float.Parse(elements[3]));
                }

                //------------------------------------------------------------------ Virtual Station Output reading ----------------------------------------------------------------------------------------
                int gangesAge = Convert.ToInt32((foreDate - DateTime.ParseExact(gangesVSfile.Substring(7, 10), "yyyy-MM-dd", CultureInfo.InvariantCulture)).TotalDays);
                int brahmaAge = Convert.ToInt32((foreDate - DateTime.ParseExact(brahmaVSfile.Substring(7, 10), "yyyy-MM-dd", CultureInfo.InvariantCulture)).TotalDays);

                string[] vsFiles = new string[] { gangesVSfile, brahmaVSfile };
                int []   ageFile = new int[] { gangesAge, brahmaAge };
                string[] basin   = new string[] { "ganges", "brahma" };

                for (int j = 0; j < basin.Length; j++)
                {
                    string[]     satFileInfo = File.ReadAllLines(virtualHdir + vsFiles[j]);
                    List <float> heights     = new List <float>();
                    float        height      = 0;
                    float[]      bScatter    = new float[satFileInfo.Length - 1];
                    for (int i = 1; i < satFileInfo.Length; i++)
                    {
                        var values = satFileInfo[i].Split('\t');
                        if (float.Parse(values[3]) >= 30.0)
                        {
                            heights.Add(float.Parse(values[2].Trim()));
                        }
                    }
                    if (heights.Count == 0)
                    {
                        Console.WriteLine("No Heights found with Backscatter greater than 30 dB for " + basin[j] + ", taken height corrsponding to Maximum BS.");
                        tracker.AppendLine("No Heights found with Backscatter greater than 30 dB for " + basin[j] + ", taken height corrsponding to Maximum BS.");
                        for (int i = 1; i < satFileInfo.Length; i++)
                        {
                            var values = satFileInfo[i].Split('\t');
                            heights.Add(float.Parse(values[2].Trim()));
                            bScatter[i - 1] = float.Parse(values[3]);
                        }
                        height = heights[Array.IndexOf(bScatter, bScatter.Max())];
                    }
                    else
                    {
                        height = heights.Average();
                    }
                    heights.Clear();
                    string passID = gangesVSfile.Substring(0, 6);

                    List <DateTime> foredates   = new List <DateTime>();
                    List <float>    foreheights = new List <float>();
                    if (ageFile[j] < 4)
                    {
                        for (int k = 0; k < (4 + ageFile[j]); k++)
                        {
                            foredates.Add(foreDate.AddDays(4 - ageFile[j] + k + 1));
                            Console.WriteLine(Tuple.Create(passID, (4 - ageFile[j]) + k + 5));
                            foreheights.Add(mvalue[Tuple.Create(passID, (4 - ageFile[j]) + k + 5)] * height - cvalue[Tuple.Create(passID, (4 - ageFile[j]) + k + 5)]);
                        }
                    }
                    else
                    {
                        for (int k = 0; k < 8; k++)
                        {
                            foredates.Add(foreDate.AddDays(4 - ageFile[j] + k + 1));
                            foreheights.Add(mvalue[Tuple.Create(passID, k + 5)] * height + cvalue[Tuple.Create(passID, k + 5)]);
                        }
                    }
                    StringBuilder sb = new StringBuilder();
                    for (int k = 0; k < foredates.Count; k++)
                    {
                        sb.AppendLine(foredates[k].ToString("yyyy-MM-dd") + "\t" + foreheights[k].ToString("0.00"));
                    }
                    File.WriteAllText(forecastHDir + "Forecast_" + basin[j] + "_" + foreDate.ToString("yyyy-MM-dd") + ".txt", sb.ToString());
                    sb.Clear();
                }
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Forecasted Water Heights at Bahadurabad and Hardinge Bridge are generated successfully.");
                tracker.AppendLine("Forecasted Water Heights at Bahadurabad and Hardinge Bridge are generated successfully.");
                Console.ResetColor();
            }
            catch (Exception error)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Forecasted Water Heights at Bahadurabad and Hardinge Bridge cannot be generated due to an error. Error: " + error);
                tracker.AppendLine("Forecasted Water Heights at Bahadurabad and Hardinge Bridge cannot be generated due to an error. Error: " + error);
                Console.ResetColor();
            }

            // ---------------------------------------------------------------------- FFWC Data Download and Processing -------------------------------------------------------------
            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Downloading in situ water level data from FFWC website ....");
                tracker.AppendLine("Downloading in situ water level data from FFWC website ....");
                Console.ResetColor();

                StringBuilder sb       = new StringBuilder();
                WebClient     client   = new WebClient();
                string        htmlCode = client.DownloadString("http://www.ffwc.gov.bd/ffwc_charts/waterlevel.php");
                HtmlDocument  doc      = new HtmlDocument();
                doc.LoadHtml(htmlCode);

                HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table");
                HtmlNodeCollection rows   = tables[0].SelectNodes(".//tr");
                HtmlNodeCollection col    = rows[1].SelectNodes(".//td");
                if (col[4].InnerText.Trim() != DateTime.Today.Day.ToString("00") + "-" + DateTime.Today.Month.ToString("00"))
                {
                    Console.WriteLine("Water Level data of " + DateTime.Today.ToString("yyyy-MM-dd") + " has not been updated on the FFWC Website.");
                    Console.WriteLine("The program will now exit....");
                    Environment.Exit(1);
                }

                else
                {
                    for (int i = 0; i < rows.Count - 3; ++i)
                    {
                        HtmlNodeCollection cols = rows[i + 3].SelectNodes(".//td");
                        if (cols.Count > 4 && cols[4].InnerText != "NP")
                        {
                            Console.WriteLine(cols[1].InnerText + "," + DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss") + "," + cols[4].InnerText);
                            sql = "insert into Waterlevel (Station, Date, WL) values ('" + cols[1].InnerText + "', '" + DateTime.Today.ToString("yyyy-MM-dd") + "', " + cols[4].InnerText + ")";
                            Console.WriteLine(sql);
                            try
                            {
                                command = new SQLiteCommand(sql, sqlconn);
                                command.ExecuteNonQuery();
                            }
                            catch (SQLiteException)
                            {
                                continue;
                            }
                        }
                    }
                }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("In situ Water Level data downloaded from FFWC website and SQL Database updated successfully.");
                tracker.AppendLine("In situ Water Level data downloaded from FFWC website and SQL Database updated successfully.");
                Console.ResetColor();
            }
            catch (Exception error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("In situ Water Level data from FFWC cannot be downloaded due to an error. Error: " + error);
                tracker.AppendLine("In situ Water Level data from FFWC cannot be downloaded due to an error. Error: " + error);
                Console.ResetColor();
            }

            // ----------------------------------------------------------- Bahadurabad Boundary Generation --------------------------------------------------------------------------------

            Dictionary <DateTime, float> trendBrahma = new Dictionary <DateTime, float>();

            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Correcting forecasted Water Heights at Bahadurabad Station ...");
                tracker.AppendLine("Correcting forecasted Water Heights at Bahadurabad Station ...");
                Console.ResetColor();

                string   station      = "Bahadurabad";
                string[] forecastFile = File.ReadAllLines(forecastHDir + "Forecast_brahma_" + foreDate.ToString("yyyy-MM-dd") + ".txt");
                Dictionary <DateTime, float> foreWL = new Dictionary <DateTime, float>();

                foreach (string line in forecastFile)
                {
                    var element = line.Split('\t');
                    foreWL.Add(DateTime.ParseExact(element[0], "yyyy-MM-dd", CultureInfo.InvariantCulture), float.Parse(element[1]));
                }
                int missingDays = Convert.ToInt32((foreWL.FirstOrDefault().Key - foreDate).TotalDays);
                Console.WriteLine(missingDays);
                Dictionary <DateTime, float> hindWL = new Dictionary <DateTime, float>();

                sql     = "Select Date, WL from WaterLevel where Date >= '" + bndstarthindDate.ToString("yyyy-MM-dd") + "' and Date<='" + foreDate.ToString("yyyy-MM-dd") + "' and Station='" + station + "' Order by Date ASC";
                command = new SQLiteCommand(sql, sqlconn);
                SQLiteDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    hindWL.Add(Convert.ToDateTime(reader["Date"]), Convert.ToSingle(reader["WL"]));
                }
                float foredateWL = hindWL[foreDate];
                float day_1WL    = hindWL[foreDate.AddDays(-1)];
                float day_2WL    = hindWL[foreDate.AddDays(-2)];
                float day_3WL    = hindWL[foreDate.AddDays(-3)];
                float meandiff   = ((foredateWL - day_1WL) + (foredateWL - day_2WL) / 2.0f + (foredateWL - day_3WL) / 3.0f) / 3.0f;

                for (int i = 1; i < missingDays; i++)
                {
                    hindWL.Add(foreDate.AddDays(i), foredateWL + meandiff * i);
                }
                float correction = foreWL.FirstOrDefault().Value - hindWL.LastOrDefault().Value;
                foreach (var record in foreWL)
                {
                    hindWL.Add(record.Key, record.Value - correction);
                }

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Bnd Date\tWL");
                foreach (DateTime dates in hindWL.Keys)
                {
                    sb.AppendLine(dates.ToString("yyyy-MM-dd") + "\t" + hindWL[dates].ToString("0.00"));
                    Console.WriteLine(dates.ToString("yyyy-MM-dd") + "," + hindWL[dates].ToString("0.00"));
                }
                File.WriteAllText(correctHDir + station + "_" + foreDate.ToString("yyyy-MM-dd") + ".txt", sb.ToString());
                sb.Clear();
                // ----------------- Calculating forecast Trend in WL of Bahadurabad Station -------------------------------------------
                for (int i = 1; i < 9; i++)
                {
                    trendBrahma.Add(foreDate.AddDays(i), (hindWL[foreDate.AddDays(i)] - hindWL[foreDate]));
                    Console.WriteLine((hindWL[foreDate.AddDays(i)] - hindWL[foreDate]).ToString("0.00"));
                }
                //---------------------- USing forecast Trend of Bahadurabad Station for depended Boundaries ------------------------------

                foreach (string element in brahmaBnds)
                {
                    Dictionary <DateTime, float> hindcastWL = new Dictionary <DateTime, float>();
                    sql     = "Select Date, WL from WaterLevel where Date >= '" + bndstarthindDate.ToString("yyyy-MM-dd") + "' and Date<='" + foreDate.ToString("yyyy-MM-dd") + "' and Station= '" + element + "' Order by Date ASC";
                    command = new SQLiteCommand(sql, sqlconn);
                    reader  = command.ExecuteReader();
                    while (reader.Read())
                    {
                        hindcastWL.Add(Convert.ToDateTime(reader["Date"]), Convert.ToSingle(reader["WL"]));
                    }
                    float foredayWL = hindcastWL.Last().Value;
                    foreach (var record in trendBrahma)
                    {
                        hindcastWL.Add(record.Key, record.Value + foredayWL);
                    }

                    sb.AppendLine("Bnd Date\tWL");
                    foreach (DateTime dates in hindcastWL.Keys)
                    {
                        sb.AppendLine(dates.ToString("yyyy-MM-dd") + "\t" + hindcastWL[dates].ToString("0.00"));
                        Console.WriteLine(dates.ToString("yyyy-MM-dd") + "," + hindcastWL[dates].ToString("0.00"));
                    }
                    File.WriteAllText(correctHDir + element + "_" + foreDate.ToString("yyyy-MM-dd") + ".txt", sb.ToString());
                    sb.Clear();
                }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Bahadurabad and depended station's forecasts generated successfully.");
                tracker.AppendLine("Bahadurabad and depended station's forecasts generated successfully.");
                Console.ResetColor();
            }
            catch (Exception error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error occurred in boundary correction at Bahadurabad Station. Error: " + error);
                tracker.AppendLine("Error occurred in boundary correction at Bahadurabad Station. Error: " + error);
                Console.ResetColor();
            }


            //------------------------------------ Hardinge Bridge Boundary Writing ---------------------------------------------------------------
            Dictionary <DateTime, float> trendGanges = new Dictionary <DateTime, float>();

            try
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Correcting forecasted Water Heights at Hardinge Bridge Station ...");
                tracker.AppendLine("Correcting forecasted Water Heights at Hardinge Bridge Station ...");
                Console.ResetColor();

                string   station      = "Hardinge-RB";
                string[] forecastFile = File.ReadAllLines(forecastHDir + "Forecast_ganges_" + foreDate.ToString("yyyy-MM-dd") + ".txt");
                Dictionary <DateTime, float> foreWL = new Dictionary <DateTime, float>();

                foreach (string line in forecastFile)
                {
                    var element = line.Split('\t');
                    foreWL.Add(DateTime.ParseExact(element[0], "yyyy-MM-dd", CultureInfo.InvariantCulture), float.Parse(element[1]));
                }
                int missingDays = Convert.ToInt32((foreWL.FirstOrDefault().Key - foreDate).TotalDays);
                Console.WriteLine(missingDays);
                Dictionary <DateTime, float> hindWL = new Dictionary <DateTime, float>();

                sql     = "Select Date, WL from WaterLevel where Date >= '" + bndstarthindDate.ToString("yyyy-MM-dd") + "' and Date<='" + foreDate.ToString("yyyy-MM-dd") + "' and Station='" + station + "' Order by Date ASC";
                command = new SQLiteCommand(sql, sqlconn);
                SQLiteDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    hindWL.Add(Convert.ToDateTime(reader["Date"]), Convert.ToSingle(reader["WL"]));
                }
                float foredateWL = hindWL[foreDate];
                float day_1WL    = hindWL[foreDate.AddDays(-1)];
                float day_2WL    = hindWL[foreDate.AddDays(-2)];
                float day_3WL    = hindWL[foreDate.AddDays(-3)];
                float meandiff   = ((foredateWL - day_1WL) + (foredateWL - day_2WL) / 2.0f + (foredateWL - day_3WL) / 3.0f) / 3.0f;

                for (int i = 1; i < missingDays; i++)
                {
                    hindWL.Add(foreDate.AddDays(i), foredateWL + meandiff * i);
                }
                float correction = foreWL.FirstOrDefault().Value - hindWL.LastOrDefault().Value;
                foreach (var record in foreWL)
                {
                    hindWL.Add(record.Key, record.Value - correction);
                }

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Bnd Date\tWL");
                foreach (DateTime dates in hindWL.Keys)
                {
                    sb.AppendLine(dates.ToString("yyyy-MM-dd") + "\t" + hindWL[dates].ToString("0.00"));
                    Console.WriteLine(dates.ToString("yyyy-MM-dd") + "," + hindWL[dates].ToString("0.00"));
                }
                File.WriteAllText(correctHDir + station + "_" + foreDate.ToString("yyyy-MM-dd") + ".txt", sb.ToString());
                sb.Clear();
                // ----------------- Calculating forecast Trend in WL of Hardinge Bridge Station -------------------------------------------
                for (int i = 1; i < 9; i++)
                {
                    trendGanges.Add(foreDate.AddDays(i), (hindWL[foreDate.AddDays(i)] - hindWL[foreDate]));
                    Console.WriteLine((hindWL[foreDate.AddDays(i)] - hindWL[foreDate]).ToString("0.00"));
                }

                //---------------------- USing forecast Trend of Bahadurabad Station for depended Boundaries ------------------------------
                foreach (string element in gangesBnds)
                {
                    Dictionary <DateTime, float> hindcastWL = new Dictionary <DateTime, float>();
                    sql     = "Select Date, WL from WaterLevel where Date >= '" + bndstarthindDate.ToString("yyyy-MM-dd") + "' and Date<='" + foreDate.ToString("yyyy-MM-dd") + "' and Station= '" + element + "' Order by Date ASC";
                    command = new SQLiteCommand(sql, sqlconn);
                    reader  = command.ExecuteReader();
                    while (reader.Read())
                    {
                        hindcastWL.Add(Convert.ToDateTime(reader["Date"]), Convert.ToSingle(reader["WL"]));
                    }
                    float foredayWL = hindcastWL.Last().Value;
                    foreach (var record in trendBrahma)
                    {
                        hindcastWL.Add(record.Key, record.Value + foredayWL);
                    }

                    sb.AppendLine("Bnd Date\tWL");
                    foreach (DateTime dates in hindcastWL.Keys)
                    {
                        sb.AppendLine(dates.ToString("yyyy-MM-dd") + "\t" + hindcastWL[dates].ToString("0.00"));
                        Console.WriteLine(dates.ToString("yyyy-MM-dd") + "," + hindcastWL[dates].ToString("0.00"));
                    }
                    File.WriteAllText(correctHDir + element + "_" + foreDate.ToString("yyyy-MM-dd") + ".txt", sb.ToString());
                    sb.Clear();
                }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Hardinge Bridge and depended station's forecasts generated successfully.");
                tracker.AppendLine("Hardinge Bridge and depended station's forecasts generated successfully.");
                Console.ResetColor();
            }
            catch (Exception error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Hardinge Bridge and depended station's forecasts cannot be generated due to an error. Error: " + error);
                tracker.AppendLine("Hardinge Bridge and depended station's forecasts cannot be generated due to an error. Error: " + error);
                Console.ResetColor();
            }
            File.WriteAllText(logfilepath, tracker.ToString());
        }
Exemple #30
0
 public mxNumericArray(sbyte[,] realValues, sbyte[,] imgValues)
     : this(BitConverterExtesions.GetBytes(realValues), BitConverterExtesions.GetBytes(imgValues), realValues.GetLength(0), realValues.GetLength(1), mxNumericType.INT8)
 {
 }
Exemple #31
0
        /// <summary>
        /// Marching squares over the given domain using the mesh defined via the dimensions
        ///    (wid,hei) to build a set of polygons such that f(x,y) less than 0, using the given number
        ///    'bin' for recursive linear inteprolation along cell boundaries.
        ///
        ///    if 'comb' is true, then the polygons will also be composited into larger possible concave
        ///    polygons.
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="cellWidth"></param>
        /// <param name="cellHeight"></param>
        /// <param name="f"></param>
        /// <param name="lerpCount"></param>
        /// <param name="combine"></param>
        /// <returns></returns>
        public static List <Vertices> DetectSquares(AABB domain, float cellWidth, float cellHeight, sbyte[,] f,
                                                    int lerpCount, bool combine)
        {
            CxFastList <GeomPoly> ret = new CxFastList <GeomPoly>();

            List <Vertices> verticesList = new List <Vertices>();

            //NOTE: removed assignments as they were not used.
            List <GeomPoly> polyList;
            GeomPoly        gp;

            int  xn = (int)(domain.Extents.X * 2 / cellWidth);
            bool xp = xn == (domain.Extents.X * 2 / cellWidth);
            int  yn = (int)(domain.Extents.Y * 2 / cellHeight);
            bool yp = yn == (domain.Extents.Y * 2 / cellHeight);

            if (!xp)
            {
                xn++;
            }
            if (!yp)
            {
                yn++;
            }

            sbyte[,] fs       = new sbyte[xn + 1, yn + 1];
            GeomPolyVal[,] ps = new GeomPolyVal[xn + 1, yn + 1];

            //populate shared function lookups.
            for (int x = 0; x < xn + 1; x++)
            {
                int x0;
                if (x == xn)
                {
                    x0 = (int)domain.UpperBound.X;
                }
                else
                {
                    x0 = (int)(x * cellWidth + domain.LowerBound.X);
                }
                for (int y = 0; y < yn + 1; y++)
                {
                    int y0;
                    if (y == yn)
                    {
                        y0 = (int)domain.UpperBound.Y;
                    }
                    else
                    {
                        y0 = (int)(y * cellHeight + domain.LowerBound.Y);
                    }
                    fs[x, y] = f[x0, y0];
                }
            }

            //generate sub-polys and combine to scan lines
            for (int y = 0; y < yn; y++)
            {
                float y0 = y * cellHeight + domain.LowerBound.Y;
                float y1;
                if (y == yn - 1)
                {
                    y1 = domain.UpperBound.Y;
                }
                else
                {
                    y1 = y0 + cellHeight;
                }
                GeomPoly pre = null;
                for (int x = 0; x < xn; x++)
                {
                    float x0 = x * cellWidth + domain.LowerBound.X;
                    float x1;
                    if (x == xn - 1)
                    {
                        x1 = domain.UpperBound.X;
                    }
                    else
                    {
                        x1 = x0 + cellWidth;
                    }

                    gp = new GeomPoly();

                    int key = MarchSquare(f, fs, ref gp, x, y, x0, y0, x1, y1, lerpCount);
                    if (gp.Length != 0)
                    {
                        if (combine && pre != null && (key & 9) != 0)
                        {
                            combLeft(ref pre, ref gp);
                            gp = pre;
                        }
                        else
                        {
                            ret.Add(gp);
                        }
                        ps[x, y] = new GeomPolyVal(gp, key);
                    }
                    else
                    {
                        gp = null;
                    }
                    pre = gp;
                }
            }
            if (!combine)
            {
                polyList = ret.GetListOfElements();

                foreach (GeomPoly poly in polyList)
                {
                    verticesList.Add(new Vertices(poly.Points.GetListOfElements()));
                }

                return(verticesList);
            }

            //combine scan lines together
            for (int y = 1; y < yn; y++)
            {
                int x = 0;
                while (x < xn)
                {
                    GeomPolyVal p = ps[x, y];

                    //skip along scan line if no polygon exists at this point
                    if (p == null)
                    {
                        x++;
                        continue;
                    }

                    //skip along if current polygon cannot be combined above.
                    if ((p.Key & 12) == 0)
                    {
                        x++;
                        continue;
                    }

                    //skip along if no polygon exists above.
                    GeomPolyVal u = ps[x, y - 1];
                    if (u == null)
                    {
                        x++;
                        continue;
                    }

                    //skip along if polygon above cannot be combined with.
                    if ((u.Key & 3) == 0)
                    {
                        x++;
                        continue;
                    }

                    float ax = x * cellWidth + domain.LowerBound.X;
                    float ay = y * cellHeight + domain.LowerBound.Y;

                    CxFastList <Vector2> bp = p.GeomP.Points;
                    CxFastList <Vector2> ap = u.GeomP.Points;

                    //skip if it's already been combined with above polygon
                    if (u.GeomP == p.GeomP)
                    {
                        x++;
                        continue;
                    }

                    //combine above (but disallow the hole thingies
                    CxFastListNode <Vector2> bi = bp.Begin();
                    while (Square(bi.Elem().Y - ay) > Settings.Epsilon || bi.Elem().X < ax)
                    {
                        bi = bi.Next();
                    }

                    //NOTE: Unused
                    //Vector2 b0 = bi.elem();
                    Vector2 b1 = bi.Next().Elem();
                    if (Square(b1.Y - ay) > Settings.Epsilon)
                    {
                        x++;
                        continue;
                    }

                    bool brk = true;
                    CxFastListNode <Vector2> ai = ap.Begin();
                    while (ai != ap.End())
                    {
                        if (VecDsq(ai.Elem(), b1) < Settings.Epsilon)
                        {
                            brk = false;
                            break;
                        }
                        ai = ai.Next();
                    }
                    if (brk)
                    {
                        x++;
                        continue;
                    }

                    CxFastListNode <Vector2> bj = bi.Next().Next();
                    if (bj == bp.End())
                    {
                        bj = bp.Begin();
                    }
                    while (bj != bi)
                    {
                        ai = ap.Insert(ai, bj.Elem()); // .clone()
                        bj = bj.Next();
                        if (bj == bp.End())
                        {
                            bj = bp.Begin();
                        }
                        u.GeomP.Length++;
                    }
                    //u.p.simplify(float.Epsilon,float.Epsilon);
                    //
                    ax = x + 1;
                    while (ax < xn)
                    {
                        GeomPolyVal p2 = ps[(int)ax, y];
                        if (p2 == null || p2.GeomP != p.GeomP)
                        {
                            ax++;
                            continue;
                        }
                        p2.GeomP = u.GeomP;
                        ax++;
                    }
                    ax = x - 1;
                    while (ax >= 0)
                    {
                        GeomPolyVal p2 = ps[(int)ax, y];
                        if (p2 == null || p2.GeomP != p.GeomP)
                        {
                            ax--;
                            continue;
                        }
                        p2.GeomP = u.GeomP;
                        ax--;
                    }
                    ret.Remove(p.GeomP);
                    p.GeomP = u.GeomP;

                    x = (int)((bi.Next().Elem().X - domain.LowerBound.X) / cellWidth) + 1;
                    //x++; this was already commented out!
                }
            }

            polyList = ret.GetListOfElements();

            foreach (GeomPoly poly in polyList)
            {
                verticesList.Add(new Vertices(poly.Points.GetListOfElements()));
            }

            return(verticesList);
        }
		/// <summary>
		/// Select current state transition matrix and offset increment matrix
		/// </summary>
		protected void UpdateMatricies ()
		{
			int distanceToEnd = W - CurrentOffset;
			switch (distanceToEnd) {		
				case 0:
				stateTransitions = ParametricDescription.StateTransitions0[N-1];
				offsetIncrements = ParametricDescription.OffsetIncrements0[N-1];
				break;
				case 1:
				stateTransitions = ParametricDescription.StateTransitions1[N-1];
				offsetIncrements = ParametricDescription.OffsetIncrements1[N-1];
				break;
				case 2:
				stateTransitions = ParametricDescription.StateTransitions2[N-1];
				offsetIncrements = ParametricDescription.OffsetIncrements2[N-1];
				break;
				case 3:
				stateTransitions = ParametricDescription.StateTransitions3[N-1];
				offsetIncrements = ParametricDescription.OffsetIncrements3[N-1];
				break;
				case 4:
				stateTransitions = ParametricDescription.StateTransitions4[N-1];
				offsetIncrements = ParametricDescription.OffsetIncrements4[N-1];
				break;
				default:
				stateTransitions = ParametricDescription.StateTransitions5[N-1];
				offsetIncrements = ParametricDescription.OffsetIncrements5[N-1];
				break;
			}
		}