コード例 #1
0
        public static unsafe void Scan(FileMap map, FileScanNode node)
        {
            using (ProgressWindow progress = new ProgressWindow(MainForm.Instance, "File Scanner", "Scanning for known file types, please wait...", true))
            {
                progress.TopMost = true;
                progress.Begin(0, map.Length, 0);

                byte *data = (byte *)map.Address;
                uint  i    = 0;
                do
                {
                    ResourceNode n = null;
                    DataSource   d = new DataSource(&data[i], 0);
                    if ((n = NodeFactory.GetRaw(d)) != null)
                    {
                        if (!(n is MSBinNode))
                        {
                            n.Initialize(node, d);
                            try
                            {
                                i += (uint)n.WorkingSource.Length;
                            }
                            catch
                            {
                            }
                        }
                    }
                    progress.Update(i + 1);
                }while (++i + 4 < map.Length);

                progress.Finish();
            }
        }
コード例 #2
0
ファイル: BRRESNode.cs プロジェクト: STulling/BrawlCrateNext
        public void ImportGIF(string file)
        {
            Action <object, DoWorkEventArgs> work = (object sender, DoWorkEventArgs e) =>
            {
                GifDecoder decoder = new GifDecoder();
                decoder.Read(file, null);
                e.Result = decoder;
            };
            Action <object, RunWorkerCompletedEventArgs> completed = (object sender, RunWorkerCompletedEventArgs e) =>
            {
                GifDecoder decoder = e.Result as GifDecoder;
                string     s       = Path.GetFileNameWithoutExtension(file);
                PAT0Node   p       = CreateResource <PAT0Node>(s);
                p._loop = true;
                p.CreateEntry();

                PAT0TextureNode      textureNode = p.Children[0].Children[0] as PAT0TextureNode;
                PAT0TextureEntryNode entry       = textureNode.Children[0] as PAT0TextureEntryNode;

                //Get the number of images in the file
                int frames = decoder.GetFrameCount();

                //The framecount will be created by adding up each image delay.
                float frameCount = 0;

                bool resized = false;
                int  w = 0, h = 0;
                Action <int, int> onResized = (newW, newH) =>
                {
                    if (resized != true)
                    {
                        w       = newW;
                        h       = newH;
                        resized = true;
                    }
                };

                using (TextureConverterDialog dlg = new TextureConverterDialog())
                {
                    using (ProgressWindow progress = new ProgressWindow(RootNode._mainForm, "GIF to PAT0 converter",
                                                                        "Converting, please wait...", true))
                    {
                        Bitmap prev = null;

                        progress.Begin(0, frames, 0);
                        for (int i = 0; i < frames; i++, entry = new PAT0TextureEntryNode())
                        {
                            if (progress.Cancelled)
                            {
                                break;
                            }

                            string name = s + "." + i;

                            dlg.ImageSource = name + ".";

                            using (Bitmap img = (Bitmap)decoder.GetFrame(i))
                            {
                                if (i == 0)
                                {
                                    dlg.LoadImages(img.Copy());
                                    dlg.Resized += onResized;
                                    if (dlg.ShowDialog(null, this) != DialogResult.OK)
                                    {
                                        return;
                                    }

                                    textureNode._hasTex = dlg.TextureData != null;
                                    textureNode._hasPlt = dlg.PaletteData != null;

                                    prev = img.Copy();
                                }
                                else
                                {
                                    //Draw the current image over the previous
                                    //This is because some GIFs use pixels of the previous frame
                                    //in order to compress the overall image data
                                    using (Graphics graphics = Graphics.FromImage(prev))
                                    {
                                        graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                        graphics.CompositingQuality = CompositingQuality.HighQuality;
                                        graphics.CompositingMode    = CompositingMode.SourceOver;
                                        graphics.SmoothingMode      = SmoothingMode.HighQuality;
                                        graphics.DrawImage(img, 0, 0, prev.Width, prev.Height);
                                    }

                                    dlg.LoadImages(prev.Copy());
                                    if (resized)
                                    {
                                        dlg.ResizeImage(w, h);
                                    }
                                    else
                                    {
                                        dlg.UpdatePreview();
                                    }

                                    dlg.EncodeSource();

                                    textureNode.AddChild(entry);
                                }
                            }

                            entry._frame = (float)Math.Round(frameCount, 2);
                            frameCount  += decoder.GetDelay(i) / 1000.0f * 60.0f;

                            if (textureNode._hasTex)
                            {
                                entry.Texture = name;
                            }

                            if (textureNode._hasPlt)
                            {
                                entry.Palette = name;
                            }

                            progress.Update(progress.CurrentValue + 1);
                        }

                        progress.Finish();
                        if (prev != null)
                        {
                            prev.Dispose();
                        }
                    }
                }

                p._numFrames = (ushort)(frameCount + 0.5f);
            };

            using (BackgroundWorker b = new BackgroundWorker())
            {
                b.DoWork             += new DoWorkEventHandler(work);
                b.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completed);
                b.RunWorkerAsync();
            }
        }
コード例 #3
0
        /**
         * Main file parser.  Reads GIF content blocks.
         */
        protected void ReadContents()
        {
            long offset = inStream.Position;

            //Scan through file and get the frame count
            frameCount = 0;

            // read GIF file content blocks
            bool done = false;

            while (!(done || Error()))
            {
                int code = Read();
                switch (code)
                {
                case 0x2C:     // image separator
                    SkipImage();
                    frameCount++;
                    break;

                case 0x21:
                    code = Read();
                    switch (code)
                    {
                    case 0xf9:         // graphics control extension
                        ReadGraphicControlExt();
                        break;

                    case 0xff:         // application extension
                        ReadBlock();
                        String app = "";
                        for (int i = 0; i < 11; i++)
                        {
                            app += (char)block[i];
                        }
                        if (app.Equals("NETSCAPE2.0"))
                        {
                            ReadNetscapeExt();
                        }
                        else
                        {
                            Skip();         // don't care
                        }
                        break;

                    default:
                        Skip();
                        break;
                    }
                    break;

                case 0x3b:
                    done = true;
                    break;

                case 0x00:
                    break;

                default:
                    status = STATUS_FORMAT_ERROR;
                    break;
                }
            }

            inStream.Position = offset;

            using (ProgressWindow p = new ProgressWindow(owner, "Decoding Image...", "Reading file, please wait...", false))
            {
                p.Begin(0, frameCount, 0);
                done = false;
                while (!(done || Error()))
                {
                    int code = Read();
                    switch (code)
                    {
                    case 0x2C:     // image separator
                        ReadImage();
                        p.Update(currentFrame);
                        break;

                    case 0x21:     // extension
                        code = Read();
                        switch (code)
                        {
                        case 0xf9:         // graphics control extension
                            ReadGraphicControlExt();
                            break;

                        case 0xff:         // application extension
                            ReadBlock();
                            String app = "";
                            for (int i = 0; i < 11; i++)
                            {
                                app += (char)block[i];
                            }
                            if (app.Equals("NETSCAPE2.0"))
                            {
                                ReadNetscapeExt();
                            }
                            else
                            {
                                Skip();         // don't care
                            }
                            break;

                        default:         // uninteresting extension
                            Skip();
                            break;
                        }
                        break;

                    case 0x3b:     // terminator
                        done = true;
                        break;

                    case 0x00:     // bad byte, but keep going and see what happens
                        break;

                    default:
                        status = STATUS_FORMAT_ERROR;
                        break;
                    }
                }
                p.Finish();
            }
        }
コード例 #4
0
        private void RenderToGIF(List <Image> images, string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            string outPath = "";

            try
            {
                outPath = path;
                if (!Directory.Exists(outPath))
                {
                    Directory.CreateDirectory(outPath);
                }

                DirectoryInfo dir   = new DirectoryInfo(outPath);
                FileInfo[]    files = dir.GetFiles();
                int           i     = 0;
                string        name  = "Animation";
Top:
                foreach (FileInfo f in files)
                {
                    if (f.Name == name + i + ".gif")
                    {
                        i++;
                        goto Top;
                    }
                }

                outPath += "\\" + name + i + ".gif";
            }
            catch
            {
                // ignored
            }

            AnimatedGifEncoder e = new AnimatedGifEncoder();

            e.Start(outPath);
            e.SetDelay(1000 / (int)PlaybackPanel.numFPS.Value);
            e.SetRepeat(0);
            e.SetQuality(10);
            using (ProgressWindow progress = new ProgressWindow(this, "GIF Encoder", "Encoding, please wait...", true))
            {
                progress.TopMost = true;
                progress.Begin(0, images.Count, 0);
                for (int i = 0, count = images.Count; i < count; i++)
                {
                    if (progress.Cancelled)
                    {
                        break;
                    }

                    //GIF transparency support is pretty poor, flickers a lot
                    //e.SetTransparent(ModelPanel.CurrentViewport.BackgroundColor);

                    e.AddFrame(images[i]);
                    progress.Update(progress.CurrentValue + 1);
                }

                progress.Finish();
                e.Finish();
            }

            _loop = PlaybackPanel.chkLoop.Checked;

            if (MessageBox.Show(this,
                                "Animated GIF successfully saved to \"" + outPath.Replace("\\", "/") + "\".\nOpen the folder now?",
                                "GIF saved", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Process.Start("explorer.exe", path);
            }
        }
コード例 #5
0
        public void copyIconsToSelcharacter2()
        {
            string fileToSaveTo = null;

            ResourceNode s2 = null;

            if (common5 != null)
            {
                s2 = common5.FindChild("sc_selcharacter2_en", false);
            }
            else if (sc_selmap != null)
            {
                if (File.Exists("../../menu2/sc_selcharacter2.pac"))
                {
                    fileToSaveTo = "../../menu2/sc_selcharacter2.pac";
                    s2           = TempFiles.MakeTempNode(fileToSaveTo);
                }
                else if (File.Exists("../../menu2/sc_selcharacter2_en.pac"))
                {
                    fileToSaveTo = "../../menu2/sc_selcharacter2_en.pac";
                    s2           = TempFiles.MakeTempNode(fileToSaveTo);
                }
            }

            if (s2 == null)
            {
                return;
            }

            ResourceNode md0  = s2.FindChild("MenuRule_en/ModelData[0]", false);
            MSBinNode    md1  = s2.FindChild("MenuRule_en/MiscData[1]", false) as MSBinNode;
            ResourceNode md80 = sc_selmap.FindChild("MiscData[80]", false);

            if (md0 == null || md80 == null)
            {
                return;
            }

            Image[] icons        = new Image[41];
            Image[] frontstnames = new Image[41];
            for (int i = 1; i < 60; i++)
            {
                if (i == 32)
                {
                    i = 50;
                }
                int    sssPos     = StageIDMap.sssPositionForSelcharacter2Icon(i);
                string nameSelmap = BestSSS[sssPos].Item2.ToString("D2");
                icons[sssPos]        = ((md80.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelmap, false) as TEX0Node).GetImage(0));
                frontstnames[sssPos] = ((md80.FindChild("Textures(NW4R)/MenSelmapFrontStname." + nameSelmap, false) as TEX0Node).GetImage(0));
            }

            var d = new RandomSelectEditNamesDialog(md1._strings, icons, frontstnames);

            d.Message = "When finished, press OK to continue.";
            if (d.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < md1._strings.Count; i++)
                {
                    md1._strings[i] = d[i].ToString();
                }
            }
            else
            {
                return;
            }

            using (ProgressWindow w = new ProgressWindow()
            {
                CanCancel = false
            }) {
                w.Begin(0, 60, 0);
                for (int i = 1; i < 60; i++)
                {
                    if (i == 32)
                    {
                        i = 50;
                    }

                    int      sssPos            = StageIDMap.sssPositionForSelcharacter2Icon(i);
                    string   tempFile1         = TempFiles.Create(".tex0");
                    string   tempFile2         = TempFiles.Create(".plt0");
                    string   nameSelcharacter2 = i.ToString("D2");
                    string   nameSelmap        = BestSSS[sssPos].Item2.ToString("D2");
                    TEX0Node iconFrom          = md80.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelmap, false) as TEX0Node;
                    TEX0Node iconTo            = md0.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelcharacter2, false) as TEX0Node;
                    var      palFrom           = md80.FindChild("Palettes(NW4R)/MenSelmapIcon." + nameSelmap, false);
                    var      palTo             = md0.FindChild("Palettes(NW4R)/MenSelmapIcon." + nameSelcharacter2, false);
                    if (iconFrom != null && iconTo != null && palFrom != null && palTo != null)
                    {
                        iconFrom.Export(tempFile1);
                        iconTo.Replace(tempFile1);
                        palFrom.Export(tempFile2);
                        palTo.Replace(tempFile2);
                    }

                    TEX0Node prevbase    = md80.FindChild("Textures(NW4R)/MenSelmapPrevbase." + nameSelmap, false) as TEX0Node;
                    TEX0Node stageswitch = md0.FindChild("Textures(NW4R)/MenStageSwitch." + nameSelcharacter2, false) as TEX0Node;
                    if (prevbase != null && stageswitch != null)
                    {
                        Bitmap thumbnail = new Bitmap(112, 56);
                        using (Graphics g = Graphics.FromImage(thumbnail)) {
                            g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            g.DrawImage(prevbase.GetImage(0), 0, -28, 112, 112);
                        }
                        stageswitch.Replace(thumbnail);
                    }

                    w.Update(i);
                }
            }

            if (fileToSaveTo != null)
            {
                s2.Export(fileToSaveTo);
            }
        }
コード例 #6
0
ファイル: ButtonClick.cs プロジェクト: 0000duck/brawltools
        public void RenderToGIF(Image[] images)
        {
            string outPath = "";

Start:
            if (!String.IsNullOrEmpty(ScreenCapBgLocText.Text))
            {
                try
                {
                    outPath = ScreenCapBgLocText.Text;
                    if (!Directory.Exists(outPath))
                    {
                        Directory.CreateDirectory(outPath);
                    }

                    DirectoryInfo dir   = new DirectoryInfo(outPath);
                    FileInfo[]    files = dir.GetFiles();
                    int           i     = 0;
                    string        name  = "Animation";
Top:
                    foreach (FileInfo f in files)
                    {
                        if (f.Name == name + i + ".gif")
                        {
                            i++;
                            goto Top;
                        }
                    }
                    outPath += "\\" + name + i + ".gif";
                }
                catch { }
            }
            else
            {
                ScreenCapBgLocText.Text = Application.StartupPath + "\\ScreenCaptures";
                goto Start;
            }

            AnimatedGifEncoder e = new AnimatedGifEncoder();

            e.Start(outPath);
            e.SetDelay(1000 / (int)pnlPlayback.numFPS.Value);
            e.SetRepeat(0);
            e.SetQuality(1);
            using (ProgressWindow progress = new ProgressWindow(this, "GIF Encoder", "Encoding, please wait...", true))
            {
                progress.TopMost = true;
                progress.Begin(0, images.Length, 0);
                for (int i = 0, count = images.Length; i < count; i++)
                {
                    if (progress.Cancelled)
                    {
                        break;
                    }

                    e.AddFrame(images[i]);
                    progress.Update(progress.CurrentValue + 1);
                }
                progress.Finish();
                e.Finish();
            }

            if (InterpolationEditor != null)
            {
                InterpolationEditor.Enabled = true;
            }
            ModelPanel.Enabled = true;
            Enabled            = true;

            MessageBox.Show("GIF successfully saved to " + outPath.Replace("\\", "/"));
        }
コード例 #7
0
        /// <summary>
        /// Creates a BRSTM from the input file.
        ///
        /// Note: while this function handles the conversion to WAV and the modification of channels/sample rate/etc.,
        /// the conversion from WAV to BRSTM is handled by the build method.
        /// </summary>
        /// <param name="mainWindow">Can be null, or a ProgressBox that can be updated by this method and other methods that call it.</param>
        /// <param name="opts">An OptionSet to read parameters from.</param>
        /// <param name="outputFile">The file to output to.</param>
        ///
        public bool create(TwoLineStatusBox mainWindow, OptionSet opts, string outputFile)
        {
            int newRate;

            if (opts.convertRate == OptionSet.RATE_RELATIVE)
            {
                newRate = (int)Math.Round(opts.rateFactor * this.SampleRate);
                if (newRate < opts.minimumRate)
                {
                    newRate = opts.minimumRate;                     // Change to the minimum rate - this only needs to be checked if the rate is defined as a fraction
                }
            }
            else if (opts.convertRate == OptionSet.RATE_ABSOLUTE)
            {
                newRate = opts.defaultRate;
            }
            else
            {
                newRate = this.SampleRate;
            }

            string basename = Path.GetFileNameWithoutExtension(input).Replace(" ", "_");

            ProgressWindow progressWindow = new ProgressWindow(mainWindow, outputFile, "Working...", false);

            progressWindow.Begin(0, 19245, 0);
            progressWindow.Location = mainWindow.PointToScreen(new Point(0, 100));

            if (mainWindow != null)
            {
                mainWindow.changeStatus("Current file: " + basename);

                if (newRate >= this.SampleRate)
                {
                    newRate = this.SampleRate;                     // This will keep the below code from changing the sample rate for this Music.
                }

                int channels = this.Channels;

                String message = "";

                if (this.Looping)
                {
                    message = message + "loop: " + this.LoopStart + "-" + this.Length + ", ";
                }
                if (opts.convertToMono && (channels > 1))
                {
                    message = message + "to mono, ";
                }
                if (opts.convertRate != OptionSet.RATE_NO_CONVERSION && this.SampleRate != newRate)
                {
                    message = message + "new rate: " + newRate + ", ";
                }
                if (opts.ampType == OptionSet.AMPLITUDE_TYPE)
                {
                    message = message + "amp: " + opts.ampAmount + "x, ";
                }
                else if (opts.ampType == OptionSet.DB_TYPE)
                {
                    message = message + "amp: " + opts.ampAmount + " dB, ";
                }
                else if (opts.ampType == OptionSet.MAX_AMP_WITHOUT_CLIPPING)
                {
                    message = message + "max amp w/o clipping, ";
                }
                if (message.Count() > 2)                                 // do this if the message is not empty
                {
                    message = message.Substring(0, message.Count() - 2); // remove last comma and space
                    mainWindow.changeMessage(message);
                }
                else
                {
                    mainWindow.changeMessage("");
                }
            }

            try {             // this is where the magic happens!
                progressWindow.Caption = "Creating temporary WAV file...";
                progressWindow.Update();
                if (wavFile == null)
                {
                    convertToWav();
                }

                progressWindow.Caption = "Converting to mono...";
                progressWindow.Update(4971);

                /**
                 * WAV files after stereo/mono conversion.
                 */
                string step1wav;
                if (channels == 1)                   // already mono
                {
                    step1wav = wavFile;
                }
                else
                {
                    if (channels > 2)
                    {
                        Console.WriteLine("This stream has more than two channels. Only using first two.");
                    }
                    step1wav = Shared.TMP_DIR + Path.DirectorySeparatorChar + "step1_" + basename + ".wav";
                    bool b;
                    if (opts.convertToMono)                   // not mono; converting to mono
                    {
                        b = combineToMono(wavFile, step1wav); // this function uses only the first two channels
                    }
                    else                                      // not mono; converting to stereo if necessary
                    {
                        b = combineToStereo(wavFile, step1wav);
                    }
                    if (b)
                    {
                        File.Delete(wavFile);
                        wavFile = null;
                    }
                    else
                    {
                        throw new MusicFileException("convertToMono or convertToStereo failed.");
                    }
                }

                progressWindow.Caption = "Converting sample rate...";
                progressWindow.Update(5610);

                /**
                 * WAV files after sample rate conversion.
                 */
                string step2wav;
                if (opts.convertRate != OptionSet.RATE_NO_CONVERSION && newRate != this.SampleRate)
                {
                    step2wav = Shared.TMP_DIR + Path.DirectorySeparatorChar + "step2_" + basename + ".wav";
                    Process rate = new SoXProcess();
                    rate.StartInfo.Arguments += step1wav + " -r " + newRate + " " + step2wav;
                    rate.Start();
                    rate.WaitForExit();
                    File.Delete(step1wav);
                }
                else
                {
                    step2wav = step1wav;
                }

                progressWindow.Caption = "Amplifying audio...";
                progressWindow.Update(7815);

                /**
                 * WAV files after amplification.
                 */
                string   step3wav;
                bool     amplify = true;
                String[] soxOpts = new String[2];
                if (opts.ampType == OptionSet.NO_AMP)
                {
                    amplify = false;
                }
                else if (opts.ampType == OptionSet.AMPLITUDE_TYPE)
                {
                    soxOpts[0] = "vol";
                    soxOpts[1] = opts.ampAmount + "amplitude";
                }
                else if (opts.ampType == OptionSet.DB_TYPE)
                {
                    soxOpts[0] = "vol";
                    soxOpts[1] = opts.ampAmount + "dB";
                }
                else if (opts.ampType == OptionSet.MAX_AMP_WITHOUT_CLIPPING)
                {
                    soxOpts[0] = "gain";
                    soxOpts[1] = "-n";
                }
                if (amplify)
                {
                    step3wav = Shared.TMP_DIR + Path.DirectorySeparatorChar + "step3_" + basename + ".wav";
                    Process amp = new SoXProcess();
                    amp.StartInfo.UseShellExecute       = false;
                    amp.StartInfo.RedirectStandardError = true;
                    amp.StartInfo.Arguments            += step2wav + " " + step3wav + " " + soxOpts[0] + " " + soxOpts[1];
                    amp.Start();
                    amp.WaitForExit();
                    File.Delete(step2wav);
                }
                else
                {
                    step3wav = step2wav;
                }

                // make the new BRSTMs
                double ratio        = (double)newRate / SampleRate;
                int    newLoopStart = (int)(LoopStart * ratio);
                int    newLength    = (int)(Length * ratio);

                progressWindow.Caption = "Creating output...";
                progressWindow.Update(8181);
                opts.outputFormat.build(progressWindow, new SubRangeProgressTracker(8181, 19245, progressWindow),
                                        step3wav, outputFile, Looping, newLoopStart, newLength, opts.loopTrim);

                progressWindow.Caption = "Deleting temporary files...";
                progressWindow.Update(19245);
                File.Delete(step3wav);

                progressWindow.Finish();
                return(true);
            } catch (Exception e) {
                // Exceptions are caught here, and then false is returned to the main method in Program.cs.
                Shared.errorDialog(e.Message);
                return(false);
            }
        }