private void WriteVersion() { // add underscore character Patch.Apply(rom, Resources.ZM_U_underscore); // format config string string temp = "Settings: " + settings.GetString(); int lineWidth = 0; string config = ""; foreach (char c in temp) { int charWidth = Text.GetCharWidth(rom, c); if (lineWidth + charWidth < 220) { lineWidth += charWidth; } else { config += '\n'; lineWidth = charWidth; } config += c; } // MZM Randomizer v1.4.0 // Seed: <seed> // Settings: <settings> string text = $"MZM Randomizer v{Program.Version}\n" + $"Seed: {seed}\n{config}\n"; byte[] values = Text.BytesFromText(text); rom.ArrayToRom(values, 0, Rom.IntroTextOffset, values.Length); }
public bool Randomize() { // allow palettes to be randomized separately Random rng = new Random(seed); // randomize palette randPals = new RandomPalettes(rom, settings, rng); randPals.Randomize(); rng = new Random(seed); // randomize items randItems = new RandomItems(rom, settings, rng); bool success = randItems.Randomize(); if (!success) { return(false); } // randomize enemies randEnemies = new RandomEnemies(rom, settings, rng); randEnemies.Randomize(); // randomize music //randMusic = new RandomMusic(rom, settings, rng); //randMusic.Randomize(); ApplyTweaks(); DrawFileSelectHash(); WriteVersion(); Patch.Apply(rom, Resources.ZM_U_titleGraphics); return(true); }
public void Apply_Sequence() { // Set original and expected string original_text = "hello"; string expected_text = "eblol"; // Encode the original UTF-8 text to byte array byte[] original_bytes = Encoding.UTF8.GetBytes(original_text); // Create the edit script to patch original to expected EditScript script = new EditScript(); script.Add(new Replacement(2, 98)); script.Add(new Deletion(0)); script.Add(new Insertion(4, 108)); // Create the Patchup patch from the edit script Patch patch = new Patch { EditScript = script }; // Apply the Patchup patch to the data byte[] patched_data = patch.Apply(original_bytes); // Decode the patched byte array back to UTF-8 text string patched_text = Encoding.UTF8.GetString(patched_data); Assert.Equal(expected_text, patched_text); }
/// <summary> /// Re-enables the hook if it has been disabled, causing all functions to be once again re-routed to your own function. /// </summary> public void Enable() { if (IsHookActivated) { _enableHookPatch.Apply(); IsHookEnabled = true; } }
private void OnRequestApplyPlaybackPatch() { if (MessageBox.Show("This will apply a patch to the *.dol file displayed in thie editor's title bar that permanently removes song playback when conducting Wind Waker songs.\n\nAre you sure you want to continue?", "Apply Patch?", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { Patch songPlaybackPatch = JsonConvert.DeserializeObject <Patch>(File.ReadAllText(@"resources\patches\disable_song_playback.json")); songPlaybackPatch.Apply(WSettingsManager.GetSettings().RootDirectoryPath); } }
/// <summary> /// Temporarily disables the hook, causing all functions re-routed to your own function to be re-routed back to the original function instead. /// </summary> /// <remarks>This is implemented in such a fashion that the hook shall never touch C# code.</remarks> public void Disable() { if (IsHookActivated) { _disableHookPatch.Apply(); IsHookEnabled = false; } }
private void DrawFileSelectHash() { // apply tweak for hash icons Patch.Apply(rom, Resources.ZM_U_hashIcons); // compute the hash based on settings and seed string s = settings.GetString() + seed; byte[] bytes = Encoding.ASCII.GetBytes(s); int hash = 5381; foreach (byte b in bytes) { hash = (hash << 5) + hash + b; } const int palPtr = 0x7C7CC; const int gfxPtr = 0x7C7E0; const int tmPtr = 0x7C80C; // get palette, graphics, and tile table int palOffset = rom.ReadPtr(palPtr); Palette filePal = new Palette(rom, palOffset, 7, palPtr); Gfx fileGfx = new Gfx(rom, gfxPtr, 32); Tilemap fileTm = new Tilemap(rom, tmPtr, true); for (int i = 0; i < 4; i++) { int index = hash & 15; hash >>= 4; ItemType item = (index + ItemType.Super); // modify palette filePal.AppendPalette(item.AbilityPalette()); // modify graphics Gfx itemGfx = item.AbilityGraphics(); Rectangle rect = new Rectangle(0, 0, 2, 2); fileGfx.AddGfx(itemGfx, rect, i * 3, 17); // modify tile table int x = 9 + i * 3; int pal = i + 7; fileTm.SetPalette(pal, x, 1); fileTm.SetPalette(pal, x, 2); fileTm.SetPalette(pal, x + 1, 1); fileTm.SetPalette(pal, x + 1, 2); fileTm.SetTileNumber(0, x + 2, 1); fileTm.SetTileNumber(0, x + 2, 2); } // write palette, graphics, and tile table filePal.Write(); fileGfx.Write(); fileTm.Write(); }
/* User Functionality */ /// <summary> /// Performs a one time activation of the hook. /// This function should only ever be called once. /// </summary> public IAsmHook Activate() { if (!_activated) { _activated = true; _activateHookPatch.Apply(); _enableHookPatch.ApplyUnsafe(); } return(this); }
/// <summary> /// Activates our hook. /// </summary> /// <remarks> /// This function should be called after instantiation as soon as possible, /// preferably in the same line as instantiation. /// /// This class exists such that we don't run into concurrency issues on /// attaching to other processes whereby the following happens: /// /// A. Original process calls a function that was just hooked. /// B. Create function has not yet returned, and OriginalFunction is unassigned. /// C. Hook tried to call OriginalFunction. NullReferenceException. /// </remarks> public IHook <TFunction> Activate() { _hookPatch.Apply(); foreach (var hookPatch in _otherHookPatches) { hookPatch.Apply(); } return(this); }
public IEnumerable <string> Patch([FromBody] Patch <Person> person) { string original = _person.ToString(); person.Apply(_person); return(new[] { $"old: {original}", $"new: {_person.ToString()}" }); }
void when_applying() { act = () => patch.Apply(); it["should replace the bytes"] = () => memory.ReadBytes(buffer, 4).should_be(replaceWith); it["should be applied"] = () => patch.IsApplied.should_be_true(); context["when removed"] = () => { act = () => patch.Remove(); it["should restore the original bytes"] = () => memory.ReadBytes(buffer, 4).should_be(new[] { 0, 0, 0, 0 }); it["should not be applied"] = () => patch.IsApplied.should_be_false(); }; }
public override bool Randomize() { if (!settings.SwapOrRemoveItems) { return(true); } Initialize(); // apply base changes Patch.Apply(rom, Properties.Resources.ZM_U_randoBase); var remainingLocationsBackup = new List <int>(remainingLocations); var remainingItemsBackup = new List <ItemType>(remainingItems); int attempts = 0; while (attempts < maxAttempts) { bool success = TryRandomize(); attempts++; if (success) { break; } else { // copy backups remainingLocations = new List <int>(remainingLocationsBackup); remainingItems = new List <ItemType>(remainingItemsBackup); } } Console.WriteLine($"Item randomization attempts: {attempts}"); if (attempts >= maxAttempts) { return(false); } rom.FindEndOfData(); WriteAssignments(); FinalChanges(); return(true); }
private static void Testv1( ) { var folder = @"Resources\Assembly-1.0\ProviderTestLib.dll"; var assembly = LoadAssembly(folder); var snapshot = SnapShot.BuildFrom(assembly); Assert.IsFalse(snapshot.IsEmpty); Assert.IsTrue(snapshot.Settings.Count == 1); Assert.IsTrue(snapshot.ConnectionStrings.Count == 0); var patch1 = new Patch(snapshot, Patch.Action.ActionType.Insert); patch1.Apply(new Patch.ApplyOptions()); snapshot = SnapShot.GetFor(snapshot.Section); Assert.IsFalse(snapshot.IsEmpty); Assert.IsTrue(snapshot.Settings.Count == 1); Assert.IsTrue(snapshot.ConnectionStrings.Count == 0); }
private void FinalChanges() { // modify pirate PB graphics PiratePB(); // fix charge beam OAM if (locations[Location.ChargeBeamst].NewItem != ItemType.Charge) { Patch.Apply(rom, Properties.Resources.ZM_U_fixChargeOAM); } // set clipdata for imago cocoon right side ItemType item = locations[Location.ImagoCocoon].NewItem; rom.Write8(0x67A199, item.Clipdata(true)); // fix number of tanks per area WriteNumTanksPerArea(); // chozo statue hints if (settings.ChozoStatueHints) { Patch.Apply(rom, Properties.Resources.ZM_U_fixChozoHints); WriteChozoStatueHints(); } else { Patch.Apply(rom, Properties.Resources.ZM_U_removeChozoHints); } // remove items from minimap if (settings.NumItemsRemoved > 0) { RemoveMinimapItems(); } // set percent for 100% ending byte percent = (byte)(99 - settings.NumItemsRemoved); rom.Write8(0x87BB8, percent); }
public void Apply_Replacement() { string original_text = "hello"; string expected_text = "bello"; // Convert byte[] original_bytes = Encoding.UTF8.GetBytes(original_text); EditScript script = new EditScript(); script.Add(new Replacement(0, 98)); Patch patch = new Patch { EditScript = script }; byte[] patched_data = patch.Apply(original_bytes); string patched_text = Encoding.UTF8.GetString(patched_data); Assert.Equal(expected_text, patched_text); }
private void ApplyTweaks() { if (settings.IceNotRequired) { Patch.Apply(rom, Resources.ZM_U_metroidIce); } if (settings.PlasmaNotRequired) { Patch.Apply(rom, Resources.ZM_U_blackPiratePlasma); } if (settings.EnableItemToggle) { Patch.Apply(rom, Resources.ZM_U_itemToggle); } if (settings.ObtainUnkItems) { Patch.Apply(rom, Resources.ZM_U_unkItems); } if (settings.HardModeAvailable) { Patch.Apply(rom, Resources.ZM_U_hardModeAvailable); } if (settings.PauseScreenInfo) { Patch.Apply(rom, Resources.ZM_U_pauseScreenInfo); } if (settings.RemoveCutscenes) { Patch.Apply(rom, Resources.ZM_U_removeCutscenes); } if (settings.SkipSuitless) { Patch.Apply(rom, Resources.ZM_U_skipSuitless); } if (settings.SkipDoorTransitions) { Patch.Apply(rom, Resources.ZM_U_skipDoorTransitions); } }
public void ApplyTest() { var rom = Tests.TestRom; byte[] patch = new byte[] { 0x50, 0x41, 0x54, 0x43, 0x48, // "PATCH" 0x00, 0x00, 0xAC, // offset 0x00, 0x04, // length 0x54, 0x45, 0x53, 0x54, // data 0x45, 0x4F, 0x46 // "EOF" }; Patch.Apply(rom, patch); byte[] actual = rom.Data; byte[] expected = Tests.TestRom.Data; expected[0xAC] = 0x54; expected[0xAD] = 0x45; expected[0xAE] = 0x53; expected[0xAF] = 0x54; CollectionAssert.AreEqual(expected, actual); }
public void Build_WeirdCase2() { // Set and encode from string from = "joker"; var from_bytes = Encoding.UTF8.GetBytes(from); // Set and encode to string to = "i"; var to_bytes = Encoding.UTF8.GetBytes(to); // Build the patch Patch patch = new Patch(); patch.Build(from_bytes, to_bytes); // Apply the patch byte[] expectedPatched = to_bytes; byte[] actualPatched = patch.Apply(from_bytes); // Test for equality Assert.Equal(expectedPatched, actualPatched); }
/// <summary> /// Performs a one time activation of the hook, making the necessary memory writes to permanently commit the hook. /// </summary> /// <remarks> /// This function should be called after instantiation as soon as possible, /// preferably in the same line as instantiation. /// /// This class exists such that we don't run into concurrency issues on /// attaching to other processes whereby the following happens: /// /// A. Original process calls a function that was just hooked. /// B. Create function has not yet returned, and OriginalFunction is unassigned. /// C. Hook tried to call OriginalFunction. NullReferenceException. /// </remarks> public IHook <TFunction> Activate() { /* Create enable/disable patch. */ var disableOpCodes = Utilities.AssembleAbsoluteJump(OriginalFunctionAddress, false); CurrentProcess.SafeReadRaw(ReverseWrapper.WrapperPointer, out var originalOpcodes, disableOpCodes.Length); _disableHookPatch = new Patch(ReverseWrapper.WrapperPointer, disableOpCodes); _enableHookPatch = new Patch(ReverseWrapper.WrapperPointer, originalOpcodes); /* Activate the hook. */ _hookPatch.Apply(); foreach (var hookPatch in _otherHookPatches) { hookPatch.Apply(); } /* Set flags. */ IsHookEnabled = true; IsHookActivated = true; return(this); }
private void OkClicked(object sender, RoutedEventArgs e) { Close(); if (PatchFileName == null || (!PatchInstalledSets && (!PatchFolder || TargetFolderName == null))) { return; } var patch = new Patch(PatchFileName); var dlg = new PatchProgressDialog { Owner = Owner }; patch.Progress += dlg.UpdateProgress; // Capture variables to prevent a cross-thread call to dependency properties. bool patchInstalledSets = PatchInstalledSets; string targetFolder = PatchFolder ? TargetFolderName : null; ThreadPool.QueueUserWorkItem( _ => patch.Apply(Program.GamesRepository, patchInstalledSets, targetFolder)); dlg.ShowDialog(); }
private void btnSaveRom_Click(object sender, EventArgs e) { if (rm != null) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "ROM Files (*.z64)|*.z64"; saveFileDialog.FilterIndex = 1; saveFileDialog.RestoreDirectory = true; saveFileDialog.FileName = romName + " - " + seed.ToString(); if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { File.WriteAllBytes(saveFileDialog.FileName, rm.rom); if (chkWarpPatch.Checked) { Patch p = new Patch(AppDomain.CurrentDomain.BaseDirectory + "patches\\warpfadefix"); p.Apply(rm); Patch.FixChksum(saveFileDialog.FileName); } MessageBox.Show("Your ROM was saved!", "Done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch (IOException) { MessageBox.Show("Failed to load!", "-_-", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } else { MessageBox.Show("Open a ROM File First!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Apply() { Patch.Apply(); }
protected override int Run(string command) { if (String.IsNullOrEmpty(name) && String.IsNullOrEmpty(path)) { Out.WriteLine("you must define either the name or the path of the assembly to check"); return -1; } Assembly assembly = Tools.LoadAssembly(name, path); SnapShot assemblySettings = SnapShot.BuildFrom(assembly); SnapShot databaseSettings = SnapShot.GetFor(assembly); Patch patch = new Patch(databaseSettings, assemblySettings); if (patch.IsEmpty) Out.WriteLine("database is already in sync"); if (!noPrompt) { Console.WriteLine(patch.ToString()); Console.Write("apply the patch? (y)es > "); string responce = Console.ReadLine(); if (!responce.ToLower().StartsWith("y")) return 0; } patch.Apply(new Patch.ApplyOptions()); return 0; }
static void Main(string[] args) { //using (Patch p = new Patch(args[1])) //{ // p.PrintHeaders(); // p.Apply(args[0], args[2], true); //} string[] oldfiles = Directory.GetFiles(args[0], "*.*", SearchOption.AllDirectories); string[] ptchs = Directory.GetFiles(args[1], "*.*", SearchOption.AllDirectories); foreach (string of in oldfiles) { if (skipFiles.Contains(Path.GetFileName(of))) continue; if (ptchs.Any(s => s.Substring(args[1].Length) == of.Substring(args[0].Length))) { Console.WriteLine("has patch for {0}", of); //string patch = Path.Combine(args[1], of.Substring(args[0].Length)); string patch = args[1] + of.Substring(args[0].Length); FileInfo fi = new FileInfo(patch); if (fi.Length == 0) // removed continue; try { using (Patch p = new Patch(patch)) { //p.PrintHeaders(); p.Apply(of, args[2] + of.Substring(args[0].Length), true); } } catch (InvalidDataException) { File.Copy(of, args[2] + of.Substring(args[0].Length), true); } } else { string file = args[2] + of.Substring(args[0].Length); if (!Directory.Exists(Path.GetDirectoryName(file))) Directory.CreateDirectory(Path.GetDirectoryName(file)); File.Copy(of, file, true); } } foreach (string pf in ptchs) { FileInfo fi = new FileInfo(pf); if (fi.Length == 0) // removed continue; string newfile = args[2] + pf.Substring(args[1].Length); try { using (Patch p = new Patch(pf)) { //p.PrintHeaders(); if (p.PatchType != "COPY") continue; Console.WriteLine("new file {0}", newfile); p.Apply("oldfile", newfile, true); } } catch (InvalidDataException) { File.Copy(pf, newfile, true); } } }
static void Main(string[] args) { //using (Patch p = new Patch(args[1])) //{ // p.PrintHeaders(); // p.Apply(args[0], args[2], true); //} string[] oldfiles = Directory.GetFiles(args[0], "*.*", SearchOption.AllDirectories); string[] ptchs = Directory.GetFiles(args[1], "*.*", SearchOption.AllDirectories); foreach (string of in oldfiles) { if (skipFiles.Contains(Path.GetFileName(of))) { continue; } if (ptchs.Any(s => s.Substring(args[1].Length) == of.Substring(args[0].Length))) { Console.WriteLine("has patch for {0}", of); //string patch = Path.Combine(args[1], of.Substring(args[0].Length)); string patch = args[1] + of.Substring(args[0].Length); FileInfo fi = new FileInfo(patch); if (fi.Length == 0) // removed { continue; } try { using (Patch p = new Patch(patch)) { //p.PrintHeaders(); p.Apply(of, args[2] + of.Substring(args[0].Length), true); } } catch (InvalidDataException) { File.Copy(of, args[2] + of.Substring(args[0].Length), true); } } else { string file = args[2] + of.Substring(args[0].Length); if (!Directory.Exists(Path.GetDirectoryName(file))) { Directory.CreateDirectory(Path.GetDirectoryName(file)); } File.Copy(of, file, true); } } foreach (string pf in ptchs) { FileInfo fi = new FileInfo(pf); if (fi.Length == 0) // removed { continue; } string newfile = args[2] + pf.Substring(args[1].Length); try { using (Patch p = new Patch(pf)) { //p.PrintHeaders(); if (p.PatchType != "COPY") { continue; } Console.WriteLine("new file {0}", newfile); p.Apply("oldfile", newfile, true); } } catch (InvalidDataException) { File.Copy(pf, newfile, true); } } }
public void TestEmptyPatch() { var empty = new Patch(); empty.Apply(new Patch.ApplyOptions()); }
private static void ClearSection(string sectionName) { var section = SnapShot.GetFor(sectionName); var patch = new Patch(section, Patch.Action.ActionType.Delete); patch.Apply(new Patch.ApplyOptions()); }