コード例 #1
0
ファイル: RenderForm.cs プロジェクト: Tilps/Stash
 private void DrawPix(PixelMap map, int toDraw, int completed)
 {
     DrawPixRunWrapArgs wrap = new DrawPixRunWrapArgs();
     wrap.map = map;
     wrap.toDraw = toDraw;
     wrap.completed = completed;
     ThreadPool.QueueUserWorkItem(new WaitCallback(DrawPixRunWrap), wrap);
 }
コード例 #2
0
        public static PixelMap GetPixelMap(string filePath)
        {
            var image   = UIImage.FromFile(filePath);
            var cgImage = image.CGImage;

            var width            = (int)cgImage.Width;
            var height           = (int)cgImage.Height;
            var bytesPerPixel    = (int)cgImage.BitsPerPixel / ByteToBit;
            var bytesPerRow      = (int)cgImage.BytesPerRow;
            var bitsPerComponent = (int)cgImage.BitsPerComponent;

            var rawData = new byte[bytesPerRow * height];

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
            {
                //Crashes on the next line with an invalid handle exception
                using (var context = new CGBitmapContext(
                           rawData,
                           width,
                           height,
                           bitsPerComponent,
                           bytesPerRow,
                           colorSpace,
                           CGBitmapFlags.ByteOrder32Big | CGBitmapFlags.PremultipliedLast))
                {
                    context.DrawImage(new CGRect(0, 0, width, height), cgImage);
                }
            }

            var source = new PixelMap(width, height, bytesPerPixel: bytesPerPixel, bitsPerComponent: bitsPerComponent);

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    var index = bytesPerRow * y + bytesPerPixel * x;

                    source[x, y] = new Pixel
                    {
                        R = rawData[index],
                        G = rawData[index + 1],
                        B = rawData[index + 2],
                        A = rawData[index + 3]
                    };
                }
            }

            return(source);
        }
コード例 #3
0
        public void SetPixel(int x, int y, PaintMode?mode = null, bool?erase = null)
        {
            Tile      curTile = CurrentWorld.Tiles[x, y];
            PaintMode curMode = mode ?? TilePicker.PaintMode;
            bool      isErase = erase ?? TilePicker.IsEraser;

            switch (curMode)
            {
            case PaintMode.Tile:
                SetTile(curTile, isErase);
                break;

            case PaintMode.Wall:
                SetWall(curTile, isErase);
                break;

            case PaintMode.TileAndWall:
                SetTile(curTile, isErase);
                SetWall(curTile, isErase);
                break;

            case PaintMode.Wire:
                SetPixelAutomatic(curTile, wire: !isErase);
                break;

            case PaintMode.Wire2:
                SetPixelAutomatic(curTile, wire2: !isErase);
                break;

            case PaintMode.Wire3:
                SetPixelAutomatic(curTile, wire3: !isErase);
                break;

            case PaintMode.Liquid:
                SetPixelAutomatic(curTile, liquid: isErase ? (byte)0 : (byte)255, liquidType: TilePicker.LiquidType);
                break;

            case PaintMode.BrickStyle:
                SetPixelAutomatic(curTile, brickStyle: TilePicker.BrickStyle);
                break;
            }


            // curTile.BrickStyle = TilePicker.BrickStyle;

            Color curBgColor = GetBackgroundColor(y);

            PixelMap.SetPixelColor(x, y, Render.PixelMap.GetTileColor(CurrentWorld.Tiles[x, y], curBgColor, _showWalls, _showTiles, _showLiquid, _showWires));
        }
コード例 #4
0
ファイル: FormMain.Implement.cs プロジェクト: sgww/cozy
        private void ChangePixelPainterImage(Bitmap bmp)
        {
            int gw = RefreshCurrGridWidth();

            CurrPixelMap = new PixelMap()
            {
                ShowGrid   = ShowGridCheckBox.Checked,
                data       = bmp,
                PixelWidth = PixelMap.DefaultPixelWidth - gw,
                GridWidth  = gw,
                GridColor  = GridColorButton.BackColor,
            };

            PixelPainter.SourceImage = CurrPixelMap;
        }
コード例 #5
0
        public Bitmap[] Map(params Func <Color, Color>[] map)
        {
            var mapWithBytes = new PixelMap[map.Length];

            for (var i = 0; i < map.Length; ++i)
            {
                var func = map[i];
                mapWithBytes[i] = (format, source, dst) =>
                {
                    ColorToPixel(format, dst, func(PixelToColor(format, source)));
                };
            }

            return(Map(mapWithBytes));
        }
コード例 #6
0
        protected override void LogMapChanged(object sender, MapChangedEventArgs e)
        {
            foreach (MapChange c in e.Changes)
            {
                MessageGroup msgGroup;
                PixelMap.OffsetToRelative(c.Offset, out byte rx, out byte ry);
                short x = PixelMap.RelativeToAbsolute(e.Chunk.Item1, rx);
                short y = PixelMap.RelativeToAbsolute(e.Chunk.Item2, ry);

                if (!placed.Remove((x, y, c.Color)))
                {
                    try
                    {
                        int irx = x - options.LeftX;
                        int iry = y - options.TopY;

                        if (irx < 0 || irx >= width || iry < 0 || iry >= height)
                        {
                            //beyond image rectangle
                            msgGroup = MessageGroup.PixelInfo;
                        }
                        else
                        {
                            byte desiredColor = imagePixels[irx, iry];
                            if (palette.IsIgnored(desiredColor))
                            {
                                msgGroup = MessageGroup.PixelInfo;
                            }
                            else if (palette.IsCorrectPixelColor(c.Color, desiredColor))
                            {
                                msgGroup = MessageGroup.Assist;
                                builtInLastMinute++;
                            }
                            else
                            {
                                msgGroup = MessageGroup.Attack;
                                griefedInLastMinute++;
                                gotGriefed?.Set();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogDebug($"LogMapChanged: unhandled exception - {ex}");
                        msgGroup = MessageGroup.PixelInfo;
                    }
                    logger.LogPixel($"Received pixel update:", e.DateTime, msgGroup, x, y, colorNameResolver.GetName(c.Color));
                }
コード例 #7
0
ファイル: PixelMapTests.cs プロジェクト: sahwar/DjvuNet
        public void ApplyGammaCorrectionTest001()
        {
            double g      = 2.90000000;
            var    map    = CreateInitVerifyPixelMap(256, 256, Pixel.GreenPixel);
            var    pixRef = map.CreateGPixelReference(0, 128);
            var    pix    = pixRef.ToPixel();

            map.ApplyGammaCorrection(g);
            var pixAfterGamma = pixRef.ToPixel();

            int[] gammaTable = PixelMap.GetGammaCorrection(g);

            Assert.Equal <byte>(unchecked ((byte)pixAfterGamma.Blue), (byte)gammaTable[unchecked ((byte)pix.Blue)]);
            Assert.Equal <byte>(unchecked ((byte)pixAfterGamma.Green), (byte)gammaTable[unchecked ((byte)pix.Green)]);
            Assert.Equal <byte>(unchecked ((byte)pixAfterGamma.Red), (byte)gammaTable[unchecked ((byte)pix.Red)]);
        }
コード例 #8
0
        public static ImageSource LoadImageFromPixelMap(PixelMap pixelMap)
        {
            var buffer = ByteBuffer.Wrap(pixelMap.ToByteArray());

            buffer.Rewind();

            var bitmap = Bitmap.CreateBitmap(pixelMap.Width, pixelMap.Height, Bitmap.Config.Argb8888);

            bitmap.CopyPixelsFromBuffer(buffer);

            var ms = new MemoryStream();

            bitmap.Compress(Bitmap.CompressFormat.Png, 100, ms);
            ms.Seek(0, SeekOrigin.Begin);
            return(ImageSource.FromStream(() => ms));
        }
コード例 #9
0
        public void ImageComparison()
        {
            manager.ActiveBrowser.NavigateTo(
                "http://automatetheplanet.com/healthy-diet-menu-generator/");
            HtmlDiv mainArticleDiv =
                manager.ActiveBrowser.Find.ByXPath <HtmlDiv>(
                    "/html/body/div[1]/div[3]/section/article/div");

            System.Drawing.Bitmap divimage = manager.ActiveBrowser.Window.GetBitmap(mainArticleDiv.GetRectangle());

            Bitmap   expectedbmp = (Bitmap)Image.FromFile("mainArticleDivExpected.bmp", true);
            PixelMap expected    = PixelMap.FromBitmap(expectedbmp);
            PixelMap actual      = PixelMap.FromBitmap(divimage);

            Assert.IsTrue(expected.Compare(actual, 5.0));
        }
コード例 #10
0
        /// <summary>
        ///     Embeds the image with image.
        /// </summary>
        /// <param name="sourcePixels">The sourceImage pixels.</param>
        /// <param name="embedPixels">The imageToEmbed pixels.</param>
        /// <param name="embedImageWidth">Width of the imageToEmbed image.</param>
        /// <param name="embedImageHeight">Height of the imageToEmbed image.</param>
        /// <param name="sourceImageWidth">Width of the sourceImage image.</param>
        /// <param name="sourceImageHeight">Height of the sourceImage image.</param>
        private static byte[] EmbedBytes(byte[] sourcePixels, byte[] embedPixels, uint embedImageWidth,
                                         uint embedImageHeight, uint sourceImageWidth, uint sourceImageHeight)
        {
            var sourceColor = Color.FromArgb(119, 119, 119, 119);

            if (embedImageWidth > sourceImageWidth || embedImageHeight > sourceImageHeight)
            {
                return(null);
            }

            for (var y = 0; y < embedImageHeight; y++)
            {
                for (var x = 0; x < embedImageWidth; x++)
                {
                    if (x == 0 && y == 0)
                    {
                        PixelMap.ModifyPixel(sourcePixels, x, y, sourceColor, sourceImageWidth);
                    }
                    else if (x == 1 && y == 0)
                    {
                        sourceColor    = PixelMap.RetrieveColor(sourcePixels, x, y, sourceImageWidth, sourceImageHeight);
                        sourceColor.R |= 0 << 0;
                        PixelMap.ModifyPixel(sourcePixels, x, y, sourceColor, sourceImageWidth);
                    }
                    else
                    {
                        var embedColor = PixelMap.RetrieveColor(embedPixels, x, y, embedImageWidth, embedImageHeight);
                        if (embedColor.Equals(Colors.Black))
                        {
                            sourceColor =
                                PixelMap.RetrieveColor(sourcePixels, x, y, sourceImageWidth, sourceImageHeight);
                            sourceColor.B |= 0 << 0;
                            PixelMap.ModifyPixel(sourcePixels, x, y, sourceColor, sourceImageWidth);
                        }
                        else
                        {
                            sourceColor =
                                PixelMap.RetrieveColor(sourcePixels, x, y, sourceImageWidth, sourceImageHeight);
                            sourceColor.B |= 1 << 0;
                            PixelMap.ModifyPixel(sourcePixels, x, y, sourceColor, sourceImageWidth);
                        }
                    }
                }
            }
            return(sourcePixels);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: Yarxxxnov/PixelPlanetTools
 private static void Wrapper_OnMapChanged(object sender, MapChangedEventArgs e)
 {
     foreach (MapChange c in e.Changes)
     {
         PixelMap.OffsetToRelative(c.Offset, out byte rx, out byte ry);
         short x = PixelMap.RelativeToAbsolute(e.Chunk.Item1, rx);
         short y = PixelMap.RelativeToAbsolute(e.Chunk.Item2, ry);
         if (x <= options.RightX && x >= options.LeftX && y <= options.BottomY && y >= options.TopY)
         {
             logger.LogPixel("Received pixel update:", e.DateTime, MessageGroup.PixelInfo, x, y, colorNameResolver.GetName(c.Color));
             lock (listLockObj)
             {
                 updates.Add((x, y, c.Color));
             }
         }
     }
 }
コード例 #12
0
 public ImageStegonography(Bitmap image)
 {
     this.bm = image;
     pm      = new PixelMap(image);
     ValidatorSets.Add(new ValidatorSet {
         Color = Color.FromArgb(255, 192, 192, 192), X = 20, Y = 20
     });
     ValidatorSets.Add(new ValidatorSet {
         Color = Color.FromArgb(255, 169, 169, 169), X = 20, Y = image.Height - 20
     });
     ValidatorSets.Add(new ValidatorSet {
         Color = Color.FromArgb(255, 128, 128, 128), X = image.Width - 20, Y = 20
     });
     ValidatorSets.Add(new ValidatorSet {
         Color = Color.FromArgb(255, 0, 0, 0), X = image.Width - 20, Y = image.Height - 20
     });
 }
コード例 #13
0
ファイル: BitmapGenerate.cs プロジェクト: sgww/cozy
        public static void DrawGrid(PixelMap pm, Graphics g)
        {
            int x = pm.PixelWidth + pm.GridWidth;
            var w = pm.Width * x;
            var h = pm.Height * x;

            var ePen       = new Pen(pm.BackColor, pm.GridWidth);
            var GridPen    = new Pen(pm.GridColor, pm.GridWidth);
            int BlockWidth = pm.PixelWidth + pm.GridWidth;

            for (int i = 0; i <= pm.Width; ++i)
            {
                g.DrawLine(ePen, 0, i * BlockWidth, w, i * BlockWidth);
                g.DrawLine(ePen, i * BlockWidth, 0, i * BlockWidth, h);
                g.DrawLine(GridPen, 0, i * BlockWidth, w, i * BlockWidth);
                g.DrawLine(GridPen, i * BlockWidth, 0, i * BlockWidth, h);
            }
        }
コード例 #14
0
        public void EditDelete()
        {
            if (Selection.IsActive)
            {
                for (int x = Selection.SelectionArea.Left; x < Selection.SelectionArea.Right; x++)
                {
                    for (int y = Selection.SelectionArea.Top; y < Selection.SelectionArea.Bottom; y++)
                    {
                        UndoManager.SaveTile(x, y);
                        CurrentWorld.Tiles[x, y].Reset();

                        Color curBgColor = GetBackgroundColor(y);
                        PixelMap.SetPixelColor(x, y, Render.PixelMap.GetTileColor(CurrentWorld.Tiles[x, y], curBgColor, _showWalls, _showTiles, _showLiquid, _showWires));
                    }
                }
                UndoManager.SaveUndo();
            }
        }
コード例 #15
0
        public void SetGridData(PixelMap gridData, bool resizeToSourceGrid = true)
        {
            if (gridData.Width != PixelGridWidth || gridData.Height != PixelGridHeight)
            {
                if (resizeToSourceGrid)
                {
                    PixelGridWidth  = gridData.Width;
                    PixelGridHeight = gridData.Height;
                }
                else
                {
                    gridData.Resize(PixelGridWidth, PixelGridHeight);
                }
            }

            _pixelMap = gridData.Clone() as PixelMap;
            InvalidateVisual();
            RaiseEvent(new RoutedEventArgs(GridUpdatedEvent, this));
        }
コード例 #16
0
ファイル: PixelMapTests.cs プロジェクト: sahwar/DjvuNet
        public void BenchmarkApplyGammaCorrectionFastMT()
        {
            sbyte[]   data  = GetRandomData(shdWidth, shdHeight, shdBytesPerPixel);
            long      ticks = 0;
            Stopwatch watch = new Stopwatch();

            for (int i = 0; i < testCount; i++)
            {
                sbyte[] testData = new sbyte[data.Length];
                Buffer.BlockCopy(data, 0, testData, 0, data.Length);

                watch.Restart();
                PixelMap.ApplyGammaFastMT(2.2, testData);
                watch.Stop();
                ticks += watch.ElapsedMilliseconds;
            }

            Console.WriteLine($"ApplyGammaCorrectionFastMT ms per call\t\t{((double)ticks / testCount).ToString("0#.000")}");
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: Kurewka/PixelPlanetTools
        private static void LogPixelChanged(object sender, PixelChangedEventArgs e)
        {
            MessageGroup msgGroup;
            short        x = PixelMap.ConvertToAbsolute(e.Chunk.Item1, e.Pixel.Item1);
            short        y = PixelMap.ConvertToAbsolute(e.Chunk.Item2, e.Pixel.Item2);

            if (!placed.Remove((x, y, e.Color)))
            {
                try
                {
                    EarthPixelColor desiredColor = imagePixels[x - options.LeftX, y - options.TopY];
                    if (desiredColor == EarthPixelColor.None)
                    {
                        msgGroup = MessageGroup.PixelInfo;
                    }
                    else
                    {
                        if (desiredColor == e.Color)
                        {
                            msgGroup = MessageGroup.Assist;
                            builtInLastMinute++;
                        }
                        else
                        {
                            msgGroup = MessageGroup.Attack;
                            griefedInLastMinute++;
                            gotGriefed?.Set();
                        }
                    }
                }
                catch (IndexOutOfRangeException)
                {
                    logger.LogDebug("LogPixelChanged(): pixel update beyond rectangle");
                    msgGroup = MessageGroup.PixelInfo;
                }
                catch (Exception ex)
                {
                    logger.LogDebug($"LogPixelChanged(): unhandled exception - {ex.Message}");
                    msgGroup = MessageGroup.PixelInfo;
                }
                logger.LogPixel($"Received pixel update:", e.DateTime, msgGroup, x, y, e.Color);
            }
コード例 #18
0
 public ChunkCache2D(short x1, short y1, short x2, short y2, Logger logger, CanvasType canvas)
 {
     this.canvas     = canvas;
     interactiveMode = false;
     this.logger     = logger;
     logger.LogTechState("Calculating list of chunks...");
     PixelMap.AbsoluteToRelative(x1, out byte chunkX1, out _);
     PixelMap.AbsoluteToRelative(y1, out byte chunkY1, out _);
     PixelMap.AbsoluteToRelative(x2, out byte chunkX2, out _);
     PixelMap.AbsoluteToRelative(y2, out byte chunkY2, out _);
     chunks = new List <XY>();
     for (ushort x = chunkX1; x <= chunkX2; x++)
     {
         for (ushort y = chunkY1; y <= chunkY2; y++)
         {
             chunks.Add(((byte)x, (byte)y));
         }
     }
     logger.LogTechInfo("Chunk list is calculated");
 }
コード例 #19
0
        public MainForm()
        {
            InitializeComponent();
            setTelepresenceLabelSoftwareVersion(AppInfo.version.ToString(System.Globalization.CultureInfo.InvariantCulture));

            //test start
            PixelMap testPixelMap = new PixelMap(521, 415, 0, 0, 0);
            Bitmap   testBmp      = testPixelMap.GetBitmap();
            Graphics graphics     = Graphics.FromImage(testBmp);

            try
            {
                Pen pen;
                pen = new Pen(Color.Green);
                graphics.DrawEllipse(pen, pictureBoxCenterX - 50, pictureBoxCenterY - 50, 101, 101);
            }
            catch (Exception ex) { }
            drawBitmapOnTelepresencePictureBox(testBmp);
            //test end
        }
コード例 #20
0
 private void UpdateRenderWorld()
 {
     Task.Factory.StartNew(
         () =>
     {
         if (CurrentWorld != null)
         {
             for (int y = 0; y < CurrentWorld.TilesHigh; y++)
             {
                 Color curBgColor = GetBackgroundColor(y);
                 OnProgressChanged(this, new ProgressChangedEventArgs(y.ProgressPercentage(CurrentWorld.TilesHigh), "Calculating Colors..."));
                 for (int x = 0; x < CurrentWorld.TilesWide; x++)
                 {
                     PixelMap.SetPixelColor(x, y, Render.PixelMap.GetTileColor(CurrentWorld.Tiles[x, y], curBgColor, _showWalls, _showTiles, _showLiquid, _showWires));
                 }
             }
         }
         OnProgressChanged(this, new ProgressChangedEventArgs(0, "Render Complete"));
     });
 }
コード例 #21
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                InitialDirectory = @"D:\OneDrive\Pictures\Misc",
                Filter           = "Bitmap|*.bmp;*.jpg;*.jpeg;*.png;"
            };

            EdgeDetection();
            return;

            //if (dialog.ShowDialog() == true)
            {
                var path     = @"D:\OneDrive\Pictures\Misc\WP_20150807_08_45_41_Pro.jpg";
                var savepath = @"D:\Desktop\test.jpg";

                var sources = new PixelMap[2];

                GetPixelMap(path, sources);
                var source = sources[0];

                image.Source = LoadFromPixelMap(source);

                var imaging = new ImagingManager(source);

                //imaging.AddFilter(new PixelInterpolation(50));

                //imaging.AddFilter(new ThresholdFilter(150, 150, 150));

                //imaging.AddFilter(new OtsuThresholdFilter());

                imaging.AddFilter(new BicubicFilter(0.5));

                imaging.Render();

                var bitmapImage = LoadFromPixelMap(imaging.Output);
                image2.Source = bitmapImage;

                SaveImageToFile(bitmapImage, savepath);
            }
        }
コード例 #22
0
        private void GetPixelMap(string path, PixelMap[] sources)
        {
            var bitmap = new BitmapImage(new Uri(path, UriKind.Relative));
            var wb     = new WriteableBitmap(bitmap);

            var width  = wb.PixelWidth;
            var height = wb.PixelHeight;
            var bpp    = wb.Format.BitsPerPixel;
            var dpiX   = wb.DpiX;
            var dpiY   = wb.DpiY;

            for (var i = 0; i < sources.Length; i++)
            {
                sources[i] = new PixelMap(width, height, dpiX, dpiY, bpp);
            }

            var stride = wb.PixelWidth * ((bpp + 7) / 8);

            var data = new byte[width * height * 4];

            wb.CopyPixels(data, stride, 0);

            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    foreach (var source in sources)
                    {
                        source[x, y] = new Pixel
                        {
                            R = data[(y * width + x) * 4 + 0],
                            G = data[(y * width + x) * 4 + 1],
                            B = data[(y * width + x) * 4 + 2],
                            A = data[(y * width + x) * 4 + 3]
                        }
                    }
                    ;
                }
            }
        }
コード例 #23
0
ファイル: BitmapGenerate.cs プロジェクト: sgww/cozy
        public static void DrawPixel(PixelMap pm, Graphics g, int x, int y, Color c)
        {
            var brush = new SolidBrush(c);

            if (pm.ShowGrid)
            {
                g.FillRectangle(
                    brush,
                    pm.GridWidth / 2.0f + x * (pm.PixelWidth + pm.GridWidth),
                    pm.GridWidth / 2.0f + y * (pm.PixelWidth + pm.GridWidth),
                    pm.PixelWidth,
                    pm.PixelWidth);
            }
            else
            {
                g.FillRectangle(
                    brush,
                    x * pm.PixelWidth,
                    y * pm.PixelWidth,
                    pm.PixelWidth,
                    pm.PixelWidth);
            }
        }
コード例 #24
0
ファイル: JB2Image.cs プロジェクト: rodrigoieh/DjvuNet
        public PixelMap GetPixelMap(ColorPalette palette, int subsample, int align)
        {
            Verify.SubsampleRange(subsample);

            if ((Width == 0) || (Height == 0))
            {
                throw new DjvuFormatException(
                          $"Image is empty and can not be used to create bitmap. Width: {Width}, Height {Height}");
            }

            int swidth  = ((Width + subsample) - 1) / subsample;
            int sheight = ((Height + subsample) - 1) / subsample;
            int border  = (((swidth + align) - 1) & ~(align - 1)) - swidth;

            PixelMap pixelMap = new PixelMap(new sbyte[swidth * sheight * 3], swidth, sheight);

            for (int blitno = 0; blitno < Blits.Count; blitno++)
            //Parallel.For(
            //    0,
            //    Blits.Count,
            //    blitno =>
            //    {
            {
                JB2Blit  pblit  = GetBlit(blitno);
                JB2Shape pshape = GetShape(pblit.ShapeNumber);
                Pixel    color  = palette.PaletteColors[palette.BlitColors[blitno]];

                if (pshape.Bitmap != null)
                {
                    pixelMap.Blit(pshape.Bitmap, pblit.Left, pblit.Bottom, color);
                }
                //});
            }

            return(pixelMap);
        }
コード例 #25
0
        public void SetTexture(string index)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            dlg.Filter = "Image files (*.png;*.jpeg;*.jpg)|*.png;*.jpeg;*.jpg|All files (*.*)|*.*";;

            bool?result = dlg.ShowDialog();

            if (result == true)
            {
                string filename = dlg.FileName;
                int    i        = int.Parse(index);
                switch (i)
                {
                case 0:
                    Settings.TriangleSettingsList[i].PickedTriangleTexture =
                        LibrariesConverters.BitmapToVectors(new Bitmap(filename));
                    break;

                case 1:
                    Settings.TriangleSettingsList[i].PickedTriangleTexture =
                        LibrariesConverters.BitmapToVectors(new Bitmap(filename));
                    break;

                case 2:
                    Settings.NormalMap =
                        PixelMap.SlowLoad(new Bitmap(filename));
                    break;

                case 3:
                    Settings.HeightMap =
                        PixelMap.SlowLoad(new Bitmap(filename));
                    break;
                }
            }
        }
コード例 #26
0
        private static void LogPixelChanged(object sender, PixelChangedEventArgs e)
        {
            MessageGroup msgGroup;
            short        x = PixelMap.ConvertToAbsolute(e.Chunk.Item1, e.Pixel.Item1);
            short        y = PixelMap.ConvertToAbsolute(e.Chunk.Item2, e.Pixel.Item2);

            if (!placed.Remove((x, y, e.Color)))
            {
                try
                {
                    PixelColor desiredColor = imagePixels[x - leftX, y - topY];
                    if (desiredColor == PixelColor.None)
                    {
                        msgGroup = MessageGroup.PixelInfo;
                    }
                    else
                    {
                        if (desiredColor == e.Color)
                        {
                            msgGroup = MessageGroup.Assist;
                            builtInLastMinute++;
                        }
                        else
                        {
                            msgGroup = MessageGroup.Attack;
                            griefedInLastMinute++;
                            gotGriefed?.Set();
                        }
                    }
                }
                catch
                {
                    msgGroup = MessageGroup.PixelInfo;
                }
                logger.LogPixel($"Received pixel update:", msgGroup, x, y, e.Color);
            }
コード例 #27
0
 public void UpdateRenderRegion(Rectangle area)
 {
     Task.Factory.StartNew(
         () =>
     {
         var bounded = new Rectangle(Math.Max(area.Left, 0),
                                     Math.Max(area.Top, 0),
                                     Math.Min(area.Width, CurrentWorld.TilesWide - Math.Max(area.Left, 0)),
                                     Math.Min(area.Height, CurrentWorld.TilesHigh - Math.Max(area.Top, 0)));
         if (CurrentWorld != null)
         {
             for (int y = bounded.Top; y < bounded.Bottom; y++)
             {
                 Color curBgColor = GetBackgroundColor(y);
                 OnProgressChanged(this, new ProgressChangedEventArgs(y.ProgressPercentage(CurrentWorld.TilesHigh), "Calculating Colors..."));
                 for (int x = bounded.Left; x < bounded.Right; x++)
                 {
                     PixelMap.SetPixelColor(x, y, Render.PixelMap.GetTileColor(CurrentWorld.Tiles[x, y], curBgColor, _showWalls, _showTiles, _showLiquid, _showWires));
                 }
             }
         }
         OnProgressChanged(this, new ProgressChangedEventArgs(0, "Render Complete"));
     });
 }
コード例 #28
0
		public static void PixelMap(PixelMap map, Int32 mapsize, UInt32[] values)
		{
			Debug.Assert(values.Length >= mapsize);
			unsafe {
				fixed (UInt32* p_values = values)
				{
					Debug.Assert(Delegates.pglPixelMapuiv != null, "pglPixelMapuiv not implemented");
					Delegates.pglPixelMapuiv((Int32)map, mapsize, p_values);
					LogFunction("glPixelMapuiv({0}, {1}, {2})", map, mapsize, LogValue(values));
				}
			}
			DebugCheckErrors(null);
		}
コード例 #29
0
ファイル: ToyTracer.cs プロジェクト: Tilps/Stash
 private void OneRenderThread(int threadCount, int threadId, PixelMap scrpix, Color[] screen, List<ColorIntensity>[] shadings, int[] successive, Counter completed)
 {
     int localAAn = AAn;
     int localAAcomr = AAcomr;
     if (!antialias)
     {
         localAAn = 0;
         localAAcomr = 1;
     }
     int tries = 0;
     int localCompleted = 0;
     Random localRnd = new Random();
     while (tries <= localAAn)
     {
         int scrIdx = 0;
         for (int y = 0; y < viewport.ScreenY; y++)
         {
             if (y % threadCount != threadId)
             {
                 scrIdx += viewport.ScreenX;
                 continue;
             }
             for (int x = 0; x < viewport.ScreenX; x++)
             {
                 if (successive[scrIdx] < localAAcomr)
                 {
                     ColorIntensity newshading;
                     double rndx = 0.0;
                     double rndy = 0.0;
                     if (antialias)
                     {
                         rndx = localRnd.NextDouble() - 0.5;
                         rndy = localRnd.NextDouble() - 0.5;
                     }
                     Line ray = viewport.RayThrough(x + rndx, y + rndy);
                     SetIn(ref ray.Start, threadId);
                     HitInfo found = scene.Intersect(ray, threadId);
                     List<ColorIntensity> shades = shadings[scrIdx];
                     if (!(found.HitDist == -1))
                     {
                         newshading = Shade(found.GetReal(ray), ray, threadId);
                         shades.Add(newshading);
                     }
                     else
                     {
                         newshading.R = 0.0;
                         newshading.G = 0.0;
                         newshading.B = 0.0;
                         shades.Add(newshading);
                     }
                     if (tries > 0)
                     {
                         ColorIntensity before = Colorav(shades, shades.Count - 1);
                         ColorIntensity after = Colorav(shades, shades.Count);
                         double total = 0.0;
                         total += Math.Abs(before.R - after.R);
                         total += Math.Abs(before.G - after.G);
                         total += Math.Abs(before.B - after.B);
                         if (total < AAco)
                         {
                             successive[scrIdx]++;
                         }
                         else
                             successive[scrIdx] = 0;
                         if (successive[scrIdx] >= AAcomr)
                             localCompleted = completed.Incriment();
                     }
                     if (!antialias)
                         localCompleted = completed.Incriment();
                     Color final = Stochav(shades);
                     screen[scrIdx] = final;
                 }
                 scrIdx++;
             }
             if (OnProgress != null)
             {
                 OnProgress(scrpix, y + 1, localCompleted);
             }
         }
         tries++;
     }
 }
コード例 #30
0
ファイル: RenderForm.cs プロジェクト: Tilps/Stash
        private void DrawPixRun(PixelMap map, int toDraw, int completed)
        {
            if (this.InvokeRequired)
            {
                lock (lockObj)
                {
                    try
                    {
                        this.Invoke(new DrawPixDel(DrawPixRun), map, toDraw, completed);
                        Thread.Sleep(10);
                    }
                    catch
                    {
                    }
                }
                return;
            }
            Bitmap img;
            if (this.outputPictureBox.Image is Bitmap)
            {
                img = this.outputPictureBox.Image as Bitmap;
                if (img.Width != map.Width || img.Height != map.Height)
                    img = new Bitmap(map.Width, map.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            }
            else
                img = new Bitmap(map.Width, map.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            if (toDraw <= 0)
            {
                /*
                for (int i = 0; i < map.Width; i++)
                {
                    for (int j = 0; j < map.Height; j++)
                    {
                        img.SetPixel(i, j, System.Drawing.Color.White);
                    }
                }
                 * */
            }
            else
            {
                System.Drawing.Imaging.BitmapData data = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, img.PixelFormat);
                int j = toDraw - 1;
                unsafe
                {
                    byte* pixels = (byte*)data.Scan0.ToPointer();
                    pixels += data.Stride * (toDraw - 1);
                    for (int i = 0; i < map.Width; i++)
                    {
                        *(pixels) = map.Pix[(j * map.Width + i)].B;
                        *(pixels+1) = map.Pix[(j * map.Width + i)].G;
                        *(pixels+2) = map.Pix[(j * map.Width + i)].R;
                        pixels += 3;
                    }
                }
                img.UnlockBits(data);
                /*
                for (int i = 0; i < map.Width; i++)
                {
                    byte r = map.Pix[(j * map.Width + i)].R;
                    byte g = map.Pix[(j * map.Width + i)].G;
                    byte b = map.Pix[(j * map.Width + i)].B;

                    img.SetPixel(i, j, System.Drawing.Color.FromArgb(r, g, b));
                }*/
                if (toDraw == map.Height)
                {
                    img.Save("Autosave" + DateTime.UtcNow.ToString("yyyyMMddHHmmss'Z'") + ".png", System.Drawing.Imaging.ImageFormat.Png);
                }
            }
            if (this.progressBar.Maximum != map.Height)
                this.progressBar.Maximum = map.Height;
            if (this.progressBar1.Maximum != map.Height * map.Width)
                this.progressBar1.Maximum = map.Height * map.Width;
            this.progressBar.Value = toDraw;
            if (completed != -1)
                this.progressBar1.Value = completed;
            this.outputPictureBox.Image = img;
            if (toDraw % 10 == 0)
                this.outputPictureBox.Refresh();
        }
コード例 #31
0
ファイル: PixelGrid.cs プロジェクト: jonathanruisi/Utility
 public void SetGridData(PixelMap gridData, bool resizeToSourceGrid = true)
 {
     if (gridData.Width != PixelGridWidth || gridData.Height != PixelGridHeight)
     {
         if (resizeToSourceGrid)
         {
             PixelGridWidth = gridData.Width;
             PixelGridHeight = gridData.Height;
         }
         else
         {
             gridData.Resize(PixelGridWidth, PixelGridHeight);
         }
     }
     _pixelMap = gridData.Clone() as PixelMap;
     InvalidateVisual();
     RaiseEvent(new RoutedEventArgs(GridUpdatedEvent, this));
 }
コード例 #32
0
        /// <summary>
        ///     This method is called when PixelMap load is requested, if you return a PixelMap 
        ///     it will return it from the user else it will keep trying all the other PixelMapLoaders
        ///     until it does get one
        /// </summary>
        /// <param name="file">File path of the image to load.</param>
        /// <returns>A PixelMap or NULL if this factory can't load the given image file.</returns>
        protected override PixelMap RequestLoad(object path)
        {
            Stream stream = StreamFactory.RequestStream(path, StreamMode.Open);
            if (stream == null) return null;
            BinaryReader reader = new BinaryReader(stream);

            if (reader.ReadByte() == 'B' && reader.ReadByte() == 'M')
            {

                // Read in file header.
                int fileSize        = reader.ReadInt32();
                short reserved1     = reader.ReadInt16();
                short reserved2     = reader.ReadInt16();
                int pixelDataOffset = reader.ReadInt32();

                // Read in image header
                int imageHeaderSize         = reader.ReadInt32();
                int imageWidth              = reader.ReadInt32();
                int imageHeight             = reader.ReadInt32();
                short imagePlanes           = reader.ReadInt16();
                short imageBitCount         = reader.ReadInt16();
                int imageCompression        = reader.ReadInt32();
                int imageSize               = reader.ReadInt32();
                int imageXPixPerMeter       = reader.ReadInt32();
                int imageYPixPerMeter       = reader.ReadInt32();
                int imageColorMapUsed       = reader.ReadInt32();
                int imageColorMapImportant  = reader.ReadInt32();
                if (imageCompression > 0)
                {
                    stream.Close();
                    return null;
                }

                byte[] pixels;
                int[]  pallete;
                byte[] tempPallete;
                PixelMap pixelMap= new PixelMap(imageWidth, imageHeight);

                // Work out the horizontal padding size.
                int paddingWidth = (int)((float)imageWidth * (float)imageBitCount / 8.0);
                while (paddingWidth % 4 != 0) paddingWidth++;

                switch (imageBitCount)
                {
                    case 1: // Monochrome

                        int color1 = ColorMethods.CombineColor(ColorFormats.B8G8R8, ColorFormats.A8R8G8B8, reader.ReadInt32());
                        int color2 = ColorMethods.CombineColor(ColorFormats.B8G8R8, ColorFormats.A8R8G8B8, reader.ReadInt32());

                        for (int y = imageHeight - 1; y >= 0; y--)
                        {
                            pixels = reader.ReadBytes(paddingWidth);
                            for (int x = 0; x < imageWidth; x++)
                                pixelMap[x, y] = ((pixels[x >> 3] & (128 >> (x & 7))) != 0) ? color2 : color1;
                        }

                        break;

                    case 4: // 16 colors.

                        pallete = new int[16];
                        tempPallete = new byte[16 * 4];
                        reader.Read(tempPallete, 0, 16 * 4);
                        for (int i = 0; i < 16; i++)
                        {
                            pallete[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, tempPallete[(i * 4) + 2], tempPallete[(i * 4) + 1], tempPallete[(i * 4)], 255);
                        }

                        for (int y = imageHeight - 1; y >= 0; y--)
                        {
                            pixels = reader.ReadBytes(paddingWidth);
                            for (int x = 0; x < imageWidth; x++)
                                pixelMap[x, y] = pallete[(x % 2 == 0) ? (pixels[x / 2] >> 4) : (pixels[x / 2] & 0x0F)];
                        }

                        break;

                    case 8: // 256 colors.

                        pallete = new int[256];
                        tempPallete = new byte[256 * 4];
                        reader.Read(tempPallete, 0, 256 * 4);
                        for (int i = 0; i < 256; i++)
                        {
                            pallete[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, tempPallete[(i * 4) + 2], tempPallete[(i * 4) + 1], tempPallete[(i * 4)], 255);
                        }

                        for (int y = imageHeight - 1; y >= 0; y--)
                        {
                            pixels = reader.ReadBytes(paddingWidth);
                            for (int x = 0; x < imageWidth; x++)
                                pixelMap[x, y] = pallete[pixels[x]];
                        }

                        break;

                    case 24: // 16,777,216 colors

                        for (int y = imageHeight - 1; y >= 0; y--)
                        {
                            pixels = reader.ReadBytes(paddingWidth);
                            for (int x = 0; x < imageWidth; x++)
                                pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixels[(x * 3) + 2], pixels[(x * 3) + 1], pixels[(x * 3)], 255);
                        }

                        break;

                    case 32: // 16,777,216 colors with alpha

                        for (int y = imageHeight - 1; y >= 0; y--)
                        {
                            pixels = reader.ReadBytes(paddingWidth);
                            for (int x = 0; x < imageWidth; x++)
                                pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixels[(x * 4) + 2], pixels[(x * 4) + 1], pixels[(x * 4)], pixels[(x * 4) + 3]);
                        }

                        break;

                    default:

                        // The user has either tried to load an corrupt file, or
                        // a file with an unsupported bit count.
                        throw new Exception("Attempt to load BMP file with an bit format storing the image data.");

                }

                stream.Close();
                return pixelMap;

            }
            else // Header check
            {
                reader.Close();
                return null;
            }
        }
コード例 #33
0
ファイル: DjvuPage.cs プロジェクト: sahwar/DjvuNet
        internal bool Stencil(IPixelMap pm, Graphics.Rectangle rect, int subsample, double gamma)
        {
            Verify.SubsampleRange(subsample);

            int width = Width;
            int height = Height;

            if (width <= 0 || height <= 0)
                return false;

            double gammaCorr = 1.0D;

            if (gamma > 0.0D)
            {
                gammaCorr = gamma / Gamma;
            }

            if (gammaCorr < 0.10000000000000001D)
            {
                gammaCorr = 0.10000000000000001D;
            }
            else if (gammaCorr > 10D)
            {
                gammaCorr = 10D;
            }

            JB2Image fgJb2 = ForegroundJB2Image;

            if (fgJb2 != null)
            {
                ColorPalette fgPalette = ForegroundPalette;

                if (fgPalette != null)
                {
                    List<int> components = new List<int>();
                    GBitmap bm = GetBitmapList(rect, subsample, 1, components);

                    if (fgJb2.Blits.Count != fgPalette.BlitColors?.Length)
                    {
                        pm.Attenuate(bm, 0, 0);

                        return false;
                    }

                    GPixmap colors =
                      new PixelMap().Init(1, fgPalette.PaletteColors.Length, null);

                    GPixelReference color = colors.CreateGPixelReference(0);

                    for (int i = 0; i < colors.Width; color.IncOffset())
                        fgPalette.IndexToColor(i++, color);

                    colors.ApplyGammaCorrection(gammaCorr);

                    List<int> compset = new List<int>();

                    while (components.Count > 0)
                    {
                        int lastx = 0;
                        int colorindex = fgPalette.BlitColors[components[0]];
                        GRect comprect = new GRect();
                        compset = new List<int>();

                        for (int pos = 0; pos < components.Count; )
                        {
                            int blitno = ((int)components[pos]);
                            JB2Blit pblit = fgJb2.Blits[blitno];

                            if (pblit.Left < lastx)
                            {
                                break;
                            }

                            lastx = pblit.Left;

                            if (fgPalette.BlitColors[blitno] == colorindex)
                            {
                                JB2Shape pshape = fgJb2.GetShape(pblit.ShapeNumber);
                                GRect xrect = new GRect(pblit.Left, pblit.Bottom,
                                    pshape.Bitmap.Width, pshape.Bitmap.Height);

                                comprect.Recthull(comprect, xrect);
                                compset.Add(components[pos]);
                                components.RemoveAt(pos);
                            }
                            else
                            {
                                pos++;
                            }
                        }

                        comprect.XMin /= subsample;
                        comprect.YMin /= subsample;
                        comprect.XMax = ((comprect.XMax + subsample) - 1) / subsample;
                        comprect.YMax = ((comprect.YMax + subsample) - 1) / subsample;
                        comprect.Intersect(comprect, rect);

                        if (comprect.Empty)
                        {
                            continue;
                        }

                        bm = new DjvuNet.Graphics.Bitmap();
                        bm.Init(comprect.Height, comprect.Width, 0);
                        bm.Grays = 1 + (subsample * subsample);

                        int rxmin = comprect.XMin * subsample;
                        int rymin = comprect.YMin * subsample;

                        for (int pos = 0; pos < compset.Count; ++pos)
                        {
                            int blitno = ((int)compset[pos]);
                            JB2Blit pblit = fgJb2.Blits[blitno];
                            JB2Shape pshape = fgJb2.GetShape(pblit.ShapeNumber);
                            bm.Blit(
                              pshape.Bitmap,
                              pblit.Left - rxmin,
                              pblit.Bottom - rymin,
                              subsample);
                        }

                        color.SetOffset(colorindex);
                        pm.Blit(
                          bm,
                          comprect.XMin - rect.XMin,
                          comprect.YMin - rect.YMin,
                          color);
                    }

                    return true;
                }

                // Three layer model.
                IInterWavePixelMap fgIWPixmap = ForegroundIWPixelMap;

                if (fgIWPixmap != null)
                {
                    GBitmap bm = GetBitmap(rect, subsample, 1, null);

                    if (bm != null && pm != null)
                    {
                        GPixmap fgPixmap = ForegroundPixelMap;
                        int w = fgPixmap.Width;
                        int h = fgPixmap.Height;
                        int red = ComputeRed(width, height, w, h);

                        //          if((red < 1) || (red > 12))
                        if (red < 1 || red > 16)
                            return false;
                        //
                        //          int supersample = (red <= subsample)
                        //            ? 1
                        //            : (red / subsample);
                        //          int wantedred = supersample * subsample;
                        //
                        //          if(red == wantedred)
                        //          {
                        //            pm.stencil(bm, fgPixmap, supersample, rect, gamma_correction);
                        //
                        //            return 1;
                        //          }
                        pm.Stencil(bm, fgPixmap, red, subsample, rect, gammaCorr);
                        return true;
                    }
                }
            }

            return false;
        }
コード例 #34
0
        /// <summary>
        ///     This method is called when PixelMap load is requested, if you return a PixelMap 
        ///     it will return it from the user else it will keep trying all the other PixelMapLoaders
        ///     until it does get one
        /// </summary>
        /// <param name="file">File path of the image to load.</param>
        /// <returns>A PixelMap or NULL if this factory can't load the given image file.</returns>
        protected override PixelMap RequestLoad(object path)
        {
            Stream stream = StreamFactory.RequestStream(path, StreamMode.Open);
            if (stream == null) return null;
            BinaryReader reader = new BinaryReader(stream);

            #region Header Parsing

            // Cheak the 8 byte identifier header at the start to make
            // sure this really is a PNG file.
            byte[] correctHeader = new byte[8] {137, 80, 78, 71, 13, 10, 26, 10};
            byte[] header = reader.ReadBytes(8);

            for (int i = 0; i < correctHeader.Length; i++)
                if (correctHeader[i] != header[i])
                {
                    reader.Close();
                    return null;
                }

            #endregion

            // Declare chunk releated local variables
            #region Local variables

            int    chunkIndex = 0;
            int    width = 0, height = 0;
            byte   bitDepth = 0, colorType = 0, compressionMethod = 0;
            byte   filterMethod = 0, interlaceMethod = 0;
            bool   readingChunks = true;
            byte[] pixelData = null;
            int	   bytesPerPixel = 0, bitsPerPixel = 0;
            int    dataSize = 0;
            PixelMap pixelMap = null;

            #endregion

            // Read in every chunk till we find the end of file chunk or
            // we read past the end of the stream.
            #region Chunk reading
            while (readingChunks)
            {
                // Read in chunk's data
                int    chunkLength    = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                byte[] chunkTypeChars = reader.ReadBytes(4);
                string chunkType	  = ((char)chunkTypeChars[0]).ToString() + ((char)chunkTypeChars[1]).ToString() +
                                        ((char)chunkTypeChars[2]).ToString() + ((char)chunkTypeChars[3]).ToString();

                #region Chunk parsing
                switch (chunkType)
                {
                    // Image header chunk, it MUST come first.
                    case "IHDR":

                        if (chunkIndex != 0) throw new Exception("Found out of sequence IHDR chunk while loading PNG file.");
                        width			  = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        height			  = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        bitDepth		  = reader.ReadByte();
                        colorType	      = reader.ReadByte();
                        compressionMethod = reader.ReadByte();
                        filterMethod      = reader.ReadByte();
                        interlaceMethod   = reader.ReadByte();

                        pixelMap = new PixelMap(width, height);

                        break;

                    // Pallete chunk.
                        /*
                    case "PLTE":

                        if (gotPallete == true || (colorType == 0 && gotData == false) || (colorType == 4 && gotData == false))
                            throw new Exception("Found out of sequence or unexpected PLTE pallete chunk while loading PNG image.");

                        for (int i = 0; i < chunkLength / 3; i++)
                        {
                            pallete[(i * 3)]	 = reader.ReadByte();
                            pallete[(i * 3) + 1] = reader.ReadByte();
                            pallete[(i * 3) + 2] = reader.ReadByte();
                        }

                        gotPallete = true;

                        break;
                        */

                    // Image data chunk.
                    case "IDAT":

                        // Read in the new data and append it to the compressed
                        // data array for future use.
                        int index = pixelData == null ? 0 : pixelData.Length;

                        if (pixelData != null)
                            Array.Resize(ref pixelData, pixelData.Length + chunkLength);
                        else
                            pixelData = new byte[chunkLength];

                        stream.Read(pixelData, index, chunkLength);
                        dataSize += chunkLength;

                        break;

                    // End of chunks chunk.
                    case "IEND":

                        readingChunks = false;

                        break;

                    /*
                    // Transparencry chunk.
                    case "tRNS":

                        break;

                    // Image gamma chunk.
                    case "gAMA":

                        gamma = EndianSwapMethods.SwapEndian(reader.ReadInt32());

                        break;

                    ///Primary chromaticities chunk.
                    case "cHRM":

                        whitePointX = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        whitePointY = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        redX	    = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        redY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        greenX		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        greenY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        blueX		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                        blueY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());

                        break;

                    // Standard RGB color space chunk.
                    case "sRGB":

                        renderingIntent = reader.ReadByte();

                        break;

                    // Embedded ICCP chunk.
                    case "iCCP":

                        break;

                    // Internation textural infomation chunk
                    case "iTXt":

                        break;

                    // Textural infomation chunk.
                    case "tEXt":

                        // Get the keyword
                        string keyword = "";
                        int	   keyAsc = 0;
                        while(true)
                        {
                            keyAsc = reader.ReadByte();
                            if (keyAsc == 0) break;
                            keyword += ((char)keyAsc).ToString();
                        }

                        // Read the text
                        string text = "";
                        int	   textLength = chunkLength - keyword.Length - 1;
                        for (int i = 0; i < textLength; i++)
                            text += ((char)reader.ReadByte()).ToString();

                        break;
                     *
                    // Compressed textural infomation chunk.
                    case "zTXt":

                        break;

                    // Default background color chunk.
                    case "bKGD":

                        break;

                    // Physical pixel dimensions chunk.
                    case "pHYs":

                        break;

                    // Bit chunk.
                    case "sBit":

                        break;

                    // Suggested pallete chunk.
                    case "sPLT":

                        break;

                    // Pallete histogram chunk.
                    case "hIST":

                        break;

                    // Last modification time chunk.
                    case "tIME":
                        */

                    default:

                        // Check the chunk is not critical if it is, this file
                        // is probably corrupt or the chunk is not implemented in this
                        // loader so throw up an exception.
                        if ((((byte)chunkTypeChars[0]) & 32) == 0)
                            throw new Exception("Found unknown or unsupported but critical chunk while reading PNG file.");

                        stream.Position += chunkLength;

                        break;
                }
                #endregion

                // We shall just ignore the CRC for now :)
                int CRC = EndianSwapMethods.SwapEndian(reader.ReadInt32());

                chunkIndex++;
            }
            #endregion

            // Check the expect size is the same as the actual size.
            if (dataSize != pixelData.Length) throw new Exception("An error occured while reading in pixel data, data size is not the same as expect size.");

            // Work out how many bytes are used by each pixel
            #region Pixel size calculations
            switch (colorType)
            {
                case 0: bitsPerPixel = bitDepth;	 break; // Grey
                case 2: bitsPerPixel = bitDepth * 3; break; // RGB
                case 3: bitsPerPixel = bitDepth;  	 break; // Pallete indexed
                case 4: bitsPerPixel = bitDepth * 2; break; // Grey and alpha.
                case 6: bitsPerPixel = bitDepth * 4; break; // RGB and alpha.
            }
            bytesPerPixel = (int)Math.Round(bitsPerPixel / 8.0, MidpointRounding.AwayFromZero);
            #endregion

            // Decompress data array.
            #region Decompression

            byte[] pixelDataWithoutHeader = new byte[pixelData.Length - 2];
            Array.Copy(pixelData, 2, pixelDataWithoutHeader, 0, pixelData.Length - 2);
            pixelData = DataMethods.Inflate(pixelDataWithoutHeader);

            #endregion

            // Remove filter.
            #region Filter removal

            switch (filterMethod)
            {
                case 0: // No filter.

                    byte[] filteredData = new byte[pixelData.Length - height];
                    int scanlineWidth = (width * bytesPerPixel);

                    byte[] scanlineData = null;
                    for (int scanline = 0; scanline < height; scanline++)
                    {
                        int priorScanlineIndex = ((scanlineWidth + 1) * (scanline - 1)) + 1;
                        int scanlineIndex = ((scanlineWidth + 1) * scanline) + 1;
                        byte slFilterMethod = pixelData[scanlineIndex - 1];
                        byte[] priorScanlineData = scanline == 0 ? new byte[scanlineWidth] : scanlineData;
                        scanlineData = new byte[scanlineWidth];
                        Array.Copy(pixelData, scanlineIndex, scanlineData, 0, scanlineWidth);

                        // Check what kind of filter is attached to this scanline.
                        switch (slFilterMethod)
                        {
                            case 0: // None
                                break;
                            case 1: // Left
                                for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                                {
                                    int left = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                                    scanlineData[pixel] = (byte)((scanlineData[pixel] + left) % 256);
                                }
                                break;
                            case 2: // Up
                                for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                                {
                                    byte prior = priorScanlineData[pixel];
                                    scanlineData[pixel] = (byte)((scanlineData[pixel] + prior) % 256);
                                }
                                break;
                            case 3: // Average
                                for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                                {
                                    float p = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                                    float prior = priorScanlineData[pixel];
                                    scanlineData[pixel] = (byte)(scanlineData[pixel] + Math.Floor((p+prior)/2));
                                }
                                break;
                            case 4: // Paeth
                                for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                                {
                                    int l = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                                    int u = priorScanlineData[pixel];
                                    int ul = pixel - bytesPerPixel < 0 ? (byte)0 : priorScanlineData[pixel - bytesPerPixel];
                                    scanlineData[pixel] = (byte)((scanlineData[pixel] + PaethPredictor((byte)l, (byte)u, (byte)ul)) % 256);
                                }
                                break;
                            default:
                                throw new Exception("PNG Factory encountered file with invalid or unsupported scanline filter while reading file.");
                        }

                        // Place the scanline data into the filtered data.
                        Array.Copy(scanlineData, 0, filteredData, scanline * scanlineWidth, scanlineWidth);
                    }

                    pixelData = filteredData;

                    break;

                default:

                    stream.Close();
                    throw new Exception("PNG Factory encountered file with invalid or unsupported filter method while reading file.");
            }

            #endregion

            // Remove interlacing.
            #region Interlace removal
            switch (interlaceMethod)
            {
                case 0: // No interlace.

                    // *whistles* may as well ignore this, sorter pointless it even
                    // being here.

                    break;

                default:

                    stream.Close();
                    throw new Exception("PNG Factory encountered file with invalid or unsupported interlace method while reading file.");

            }
            #endregion

            // Store decompressed data in pixelmap.
            #region PixelMap building
            switch (colorType)
            {
                case 2: // RGB

                    for (int i = 0; i < (width * height); i++)
                    {
                        int pixelIndex = i * bytesPerPixel;
                        pixelMap[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixelData[pixelIndex], pixelData[pixelIndex + 1], pixelData[pixelIndex + 2], 255);
                    }

                    break;

                case 6: // RGB with alpha.

                    for (int i = 0; i < (width * height); i++)
                    {
                        int pixelIndex = i * bytesPerPixel;
                        pixelMap[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixelData[pixelIndex], pixelData[pixelIndex + 1], pixelData[pixelIndex + 2], pixelData[pixelIndex + 3]);
                    }

                    break;

                // Sherlock, somethings amiss!
                default:

                    stream.Close();
                    throw new Exception("PNG Factory encountered an invalid or unsupported image type while loading an image.");

            }
            #endregion

            // Return pixelmap and close stream
            stream.Close();
            return pixelMap;
        }
コード例 #35
0
		public static void PixelMap(PixelMap map, UInt16[] values)
		{
			unsafe {
				fixed (UInt16* p_values = values)
				{
					Debug.Assert(Delegates.pglPixelMapusv != null, "pglPixelMapusv not implemented");
					Delegates.pglPixelMapusv((Int32)map, (Int32)values.Length, p_values);
					LogFunction("glPixelMapusv({0}, {1}, {2})", map, values.Length, LogValue(values));
				}
			}
			DebugCheckErrors(null);
		}
コード例 #36
0
ファイル: Gl.VERSION_1_0.cs プロジェクト: MagmaiKH/OpenGL.Net
		public static void PixelMap(PixelMap map, Int32 mapsize, UInt16[] values)
		{
			Debug.Assert(values.Length >= mapsize);
			unsafe {
				fixed (UInt16* p_values = values)
				{
					Debug.Assert(Delegates.pglPixelMapusv != null, "pglPixelMapusv not implemented");
					Delegates.pglPixelMapusv((Int32)map, mapsize, p_values);
					CallLog("glPixelMapusv({0}, {1}, {2})", map, mapsize, values);
				}
			}
			DebugCheckErrors();
		}
コード例 #37
0
		public static void GetPixelMap(PixelMap map, [Out] UInt32[] values)
		{
			unsafe {
				fixed (UInt32* p_values = values)
				{
					Debug.Assert(Delegates.pglGetPixelMapuiv != null, "pglGetPixelMapuiv not implemented");
					Delegates.pglGetPixelMapuiv((Int32)map, p_values);
					LogFunction("glGetPixelMapuiv({0}, {1})", map, LogValue(values));
				}
			}
			DebugCheckErrors(null);
		}
コード例 #38
0
        /// <summary>
        ///     This method is called when PixelMap load is requested, if you return a PixelMap 
        ///     it will return it from the user else it will keep trying all the other PixelMapLoaders
        ///     until it does get one
        /// </summary>
        /// <param name="file">File path of the image to load.</param>
        /// <returns>A PixelMap or NULL if this factory can't load the given image file.</returns>
        protected override PixelMap RequestLoad(object path)
        {
            Stream stream = StreamFactory.RequestStream(path, StreamMode.Open);
            if (stream == null) return null;
            BinaryReader reader = new BinaryReader(stream);
            if (stream.Length < 18)
            {
                reader.Close();
                return null;
            }

            // Read in TGA header.
            #region Header reading

            byte identSize	  = reader.ReadByte();
            byte colorMapType = reader.ReadByte();
            byte imageType	  = reader.ReadByte();

            short colorMapStart  = reader.ReadInt16();
            short colorMapLength = reader.ReadInt16();
            byte  colorMapBits   = reader.ReadByte();

            short xStart	 = reader.ReadInt16();
            short yStart	 = reader.ReadInt16();
            short width		 = reader.ReadInt16();
            short height	 = reader.ReadInt16();
            byte  bits		 = reader.ReadByte();
            byte  descriptor = reader.ReadByte();

            // Check the header is a true tga header.
            if (colorMapType != 0 || width < 1 || width > 4096 ||
                height < 1 || height > 4096 || (imageType != (int)TGAImageType.RGB && imageType != (int)TGAImageType.RLERGB))
            {
                reader.Close();
                return null;
            }

            for (int identCounter = 0; identCounter < identSize; identCounter++)
                reader.ReadByte();

            int pixelCount = width * height;
            int chunkSize = 0;
            int argbColor = 0, rgbColor = 0;

            #endregion

            // Create pixelmap to store data in
            PixelMap pixelMap = new PixelMap(width, height);

            // Most Image types are unused in this day and age so only the most
            // common will be loaded (RGB, RGBRLE, both with 15,16,24 and 32 bit support).
            switch(imageType)
            {
                #region Uncompressed RGB

                case (int)TGAImageType.RGB: // RGB uncompressed color data, the BMP of the TGA world!

                    // Read in depending on bit depth
                    switch (bits)
                    {
                        case 15:

                            for (int y = height - 1; y >= 0; y--)
                            {
                                for (int x = 0; x < width; x++)
                                {
                                    rgbColor = reader.ReadInt16();
                                    pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, 255);
                                }
                            }

                            break;

                        case 16:

                            for (int y = height - 1; y >= 0; y--)
                            {
                                for (int x = 0; x < width; x++)
                                {
                                    rgbColor = reader.ReadInt16();
                                    pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, (rgbColor & 0x8000) != 0 ? 255 : 0);
                                }
                            }

                            break;

                        case 24:

                            for (int y = height - 1; y >= 0; y--)
                            {
                                for (int x = 0; x < width; x++)
                                {
                                    byte[] color = reader.ReadBytes(3);
                                    pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], 255);
                                }
                            }

                            break;

                        case 32:

                            for (int y = height - 1; y >= 0; y--)
                            {
                                for (int x = 0; x < width; x++)
                                {
                                    byte[] color = reader.ReadBytes(4);
                                    pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], color[3]);
                                }
                            }

                            break;

                        default:
                            reader.Close();
                            return null;
                    }

                    reader.Close();
                    return pixelMap;

                #endregion
                #region Compressed RGB

                case (int)TGAImageType.RLERGB: // Run length encoded RGB color data.

                    // Read in depending on bit depth
                    switch (bits)
                    {
                        case 15:

                            // Read in each image color packet.
                            for (int counter = 0; counter < pixelCount; )
                            {
                                chunkSize = reader.ReadByte();

                                // Check if color packet is RLE or RAW.
                                if ((chunkSize & 128) != 0)
                                {
                                    chunkSize -= 127;
                                    rgbColor = reader.ReadInt16();
                                    argbColor = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, 255);
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                        counter++;
                                    }
                                }
                                else
                                {
                                    chunkSize++;
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        rgbColor = reader.ReadInt16();
                                        pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, 255);
                                        counter++;
                                    }
                                }

                            }

                            break;

                        case 16:

                            // Read in each image color packet.
                            for (int counter = 0; counter < pixelCount; )
                            {
                                chunkSize = reader.ReadByte();

                                // Check if color packet is RLE or RAW.
                                if ((chunkSize & 128) != 0)
                                {
                                    chunkSize -= 127;
                                    rgbColor = reader.ReadInt16();
                                    argbColor = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, (rgbColor & 0x8000) != 0 ? 255 : 0);
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                        counter++;
                                    }
                                }
                                else
                                {
                                    chunkSize++;
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        rgbColor = reader.ReadInt16();
                                        pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, (rgbColor & 0x8000) != 0 ? 255 : 0);
                                        counter++;
                                    }
                                }

                            }

                            break;

                        case 24:

                            // Read in each image color packet.
                            for (int counter = 0; counter < pixelCount; )
                            {
                                chunkSize = reader.ReadByte();

                                // Check if color packet is RLE or RAW.
                                if ((chunkSize & 128) != 0)
                                {
                                    chunkSize -= 127;
                                    byte[] color = reader.ReadBytes(3);
                                    argbColor = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], 255);
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                        counter++;
                                    }
                                }
                                else
                                {
                                    chunkSize++;
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        byte[] color = reader.ReadBytes(3);
                                        pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], 255);
                                        counter++;
                                    }
                                }
                            }

                            break;

                        case 32:

                            // Read in each image color packet.
                            for (int counter = 0; counter < pixelCount;)
                            {
                                chunkSize = reader.ReadByte();

                                // Read in as RLE packet.
                                if ((chunkSize & 128) != 0)
                                {
                                    chunkSize -= 127;
                                    byte[] color = reader.ReadBytes(4);
                                    argbColor = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], color[3]);
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                        counter++;
                                    }
                                }

                                // Read in as RAW packet.
                                else
                                {
                                    chunkSize++;
                                    for (int i = 0; i < chunkSize; i++)
                                    {
                                        byte[] color = reader.ReadBytes(4);
                                        pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], color[3]);
                                        counter++;
                                    }
                                }

                            }

                            break;

                        default:
                            reader.Close();
                            return null;
                    }

                    reader.Close();
                    return pixelMap;

                #endregion
                default:
                    stream.Close();
                    return null;
            }
        }
コード例 #39
0
 public static extern void GetPixelMapfv( PixelMap map, [Out]float[] values );
コード例 #40
0
 /// <summary>
 ///		Creates a new valid image frame from a pixelmap.
 /// 
 ///		This is mainly used by the Image class to recreate images whenever the driver changes 
 /// </summary>
 /// <param name="pixelMap">Pixelmap to create new image frame from.</param>
 IImageFrame IGraphicsDriver.CreateImageFrame(PixelMap pixelMap)
 {
     return pixelMap == null ? new OpenGLImageFrame(this) : new OpenGLImageFrame(this, pixelMap);
 }
コード例 #41
0
        /// <summary>
        ///     This method is called when PixelMap save is requested, if it returns true
        ///		the calling method will stop illiterating through the PixelMapFactorys and 
        ///		return success to the user.
        /// </summary>
        /// <param name="path">File path or object of the image to load.</param>
        /// <param name="pixelMap">PixelMap to save.</param>
        /// <param name="flags">Bitmask of flags defining how the pixel map should be saved.</param>
        /// <returns>True if the save was successfull else false.</returns>
        protected override bool RequestSave(object path, PixelMap pixelMap, PixelMapSaveFlags flags)
        {
            if (path.ToString().ToLower().EndsWith(".bmp") == false &&
                path.ToString().ToLower().EndsWith(".dib") == false) return false;

            Stream stream = StreamFactory.RequestStream(path, StreamMode.Truncate);
            if (stream == null) return false;

            BinaryWriter writer = new BinaryWriter(stream);

            // Work out how to save.
            int bitCount = 24;
            if ((flags & PixelMapSaveFlags.BITDEPTH1) != 0)
                bitCount = 1;
            if ((flags & PixelMapSaveFlags.BITDEPTH4) != 0)
                bitCount = 4;
            if ((flags & PixelMapSaveFlags.BITDEPTH8) != 0)
                bitCount = 8;
            if ((flags & PixelMapSaveFlags.BITDEPTH24) != 0)
                bitCount = 24;
            if ((flags & PixelMapSaveFlags.BITDEPTH32) != 0)
                bitCount = 32;

            // Write in header.
            writer.Write(new char[2] { 'B', 'M' });

            // Write in file header.
            writer.Write((int)0);
            writer.Write((short)0);
            writer.Write((short)0);
            writer.Write((int)54);

            // Write in image header.
            writer.Write((int)40);
            writer.Write((int)pixelMap.Width);
            writer.Write((int)pixelMap.Height);
            writer.Write((short)1);
            writer.Write((short)bitCount);
            writer.Write((int)0);
            writer.Write((int)0);
            writer.Write((int)3780);
            writer.Write((int)3780);
            writer.Write((int)0);
            writer.Write((int)0);

            // Work out the horizontal padding size.
            int paddingWidth = (int)((float)pixelMap.Width * (float)bitCount / 8.0f);
            while (paddingWidth % 4 != 0) paddingWidth++;

            // Grab a few usefull details from the pixel map.
            int maskColor = pixelMap.MaskColor, maskRed, maskGreen, maskBlue, maskAlpha;
            ColorMethods.SplitColor(ColorFormats.A8R8G8B8, maskColor, out maskRed, out maskGreen, out maskBlue, out maskAlpha);

            // Write in based of bit count
            switch (bitCount)
            {
                case 1:

                    // Write out our lovely monocromatic colors, black and white obviously :).
                    writer.Write((int)ColorMethods.CombineColor(ColorFormats.A8R8G8B8, ColorFormats.B8G8R8, unchecked((int)0xFF000000)));
                    writer.Write((int)ColorMethods.CombineColor(ColorFormats.A8R8G8B8, ColorFormats.B8G8R8, unchecked((int)0xFFFFFFFF)));

                    // Write byte here!
                    for (int y = pixelMap.Height - 1; y >= 0; y--)
                    {
                        int bit = 128;
                        int bitMask = 0;

                        for (int x = 0; x < pixelMap.Width; x++)
                        {
                            // Mask with bit if pixel should be black.
                            int red, green, blue, alpha;
                            ColorMethods.SplitColor(ColorFormats.A8R8G8B8, pixelMap[x, y], out red, out green, out blue, out alpha);
                            if (red > 128 || green > 128 || blue > 128)
                                bitMask |= bit;

                            // Flips horizontal direction at every 8th horizontal pixel.
                            // Update bit mask.
                            bit >>= 1;
                            if (bit < 1)
                            {
                                writer.Write((byte)bitMask);
                                bit     = 128;
                                bitMask = 0;
                            }
                        }

                        // Write in last bit if neccessary.
                        if (bitMask > 0)
                            writer.Write((byte)bitMask);

                        // Pad out scan line.
                        for (int i = (pixelMap.Width / 8); i < paddingWidth - 1; i++)
                            writer.Write((byte)0);
                    }

                    break;

                //case 4: // - Can't think when this would be needed? Can you?

                //	break;

                //case 8: // Same as 4bit.

                //	break;

                case 24:

                    for (int y = pixelMap.Height - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < paddingWidth / (bitCount / 8); x++)
                        {
                            int red = 0, green = 0, blue = 0, alpha = 0;
                            if (x < pixelMap.Width)
                            {
                                // If the pixel map is masked we need to substitute the pixel color
                                // for the correct mask color or we will just end up with an invisible pixel (>_>).
                                if (pixelMap[x, y] != pixelMap.MaskColor)
                                {
                                    ColorMethods.SplitColor(ColorFormats.A8R8G8B8, pixelMap[x, y], out red, out green, out blue, out alpha);
                                }
                                else
                                {
                                    blue   = maskBlue;
                                    green  = maskGreen;
                                    red	   = maskRed;
                                }
                                writer.Write((byte)blue);
                                writer.Write((byte)green);
                                writer.Write((byte)red);
                            }
                            else
                            {
                                writer.Write((byte)0);
                            }
                        }
                    }

                    break;

                case 32:

                    for (int y = pixelMap.Height - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < paddingWidth / (bitCount / 8); x++)
                        {
                            int red = 0, green = 0, blue = 0, alpha = 0;
                            if (x < pixelMap.Width)
                            {
                                // If the pixel map is masked we need to substitute the pixel color
                                // for the correct mask color or we will just end up with an invisible pixel (>_>).
                                if (pixelMap[x, y] != pixelMap.MaskColor)
                                {
                                    ColorMethods.SplitColor(ColorFormats.A8R8G8B8, pixelMap[x, y], out red, out green, out blue, out alpha);
                                }
                                else
                                {
                                    blue   = maskBlue;
                                    green  = maskGreen;
                                    red	   = maskRed;
                                    alpha  = maskAlpha;
                                }
                                writer.Write((byte)blue);
                                writer.Write((byte)green);
                                writer.Write((byte)red);
                                writer.Write((byte)alpha);
                            }
                            else
                            {
                                writer.Write((byte)0);
                            }
                        }
                    }

                    break;

                default:

                    stream.Close();
                    throw new Exception(bitCount+"bit bmp saving is not supported");

            }

            // Seek back to start and write in file size
            stream.Flush();
            int fileSize = (int)stream.Length;
            stream.Seek(2, SeekOrigin.Begin);
            writer.Write(fileSize);

            // Seek back to start and write in image size.
            stream.Seek(34, SeekOrigin.Begin);
            writer.Write(fileSize - 54);

            // Cleanup stream and return success.
            stream.Close();
            return true;
        }
コード例 #42
0
 public static void glGetPixelMapfv(PixelMap map, ref Single[] values)
 {
     i_OpenGL1_0.glGetPixelMapfv(map, ref values);
 }
コード例 #43
0
ファイル: PixelGrid.cs プロジェクト: jonathanruisi/Utility
 public PixelGrid()
 {
     MouseEnter += PixelGrid_MouseEnter;
     MouseLeave += PixelGrid_MouseLeave;
     MouseMove += PixelGrid_MouseMove;
     MouseDown += PixelGrid_MouseDown;
     MouseUp += PixelGrid_MouseUp;
     _pixelMap = new PixelMap(PixelGridWidth, PixelGridHeight);
     _isLeftButtonDown = false;
     _isRightButtonDown = false;
 }
コード例 #44
0
        /// <summary>
        ///     Constructs a DirectX9 surface for this image from a PixelMap.
        /// </summary>
        /// <param name="pixelMap">PixelMap to construct surface from.</param>
        void ConstructFromPixelMap(PixelMap pixelMap)
        {
            _pixelMap = pixelMap;

            // Work out size of texture to create so that we have a nice square texture.
             if (_dx9Driver.DX9Device.DeviceCaps.TextureCaps.SupportsSquareOnly == true || _dx9Driver.DX9Device.DeviceCaps.TextureCaps.SupportsPower2 == true)
            {
                 if (pixelMap.Width > pixelMap.Height)
                 {
                     _textureWidth = MathMethods.Pow(pixelMap.Width, 2);
                     _textureHeight = _textureWidth;
                 }
                 else
                 {
                     _textureHeight = MathMethods.Pow(pixelMap.Height, 2);
                     _textureWidth = _textureHeight;
                 }
            }
            else
            {
                _textureWidth = pixelMap.Width;
                _textureHeight = pixelMap.Height;
            }

            // Create texture.
            _texture = new Texture(_dx9Driver.DX9Device, _textureWidth, _textureHeight, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);

            // Copy the pixelMap and resize it.
            PixelMap copy = new PixelMap(_textureWidth, _textureHeight);
            copy.Fill(0x00000000);
            copy.Paste(pixelMap, 0, 0);

            // Add memory pressure so the GC collects faster.
            _memoryPressure = copy.Data.Length;
            GC.AddMemoryPressure(_memoryPressure);

            // Create a buffer and then write the image data into it.
            int pitch;
            GraphicsStream stream = _texture.LockRectangle(0, 0, out pitch);
            stream.Write(copy.Data);
            _texture.UnlockRectangle(0);

            // Sets up the vertex-buffer so all our data is correct
            _vertexArray[0].X = 0;
            _vertexArray[0].Y = 0;
            _vertexArray[1].X = _textureWidth;
            _vertexArray[1].Y = 0;
            _vertexArray[2].X = _textureWidth;
            _vertexArray[2].Y = _textureHeight;
            _vertexArray[3].X = 0;
            _vertexArray[3].Y = _textureHeight;

            // Hook into the dx9 disposal event so we can clean up.
            _dx9Driver.DX9Device.Disposing += new EventHandler(DX9Device_Disposing);
        }
コード例 #45
0
 /// <summary>
 ///		Creates a new image frame out of a PixelMap and associates it with a specific image.
 /// </summary>
 /// <param name="driver">Direct3D9Driver that this image frame should be associated with.</param>
 /// <param name="pixelMap">PixelMap to create frame from.</param>
 public Direct3D9ImageFrame(Direct3D9Driver driver, PixelMap pixelMap)
 {
     _dx9Driver = driver;
     ConstructFromPixelMap(pixelMap);
 }
コード例 #46
0
ファイル: GLCore.cs プロジェクト: nagyist/Pencil.Gaming
		internal static extern void glPixelMapusv(PixelMap map, Int32 mapsize, UInt16* values);
コード例 #47
0
ファイル: GLCore.cs プロジェクト: nagyist/Pencil.Gaming
		internal static extern void glGetPixelMapusv(PixelMap map, [OutAttribute] UInt16* values);
コード例 #48
0
ファイル: ToyTracer.cs プロジェクト: Tilps/Stash
        private PixelMap Trace(int threadCount)
        {
            if (scene == null)
            {
                throw new NullReferenceException("Empty Scene");
            }
            scene.SetTracer(this, threadCount);
            raycount = new int[threadCount];
            Pools = new HitInfoListPool[threadCount];
            #if DEBUG
            PhotonParents = new Photon[threadCount];
            #endif
            for (int i = 0; i < threadCount; i++)
                Pools[i] = new HitInfoListPool();
            if (photons)
            {
                if (PhotonFile == null || !File.Exists(PhotonFile))
                {
                    Map.InitForThreads(threadCount, true);
                    Thread[] pthreads = new Thread[threadCount];
                    for (int i = 0; i < threadCount; i++)
                    {
                        pthreads[i] = new Thread(GeneratePhotonsWrap);
                        pthreads[i].IsBackground = true;
                        PhotonThreadArgs args = new PhotonThreadArgs();
                        args.threadCount = threadCount;
                        args.threadId = i;
                        pthreads[i].Start(args);
                    }
                    for (int i = 0; i < threadCount; i++)
                    {
                        pthreads[i].Join();
                    }
                    Map.BalanceMap();
                    if (PhotonFile != null)
                        Map.Save(PhotonFile);
                    Map.OptimiseRadi();
                }
                else
                {
                    Map.InitForThreads(threadCount, false);
                    Map.Load(PhotonFile);
                    Map.ValidateBalance();
                    Map.OptimiseRadi();
                }
            }
            PixelMap scrpix = new PixelMap(viewport.ScreenX, viewport.ScreenY);
            Color[] screen = scrpix.Pix;

            List<ColorIntensity>[] shadings = new List<ColorIntensity>[screen.Length];
            for (int i = 0; i < shadings.Length; i++)
                shadings[i] = new List<ColorIntensity>();
            Counter completed = new Counter();
            int[] successive = new int[screen.Length];
            if (OnProgress != null)
            {
                OnProgress(scrpix, 0 , 0);
            }
            Thread[] threads = new Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                threads[i] = new Thread(OneRenderThreadWrap);
                threads[i].IsBackground = true;
                RenderThreadArgs args = new RenderThreadArgs();
                args.threadCount = threadCount;
                args.threadId = i;
                args.successive = successive;
                args.shadings = shadings;
                args.scrpix = scrpix;
                args.screen = screen;
                args.completed = completed;
                threads[i].Start(args);
            }
            for (int i = 0; i < threadCount; i++)
            {
                threads[i].Join();
            }
            return scrpix;
        }
コード例 #49
0
 public static void glPixelMapusv(PixelMap map, Int32 mapsize, ref UInt16[] values)
 {
     i_OpenGL1_0.glPixelMapusv(map, mapsize, ref values);
 }
コード例 #50
0
ファイル: GLCore.cs プロジェクト: nagyist/Pencil.Gaming
		internal static extern void glPixelMapfv(PixelMap map, Int32 mapsize, Single* values);
コード例 #51
0
 public static void glGetPixelMapusv(PixelMap map, ref UInt16[] values)
 {
     i_OpenGL1_0.glGetPixelMapusv(map, ref values);
 }
コード例 #52
0
ファイル: GL.cs プロジェクト: Wiladams/NewTOAPIA
 public static void PixelMapuiv(PixelMap map, int mapsize, uint[] values)
 {
     gl.glPixelMapuiv((int)map, mapsize, values);
 }
コード例 #53
0
 public static extern void GetPixelMapuiv( PixelMap map, [Out]uint[] values );
コード例 #54
0
ファイル: GLCore.cs プロジェクト: nagyist/Pencil.Gaming
		internal static extern void glGetPixelMapfv(PixelMap map, [OutAttribute] Single* values);
コード例 #55
0
 public static extern void GetPixelMapusv( PixelMap map, [Out]ushort[] values );
コード例 #56
0
 public void PixelMapusv(PixelMap map, int mapsize, ushort[] values)
 {
     gl.glPixelMapusv((int)map, mapsize, values);
 }
コード例 #57
0
ファイル: Gl.VERSION_1_0.cs プロジェクト: MagmaiKH/OpenGL.Net
		public static void PixelMap(PixelMap map, UInt32[] values)
		{
			unsafe {
				fixed (UInt32* p_values = values)
				{
					Debug.Assert(Delegates.pglPixelMapuiv != null, "pglPixelMapuiv not implemented");
					Delegates.pglPixelMapuiv((Int32)map, (Int32)values.Length, p_values);
					CallLog("glPixelMapuiv({0}, {1}, {2})", map, values.Length, values);
				}
			}
			DebugCheckErrors();
		}
コード例 #58
0
        /// <summary>
        ///     This method is called when PixelMap save is requested, if it returns true
        ///		the calling method will stop illiterating through the PixelMapFactorys and 
        ///		return success to the user.
        /// </summary>
        /// <param name="path">File path or object of the image to load.</param>
        /// <param name="pixelMap">PixelMap to save.</param>
        /// <param name="flags">Bitmask of flags defining how the pixel map should be saved.</param>
        /// <returns>True if the save was successfull else false.</returns>
        protected override bool RequestSave(object path, PixelMap pixelMap, PixelMapSaveFlags flags)
        {
            if (path.ToString().ToLower().EndsWith(".png") == false) return false;

            // Not supported yet so throw error.
            throw new Exception("PNG factory is not currently supported.");
        }
コード例 #59
0
ファイル: Gl.VERSION_1_0.cs プロジェクト: MagmaiKH/OpenGL.Net
		public static void GetPixelMap(PixelMap map, [Out] UInt16[] values)
		{
			unsafe {
				fixed (UInt16* p_values = values)
				{
					Debug.Assert(Delegates.pglGetPixelMapusv != null, "pglGetPixelMapusv not implemented");
					Delegates.pglGetPixelMapusv((Int32)map, p_values);
					CallLog("glGetPixelMapusv({0}, {1})", map, values);
				}
			}
			DebugCheckErrors();
		}
コード例 #60
0
 /// <summary>
 ///		Creates a new image frame out of a PixelMap and associates it with a specific image.
 /// </summary>
 /// <param name="driver">Direct3D9Driver that this image frame should be associated with.</param>
 /// <param name="pixelMap">PixelMap to create frame from.</param>
 public OpenGLImageFrame(OpenGLDriver driver, PixelMap pixelMap)
 {
     _glDriver = driver;
     ConstructFromPixelMap(pixelMap);
 }