1 line
No EOL
146 KiB
JSON
1 line
No EOL
146 KiB
JSON
[{"uri":"/apireference/changelog.html","title":"Changelog","tags":[],"description":"","content":"Changes between 0.9.7 and 0.9.8 New Features New function to get a label\u0026rsquo;s current CPU address: getLabelAddress Changes between 0.9.6 and 0.9.7 No changes.\nChanges between 0.9.5 and 0.9.6 New Features New event callback: scriptEnded. New functions to get PRG/CHR ROM offsets based on a CPU/PPU address: getPrgRomOffsetand getChrRomOffset. New function for use with the test runner mode: stop Changes The end address parameter for addMemoryCallbackand removeMemoryCallbackis now optional. The drawRectanglefunction now accepts negative height/width values. Added a new delay parameter to drawRectangle, drawLine, drawStringand drawPixel. Breaking Changes addMemoryCallbackand removeMemoryCallbackno longer exclude the end address from the range. The endFrameevent now triggers on scanline 240 instead of scanline 241. Changes between 0.9.4 and 0.9.5 New features New functions:\n getScreenBuffer setScreenBuffer getAccessCounters resetAccessCounters New enums:\n counterMemType counterOpType Changes between 0.9.3 and 0.9.4 New features New functions:\n getLogWindowLog getRomInfo getScriptDataFolder isKeyPressed clearSavestateData getSavestateData loadSavestateAsync saveSavestateAsync New event callbacks: inputPolled, stateLoaded, stateSaved\n New memory types: cpuDebug, ppuDebug\n Breaking changes Removed the debugRead, debugReadWord, debugWrite and debugWriteWord functions. They have been replaced by the memType.cpuDebug and memType.ppuDebug enum values. The behavior of the setInput function has changed. The return values for the APU portion of the getState function has slightly changed. "},{"uri":"/gettingstarted.html","title":"Getting Started","tags":[],"description":"","content":"System Requirements Windows Windows Vista, 7, 8, 8.1 and 10 are supported DirectX 11 .NET Framework 4.5+ Linux glibc 2.24+ Mono 5.18+ SDL 2 Installation There is no actual installer for Mesen \u0026ndash; run the Mesen.exe application and a first-run configuration wizard will be shown.\nData Storage Location: This section of the wizard allows you to select where you prefer to keep Mesen\u0026rsquo;s files.\nInput Mappings: Select which input types you want to use to play games. There are built-in presets for:\n Xbox controllers PS4 controllers WASD keyboard layout Arrow keyboard layout You can select multiple presets at once, but only a single keyboard layout.\nCreate a shortcut on my desktop: Check this option if you want to add a Mesen shortcut to your desktop.\nUsing Mesen Mesen\u0026rsquo;s default configuration should work out of the box and allow you to get right into playing games.\nTo load a game, use the File→Open command and select any supported file (.nes, .fds, .nsf, .nsfe, .unf) you want to load.\nOnce a game is loaded, you can pause, reset or stop the game via the Game menu.\nThe game menu also contains additional options for Famicom Disk System (FDS) games and VS System games.\nFamicom Disk System (FDS) games FDS games were originally stored on floppy disks - sometimes split across multiple disks and disk sides. The Game menu contains a number of additional shortcuts for FDS games to handle these:\n Switch Disk Side: Switches between sides A and B of the current disk. Select Disk: Allows you to select any disk and side combination availble for the current game. Eject Disk: Ejects the current disk. Ejecting the disk is usually unnecessary and only available for the sake of completeness. VS System games VS System games were originally in the form of arcade cabinets \u0026ndash; unlike FDS games, playing them does not require any special BIOS.\nBeing arcade cabinets, VS System games typically require the player to insert coins before the game can be played. Additionally, the arcade cabinets could often be configured via a number of physical DIP switches \u0026ndash; for example, to select how much money needs to be inserted to play, or to alter a game\u0026rsquo;s difficulty. The Game menu offers additional options when playing VS System games to handle these:\n Game Configuration: Displays a configuration dialog containing the DIP switch options available for this game. Insert Coin 1: Inserts a coin into the first coin slot. Insert Coin 2: Inserts a coin into the second coin slot. NSF Player NSF and NSFe files are used to store music from NES and Famicom games.\nWhen loading NSF files into Mesen, the UI will change into a media player style UI. From this UI, you can control the volume, select the track, pause the music or fast forward by holding down the mouse button.\nAdditionally, the two icons at the top right allow you to toggle the repeat and shuffle playback modes.\nGame Selection Screen The game selection screen is shown when no game is currently loaded \u0026ndash; it will display the last games you\u0026rsquo;ve played, along with a screenshot of the game at the point where you left off playing. The number of games shown depends on the window\u0026rsquo;s size.\nYou can use this screen via the key bindings for player 1 - e.g press the d-pad to change selection, and the A button to start the game. You can also navigate the screen with your mouse \u0026ndash; use the arrows on each side of the screen to change game, and click on the game\u0026rsquo;s screenshot to start playing.\nShortcut Keys Mesen has a number of shortcut keys that you may find useful:\n Ctrl-O: Open a file Ctrl-R: Reset the game Escape: Pause/resume the game Alt-1 to Alt-6: Change the video scale. F1 to F8: Load save state in the corresponding slot. Shift-F1 to Shift-F7: Save a save state in the corresponding slot. Ctrl-S: Manually save a save state to a file. Ctrl-L: Manually load a save state from a file. Tab: Hold the tab key to fast forward the emulation (defaults to 300% speed) Backspace: Hold the backspace key to rewind the emulation, frame-by-frame. The shortcut keys can be customized in the preferences.\nCommand-line Options Mesen supports a large number of command-line options.\nTo see a full list and some examples, click on the Help→Command-line Options menu option.\n"},{"uri":"/","title":"Home","tags":[],"description":"","content":"Table of contents Getting Started Configuration Audio Options Input Options Video Options Emulation Options Preferences Tools Netplay Movies Cheats Sound Recorder Video Recorder Log Window Debugging Tools Assembler Debugger Event Viewer Memory Tools Performance Profiler PPU Viewer Script Window Text Hooker Trace Logger Integration with CC65/ASM6 HD Packs Lua API reference "},{"uri":"/configuration/audio.html","title":"Audio Options","tags":[],"description":"","content":"General Options Audio Device: Selects which device is used for audio output (e.g computer speakers, or a headset)\nSample Rate: Selects the sample rate for the audio output \u0026ndash; typically, computers output at 44,100Hz or 48,000Hz, so they usually offer the best sound quality.\nLatency: This represents the length of the buffer used in audio processing. A smaller value results in less delay between the audio and video, however, depending on the hardware used, a value that is too small may cause sound problems.\nIn addition, the volume and panning of each sound channel can be adjusted. For more control over the actual sound, the equalizer can be used to alter the relative strength of specific frequencies \u0026ndash; with work, this can be used to make the audio sound more like an actual NES would.\nA number of audio effects are available in the Effects tab, including a few different fake stereo effects.\nAdvanced Options Unlike all the other options before it, the options in this section affect the way the sound is emulated.\n Mute ultrasonic frequencies on the triangle channel: This option mutes the triangle channel under certain conditions, which prevents it from causing popping sounds.\n Reduce popping sounds on the DMC channel: Similar to the previous option, but for the DMC channel \u0026ndash; this option prevents games from changing the output of the DMC channel too abruptly, which often causes popping sounds.\n Disable dynamic sample rate: While a game is running, the video and audio typically slowly drift out of sync. Mesen will automatically make adjustments to the audio sample rate while the game is running to keep them in sync. Disabling this option will typically cause sound issues such as crackling.\n Swap square channel duty cycles: This option is to mimic some older NES clones that had incorrect sound output for both of the square channels. It greatly alters the sound in some games, and shouldn\u0026rsquo;t be enabled unless you want this behavior.\n Disable noise channel mode flag: Very early Famicom models did not implement this feature, so this option is available to mimic early Famicom consoles. It changes the sound output of the noise channel in some games, and shouldn\u0026rsquo;t be enabled unless you want this behavior.\n EPSG Clock Frequency (default is 3579545Hz): This option sets the base frequency the Yamaha Sound Chip works at, it mainly affect pitch and timings. simply how it calculates sound. The YMF288 it made to work at 8Mhz, but 3.579545Mhz is used as default so it matches up with S5b.\n "},{"uri":"/configuration.html","title":"Configuration","tags":[],"description":"","content":"Options Menu The options menu contains a number of shortcuts to change some popular settings:\nSpeed: Selects the emulation\u0026rsquo;s current speed. Also see the Rewind and Fast Forward shortcut keys.\nVideo Size: Selects the picture\u0026rsquo;s size \u0026ndash; when fullscreen is selected, the picture will automatically fill the screen. Additionally, you can also manually resize the window to select any size you prefer.\nVideo Filter: Selects a filter to apply to the picture. The NTSC filters attempt to reproduce the feeling of old CRT screens, while the other filters are a variety of different techniques used to scale up pixel art. Additional NTSC filter specific settings are available in the video options.\nRegion: When set to Auto, the emulator will try to detect the game\u0026rsquo;s region (NTSC or PAL) - however, this is not always possible. When there is nothing to suggest a game is for the PAL region (Australia \u0026amp; Europe), the NTSC region (North America \u0026amp; Japan) will be used by default. Dendy is used to mimic a number of different NES clones, in particular, the Dendy, which was a popular clone in Russia.\nConfiguration Dialogs Additional settings can be found in each of the available menu options:\n Audio Options Input Options Video Options Emulation Options Preferences "},{"uri":"/tools.html","title":"Tools","tags":[],"description":"","content":"Netplay Hosting a game Server name: This name will be shown to clients when they connect.\nPort: The port used for the communication. Mesen will attempt to automatically port-forward this port on your router when you start the server \u0026ndash; if this fails, you will have to manually forward the port on your router to allow people outside of your LAN to connect to your server.\nThe other options on this screen have not been implemented yet and are disabled for now.\nConnecting to a server Host: The host name of the server you want to connect to. This is usually an IP address but can also be a domain name.\nPort: The port to connect to \u0026ndash; this must match the Port value used by the server\u0026rsquo;s host.\nJoin as a spectator: When enabled, you will join the server without taking control of a specific controller. An unlimited number of spectators can join a game, but only 4 people can take control of a controller.\nOnce you are connected to a server, you can select your controller via the Tools→Netplay→Select Controller menu.\nMovies Movies are files that can be created by Mesen and played back within Mesen itself. They are essentially a recording of the events that occurred during recording. To record an actual video file, see Video Recorder.\nWhen you start recording, a configuration dialog is shown that allows you to select a number of options.\n Save to: The location where the movie will be saved. Press the Browse button to change it. Record from: Selects where the recording should start: Power on: This will reset the game and start recording from the start. Your save data (.sav files) will be excluded from the movie file - after the reset, you will start the game as if it had never been run yet. Power on, with save data: This will reset the game and start recording from the start. Your save data (.sav files, etc.) will be included in the movie file. Current state: This will start recording from the current state \u0026ndash; in this case, the movie file will contain a save state. Author: The movie\u0026rsquo;s author (optional) - this will be saved in the movie file. Description: A description of the movie\u0026rsquo;s content (optional) - this will be saved in the movie file. To play a movie file, select it via the Tools→Movies→Play command.\nHistory Viewer The history viewer allows you to replay (in a video player) any gameplay since the last time you power cycled or loaded a game.\nYou can start playback at any point in time, and instantly seek to any point in time, too.\nTo resume gameplay from the history viewer\u0026rsquo;s current position, select File→Resume Gameplay\nTo create a save state for the current position, select File→Create Save State\nTo export a movie (.mmo file) of your gameplay, select File→Export Movie\nWhen exporting a movie, you can select the specific time range you want to export.\nCheats Mesen supports cheats in a number of different formats, including Game Genie and Pro Action Rocky codes.\nIt is also possible to import cheats from the built-in Cheat Database or from XML or CHT files.\nSelect a game on the left to see all the cheats currently available for that game.\nTo add a new cheat code, click the Add Cheat button.\nTo edit a cheat code, double-click on it in the list.\nTo delete a cheat code, select it from the list and click the Delete button.\nTo import cheats, click the Import button.\nTo export cheats to an XML file, click the Export button.\nTo disable a specific cheat, uncheck it from the list.\nTo disable all cheats, check the Disable all cheats option.\nAdding/Editing Cheats When adding a cheat, you must first select the game to which it should be applied. By default, the game that is currently loaded will be selected.\nYou must give each cheat a name, which will be used to display it in the cheats list.\nThe Code section lets you enter the actual cheat \u0026ndash; select Game Genie for Game Genie codes.\nIf you want to create a custom code, select the Custom action.\nWhen creating custom codes, the Memory / Game Code options select whether the code should be applied to a specific CPU address (Memory) or a specific offset in the PRG ROM (Game Code).\nImporting Cheats From the Cheat Database To import from the cheats database, click Import and select From Cheat Database.\nIn the next dialog, select the game for which you want to import cheats. You can type in the Search bar at the top to filter the game list. Once you\u0026rsquo;ve selected a game, press OK \u0026ndash; this will import all cheats for that game into the cheats list. You can then manually enable any cheat you want to use.\nBy default, the game that is currently loaded will be selected for you. Having no game selected when the dialog opens indicates that there are no built-in cheats available for the game that is currently running.\nFrom XML/CHT files To import cheats from external files (FCEUX\u0026rsquo;s .cht files or Nestopia\u0026rsquo;s .xml files), click Import, and select From File (XML, CHT).\nIn the next dialog, select the file you want to import.\nFor FCEUX\u0026rsquo;s .cht files, you will also need to select the game for which you are importing cheats for.\nOnce you\u0026rsquo;re done, click OK \u0026ndash; the cheats will be imported and added to the cheats list.\nSound Recorder The sound recorder allows you to record uncompressed .wav files. The .wav file will use the exact same output settings as Mesen\u0026rsquo;s audio options \u0026ndash; this means the sample rate will match Mesen\u0026rsquo;s current sample rate, and that any sound modification (volume, panning, equalizer or effects) will also be applied to the .wav files.\nTo start recording, use the Tools→Sound Recorder→Record command.\nTo stop an on-going recording, use the Tools→Sound Recorder→Stop Recording command.\nVideo Recorder Much like the sound recorder, the video recorder allows you to record .avi files.\nBefore you start a recording, you can select where to save the .avi file and which video codec to use. All video codecs are lossless codecs \u0026ndash; the only reason to reduce the compression level to a lower level is to improve performance in the event your computer is having a hard time recording the video and running the emulation at its normal speed at the same time.\nTo start recording, use the Tools→Video Recorder→Record command.\nTo stop an on-going recording, use the Tools→Video Recorder→Stop Recording command.\nLog Window The Log Window displays a number of useful information \u0026ndash; mostly about the roms you load.\nIt is also sometimes used as a way to log errors or warnings.\nDebugger See Debugging Tools\nHD Pack Builder See HD Packs\n"},{"uri":"/apireference/callbacks.html","title":"Callbacks","tags":[],"description":"","content":"addEventCallback Syntax\nemu.addEventCallback(function, type) Parameters\nfunction - A Lua function.\ntype - Enum See eventType.\nReturn value\nReturns an integer value that can be used to remove the callback by calling removeEventCallback.\nDescription\nRegisters a callback function to be called whenever the specified event occurs.\nThe callback function receives no parameters.\nremoveEventCallback Syntax\nemu.removeEventCallback(reference, type) Parameters\nreference - The value returned by the call to addEventCallback.\ntype - Enum See eventType.\nReturn value\nNone\nDescription\nRemoves a previously registered callback function.\naddMemoryCallback Syntax\nemu.addMemoryCallback(function, type, startAddress [, endAddress]) Parameters\nfunction - A Lua function.\ntype - Enum See memCallbackType\nstartAddress - Integer Start of the CPU memory address range to register the callback on.\nendAddress - (optional) Integer End of the CPU memory address range to register the callback on.\nReturn value\nReturns an integer value that can be used to remove the callback by calling removeMemoryCallback.\nDescription\nRegisters a callback function to be called whenever the specified event occurs.\nThe callback function receives 2 parameters address and value that correspond to the address being written to or read from, and the value that is being read/written.\nFor reads, the callback is called after the read is performed.\nFor writes, the callback is called before the write is performed.\nIf the callback returns an integer value, it will replace the value \u0026ndash; you can alter the results of read/write operation using this. e.g:\nfunction writeCallback(address, value) --This sets bit 0 to 0 for all CHR RAM writes return value \u0026amp; 0xFE end emu.addMemoryCallback(writeCallback, emu.memCallbackType.ppuWrite, 0, 0x1FFF) removeMemoryCallback Syntax\nemu.removeMemoryCallback(reference, type, startAddress [, endAddress]) Parameters\nreference - The value returned by the call to addMemoryCallback.\ntype - Enum See memCallbackType.\nstartAddress - Integer Start of the CPU memory address range to unregister the callback from.\nendAddress - (optional) Integer End of the CPU memory address range to unregister the callback from.\nReturn value\nNone\nDescription\nRemoves a previously registered callback function.\n"},{"uri":"/debugging.html","title":"Debugging Tools","tags":[],"description":"","content":"The debugging capabilities of Mesen are split across a number of different tools, including the debugger itself:\nAPU Viewer: Displays every detail of the APU\u0026rsquo;s current state for each channel.\nAssembler: Allows you to edit a game\u0026rsquo;s code or run custom code on-the-fly.\nDebugger: View the code, add breakpoints, labels, watch values, and much more.\nEvent Viewer: Visualize the timing of a variety of events (register read/writes, nmi, irq, etc.).\nMemory Tools: Contains a hex editor and performance profiler. Performance Profiler: Profiles the CPU\u0026rsquo;s execution to help find bottlenecks in code. PPU Viewer: Displays information on the nametables, sprites, CHR banks and palette. Contains a CHR graphic editor and a palette editor. Script Window: Allows the execution of Lua scripts, which can communicate with the emulation via an API.\nText Hooker: Converts text shown on the screen into a text string (useful when trying to translate games.)\nTrace Logger: View or log to a file the execution trace of the CPU and PPU.\nAdditionally, some other smaller features are available from the main debugger window. e.g:\n Import labels from CA65/CC65 or ASM6 Save any modification done to PRG/CHR ROM via the CHR Viewer, Assembler or the Memory Viewer as a new .nes file, or as an .ips patch file Edit a rom\u0026rsquo;s iNES header "},{"uri":"/hdpacks.html","title":"HD Packs","tags":[],"description":"","content":"HD Packs make it possible to replace a game\u0026rsquo;s graphics and audio with high definition alternatives. This can be used in many ways, for example, one could keep the game\u0026rsquo;s original resolution and simply improve its graphics by adding more colors and shading.\nUsing HD packs Installing HD Packs To install an HD Pack:\n First, load the game for which you want to install the HD Pack. Then, click on the Tools→Install HD Pack menu and select the .zip file that contains the HD Pack you want to install. A message will be shown indicating whether the installation succeeded or failed. Manual installation If the HD Pack installation tool fails to install the HD Pack, you can try to install it manually with these instructions:\nTo use HD packs, first make sure to turn on the Enable HDNes HD Packs option.\nTo install a HD Pack, you should extract it in a subfolder inside the HdPacks folder in Mesen\u0026rsquo;s data folder. You can open this folder by clicking on the Open Mesen Folder button in the Preferences window. The subfolder should have the same name as the rom file itself.\nFor HD packs created with Mesen\u0026rsquo;s HD Pack Builder, you can also put them in .zip format in the HdPacks folder, without unzipping them nor worrying about renaming the file.\nUsing the HD Pack Builder The HD Pack Builder can be used to record a game\u0026rsquo;s graphics into PNG image files and build a matching hires.txt file. These are the 2 basic elements needed for HD Packs: a tile map (the PNG files) and a definition file that specifies where each tile is on the tile map (the hires.txt file).\nThe basic concept of this tool is to use it to record gameplay of a game from start to finish, attempting to trigger every possible animation or graphics during gameplay. This will create a complete set of tiles (saved in PNG files) and a single hires.txt file that contains all that is needed to replace the tiles with HD tiles. Once this is done, the only thing left to do, in most cases, is to replace the graphics in the PNG files with better alternatives (e.g higher resolution, more colors, etc.).\nA number of options exist to control the way the PNG files are generated:\nScale/Filter: Selects the scale and video filter to use when generating the PNG files for the HD Pack. Use the \u0026ldquo;Prescale\u0026rdquo; filters to generate the tiles at a larger scale without applying any transformation to the pixels.\nCHR Bank Size: This option is only available for CHR RAM games. CHR RAM games have no fixed \u0026ldquo;banks\u0026rdquo; - they are dynamically created by the game\u0026rsquo;s code. This option alters the HD Pack Builder\u0026rsquo;s behavior when grouping the tiles into the PNG files - a smaller bank size will usually result in less PNG files (but depending on the game\u0026rsquo;s code, larger values may produce better results).\nGroup blank tiles: This option groups all the blank tiles sequentially into the same PNG files - this helps reduce the number of PNG files produced by removing almost-empty PNG files containing only blank tiles.\nSort pages by usage frequency: When this option is enabled, the tiles in PNG files are sorted by the frequency at which they are shown on the screen while recording (more common palettes will be grouped together in the first PNG for a specific bank number. If this option is unchecked, the PNGs will be sorted by palette - each PNG will only contain up to 4 different colors in this case.\nUse 8x16 sprite display mode: When enabled, this option will alter the display order of CHR banks that contain only sprites to make the sprites easier to edit in the PNG file.\nIgnore tiles at the edges of the screen (overscan): When enabled, this will make the builder ignore any pixels in the overscan area. This is useful in games that contain glitches on the outer edge of the screen. Incorrect palette combinations due to these glitches will be ignored and won\u0026rsquo;t be shown in the PNG files.\nSave frames which the tiles are first shown: When enabled, the builder will save a screenshot and the composition of the screen in the pack folder when it encounters new tile in a frame. This is useful for checking where that tile is used. These files are not needed in the pack and should be deleted when sharing the pack.\nTile Type: This option controls whether only BG tiles or sprite tiles or both are added to the HD Pack.\nBefore you start recording, select the options you want to use and the location to which you want to save the HD Pack, then press the Start Recording button.\nFile Format (hires.txt) The following are the specifications for the hires.txt file, as of version \u0026ldquo;106\u0026rdquo;.\n\u0026lt;ver\u0026gt; tag Syntax: \u0026lt;ver\u0026gt;[integer]\nExample: \u0026lt;ver\u0026gt;106\nThe format\u0026rsquo;s version number (currently 106).\n\u0026lt;scale\u0026gt; tag Syntax: \u0026lt;scale\u0026gt;[integer]\nExample: \u0026lt;scale\u0026gt;4\nThe scale used for the replacement graphics \u0026ndash; this can be any integer number (minimum: 1). Anything above 8-10x will probably have a very hard time running on any computer. It is suggested to use scales between 1x and 4x.\n\u0026lt;overscan\u0026gt; tag Syntax: \u0026lt;overscan\u0026gt;[top],[right],[bottom],[left]\nExample: \u0026lt;overscan\u0026gt;8,8,8,8\nThe overscan values to use when the HD Pack is loaded - this is useful for games that produce glitches on the edges of the screen.\nNote: This feature is only available for HD Packs that contain tile replacement rules. HD Packs that only replace audio cannot use the overscan setting.\n\u0026lt;patch\u0026gt; tag Syntax: \u0026lt;patch\u0026gt;[filename],[sha1 hash]\nExample: \u0026lt;patch\u0026gt;MyPatch.ips,26aec27ef0fc1a6fd282937b918ebdd1fb480891\nSpecifies a patch file to apply if the loaded ROM matches the specified SHA1 hash.\nThe patches can be in either .ips or .bps format. Multiple \u0026lt;patch\u0026gt; tags with different SHA1 hashes can be present in the same hires.txt file.\n\u0026lt;img\u0026gt; tag Syntax: \u0026lt;img\u0026gt;[filename]\nExample: \u0026lt;img\u0026gt;Tileset01.png\nSpecifies a PNG file that contains tile graphics \u0026ndash; each \u0026lt;img\u0026gt; tag is indexed (starting from 0) according to the order it appears in the hires.txt file, the tag\u0026rsquo;s index must be used when using \u0026lt;tile\u0026gt; tags.\n\u0026lt;condition\u0026gt; tag HD Packs support a number of conditionals that can be used to replace graphics when certain conditions are met.\nThis is useful to resolve conflicts that can occur in some games (where the same tile \u0026amp; palette can be reused in multiple distinct objects), etc.\nThe sections below describe every available condition type.\nBuilt-in Conditions A number of built-in conditions can be used to check the value of some flags:\n hmirror: True if the current pixel is a sprite pixel, and the sprite is mirrored horizontally. vmirror: True if the current pixel is a sprite pixel, and the sprite is mirrored vertically. bgpriority: True if the current pixel is a sprite pixel, and the sprite is marked as a background priority sprite. sppalette0: True if the current pixel is a sprite pixel, and the sprite is using the palette at address $3F10. sppalette1: True if the current pixel is a sprite pixel, and the sprite is using the palette at address $3F14. sppalette2: True if the current pixel is a sprite pixel, and the sprite is using the palette at address $3F18. sppalette3: True if the current pixel is a sprite pixel, and the sprite is using the palette at address $3F1C. Example: [hmirror]\u0026lt;tile\u0026gt;...\ntileNearby / spriteNearby The tileNearby and spriteNearby conditions are used to check whether a specific tile or sprite exists in the vicinity of the current pixel. If a matching tile/sprite is found, the condition will be true.\nSyntax: \u0026lt;condition\u0026gt;[name - text], [conditionType - text], [x value - integer], [y value - integer], [tile data], [palette data - hex]\nExample (CHR ROM): \u0026lt;condition\u0026gt;myCondition,tileNearby,8,0,10,0F100017\nExample (CHR RAM): \u0026lt;condition\u0026gt;myCondition,tileNearby,8,0,D2C2C2C7CF2FFEFC2C3C3C3830D00000,0F100017\nNotes:\ntileNearby and spriteNearby use positive or negative X/Y offsets to the current position. e.g:\n\u0026lt;condition\u0026gt;myCondition2,tileNearby,-8,0,[tile data],[palette data]\nIn this case, myCondition2 will be true if the tile 8 pixels to the left of the current tile matches the tile+palette data specified.\nFor CHR ROM games, tile data is an integer (in hexadecimal) representing the position of the original tile in CHR ROM.\nFor CHR RAM games, tile data is a 32-character hexadecimal string representing all 16 bytes of the tile.\npalette data is always an 8-character hexadecimal string representing all 4 bytes of the palette used for the tile. For sprites, the first byte is always \u0026ldquo;FF\u0026rdquo;.\ntileAtPosition / spriteAtPosition The tileAtPosition and spriteAtPosition conditions are used to check whether a specific tile or sprite exists at the specified coordinates. If a matching tile/sprite is found, the condition will be true.\nSyntax: \u0026lt;condition\u0026gt;[name - text], [conditionType - text], [x value - integer], [y value - integer], [tile data], [palette data - hex]\nExample (CHR ROM): \u0026lt;condition\u0026gt;myCondition,tileAtPosition,8,0,10,0F100017\nExample (CHR RAM): \u0026lt;condition\u0026gt;myCondition,tileAtPosition,8,0,D2C2C2C7CF2FFEFC2C3C3C3830D00000,0F100017\nNotes:\ntileAtPosition and spriteAtPosition use the X/Y parameters as screen coordinates. e.g:\n\u0026lt;condition\u0026gt;myCondition,tileAtPosition,10,10,[tile data],[palette data]\nIn this case, myCondition will be true if the tile at position 10,10 on the NES' screen (256x240 resolution) matches the tile+palette data given.\nFor CHR ROM games, tile data is an integer (in hexadecimal) representing the position of the original tile in CHR ROM.\nFor CHR RAM games, tile data is a 32-character hexadecimal string representing all 16 bytes of the tile.\npalette data is always an 8-character hexadecimal string representing all 4 bytes of the palette used for the tile. For sprites, the first byte is always \u0026ldquo;FF\u0026rdquo;.\nmemoryCheck / ppuMemoryCheck The memoryCheck and ppuMemoryCheck conditions are used to compare the value stored at 2 different memory addresses together. (Use the ppuMemoryCheck variant to check PPU memory)\nSyntax: \u0026lt;condition\u0026gt;[name - text], [conditionType - text], [memory address 1 - hex], [operator - string], [memory address 2 - hex], [mask - hex (optional)]\nSupported operators: ==, !=, \u0026gt;, \u0026lt;, \u0026gt;=, \u0026lt;=\nExample: \u0026lt;condition\u0026gt;myCondition,memoryCheck,8FFF,\u0026gt;,8000 (If the value stored at $8FFF is greater than the value stored at $8000, the condition will be true)\nExample (with mask): \u0026lt;condition\u0026gt;myCondition,memoryCheck,8FFF,==,8000,10 (If the bit 4 of the value stored at $8FFF is equal to bit 4 of the value at $8000, the condition will be true. i.e: ([$8FFF] \u0026amp; $10) == ([$8000] \u0026amp; $10))\nmemoryCheckConstant / ppuMemoryCheckConstant The memoryCheck and ppuMemoryCheck conditions are used to compare the value stored at a memory address with a constant. (Use the ppuMemoryCheckConstant variant to check PPU memory)\nSyntax: \u0026lt;condition\u0026gt;[name - text], [conditionType - text], [memory address - hex], [operator - string], [constant - hex], [mask - hex (optional)]\nSupported operators: ==, !=, \u0026gt;, \u0026lt;, \u0026gt;=, \u0026lt;=\nExample: \u0026lt;condition\u0026gt;myCondition,memoryCheckConstant,8FFF,==,3F (If the value stored at $8FFF is equal to $3F, the condition will be true)\nExample (with mask): \u0026lt;condition\u0026gt;myCondition,memoryCheckConstant,8FFF,==,1F,3F (If the value stored at $8FFF ANDed with $3F is equal to $1F then the condition will be true. i.e: ([$8FFF] \u0026amp; $3F) == $1F)\nframeRange The frameRange conditions can be used to conditionally replace tiles based on the current frame number. The condition is true when the following expression is true:\n[current frame number] % [divisorValue] \u0026gt;= [compareValue]\nSyntax: \u0026lt;condition\u0026gt;[name - text], frameRange, [divisorValue - integer], [compareValue - integer]\nExample: \u0026lt;condition\u0026gt;myCondition,frameRange,8,10 (This condition will be true for the last 2 frames out of every 10 frames)\n\u0026lt;tile\u0026gt; tag Syntax: \u0026lt;tile\u0026gt;[img index - integer], [tile data], [palette data], [x - integer], [y - integer], [brightness - float (default: 1.0)], [default tile - Y or N]\nExample (CHR ROM): \u0026lt;tile\u0026gt;0,2E,FF16360F,0,0,1,N\nExample (CHR RAM): \u0026lt;tile\u0026gt;0,0E0E079C1E3EA7076101586121010000,0F100017,176,1168,1,N\nFor CHR ROM games, tile data is an integer (in hexadecimal) representing the position of the original tile in CHR ROM.\nFor CHR RAM games, tile data is a 32-character hexadecimal string representing all 16 bytes of the tile.\npalette data is always an 8-character hexadecimal string representing all 4 bytes of the palette used for the tile. For sprites, the first byte is always \u0026ldquo;FF\u0026rdquo;.\n\u0026lt;tile\u0026gt; define mappings between the original game\u0026rsquo;s tile data and their replacements in the PNG file. The tile data and palette data are used to identify the original tile, while the img index, x and y fields are used to specify in which PNG file the replacement can be found, and at what x,y coordinates in that PNG file.\nbrightness can be used to reuse the same HD tile for multiple original tiles \u0026ndash; this can be useful when a game has fade in and out effects (the brightness can be set to values above 1.0 to increase the PNG\u0026rsquo;s normal brightness level).\nWhen default tile is enabled (with Y), the tile is marked as the default tile for all palettes. Whenever a tile appears on the screen that matches the tile data, but has no rules matching its palette data, the default tile will be used instead.\n\u0026lt;background\u0026gt; tag Syntax: \u0026lt;background\u0026gt;[name - text], [brightness level - float (default: 1.0)], [horizontal scroll ratio (optional) - float], [vertical scroll ratio (optional) - float], [priority level (optional) - int, 0 to 39 (default 10)], [image left offset (optional) - int], [image top offset (optional) - int]\nExample: \u0026lt;background\u0026gt;myBackground.png,1.0,0,0,10,0,0\n\u0026lt;background\u0026gt; tags are meant to be used alongside conditions to add a background image under certain conditions (e.g on a specific screen, for example).\nThe Horizontal Scroll Ratio and Vertical Scroll Ratio parameters are optional (their default value is 0.0) and can be used to specify at what speed the background picture should scroll compared to the NES' scrolling.\nThis can be used to create simple parallax scrolling effects.\nThe Image Left Offset and Image Top Offset parameters are optional (their default value is 0) and can be used to offset the position of the background image within the PNG file. e.g: Specifying 100 for the left offset will cause the background to be scrolled 100 pixels to the left by default. With conditions, this can be used to create scrolling effects that are based on something other than the PPU\u0026rsquo;s current scroll offset.\nThe Priority Level parameter determines where the background is inserted compared to the NES' 3 \u0026ldquo;layers\u0026rdquo; (background sprites -\u0026gt; background tiles -\u0026gt; foreground sprites).\nThe screen is drawn in this order:\n Priority 0 to 9 HD backgrounds (priority 0 is below priority 1, etc.) Background-priority sprites Priority 10 to 19 HD backgrounds Background tiles Priority 20 to 29 HD backgrounds Foreground-priority sprites Priority 30 to 39 HD backgrounds Note: Only a single background can be active per priority level.\nBackgrounds can use a PNG\u0026rsquo;s alpha channel to allow the graphics below to show through them (this can be used to add a fog effect to the screen, etc.)\n\u0026lt;options\u0026gt; tag Syntax: \u0026lt;options\u0026gt;[option1 - text], [option2 - text], [...]\nExample: \u0026lt;options\u0026gt;disableSpriteLimit\nAvailable options:\ndisableSpriteLimit: Forces the emulator to disable the sprite limit when the HD pack is loaded.\ndisableOriginalTiles: Normally, when a replacement for a tile is not found, the original tile is drawn. When this option is enabled, the original tiles are never drawn, only their HD replacements.\n\u0026lt;bgm\u0026gt; tag Syntax: \u0026lt;bgm\u0026gt;[album - integer],[track - integer],[filename - ogg],[loop point (optional) - integer],[playback option (optional) - integer],[volume (optional) - integer]\nExample: \u0026lt;bgm\u0026gt;0,0,myBgm.ogg\nExample (with optional values): \u0026lt;bgm\u0026gt;0,0,myBgm.ogg,40000,1,-1\nLoop point: The sample number in the ogg file where the track will loop back to. Playback option: Use 1 for looping playback, 0 for single playback, -1 for keeping the current value. Volume: Use 0 to 128 for changing the volume, -1 for keeping the current volume.\nUsed to assign a background music track (.ogg audio file) to a specific album and track number. Album and track numbers are used to form a unique ID for each bgm, allowing up to 64k different bgm tracks.\n\u0026lt;sfx\u0026gt; tag Syntax: \u0026lt;sfx\u0026gt;[album - integer],[track - integer],[filename - ogg]\nExample: \u0026lt;sfx\u0026gt;0,0,myBgm.ogg\nUsed to assign a sound effect (.ogg audio file) to a specific album and track number. Album and track numbers are used to form a unique ID for each sound effect, allowing up to 64k different sound effects.\nUsing conditions To use conditions, add the condition\u0026rsquo;s name at the start of the line. e.g:\n[myConditionName]\u0026lt;tile\u0026gt;...\nConditions can only be applied to \u0026lt;tile\u0026gt; or \u0026lt;background\u0026gt; tags. When a condition is applied to a \u0026lt;tile\u0026gt; or \u0026lt;background\u0026gt; tag, that rule will only be used if the condition is met.\nThe first matching rule (in the order they are written in the hires.txt file) will be used. So conditional tiles MUST be placed before tiles with no conditions (for the same tile data+palette data) to have any effect.\nYou can also make it so multiple conditions must be met for a rule to be used by joining each condition name with a \u0026amp;:\n[cond1\u0026amp;cond2]\u0026lt;tile\u0026gt;...\nIt is also possible to invert the result of a condition by prepending a an exclamation mark (!) to it:\n[!myCondition]\u0026lt;tile\u0026gt;...\nReplacing audio in games Audio replacement in HD packs in Mesen works in a similar fashion to the MSU-1 for the SNES. It adds a number of read/write registers in memory and they can be used to play OGG files specified via \u0026lt;bgm\u0026gt; and \u0026lt;sfx\u0026gt; tags.\nRegister Write Operations $4100: Playback Options This register allows you to set the BGM loop flag (bit 0) on or off.\n$4101: Playback Control This register allows you to pause/resume or stop sounds.\nBit 0: When set, pauses/resumes the BGM track.\nBit 1: When set, the BGM track is stopped.\nBit 2: When set, all SFX tracks are stopped.\n$4102: BGM Volume Sets the current volume for the BGM tracks (0: Muted, 255: Maximum volume).\nSetting this register affects the currently playing BGM track - this can be used for fade in/out effects.\n$4103: SFX Volume Sets the current volume for the SFX tracks (0: Muted, 255: Maximum volume).\nSetting this register affects all currently playing SFX - this can be used for fade in/out effects.\n$4104: Album Number Selects the current album (0 - 255).\nThis allows up to 65536 BGM and SFX tracks to be defined.\nWriting to this register has no immediate effect - only subsequent writes to the Play BGM Track and Play SFX Track registers will be affected.\n$4105: Play BGM Track Starts playback of the specified BGM track from the specified album (based on the Album Number register).\nOnly a single BGM track can be playing at any given time.\n$4106: Play SFX Track Starts playback of the specified SFX track from the specified album (based on the Album Number register).\nAny number of SFX tracks can be played at once.\nRegister Read Operations $4100: Status This register returns the current playback status.\nBit 0: Set when a BGM track is currently playing.\nBit 1: Set when at least one SFX track is currently playing.\nBit 2: Set if an error occurred (e.g the last play BGM/SFX failed because the specified Album+Track number combination was invalid)\n$4101: Revision Number Returns the current revision of the HD Audio API. This value is currently set to 1.\n$4102/$4103/$4104: Signature These registers return the ASCII string NEA (NES Enhanced Audio) - this can be used to detect whether or not the audio API is available.\nFile Format Changelog Version 106 Replaced Show Behind Background Priority Sprites flag for \u0026lt;background\u0026gt; tags by a 0 to 39 priority level value. Removed contour feature for backgrounds, and removed disableContours option. Version 105 Brightness values above 1.0 are now allowed. Added disableOriginalTiles option Background tags can now specify left and top values. Added loopback point, playback option, volume to \u0026lt;bgm\u0026gt; tag. Version 104 Tile indexes for the \u0026lt;condition\u0026gt; tag (tileNearby/spriteNearby/tileAtPosition/spriteAtPosition) are now in hex instead of decimal (affects CHR ROM games only) Version 103 Added a Mask parameter to the memoryCheck and memoryCheckConstant conditions Tile indexes for the \u0026lt;tile\u0026gt; tag are now in hex instead of decimal (affects CHR ROM games only) Version 102 Operands for memoryCheck/memoryCheckConstant conditions must now be specified in hex (used to be decimal) Added the Show Behind Background Priority Sprites option to the \u0026lt;background\u0026gt; tag "},{"uri":"/configuration/input.html","title":"Input Options","tags":[],"description":"","content":"General Options Console Type: Selects which console to emulate for all input ports. The NES and Famicom have different accessories and some of the identical accessories (e.g the Zapper) have different behavior on a hardware level. If you want to connect Famicom-only accessories that plug into the Famicom\u0026rsquo;s expansion port, select Famicom.\nAutomatically configure controllers when loading a game: When enabled, when loading any game recognized by Mesen\u0026rsquo;s internal game database, the appropriate controllers will automatically be setup. For example, loading up a game like Duck Hunt will connect a Zapper to the second port.\nSetting up controllers NES For each player, select the device you want to use. To connect more than 2 controllers, check the Use Four Score accessory option.\nTo setup the key mappings for a controller (or other device-specific options), click the Setup button on the right of the player you want to configure.\nFamicom On older Famicoms, the player 1 \u0026amp; 2 controllers are hard-wired and cannot be disconnected \u0026ndash; Mesen does the same. To connect additional controllers, select the Four Player Adapter expansion device.\nTo setup the key mappings for a controller (or other device-specific options), click the Setup button on the right of the player you want to configure.\nConfiguring Key Bindings Each player can have up to four tabs of key bindings \u0026ndash; this allows you to control the same player with different input devices. For example, you can setup player 1 to be controlled by your keyboard and your Xbox controller at the same time.\nTo select a binding for a button, click on the corresponding button in the UI and then press the key or gamepad button you want to use for this button.\nTo clear a binding, click on it and then close the popup window by clicking on the X button.\nTo clear all bindings for this tab, click on the Clear Key Bindings.\nTo simplify configuration, a number of presets are available \u0026ndash; click on the Select Preset button to choose one.\nYou can also configure that controller\u0026rsquo;s turbo buttons' speed with the Turbo Speed slider. Note: setting the turbo speed to the fastest setting may cause some games to not detect the button presses at all.\nZapper / Light Gun To shoot a target on the screen, target it with the mouse and use the left mouse button to shoot.\nTo shoot outside the screen (which some games need to control menus, etc.), hold down the right mouse button while you click on the left mouse button.\nAdvanced Options Controller axis deadzone size: Controls the deadzone size for analog sticks. A larger deadzone means that the analog stick will need to be moved more before a button press is registered.\nHide mouse pointer when using zapper: Hides the mouse pointer completely when a Zapper is connected. This is useful when using light guns (for PCs) that simulate a mouse.\nDisplay Controller Input Use these options to display the controller input on the screen.\n"},{"uri":"/configuration/video.html","title":"Video Options","tags":[],"description":"","content":"General Options Scale: The scale determines the emulator window\u0026rsquo;s size - use integer factors (e.g: 2x, 3x, 4x) for best results.\nAspect Ratio: The NES' internal aspect ratio is almost square (Default (No Stretching)), but it used to be displayed on CRT TVs that had a rectangular picture. To simulate a CRT TV, you can use the Auto option - it will switch between NTSC and PAL aspect ratios depending on the game you are playing. Using anything other than the Default (No Stretching) option may cause pixels to have irregular sizes. You can reduce this effect by using a combination of video filters and the bilinear filtering option.\nEnable integer FPS mode: Under normal conditions, the NTSC NES runs at 60.1 fps. When playing a 60hz LCD, this causes a lot of dropped frames. This option slows down the emulation by a tiny amount to produce 60 frames per second instead, which reduces the number of dropped frames.\nEnable vertical sync: Turns on vertical sync \u0026ndash; can help prevent screen tearing on some hardware configurations.\nUse exclusive fullscreen mode: Turns on exclusive fullscreen mode. This may be useful if you are experiencing screen tearing issues in regular fullscreen despite vertical sync being turned on.\nFulscreen Resolution: This option is shown only when exclusive fullsceen mode is enabled. It allows you to select the screen resolution that should be used when in exclusive fullscreen mode. The default resolution is the current Windows screen resolution.\nRequested Refresh Rate: This option is shown only when exclusive fullsceen mode is enabled. It allows you to select your preferred refresh rate for NTSC and PAL/Dendy when running in exclusive fullscreen mode.\nUse integer scale values when entering fullscreen mode: By default, fullscreen mode fills the entire screen. However, this can cause non-integer scaling values to be used \u0026ndash; for example, in 1080p resolution, the scale becomes 4.5x. Since this can cause irregularly shaped pixels, you can use this option to use the nearest integer scale value instead (e.g 4x in this example).\nUse HDNes HD packs: Enables the use of HD packs.\nShow FPS: Displays an FPS counter on the screen. The first number is the number of frames emulated, the second number is the number of frames displayed on the screen. These values are usually identical, except when vertical sync is enabled.\nPicture Filter: Allows you to select a video filter. Selecting NTSC filters will cause additional configuration options to appear below.\nCommon Options The Brightness, Contrast, Hue, Saturation, Scanline settings are common to all filters and can even be used without a filter.\nUse bilinear interpolation when scaling: When enabled, bilinear interpolation is used when stretching (due to scale or aspect ratio). When disabled, nearest neighbor scaling is used. An easy way to get a slightly-softened screen, for example, is to use the Prescale filters (which use nearest neighbor scaling), use a bigger scale and enable bilinear filtering. For example, try this configuration:\nFilter: Prescale 3x Scale: 4x Use bilinear interpolation when scaling: Enabled Scanlines: Simulates the scanlines on a CRT TV - the higher the value, the deeper the scanlines appear on the screen.\nNTSC Filter Options There are 2 separate NTSC filters implemented in Mesen. The NTSC filter is blargg\u0026rsquo;s implementation - this filter is very fast, and available in various other emulators. The NTSC (bisqwit) filter is an implementation of bisqwit\u0026rsquo;s NTSC filter \u0026ndash; it is slower and produces a different output.\nThe 2 filters have a different set of options:\nNTSC (blargg): Artifacts, Bleed, Fringing, Gamma, Resolution, Sharpness\nNTSC (bisqwit): Y Filter (Horizontal Blur), I Filter (Horizontal Blur), Q Filter (Horizontal Bleed)\nFeel free to experiment with the settings and choose what you feel looks best.\nOverscan The overscan settings allow you to cut out pixels on any edge of the screen. On a CRT TV, a few pixels on each side of the screen was usually invisible to the player. Because of this, games often have glitches or incorrect palette colors on the edges of the screen \u0026ndash; this is normal and caused by the game itself. Setting a value of 8 or so on each side of the overscan configuration will usually hide most glitches.\nIt is possible to configure the overscan settings on a per-game basis in the Game-Specific tab. All games without specific settings will automatically use the overscan parameters shown in the Global tab.\nPalette This tab allows you to customize the palette used by all games.\nLoad Preset Palette: Mesen comes with a number of built-in palette options - you can select them from here.\nLoad Palette File: Use this to load a .pal file into the emulator. Mesen supports both 64-color (192 bytes) and 512-color (1536 bytes) palette files. The 512-color palette files can be used to control the colors used when the PPU\u0026rsquo;s R/G/B emphasis bits are turned on.\nExport Palette: Use this to export your current palette into a .pal file.\nUse this palette for VS System games: By default, VS System games have their own predefined RGB palettes and don\u0026rsquo;t use the palette defined here. When enabled, this option forces VS System games to ignore their default palette and use this one instead.\nAdvanced Options Remove sprite limit: The NES can normally only draw up to 8 sprites per line \u0026ndash; this limitation is indirectly responsible for some of the flickering seen in games at times. When this option is enabled, the limit is disabled, allowing up to 64 sprites to be drawn on the same line.\nAutomatically re-enable sprite limit as needed to prevent graphical glitches when possible: Some games rely on the sprite limit to hide objects from view. These games will have graphical glitches when the Remove sprite limit option is enabled. By enabling this option, Mesen will try to detect when games are attempting to hit the sprite limit on purpose and temporarely re-enable the limit in these specific cases. This option is not perfect and may not work in certain games, but it helps reduce the potential negative impacts of the Remove sprite limit option.\nDisable background: Disables rendering of the background layer.\nDisable sprite: Disables rendering of all sprites.\nForce background display in first column: The NES has a flag that prevents the background from rendering in the first 8 pixels on the left of the screen. When enabled, this option forces the background to be rendered in the first 8 pixels, no matter what the flag\u0026rsquo;s value is.\nForce sprite display in first column: The NES has a flag that prevents sprites from rendering in the first 8 pixels on the left of the screen. When enabled, this option forces the sprites to be rendered in the first 8 pixels, no matter what the flag\u0026rsquo;s value is.\nScreen Rotation: Rotates the display by the specified angle. This is useful to play games (generally homebrew games) designed for a vertical display.\n"},{"uri":"/configuration/emulation.html","title":"Emulation Options","tags":[],"description":"","content":"General Options Emulation Speed: This configures the regular speed to use when emulating. This should normally be set to 100%.\nFast Forward Speed: This is the alternate speed that is used when the Fast Forward button is held down.\nRewind Speed: This configures the speed at which to rewind the gameplay when the Rewind button is held down.\nRun Ahead: Run ahead allows the reduction of input lag by the number of frames specified. CPU requirements increase proportionally with the number of run ahead frames specified.\n Run ahead is currently not compatible with movies or netplay - the movies and netplay menus will be disabled if runahead is turned on. Note for speedrunners: Using features such as run ahead to reduce lag typically counts as cheating for the purposes of speed running. Advanced Options Recommended settings for developers (homebrew / ROM hacking) Enable OAM RAM decay: On all models, OAM RAM decays whenever rendering is disabled. This causes the values in OAM RAM to decay to a specific value after a certain amount of time has elapsed since the last time the value was read or written (which may cause sprite-related glitches to appear on the screen). No known game relies on this \u0026ndash; the option is offered here mostly for the sake of homebrew software testing. There is a corresponding option to break on decayed OAM reads available in the debugger to help find and debug OAM decay-related bugs.\nRandomize power-on state for mappers: Cartridges often have a random state at power-on and need to be fully initialized before being used. This option causes Mesen to randomize the power-on state of the most common mappers. This is useful when developing homebrew software.\nRandomize power-on/reset CPU/PPU alignment: Each time the NES is reset, the CPU and PPU run with a slightly different and random alignment. This option simulates that behavior. When enabled, some test roms may randomily fail from one reset to another, because of the different alignments (this can also happen on the NES.)\nEnable PPU $2006 scroll glitch emulation: When enabled, a known hardware bug that occurs when the $2006 register is written at specific cycles during rendering. This glitch is known to occur in some licensed NES games and usually results in a single frame displaying with an incorrect scroll position.\nEnable PPU $2000/$2005/$2006 first-write scroll glitch emulation: When enabled, a known hardware bug that occurs on the first write to the $2005/$2006 registers (or any write to the $2000 register) when the write occurs at cycle during rendering. This glitch is known to occur in some licensed NES games and usually results in a single scanline displaying incorrectly.\nDefault power on state for RAM: On a console, the RAM\u0026rsquo;s state at power on is undetermined and relatively random. This option lets you select Mesen\u0026rsquo;s behavior when initializing RAM - set all bits to 0, set all bits to 1, or randomize the value of each bit.\nMiscellaneous settings Use alternative MMC3 IRQ behavior: The MMC3 has a number of different variants (A, B and C). By default, Mesen uses the IRQ behavior for versions B and C. By turning this option on, Mesen will default to using the MMC3A\u0026rsquo;s IRQ behavior instead. There is usually no reason to enable this.\nUse NES/HVC-101 (Top-loader / AV Famicom) behavior: The NES and Famicom both had 2 different releases - their original model and the \u0026ldquo;top loader\u0026rdquo; model. Both of these have slightly different behavior when it comes to their input ports. When enabled, this option causes Mesen to simulate the top loader models. No games are known to rely on this behavior.\nDo not reset PPU when resetting console: On the Famicom and top loader NES, the PPU does not reset when pressing the reset button (only the CPU is reset). When enabled, only the CPU resets when the reset button is pressed.\nDisable PPU $2004 reads: On some early models, the OAM RAM cannot be read via the $2004 register (in this case, $2004 becomes a write-only register). When enabled, this option emulates this behavior.\nDisable PPU OAMADDR bug emulation: On some models, a bug occurs that corrupts OAM RAM under certain circumstances. When this option is enabled, the bug is no longer emulated. This bug is required for at least 1 game to work properly.\nDisable PPU palette reads: On some early models, it is not possible to read the palette RAM via $2007 \u0026ndash; when enabled, this option emulates this behavior, making reads to palette RAM return corresponding values in the PPU\u0026rsquo;s memory instead.\nAllow invalid input: On a NES controller, it is impossible to press both left and right or up and down at the same time on the controller\u0026rsquo;s D-pad. Some games rely on this and pressing both buttons at once can cause glitches. When enabled, this option makes it possible to press opposite directional buttons at the same time.\nOverclocking Additional scanlines before NMI: Increases the number of scanlines in the PPU, before the NMI signal is triggered at the end of the visible frame. This effectively gives more time for games to perform calculations, which can reduce slowdowns in games. This is the preferred option for overclocking.\nAdditional scanlines after NMI: Increases the number of scanlines in the PPU, after the NMI signal is triggered at the end of the visible frame. This effectively gives more time for games to perform calculations, which can reduce slowdowns in games. This option is less compatible and should only be used if the before NMI variation does not work as expected.\nShow Lag Counter: When enabled, the lag counter is displayed on the screen. The lag counter keeps track of frames where the game does not attempt to read the input ports \u0026ndash; this is usually an indication of the game running out of time to perform calculations, which usually causes slowdowns.\n"},{"uri":"/debugging/debugger.html","title":"Debugger","tags":[],"description":"","content":"The debugger is the main part of the debugging tools available in Mesen. This window displays the disassembled code, allows you to configure breakpoints, labels and watch values. It also contains a large number of options and smaller features \u0026ndash; all of which are described below.\nGeneral Usage Tips Most elements in the debugger\u0026rsquo;s interface have right-click menu options - make sure you explore the right-click options available in each list and window.\nWatch expressions, breakpoints and labels are automatically saved on a per-rom basis in a Workspace.\nYou can completely reset the workspace for a specific rom by using the File→Workspace→Reset Workspace command.\nSearch Tools There are a number of different tools that can be used to search/navigate the code:\n Go To All: The Go To All feature allows you to search for any label by its name and navigate to it. It also works with CA/CC65 and displays the location of the labels in the original source code. (Ctrl+,) Find/Find Next/Find Previous: Incremental search that can be used to search through any text shown in the code window (Ctrl+F) Find All Occurrences: Search the code for a specific string or label and return all the results in a list. (Ctrl+Shift+F) Go To\u0026hellip;: These options allow you to quickly reach the NMI, IRQ or Reset handlers or a specific address (Ctrl+G) Customizing the debugger All keyboard shortcuts can be customized in Options→Customize Shortcut Keys\nThe font used in the code window can be customized in Options→Font Options→Select Font\nThe colors used for syntax highlighting can be changed in Options→Configure Colors\nVarious portions of the debugger can be hidden/shown via Options→Show\nCode Window The code window displays the disassembled code and contains a number of features and options.\nGeneral information Several options control what is shown in the code window, and how it is shown - see Display Options below. Labels and comments defined in the label list are shown in the code. Single-line comments appear on the right, multi-line comments appear on top. The instruction that\u0026rsquo;s currently executing is highlighted in yellow. Mouse-hovering any label or address will display a tooltip giving additional information (label, comment, current value in memory, etc.) You can alter the flow of execution by using the Set Next Statement command to change the next instruction to be executed. Disassembly Options Disassemble\u0026hellip;:\n Verified Code: (Always enabled) Bytes that are known by the debugger to be valid code will be disassembled as code. Verified Data: Bytes that are known to be data will be disassembled as code (enabling this is not recommended). Unidentified Code/Data: Bytes that have not been used yet by the CPU will be disassembled as code. Show\u0026hellip;:\n Verified Code: (Always enabled) All verified code will be disassembled and shown in the code window. Verified Data: Verified data blocks will be shown. If the option to disassemble verified data is enabled, a disassembly of the data will be shown. Unidentified Code/Data: Blocks that are not marked as data nor code will be shown. If the option to disassemble unidentified data/code is enabled, a disassembly of the bytes will be shown. Display OP codes in lower case: When enabled, OP codes are displayed in lowercase letters\nShow Effective Addresses: When enabled, the resulting address of indirect addressing modes (e.g LDA $3321, Y) will be displayed next to the instruction in blue. e.g: @ $3323\nShow Memory Values: When enabled, every line of code that refers to a specific address in memory will display that address' current value on the right.\nByte Code Display: When enabled, the byte code matching the instructions will be displayed next to them (either on the left, or on the line below based on your selection)\nPRG Address Display: When enabled, the address matching the actual position of an instructions in PRG ROM will be displayed next to the CPU address (or replace it entirely, based on your selection)\nEmulation Status This section of the debugger window displays the CPU and PPU\u0026rsquo;s current state.\nWhile execution is paused, most fields are editable. Altering the value of any field will change its corresponding value in the emulation core. To undo any edits you have done by mistake, click the \u0026ldquo;Undo Changes\u0026rdquo; button.\nInput Button Setup This section lets you force certain buttons to be held down on the NES' controller. This is often useful when trying to debug input-related code.\nClicking on a button on the mini NES controllers will toggle its state - green buttons are currently being held down.\nWatch List/Window The watch window and watch list allow you to evaluate expression and see their value. The Watch Window is a standalone window that can be resized and moved independently from everything else, whereas the Watch List is a part of the main debugger window for quick access to watch expressions.\nTo add a new watch expression, click on the last empty line in the list to enter edit mode.\nTo edit a watch expression, double-click on it to enter edit mode.\nYou can use the right-click context menu to delete or move entries, as well as select formatting options.\nAn import and export feature is also available to save/load watch expressions from a plain text file.\nSyntax The syntax is identical to C/C++ (e.g \u0026amp;\u0026amp; for AND, || for OR) and uses the same operator precedence as well.\nOperators The following operators are supported (same usage/precedence as C):\n*, /, %, +, -, \u0026lt;\u0026lt;, \u0026gt;\u0026gt;, \u0026lt;, \u0026lt;=, \u0026gt;, \u0026gt;=, ==, !=, \u0026amp;, ^, |, \u0026amp;\u0026amp;, ||, ~, !, (, )\nAdditionally, the following special operators exist:\n [address/label]: Surrounding a value/expression with brackets will read the corresponding memory address and return its value (1 byte). e.g: [$8000] will read the value at address $8000 and return it. {address/label}: Surrounding a value/expression with curly brackets will read the corresponding memory address and return its value (2 byte). e.g: {myLabel} will read 2 bytes of memory at the address represented by the myLabel label and return its value :address/label: Prepending a : before an address/label will return the offset of the corresponding address within that memory type. If an address is not mapped to any type of memory, -1 will be returned. e.g: :$8000 will return the offset in PRG ROM of the byte currently mapped at the CPU address $8000. Special values The following \u0026ldquo;variables\u0026rdquo; can be used in both the watch window and contional breakpoints to check the state of specific portions of the emulation core.\nNumeric values\n A/X/Y/PS/SP: Value of corresponding registers PC: Program Counter OpPC: Address of the current instruction\u0026rsquo;s first byte PreviousOpPC: Address of the previous instruction\u0026rsquo;s first byte Cycle/Scanline: Current cycle (0-340)/scanline(-1 to 260) of the PPU Frame: PPU frame number (since power on/reset) Value: Current value being read/written from/to memory Address: Current CPU memory address being read/written Flags\n Branched: true if the current instruction was reached by a branch/jump instruction IsRead: true if the CPU is reading from a memory address IsWrite: true if the CPU is writing to a memory address IRQ: true if the IRQ flag is set NMI: true if the NMI flag is set Sprite0Hit: true if the PPU\u0026rsquo;s \u0026ldquo;Sprite 0 Hit\u0026rdquo; flag is set SpriteOverflow: true if the PPU\u0026rsquo;s \u0026ldquo;Sprite Overflow\u0026rdquo; flag is set VerticalBlank: true if the PPU\u0026rsquo;s \u0026ldquo;Vertical Blank\u0026rdquo; flag is set Formatting It is possible to customize the format of each entry by adding a suffix to the expression. Suffixes contain a single letter and are optionally followed by a number indicating the number of bytes expected in the return value (up to 4).\nThe available suffixes are:\n S - Signed decimal value U - Unsigned decimal value H - Hexadecimal B - Binary For example, suffixing an expression with:\n , H2 will display the result as a 2-byte hexadecimal value (e.g: 26, H2 will display as $001A) , B will display the result as a binary value (e.g: 141,B will display as %10001101) , S2 will display the result as a 16-bit signed decimal value (e.g: $FE4F, S2 will display as -433) , U will display the result as an unsigned decimal value (e.g: 180, U will display as 180) You can select the default format to use for entries without prefixes by right-clicking and choosing between:\n Decimal Display (equivalent to S4 to all entries - displays the result as 32-bit signed decimal values) Hexadecimal Display (equivalent to H1 to all entries) Binary Display (equivalent to B1 to all entries) Usage Examples [$10] //Displays the value of memory at address $10 (CPU) a == 10 || x == $23 scanline == 10 \u0026amp;\u0026amp; (cycle \u0026gt;= 55 \u0026amp;\u0026amp; cycle \u0026lt;= 100) x == [$150] || y == [10] [[$15] + y] //Reads the value at address $15, adds Y to it and reads the value at the resulting address. {$FFFA} //Returns the NMI handler's address. [$14] | ([$15] \u0026lt;\u0026lt; 8), H2 //Display the value of the 2-byte variable stored at $14 in hexadecimal format. Using labels\nAny label defined in the debugger can be used in watch expressions (their value will match the label\u0026rsquo;s address in CPU memory).\nFor example, if you have a label called \u0026ldquo;velocity\u0026rdquo; that points to 1-byte value at address $30 in the CPU\u0026rsquo;s memory, you can display its value in the watch using the following syntax: [velocity]\nDisplaying arrays\nThe watch window allows you display several consecutive memory values on the same row using a special syntax. e.g:\n[$30, 16] //This will display the values of addresses $30 to $3F [MyLabel, 10] //This syntax can also be used with labels Breakpoints Breakpoints define conditions under which the execution of the game\u0026rsquo;s code will be suspended. Any number of breakpoints can be defined. You can also make a breakpoint appear as a mark on the Event Viewer by checking the M column.\nTo add a breakpoint, right-click the breakpoint list and select Add.\nTo edit a breakpoint, double-click on it in the list.\nTo disable a breakpoint, uncheck it.\nTo delete a breakpoint, right-click on it and select Delete\nTo view the breakpoint in the code, right-click on it and select Go to location\nBreakpoint configuration Breakpoints can be set to trigger based on CPU/PPU memory accesses at specific memory addresses.\nBreakpoint Type\nSelect the type of memory for which you want to set a breakpoint. The valid range of addresses for the breakpoint will vary based on the selected memory type.\nBreak On\nSelect which types of accesses (read, write or execute) should trigger the breakpoint.\nAddress\nSelect which address or address range this breakpoint should apply to.\nIt is also possible to specify no address at all by selecting Any - in this case, breakpoints will be evaluated on every CPU cycle.\nCondition (optional)\nConditions allow you to use the same expression syntax as the one used in the Watch Window to cause a breakpoint to trigger under specific conditions.\nProcess breakpoint on dummy reads/writes\nWhen enabled, the breakpoint will be processed for dummy reads and writes (only available for read or write breakpoints). When disabled, the debugger will never break on a dummy read or write for this breakpoint.\nMark on Event Viewer\nWhen enabled, a mark will be visible on the Event Viewer whenever this breakpoint\u0026rsquo;s conditions are met. This can be used to add marks to the event viewer based on a variety of conditions by using conditional breakpoints.\nBreak Execution\nThis enables the breakpoint - if this is disabled, the execution will not break when the breakpoint is hit.\nExamples\nTo break when the sum of the X and Y registers is 5:\nx + y == 5 To break when the value at memory address $10 is smaller or equal to $40:\n[$10] \u0026lt;= $40 To break when the CPU writes the value $60 to any address:\nIsWrite \u0026amp;\u0026amp; Value == $60 Call Stack The call stack displays the currently executing function, and all functions that are below it on the stack. The top of the list is the current function, while the row below it is the location that the code will return to once the current function executes the RTS instruction. The call stack also displays NMI and IRQ routine handlers and processes calls to RTI in the same manner as calls to JSR and RTS.\nNote: Rows shown in gray and italic represent portions of the call stack that are currently not inside the CPU\u0026rsquo;s memory (e.g because the PRG banks were changed since that point in the execution).\nLabels: When labels are defined for the PRG ROM offset matching the function\u0026rsquo;s entry point, that label is shown as the function\u0026rsquo;s name in the call stack.\nTo view the code at any location in the call stack, double-click on the row.\nLabels Labels can be used to simplify debugging. They allow you to give names to variables and functions which will be used instead of numeric addresses when viewing the code in the debugger. Labels can also be used to display single and multi-line comments to the code.\nThe label list displays every label defined in alphabetical order.\nTo add a label, right-click in the label list and select Add.\nTo edit a label, right-click in the label list and select Edit.\nTo delete a label, right-click in the label list and select Delete.\nTo add a breakpoint to a label, right-click in the label list and select Add breakpoint.\nTo add the label to the watch, right-click in the label list and select Add to watch.\nTo find where a label is used, right-click in the label list and select Find Occurrences.\nTo view the code at the label\u0026rsquo;s location, double-click on the label in the list.\nTo view the label in the hex editor, use any of the View in CPU memory/View in PRG ROM/View in Save RAM/View in Work RAM options.\nShow Comments controls wheter or not code comments that are not labelled are shown in the label list. Show Automatic Jump Labels determines whether or not the labels that are automatically generated by the Auto-create jump labels option are shown in the label list.\nNote: Labels shown in gray color and italic font are currently not mapped in CPU memory.\nEditing Labels Various types of labels can be defined:\n NES RAM (2 KB): Used for labels residing in the $0000-$1FFF memory range (the NES' built-in RAM) PRG ROM: Used for constants, data, code labels and functions in PRG ROM - the address value represents the offset from the start of PRG ROM (which can exceed $FFFF) Work RAM: Used for variables in work ram (also called PRG RAM without battery backup) - the address value represents the offset from the start of the ram chip. Save RAM: Used for variables in work ram (also called battery-backed PRG RAM) - the address value represents the offset from the start of the ram chip. Register: These are used to give name to built-in or mapper-specific registers. For example, the $2000 PPU register could be renamed to \u0026ldquo;PpuControl\u0026rdquo;. Essentially, they are CPU memory labels ($0000-$FFFF) that ignore all banking, etc. The rules for them to be used in the disassembly window are slightly different. There are some restrictions on what a label can contain \u0026ndash; in general, they must begin with a letter or an underscore and cannot contain spaces or most non-alphanumeric characters. Labels can also contain a comment which is shown in the code window as well as in the tooltips that are displayed when putting your cursor over a label in the code window.\nMulti-byte labels can be defined using the Length setting. This can be used to define multi-byte values, arrays or pointers in the code. Multi-byte labels will be shown with a +X offset modifier when referred to in the code window (e.g: MyArrayLabel+2)\nFunction List The function list is similar to the label list and allows you to easily add or edit the name of functions (which are also labels).\nUnlike the label list, which only displays labels, the function list displays all known functions, including those with no labels. This is useful to quickly check an unnamed function\u0026rsquo;s code (by double-clicking on it) and give it a name. This can help when attempting to reverse-engineer code.\nCPU/PPU Memory Mappings The CPU and PPU memory mappings are visual aids that display information about the currently selected PRG/CHR banks and the nametable configuration.\nThe banking configuration represents Mesen\u0026rsquo;s internal representation of the mapper in use, which may not exactly match the mapper\u0026rsquo;s specs. For example, a mapper with 2x 8 KB + 1x 16 KB PRG banking is emulated as 4x 8 KB internally, so it will appear as four 8 KB banks.\nOther Options Display Options The Show... submenu contains a number of options to show/hide various elements on the UI. Specifically, the toolbar, CPU/PPU memory mappings, function/label lists, watch list, breakpoint list and the call stack window.\nTooltip Options A number of tooltip-related options are available here:\n Show Code Preview in Tooltips: When enabled, label/address tooltips will now show a preview of the code at the target location. Show OP Code Info Tooltips: When enabled, putting the mouse over an OP code will display a tooltip containing information about the OP code and which CPU flags are affected by it. Only show tooltips when Shift key is pressed: When enabled, no tooltips will be shown unless the shift key is held down. Break Options The Break Options submenu contains a number of options to configure under which conditions the debugger will break (even when no breakpoint is hit):\n Break on power/reset: Break the emulation whenever a reset or power cycle occurs. Break on unofficial opcodes: Break the emulation whenever an unofficial opcode is about to execute. Break on BRK: Break the emulation whenever a BRK instruction is about to execute. Break on CPU crash: Break the emulation whenever an instruction that will cause the CPU to freeze is about to execute. Break on unlogged code: Break the emulation whenever an instruction that haven\u0026rsquo;t been logged is about to execute. Break on bus conflict: Break whenever a bus conflict is detected. This option only causes a break when using mappers that have bus conflicts enabled. Break on decayed OAM read: Break whenever the code a read is performed on decayed OAM memory. Note: This option is only available when the Enable OAM RAM decay option is enabled in the Emulation Settings. Break on $2006 scroll glitch: Break whenever the $2006 scroll glitch is triggered by a write to $2006. Note: This option will only trigger a breakpoint if the option to emulate the glitch is turned on Break on uninitialized memory read: Break whenever the code reads from a memory address containing an uninitialized value. Note: This option only works if the debugger has been opened since the last reset or power cycle. Break when debugger is opened: The emulation will break when you first open the debugger. Break on debugger focus: Whenever the debugger\u0026rsquo;s window gains focus (e.g by clicking on it), the emulation will break. Break on Init (NSF): Break when the NSF\u0026rsquo;s Init routine is called. Break on Play (NSF): Break when the NSF\u0026rsquo;s Play routine is called. Enable sub-instruction breakpoints: This option allows Mesen to process breakpoints in the middle of CPU instructions. This was the default up to version 0.9.7. When this option is disabled, the debugger will break at the beginning of CPU instructions only (and will only break once per instruction). This option is disabled by default as of 0.9.8.\nAdditionally, you can configure whether or not the debugger window gets focused when a break or pause occurs.\nCopy Options These options configure which portions of the code is copied into the clipboard when copying code from the code window.\nLayout Options Split View: Displays 2 separate code windows side-by-side. Vertical Layout: Moves the location of the label and function lists to improve space utilization on larger screens. Misc. Options Auto-create jump labels: When enabled, the debugger will automatically generate labels for all jumps/branches in PRG ROM (when it executes the branch instruction). These are labelled L#####, where ##### is the label\u0026rsquo;s location in PRG ROM. Hide Pause Icon: When enabled, the pause icon that is normally shown whenever execution is paused will be hidden. Draw Partial Frame: When enabled, the emulator\u0026rsquo;s main window will display the current partially-drawn frame instead of the last complete frame. Show previous frame behind current: When enabled along with Draw Partial Frame, the previous frame\u0026rsquo;s data will be shown behind the current frame. Show break notifications: When enabled, a \u0026ldquo;notification\u0026rdquo; will be shown over the disassembly window indicating what caused the debugger to break the execution (e.g: a CPU/PPU read/write, a decayed OAM read, etc.) Show instruction progression: When enabled, the code window will display an indicator showing how far along into the current instruction the execution is. This also shows an estimate of how many cycles the instruction will take to complete (this estimate may increase for various reasons such as a page being crossed, etc.). R is read, W is write, X is execution, DR is a dummy read, and DMC is an APU DMC read Show selection length: When enabled, the code window will display the current selection\u0026rsquo;s length in bytes (when more than 1 line is selected) Keep active statement in the center: When enabled, the code window will always put the current statement in the center whenever it updates (causing it to scroll on every step). When disabled, the code window will only scroll the code when necessary. Refresh UI while running: When enabled, the watch window and the CPU/PPU status will be updated continuously while the emulation is running (instead of only updating when the execution breaks) Reload ROM on Power Cycle: When enabled, the ROM will be loaded again if the Power Cycle is triggered and changes made to the ROM since it is last loaded will take effect. Workspaces Debugger \u0026ldquo;workspaces\u0026rdquo; are used to store information specific to each ROM you debug. This includes watch expressions, breakpoints and labels.\nDefault Workspace Labels By default, Mesen setups labels for the NES' PPU and APU registers. These can be disabled using the Disable default labels option.\nAdditionally, it\u0026rsquo;s possible to setup your own set of default labels by creating a file called DefaultLabels.Global.mlb in the Debugger folder (where the workspace and CDL files are stored). When Mesen finds this file, it will ignore the its own default labels and use the ones contained in that file instead, for all ROMs.\nYou can also setup default labels for specific mappers by creating a file called DefaultLabels.[mapper number].mlb (e.g, for MMC3 games: DefaultLabels.4.mlb).\nFor FDS and NSF ROMs, DefaultLabels.FDS.mlb and DefaultLabels.NSF.mlb can be used, respectively.\nIf both a global and mapper-specific mlb is found, both of them will be used (with the mapper-specific file having priority in case of conflicting labels).\nPerformance Tracker From the code window, you can right-click on an address and activate the \u0026ldquo;performance tracker\u0026rdquo;. This feature will track when the selected address is executed by the CPU on each frame, and display a CPU/FPS chart overlay based on those statistics.\nBy setting the performance tracker to the part of the code that most games use to wait for vertical blank after the next frame\u0026rsquo;s logic is done processing, you can get an estimate of how much extra CPU time remains on each frame.\nHow To: Edit Code From the code window, you can select code (via click and drag, or shift+arrow keys) and use the \u0026ldquo;Edit Selected Code\u0026rdquo; command to open the Assembler and edit that section of code. The assembler recognizes labels and allows you to define temporary labels as well. If the new code is smaller (in terms of bytes) than the original code, the extra bytes will be replaced by NOPs. If the new code is larger, it will override whatever comes next in the code \u0026ndash; a warning will be shown beforehand in this case. When you\u0026rsquo;re ready to apply your modifications, press the Apply button.\n"},{"uri":"/apireference/drawing.html","title":"Drawing","tags":[],"description":"","content":"Drawing basics All drawing-related functions share a few properties:\n (x, y) coordinates must be between (0, 0) and (255, 239)\n The \u0026ldquo;duration\u0026rdquo; is specified as a number of frames during which the drawing must remain on the screen. This defaults to 1 frame when unspecified, and draw calls will be permanent (until a call to clearScreen) if duration is set to 0.\n Colors are integers in ARGB format:\nWhite: 0xFFFFFF Black: 0x000000 Red: 0xFF0000 Green: 0x00FF00 Blue: 0x0000FF\nThe alpha component (transparency) can be used and defaults to being fully opaque when set to 0 or omitted. (0xFF is fully transparent) e.g: semi-transparent black: 0x7F000000 opaque gray: 0xFF888888 (fully transparent gray color)\n drawPixel Syntax\nemu.drawPixel(x, y, color [, duration, delay]) Parameters\nx - Integer X position\ny - Integer Y position color - Integer Color\nduration - Integer Number of frames to display (Default: 1 frame)\ndelay - Integer Number of frames to wait before drawing the pixel (Default: 0 frames)\nReturn value\nNone\nDescription\nDraws a pixel at the specified (x, y) coordinates using the specified color for a specific number of frames.\ndrawLine Syntax\nemu.drawLine(x, y, x2, y2, color [, duration, delay]) Parameters\nx - Integer X position (start of line)\ny - Integer Y position (start of line)\nx2 - Integer X position (end of line)\ny2 - Integer Y position (end of line)\ncolor - Integer Color\nduration - Integer Number of frames to display (Default: 1 frame)\ndelay - Integer Number of frames to wait before drawing the line (Default: 0 frames)\nReturn value\nNone\nDescription\nDraws a line between (x, y) to (x2, y2) using the specified color for a specific number of frames.\ndrawRectangle Syntax\nemu.drawRectangle(x, y, width, height, color, fill [, duration, delay]) Parameters\nx - Integer X position\ny - Integer Y position width - Integer The rectangle\u0026rsquo;s width\nheight - Integer The rectangle\u0026rsquo;s height\ncolor - Integer Color\nfill - Boolean Whether or not to draw an outline, or a filled rectangle.\nduration - Integer Number of frames to display (Default: 1 frame)\ndelay - Integer Number of frames to wait before drawing the rectangle (Default: 0 frames)\nReturn value\nNone\nDescription\nDraws a rectangle between (x, y) to (x+width, y+height) using the specified color for a specific number of frames.\nIf fill is false, only the rectangle\u0026rsquo;s outline will be drawn.\ndrawString Syntax\nemu.drawString(x, y, text, textColor, backgroundColor [, duration, delay]) Parameters\nx - Integer X position\ny - Integer Y position\ntext- String The text to display\ntextColor - Integer Color to use for the text\nbackgroundColor - Integer Color to use for the text\u0026rsquo;s background color\nduration - Integer Number of frames to display (Default: 1 frame)\ndelay - Integer Number of frames to wait before drawing the text (Default: 0 frames)\nReturn value\nNone\nDescription\nDraws text at (x, y) using the specified text and colors for a specific number of frames.\nclearScreen Syntax\nemu.clearScreen() Return value\nNone\nDescription\nRemoves all drawings from the screen.\ngetPixel Syntax\nemu.getPixel(x, y) Parameters\nx - Integer X position\ny - Integer Y position\nReturn value\nInteger ARGB color\nDescription\nReturns the color (in ARGB format) of the PPU\u0026rsquo;s output for the specified location.\ngetScreenBuffer Syntax\nemu.getScreenBuffer() Return value\nArray 32-bit integers in ARGB format\nDescription\nReturns an array of ARGB values for the entire screen (256px by 240px) - can be used with emu.setScreenBuffer() to alter the frame.\nsetScreenBuffer Syntax\nemu.setScreenBuffer(screenBuffer) Parameters\nscreenBuffer - Array An array of 32-bit integers in ARGB format\nReturn value\nNone\nDescription\nReplaces the current frame with the contents of the specified array.\n"},{"uri":"/configuration/preferences.html","title":"Preferences","tags":[],"description":"","content":"General Options Display Language: Selects in which language the UI is shown \u0026ndash; defaults the user\u0026rsquo;s default language.\nAutomatically check for updates: When enabled, Mesen will check for a new version of the emulator every time the emulator is started.\nOnly allow one instance of Mesen at a time: When enabled, only a single copy of Mesen can be opened at the same time. This is useful when using file associations to load games by double-clicking on the rom files.\nPause/Background settings Hide the pause screen: When enabled, the PAUSE screen is no longer shown when the emulator is paused.\nPause when a movie finishes playing: When enabled, the emulator will automatically pause when a movie ends its playback.\nAllow input when in background: When enabled, gamepad input can still be used even if the window is in the background. This does not work for keyboard key bindings.\nPause when in:\n Background: When enabled, the emulator will automatically pause when in the background. Menu and config dialogs: When enabled, the emulator will automatically pause when in menus or configuration dialogs. Debugging tools: When enabled, the emulator will automatically pause when in debugging tools. Misc. Settings Automatically apply IPS/BPS patches: When enabled, any IPS or BPS patch file found in the same folder as the ROM file will automatically be applied. (i.e: when loading MyRom.nes, if a file called MyRom.ips exists in the same folder, it will be loaded automatically.)\nAutomatically hide the menu bar: When enabled, the menu bar will automatically be hidden when not in use, even in windowed mode. The menu bar is always hidden automatically when playing in fullscreen mode, whether this option is enabled or not.\nDisplay confirmation dialog before reset/power cycle/exit: When enabled, a confirmation dialog will be shown before a reset or a power cycle or before the emulator is closed.\nDisplay play/record icon when playing or recording a movie: When enabled, an icon will be shown on the screen whenever a movie is playing or recording.\nShortcut Keys Shortcut keys are user-defined shortcuts for various features in Mesen. Some of these features can only be accessed via shortcut keys (e.g: Fast Forward and Rewind).\nMost of these options are also available through the main window\u0026rsquo;s menu \u0026ndash; the shortcuts configured in this section will appear next to the matching action in the main window\u0026rsquo;s menu.\nTo change a shortcut, click on the button for the shortcut you want to change and press the key(s) you want to set for this shortcut. Once you release a key, all the keys you had pressed will be assigned to the shortcut.\nTo clear a key binding, right-click on the button.\nAvailable shortcuts:\n Fast Forward (Hold button): Hold down this key to fast forward the game. Toggle Fast Forward: Start/stop fast forwarding. Rewind (Hold button): Hold down this key to rewind the game in real-time. Toggle Rewind: Start/stop rewinding. Rewind 10 seconds: Instantly rewinds 10 seconds of gameplay. Rewind 1 minute: Instantly rewinds 1 minute of gameplay. Pause: Pauses or unpauses the game. Reset: Resets the game (equivalent to pressing the reset button on the NES.) Power Cycle: Power cycles the game (equivalent to turning the power off and then back on.) Reload ROM: Reloads the ROM from the disk and power cycles the console. Power Off: Powers off the game, returning to the game selection screen. Exit: Exits the emulator. FDS - Insert Next Disk: Inserts face A of the next disk. FDS - Switch Side: Switches to the current disk\u0026rsquo;s other side (A or B) FDS - Eject Disk: Ejects the currently inserted disk VS - Insert Coin 1: Inserts a coin in slot 1. VS - Insert Coin 2: Inserts a coin in slot 2. VS - Insert Coin 3: Inserts a coin in slot 1 of the second console (VS DualSystem only). VS - Insert Coin 4: Inserts a coin in slot 2 of the second console (VS DualSystem only). VS - Service Button: Press to activate the service button. VS - Service Button 2: Press to activate the service button on the second console (VS DualSystem only). Input Barcode: Inputs a barcode into the connected barcode reader device. Take Screenshot: Takes a screenshot. Load Random Game: Loads a random game from your game folder. Run Single Frame: Press to run a single frame and pause. Set Scale 1x to 6x: Sets the scale to the matching value. Toggle Fullscreen Mode: Enters/exits fullscreen mode. Toggle Debug Information: Turns on/off the debug screen overlay. Toggle FPS Counter: Turns on/off the FPS counter. Toggle Game Timer: Turns on/off the game timer. Toggle Frame Counter: Turns on/off the frame counter. Toggle Lag Counter: Turns on/off the lag counter. Toggle OSD (On-Screen Display): Turns on/off the OSD. Toggle Display on Top: Turns on/off the display on top option. Toggle Background Layer: Turns on/off the background layer. Toggle Sprite Layer: Turns on/off the sprite layer. Enable/Disable Cheat Codes: Press to toggle cheats on or off. Enable/Disable Audio: Press to toggle audio output on or off. Toggle Keyboard Mode: Turns on/off keyboard mode. Toggle Maximum Speed: Toggles emulation speed between 100% and maximum speed. Increase Speed: Increases the emulation speed. Decrease Speed: Decreases the emulation speed. Open File: Displays the open file dialog. Open Debugger: Opens the debugger. Open Assembler: Opens the assembler. Open Ppu Viewer: Opens the PPU viewer. Open Memory Tools: Opens the memory tools. Open Script Window: Opens the script window. Open Trace Logger: Opens the trace logger. Select Next Save Slot: Move to the next save state slot. Select Previous Save Slot: Move to the previous save state slot. Save State: Save the game\u0026rsquo;s state in the currently selected slot. Load State: Load the game\u0026rsquo;s state from the currently selected slot. Save State - Slot X: Save the game\u0026rsquo;s state to the matching slot. Load State - Slot X: Load the game\u0026rsquo;s state from the matching slot. Load State - Auto Save Slot: Load the game\u0026rsquo;s state from the auto save slot. Save State to File: Save the game\u0026rsquo;s state to a user-specified file. Load State from File: Load the game\u0026rsquo;s state from a user-specified file. Select Save Slot X: Select the specified save state slot. Load Last Session: Restores the game to the state it was the last time you stopped playing it. FDS / VS System / NSF settings FDS Settings The FDS (Famicom Disk System) is a Famicom-specific add-on that allows games to be stored on special floppy disks. These options help simplify playing FDS games by allowing the emulation to fast-forward through load screens and automatically switch disk when needed.\nAutomatically insert disk 1 side A when starting FDS games: By default, the FDS boots with no disk inserted in the drive. This option makes it so the player does not need to manually insert disk 1, side A manually.\nAutomatically fast forward FDS games when disk or BIOS is loading: FDS games contain a large number of load screens due to their data being stored on floppy drives. Mesen needs to emulate this floppy drive\u0026rsquo;s speed to ensure accurate emulation. This option makes it so Mesen runs the emulation as fast as it can when a game is loading data from the disk, which greatly reduces the time spent on loading screens.\nAutomatically switch disks for FDS games: FDS games are often split into multiple floppy disks, and each disk has 2 separate sides. Due to this, FDS games often ask the player to change disk, or flip to the other side. When this option is enabled, Mesen will attempt to detect when a game is asking for another disk and automatically insert it.\nVS DualSystem Settings For VS DualSystem games, 2 separate consoles run at the same time, producing 2 different sets of audio and video. These options allow you to configure which audio/video streams you want to hear/see.\nShow video for [\u0026hellip;]: Selects whether both screens should be shown, or just one of them.\nPlay audio for [\u0026hellip;]: Selects whether both audio streams should be played, or just one of them.\nNSF Settings Move to the next track after [x] milliseconds of silence: If the currently playing track outputs no audio for over X milliseconds, the player will automatically move to the next track. Note: This only applies for .nsf files, not .nsfe files.\nLimit track run time to [x] seconds: Once the current track has been playing for over X seconds, the player will automatically move to the next track. Note: This only applies for .nsf files, not .nsfe files.\nEnable APU IRQs for NSF files: When enabled, APU IRQs will be allowed when NSF files are playing. Some NSF files do not properly disable APU IRQs in their initialization code, which will cause them to break if this option is enabled. This option should not be enabled unless absolutely necessary.\nFolders and File Associations File Associations: Use these options to associate Mesen with these file types. This will allow you to double-click on these files in a file explorer to open them in Mesen.\nData Storage Location: Mesen can either store its data in your user profile or in the same folder as the executable file itself. This is configured when you launch Mesen for the first time, but can also be changed here. When changing from one option to the other, Mesen will automatically copy all files from one folder to the other, allowing you to keep your save data and all other important files automatically.\nFolder Overrides: On top of configuring the main folder where Mesen keeps its data, you may also specify custom locations for certain folders used by Mesen to store user-created files such as recordings or save data.\nAdvanced Options Disable built-in game database: Mesen contains a built-in database containing information on thousands of rom files \u0026ndash; it uses this database to use the most appropriate settings when loading a game (e.g NTSC vs PAL) and to fix incorrect file headers. Disabling this option is not recommended.\nDisable high resolution timer: Mesen normally forces Windows' timer resolution down to 1 millisecond when a game is running. Keeping a low timer resolution helps keep the video and audio output as smooth as possible. Enabling this option disables Mesen\u0026rsquo;s default behavior and keeps the timer interval to its regular value, which may slightly improve battery life on a laptop (which is the only reason why this option exists). Disabling this option is not recommended.\nKeep rewind data for the last [x] minutes: The rewind feature in Mesen periodically takes save states and keeps them in memory to allow the emulator to rewind the game. These save states take a minimal amount of memory (roughly 1MB per minute). To limit the amount of memory that Mesen can use for rewind data, this configures the number of minutes that it is possible to rewind for.\nWindow Settings Always display on top of other windows: When enabled, Mesen\u0026rsquo;s window will always be displayed above all other windows.\nDo not allow the main window to be resized using the mouse: When enabled, the main window can only be resized by changing the video scaling option.\nUI Settings Disable on-screen display (OSD): When enabled, all on-screen messages are disabled.\nDisplay additional information in title bar: When enabled, additional information is shown in the title bar (such as filter, scale, etc.), next to the game\u0026rsquo;s name.\nShow full file path in recent file list: When enabled, the recent files menu will display the file\u0026rsquo;s full path instead of just its name.\nShow frame counter: When enabled, the number of frames emulated since the last reset will be shown on the screen.\nShow game timer: When enabled, the amount of time elapsed since the last reset will be shown on the screen.\nShow game configuration dialog when loading VS System games: VS System arcade cabinets usually have a number of options that can be physically configured via DIP switches in the arcade cabinet itself. When enabled, this option makes it so the DIP switches' configuration dialog is shown every time a VS System game is loaded. This dialog can also be manually accessed from the Game menu.\nGame Selection Screen Settings Start game from power-on instead of resuming the previous state: Normally, when using the game selection screen to start a game, the game resumes where you left off. When this option is enabled, the game starts over from power on.\nDisable game selection screen: When enabled, the game selection screen is hidden and cannot be used.\n"},{"uri":"/debugging/apuviewer.html","title":"APU Viewer","tags":[],"description":"","content":"The APU Viewer displays information about the APU\u0026rsquo;s channels. The internal flags of every channel are shown, as well as some additional information, such as the channel\u0026rsquo;s current frequency.\nIt can also be used to temporarily mute specific channels by unchecking them in the Channel Control section.\n"},{"uri":"/debugging/assembler.html","title":"Assembler","tags":[],"description":"","content":"The assembler allows writing new code, editing existing code and running arbitrary code.\nUsage Code is assembled on-the-fly, with the resulting byte code being shown on the right.\nAny compilation error will be shown in the list at the bottom \u0026ndash; double-click an error in the list to navigate to the line that caused it.\nOnce you are done editing the code, you can either Execute it, or Apply it. Executing the code will make it run in the $3000-$3FFF memory range (temporarely overriding the PPU\u0026rsquo;s normal behavior) and break the execution once the code is done executing. On the other hand, clicking Apply will write the code to the specified memory address - this can be used to create new code in RAM, for example, or alter existing code in PRG ROM.\nNote: When editing an existing block of code, the assembler keeps track of how many bytes of code the original code contained, as well as whether or not an RTS instruction was present. If the new code is lacking an RTS instruction, or is too large to fit into the original block of code, a warning will be shown before applying the changes.\nSupported features All official opcodes and addressing modes are fully supported. All unofficial opcodes with well-defined behavior are supported (see limitations below) Hexadecimal ($ prefix) and decimal values are supported. Labels can be used and defined in the code. When using labels, the assembler will favor zero-page addressing when possible - only using other types of addressing when necessary. The .byte directive can be used to add arbitrary data to the output. Limitations Unofficial opcodes: The assembler supports all unofficial opcodes that Mesen can emulate. However, opcodes that have undefined behavior (and thus are not emulated by Mesen) are not supported. Additionally, name conflicts make it so it is impossible to use any NOP opcode other than the standard NOP opcode.\n Defining labels: As mentioned above, it is possible to define labels to use in the assembler. However, these labels are (currently) not permanent - they are discarded once the assembler is closed.\n Display Options Syntax highlighting can be configured (or disabled) via the View menu.\nIt is also possible to change the font size.\n"},{"uri":"/debugging/eventviewer.html","title":"Event Viewer","tags":[],"description":"","content":"PPU View The Event Viewer\u0026rsquo;s PPU view allows you to visually check the timing at which various events (register read/writes, NMIs, IRQs, etc.) occur. This can be useful when trying to perform timing-critical mid-frame changes to the PPU, or to verify that PPU updates finish before vertical blank ends, etc.\nThe colors can be configured and it\u0026rsquo;s also possible to define breakpoints as marks to be shown on the Event Viewer. This is done by enabling a breakpoint\u0026rsquo;s Mark on Event Viewer option. This allows the event viewer to be used to display virtually any special event that needs to be tracked.\nWhen the Show previous frame's events option is enabled, all events for the last full frame (e.g the last 261 scanlines for NTSC) will be shown. Otherwise, only events that have occurred since the last pre-render scanline (scanline -1) will be shown.\nList View The list view displays the same general information as the PPU view, but in a sortable list.\n"},{"uri":"/debugging/memorytools.html","title":"Memory Tools","tags":[],"description":"","content":"Memory Viewer The memory viewer offers read and write access to all types of ROM and RAM:\n CPU Memory PPU Memory PRG ROM Work RAM Save RAM CHR ROM CHR RAM Nametable RAM Palette RAM Sprite / OAM RAM Secondary OAM RAM Note: Only memory types that are available for the currently loaded ROM will be shown in the dropdown.\nHighlighting There are a number of highlighting/coloring options in the memory viewer.\nView→Memory Access Highlightinghas coloring options for addresses that were recently read, written or executed (colored in blue, redand green, respectively). A fade-out period can also be configured, after which the byte will revert to its normal black color.\nView→Data Type Highlightingoffers options to change the background color of specific bytes based on their type: Labeled bytes Breakpoints Code bytes (PRG ROM only) Data bytes (PRG ROM only) DMC sample bytes (PRG ROM only) Drawn bytes (CHR ROM only) Read bytes (CHR ROM only) View→De-emphasizeoffers options to display bytes matching certain conditions (unused, read, written or executed) in gray.\nThe Ignore writes that do not alter data option prevents CPU writes from being highlighted when the value being written matches the one already present in memory.\nNote: It is possible to customize the colors used by the memory viewer in View→Configure ColorsOptions Display Options Auto-refresh speed: Configures the speed at which the memory view refreshes. Select Font: Allows you to select which font to use in the memory view. Use high text density mode: When enabled, the vertical space between every row is reduced, allowing more bytes to be shown on the screen at once. Show characters: When enabled, a character representation of the binary data is shown on the right. This can be combined with TBL files to find/edit in-game dialog in the memory tools. Show label tooltip on mouseover: When enabled, bytes for which a label exists will have a tooltip with the label\u0026rsquo;s information. Other Options Use per-byte left/right navigation: When enabled, pressing the left or right arrows more directly to the next byte, instead of the next nibble. Use per-byte editing mode: When enabled, it is no longer possible to select individual nibbles and a full byte\u0026rsquo;s value must be written before it takes effect. (Normally, edits are applied immediately once either nibble is modified) Editing Memory Values There are 2 ways to edit memory values:\n Using the hex view: Click on the byte you want to change in the hex view (on the left), and type hexadecimal values to replace it.\n Using the text view: Click on the section you want to change in the text view (on the right), and type ASCII text to replace. This method is rather limited and usually not very useful unless the ROM uses ASCII values for its text.\n Importing / Exporting For most types of memory, it is possible to export its contents to a binary file as well as import it back from a file. Use the Import and Export commands to do this.\nFreezing values Using the right-click menu, you can Freeze values in CPU Memory. Frozen addresses are shown in magenta.\nFrozen addresses will no longer be affected by write operations - effectively making those addresses read-only for the CPU. It is still possible to manually edit the value of frozen addresses using the memory viewer.\nUsing TBL Files TBL files are text files that define mappings between sequences of bytes and text characters. For example, it might define the byte $95 as the character \u0026lsquo;A\u0026rsquo;.\nNormally, when no TBL file is loaded, the memory viewer will display each byte\u0026rsquo;s standard ASCII representation on the right-hand side. Once a TBL file is loaded, the text representation of the data will be updated to reflect the TBL mappings. This is useful, for example, when translating text.\nMemory Access Counters When active, the debugger keeps track of all CPU and PPU memory reads, writes and executions. It is possible to view these counters here.\nUse the Sort By option to sort the list based on different criteria.\nThe Reset button allows you to reset all counters back to 0 \u0026ndash; this is useful when you are trying to gather data for a specific portion of the execution.\nUse the Highlight uninitialized memory reads option to track down any reads done to RAM memory before the RAM memory has been initialized after a power cycle \u0026ndash; reading from uninitialized memory can produce random behavior, which is usually unwanted.\n"},{"uri":"/apireference/emulation.html","title":"Emulation","tags":[],"description":"","content":"getState Syntax\nemu.getState() Return value\nTable Current emulation state with the following structure:\nregion: int, clockRate: int, cpu: { status: int, a: int, irqFlag: int, cycleCount: int (64-bit, unsigned), pc: int, y: int, x: int, sp: int, nmiFlag: bool }, ppu: { cycle: int, scanline: int, frameCount: int, control: { backgroundEnabled: bool, intensifyBlue: bool, intensifyRed: bool, backgroundPatternAddr: int, grayscale: bool, verticalWrite: bool, intensifyGreen: bool, nmiOnVBlank: bool, spritesEnabled: bool, spritePatternAddr: int, spriteMask: bool, largeSprites: bool, backgroundMask: bool }, status: {, spriteOverflow: bool, verticalBlank: bool, sprite0Hit: bool }, state: { status: int, lowBitShift: int, xScroll: int, highBitShift: int, videoRamAddr: int, control: int, mask: int, tmpVideoRamAddr: int, writeToggle: bool, spriteRamAddr: int } }, apu: { square1: { outputVolume: int, frequency: float, duty: int, period: int, enabled: bool, dutyPosition: int, sweepShift: int, sweepPeriod: int, sweepEnabled: bool, sweepNegate: bool envelope: { counter: int, loop: bool, divider: int, volume: int, startFlag: bool, constantVolume: bool },\tlengthCounter: { halt: bool, counter: int, reloadValue: int }\t}, square2: { outputVolume: int, frequency: float, duty: int, period: int, enabled: bool, dutyPosition: int, sweepShift: int, sweepPeriod: int, sweepEnabled: bool, sweepNegate: bool, envelope: { counter: int, loop: bool, divider: int volume: int, startFlag: bool, constantVolume: bool }, lengthCounter: { halt: bool, counter: int, reloadValue: int }\t}, triangle: { outputVolume: int, frequency: float, sequencePosition: int, period: int, enabled: bool, lengthCounter: { halt: bool, counter: int, reloadValue: int }\t}, noise: { modeFlag: bool, enabled: bool, outputVolume: int, frequency: float, period: int, shiftRegister: int, envelope: { counter: int, loop: bool, divider: int, volume: int, startFlag: bool, constantVolume: bool },\tlengthCounter: { halt: bool, counter: int, reloadValue: int } }, dmc: { sampleLength: int, irqEnabled: bool, loop: bool, outputVolume: int, bytesRemaining: int, sampleAddr: int, period: int, sampleRate: float }, frameCounter: { fiveStepMode: int, irqEnabled: int, sequencePosition: int } }, cart: { selectedPrgPages: array, chrRomSize: int, chrRamSize: int, prgPageCount: int, chrPageSize: int, selectedChrPages: array, chrPageCount: int, prgRomSize: int, prgPageSize: int, } Description\nReturn a table containing information about the state of the CPU, PPU, APU and cartridge.\nsetState Syntax\nemu.setState(state) Parameters\nstate - Table A table containing the state of the emulation to apply.\nReturn value\nNone\nDescription\nUpdates the CPU and PPU\u0026rsquo;s state. The state parameter must be a table in the same format as the one returned by getState()\nNote: the state of the APU or cartridge cannot be modified by using setState().\nbreakExecution Syntax\nemu.breakExecution() Return value\nNone\nDescription\nBreaks the execution of the game and displays the debugger window.\nexecute Syntax\nemu.execute(count, type) Parameters\ncount - Integer The number of cycles or instructions to run before breaking\ntype - Enum See executeCountType\nReturn value\nNone\nDescription\nRuns the emulator for the specified number of cycles/instructions and then breaks the execution.\nstepOut Syntax\nemu.stepOut() Parameters\nNone\nReturn value\nNone\nDescription\nSteps over the next instruction and then breaks the execution.\nstepOver Syntax\nemu.stepOver() Parameters\nNone\nReturn value\nNone\nDescription\nSteps out of the current subroutine and then breaks the execution.\nreset Syntax\nemu.reset() Return value\nNone\nDescription\nResets the current game.\nstop Syntax\nemu.stop(exitCode) Parameters\nexitCode - Integer The exit code that the Mesen process will return when exiting (when used in test runner mode)\nReturn value\nNone\nDescription\nStops and unloads the current game. When in test runner mode, this will also exit Mesen itself and the Mesen process will return the specified exit code.\nresume Syntax\nemu.resume() Return value\nNone\nDescription\nResumes execution after breaking.\nrewind Syntax\nemu.rewind(seconds) Parameters\nseconds - Integer The number of seconds to rewind\nReturn value\nNone\nDescription\nInstantly rewinds the emulation by the number of seconds specified.\nNote: this can only be called from within a \u0026ldquo;StartFrame\u0026rdquo; event callback.\n"},{"uri":"/debugging/performanceprofiler.html","title":"Performance Profiler","tags":[],"description":"","content":"The profiler automatically collects data about all function calls done by the code, as well as the number of clock cycles spent in each respective function.\nUsing the profiler makes it is easy to find the bottlenecks in a game\u0026rsquo;s code, which can help code optimization efforts.\nIf you are familiar with Visual Studio\u0026rsquo;s profiler, these columns should be familiar:\n Call Count: The number of times this function was called during profiling Inclusive Time (Cyc): The amount of CPU cycles spent within this function (including the cycles spent by all functions called by this function) Inclusive Time (%): The relative portion of CPU time spent within this function (including the time spent by all functions called by this function) Exclusive Time (Cyc): The amount of CPU cycles spent within this function (functions called by this function are excluded) Exclusive Time (%): The relative portion of CPU time spent within this function (functions called by this function are excluded) Call Count: The number of times this function was called during profiling Use the Reset button to reset the profiler\u0026rsquo;s data \u0026ndash; use this when you want to profile a specific portion of the execution.\n"},{"uri":"/apireference/input.html","title":"Input","tags":[],"description":"","content":"getInput Syntax\nemu.getInput(port) Parameters\nport - Integer The port number to read (0 to 3)\nReturn value\nTable A table containing the status of all 8 buttons.\nDescription\nReturns a table containing the status of all 8 buttons: { a, b, select, start, up, down, left, right }\nsetInput Syntax\nemu.setInput(port, input) Parameters\nport - Integer The port number to apply the input to (0 to 3)\ninput - Table A table containing the state of some (or all) of the 8 buttons (same format as returned by getInput)\nReturn value\nNone\nDescription\nButtons enabled or disabled via setInput will keep their state until the next inputPolled event.\nIf a button\u0026rsquo;s value is not specified to either true or false in the input argument, then the player retains control of that button. For example, setInput(0, { select = false, start = false}) will prevent the player 1 from using both the start and select buttons, but all other buttons will still work as normal. To properly control the emulation, it is recommended to use this function within a callback for the inputPolled event. Otherwise, the inputs may not be applied before the ROM has the chance to read them.\ngetMouseState Syntax\nemu.getMouseState() Return value\nTable The mouse\u0026rsquo;s state\nDescription\nReturns a table containing the position and the state of all 3 buttons: { x, y, left, middle, right }\nisKeyPressed Syntax\nemu.isKeyPressed(keyName) Parameters\nkeyName - String The name of the key to check\nReturn value\nBoolean The key\u0026rsquo;s state (true = pressed)\nDescription\nReturns whether or not a specific key is pressed. The \u0026ldquo;keyName\u0026rdquo; must be the same as the string shown in the UI when the key is bound to a button.\n"},{"uri":"/debugging/ppuviewer.html","title":"PPU Viewer","tags":[],"description":"","content":"The PPU Viewer is a collection of tools allowing you to view/edit the current state of various parts of the PPU\u0026rsquo;s memory: nametable RAM, CHR ROM/RAM, palette RAM and OAM (sprite) RAM.\nAll tabs share some common settings:\n Auto-refresh: Enabled by default, this makes the PPU viewer refresh at a rate of 15 FPS. Auto-refresh speed: Configures at what speed the PPU viewer will refresh itself (15/30/60 FPS) Show information overlay: When enabled, a mouse-over overlay is shown in the nametable/CHR/sprite viewers with information on the tile/sprite below the mouse cursor. When emulation is running, show PPU data at scanline [y] and cycle : When using the auto-refresh option, this allows you to control at which point in a frame (cycle \u0026amp; scanline) the data is refreshed while the emulation is running. This is useful for games that perform CHR bank switching in the middle of a frame, for example. Nametable Viewer The nametable viewer displays the contents of all 4 nametables (PPU addresses $2000 to $2FFF).\nMouve-over a tile to display that tile\u0026rsquo;s information on the right. Double-clickon a tile in the nametable viewer to view/edit it in the CHR Viewer.\nAdditionally, you can right-clickon a tile to get more options:\n Edit in Memory Viewer: Opens up the memory tools at this specific tile\u0026rsquo;s location in nametable memory. View in CHR Viewer: Switches to the CHR Viewer and selects the tile (same as double-clicking) Copy Tile (HD Pack format): Copies the tile\u0026rsquo;s information (text) to the clipboard (for use with HD Packs). Copy image to clipboard: Copies the nametable to the clipboard. Export image to PNG: Exports the current nametable image to a PNG file. There are also a number of display options:\n Show PPU Scroll Overlay: Shows a blue rectangular overlay showing the current scroll position of the screen. Show attribute colors only: When enabled, the viewer will show the 4 colors available in each tile, rather than the actual contents of the nametables. This can be useful when trying to debug attribute-related coloring issues. Show Tile Grid: Displays a 8x8 pixels redgrid. Show Attribute Grid: Displays a 16x16 pixels bluegrid. Use Grayscale Palette: Forces the nametables to be shown in a 4-color grayscale palette. Highlight tile selected in CHR viewer: When enabled, click on a tile in the CHR viewer to select it, all occurrences of that tile will then be marked by a redrectangle in the nametable viewer. Update Highlighting The nametable viewer can display nametable (tiles and attributes) updates by highlighting the tiles affected by the updates.\n Tile Updates: Displays a 8x8 red square overlay over tiles that have changed since the last frame. Attribute Updates: Displays a 16x16 yellow square overlay over attributes that have changed since the last frame. Ignore writes that do not alter data: By default, all memory locations written to during the last frame will be highlighted. By enabling this option, only memory locations that have changed value will be highlighted. CHR Viewer/Editor The CHR Viewer tab displays up to 2 4kb banks of CHR data at once. It can display any portion of CHR RAM/ROM, even banks that are not currently selected.\nIt also doubles up as a very simple graphic editor.\nYou can right-clickon a tile to copy the tile\u0026rsquo;s information (based on the currently selected palette) to the clipboard (for use with HD Packs).\nDisplay Options CHR Selection: Select which portion of CHR memory to display in the viewer - by default, the portions of CHR memory mapped to the $0000-$1FFF range in PPU memory are shown. Palette Selection: Selects which palette to use to render the tiles - the first 4 palettes are for tiles, the last 4 palettes are for sprites. There is also a 9th palette named \u0026ldquo;Grayscale\u0026rdquo; which forces the CHR viewer to display tiles in a 4-color grayscale palette. Highlight: This option allows tiles to be highlighted/dimmed based on the CDL file\u0026rsquo;s current data. This makes it possible to highlight/dim tiles that have never been drawn by the PPU, or vice versa. This option is only available for CHR ROM games. Display as 16x8 sprites: When enabled, changes the display order of the tiles to make it easier to visualize 16x8 sprites. Display tiles using their last known palette: When enabled, any tile that has appeared in nametable memory since the debugger was opened will be shown using their last known palette (this overrides the palette selection dropdown for those tiles) Show single color tiles using grayscale palette: When enabled, any tile that contains a single color will be displayed using the grayscale palette instead (this overrides the palette selection dropdown for those tiles) Editing Tiles To edit a tile, first click on the tile you want to edit in the left-side of the window. This will select the tile and highlight it with a transparent square.\nYou can select the color you want to use by clicking on the Color Picker. You can also press keys 1 to 4 on your keyboard to quickly switch between the four colors.\nWith a tile selected, move your mouse to the tile preview above the Color Picker and click+drag to start drawing. Right-click can be used to draw as well \u0026ndash; it always draws color #0.\nSprite Viewer The Sprite Viewer displays the contents of OAM RAM. Mouve-over a sprite to display that sprite\u0026rsquo;s information on the right.\nThe Screen Preview displays all sprites as they will be shown on the screen, based on the current OAM data.\nLike the nametable viewer, double-clickon a tile to view/edit it in the CHR Viewer \u0026ndash; this works in the Screen Preview as well.\nAdditionally, you can right-clickon a tile to copy the tile\u0026rsquo;s information to the clipboard (for use with HD Packs).\nDisplay outline around all sprites in preview: When enabled, all the sprites shown in the preview screen will be highlighted by a white rectangle.\nPalette Viewer/Editor The Palette Viewer displays basic information about the current state of palette RAM.\nIt shows which colors are configured in each of the 8 available palettes.\nYou can click on any color to select another color for that slot.\nCompact View All PPU viewer tabs can be toggled to a standalone compact window, this can be done by pressing on the green arrow at the top right of the window. There is also a customizable keyboard shortcut for this (Default: Ctrl+Q) and the windows can be opened in compact mode directly using keyboard shortcuts or the PPU Viewer (Compact) menu in the Tools or Debug menus.\nThe compact viewers save their own position independently from the regular full-sized PPU window.\nZoomed View In addition to the compact view, it\u0026rsquo;s also possible to double the size of the viewers by clicking on the 2x button next to the compact view button at the top right of the window. There is a shortcut for this as well (Default: Ctrl+W).\n"},{"uri":"/apireference/logging.html","title":"Logging","tags":[],"description":"","content":"displayMessage Syntax\nemu.displayMessage(category, text) Parameters\ncategory - String The category is the portion shown between brackets []\ntext - String Text to show on the screen\nReturn value\nNone\nDescription\nDisplays a message on the main window in the format \u0026ldquo;[category] text\u0026rdquo;\nlog Syntax\nemu.log(text) Parameters\ntext - String Text to log\nReturn value\nNone\nDescription\nLogs the given string in the script\u0026rsquo;s log window - useful for debugging scripts.\n"},{"uri":"/debugging/scriptwindow.html","title":"Script Window","tags":[],"description":"","content":"The Script Window allows Lua scripting via a Mesen-specific API. Using this API, you can interact with the emulation core to perform a variety of things (e.g: logging, drawing, implementing an AI).\nThe code editor contains an autocomplete feature for all of Mesen\u0026rsquo;s API \u0026ndash; typing emu. will display an autocomplete popup displaying all available functions. Select a function in the list to see its parameters, return value and description.\nMultiple script windows can be opened at once to combine the effects of several scripts together.\nScripts can be loaded from the disk and edited in any other text editor. When using an external editor to modify the script, it is suggested to turn on the Script→Auto-reload when file changes option to automatically reload the script each time it is saved to the disk.\nTo start a script, press F5.\nTo stop a script, press Escape or close the script window.\nThe Log Window at the bottom will display any Lua errors that occur while running the script. Additionally, any calls to emu.log() will also display their content in the log window.\nBuilt-in Scripts A number of built-in scripts are accessible from the script window\u0026rsquo;s UI. They can be accessed from the File→Built-in Scripts menu, or directly from the toolbar. These scripts serve as both examples for the Lua API and can also be useful in a number of ways.\nThe scripts have (mostly) been contributed by users of Mesen (see the top of each script for proper credits) - if you have useful/interesting scripts that you have written and would like to have included, let me know!\n"},{"uri":"/apireference/memoryaccess.html","title":"Memory Access","tags":[],"description":"","content":"read / readWord Syntax\nemu.read(address, type, signed = false) emu.readWord(address, type, signed = false) Parameters\naddress - Integer The address/offset to read from.\ntype - Enum The type of memory to read from. See memType.\nsigned - (optional) Boolean If true, the value returned will be interpreted as a signed value.\nReturn value\nAn 8-bit (read) or 16-bit (readWord) value.\nDescription\nReads a value from the specified memory type.\nWhen calling read / readWord with the memType.cpu or memType.ppu memory types, emulation side-effects may occur.\nTo avoid triggering side-effects, use the memType.cpuDebug or memType.ppuDebug types, which will not cause side-effects.\nwrite / writeWord Syntax\nemu.write(address, value, type) emu.writeWord(address, value, type) Parameters\naddress - Integer The address/offset to write to. value - Integer The value to write.\ntype - Enum The type of memory to write to. See memType.\nReturn value\nNone\nDescription\nWrites an 8-bit or 16-bit value to the specified memory type.\nNormally read-only types such as PRG-ROM or CHR-ROM can be written to when using memType.prgRom or memType.chrRom.\nChanges will remain in effect until a power cycle occurs.\nTo revert changes done to ROM, see revertPrgChrChanges.\nWhen calling write / writeWord with the memType.cpu or memType.ppu memory types, emulation side-effects may occur.\nTo avoid triggering side-effects, use the memType.cpuDebug or memType.ppuDebug types, which will not cause side-effects.\nrevertPrgChrChanges Syntax\nemu.revertPrgChrChanges() Return value\nNone\nDescription\nReverts all modifications done to PRG-ROM and CHR-ROM via write/writeWord calls.\ngetPrgRomOffset Syntax\nemu.getPrgRomOffset(address) Parameters\naddress - Integer A CPU address (Valid range: $0000-$FFFF)\nReturn value\nInteger The corresponding byte offset in PRG ROM\nDescription\nReturns an integer representing the byte offset of the specified CPU address in PRG ROM based on the mapper\u0026rsquo;s current configuration. Returns -1 when the specified address is not mapped to PRG ROM.\ngetChrRomOffset Syntax\nemu.getChrRomOffset(address) Parameters\naddress - Integer A PPU address (Valid range: $0000-$3FFF)\nReturn value\nInteger The corresponding byte offset in CHR ROM\nDescription\nReturns an integer representing the byte offset of the specified PPU address in CHR ROM based on the mapper\u0026rsquo;s current configuration. Returns -1 when the specified address is not mapped to CHR ROM.\ngetLabelAddress Syntax\nemu.getLabelAddress(label) Parameters\nlabel - String The label to look up\nReturn value\nInteger The corresponding CPU address\nDescription\nReturns the address of the specified label. This address can be used with the memory read/write functions (read(), readWord(), write(), writeWord()) using the emu.memType.cpu or emu.memType.cpuDebug memory types.\n"},{"uri":"/debugging/texthooker.html","title":"Text Hooker","tags":[],"description":"","content":"Text Hooker The text hooker\u0026rsquo;s main window scans the current screen for recognized characters and outputs the equivalent text on the right.\nFor games that split the screen, you can use the When emulation is running, show PPU data at scanline option at the bottom to capture the portion of the screen that you need.\nTo configure character mappings, see the Character Mappings section below.\nCharacter Mappings This tab allows you to configure the mappings between CHR tiles and text characters. These mappings are based on the shape of the tile and are shared between all games. A number of mappings are built into Mesen, so some characters may already be recognized automatically.\nWhen you want to add new mappings, simply edit the textbox below the tile you want to configure.\nFor Japanese text, you can specify dakuten (濁点) and handakuten (半濁点) by typing daku and han in the textbox. Alternatively, you can also use the Unicode characters for them: ゙ (U+3099) and ゚ (U+309A), respectively.\n"},{"uri":"/debugging/tracelogger.html","title":"Trace Logger","tags":[],"description":"","content":"Basic Information The trace logger displays the execution log of the CPU. It can display the last 30,000 CPU instructions executed. Additionally, it is also possible to log these instructions to the disk by using the Start Logging button. Log files can rapidly grow in size (to several GBs worth of data in a few seconds), so it is recommended to log for the shortest amount of time needed.\nDisplay Options A number of options that toggle the display of several elements exist: Registers, CPU Cycles, PPU Cycles, PPU Scanline, Show Effective Addresses, Byte Code, Frame Count, Additional Information (IRQ, NMI, etc.). Adjust these based on your needs.\nAdditionally, you can alter the way some elements are displayed:\n Status Flag Format: Offers a number of different ways to display the CPU\u0026rsquo;s status flags. Indent code based on stack pointer: When enabled, the log\u0026rsquo;s lines will be indented by 1 character for every byte pushed to the stack. This is useful to quickly be able to identify function calls, for example. Use Labels: When enabled, addresses that match known labels will be replaced by their label instead. Custom Formatting The trace logger\u0026rsquo;s output can be customized by enabling the Format Override option and editing the format string. The following tags can be used to customize the format:\n[ByteCode]: The byte code for the instruction (1 to 3 bytes). [Disassembly]: The disassembly for the current instruction. [EffectiveAddress]: The effective address used for indirect addressing modes. [MemoryValue]: The value stored at the memory location referred to by the instruction. [PC]: Program Counter [A]: A register [X]: X register [Y]: Y register [SP]: Stack Pointer [P]: Processor Flags [Cycle]: The current PPU cycle. [Scanline]: The current PPU scanline. [FrameCount]: The current PPU frame. [CycleCount]: The current CPU cycle (64-bit unsigned value, resets to 0 at power on) You can also specify some options by using a comma. e.g:\n[Cycle,3] will display the cycle and pad out the output to always be 3 characters wide. [Scanline,h] will display the scanline in hexadecimal. [Align,50]: Align is a special tag that is useful when trying to align some content. [Align,50] will make the next tag start on column 50. Conditional Logging The Condition field accepts conditional statements in the same format as breakpoints.\nWhen a condition is entered, only instructions that match the given condition will be logged. This can be used, for example, to log cartridge register writes (e.g: IsWrite \u0026amp;\u0026amp; Address \u0026gt;= $8000), PPU register reads (e.g: IsRead \u0026amp;\u0026amp; Address \u0026gt;= $2000 \u0026amp;\u0026amp; Address \u0026lt;= $3FFF) or when a specific portion of CPU memory is being executed (e.g: pc \u0026gt;= $8100 \u0026amp;\u0026amp; pc \u0026lt;= $8150).\nConditions are very flexible and can be used to check just about any condition \u0026ndash; use them to your advantage.\n"},{"uri":"/debugging/debuggerintegration.html","title":"Integration with compilers","tags":[],"description":"","content":"When building homebrew software in assembly or C, it is possible to export the labels used in your code and import them into Mesen to simplify the debugging process. This allows the debugger to know which portions of the ROM correspond to which functions in your code, as well as display your code\u0026rsquo;s comments inside the debugger itself.\nIntegration with compilers CC65 / CA65 CC65/CA65 are able to produce .DBG files which can be imported into Mesen\u0026rsquo;s debugger.\nTo make CC65/CA65 create a .DBG file during the compilation, use the --dbgfile command line option.\nTo import the .DBG file, use the File→Workspace→Import Labels command in the debugger window.\nYou can also enable the Auto-load DBG/MLB files to make Mesen load any .DBG file it finds next to the ROM whenever the debugger is opened or the power cycle button is used.\nNote: For this option to work, the ROM file must have the same name as the DBG file (e.g MyRom.nes and MyRom.dbg) and be inside the same folder.\nSource View When a .DBG file is loaded, 2 additional options appear in the code window\u0026rsquo;s right-click menu:\n Switch to Source View: This turns on Source View mode, which allows you to debug the game using the original code files, rather than the disassembly. This can be used for both assembly and C projects. Show source code as comments: When enabled, the debugger will show the original source code to the right of the disassembly, as comments. ASM6f Integration with ASM6 is possible by using freem\u0026rsquo;s branch of ASM6 named ASM6f.\nThis fork contains 2 additional command line options that are useful when using Mesen: -m and -c\n-m produces a .mlb (Mesen labels) file that can be imported manually using the File→Workspace→Import Labels command.\n-c produces a .cdl (Code Data Logger) file which can be imported manually using the Tools→Code/Data Logger→Load CDL file command.\nAdditionally, you can use the Auto-load DBG/MLB files and Auto-load CDL files options in the File→Workspace menu to automatically load MLB and CDL files present in the same folder as the current ROM, with the same filename (e.g MyRom.nes, MyRom.mlb, MyRom.cdl).\nNESASM Mesen can also import the .fns symbol files that NESASM produces. However, due to limitations in the .fns format, these labels can only be reliably imported for games containing exactly 32kB of PRG ROM. If you are creating a larger game, CC65/CA65 offers the best integration features at the moment.\nImporting and exporting labels Mesen can also import and export labels in .mlb format. This is the same format as the label files produced by ASM6f. The ability to import labels can be used to integrate the debugger with your own workflow (e.g by creating your own scripts that produce .mlb files)\nMesen Label Files (.mlb) The .mlb files used by Mesen to import/export labels is a simple text format. For example, this defines a label and comment on byte $100 of PRG ROM:\nP:100:MyLabel:This is a comment The format also supports multi-byte labels, defined by giving specifying an address range:\nR:200-2FF:ShadowOam The first letter on each row is used to specify the label\u0026rsquo;s type:\nP: PRG ROM labels R: RAM labels (for the NES' internal 2kb RAM) S: Save RAM labels W: Work RAM labels G: Register labels (these are used to define PPU/APU/Mapper registers, etc.) Import Settings For fine-grain control over the DBG/MLB file imports, the Import Settings window can be used.\nThis allows you to configure which types of labels/comments should be imported, as well as choosing whether or not Mesen should delete all existing labels before importing DBG/MLB files.\n"},{"uri":"/apireference/misc.html","title":"Miscellaneous","tags":[],"description":"","content":"Save States There are 2 separate save state APIs.\nThe first one is synchronous and uses the saveSavestate and loadSavestate functions. Its main restriction is that it can only be used inside \u0026ldquo;startFrame\u0026rdquo; or \u0026ldquo;cpuExec\u0026rdquo; callback functions.\nThe second API is asynchronous and uses an internally-managed \u0026ldquo;save slot\u0026rdquo; system to hold states in memory. It uses the following functions: saveSavestateAsync, loadSavestateAsync, getSavestateData and clearSavestateData.\nsaveSavestate Syntax\nemu.saveSavestate() Return value\nString A string containing a binary blob representing the emulation\u0026rsquo;s current state.\nDescription\nCreates a savestate and returns it as a binary string. (The savestate is not saved on disk)\nNote: this can only be called from within a \u0026ldquo;startFrame\u0026rdquo; event callback or \u0026ldquo;cpuExec\u0026rdquo; memory callback.\nsaveSavestateAsync Syntax\nemu.saveSavestateAsync(slotNumber) Parameters\nslotNumber - Integer A slot number to which the savestate data will be stored (slotNumber must be \u0026gt;= 0)\nReturn value\nNone\nDescription\nQueues a save savestate request. As soon at the emulator is able to process the request, it will be saved into the specified slot.\nThis API is asynchronous because save states can only be taken in-between 2 CPU instructions, not in the middle of an instruction. When called while the CPU is in-between 2 instructions (e.g: inside the callback of an cpuExec or startFrame event), the save state will be taken immediately and its data will be available via getSavestateData right after the call to saveSavestateAsync.\nThe savestate can be loaded by calling the loadSavestateAsync function.\nloadSavestate Syntax\nemu.loadSavestate(savestate) Parameters\nsavestate - String A binary blob representing a savestate, as returned by saveSavestate()\nReturn value\nNone\nDescription\nLoads the specified savestate.\nNote: this can only be called from within a \u0026ldquo;startFrame\u0026rdquo; event callback or \u0026ldquo;cpuExec\u0026rdquo; memory callback.\nloadSavestateAsync Syntax\nemu.loadSavestateAsync(slotNumber) Parameters\nslotNumber - Integer The slot number to load the savestate data from (must be a slot number that was used in a preceding saveSavestateAsync call)\nReturn value\nBoolean Returns true if the slot number was valid.\nDescription\nQueues a load savestate request. As soon at the emulator is able to process the request, the savestate will be loaded from the specified slot.\nThis API is asynchronous because save states can only be loaded in-between 2 CPU instructions, not in the middle of an instruction. When called while the CPU is in-between 2 instructions (e.g: inside the callback of an cpuExec or startFrame event), the savestate will be loaded immediately.\ngetSavestateData Syntax\nemu.getSavestateData(slotNumber) Parameters\nslotNumber - Integer The slot number to get the savestate data from (must be a slot number that was used in a preceding saveSavestateAsync call)\nReturn value\nString A binary string containing the savestate\nDescription\nReturns the savestate stored in the specified savestate slot.\nclearSavestateData Syntax\nemu.clearSavestateData(slotNumber) Parameters\nslotNumber - Integer The slot number to get the savestate data from (must be a slot number that was used in a preceding saveSavestateAsync call)\nReturn value\nNone\nDescription\nClears the specified savestate slot (any savestate data in that slot will be removed from memory).\nCheats addCheat Syntax\nemu.addCheat(cheatCode) Parameters\ncheatCode - String A game genie format cheat code.\nReturn value\nNone\nDescription\nActivates a game genie cheat code (6 or 8 characters).\nNote: cheat codes added via this function are not permanent and not visible in the UI.\nclearCheats Syntax\nemu.clearCheats() Return value\nNone\nDescription\nRemoves all active cheat codes (has no impact on cheat codes saved within the UI)\nAccess Counters getAccessCounters Syntax\nemu.getAccessCounters(counterMemType, counterOpType) Parameters\ncounterMemType - Enum A value from the emu.counterMemType enum\ncounterOpType - Enum A value from the emu.counterOpType enum\nReturn value\nArray 32-bit integers\nDescription\nReturns an array of access counters for the specified memory and operation types.\nresetAccessCounters Syntax\nemu.resetAccessCounters() Return value\nNone\nDescription\nResets all access counters.\nMisc getLogWindowLog Syntax\nemu.getLogWindowLog() Return value\nString A string containing the log shown in the log window\nDescription\nReturns the same text as what is shown in the emulator\u0026rsquo;s Log Window.\ngetRomInfo Syntax\nemu.getRomInfo() Return value\nTable Information about the current ROM with the following structure:\nname: string, Filename of the current ROM path: string, Full path to the current ROM (including parent compressed archive when needed) fileCrc32Hash: int, The CRC32 value for the whole ROM file fileSha1Hash: string, The SHA1 hash for the whole ROM file prgChrCrc32Hash: int,\tThe CRC32 value for the file, excluding its 16-byte header prgChrMd5Hash: string, The MD5 hash for the file, excluding its 16-byte header format: int,\tValue that represents the ROM format: 1 = iNES, 2 = UNIF, 3 = FDS, 4 = NSF isChrRam: bool true when the game uses CHR RAM, false otherwise Description\nReturns information about the ROM file that is currently running.\ngetScriptDataFolder Syntax\nemu.getScriptDataFolder() Return value\nString The script\u0026rsquo;s data folder\nDescription\nThis function returns the path to a unique folder (based on the script\u0026rsquo;s filename) where the script should store its data (if any data needs to be saved).\nThe data will be saved in subfolders inside the LuaScriptData folder in Mesen\u0026rsquo;s home folder.\ntakeScreenshot Syntax\nemu.takeScreenshot() Return value\nString A binary string containing a PNG image.\nDescription\nTakes a screenshot and returns a PNG file as a string.\nThe screenshot is not saved to the disk.\n"},{"uri":"/apireference/enums.html","title":"Enums","tags":[],"description":"","content":"eventType Syntax\nemu.eventType.[value] Values\nreset = 0, Triggered when a soft reset occurs nmi = 1, Triggered when an nmi occurs irq = 2, Triggered when an irq occurs startFrame = 3, Triggered at the start of a frame (cycle 0, scanline -1) endFrame = 4, Triggered at the end of a frame (cycle 0, scanline 240) codeBreak = 5, Triggered when code execution breaks (e.g due to a breakpoint, etc.) stateLoaded = 6, Triggered when a user manually loads a savestate stateSaved = 7, Triggered when a user manually saves a savestate inputPolled = 8, Triggered when the emulation core polls the state of the input devices for the next frame spriteZeroHit = 9, Triggered when the PPU sets the sprite zero hit flag scriptEnded = 10 Triggered when the current Lua script ends (script window closed, execution stopped, etc.) Description\nUsed by addEventCallback / removeEventCallback calls.\nexecuteCountType Syntax\nemu.executeCountType.[value] Values\ncpuCycles = 0, Count the number of CPU cycles ppuCycles = 1, Count the number of PPU cycles cpuInstructions = 2 Count the number of CPU instructions Description\nUsed by execute calls.\nmemCallbackType Syntax\nemu.memCallbackType.[value] Values\ncpuRead = 0, Triggered when a read instruction is executed cpuWrite = 1, Triggered when a write instruction is executed cpuExec = 2, Triggered when any memory read occurs due to the CPU\u0026#39;s code execution ppuRead = 3, Triggered when the PPU reads from its memory bus ppuWrite = 4 Triggered when the PPU writes to its memory bus Description\nUsed by addMemoryCallback / removeMemoryCallback calls.\nmemType Syntax\nemu.memType.[value] Values\ncpu = 0, CPU memory - $0000 to $FFFF Warning: Reading or writing to this memory type may cause side-effects! ppu = 1, PPU memory - $0000 to $3FFF Warning: Reading or writing to this memory type may cause side-effects! palette = 2, Palette memory - $00 to $3F oam = 3, OAM memory - $00 to $FF secondaryOam = 4, Secondary OAM memory - $00 to $1F prgRom = 5, PRG ROM - Range varies by game chrRom = 6, CHR ROM - Range varies by game chrRam = 7, CHR RAM - Range varies by game workRam = 8, Work RAM - Range varies by game saveRam = 9, Save RAM - Range varies by game cpuDebug = 256, CPU memory - $0000 to $FFFF Same as memType.cpu but does NOT cause any side-effects. ppuDebug = 257 PPU memory - $0000 to $3FFF Same as memType.ppu but does NOT cause any side-effects. Description\nUsed by read / write calls.\ncounterMemType Syntax\nemu.counterMemType.[value] Values\nnesRam = 0, prgRom = 1, workRam = 2, saveRam = 3 Description\nUsed by getAccessCounters calls.\ncounterOpType Syntax\nemu.counterOpType.[value] Values\nread = 0, write = 1, exec = 2 Description\nUsed by getAccessCounters calls.\n"},{"uri":"/apireference.html","title":"Lua API reference","tags":[],"description":"","content":"This section documents the Mesen-specific Lua API that is available in scripts via the script window.\nChangelog Lua scripting is still a relatively recent feature and the API is not quite stable yet. To get a list of the major changes between different versions of Mesen, take a look at the Changelog.\nAPI References Callbacks Drawing Emulation Input Logging Memory Access Miscellaneous Enums Additional features Test Runner Mode Mesen can be started in a headless test runner mode that can be used to implement automated testing by using Lua scripts.\nTo start Mesen in headless mode, use the --testrunner command line option and specify both a game and a Lua script to run:\nMesen.exe --testrunner MyGame.nes MyTest.lua This will start Mesen (headless), load the game and the Lua script and start executing the game at maximum speed until the Lua script calls the emu.stop()function. The emu.stop()function can specify an exit code, which will be returned by the Mesen process, which can be used to validate whether the test passed or failed.\nLuaSocket The Lua implementation found in Mesen has a version of LuaSocket (GitHub) built into it. The socket and mime packages are available and can be accessed by using local socket = require(\u0026quot;socket.core\u0026quot;) and local mime = require(\u0026quot;mime.core\u0026quot;), respectively.\nSee LuaSocket\u0026rsquo;s documentation for more information on how to use this library.\nHere is a tiny TCP socket sample that connects to google.com via HTTP and downloads the page:\nlocal socket = require(\u0026quot;socket.core\u0026quot;) local tcp = sock.tcp() --Set a 2-second timeout for all request, otherwise the process could hang! tcp:settimeout(2) local res = tcp:connect(\u0026quot;www.google.com\u0026quot;, 80) tcp:send(\u0026quot;GET / HTTP/1.1\\r\\nHost: www.google.com\\r\\nConnection: close\\r\\n\\r\\n\u0026quot;) local text repeat text = tcp:receive() emu.log(text) until text == nil "},{"uri":"/categories.html","title":"Categories","tags":[],"description":"","content":""},{"uri":"/tags.html","title":"Tags","tags":[],"description":"","content":""}] |