/// <summary> Writes 16-bit grayscale image </summary>
        public static async Task WriteGrayscaleAsync
        (
            ushort[] pixels,
            int width,
            int height,
            bool alpha,
            string filePath
        )
        {
            try {
                var imageInfo = new ImageInfo(
                    width,
                    height,
                    16,
                    alpha,
                    true,
                    false                    //not implemented here yet
                    );
                await Task.Run(() => {
                    // open image for writing:
                    PngWriter writer = FileHelper.CreatePngWriter(filePath, imageInfo, true);

                    // add some optional metadata (chunks)
                    var meta = writer.GetMetadata();
                    meta.SetTimeNow(0);                      // 0 seconds fron now = now

                    int numRows  = imageInfo.Rows;
                    int numCols  = imageInfo.Cols;
                    int channels = imageInfo.Channels;
                    for (int row = 0; row < numRows; row++)
                    {
                        //fill line:
                        int[] ints = new int[imageInfo.SamplesPerRow];
                        if (alpha == false)
                        {
                            for (int col = 0; col < numCols; col++)
                            {
                                ushort R = pixels[IndexPngToTexture(row, col, numRows, numCols)];
                                ImageLineHelper.SetPixel(ints, R, col, channels);
                            }
                        }
                        else
                        {
                            for (int col = 0; col < numCols; col++)
                            {
                                ushort A = pixels[IndexPngToTexture(row, col, numRows, numCols)];
                                ImageLineHelper.SetPixel(ints, A, col, channels);
                            }
                        }

                        //write line:
                        ImageLine imageline = new ImageLine(imageInfo, ImageLine.ESampleType.INT, false, ints, null, row);
                        writer.WriteRow(imageline, row);
                    }
                    writer.End();
                });
            }
            catch (System.Exception ex) { Debug.LogException(ex); await Task.CompletedTask; }             //kills debugger execution loop on exception
            finally { await Task.CompletedTask; }
        }
        public static void doit(String orig)
        {
            string copy = TestsHelper.addSuffixToName(orig, "_tc");

            PngReader pngr = FileHelper.CreatePngReader(orig);

            if (!pngr.ImgInfo.Indexed)
            {
                throw new Exception("Not indexed image");
            }
            PngChunkPLTE plte  = pngr.GetMetadata().GetPLTE();
            PngChunkTRNS trns  = pngr.GetMetadata().GetTRNS(); // transparency metadata, can be null
            bool         alpha = trns != null;
            ImageInfo    im2   = new ImageInfo(pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, 8, alpha);
            PngWriter    pngw  = FileHelper.CreatePngWriter(copy, im2, true);

            pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            int[] buf = null;
            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine line = pngr.ReadRowInt(row);
                buf = ImageLineHelper.Palette2rgb(line, plte, trns, buf);
                pngw.WriteRowInt(buf, row);
            }
            pngw.CopyChunksLast(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            pngr.End();
            pngw.End();
            Console.WriteLine("True color: " + copy);
        }
Example #3
0
    public static void WriteToFile(int imageWidth, int imageHeight, Color32[] pixels, String filename, bool hasAlpha)
    {
        ImageInfo imageInfo = new ImageInfo(imageWidth, imageHeight, 8, hasAlpha); // 8 bits per channel, with alpha
        // open image for writing
        PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInfo, false);

        // add some optional metadata (chunks)
        pngWriter.GetMetadata().SetDpi(70.0);
        pngWriter.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now

        ImageLine iline = new ImageLine(imageInfo);

        for (int row = 0; row < imageHeight; row++)
        {
            var bottomRow = (imageHeight - 1) - row;
            for (int col = 0; col < imageWidth; col++)
            {
                var pixel = pixels[col + (bottomRow * imageWidth)];
                if (hasAlpha)
                {
                    ImageLineHelper.SetPixel(iline, col, pixel.r, pixel.g, pixel.b, pixel.a);
                }
                else
                {
                    ImageLineHelper.SetPixel(iline, col, pixel.r, pixel.g, pixel.b);
                }
            }
            pngWriter.WriteRow(iline, row);
        }
        pngWriter.End();
    }
Example #4
0
 public static void BuildBlankPngImageLineSegment(int pixPtr, int len, ImageLine iLine)
 {
     for (int xPtr = 0; xPtr < len; xPtr++)
     {
         ImageLineHelper.SetPixel(iLine, pixPtr++, 255, 255, 255);
     }
 }
Example #5
0
        public static void Create(string filename, int cols, int rows)
        {
            ImageInfo imi = new ImageInfo(cols, rows, 8, false); // 8 bits per channel, no alpha
            // open image for writing
            PngWriter png = FileHelper.CreatePngWriter(filename, imi, true);

            // add some optional metadata (chunks)
            png.GetMetadata().SetDpi(100.0);
            png.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now
            png.GetMetadata().SetText(PngChunkTextVar.KEY_Title, "Just a text image");
            PngChunk chunk = png.GetMetadata().SetText("my key", "my text .. bla bla");

            chunk.Priority = true; // this chunk will be written as soon as possible
            ImageLine iline = new ImageLine(imi);

            for (int col = 0; col < imi.Cols; col++)   // this line will be written to all rows
            {
                int r = 255;
                int g = 127;
                int b = 255 * col / imi.Cols;
                ImageLineHelper.SetPixel(iline, col, r, g, b);  // orange-ish gradient
            }
            for (int row = 0; row < png.ImgInfo.Rows; row++)
            {
                png.WriteRow(iline, row);
            }
            png.End();
        }
Example #6
0
        private void GenerateImage(string name, float[] data, int colors, int w, int h)
        {
            var imageInfo = new ImageInfo(w, h, 8, false);
            var png       = FileHelper.CreatePngWriter(Path.Combine(Helpers.TempDir, name), imageInfo, true);

            for (int y = 0; y < h; y++)
            {
                var line = new ImageLine(imageInfo);
                for (int x = 0; x < w; x++)
                {
                    if (colors == 1)
                    {
                        var r = (int)(255f * data[x + y * w]);
                        ImageLineHelper.SetPixel(line, x, r, r, r);
                    }
                    else
                    {
                        var r = (int)(255f * data[(x + y * w) * 3 + 0]);
                        var g = (int)(255f * data[(x + y * w) * 3 + 1]);
                        var b = (int)(255f * data[(x + y * w) * 3 + 2]);
                        ImageLineHelper.SetPixel(line, x, r, g, b);
                    }
                }
                png.WriteRow(line, y);
            }
            png.End();
        }
Example #7
0
        public void BuildPngImageLine(int lineNumber, ImageLine iLine)
        {
            DPoint c = new DPoint(0, _yVals[lineNumber]);

            for (int xPtr = 0; xPtr < CanvasSize.Width; xPtr++)
            {
                c.X = _xVals[xPtr];

                DPoint z              = new DPoint(0, 0);
                int    cnt            = 0;
                double escapeVelocity = _mPointWork.Iterate(c, z, ref cnt, done: out bool notUsed);

                int[] cComps;
                if (cnt == MapInfo.MaxIterations)
                {
                    cComps = ColorMap.HighColorEntry.StartColor.ColorComps;
                }
                else
                {
                    cComps = ColorMap.GetColor(cnt, escapeVelocity);
                }

                ImageLineHelper.SetPixel(iLine, xPtr, cComps[0], cComps[1], cComps[2]);
            }
        }
        static async Task FillLine
        (
            Texture2D texture,
            int[] samples,
            ImageInfo imageInfo,
            int row
        )
        {
            int  numCols   = imageInfo.Cols;
            int  numRows   = imageInfo.Rows;
            int  bitDepth  = imageInfo.BitDepth;
            bool alpha     = imageInfo.Alpha;
            bool greyscale = imageInfo.Greyscale;
            int  channels  = imageInfo.Channels;

            //fill line:
            Color[] pixels = texture.GetPixels(0, row, numCols, 1);
            if (greyscale == false)
            {
                if (alpha)
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        RGBA <int> rgba = ToRGBA(pixels[col], bitDepth);
                        ImageLineHelper.SetPixel(samples, rgba, col, channels);
                    }
                }
                else
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        RGB <int> rgb = ToRGB(pixels[col], bitDepth);
                        ImageLineHelper.SetPixel(samples, rgb, col, channels);
                    }
                }
            }
            else
            {
                if (alpha == false)
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        int R = ToInt(pixels[col].r, bitDepth);
                        ImageLineHelper.SetPixel(samples, R, col, channels);
                    }
                }
                else
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        int A = ToInt(pixels[col].a, bitDepth);
                        ImageLineHelper.SetPixel(samples, A, col, channels);
                    }
                }
            }

            await Task.CompletedTask;
        }
Example #9
0
        static async Task FillLine
        (
            Texture2D texture,
            ImageLine line,
            ImageInfo info,
            int row
        )
        {
            int  numCols   = info.Cols;
            int  numRows   = info.Rows;
            int  bitDepth  = info.BitDepth;
            bool alpha     = info.Alpha;
            bool greyscale = info.Greyscale;

            //fill line:
            Color[] pixels = texture.GetPixels(0, row, numCols, 1);
            if (greyscale == false)
            {
                if (alpha)
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        RGBA rgba = ToRGBA(pixels[col], bitDepth);
                        ImageLineHelper.SetPixel(line, col, rgba.r, rgba.g, rgba.b, rgba.a);
                    }
                }
                else
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        RGB rgb = ToRGB(pixels[col], bitDepth);
                        ImageLineHelper.SetPixel(line, col, rgb.r, rgb.g, rgb.b);
                    }
                }
            }
            else
            {
                if (alpha == false)
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        int r = ToInt(pixels[col].r, bitDepth);
                        ImageLineHelper.SetPixel(line, col, r);
                    }
                }
                else
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        int a = ToInt(pixels[col].a, bitDepth);
                        ImageLineHelper.SetPixel(line, col, a);
                    }
                }
            }

            await Task.CompletedTask;
        }
Example #10
0
        public void WriteLine(int[] pixelData)
        {
            ImageLine iLine = new ImageLine(imi);

            for (int ptr = 0; ptr < pixelData.Length; ptr++)
            {
                ImageLineHelper.SetPixelFromARGB8(iLine, ptr, pixelData[ptr]);
            }

            png.WriteRow(iLine, curRow++);
        }
Example #11
0
        public void ConvertTrueColor(BinaryReader reader, Stream outStream)
        {
            ImageInfo info = new ImageInfo(Header.Width, Header.Height, Header.BitDepth, Header.BitCount == 32);
            PngWriter png  = new PngWriter(outStream, info);

            // dataPerLine also known as ScanlineStride
            int dataPerLine = Header.Width * Header.Channels;
            // Calculation from https://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage
            int bytesPerLine    = ((Header.BitCount * Header.Width + 31) / 32) * 4;
            int padBytesPerLine = bytesPerLine - dataPerLine;


            long dataStart = Header.DataOffset;
            int  dataEnd   = Header.ImageSize;


            for (int y = 0; y < Header.Height; y++)
            {
                // Seek to the start of the line
                Stream.Seek(dataStart + (dataEnd - (bytesPerLine * y) - bytesPerLine), SeekOrigin.Begin);

                // build the row data - this going to be slow for big images sadly.
                // not too much we can do, we're going for safety, not performance.
                // we might be able to just pack the bytes in future.
                ImageLine pngLine = new ImageLine(info);

                for (int x = 0; x < Header.Width; x++)
                {
                    int b = reader.ReadByte();
                    int g = reader.ReadByte();
                    int r = reader.ReadByte();
                    int a = 255;
                    if (Header.BitCount == 32)
                    {
                        a = reader.ReadByte();
                    }

                    // having issues writing out the alpha component in the png
                    // ignoring it for now
                    ImageLineHelper.SetPixel(pngLine, x, r, g, b);
                }

                png.WriteRow(pngLine, y);
            }
            png.End();
        }
Example #12
0
        public void Write(RGBA rgba)
        {
            Debug.Assert(irow < pngw.ImgInfo.Rows);
            Debug.Assert(icol < pngw.ImgInfo.Cols);

            ImageLineHelper.SetPixel(iline, icol, rgba.r, rgba.g, rgba.b, rgba.a);
            icol++;

            if (icol != pngw.ImgInfo.Cols)
            {
                return;
            }

            icol = 0;
            pngw.WriteRow(iline, irow);
            irow++;
            iline = new ImageLine(pngw.ImgInfo);
        }
Example #13
0
        //private int[] GetOneLineFromCountsBlock(int[] counts, int lPtr)
        //{
        //	int[] result = new int[BlockWidth];

        //	Array.Copy(counts, lPtr * BlockWidth, result, 0, BlockWidth);
        //	return result;
        //}

        //private int[] GetOneLineFromCountsBlock(uint[] counts, int lPtr)
        //{
        //	int[] result = new int[BlockWidth];
        //	int srcPtr = lPtr * BlockWidth;

        //	for (int i = 0; i < result.Length; i++)
        //		result[i] = (int)counts[srcPtr++];

        //	return result;
        //}

        public static void BuildPngImageLineSegment(int pixPtr, int[] counts, ImageLine iLine, int maxIterations, ColorMap colorMap)
        {
            for (int xPtr = 0; xPtr < counts.Length; xPtr++)
            {
                double escapeVelocity = GetEscVel(counts[xPtr], out int cnt);

                int[] cComps;
                if (cnt == maxIterations)
                {
                    cComps = colorMap.HighColorEntry.StartColor.ColorComps;
                }
                else
                {
                    cComps = colorMap.GetColor(cnt, escapeVelocity);
                }

                ImageLineHelper.SetPixel(iLine, pixPtr++, cComps[0], cComps[1], cComps[2]);
            }
        }
Example #14
0
        public void Convert16BitImage(BinaryReader reader, Stream outStream)
        {
            // Force 8 bit images as PNG doesn't support 16bit iamges
            ImageInfo info = new ImageInfo(Header.Width, Header.Height, 8, false);
            PngWriter png  = new PngWriter(outStream, info);


            int bytesPerLine = ((Header.BitCount * Header.Width + 31) / 32) * 4;

            long dataStart = Header.DataOffset;
            int  dataEnd   = Header.ImageSize;

            // Masks from https://docs.microsoft.com/en-us/windows/desktop/directshow/working-with-16-bit-rgb
            // Assuming RGB555, until I deal with packed bits. I don't expect these to be common for our purpsoses though.
            var red_mask   = 0x7C00;
            var green_mask = 0x3E0;
            var blue_mask  = 0x1F;

            for (int y = 0; y < Header.Height; y++)
            {
                var offSet = (Header.Height - y - 1) * Header.Width;
                // Seek to the start of the line
                Stream.Seek(dataStart + (dataEnd - (bytesPerLine * y) - bytesPerLine), SeekOrigin.Begin);

                // build the row data - this going to be slow for big images sadly.
                // not too much we can do, we're going for safety, not performance.
                ImageLine pngLine = new ImageLine(info);

                for (int x = 0; x < Header.Width; x++)
                {
                    var value = reader.ReadInt16();

                    int r = ((value & red_mask) >> 10) << 3;
                    int g = ((value & green_mask) >> 5) << 3;
                    int b = ((value & blue_mask)) << 3;
                    ImageLineHelper.SetPixel(pngLine, x, r, g, b);
                }

                png.WriteRow(pngLine, y);
            }
            png.End();
        }
Example #15
0
        private static void additionalTestPalette(string orig, string truecolor)
        {
            // covnert to true color 8 bits and check equality
            PngReader    pngr  = FileHelper.CreatePngReader(orig);
            PngChunkPLTE plte  = pngr.GetMetadata().GetPLTE();
            PngChunkTRNS trns  = pngr.GetMetadata().GetTRNS();
            string       copy  = TestsHelper.addSuffixToName(orig, "_tccopy");
            bool         alpha = trns != null;
            ImageInfo    im2   = new ImageInfo(pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, 8, alpha);
            PngWriter    pngw  = FileHelper.CreatePngWriter(copy, im2, true);

            pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            int[] buf = null;
            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine line = pngr.ReadRowInt(row);
                buf = ImageLineHelper.Palette2rgb(line, plte, trns, buf);
                pngw.WriteRowInt(buf, row);
            }
            pngr.End();
            pngw.End();
            TestsHelper.testEqual(copy, truecolor);
            System.IO.File.Delete(copy);
        }
Example #16
0
        /// <summary>
        /// This method performs a preanalysis on the path to make sure there's no super high memory usage for a certain area
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="pathPosjes"></param>
        /// <param name="lineSavingProgress"></param>
        /// <param name="debugMessageCallback"></param>
        private void SaveMazeAsImageDeluxePngWithDynamicallyGeneratedPathWithAnalysis(string fileName, IEnumerable <MazePointPos> pathPosjes, Action <int, int> lineSavingProgress, Action <string> debugMessageCallback = null)
        {
            if (debugMessageCallback == null)
            {
                debugMessageCallback = (x) => { };
            }

            debugMessageCallback("Performing path analysis...");

            var  pathPointsPerRow = new int[this.Height];
            long totalPathLength  = 0;

            for (int i = 0; i < this.Height; i++)
            {
                pathPointsPerRow[i] = 0;
            }

            foreach (var pathPos in pathPosjes)
            {
                pathPointsPerRow[pathPos.Y]++;
                totalPathLength++;
            }

            debugMessageCallback(string.Format("Path analysis completed. Total path length: {0}, this would take up {1}mb.", totalPathLength, Math.Round(totalPathLength * 9.0 / 1024.0 / 1024.0, 2)));

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            var compinfo   = new Microsoft.VisualBasic.Devices.ComputerInfo();
            var memoryFree = compinfo.AvailablePhysicalMemory;

            debugMessageCallback(string.Format("Memory free: {0}mb", memoryFree / 1024 / 1024));
            memoryFree = (ulong)(memoryFree * 0.6);
            debugMessageCallback(string.Format("Setting max usage to 60% of this: {0}mb", memoryFree / 1024 / 1024));

            debugMessageCallback("Determining desired rows to generate each path cycle...");
            int rowsPerPathDeterminingCycle = FindTheMinimalRowsToWriteForPng(debugMessageCallback, pathPointsPerRow, memoryFree);



            int tiffTileSize = HybridInnerMap.GridSize;

            if (rowsPerPathDeterminingCycle < tiffTileSize)
            {
                debugMessageCallback(string.Format("We can't work with the default tilesize of '{0}' so we have to scale it back to RowsPerCycle: '{1}'", tiffTileSize, rowsPerPathDeterminingCycle));
                tiffTileSize = rowsPerPathDeterminingCycle;
            }

            debugMessageCallback(string.Format("TiffTileSize: {0}", tiffTileSize));

            debugMessageCallback("Starting generation of Maze Path and saving maze...");

            //Should actually be Width -1 -1 but since we use the full Width it's only once -1
            //This will count the amount of tiles per line so if it's 15 Pixels we still want 2 tiles of 8
            int tilesInWidth = (((this.Width - 1) / tiffTileSize) + 1);



            ImageInfo imi = new ImageInfo(this.Width - 1, this.Height - 1, 8, false); // 8 bits per channel, no alpha
            // open image for writing
            PngWriter png = CreatePngWriter(fileName, imi);

            // add some optional metadata (chunks)
            png.GetMetadata().SetDpi(100.0);
            png.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now
            png.CompLevel = 4;
            //png.GetMetadata().SetText(PngChunkTextVar.KEY_Title, "Just a text image");
            //PngChunk chunk = png.GetMetadata().SetText("my key", "my text .. bla bla");
            //chunk.Priority = true; // this chunk will be written as soon as possible



            //int stepsPerLoop = rowsPerPathDeterminingCycle;

            int partNumber = 0;

            int yChunkStart = 0;

            while (yChunkStart < this.Height - 1)
            {
                //We must use rowsperpathdeterminingcycle here instead of tifftilesize because else you might get into a scenario where the first 4 values and the second 4 values are beneath 1000. But if we would take value 2 to 6 which are also 4 values we would go above 1000.
                //And yes I thought about this pretty well, it needs to be like this because you get forced into reading 500 lines of path from for example 1000 to 1500 where the other thing is 2000, hmmmm...
                //Or not I really need to think about this a bit more. Because if the chunk size is 1000 then you can never end up reading something smaller then that which works because the rowsperpath is always bigger.
                //So yeah, because rows per path is always a multiple or equal to tifftilesize you can never go out of sync becuase no matter what happens, e.g. tifftile = 500 and perpath = 2000. When you're at 2500 you just need to read 500. And you are never forced in reading anything that was
                //not measured. Because you can't end up in having to read somewhere from 1250 to 1750 because of the multiple thingy. Ok I'm quite sure now it needs to be tiffTileSize.
                //
                //Additional note, it always needs to be a multiple of tiffTileSize because we write tiles at a time (we can't write half tiles). So that's why we don't want some stupidly small numbers here.
                int stepsThisLoop = FindTheMaxPathRowsThatWouldFitInMemoryFromHerePng(debugMessageCallback, pathPointsPerRow, yChunkStart, tiffTileSize, memoryFree);

                var yChunkEnd = Math.Min(yChunkStart + stepsThisLoop, this.Height - 1);
                stepsThisLoop = yChunkEnd - yChunkStart;

                var wObtainPathPart = Stopwatch.StartNew();

                //We don't use a ToList here because we do actually know the expected list size beforehand. This way we make sure we don't have to do any internal Array Resizing.
                var expectedPathCount   = pathPointsPerRow.Skip(yChunkStart).Take(yChunkEnd - yChunkStart).Sum();
                var pathPointsHere      = new List <MazePointPos>(expectedPathCount);
                int currentPathPosPoint = 0;
                foreach (var pathPos in pathPosjes.Where(t => t.Y >= yChunkStart && t.Y < yChunkEnd))
                {
                    pathPointsHere.Add(pathPos);
                    currentPathPosPoint++;
                }
                wObtainPathPart.Stop();

                if (pathPointsHere.Count != expectedPathCount)
                {
                    debugMessageCallback(string.Format("Warning: Something strange is happening where the actual path point count '{0}' is not equal to the expected path point count '{1}' (Maze will still save correctly but it uses more memory then expected)", pathPointsHere.Count, expectedPathCount));
                }

                var wSort = Stopwatch.StartNew();
                pathPointsHere.Sort((first, second) =>
                {
                    if (first.Y == second.Y)
                    {
                        return(first.X - second.X);
                    }
                    return(first.Y - second.Y);
                });
                wSort.Stop();



                var wGmemorifiedPieceOpMap = Stopwatch.StartNew();

                var innerMapTemporaryInMemoryCopy = new BitArreintjeFastInnerMap(this.Width, stepsThisLoop);



                for (int startY = yChunkStart; startY < yChunkEnd; startY += tiffTileSize)
                {
                    for (int startX = 0; startX < this.Width - 1; startX += tiffTileSize)
                    {
                        int yStart = startY - yChunkStart;
                        int yEnd   = yStart + tiffTileSize;

                        for (int y = startY, othery = yStart; othery < yEnd; y++, othery++)
                        {
                            for (int x = startX, otherx = 0; otherx < tiffTileSize; x++, otherx++)
                            {
                                innerMapTemporaryInMemoryCopy[x, othery] = innerMap[x, y];
                            }
                        }
                    }
                }



                wGmemorifiedPieceOpMap.Stop();



                int curpos = 0;

                var wSaveAsImage = Stopwatch.StartNew();

                var yChunkMaxRealEnzo = Math.Min(yChunkEnd, this.Height - 1);

                for (int startY = yChunkStart, y = 0; startY < yChunkMaxRealEnzo; startY += 1, y++)
                {
                    ImageLine iline = new ImageLine(imi);

                    //int xMax = Math.Min(this.Width - 1 - startX, tiffTileSize);
                    int yMax = Math.Min(this.Height - 1 - startY, tiffTileSize);
                    for (int x = 0, otherx = 0; otherx < this.Width - 1; x++, otherx++)
                    {
                        byte r = 0;
                        byte g = 0;
                        byte b = 0;

                        MazePointPos curPathPos;
                        if (curpos < pathPointsHere.Count)
                        {
                            curPathPos = pathPointsHere[curpos];
                            if (curPathPos.X == x && curPathPos.Y == startY)
                            {
                                r = curPathPos.RelativePos;
                                g = (byte)(255 - curPathPos.RelativePos);
                                b = 0;
                                curpos++;
                            }
                            else if (innerMapTemporaryInMemoryCopy[x, y])
                            {
                                r = 255;
                                g = 255;
                                b = 255;
                            }
                        }
                        else if (innerMapTemporaryInMemoryCopy[x, y])
                        {
                            r = 255;
                            g = 255;
                            b = 255;
                        }



                        ImageLineHelper.SetPixel(iline, x, r, g, b);
                    }



                    //var result = tif.WriteEncodedTile(tileNumber, color_ptr, tiffTileSize * tiffTileSize * 3);
                    //var result = tif.WriteTile(color_ptr, startX / tileSize, startY / tileSize, 0, 0);
                    //var result = tif.WriteRawTile(tileNumber, color_ptr, tileSize * tileSize * 3);
                    //Result should not be -1

                    //lineSavingProgress((int)Math.Min((tileNumber + 1L) * tiffTileSize / tilesInWidth, this.Height - 2), this.Height - 2);
                    png.WriteRow(iline, y + yChunkStart);
                    lineSavingProgress(y + yChunkStart, this.Height - 2);
                }



                wSaveAsImage.Stop();

                debugMessageCallback(string.Format("{0}: YChunkStart: {1}, YChunkEnd: {2}, Rows written: {3}, Count: {4}, Time to generate this part: {5} sec, Time to sort this part: {6} sec, Time to put this part in memory: {7}, Time to save this part in the image: {8} sec, Combined time: {9} sec, Size: {10}mb",
                                                   partNumber,
                                                   yChunkStart,
                                                   yChunkEnd,
                                                   stepsThisLoop,
                                                   pathPointsHere.Count,
                                                   Math.Round(wObtainPathPart.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wSort.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wGmemorifiedPieceOpMap.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wSaveAsImage.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wObtainPathPart.Elapsed.TotalSeconds + wSort.Elapsed.TotalSeconds + wGmemorifiedPieceOpMap.Elapsed.TotalSeconds + wSaveAsImage.Elapsed.TotalSeconds, 2),
                                                   Math.Round(pathPointsHere.Count * 9.0 / 1024.0 / 1024.0, 3)));
                partNumber++;

                yChunkStart += stepsThisLoop;

                //Do some forced garbage collection since we're finished with this loop
                pathPointsHere = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }

            png.End();

            //    tif.FlushData();
            //}
        }
        public static void Write
        (
            Color[] pixels,
            int width,
            int height,
            int bitDepth,
            bool alpha,
            bool greyscale,
            string filePath
        )
        {
            var imageInfo = new ImageInfo(
                width,
                height,
                bitDepth,
                alpha,
                greyscale,
                false                //not implemented here yet//bitDepth==4
                );

            // open image for writing:
            PngWriter writer = FileHelper.CreatePngWriter(filePath, imageInfo, true);

            // add some optional metadata (chunks)
            var meta = writer.GetMetadata();

            meta.SetTimeNow(0);              // 0 seconds fron now = now

            int numRows  = imageInfo.Rows;
            int numCols  = imageInfo.Cols;
            int channels = imageInfo.Channels;

            for (int row = 0; row < numRows; row++)
            {
                int[] ints = new int[imageInfo.SamplesPerRow];

                //fill line:
                if (greyscale == false)
                {
                    if (alpha)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGBA <int> rgba = ToRGBA(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(ints, rgba, col, channels);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGB <int> rgb = ToRGB(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(ints, rgb, col, channels);
                        }
                    }
                }
                else
                {
                    if (alpha == false)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int R = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].r, bitDepth);
                            ImageLineHelper.SetPixel(ints, R, col, channels);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int A = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].a, bitDepth);
                            ImageLineHelper.SetPixel(ints, A, col, channels);
                        }
                    }
                }

                //write line:
                ImageLine imageline = new ImageLine(imageInfo, ImageLine.ESampleType.INT, false, ints, null, row);
                writer.WriteRow(imageline, row);
            }
            writer.End();
        }
Example #18
0
        public static void Write
        (
            Color[] pixels,
            int width,
            int height,
            int bitDepth,
            bool alpha,
            bool greyscale,
            string filePath
        )
        {
            // convert pixels
            float max = GetBitDepthMaxValue(bitDepth);

            for (var i = 0; i < pixels.Length; i++)
            {
                pixels[i] = pixels[i] * max;
            }

            var info = new ImageInfo(
                width,
                height,
                bitDepth,
                alpha,
                greyscale,
                false//not implemented here yet//bitDepth==4
                );

            // open image for writing:
            PngWriter writer = FileHelper.CreatePngWriter(filePath, info, true);

            int       numRows   = info.Rows;
            int       numCols   = info.Cols;
            ImageLine imageline = new ImageLine(info);

            for (int row = 0; row < numRows; row++)
            {
                //fill line:
                if (greyscale == false)
                {
                    for (int col = 0; col < numCols; col++)
                    {
                        var rgba = pixels[IndexPngToTexture(row, col, numRows, numCols)];
                        ImageLineHelper.SetPixel(imageline, col, (int)rgba.r, (int)rgba.g, (int)rgba.b, (int)rgba.a);
                    }
                }
                else
                {
                    if (alpha == false)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int r = (int)pixels[IndexPngToTexture(row, col, numRows, numCols)].r;
                            ImageLineHelper.SetPixel(imageline, col, r);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int a = (int)pixels[IndexPngToTexture(row, col, numRows, numCols)].a;
                            ImageLineHelper.SetPixel(imageline, col, a);
                        }
                    }
                }

                //write line:
                writer.WriteRow(imageline, row);
            }
            writer.End();
        }
Example #19
0
        public IEnumerable <RGBA> EnRGBA()
        {
            PngChunkPLTE oplte = null;
            PngChunkTRNS otrns = null; // transparency metadata, can be null

            if (pngr.ImgInfo.Indexed)
            {
                oplte = pngr.GetMetadata().GetPLTE();
                otrns = pngr.GetMetadata().GetTRNS();
            }

            for (var row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                var line = pngr.ReadRowInt(row);
                if (pngr.ImgInfo.Indexed)
                {
                    var rgrgba = ImageLineHelper.Palette2rgb(line, oplte, otrns, null);
                    for (var irgba = 0; irgba < rgrgba.Length;)
                    {
                        yield return(new RGBA
                        {
                            r = rgrgba[irgba++],
                            g = rgrgba[irgba++],
                            b = rgrgba[irgba++],
                            a = (otrns != null ? rgrgba[irgba++] : 255),
                        });
                    }
                }
                else
                {
                    if (pngr.ImgInfo.Packed)
                    {
                        line = line.unpackToNewImageLine();
                    }
                    for (var col = 0; col < pngr.ImgInfo.Cols; col++)
                    {
                        switch (pngr.ImgInfo.Channels)
                        {
                        case 1:
                            yield return(new RGBA
                            {
                                r = Read8(col, line),
                                g = Read8(col, line),
                                b = Read8(col, line),
                            });

                            break;

                        case 2:
                            yield return(new RGBA
                            {
                                r = Read8(col * 2, line),
                                g = Read8(col * 2, line),
                                b = Read8(col * 2, line),
                                a = Read8(col * 2 + 1, line),
                            });

                            break;

                        case 3:
                            yield return(new RGBA
                            {
                                r = Read8(col * 3, line),
                                g = Read8(col * 3 + 1, line),
                                b = Read8(col * 3 + 2, line),
                            });

                            break;

                        case 4:
                            yield return(new RGBA
                            {
                                r = Read8(col * 4, line),
                                g = Read8(col * 4 + 1, line),
                                b = Read8(col * 4 + 2, line),
                                a = Read8(col * 4 + 3, line),
                            });

                            break;
                        }
                    }
                }
            }
        }
Example #20
0
        private void SaveMazeAsImageDeluxePngWithDynamicallyGeneratedPath(String fileName, IEnumerable <MazePointPos> pathPosjes, Action <int, int> lineSavingProgress)
        {
            ImageInfo imi = new ImageInfo(this.Width - 1, this.Height - 1, 8, false); // 8 bits per channel, no alpha
            // open image for writing
            PngWriter png = FileHelper.CreatePngWriter(fileName, imi, true);

            // add some optional metadata (chunks)
            png.GetMetadata().SetDpi(100.0);
            png.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now
            png.CompLevel = 4;
            //png.GetMetadata().SetText(PngChunkTextVar.KEY_Title, "Just a text image");
            //PngChunk chunk = png.GetMetadata().SetText("my key", "my text .. bla bla");
            //chunk.Priority = true; // this chunk will be written as soon as possible



            for (int yChunkStart = 0; yChunkStart < this.Height - 1; yChunkStart += Maze.LineChunks)
            {
                var yChunkEnd = Math.Min(yChunkStart + Maze.LineChunks, this.Height - 1);

                var pathPointsHere = pathPosjes.Where(t => t.Y >= yChunkStart && t.Y < yChunkEnd).ToList();
                pathPointsHere.Sort((first, second) =>
                {
                    if (first.Y == second.Y)
                    {
                        return(first.X - second.X);
                    }
                    return(first.Y - second.Y);
                });
                int curpos = 0;

                for (int y = yChunkStart; y < yChunkEnd; y++)
                {
                    ImageLine iline = new ImageLine(imi);

                    for (int x = 0; x < this.Width - 1; x++)
                    {
                        int r = 0;
                        int g = 0;
                        int b = 0;

                        MazePointPos curPathPos;
                        if (curpos < pathPointsHere.Count)
                        {
                            curPathPos = pathPointsHere[curpos];
                            if (curPathPos.X == x && curPathPos.Y == y)
                            {
                                r = curPathPos.RelativePos;
                                g = 255 - curPathPos.RelativePos;
                                b = 0;
                                curpos++;
                            }
                            else if (this.innerMap[x, y])
                            {
                                r = 255;
                                g = 255;
                                b = 255;
                            }
                        }
                        else if (this.innerMap[x, y])
                        {
                            r = 255;
                            g = 255;
                            b = 255;
                        }

                        ImageLineHelper.SetPixel(iline, x, r, g, b);
                    }
                    png.WriteRow(iline, y);
                    lineSavingProgress(y, this.Height - 2);
                }
            }
            png.End();
        }
Example #21
0
        static void Main(string[] args)
        {
            CASC.InitCasc(null, "S:\\World of Warcraft Public Test", "wowt");

            Console.WriteLine("CASC initialized for build " + CASC.cascHandler.Config.ActiveBuild);

            /*var reader = new DB6Reader(CASC.OpenFile("DBFilesClient\\Map.db2"));
             *
             * foreach (var row in reader)
             * {
             *  var map = row.Value.GetField<string>(1);
             *  Console.WriteLine(map);
             * }
             */

            var maps = new string[] { "Azeroth", "Kalimdor", "test", "ScottTest", "PVPZone01", "Shadowfang", "StormwindJail", "StormwindPrison", "DeadminesInstance", "PVPZone02", "Collin", "WailingCaverns", "Monastery", "RazorfenKraulInstance", "Blackfathom", "Uldaman", "GnomeragonInstance", "SunkenTemple", "RazorfenDowns", "EmeraldDream", "MonasteryInstances", "TanarisInstance", "BlackRockSpire", "BlackrockDepths", "OnyxiaLairInstance", "CavernsOfTime", "SchoolofNecromancy", "Zul'gurub", "Stratholme", "Mauradon", "DeeprunTram", "OrgrimmarInstance", "MoltenCore", "DireMaul", "AlliancePVPBarracks", "HordePVPBarracks", "development", "BlackwingLair", "PVPZone03", "AhnQiraj", "PVPZone04", "Expansion01", "AhnQirajTemple", "Karazahn", "Stratholme Raid", "HyjalPast", "HellfireMilitary", "HellfireDemon", "HellfireRampart", "HellfireRaid", "CoilfangPumping", "CoilfangMarsh", "CoilfangDraenei", "CoilfangRaid", "TempestKeepRaid", "TempestKeepArcane", "TempestKeepAtrium", "TempestKeepFactory", "AuchindounShadow", "AuchindounDemon", "AuchindounEthereal", "AuchindounDraenei", "PVPZone05", "HillsbradPast", "bladesedgearena", "BlackTemple", "GruulsLair", "NetherstormBG", "ZulAman", "Northrend", "PVPLordaeron", "ExteriorTest", "Valgarde70", "UtgardePinnacle", "Nexus70", "Nexus80", "SunwellPlateau", "Transport176244", "Transport176231", "Sunwell5ManFix", "Transport181645", "Transport177233", "Transport176310", "Transport175080", "Transport176495", "Transport164871", "Transport186238", "Transport20808", "Transport187038", "StratholmeCOT", "Transport187263", "CraigTest", "Sunwell5Man", "Ulduar70", "DrakTheronKeep", "Azjol_Uppercity", "Ulduar80", "UlduarRaid", "GunDrak", "development_nonweighted", "QA_DVD", "NorthrendBG", "DalaranPrison", "DeathKnightStart", "Transport_Tirisfal _Vengeance_Landing", "Transport_Menethil_Valgarde", "Transport_Orgrimmar_Warsong_Hold", "Transport_Stormwind_Valiance_Keep", "ChamberOfAspectsBlack", "NexusRaid", "DalaranArena", "OrgrimmarArena", "Azjol_LowerCity", "Transport_Moa'ki_Unu'pe", "Transport_Moa'ki_Kamagua", "Transport192241", "Transport192242", "WintergraspRaid", "unused", "IsleofConquest", "IcecrownCitadel", "IcecrownCitadel5Man", "AbyssalMaw", "Gilneas", "Transport_AllianceAirshipBG", "Transport_HordeAirshipBG", "AbyssalMaw_Interior", "Uldum", "BlackRockSpire_4_0", "Deephome", "Transport_Orgrimmar_to_Thunderbluff", "LostIsles", "ArgentTournamentRaid", "ArgentTournamentDungeon", "ElevatorSpawnTest", "Gilneas2", "GilneasPhase1", "GilneasPhase2", "SkywallDungeon", "QuarryofTears", "LostIslesPhase1", "Deephomeceiling", "LostIslesPhase2", "Transport197195", "HallsOfReflection", "BlackwingDescent", "GrimBatolDungeon", "GrimBatolRaid", "Transport197347", "Transport197348", "Transport197349-2", "Transport197349", "Transport197350", "Transport201834", "MountHyjalPhase1", "Firelands1", "Firelands2", "Stormwind", "ChamberofAspectsRed", "DeepholmeDungeon", "CataclysmCTF", "STV_Mine_BG", "TheBattleforGilneas", "MaelstromZone", "DesolaceBomb", "TolBarad", "AhnQirajTerrace", "TwilightHighlandsDragonmawPhase", "Transport200100", "Transport200101", "Transport200102", "Transport200103", "Transport203729", "Transport203730", "UldumPhaseOasis", "Transport 203732", "Transport203858", "Transport203859", "Transport203860", "RedgridgeOrcBomb", "RedridgeBridgePhaseOne", "RedridgeBridgePhaseTwo", "SkywallRaid", "UldumDungeon", "BaradinHold", "UldumPhasedEntrance", "TwilightHighlandsPhasedEntrance", "Gilneas_BG_2", "Transport 203861", "Transport 203862", "UldumPhaseWreckedCamp", "Transport203863", "Transport 2033864", "Transport 2033865", "Zul_Gurub5Man", "NewRaceStartZone", "FirelandsDailies", "HawaiiMainLand", "ScenarioAlcazIsland", "COTDragonblight", "COTWarOfTheAncients", "TheHourOfTwilight", "NexusLegendary", "ShadowpanHideout", "EastTemple", "StormstoutBrewery", "TheGreatWall", "DeathwingBack", "EyeoftheStorm2.0", "JadeForestAllianceHubPhase", "JadeForestBattlefieldPhase", "DarkmoonFaire", "TurtleShipPhase01", "TurtleShipPhase02", "MaelstromDeathwingFight", "TolVirArena", "MoguDungeon", "MoguInteriorRaid", "MoguExteriorRaid", "ValleyOfPower", "BFTAllianceScenario", "BFTHordeScenario", "ScarletSanctuaryArmoryAndLibrary", "ScarletMonasteryCathedralGY", "BrewmasterScenario01", "NewScholomance", "MogushanPalace", "MantidRaid", "MistsCTF3", "MantidDungeon", "MonkAreaScenario", "RuinsOfTheramore", "PandaFishingVillageScenario", "MoguRuinsScenario", "AncientMoguCryptScenario", "AncientMoguCyptDestroyedScenario", "ProvingGroundsScenario", "PetBattleJadeForest", "ValleyOfPowerScenario", "RingOfValorScenario", "BrewmasterScenario03", "BlackOxTempleScenario", "ScenarioKlaxxiIsland", "ScenarioBrewmaster04", "LevelDesignLand-DevOnly", "HordeBeachDailyArea", "AllianceBeachDailyArea", "MoguIslandDailyArea", "StormwindGunshipPandariaStartArea", "OrgrimmarGunshipPandariaStart", "TheramoreScenarioPhase", "JadeForestHordeStartingArea", "HordeAmbushScenario", "ThunderIslandRaid", "NavalBattleScenario", "DefenseOfTheAleHouseBG", "HordeBaseBeachScenario", "AllianceBaseBeachScenario", "ALittlePatienceScenario", "GoldRushBG", "JainaDalaranScenario", "WarlockArea", "BlackTempleScenario", "DarkmoonCarousel", "Draenor", "ThunderKingHordeHub", "ThunderIslandAllianceHub", "CitySiegeMoguIslandProgressionScenario", "LightningForgeMoguIslandProgressionScenario", "ShipyardMoguIslandProgressionScenario", "AllianceHubMoguIslandProgressionScenario", "HordeHubMoguIslandProgressionScenario", "FinalGateMoguIslandProgressionScenario", "MoguIslandEventsHordeBase", "MoguIslandEventsAllianceBase", "ShimmerRidgeScenario", "DarkHordeScenario", "Transport218599", "Transport218600", "ShadoPanArena", "MoguIslandLootRoom", "OrgrimmarRaid", "HeartOfTheOldGodScenario", "ProvingGrounds", "FWHordeGarrisonLevel1", "FWHordeGarrisonLevel2", "FWHordeGarrisonLevel3", "Stormgarde Keep", "HalfhillScenario", "SMVAllianceGarrisonLevel1", "SMVAllianceGarrisonLevel2", "SMVAllianceGarrisonLevel3", "CelestialChallenge", "SmallBattlegroundA", "ThePurgeOfGrommarScenario", "SmallBattlegroundB", "SmallBattlegroundC", "SmallBattlegroundD", "Transport_Siege_of_Orgrimmar_Alliance", "Transport_Siege_of_Orgrimmar_Horde", "OgreCompound", "MoonCultistHideout", "WarcraftHeroes", "PattyMackTestGarrisonBldgMap", "DraenorAuchindoun", "GORAllianceGarrisonLevel1", "GORAllianceGarrisonLevel2", "GORAllianceGarrisonLevel3", "BlastedLands", "Ashran", "Transport_Iron_Horde_Gorgrond_Train", "WarWharfSmackdown", "BonetownScenario", "FrostfireFinaleScenario", "BlackrockFoundryRaid", "TaladorIronHordeFinaleScenario", "BlackrockFoundryTrainDepot", "ArakkoaDungeon", "6HU_GARRISON_Blacksmithing_hub", "alliance_garrison_alchemy", "alliance_garrison_enchanting", "garrison_alliance_engineering", "garrison_alliance_farmhouse", "garrison_alliance_inscription", "garrison_alliance_jewelcrafting", "garrison_alliance_leatherworking", "Troll Raid", "garrison_alliance_mine_1", "garrison_alliance_mine_2", "garrison_alliance_mine_3", "garrison_alliance_stable_1", "garrison_alliance_stable_2", "garrison_alliance_stable_3", "garrison_alliance_tailoring", "HighmaulOgreRaid", "garrison_alliance_inn_1", "garrison_alliance_barn", "Transport227523", "GorHordeGarrisonLevel0", "GORHordeGarrisonLevel3", "TALAllianceGarrisonLevel0", "TALAllianceGarrisonLevel3", "TALHordeGarrisonLevel0", "TALHordeGarrisonLevel3", "SOAAllianceGarrison0", "SOAAllianceGarrison3", "SOAHordeGarrison0", "SOAHordeGarrison3", "NAGAllianceGarrisonLevel0", "NAGAllianceGarrisonLevel3", "NAGHordeGarrisonLevel0", "NAGHordeGarrisonLevel3", "garrison_alliance_armory1", "garrison_alliance_barracks1", "garrison_alliance_engineering1", "alliance_garrison_herb_garden1", "alliance_garrison_inn1", "garrison_alliance_lumbermill1", "alliance_garrison_magetower1", "garrison_alliance_pet_stable1", "garrison_alliance_salvageyard1", "garrison_alliance_storehouse1", "garrison_alliance_trading_post1", "garrison_alliance_tailoring1", "garrison_alliance_enchanting", "garrison_alliance_blacksmith1", "garrison_alliance_plot_small", "garrison_alliance_plot_medium", "garrison_alliance_plot_large", "Propland-DevOnly", "TanaanJungleIntro", "CircleofBloodScenario", "TerongorsConfrontation", "devland3", "nagrand_garrison_camp_stable_2", "DefenseOfKaraborScenario", "garrison_horde_barracks1", "ShaperDungeon", "TrollRaid2", "garrison_horde_alchemy1", "garrison_horde_armory1", "garrison_horde_barn1", "garrison_horde_blacksmith1", "garrison_horde_enchanting1", "garrison_horde_engineering1", "garrison_horde_inn1", "garrison_horde_inscription1", "garrison_horde_jewelcrafting1", "garrison_horde_leatherworking1", "garrison_horde_lumbermill1", "garrison_horde_magetower1", "garrison_horde_mine1", "garrison_alliance_petstabe", "garrison_horde_salvageyard1", "garrison_horde_sparringarena1", "garrison_horde_stable1", "garrison_horde_storehouse1", "garrison_horde_tailoring1", "garrison_horde_tradingpost1", "garrison_horde_workshop1", "garrison_alliance_workshop1", "garrison_horde_farm1", "garrison_horde_plot_large", "garrison_horde_plot_medium", "garrison_horde_plot_small", "TanaanJungleIntroForgePhase", "garrison_horde_fishing1", "garrison_alliance_fishing1", "Expansion5QAModelMap", "outdoorGarrisonArenaHorde", "outdoorGarrisonArenaAlliance", "outdoorGarrisonLumberMillAlliance", "outdoorGarrisonLumberMillHorde", "outdoorGarrisonArmoryHorde", "outdoorGarrisonArmoryAlliance", "outdoorGarrisonMageTowerHorde", "outdoorGarrisonMageTowerAlliance", "outdoorGarrisonStablesHorde", "outdoorGarrisonStablesAlliance", "outdoorGarrisonWorkshopHorde", "outdoorGarrisonWorkshopAlliance", "outdoorGarrisonInnHorde", "outdoorGarrisonInnAlliance", "outdoorGarrisonTradingPostHorde", "outdoorGarrisonTradingPostAlliance", "outdoorGarrisonConstructionPlotHorde", "outdoorGarrisonConstructionPlotAlliance", "GrommasharScenario", "FWHordeGarrisonLeve2new", "SMVAllianceGarrisonLevel2new", "garrison_horde_barracks2", "garrison_horde_armory2", "garrison_horde_barn2", "garrison_horde_inn2", "garrison_horde_lumbermill2", "garrison_horde_magetower2", "garrison_horde_petstable2", "garrison_horde_stable2", "garrison_horde_tradingpost2", "garrison_horde_workshop2", "garrison_horde_barracks3", "garrison_horde_armory3", "garrison_horde_barn3", "garrison_horde_inn3", "garrison_horde_magetower3", "garrison_horde_petstable3", "garrison_horde_stable3", "garrison_horde_tradingpost3", "garrison_horde_workshop3", "Garrison_Alliance_Large_Construction", "Garrison_Alliance_Medium_Construction", "Garrison_Horde_Large_Construction", "Garrison_Horde_Medium_Construction", "UpperBlackRockSpire", "garrisonAllianceMageTower2", "garrisonAllianceMageTower3", "garrison_horde_mine2", "garrison_horde_mine3", "garrison_alliance_workshop2", "garrison_alliance_workshop3", "garrison_alliance_lumbermill2", "garrison_alliance_lumbermill3", "Garrison_Horde_Small_Construction", "Garrison_Alliance_Small_Construction", "AuchindounQuest", "alliance_garrison_alchemy_rank2", "alliance_garrison_alchemy_rank3", "garrison_alliance_blacksmith2", "garrison_alliance_enchanting2", "garrison_alliance_engineering2", "garrison_alliance_inscription2", "garrison_alliance_inscription3", "garrison_alliance_jewelcrafting2", "garrison_alliance_jewelcrafting3", "garrison_alliance_leatherworking2", "garrison_alliance_leatherworking3", "garrison_alliance_tailoring2", "garrison_alliance_storehouse2", "garrison_alliance_storehouse3", "garrison_horde_storehouse2", "garrison_horde_storehouse3", "garrison_alliance_salvageyard2", "garrison_alliance_salvageyard3", "garrison_horde_lumbermill3", "garrison_alliance_pet_stable2", "garrison_alliance_pet_stable3", "garrison_alliance_trading_post2", "garrison_alliance_trading_post3", "garrison_alliance_barn2", "garrison_alliance_barn3", "garrison_alliance_inn_2", "garrison_alliance_inn_3", "GorgrondFinaleScenario", "garrison_alliance_barracks2", "garrison_alliance_barracks3", "garrison_alliance_armory2", "garrison_alliance_armory3", "GorgrondFinaleScenarioMap", "garrison_horde_sparringarena2", "garrison_horde_sparringarena3", "garrison_horde_alchemy2", "garrison_horde_alchemy3", "garrison_horde_blacksmith2", "garrison_horde_blacksmith3", "garrison_horde_enchanting2", "garrison_horde_enchanting3", "garrison_horde_inscription2", "garrison_horde_inscription3", "garrison_horde_leatherworking2", "garrison_horde_leatherworking3", "garrison_horde_jewelcrafting2", "garrison_horde_jewelcrafting3", "garrison_horde_tailoring2", "garrison_horde_tailoring3", "garrison_horde_salvageyard2", "garrison_horde_salvageyard3", "PattyMackTestGarrisonBldgMap2", "garrison_horde_engineering2", "garrison_horde_engineering3", "SparringArenaLevel3Stadium", "garrison_horde_fishing2", "garrison_horde_fishing3", "garrison_alliance_fishing2", "garrison_alliance_fishing3", "garrison_alliance_petstable1", "garrison_alliance_petstable2", "garrison_alliance_petstable3", "garrison_alliance_infirmary1", "garrison_alliance_infirmary2", "garrison_alliance_infirmary3", "outdoorGarrisonConstructionPlotAllianceLarge", "outdoorGarrisonConstructionPlotHordeLarge", "HellfireRaid62", "TanaanLegionTest", "ScourgeofNorthshire", "ArtifactAshbringerOrigin", "EdgeofRealityMount", "NagaDungeon", "FXlDesignLand-DevOnly", "7_DungeonExteriorNeltharionsLair", "Transport_The_Iron_Mountain", "BrokenShoreScenario", "AzsunaScenario", "IllidansRock", "HelhiemExteriorArea", "TanaanJungle", "TanaanJungleNoHubsPhase", "Emerald_Nightmare_ValSharah_exterior", "WardenPrison", "MaelstromShaman", "Legion Dungeon", "1466", "GarrisonAllianceShipyard", "GarrisonHordeShipyard", "TheMawofNashal", "Transport_The_Maw_of_Nashal", "Valhallas", "ValSharahTempleofEluneScenario", "WarriorArtifactArea", "DeathKnightArtifactArea", "legionnexus", "GarrisonShipyardAllianceSubmarine", "GarrisonShipyardAllianceDestroyer", "GarrisonShipyardTransport", "GarrisonShipyardDreadnaught", "GarrisonShipyardCarrier", "GarrisonShipyardHordeSubmarine", "GarrisonShipyardHordeDestroyer", "Artifact-PortalWorldAcqusition", "Helheim", "WardenPrisonDungeon", "AcquisitionVioletHold", "AcquisitionWarriorProt", "GarrisonShipyardCarrierAlliance", "GarrisonShipyardGalleonHorde", "AcquisitionHavoc", "Artifact-Warrior Fury Acquisition", "ArtifactPaladinRetAcquisition", "BlackRookHoldDungeon", "DalaranUnderbelly", "ArtifactShamanElementalAcquisition", "BlackrookHoldArena", "NagrandArena2", "BloodtotemCavernFelPhase", "BloodtotemCavernTaurenPhase", "Artifact-WarriorFuryAcquisition", "Artifact-PriestHunterOrderHall", "Artifact-MageOrderHall", "Artifact-MonkOrderHall", "HulnHighmountain", "SuramarCatacombsDungeon", "StormheimPrescenarioWindrunner", "StormheimPrescenarioSkyfire", "ArtifactsDemonHunterOrderHall", "NightmareRaid", "ArtifactWarlockOrderHallScenario", "MardumScenario", "Artifact-WhiteTigerTempleAcquisition", "HighMountain", "Artifact-SkywallAcquisition", "KarazhanScenario", "SuramarRaid", "HighMountainMesa", "Artifact-KarazhanAcquisition", "Artifact-DefenseofMoongladeScenario", "DefenseofMoongladeScenario", "UrsocsLairScenario", "BoostExperience", "Karazhan Scenario", "Artifact-AcquisitionArmsHolyShadow", "Artifact-Dreamway", "Artifact-TerraceofEndlessSpringAcquisition", "LegionVioletHoldDungeon", "Artifact-Acquisition-CombatResto", "Artifacts-CombatAcquisitionShip", "TechTestSeamlessWorldTransitionA", "TechTestSeamlessWorldTransitionB", "ValsharahArena", "Artifact-Acquisition-Underlight", "BoostExperience2", "TransportBoostExperienceAllianceGunship", "TransportBoostExperienceHordeGunship", "BoostExperience2Horde", "TransportBoostExperienceHordeGunship2", "TransportBoostExperienceAllianceGunship2", "TechTestCosmeticParentPerformance", "SuramarCityDungeon", "MaelstromShamanHubIntroScenario", "UdluarScenario", "MaelstromTitanScenario", "Artifact�DalaranVaultAcquisition", "Artifact-DalaranVaultAcquisition", "JulienTestLand-DevOnly", "AssualtOnStormwind", "DevMapA", "DevMapB", "DevMapC", "DevMapD", "DevMapE", "DevMapF", "DevMapG", "ArtifactRestoAcqusition", "ArtifactThroneoftheTides", "SkywallDungeon_OrderHall", "AbyssalMaw_Interior_Scenario", "Artifact-PortalWorldNaskora", "FirelandsArtifact", "ArtifactAcquisitionSubtlety", "Hyjal Instance", "AcquisitionTempleofstorms", "Artifact-SerenityLegionScenario", "DeathKnightCampaign-LightsHopeChapel", "TheRuinsofFalanaar", "Faronaar", "DeathKnightCampaign-Undercity", "DeathKnightCampaign-ScarletMonastery", "ArtifactStormwind", "BlackTemple-Legion", "IllidanTemp", "MageCampaign-TheOculus", "BattleofExodar", "TrialoftheSerpent", "TheCollapseSuramarScenario", "FelHammerDHScenario", "Transport251513", "NetherlightTemplePrison", "TolBarad1", "TheArcwaySuramarScenario", "TransportAllianceShipPhaseableMO", "TransportHordeShipPhaseableMO", "TransportKvaldirShipPhaseableMO", "BlackRookSenario", "VoljinsFuneralPyre", "Helhiem2", "Transport254124", "Acherus", "Karazahn1", "LightsHeart", "BladesEdgeArena2", "EnvironmentLandDevOnly", "SuramarEndScenario", "DungeonBlockout", "BrokenShoreIntro", "LegionShipVertical", "LegionShipHorizontal", "BrokenshorePristine", "BrokenShorePrepatch", "bladesedgearena2b", "EyeofEternityScenario", "TombofSargerasRaid", "TombofSargerasDeungeon", "ABWinter", "ArtifactsDemonHunterOrderHallPhase", "ArtifactGnomeregan", "dreadscarriftwarlockplatform", "WailingCavernsPetBattle", "DeadminesPetBattle", "EyeofEternityMageClassMount", "CookingImpossible", "PitofSaronDeathKnight", "MardumScenarioClientScene", "GnomereganPetBattle", "BrokenShoreBattleshipFinale", "LegionCommandCenter", "LegionSpiderCave", "ArtifactAcquisitionTank", "LegionFelCave", "LegionFelFirenovaArea", "LegionBarracks", "ArtifactHighmountainDualBoss", "HallsofValorScenario", "LegionShipHorizontalValsharah", "LegionShipHorizontalAzsuna", "LegionShipHorizontalHighMountain", "LegionShipHorizontalStormheim", "StratholmePaladinClassMount", "BlackRookHoldArtifactChallenge", "SouthseaPirateShip715BoatHoliday", "hearthstonetavern", "HallsOfValorWarriorClassMount", "BlackrockMountainBrawl", "brokenshorewardentower", "warlockmountscenario", "ColdridgeValley", "HallsofValorHunterScenario", "EyeofEternityMageClassMountShort", "ShrineofAvianaDefenseScenario", "DruidMountFinaleScenario", "FelwingLedgeDemonHunterClassMount", "ThroneoftheFourWindsShamanClassMounts", "DKMountScenario", "RubySanctumDKMountScenario", "AkazamarakHatScenario", "LostGlacierDKMountScenario" };

            //var maps = new string[] { "ABWinter" };
            foreach (var map in maps)
            {
                var mapname = map;

                var hasMinimaps = false;

                var min_x = 64;
                var min_y = 64;

                var max_x = 0;
                var max_y = 0;

                Console.WriteLine("[" + mapname + "] Loading tiles..");

                var bmpDict = new Dictionary <string, Bitmap>();

                for (int cur_x = 0; cur_x < 64; cur_x++)
                {
                    for (int cur_y = 0; cur_y < 64; cur_y++)
                    {
                        var tilename = "World\\Minimaps\\" + mapname + "\\map" + cur_x + "_" + cur_y + ".blp";

                        if (CASC.cascHandler.FileExists(tilename))
                        {
                            hasMinimaps = true;

                            if (cur_x > max_x)
                            {
                                max_x = cur_x;
                            }
                            if (cur_y > max_y)
                            {
                                max_y = cur_y;
                            }

                            if (cur_x < min_x)
                            {
                                min_x = cur_x;
                            }
                            if (cur_y < min_y)
                            {
                                min_y = cur_y;
                            }

                            using (var blp = new BlpFile(CASC.cascHandler.OpenFile(tilename)))
                            {
                                bmpDict.Add(cur_x + "_" + cur_y, blp.GetBitmap(0));
                            }
                        }
                    }
                }

                if (hasMinimaps == false)
                {
                    Console.WriteLine("[" + mapname + "] " + "Skipping map, has no minimap tiles");
                    continue;
                }

                Console.WriteLine("[" + mapname + "] MIN: (" + min_x + " " + min_y + ") MAX: (" + max_x + " " + max_y + ")");

                var res_x = (((max_x - min_x) * 256) + 256);
                var res_y = (((max_y - min_y) * 256) + 256);

                if (res_x < 0 || res_y < 0)
                {
                    Console.WriteLine("Invalid resolution!");
                }

                Console.WriteLine("[" + mapname + "] " + "Image will be " + res_x + "x" + res_y);


                ImageInfo imi = new ImageInfo(res_x, res_y, 8, true);
                PngWriter png = FileHelper.CreatePngWriter("maps/" + mapname + ".png", imi, true);

                for (int row = 0; row < png.ImgInfo.Rows; row++)
                {
                    var blp_y       = min_y + (row / 256);
                    var blp_pixel_y = row - ((blp_y - min_y) * 256);

                    ImageLine iline = new ImageLine(imi);
                    for (int col = 0; col < imi.Cols; col++)
                    {
                        var blp_x       = min_x + (col / 256);
                        var blp_pixel_x = col - ((blp_x - min_x) * 256);

                        if (bmpDict.ContainsKey(blp_x + "_" + blp_y))
                        {
                            var pixel = bmpDict[blp_x + "_" + blp_y].GetPixel(blp_pixel_x, blp_pixel_y);
                            ImageLineHelper.SetPixel(iline, col, pixel.R, pixel.G, pixel.B, pixel.A);
                        }
                        else
                        {
                            ImageLineHelper.SetPixel(iline, col, 0x00, 0x00, 0x00, 0x00);
                        }
                    }
                    png.WriteRow(iline, row);
                    if (row % (png.ImgInfo.Rows / 100) == 0)
                    {
                        Console.Write("\r[" + mapname + "] Writing image: " + Math.Round((double)(100 * row) / png.ImgInfo.Rows) + "%");
                    }
                }

                png.End();
                GC.Collect();

                Console.WriteLine("\n[" + mapname + "] Done");
            }
            Console.ReadLine();
        }
Example #22
0
        /// <summary>
        /// Saves the maze with a specified path as PNG
        /// </summary>
        /// <param name="fileName">The filename of the file</param>
        /// <param name="pathPosjes">The path (can be generated by calling PathFinderDepthFirst.GoFind)</param>
        /// <param name="lineSavingProgress">An action that will be called to obtain the status of the saving.</param>
        public void SaveMazeAsImageDeluxe(String fileName, List <MazePointPos> pathPosjes, Action <int, int> lineSavingProgress)
        {
            //pathPosjes = pathPosjes.OrderBy(t => t.Y).ThenBy(t => t.X).ToArray();


            pathPosjes.Sort((first, second) =>
            {
                if (first.Y == second.Y)
                {
                    return(first.X - second.X);
                }
                return(first.Y - second.Y);
            });



            ImageInfo imi = new ImageInfo(this.Width - 1, this.Height - 1, 8, false); // 8 bits per channel, no alpha
            // open image for writing
            PngWriter png = FileHelper.CreatePngWriter(fileName, imi, true);

            // add some optional metadata (chunks)
            png.GetMetadata().SetDpi(100.0);
            png.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now
            png.CompLevel = 4;
            //png.GetMetadata().SetText(PngChunkTextVar.KEY_Title, "Just a text image");
            //PngChunk chunk = png.GetMetadata().SetText("my key", "my text .. bla bla");
            //chunk.Priority = true; // this chunk will be written as soon as possible


            int curpos = 0;

            for (int y = 0; y < this.Height - 1; y++)
            {
                ImageLine iline = new ImageLine(imi);

                for (int x = 0; x < this.Width - 1; x++)
                {
                    int r = 0;
                    int g = 0;
                    int b = 0;

                    MazePointPos curPathPos;
                    if (curpos < pathPosjes.Count)
                    {
                        curPathPos = pathPosjes[curpos];
                        if (curPathPos.X == x && curPathPos.Y == y)
                        {
                            r = curPathPos.RelativePos;
                            g = 255 - curPathPos.RelativePos;
                            b = 0;
                            curpos++;
                        }
                        else if (this.innerMap[x, y])
                        {
                            r = 255;
                            g = 255;
                            b = 255;
                        }
                    }
                    else if (this.innerMap[x, y])
                    {
                        r = 255;
                        g = 255;
                        b = 255;
                    }

                    ImageLineHelper.SetPixel(iline, x, r, g, b);
                }
                png.WriteRow(iline, y);
                lineSavingProgress(y, this.Height - 2);
            }
            png.End();
        }
Example #23
0
        public static void Write
        (
            Color[] pixels,
            int width,
            int height,
            int bitDepth,
            bool alpha,
            bool greyscale,
            string filePath
        )
        {
            var info = new ImageInfo(
                width,
                height,
                bitDepth,
                alpha,
                greyscale,
                false//not implemented here yet//bitDepth==4
                );

            // open image for writing:
            PngWriter writer = FileHelper.CreatePngWriter(filePath, info, true);
            // add some optional metadata (chunks)
            var meta = writer.GetMetadata();

            int       numRows   = info.Rows;
            int       numCols   = info.Cols;
            ImageLine imageline = new ImageLine(info);

            for (int row = 0; row < numRows; row++)
            {
                //fill line:
                if (greyscale == false)
                {
                    if (alpha)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGBA rgba = ToRGBA(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, rgba.r, rgba.g, rgba.b, rgba.a);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            RGB rgb = ToRGB(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, rgb.r, rgb.g, rgb.b);
                        }
                    }
                }
                else
                {
                    if (alpha == false)
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int r = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].r, bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, r);
                        }
                    }
                    else
                    {
                        for (int col = 0; col < numCols; col++)
                        {
                            int a = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].a, bitDepth);
                            ImageLineHelper.SetPixel(imageline, col, a);
                        }
                    }
                }

                //write line:
                writer.WriteRow(imageline, row);
            }
            writer.End();
        }