code:
//=============================================================================
// Yanfly Engine Plugins - Message Core Extension - Backlog
// YEP_X_MessageBacklog.js
// Translate to Japanese : munokura.tk
//=============================================================================

var Imported = Imported || {};
Imported.YEP_X_MessageBacklog = true;

var Yanfly = Yanfly || {};
Yanfly.MsgBacklog = Yanfly.MsgBacklog || {};
Yanfly.MsgBacklog.version = 1.01;

//=============================================================================
 /*:
 * @plugindesc v1.01 (Requires YEP_MessageCore.js) Add a message backlog
 * function to your game's message system!
 * @author Yanfly Engine Plugins
 *
 * @help
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * This plugin requires the following plugins:
 * - YEP_MessageCore
 *
 * * Note: If you have any Extended Message Pack plugins from the YEP library,
 * place this plugin under those entries in the plugin list.
 *
 * It's not uncommon for RPG's to have a message backlog, an in-game tool for
 * the player to review any and all dialogue he/she has encountered previously.
 * This tool can be helpful in case a player would accidentally skip some
 * dialogue and/or would like to revisit what kind of messages were made before
 * making a decision during an important moment.
 *
 * This plugin creates a message backlog system for your game's message system.
 * Upon pressing 'Shift' (or any other button you desire) during a message, the
 * player can open up a Backlog window to review over the last 20 encountered
 * messages (number of stored messages can be modified within the parameters).
 * These saved messages can also include any choices from the choice lists they
 * have selected, any numbers they may have inputted, or items they selected
 * from special events.
 *
 * Now, your players can go forward, knowing full well they have little to
 * worry about in case they've missed any messages.
 *
 * ============================================================================
 * Disabled Text Codes
 * ============================================================================
 *
 * Due to the nature of some text codes, some of them are disabled for the
 * message log. Most of the default RPG Maker MV text codes will work, but some
 * custom ones added through the Message Core or Extension Packs are disabled
 * for various reasons. Here is a list of those disabled message codes:
 *
 *    RPG Maker MV Default:
 *    \{          Changes to font sizes cause errors in the backlog.
 *    \}          Changes to font sizes cause errors in the backlog.
 *
 *    Message Core:
 *    \AF[x]      Face graphics aren't displayed in the backlog.
 *    \PF[x]      Face graphics aren't displayed in the backlog.
 *    \FS[X]      Changes to font sizes cause errors in the backlog.
 *
 *    \PY[X]      While this works, it is known to cause some problems.
 *
 *    Extended Message Pack 1:
 *    \LSON       Letter sounds are disabled for the backlog.
 *    \LSOFF      Letter sounds are disabled for the backlog.
 *    \LSR        Letter sounds are disabled for the backlog.
 *    \FACEINDEX  Face graphics aren't displayed in the backlog.
 *    \MSGPOSX    Backlog does not change message window size.
 *    \MSGPOSY    Backlog does not change message window size.
 *    \MSGEVENT   Backlog does not change message window size.
 *    \MSGACTOR   Backlog does not change message window size.
 *    \MSGPARTY   Backlog does not change message window size.
 *    \MSGENEMY   Backlog does not change message window size.
 *    \AUTOEVENT  Backlog does not change message window size.
 *    \AUTOACTOR  Backlog does not change message window size.
 *    \AUTOPARTY  Backlog does not change message window size.
 *    \AUTOENEMY  Backlog does not change message window size.
 *    \MSGROWS    Backlog does not change message window size.
 *    \MSGWIDTH   Backlog does not change message window size.
 *    \AUTO       Backlog does not change message window size.
 *    \MSGRESET   Backlog does not change message window size.
 *
 *    Extended Message Pack 2:
 *    - Quantity, Actor, and Enemy text codes will be converted before added.
 *    This is so the data made will be localized instead of current.
 *
 * ============================================================================
 * Plugin Commands
 * ============================================================================
 *
 * The following plugin commands can be used to alter various settings
 * regarding the Message Backlog.
 *
 * Plugin Command:
 *
 *   EnableMessageBacklog
 *   DisableMessageBacklog
 *   - This enables/disables the message backlog from being playeraccessed.
 *
 *   EnableMessageLogging
 *   DisableMessageLogging
 *   - If enabled, new messages will be recorded to the backlog.
 *   If disabled, they won't be recorded.
 *
 *   OpenMessageBacklog
 *   - This will forcefully open the message backlog if done on the map scene.
 *   (Highly recommended to be used with Button Common Events)
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.01:
 * - Message Backlog now removes more text codes regarding Letter Sounds.
 *
 * Version 1.00:
 * - Finished Plugin!
 *
 * ============================================================================
 * End of Helpfile
 * ============================================================================
 *
 * @param ---Backlog Key---
 * @default
 *
 * @param LogKeyButton
 * @text Backlog Key Button
 * @parent ---Backlog Key---
 * @type combo
 * @option tab
 * @option shift
 * @option control
 * @option pageup
 * @option pagedown
 * @desc When pressed during a message, this will open up
 * the Backlog window.
 * @default shift
 *
 * @param EnableLogKey
 * @text Enable Backlog Key
 * @parent ---Backlog Key---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Enable Backlog button for your messages by default?
 * NO - false     YES - true
 * @default true
 *
 * @param ---Settings---
 * @default
 *
 * @param DefaultLogging
 * @text Default Logging
 * @parent ---Settings---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Log all messages by default?
 * NO - false     YES - true
 * @default true
 *
 * @param LogSpecialInput
 * @text Log Special Inputs
 * @parent ---Settings---
 * @type boolean
 * @on YES
 * @off NO
 * @desc Log the special inputs made by the player?
 * NO - false     YES - true
 * @default true
 *
 * @param SpecialInputFmt
 * @text Special Input Format
 * @parent LogSpecialInput
 * @desc Format used to display special input text in backlog.
 * %1 - The text used in the selected choice.
 * @default »%1
 *
 * @param MaximumEntries
 * @text Maximum Entries
 * @parent ---Settings---
 * @type number
 * @min 1
 * @desc This is the maximum number of backlog entries.
 * If more than max are added, oldest entry will be removed.
 * @default 20
 *
 * @param ScrollBarEnabled
 * @text Scroll Bar Enabled
 * @parent ---Settings---
 * @type boolean
 * @on SHOW
 * @off HIDE
 * @desc Show a scroll bar for the message log?
 * HIDE - false     SHOW - true
 * @default true
 *
 * @param ScrollBarColor
 * @text Scroll Bar Color
 * @parent ScrollBarEnabled
 * @type number
 * @min 0
 * @max 31
 * @desc This is the text color used for the scroll bar.
 * @default 0
 *
 * @param ScrollBarSpriteCode
 * @text Sprite Code
 * @parent ScrollBarEnabled
 * @type note
 * @desc This is the code used for the scroll bar's sprite.
 * Edit this if you wish to customize it for your game.
 * @default "// Establish basic measurements\nvar padding = backlogWindow.standardPadding();\nvar width = padding / 2;\nvar height = Graphics.boxHeight;\n\n// Calculate number of visible rows\nvar visibleRows = backlogWindow.height - padding * 2;\nvisibleRows = Math.floor(visibleRows / backlogWindow.lineHeight());\nif (visibleRows < backlogWindow.maxItems()) {\n  height *= visibleRows / Math.max(1, backlogWindow.maxItems());\n}\n\n// Calculate the size of a basic scrolling increment\nvar max = Math.floor(Math.max(1, backlogWindow.maxItems()) / backlogWindow.maxCols()) - 1;\nthis._increment = Graphics.boxHeight / Math.max(1, max);\n\n// Generate the bitmap\nthis.bitmap = new Bitmap(width, height);\nthis.bitmap.fillAll(backlogWindow.textColor(scrollBarColor));"
 *
 * @param ScrollSpeed
 * @text Scroll Speed
 * @parent ---Settings---
 * @type number
 * @min 0
 * @desc This is the scroll speed used for backlog.
 * Lower numbers are faster. Higher numbers are slower.
 * @default 4
 *
 * @param ScrollWrap
 * @text Scroll Wrap
 * @parent ---Settings---
 * @type boolean
 * @on YES
 * @off NO
 * @desc If player is at the bottom log entry, hitting down
 * would wrap the player back to the top. Enable this?
 * @default true
 *
 * @param ---Visual---
 * @default
 *
 * @param BackgroundType
 * @text Background Type
 * @parent ---Visual---
 * @type select
 * @option Window
 * @value 0
 * @option Dimmed
 * @value 1
 * @option Picture
 * @value 2
 * @option Transparent
 * @value 3
 * @desc What kind of background type do you wish to use
 * for the message backlog window?
 * @default 1
 *
 * @param BackOpacity
 * @text Back Opacity
 * @parent ---Visual---
 * @type number
 * @min 0
 * @max 255
 * @desc If you are using a Window background type,
 * adjust this number to set the window's back opacity.
 * @default 192
 *
 * @param DimColor1
 * @text Dim Color 1
 * @parent ---Visual---
 * @desc If you are using a Dimmed background type,
 * adjust the first color here. Default: rgba(0, 0, 0, 0.6)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param DimColor2
 * @text Dim Color 2
 * @parent ---Visual---
 * @desc If you are using a Dimmed background type,
 * adjust the first color here. Default: rgba(0, 0, 0, 0)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param Picture
 * @parent ---Visual---
 * @type file
 * @dir img/pictures/
 * @require 1
 * @desc If you are using a Picture background type,
 * select a picture to use for your background.
 * @default
 *
 * @param PictureOpacity
 * @text Picture Opacity
 * @parent ---Visual---
 * @type number
 * @min 0
 * @max 255
 * @desc If you are using a Picture background type,
 * adjust this number to set the picture's opacity.
 * @default 255
 *
 * @param PictureStretch
 * @text Picture Stretch
 * @parent ---Visual---
 * @type boolean
 * @on Stretch
 * @off Don't Stretch
 * @desc If the picture used for the background is smaller than
 * the screen, stretch it to fit the screen?
 * @default true
 *
 */
 /*:ja
 * @plugindesc v1.01 (要YEP_MessageCore.js) メッセージシステムにメッセージバックログ機能を追加します。
 * @author Yanfly Engine Plugins
 *
 * @help
 * 翻訳:ムノクラ
 * https://munokura.tk/
 * https://twitter.com/munokura/
 *
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * このプラグインはには YEP_MessageCore プラグインが必要です。
 *
 * 注:Extended Message Packプラグインがある場合、
 * このプラグインをプラグインリストのそれらのエントリの下に配置します。
 *
 * RPGがメッセージバックログを持つことは珍しいことではありません。
 * プレイヤーが以前に遭遇したすべての対話を確認するためのゲーム内ツールです。
 * このツールは、プレイヤーが誤って会話をスキップしたり、
 * 重要な瞬間に決定を下す前に過去のメッセージを再確認したい場合に役立ちます。
 *
 * このプラグインはあなたのゲームのメッセージシステム用の
 * メッセージバックログシステムを作成します。
 * ※「メッセージ中に」'Shift'（またはあなたが望む他のボタン）を押すと、
 * プレイヤーはバックログウィンドウを開いて
 * 直近20個のメッセージを見直すことができます
 * （保存されたメッセージの数はパラメータ内で変更できます）。
 * これらの保存されたメッセージには、選択リストからの選択、
 * 入力した番号、または特別なイベントから選択した項目を含めることもできます。
 *
 * プレイヤーはメッセージを見逃してしまったとしても、
 * 心配する必要がほとんどないことを十分に知っているので、
 * 先に進むことができます。
 *
 * ============================================================================
 * Disabled Text Codes
 * ============================================================================
 *
 * 一部のテキストコードの性質上、
 * それらの一部はメッセージログに対して無効になっています。
 * RPGツクールMVのデフォルトのテキストコードの大部分は機能しますが、
 * Message Core または Extension Pack を通じて追加されたカスタムコードは
 * さまざまな理由で無効になっています。
 * これらの無効にされたメッセージコードのリストは以下です。
 *
 *    RPG Maker MV Default:
 *    \{          フォントサイズを変更すると、バックログにエラーが発生します。
 *    \}          フォントサイズを変更すると、バックログにエラーが発生します。
 *
 *    Message Core:
 *    \AF[x]      バックログには顔グラフィックは表示されません。
 *    \PF[x]      バックログには顔グラフィックは表示されません。
 *    \FS[X]      フォントサイズを変更すると、バックログにエラーが発生します。
 *
 *    \PY[X]      一応動作しますが、
 *                いくつかの問題を引き起こすことが分かっています。
 *
 *    Extended Message Pack 1:
 *    \LSON       バックログのレターサウンドは無効になっています。
 *    \LSOFF      バックログのレターサウンドは無効になっています。
 *    \LSR        バックログのレターサウンドは無効になっています。
 *    \FACEINDEX  バックログには顔グラフィックは表示されません。
 *    \MSGPOSX    バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGPOSY    バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGEVENT   バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGACTOR   バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGPARTY   バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGENEMY   バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOEVENT  バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOACTOR  バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOPARTY  バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTOENEMY  バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGROWS    バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGWIDTH   バックログはメッセージウィンドウサイズを変更しません。
 *    \AUTO       バックログはメッセージウィンドウサイズを変更しません。
 *    \MSGRESET   バックログはメッセージウィンドウサイズを変更しません。
 *
 *    Extended Message Pack 2:
 *    - 数、アクター、敵のテキストコードは追加前に変換されます。
 *    作成されたデータが最新のデータではなくローカライズされるためです。
 *
 * ============================================================================
 * Plugin Commands
 * ============================================================================
 *
 * 以下のプラグインコマンドを使用して、
 * メッセージバックログに関するさまざまな設定を変更できます。
 *
 * プラグインコマンド:
 *
 *   EnableMessageBacklog
 *   DisableMessageBacklog
 *   - メッセージバックログが再生されないようにします。
 *
 *   EnableMessageLogging
 *   DisableMessageLogging
 *   - 有効にすると、新しいメッセージがバックログに記録されます。
 *   無効にした場合、それらは記録されません。
 *
 *   OpenMessageBacklog
 *   - マップシーンでこれを行うと、メッセージバックログが強制的に開かれます。
 *   （ボタンコモンイベントとの併用を強く推奨）
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.01:
 * - Message Backlog now removes more text codes regarding Letter Sounds.
 *
 * Version 1.00:
 * - Finished Plugin!
 *
 * ============================================================================
 * End of Helpfile
 * ============================================================================
 *
 * @param ---バックログキー---
 * @default
 *
 * @param LogKeyButton
 * @text Backlog Key Button
 * @parent ---バックログキー---
 * @type combo
 * @option tab
 * @option shift
 * @option control
 * @option pageup
 * @option pagedown
 * @desc メッセージ中に押すと、バックログウィンドウが開きます。
 * @default shift
 *
 * @param EnableLogKey
 * @text Enable Backlog Key
 * @parent ---バックログキー---
 * @type boolean
 * @on 有効
 * @off 無効
 * @desc メッセージのバックログボタンのデフォルト設定
 * 無効 - false     有効 - true
 * @default true
 *
 * @param ---設定---
 * @default
 *
 * @param DefaultLogging
 * @text Default Logging
 * @parent ---設定---
 * @type boolean
 * @on すべて記録
 * @off 記録しない
 * @desc メッセージのデフォルト記録設定
 * 記録しない - false     すべて記録 - true
 * @default true
 *
 * @param LogSpecialInput
 * @text Log Special Inputs
 * @parent ---設定---
 * @type boolean
 * @on YES
 * @off NO
 * @desc プレイヤーによる特別な入力を記録しますか？
 * NO - false     YES - true
 * @default true
 *
 * @param SpecialInputFmt
 * @text Special Input Format
 * @parent LogSpecialInput
 * @desc バックログに特別な入力テキストを表示するために使用される形式。
 * %1 - 選択肢で選択したテキスト
 * @default »%1
 *
 * @param MaximumEntries
 * @text Maximum Entries
 * @parent ---設定---
 * @type number
 * @min 1
 * @desc バックログの記録最大数。最大数を超えて追加された場合、最も古いエントリが削除されます。
 * @default 20
 *
 * @param ScrollBarEnabled
 * @text Scroll Bar Enabled
 * @parent ---設定---
 * @type boolean
 * @on 表示
 * @off 非表示
 * @desc メッセージログのスクロールバー表示設定
 * 非表示 - false     表示 - true
 * @default true
 *
 * @param ScrollBarColor
 * @text Scroll Bar Color
 * @parent ScrollBarEnabled
 * @type number
 * @min 0
 * @max 31
 * @desc スクロールバーのテキスト色
 * @default 0
 *
 * @param ScrollBarSpriteCode
 * @text Sprite Code
 * @parent ScrollBarEnabled
 * @type note
 * @desc これはスクロールバーのスプライトに使用されるコードです。
 * カスタマイズしたい場合、これを編集してください。
 * @default "// Establish basic measurements\nvar padding = backlogWindow.standardPadding();\nvar width = padding / 2;\nvar height = Graphics.boxHeight;\n\n// Calculate number of visible rows\nvar visibleRows = backlogWindow.height - padding * 2;\nvisibleRows = Math.floor(visibleRows / backlogWindow.lineHeight());\nif (visibleRows < backlogWindow.maxItems()) {\n  height *= visibleRows / Math.max(1, backlogWindow.maxItems());\n}\n\n// Calculate the size of a basic scrolling increment\nvar max = Math.floor(Math.max(1, backlogWindow.maxItems()) / backlogWindow.maxCols()) - 1;\nthis._increment = Graphics.boxHeight / Math.max(1, max);\n\n// Generate the bitmap\nthis.bitmap = new Bitmap(width, height);\nthis.bitmap.fillAll(backlogWindow.textColor(scrollBarColor));"
 *
 * @param ScrollSpeed
 * @text Scroll Speed
 * @parent ---設定---
 * @type number
 * @min 0
 * @desc バックログに使用されるスクロール速度。 数値が小さいと速く大きいと遅くなります。
 * @default 4
 *
 * @param ScrollWrap
 * @text Scroll Wrap
 * @parent ---設定---
 * @type boolean
 * @on 有効
 * @off 無効
 * @desc 一番下のログエントリを選択している時、下を押すとエントリの一番上に戻る設定
 * @default true
 *
 * @param ---ビジュアル---
 * @default
 *
 * @param BackgroundType
 * @text Background Type
 * @parent ---ビジュアル---
 * @type select
 * @option ウィンドウ
 * @value 0
 * @option ぼかし
 * @value 1
 * @option 画像
 * @value 2
 * @option 透明
 * @value 3
 * @desc バックログウィンドウの背景
 * @default 1
 *
 * @param BackOpacity
 * @text Back Opacity
 * @parent ---ビジュアル---
 * @type number
 * @min 0
 * @max 255
 * @desc ウィンドウの背面の不透明度
 * @default 192
 *
 * @param DimColor1
 * @text Dim Color 1
 * @parent ---ビジュアル---
 * @desc ぼかし背景の色1 Default: rgba(0, 0, 0, 0.6)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param DimColor2
 * @text Dim Color 2
 * @parent ---ビジュアル---
 * @desc ぼかし背景の色2 Default: rgba(0, 0, 0, 0)
 * @default rgba(0, 0, 0, 0.8)
 *
 * @param Picture
 * @parent ---ビジュアル---
 * @type file
 * @dir img/pictures/
 * @require 1
 * @desc 画像背景の使用画像
 * @default
 *
 * @param PictureOpacity
 * @text Picture Opacity
 * @parent ---ビジュアル---
 * @type number
 * @min 0
 * @max 255
 * @desc 画像背景の不透明度
 * @default 255
 *
 * @param PictureStretch
 * @text Picture Stretch
 * @parent ---ビジュアル---
 * @type boolean
 * @on 拡大する
 * @off 拡大しない
 * @desc 背景画像が画面より小さい場合、画面に合わせて拡大
 * @default true
 *
 */
//=============================================================================

if (Imported.YEP_MessageCore) {

//=============================================================================
// Parameter Variables
//=============================================================================

Yanfly.Parameters = PluginManager.parameters('YEP_X_MessageBacklog');
Yanfly.Param = Yanfly.Param || {};

Yanfly.Param.MsgBacklogKeyButton = String(Yanfly.Parameters['LogKeyButton']);
Yanfly.Param.MsgBacklogEnableKey = String(Yanfly.Parameters['EnableLogKey']);
Yanfly.Param.MsgBacklogEnableKey = eval(Yanfly.Param.MsgBacklogEnableKey);

Yanfly.Param.MsgBacklogDefaultLog = String(Yanfly.Parameters['DefaultLogging']);
Yanfly.Param.MsgBacklogDefaultLog = eval(Yanfly.Param.MsgBacklogDefaultLog);
Yanfly.Param.MsgBacklogSpcInput = String(Yanfly.Parameters['LogSpecialInput']);
Yanfly.Param.MsgBacklogSpcInput = eval(Yanfly.Param.MsgBacklogSpcInput);
Yanfly.Param.MsgBacklogSpcFmt = String(Yanfly.Parameters['SpecialInputFmt']);
Yanfly.Param.MsgBacklogMaxEntries = Number(Yanfly.Parameters['MaximumEntries']);
Yanfly.Param.MsgBacklogScrBarEn = String(Yanfly.Parameters['ScrollBarEnabled']);
Yanfly.Param.MsgBacklogScrBarEn = eval(Yanfly.Param.MsgBacklogScrBarEn);
Yanfly.Param.MsgBacklogScrBarCol = Number(Yanfly.Parameters['ScrollBarColor']);
Yanfly.Param.MsgBacklogScrBarSpriteCode =
  JSON.parse(Yanfly.Parameters['ScrollBarSpriteCode']);
Yanfly.Param.MsgBacklogScrollSpd = Number(Yanfly.Parameters['ScrollSpeed']);
Yanfly.Param.MsgBacklogScrollWrap = String(Yanfly.Parameters['ScrollWrap']);
Yanfly.Param.MsgBacklogScrollWrap = eval(Yanfly.Param.MsgBacklogScrollWrap);

Yanfly.Param.MsgBacklogBgType = Number(Yanfly.Parameters['BackgroundType']);
Yanfly.Param.MsgBacklogBackOpacity = Number(Yanfly.Parameters['BackOpacity']);
Yanfly.Param.MsgBacklogDimColor1 = String(Yanfly.Parameters['DimColor1']);
Yanfly.Param.MsgBacklogDimColor2 = String(Yanfly.Parameters['DimColor2']);
Yanfly.Param.MsgBacklogPicture = String(Yanfly.Parameters['Picture']);
Yanfly.Param.MsgBacklogPicOpacity = Number(Yanfly.Parameters['PictureOpacity']);
Yanfly.Param.MsgBacklogPicStretch = String(Yanfly.Parameters['PictureStretch']);
Yanfly.Param.MsgBacklogPicStretch = eval(Yanfly.Param.MsgBacklogPicStretch);

//=============================================================================
// Game_Temp
//=============================================================================

Game_Temp.prototype.isMessageBacklogOpened = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    var win = SceneManager._scene._messageWindow;
    if (win._backlogWindow && win._backlogWindow.isOpenAndActive()) {
      return true;
    }
  }
  return false;
};

//=============================================================================
// Game_System
//=============================================================================

Yanfly.MsgBacklog.Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
  Yanfly.MsgBacklog.Game_System_initialize.call(this);
  this.initMessageBacklog();
};

Game_System.prototype.initMessageBacklog = function() {
  this._messageBacklog = [];
  this._messageBacklogKeyEnable = Yanfly.Param.MsgBacklogEnableKey;
  this._messageBacklogLoggingEnable = Yanfly.Param.MsgBacklogDefaultLog;
};

Game_System.prototype.addMessageBacklog = function(text) {
  if (!this.isMessageBacklogLoggingEnabled()) return;
  text = this.convertMessageBacklogText(text);
  this._messageBacklog.push(text);
  while (this._messageBacklog.length > Yanfly.Param.MsgBacklogMaxEntries) {
    this._messageBacklog.shift();
  }
};

Game_System.prototype.convertMessageBacklogText = function(text) {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    var win = SceneManager._scene._messageWindow._backlogWindow;
    if (win) text = win.convertMessageText(text);
  }
  return text;
};

Game_System.prototype.getMessageBacklog = function() {
  if (this._messageBacklog === undefined) this.initMessageBacklog();
  return this._messageBacklog;
};

Game_System.prototype.isMessageBacklogKeyEnabled = function() {
  if (this._messageBacklogKeyEnable === undefined) this.initMessageBacklog();
  return this._messageBacklogKeyEnable;
};

Game_System.prototype.setMessageBacklogKeyEnable = function(value) {
  if (this._messageBacklogKeyEnable === undefined) this.initMessageBacklog();
  this._messageBacklogKeyEnable = value;
};

Game_System.prototype.isMessageBacklogLoggingEnabled = function() {
  if (this._messageBacklogLoggingEnable === undefined) {
    this.initMessageBacklog();
  }
  return this._messageBacklogLoggingEnable;
};

Game_System.prototype.setMessageBacklogLoggingEnable = function(value) {
  if (this._messageBacklogLoggingEnable === undefined) {
    this.initMessageBacklog();
  }
  this._messageBacklogLoggingEnable = value;
};

//=============================================================================
// Game_Player
//=============================================================================

Yanfly.MsgBacklog.Game_Player_canMove = Game_Player.prototype.canMove;
Game_Player.prototype.canMove = function() {
  if ($gameTemp.isMessageBacklogOpened()) return false;
  return Yanfly.MsgBacklog.Game_Player_canMove.call(this);
};

//=============================================================================
// Game_Event
//=============================================================================

Yanfly.MsgBacklog.Game_Event_updateSelfMovement =
  Game_Event.prototype.updateSelfMovement;
Game_Event.prototype.updateSelfMovement = function() {
  if ($gameTemp.isMessageBacklogOpened()) return;
  Yanfly.MsgBacklog.Game_Event_updateSelfMovement.call(this);
};

//=============================================================================
// Game_Interpreter
//=============================================================================

Yanfly.MsgBacklog.Game_Interpreter_pluginCommand =
  Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
  Yanfly.MsgBacklog.Game_Interpreter_pluginCommand.call(this, command, args);
  // Plugin Commands
  if (command === 'EnableMessageBacklog') {
    $gameSystem.setMessageBacklogKeyEnable(true);

  } else if (command === 'DisableMessageBacklog') {
    $gameSystem.setMessageBacklogKeyEnable(false);

  } else if (command === 'EnableMessageLogging') {
    $gameSystem.setMessageBacklogLoggingEnable(true);

  } else if (command === 'DisableMessageLogging') {
    $gameSystem.setMessageBacklogLoggingEnable(false);

  } else if (command === 'OpenMessageBacklog') {
    if (SceneManager._scene instanceof Scene_Map) {
      var win = SceneManager._scene._messageWindow;
      if (win) win.openBacklogWindow();
    }

  // End
  }
};

//=============================================================================
// Scene_Map
//=============================================================================

Yanfly.MsgBacklog.Scene_Map_isMenuEnabled = Scene_Map.prototype.isMenuEnabled;
Scene_Map.prototype.isMenuEnabled = function() {
  if ($gameTemp.isMessageBacklogOpened()) return false;
  return Yanfly.MsgBacklog.Scene_Map_isMenuEnabled.call(this);
};

//=============================================================================
// Window_Message
//=============================================================================

Yanfly.MsgBacklog.Window_Message_createSubWindows =
  Window_Message.prototype.createSubWindows;
Window_Message.prototype.createSubWindows = function() {
  Yanfly.MsgBacklog.Window_Message_createSubWindows.call(this);
  this.createMessageBacklogWindow();
};

Window_Message.prototype.createMessageBacklogWindow = function() {
  this._backlogWindow = new Window_MessageBacklog();
  SceneManager._scene.addChild(this._backlogWindow);
};

Yanfly.MsgBacklog.Window_Message_isAnySubWindowActive =
  Window_Message.prototype.isAnySubWindowActive;
Window_Message.prototype.isAnySubWindowActive = function() {
  if (this._backlogWindow.active) return true;
  return Yanfly.MsgBacklog.Window_Message_isAnySubWindowActive.call(this);
};

Yanfly.MsgBacklog.Window_Message_startMessage =
  Window_Message.prototype.startMessage;
Window_Message.prototype.startMessage = function() {
  Yanfly.MsgBacklog.Window_Message_startMessage.call(this);
  $gameSystem.addMessageBacklog($gameMessage.allText());
};

Yanfly.MsgBacklog.Window_Message_updateInput =
  Window_Message.prototype.updateInput;
Window_Message.prototype.updateInput = function() {
  if (this.isAnySubWindowActive()) return true;
  this.updateBacklogInput();
  var value = Yanfly.MsgBacklog.Window_Message_updateInput.call(this);
  return value;
};

Window_Message.prototype.updateBacklogInput = function() {
  if (!this.pause) return;
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  // キーが押されたら待機フラグを立てる
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = true;
  }
  if (this._waitForBacklogRelease && (Input.isPressed('ok') || Input.isPressed('cancel') || Input.isPressed('up') || Input.isPressed('down') || Input.isPressed('right') || Input.isPressed('left') || Input.isPressed('shift') || Input.isPressed('menu') || Input.isPressed('pagedown') || Input.isPressed('control') || Input.isPressed('escape') || TouchInput.isTriggered() || TouchInput.isCancelled())){
    this._waitForBacklogRelease = false;
  }
  // キーを離したらバックログを開く
  if (this._waitForBacklogRelease && !Input.isPressed(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = false;
    this.openBacklogWindow();
  }
};

Window_Message.prototype.openBacklogWindow = function() {
  this._backlogWindow.fullActivate();
};

Window_Message.prototype.setReturnWindow = function(target) {
  this._backlogWindow.setReturnWindow(target);
};

//=============================================================================
// Window_ChoiceList
//=============================================================================

Yanfly.MsgBacklog.Window_ChoiceList_processHandling =
  Window_ChoiceList.prototype.processHandling;
Window_ChoiceList.prototype.processHandling = function() {
  if (this.isOpenAndActive()) this.updateBacklogInput();
  Yanfly.MsgBacklog.Window_ChoiceList_processHandling.call(this);
};

Window_ChoiceList.prototype.updateBacklogInput = function() {
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  // キーが押されたら待機フラグを立てる
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = true;
  }
  if (this._waitForBacklogRelease && (Input.isPressed('ok') || Input.isPressed('cancel') || Input.isPressed('up') || Input.isPressed('down') || Input.isPressed('right') || Input.isPressed('left') || Input.isPressed('shift') || Input.isPressed('menu') || Input.isPressed('pagedown') || Input.isPressed('control') || Input.isPressed('escape') || TouchInput.isTriggered() || TouchInput.isCancelled())){
    this._waitForBacklogRelease = false;
  }

  // キーを離したらバックログを開く
  if (this._waitForBacklogRelease && !Input.isPressed(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = false;
    this.openBacklogWindow();
  }
};

Window_ChoiceList.prototype.openBacklogWindow = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    SceneManager._scene._messageWindow.setReturnWindow(this);
    SceneManager._scene._messageWindow.openBacklogWindow();
  }
};

Yanfly.MsgBacklog.Window_ChoiceList_callOkHandler =
  Window_ChoiceList.prototype.callOkHandler;
Window_ChoiceList.prototype.callOkHandler = function() {
  this.backlogAddSelectedChoice();
  Yanfly.MsgBacklog.Window_ChoiceList_callOkHandler.call(this);
};

Window_ChoiceList.prototype.backlogAddSelectedChoice = function() {
  if (!Yanfly.Param.MsgBacklogSpcInput) return;
  var fmt = Yanfly.Param.MsgBacklogSpcFmt;
  var text = fmt.format(this.commandName(this.index()));
  $gameSystem.addMessageBacklog(text);
};

//=============================================================================
// Window_NumberInput
//=============================================================================

Yanfly.MsgBacklog.Window_NumberInput_processHandling =
  Window_NumberInput.prototype.processHandling;
Window_NumberInput.prototype.processHandling = function() {
  if (this.isOpenAndActive()) this.updateBacklogInput();
  Yanfly.MsgBacklog.Window_NumberInput_processHandling.call(this);
};

Window_NumberInput.prototype.updateBacklogInput = function() {
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  // キーが押されたら待機フラグを立てる
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = true;
  }
  if (this._waitForBacklogRelease && (Input.isPressed('ok') || Input.isPressed('cancel') || Input.isPressed('up') || Input.isPressed('down') || Input.isPressed('right') || Input.isPressed('left') || Input.isPressed('shift') || Input.isPressed('menu') || Input.isPressed('pagedown') || Input.isPressed('control') || Input.isPressed('escape') || TouchInput.isTriggered() || TouchInput.isCancelled())){
    this._waitForBacklogRelease = false;
  }
  // キーを離したらバックログを開く
  if (this._waitForBacklogRelease && !Input.isPressed(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = false;
    this.openBacklogWindow();
  }
};

Window_NumberInput.prototype.openBacklogWindow = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    SceneManager._scene._messageWindow.setReturnWindow(this);
    SceneManager._scene._messageWindow.openBacklogWindow();
  }
};

Yanfly.MsgBacklog.Window_NumberInput_processOk =
  Window_NumberInput.prototype.processOk;
Window_NumberInput.prototype.processOk = function() {
  this.backlogAddSelectedChoice();
  Yanfly.MsgBacklog.Window_NumberInput_processOk.call(this);
};

Window_NumberInput.prototype.backlogAddSelectedChoice = function() {
  if (!Yanfly.Param.MsgBacklogSpcInput) return;
  var fmt = Yanfly.Param.MsgBacklogSpcFmt;
  var text = fmt.format(Yanfly.Util.toGroup(this._number));
  $gameSystem.addMessageBacklog(text);
};

//=============================================================================
// Window_EventItem
//=============================================================================

Yanfly.MsgBacklog.Window_EventItem_processHandling =
  Window_EventItem.prototype.processHandling;
Window_EventItem.prototype.processHandling = function() {
  if (this.isOpenAndActive()) this.updateBacklogInput();
  Yanfly.MsgBacklog.Window_EventItem_processHandling.call(this);
};

Window_EventItem.prototype.updateBacklogInput = function() {
  if (!$gameSystem.isMessageBacklogKeyEnabled()) return;
  // キーが押されたら待機フラグを立てる
  if (Input.isTriggered(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = true;
  }
  if (this._waitForBacklogRelease && (Input.isPressed('ok') || Input.isPressed('cancel') || Input.isPressed('up') || Input.isPressed('down') || Input.isPressed('right') || Input.isPressed('left') || Input.isPressed('shift') || Input.isPressed('menu') || Input.isPressed('pagedown') || Input.isPressed('control') || Input.isPressed('escape') || TouchInput.isTriggered() || TouchInput.isCancelled())){
    this._waitForBacklogRelease = false;
  }
  // キーを離したらバックログを開く
  if (this._waitForBacklogRelease && !Input.isPressed(Yanfly.Param.MsgBacklogKeyButton)) {
    this._waitForBacklogRelease = false;
    this.openBacklogWindow();
  }
};

Window_EventItem.prototype.openBacklogWindow = function() {
  if (SceneManager._scene && SceneManager._scene._messageWindow) {
    SceneManager._scene._messageWindow.setReturnWindow(this);
    SceneManager._scene._messageWindow.openBacklogWindow();
  }
};

Yanfly.MsgBacklog.Window_EventItem_onOk = Window_EventItem.prototype.onOk;
Window_EventItem.prototype.onOk = function() {
  this.backlogAddSelectedChoice();
  Yanfly.MsgBacklog.Window_EventItem_onOk.call(this);
};

Window_EventItem.prototype.backlogAddSelectedChoice = function() {
  if (!Yanfly.Param.MsgBacklogSpcInput) return;
  var fmt = Yanfly.Param.MsgBacklogSpcFmt;
  var item = this.item();
  var text = fmt.format('\\i[' + item.iconIndex + ']' + item.name);
  $gameSystem.addMessageBacklog(text);
};

//=============================================================================
// Sprite_BacklogScroll
//=============================================================================

function Sprite_BacklogScroll() {
    this.initialize.apply(this, arguments);
}

Sprite_BacklogScroll.prototype = Object.create(Sprite.prototype);
Sprite_BacklogScroll.prototype.constructor = Sprite_BacklogScroll;

Sprite_BacklogScroll.prototype.initialize = function(target) {
  this._target = target;
  Sprite.prototype.initialize.call(this);
  this._target._scrollSprite = this;
  this.initMembers();
  this.createBitmap();
};

Sprite_BacklogScroll.prototype.initMembers = function() {
  this.anchor.x = 1;
  this.anchor.y = 0;
  this.x = Graphics.boxWidth;
  this.y = 0;
  this._increment = 1;
};

Sprite_BacklogScroll.prototype.createBitmap = function() {
  var scrollBarColor = Yanfly.Param.MsgBacklogScrBarCol;
  var backlogWindow = this._target;
  this._increment = 1;
  eval(Yanfly.Param.MsgBacklogScrBarSpriteCode);
};

Sprite_BacklogScroll.prototype.resize = function() {
  this.bitmap.clear();
  this.createBitmap();
};

Sprite_BacklogScroll.prototype.update = function() {
  Sprite.prototype.update.call(this);
  if (!this._target) return;
  this.updateOpacity();
  //this.updatePosition();
};

Sprite_BacklogScroll.prototype.updateOpacity = function() {
  this.opacity = this._target.isOpen() ? 255 : 0;
};

Sprite_BacklogScroll.prototype.updatePosition = function() {
  var target = this._target;
  if (!target.isOpen()) return;
  this.y = target.topRow() * this._increment;
};

//=============================================================================
// Window_MessageBacklog
//=============================================================================

function Window_MessageBacklog() {
    this.initialize.apply(this, arguments);
}

Window_MessageBacklog.prototype = Object.create(Window_Command.prototype);
Window_MessageBacklog.prototype.constructor = Window_MessageBacklog;

Window_MessageBacklog.prototype.initialize = function() {
  this._touchHold = 0;
  this._ready = false;
  Window_Command.prototype.initialize.call(this, 0, 0);
  this.createScrollSprite(this);
  this.setBackgroundType(Yanfly.Param.MsgBacklogBgType);
  this.deactivate();
  this.openness = 0;
  this._ready = true;
};

Window_MessageBacklog.prototype.createScrollSprite = function() {
  if (!Yanfly.Param.MsgBacklogScrBarEn) return;
  this._scrollSprite = new Sprite_BacklogScroll(this);
  this.addChild(this._scrollSprite);
};

Window_MessageBacklog.prototype.windowWidth = function() {
  return Graphics.boxWidth;
};

Window_MessageBacklog.prototype.windowHeight = function() {
  return Graphics.boxHeight;
};

Window_MessageBacklog.prototype.dimColor1 = function() {
  return Yanfly.Param.MsgBacklogDimColor1;
};

Window_MessageBacklog.prototype.dimColor2 = function() {
  return Yanfly.Param.MsgBacklogDimColor2;
};

Window_MessageBacklog.prototype.setBackgroundType = function(type) {
  Window_Base.prototype.setBackgroundType.call(this, type);
  if (type === 2) this.createBackgroundPicture();
};

Window_MessageBacklog.prototype.createBackgroundPicture = function() {
  var filename = Yanfly.Param.MsgBacklogPicture;
  if (filename === '') return;
  this._backgroundPicture = new Sprite();
  this._backgroundPicture.bitmap = ImageManager.loadPicture(filename, 0);
  SceneManager._scene.addChild(this._backgroundPicture);
  this._backgroundPicture.opacity = 0;
  this._backgroundPicture.anchor.x = 0.5;
  this._backgroundPicture.anchor.y = 0.5;
  this._backgroundPicture.x = Graphics.boxWidth / 2;
  this._backgroundPicture.y = Graphics.boxHeight / 2;
};

Window_MessageBacklog.prototype.setBgPictureOpacity = function(opacity) {
  this._backgroundPicture.opacity = opacity;

  this.stretchBgPicture();
};

Window_MessageBacklog.prototype.stretchBgPicture = function() {
  if (!Yanfly.Param.MsgBacklogPicStretch) return;
  if (this._backgroundPicture.width < Graphics.boxWidth) {
    var rate = Graphics.boxWidth / this._backgroundPicture.width;
    this._backgroundPicture.scale.x = rate;
  }
  if (this._backgroundPicture.height < Graphics.boxHeight) {
    var rate = Graphics.boxHeight / this._backgroundPicture.height;
    this._backgroundPicture.scale.y = rate;
  }
};

Window_MessageBacklog.prototype.standardFontFace = function() {
  return Window_Message.prototype.standardFontFace.call(this);
};

Window_MessageBacklog.prototype.standardFontSize = function() {
  return Window_Message.prototype.standardFontSize.call(this);
};

Window_MessageBacklog.prototype.standardBackOpacity = function() {
  return Yanfly.Param.MsgBacklogBackOpacity;
};

Window_MessageBacklog.prototype.makeFontBigger = function() {
};

Window_MessageBacklog.prototype.makeFontSmaller = function() {
};

Window_MessageBacklog.prototype.select = function(index) {
};

Window_MessageBacklog.prototype.moveSelect = function(index) {
  Window_Command.prototype.select.call(this, index);
  if (this._scrollSprite) this._scrollSprite.updatePosition();
};

Window_MessageBacklog.prototype.deselect = function() {
  this.moveSelect(-1);
};

const _Window_MessageBacklog_update = Window_MessageBacklog.prototype.update;
Window_MessageBacklog.prototype.update = function() {
    _Window_MessageBacklog_update.call(this);

    if (this.active && this.isOpen()) {
        if (TouchInput.wheelY > 0) {
            this.cursorDown(false);  // 下にスクロール
        } else if (TouchInput.wheelY < 0) {
            this.cursorUp(false);    // 上にスクロール
        }
        if (this._scrollSprite) {
            this._scrollSprite.updatePosition();  // バーも更新
        }
    }
};

Window_MessageBacklog.prototype.processHandling = function() {
  if (!this.isOpenAndActive()) return;

  if (Input.isTriggered('ok') || Input.isTriggered('cancel')) {
    this._waitForRelease = true; // キーリリース待機フラグをセット
  }

  if (this._waitForRelease && !(Input.isPressed('ok') || Input.isPressed('cancel'))) {
    this._waitForRelease = false; // フラグ解除
    this.processCancel();
  }
};

Window_MessageBacklog.prototype.setReturnWindow = function(target) {
  this._returnWindow = target;
  this._returnWindow.deactivate();
};

Window_MessageBacklog.prototype.fullActivate = function() {
  this.updateInputData();
  Input.clear();
  TouchInput.clear();
  this.refresh();
  this.activate();
  this.openness = 255;
  this.moveSelect(this.maxItems() - 1);
  if (this._scrollSprite) this._scrollSprite.resize();
  if (this._backgroundPicture) {
    this.setBgPictureOpacity(Yanfly.Param.MsgBacklogPicOpacity);
  }
};

Window_MessageBacklog.prototype.processOk = function() {
  SoundManager.playOk();
  this.fullDeactivate();
};

Window_MessageBacklog.prototype.isCancelEnabled = function() {
  return true;
};

Window_MessageBacklog.prototype.processCancel = function() {
  SoundManager.playCancel();
  this.fullDeactivate();
};

Window_MessageBacklog.prototype.fullDeactivate = function() {
  this.updateInputData();
  Input.clear();
  TouchInput.clear();
  this.deactivate();
  this.openness = 0;
  this.deselect();
  if (this._returnWindow) {
    this._returnWindow.activate();
    this._returnWindow = undefined;
  }
  if (this._backgroundPicture) this.setBgPictureOpacity(0)
};

Window_MessageBacklog.prototype.isCursorVisible = function() {
  return false;
};

Window_MessageBacklog.prototype.cursorDown = function(wrap) {
  var index = this.bottomRow();
  var maxItems = this.maxItems();
  var maxCols = this.maxCols();
  wrap = Yanfly.Param.MsgBacklogScrollWrap;
  if (index < maxItems - maxCols || (wrap && maxCols === 1)) {
    this.moveSelect((index + maxCols) % maxItems);
  }
};

Window_MessageBacklog.prototype.cursorUp = function(wrap) {
  var index = this.topRow();
  var maxItems = this.maxItems();
  var maxCols = this.maxCols();
  wrap = Yanfly.Param.MsgBacklogScrollWrap;
  if (index >= maxCols || (wrap && maxCols === 1)) {
    this.moveSelect((index - maxCols + maxItems) % maxItems);
  }
};

Window_MessageBacklog.prototype.cursorPagedown = function() {
  var index = this.index();
  var maxItems = this.maxItems();
  if (this.topRow() + this.maxPageRows() < this.maxRows()) {
    SoundManager.playCursor();
  }
  Window_Selectable.prototype.cursorPagedown.call(this);
  if (this._scrollSprite) this._scrollSprite.updatePosition();
};

Window_MessageBacklog.prototype.cursorPageup = function() {
  var index = this.index();
  if (this.topRow() > 0) {
    SoundManager.playCursor();
  }
  Window_Selectable.prototype.cursorPageup.call(this);
  if (this._scrollSprite) this._scrollSprite.updatePosition();
};

Window_MessageBacklog.prototype.processTouch = function() {
  if (!this.isOpenAndActive()) return;
  this._touchHold -= 1;
  if (TouchInput.isPressed() && this._touchHold <= 0) {
    if (TouchInput.y < Graphics.boxHeight / 4) {
      this.scrollUp();
      this._touchHold = Yanfly.Param.MsgBacklogScrollSpd;
    } else if (TouchInput.y > Graphics.boxHeight * 3 / 4) {
      this.scrollDown();
      this._touchHold = Yanfly.Param.MsgBacklogScrollSpd;
    } else {
      this.processOk();
    }
  } else if (TouchInput.isCancelled()) {
    if (this.isCancelEnabled()) {
      this.processCancel();
    }
  }
};

Window_MessageBacklog.prototype.drawItem = function(index) {
  var rect = this.itemRectForText(index);
  var align = this.itemTextAlign();
  var symbol = this.commandSymbol(index);
  if (symbol === 'linebreak') {
    this.drawHorzLine(rect.y);
    this.resetFontSettings();
  } else if (symbol === 'text') {
    this.drawTextEx(this.commandName(index), rect.x, rect.y);
  } else if (symbol === 'buffer') {
    if (index !== this.topRow()) return;
    var ext = this._list[index].ext;
    this.drawItem(index - ext);
  }
};

Window_MessageBacklog.prototype.drawHorzLine = function(y) {
  var lineY = y + this.lineHeight() / 2 - 1;
  this.contents.paintOpacity = 48;
  this.contents.fillRect(0, lineY, this.contentsWidth(), 2, this.normalColor());
  this.contents.paintOpacity = 255;
};

Window_MessageBacklog.prototype.drawTextEx = function(text, x, y) {
  if (text) {
    var textState = { index: 0, x: x, y: y, left: x };
    textState.text = this.convertEscapeCharacters(text);
    textState.height = this.calcTextHeight(textState, false);
    while (textState.index < textState.text.length) {
      this.processCharacter(textState);
    }
    return textState.x - x;
  } else {
    return 0;
  }
};

Window_MessageBacklog.prototype.textHeightEx = function(text) {
  return this.getTextExHeight(text, 0, 0);
};

Window_MessageBacklog.prototype.getTextExHeight = function(text, x, y) {
  if (text) {
    var textState = { index: 0, x: x, y: y, left: x };
    textState.text = this.convertEscapeCharacters(text);
    textState.height = this.calcTextHeight(textState, false);
    while (textState.index < textState.text.length) {
      this.processCharacter(textState);
    }
    this.contents.clear();
    return textState.y;
  } else {
    return 0;
  }
};

Window_MessageBacklog.prototype.makeCommandList = function() {
  if (!this._ready) return;
  var backlog = $gameSystem.getMessageBacklog();
  var length = backlog.length;
  for (var i = 0; i < length; ++i) {
    var text = backlog[i];
    this.addCommand('---', 'linebreak');
    this.addIndividualLines(text);
  }
  this.addCommand('---', 'linebreak');
};

Window_MessageBacklog.prototype.addIndividualLines = function(text) {
  var text = this.convertMessageText(text);
  var items = text.split('\n');
  var length = items.length;
  for (var i = 0; i < length; ++i) {
    var line = items[i];
    if (line.length <= 0) continue;
    this.addCommand(line, 'text');
    this.addWordWrapBuffer(line);
  }
};

Window_MessageBacklog.prototype.convertMessageText = function(text) {
  text = this.convertMessageMacros(text);
  text = text.replace(/\\/g, '\x1b');
  text = this.convertNameboxCodes(text);
  text = this.convertBasicCodes(text);
  text = this.convertSpecialCodes(text);
  text = this.removeMessageBoxOnlyCodes(text);
  return text;
};

Window_MessageBacklog.prototype.convertMessageMacros = function(text) {
  if (Imported.YEP_X_MessageMacros1) {
    text = this.convertMacroText(text);
  }
  return text;
};

Window_MessageBacklog.prototype.convertNameboxCodes = function(text) {
  var name = '';
  // \x1b
  if (text.match(/\x1bN\<(.*?)\>/gi)) {
    name = RegExp.$1;
  } else if (text.match(/\x1bN(\d+)\<(.*?)\>/gi)) {
    name = RegExp.$2;
  } else if (text.match(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)\<(.*?)\>/gi)) {
    name = RegExp.$1;
  } else if
  (text.match(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)(\d+)\<(.*?)\>/gi)) {
    name = RegExp.$2;
  }
  if (name.length > 0) {
    var nameText = Yanfly.Param.MSGNameBoxText + name + '\\c[0]\n';
    text = nameText + text;
  }
  // \x1b version
  text = text.replace(/\x1bN\<(.*?)\>/gi, '');
  text = text.replace(/\x1bN(\d+)\<(.*?)\>/gi, '');
  text = text.replace(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)\<(.*?)\>/gi, '');
  text = text.replace(/\x1bN\<(.*?)\>/gi, '');
  text =
    text.replace(/\x1bN(?:T|D|L|C|R|DL|DC|DR|TL|TC|TR)(\d+)\<(.*?)\>/gi, '');
  return text;
};

Window_MessageBacklog.prototype.convertBasicCodes = function(text) {
  text = text.replace(/\\/g, '\x1b');
  text = text.replace(/\x1b\x1b/g, '\\');
  text = text.replace(/\x1bV\[(\d+)\]/gi, function() {
    return $gameVariables.value(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bV\[(\d+)\]/gi, function() {
    return $gameVariables.value(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bN\[(\d+)\]/gi, function() {
    return this.actorName(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bP\[(\d+)\]/gi, function() {
    return this.partyMemberName(parseInt(arguments[1]));
  }.bind(this));
  text = text.replace(/\x1bG/gi, TextManager.currencyUnit);
  return text;
};

Window_MessageBacklog.prototype.convertSpecialCodes = function(text) {
  if (Imported.YEP_X_ExtMesPack2) {
    text = this.convertItemQuantitiesCodes(text);
    text = this.convertActorParameterCodes(text);
    text = this.convertEnemyParameterCodes(text);
  }
  return text;
};

Window_MessageBacklog.prototype.removeMessageBoxOnlyCodes = function(text) {
  text = text.replace(/\x1b/gi, '\\');
  // Message Core
  text = text.replace(/\\AF\[(\d+)\]/gi, '');
  text = text.replace(/\\PF\[(\d+)\]/gi, '');
  text = text.replace(/\\FS\[(\d+)\]/gi, '');
  // Extended Message Pack 1
  text = text.replace(/\\LSON/gi, '');
  text = text.replace(/\\LSOFF/gi, '');
  text = text.replace(/\\LSRESET/gi, '');
  text = text.replace(/\\LSR/gi, '');
  text = text.replace(/\\LSN\[(.*?)\]/gi, '');
  text = text.replace(/\\LSV\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPIV\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPI\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPAV\[(\d+)\]/gi, '');
  text = text.replace(/\\LSPA\[(\d+)\]/gi, '');
  text = text.replace(/\\LSI\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGPOSX\[(.*?)\]/gi, '');
  text = text.replace(/\\MSGPOSY\[(.*?)\]/gi, '');
  text = text.replace(/\\MSGEVENT\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGACTOR\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGPARTY\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGENEMY\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOEVENT\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOACTOR\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOPARTY\[(\d+)\]/gi, '');
  text = text.replace(/\\AUTOENEMY\[(\d+)\]/gi, '');
  text = text.replace(/\\MSGROWS\[(.*?)\]/gi, '');
  text = text.replace(/\\MSGWIDTH\[(.*?)\]/gi, '');
  text = text.replace(/\\AUTO/gi, '');
  text = text.replace(/\\MSGRESET/gi, '');
  text = text.replace(/\\FACEINDEX\[(\d+)\]/gi, '');

  // 追加: 他のプラグインの制御文字を削除
  text = text.replace(/\\CE\[\d+\]/gi, ''); //

  return text;
};

Window_MessageBacklog.prototype.addWordWrapBuffer = function(text) {
  if (!text.match(/<(?:WordWrap)>/gi)) return;
  var textHeight = this.textHeightEx(text);
  var bufferTimes = Math.ceil(textHeight / this.lineHeight());
  for (var i = 1; i <= bufferTimes; ++i) {
    this.addCommand('', 'buffer', true, i);
  }
};

//=============================================================================
// Utilities
//=============================================================================

Yanfly.Util = Yanfly.Util || {};

if (!Yanfly.Util.toGroup) {

Yanfly.Util.toGroup = function(inVal) {
  return inVal;
}

};

//=============================================================================
// End of File
//=============================================================================
} else {

var text = '';
text += 'You are getting this error because you are trying to run ';
text += 'YEP_X_MessageBacklog without the required plugins. Please visit ';
text += 'Yanfly.moe and install the required plugins neede for this plugin ';
text += 'found in this plugin\'s help file before you can use it.';
console.log(text);
require('nw.gui').Window.get().showDevTools();

}; // Imported.YEP_MessageCore


code:
/*:
 * @plugindesc Basic plugin for manipulating important parameters.
 * @author RM CoreScript team
 *
 * @help
 * Basic plugin for manipulating important parameters.
 * There is no plugin command.
 *
 * Caching images improves performance but increases memory allocation.
 * On mobile devices, a lot of memory allocation causes the browser to crash.
 * Therefore, the upper limit of memory allocation is set with cacheLimit.
 *
 * If you want to regain high performance, just increase cacheLimit.
 * There is no need to revert to 1.4.
 *
 * @param cacheLimit
 * @type number
 * @desc The upper limit of images' cached size (MPixel)
 * @default 10
 *
 * @param screenWidth
 * @type number
 * @desc The resolution of screen width
 * @default 816
 *
 * @param screenHeight
 * @type number
 * @desc The resolution of screen height
 * @default 624
 *
 * @param changeWindowWidthTo
 * @type number
 * @desc If set, change window width to this value
 *
 * @param changeWindowHeightTo
 * @type number
 * @desc If set, change window height to this value
 *
 * @param renderingMode
 * @type select
 * @option canvas
 * @option webgl
 * @option auto
 * @desc The rendering mode (canvas/webgl/auto)
 * @default auto
 *
 * @param alwaysDash
 * @type boolean
 * @desc The initial value whether the player always dashes (on/off)
 * @on ON
 * @off OFF
 * @default false
 *
 * @param textSpeed
 * @type number
 * @desc The text speed on "Show Text". The larger this parameter is, the slower text speed. (0: show all texts at once)
 * @default 1
 *
 * @param autoSaveFileId
 * @type number
 * @desc The file number to auto save when "Transfer Player" (0: off)
 * @default 0
 *
 * @param errorMessage
 * @type string
 * @desc The message when error occurred
 * @default Error occurred. Please ask to the creator of this game.
 *
 * @param showErrorDetail
 * @type boolean
 * @desc Show where the error is caused and stack trace when error
 * @default true
 *
 * @param enableProgressBar
 * @type boolean
 * @desc Show progress bar when it takes a long time to load resources
 * @default true
 *
 * @param maxRenderingFps
 * @type number
 * @desc The maximum value of rendering frame per seconds (0: unlimited)
 * @default 0
 */

/*:ja
 * @plugindesc 基本的なパラメーターを設定するプラグインです。
 * @author RM CoreScript team
 *
 * @help
 * 基本的なパラメーターを設定するプラグインです。
 * このプラグインにはプラグインコマンドはありません。
 *
 * 画像をキャッシュするとパフォーマンスは向上しますが、その分メモリ確保も増大します。
 * モバイルデバイスでは、たくさんのメモリ確保はブラウザをクラッシュさせます。
 * そこで、メモリ確保の上限を「画像キャッシュ上限値」で設定しています。
 *
 * もし高いパフォーマンスを取り戻したければ、ただ画像キャッシュ上限値を増加させればよいです。
 * 1.4に戻す必要はありません。
 *
 * @param cacheLimit
 * @type number
 * @text 画像キャッシュ上限値
 * @desc 画像のメモリへのキャッシュの上限値 (MPix)
 * @default 10
 *
 * @param screenWidth
 * @type number
 * @text ゲーム画面の幅
 * @default 816
 *
 * @param screenHeight
 * @type number
 * @text ゲーム画面の高さ
 * @default 624
 *
 * @param changeWindowWidthTo
 * @type number
 * @text ウィンドウの幅
 * @desc 値が設定されなかった場合、ゲーム画面の幅と同じ
 *
 * @param changeWindowHeightTo
 * @type number
 * @text ウィンドウの高さ
 * @desc 値が設定されなかった場合、ゲーム画面の高さと同じ
 *
 * @param renderingMode
 * @type select
 * @option canvas
 * @option webgl
 * @option auto
 * @text レンダリングモード
 * @default auto
 *
 * @param alwaysDash
 * @type boolean
 * @text 「常時ダッシュ」の初期値
 * @on ON
 * @off OFF
 * @default false
 *
 * @param textSpeed
 * @type number
 * @text 「文章の表示」のスピード
 * @desc 数字が大きいほど文章の表示スピードが遅くなります (0を指定した場合は一度に全文を表示します)
 * @default 1
 *
 * @param autoSaveFileId
 * @type number
 * @text オートセーブ番号
 * @desc 「場所移動」の際に指定したファイル番号にオートセーブします（0を指定した場合はオートセーブしません）
 * @default 0
 *
 * @param errorMessage
 * @type string
 * @text エラーメッセージ
 * @desc エラー時にプレイヤーに向けて表示するメッセージです
 * @default エラーが発生しました。ゲームの作者にご連絡ください。
 *
 * @param showErrorDetail
 * @type boolean
 * @text エラー詳細表示
 * @desc ONにすると、エラー時にエラーを発生させたイベントの情報とスタックトレースを表示します
 * @default true
 *
 * @param enableProgressBar
 * @type boolean
 * @text ロード進捗バー有効化
 * @desc ONにすると、読み込みに時間がかかっている時にロード進捗バーを表示します
 * @default true
 *
 * @param maxRenderingFps
 * @type number
 * @text 描画FPS上限値
 * @desc 描画FPSの上限値を設定します (0を指定した場合は制限なし)
 * @default 0
 */

(function() {
    'use strict';
    function isNumber(str) {
        return !!str && !isNaN(str);
    }

    function toNumber(str, def) {
        return isNumber(str) ? +str : def;
    }

    var parameters = PluginManager.parameters('Community_Basic');
    var cacheLimit = toNumber(parameters['cacheLimit'], 10);
    var screenWidth = toNumber(parameters['screenWidth'], 816);
    var screenHeight = toNumber(parameters['screenHeight'], 624);
    var renderingMode = parameters['renderingMode'].toLowerCase();
    var alwaysDash = (parameters['alwaysDash'] === 'true') ||(parameters['alwaysDash'] === 'on');
    var textSpeed = toNumber(parameters['textSpeed'], 1);
    var windowWidthTo = toNumber(parameters['changeWindowWidthTo'], 0);
    var windowHeightTo = toNumber(parameters['changeWindowHeightTo'], 0);
    var maxRenderingFps = toNumber(parameters['maxRenderingFps'], 0);
    var autoSaveFileId = toNumber(parameters['autoSaveFileId'], 0);
    var errorMessage = parameters['errorMessage'];
    var showErrorDetail = parameters['showErrorDetail'] === 'true';
    var enableProgressBar = parameters['enableProgressBar'] === 'true';

    var windowWidth;
    var windowHeight;

    if(windowWidthTo){
        windowWidth = windowWidthTo;
    }else if(screenWidth !== SceneManager._screenWidth){
        windowWidth = screenWidth;
    }

    if(windowHeightTo){
        windowHeight = windowHeightTo;
    }else if(screenHeight !== SceneManager._screenHeight){
        windowHeight = screenHeight;
    }

    ImageCache.limit = cacheLimit * 1000 * 1000;
    SceneManager._screenWidth = screenWidth;
    SceneManager._screenHeight = screenHeight;
    SceneManager._boxWidth = screenWidth;
    SceneManager._boxHeight = screenHeight;

    SceneManager.preferableRendererType = function() {
        if (Utils.isOptionValid('canvas')) {
            return 'canvas';
        } else if (Utils.isOptionValid('webgl')) {
            return 'webgl';
        } else if (renderingMode === 'canvas') {
            return 'canvas';
        } else if (renderingMode === 'webgl') {
            return 'webgl';
        } else {
            return 'auto';
        }
    };

    var _ConfigManager_applyData = ConfigManager.applyData;
    ConfigManager.applyData = function(config) {
        _ConfigManager_applyData.apply(this, arguments);
        if (config['alwaysDash'] === undefined) {
            this.alwaysDash = alwaysDash;
        }
    };

    var _Window_Message_clearFlags = Window_Message.prototype.clearFlags;
    Window_Message.prototype.clearFlags = function(textState) {
        _Window_Message_clearFlags.apply(this, arguments);
        this._textSpeed = textSpeed - 1;
    };

    var _SceneManager_initNwjs = SceneManager.initNwjs;
    SceneManager.initNwjs = function() {
        _SceneManager_initNwjs.apply(this, arguments);

        if (Utils.isNwjs() && windowWidth && windowHeight) {
            var dw = windowWidth - window.innerWidth;
            var dh = windowHeight - window.innerHeight;
            window.moveBy(-dw / 2, -dh / 2);
            window.resizeBy(dw, dh);
        }
    };

    if (maxRenderingFps) {
        var currentTime = Date.now();
        var deltaTime = 1000 / maxRenderingFps;
        var accumulator = 0;
        var _SceneManager_renderScene = SceneManager.renderScene;
        SceneManager.renderScene = function() {
            var newTime = Date.now();
            accumulator += newTime - currentTime;
            currentTime = newTime;
            if (accumulator >= deltaTime) {
                accumulator -= deltaTime;
                _SceneManager_renderScene.apply(this, arguments);
            }
        };
    }

    DataManager.setAutoSaveFileId(autoSaveFileId);
    Graphics.setErrorMessage(errorMessage);
    Graphics.setShowErrorDetail(showErrorDetail);
    Graphics.setProgressEnabled(enableProgressBar);
})();

repo_name: dazed/translations

license: unknown


code:
// [SQUARE PHOENIX] : http://enix.web.fc2.com/
/*:
* @plugindesc ドロップ率と取得ゴールド＆経験値を数倍にできるスキル
* @author SQUARE PHOENIX
* @help
ドロップ率と取得ゴールド＆経験値を数倍にできるスキルを作成できます。
スキルは覚えているだけで効果を発揮します。

↓例（スキルのメモに書きます）
<gold_x:3>：戦闘後に取得できるゴールドが３倍になります
<exp_x:4> ：戦闘後に取得できるゴールドが４倍になります
<drop_x:5>：戦闘後にアイテムを取得できる可能性が５倍になります

* 利用規約：
*  自己責任で自由にお使いください。
*/
(function() {
  //=============================================================================
  // rpg_objects
  //=============================================================================
  Game_Enemy.prototype.dropItemRate = function() {
    var actId = 0;
    var ninzu = $gameParty._actors.length
    for(var i=1;i <= ninzu;i++){
    actId = $gameParty._actors[i-1];
      var actor = $gameActors.actor(actId);
      var skill_suu = actor.skills().length
      for(var ii = 1; ii <= skill_suu; ii++){
        //drop
        if (actor.skills()[ii-1].meta['drop_x']){
         console.log(actor.skills()[ii-1].meta['drop_x']);
         return actor.skills()[ii-1].meta['drop_x'];
        }
      }
    }
  //-------------------------------------------------------
      return $gameParty.hasDropItemDouble() ? 2 : 1;//moto
  };

  //=============================================================================
  // rpg_managers.js v1.5.0
  //=============================================================================
  BattleManager.makeRewards = function() {
      this._rewards = {};
      this._rewards.gold = $gameTroop.goldTotal();
      this._rewards.exp = $gameTroop.expTotal();
      this._rewards.items = $gameTroop.makeDropItems();
      //------------------------------------
      var actId = 0;
      var ninzu = $gameParty._actors.length
      for(var i=1;i <= ninzu;i++){
      actId = $gameParty._actors[i-1];
        var actor = $gameActors.actor(actId);
        var skill_suu = actor.skills().length
        for(var ii = 1; ii <= skill_suu; ii++){
          //gold
          if (actor.skills()[ii-1].meta['gold_x']){
           this._rewards.gold = $gameTroop.goldTotal()*actor.skills()[ii-1].meta['gold_x'];
          }
          //exp
          if (actor.skills()[ii-1].meta['exp_x']){
           this._rewards.exp = $gameTroop.expTotal()*actor.skills()[ii-1].meta['exp_x'];
          }
        }
      }
  };

})();


code:
//==============================================================================
// dsShowBattleCommand.js
// Copyright (c) 2016 Douraku
// Released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//==============================================================================

/*:
 * @plugindesc 戦闘中のコマンド表示制御プラグイン ver1.00
 * @author 道楽
 *
 * @param Show Attack Command
 * @desc 攻撃コマンドを表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Guard Command
 * @desc 防御コマンドを表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Item Command
 * @desc アイテムコマンドを表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 01
 * @desc スキルタイプ01を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 02
 * @desc スキルタイプ02を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 03
 * @desc スキルタイプ03を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 04
 * @desc スキルタイプ04を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 05
 * @desc スキルタイプ05を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 06
 * @desc スキルタイプ06を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 07
 * @desc スキルタイプ07を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 08
 * @desc スキルタイプ08を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 09
 * @desc スキルタイプ09を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 10
 * @desc スキルタイプ10を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 11
 * @desc スキルタイプ11を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 12
 * @desc スキルタイプ12を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 13
 * @desc スキルタイプ13を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 14
 * @desc スキルタイプ14を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 15
 * @desc スキルタイプ15を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 16
 * @desc スキルタイプ16を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 17
 * @desc スキルタイプ17を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 18
 * @desc スキルタイプ18を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 19
 * @desc スキルタイプ19を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 20
 * @desc スキルタイプ20を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 21
 * @desc スキルタイプ21を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 22
 * @desc スキルタイプ22を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 23
 * @desc スキルタイプ23を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 24
 * @desc スキルタイプ24を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 25
 * @desc スキルタイプ25を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 26
 * @desc スキルタイプ26を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 27
 * @desc スキルタイプ27を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 28
 * @desc スキルタイプ28を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 29
 * @desc スキルタイプ29を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 *
 * @param Show Skill Type 30
 * @desc スキルタイプ30を表示するか
 * (true なら表示する / false なら表示しない)
 * @default true
 */

var Imported = Imported || {};
Imported.dsShowBattleCommand = true;

var dsShowBattleCommand = {};

(function(ns) {

	ns.Param = (function() {
		var ret = {};
		var parameters = PluginManager.parameters('dsShowBattleCommand');
		ret.ShowAttackCommand = Boolean(parameters['Show Attack Command'] === 'true' || false);
		ret.ShowGuardCommand = Boolean(parameters['Show Guard Command'] === 'true' || false);
		ret.ShowItemCommand = Boolean(parameters['Show Item Command'] === 'true' || false);
		ret.ShowSkillTypeMax = 1 + 30;
		ret.ShowSkillType = [];
		for ( var ii = 1; ii < ret.ShowSkillTypeMax; ii++ )
		{
			var paramName = 'Show Skill Type ' + ('00'+ii).slice(-2);
			ret.ShowSkillType[ii] = Boolean(parameters[paramName] === 'true' || false);
		}
		return ret;
	})();

	//--------------------------------------------------------------------------
	/** Window_ActorCommand */
	var _Window_ActorCommand_addAttackCommand = Window_ActorCommand.prototype.addAttackCommand;
	Window_ActorCommand.prototype.addAttackCommand = function()
	{
		if ( ns.Param.ShowAttackCommand )
		{
			_Window_ActorCommand_addAttackCommand.call(this);
		}
	};

	Window_ActorCommand.prototype.addSkillCommands = function()
	{
		var skillTypes = this._actor.addedSkillTypes();
		skillTypes.sort(function(a, b) {
			return a - b;
		});
		skillTypes.forEach(function(stypeId) {
			if ( this.isShowSkillType(stypeId) )
			{
				var name = $dataSystem.skillTypes[stypeId];
				this.addCommand(name, 'skill', true, stypeId);
			}
		}, this);
	};

	var _Window_ActorCommand_addGuardCommand = Window_ActorCommand.prototype.addGuardCommand;
	Window_ActorCommand.prototype.addGuardCommand = function()
	{
		if ( ns.Param.ShowGuardCommand )
		{
			_Window_ActorCommand_addGuardCommand.call(this);
		}
	};

	var _Window_ActorCommand_addItemCommand = Window_ActorCommand.prototype.addItemCommand;
	Window_ActorCommand.prototype.addItemCommand = function()
	{
		if ( ns.Param.ShowItemCommand )
		{
			_Window_ActorCommand_addItemCommand.call(this);
		}
	};

	Window_ActorCommand.prototype.isShowSkillType = function(stypeId)
	{
		if ( stypeId < ns.Param.ShowSkillTypeMax )
		{
			return ns.Param.ShowSkillType[stypeId];
		}
		return true;
	};

})(dsShowBattleCommand);


code:
//=============================================================================
// ゲーム終了コマンド追加プラグイン
// gamEnd.js
// Copyright (c) 2018 村人Ａ
//=============================================================================

/*:ja
 * @plugindesc このプラグインはタイトル画面にウィンドウを閉じるゲーム終了コマンドを追加します。
 * @author 村人A
 *
 * @param endName
 * @desc ゲーム終了の表記です
 * @default ゲーム終了
 *
 * @help このプラグインにはプラグインコマンドはありません。
 * 「endName」にはタイトルで表記するゲーム終了のコマンド名を入れてください。
 */

(function() {

    var parameters = PluginManager.parameters('gameEnd');
    var EndName = String(parameters['endName'] || 'ゲーム終了');

	Window_TitleCommand.prototype.makeCommandList = function() {
		this.addCommand(TextManager.newGame,   'newGame');
		this.addCommand(TextManager.continue_, 'continue', this.isContinueEnabled());
		this.addCommand(TextManager.options,   'options');
		this.addCommand(EndName,   'gameEnd');
	};

	Scene_Title.prototype.createCommandWindow = function() {
		this._commandWindow = new Window_TitleCommand();
		this._commandWindow.setHandler('newGame',  this.commandNewGame.bind(this));
		this._commandWindow.setHandler('continue', this.commandContinue.bind(this));
		this._commandWindow.setHandler('options',  this.commandOptions.bind(this));
		this._commandWindow.setHandler('gameEnd',  this.commandGameEnd.bind(this));
		this.addWindow(this._commandWindow);
	};

	Scene_Title.prototype.commandGameEnd = function() {
		if(StorageManager.isLocalMode()){
			window.close();
		} else {
			window.open('about:blank', '_self').close();
		}
	};
})();


code:
/*:ja
 * @plugindesc メニューコマンドの画像化
 * @author 剣崎宗二
 *
 * @param icon width
 * @desc 画像アイコンの横幅
 * @type number
 * @min 0
 * @default 100
 *
 * @param icon height
 * @desc 画像アイコンの一つ辺りの縦幅
 * @type number
 * @min 0
 * @default 100
 *
 * @param item icon
 * @desc 「アイテム」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 0
 *
 * @param skill icon
 * @desc 「スキル」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 1
 *
 * @param equip icon
 * @desc 「装備」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 2
 *
 * @param status icon
 * @desc 「ステータス」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 3
 *
 * @param Hstatus icon
 * @desc 「Hステータス」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 3
 *
 * @param Lock icon
 * @desc 「ロック中」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 8
 *
 * @param Skillpanel icon
 * @desc 「スキルパネル」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 5
 *
 * @param Skillpanelban icon
 * @desc 「スキルパネル禁止」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 10
 *
 * @param options icon
 * @desc 「オプション」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 6
 *
 * @param save icon
 * @desc 「セーブ」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 7
 *
 * @param saveban icon
 * @desc 「セーブ禁止」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 9
 *
 * @param gameEnd icon
 * @desc 「ゲーム終了」に該当する画像アイコンのインデックス
 * @type number
 * @min 0
 * @default 8
 *
 * @param icon itemrect
 * @desc アイコンの間隔
 * @type number
 * @min 0
 * @default 10
 *
 * @param icon rows
 * @desc アイコンを縦に並べる数
 * @type number
 * @min 1
 * @default 2
 *
 * @param icon cols
 * @desc アイコンを横に並べる数
 * @type number
 * @min 1
 * @default 4
 *
 * @param icon maxexpansion
 * @desc アイコンの拡縮率
 * @type number
 * @min 0
 * @decimals 2
 * @default 0.1
 *
 * @param x overhead
 * @desc アイコンを並べる開始位置x
 * @type number
 * @min 0
 * @default 0
 *
 * @param y overhead
 * @desc アイコンを並べる開始位置y
 * @type number
 * @min 0
 * @default 0
 *
 * @param commandwindow x
 * @desc コマンドウインドウの位置ｘ
 * @type number
 * @min -1000
 * @default 0
 *
 * @param commandwindow y
 * @desc コマンドウインドウの位置y
 * @type number
 * @min -1000
 * @default 0
 *
 * @param commandwindow width
 * @desc コマンドウインドウの幅
 * @type number
 * @min 0
 * @default 240
 *
 * @param commandwindow height
 * @desc コマンドウインドウの高さ
 * @type number
 * @min 0
 * @default 585
 *
 * @param display cursor
 * @desc カーソルを表示/消去
 * @type boolean
 * @on YES
 * @off NO
 * @default true
 *
 * @param window background file
 * @desc メニューウィンドウの背景ファイル。空白でデフォルト仕様になります。
 * @type string
 * @default
 *
 * @help kz_PicMenu.js
 *
 * Special Thanks: サイリ(Twitter:sairi55)-アイデア発案、及びサンプル素材制作
 *
 * 使用する画像は全て img/system　フォルダ内に入れてください。
 *
 * □アイコン用画像… MenuIcon.png
 *　 サイズは任意ですが必ず【縦に等幅】でそれぞれのアイコンを用意して下さい。
 *
 * □ウインドウ背景用画像…名称任意、パラメータ【window background file】
 *　 画像を使用しないがウインドウを透過したい場合は1 × 1 pixelの
 *　 透過画像を用意してその名前をパラメータに入れて下さい。
 *
 *
 */

(function () {

    var parameters = PluginManager.parameters('kz_PicMenu');
    var _itemicon = Number(parameters['item icon'] || 0);
    var _skillicon = Number(parameters['skill icon'] || 1);
    var _equipicon = Number(parameters['equip icon'] || 2);
    var _statusicon = Number(parameters['status icon'] || 3);
    var _Hstatusicon = Number(parameters['Hstatus icon'] || 4);
    var _skillpanelicon = Number(parameters['Skillpanel icon'] || 5);
    var _skillpanelbanicon = Number(parameters['Skillpanelban icon'] || 10);
    var _lockicon = Number(parameters['Lock icon'] || 5);
    var _optionsicon = Number(parameters['options icon'] || 6);
    var _saveicon = Number(parameters['save icon'] || 7);
    var _savebanicon = Number(parameters['saveban icon'] || 9);
    var _endicon = Number(parameters['gameEnd icon'] || 8);

    var _cmdlistTxt = ['item:' + _itemicon, 'skill:' + _skillicon, 'equip:' + _equipicon, 'status:' + _statusicon, 'achievement:' + _Hstatusicon, '????:' + _lockicon, 'skillpanel:' + _skillpanelicon, 'skillpanelban:' + _skillpanelbanicon, 'options:' + _optionsicon, 'save:' + _saveicon, 'saveban:' + _savebanicon, 'gameEnd:' + _endicon, 'default:-1'];
    //defaultは普段では使わない。リストにないアイコンが出た時の表示用！ Indexは0からカウント

    var _MenuIconWidth = Number(parameters['icon width'] || 100);
    var _MenuIconHeight = Number(parameters['icon height'] || 100);
    var _IconitemRect = Number(parameters['icon itemrect'] || 10);
    var _iconrows = Number(parameters['icon rows'] || 2);
    var _iconcols = Number(parameters['icon cols'] || 4);
    var _MaxExpansion = Number(parameters['icon maxexpansion'] || 0.1);
    var _xOverhead = Number(parameters['x overhead'] || 0);
    var _yOverhead = Number(parameters['y overhead'] || 0);

    var _CwindowX = Number(parameters['commandwindow x'] || 0);
    var _CwindowY = Number(parameters['commandwindow y'] || 0);
    var _CwindowWidth = Number(parameters['commandwindow width'] || 240);
    var _CwindowHeight = Number(parameters['commandwindow height'] || 500);

    var _cursorDisplay = eval(parameters['display cursor']);

    var _windowBack = parameters['window background file'] || '';

    var _cmdlist = [];
    _cmdlistTxt.forEach(function (element) {
        var tArray = element.split(':');
        _cmdlist[tArray[0]] = Number(tArray[1]);
    });

    var kz_Scene_Boot_loadSystemImages = Scene_Boot.loadSystemImages;
    Scene_Boot.loadSystemImages = function () {
        kz_Scene_Boot_loadSystemImages.call(this);
        ImageManager.reserveSystem('[Menu]CommandIcon');
        ImageManager.reserveSystem('[Menu]CommandIcon2');
    };

    var kz_Window_MenuCommand_prototype_initialize = Window_MenuCommand.prototype.initialize;
    Window_MenuCommand.prototype.initialize = function (x, y) {
        kz_Window_MenuCommand_prototype_initialize.call(this, _CwindowX, _CwindowY);
        if (_windowBack != '') {
            this.setBackgroundType(2);
            this.createBackSprite();
        }
    };

    Window_MenuCommand.prototype.createBackSprite = function () {
        this._backSprite = new Sprite();
        this._backSprite.bitmap = ImageManager.loadSystem(_windowBack);
        this.addChildToBack(this._backSprite);
    };

    Window_MenuCommand.prototype.drawItem = function (index) {
        var rect = this.itemRect(index);
        var symbol = this.commandSymbol(index);
        var properIndex = _cmdlist[symbol] >= 0 ? _cmdlist[symbol] : _cmdlist['default'];
        var selected = (this.index() == index);
        if (properIndex >= 0);
        {
        	if(properIndex == 4 && ($gameSwitches.value(27) || $gameSwitches.value(627))){properIndex=10}
        	this.drawMenuIcon(properIndex, rect.x, rect.y, selected)
        }
    };

    Window_MenuCommand.prototype.drawMenuIcon = function (iconIndex, x, y, selected) {
        var bitmap = ImageManager.loadSystem('[Menu]CommandIcon');
        var bitmap2 = ImageManager.loadSystem('[Menu]CommandIcon2');
        var pw = _MenuIconWidth;
        var ph = _MenuIconHeight;
        var sx = 0;
        var sy = iconIndex * ph;

        var dw = pw;
        var dh = ph;
        if (selected) {
            var expScale = 1 +  _MaxExpansion;
            dw = Math.round(dw * expScale)+10;
            dh = Math.round(dh * expScale);
            x += Math.round((pw - dw) / 2);
            y += Math.round((ph - dh) / 2);
        }
		if(selected){
	        this.contents.blt(bitmap2, sx, sy, pw, ph, x, y, dw, dh);
	    }else{
	        this.contents.blt(bitmap, sx, sy, pw, ph, x, y, dw, dh);
	    }
    };

    Window_MenuCommand.prototype.itemWidth = function () {
        return _MenuIconWidth;
    };

    Window_MenuCommand.prototype.itemHeight = function () {
        return _MenuIconHeight;
    };

    kz_Window_MenuCommand_prototype_itemRect = Window_MenuCommand.prototype.itemRect;
    Window_MenuCommand.prototype.itemRect = function (index) {
        var rect = kz_Window_MenuCommand_prototype_itemRect.call(this, index);
        var maxCols = this.maxCols();
        rect.x += _xOverhead;
        rect.y = Math.floor(index / maxCols) * (rect.height + _IconitemRect) - this._scrollY + _yOverhead;
        return rect;
    };

    Window_MenuCommand.prototype.numVisibleRows = function () {
        return _iconrows;  //縦列数
    };

    Window_MenuCommand.prototype.maxCols = function () {
        return _iconcols;  //横列数
    };

    Window_MenuCommand.prototype.windowWidth = function () {
        return _CwindowWidth;   //横幅
    };

    Window_MenuCommand.prototype.windowHeight = function () {
        return _CwindowHeight;   //高さ
    };

    Window_MenuCommand.prototype.update = function () {
        Window_Selectable.prototype.update.call(this);
        this.refresh();
    };

    var kz_Window_MenuCommand_prototype_isCursorVisible = Window_MenuCommand.prototype.isCursorVisible
    Window_MenuCommand.prototype.isCursorVisible = function () {
        if (!_cursorDisplay) {
            return false;
        }
        return kz_Window_MenuCommand_prototype_isCursorVisible.call(this);
    };

})();


code:
/*=============================================================================
 * Orange - Mapshot
 * By Hudell - www.hudell.com
 * OrangeMapshot.js
 * Version: 1.7
 * Free for commercial and non commercial use.
 *=============================================================================*/
/*:
 * @plugindesc This plugin will save a picture of the entire map on a Mapshots folder when you press a key. <OrangeMapshot>
 * @author Hudell
 *
 * @param useMapName
 * @desc if true, the filename will be the name of the map. If false it will be the number.
 * @default true
 *
 * @param layerType
 * @desc 0 = all, 1 = upper and lower, 2 = separate everything
 * @default 0
 *
 * @param drawAutoShadows
 * @desc set this to false to disable autoshadows on the map shot
 * @default true
 *
 * @param drawEvents
 * @desc set this to false to stop drawing the events on the full bitmap
 * @default true
 *
 * @param keyCode
 * @desc code of the key that will be used (44 = printscreen). http://link.hudell.com/js-keys
 * @default 44
 *
 * @param imageType
 * @desc What type of image should be generated. Can be png, jpeg or webp
 * @default png
 *
 * @param imageQuality
 * @desc If the imageType is jpeg or webp, you can set this to a number between 0 and 100 indicating the quality of the image
 * @default 70
 *
 * @param imagePath
 * @desc The path where the images will be saved
 * @default ./Mapshots
 *
 * @help
 * Check keycodes at  http://link.hudell.com/js-keys
 */
var Imported = Imported || {};

var OrangeMapshot = OrangeMapshot || {};

(function($) {
  "use strict";

  var parameters = $plugins.filter(function(plugin) {
    return plugin.description.indexOf('<OrangeMapshot>') >= 0;
  });
  if (parameters.length === 0) {
    throw new Error("Couldn't find OrangeMapshot parameters.");
  }
  $.Parameters = parameters[0].parameters;

  $.Param = {};
  $.Param.useMapName = $.Parameters.useMapName !== "false";
  $.Param.drawAutoShadows = $.Parameters.drawAutoShadows !== "false";
  $.Param.drawEvents = $.Parameters.drawEvents !== "false";
  $.Param.layerType = Number($.Parameters.layerType || 0);
  $.Param.imageType = $.Parameters.imageType || 'png';
  $.Param.imagePath = $.Parameters.imagePath || './Mapshots';
  $.Param.imageQuality = Number($.Parameters.imageQuality || 70);

  $.Param.keyCode = Number($.Parameters.keyCode || 44);

  $.imageType = function() {
    if ($.Param.imageType == 'webp') return 'image/webp';
    if ($.Param.imageType == 'jpeg' || $.Param.imageType == 'jpg') return 'image/jpeg';
    return 'image/png';
  };

  $.imageRegex = function() {
    if ($.Param.imageType == 'webp') return (/^data:image\/webp;base64,/);
    if ($.Param.imageType == 'jpeg' || $.Param.imageType == 'jpg') return (/^data:image\/jpeg;base64,/);

    return (/^data:image\/png;base64,/);
  };

  $.fileExtension = function() {
    if ($.Param.imageType == 'webp') return '.webp';
    if ($.Param.imageType == 'jpeg' || $.Param.imageType == 'jpg') return '.jpg';
    return '.png';
  };

  $.imageQuality = function() {
    if ($.fileExtension() == '.jpg' || $.fileExtension() == '.webp') {
      return Math.min($.Param.imageQuality, 100) / 100;
    }

    return 1;
  };

  $.baseFileName = function() {
    var mapName = ($gameMap._mapId).padZero(3);
    if ($.Param.useMapName) {
      mapName = $dataMapInfos[$gameMap._mapId].name;
    } else {
      mapName = 'Map' + mapName;
    }

    return mapName;
  };

  $.getMapshot = function() {
    var lowerBitmap;
    var upperBitmap;

    switch($.Param.layerType) {
      case 1 :
        lowerBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        upperBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        SceneManager._scene._spriteset._tilemap._paintEverything(lowerBitmap, upperBitmap);

        return [lowerBitmap, upperBitmap];
      case 2 :
        var groundBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        var ground2Bitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        var lowerBitmapLayer = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        var upperBitmapLayer = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        var shadowBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        var lowerEvents = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        var normalEvents = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        var upperEvents = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());

        SceneManager._scene._spriteset._tilemap._paintLayered(groundBitmap, ground2Bitmap, lowerBitmapLayer, upperBitmapLayer, shadowBitmap, lowerEvents, normalEvents, upperEvents);
        return [groundBitmap, ground2Bitmap, lowerBitmapLayer, upperBitmapLayer, shadowBitmap, lowerEvents, normalEvents, upperEvents];
      default :
        lowerBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        upperBitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        SceneManager._scene._spriteset._tilemap._paintEverything(lowerBitmap, upperBitmap);

        var bitmap = new Bitmap($dataMap.width * $gameMap.tileWidth(), $dataMap.height * $gameMap.tileHeight());
        bitmap.blt(lowerBitmap, 0, 0, lowerBitmap.width, lowerBitmap.height, 0, 0, lowerBitmap.width, lowerBitmap.height);
        bitmap.blt(upperBitmap, 0, 0, upperBitmap.width, upperBitmap.height, 0, 0, upperBitmap.width, upperBitmap.height);
        return [bitmap];
    }
  };

  function MapShotTileMap() {
  }

  MapShotTileMap.prototype = Object.create(Tilemap.prototype);
  MapShotTileMap.prototype.constructor = MapShotTileMap;

  MapShotTileMap.prototype._drawAutotile = function(bitmap, tileId, dx, dy) {
    var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
    var kind = Tilemap.getAutotileKind(tileId);
    var shape = Tilemap.getAutotileShape(tileId);
    var tx = kind % 8;
    var ty = Math.floor(kind / 8);
    var bx = 0;
    var by = 0;
    var setNumber = 0;
    var isTable = false;

    if (Tilemap.isTileA1(tileId)) {
      var waterSurfaceIndex = [0, 1, 2, 1][this.animationFrame % 4];
      setNumber = 0;
      if (kind === 0) {
        bx = waterSurfaceIndex * 2;
        by = 0;
      } else if (kind === 1) {
        bx = waterSurfaceIndex * 2;
        by = 3;
      } else if (kind === 2) {
        bx = 6;
        by = 0;
      } else if (kind === 3) {
        bx = 6;
        by = 3;
      } else {
        bx = Math.floor(tx / 4) * 8;
        by = ty * 6 + Math.floor(tx / 2) % 2 * 3;
        if (kind % 2 === 0) {
          bx += waterSurfaceIndex * 2;
        }
        else {
          bx += 6;
          autotileTable = Tilemap.WATERFALL_AUTOTILE_TABLE;
          by += this.animationFrame % 3;
        }
      }
    } else if (Tilemap.isTileA2(tileId)) {
      setNumber = 1;
      bx = tx * 2;
      by = (ty - 2) * 3;
      isTable = this._isTableTile(tileId);
    } else if (Tilemap.isTileA3(tileId)) {
      setNumber = 2;
      bx = tx * 2;
      by = (ty - 6) * 2;
      autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
    } else if (Tilemap.isTileA4(tileId)) {
      setNumber = 3;
      bx = tx * 2;
      by = Math.floor((ty - 10) * 2.5 + (ty % 2 === 1 ? 0.5 : 0));
      if (ty % 2 === 1) {
        autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
      }
    }

    var table = autotileTable[shape];
    var source = this.bitmaps[setNumber];

    if (table && source) {
      var w1 = this._tileWidth / 2;
      var h1 = this._tileHeight / 2;
      for (var i = 0; i < 4; i++) {
        var qsx = table[i][0];
        var qsy = table[i][1];
        var sx1 = (bx * 2 + qsx) * w1;
        var sy1 = (by * 2 + qsy) * h1;
        var dx1 = dx + (i % 2) * w1;
        var dy1 = dy + Math.floor(i / 2) * h1;
        if (isTable && (qsy === 1 || qsy === 5)) {
          var qsx2 = qsx;
          var qsy2 = 3;
          if (qsy === 1) {
            qsx2 = [0,3,2,1][qsx];
          }
          var sx2 = (bx * 2 + qsx2) * w1;
          var sy2 = (by * 2 + qsy2) * h1;
          bitmap.blt(source, sx2, sy2, w1, h1, dx1, dy1, w1, h1);
          dy1 += h1/2;
          bitmap.blt(source, sx1, sy1, w1, h1 / 2, dx1, dy1, w1, h1 / 2);
        } else {
          bitmap.blt(source, sx1, sy1, w1, h1, dx1, dy1, w1, h1);
        }
      }
    }
  };

  MapShotTileMap.prototype._drawNormalTile = function(bitmap, tileId, dx, dy) {
    var setNumber = 0;

    if (Tilemap.isTileA5(tileId)) {
      setNumber = 4;
    } else {
      setNumber = 5 + Math.floor(tileId / 256);
    }

    var w = this._tileWidth;
    var h = this._tileHeight;
    var sx = (Math.floor(tileId / 128) % 2 * 8 + tileId % 8) * w;
    var sy = (Math.floor(tileId % 256 / 8) % 16) * h;

    var source = this.bitmaps[setNumber];
    if (source) {
      bitmap.blt(source, sx, sy, w, h, dx, dy, w, h);
    }
  };

  MapShotTileMap.prototype._drawTableEdge = function(bitmap, tileId, dx, dy) {
    if (Tilemap.isTileA2(tileId)) {
      var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
      var kind = Tilemap.getAutotileKind(tileId);
      var shape = Tilemap.getAutotileShape(tileId);
      var tx = kind % 8;
      var ty = Math.floor(kind / 8);
      var setNumber = 1;
      var bx = tx * 2;
      var by = (ty - 2) * 3;
      var table = autotileTable[shape];

      if (table) {
        var source = this.bitmaps[setNumber];
        var w1 = this._tileWidth / 2;
        var h1 = this._tileHeight / 2;
        for (var i = 0; i < 2; i++) {
          var qsx = table[2 + i][0];
          var qsy = table[2 + i][1];
          var sx1 = (bx * 2 + qsx) * w1;
          var sy1 = (by * 2 + qsy) * h1 + h1/2;
          var dx1 = dx + (i % 2) * w1;
          var dy1 = dy + Math.floor(i / 2) * h1;
          bitmap.blt(source, sx1, sy1, w1, h1/2, dx1, dy1, w1, h1/2);
        }
      }
    }
  };

  Tilemap.prototype._drawTileOldStyle = function(bitmap, tileId, dx, dy) {
    if (Tilemap.isVisibleTile(tileId)) {
      if (Tilemap.isAutotile(tileId)) {
        MapShotTileMap.prototype._drawAutotile.call(this, bitmap, tileId, dx, dy);
      } else {
        MapShotTileMap.prototype._drawNormalTile.call(this, bitmap, tileId, dx, dy);
      }
    }
  };

  Tilemap.prototype._paintEverything = function(lowerBitmap, upperBitmap) {
    var tileCols = $dataMap.width;
    var tileRows = $dataMap.height;

    for (var y = 0; y < tileRows; y++) {
      for (var x = 0; x < tileCols; x++) {
        this._paintTilesOnBitmap(lowerBitmap, upperBitmap, x, y);
      }
    }

    if ($.Param.drawEvents !== false) {
      this._paintCharacters(lowerBitmap, 0);
      this._paintCharacters(lowerBitmap, 1);
      this._paintCharacters(upperBitmap, 2);
    }
  };

  Tilemap.prototype._paintLayered = function(groundBitmap, ground2Bitmap, lowerBitmap, upperLayer, shadowBitmap, lowerEvents, normalEvents, upperEvents) {
    var tileCols = $dataMap.width;
    var tileRows = $dataMap.height;

    for (var y = 0; y < tileRows; y++) {
      for (var x = 0; x < tileCols; x++) {
        this._paintTileOnLayers(groundBitmap, ground2Bitmap, lowerBitmap, upperLayer, shadowBitmap, x, y);
      }
    }

    this._paintCharacters(lowerEvents, 0);
    this._paintCharacters(normalEvents, 1);
    this._paintCharacters(upperEvents, 2);
  };

  Tilemap.prototype._paintCharacters = function(bitmap, priority) {
    this.children.forEach(function(child) {
      if (child instanceof Sprite_Character) {
        if (child._character !== null) {
          if (child._character instanceof Game_Player || child._character instanceof Game_Follower || child._character instanceof Game_Vehicle) return;
        }

        child.update();

        if (child._characterName === '' && child._tileId === 0) return;
        if (priority !== undefined && child._character._priorityType !== priority) return;

        var x = child.x - child._frame.width / 2 + $gameMap._displayX * $gameMap.tileWidth();
        var y = child.y - child._frame.height + $gameMap._displayY * $gameMap.tileHeight();

        bitmap.blt(child.bitmap, child._frame.x, child._frame.y, child._frame.width, child._frame.height, x, y, child._frame.width, child._frame.height);
      }
    });
  };

  Tilemap.prototype._paintTileOnLayers = function(groundBitmap, ground2Bitmap, lowerBitmap, upperBitmap, shadowBitmap, x, y) {
    var tableEdgeVirtualId = 10000;
    var mx = x;
    var my = y;
    var dx = (mx * this._tileWidth);
    var dy = (my * this._tileHeight);
    var lx = dx / this._tileWidth;
    var ly = dy / this._tileHeight;
    var tileId0 = this._readMapData(mx, my, 0);
    var tileId1 = this._readMapData(mx, my, 1);
    var tileId2 = this._readMapData(mx, my, 2);
    var tileId3 = this._readMapData(mx, my, 3);
    var shadowBits = this._readMapData(mx, my, 4);
    var upperTileId1 = this._readMapData(mx, my - 1, 1);

    if (groundBitmap !== undefined) {
      groundBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
    }

    if (ground2Bitmap !== undefined) {
      ground2Bitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
    }

    if (lowerBitmap !== undefined) {
      lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
    }

    if (upperBitmap !== undefined) {
      upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
    }

    if (shadowBitmap !== undefined) {
      shadowBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
    }

    var me = this;

    function drawTiles(bitmap, tileId, shadowBits, upperTileId1) {
      if (tileId < 0) {
        if ($.Param.drawAutoShadows && shadowBits !== undefined) {
          MapShotTileMap.prototype._drawShadow.call(me, bitmap, shadowBits, dx, dy);
        }
      } else if (tileId >= tableEdgeVirtualId) {
        MapShotTileMap.prototype._drawTableEdge.call(me, bitmap, upperTileId1, dx, dy);
      } else {
        me._drawTileOldStyle(bitmap, tileId, dx, dy);
      }
    }

    if (groundBitmap !== undefined) {
      drawTiles(groundBitmap, tileId0, undefined, upperTileId1);

      if (shadowBitmap !== undefined && tileId0 < 0) {
        drawTiles(shadowBitmap, tileId0, shadowBits, upperTileId1);
      }
    }

    if (ground2Bitmap !== undefined) {
      drawTiles(ground2Bitmap, tileId1, undefined, upperTileId1);

      if (shadowBitmap !== undefined && tileId1 < 0) {
        drawTiles(shadowBitmap, tileId1, shadowBits, upperTileId1);
      }
    }

    if (lowerBitmap !== undefined) {
      drawTiles(lowerBitmap, tileId2, undefined, upperTileId1);

      if (shadowBitmap !== undefined && tileId2 < 0) {
        drawTiles(shadowBitmap, tileId2, shadowBits, upperTileId1);
      }
    }

    if (upperBitmap !== undefined) {
      drawTiles(upperBitmap, tileId3, shadowBits, upperTileId1);

      if (shadowBitmap !== undefined && tileId3 < 0) {
        drawTiles(shadowBitmap, tileId3, shadowBits, upperTileId1);
      }
    }
  };

  Tilemap.prototype._paintTilesOnBitmap = function(lowerBitmap, upperBitmap, x, y) {
    var tableEdgeVirtualId = 10000;
    var mx = x;
    var my = y;
    var dx = (mx * this._tileWidth);
    var dy = (my * this._tileHeight);
    var lx = dx / this._tileWidth;
    var ly = dy / this._tileHeight;
    var tileId0 = this._readMapData(mx, my, 0);
    var tileId1 = this._readMapData(mx, my, 1);
    var tileId2 = this._readMapData(mx, my, 2);
    var tileId3 = this._readMapData(mx, my, 3);
    var shadowBits = this._readMapData(mx, my, 4);
    var upperTileId1 = this._readMapData(mx, my - 1, 1);
    var lowerTiles = [];
    var upperTiles = [];

    if (this._isHigherTile(tileId0)) {
      upperTiles.push(tileId0);
    } else {
      lowerTiles.push(tileId0);
    }
    if (this._isHigherTile(tileId1)) {
      upperTiles.push(tileId1);
    } else {
      lowerTiles.push(tileId1);
    }

    lowerTiles.push(-shadowBits);

    if (this._isTableTile(upperTileId1) && !this._isTableTile(tileId1)) {
      if (!Tilemap.isShadowingTile(tileId0)) {
        lowerTiles.push(tableEdgeVirtualId + upperTileId1);
      }
    }

    if (this._isOverpassPosition(mx, my)) {
      upperTiles.push(tileId2);
      upperTiles.push(tileId3);
    } else {
      if (this._isHigherTile(tileId2)) {
        upperTiles.push(tileId2);
      } else {
        lowerTiles.push(tileId2);
      }
      if (this._isHigherTile(tileId3)) {
        upperTiles.push(tileId3);
      } else {
        lowerTiles.push(tileId3);
      }
    }

    lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
    upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);

    for (var i = 0; i < lowerTiles.length; i++) {
      var lowerTileId = lowerTiles[i];
      if (lowerTileId < 0) {
        if ($.Param.drawAutoShadows) {
          MapShotTileMap.prototype._drawShadow.call(this, lowerBitmap, shadowBits, dx, dy);
        }
      } else if (lowerTileId >= tableEdgeVirtualId) {
        MapShotTileMap.prototype._drawTableEdge.call(this, lowerBitmap, upperTileId1, dx, dy);
      } else {
        this._drawTileOldStyle(lowerBitmap, lowerTileId, dx, dy);
      }
    }

    for (var j = 0; j < upperTiles.length; j++) {
      this._drawTileOldStyle(upperBitmap, upperTiles[j], dx, dy);
    }
  };

  $.saveMapshot = function() {
    if (!Utils.isNwjs()) return;

    var fs = require('fs');
    var path = $.Param.imagePath;

    try {
      fs.mkdir(path, function() {
        try{
          var fileName = path + '/' + $.baseFileName();
          var ext = $.fileExtension();
          var names = [fileName + ext];
          var regex = $.imageRegex();

          switch ($.Param.layerType) {
            case 1 :
              names = [
                fileName + ' Lower' + ext,
                fileName + ' Upper' + ext
              ];
              break;
            case 2 :
              names = [
                fileName + ' Ground' + ext,
                fileName + ' Ground 2' + ext,
                fileName + ' Lower' + ext,
                fileName + ' Upper' + ext,
                fileName + ' Shadows' + ext,
                fileName + ' Lower Events' + ext,
                fileName + ' Normal Events' + ext,
                fileName + ' Upper Events' + ext
              ];

              break;
            default :
              names = [fileName + ext];
              break;
          }

          var snaps = $.getMapshot();

          var callback = function(error) {
            if (error !== undefined && error !== null) {
              console.error('An error occured while saving the mapshot', error);
            }
          };

          for (var i = 0; i < names.length; i++) {
            var urlData = snaps[i].canvas.toDataURL($.imageType(), $.imageQuality());
            var base64Data = urlData.replace(regex, "");

            fs.writeFile(names[i], base64Data, 'base64', callback);
          }
        } catch (error) {
          if (error !== undefined && error !== null) {
            console.error('An error occured while saving the map shot:', error);
          }
        }
      });

      var nodePath = require('path');
      var longPath = nodePath.resolve(path);

      if (process.platform == 'win32' && $._openedFolder === undefined) {
        $._openedFolder = true;

        setTimeout(function(){
          var exec = require('child_process').exec;
          exec('explorer ' + longPath);
        }, 100);
      } else {
        $gameMessage.add('Mapshot saved to \n' + longPath.replace(/\\/g, '\\\\').match(/.{1,40}/g).join('\n'));
      }

    } catch (error) {
      if (error !== undefined && error !== null) {
        console.error('An error occured while saving the mapshot:', error);
      }
    }
  };

  $.onKeyUp = function(event) {
    if (event.keyCode == $.Param.keyCode) {
      if (SceneManager._scene instanceof Scene_Map) {
        $.saveMapshot();
      }
    }
  };

  document.addEventListener('keyup', $.onKeyUp);
})(OrangeMapshot);

Imported.OrangeMapshot = 1.7;