public unsafe static void PutPixels(WriteableBitmap bitmap, PixelColor[,] pixels, int x, int y) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); var stride = width * ((bitmap.Format.BitsPerPixel + 7) / 8); byte[] pixel = new byte[height * stride]; Parallel.For(0, height, n => { int m; for (m = 0; m < width; m++) { pixel[(n * width + m) * 4 + 0] = pixels[m, n].Blue; pixel[(n * width + m) * 4 + 1] = pixels[m, n].Green; pixel[(n * width + m) * 4 + 2] = pixels[m, n].Red; pixel[(n * width + m) * 4 + 3] = pixels[m, n].Alpha; } }); fixed(byte *buffer = &pixel[0]) bitmap.WritePixels( new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight), (IntPtr)(buffer), width * height * sizeof(PixelColor), stride); }
public static bool CompareImages(PixelColor[,] p1, PixelColor[,] p2) { if (p1.GetLength(0) != p2.GetLength(0)) { return(false); } long red = 0, green = 0, blue = 0; for (int i = 1; i < p1.GetLength(0) - 1; i++) { for (int j = 1; j < p1.GetLength(1) - 1; j++) { PixelColor color = p1[i, j]; PixelColor average = getAverageColor(p2, i, j); PixelColor diff = color - average; red += diff.Red; green += diff.Green; blue += diff.Blue; } } red = (int)((float)red / p1.Length); green = (int)((float)green / p1.Length); blue = (int)((float)blue / p1.Length); float total = (float)(red + green + blue) / 3f; return(total < 6); }
void GenerateMap(Uri uri) { ImageDataLoader imageDataLoader = new ImageDataLoader(uri); PixelColor[,] pixels = imageDataLoader.GetPixels(); int countX = pixels.GetLength(0); int countZ = pixels.GetLength(1); int startX = 0; int startZ = 0; int gridStep = 100; double minY = -300; double maxY = 3000; ImageData imageData = new ImageData( new DoubleCollection(countX), new DoubleCollection(countZ), new DoubleCollection(countX * countZ) ); bool fullZ = false; for (int i = 0; i < countX; i++) { imageData.XArguments.Add(startX + i * gridStep); for (int j = 0; j < countZ; j++) { if (!fullZ) { imageData.YArguments.Add(startZ + j * gridStep); } double value = GetValue(pixels[i, j], minY, maxY); imageData.Values.Add(value); } fullZ = true; } ImageData = imageData; }
public static Texture2D Texture2DFromPixelsTopLeft(PixelColor[,] pixels) { int ImgH = pixels.GetLength(0); int ImgW = pixels.GetLength(1); var texture2D = new Texture2D(ImgW, ImgH); var c = new Color32[pixels.Length]; for (var i = 0; i < ImgH; i++) { for (var j = 0; j < ImgW; j++) { var p = pixels[i, j]; var col = new Color32(p.Red, p.Green, p.Blue, p.Alpha); c[i * ImgW + j] = col; } } texture2D.SetPixels32(c); // DPI must be same as original image, otherwise rescaling display can occur (NoScaling) //var wBitmap = new WriteableBitmap(ImgW, ImgH, DpiX, DpiY, System.Windows.Media.PixelFormats.Bgra32, null); // 1) copy PixelsOut to bitmap // qq to do: ImgW or ImgW-1 in rect??; stride=0 seems to work ... //Int32Rect sourceRect = new Int32Rect(0, 0, ImgW, ImgH); //wBitmap.WritePixels(sourceRect, PixelsTopLeft, ImgW * 4, 0); // 2) set Image1.Source=wBitmap; e.g. handle change source in Bitmap. return(texture2D); }
public unsafe static void CopyPixels(this BitmapSource source, PixelColor[,] pixels, int stride, int offset) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); byte[] pixel = new byte[height * stride]; fixed(byte *buffer = &pixel[0]) source.CopyPixels( new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), (IntPtr)(buffer + offset), width * height * sizeof(PixelColor), stride); Parallel.For(0, height, n => { int m; for (m = 0; m < width; m++) { pixels[m, n].Blue = pixel[(n * width + m) * 4 + 0]; pixels[m, n].Green = pixel[(n * width + m) * 4 + 1]; pixels[m, n].Red = pixel[(n * width + m) * 4 + 2]; pixels[m, n].Alpha = pixel[(n * width + m) * 4 + 3]; } }); }
private static void Validate(PixelColor[,] pixels) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { // Check the image is loaded correctly, but note that // what constitutes a closed pixel will change. var closedPixel = x == 4 || x == 5 || y == 4 || y == 5; var pixel = pixels[x, y]; bool r; bool g; bool b; if (closedPixel) { r = pixel.Red == 0; g = pixel.Green == 0; b = pixel.Blue == 0; } else { r = pixel.Red == 255; g = pixel.Green == 255; b = pixel.Blue == 255; } Assert.IsTrue(r && g && b, "Pixel Invalid"); } } }
public static void PutPixels(this WriteableBitmap bitmap, PixelColor[,] pixels, int x, int y) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, x, y); }
public MapState[,] GetExplorationMap(IPixelComparer pixelComparer, PixelColor[,] source) { int width = source.GetLength(0); int height = source.GetLength(1); var cellState = new MapState[width, height]; // TODO: Parallelise // TODO: Refactor into Strategy pattern. for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { var newColor = source[x, y] .ToColor(); var open = pixelComparer .IsOpen(newColor); cellState[x, y] = open ? MapState.AsOpen() : MapState.AsClosed(); } } return(cellState); }
PixelColor Dilation_Crossdot(PixelColor[,] temp, int x, int y, int ksize) { int k, l, m, n; byte checkpixel_R = 0; byte checkpixel_G = 0; byte checkpixel_B = 0; var weidth = temp.GetLength(0); var height = temp.GetLength(1); for (int i = 0; i < ksize; i++) { k = (i - ksize / 2); for (int j = 0; j < ksize; j++) { l = (j - ksize / 2); m = ((x - k) >= 0 && (x - k) < weidth) ? (x - k) : x + k; n = ((y - l) >= 0 && (y - l) < height) ? (y - l) : y + l; checkpixel_R = Math.Max(checkpixel_R, temp[m, n].Red); checkpixel_G = Math.Max(checkpixel_G, temp[m, n].Green); checkpixel_B = Math.Max(checkpixel_B, temp[m, n].Blue); } } return(new PixelColor { Blue = checkpixel_B, Green = checkpixel_G, Red = checkpixel_R, Alpha = temp [x, y].Alpha }); }
protected void SetPixel(int x, int y, PixelColor c) { if (x < 0 || y < 0 || x >= colorMap.GetLength(0) || y >= colorMap.GetLength(1)) { return; } colorMap[x, y] = c; }
public unsafe static void CopyPixels(BitmapSource source, PixelColor[,] pixels, int stride, int offset) { fixed(PixelColor *buffer = &pixels[0, 0]) source.CopyPixels( new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), (IntPtr)(buffer + offset), pixels.GetLength(0) * pixels.GetLength(1) * sizeof(PixelColor), stride); }
public static void RemoveWeakColors() { PixelColor[,] pixels = CurrentState.currentPixels; for (int i = 0; i < pixels.GetLength(0); i++) { for (int j = 0; j < pixels.GetLength(1); j++) { CurrentState.currentPixels[i, j].RemoveWeakColors(); } } }
public static void ToOneBit() { PixelColor[,] pixels = CurrentState.currentPixels; for (int i = 0; i < pixels.GetLength(0); i++) { for (int j = 0; j < pixels.GetLength(1); j++) { pixels[i, j].ToOneBit(); } } }
public static void IntensifyHighBitsReduceLowBits(byte amount) { PixelColor[,] pixels = CurrentState.currentPixels; for (int i = 0; i < pixels.GetLength(0); i++) { for (int j = 0; j < pixels.GetLength(1); j++) { pixels[i, j].IntensifyHighBitsReduceLowBits(amount); } } }
private void ResolutionSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs <double> e) { Kernel = (int)resolutionSlider.Value; if (IsStart && pixels != null) { EnableTextBoxes((int)resolutionSlider.Value); ASCIIWidthTextBox.Text = (pixels.GetLength(0) / (int)resolutionSlider.Value).ToString(); ASCIIHeightTextBox.Text = (pixels.GetLength(1) / (int)resolutionSlider.Value).ToString(); } else { IsStart = true; } }
public override void Render(PixelColor[,] colorMap) { if (client != null && client.Connected && stream != null) { ledCount = colorMap.GetLength(0) * colorMap.GetLength(1); numBytes = 3 * ledCount; packetLen = 4 + numBytes; byte[] packetData = new byte[packetLen]; packetData[0] = 0; // Channel packetData[1] = 0; // Command (Set pixel colors) packetData[2] = (byte)(numBytes >> 8); packetData[3] = (byte)(numBytes & 0xFF); // WRAP: ZigZag for (int x = 0; x < colorMap.GetLength(0); x++) { for (int y = 0; y < colorMap.GetLength(1); y++) { //int i = y + x * colorMap.GetLength(1); int i = (Mathf.IsOdd(x) ? (colorMap.GetLength(1) - y) - 1 : y) + x * colorMap.GetLength(1); //i = Math.Abs(i - 99); packetData[i * 3 + 4] = (byte)(colorMap[x, y].r); // R packetData[i * 3 + 5] = (byte)(colorMap[x, y].g); // G packetData[i * 3 + 6] = (byte)(colorMap[x, y].b); // B } } /* WRAP: Line for Line * for (int x = 0; x < colorMap.GetLength(0); x++) * { * for (int y = 0; y < colorMap.GetLength(1); y++) * { * int i = y + x * colorMap.GetLength(1); * * packetData[i * 3 + 4] = (byte)(colorMap[x, y].r); // R * packetData[i * 3 + 5] = (byte)(colorMap[x, y].g); // G * packetData[i * 3 + 6] = (byte)(colorMap[x, y].b); // B * } * } */ //Send to FadeCandy Server stream.Write(packetData, 0, packetData.Length); stream.Write(packetData, 0, packetData.Length); } }
public static unsafe void ConstructPixelBufferFromFile() { BitmapSource source = CurrentState.bitmapImage as BitmapSource; PixelColor[,] pixels = CurrentState.pixelsBeforeColorEnhancing; fixed(PixelColor *buffer = &pixels[0, 0]) source.CopyPixels( new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), (IntPtr)(buffer), pixels.GetLength(0) * pixels.GetLength(1) * sizeof(PixelColor), source.PixelWidth * sizeof(PixelColor)); CurrentState.currentPixels = new PixelColor[CurrentState.pixelsBeforeColorEnhancing.GetLength(0), CurrentState.pixelsBeforeColorEnhancing.GetLength(1)]; Array.Copy(CurrentState.pixelsBeforeColorEnhancing, CurrentState.currentPixels, pixels.Length); CurrentState.originalPixels = CurrentState.currentPixels; }
private void StartTransformation() { int stepsVertical = resultPic.GetLength(1); //Vektor linke seite for (int vStep = 0; vStep < stepsVertical; vStep++) { StepsOnVektor(pA, pD, stepsVertical, vStep, out Point pOrigAD); StepsOnVektor(pB, pC, stepsVertical, vStep, out Point pOrigBC); int stepsHorizontal = resultPic.GetLength(0); for (int i = 0; i < stepsHorizontal; i++) { StepsOnVektor(pOrigAD, pOrigBC, stepsHorizontal, i, out Point pOrig); resultPic[i, vStep] = originalPic[pOrig.X, pOrig.Y]; } } }
private PixelHSV[,] Transfer_to_HSV(PixelColor[,] pixel) { var height = pixel.GetLength(1); var width = pixel.GetLength(0); double max, min; PixelHSV[,] result = new PixelHSV[width, height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { max = Math.Max(Math.Max(pixel[x, y].Red, pixel[x, y].Green), pixel[x, y].Blue); min = Math.Min(Math.Min(pixel[x, y].Red, pixel[x, y].Green), pixel[x, y].Blue); result[x, y].Value = max / 255; if (max == min) { result[x, y].Hue = 0; } else if (max == pixel[x, y].Red && pixel[x, y].Green >= pixel[x, y].Blue) { result[x, y].Hue = 60 * (pixel[x, y].Green - pixel[x, y].Blue) / ((max - min)) + 0; } else if (max == pixel[x, y].Red && pixel[x, y].Green < pixel[x, y].Blue) { result[x, y].Hue = 60 * (pixel[x, y].Green - pixel[x, y].Blue) / ((max - min)) + 360; } else if (max == pixel[x, y].Green) { result[x, y].Hue = 60 * (pixel[x, y].Blue - pixel[x, y].Red) / ((max - min)) + 120; } else if (max == pixel[x, y].Blue) { result[x, y].Hue = 60 * (pixel[x, y].Red - pixel[x, y].Green) / ((max - min)) + 240; } if (max == 0) { result[x, y].Saturation = 0; } else { result[x, y].Saturation = 1 - (min / max) / 255; } } } return(result); }
public static unsafe WriteableBitmap WritePixelsToBitmap() { BitmapSource source = CurrentState.bitmapImage as BitmapSource; PixelColor[,] pixels = CurrentState.currentPixels; WriteableBitmap writableBitmap = new WriteableBitmap(source); int rows = pixels.GetLength(0); int cols = pixels.GetLength(1); fixed(PixelColor *buffer = &pixels[0, 0]) writableBitmap.WritePixels( new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), (IntPtr)(buffer), pixels.GetLength(0) * pixels.GetLength(1) * sizeof(PixelColor), source.PixelWidth * sizeof(PixelColor), 0, 0); return(writableBitmap); }
private BitmapSource BitmapSourceFromArray(PixelColor[,] resultPic) { List <byte> pixelList = new List <byte>(); for (int y = 0; y < resultPic.GetLength(1); y++) { for (int x = 0; x < resultPic.GetLength(0); x++) { List <byte> point = resultPic[x, y].GetValues(); pixelList.AddRange(point); } } byte[] pixels = pixelList.Cast <byte>().ToArray(); int width = resultPic.GetLength(0); int height = resultPic.GetLength(1); WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null); bitmap.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), pixels, width * (bitmap.Format.BitsPerPixel / 8), 0); return(bitmap); }
public TableAppChess() { updateSpeed = 50; //Setup Chess Field chessMap = new PixelColor[Program.TableWidth, Program.TableHeight]; for (int i = 1; i < chessMap.GetLength(0) - 1; i++) { for (int j = 1; j < chessMap.GetLength(1) - 1; j++) { if ((j % 2 == 0 && i % 2 == 0) || (j % 2 != 0 && i % 2 != 0)) { chessMap[i, j] = PixelColor.BLACK; } else if ((j % 2 == 0 && i % 2 != 0) || (j % 2 != 0 && i % 2 == 0)) { chessMap[i, j] = PixelColor.WHITE; } } } }
public static WriteableBitmap PixelsToBitmapSource(PixelColor[,] pixels) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); byte[] pixelData = new byte[width * height * 4]; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { PixelColor color = pixels[x, y]; pixelData[(y * width + x) * 4 + 0] = color.Blue; pixelData[(y * width + x) * 4 + 1] = color.Green; pixelData[(y * width + x) * 4 + 2] = color.Red; pixelData[(y * width + x) * 4 + 3] = color.Alpha; } } WriteableBitmap bitmap = new WriteableBitmap(width, height, Dpi, Dpi, PixelFormats.Bgra32, null); bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixelData, bitmap.PixelWidth * 4, 0); return(bitmap); }
public void PutPixels(WriteableBitmap bitmap, PixelColor[,] pixels, int x, int y) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); var stride = width * ((bitmap.Format.BitsPerPixel + 7) / 8); byte[] pixel = new byte[height * stride]; Parallel.For(0, height, n => { int m; for (m = 0; m < width; m++) { pixel[(n * width + m) * 4 + 0] = pixels[m, n].Blue; pixel[(n * width + m) * 4 + 1] = pixels[m, n].Green; pixel[(n * width + m) * 4 + 2] = pixels[m, n].Red; pixel[(n * width + m) * 4 + 3] = pixels[m, n].Alpha; } }); bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixel, width * 4, x, y); }
void Dilation(ref PixelColor[,] pixels, int ksize) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); PixelColor[,] temp = (PixelColor[, ])pixels.Clone(); PixelColor[,] temp1 = pixels; Parallel.For(0, pixels.GetLength(0) - 1, x => { for (int y = 0; y < temp.GetLength(1); y++) { temp1[x, y] = Dilation_Crossdot(temp, x, y, ksize); } }); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime); }
private static void Main(string[] args) { try { if (args.Length == 1) { try { SaveFingerprint(Guid.Parse(args[0])); Console.WriteLine("Fingerprint is saved, now you can relauch bot with needed parameters"); } catch { Console.WriteLine("You should pass correct 128-bit fingerprint (GUID)"); } return; } ushort width, height; PlacingOrderMode order = PlacingOrderMode.Random; notificationMode = CaptchaNotificationMode.Browser; try { try { leftX = short.Parse(args[0]); topY = short.Parse(args[1]); fingerprint = GetFingerprint(); string logFilePath = null; if (args.Length > 3) { notificationMode = CaptchaNotificationMode.None; string upper = args[3].ToUpper(); if (upper.Contains('B')) { notificationMode |= CaptchaNotificationMode.Browser; } if (upper.Contains('S')) { notificationMode |= CaptchaNotificationMode.Sound; } if (args.Length > 4) { defendMode = args[4].ToUpper() == "Y"; if (args.Length > 5) { switch (args[5].ToUpper()) { case "R": order = PlacingOrderMode.FromRight; break; case "L": order = PlacingOrderMode.FromLeft; break; case "T": order = PlacingOrderMode.FromTop; break; case "B": order = PlacingOrderMode.FromBottom; break; } if (args.Length > 6) { try { File.OpenWrite(args[6]).Dispose(); logFilePath = args[6]; } catch { } } } } } logger = new Logger(finishCTS.Token, logFilePath); imagePixels = ImageProcessing.PixelColorsByUri(args[2], logger.LogLine); checked { width = (ushort)imagePixels.GetLength(0); height = (ushort)imagePixels.GetLength(1); short check; check = (short)(leftX + width); check = (short)(topY + height); } } catch (OverflowException) { throw new Exception("Entire image should be inside the map"); } catch (WebException) { throw new Exception("Cannot download image"); } catch (ArgumentException) { throw new Exception("Cannot convert image"); } catch (IOException) { throw new Exception("Fingerprint is not saved, pass it from browser as only parameter to app to save before usage"); } catch { throw new Exception("Parameters: <leftX> <topY> <imageURI> [notificationMode: N/B/S/BS = B] [defendMode: Y/N = N] [buildFrom L/R/T/B/RND = RND] [logFileName = none]"); } } catch (Exception ex) { Console.WriteLine(ex.Message); finishCTS.Cancel(); return; } IEnumerable <int> allY = Enumerable.Range(0, height); IEnumerable <int> allX = Enumerable.Range(0, width); Pixel[] nonEmptyPixels = allX. SelectMany(X => allY.Select(Y => (X: (short)(X + leftX), Y: (short)(Y + topY), C: imagePixels[X, Y]))). Where(xy => xy.C != PixelColor.None).ToArray(); switch (order) { case PlacingOrderMode.FromLeft: pixelsToBuild = nonEmptyPixels.OrderBy(xy => xy.Item1).ToList(); break; case PlacingOrderMode.FromRight: pixelsToBuild = nonEmptyPixels.OrderByDescending(xy => xy.Item1).ToList(); break; case PlacingOrderMode.FromTop: pixelsToBuild = nonEmptyPixels.OrderBy(xy => xy.Item2).ToList(); break; case PlacingOrderMode.FromBottom: pixelsToBuild = nonEmptyPixels.OrderByDescending(xy => xy.Item2).ToList(); break; default: Random rnd = new Random(); for (int i = 0; i < nonEmptyPixels.Length; i++) { int r = rnd.Next(i, nonEmptyPixels.Length); Pixel tmp = nonEmptyPixels[r]; nonEmptyPixels[r] = nonEmptyPixels[i]; nonEmptyPixels[i] = tmp; } pixelsToBuild = nonEmptyPixels; break; } cache = new ChunkCache(pixelsToBuild, logger.LogLine); mapDownloadedResetEvent = new ManualResetEvent(false); cache.OnMapDownloaded += (o, e) => mapDownloadedResetEvent.Set(); if (defendMode) { gotGriefed = new AutoResetEvent(false); cache.OnMapDownloaded += (o, e) => gotGriefed.Set(); waitingGriefLock = new object(); } statsThread = new Thread(StatsCollectionThreadBody); statsThread.Start(); do { try { using (InteractionWrapper wrapper = new InteractionWrapper(fingerprint, logger.LogLine)) { wrapper.OnPixelChanged += LogPixelChanged; wrapper.OnConnectionLost += (o, e) => mapDownloadedResetEvent.Reset(); cache.Wrapper = wrapper; cache.DownloadChunks(); placed.Clear(); bool wasChanged; do { wasChanged = false; repeatingFails = false; foreach (Pixel pixel in pixelsToBuild) { (short x, short y, PixelColor color) = pixel; PixelColor actualColor = cache.GetPixelColor(x, y); if (!IsCorrectPixelColor(actualColor, color)) { wasChanged = true; bool success; placed.Add(pixel); do { byte placingPixelFails = 0; mapDownloadedResetEvent.WaitOne(); success = wrapper.PlacePixel(x, y, color, out double cd, out double totalCd, out string error); if (success) { string prefix = cd == 4 ? "P" : "Rep"; logger.LogPixel($"{prefix}laced pixel:", MessageGroup.Pixel, x, y, color); Thread.Sleep(TimeSpan.FromSeconds(totalCd < 53 ? 1 : cd)); } else { if (cd == 0.0) { logger.LogLine("Please go to browser and place pixel, then return and press any key", MessageGroup.Captcha); if (notificationMode.HasFlag(CaptchaNotificationMode.Sound)) { Task.Run(() => { for (int j = 0; j < 7; j++) { Console.Beep(1000, 100); } }); } if (notificationMode.HasFlag(CaptchaNotificationMode.Browser)) { Process.Start($"{InteractionWrapper.BaseHttpAdress}/#{x},{y},30"); } Thread.Sleep(100); logger.ConsoleLoggingResetEvent.Reset(); while (Console.KeyAvailable) { Console.ReadKey(true); } Console.ReadKey(true); logger.ConsoleLoggingResetEvent.Set(); } else { logger.LogLine($"Failed to place pixel: {error}", MessageGroup.PixelFail); if (++placingPixelFails == 3) { throw new Exception("Cannot place pixel 3 times"); } } Thread.Sleep(TimeSpan.FromSeconds(cd)); } } while (!success); } } if (defendMode) { if (!wasChanged) { logger.LogLine("Image is intact, waiting...", MessageGroup.ImageDone); lock (waitingGriefLock) { gotGriefed.Reset(); gotGriefed.WaitOne(); } Thread.Sleep(new Random().Next(500, 3000)); } } }while (defendMode || wasChanged); logger.LogLine("Building is finished, exiting...", MessageGroup.ImageDone); return; } } catch (Exception ex) { logger.LogLine($"Unhandled exception: {ex.Message}", MessageGroup.Error); int delay = repeatingFails ? 30 : 10; repeatingFails = true; logger.LogLine($"Reconnecting in {delay} seconds...", MessageGroup.TechState); Thread.Sleep(TimeSpan.FromSeconds(delay)); continue; } } while (true); } finally { finishCTS.Cancel(); gotGriefed?.Dispose(); mapDownloadedResetEvent?.Dispose(); logger?.Dispose(); Thread.Sleep(1000); finishCTS.Dispose(); if (statsThread?.IsAlive ?? false) { statsThread.Interrupt(); //fallback, should never work } } }
public static int GetW(PixelColor[,] PixelsTopLeft) { return(PixelsTopLeft.GetLength(1)); }
private StringBuilder[] ConvertPixelsToASCII(PixelColor[,] pixels, int resolution) { StringBuilder[] ASCIIarr = null; if (pixels != null) { var width = pixels.GetLength(0); WidthTextBox.Text = width.ToString(); var height = pixels.GetLength(1); HeightTextBox.Text = height.ToString(); ASCIIarr = new StringBuilder[height / resolution - 1]; /*Stopwatch sw = new Stopwatch(); * sw.Start(); * for (int i = 0; i < (height / resolution) - 1; i++) * { * StringBuilder convertedString = new StringBuilder(); * for (int j = 0; j < (width / resolution) - 1; j++) * { * int sum = 0; * for (int k = 0; k < resolution; k++) * { * for (int l = 0; l < resolution; l++) * { * sum += pixels[(j * resolution) + k, (i * resolution) + l].Blue; * } * } * sum /= 25; * AppendASCII(convertedString, sum); * } * ASCIIarr[i] = convertedString; * outputTextBoxes[resolution].Text += (convertedString.ToString() + "\n"); * } * sw.Stop(); * TimeSpan ts = sw.Elapsed; * Console.WriteLine("Time elapsed: {0}", sw.Elapsed); */ //Stopwatch sw = new Stopwatch(); //sw.Start(); Parallel.For(0, (height / resolution) - 1, i => { StringBuilder convertedString = new StringBuilder(); for (int j = 0; j < (width / resolution) - 1; j++) { int sum = 0; for (int k = 0; k < resolution; k++) { for (int l = 0; l < resolution; l++) { sum += pixels[(j * resolution) + k, (i * resolution) + l].Blue; } } sum /= 25; ConverToASCIIAndAppend(convertedString, sum); } ASCIIarr[i] = convertedString; }); //sw.Stop(); //TimeSpan ts = sw.Elapsed; //Console.WriteLine("Time elapsed: {0}", sw.Elapsed); } return(ASCIIarr); }