/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> //public static ICacheFile LoadCacheFile(IReader map_reader, IReader tag_reader, IReader string_reader, EngineDatabase engineDb) public static ICacheFile LoadCacheFile(IReader map_reader, EngineDatabase engineDb) { EngineDescription tempDesc; string ns = null; return(LoadCacheFile(map_reader, null, null, out ns, null, engineDb, out tempDesc, null, null)); }
private void Initalize(Stream blfStream, EngineDatabase database) { _stream = new EndianStream(blfStream, Endian.BigEndian); // Load MapInfo data from file LoadMapInfo(database); }
private static void DumpSharedResources(string mapPath, EngineDatabase db) { ICacheFile cacheFile; ResourceTable resources; using (var reader = new EndianReader(File.OpenRead(mapPath), Endian.BigEndian)) { cacheFile = CacheFileLoader.LoadCacheFile(reader, db); resources = cacheFile.Resources.LoadResourceTable(reader); } using (var output = new StreamWriter(Path.ChangeExtension(mapPath, ".txt"))) { output.WriteLine("Shared resources referenced by {0}:", Path.GetFileName(mapPath)); output.WriteLine(); output.WriteLine("Rsrc Datum Map File Class Tag"); output.WriteLine("---------- -------- ----- ---"); foreach (Resource resource in resources.Resources.Where(r => r.Location != null && r.ParentTag != null)) { // If either page has a null file path, then it's shared ResourcePointer loc = resource.Location; string primaryFile = (loc.PrimaryPage != null) ? loc.PrimaryPage.FilePath : null; string secondaryFile = (loc.SecondaryPage != null) ? loc.SecondaryPage.FilePath : null; if (primaryFile != null || secondaryFile != null) { string className = CharConstant.ToString(resource.ParentTag.Class.Magic); string name = cacheFile.FileNames.GetTagName(resource.ParentTag) ?? resource.ParentTag.Index.ToString(); string fileName = primaryFile ?? secondaryFile; fileName = fileName.Substring(fileName.IndexOf('\\') + 1); output.WriteLine("{0} {1, -12} {2} {3}", resource.Index, fileName, className, name); } } } }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <param name="engineInfo">On output, this will contain the cache file's engine description.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader reader, EngineDatabase engineDb, out EngineDescription engineInfo) { // Set the reader's endianness based upon the file's header magic reader.SeekTo(0); byte[] headerMagic = reader.ReadBlock(4); reader.Endianness = DetermineCacheFileEndianness(headerMagic); // Load engine version info var version = new CacheFileVersionInfo(reader); if (version.Engine != EngineType.SecondGeneration && version.Engine != EngineType.ThirdGeneration) { throw new NotSupportedException("Engine not supported"); } // Load build info engineInfo = engineDb.FindEngineByVersion(version.BuildString); if (engineInfo == null) { throw new NotSupportedException("Engine version \"" + version.BuildString + "\" not supported"); } // Load the cache file depending upon the engine version switch (version.Engine) { case EngineType.SecondGeneration: return(new SecondGenCacheFile(reader, engineInfo, version.BuildString)); case EngineType.ThirdGeneration: return(new ThirdGenCacheFile(reader, engineInfo, version.BuildString)); default: throw new NotSupportedException("Engine not supported"); } }
/// <summary> /// Loads an engine database from an XML container. /// </summary> /// <param name="container">The container to read engine elements from.</param> /// <returns>The built engine database.</returns> public static EngineDatabase LoadDatabase(XContainer container) { XMLSettingsGroupLoader loader = CreateSettingsGroupLoader(); var result = new EngineDatabase(); foreach (XElement elem in container.Elements("engine")) { string name = XMLUtil.GetStringAttribute(elem, "name"); string build = XMLUtil.GetStringAttribute(elem, "build"); var version = XMLUtil.GetNumericAttribute(elem, "version"); var versionAlt = XMLUtil.GetNumericAttribute(elem, "version", -1); string inherits = XMLUtil.GetStringAttribute(elem, "inherits", null); SettingsGroup settings = loader.LoadSettingsGroup(elem); if (!string.IsNullOrWhiteSpace(inherits)) { // Clone the base engine's settings and then import the new settings on top of it SettingsGroup baseSettings = result.FindEngineByName(inherits).Settings.DeepClone(); baseSettings.Import(settings); settings = baseSettings; } var desc = new EngineDescription(name, (int)version, (int)versionAlt, build, settings); result.RegisterEngine(desc); } return(result); }
public ScriptDumper() { _exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _formatsDir = Path.Combine(_exeDir, "Formats"); _supportedBuildsPath = Path.Combine(_formatsDir, "Engines.xml"); _db = XMLEngineDatabaseLoader.LoadDatabase(_supportedBuildsPath); }
private static async Task WalkFiles(string cleanFolder, string modifiedFolder, string outputFolder) { string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string formatsDir = Path.Combine(exeDir, "Formats"); string supportedBuildsPath = Path.Combine(formatsDir, "Engines.xml"); EngineDatabase db = XMLEngineDatabaseLoader.LoadDatabase(supportedBuildsPath); List <string> cleanFileNames = Directory.EnumerateFiles(cleanFolder, "*.map").Select(Path.GetFileName).ToList(); List <string> modifiedFileNames = Directory.EnumerateFiles(modifiedFolder, "*.map").Select(Path.GetFileName).ToList(); Console.WriteLine($"{modifiedFileNames.Count} modified cache files were found. Processing the files now."); List <Task> tasks = new List <Task>(); foreach (string fileName in modifiedFileNames) { if (cleanFileNames.Contains(fileName)) { string cleanFile = Path.Combine(cleanFolder, fileName); string modifiedFile = Path.Combine(modifiedFolder, fileName); string outputName = Path.GetFileNameWithoutExtension(fileName) + "_walk.txt"; string outputFile = Path.Combine(outputFolder, outputName); tasks.Add(Task.Run(() => WalkFile(cleanFile, modifiedFile, outputFile, db))); } else { Console.WriteLine($"An unmodified cache file with the name \"{fileName}\" could not be found. The operation will be skipped."); } } await Task.WhenAll(tasks); Console.WriteLine("Finished processing the files. You can close this program now."); }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="filePath">The full file path of the cache file.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <param name="engineInfo">On output, this will contain the cache file's engine description.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader reader, string filePath, EngineDatabase engineDb, out EngineDescription engineInfo) { engineInfo = FindEngineDescription(reader, engineDb); if (engineInfo == null) { throw new NotSupportedException("Engine build of given cache file \"" + Path.GetFileName(filePath) + "\" not supported"); } // Load the cache file depending upon the engine version switch (engineInfo.Engine) { case EngineType.FirstGeneration: return(new FirstGenCacheFile(reader, engineInfo, filePath)); case EngineType.SecondGeneration: return(new SecondGenCacheFile(reader, engineInfo, filePath)); case EngineType.ThirdGeneration: return(new ThirdGenCacheFile(reader, engineInfo, filePath)); default: throw new NotSupportedException("Engine not supported"); } }
private static CompressionState DetermineState(IReader reader, EngineDatabase engineDb, out EngineType type) { // Set the reader's endianness based upon the file's header magic reader.SeekTo(0); byte[] headerMagic = reader.ReadBlock(4); reader.Endianness = CacheFileLoader.DetermineCacheFileEndianness(headerMagic); // Load engine version info var version = new CacheFileVersionInfo(reader); type = version.Engine; if (version.Engine == EngineType.SecondGeneration) { // Load build info var engineInfo = engineDb.FindEngineByVersion(version.BuildString); if (engineInfo == null) { return(CompressionState.Null); } if (!engineInfo.UsesCompression) { return(CompressionState.Null); } return(AnalyzeSecondGen(reader, engineInfo)); } else { return(CompressionState.Null); } }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <param name="engineInfo">On output, this will contain the cache file's engine description.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader reader, EngineDatabase engineDb, out EngineDescription engineInfo) { // Set the reader's endianness based upon the file's header magic reader.SeekTo(0); byte[] headerMagic = reader.ReadBlock(4); reader.Endianness = DetermineCacheFileEndianness(headerMagic); // Load engine version info var version = new CacheFileVersionInfo(reader); if (version.Engine != EngineType.SecondGeneration && version.Engine != EngineType.ThirdGeneration) throw new NotSupportedException("Engine not supported"); // Load build info engineInfo = engineDb.FindEngineByVersion(version.BuildString); if (engineInfo == null) throw new NotSupportedException("Engine version \"" + version.BuildString + "\" not supported"); // Load the cache file depending upon the engine version switch (version.Engine) { case EngineType.SecondGeneration: return new SecondGenCacheFile(reader, engineInfo, version.BuildString); case EngineType.ThirdGeneration: return new ThirdGenCacheFile(reader, engineInfo, version.BuildString); default: throw new NotSupportedException("Engine not supported"); } }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <param name="engineInfo">On output, this will contain the cache file's engine description.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader map_reader, IReader tag_reader, IReader string_reader, out string tagnamesLocation, string filesLocation, EngineDatabase engineDb, out EngineDescription engineInfo) { // Set the reader's endianness based upon the file's header magic map_reader.SeekTo(0); byte[] headerMagic = map_reader.ReadBlock(4); Endian engianess = DetermineCacheFileEndianness(headerMagic); map_reader.Endianness = engianess; if(tag_reader != null) tag_reader.Endianness = engianess; if (tag_reader != null) string_reader.Endianness = engianess; // Load engine version info var version = new CacheFileVersionInfo(map_reader); if (version.Engine != EngineType.SecondGeneration && version.Engine != EngineType.ThirdGeneration && version.Engine != EngineType.FourthGeneration) throw new NotSupportedException("Engine not supported"); // Load build info engineInfo = engineDb.FindEngineByVersion(version.BuildString); if (engineInfo == null) throw new NotSupportedException("Engine version \"" + version.BuildString + "\" not supported"); // Load the cache file depending upon the engine version switch (version.Engine) { case EngineType.SecondGeneration: tagnamesLocation = null; return new SecondGenCacheFile(map_reader, engineInfo, version.BuildString); case EngineType.ThirdGeneration: tagnamesLocation = null; return new ThirdGenCacheFile(map_reader, engineInfo, version.BuildString); case EngineType.FourthGeneration: if (tag_reader == null || tag_reader.BaseStream.Length == 0) throw new Exception("Can't load version 4 cache file without tags file. Please make sure that tags.dat is in the same folder at the map file."); if (string_reader == null || tag_reader.BaseStream.Length == 0) throw new Exception("Can't load version 4 cache file without strings file. Please make sure that tags.dat is in the same folder at the map file."); // Load the tag names csv file string tagnames_filename = "tagnames_" + version.BuildString + ".csv"; string tagnames_location = filesLocation != null ? filesLocation + tagnames_filename : ""; if (!File.Exists(tagnames_location)) tagnames_location = "tagnames\\" + tagnames_filename; if (!File.Exists(tagnames_location)) tagnames_location = null; FileStream tagnamesFileStream = tagnames_location != null ? TryInitFilestream(tagnames_location) : null; EndianReader tagnames_reader = null; if (tagnamesFileStream != null) { tagnames_reader = new EndianReader(tagnamesFileStream, Endian.BigEndian); tagnames_reader.Endianness = engianess; } tagnamesLocation = tagnames_location; FourthGenCacheFile cache_file = new FourthGenCacheFile(map_reader, tag_reader, string_reader, tagnames_reader, engineInfo, version.BuildString); tagnamesFileStream.Close(); return cache_file; default: throw new NotSupportedException("Engine not supported"); } }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="filePath">The full file path of the cache file.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <param name="engineInfo">On output, this will contain the cache file's engine description.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader reader, string filePath, EngineDatabase engineDb, out EngineDescription engineInfo) { engineInfo = FindEngineDescription(reader, engineDb); if (engineInfo == null) { throw new NotSupportedException("Engine build of given cache file \"" + Path.GetFileName(filePath) + "\" not supported"); } return(LoadCacheFileWithEngineDescription(reader, filePath, engineInfo)); }
public static async Task Create(Dictionary <string, string> arguments, Dictionary <string, string> options) { await Task.Delay(1); var cacheFilePath = arguments["cache"]; var projectDirectory = arguments["project"]; // Check file exists if (cacheFilePath == null || !File.Exists(cacheFilePath)) { throw new ComposerException("Cache doesn't exist"); } // Create project directory // TODO: think about logic if directory already exists if (!Directory.Exists(projectDirectory)) { Directory.CreateDirectory(projectDirectory); } // Create Project var project = new Models.Project { Title = "Example Halo Project", Version = "1.0.0", Description = "Simple project for testing the tool", Properties = new ProjectProperties { TagsFolder = "tags", GitEnabled = true } }; using (var stream = File.OpenRead(cacheFilePath)) using (var reader = new EndianReader(stream, Endian.BigEndian)) { EngineDescription engineDescription = null; EngineDatabase engineDatabase = XMLEngineDatabaseLoader.LoadDatabase("data/formats/engines.xml"); var cacheFile = CacheFileLoader.LoadCacheFile(reader, engineDatabase, out engineDescription); var stringIdTrie = new Trie(); if (cacheFile.StringIDs != null) { stringIdTrie.AddRange(cacheFile.StringIDs); } if (cacheFile.TagClasses.Any()) { LoadTags(project, cacheFile, projectDirectory, stringIdTrie); } } File.WriteAllText(Path.Combine(projectDirectory, "project.json"), JsonConvert.SerializeObject(project, Formatting.Indented)); }
public static IEnumerable <ICacheFile> LoadAllMaps(string[] paths, EngineDatabase db) { List <ICacheFile> result = new List <ICacheFile>(); foreach (string path in paths) { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read); var reader = new EndianReader(stream, Endian.BigEndian); var cache = CacheFileLoader.LoadCacheFile(reader, Path.GetFileNameWithoutExtension(path), db); result.Add(cache); } return(result); }
/// <summary> /// Finds the first EngineDatabase that matches a cache file from a stream, if available. /// This is the legacy behavior for uses where showing a selection UI isn't as feasible. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <returns>The EngineDescription used to describe the cache file, otherwise null.</returns> public static EngineDescription FindEngineDescription(IReader reader, EngineDatabase engineDb) { var matches = FindEngineDescriptions(reader, engineDb); if (matches.Count > 0) { return(matches[0]); } else { return(null); } }
private static ScriptTable LoadScripts(string path, EngineDatabase db, out EngineDescription desc) { using (var stream = File.OpenRead(path)) { EngineDescription engine; var reader = new EndianReader(stream, Endian.BigEndian); var cache = CacheFileLoader.LoadCacheFile(reader, Path.GetFileName(path), db, out engine); desc = engine; var scripts = cache.ScriptFiles[0].LoadScripts(reader); return(scripts); } }
private void btnCreateSde_Click(object sender, EventArgs e) { setArcgis.init(); EngineDatabase engine = new EngineDatabase(); Db db = QuickConfig.Common.setXml.getConfig(ConfigName).Db; try { setDB setdb = new setDB(db.DbSystemUser.User, db.DbSystemUser.Password, db.Datasource); foreach (Control ctl in dbControlList) { if (ctl is gdbChoose && ((gdbChoose)ctl).Check == true) { string Name = ((gdbChoose)ctl).Name; DbSdeUser dbsdeuser = db.DbSdeUserList.Find((DbSdeUser ds) => ds.Name == Name); if (setdb.isUserExist(dbsdeuser.User)) { // MessageBox.Show("现势库已存在"); if (MessageBox.Show("现势库已存在,是否删除已有的现势库", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) { bool res = setdb.deleteUser(dbsdeuser.User); if (res == true) { MessageBox.Show("现势库删除成功!"); } else { MessageBox.Show("现势库删除失败!"); } } } else { string ans1 = engine.createSDE("Oracle", db.Datasource, db.DbSystemUser.User, db.DbSystemUser.Password, dbsdeuser.User, dbsdeuser.Password, dbsdeuser.Tablespace, Common.getSdeEcpFile()); setdb.grantUser(dbsdeuser.User); MessageBox.Show("现势库创建结果如下:\r\n" + ans1); } } } } catch (Exception eg) { MessageBox.Show(eg.Message.ToString()); } MessageBox.Show("企业空间库操作结束"); }
/// <summary> /// Reads in the input file, determines its current compression state, and reverses it by default. /// </summary> /// <param name="input">Cache file to compress</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <param name="desiredState">Optional. When set to not null, the default behavior is overridden and skips action if the cache file is already that state.</param> /// <returns></returns> public static CompressionState HandleCompression(string input, EngineDatabase engineDb, CompressionState desiredState = CompressionState.Null) { CompressionState state; EngineType type; using (FileStream fileStream = File.OpenRead(input)) { var reader = new EndianReader(fileStream, Endian.BigEndian); state = DetermineState(reader, engineDb, out type); } if (state == desiredState) { return(state); } switch (state) { default: case CompressionState.Null: return(state); case CompressionState.Compressed: { if (type == EngineType.SecondGeneration) { DecompressSecondGen(input); return(CompressionState.Decompressed); } else { return(state); } } case CompressionState.Decompressed: { if (type == EngineType.SecondGeneration) { CompressSecondGen(input); return(CompressionState.Compressed); } else { return(state); } } } }
public static bool applyPatch(ZipArchiveEntry zippedPatchFile, string patchFileName, string unmoddedMapPath, string outputPath) { createTmpDir(); try { zippedPatchFile.ExtractToFile(Config.modpack_dir + @"\tmp\" + patchFileName); } catch (IOException) { rmTmpDir(); createTmpDir(); zippedPatchFile.ExtractToFile(Config.modpack_dir + @"\tmp\" + patchFileName); } Patch currentPatch = LoadPatch(Config.modpack_dir + @"\tmp\" + patchFileName); // Copy the original map to the destination path IO.CopyFile(unmoddedMapPath, outputPath, true); //if modpack has written to unmoddedmap, take from backups // Open the destination map using (var stream = new EndianStream(File.Open(outputPath, FileMode.Open, FileAccess.ReadWrite), Endian.BigEndian)) { EngineDatabase engineDb = XMLEngineDatabaseLoader.LoadDatabase("Formats/Engines.xml"); ICacheFile cacheFile; try { cacheFile = CacheFileLoader.LoadCacheFile(stream, engineDb); } catch (NotSupportedException nse) { form1.showMsg("Error patching '" + patchFileName + "':" + nse.Message, "Error"); return(false); } if (!string.IsNullOrEmpty(currentPatch.BuildString) && cacheFile.BuildString != currentPatch.BuildString) { form1.showMsg("Unable to patch. That patch is for a map with a build version of " + currentPatch.BuildString + ", and the unmodified map file doesn't match that.", "Error"); return(false); } if (currentPatch.MapInternalName == null) { // Because Ascension doesn't include this, and ApplyPatch() will complain otherwise currentPatch.MapInternalName = cacheFile.InternalName; } // Apply the patch! try { PatchApplier.ApplyPatch(currentPatch, cacheFile, stream); } catch (ArgumentException ae) { form1.showMsg("There was an issue applying the patch file '" + patchFileName + "': " + ae.Message, "Info"); return(false); } } rmTmpDir(); return(true); }
/// <summary> /// Loads an engine database from an XML container. /// </summary> /// <param name="container">The container to read engine elements from.</param> /// <returns>The built engine database.</returns> public static EngineDatabase LoadDatabase(XContainer container) { XMLSettingsGroupLoader loader = CreateSettingsGroupLoader(); var result = new EngineDatabase(); foreach (XElement elem in container.Elements("engine")) { string name = XMLUtil.GetStringAttribute(elem, "name"); int levlSize = XMLUtil.GetNumericAttribute(elem, "levlSize"); int version = XMLUtil.GetNumericAttribute(elem, "version"); SettingsGroup settings = loader.LoadSettingsGroup(elem); var desc = new EngineDescription(name, levlSize, version, settings); result.RegisterEngine(desc); } return result; }
private void btnInitSde_Click(object sender, EventArgs e) { if (MessageBox.Show("初始化空间库,会删除空间库原有内容,\r\n,请先备空间库库!\r\n继续请点击确定,放弃请点击取消。", "初始化空间库", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Cancel) { return; } if (!checkSDEimportSet()) { return; } //初始化 esri授权 setArcgis.init(); setArcgis.grant(); EngineDatabase engine = new EngineDatabase(); Db db = QuickConfig.Common.setXml.getConfig(ConfigName).Db; try { setDB setdb = new setDB(db.DbSystemUser.User, db.DbSystemUser.Password, db.Datasource); foreach (Control ctl in dbControlList) { if (ctl is gdbChoose && ((gdbChoose)ctl).Check == true) { string Name = ((gdbChoose)ctl).Name; DbSdeUser dbsdeuser = db.DbSdeUserList.Find((DbSdeUser ds) => ds.Name == Name); string ans1 = ""; if (setdb.isUserExist(dbsdeuser.User)) { setdb.grantUser(dbsdeuser.User); ans1 += "用户 " + dbsdeuser.User + "授权成功\r\n"; } ans1 += engine.importGDB2SDEWithWorkspace(db.Ip, "sde:oracle10g:" + db.Datasource, dbsdeuser.User, dbsdeuser.Password, dbsdeuser.Gdbfile, db.CS_TYPE, db.WKID, db.Prjpath); MessageBox.Show(dbsdeuser.Label + "创建结果如下:\r\n" + ans1); } } } catch (Exception eg) { MessageBox.Show(eg.Message.ToString()); } MessageBox.Show("企业空间库初始化完成"); }
/// <summary> /// Finds the EngineDatabase that matches a cache file from a stream, if available. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <returns>The EngineDescription used to describe the cache file, otherwise null.</returns> public static EngineDescription FindEngineDescription(IReader reader, EngineDatabase engineDb) { // Set the reader's endianness based upon the file's header magic reader.SeekTo(0); byte[] headerMagic = reader.ReadBlock(4); reader.Endianness = DetermineCacheFileEndianness(headerMagic); reader.SeekTo(0x4); int fileVersion = reader.ReadInt32(); var matches = engineDb.FindEnginesByVersion(fileVersion, reader.Endianness); Dictionary <int, string> offsetCache = new Dictionary <int, string>(); foreach (EngineDescription engine in matches) { if (offsetCache.ContainsKey(engine.BuildStringOffset)) { if (offsetCache[engine.BuildStringOffset] == engine.BuildVersion) { return(engine); } else { continue; } } reader.SeekTo(engine.BuildStringOffset); string buildString = reader.ReadAscii(); if (buildString == engine.BuildVersion) { return(engine); } offsetCache[engine.BuildStringOffset] = buildString; } return(null); }
private static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Usage: SharedDump <map file(s)>"); return; } // Locate the Formats folder and SupportedBuilds.xml string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string formatsDir = Path.Combine(exeDir, "Formats"); string supportedBuildsPath = Path.Combine(formatsDir, "Engines.xml"); EngineDatabase db = XMLEngineDatabaseLoader.LoadDatabase(supportedBuildsPath); // Dump each map file foreach (string arg in args) { Console.WriteLine("{0}...", arg); DumpSharedResources(arg, db); } }
/// <summary> /// Loads an engine database from an XML container. /// </summary> /// <param name="container">The container to read engine elements from.</param> /// <returns>The built engine database.</returns> public static EngineDatabase LoadDatabase(XContainer container) { XMLSettingsGroupLoader loader = CreateSettingsGroupLoader(); var result = new EngineDatabase(); foreach (XElement elem in container.Elements("engine")) { string name = XMLUtil.GetStringAttribute(elem, "name"); string version = XMLUtil.GetStringAttribute(elem, "version"); string inherits = XMLUtil.GetStringAttribute(elem, "inherits", null); SettingsGroup settings = loader.LoadSettingsGroup(elem); if (!string.IsNullOrWhiteSpace(inherits)) { // Clone the base engine's settings and then import the new settings on top of it SettingsGroup baseSettings = result.FindEngineByName(inherits).Settings.DeepClone(); baseSettings.Import(settings); settings = baseSettings; } var desc = new EngineDescription(name, version, settings); result.RegisterEngine(desc); } return result; }
public BlamCacheFile(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException("Invalid cache file path"); } fileStream = new EndianStream(File.Open(filePath, FileMode.Open, FileAccess.ReadWrite), Endian.LittleEndian); cacheFileVersion = new CacheFileVersionInfo(fileStream); EngineDatabase database = XMLEngineDatabaseLoader.LoadDatabase("Formats/Engines.xml"); buildInfo = database.FindEngineByVersion(cacheFileVersion.BuildString); switch (cacheFileVersion.Engine) { case EngineType.ThirdGeneration: internalCacheFile = CreateThirdGenCacheFile(fileStream, buildInfo, cacheFileVersion); break; default: throw new InvalidOperationException("Only third generation engine map files are supported at the moment!"); } }
private void LoadMap() { using (var fileStream = File.OpenRead(MapFilePath)) { _engineDatabase = XMLEngineDatabaseLoader.LoadDatabase(Path.Combine(_appLocation, @"bin/Formats/Engines.xml")); var reader = new EndianReader(fileStream, Endian.BigEndian); _cacheFile = CacheFileLoader.LoadCacheFile(reader, _engineDatabase, out _engineDescription); _streamManager = new FileStreamManager(MapFilePath, reader.Endianness); var weapons = _cacheFile.Tags.Where(t => t.Class.Magic == CharConstant.FromString("weap")) .Select(t => _cacheFile.FileNames.GetTagName(t.Index)); var projectiles = _cacheFile.Tags.Where(t => t.Class.Magic == CharConstant.FromString("proj")) .Select(t => _cacheFile.FileNames.GetTagName(t.Index)); } }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader reader, EngineDatabase engineDb) { EngineDescription tempDesc; return(LoadCacheFile(reader, engineDb, out tempDesc)); }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="filePath">The full file path of the cache file.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader reader, string filePath, EngineDatabase engineDb) { return(LoadCacheFile(reader, filePath, engineDb, out _)); }
public MapInfo(string blfLocation, EngineDatabase database) { Initalize(new FileStream(blfLocation, FileMode.OpenOrCreate), database); }
public static Dictionary <string, ScriptTable> LoadAllScriptFiles(string path, EngineDatabase db, out EngineDescription engineInfo) { Dictionary <string, ScriptTable> result = new Dictionary <string, ScriptTable>(); string fileName = Path.GetFileNameWithoutExtension(path); using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { var reader = new EndianReader(stream, Endian.BigEndian); var cache = CacheFileLoader.LoadCacheFile(reader, fileName, db, out engineInfo); if (cache.Type != CacheFileType.Shared && cache.Type != CacheFileType.SinglePlayerShared && cache.ScriptFiles.Length > 0) { foreach (var file in cache.ScriptFiles) { result.Add(file.Name, file.LoadScripts(reader)); } } } return(result); }
public static Dictionary <string, IEnumerable <UnitSeatMapping> > LoadAllSeatMappings(string path, EngineDatabase db, out EngineDescription engineInfo) { Dictionary <string, IEnumerable <UnitSeatMapping> > result = new Dictionary <string, IEnumerable <UnitSeatMapping> >(); string fileName = Path.GetFileNameWithoutExtension(path); using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { var reader = new EndianReader(stream, Endian.BigEndian); var cache = CacheFileLoader.LoadCacheFile(reader, fileName, db, out engineInfo); if (cache.Type != CacheFileType.Shared && cache.Type != CacheFileType.SinglePlayerShared && cache.ScriptFiles.Length > 0) { foreach (var file in cache.ScriptFiles) { if (file is ScnrScriptFile scnr) { var mappings = SeatMappingNameExtractor.ExtractScnrSeatMappings(scnr, reader, engineInfo.ScriptInfo); if (mappings.Any()) { result[file.Name] = mappings; } } } } } return(result); }
private static void WalkFile(string cleanFile, string modifiedFile, string outputFile, EngineDatabase db) { var cleanScripts = LoadScripts(cleanFile, db, out EngineDescription desc); var modifiedScripts = LoadScripts(modifiedFile, db, out _); using (var writer = File.CreateText(outputFile)) { var txtWriter = new IndentedTextWriter(writer); ScriptWalker walker = new ScriptWalker(cleanScripts, modifiedScripts, txtWriter, desc); walker.Analyze(); } Console.WriteLine($"Compared {Path.GetFileName(modifiedFile)}."); }
public MapInfo(Stream blfStream, EngineDatabase database) { Initalize(blfStream, database); }
public void LoadMapInfo(EngineDatabase database) { _mapInformation = new MaplevlInfo(); // Find out which engine the file uses _stream.SeekTo(0x34); var size = _stream.ReadInt32(); _stream.SeekTo(0x38); var version = _stream.ReadUInt16(); Engine = database.FindEngine(size, version); if (Engine == null) throw new NotSupportedException("Engine version " + version + " of size 0x" + size.ToString("X") + " is not supported"); // Update offsets based on engine info UpdateOffsets(); // Load Map ID _stream.SeekTo(0x3C); _mapInformation.MapID = _stream.ReadInt32(); // Load Flags _stream.SeekTo(0x42); _mapInformation.Flags = (LevelFlags)_stream.ReadInt16(); // Load Map Names and Descriptions LoadMapNames(MapNamesOffset); LoadMapDescriptions(_mapDescriptionsOffset); // Load Map Physical Name _stream.SeekTo(_physicalNameOffset); _mapInformation.PhysicalName = _stream.ReadAscii(); // Load Map Internal Name _stream.SeekTo(_internalNameOffset); _mapInformation.InternalName = _stream.ReadAscii(); // Load Map Index _stream.SeekTo(_mapIndexOffset); _mapInformation.MapIndex = _stream.ReadInt32(); // Load Max Teams if (Engine.MaxTeamCollection != null) LoadMapMaxTeams(_maxTeamsOffset); // Load Multiplayer Object Table if (Engine.MultiplayerObjectCollection != null) LoadMPObjectTable(_mpObjectsOffset); // Load Insertion Points LoadInsertionPoints(_insertionOffset); // Load Default Author Name if (Engine.UsesDefaultAuthor) { _stream.SeekTo(_defaultAuthorOffset); _mapInformation.DefaultAuthor = _stream.ReadAscii(); } }
public void LoadMapInfo(EngineDatabase database) { _mapInformation = new MaplevlInfo(); // Find out which engine the file uses _stream.SeekTo(0x34); var size = _stream.ReadInt32(); _stream.SeekTo(0x38); var version = _stream.ReadUInt16(); Engine = database.FindEngine(size, version); if (Engine == null) { throw new NotSupportedException("Engine version " + version + " of size 0x" + size.ToString("X") + " is not supported"); } // Update offsets based on engine info UpdateOffsets(); // Load Map ID _stream.SeekTo(0x3C); _mapInformation.MapID = _stream.ReadInt32(); // Load Flags _stream.SeekTo(0x42); _mapInformation.Flags = (LevelFlags)_stream.ReadInt16(); // Load Map Names and Descriptions LoadMapNames(MapNamesOffset); LoadMapDescriptions(_mapDescriptionsOffset); // Load Map Physical Name _stream.SeekTo(_physicalNameOffset); _mapInformation.PhysicalName = _stream.ReadAscii(); // Load Map Internal Name _stream.SeekTo(_internalNameOffset); _mapInformation.InternalName = _stream.ReadAscii(); // Load Map Index _stream.SeekTo(_mapIndexOffset); _mapInformation.MapIndex = _stream.ReadInt32(); // Load Max Teams if (Engine.MaxTeamCollection != null) { LoadMapMaxTeams(_maxTeamsOffset); } // Load Multiplayer Object Table if (Engine.MultiplayerObjectCollection != null) { LoadMPObjectTable(_mpObjectsOffset); } // Load Insertion Points LoadInsertionPoints(_insertionOffset); // Load Default Author Name if (Engine.UsesDefaultAuthor) { _stream.SeekTo(_defaultAuthorOffset); _mapInformation.DefaultAuthor = _stream.ReadAscii(); } }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> public static ICacheFile LoadCacheFile(IReader reader, EngineDatabase engineDb) { EngineDescription tempDesc; return LoadCacheFile(reader, engineDb, out tempDesc); }
// Patch Applying private void btnApplyPatch_Click(object sender, RoutedEventArgs e) { try { // Check the user isn't completly retarded if (!CheckAllApplyMandatoryFields() || currentPatch == null) { return; } // Check the output name if (cacheOutputName != "") { if (Path.GetFileNameWithoutExtension(txtApplyPatchOutputMap.Text) != cacheOutputName) { if (MetroMessageBox.Show("Warning", "This patch suggests to use the filename \"" + cacheOutputName + ".map\" to save this map. This filename may be required in order for the map to work correctly.\r\n\r\nAre you sure you want to save this map as \"" + Path.GetFileName(txtApplyPatchOutputMap.Text) + "\"?", MetroMessageBox.MessageBoxButtons.OkCancel) != MetroMessageBox.MessageBoxResult.OK) { Close(); return; } } } // Paths string unmoddedMapPath = txtApplyPatchUnmodifiedMap.Text; string outputPath = txtApplyPatchOutputMap.Text; // Copy the original map to the destination path File.Copy(unmoddedMapPath, outputPath, true); // Open the destination map using (var stream = new EndianStream(File.Open(outputPath, FileMode.Open, FileAccess.ReadWrite), Endian.BigEndian)) { EngineDatabase engineDb = XMLEngineDatabaseLoader.LoadDatabase("Formats/Engines.xml"); ICacheFile cacheFile = CacheFileLoader.LoadCacheFile(stream, outputPath, engineDb); if (currentPatch.MapInternalName != null && cacheFile.InternalName != currentPatch.MapInternalName) { MetroMessageBox.Show("Unable to apply patch", "Hold on there! That patch is for " + currentPatch.MapInternalName + ".map, and the unmodified map file you selected doesn't seem to match that. Find the correct file and try again."); return; } if (!string.IsNullOrEmpty(currentPatch.BuildString) && cacheFile.BuildString != currentPatch.BuildString) { MetroMessageBox.Show("Unable to apply patch", "Hold on there! That patch is for a map with a build version of" + currentPatch.BuildString + ", and the unmodified map file you selected doesn't seem to match that. Find the correct file and try again."); return; } // Apply the patch! if (currentPatch.MapInternalName == null) { currentPatch.MapInternalName = cacheFile.InternalName; } // Because Ascension doesn't include this, and ApplyPatch() will complain otherwise PatchApplier.ApplyPatch(currentPatch, cacheFile, stream); // Check for blf snaps if (cbApplyPatchBlfExtraction.IsChecked != null && (PatchApplicationPatchExtra.Visibility == Visibility.Visible && (bool)cbApplyPatchBlfExtraction.IsChecked)) { string extractDir = Path.GetDirectoryName(outputPath); string blfDirectory = Path.Combine(extractDir, "images"); string infDirectory = Path.Combine(extractDir, "info"); if (!Directory.Exists(blfDirectory)) { Directory.CreateDirectory(blfDirectory); } if (!Directory.Exists(infDirectory)) { Directory.CreateDirectory(infDirectory); } string infPath = Path.Combine(infDirectory, Path.GetFileName(currentPatch.CustomBlfContent.MapInfoFileName)); File.WriteAllBytes(infPath, currentPatch.CustomBlfContent.MapInfo); foreach (BlfContainerEntry blfContainerEntry in currentPatch.CustomBlfContent.BlfContainerEntries) { string blfPath = Path.Combine(blfDirectory, Path.GetFileName(blfContainerEntry.FileName)); File.WriteAllBytes(blfPath, blfContainerEntry.BlfContainer); } } } MetroMessageBox.Show("Patch Applied!", "Your patch has been applied successfully. Have fun!"); } catch (Exception ex) { MetroException.Show(ex); } }
/// <summary> /// Loads a cache file from a stream. /// </summary> /// <param name="reader">The stream to read from.</param> /// <param name="engineDb">The engine database to use to process the cache file.</param> /// <returns>The cache file that was loaded.</returns> /// <exception cref="ArgumentException">Thrown if the cache file is invalid.</exception> /// <exception cref="NotSupportedException">Thrown if the cache file's target engine is not supported.</exception> //public static ICacheFile LoadCacheFile(IReader map_reader, IReader tag_reader, IReader string_reader, EngineDatabase engineDb) public static ICacheFile LoadCacheFile(IReader map_reader, EngineDatabase engineDb) { EngineDescription tempDesc; string ns = null; return LoadCacheFile(map_reader, null, null, out ns, null, engineDb, out tempDesc); }