public void loadDDS(string filename)
        {
            this.lockImage = true;

            FileInfo f = new FileInfo(filename);

            ddsFile = new DdsFileTypePlugin.DdsFile();
            Stream input = File.Open(f.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
            ddsFile.Load(input);
            pictureBox1.Image = ddsFile.Image();

            toolStripStatusLabel1.Text = f.Name;
            toolStripStatusLabel2.Text = "W: " + ddsFile.m_header.m_width.ToString();
            toolStripStatusLabel3.Text = "H: " + ddsFile.m_header.m_height.ToString();
            if (ddsFile.m_header.m_pixelFormat.m_rgbBitCount.ToString() != "0")
            {
                toolStripStatusLabel4.Text = ddsFile.m_header.m_pixelFormat.m_rgbBitCount.ToString() + "bit";
            }
            toolStripStatusLabel5.Text = ddsFile.m_header.fileFormat;

            chkShowRed.Checked = true;
            chkShowGreen.Checked = true;
            chkShowBlue.Checked = true;
            chkShowAlpha.Checked = true;

            input.Close();

            this.lockImage = false;
        }
        /*
        public Stream findPattern(patternsFile pattern)
        {
            if (File.Exists(pattern.subcategory))
            {
                Stream cast = File.Open(pattern.subcategory, FileMode.Open, FileAccess.Read, FileShare.Read);
                MadScience.Wrappers.Database castdb = new MadScience.Wrappers.Database(cast, true);

                MadScience.Wrappers.ResourceKey temp = new MadScience.Wrappers.ResourceKey(pattern.texturename);
                Stream patternThumb = null;

                try
                {
                    patternThumb = castdb.GetResourceStream(temp);
                }
                catch (System.Collections.Generic.KeyNotFoundException ex)
                {
                }
                catch (Exception ex)
                {
                    Helpers.logMessageToFile(ex.Message);
                }
                cast.Close();

                if (patternThumb != null)
                {
                    return patternThumb;
                }
            }

            return Stream.Null;
        }
        */
        /*
        public patternsFile findPattern(string resKey)
        {
            // Get pattern details from XML
            keyName patternXML = new keyName(resKey);
            patternsFile temp = new patternsFile();

            bool hasMatch = false;

            for (int i = 0; i < this.customPatterns.Items.Count; i++)
            {
                patternsFile pattern = this.customPatterns.Items[i];

                if (MadScience.StringHelpers.ParseHex32(pattern.typeid) == patternXML.typeId && MadScience.StringHelpers.ParseHex32(pattern.groupid) == patternXML.groupId && MadScience.StringHelpers.ParseHex64(pattern.instanceid) == patternXML.instanceId)
                {
                    hasMatch = true;
                    temp = pattern;
                    break;
                }
            }

            if (!hasMatch)
            {
                for (int i = 0; i < this.patterns.Items.Count; i++)
                {
                    patternsFile pattern = this.patterns.Items[i];

                    if (MadScience.StringHelpers.ParseHex32(pattern.typeid) == patternXML.typeId && MadScience.StringHelpers.ParseHex32(pattern.groupid) == patternXML.groupId && MadScience.StringHelpers.ParseHex64(pattern.instanceid) == patternXML.instanceId)
                    {
                        hasMatch = true;
                        temp = pattern;
                        break;
                    }
                }
            }

            return temp;
        }
        */
        /*
        public Image makePatternThumb(string resKey)
        {
            return makePatternThumb(findPattern(resKey), null);
        }
        */
        /*
        public patternsFile pDetailsTopFile(patternDetails pDetails)
        {
            patternsFile pFile = new patternsFile();

            keyName pKey = new keyName(pDetails.key);
            pFile.casPart = pDetails.filename;
            pFile.typeid = "0x" + pKey.typeId.ToString("X8");
            pFile.groupid = "0x" + pKey.groupId.ToString("X8");
            pFile.instanceid = "0x" + pKey.instanceId.ToString("X16");

            pFile.category = pDetails.category;
            pFile.color0 = pDetails.ColorP[0];
            pFile.color1 = pDetails.ColorP[1];
            pFile.color2 = pDetails.ColorP[2];
            pFile.color3 = pDetails.ColorP[3];
            pFile.color4 = pDetails.ColorP[4];

            pFile.HBg = pDetails.HBg;
            pFile.SBg = pDetails.SBg;
            pFile.VBg = pDetails.VBg;

            return pFile;
        }
        */
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            panel1.Visible = false;

            label2.Text = "Loading patterns... Please wait...";
            label2.Refresh();

            numFound = 0;
            horizontal = 0;
            vertical = 0;

            ToolTip tt = new ToolTip();

            DdsFileTypePlugin.DdsFile ddsP = new DdsFileTypePlugin.DdsFile();

            if (comboBox1.Text == "* Custom")
            {

                for (int i = 0; i < this.customPatterns.Items.Count; i++)
                {
                    patternsFile pattern = this.customPatterns.Items[i];
                    //if (pattern.category == comboBox1.Text)
                    //{

                        numFound++;

                        PictureBox picBox = new PictureBox();
                        picBox.BackColor = System.Drawing.Color.White;
                        picBox.Name = pattern.casPart;

                        string toolTip = pattern.category + "\\";
                        //if (pattern.subcategory != "")
                        //{
                            //toolTip += pattern.subcategory + "\\";
                        //}
                        toolTip += pattern.casPart;
                        tt.SetToolTip(picBox, toolTip);

                        // Find thumbnail
                        if (File.Exists(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png"))))
                        {
                            Stream tmpImage = File.OpenRead(Path.Combine(Application.StartupPath, Path.Combine("patterncache",  pattern.casPart + ".png")));
                            picBox.Image = Image.FromStream(tmpImage);
                            tmpImage.Close();
                        }
                        else
                        {
                            if (File.Exists(pattern.subcategory))
                            {

                                //if (pattern.typeid.StartsWith("0x")) pattern.typeid = pattern.typeid.Remove(0, 2);
                                //if (pattern.groupid.StartsWith("0x")) pattern.groupid = pattern.groupid.Remove(0, 2);
                                //if (pattern.instanceid.StartsWith("0x")) pattern.instanceid = pattern.instanceid.Remove(0, 2);

                                Stream patternXml = KeyUtils.searchForKey(pattern.key, pattern.subcategory);
                                if (StreamHelpers.isValidStream(patternXml))
                                {
                                    Patterns.patternDetails pDetails = Patterns.parsePatternComplate(patternXml);
                                    //Stream patternThumb = KeyUtils.searchForKey(pattern.texturename, pattern.subcategory);
                                    //if (Helpers.isValidStream(patternThumb))
                                    //{
                                        //picBox.Image = Patterns.makePatternThumb(patternThumb, pDetails);
                                    picBox.Image = Patterns.makePatternThumb(pDetails);
                                        try
                                        {
                                            picBox.Image.Save(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png")), System.Drawing.Imaging.ImageFormat.Png);
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    //}
                                }
                            }

                        }

                        addToPanel(picBox);
                    //}

                }

            }
            else
            {

                string s3root = MadScience.Helpers.findSims3Root();
                string thumbnailPackage = Helpers.getGameSubPath(@"\GameData\Shared\Packages\FullBuild2.package");

                Console.WriteLine("Starting at: " + DateTime.Now.ToString());

                Stream cast = File.Open(Path.Combine(s3root, thumbnailPackage), FileMode.Open, FileAccess.Read, FileShare.Read);
                MadScience.Wrappers.Database castdb = new MadScience.Wrappers.Database(cast);

                Stream fullBuild0 = File.Open(Path.Combine(s3root, Helpers.getGameSubPath(@"\GameData\Shared\Packages\FullBuild0.package")), FileMode.Open, FileAccess.Read, FileShare.Read);
                MadScience.Wrappers.Database xmldb = new MadScience.Wrappers.Database(fullBuild0);

                for (int i = 0; i < this.patterns.Items.Count; i++)
                {
                    patternsFile pattern = this.patterns.Items[i];
                    if (pattern.category == comboBox1.Text)
                    {

                        numFound++;

                        PictureBox picBox = new PictureBox();
                        picBox.BackColor = System.Drawing.Color.White;
                        picBox.Name = pattern.casPart;

                        string toolTip = pattern.category + "\\";
                        if (pattern.subcategory != "")
                        {
                            toolTip += pattern.subcategory + "\\";
                        }
                        toolTip += pattern.casPart;
                        tt.SetToolTip(picBox, toolTip);

                        // Find thumbnail
                        if (File.Exists(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png"))))
                        {
                            Stream tmpImage = File.OpenRead(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png")));
                            picBox.Image = Image.FromStream(tmpImage);
                            tmpImage.Close();
                        }
                        else
                        {
                            //Console.WriteLine(pattern.casPart);

                            Stream patternXml = KeyUtils.findKey(new MadScience.Wrappers.ResourceKey(pattern.key), 0, xmldb);
                            if (StreamHelpers.isValidStream(patternXml))
                            {
                                Patterns.patternDetails pDetails2 = Patterns.parsePatternComplate(patternXml);
                                //Stream patternThumb = KeyUtils.findKey(new MadScience.Wrappers.ResourceKey("key:00B2D882:00000000:" + StringHelpers.HashFNV64(pDetails2.name).ToString("X16")), 0, castdb);
                                //if (!Helpers.isValidStream(patternThumb))
                                //{
                                //    patternThumb = KeyUtils.findKey(new MadScience.Wrappers.ResourceKey(pDetails2.BackgroundImage), 0, castdb);
                                //}
                                //if (Helpers.isValidStream(patternThumb))
                                //{
                                    picBox.Image = Patterns.makePatternThumb(pDetails2, castdb);
                                    try
                                    {
                                        picBox.Image.Save(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png")), System.Drawing.Imaging.ImageFormat.Png);
                                    }
                                    catch (Exception)
                                    {
                                    }
                                //}
                            }
                        }

                        addToPanel(picBox);

                    }

                }

                Console.WriteLine("Stopping at: " + DateTime.Now.ToString());

                //dbpf = null;
                fullBuild0.Close();
                cast.Close();
                //castdb = null;
            }
            label2.Text = numFound.ToString() + " patterns";
            panel1.Visible = true;
            this.curCategory = comboBox1.SelectedIndex;
        }
 public static Bitmap mergeStencils(List<Stream> Stencils)
 {
     Bitmap output = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb);
     Graphics g = Graphics.FromImage(output);
     var d = new DdsFileTypePlugin.DdsFile();
     if ((Stencils != null))
     {
         for (int i = 0; i < Stencils.Count; i++)
         {
             if (Stencils[i].Length != 0)
             {
                 d.Load(Stencils[i]);
                 Bitmap _Stencil = (Bitmap)d.Image(true, true, true, true);
                 Stencils[i].Close();
                 if (!(_Stencil.Width == 1024 || _Stencil.Height == 1024))
                 {
                     ResizeBitmapCorrect(ref _Stencil, 1024, 1024);
                 }
                 g.DrawImage(_Stencil, 0, 0);
             }
         }
     }
     g.Dispose();
     return output;
 }
        public static Image makePatternThumb(patternDetails pattern, Wrappers.Database db)
        {
            Image temp = null;

                if (pattern.type == "HSV")
                {
                    DdsFileTypePlugin.DdsFile ddsP = new DdsFileTypePlugin.DdsFile();

                    Colours.HSVColor channel1Color = new Colours.HSVColor();
                    Colours.HSVColor channel2Color = new Colours.HSVColor();
                    Colours.HSVColor channel3Color = new Colours.HSVColor();

                    Colours.HSVColor backColor = new Colours.HSVColor(Convert.ToDouble(pattern.HBg, CultureInfo.InvariantCulture) * 360, Convert.ToDouble(pattern.SBg, CultureInfo.InvariantCulture), Convert.ToDouble(pattern.VBg, CultureInfo.InvariantCulture));
                    bool[] channelsEnabled = new bool[3];

                    if (pattern.ChannelEnabled[0] != null && pattern.ChannelEnabled[0].ToLower() == "true")
                    {
                        channel1Color = new Colours.HSVColor(Convert.ToDouble(pattern.H[0], CultureInfo.InvariantCulture) * 360, Convert.ToDouble(pattern.S[0], CultureInfo.InvariantCulture), Convert.ToDouble(pattern.V[0], CultureInfo.InvariantCulture));
                        channelsEnabled[0] = true;
                    }
                    if (pattern.ChannelEnabled[1] != null && pattern.ChannelEnabled[1].ToLower() == "true")
                    {
                        channel2Color = new Colours.HSVColor(Convert.ToDouble(pattern.H[1], CultureInfo.InvariantCulture) * 360, Convert.ToDouble(pattern.S[1], CultureInfo.InvariantCulture), Convert.ToDouble(pattern.V[1], CultureInfo.InvariantCulture));
                        channelsEnabled[1] = true;
                    }
                    if (pattern.ChannelEnabled[2] != null && pattern.ChannelEnabled[2].ToLower() == "true")
                    {
                        channel3Color = new Colours.HSVColor(Convert.ToDouble(pattern.H[2], CultureInfo.InvariantCulture) * 360, Convert.ToDouble(pattern.S[2], CultureInfo.InvariantCulture), Convert.ToDouble(pattern.V[2], CultureInfo.InvariantCulture));
                        channelsEnabled[2] = true;
                    }
                    if (isEmptyMask(pattern.rgbmask))
                    {
                        if (db != null)
                        {
                            temp = Patterns.createHSVPattern(KeyUtils.findKey(new Wrappers.ResourceKey(pattern.BackgroundImage), 2, db), backColor);
                        }
                        else
                        {
                            temp = Patterns.createHSVPattern(KeyUtils.findKey(pattern.BackgroundImage), backColor);
                        }
                    }
                    else
                    {
                        if (db != null)
                        {
                            temp = Patterns.createHSVPattern(KeyUtils.findKey(new Wrappers.ResourceKey(pattern.BackgroundImage), 2, db), KeyUtils.findKey(new Wrappers.ResourceKey(pattern.rgbmask), 2, db), backColor, KeyUtils.findKey(new MadScience.Wrappers.ResourceKey(makeKey(pattern.Channel[0])), 0, db), KeyUtils.findKey(new Wrappers.ResourceKey(makeKey(pattern.Channel[1])), 0, db), KeyUtils.findKey(new Wrappers.ResourceKey(makeKey(pattern.Channel[2])), 0, db), channel1Color, channel2Color, channel3Color, channelsEnabled);
                        }
                        else
                        {
                            temp = Patterns.createHSVPattern(KeyUtils.findKey(pattern.BackgroundImage), KeyUtils.findKey(pattern.rgbmask), backColor, KeyUtils.findKey(makeKey(pattern.Channel[0])), KeyUtils.findKey(makeKey(pattern.Channel[1])), KeyUtils.findKey(makeKey(pattern.Channel[2])), channel1Color, channel2Color, channel3Color, channelsEnabled);
                        }
                    }
                }
                else if (pattern.type == "Coloured")
                {
                    DdsFileTypePlugin.DdsFile ddsP = new DdsFileTypePlugin.DdsFile();
                    Color bgColor = Colours.convertColour(pattern.ColorP[0], true);
                    if (bgColor == Color.Empty)
                    {
                        bgColor = Color.Black;
                    }
                    if (pattern.isCustom)
                    {
                        // We need this in here becuase findKey only searches the game files and any local DDS files - it
                        // doesn't search custom packages
                        if (File.Exists(pattern.customFilename))
                        {
                            Stream patternThumb = KeyUtils.searchForKey(pattern.rgbmask, pattern.customFilename);
                            if (!StreamHelpers.isValidStream(patternThumb))
                            {
                                patternThumb = KeyUtils.searchForKey(pattern.BackgroundImage, pattern.customFilename);
                            }
                            if (StreamHelpers.isValidStream(patternThumb))
                            {
                                ddsP.Load(patternThumb);
                            }
                            patternThumb.Close();
                        }
                    }
                    else
                    {
                        if (db != null)
                        {
                            ddsP.Load(KeyUtils.findKey(new Wrappers.ResourceKey(pattern.rgbmask), 2, db));
                        }
                        else
                        {
                            ddsP.Load(KeyUtils.findKey(pattern.rgbmask));
                        }
                    }
                    temp = ddsP.Image(bgColor, Colours.convertColour(pattern.ColorP[1], true), Colours.convertColour(pattern.ColorP[2], true), Colours.convertColour(pattern.ColorP[3], true), Colours.convertColour(pattern.ColorP[4], true));

                }
                else if (pattern.type == "solidColor")
                {
                    temp = new Bitmap(256,256);
                    using (Graphics g = Graphics.FromImage(temp))
                    {
                        g.FillRectangle(new SolidBrush(Colours.convertColour(pattern.Color)),0,0,256,256);
                    }

                }

            return temp;
        }
 public static Bitmap LoadBitmapFromStreamOrEmpty(Stream source, int width, int height)
 {
     Bitmap output;
     DdsFileTypePlugin.DdsFile d = new DdsFileTypePlugin.DdsFile();
     if (source != null && source.Length != 0)
     {
         d.Load(source);
         output = (Bitmap)d.Image(true, true, true, true);
         source.Close();
         if (output.Width != width || output.Height != height)
         {
             if (isAlphaFormat(d.m_header.fileFormat))
                 MadScience.Patterns.ResizeBitmapCorrect(ref output, width, height);
             else
                 MadScience.Patterns.ResizeBitmapFast(ref output, width, height);
         }
     }
     else
     {
         output = new Bitmap(width, height, PixelFormat.Format32bppArgb);
     }
     return output;
 }
 public static Bitmap LoadBitmapFromStream(Stream source)
 {
     Bitmap output;
     DdsFileTypePlugin.DdsFile d = new DdsFileTypePlugin.DdsFile();
     if (source != null && source.Length != 0)
     {
         d.Load(source);
         output = (Bitmap)d.Image();
         source.Close();
     }
     else
     {
         output = null;
     }
     return output;
 }
        public static Bitmap ProcessSingleChannelTexture(
            List<Stream> textures,
            Bitmap pattern,
            PointF tiling)
        {
            Bitmap baseTexture = MadScience.Patterns.LoadBitmapFromStream(textures[0]);
            Bitmap output;

            if (baseTexture != null)
            {
                output = new Bitmap(baseTexture.Width, baseTexture.Height, PixelFormat.Format32bppArgb);

                var d = new DdsFileTypePlugin.DdsFile();
                int patternWidth = (int)(baseTexture.Width / tiling.X);
                int patternHeight = (int)(baseTexture.Height / tiling.Y);

                if (pattern != null)
                {
                    BitmapData outputData = output.LockBits(new Rectangle(0, 0, baseTexture.Width, baseTexture.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                    BitmapData baseTextureData = baseTexture.LockBits(new Rectangle(0, 0, baseTexture.Width, baseTexture.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                    BitmapData patternData = pattern.LockBits(new Rectangle(0, 0, patternWidth, patternHeight), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

                    const int pixelSize = 4;

                    byte[] byteMask = new byte[4];
                    byteMask[0] = 2;
                    byteMask[1] = 1;
                    byteMask[2] = 0;
                    byteMask[3] = 3;

                    //process every pixel
                    unsafe
                    {
                        for (int y = 0; y < baseTexture.Height; y++)
                        {
                            byte* outputRow = (byte*)outputData.Scan0 + (y * outputData.Stride);
                            byte* baseTextureRow = (byte*)baseTextureData.Scan0 + (y * baseTextureData.Stride);
                            byte* patternRow = (byte*)patternData.Scan0 + ((y % patternHeight) * patternData.Stride);

                            for (int x = 0; x < baseTexture.Width; x++)
                            {
                                int pixelLocation = x * pixelSize;

                                Color baseColor = Color.FromArgb(baseTextureRow[pixelLocation + 3], baseTextureRow[pixelLocation + 2], baseTextureRow[pixelLocation + 1], baseTextureRow[pixelLocation]);
                                if (baseColor.A != 0)
                                {
                                    Color outColor = baseColor;
                                    Color patternColor;
                                    if (pattern != null)
                                    {
                                        int xs = x % patternWidth;
                                        int pixelLocation2 = xs * pixelSize;
                                        patternColor = Color.FromArgb(patternRow[pixelLocation2 + 3], patternRow[pixelLocation2 + 2], patternRow[pixelLocation2 + 1], patternRow[pixelLocation2]);
                                        outColor = MadScience.Patterns.ColorMultiply(baseColor, patternColor);
                                    }
                                    outputRow[pixelLocation] = (byte)outColor.B;
                                    outputRow[pixelLocation + 1] = (byte)outColor.G;
                                    outputRow[pixelLocation + 2] = (byte)outColor.R;
                                    outputRow[pixelLocation + 3] = (byte)outColor.A;
                                }
                            }
                        }
                    }
                    output.UnlockBits(outputData);
                    baseTexture.UnlockBits(baseTextureData);
                }
                else
                {
                    output = baseTexture;
                }
            }
            else
            {
                output = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb);
            }
            return output;
        }
        public static Bitmap ProcessClothingTexture(
            List<Stream> textures,
            Bitmap[] Patterns,
            PointF[] Tilings)
        {
            int numPatterns = Patterns.Length;
            Bitmap baseTexture = MadScience.Patterns.LoadBitmapFromStream(textures[0]);
            Bitmap output;

            if (baseTexture != null)
            {
                output = new Bitmap(baseTexture.Width, baseTexture.Height, PixelFormat.Format32bppArgb);

                Bitmap mask = MadScience.Patterns.LoadBitmapFromStream(textures[1], baseTexture.Width, baseTexture.Height);

                var d = new DdsFileTypePlugin.DdsFile();

                int[] PatternsWidth = new int[numPatterns];
                int[] PatternsHeight = new int[numPatterns];

                for (int i = 0; i < numPatterns; i++)
                    if (Patterns[i] != null)
                    {
                        PatternsWidth[i] = (int)(baseTexture.Width / Tilings[i].X);
                        PatternsHeight[i] = (int)(baseTexture.Height / Tilings[i].Y);
                        if (PatternsWidth[i] != Patterns[i].Width || PatternsHeight[i] != Patterns[i].Height)
                            MadScience.Patterns.ResizeBitmapFast(ref Patterns[i], PatternsWidth[i], PatternsHeight[i]);
                    }

                BitmapData outputData = output.LockBits(new Rectangle(0, 0, baseTexture.Width, baseTexture.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                BitmapData baseTextureData = baseTexture.LockBits(new Rectangle(0, 0, baseTexture.Width, baseTexture.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                BitmapData maskData = mask.LockBits(new Rectangle(0, 0, baseTexture.Width, baseTexture.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                BitmapData[] patternData = new BitmapData[numPatterns];

                for (int i = 0; i < numPatterns; i++)
                    if (Patterns[i] != null)
                        patternData[i] = Patterns[i].LockBits(new Rectangle(0, 0, PatternsWidth[i], PatternsHeight[i]), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

                const int pixelSize = 4;

                byte[] byteMask = new byte[4];
                byteMask[0] = 2;
                byteMask[1] = 1;
                byteMask[2] = 0;
                byteMask[3] = 3;

                //process every pixel
                unsafe
                {
                    for (int y = 0; y < baseTexture.Height; y++)
                    {
                        byte* outputRow = (byte*)outputData.Scan0 + (y * outputData.Stride);
                        byte* baseTextureRow = (byte*)baseTextureData.Scan0 + (y * baseTextureData.Stride);
                        byte* maskRow = (byte*)maskData.Scan0 + (y * maskData.Stride);

                        byte*[] patternRows = new byte*[numPatterns];
                        for (int i = 0; i < numPatterns; i++)
                            if (Patterns[i] != null)
                                patternRows[i] = (byte*)patternData[i].Scan0 + ((y % PatternsHeight[i]) * patternData[i].Stride);

                        for (int x = 0; x < baseTexture.Width; x++)
                        {
                            int pixelLocation = x * pixelSize;

                            Color baseColor = Color.FromArgb(baseTextureRow[pixelLocation + 3], baseTextureRow[pixelLocation + 2], baseTextureRow[pixelLocation + 1], baseTextureRow[pixelLocation]);
                            if (baseColor.A != 0)
                            {
                                Color outColor = baseColor;

                                for (int i = 0; i < numPatterns; i++)
                                    if (Patterns[i] != null)
                                    {
                                        int xs = x % PatternsWidth[i];
                                        int pixelLocation2 = xs * pixelSize;
                                        Color patternColor = Color.FromArgb(patternRows[i][pixelLocation2 + 3], patternRows[i][pixelLocation2 + 2], patternRows[i][pixelLocation2 + 1], patternRows[i][pixelLocation2]);
                                        outColor = MadScience.Patterns.ColorOverlay(maskRow[pixelLocation + byteMask[i]], outColor, MadScience.Patterns.ColorMultiply(baseColor, patternColor));
                                    }
                                outputRow[pixelLocation] = (byte)outColor.B;
                                outputRow[pixelLocation + 1] = (byte)outColor.G;
                                outputRow[pixelLocation + 2] = (byte)outColor.R;
                                outputRow[pixelLocation + 3] = (byte)outColor.A;
                            }
                        }
                    }
                }
                output.UnlockBits(outputData);
                mask.UnlockBits(maskData);
                baseTexture.UnlockBits(baseTextureData);
            }
            else
            {
                output = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb);
            }
            return output;
        }
        private void button3_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";
            openFileDialog1.Filter = "DDS files|*.dds";

            openFileDialog1.ShowDialog();
            if (openFileDialog1.FileName != "")
            {
                txtSourceDDS.Text = openFileDialog1.FileName;

                Stream input = File.Open(txtSourceDDS.Text, FileMode.Open);

                DdsFileTypePlugin.DdsFile ddsFile = new DdsFileTypePlugin.DdsFile();
                ddsFile.Load(input);
                input.Close();

                pictureBox1.Image = ddsFile.Image();

                this.lockImage = true;
                chkShowRed.Enabled = chkShowRed.Checked = true;
                chkShowGreen.Enabled = chkShowGreen.Checked = true;
                chkShowBlue.Enabled = chkShowBlue.Checked = true;
                chkShowAlpha.Enabled = true;
                chkShowAlpha.Checked = false;
                button3.Enabled = true;
                button2.Enabled = false;

                this.lockImage = false;

                radioButton1.Enabled = true;
                radioButton2.Enabled = true;
                radioButton3.Enabled = true;
                radioButton4.Enabled = true;

                chkAllowDecal.Enabled = true;
                chkUseDefaultSpecular.Enabled = true;
                button4.Enabled = true;

            }
        }
Esempio n. 10
0
        /*
        private static void colourFill(Image mask, Image dst, Color c2, uint channel, bool blend)
        {
            FastPixel pixel = new FastPixel(mask as Bitmap);
            FastPixel pixel2 = new FastPixel(dst as Bitmap);
            pixel.Lock();
            pixel2.Lock();
            for (int i = 0; i < pixel.Width; i++)
            {
                for (int j = 0; j < pixel.Height; j++)
                {
                    Color color = pixel.GetPixel(i, j);
                    Color color2 = pixel2.GetPixel(i, j);
                    float num3 = 0f;
                    if (channel == uint.MaxValue)
                    {
                        num3 = 1f;
                    }
                    else if ((channel & 0xff000000) == 0xff000000)
                    {
                        num3 = 0.003921569f * color.R;
                    }
                    else if ((channel & 0xff0000) == 0xff0000)
                    {
                        num3 = 0.003921569f * color.G;
                    }
                    else if ((channel & 0xff00) == 0xff00)
                    {
                        num3 = 0.003921569f * color.B;
                    }
                    else if ((channel & 0xff) == 0xff)
                    {
                        num3 = 0.003921569f * color.A;
                    }
                    Color black = Color.Black;
                    if (!blend)
                    {
                        black = (num3 == 0f) ? color2 : Color.FromArgb(0xff, c2);
                    }
                    else
                    {
                        black = Color.FromArgb(0xff, Math.Max(0, Math.Min(0xff, (int)((color2.R + (color2.R * -num3)) + (((int)(c2.R * (0.003921569f * c2.A))) * num3)))), Math.Max(0, Math.Min(0xff, (int)((color2.G + (color2.G * -num3)) + (((int)(c2.G * (0.003921569f * c2.A))) * num3)))), Math.Max(0, Math.Min(0xff, (int)((color2.B + (color2.B * -num3)) + (((int)(c2.B * (0.003921569f * c2.A))) * num3)))));
                    }
                    pixel2.SetPixel(i, j, black);
                }
            }
            pixel.Unlock(false);
            pixel2.Unlock(true);
        }
        */
        /*
        private Image imagePreview(Image sourceImage)
        {
            Image destImage = new Bitmap(256, 256);
            Graphics.FromImage(destImage);

            Color white = Color.White;
            uint maxValue = 0;

            colourFill(sourceImage, destImage, lblBackgroundColour.BackColor, 0, false);

            if (chkShowRed.Checked)
            {
                maxValue = ((uint) ((((((uint) Convert.ToSingle(1.00)) * 0xff) << 0x18) + ((((uint) Convert.ToSingle(0.00) * 0xff) << 0x10)) + ((((uint) Convert.ToSingle(0.00)) * 0xff) << 8))) + (((uint) Convert.ToSingle(0.00)) * 0xff));
                white = Color.FromArgb(lblPalette1.BackColor.A, lblPalette1.BackColor.R, lblPalette1.BackColor.G, lblPalette1.BackColor.B);
                colourFill(sourceImage, destImage, white, maxValue, chkPalette1Blend.Checked);
            }
            if (chkShowGreen.Checked)
            {
                maxValue = ((0 * 0xff) << 0x18) + ((1 * 0xff) << 0x10) + ((0 * 0xff) << 8) + ((0 * 0xff));
                white = Color.FromArgb(lblPalette2.BackColor.A, lblPalette2.BackColor.R, lblPalette2.BackColor.G, lblPalette2.BackColor.B);
                colourFill(sourceImage, destImage, white, maxValue, chkPalette2Blend.Checked);
            }
            if (chkShowBlue.Checked)
            {
                maxValue = ((0 * 0xff) << 0x18) + ((0 * 0xff) << 0x10) + ((1 * 0xff) << 8) + ((0 * 0xff));
                white = Color.FromArgb(lblPalette3.BackColor.A, lblPalette3.BackColor.R, lblPalette3.BackColor.G, lblPalette3.BackColor.B);
                colourFill(sourceImage, destImage, white, maxValue, chkPalette3Blend.Checked);
            }
            if (chkShowAlpha.Checked)
            {
                maxValue = ((0 * 0xff) << 0x18) + ((0 * 0xff) << 0x10) + ((0 * 0xff) << 8) + ((1 * 0xff));
                white = Color.FromArgb(lblPalette4.BackColor.A, lblPalette4.BackColor.R, lblPalette4.BackColor.G, lblPalette4.BackColor.B);
                colourFill(sourceImage, destImage, white, maxValue, chkPalette4Blend.Checked);
            }

            return destImage;
        }
        */
        private void showDDSChannels()
        {
            if (!this.lockImage && txtSourceDDS.Text.Trim() != "")
            {

                Stream input = File.Open(txtSourceDDS.Text, FileMode.Open);

                DdsFileTypePlugin.DdsFile ddsFile = new DdsFileTypePlugin.DdsFile();
                ddsFile.Load(input);

                if (isPreviewImage)
                {
                    //pictureBox1.Image = imagePreview(ddsFile.Image(chkShowRed.Checked, chkShowGreen.Checked, chkShowBlue.Checked, chkShowAlpha.Checked, false));
                    Color colorbg = Color.Empty;
                    Color color1 = Color.Empty;
                    Color color2 = Color.Empty;
                    Color color3 = Color.Empty;
                    Color color4 = Color.Empty;
                    if (chkShowRed.Checked) color1 = lblPalette1.BackColor;
                    if (chkShowGreen.Checked) color2 = lblPalette2.BackColor;
                    if (chkShowBlue.Checked) color3 = lblPalette3.BackColor;
                    if (chkShowAlpha.Checked) color4 = lblPalette4.BackColor;

                    pictureBox1.Image = ddsFile.Image(colorbg, color1, color2, color3, color4);
                    //pictureBox1.Image = ddsFile.PreviewImage(chkShowRed.Checked, lblPalette1.BackColor, chkShowGreen.Checked, lblPalette2.BackColor, chkShowBlue.Checked, lblPalette3.BackColor, chkShowAlpha.Checked, lblPalette4.BackColor);

                }
                else
                {
                    pictureBox1.Image = ddsFile.Image(chkShowRed.Checked, chkShowGreen.Checked, chkShowBlue.Checked, chkShowAlpha.Checked, true);
                }

                input.Close();

            }
        }
        /*
         * public Stream findPattern(patternsFile pattern)
         * {
         *  if (File.Exists(pattern.subcategory))
         *  {
         *      Stream cast = File.Open(pattern.subcategory, FileMode.Open, FileAccess.Read, FileShare.Read);
         *      MadScience.Wrappers.Database castdb = new MadScience.Wrappers.Database(cast, true);
         *
         *      MadScience.Wrappers.ResourceKey temp = new MadScience.Wrappers.ResourceKey(pattern.texturename);
         *      Stream patternThumb = null;
         *
         *      try
         *      {
         *          patternThumb = castdb.GetResourceStream(temp);
         *      }
         *      catch (System.Collections.Generic.KeyNotFoundException ex)
         *      {
         *      }
         *      catch (Exception ex)
         *      {
         *          Helpers.logMessageToFile(ex.Message);
         *      }
         *      cast.Close();
         *
         *      if (patternThumb != null)
         *      {
         *          return patternThumb;
         *      }
         *  }
         *
         *  return Stream.Null;
         * }
         */
        /*
         * public patternsFile findPattern(string resKey)
         * {
         *  // Get pattern details from XML
         *  keyName patternXML = new keyName(resKey);
         *  patternsFile temp = new patternsFile();
         *
         *  bool hasMatch = false;
         *
         *  for (int i = 0; i < this.customPatterns.Items.Count; i++)
         *  {
         *      patternsFile pattern = this.customPatterns.Items[i];
         *
         *      if (MadScience.StringHelpers.ParseHex32(pattern.typeid) == patternXML.typeId && MadScience.StringHelpers.ParseHex32(pattern.groupid) == patternXML.groupId && MadScience.StringHelpers.ParseHex64(pattern.instanceid) == patternXML.instanceId)
         *      {
         *          hasMatch = true;
         *          temp = pattern;
         *          break;
         *      }
         *  }
         *
         *  if (!hasMatch)
         *  {
         *      for (int i = 0; i < this.patterns.Items.Count; i++)
         *      {
         *          patternsFile pattern = this.patterns.Items[i];
         *
         *          if (MadScience.StringHelpers.ParseHex32(pattern.typeid) == patternXML.typeId && MadScience.StringHelpers.ParseHex32(pattern.groupid) == patternXML.groupId && MadScience.StringHelpers.ParseHex64(pattern.instanceid) == patternXML.instanceId)
         *          {
         *              hasMatch = true;
         *              temp = pattern;
         *              break;
         *          }
         *      }
         *  }
         *
         *  return temp;
         * }
         */
        /*
         * public Image makePatternThumb(string resKey)
         * {
         *  return makePatternThumb(findPattern(resKey), null);
         * }
         */
        /*
         * public patternsFile pDetailsTopFile(patternDetails pDetails)
         * {
         *  patternsFile pFile = new patternsFile();
         *
         *  keyName pKey = new keyName(pDetails.key);
         *  pFile.casPart = pDetails.filename;
         *  pFile.typeid = "0x" + pKey.typeId.ToString("X8");
         *  pFile.groupid = "0x" + pKey.groupId.ToString("X8");
         *  pFile.instanceid = "0x" + pKey.instanceId.ToString("X16");
         *
         *  pFile.category = pDetails.category;
         *  pFile.color0 = pDetails.ColorP[0];
         *  pFile.color1 = pDetails.ColorP[1];
         *  pFile.color2 = pDetails.ColorP[2];
         *  pFile.color3 = pDetails.ColorP[3];
         *  pFile.color4 = pDetails.ColorP[4];
         *
         *  pFile.HBg = pDetails.HBg;
         *  pFile.SBg = pDetails.SBg;
         *  pFile.VBg = pDetails.VBg;
         *
         *  return pFile;
         * }
         */

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            panel1.Visible = false;

            label2.Text = "Loading patterns... Please wait...";
            label2.Refresh();

            numFound   = 0;
            horizontal = 0;
            vertical   = 0;

            ToolTip tt = new ToolTip();


            DdsFileTypePlugin.DdsFile ddsP = new DdsFileTypePlugin.DdsFile();

            if (comboBox1.Text == "* Custom")
            {
                for (int i = 0; i < this.customPatterns.Items.Count; i++)
                {
                    patternsFile pattern = this.customPatterns.Items[i];
                    //if (pattern.category == comboBox1.Text)
                    //{

                    numFound++;

                    PictureBox picBox = new PictureBox();
                    picBox.BackColor = System.Drawing.Color.White;
                    picBox.Name      = pattern.casPart;

                    string toolTip = pattern.category + "\\";
                    //if (pattern.subcategory != "")
                    //{
                    //toolTip += pattern.subcategory + "\\";
                    //}
                    toolTip += pattern.casPart;
                    tt.SetToolTip(picBox, toolTip);

                    // Find thumbnail
                    if (File.Exists(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png"))))
                    {
                        Stream tmpImage = File.OpenRead(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png")));
                        picBox.Image = Image.FromStream(tmpImage);
                        tmpImage.Close();
                    }
                    else
                    {
                        if (File.Exists(pattern.subcategory))
                        {
                            //if (pattern.typeid.StartsWith("0x")) pattern.typeid = pattern.typeid.Remove(0, 2);
                            //if (pattern.groupid.StartsWith("0x")) pattern.groupid = pattern.groupid.Remove(0, 2);
                            //if (pattern.instanceid.StartsWith("0x")) pattern.instanceid = pattern.instanceid.Remove(0, 2);

                            Stream patternXml = KeyUtils.searchForKey(pattern.key, pattern.subcategory);
                            if (StreamHelpers.isValidStream(patternXml))
                            {
                                Patterns.patternDetails pDetails = Patterns.parsePatternComplate(patternXml);
                                //Stream patternThumb = KeyUtils.searchForKey(pattern.texturename, pattern.subcategory);
                                //if (Helpers.isValidStream(patternThumb))
                                //{
                                //picBox.Image = Patterns.makePatternThumb(patternThumb, pDetails);
                                picBox.Image = Patterns.makePatternThumb(pDetails);
                                try
                                {
                                    picBox.Image.Save(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png")), System.Drawing.Imaging.ImageFormat.Png);
                                }
                                catch (Exception)
                                {
                                }
                                //}
                            }
                        }
                    }

                    addToPanel(picBox);
                    //}
                }
            }
            else
            {
                string s3root           = MadScience.Helpers.findSims3Root();
                string thumbnailPackage = Helpers.getGameSubPath(@"\GameData\Shared\Packages\FullBuild2.package");

                Console.WriteLine("Starting at: " + DateTime.Now.ToString());

                Stream cast = File.Open(Path.Combine(s3root, thumbnailPackage), FileMode.Open, FileAccess.Read, FileShare.Read);
                MadScience.Wrappers.Database castdb = new MadScience.Wrappers.Database(cast);

                Stream fullBuild0 = File.Open(Path.Combine(s3root, Helpers.getGameSubPath(@"\GameData\Shared\Packages\FullBuild0.package")), FileMode.Open, FileAccess.Read, FileShare.Read);
                MadScience.Wrappers.Database xmldb = new MadScience.Wrappers.Database(fullBuild0);


                for (int i = 0; i < this.patterns.Items.Count; i++)
                {
                    patternsFile pattern = this.patterns.Items[i];
                    if (pattern.category == comboBox1.Text)
                    {
                        numFound++;

                        PictureBox picBox = new PictureBox();
                        picBox.BackColor = System.Drawing.Color.White;
                        picBox.Name      = pattern.casPart;


                        string toolTip = pattern.category + "\\";
                        if (pattern.subcategory != "")
                        {
                            toolTip += pattern.subcategory + "\\";
                        }
                        toolTip += pattern.casPart;
                        tt.SetToolTip(picBox, toolTip);

                        // Find thumbnail
                        if (File.Exists(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png"))))
                        {
                            Stream tmpImage = File.OpenRead(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png")));
                            picBox.Image = Image.FromStream(tmpImage);
                            tmpImage.Close();
                        }
                        else
                        {
                            //Console.WriteLine(pattern.casPart);

                            Stream patternXml = KeyUtils.findKey(new MadScience.Wrappers.ResourceKey(pattern.key), 0, xmldb);
                            if (StreamHelpers.isValidStream(patternXml))
                            {
                                Patterns.patternDetails pDetails2 = Patterns.parsePatternComplate(patternXml);
                                //Stream patternThumb = KeyUtils.findKey(new MadScience.Wrappers.ResourceKey("key:00B2D882:00000000:" + StringHelpers.HashFNV64(pDetails2.name).ToString("X16")), 0, castdb);
                                //if (!Helpers.isValidStream(patternThumb))
                                //{
                                //    patternThumb = KeyUtils.findKey(new MadScience.Wrappers.ResourceKey(pDetails2.BackgroundImage), 0, castdb);
                                //}
                                //if (Helpers.isValidStream(patternThumb))
                                //{
                                picBox.Image = Patterns.makePatternThumb(pDetails2, castdb);
                                try
                                {
                                    picBox.Image.Save(Path.Combine(Application.StartupPath, Path.Combine("patterncache", pattern.casPart + ".png")), System.Drawing.Imaging.ImageFormat.Png);
                                }
                                catch (Exception)
                                {
                                }
                                //}
                            }
                        }

                        addToPanel(picBox);
                    }
                }

                Console.WriteLine("Stopping at: " + DateTime.Now.ToString());

                //dbpf = null;
                fullBuild0.Close();
                cast.Close();
                //castdb = null;
            }
            label2.Text      = numFound.ToString() + " patterns";
            panel1.Visible   = true;
            this.curCategory = comboBox1.SelectedIndex;
        }