Пример #1
0
 static extern bool ReadConsoleOutput(
     IntPtr hConsoleOutput,
     [Out] CHAR_INFO[,] lpBuffer,
     COORD dwBufferSize,
     COORD dwBufferCoord,
     ref SMALL_RECT lpReadRegion
     );
Пример #2
0
 /// <summary>Cosntructor</summary>
 public ConsoleProgressBar()
 {
     m_HConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
     m_barCoord = GetCursorPos();
     Console.WriteLine();
     Console.WriteLine();
     Console.WriteLine();
 }
Пример #3
0
        public static extern bool WriteConsoleOutput(
			IntPtr hConsoleOutput,
			/* This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures
			whose size is specified by the dwBufferSize parameter.*/
			[MarshalAs(UnmanagedType.LPArray), In] CHAR_INFO[] lpBuffer,
			COORD dwBufferSize,
			COORD dwBufferCoord,
			ref SMALL_RECT lpWriteRegion);
Пример #4
0
		/// <summary>Cosntructor</summary>
		public ConsoleProgressBar()
		{
			//
			// TODO: Add constructor logic here.
			//
			mHConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
			
			barCoord = this.GetCursorPos();
			Console.WriteLine();
			Console.WriteLine();
			Console.WriteLine();
		}
Пример #5
0
    public static bool InitConsole()
    {
        if (Application.platform != RuntimePlatform.WindowsPlayer)
            return false;

        AllocConsole();
        SetConsoleCtrlHandler(null, true);

        StdOutHandle = GetStdHandle(unchecked((uint)STD_OUTPUT_HANDLE));
        StdInHandle = GetStdHandle(unchecked((uint)STD_INPUT_HANDLE));

        // 允许控制台右键菜单
        uint dwConsoleMode = 0;
        GetConsoleMode(StdInHandle, out dwConsoleMode);
        SetConsoleMode(StdInHandle, ~ENABLE_MOUSE_INPUT & dwConsoleMode);

        // forbid close
        IntPtr hWnd = GetConsoleWindow();
        IntPtr hMenu = GetSystemMenu(hWnd, 0);
        RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

        COORD BufferSize = new COORD()
        {
            X = 120,
            Y = 320,
        };

        SMALL_RECT WinRect = new SMALL_RECT()
        {
            Left = 0,
            Top = 0,
            Right = (short)(BufferSize.X - 1),
            Bottom = 30,
        };

        IntPtr pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(BufferSize));
        Marshal.StructureToPtr(BufferSize, pBuffer, false);
        Debug.Log(SetConsoleScreenBufferSize(StdOutHandle, pBuffer));
        Marshal.FreeHGlobal(pBuffer);

        IntPtr pWinRect = Marshal.AllocHGlobal(Marshal.SizeOf(WinRect));
        Marshal.StructureToPtr(WinRect, pWinRect, false);
        Debug.Log(SetConsoleWindowInfo(StdOutHandle, true, pWinRect));
        Marshal.FreeHGlobal(pWinRect);

        ConsoleAlive = true;

        Thread th = new Thread(new ThreadStart(WorkingThread));
        th.Start();

        return true;
    }
Пример #6
0
        static private void SetPrompt(string prompt)
        {
            if (string.IsNullOrEmpty(prompt))
                return;

            var handle = NativeMethods.GetStdHandle((uint) StandardHandleId.Output);

            var lineCount = 1 + prompt.Count(c => c == '\n');
            if (lineCount > 1)
            {
                var options = new SetPSReadlineOption {ExtraPromptLineCount = lineCount - 1};
                PSConsoleReadLine.SetOptions(options);
            }
            int bufferWidth = Console.BufferWidth;
            var consoleBuffer = new CHAR_INFO[lineCount * bufferWidth];
            int j = 0;
            for (int i = 0; i < prompt.Length; i++, j++)
            {
                if (prompt[i] == '\n')
                {
                    for (; j % Console.BufferWidth != 0; j++)
                    {
                        consoleBuffer[j] = new CHAR_INFO(' ', Console.ForegroundColor, Console.BackgroundColor);
                    }
                    Console.CursorTop += 1;
                    Console.CursorLeft = 0;
                    j -= 1;  // We don't actually write the newline
                }
                else
                {
                    consoleBuffer[j] = new CHAR_INFO(prompt[i], Console.ForegroundColor, Console.BackgroundColor);
                    Console.CursorLeft += 1;
                }
            }

            var bufferSize = new COORD
                             {
                                 X = (short) bufferWidth,
                                 Y = (short) lineCount
                             };
            var bufferCoord = new COORD {X = 0, Y = 0};
            var writeRegion = new SMALL_RECT
                              {
                                  Top = 0,
                                  Left = 0,
                                  Bottom = (short) (lineCount - 1),
                                  Right = (short) bufferWidth
                              };
            NativeMethods.WriteConsoleOutput(handle, consoleBuffer, bufferSize, bufferCoord, ref writeRegion);
        }
Пример #7
0
        //static ConsoleBuffer buffer;



        /// <summary>
        /// Maximizuje okno, hiduje kurzor, a nastavi kodovu stranku na 866, kde su nejake graficke znaky. googluj codepage 866
        /// </summary>
        public static void FullScreen()
        {
            IntPtr hConsole = GetStdHandle(-11);   // get console handle
            COORD  xy       = new COORD(100, 100);

            SetConsoleDisplayMode(hConsole, 1, out xy); // set the console to fullscreen
            System.Console.OutputEncoding = Encoding.GetEncoding(866);
            System.Console.CursorVisible  = false;
            Wait(100);
            System.Console.BufferHeight = System.Console.WindowHeight;
            System.Console.BufferWidth  = System.Console.WindowWidth;
            Width  = System.Console.WindowWidth;
            Height = System.Console.WindowHeight;
        }
Пример #8
0
    //istanza Random

    public Maze(int dimx, int dimy, int difficultyPercentage, int randomPercentage)
    {
        dim = new COORD(dimx, dimy);
        this.randomPercentage     = (double)randomPercentage / 100;
        this.difficultyPercentage = (double)difficultyPercentage / 100;
        maze = new int[dimy, dimx];
        for (int i = 0; i < dim.y; i++)
        {
            for (int j = 0; j < dim.x; j++)
            {
                maze[i, j] = 0;
            }
        }
    }
Пример #9
0
        private static void ScrollBuffer(int lines)
        {
            var handle = NativeMethods.GetStdHandle((uint) StandardHandleId.Output);

            var scrollRectangle = new SMALL_RECT
            {
                Top = (short) lines,
                Left = 0,
                Bottom = (short) (lines + Console.BufferHeight - 1),
                Right = (short)Console.BufferWidth
            };
            var destinationOrigin = new COORD {X = 0, Y = 0};
            var fillChar = new CHAR_INFO(' ', Console.ForegroundColor, Console.BackgroundColor);
            NativeMethods.ScrollConsoleScreenBuffer(handle, ref scrollRectangle, IntPtr.Zero, destinationOrigin, ref fillChar);
        }
Пример #10
0
        public static IEnumerable <string> ReadFromBuffer(short x, short y, short width, short height)
        {
            IntPtr buffer = Marshal.AllocHGlobal(width * height * Marshal.SizeOf(typeof(CHAR_INFO)));

            if (buffer == null)
            {
                throw new OutOfMemoryException();
            }

            try
            {
                COORD      coord = new COORD();
                SMALL_RECT rc    = new SMALL_RECT();
                rc.Left   = x;
                rc.Top    = y;
                rc.Right  = (short)(x + width - 1);
                rc.Bottom = (short)(y + height - 1);

                COORD size = new COORD();
                size.X = width;
                size.Y = height;

                const int STD_OUTPUT_HANDLE = -11;
                if (!ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE), buffer, size, coord, ref rc))
                {
                    // 'Not enough storage is available to process this command' may be raised for buffer size > 64K (see ReadConsoleOutput doc.)
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                IntPtr ptr = buffer;
                for (int h = 0; h < height; h++)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int w = 0; w < width; w++)
                    {
                        CHAR_INFO ci    = (CHAR_INFO)Marshal.PtrToStructure(ptr, typeof(CHAR_INFO));
                        char[]    chars = Console.OutputEncoding.GetChars(ci.charData);
                        sb.Append(chars[0]);
                        ptr += Marshal.SizeOf(typeof(CHAR_INFO));
                    }
                    yield return(sb.ToString());
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
Пример #11
0
        public static void CenterConsoleWindow(int Width, int Height)
        {
            Screen scr      = Screen.PrimaryScreen;
            COORD  FontSize = GetConsoleFontSize();

            if (FontSize.X > 0 && FontSize.Y > 0)
            {
                int    X    = (scr.Bounds.Width - (Width * FontSize.X)) / 2;
                int    Y    = (scr.Bounds.Height - (Height * FontSize.Y)) / 2;
                IntPtr hWnd = GetConsoleWindow();
                if (hWnd != IntPtr.Zero)
                {
                    MoveWindow(hWnd, X, Y, Width * FontSize.X, Height * FontSize.Y, true);
                }
            }
        }
Пример #12
0
    private List <COORD> CalcTargetTileCenter()
    {
        List <COORD> coords = null;

        int index = _path.nodes.Count - 1;

        while (index > 0)
        {
            MapAStar.NODE n  = _path.nodes [index];
            Vector2       nc = MapGrid.GetTileCenter(n.x, n.z);

            coords = CollectTilesInLine(
                _unit.transform.position.x, _unit.transform.position.z, nc.x, nc.y);

            bool blocked = false;
            for (int i = 1; i < coords.Count; ++i)
            {
                COORD coord = coords[i];
                if (_mapGrid.IsBlock(coord.x, coord.z))
                {
                    blocked = true;
                    break;
                }
            }

            if (!blocked)
            {
//				SetPathLineTiles(coords);
                break;
            }
            --index;
        }

        if (index == 0)
        {
            coords = new List <COORD>();
            coords.Add(new COORD(_path.nodes [index].x, _path.nodes [index].z));
//			SetPathLineTiles(coords);
        }

        MapAStar.NODE nodeShortPath   = _path.nodes [index];
        Vector2       centerShortPath = MapGrid.GetTileCenter(nodeShortPath.x, nodeShortPath.z);

        _targetTileCenter = new Vector3(centerShortPath.x, 0, centerShortPath.y);

        return(coords);
    }
Пример #13
0
        private void StartCore()
        {
            if (!_attr.Sys.UseTty)
            {
                throw new Exception("Only a new process with controlled tty supported");
            }

            _inputPipe  = new Win32Pipe();
            _outputPipe = new Win32Pipe();

            var size = new COORD
            {
                X = DEFAULT_WIDTH,
                Y = DEFAULT_HEIGHT,
            };

            var result = Kernel32.CreatePseudoConsole(
                size: size,
                hInput: _inputPipe.Read,
                hOutput: _outputPipe.Write,
                dwFlags: 0,
                phPC: out _ptyHandle
                );

            if (result != 0)
            {
                throw new Win32Exception(result, "Could not create pseudo console.");
            }

            startupInfo = ConfigureProcessThread(_ptyHandle, (IntPtr)Kernel32.PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE);
            processInfo = RunProcess(ref startupInfo, _fileName);

            if (_attr.RedirectStdin)
            {
                var inStream = new FileStream(_inputPipe.Write, FileAccess.Write);
                Stdin = new StreamWriter(inStream);
            }

            if (_attr.RedirectStdout)
            {
                var outStream = new FileStream(_outputPipe.Read, FileAccess.Read);
                Stdout = new StreamReader(outStream);
            }

            Pid       = processInfo.dwProcessId;
            IsRunning = true;
        }
        public static char GetCharacterAtPosition(EngineFunctions.COORD pos)
        {
            IntPtr        handler      = GetStdHandle(STD_OUTPUT_HANDLE);
            uint          width        = 1;
            StringBuilder sb           = new StringBuilder((int)width);
            COORD         readCoord    = new COORD(pos.X, pos.Y);
            uint          numCharsRead = 0;

            if (!ReadConsoleOutputCharacter(handler, sb, width, readCoord, out numCharsRead))
            {
                return((char)0);
            }
            else
            {
                return(sb.ToString()[0]);
            }
        }
Пример #15
0
        public static CharInfo GetCharInfo(int x, int y)
        {
            COORD      size = new COORD(1, 1);
            SMALL_RECT rect = new SMALL_RECT(new COORD((short)x, (short)y), size);

            CharInfo[,] chars = new CharInfo[1, 1];
            WinApi.ReadConsoleOutput(
                bufferHandle,
                chars,
                size,
                new COORD(0, 0),
                ref rect
                );
            CharInfo info = chars[0, 0];

            return(info);
        }
Пример #16
0
        public static IEnumerable<string> ReadFromBuffer(short x, short y, short width, short height)
        {
            IntPtr buffer = Marshal.AllocHGlobal(width * height * Marshal.SizeOf(typeof(CHAR_INFO)));
            if (buffer == null)
                throw new OutOfMemoryException();

            try
            {
                COORD coord = new COORD();
                SMALL_RECT rc = new SMALL_RECT();
                rc.Left = x;
                rc.Top = y;
                rc.Right = (short)(x + width - 1);
                rc.Bottom = (short)(y + height - 1);

                COORD size = new COORD();
                size.X = width;
                size.Y = height;

                const int STD_OUTPUT_HANDLE = -11;
                if (!ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE), buffer, size, coord, ref rc))
                {
                    // 'Not enough storage is available to process this command' may be raised for buffer size > 64K (see ReadConsoleOutput doc.)
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                IntPtr ptr = buffer;
                for (int h = 0; h < height; h++)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int w = 0; w < width; w++)
                    {
                        CHAR_INFO ci = (CHAR_INFO)Marshal.PtrToStructure(ptr, typeof(CHAR_INFO));
                        char[] chars = Console.OutputEncoding.GetChars(ci.charData);
                        sb.Append(chars[0]);
                        ptr += Marshal.SizeOf(typeof(CHAR_INFO));
                    }
                    yield return sb.ToString();
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
Пример #17
0
        /// <summary>
        /// Retrieve character from console window
        /// </summary>
        /// <param name="coordinate"></param>
        /// <param name="ptr"></param>
        /// <returns>One character</returns>
        public static char GetChar(COORD coordinate, IntPtr ptr)
        {
            // Convert the coordinates to a uint containing both
            uint coord = (uint)coordinate.X;

            coord |= (uint)coordinate.Y << 16;

            if (!ReadConsoleOutputCharacterW(
                    ptr,
                    out char chUnicode,     // result: single Unicode char
                    1,                      // # of chars to read
                    coord,                  // (X,Y) screen location to read (see above)
                    out _))                 // result: actual # of chars (unwanted)
            {
                throw new Win32Exception();
            }
            return(chUnicode);
        }
Пример #18
0
        public static void SetSize(int width, int height, int bufferHeight = -1)
        {
            if (width > 0 && width <= MaximumWidth && height > 0 && height <= MaximumHeight)
            {
                COORD bufferSize = GetConsoleBufferSize();

                if (bufferSize.X > width || bufferSize.Y > height)
                {
                    SetWindowSize(
                        Math.Min(width, bufferSize.X) - 1,
                        Math.Min(height, bufferSize.Y) - 1
                        );
                }

                SetBufferSize(width, bufferHeight > 0 ? bufferHeight : height);
                SetWindowSize(width - 1, height - 1);
            }
        }
Пример #19
0
    public static void CLS()
    {
        IntPtr hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

        CONSOLE_SCREEN_BUFFER_INFO csbi = new CONSOLE_SCREEN_BUFFER_INFO();

        if (!GetConsoleScreenBufferInfo(hConsole, ref csbi))
        {
            throw new ApplicationException("CLS não pode executado");
        }

        long dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

        COORD coordScreen = new COORD();

        coordScreen.Y = coordScreen.X = 0;

        long cCharsWritten = 0;

        if (FillConsoleOutputCharacter(hConsole, ' ', dwConSize, coordScreen, ref cCharsWritten))
        {
            throw new ApplicationException("CLS não pode executado");
        }

        if (!GetConsoleScreenBufferInfo(hConsole, ref csbi))
        {
            throw new ApplicationException("Problema no reposicionamento1");
        }

        if (FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, ref cCharsWritten))
        {
            throw new ApplicationException("Problema no reposicionamento2");
        }

        if (!SetConsoleCursorPosition(hConsole, coordScreen))
        {
            throw new ApplicationException("Problema no reposicionamento3");
        }

        if (!CloseHandle(hConsole))
        {
            throw new ApplicationException("Handle não liberado");
        }
    }
Пример #20
0
        private ConsoleEvent GetConsoleEvent()
        {
            // CONSIDER: Any reason to buffer more than one record in our Win32Console class?
            var  records = new INPUT_RECORD[1];
            uint count;

            if (!ReadConsoleInput(_handleIn, records, (uint)records.Length, out count))
            {
                throw new Exception("ReadConsoleInput failed");
            }

            var record = records[0];

            switch (record.EventType)
            {
            case EventType.KEY_EVENT:
            {
                var keyEvent = record.KeyEvent;
                return(new KeyEvent(keyEvent.bKeyDown, keyEvent.UnicodeChar, keyEvent.wRepeatCount, keyEvent.wVirtualKeyCode, keyEvent.dwControlKeyState));
            }

            case EventType.MOUSE_EVENT:
            {
                var mouseEvent = record.MouseEvent;
                return(new MouseEvent(mouseEvent.dwMousePosition.x, mouseEvent.dwMousePosition.y, mouseEvent.dwButtonState, mouseEvent.dwControlKeyState, mouseEvent.dwEventFlags));
            }

            case EventType.WINDOW_BUFFER_SIZE_EVENT:
            {
                COORD size = record.WindowBufferSizeEvent.dwSize;
                return(new BufferSizeEvent(size.x, size.y));
            }

            case EventType.FOCUS_EVENT:
            case EventType.MENU_EVENT:
            {
                // Ignore.
                return(null);
            }

            default:
                throw new Exception("Invalid EventType enum value");
            }
        }
Пример #21
0
        public static void DrawRectangle(int left, int top, int right, int bottom)
        {
            if (!AreScreenBufferArraysEqual(left, top, right, bottom))
            {
                int rows = bottom - top + 1;
                int cols = right - left + 1;

                CHAR_INFO[] rectBuf = new CHAR_INFO[rows * cols];

                int i = 0;
                for (int row = top; row <= bottom; row++)
                {
                    for (int col = left; col <= right; col++)
                    {
                        rectBuf[i++] = ScreenBuffer.screenBuf[(row * ScreenBuffer.cols) + col];
                    }
                }

                COORD rectBufSize = new COORD()
                {
                    X = (short)cols, Y = (short)rows
                };
                COORD rectBufCoord = new COORD()
                {
                    X = 0, Y = 0
                };

                SMALL_RECT rectangle = new SMALL_RECT()
                {
                    Left = (short)left, Top = (short)top, Right = (short)right, Bottom = (short)bottom
                };

                // note that the screen is NOT cleared at any point as this will simply
                // overwrite the existing values on screen. Clearing will cause flickering again.
                bool b = WriteConsoleOutput(
                    ScreenBuffer.handle,
                    rectBuf,
                    rectBufSize,
                    rectBufCoord,
                    ref rectangle);

                Array.Copy(ScreenBuffer.screenBuf, ScreenBuffer.screenBufCopy, ScreenBuffer.screenBuf.Length);
            }
        }
Пример #22
0
    public static GameObject[] CreateBattleTeam(InstanceTeam team, DataConfig.TEAM teamSide,
                                                COORD location, COORD playerLocation, float rotationDegree)
    {
        int n = team.units.Length;

        GameObject[] objects = new GameObject[n];

        for (int i = 0; i < n; ++i)
        {
            InstanceUnit unit = team.units[i];
            if (unit != null)
            {
                GameObject obj = CreateBattleUnit(unit, i, teamSide, location, playerLocation, rotationDegree);
                objects[i] = obj;
            }
        }

        return(objects);
    }
Пример #23
0
    public void AddSelfToGrid()
    {
        COORD c = MapGrid.GetTileCoord(_unit.transform.position.x, _unit.transform.position.z);

        if (_mapGrid.IsInsideMap(c.x, c.z))
        {
            _tiles.Add(c);
            _mapGrid.Add(c.x, c.z);
        }

        if (USER_SQUARE)
        {
            float r = _unit.unit.dataUnit.GetCollisionRadius();

            COORD c1 = MapGrid.GetTileCoord(_unit.transform.position.x - r, _unit.transform.position.z);
            if (_mapGrid.IsInsideMap(c1.x, c1.z))
            {
                _tiles.Add(c1);
                _mapGrid.Add(c1.x, c1.z);
            }

            COORD c2 = MapGrid.GetTileCoord(_unit.transform.position.x + r, _unit.transform.position.z);
            if (_mapGrid.IsInsideMap(c2.x, c2.z))
            {
                _tiles.Add(c2);
                _mapGrid.Add(c2.x, c2.z);
            }

            COORD c3 = MapGrid.GetTileCoord(_unit.transform.position.x, _unit.transform.position.z - r);
            if (_mapGrid.IsInsideMap(c3.x, c3.z))
            {
                _tiles.Add(c3);
                _mapGrid.Add(c3.x, c3.z);
            }

            COORD c4 = MapGrid.GetTileCoord(_unit.transform.position.x, _unit.transform.position.z + r);
            if (_mapGrid.IsInsideMap(c4.x, c4.z))
            {
                _tiles.Add(c4);
                _mapGrid.Add(c4.x, c4.z);
            }
        }
    }
Пример #24
0
        private static CHAR_INFO[] ReadBufferLines(int top, int count)
        {
            var result = new CHAR_INFO[Console.BufferWidth * count];
            var handle = NativeMethods.GetStdHandle((uint) StandardHandleId.Output);

            var readBufferSize = new COORD {
                X = (short)Console.BufferWidth,
                Y = (short)count};
            var readBufferCoord = new COORD {X = 0, Y = 0};
            var readRegion = new SMALL_RECT
            {
                Top = (short)top,
                Left = 0,
                Bottom = (short)(top + count),
                Right = (short)(Console.BufferWidth - 1)
            };
            NativeMethods.ReadConsoleOutput(handle, result,
                readBufferSize, readBufferCoord, ref readRegion);
            return result;
        }
Пример #25
0
        public static void Draw(CHAR_INFO[] buffer, int width, int height, int x = 0, int y = 0)
        {
            COORD bufferSize = new COORD();

            bufferSize.x = (short)width;
            bufferSize.y = (short)height;

            COORD bufferCoord = new COORD();

            bufferCoord.x = 0;
            bufferCoord.y = 0;

            SMALL_RECT lpWriteRegion = new SMALL_RECT();

            lpWriteRegion.Left   = (short)x;
            lpWriteRegion.Top    = (short)y;
            lpWriteRegion.Bottom = (short)(y + height);
            lpWriteRegion.Right  = (short)(x + width);

            WriteConsoleOutputW(handle, buffer, bufferSize, bufferCoord, ref lpWriteRegion);
        }
Пример #26
0
        public static void Draw()
        {
            COORD bufferSize = new COORD();

            bufferSize.x = (short)Width;
            bufferSize.y = (short)Height;

            COORD bufferCoord = new COORD();

            bufferCoord.x = 0;
            bufferCoord.y = 0;

            SMALL_RECT lpWriteRegion = new SMALL_RECT();

            lpWriteRegion.Left   = 0;
            lpWriteRegion.Top    = 0;
            lpWriteRegion.Bottom = (short)(Height);
            lpWriteRegion.Right  = (short)(Width);

            WriteConsoleOutputW(handle, screen_buffer, bufferSize, bufferCoord, ref lpWriteRegion);
        }
Пример #27
0
        public void Blit(Rectangle rect)
        {
            COORD sz = new COORD();

            sz.X = (short)consize.Width;
            sz.Y = (short)consize.Height;

            COORD pos = new COORD();

            pos.X = (short)rect.X;
            pos.Y = (short)rect.Y;

            SMALL_RECT rgn = new SMALL_RECT();

            rgn.Left   = (short)rect.X;
            rgn.Top    = (short)rect.Y;
            rgn.Right  = (short)(rect.X + rect.Width - 1);
            rgn.Bottom = (short)(rect.Y + rect.Height - 1);

            bool success = WriteConsoleOutput(output, buf, sz, pos, ref rgn);
        }
Пример #28
0
        static ConsoleEx()
        {
            // Grab input and output buffer handles
            hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
            hConsoleInput  = GetStdHandle(STD_INPUT_HANDLE);
            if (hConsoleOutput == INVALID_HANDLE_VALUE || hConsoleInput == INVALID_HANDLE_VALUE)
            {
                throw new ApplicationException("Unable to obtain buffer handle during initialization.");
            }

            // Get information about the console window characteristics.
            ConsoleInfo           = new CONSOLE_SCREEN_BUFFER_INFO();
            ConsoleOutputLocation = new COORD();
            GetConsoleScreenBufferInfo(hConsoleOutput, ref ConsoleInfo);
            OriginalConsolePen = ConsoleInfo.wAttributes;

            // Disable wrapping at the end of a line (ENABLE_WRAP_AT_EOL_INPUT); this enables rectangles
            // to be drawn that fill the screen without the window scrolling.
            SetConsoleMode(hConsoleOutput,
                           (int)OutputModeFlags.ENABLE_PROCESSED_OUTPUT);
        }
Пример #29
0
    private bool IsDestinationBlocked(Vector3 destination)
    {
        //should already remove self grid block, so don't need to check whether grid is change
        //that means if unit alread inside a grid is blocked, then it is blocked by other unit

        //		COORD c1 = MapGrid.GetTileCoord (_owner.transform.position.x, _owner.transform.position.z);
        COORD c2 = MapGrid.GetTileCoord(destination.x, destination.z);

        //		if(c1.IsEqual(c2))
        //		{
        //			return false;
        //		}

        if (_game.mapGrid.IsBlock(c2.x, c2.z))
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Пример #30
0
    private void ValidatePositions()
    {
        COORD[] positions = new COORD[5];
        positions [0] = startPosition;
        positions [1] = extraPositionA;
        positions [2] = extraPositionB;
        positions [3] = extraPositionC;
        positions [4] = extraPositionD;

        for (int i = 0; i < positions.Length; ++i)
        {
            for (int j = i + 1; j < positions.Length; ++j)
            {
                if (positions[i] != null && positions[j] != null)
                {
                    int dx = positions[i].x - positions[j].x;
                    int dz = positions[i].z - positions[j].z;
                    Assert.assert(Mathf.Abs(dx) >= 3 || Mathf.Abs(dz) >= 3);
                }
            }
        }
    }
Пример #31
0
        /// <summary>
        ///     Copies a given character to a rectangular region of the screen
        ///     buffer.
        /// </summary>
        /// <param name="rectangle">A Rectangle structure that defines the area to be filled.</param>
        /// <param name="fill">A BufferCell structure that defines the fill character.</param>
        public override void SetBufferContents(Rectangle rectangle, BufferCell fill)
        {
            var   stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
            COORD coord  = new COORD()
            {
                X = (short)rectangle.Top, Y = (short)rectangle.Left
            };
            var  rows   = rectangle.Top - rectangle.Bottom;
            var  cols   = rectangle.Right - rectangle.Left;
            uint length = (uint)(rows * cols);

            if (length == 0)
            {
                length = (uint)(Console.BufferWidth * Console.BufferHeight);
                coord  = new COORD()
                {
                    X = 0, Y = 0
                };
            }
            uint written;
            int  res = FillConsoleOutputCharacter(stdOut, fill.Character, length, coord, out written);
        }
Пример #32
0
    // Update is called once per frame
    public void Update()
    {
        if (_hasPath)
        {
            COORD currentCoord = MapGrid.GetTileCoord(_unit.transform.position.x, _unit.transform.position.z);
            COORD targetCoord  = MapGrid.GetTileCoord(_targetTileCenter.x, _targetTileCenter.z);
            if (currentCoord.IsEqual(targetCoord))
            {
                _hasPath = false;
            }

            /*
             * foreach(MapAStar.NODE node in _path.nodes)
             * {
             *      if(tileCoord.x == node.x && tileCoord.z == node.z)
             *      {
             *              _hasPath = false;
             *              break;
             *      }
             * }
             */
        }
    }
Пример #33
0
    public void InitShowTile()
    {
        GameObject root = new GameObject();

        root.name = "HEXAGON_ROOT";

        _tileObjects = new GameObject[MAP_GRID_COUNT_X * MAP_GRID_COUNT_Z];

        string asset  = AppConfig.FOLDER_PROFAB + "tile/hexagon";
        Object profab = Resources.Load(asset);

        for (int x = 0; x < MAP_GRID_COUNT_X; ++x)
        {
            for (int z = 0; z < MAP_GRID_COUNT_Z; ++z)
            {
                GameObject tile = GameObject.Instantiate(profab) as GameObject;
                tile.transform.parent = root.transform;

                tile.transform.localScale = new Vector3(1.732f * HEXAGON_L, 0.1f, 1.732f * HEXAGON_L);
                Vector2 tileCenter = GetTileCenter(x, z);

                if (AppConfig.DEBUGGING)
                {
                    //validate tile coord <-> pos algorithm
                    COORD tileCoord = GetTileCoord(tileCenter.x, tileCenter.y);
                    if (tileCoord.x != x || tileCoord.z != z)
                    {
                        Assert.assert(false);
                    }
                }

                tile.transform.position = new Vector3(tileCenter.x, 0, tileCenter.y);

                _tileObjects[GetGridIndex(x, z)] = tile;
            }
        }
    }
Пример #34
0
    public void InitShowTile()
    {
        GameObject root = new GameObject();

        root.name = "HEXAGON_ROOT";

        _tileObjects = new GameObject[mapGridWidth * mapGridHeight];

        string asset  = AppConfig.FOLDER_PROFAB + "tile/square";
        Object profab = Resources.Load(asset);

        for (int x = 0; x < mapGridWidth; ++x)
        {
            for (int z = 0; z < mapGridHeight; ++z)
            {
                GameObject tile = GameObject.Instantiate(profab) as GameObject;
                tile.transform.parent = root.transform;

                tile.transform.localScale = new Vector3(GRID_SIZE - 0.5f, 0.1f, GRID_SIZE - 0.5f);
                Vector2 tileCenter = GetTileCenter(x, z);

                if (AppConfig.DEBUGGING)
                {
                    //validate tile coord <-> pos algorithm
                    COORD tileCoord = GetTileCoord(tileCenter.x, tileCenter.y);
                    if (tileCoord.x != x || tileCoord.z != z)
                    {
                        Assert.assert(false);
                    }
                }

                tile.transform.position = new Vector3(tileCenter.x, 0, tileCenter.y);

                _tileObjects[GetGridIndex(x, z)] = tile;
            }
        }
    }
        private void processInputEvent(INPUT_RECORD inputRecord)
        {
            if (inputRecord.EventType == EventType.WINDOW_BUFFER_SIZE_EVENT)
            {
                if (usingLinux)
                {
                    // Reinitializing ncurses to deal with new dimensions
                    // http://stackoverflow.com/questions/13707137/ncurses-resizing-glitch
                    NCurses.endwin();
                    // Needs to be called after an endwin() so ncurses will initialize
                    // itself with the new terminal dimensions.
                    NCurses.refresh();
                    NCurses.clear();
                }

                COORD dwSize = inputRecord.WindowBufferSizeEvent.dwSize;

                // Invoke default handler if no custom handlers attached and
                // userCanvasSize and userRootElementRect are not defined
                if (TerminalSizeChanged == null &&
                    userCanvasSize.IsEmpty &&
                    userRootElementRect.IsEmpty)
                {
                    OnTerminalSizeChangedDefault(this, new TerminalSizeChangedEventArgs(dwSize.X, dwSize.Y));
                }
                else if (TerminalSizeChanged != null)
                {
                    TerminalSizeChanged.Invoke(this, new TerminalSizeChangedEventArgs(dwSize.X, dwSize.Y));
                }

                // Refresh whole display
                renderer.FinallyApplyChangesToCanvas(true);

                return;
            }
            eventManager.ParseInputEvent(inputRecord, mainControl);
        }
Пример #36
0
    public static GameObject[][] CreateBattleUnits(InstanceBattle battle, DataMap dataMap)
    {
        int totalGroup = 1 + battle.extraTeamCount;

        GameObject[][] objects = new GameObject[totalGroup][];

        GameObject[] myObjects = CreateBattleTeam(battle.myTeam, DataConfig.TEAM.MY, dataMap.startPosition, dataMap.startPosition, battle.mission.playerRotation);
        objects [0] = myObjects;

        for (int i = 1; i < totalGroup; ++i)
        {
            int   teamIndex = i - 1;
            COORD location  = dataMap.GetExtraPosition(teamIndex);

            InstanceTeam enemyTeam  = battle.enemyTeams[teamIndex];
            InstanceTeam friendTeam = battle.friendTeams[teamIndex];
            Assert.assert(enemyTeam == null || friendTeam == null);

            float teamRotation = battle.mission.teamsRotation[teamIndex];

            GameObject[] members = null;
            if (enemyTeam != null)
            {
                Assert.assert(location != null);
                members = CreateBattleTeam(enemyTeam, DataConfig.TEAM.ENEMY, location, dataMap.startPosition, teamRotation);
            }
            if (friendTeam != null)
            {
                Assert.assert(location != null);
                members = CreateBattleTeam(friendTeam, DataConfig.TEAM.FRIEND, location, dataMap.startPosition, teamRotation);
            }
            objects [i] = members;
        }

        return(objects);
    }
Пример #37
0
 public static extern bool SetConsoleDisplayMode(
     IntPtr ConsoleOutput,
     uint Flags,
     out COORD NewScreenBufferDimensions
     );
Пример #38
0
        public string readvalue(ref System.IntPtr ptr, short a)
        {
            SMALL_RECT srctReadRect = new SMALL_RECT
            {
                Top = 0,
                Left = 0,
                Bottom = 1,
                Right = 80
            };
            CHAR_INFO[,] chiBuffer = new CHAR_INFO[2, 80]; // [2][80];10 lines,  with 50 characters

            COORD coordBufSize = new COORD
            {
                X = 80,
                Y = 2
            };
            COORD coordBufCoord = new COORD
            {
                X = 0,
                Y = 0
            };

            bool fSuccess;
            int i = 0;
            int j = 0;
            string chartostring = "start";
            string previousstring = "";

            short g = a;
            short h = (short)(g + 1);

            srctReadRect.Top = g;
            srctReadRect.Bottom = h;
            int count = 0;

            //System.Console.WriteLine(g + "." + h);
            while (count < 1)//Hunting:if it find 1 empty rows with text then it will stop reading
            {
                previousstring = chartostring;
                srctReadRect.Top = g;
                srctReadRect.Bottom = h;

                fSuccess = ReadConsoleOutput(ptr, chiBuffer, coordBufSize, coordBufCoord, ref srctReadRect);

                i = 0;
                j = 0;
                chartostring = "";
                while (j < coordBufSize.Y)
                {
                    while (i < coordBufSize.X)
                    {
                        if (chiBuffer[j, i].UnicodeChar != 0 && chiBuffer[j, i].UnicodeChar != 32)
                            chartostring += chiBuffer[j, i].UnicodeChar;
                        i++;
                    }
                    i = 0;
                    j++;
                }

                if (chartostring.Length == 0)//The character length is zero, reverse the top of the source rect
                {
                    count++;
                }
                else
                {
                    count = 0;
                }
                g += 1;
                h += 1;
            }
            return previousstring;
        }
Пример #39
0
 internal static extern bool SetConsoleCursorPosition(IntPtr hConsoleOutput, 
     COORD cursorPosition);
Пример #40
0
 internal static unsafe extern bool WriteConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* buffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT writeRegion);
Пример #41
0
 public static extern bool WriteConsoleOutputCharacter(
     IntPtr hConsoleOutput,
     string lpCharacter,
     uint nLength,
     COORD dwWriteCoord,
     out uint lpNumberOfCharsWritten
     );
Пример #42
0
 public static extern bool WriteConsoleOutputAttribute(
     IntPtr hConsoleOutput,
     ushort[] lpAttribute,
     uint nLength,
     COORD dwWriteCoord,
     out uint lpNumberOfAttrsWritten
     );
Пример #43
0
 public static extern bool WriteConsoleOutput(
     IntPtr hConsoleOutput,
     CHAR_INFO[] lpBuffer,
     COORD dwBufferSize,
     COORD dwBufferCoord,
     ref SMALL_RECT lpWriteRegion
     );
Пример #44
0
 public static extern bool SetConsoleScreenBufferSize(
     IntPtr hConsoleOutput,
     COORD dwSize
     );
Пример #45
0
	private static extern int FillConsoleOutputCharacter(int hConsoleOutput, byte cCharacter, int nLength, COORD dwWriteCoord, ref int lpNumberOfCharsWritten);
Пример #46
0
        private int ConvertLineAndColumnToOffset(COORD coord)
        {
            int offset;
            int x = _initialX;
            int y = _initialY + Options.ExtraPromptLineCount;

            int bufferWidth = _console.BufferWidth;
            var continuationPromptLength = Options.ContinuationPrompt.Length;
            for (offset = 0; offset < _buffer.Length; offset++)
            {
                // If we are on the correct line, return when we find
                // the correct column
                if (coord.Y == y && coord.X <= x)
                {
                    return offset;
                }
                char c = _buffer[offset];
                if (c == '\n')
                {
                    // If we are about to move off of the correct line,
                    // the line was shorter than the column we wanted so return.
                    if (coord.Y == y)
                    {
                        return offset;
                    }
                    y += 1;
                    x = continuationPromptLength;
                }
                else
                {
                    int size = LengthInBufferCells(c);
                    x += size;
                    // Wrap?  No prompt when wrapping
                    if (x >= bufferWidth)
                    {
                        int offsize = x - bufferWidth;
                        if (offsize % size == 0)
                        {
                            x -= bufferWidth;
                        }
                        else
                        {
                            x = size;
                        }
                        y += 1;
                    }
                }
            }

            // Return -1 if y is out of range, otherwise the last line was shorter
            // than we wanted, but still in range so just return the last offset.
            return (coord.Y == y) ? offset : -1;
        }
Пример #47
0
 internal static extern bool FillConsoleOutputCharacter(IntPtr hConsoleOutput,
     char character, int nLength, COORD dwWriteCoord, out int pNumCharsWritten);
Пример #48
0
 static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput,
     [Out] StringBuilder lpCharacter, uint nLength, COORD dwReadCoord,
     out uint lpNumberOfCharsRead);
 public static extern bool WriteConsoleOutputCharacter(
     IntPtr hConsoleOutput,          // handle to screen buffer
     string lpCharacter,            // characters
     uint nLength,                  // number of characters to write
     COORD dwWriteCoord,             // first cell coordinates
     ref uint lpNumberOfCharsWritten  // number of cells written
     );
Пример #50
0
 internal static extern bool SetConsoleScreenBufferSize(IntPtr hConsoleOutput, COORD size);
Пример #51
0
 public static extern bool ScrollConsoleScreenBuffer(
     IntPtr hConsoleOutput,
    [In] ref SMALL_RECT lpScrollRectangle,
     IntPtr lpClipRectangle,
    COORD dwDestinationOrigin,
     [In] ref CHAR_INFO lpFill
     );
Пример #52
0
 internal static extern bool FillConsoleOutputAttribute(IntPtr hConsoleOutput,
     short wColorAttribute, int numCells, COORD startCoord, out int pNumBytesWritten);
Пример #53
0
 public static extern bool FillConsoleOutputAttribute(IntPtr Handle, short att, int Len, COORD start, ref int writted);
Пример #54
0
 internal static unsafe extern bool ReadConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* pBuffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT readRegion);
Пример #55
0
 public static extern int FillConsoleOutputCharacter(IntPtr Handle, char uChar, int Len, COORD start, ref int written);
Пример #56
0
		private static extern int SetConsoleCursorPosition(int hConsoleOutput, COORD dwCursorPosition);
Пример #57
0
 public static extern bool ReadConsoleOutputAttribute(
     IntPtr hConsoleOutput,
     [Out] ushort[] lpAttribute,
     uint nLength,
     COORD dwReadCoord,
     out uint lpNumberOfAttrsRead
     );
Пример #58
0
 internal static extern bool FillConsoleOutputAttribute(IntPtr hConsole, ushort wAttributes, int nLength, COORD dwWriteCoord, out uint written);
Пример #59
0
 public static extern bool SetConsoleCursorPosition(
     IntPtr hConsoleOutput,
    COORD dwCursorPosition
     );
Пример #60
-1
 // Constructor.
 public ColorConsole()
 {
     ConsoleInfo = new CONSOLE_SCREEN_BUFFER_INFO();
     ConsoleOutputLocation = new COORD();
     hConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
     GetConsoleScreenBufferInfo(hConsoleHandle, ref ConsoleInfo);
     OriginalColors = ConsoleInfo.wAttributes;
 }