Exemplo n.º 1
0
        public static bool Read(int skin, RAFFileListEntry file, ref Dictionary <String, String> animations, Logger logger)
        {
            bool result = true;

            logger.Event("Parsing animation list: " + file.FileName);

            try
            {
                // Get the data from the archive
                MemoryStream myInput = new MemoryStream(file.GetContent());
                StreamReader reader  = new StreamReader(myInput);

                ParseAnimations(skin, reader, ref animations);

                reader.Close();
                myInput.Close();
            }
            catch
            {
                logger.Error("Failed to parse animation list: " + file.FileName);

                result = false;
                animations.Clear();
            }

            return(result);
        }
Exemplo n.º 2
0
        public static bool Read(RAFFileListEntry file, ref InibinFile data, Logger logger)
        {
            bool result = true;

            logger.Event("Reading inibin: " + file.FileName);

            try
            {
                // Get the data from the archive
                MemoryStream myInput = new MemoryStream(file.GetContent());
                result = ReadCharacterInibin(myInput, ref data, logger);

                int    end       = file.FileName.LastIndexOf("/");
                String directory = file.FileName.Substring(0, end);
                String archive   = file.RAFArchive.RAFFilePath;
                archive = archive.Replace("\\", "/");
                end     = archive.LastIndexOf("/");
                archive = archive.Substring(0, end);

                data.directory = new DirectoryInfo(archive + "/" + directory);
                myInput.Close();
            }
            catch (Exception e)
            {
                logger.Error("Unable to open memory stream: " + file.FileName);
                logger.Error(e.Message);
                result = false;
            }

            return(result);
        }
Exemplo n.º 3
0
        public LOLModel()
        {
            skn     = null;
            skl     = null;
            texture = null;

            animationList = String.Empty;
            animations    = new Dictionary <String, RAFFileListEntry>();

            skinNumber = -1;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Read in binary .dds file from RAF.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="data">The contents of the file are stored in here.</param>
        /// <returns></returns>
        public static bool Read(RAFFileListEntry file, ref Bitmap bitmap, Logger logger)
        {
            bool result = true;

            logger.Event("Reading dds: " + file.FileName);

            try
            {
                // Create image.
                int[] images = new int[1];
                Il.ilGenImages(1, images);

                // Bind image.
                Il.ilBindImage(images[0]);

                // Load the image data into DevIL.
                byte[] data = file.GetContent();
                result = Il.ilLoadL(Il.IL_DDS, data, data.Length);
                if (result == true)
                {
                    int width  = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
                    int height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);;

                    // Create the bitmap.
                    bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                    Rectangle rect = new Rectangle(0, 0, width, height);

                    // Store the DevIL image data into the bitmap.
                    BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

                    Il.ilConvertImage(Il.IL_BGRA, Il.IL_UNSIGNED_BYTE);
                    Il.ilCopyPixels(0, 0, 0, width, height, 1, Il.IL_BGRA, Il.IL_UNSIGNED_BYTE, bitmapData.Scan0);

                    bitmap.UnlockBits(bitmapData);
                }

                // Free image.
                Il.ilDeleteImages(1, images);

                if (result == false)
                {
                    throw new System.Exception("Unable to load image data.");
                }
            }
            catch (Exception e)
            {
                logger.Error("Unable to open dds file: " + file.FileName);
                logger.Error(e.Message);
                result = false;
            }

            return(result);
        }
Exemplo n.º 5
0
        private bool ExpandRAF(string fileDirectory)
        {
            LogTextBox("Loading RAF Packages in " + fileDirectory);
            var list = new RAFMasterFileList(fileDirectory);

            LogTextBox("Expanding RAF packages. This will take a while (~20-30 minutes)...");
            LogTextBox(
                "During this time computer performance may be affected. While patching, running applications should be closed or not in-use");
            int i = 0;

            foreach (var x in list.FileDictFull)
            {
                string           FileLastWritten = string.Empty;
                RAFFileListEntry RAFFile         = x.Value[0];
                string           n = Path.Combine(Client.ExecutingDirectory, "RADS", "lol_game_client");
                foreach (string directories in RAFFile.FileName.Split('/'))
                {
                    if (!directories.Contains('.'))
                    {
                        if (!Directory.Exists(Path.Combine(n, directories)))
                        {
                            Directory.CreateDirectory(Path.Combine(n, directories));
                        }

                        n = Path.Combine(n, directories);
                    }
                    else
                    {
                        try
                        {
                            var writer = new BinaryWriter(File.OpenWrite(Path.Combine(n, directories)));

                            // Writer raw data
                            writer.Write(RAFFile.GetContent());
                            writer.Flush();
                            writer.Close();
                            FileLastWritten = Path.Combine(n, directories);
                        }
                        catch
                        {
                            LogTextBox("Unable to write " + Path.Combine(n, directories));
                        }
                    }
                }
                LogTextBox("(" + i + "/" + list.FileDictFull.Count + ") " +
                           ((i / (decimal)list.FileDictFull.Count) * 100).ToString("N2") + "%");
                i += 1;
            }
            return(true);
        }
        /// <summary>
        /// When a RafContentView node is double clicked, extract and view its content
        /// </summary>
        void rafContentView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            RAFInMemoryFileSystemObject node = (RAFInMemoryFileSystemObject)e.Node;
            string nodeInternalPath          = node.GetRAFPath();

            if (node.GetFSOType() == RAFFSOType.FILE)
            {
                //We have double clicked a file... find out what file it was
                List <RAFFileListEntry> entries = rafManager.Archives.Where(
                    (Func <RAFArchive, bool>) delegate(RAFArchive arc)
                {
                    return(arc.GetID().ToLower() == node.GetTopmostParent().Name);
                }
                    ).First().GetDirectoryFile().GetFileList().GetFileEntries();

                //Find the RAF File entry that corresponds to the clicked file...
                RAFFileListEntry entry = entries.Where(
                    (Func <RAFFileListEntry, bool>) delegate(RAFFileListEntry theEntry)
                {
                    return(theEntry.FileName == nodeInternalPath);
                }
                    ).First();

                //Now select a viewer to use for the file.
                //Unnecessary for the most part, can be enabled in the future: if (entry.FileSize < 10000 || //If > 200, ask, then continue MessageBox.Show("This file is quite large ({0} bytes).  Sure you want to read it?".F(entry.FileSize), "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)

                if (entry.FileName.ToLower().EndsWith("dds"))
                {
                    ShowDirectDrawSurface(entry.GetContent());
                }
                else if (entry.FileName.ToLower().EndsWith("inibin") || entry.FileName.ToLower().EndsWith("troybin"))
                {
                    ShowInibinFile(this.baseTitle + " - inibin/troybin view - " + nodeInternalPath, entry.GetContent());
                }
                else if (entry.FileName.EndsWithAny(new string[] { ".cfg", ".ini", ".txt", ".log", ".list", ".xml" }))
                {
                    ShowEditableTextFile(rafManager.ResolveRAFPathToEntry(node.GetTopmostParent().Text + "/" + node.GetRAFPath()));
                }
                else if (entry.FileName.EndsWithAny(new string[] { ".bmp", ".jpg" }))
                {
                    new BitmapViewer("Bitmap Viewer", entry.GetContent()).Show();
                }
                else //If all else fails, just use the binary viewer
                {
                    ShowBinaryFile(this.baseTitle + " - " + nodeInternalPath, entry.GetContent());
                }
            }
        }
Exemplo n.º 7
0
        public Tuple <IoResult, byte[]> ReadAllBytesInternal(IFileSystemHandle handle)
        {
            var internalHandle = handle as InternalHandle;

            if (internalHandle == null || internalHandle.State == HandleState.Invalidated || internalHandle.State == HandleState.Disposed)
            {
                return(new Tuple <IoResult, byte[]>(IoResult.InvalidHandle, null));
            }

            var asFile = internalHandle.Node as ReleaseManifestFileEntry;

            if (asFile == null)
            {
                // we have a directory
                return(new Tuple <IoResult, byte[]>(IoResult.InvalidOperation, null));
            }

            IReadOnlyList <RiotArchive> archives;

            try {
                archives = GetArchivesOrNull(asFile.ArchiveId);
            } catch (ArchiveNotFoundException) {
                return(new Tuple <IoResult, byte[]>(IoResult.Unavailable, null));
            }

            RAFFileListEntry entry = null;

            foreach (var archive in archives)
            {
                entry = archive.GetDirectoryFile().GetFileList().GetFileEntryOrNull(internalHandle.Node.GetPath());
                if (entry != null)
                {
                    break;
                }
            }
            if (entry == null)
            {
                return(new Tuple <IoResult, byte[]>(IoResult.NotFound, null));
            }

            return(new Tuple <IoResult, byte[]>(IoResult.Success, entry.GetContent()));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Read in binary .skn file from RAF.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="data">The contents of the file are stored in here.</param>
        /// <returns></returns>
        public static bool Read(RAFFileListEntry file, ref SKNFile data, Logger logger)
        {
            bool result = true;

            logger.Event("Reading skn: " + file.FileName);

            try
            {
                // Get the data from the archive
                MemoryStream myInput = new MemoryStream(file.GetContent());
                result = ReadBinary(myInput, ref data, logger);
                myInput.Close();
            }
            catch (Exception e)
            {
                logger.Error("Unable to open memory stream: " + file.FileName);
                logger.Error(e.Message);
                result = false;
            }

            return(result);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Instantiates a TextViewer form which displays a string
        /// </summary>
        /// <param name="title">Title of the window</param>
        /// <param name="content">Content displayed</param>
        public TextViewer(RAFFileListEntry fileEntry)
        {
            InitializeComponent();
            this.fileEntry = fileEntry;
            string content = Encoding.ASCII.GetString(fileEntry.GetContent());

            this.Text           = defaultTitle = "Text Viewer - " + fileEntry.FileName;
            this.contentTB.Text = content;

            this.Load += delegate(object sender, EventArgs e)
            {
                if (lastSize != Size.Empty)
                {
                    Size = lastSize;
                }
                if (lastLocation != Point.Empty)
                {
                    Location = lastLocation;
                }
            };

            this.FormClosing += new FormClosingEventHandler(TextViewer_FormClosing);
        }
Exemplo n.º 10
0
        public int ReadFile(string filename, byte[] buffer, ref uint readBytes, long offset, DokanFileInfo info)
        {
            Console.WriteLine("RF: " + filename + ", off" + offset + ", len" + buffer.Length);

            RAFInMemoryFileSystemObject fso = rafManager.ResolveRAFPathTOFSO(filename);

            Console.WriteLine("->FSO NULL: " + (fso == null));
            if (fso == null)
            {
                return(-DokanNet.ERROR_FILE_NOT_FOUND);
            }
            else
            {
                RAFFileListEntry entry   = rafManager.ResolveRAFPathToEntry(fso.GetRAFPath(true));
                byte[]           content = entry.GetContent();

                readBytes = Math.Min((uint)(content.Length - offset), (uint)buffer.Length);

                Array.Copy(content, offset, buffer, 0, readBytes);
                Console.WriteLine("-> " + readBytes + " bytes read");
                return(0);
            }
            //throw new NotImplementedException();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Load texture from RAF.
        /// </summary>
        /// <param name="file">The RAF file entry of the texture.</param>
        /// <param name="target">Only supports 2D.</param>
        /// <returns></returns>
        public bool Create(RAFFileListEntry file, TextureTarget target, SupportedImageEncodings encoding, Logger logger)
        {
            bool result = true;

            this.target = target;

            // Hacky sanity check
            if (target != TextureTarget.Texture2D)
            {
                return(false);
            }

            GL.Enable(EnableCap.Texture2D);
            GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

            // Create a System.Drawing.Bitmap.
            Bitmap bitmap = null;

            if (encoding == SupportedImageEncodings.DDS)
            {
                // Special case.
                result = DDSReader.Read(file, ref bitmap, logger);
            }
            else
            {
                // Normal case.
                result = CreateBitmap(file.GetContent(), ref bitmap);
            }

            // Pass the Bitmap into OpenGL.
            if (result == true &&
                bitmap != null)
            {
                result = CreateTexture(bitmap, target);
            }

            if (result == true)
            {
                // Set up texture parameters.
                GL.TexEnv(TextureEnvTarget.TextureEnv,
                          TextureEnvParameter.TextureEnvMode,
                          (Int32)TextureEnvModeCombine.Modulate);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureMinFilter,
                                (Int32)TextureMinFilter.Linear);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureMagFilter,
                                (Int32)TextureMagFilter.Linear);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureWrapS,
                                (Int32)TextureWrapMode.Repeat);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureWrapT,
                                (Int32)TextureWrapMode.Repeat);
            }

            return(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Todo: this needs to be modularized
        /// </summary>
        /// <param name="lines"></param>
        /// <param name="startLine"></param>
        /// <param name="isInitializerCall"></param>
        /// <param name="multilineExec"></param>
        /// <returns></returns>
        private int ProcessToEndStatement(string[] lines, int startLine, bool isInitializerCall, bool multilineExec)
        {
            int i = startLine;

            for (; i < lines.Length && lines[i].Trim().ToUpper() != "END";)
            {
                Console.WriteLine("ProcessToEndStatement @ ln" + i);
                string   line      = lines[i].Trim();
                string[] lineParts = line.QASS(' ');

                if (lineParts.Length == 0)
                {
                    i++;
                }
                else
                {
                    switch (lineParts[0].ToUpper())
                    {
                    case "SET":
                        string varName  = lineParts[1].Trim();
                        string varValue = lineParts[2];

                        Console.WriteLine("SETTING VARIABLE " + varName + " TO " + varValue);
                        if (!variables.ContainsKey(varName))
                        {
                            variables.Add(varName, varValue);
                        }
                        else
                        {
                            variables[varName] = varValue;
                        }
                        i++;
                        break;

                    case "OPTIONS":
                        i = ProcessOptionsBlock(lines, i) + 1;
                        break;

                    case "BACKUP_ONCE":
                    {
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("BACKUP_ONCE invalid syntax.  Expected: 'BACKUP_ONCE rafPath'.  ERROR @ ln " + i);
                        }

                        string rafFilePath = ResolveVariableToValue(lineParts[1].Trim());
                        Console.WriteLine("RAF FILE PATH: " + rafFilePath);
                        Console.WriteLine(variables.ContainsKey(rafFilePath));
                        string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + rafFilePath.Replace("/", "_");
                        if (File.Exists(fileBackupLoc))
                        {
                            Console.WriteLine("BACKUP_ONCE called when backup already created.  Ignoring command @ ln " + i);
                        }
                        else
                        {
                            RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(rafFilePath);
                            if (entry == null)
                            {
                                throw new Exception("BACKUP_ONCE: Entry '" + rafFilePath + "' did NOT exist, or could NOT be found. @ ln " + i + "\r\n" +
                                                    "Correct Syntax: BACKUP_ONCE [full raf path including archive]\r\n" +
                                                    "Ex: BACKUP_ONCE 0.0.0.25/DATA/CFG/defaults/Game.cfg");
                            }
                            else
                            {
                                Console.WriteLine("Backing up to " + fileBackupLoc);
                                Util.PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                            }
                        }
                        i++;
                        break;
                    }

                    case "INI_SET":
                    {
                        if (lineParts.Length < 4)
                        {
                            throw new Exception("INI_SET invalid syntax.  Expected: 'INI_SET RAFPath Section.Key value'.  ERROR @ ln " + i);
                        }
                        string rafPath       = ResolveVariableToValue(lineParts[1]);
                        string iniSectionKey = ResolveVariableToValue(lineParts[2]);
                        string newValue      = ResolveVariableToValue(lineParts[3]);

                        string[] sectionKeyParts = iniSectionKey.Split(".");
                        if (sectionKeyParts.Length != 2)
                        {
                            throw new Exception("Section.Key should only have 1 period in it.  ERROR @ ln " + i);
                        }
                        string iniSection = sectionKeyParts[0];
                        string iniKey     = sectionKeyParts[1];

                        RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(rafPath);
                        if (entry == null)
                        {
                            throw new Exception("BACKUP_ONCE: Entry '" + rafPath + "' did NOT exist, or could NOT be found. @ ln " + i);
                        }
                        else
                        {
                            Console.WriteLine("INI_SET: Section:{0}; Key:{1}; Value:{2};".F(iniSection, iniKey, newValue));
                            //extract it
                            string tempPath = Environment.CurrentDirectory + "/temp" + DateTime.Now.ToFileTime() + ".ini";
                            File.WriteAllBytes(tempPath, entry.GetContent());
                            IniFile iniFile = new IniFile(tempPath);
                            iniFile.IniWriteValue(iniSection, iniKey, newValue);

                            //write it again
                            entry.RAFArchive.InsertFile(
                                entry.FileName, File.ReadAllBytes(tempPath), null
                                );

                            //delete temp file
                            File.Delete(tempPath);
                        }
                        i++;
                        break;
                    }

                    case "PACKTIME":
                        if (isInitializerCall)
                        {
                            //We're done reading, since we're just running the initializer
                            //Store the PC of the packtime declaration
                            Console.WriteLine("Encountered PACKTIME command.  In Initializer call, skipping.");
                            packtimeCodeStartIndex = i;
                            i = FindNextEndOnSameLevel(lines, i) + 1;
                        }
                        else
                        {
                            //We're running the packtime code
                            i = ProcessToEndStatement(lines, i + 1, false);
                            Console.WriteLine("End of PACKTIME: " + i);
                            i++;
                            return(i);    //Return, as this is ALWAYS called by this.RunPacktimeCommand()
                        }
                        break;

                    case "RESTORETIME":
                        if (isInitializerCall)
                        {
                            //We're done reading, since we're just running the initializer
                            //Store the PC of the packtime declaration
                            Console.WriteLine("Encountered RESTORETIME command.  In Initializer call, returning.");
                            restoretimeCodeStartIndex = i;
                            i = FindNextEndOnSameLevel(lines, i) + 1;
                        }
                        else
                        {
                            //We're running the packtime code
                            i = ProcessToEndStatement(lines, i + 1, false) + 1;
                        }
                        break;

                    case "PACK":
                    {
                        Console.WriteLine("PACK COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("PACK invalid syntax.  Expected: 'PACK LocalPath'.  ERROR @ ln " + i);
                        }

                        string path = ResolveVariableToValue(lineParts[1]);

                        string rafPath = mainForm.GuessRafPathFromPath(path);
                        if (rafPath == "undefined")
                        {
                            Console.WriteLine("Pack probably failed - Didn't pack " + path);
                        }
                        else
                        {
                            RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(
                                mainForm.GuessRafPathFromPath(path)
                                );

                            string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.RAFArchive.GetID() + "_" + entry.FileName.Replace("/", "_");
                            if (!File.Exists(fileBackupLoc))
                            {
                                Util.PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                            }

                            entry.RAFArchive.InsertFile(
                                entry.FileName,
                                File.ReadAllBytes(path),
                                null
                                );
                        }
                        i++;
                        break;
                    }

                    case "PACKDIR":
                    {
                        Console.WriteLine("PACKDIR COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("PACKDIR invalid syntax.  Expected: 'PACKDIR LocalPath'.  ERROR @ ln " + i);
                        }

                        string   localPath = ResolveVariableToValue(lineParts[1]);
                        string[] paths     = Util.GetAllChildFiles(scriptDir + "/" + localPath);
                        foreach (string path in paths)
                        {
                            string rafPath = mainForm.GuessRafPathFromPath(path);
                            if (rafPath == null || rafPath == "undefined")
                            {
                                Console.WriteLine("Pack probably failed - Didn't pack " + path);
                            }
                            else
                            {
                                RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(
                                    mainForm.GuessRafPathFromPath(path)
                                    );

                                string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.RAFArchive.GetID() + "_" + entry.FileName.Replace("/", "_");
                                if (!File.Exists(fileBackupLoc))
                                {
                                    Util.PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                    File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                                }

                                entry.RAFArchive.InsertFile(
                                    entry.FileName,
                                    File.ReadAllBytes(path),
                                    null
                                    );
                            }
                        }
                        i++;
                        break;
                    }

                    //The parameter can either be a RAF path or a LOCAL path... doesn't matter
                    case "RESTORE":
                    {
                        Console.WriteLine("RESTORE COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("RESTORE invalid syntax.  Expected: 'RESTORE RAFPath'.  ERROR @ ln " + i);
                        }
                        string rafPath = ResolveVariableToValue(lineParts[1]);

                        string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + rafPath.Replace("/", "_");

                        RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(rafPath);
                        if (entry == null)
                        {
                            throw new Exception("RESTORE: Entry '" + rafPath + "' did NOT exist, or could NOT be found. @ ln " + i);
                        }
                        else
                        {
                            entry.RAFArchive.InsertFile(
                                entry.FileName, File.ReadAllBytes(fileBackupLoc), null
                                );
                        }
                        i++;
                        break;
                    }

                    //The parameter must be a LOCAL path
                    case "RESTOREDIR":
                    {
                        Console.WriteLine("RESTOREDIR COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("RESTOREDIR invalid syntax.  Expected: 'RESTOREDIR LocalDirPath'.  ERROR @ ln " + i);
                        }
                        string   localDirPath = ResolveVariableToValue(lineParts[1]);
                        string[] paths        = Util.GetAllChildFiles(scriptDir + "/" + localDirPath);

                        foreach (string path in paths)
                        {
                            RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(
                                mainForm.GuessRafPathFromPath(path)
                                );

                            string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.RAFArchive.GetID() + "_" + entry.FileName.Replace("/", "_");

                            if (entry == null)
                            {
                                throw new Exception("RESTORE: Entry similar to '" + path + "' did NOT exist, or could NOT be found. @ ln " + i);
                            }
                            else
                            {
                                if (File.Exists(fileBackupLoc))    //Only swap if a backup exists.  Otherwise, we haven't changed it either way.
                                {
                                    entry.RAFArchive.InsertFile(
                                        entry.FileName, File.ReadAllBytes(fileBackupLoc), null
                                        );
                                }
                            }
                        }
                        i++;
                        break;
                    }

                    case "IF":
                    {
                        Console.WriteLine("IF STATEMENT : " + line);
                        if (lineParts[2] == "==" || lineParts[2] == "!=")
                        {
                            bool eval = ResolveVariableToValue(lineParts[1]) == ResolveVariableToValue(lineParts[3]);
                            if (lineParts[2] == "!=")
                            {
                                eval = !eval;
                            }

                            if (eval)
                            {
                                Console.WriteLine("EVAL");
                                if (lines[i + 1].ToUpper().Trim() == "THEN")
                                {
                                    i = ProcessToEndStatement(lines, i + 1, false, false) + 1;
                                }
                                else
                                {
                                    i++;
                                }
                            }
                            else
                            {
                                Console.WriteLine("NO EVAL");
                                if (lines[i + 1].ToUpper().Trim() == "THEN")
                                {
                                    Console.WriteLine("THEN " + (i + 1));
                                    i = FindNextEndOnSameLevel(lines, i + 1) + 1;
                                }
                                else
                                {
                                    i += 2;
                                    Console.WriteLine(i);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("IF STATEMENT only supports IF [varname/value] == [varname/value] ERROR @ ln " + i);
                        }
                        break;
                    }

                    case "THEN":
                        return(ProcessToEndStatement(lines, i + 1, false));

                        break;

                    default:
                        throw new Exception("INVALID SYNTAX @ LN " + i + " - Unknown command");
                        break;
                    }
                }
                if (!multilineExec)
                {
                    return(i);
                }
            }
            return(i);
        }
Exemplo n.º 13
0
 public AIMesh(RAFFileListEntry file)
     : this(file.GetContent())
 {
 }
        void rafContentView_MouseClick(object sender, MouseEventArgs e)
        {
            rafContentView.SelectedNode = rafContentView.GetNodeAt(e.Location);
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                RAFInMemoryFileSystemObject fso = (RAFInMemoryFileSystemObject)rafContentView.SelectedNode;
                ContextMenu cm = new ContextMenu();
                if (fso != null)
                {
                    MenuItem dump = new MenuItem("Dump");
                    #region Dump Menu Entry
                    dump.Click += delegate(Object sender2, EventArgs e2)
                    {
                        if (fso.GetFSOType() == RAFFSOType.ARCHIVE || fso.GetFSOType() == RAFFSOType.DIRECTORY)
                        {
                            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
                            folderDialog.Description = "Select the folder where you wish to dump the files";
                            folderDialog.ShowDialog();
                            if (folderDialog.SelectedPath != "")
                            {
                                Title("Begin Dumping: " + fso.GetRAFPath());
                                DumpRafArchiveByFSO(fso, folderDialog.SelectedPath);
                                Log("Done dumping: " + fso.GetRAFPath());
                                Title("");
                            }
                        }
                        else
                        {
                            SaveFileDialog sfd      = new SaveFileDialog();
                            string         fileName = fso.GetRAFPath().Replace("\\", "/").Split("/").Last();
                            string         fileExt  = fileName.Substring(fileName.LastIndexOf(".") + 1);
                            sfd.Filter   = "File|." + fileExt;
                            sfd.FileName = fileName;
                            sfd.ShowDialog();

                            if (sfd.FileName != "")
                            {
                                Log("Begin dumping: " + fileName);
                                File.WriteAllBytes(
                                    sfd.FileName,
                                    rafManager.ResolveRAFPathToEntry(
                                        fso.GetTopmostParent().Text + "/" + fso.GetRAFPath()
                                        ).GetContent()
                                    );
                                Log("Done dumping: " + fileName);
                            }
                        }
                    };
                    #endregion
                    cm.MenuItems.Add(dump);
                    #region file viewing entries
                    if (fso.GetFSOType() == RAFFSOType.FILE)
                    {
                        MenuItem viewAsTextFile = new MenuItem("View As Text File");
                        viewAsTextFile.Click += delegate(Object sender2, EventArgs e2)
                        {
                            new TextViewer(
                                rafManager.ResolveRAFPathToEntry(
                                    fso.GetTopmostParent().Text + "/" + fso.GetRAFPath()
                                    )
                                ).Show();
                        };
                        cm.MenuItems.Add(viewAsTextFile);

                        MenuItem viewAsBinary = new MenuItem("View As Binary File");
                        viewAsBinary.Click += delegate(Object sender2, EventArgs e2)
                        {
                            new BinaryViewer(this.baseTitle + " - " + fso.GetTopmostParent() + "/" + fso.GetRAFPath(),
                                             rafManager.ResolveRAFPathToEntry(
                                                 fso.GetTopmostParent().Text + "/" + fso.GetRAFPath()
                                                 ).GetContent()
                                             ).Show();
                        };
                        cm.MenuItems.Add(viewAsBinary);

                        if (fso.GetRAFPath().ToLower().EndsWith("inibin") || fso.GetRAFPath().ToLower().EndsWith("troybin"))
                        {
                            MenuItem viewAsINIBIN = new MenuItem("View As INIBIN File");
                            viewAsINIBIN.Click += delegate(Object sender2, EventArgs e2)
                            {
                                try
                                {
                                    new TextViewer(this.baseTitle + " - inibin/troybin view - " + fso.GetTopmostParent() + "/" + fso.GetRAFPath(),
                                                   new InibinFile().main(
                                                       rafManager.ResolveRAFPathToEntry(
                                                           fso.GetTopmostParent().Text + "/" + fso.GetRAFPath()
                                                           ).GetContent()
                                                       )
                                                   ).Show();
                                    return;
                                }
                                catch { Log("Error parsing INIBIN/TROYBIN file"); }
                            };
                            cm.MenuItems.Add(viewAsINIBIN);
                        }
                    }
                    #endregion

#if true || DEBUG
                    if (fso.GetFSOType() == RAFFSOType.FILE)
                    {
                        MenuItem delete = new MenuItem("Delete - Note, RAF Manager MUST RESTART after you use this for things to display properly.");
                        delete.Click += delegate(Object s2, EventArgs e2)
                        {
                            RAFFileListEntry entry = rafManager.ResolveRAFPathToEntry(fso.GetRAFPath(true));

                            entry.RAFArchive.GetDirectoryFile().DeleteFileEntry(entry);
                            entry.RAFArchive.SaveDirectoryFile();
                        };
                        cm.MenuItems.Add(delete);
                        //TOdo: delete treenodes.  For now, just restart client
                    }
#endif
                }
                MenuItem searchThis = new MenuItem("Search This Archive");
                searchThis.Click += delegate(object s2, EventArgs e2)
                {
                    new RAFSearchBox(fso).Show();
                };
                cm.MenuItems.Add(searchThis);
                MenuItem searchAll = new MenuItem("Search All Archives");
                searchAll.Click += delegate(object s2, EventArgs e2)
                {
                    RAFInMemoryFileSystemObject[] nodes = new RAFInMemoryFileSystemObject[rafContentView.Nodes.Count];
                    for (int i = 0; i < rafContentView.Nodes.Count; i++)
                    {
                        nodes[i] = (RAFInMemoryFileSystemObject)rafContentView.Nodes[i];
                    }
                    new RAFSearchBox(nodes).Show();
                };
                cm.MenuItems.Add(searchAll);
                cm.Show(rafContentView, new Point(e.X, e.Y));
            }
        }
Exemplo n.º 15
0
        private void packToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Console.Clear();
            Log("");
            Log("Begin Packing");
            for (int i = 0; i < modEntries.Count; i++)
            {
                ModEntry entry = modEntries[i];
                if (entry.Script == null || (entry.IsChecked?!entry.Script.HasPackTimeOverride:!entry.Script.HasRestoreTimeOverride))
                {
                    DLog("->Pack/Restore Nonscripted Entry: " + entry.ModName);
                    ModEntryNodeTag[] nodeTags = entry.GetModEntryTags();
                    for (int j = 0; j < nodeTags.Length; j++)
                    {
                        RAFFileListEntry rafEntry = ResolveRAFPathToEntry(nodeTags[j].rafPath);

                        string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + nodeTags[j].rafPath.Replace("/", "_");
                        if (entry.IsChecked)
                        {
                            if (rafEntry == null && permitExperimentalFileAddingCB.Checked)
                            {
                                //File doesn't exist in archive
                                //Our backup = "this file should be deleted"
                                DLog("  Marking for restore op deletion: " + nodeTags[j].rafPath);
                                PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                File.WriteAllText(fileBackupLoc, "this file should be deleted");

                                DLog("  Adding " + nodeTags[j].rafPath);
                                string archiveName = nodeTags[j].rafPath.Split("/").First();
                                rafArchives[archiveName].InsertFile(
                                    nodeTags[j].rafPath.Replace(archiveName + "/", ""),
                                    File.ReadAllBytes(nodeTags[j].localPath),
                                    new LogTextWriter(
                                        (Func <string, object>) delegate(string s)
                                {
                                    if (updateDuringLongOperationsCB.Checked)
                                    {
                                        DLog(s);
                                    }
                                    return(null);
                                }
                                        )
                                    );
                            }
                            else
                            {
                                //File does exist in archive, do backup if not done already
                                if (!File.Exists(fileBackupLoc))
                                {
                                    DLog("  Backing up " + nodeTags[j].rafPath);
                                    PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                    File.WriteAllBytes(fileBackupLoc, rafEntry.GetContent());
                                }
                                DLog("  Inserting " + nodeTags[j].rafPath);
                                rafEntry.RAFArchive.InsertFile(
                                    rafEntry.FileName,
                                    File.ReadAllBytes(nodeTags[j].localPath),
                                    new LogTextWriter(
                                        (Func <string, object>) delegate(string s)
                                {
                                    if (updateDuringLongOperationsCB.Checked)
                                    {
                                        DLog(s);
                                    }
                                    return(null);
                                }
                                        )
                                    );
                            }
                        }
                        else if (File.Exists(fileBackupLoc))
                        {
                            if (permitExperimentalFileAddingCB.Checked && File.ReadAllText(fileBackupLoc) == "this file should be deleted")
                            {
                                DLog("  Deleting " + nodeTags[j].rafPath);
                                rafEntry.RAFArchive.GetDirectoryFile().DeleteFileEntry(rafEntry);
                            }
                            else
                            {
                                DLog("  Restoring " + nodeTags[j].rafPath);
                                rafEntry.RAFArchive.InsertFile(
                                    rafEntry.FileName,
                                    File.ReadAllBytes(fileBackupLoc),
                                    null
                                    );
                            }
                        }
                    }
                    DLog("  Done");
                }
                else
                {
                    if (entry.IsChecked)
                    {
                        DLog("->Running RAF Manager Script : Packtime Command");
                        entry.Script.RunPacktimeCommand();
                        DLog("  Done");
                    }
                    else
                    {
                        DLog("->Running RAF Manager Script : Restoretime Command");
                        entry.Script.RunRestoreTimeCommand();
                        DLog("  Done");
                    }
                }
            }
            DLog("Saving Archive Directory Files (*.raf)");
            for (int i = 0; i < rafArchives.Count; i++)
            {
                new List <RAFArchive>(rafArchives.Values)[i].SaveDirectoryFile();
            }
            Log("Done Packing");
        }
Exemplo n.º 16
0
 public ChangesViewEntry(string localPath, RAFFileListEntry entry, TristateTreeNode node)
 {
     this.localPath = localPath;
     this.entry     = entry;
     this.node      = node;
 }
 /// <summary>
 /// Presents an editable text file viewer to the user
 /// </summary>
 void ShowEditableTextFile(RAFFileListEntry entry)
 {
     new TextViewer(entry).Show();
 }
Exemplo n.º 18
0
        // Replacement for individual raf reading and individual filetype searching
        // Provide the directory of RADS\projects\lol_game_client\filearchives or the equivalent
        private bool ReadRAFs(DirectoryInfo dir, Logger logger)
        {
            try
            {
                RAFMasterFileList rafFiles = new RAFMasterFileList(dir.FullName);
                logger.Event("Opening the 'filearchives' directory: " + dir.FullName);
                foreach (RAFMasterFileList.RAFSearchResult result in rafFiles.SearchFileEntries(new string[] { ".dds", ".skn", ".skl", ".inibin", "animations.list", ".anm" }, RAFMasterFileList.RAFSearchType.All))
                {
                    RAFFileListEntry e = result.value;

                    // Split off the actual file name from the full path
                    String name = e.FileName.Substring(e.FileName.LastIndexOf('/') + 1).ToLower();

                    switch (result.searchPhrase)
                    {
                    case ".dds":
                        // Try to parse out unwanted textures.
                        if (!e.FileName.ToLower().Contains("loadscreen") &&
                            !e.FileName.ToLower().Contains("circle") &&
                            !e.FileName.ToLower().Contains("square") &&
                            e.FileName.ToLower().Contains("data") &&
                            e.FileName.ToLower().Contains("characters"))
                        {
                            // Check that the file isn't already in the dictionary
                            if (!textures.ContainsKey(name))
                            {
                                textures.Add(name, e);
                            }
                            else
                            {
                                logger.Warning("Duplicate texture " + name + ": " + e.FileName);
                            }
                        }
                        break;

                    case ".skn":
                        if (!skns.ContainsKey(name))
                        {
                            skns.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate skn " + name + ": " + e.FileName);
                        }
                        break;

                    case ".skl":
                        if (!skls.ContainsKey(name))
                        {
                            skls.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate skn " + name + ": " + e.FileName);
                        }
                        break;

                    case ".inibin":
                        // Try to only read champion inibins
                        if (e.FileName.ToLower().Contains("data") &&
                            e.FileName.ToLower().Contains("characters"))
                        {
                            inibins.Add(e);
                        }
                        else
                        {
                            logger.Warning("Excluding inibin " + name + ": " + e.FileName);
                        }
                        break;

                    case "animations.list":
                        // Riot changed their directory structure for some skins.
                        // Originally, champion Animation.list files were stored in a directory structure like
                        // "*/ChampionName/Animation.list".  Now, some are stored like
                        // "*/ChampionName/Skins/Skin01/Animation.list".

                        if (e.FileName.ToLower().Contains("skin") == false &&
                            e.FileName.ToLower().Contains("base") == false)
                        {
                            // Original Case.

                            // Remove the file name.
                            name = e.FileName.Remove(e.FileName.LastIndexOf('/'));

                            // Remove proceeding directories to get the parent directory
                            name = name.Substring(name.LastIndexOf('/') + 1).ToLower();
                        }
                        else
                        {
                            // Newer Case.
                            string   path      = e.FileName.ToString();
                            string[] splitPath = path.Split('/');

                            // Sanity
                            if (splitPath.Length > 3)
                            {
                                name = splitPath[splitPath.Length - 4].ToLower();
                            }
                        }

                        // Store.
                        if (!animationLists.ContainsKey(name))
                        {
                            animationLists.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate animation list " + name + ": " + e.FileName);
                        }
                        break;

                    case ".anm":
                        // Remove the .anm extension.
                        name = name.Remove(name.Length - 4);

                        if (!animations.ContainsKey(name))
                        {
                            animations.Add(name, e);
                        }
                        else
                        {
                            logger.Warning("Duplicate anm " + name + ": " + e.FileName);
                        }
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                // Something went wrong. Most likely the RAF read failed due to a bad directory.
                logger.Error("Failed to open RAFs");
                logger.Error(e.Message);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Event handler for when a DragDrop operation completed on top of the changesview
        /// </summary>
        void changesView_DragDrop(object sender, DragEventArgs e)
        {
            //Check if we have a file/list of filfes
            if (e.Data is DataObject && ((DataObject)e.Data).ContainsFileDropList())
            {
                DataObject       dataObject = (DataObject)e.Data;
                StringCollection dropList   = dataObject.GetFileDropList();

                List <string> filePaths = new List <string>();
                foreach (string path in dropList)
                {
                    if (File.GetAttributes(path).HasFlag(FileAttributes.Directory))
                    {
                        filePaths.AddRange(Util.GetAllChildFiles(path));//Directory.GetFiles(rootPath, "**", SearchOption.AllDirectories);
                    }
                    else
                    {
                        filePaths.Add(path);
                    }
                }
                if (filePaths.Count == 1) //test if its a project
                {
                    if (filePaths[0].ToLower().EndsWith(".rmproj"))
                    {
                        if (HasProjectChanged)
                        {
                            PromptSaveToClose();
                        }

                        //Load the project
                        LoadProject(filePaths[0]);
                        return;
                    }
                }

                //Iterate through all files
                StringQueryDialog nameQueryDialog = new StringQueryDialog("Type File Group Name:");
                nameQueryDialog.ShowDialog();
                if (nameQueryDialog.Value.Trim() == "")
                {
                    Log("Invalid name '{0}' given.  ".F(nameQueryDialog.Value.Trim()));
                    return;
                }
                TristateTreeNode topNode = new TristateTreeNode(nameQueryDialog.Value);
                topNode.HasCheckBox = true;
                for (int z = 0; z < filePaths.Count; z++)
                {
                    SetTaskbarProgress(z * 100 / filePaths.Count);
                    string filePath = filePaths[z].Replace("\\", "/");
                    //Console.WriteLine(filePath);

                    //ADD TO VIEW HERE
                    TristateTreeNode node;
                    topNode.Nodes.Add(
                        node = new TristateTreeNode(filePath)
                        );
                    node.HasCheckBox = true;

                    //changesView.Rows[rowIndex].Cells[CN_LOCALPATH].Style.Alignment = DataGridViewContentAlignment.MiddleRight;

                    //Split the path into pieces split by FSOs...  Search the RAF archives and see if we can link it to the raf path

                    string[]                pathParts    = filePath.Split("/");
                    RAFFileListEntry        matchedEntry = null;
                    List <RAFFileListEntry> lastMatches  = null;
                    bool done = false;

                    //Smart search insertion
                    for (int i = 1; i < pathParts.Length + 1 && !done; i++)
                    {
                        string[] searchPathParts = pathParts.SubArray(pathParts.Length - i, i);
                        string   searchPath      = String.Join("/", searchPathParts);
                        //Console.WriteLine(searchPath);
                        List <RAFFileListEntry> matches  = new List <RAFFileListEntry>();
                        RAFArchive[]            archives = rafArchives.Values.ToArray();
                        for (int j = 0; j < archives.Length; j++)
                        {
                            List <RAFFileListEntry> newmatches = archives[j].GetDirectoryFile().GetFileList().SearchFileEntries(searchPath);
                            matches.AddRange(newmatches);
                        }
                        if (matches.Count == 1)
                        {
                            matchedEntry = matches[0];
                            done         = true;
                        }
                        else if (matches.Count == 0)
                        {
                            done = true;
                        }
                        else
                        {
                            lastMatches = matches;
                        }
                    }
                    if (matchedEntry == null)
                    {
                        if (lastMatches != null && lastMatches.Count > 0)
                        {
                            //Resolve ambiguity
                            FileEntryAmbiguityResolver ambiguityResolver = new FileEntryAmbiguityResolver(lastMatches.ToArray(), "!");
                            ambiguityResolver.ShowDialog();
                            RAFFileListEntry resolvedItem = (RAFFileListEntry)ambiguityResolver.SelectedItem;
                            if (resolvedItem != null)
                            {
                                matchedEntry = resolvedItem;
                            }
                        }
                        else if (advancedUser)
                        {
                            //We'll use the file browser to select where we want to save...
                            string     rafPath = PickRafPath(false) + "/";
                            RAFArchive archive = rafArchives[rafPath.Replace("\\", "/").Split("/").First()];
                            rafPath = rafPath.Substring(rafPath.IndexOf("/") + 1); //remove the archive name now...
                            if (rafPath.Length != 0)
                            {
                                Console.WriteLine("FRP: " + "len!= 0");
                                if (rafPath[rafPath.Length - 1] == '/')
                                {
                                    Console.WriteLine("FRP: " + rafPath);
                                    rafPath = rafPath.Substring(0, rafPath.Length - 1);//remove the trailing /, since we add it later
                                }
                            }
                            Console.WriteLine("FRP: " + rafPath);
                            if (rafPath == "")
                            {
                                matchedEntry = new RAFFileListEntry(archive, pathParts.Last(), UInt32.MaxValue, (UInt32) new FileInfo(filePath).Length, UInt32.MaxValue);
                            }
                            else
                            {
                                matchedEntry = new RAFFileListEntry(archive, rafPath + "/" + pathParts.Last(), UInt32.MaxValue, (UInt32) new FileInfo(filePath).Length, UInt32.MaxValue);
                            }

                            //Add the tree node to the raf viewer
                        }
                    }
                    if (matchedEntry != null) //If it's still not resolved
                    {
                        node.Tag = new ChangesViewEntry(filePath, matchedEntry, node);
                        node.Nodes.Add(new TristateTreeNode("Local Path: " + filePath));
                        node.Nodes.Add(new TristateTreeNode("RAF Path: " + matchedEntry.RAFArchive.GetID() + "/" + matchedEntry.FileName));
                        node.Nodes[0].HasCheckBox = false;
                        node.Nodes[1].HasCheckBox = false;
                        //changesView.Rows[rowIndex].Cells[CN_RAFPATH].Value = matchedEntry.RAFArchive.GetID() + "/" + matchedEntry.FileName;
                        //changesView.Rows[rowIndex].Cells[CN_RAFPATH].Tag = matchedEntry;
                    }
                    else
                    {
                        node.Tag = new ChangesViewEntry(filePath, null, node);
                        node.Nodes.Add(new TristateTreeNode("Local Path: " + filePath));
                        node.Nodes.Add(new TristateTreeNode("RAF Path: " + "undefined"));
                        node.Nodes[0].HasCheckBox = false;
                        node.Nodes[1].HasCheckBox = false;
                        Log("Unable to link file '" + filePath + "' to RAF Archive.  Please manually select RAF path");
                    }
                }
                changesView.Nodes.Add(topNode);
                changesView.Invalidate();
                SetTaskbarProgress(0);
            }
        }
Exemplo n.º 20
0
        ///<summary>
        ///Returns a guess of the RAF Path, including the archive id or "undefined"
        ///</summary>
        public string GuessRafPathFromPath(string basePath)
        {
            string[]                pathParts    = basePath.Replace("\\", "/").Split("/");
            RAFFileListEntry        matchedEntry = null;
            List <RAFFileListEntry> lastMatches  = null;
            bool done = false;

            //Smart search insertion
            for (int i = 1; i < pathParts.Length + 1 && !done; i++)
            {
                string[] searchPathParts = pathParts.SubArray(pathParts.Length - i, i);
                string   searchPath      = String.Join("/", searchPathParts);
                //Console.WriteLine(searchPath);
                List <RAFFileListEntry> matches  = new List <RAFFileListEntry>();
                RAFArchive[]            archives = rafManager.Archives.ToArray();
                for (int j = 0; j < archives.Length; j++)
                {
                    List <RAFFileListEntry> newmatches = archives[j].GetDirectoryFile().GetFileList().SearchFileEntries(searchPath);
                    matches.AddRange(newmatches);
                }
                if (matches.Count == 1)
                {
                    matchedEntry = matches[0];
                    done         = true;
                }
                else if (matches.Count == 0)
                {
                    done = true;
                }
                else
                {
                    lastMatches = matches;
                }
            }
            if (matchedEntry == null)
            {
                if (lastMatches != null && lastMatches.Count > 0)
                {
                    //Resolve ambiguity
                    FileEntryAmbiguityResolver ambiguityResolver = new FileEntryAmbiguityResolver(lastMatches.ToArray(), "Notes: " + basePath);
                    ambiguityResolver.ShowDialog();
                    RAFFileListEntry resolvedItem = (RAFFileListEntry)ambiguityResolver.SelectedItem;
                    if (resolvedItem != null)
                    {
                        matchedEntry = resolvedItem;
                    }
                }
                else if (permitExperimentalFileAddingCB.Checked)//advanced user
                {
                    //We'll use the file browser to select where we want to save...
                    string     rafPath = PickRafPath(false) + "/";
                    RAFArchive archive = rafManager.Archives.Where(
                        (Func <RAFArchive, bool>) delegate(RAFArchive arc)
                    {
                        return(arc.GetID().ToLower() == rafPath.Replace("\\", "/").Split("/").First().ToLower());
                    }
                        ).First();
                    rafPath = rafPath.Substring(rafPath.IndexOf("/") + 1); //remove the archive name now...
                    if (rafPath.Length != 0)
                    {
                        Console.WriteLine("FRP: " + "len!= 0");
                        if (rafPath[rafPath.Length - 1] == '/')
                        {
                            Console.WriteLine("FRP: " + rafPath);
                            rafPath = rafPath.Substring(0, rafPath.Length - 1);//remove the trailing /, since we add it later
                        }
                    }
                    Console.WriteLine("FRP: " + rafPath);
                    if (rafPath == "")
                    {
                        matchedEntry = new RAFFileListEntry(archive, pathParts.Last(), UInt32.MaxValue, (UInt32) new FileInfo(basePath).Length, UInt32.MaxValue);
                    }
                    else
                    {
                        matchedEntry = new RAFFileListEntry(archive, rafPath + "/" + pathParts.Last(), UInt32.MaxValue, (UInt32) new FileInfo(basePath).Length, UInt32.MaxValue);
                    }

                    //Add the tree node to the raf viewer
                }
            }
            if (matchedEntry != null) //If it is resolved
            {
                /*
                 * node.Tag = new ChangesViewEntry(filePath, matchedEntry, node);
                 * node.Nodes.Add(new TristateTreeNode("Local Path: " + filePath));
                 * node.Nodes.Add(new TristateTreeNode("RAF Path: " + matchedEntry.RAFArchive.GetID() + "/" + matchedEntry.FileName));
                 * node.Nodes[0].HasCheckBox = false;
                 * node.Nodes[1].HasCheckBox = false;
                 */
                //Don't add it
                return(matchedEntry.RAFArchive.GetID() + "/" + matchedEntry.FileName);
                //changesView.Rows[rowIndex].Cells[CN_RAFPATH].Value = matchedEntry.RAFArchive.GetID() + "/" + matchedEntry.FileName;
                //changesView.Rows[rowIndex].Cells[CN_RAFPATH].Tag = matchedEntry;
            }
            else
            {
                /*
                 * node.Tag = new ChangesViewEntry(filePath, null, node);
                 * node.Nodes.Add(new TristateTreeNode("Local Path: " + filePath));
                 * node.Nodes.Add(new TristateTreeNode("RAF Path: " + "undefined"));
                 * node.Nodes[0].HasCheckBox = false;
                 * node.Nodes[1].HasCheckBox = false;
                 * Log("Unable to link file '" + filePath + "' to RAF Archive.  Please manually select RAF path");
                 */
                //Log("Unable to resolve local path to RAF path: " + basePath);
                return("undefined");
            }
        }
Exemplo n.º 21
0
        public CommandList LinkGameModifications(IReadOnlyList <Modification> modifications)
        {
            var archiveLoader = new RiotArchiveLoader(leagueConfiguration.RadsPath);
            Dictionary <uint, List <KeyValuePair <RiotArchive, SectorCollection> > > archivePairsById = new Dictionary <uint, List <KeyValuePair <RiotArchive, SectorCollection> > >();

            var riotSolution = riotSolutionLoader.Load(leagueConfiguration.RadsPath, RiotProjectType.GameClient);
            var gameProject  = riotSolution.ProjectsByType[RiotProjectType.GameClient];
            var gameManifest = gameProject.ReleaseManifest;

            foreach (var modification in modifications)
            {
                var resolutionTableComponent = modification.GetComponent <LeagueResolutionTableComponent>();
                var resolutionTable          = resolutionTableComponent.Table;
                var contentPath          = Path.Combine(modification.RepositoryPath, "content");
                var contentDirectory     = fileSystemProxy.GetDirectoryInfo(contentPath);
                var contentFiles         = contentDirectory.EnumerateFiles("*", SearchOption.AllDirectories);
                var contentRelativePaths = contentFiles.Select(f => f.FullName.Substring(contentPath.Length + 1));
                var objectsPath          = Path.Combine(modification.RepositoryPath, "objects");

                foreach (var contentRelativePath in contentRelativePaths)
                {
                    LeagueResolutionTableValue resolutionTableValue;
                    if (!resolutionTable.TryGetValue(contentRelativePath, out resolutionTableValue))
                    {
                        logger?.Warn($"Not linking {contentRelativePath}: resolution table lookup failed");
                        continue;
                    }
                    if (resolutionTableValue.Target != LeagueModificationTarget.Game)
                    {
                        logger?.Warn($"Not linking {contentRelativePath}: does not target game client.");
                        continue;
                    }
                    var manifestEntry = gameManifest.Root.GetRelativeOrNull <ReleaseManifestFileEntry>(resolutionTableValue.ResolvedPath);
                    if (manifestEntry == null)
                    {
                        logger?.Warn($"Not linking {contentRelativePath}: could not find {resolutionTableValue.ResolvedPath} in manifest.");
                        continue;
                    }

                    List <KeyValuePair <RiotArchive, SectorCollection> > archivePairs;
                    if (!archivePairsById.TryGetValue(manifestEntry.ArchiveId, out archivePairs))
                    {
                        archivePairs = new List <KeyValuePair <RiotArchive, SectorCollection> >();
                        IReadOnlyList <RiotArchive> archives;
                        if (!archiveLoader.TryLoadArchives(manifestEntry.ArchiveId, out archives))
                        {
                            logger?.Error($"Not linking {contentRelativePath}: could not load archives for {manifestEntry.ArchiveId}!");
                            continue;
                        }
                        archives.ForEach(archive => {
                            var datLength = new FileInfo(archive.DatFilePath).Length;
                            SectorCollection sectorCollection = new SectorCollection();
                            sectorCollection.AssignSector(new SectorRange(0, datLength), new FileSector(archive.DatFilePath, 0, datLength));
                            archivePairs.Add(archive.PairValue(sectorCollection));
                        });
                        archivePairsById.Add(manifestEntry.ArchiveId, archivePairs);
                    }

                    var rafPath = RAFUtil.FormatPathToRAFPath(resolutionTableValue.ResolvedPath);
                    RAFFileListEntry rafEntry = null;
                    SectorCollection sectors  = null;
                    foreach (var archivePair in archivePairs)
                    {
                        rafEntry = archivePair.Key.GetDirectoryFile().GetFileList().GetFileEntryOrNull(rafPath);
                        if (rafEntry != null)
                        {
                            sectors = archivePair.Value;
                            break;
                        }
                    }
                    if (rafEntry == null)
                    {
                        logger?.Warn($"Not linking {contentRelativePath}: could not find {resolutionTableValue.ResolvedPath} in {manifestEntry.ArchiveId} archives.");
                        continue;
                    }

                    var vfmEndOffset = sectors.EnumerateSectorPairs().Last().Key.endExclusive;

                    sectors.DeleteRange(rafEntry.FileOffset, rafEntry.FileOffset + rafEntry.FileSize);

                    var objectsFilePath   = Path.Combine(objectsPath, contentRelativePath);
                    var objectsFileLength = new FileInfo(objectsFilePath).Length;

                    rafEntry.FileOffset = (uint)vfmEndOffset;
                    rafEntry.FileSize   = (uint)objectsFileLength;

                    sectors.AssignSector(new SectorRange(vfmEndOffset, vfmEndOffset + objectsFileLength), new FileSector(objectsFilePath, 0, objectsFileLength));

                    var originalFileLength = new FileInfo(Path.Combine(contentPath, contentRelativePath)).Length;
                    manifestEntry.CompressedSize   = (uint)objectsFileLength;
                    manifestEntry.DecompressedSize = (uint)originalFileLength;

                    logger?.Warn("Successfully linked " + resolutionTableValue.ResolvedPath + " in archive " + manifestEntry.ArchiveId + ".");
                }
            }

            var commandList            = new DefaultCommandList();
            var versionStringUtilities = new VersionStringUtilities();
            var tempDir = temporaryFileService.AllocateTemporaryDirectory(TimeSpan.FromMinutes(1));

            logger?.Info("Allocated temporary directory " + tempDir);
            foreach (var archivePair in archivePairsById)
            {
                string versionString = versionStringUtilities.GetVersionString(archivePair.Key);

                foreach (var archiveData in archivePair.Value)
                {
                    // Get archive name (e.g. archive_2.raf or archive_12930813.raf)
                    string archiveFileName = archiveData.Key.RAFFilePath.With(x => x.Substring(x.LastIndexOfAny(new[] { '/', '\\' }) + 1));

                    // Serialize the VFM
                    var vfmSerializer = new SectorCollectionSerializer();
                    var vfmFileName   = versionString + "/" + archiveFileName + ".dat.vfm";
                    var vfmPath       = temporaryFileService.AllocateTemporaryFile(tempDir, vfmFileName);
                    using (var vfmFileStream = File.Open(vfmPath, FileMode.Create, FileAccess.Write, FileShare.None))
                        using (var writer = new BinaryWriter(vfmFileStream)) {
                            vfmSerializer.Serialize(archiveData.Value, writer);
                            commandList.Add(commandFactory.CreateFileRemappingCommand(archiveData.Key.DatFilePath, vfmFileStream.Name));
                        }
                    logger?.Info("Wrote VFM " + vfmFileName + " to " + tempDir);

                    // Serialize the RAF
                    var rafFileName = versionString + "/" + archiveFileName;
                    var rafPath     = temporaryFileService.AllocateTemporaryFile(tempDir, rafFileName);
                    using (var rafFileStream = File.Open(rafPath, FileMode.Create, FileAccess.Write, FileShare.None))
                        using (var writer = new BinaryWriter(rafFileStream)) {
                            writer.Write(archiveData.Key.GetDirectoryFile().GetBytes());
                            commandList.Add(commandFactory.CreateFileRedirectionCommand(archiveData.Key.RAFFilePath, rafFileStream.Name));
                        }
                    logger?.Info("Wrote RAF " + rafFileName + " to " + tempDir);
                }
            }

            // Serialize the Release Manifest
            var manifestPath = temporaryFileService.AllocateTemporaryFile(tempDir, "releasemanifest");

            using (var manifestFileStream = File.Open(manifestPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (var writer = new BinaryWriter(manifestFileStream)) {
                    new ReleaseManifestWriter(gameManifest).Save(writer);
                    commandList.Add(commandFactory.CreateFileRedirectionCommand(gameManifest.Path, manifestFileStream.Name));
                }
            logger?.Info("Wrote release manifest to " + tempDir);
            return(commandList);
        }
Exemplo n.º 22
0
        private void PackNode(TristateTreeNode node)
        {
            ChangesViewEntry cventry = (ChangesViewEntry)node.Tag;

            if (cventry == null) //Group node
            {
                for (int i = 0; i < node.Nodes.Count; i++)
                {
                    PackNode(node.Nodes[i]);
                }
            }
            else
            {
                RAFFileListEntry entry     = cventry.Entry;
                string           rafPath   = entry.FileName;
                string           localPath = cventry.LocalPath;
                bool             useFile   = cventry.Checked;

                packTick = (packTick + 1) % 10;
                if (packTick == 0 || verboseLoggingCB.Checked)
                {
                    Title("Pack File: " + localPath.Replace("\\", "/").Split("/").Last());
                }

                //Console.WriteLine(Environment.CurrentDirectory + "/backup/");
                PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.FileName.Replace("/", "_");
                if (!File.Exists(fileBackupLoc))
                {
                    if (entry.IsMemoryEntry)
                    {
                        File.WriteAllText(fileBackupLoc, "this file should be deleted");
                    }
                    else
                    {
                        File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                    }
                }

                //Open the RAF archive, insert.
                if (useFile)
                {
                    entry.RAFArchive.InsertFile(
                        rafPath,
                        File.ReadAllBytes(localPath),
                        new LogTextWriter(
                            (Func <string, object>) delegate(string s)
                    {
                        if (verboseLoggingCB.Checked)
                        {
                            Log(s);
                        }
                        return(null);
                    }
                            )
                        );
                }
                else
                {
                    //Insert backup
                    if (File.ReadAllText(fileBackupLoc) == "this file should be deleted")
                    {
                        //The file should be deleted...
                        entry.RAFArchive.GetDirectoryFile().DeleteFileEntry(entry);
                    }
                    else
                    {
                        entry.RAFArchive.InsertFile(
                            rafPath,
                            File.ReadAllBytes(fileBackupLoc),
                            new LogTextWriter(
                                (Func <string, object>) delegate(string s)
                        {
                            if (verboseLoggingCB.Checked)
                            {
                                Log(s);
                            }
                            return(null);
                        }
                                )
                            );
                    }
                }
                List <RAFArchive> archives = new List <RAFArchive>(rafArchives.Values);
                for (int i = 0; i < archives.Count; i++)
                {
                    SetTaskbarProgress((i + 1) * 100 / (archives.Count + 1));
                    archives[i].SaveDirectoryFile();
                }

                SetTaskbarProgress(0);
            }
        }