Beispiel #1
0
        public void DoPreview(string selectedFilePath)
        {
            //  Load the icons.
            try
            {
                Logging.Log("Displaying preview 1");
                using (var stream = File.OpenRead(selectedFilePath))
                    using (var blpFile = new BlpFile(stream))
                    {
                        Logging.Log("Displaying preview 2");
                        OriginalImage     = blpFile.GetBitmap(0);
                        pictureBox1.Image = OriginalImage;
                        label1.Text       = string.Format("Size: {0}x{1} Compression: {2}", OriginalImage.Width, OriginalImage.Height, blpFile.Compression);
                        Logging.Log("Displaying preview 3");
                    }

                /*
                 * using (var image = Blp2.FromFile(selectedFilePath))
                 * {
                 *  Logging.Log("Displaying preview 2");
                 *  OriginalImage = (Bitmap)image;
                 *  pictureBox1.Image = OriginalImage;
                 *  label1.Text = string.Format("Size: {0}x{1} Compression: {2}", OriginalImage.Width, OriginalImage.Height, image.Format);
                 *  Logging.Log("Displaying preview 3");
                 * }*/
            }
            catch (Exception ex)
            {
                //  Maybe we could show something to the user in the preview
                //  window, but for now we'll just ignore any exceptions.
                label1.Text = "Error: " + ex.Message;
                Logging.Error(ex.Message);
            }
        }
 public void LoadBLP(string filename)
 {
     using (var blp = new BlpFile(CASC.OpenFile(filename)))
     {
         bmp = blp.GetBitmap(0);
     }
 }
Beispiel #3
0
        public void TestGetBlpBitmap(string inputImagePath, string expectedImagePath, int mipMapLevel)
        {
            using (var fileStream = File.OpenRead(inputImagePath))
            {
                var expectedImage = new Bitmap(expectedImagePath);
                var blpFile       = new BlpFile(fileStream);
                var actualImage   = blpFile.GetBitmap(mipMapLevel);

                Assert.AreEqual(expectedImage.Width, actualImage.Width);
                Assert.AreEqual(expectedImage.Height, actualImage.Height);

                for (var y = 0; y < expectedImage.Height; y++)
                {
                    for (var x = 0; x < expectedImage.Width; x++)
                    {
                        // Allow pixel values to be slightly different, since some testcases were decoded with WPF (BitmapSource), not SkiaSharp.
                        const int delta = 1;

                        var expectedPixel = expectedImage.GetPixel(x, y);
                        var actualPixel   = actualImage.GetPixel(x, y);

                        var message = $"Expected:<{expectedPixel}>. Actual:<{actualPixel}>";

                        Assert.IsTrue(Math.Abs(expectedPixel.A - actualPixel.A) <= delta, message);
                        Assert.IsTrue(Math.Abs(expectedPixel.R - actualPixel.R) <= delta, message);
                        Assert.IsTrue(Math.Abs(expectedPixel.G - actualPixel.G) <= delta, message);
                        Assert.IsTrue(Math.Abs(expectedPixel.B - actualPixel.B) <= delta, message);
                    }
                }

                expectedImage.Dispose();
                blpFile.Dispose();
            }
        }
Beispiel #4
0
        private void OpenClick(object sender, EventArgs e)
        {
            try
            {
                var dlg = openFileDialog.ShowDialog();
                if (dlg != DialogResult.OK)
                {
                    return;
                }

                var file = openFileDialog.OpenFile();

                using (var blp = new BlpFile(file))
                {
                    bmp = blp.GetBitmap(0);
                }

                var graphics = panel1.CreateGraphics();
                graphics.Clear(panel1.BackColor);
                graphics.DrawImage(bmp, 0, 0);

                button3.Enabled = true;
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("The 'example.blp' was not found!");
            }
        }
 public void LoadBLP(Stream file)
 {
     using (var blp = new BlpFile(file))
     {
         bmp = blp.GetBitmap(0);
     }
 }
Beispiel #6
0
        public static Texture LoadBlpTexture(
            GraphicsDevice graphicsDevice,
            ResourceFactory resourceFactory,
            Stream stream,
            Veldrid.PixelFormat pixelFormat = Veldrid.PixelFormat.B8_G8_R8_A8_UNorm)
        {
            using var blpFile = new BlpFile(stream);

            var width  = (uint)blpFile.Width;
            var height = (uint)blpFile.Height;

            var mipMapCount = (uint)blpFile.MipMapCount;

            var sampledTexture = resourceFactory.CreateTexture(TextureDescription.Texture2D(width, height, mipMapCount, 1, pixelFormat, TextureUsage.Sampled));
            var stagingTexture = resourceFactory.CreateTexture(TextureDescription.Texture2D(width, height, mipMapCount, 1, pixelFormat, TextureUsage.Staging));

            var mipMapWidths  = new uint[mipMapCount];
            var mipMapHeights = new uint[mipMapCount];

            for (var mipMapLevel = 0; mipMapLevel < mipMapCount; mipMapLevel++)
            {
                var pixelData    = blpFile.GetPixels(mipMapLevel, out var w, out var h);
                var mipMapWidth  = (uint)w;
                var mipMapHeight = (uint)h;

                mipMapWidths[mipMapLevel]  = mipMapWidth;
                mipMapHeights[mipMapLevel] = mipMapHeight;
                graphicsDevice.UpdateTexture(stagingTexture, pixelData, 0, 0, 0, mipMapWidth, mipMapHeight, 1, (uint)mipMapLevel, 0);
            }

            CreateCommandList(graphicsDevice, resourceFactory, stagingTexture, sampledTexture);

            return(sampledTexture);
        }
Beispiel #7
0
        public Control Show(Stream stream, string fileName)
        {
            m_fileName = fileName;
            m_mips.Clear();
            try
            {
                using (var blp = new BlpFile(stream))
                {
                    for (int i = 0; i < blp.MipMapCount; ++i)
                    {
                        var bmp = blp.GetBitmap(i);
                        if (bmp.Width > 0 && bmp.Height > 0)
                        {
                            m_mips.Add(bmp);
                        }
                    }
                }
            }
            catch// (System.Exception ex)
            {
                //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            cbMipIndex.Items.Clear();
            cbMipIndex.Items.AddRange(Enumerable.Range(0, m_mips.Count).Select(m => m.ToString()).ToArray());
            if (cbMipIndex.Items.Count > 0)
            {
                cbMipIndex.SelectedIndex = 0;
            }
            return(this);
        }
        static void Draw(dynamic map, WDT.WDTFileDataId chunk, ref NetVips.Image canvas, int positionX, int positionY)
        {
            Stream chunkStream = null;

            try
            {
                var casc = new CASC();
                chunkStream = casc.File(BuildConfig, chunk.fileDataId);
            }
            catch
            {
                Console.WriteLine($"Failed to download chunk {chunk.x}_{chunk.y} for map {map.MapName_lang} ({map.ID})");
                return;
            }

            var blpStream = new MemoryStream();
            var blpFile   = new BlpFile(chunkStream);

            var bitmap = blpFile.GetBitmap(0);

            bitmap.Save(blpStream, System.Drawing.Imaging.ImageFormat.Png);

            var image = NetVips.Image.NewFromBuffer(blpStream.ToArray(), access: Enums.Access.Sequential);

            canvas = canvas.Insert(image, positionX * bitmap.Width, positionY * bitmap.Height, true);

            blpStream.Dispose();
            blpFile.Dispose();
            bitmap.Dispose();
            image.Dispose();;
        }
Beispiel #9
0
        public static int LoadTexture(uint filedataid, CacheStorage cache)
        {
            GL.ActiveTexture(TextureUnit.Texture0);

            if (cache.materials.ContainsKey(filedataid))
            {
                return(cache.materials[filedataid]);
            }

            int textureId = GL.GenTexture();

            using (var blp = new BlpFile(CASC.OpenFile(filedataid)))
            {
                var bmp = blp.GetBitmap(0);

                if (bmp == null)
                {
                    throw new Exception("BMP is null!");
                }

                GL.BindTexture(TextureTarget.Texture2D, textureId);
                cache.materials.Add(filedataid, textureId);
                var bmp_data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                bmp.UnlockBits(bmp_data);
            }

            return(textureId);
        }
Beispiel #10
0
 public void LoadBLP(Stream filename)
 {
     var blp = new BlpFile(filename);
     {
         bmp = blp.GetBitmap(0);
     }
 }
 public void LoadBLP(uint fileDataID)
 {
     using (var blp = new BlpFile(CASC.OpenFile(fileDataID)))
     {
         bmp = blp.GetBitmap(0);
     }
 }
Beispiel #12
0
        public override void Work()
        {
            bool success = false;

            try
            {
                foreach (string path in paths)
                {
                    string newFile = Path.Combine(dest, Path.GetFileNameWithoutExtension(path) + ".png");
                    Log.Write("Exporting {0} -> {1}", path, newFile);

                    using (BlpFile blp = new BlpFile(File.OpenRead(path)))
                    {
                        Bitmap bmp = blp.GetBitmap(0);
                        bmp.Save(newFile, ImageFormat.Png);
                        bmp.Dispose();
                    }
                }
                success = true;
            }
            catch (Exception e)
            {
                // We have failed, the elders will be disappointed.
                Log.Write("BLP to PNG export failed: {0}.", e.Message);
            }

            EventManager.Trigger_ExportBLPtoPNGComplete(success);
        }
Beispiel #13
0
    /// <summary>
    /// Create a Texture2D in memory from a BLP image file
    /// </summary>
    /// <param name="file"></param>
    public Texture2D BlpToTexture2d(CASCFile file)
    {
        Texture2D blpTex = null;

        using (var blp = new BlpFile(new MemoryStream(CascFileBytes(file)))) {
            blpTex = blp.GetTexture2d(0); // getting mipmap 0, TODO: get all mipmaps
        }
        return(blpTex);
    }
Beispiel #14
0
        private void PreviewBlp(string fullName)
        {
            var stream = cascHandler.OpenFile(fullName, LocaleFlags.All);
            var blp    = new BlpFile(stream);
            var bitmap = blp.GetBitmap(0);
            var form   = new ImagePreviewForm(bitmap);

            form.Show();
        }
Beispiel #15
0
 private void PreviewBlp(CASCFile file)
 {
     using (var stream = _casc.OpenFile(file.Hash))
     {
         var blp    = new BlpFile(stream);
         var bitmap = blp.GetBitmap(0);
         var form   = new ImagePreviewForm(bitmap);
         form.Show();
     }
 }
Beispiel #16
0
 public void LoadBLP(string filename)
 {
     using (FileStream reader = File.OpenRead(filename))
     {
         var blp = new BlpFile(reader);
         {
             bmp = blp.GetBitmap(0);
         }
         reader.Close();
     }
 }
Beispiel #17
0
        public static void Run([BlobTrigger("wow/{name}.blp")] Stream input, string name, [Blob("wow/{name}.png", FileAccess.Write)] Stream output, ILogger log)
        {
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {input.Length} Bytes");

            using (var blp = new BlpFile(input))
                using (var image = blp.GetImage(0))
                    using (var file = new MemoryStream())
                    {
                        image.SaveAsPng(output);
                    }
        }
Beispiel #18
0
        private static void ExportExtraMaterials(uint tex, WoWFormatLib.Structs.WMO.WMO wmo, List <Structs.Material> mats, int matIdx, string path)
        {
            Stream ms = null;

            if (CASC.FileExists(tex))
            {
                var mat = new Structs.Material();
                if (wmo.textures == null)
                {
                    if (Listfile.TryGetFilename(tex, out var textureFilename))
                    {
                        mat.filename = Path.GetFileNameWithoutExtension(textureFilename).Replace(" ", "");
                    }
                    else
                    {
                        mat.filename = tex.ToString();
                    }

                    ms = CASC.OpenFile(tex);
                }
                else
                {
                    for (var ti = 0; ti < wmo.textures.Count(); ti++)
                    {
                        if (wmo.textures[ti].startOffset == tex)
                        {
                            mat.filename = Path.GetFileNameWithoutExtension(wmo.textures[ti].filename).Replace(" ", "");
                            ms           = CASC.OpenFile(wmo.textures[ti].filename);
                        }
                    }
                }

                if (ms == null)
                {
                    return; // Can this even happen?
                }
                string saveLocation = Path.Combine(path, mat.filename + ".png");
                if (!File.Exists(saveLocation))
                {
                    try
                    {
                        using (BlpFile blp = new BlpFile(ms))
                            blp.GetBitmap(0).Save(saveLocation);
                    }
                    catch (Exception e)
                    {
                        CASCLib.Logger.WriteLine("Exception while saving BLP " + mat.filename + ": " + e.Message);
                    }
                }

                mats.Add(mat);
            }
        }
Beispiel #19
0
        public void UpdateMainWindowIcons(double margin)
        {
            // adapter.query below caused unhandled exception with main.selectedID as 0.
            if (adapter == null || main.selectedID == 0)
            {
                return;
            }

            // Convert to background worker here

            DataRow res           = adapter.Query(string.Format("SELECT `SpellIconID`,`ActiveIconID` FROM `{0}` WHERE `ID` = '{1}'", "spell", main.selectedID)).Rows[0];
            uint    iconInt       = uint.Parse(res[0].ToString());
            uint    iconActiveInt = uint.Parse(res[1].ToString());

            // Update currently selected icon, we don't currently use ActiveIconID
            using (FileStream fileStream = new FileStream(GetIconPath(iconInt) + ".blp", FileMode.Open))
            {
                using (BlpFile image = new BlpFile(fileStream))
                {
                    using (var bit = image.getBitmap(0))
                    {
                        System.Windows.Controls.Image temp = new System.Windows.Controls.Image();

                        temp.Width               = iconSize == null ? 32 : iconSize.Value;
                        temp.Height              = iconSize == null ? 32 : iconSize.Value;
                        temp.Margin              = iconMargin == null ? new Thickness(margin, 0, 0, 0) : iconMargin.Value;
                        temp.VerticalAlignment   = VerticalAlignment.Top;
                        temp.HorizontalAlignment = HorizontalAlignment.Left;
                        temp.Source              = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                            bit.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
                            BitmapSizeOptions.FromWidthAndHeight(bit.Width, bit.Height));
                        temp.Name = "CurrentSpellIcon";

                        // Code smells here on hacky positioning and updating the icon
                        temp.Margin = new Thickness(103, 38, 0, 0);
                        main.CurrentIconGrid.Children.Clear();
                        main.CurrentIconGrid.Children.Add(temp);
                    }
                }
            }

            // Load all icons available if have not already
            if (!loadedAllIcons)
            {
                var watch = new Stopwatch();
                watch.Start();
                LoadAllIcons(margin);
                watch.Stop();
                Console.WriteLine($"Loaded all icons as UI elements in {watch.ElapsedMilliseconds}ms");
            }
        }
Beispiel #20
0
        public void LoadAllIcons(double margin)
        {
            loadedAllIcons = true;
            List <Icon_DBC_Lookup> lookups = Lookups.ToList();

            foreach (var entry in lookups)
            {
                var path = entry.Name;
                if (!File.Exists(path + ".blp"))
                {
                    Console.WriteLine("Warning: Icon not found: " + path + ".blp");
                    continue;
                }
                bool   loaded = false;
                Bitmap bit    = null;
                try
                {
                    using (FileStream fileStream = new FileStream(path + ".blp", FileMode.Open))
                    {
                        using (BlpFile image = new BlpFile(fileStream))
                        {
                            bit    = image.getBitmap(0);
                            loaded = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error loading image, unsupported BLP format: {path}.blp\n{e.Message}\n{e}");
                }
                if (!loaded)
                {
                    continue;
                }

                System.Windows.Controls.Image temp = new System.Windows.Controls.Image();
                temp.Width               = iconSize == null ? 32 : iconSize.Value;
                temp.Height              = iconSize == null ? 32 : iconSize.Value;
                temp.Margin              = iconMargin == null ? new Thickness(margin, 0, 0, 0) : iconMargin.Value;
                temp.VerticalAlignment   = VerticalAlignment.Top;
                temp.HorizontalAlignment = HorizontalAlignment.Left;
                temp.Source              = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bit.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bit.Width, bit.Height));
                temp.Name       = "Index_" + entry.Offset;
                temp.ToolTip    = path;
                temp.MouseDown += ImageDown;

                main.IconGrid.Children.Add(temp);
                bit.Dispose();
            }
        }
Beispiel #21
0
        private void displayImage(string file)
        {
            currentImage = null;
            UI_PreviewStatus.Hide();

            using (var blp = new BlpFile(File.OpenRead(file)))
                currentImage = blp.GetBitmap(0);

            Graphics gfx = UI_ImagePreview.CreateGraphics();

            gfx.Clear(UI_ImagePreview.BackColor);
            gfx.DrawImage(currentImage, 0, 0);
            UI_ExportButton.Show();

            currentImageName = file;
        }
Beispiel #22
0
        protected override Icon GetIcon(bool smallIcon, uint iconSize)
        {
            if (!File.Exists(SelectedItemPath))
            {
                return(new Icon(SystemIcons.Exclamation, new Size((int)iconSize, (int)iconSize)));
            }

            using (var stream = File.OpenRead(SelectedItemPath))
                using (var blpFile = new BlpFile(stream))
                {
                    using (var bitmap = blpFile.GetBitmap(0))
                    {
                        return(Icon.FromHandle(bitmap.GetHicon()));
                    }
                }
        }
Beispiel #23
0
 private void RedrawImage()
 {
     image = new Bitmap(canvasSize, canvasSize);
     using (Graphics g = Graphics.FromImage(image))
     {
         foreach (SubTile tile in tiles)
         {
             using (BlpFile blp = new BlpFile(File.OpenRead(tile.File)))
             {
                 g.DrawImage(
                     blp.GetBitmap(0),
                     new Rectangle(tile.DrawX, tile.DrawY, tileSize, tileSize),
                     new Rectangle(0, 0, tileSize, tileSize),
                     GraphicsUnit.Pixel
                     );
             }
         }
     }
 }
Beispiel #24
0
        public void LoadBLP(string filename)
        {
            if (!CASC.FileExists(filename))
            {
                new WoWFormatLib.Utils.MissingFile(filename);

                // @TODO Quick fix to get texture working when it doesn't exist. Happened because Blizzard accidentally referenced a texture on their shares instead of in files.
                using (var blp = new BlpFile(CASC.OpenFile(@"World\Expansion05\Doodads\IronHorde\Ember_Offset_Streak.blp")))
                {
                    bmp = blp.GetBitmap(0);
                }
            }
            else
            {
                using (var blp = new BlpFile(CASC.OpenFile(filename)))
                {
                    bmp = blp.GetBitmap(0);
                }
            }
        }
Beispiel #25
0
        private static Bitmap ReadBLP(String filePath)
        {
            FileStream fs      = File.OpenRead(filePath);
            BlpFile    blpFile = new BlpFile(fs);
            int        width;
            int        height;

            // The library does not determine what's BLP1 and BLP2 properly, so we manually set bool bgra in GetPixels depending on the checkbox.
            byte[] bytes         = blpFile.GetPixels(0, out width, out height, blpFile._isBLP2); // 0 indicates first mipmap layer. width and height are assigned width and height in GetPixels().
            var    actualImage   = blpFile.GetBitmapSource(0);
            int    bytesPerPixel = (actualImage.Format.BitsPerPixel + 7) / 8;
            int    stride        = bytesPerPixel * actualImage.PixelWidth;

            // blp read and convert
            Bitmap image = new Bitmap(width, height);

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    var offset = (y * stride) + (x * bytesPerPixel);

                    byte red;
                    byte green;
                    byte blue;
                    byte alpha = 0;

                    red   = bytes[offset + 0];
                    green = bytes[offset + 1];
                    blue  = bytes[offset + 2];
                    alpha = bytes[offset + 3];

                    image.SetPixel(x, y, Color.FromArgb(alpha, blue, green, red)); // assign color to pixel
                }
            }

            blpFile.Dispose();

            return(image);
        }
Beispiel #26
0
        public void TestGetBlpBitmapSource(string inputImagePath, string expectedImagePath, int mipMapLevel)
        {
            using (var fileStream = File.OpenRead(inputImagePath))
            {
                var expectedImage = new Bitmap(expectedImagePath);
                var blpFile       = new BlpFile(fileStream);
                var actualImage   = blpFile.GetBitmapSource(mipMapLevel);

                Assert.AreEqual(expectedImage.Width, actualImage.PixelWidth);
                Assert.AreEqual(expectedImage.Height, actualImage.PixelHeight);

                var bytesPerPixel = (actualImage.Format.BitsPerPixel + 7) / 8;
                var stride        = bytesPerPixel * actualImage.PixelWidth;
                var bytes         = new byte[stride * actualImage.PixelHeight];
                actualImage.CopyPixels(bytes, stride, 0);

                for (var y = 0; y < expectedImage.Height; y++)
                {
                    for (var x = 0; x < expectedImage.Width; x++)
                    {
                        var offset = (y * stride) + (x * bytesPerPixel);

                        // Assumes actualImage.Format is either PixelFormats.Bgr32 or PixelFormats.Bgra32
                        Assert.AreEqual(expectedImage.GetPixel(x, y).B, bytes[offset + 0]);
                        Assert.AreEqual(expectedImage.GetPixel(x, y).G, bytes[offset + 1]);
                        Assert.AreEqual(expectedImage.GetPixel(x, y).R, bytes[offset + 2]);

                        if (bytesPerPixel > 3)
                        {
                            Assert.AreEqual(expectedImage.GetPixel(x, y).A, bytes[offset + 3]);
                        }
                    }
                }

                expectedImage.Dispose();
                blpFile.Dispose();
            }
        }
Beispiel #27
0
        public void addTexture(int extID, string file)
        {
            int width  = 0;
            int height = 0;

            byte[] data = null;

            fileMapping.Add(extID, file);

            using (BlpFile raw = new BlpFile(File.OpenRead(file)))
            {
                Bitmap bitmap = raw.GetBitmap(0);
                width  = bitmap.Width;
                height = bitmap.Height;

                int length  = width * height * 4;
                var rawData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
                data = new byte[length];

                Marshal.Copy(rawData.Scan0, data, 0, length);
                bitmap.UnlockBits(rawData);
                bitmap.Dispose();
            }

            uint[] intID = new uint[1];
            gl.GenTextures(1, intID);

            gl.BindTexture(OpenGL.GL_TEXTURE_2D, intID[0]);
            gl.TexImage2D(OpenGL.GL_TEXTURE_2D, 0, OpenGL.GL_RGBA, width, height, 0, OpenGL.GL_BGRA, OpenGL.GL_UNSIGNED_BYTE, data);

            gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_LINEAR);
            gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_LINEAR_MIPMAP_LINEAR);

            mapping.Add(extID, intID);
            gl.GenerateMipmapEXT(OpenGL.GL_TEXTURE_2D);

            Log.Write("TextureManager: {0} assigned to GL with @ {1}", file, intID[0]);
        }
Beispiel #28
0
        public async void UpdateMainWindowIcons(double margin)
        {
            if (adapter == null || main.selectedID == 0)               // adapter.query below caused unhandled exception with main.selectedID as 0.
            {
                return;
            }

            DataRow res;

            try
            {
                res = adapter.query(string.Format("SELECT `SpellIconID`,`ActiveIconID` FROM `{0}` WHERE `ID` = '{1}'", adapter.Table, main.selectedID)).Rows[0];
            }
            catch (Exception)
            {
                return;
            }
            UInt32 iconInt        = UInt32.Parse(res[0].ToString());
            UInt32 iconActiveInt  = UInt32.Parse(res[1].ToString());
            UInt32 selectedRecord = UInt32.MaxValue;

            for (UInt32 i = 0; i < header.RecordCount; ++i)
            {
                if (body.records[i].ID == iconInt)
                {
                    selectedRecord = i;

                    break;
                }

                if (body.records[i].ID == iconActiveInt)
                {
                    selectedRecord = i;

                    break;
                }
            }

            string icon = "";

            int offset = 0;

            try
            {
                if (selectedRecord == UInt32.MaxValue)
                {
                    throw new Exception("The icon for this spell does not exist in the SpellIcon.dbc");
                }

                offset = (int)body.records[selectedRecord].Name;

                while (body.StringBlock[offset] != '\0')
                {
                    icon += body.StringBlock[offset++];
                }

                if (!File.Exists(icon + ".blp"))
                {
                    throw new Exception("File could not be found: " + "Icons\\" + icon + ".blp");
                }
            }

            catch (Exception ex)
            {
                main.Dispatcher.Invoke(new Action(() => main.HandleErrorMessage(ex.Message)));

                return;
            }

            FileStream fileStream = new FileStream(icon + ".blp", FileMode.Open);

            SereniaBLPLib.BlpFile image;

            image = new SereniaBLPLib.BlpFile(fileStream);

            Bitmap bit = image.getBitmap(0);

            await Task.Factory.StartNew(() =>
            {
                main.CurrentIcon.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bit.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bit.Width, bit.Height));
            }, CancellationToken.None, TaskCreationOptions.None, main.UIScheduler);

            image.close();
            fileStream.Close();

            if (!loadedAllIcons)
            {
                loadedAllIcons = true;

                int currentOffset = 1;

                string[] icons = body.StringBlock.Split('\0');

                int iconIndex   = 0;
                int columnsUsed = icons.Length / 11;
                int rowsToDo    = columnsUsed / 2;

                for (int j = -rowsToDo; j <= rowsToDo; ++j)
                {
                    for (int i = -5; i < 6; ++i)
                    {
                        ++iconIndex;
                        if (iconIndex >= icons.Length - 1)
                        {
                            break;
                        }
                        int this_icons_offset = currentOffset;

                        currentOffset += icons[iconIndex].Length + 1;

                        if (!File.Exists(icons[iconIndex] + ".blp"))
                        {
                            Console.WriteLine("Warning: Icon not found: " + icons[iconIndex] + ".blp");

                            continue;
                        }

                        bool loaded = false;
                        try
                        {
                            fileStream = new FileStream(icons[iconIndex] + ".blp", FileMode.Open);
                            image      = new BlpFile(fileStream);
                            bit        = image.getBitmap(0);
                            loaded     = true;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"Error loading image, unsupported BLP format: {icons[iconIndex]}.blp\n{e.Message}\n{e}");
                        }
                        if (!loaded)
                        {
                            image?.close();
                            fileStream?.Close();
                            continue;
                        }

                        await Task.Factory.StartNew(() =>
                        {
                            System.Windows.Controls.Image temp = new System.Windows.Controls.Image();

                            temp.Width               = iconSize == null ? 32 : iconSize.Value;
                            temp.Height              = iconSize == null ? 32 : iconSize.Value;
                            temp.Margin              = iconMargin == null ? new System.Windows.Thickness(margin, 0, 0, 0) : iconMargin.Value;
                            temp.VerticalAlignment   = VerticalAlignment.Top;
                            temp.HorizontalAlignment = HorizontalAlignment.Left;
                            temp.Source              = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bit.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bit.Width, bit.Height));
                            temp.Name       = "Index_" + this_icons_offset;
                            temp.ToolTip    = icons[iconIndex];
                            temp.MouseDown += this.ImageDown;

                            main.IconGrid.Children.Add(temp);
                        }, CancellationToken.None, TaskCreationOptions.None, main.UIScheduler);

                        image.close();
                        fileStream.Close();
                    }
                }
            }
        }
        private static void Main(string[] args)
        {
            var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("settings.json", true, true).Build();

            var saveExplored   = bool.Parse(config["saveExploredMaps"]);
            var saveUnexplored = bool.Parse(config["saveUnexploredMaps"]);
            var saveLayers     = bool.Parse(config["saveMapLayers"]);

            if (saveExplored && !Directory.Exists("explored"))
            {
                Directory.CreateDirectory("explored");
            }

            if (saveUnexplored && !Directory.Exists("unexplored"))
            {
                Directory.CreateDirectory("unexplored");
            }

            if (saveLayers && !Directory.Exists("layers"))
            {
                Directory.CreateDirectory("layers");
            }

            var locale = CASCLib.LocaleFlags.enUS;

            if (config["locale"] != string.Empty)
            {
                switch (config["locale"])
                {
                case "deDE":
                    locale = CASCLib.LocaleFlags.deDE;
                    break;

                case "enUS":
                    locale = CASCLib.LocaleFlags.enUS;
                    break;

                case "ruRU":
                    locale = CASCLib.LocaleFlags.ruRU;
                    break;

                case "zhCN":
                    locale = CASCLib.LocaleFlags.zhCN;
                    break;

                case "zhTW":
                    locale = CASCLib.LocaleFlags.zhTW;
                    break;
                }
            }

            if (config["installDir"] != string.Empty && Directory.Exists(config["installDir"]))
            {
                CASC.InitCasc(null, config["installDir"], config["program"], locale);
            }
            else
            {
                CASC.InitCasc(null, null, config["program"], locale);
            }

            using (var UIMapStream = CASC.OpenFile("DBFilesClient\\UIMap.db2"))
                using (var UIMapXArtStream = CASC.OpenFile("DBFilesClient\\UIMapXMapArt.db2"))
                    using (var UIMapArtTileStream = CASC.OpenFile("DBFilesClient\\UIMapArtTile.db2"))
                        using (var WorldMapOverlayStream = CASC.OpenFile("DBFilesClient\\WorldMapOverlay.db2"))
                            using (var WorldMapOverlayTileStream = CASC.OpenFile("DBFilesClient\\WorldMapOverlayTile.db2"))
                            {
                                if (!Directory.Exists("dbcs"))
                                {
                                    Directory.CreateDirectory("dbcs");
                                }

                                var uimapfs = File.Create("dbcs/UIMap.db2");
                                UIMapStream.CopyTo(uimapfs);
                                uimapfs.Close();

                                var uimapxartfs = File.Create("dbcs/UIMapXMapArt.db2");
                                UIMapXArtStream.CopyTo(uimapxartfs);
                                uimapxartfs.Close();

                                var uimapatfs = File.Create("dbcs/UIMapArtTile.db2");
                                UIMapArtTileStream.CopyTo(uimapatfs);
                                uimapatfs.Close();

                                var wmofs = File.Create("dbcs/WorldMapOverlay.db2");
                                WorldMapOverlayStream.CopyTo(wmofs);
                                wmofs.Close();

                                var wmotfs = File.Create("dbcs/WorldMapOverlayTile.db2");
                                WorldMapOverlayTileStream.CopyTo(wmotfs);
                                wmotfs.Close();
                            }

            var UIMap               = DBCManager.LoadDBC("UIMap", CASC.BuildName);
            var UIMapXArt           = DBCManager.LoadDBC("UIMapXMapArt", CASC.BuildName);
            var UIMapArtTile        = DBCManager.LoadDBC("UIMapArtTile", CASC.BuildName);
            var WorldMapOverlay     = DBCManager.LoadDBC("WorldMapOverlay", CASC.BuildName);
            var WorldMapOverlayTile = DBCManager.LoadDBC("WorldMapOverlayTile", CASC.BuildName);

            Console.WriteLine(); // new line after wdc2 debug output

            foreach (dynamic mapRow in UIMap)
            {
                var mapName = mapRow.Value.Name_lang;

                Console.WriteLine(mapRow.Key + " = " + mapName);

                foreach (dynamic mxaRow in UIMapXArt)
                {
                    var uiMapArtID = mxaRow.Value.UiMapArtID;
                    var uiMapID    = mxaRow.Value.UiMapID;

                    if (mxaRow.Value.PhaseID != 0)
                    {
                        continue; // Skip phase stuff for now
                    }
                    if (uiMapID == mapRow.Key)
                    {
                        var maxRows  = uint.MinValue;
                        var maxCols  = uint.MinValue;
                        var tileDict = new Dictionary <string, int>();

                        foreach (dynamic matRow in UIMapArtTile)
                        {
                            var matUiMapArtID = matRow.Value.UiMapArtID;
                            if (matUiMapArtID == uiMapArtID)
                            {
                                var fdid       = matRow.Value.FileDataID;
                                var rowIndex   = matRow.Value.RowIndex;
                                var colIndex   = matRow.Value.ColIndex;
                                var layerIndex = matRow.Value.LayerIndex;

                                // Skip other layers for now
                                if (layerIndex != 0)
                                {
                                    continue;
                                }

                                if (rowIndex > maxRows)
                                {
                                    maxRows = rowIndex;
                                }

                                if (colIndex > maxCols)
                                {
                                    maxCols = colIndex;
                                }

                                tileDict.Add(rowIndex + "," + colIndex, fdid);
                            }
                        }

                        var res_x = (maxRows + 1) * 256;
                        var res_y = (maxCols + 1) * 256;

                        var bmp = new Bitmap((int)res_y, (int)res_x);

                        var g = Graphics.FromImage(bmp);

                        for (var cur_x = 0; cur_x < maxRows + 1; cur_x++)
                        {
                            for (var cur_y = 0; cur_y < maxCols + 1; cur_y++)
                            {
                                var fdid = tileDict[cur_x + "," + cur_y];

                                if (CASC.FileExists((uint)fdid))
                                {
                                    using (var stream = CASC.OpenFile((uint)fdid))
                                    {
                                        try
                                        {
                                            var blp = new BlpFile(stream);
                                            g.DrawImage(blp.GetBitmap(0), cur_y * 256, cur_x * 256, new Rectangle(0, 0, 256, 256), GraphicsUnit.Pixel);
                                        }
                                        catch (Exception e)
                                        {
                                            Console.WriteLine("An error occured opening BLP with filedataid " + fdid);
                                        }
                                    }
                                }
                            }
                        }

                        if (saveUnexplored)
                        {
                            bmp.Save("unexplored/ " + CleanFileName(mapRow.Key + " - " + mapName + ".png"));
                        }

                        if (!saveLayers && !saveExplored)
                        {
                            continue;
                        }

                        foreach (dynamic wmorow in WorldMapOverlay)
                        {
                            var WMOUIMapArtID = wmorow.Value.UiMapArtID;
                            var offsetX       = wmorow.Value.OffsetX;
                            var offsetY       = wmorow.Value.OffsetY;

                            uint maxWMORows  = 0;
                            uint maxWMOCols  = 0;
                            var  wmoTileDict = new Dictionary <string, int>();

                            if (WMOUIMapArtID == uiMapArtID)
                            {
                                foreach (dynamic wmotrow in WorldMapOverlayTile)
                                {
                                    var worldMapOverlayID = wmotrow.Value.WorldMapOverlayID;

                                    // something wrong in/around this check
                                    if (worldMapOverlayID == wmorow.Key)
                                    {
                                        var fdid       = wmotrow.Value.FileDataID;
                                        var rowIndex   = wmotrow.Value.RowIndex;
                                        var colIndex   = wmotrow.Value.ColIndex;
                                        var layerIndex = wmotrow.Value.LayerIndex;

                                        // Skip other layers for now
                                        if (layerIndex != 0)
                                        {
                                            continue;
                                        }

                                        if (rowIndex > maxWMORows)
                                        {
                                            maxWMORows = rowIndex;
                                        }

                                        if (colIndex > maxWMOCols)
                                        {
                                            maxWMOCols = colIndex;
                                        }

                                        wmoTileDict.Add(rowIndex + "," + colIndex, fdid);
                                    }
                                }
                            }

                            if (wmoTileDict.Count == 0)
                            {
                                continue;
                            }

                            var layerResX = (maxWMORows + 1) * 256;
                            var layerResY = (maxWMOCols + 1) * 256;

                            var layerBitmap   = new Bitmap((int)layerResY, (int)layerResX);
                            var layerGraphics = Graphics.FromImage(layerBitmap);

                            for (var cur_x = 0; cur_x < maxWMORows + 1; cur_x++)
                            {
                                for (var cur_y = 0; cur_y < maxWMOCols + 1; cur_y++)
                                {
                                    var fdid = wmoTileDict[cur_x + "," + cur_y];

                                    if (CASC.FileExists((uint)fdid))
                                    {
                                        using (var stream = CASC.OpenFile((uint)fdid))
                                        {
                                            try
                                            {
                                                var blp  = new BlpFile(stream);
                                                var posY = cur_y * 256 + offsetX;
                                                var posX = cur_x * 256 + offsetY;

                                                if (saveLayers)
                                                {
                                                    layerGraphics.DrawImage(blp.GetBitmap(0), cur_y * 256, cur_x * 256, new Rectangle(0, 0, 256, 256), GraphicsUnit.Pixel);
                                                }
                                                g.DrawImage(blp.GetBitmap(0), posY, posX, new Rectangle(0, 0, 256, 256), GraphicsUnit.Pixel);
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("An error occured opening BLP with filedataid " + fdid);
                                            }
                                        }
                                    }
                                }
                            }

                            if (saveLayers)
                            {
                                if (!Directory.Exists("layers/" + CleanFileName(mapRow.Key + " - " + mapName) + "/"))
                                {
                                    Directory.CreateDirectory("layers/" + CleanFileName(mapRow.Key + " - " + mapName) + "/");
                                }
                                layerBitmap.Save("layers/" + CleanFileName(mapRow.Key + " - " + mapName) + "/" + wmorow.Key + ".png");
                            }
                        }

                        if (saveExplored)
                        {
                            bmp.Save("explored/ " + CleanFileName(mapRow.Key + " - " + mapName + ".png"));
                        }
                    }
                }
            }
        }
        public void UpdateMainWindowIcons(double margin)
        {
            // adapter.query below caused unhandled exception with main.selectedID as 0.
            if (adapter == null || main.selectedID == 0)
            {
                return;
            }

            DataRow res           = adapter.query(string.Format("SELECT `SpellIconID`,`ActiveIconID` FROM `{0}` WHERE `ID` = '{1}'", adapter.Table, main.selectedID)).Rows[0];
            uint    iconInt       = uint.Parse(res[0].ToString());
            uint    iconActiveInt = uint.Parse(res[1].ToString());

            // Update currently selected icon, we don't currently use ActiveIconID
            using (FileStream fileStream = new FileStream(GetIconPath(iconInt) + ".blp", FileMode.Open))
            {
                using (BlpFile image = new BlpFile(fileStream))
                {
                    Bitmap bit = image.getBitmap(0);
                    System.Windows.Controls.Image temp = new System.Windows.Controls.Image();

                    temp.Width               = iconSize == null ? 32 : iconSize.Value;
                    temp.Height              = iconSize == null ? 32 : iconSize.Value;
                    temp.Margin              = iconMargin == null ? new Thickness(margin, 0, 0, 0) : iconMargin.Value;
                    temp.VerticalAlignment   = VerticalAlignment.Top;
                    temp.HorizontalAlignment = HorizontalAlignment.Left;
                    temp.Source              = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bit.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bit.Width, bit.Height));
                    temp.Name = "CurrentSpellIcon";

                    // Code smells here on hacky positioning and updating the icon
                    temp.Margin = new Thickness(103, 38, 0, 0);
                    main.CurrentIconGrid.Children.Clear();
                    main.CurrentIconGrid.Children.Add(temp);
                }
            }

            // Load all icons available if have not already
            if (!loadedAllIcons)
            {
                loadedAllIcons = true;

                List <Icon_DBC_Lookup> lookups = Lookups.ToList();
                foreach (var entry in lookups)
                {
                    var path = entry.Name;
                    if (!File.Exists(path + ".blp"))
                    {
                        Console.WriteLine("Warning: Icon not found: " + path + ".blp");
                        continue;
                    }
                    bool   loaded = false;
                    Bitmap bit    = null;
                    try
                    {
                        using (FileStream fileStream = new FileStream(path + ".blp", FileMode.Open))
                        {
                            using (BlpFile image = new BlpFile(fileStream))
                            {
                                bit    = image.getBitmap(0);
                                loaded = true;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Error loading image, unsupported BLP format: {path}.blp\n{e.Message}\n{e}");
                    }
                    if (!loaded)
                    {
                        continue;
                    }

                    System.Windows.Controls.Image temp = new System.Windows.Controls.Image();

                    temp.Width               = iconSize == null ? 32 : iconSize.Value;
                    temp.Height              = iconSize == null ? 32 : iconSize.Value;
                    temp.Margin              = iconMargin == null ? new Thickness(margin, 0, 0, 0) : iconMargin.Value;
                    temp.VerticalAlignment   = VerticalAlignment.Top;
                    temp.HorizontalAlignment = HorizontalAlignment.Left;
                    temp.Source              = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bit.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bit.Width, bit.Height));
                    temp.Name       = "Index_" + entry.Offset;
                    temp.ToolTip    = path;
                    temp.MouseDown += ImageDown;

                    main.IconGrid.Children.Add(temp);
                }
            }
        }