code:
//=============================================================================
// TemplateEvent.js
// ----------------------------------------------------------------------------
// Copyright (c) 2015-2017 Triacontane
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// ----------------------------------------------------------------------------
// Version
// 1.8.0 2018/05/27 セルフ変数のキーに数値ではなく文字列を使用できるよう修正
// 1.7.1 2017/09/01 スクリプトヘルプの誤記を修正
// 1.7.0 2017/08/29 プラグインコマンドで制御文字\sv[n]が利用できる機能を追加
// 1.6.1 2017/08/26 セルフ変数に文字列が入っている場合でも出現条件の注釈が正しく動作するよう修正
// 1.6.0 2017/08/19 セルフ変数の一括操作のコマンドおよびセルフ変数を外部から操作するスクリプトを追加
// 1.5.1 2017/08/15 文章のスクロール表示でセルフ変数が正しく表示できていなかった問題を修正
// 1.5.0 2017/08/14 セルフ変数の操作を「移動ルートの設定」からも行えるよう修正
// 1.4.1 2017/07/21 SAN_MapGenerator.jsとの競合を解消
// 1.4.0 2017/07/16 セルフ変数機能を追加
// 1.3.0 2017/07/07 固有処理呼び出し中にテンプレートイベントのIDと名称を取得できるスクリプトを追加
// 1.2.0 2017/06/09 設定を固有イベントで上書きする機能を追加。それに伴い既存のパラメータ名称を一部変更
// 1.1.2 2017/06/03 固有イベントのグラフィックで上書きした場合は、オプションと向き、パターンも固有イベントで上書きするよう変更
// 1.1.1 2017/05/25 場所移動直後にアニメパターンが一瞬だけ初期化されてしまう問題を修正
// 1.1.0 2017/04/22 テンプレートイベントIDに変数の値を指定できる機能を追加
// 1.0.2 2017/04/09 イベント生成系のプラグインで発生する可能性のある競合を解消
// 1.0.1 2016/06/28 固有イベントのページ数がテンプレートイベントのページ数より少ない場合に発生するエラーを修正
// 1.0.0 2016/06/12 初版
// ----------------------------------------------------------------------------
// [Blog]   : https://triacontane.blogspot.jp/
// [Twitter]: https://twitter.com/triacontane/
// [GitHub] : https://github.com/triacontane/
//=============================================================================

/*:
 * @plugindesc Template Event Plugin
 * @author triacontane
 *
 * @param TemplateMapId
 * @desc The map ID where the template event resides.
 * @default 1
 * @type number
 *
 * @param KeepEventId
 * @desc Maintain the event ID of the caller when invoking the map event.
 * @default false
 * @type boolean
 *
 * @param NoOverride
 * @desc Even if a graphic is specified for a specific event, it will not overwrite the setting.
 * @default false
 * @type boolean
 *
 * @help TemplateEvent.js[Template Event Plugin]
 *
 * You can template commonly used events.
 * Please define the template event in the map prepared exclusively.
 * Just by writing a predetermined description in the note of the actual event,
 * It can be replaced dynamically.
 *
 * You can also call up the source event from the template event.
 * It is effective when you want to do some unique processing,
 * such as treasure boxes and place movement events.
 * Describe the appearance and event processing of the common part
 * in the template event,
 * We describe only the unique part such as item acquisition and
 * location destination designation in the original event.
 *
 * It also provides a function to call an arbitrary map event like a common event.
 * Events to be called can be specified by ID and event name.
 *
 * Procedure
 * 1.Create a template map and place a template event.
 *
 * 2.Write a memo field of the event you want to replace
 * with the template event. Both ID and event name can be specified.
 * <TE:1>   It is replaced with the event of ID [1] of the template map.
 * <TE:aaa> It is replaced with the event of event name [aaa] of the template map.
 * <TE:\v[1]> It is replaced with the event of ID of template map [value of variable [1]].
 *
 * In principle, all settings except initial placement will be replaced with
 * template event settings If you specify graphics as an exception and when you
 * write a memo field (* 1)
 * Priority is given to the settings of unique events for the following settings.
 * Image
 * Autonomous Movement
 * Options
 * Priority
 * Trigger
 *
 * *1 Write it in the memo field of the unique event as follows.
 * <TEOverRide>
 *
 * Plugin Command
 *
 * TE_CALL_ORIGIN_EVENT [PageIndex]
 *  Call up the event processing of the replacement source. After processing is completed,
 *  it returns to the original processing. If you omit the page number, the running page
 *  number is applied as it is. It is effective only when described in the template event.
 *
 *  ex
 *  TE_CALL_ORIGIN_EVENT 1
 *
 * TE_CALL_MAP_EVENT [EventId] [PageIndex]
 *  Call up another event processing in the same map. After processing is completed,
 *  it returns to the original processing. If you specify an event ID other than a numeric value,
 *  it calls processing of an event that is treated as an event name and whose event name matches.
 *  It is valid even if it is described in the template event.
 *
 *  ex1
 *  TE_CALL_MAP_EVENT 5 1
 *
 *  ex2
 *  TE_CALL_MAP_EVENT aaa 1
 *
 * This plugin is released under the MIT License.
 */
/*:ja
 * @plugindesc テンプレートイベントプラグイン
 * @author トリアコンタン
 *
 * @param テンプレートマップID
 * @desc テンプレートイベントが存在するマップIDです。
 * @default 1
 * @type number
 *
 * @param イベントIDを維持
 * @desc マップイベントを呼び出す際に、呼び出し元のイベントIDを維持します。対象を「このイベント」にした際の挙動が変わります。
 * @default false
 * @type boolean
 *
 * @param 上書き禁止
 * @desc 固有イベントにグラフィックが指定されていた場合でも、設定の上書きを行いません。
 * @default false
 * @type boolean
 *
 * @help TemplateEvent.js[テンプレートイベントプラグイン]
 *
 * 汎用的に使用するイベントをテンプレート化できます。
 * テンプレートイベントは、専用に用意したマップに定義してください。
 * 実際のイベントのメモ欄に所定の記述をするだけで、テンプレートイベントと
 * 動的に置き換えることができます。
 *
 * またテンプレートイベントから置き換え元のイベントを呼び出すことができます。
 * 宝箱や場所移動イベント等、一部だけ固有の処理をしたい場合に有効です。
 * 外観や共通部分のイベント処理をテンプレートイベントに記述し、
 * アイテム入手や場所移動先指定など固有部分だけを元のイベントに記述します。
 *
 * 任意のマップイベントをコモンイベントのように呼び出す機能も提供します。
 * IDおよびイベント名で呼び出すイベントを指定可能です。
 *
 * 利用手順
 * 1.テンプレートマップを作成して、テンプレートイベントを配置します。
 *
 * 2.テンプレートイベントに置き換えたいイベントのメモ欄を記述します。
 *   IDとイベント名の双方が指定可能です。
 * <TE:1>   テンプレートマップのID[1]のイベントに置き換わります。
 * <TE:aaa> テンプレートマップのイベント名[aaa]のイベントに置き換わります。
 * <TE:\v[1]> テンプレートマップのID[変数[1]の値]のイベントに置き換わります。
 *
 * 原則、初期配置以外の全設定はテンプレートイベントの設定に置き換わりますが
 * 例外としてグラフィックを指定していた場合とメモ欄(※1)を記述した場合は
 * 以下の設定について固有イベントの設定を優先します。
 * ・画像
 * ・自律移動
 * ・オプション
 * ・プライオリティ
 * ・トリガー
 *
 * ※1 固有イベントのメモ欄に以下の通り記述します。
 * <TE上書き>
 * <TEOverRide>
 *
 * ・セルフ変数機能
 * イベントに対してセルフ変数（そのイベント専用の変数）を定義できます。
 * プラグインコマンドから操作し、文章の表示やイベント出現条件として使用可能です。
 *
 * 「文章の表示」で使用する場合
 * 制御文字「\sv[n](n:インデックス)」で表示できます。
 *
 * 「イベント出現条件」で使用する場合
 * 対象ページのイベントコマンドの先頭を「注釈」にして
 * 以下の書式で条件を指定してください。複数指定も可能です。
 *
 * \TE{条件}
 *
 * 条件はJavaScriptとしてで記述し、制御文字が使用可能です。
 * 指定例：
 * \TE{\sv[1] >= 3}      # セルフ変数[1]が3以上の場合
 * \TE{\sv[2] === \v[1]} # セルフ変数[2]が変数[1]と等しい場合
 * \TE{\sv[3] === 'AAA'} # セルフ変数[3]が'AAA'と等しい場合
 *
 * 「条件分岐」などのスクリプトで使用する場合
 * 以下のスクリプトで指定したインデックスのセルフ変数が取得できます。
 * this.getSelfVariable(n)
 * 指定例：
 * this.getSelfVariable(1) !== 0 # セルフ変数[1]が3以上の場合
 *
 * プラグインコマンド詳細
 *  イベントコマンド「プラグインコマンド」から実行。
 *  （パラメータの間は半角スペースで区切る）
 *
 * TE固有イベント呼び出し [ページ番号]
 * TE_CALL_ORIGIN_EVENT [ページ番号]
 *  置き換え元のイベント処理を呼び出します。処理完了後、元の処理に戻ります。
 *  ページ番号を省略すると、実行中のページ番号がそのまま適用されます。
 *  テンプレートイベントに記述した場合のみ有効です。
 *
 *  例1:置き換え元イベントの1ページ目を呼び出します。
 *  TE固有イベント呼び出し 1
 *
 * TEマップイベント呼び出し [イベントID] [ページ番号]
 * TE_CALL_MAP_EVENT [イベントID] [ページ番号]
 *  同一マップ内の別イベント処理を呼び出します。処理完了後、元の処理に戻ります。
 *  イベントIDに数値以外を指定すると、イベント名として扱われ
 *  イベント名が一致するイベントの処理を呼び出します。
 *  テンプレートイベントに記述した場合以外でも有効です。
 *
 *  例1:ID[5]のイベントの1ページ目を呼び出します。
 *  TEマップイベント呼び出し 5 1
 *
 *  例2:[aaa]という名前のイベントの1ページ目を呼び出します。
 *  TEマップイベント呼び出し aaa 1
 *
 * TEセルフ変数の操作 [インデックス] [操作種別] [オペランド]
 * TE_SET_SELF_VARIABLE [インデックス] [操作種別] [オペランド]
 *  セルフ変数を操作します。
 *  インデックス : 操作対象のセルフ変数のインデックスです。1以上の数値を指定
 *  操作種別     : 操作種別です。以下の通り指定してください。
 *   0 : 代入
 *   1 : 加算
 *   2 : 減算
 *   3 : 乗算
 *   4 : 除算
 *   5 : 剰余
 *  オペランド   : 設定値です。数値を指定してください。
 * ※セルフ変数に数値以外を設定したい場合は、スクリプトで指定してください。
 *
 *  例1:インデックス[1]のセルフ変数に値[100]を代入します。
 *  TE_SET_SELF_VARIABLE 1 0 100
 *
 *  例2:インデックス[3]のセルフ変数から値[50]を減算します。
 *  TE_SET_SELF_VARIABLE 3 2 50
 *
 *  例2:インデックス[5]のセルフ変数に値[セルフ変数[1]の値]を加算します。
 *  TE_SET_SELF_VARIABLE 5 1 \sv[1]
 *
 * TEセルフ変数の一括操作 [開始INDEX] [終了INDEX] [操作種別] [オペランド]
 * TE_SET_RANGE_SELF_VARIABLE [開始INDEX] [終了INDEX] [操作種別] [オペランド]
 *  セルフ変数を一括操作します。
 *
 * 本プラグインのすべてのプラグインコマンドで制御文字\sv[n]を使用できます。
 *
 * ・スクリプト（イベントコマンドのスクリプト、変数の操作から実行）
 * 固有処理呼び出し中にテンプレートイベントのIDと名称を取得します。
 *  this.character(0).getTemplateId();
 *  this.character(0).getTemplateName();
 *
 * 指定したインデックスのセルフ変数を取得します。
 *  this.getSelfVariable(index);
 *
 * セルフ変数に値を設定します。
 * このスクリプトは「移動ルートの設定」でも実行できます。
 * formulaFlgをtrueに設定すると、operandを計算式として評価します。
 *  this.controlSelfVariable(index, type, operand, formulaFlg);
 *
 * セルフ変数に値を一括設定します。
 * このスクリプトは「移動ルートの設定」でも実行できます。
 *  this.controlSelfVariableRange(start, end, type, operand, formulaFlg);
 *
 * 外部のイベントのセルフ変数を操作します。
 *  $gameSelfSwitches.setVariableValue([マップID, イベントID, INDEX], 設定値);
 *
 * 外部のイベントのセルフ変数を取得します。
 *  $gameSelfSwitches.getVariableValue([マップID, イベントID, INDEX]);
 *
 * SAN_MapGenerator.jsと組み合わせる場合
 * このプラグインをSAN_MapGenerator.jsより下に定義してください。
 *
 * 利用規約：
 *  作者に無断で改変、再配布が可能で、利用形態（商用、18禁利用等）
 *  についても制限はありません。
 *  このプラグインはもうあなたのものです。
 */

var $dataTemplateEvents = null;

(function () {
    'use strict';
    var pluginName = 'TemplateEvent';
    var metaTagPrefix = 'TE';

    var getParamNumber = function (paramNames, min, max) {
        var value = getParamOther(paramNames);
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return (parseInt(value) || 0).clamp(min, max);
    };

    var getParamBoolean = function (paramNames) {
        var value = getParamOther(paramNames);
        return (value || '').toUpperCase() === 'ON' || (value || '').toUpperCase() === 'TRUE';
    };

    var getParamOther = function (paramNames) {
        if (!Array.isArray(paramNames)) paramNames = [paramNames];
        for (var i = 0; i < paramNames.length; i++) {
            var name = PluginManager.parameters(pluginName)[paramNames[i]];
            if (name) return name;
        }
        return null;
    };

    var getMetaValue = function (object, name) {
        var metaTagName = metaTagPrefix + (name ? name : '');
        return object.meta.hasOwnProperty(metaTagName) ? object.meta[metaTagName] : undefined;
    };

    var getMetaValues = function (object, names) {
        if (!object) return undefined;
        if (!Array.isArray(names)) return getMetaValue(object, names);
        for (var i = 0, n = names.length; i < n; i++) {
            var value = getMetaValue(object, names[i]);
            if (value !== undefined) return value;
        }
        return undefined;
    };

    var getArgNumber = function (arg, min, max) {
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return (parseInt(arg) || 0).clamp(min, max);
    };

    var convertEscapeCharacters = function (text) {
        if (isNotAString(text)) 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 () {
            var actor = parseInt(arguments[1]) >= 1 ? $gameActors.actor(parseInt(arguments[1])) : null;
            return actor ? actor.name() : '';
        }.bind(this));
        text = text.replace(/\x1bP\[(\d+)]/gi, function () {
            var actor = parseInt(arguments[1]) >= 1 ? $gameParty.members()[parseInt(arguments[1]) - 1] : null;
            return actor ? actor.name() : '';
        }.bind(this));
        text = text.replace(/\x1bG/gi, TextManager.currencyUnit);
        return text;
    };

    var isNotAString = function (args) {
        return String(args) !== args;
    };

    var isExistPlugin = function (pluginName) {
        return Object.keys(PluginManager.parameters(pluginName)).length > 0;
    };

    var convertAllArguments = function (args) {
        return args.map(function (arg) {
            return convertEscapeCharacters(arg);
        });
    };

    var setPluginCommand = function (commandName, methodName) {
        pluginCommandMap.set(metaTagPrefix + commandName, methodName);
    };

    var pluginCommandMap = new Map();
    setPluginCommand('固有イベント呼び出し', 'execCallOriginEvent');
    setPluginCommand('_CALL_ORIGIN_EVENT', 'execCallOriginEvent');
    setPluginCommand('マップイベント呼び出し', 'execCallMapEvent');
    setPluginCommand('_CALL_MAP_EVENT', 'execCallMapEvent');
    setPluginCommand('セルフ変数の操作', 'execControlSelfVariable');
    setPluginCommand('_SET_SELF_VARIABLE', 'execControlSelfVariable');
    setPluginCommand('セルフ変数の一括操作', 'execControlSelfVariableRange');
    setPluginCommand('_SET_RANGE_SELF_VARIABLE', 'execControlSelfVariableRange');

    //=============================================================================
    // パラメータの取得と整形
    //=============================================================================
    var paramTemplateMapId = getParamNumber(['TemplateMapId', 'テンプレートマップID'], 1);
    var paramKeepEventId = getParamBoolean(['KeepEventId', 'イベントIDを維持']);
    var paramNoOverride = getParamBoolean(['NoOverride', '上書き禁止']);

    //=============================================================================
    // Game_Interpreter
    //  プラグインコマンドを追加定義します。
    //=============================================================================
    var _Game_Interpreter_command101 = Game_Interpreter.prototype.command101;
    Game_Interpreter.prototype.command101 = function () {
        if (!$gameMessage.isBusy()) {
            $gameMessage.setEventId(this._eventId);
        }
        return _Game_Interpreter_command101.apply(this, arguments);
    };

    var _Game_Interpreter_command105 = Game_Interpreter.prototype.command105;
    Game_Interpreter.prototype.command105 = function () {
        if (!$gameMessage.isBusy()) {
            $gameMessage.setEventId(this._eventId);
        }
        return _Game_Interpreter_command105.apply(this, arguments);
    };

    var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.apply(this, arguments);
        var pluginCommandMethod = pluginCommandMap.get(command.toUpperCase());
        if (pluginCommandMethod) {
            this[pluginCommandMethod](this.convertAllSelfVariables(convertAllArguments(args)));
        }
    };

    Game_Interpreter.prototype.execCallOriginEvent = function (args) {
        this.callOriginEvent(getArgNumber(args[0]));
    };

    Game_Interpreter.prototype.execCallMapEvent = function (args) {
        var pageIndex = getArgNumber(args[1], 1);
        var eventId = getArgNumber(args[0]);
        if ($gameMap.event(eventId)) {
            this.callMapEventById(pageIndex, eventId);
        } else if (args[0] !== '') {
            this.callMapEventByName(pageIndex, args[0]);
        } else {
            this.callMapEventById(pageIndex, this._eventId);
        }
    };

    Game_Interpreter.prototype.execControlSelfVariable = function (args) {
        var selfIndex = getArgNumber(args[0], 0) || args[0];
        var controlType = getArgNumber(args[1], 0, 5);
        var operand = isNaN(Number(args[2])) ? args[2] : getArgNumber(args[2]);
        this.controlSelfVariable(selfIndex, controlType, operand, false);
    };

    Game_Interpreter.prototype.execControlSelfVariableRange = function (args) {
        var selfStartIndex = getArgNumber(args[0], 0) || args[0];
        var selfEndIndex = getArgNumber(args[1], 0) || args[0];
        var controlType = getArgNumber(args[2], 0, 5);
        var operand = isNaN(Number(args[3])) ? args[3] : getArgNumber(args[3]);
        this.controlSelfVariableRange(selfStartIndex, selfEndIndex, controlType, operand, false);
    };

    Game_Interpreter.prototype.callOriginEvent = function (pageIndex) {
        var event = $gameMap.event(this._eventId);
        if (event && event.hasTemplate()) {
            this.setupAnotherList(null, event.getOriginalPages(), pageIndex);
        }
    };

    Game_Interpreter.prototype.callMapEventById = function (pageIndex, eventId) {
        var event = $gameMap.event(eventId);
        if (event) {
            this.setupAnotherList(paramKeepEventId ? null : eventId, event.getPages(), pageIndex);
        }
    };

    Game_Interpreter.prototype.callMapEventByName = function (pageIndex, eventName) {
        var event = DataManager.searchDataItem($dataMap.events, 'name', eventName);
        if (event) {
            this.setupAnotherList(paramKeepEventId ? null : event.id, event.pages, pageIndex);
        }
    };

    Game_Interpreter.prototype.setupAnotherList = function (eventId, pages, pageIndex) {
        var page = pages[pageIndex - 1 || this._pageIndex] || pages[0];
        if (!eventId) eventId = this.isOnCurrentMap() ? this._eventId : 0;
        this.setupChild(page.list, eventId);
    };

    Game_Interpreter.prototype.controlSelfVariable = function (index, type, operand, formulaFlg) {
        var character = this.character(0);
        if (character) {
            character.controlSelfVariable(index, type, operand, formulaFlg);
        }
    };

    Game_Interpreter.prototype.controlSelfVariableRange = function (startIndex, endIndex, type, operand, formulaFlg) {
        var character = this.character(0);
        if (character) {
            character.controlSelfVariableRange(startIndex, endIndex, type, operand, formulaFlg);
        }
    };

    Game_Interpreter.prototype.getSelfVariable = function (selfVariableIndex) {
        var character = this.character(0);
        return character ? character.getSelfVariable(selfVariableIndex) : 0;
    };

    Game_Interpreter.prototype.convertAllSelfVariables = function (args) {
        return args.map(function (arg) {
            return $gameSelfSwitches.convertSelfVariableCharacter(this._eventId, arg, false);
        }, this);
    };

    //=============================================================================
    // Game_Message
    //  メッセージ表示中のイベントIDを保持します。
    //=============================================================================
    var _Game_Message_clear = Game_Message.prototype.clear;
    Game_Message.prototype.clear = function () {
        _Game_Message_clear.apply(this, arguments);
        this._eventId = 0;
    };

    Game_Message.prototype.setEventId = function (id) {
        this._eventId = id;
    };

    Game_Message.prototype.getEventId = function () {
        return this._eventId;
    };

    //=============================================================================
    // Game_System
    //  ロード完了時に必要ならセルフ変数を初期化します。
    //=============================================================================
    var _Game_System_onAfterLoad = Game_System.prototype.onAfterLoad;
    Game_System.prototype.onAfterLoad = function () {
        _Game_System_onAfterLoad.apply(this, arguments);
        $gameSelfSwitches.clearVariableIfNeed();
    };

    //=============================================================================
    // Game_SelfSwitches
    //  セルフ変数を追加します。
    //=============================================================================
    var _Game_SelfSwitches_initialize = Game_SelfSwitches.prototype.initialize;
    Game_SelfSwitches.prototype.initialize = function () {
        _Game_SelfSwitches_initialize.apply(this, arguments);
        this.clearVariable();
    };

    Game_SelfSwitches.prototype.clearVariable = function () {
        this._variableData = {};
    };

    Game_SelfSwitches.prototype.clearVariableIfNeed = function () {
        if (!this._variableData) {
            this.clearVariable();
        }
    };

    Game_SelfSwitches.prototype.getVariableValue = function (key) {
        return this._variableData.hasOwnProperty(key) ? this._variableData[key] : 0;
    };

    Game_SelfSwitches.prototype.setVariableValue = function (key, value) {
        if (this._variableData[key] === value) {
            return;
        }
        if (value !== undefined && value !== 0) {
            this._variableData[key] = value;
        } else {
            delete this._variableData[key];
        }
        this.onChange();
    };

    Game_SelfSwitches.prototype.makeSelfVariableKey = function (eventId, index) {
        return eventId > 0 ? [$gameMap.mapId(), eventId, index] : null;
    };

    Game_SelfSwitches.prototype.convertSelfVariableCharacter = function (eventId, text, scriptFlag) {
        text = text.replace(/\x1bSV\[(\w+)]/gi, function () {
            var key = this.makeSelfVariableKey(eventId, arguments[1]);
            var value = this.getVariableValue(key);
            return isNotAString(value) || !scriptFlag ? value : '\'' + value + '\'';
        }.bind(this));
        return text;
    };

    //=============================================================================
    // Game_Event
    //  テンプレートイベントマップをロードしてグローバル変数に保持します。
    //=============================================================================
    var _Game_Event_initialize = Game_Event.prototype.initialize;
    Game_Event.prototype.initialize = function (mapId, eventId) {
        var event = $dataMap.events[eventId];
        this.setTemplate(event);
        _Game_Event_initialize.apply(this, arguments);
        if (this.hasTemplate()) {
            this.setPosition(event.x, event.y);
            this.refreshBushDepth();
        }
    };

    var _Game_Event_setupPageSettings = Game_Event.prototype.setupPageSettings;
    Game_Event.prototype.setupPageSettings = function () {
        if (this.hasTemplate() && this.isOverrideProperty()) {
            this._needOriginalPage = true;
        }
        _Game_Event_setupPageSettings.apply(this, arguments);
        this._needOriginalPage = false;
    };

    var _Game_Event_page = Game_Event.prototype.page;
    Game_Event.prototype.page = function () {
        return this._needOriginalPage ? this.getOriginalPage() : _Game_Event_page.apply(this, arguments);
    };

    Game_Event.prototype.isOverrideProperty = function () {
        var page = this.getOriginalPage();
        if (!page) return false;
        return (!paramNoOverride && (page.image.tileId > 0 || page.image.characterName)) || this._override;
    };

    Game_Event.prototype.setTemplate = function (event) {
        var value = getMetaValues(event, '');
        if (value) {
            var templateId = getArgNumber(value, 0, $dataTemplateEvents.length - 1);
            if (!templateId) {
                var template = DataManager.searchDataItem($dataTemplateEvents, 'name', value);
                if (template) templateId = template.id;
            }
            this._templateId = templateId;
            this._override = !!getMetaValues(event, ['OverRide', '上書き']);
        } else {
            this._templateId = 0;
            this._override = false;
        }
    };

    Game_Event._userScripts = ['getTemplateId', 'getTemplateName'];
    Game_Event.prototype.getTemplateId = function () {
        return this._templateId;
    };

    Game_Event.prototype.getTemplateName = function () {
        return this.hasTemplate() ? $dataTemplateEvents[this._templateId].name : '';
    };

    Game_Event.prototype.hasTemplate = function () {
        return this._templateId > 0;
    };

    var _Game_Event_event = Game_Event.prototype.event;
    Game_Event.prototype.event = function () {
        return this.hasTemplate() ? $dataTemplateEvents[this._templateId] : _Game_Event_event.apply(this, arguments);
    };

    Game_Event.prototype.getOriginalPages = function () {
        var eventId = isExistPlugin('SAN_MapGenerator') ? this._dataEventId : this._eventId;
        return $dataMap.events[eventId].pages;
    };

    Game_Event.prototype.getOriginalPage = function () {
        return this.getOriginalPages()[this._pageIndex];
    };

    Game_Event.prototype.getPages = function () {
        return this.event().pages;
    };

    var _Game_Event_meetsConditions = Game_Event.prototype.meetsConditions;
    Game_Event.prototype.meetsConditions = function (page) {
        return _Game_Event_meetsConditions.apply(this, arguments) && this.meetsConditionsForSelfVariable(page);
    };

    Game_Event.prototype.meetsConditionsForSelfVariable = function (page) {
        var comment = this.getStartComment(page);
        return !(comment && this.execConditionScriptForSelfVariable(comment) === false);
    };

    Game_Event.prototype.getStartComment = function (page) {
        return page.list.filter(function (command) {
            return command && (command.code === 108 || command.code === 408);
        }).reduce(function (prev, command) {
            return prev + command.parameters[0];
        }, '');
    };

    Game_Event.prototype.execConditionScriptForSelfVariable = function (note) {
        var scripts = [];
        note.replace(/\\TE{(.+?)}/gi, function () {
            scripts.push(arguments[1]);
        }.bind(this));
        return scripts.every(function (script) {
            script = convertEscapeCharacters(script);
            script = $gameSelfSwitches.convertSelfVariableCharacter(this._eventId, script, true);
            return eval(script);
        }, this);
    };

    Game_Event.prototype.getSelfVariableKey = function (index) {
        return $gameSelfSwitches.makeSelfVariableKey(this._eventId, index);
    };

    Game_Event.prototype.controlSelfVariable = function (index, type, operand, formulaFlg) {
        var key = this.getSelfVariableKey(index);
        if (key) {
            this.operateSelfVariable(key, type, formulaFlg ? eval(operand) : operand);
        }
    };

    Game_Event.prototype.controlSelfVariableRange = function (startIndex, endIndex, type, operand, formulaFlg) {
        for (var index = startIndex; index <= endIndex; index++) {
            this.controlSelfVariable(index, type, operand, formulaFlg);
        }
    };

    Game_Event.prototype.getSelfVariable = function (selfVariableIndex) {
        var key = this.getSelfVariableKey(selfVariableIndex);
        return $gameSelfSwitches.getVariableValue(key);
    };

    Game_Event.prototype.operateSelfVariable = function (key, operationType, value) {
        var oldValue = $gameSelfSwitches.getVariableValue(key);
        switch (operationType) {
            case 0:  // Set
                $gameSelfSwitches.setVariableValue(key, oldValue = value);
                break;
            case 1:  // Add
                $gameSelfSwitches.setVariableValue(key, oldValue + value);
                break;
            case 2:  // Sub
                $gameSelfSwitches.setVariableValue(key, oldValue - value);
                break;
            case 3:  // Mul
                $gameSelfSwitches.setVariableValue(key, oldValue * value);
                break;
            case 4:  // Div
                $gameSelfSwitches.setVariableValue(key, oldValue / value);
                break;
            case 5:  // Mod
                $gameSelfSwitches.setVariableValue(key, oldValue % value);
                break;
        }
    };

    //=============================================================================
    // DataManager
    //  データ検索用の共通処理です。
    //=============================================================================
    if (!DataManager.searchDataItem) {
        DataManager.searchDataItem = function (dataArray, columnName, columnValue) {
            var result = 0;
            dataArray.some(function (dataItem) {
                if (dataItem && dataItem[columnName] === columnValue) {
                    result = dataItem;
                    return true;
                }
                return false;
            });
            return result;
        };
    }

    var _Window_Base_convertEscapeCharacters = Window_Base.prototype.convertEscapeCharacters;
    Window_Base.prototype.convertEscapeCharacters = function (text) {
        text = _Window_Base_convertEscapeCharacters.apply(this, arguments);
        return $gameSelfSwitches.convertSelfVariableCharacter($gameMessage.getEventId(), text, false);
    };

    //=============================================================================
    // Scene_Boot
    //  テンプレートイベントマップをロードしてグローバル変数に保持します。
    //=============================================================================
    var _Scene_Boot_create = Scene_Boot.prototype.create;
    Scene_Boot.prototype.create = function () {
        _Scene_Boot_create.apply(this, arguments);
        DataManager.loadMapData(paramTemplateMapId);
    };

    var _Scene_Boot_isReady = Scene_Boot.prototype.isReady;
    Scene_Boot.prototype.isReady = function () {
        if (!this._mapLoaded && DataManager.isMapLoaded()) {
            this.onTemplateMapLoaded();
            this._mapLoaded = true;
        }
        return this._mapLoaded && _Scene_Boot_isReady.apply(this, arguments);
    };

    Scene_Boot.prototype.onTemplateMapLoaded = function () {
        $dataTemplateEvents = $dataMap.events;
        $dataMap = undefined;
    };
})();


code:
//=============================================================================
// Terrax Plugins - Lighting system
// TerraxLighting.js
// Version: 1.2.7
//=============================================================================
//
// This script overwrites the following core scripts.
// Scene_Load.prototype.onSavefileOk
// Game_CharacterBase.prototype.updateMove
// Spriteset_Map.prototype.createLowerLayer

//=============================================================================
/*:
* @plugindesc v1.2.7 Creates an extra layer that darkens a map and adds lightsources!
* @author Terrax
*
* @param Player radius
* @desc Adjust the light radius around the player
* Default: 300
* @default 300
*
* @param Reset Lights
* @desc Resets the light switches each map
* Default: No
* @default No
*
* @param Save DaynightHours
* @desc Game variable the time of day (0-23) can be stored in
* Default: 0
* @default 0
*
* @param Save DaynightMinutes
* @desc Game variable the time of day (0-59) can be stored in
* Default: 0
* @default 0
*
* @param Save DaynightSeconds
* @desc Game variable the time of day (0-59) can be stored in
* Default: 0
* @default 0
*
* @param Flashlight offset
* @desc Increase this setting to move up the flashlight for double height characters.
* Default: 0
* @default 0
*
* @param Screensize X
* @desc Increase if your using a higher screen resolution then the default
* Default : 866
* @default 866
*
* @param Screensize Y
* @desc Increase if your using a higher screen resolution then the default
* Default : 630
* @default 630
*
* @param Kill Switch
* @desc Possible values A,B,C,D. If Selfswitch X is switched ON, the events lightsource will be disabled.
* Default : No
* @default No
*
* @help
* To activate the script in an area, do the following:
* 1. Put an event switch into the map.
* 2. In the 'Note' field (Next to the name) put the following text :
* Light 250 #FFFFFF
* - Light activates the script
* - 250 is the lightradius of the object
* - #FFFFFF is the lightcolor (white in this case)
* 3. You're done, its that simple.
*
* You can add two optional commands for brightness and direction
* Light 200 #FFFFFF B50 increases the brightness with 50%. Value between 0 and 99.
* Light 200 #FFFFFF D1 will give half a lightglobe for lightsources placed on walls.
* 1. For lights on north walls, light will face down.
* 2. For lights on east walls, light will face west.
* 3. For lights on south walls, light will face north.
* 4. For lights on west walls, light will face east.
*
* To alter the player radius in game use the following plugin command :
* Light radius 200 #FFFFFF  (to change the radius and the color)
* If you want to change the player radius slowly over time (like a dying torch)
* use the command 'Light radiusgrow 200 #FFFFFF'
* You can alter the brightness of the players lightsource by adding:
* 'Light radius 200 #FFFFFF B70' (Brightness values between 0 and 99, 0 is default)
*
* To turn on and off lightsources in the game, do the following:
* Give the lightsource the normal def :  Light 250 #FFFFFF and an extra number
* so it becomes 'Light 250 #FFFFFF 1'
* (If your using the optional brightness and direction place it after those (Light 250 #FFFFFF B50 D2 1)
* To turn on this light use plugin command : 'Light on 1'.
* The plugin command will also trigger SelfSwitch 'D' on the targeted light(s).
* To turn off the light use plugin command : 'Light off 1'.
* You can reset the switches each map with the option or manualy by
* the plugin command 'Light switch reset'
* You can also turn off lights with the kill-selfswitch defined in the parameters.
*
* Replacing the 'Light' keyworld with 'Fire' will give the lights a subtle flicker
* You can configure the fire effect with the plugin command 'SetFire 7 10'
* Where 7 is the radius change and 10 is the shift in color from red to yellow.
*
* To completly turn off the script use : 'Light deactivate'
* To turn it on again use the command: 'Light activate'
*
* To activate a day-night cycle on a map, put in a trigger with 'DayNight' in an event note
* or in the map note.
* Plugin command 'Daynight speed 10' changes the speed.
* Speed 10 means it takes 10 seconds to to pass one hour in game (probably to fast)
* Plugin command 'Daynight hour 16 30' sets the hour to 16:30 hours
* Each hour has its own color value.
* Plugin command 'Daynight color 0 #222222' changes 0:00 hours to color value '#222222'
* You can add time with the plugin command 'Daynight add 8 30' (this adds 8 hours and 30 minutes)
*
* If you want to use the time of day to trigger effects (like turning on lights when it gets dark)
* you can use the parameters 'Save DaynightHours','Save DaynightMinutes','Save DaynightSeconds'
* The default is 0, which means its off.
* If you set it to a value,5 for example, it will store the daynight value inside game variable 5.
* You can then use that variable to trigger lights.
* To help syncing/debugging the time system you can use scriptcommand 'daynight debug' to display the current time.
* If you want to go 'alien world' and stuff, you can change the number of hours in a day with
* script command 'daynight hoursinday 48' (for 48 hours in day, don't forget to fill in the hour values)
*
* As an alternative to the daynight cycle you can use the tint system. If you want to use another plugin for the
* day/night cycle, the tint option is probably best to use.
* The plugin command 'Tint set #333333' will make the room less dark.
* The plugin command 'Tint fade #777777 5' will fade the color from the current color to the new, the last
* number (5) is the speed of the fade, were 1 is a fast fade and 20 is a very slow one.
* If an area has a daynight cycle system, the tint system is disabled.
*
* To use a flashlight effect use 'Flashlight on 8 12 #FFFFFF 3' and 'Flashlight off'
* The arguments are optional (8=beamlength, 12=beamwidth, #FFFFFF=color, 3=beam density)
* Events can also use the flashlight effect. Use 'Flashlight 8 12 #888888 1 2' in the note-tag.
* where 8 is the length of the flashlights beam and 12 is the width of the beam. The last numbers are
* optional and can be used to turn the NPC's flashlight on or off and set the direction of the beam
* if the event is not moving (1=up, 2=right, 3=down, 4=left) the default is down.
*
* TileLight and RegionLight settings
* To create lightsources without using events you can use the following plugin command.
* TileLight 1 ON #FFFFFF 150  Will create a lightsource (color #FFFFFF radius 150) on all tiles with tile-tag 1.
* TileRegion 1 ON #FFFFFF 150 Will create a lightsource on all tiles with region-number 1.
* You can increase the brightness of a lightsource with the optional TileRegion 1 ON #FFFFFF 150 B50  (for 50% increased brightness)
* TileLight 1 OFF will turn off the lights on tile-tag 1 again
* TileRegion 1 OFF will turn off the lights on region-number 1 again
* TileFire and RegionFire works the same as TileLight, but with fire effect.
* Make sure your map still has at least one event with lights in it, otherwise the script will not run.
*
* TileBlock and RegionBlock settings
* To block lights on certain tiles (roofs for instance) you can use the following plugin command.
* TileBlock 1 ON #000000  Will block light on tiles with tile-tag 1.
* RegionBlock 1 ON #000000 Will block lights on tiles with region-number 1.
* TileBlock 1 OFF and TileRegion 1 OFF turns off the blocking again.
* To darken but not completly block light use a slightly higher color setting (#333333) for instance.
* This function does not raytrace. If the players lightradius is bigger then the blocking tiles the
* light will show on the other side. For the best effect keep the lightradius a bit smaller then the block section.
*
* Released under the MIT license,
* if used for commercial projects feel free to make a donation or
* better yet, give me a free version of what you have created.
* e-mail : fox(AT)caiw.nl / terraxz2 on steam.
*
* Special thanks to everyone in the rpgmakerweb community for idea's, support and interest.
*/
//=============================================================================
//  ps.. if my code looks funky, i'm an old guy..
// object orientated programming bugs the hell out of me.
var Imported = Imported || {};
Imported.TerraxLighting = true;

// These are global variables so they can be used by other daynight plugins

var Terrax_tint_speed = 60;
var Terrax_tint_target = '#000000';

// Global so it can be called from other plugins (compatability)

(function () {
	var lightarray_id = [];
	var tilearray = [];
	var lightarray_state = [];
	var lightgrow_value;
	var lightgrow_target;
	var lightgrow_speed;
	var oldmap = 0;
	var oldseconds = 0;
	var playercolor = '#FFFFFF';
	var playerflicker = false;
	var playerbrightness = 0.0;
	var flickerradiusshift = 7;
	var flickercolorshift = 10;
	var playerflashlight = false;
	var flashlightlength = 8;
	var flashlightwidth = 12;
	var flashlightdensity = 3;
	var scriptactive = true;
	var daynightspeed = 10;
	var daynightcycle = 17;
	var daynighttimer = 0;
	var daynightstop = false;
	var daynightcolors = ['#000000', '#000000', '#000000', '#000000',
		'#000000', '#000000', '#666666', '#AAAAAA',
		'#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
		'#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF',
		'#FFFFFF', '#FFFFFF', '#AAAAAA', '#666666',
		'#000000', '#000000', '#000000', '#000000'];
	var daynightHoursInDay = 24;
	var parameters = PluginManager.parameters('TerraxLighting');
	var player_radius = Number(parameters['Player radius'] || 300);
	var reset_each_map = parameters['Reset Lights'] || No;
	var daynightsave = Number(parameters['Save DaynightHours'] || 10);
	var daynightsavemin = Number(parameters['Save DaynightMinutes'] || 11);
	var daynightsavesec = Number(parameters['Save DaynightSeconds'] || 12);
	var flashlightoffset = Number(parameters['Flashlight offset'] || 0);
	var killswitch = parameters['Kill Switch'] || No;

	var maxX = Number(parameters['Screensize X'] || 866);
	var maxY = Number(parameters['Screensize Y'] || 630);

	var daynightdebug = false;

	var tint_value = '#000000';
	var tint_timer = 0;
	//var tint_speed = 60;
	//var tint_target = '#000000';
	var tint_oldseconds = 0;

	var move_event_x = [];
	var move_event_y = [];
	var move_event_id = [];
	var move_event_dir = [];

	var tiletest = false;

	var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
	Game_Interpreter.prototype.pluginCommand = function (command, args) {
		_Game_Interpreter_pluginCommand.call(this, command, args);
		command = command.toLowerCase();

		// ************* TILE TAGS ***************

		if (command === 'tileblock' || command === 'regionblock' || command === 'tilelight' || command === 'regionlight' || command === 'tilefire' || command === 'regionfire') {
			var tiletype = 0;
			if (command === 'tileblock') { tiletype = 1; }
			if (command === 'regionblock') { tiletype = 2; }
			if (command === 'tilelight') { tiletype = 3; }
			if (command === 'regionlight') { tiletype = 4; }
			if (command === 'tilefire') { tiletype = 5; }
			if (command === 'regionfire') { tiletype = 6; }
			var tilenumber = Number(args[0]);
			var tile_on = 0;
			if (args[1] === 'on' || args[1] === 'ON') {
				var tile_on = 1;
			}
			var tilecolor = args[2];
			var isValidColor = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(tilecolor);
			if (!isValidColor) {
				if (tiletype === 1 || tiletype === 2) {
					tilecolor = '#000000';
				} else {
					tilecolor = '#FFFFFF';
				}
			}
			var tileradius = 100;
			if (args.length > 3) { tileradius = args[3]; }
			var tilebrightness = 0.0;
			if (args.length > 4) { tilebrightness = args[4]; }
			var tilefound = false;

			for (var i = 0; i < tilearray.length; i++) {
				tilestr = tilearray[i];
				var tileargs = tilestr.split(";");
				if (tileargs[0] == tiletype && tileargs[1] == tilenumber) {
					tilefound = true;
					tilearray[i] = tiletype + ";" + tilenumber + ";" + tile_on + ";" + tilecolor + ";" + tileradius + ";" + tilebrightness;
					//Graphics.Debug('Set',tilearray[i]);
				}
			}

			if (tilefound === false) {
				var tiletag = tiletype + ";" + tilenumber + ";" + tile_on + ";" + tilecolor + ";" + tileradius + ";" + tilebrightness;
				tilearray.push(tiletag);
				//Graphics.Debug('Push',tiletag);
			}
			$gameVariables.setTileArray(tilearray);

		}

		// ************* TINT  *******************
		if (command === 'tint') {

			if (args[0] === 'set') {
				tint_value = args[1];
				Terrax_tint_target = tint_value;
				$gameVariables.setTintValue(tint_value);
			}
			if (args[0] === 'fade') {
				Terrax_tint_target = args[1];
				Terrax_tint_speed = args[2];
				$gameVariables.setTintValue(Terrax_tint_target);
			}

			//Graphics.Debug('TINT',tint_value+' '+tint_target+' '+tint_speed);
		}
		// ************* DAYNIGHT *******************
		if (command === 'daynight') {

			if (args[0] === 'speed') {
				daynightspeed = Number(args[1]);
				if (daynightspeed == 0) {
					daynightspeed = 1000;
					daynightstop = true;
				} else {
					daynightstop = false;
				}
				$gameVariables.setSpeedDayNightSave(daynightspeed);
			}

			if (args[0] === 'add') {
				var houradd = Number(args[1]);
				var minuteadd = 0;
				if (args.length > 2) {
					minuteadd = Number(args[2]);
				}

				var daynightminutes = Math.floor(daynighttimer / daynightspeed);
				daynightminutes = daynightminutes + minuteadd;
				if (daynightminutes > 60) {
					daynightminutes = daynightminutes - 60;
					daynightcycle = daynightcycle + 1;
				}
				daynightcycle = daynightcycle + houradd;
				daynighttimer = daynightminutes * daynightspeed;
				$gameVariables.setDayNightSaveMin(daynightminutes);
				if (daynightsavemin > 0) {
					$gameVariables.setValue(daynightsavemin, daynightminutes);
				}
				if (daynightcycle < 0) {
					daynightcycle = 0;
				}
				if (daynightcycle >= daynightHoursInDay) {
					daynightcycle = daynightcycle - daynightHoursInDay;
				}
				if (daynightsave > 0) {
					$gameVariables.setValue(daynightsave, daynightcycle);
				}
				$gameVariables.setDayNightSave(daynightcycle);
			}

			if (args[0] === 'hour') {
				daynightcycle = Number(args[1]);
				if (args.length > 2) {
					daynightminutes = Number(args[2]);
				} else {
					daynightminutes = 0;
				}
				daynighttimer = daynightminutes * daynightspeed;
				$gameVariables.setDayNightSaveMin(daynightminutes);
				if (daynightsavemin > 0) {
					$gameVariables.setValue(daynightsavemin, daynightminutes);
				}
				if (daynightcycle < 0) {
					daynightcycle = 0;
				}
				if (daynightcycle >= daynightHoursInDay) {
					daynightcycle = (daynightHoursInDay - 1);
				}
				if (daynightsave > 0) {
					$gameVariables.setValue(daynightsave, daynightcycle);
				}
				$gameVariables.setDayNightSave(daynightcycle);

			}

			if (args[0] === 'hoursinday') {
				var old_value = daynightHoursInDay;
				daynightHoursInDay = Number(args[1]);
				if (daynightHoursInDay < 0) {
					daynightHoursInDay = 0;
				}
				if (daynightHoursInDay > old_value) {
					for (var i = old_value; i < daynightHoursInDay; i++) {
						daynightcolors.push('#FFFFFF');
					}
				}
				$gameVariables.setDayNightColorArray(daynightcolors);
				$gameVariables.setDayNightHoursInDay(daynightHoursInDay);
			}

			if (args[0] === 'debug') {
				daynightdebug = true;
			}

			if (args[0] === 'color') {
				var hour = Number(args[1]);
				if (hour < 0) {
					hour = 0;
				}
				if (hour >= daynightHoursInDay) {
					hour = (daynightHoursInDay - 1);
				}
				hourcolor = args[2];
				var isValidColor = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hourcolor);
				if (isValidColor) {
					daynightcolors[hour] = hourcolor;
				}
				$gameVariables.setDayNightColorArray(daynightcolors);
			}

		}

		// ************* FLASHLIGHT *******************
		if (command === 'flashlight') {
			if (args[0] == 'on') {
				playerflashlight = true;
				if (args.length >= 1) { flashlightlength = args[1]; }
				if (args.length >= 2) { flashlightwidth = args[2]; }
				if (args.length >= 3) {
					playercolor = args[3];
					var isValidPlayerColor = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(playercolor);
					if (!isValidPlayerColor) {
						playercolor = '#FFFFFF'
					}
				}
				if (args.length >= 4) {
					flashlightdensity = args[4]; // density
				}

				if (flashlightlength == 0 || isNaN(flashlightlength)) { flashlightlength = 8 }
				if (flashlightwidth == 0 || isNaN(flashlightwidth)) { flashlightwidth = 12 }
				if (flashlightdensity == 0 || isNaN(flashlightdensity)) { flashlightdensity = 3 }

				$gameVariables.setPlayerColor(playercolor);
				$gameVariables.setFlashlightWidth(flashlightwidth);
				$gameVariables.setFlashlightLength(flashlightlength);
				$gameVariables.setFlashlightDensity(flashlightdensity);
			}
			if (args[0] === 'off') {
				playerflashlight = false;
			}
			$gameVariables.setFlashLight(playerflashlight);
		}

		// ******************* SET FIRE *******************
		if (command === 'setfire') {

			flickerradiusshift = args[0];
			flickercolorshift = args[1];
			$gameVariables.setFireRadius(flickerradiusshift);
			$gameVariables.setFireColorshift(flickercolorshift);
		}

		// ******************* FIRE *******************
		if (command === 'fire') {
			playerflicker = true;
			$gameVariables.setFire(playerflicker);
			$gameVariables.setFireRadius(flickerradiusshift);
			$gameVariables.setFireColorshift(flickercolorshift);
		} else {
			playerflicker = false;
			$gameVariables.setFire(playerflicker);
			$gameVariables.setFireRadius(flickerradiusshift);
			$gameVariables.setFireColorshift(flickercolorshift);
		}

		//var evid = this._eventId;
		if (command === 'light' || command === 'fire') {

			//******************* Light radius 100 #FFFFFF ************************
			if (args[0] == 'radius') {
				var newradius = Number(args[1]);
				if (newradius >= 0) {
					player_radius = newradius;
					lightgrow_value = newradius;
					lightgrow_target = newradius;
					$gameVariables.setRadiusSave(player_radius);
				}
				if (args.length > 2) {
					playercolor = args[2];
					var isValidPlayerColor = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(playercolor);
					if (!isValidPlayerColor) {
						playercolor = '#FFFFFF'
					}
					$gameVariables.setPlayerColor(playercolor);
				}
				// player brightness
				if (args.length > 3) {
					var brightness = 0.0;
					var b_arg = args[3];
					if (typeof b_arg != 'undefined') {
						var key = b_arg.substring(0, 1);
						if (key == 'b' || key == 'B') {
							playerbrightness = Number(b_arg.substring(1)) / 100;
							$gameVariables.setPlayerBrightness(playerbrightness);
						}
					}
				}
			}

			//******************* Light radiusgrow 100 #FFFFFF ************************
			if (args[0] === 'radiusgrow') {
				var evid = this._eventId;
				//Graphics.printError('test',evid);
				var newradius = Number(args[1]);
				if (newradius >= 0) {
					//player_radius = newradius;
					lightgrow_value = player_radius;
					lightgrow_target = newradius;
					if (args.length >= 4) {
						if (player_radius > newradius) {
							//shrinking
							lightgrow_speed = (player_radius * 0.012) / Number(args[4]);
						} else {
							//growing
							lightgrow_speed = (newradius * 0.012) / Number(args[4]);
						}
					} else {
						lightgrow_speed = (Math.abs(newradius - player_radius)) / 500;
					}
					//lightgrow_speed = (Math.abs(newradius-player_radius))/500;

				}
				// player color
				if (args.length > 2) {
					playercolor = args[2];
					var isValidPlayerColor = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(playercolor);
					if (!isValidPlayerColor) {
						playercolor = '#FFFFFF'
					}
					$gameVariables.setPlayerColor(playercolor);
				}
				// player brightness
				if (args.length > 3) {
					var brightness = 0.0;
					var b_arg = args[3];
					if (typeof b_arg != 'undefined') {
						var key = b_arg.substring(0, 1);
						if (key == 'b' || key == 'B') {
							playerbrightness = Number(b_arg.substring(1)) / 100;
							$gameVariables.setPlayerBrightness(playerbrightness);
						}
					}
				}

			}

			// *********************** TURN SPECIFIC LIGHT ON *********************
			if (args[0] === 'on') {
				var lightid = Number(args[1]);
				var idfound = false;
				for (var i = 0; i < lightarray_id.length; i++) {
					if (lightarray_id[i] == lightid) {
						idfound = true;
						lightarray_state[i] = true;
					}
				}
				if (idfound == false) {
					lightarray_id.push(lightid);
					lightarray_state.push(true);
				}
				//Graphics.printError('test',lightarray_id.length+' '+lightarray_state.length);
				$gameVariables.setLightArrayId(lightarray_id);
				$gameVariables.setLightArrayState(lightarray_state);
			}

			// *********************** TURN SPECIFIC LIGHT OFF *********************
			if (args[0] === 'off') {
				var lightid = Number(args[1]);
				var idfound = false;
				for (var i = 0; i < lightarray_id.length; i++) {
					if (lightarray_id[i] == lightid) {
						idfound = true;
						lightarray_state[i] = false;
					}
				}
				if (idfound == false) {
					lightarray_id.push(lightid);
					lightarray_state.push(false);
				}
				$gameVariables.setLightArrayId(lightarray_id);
				$gameVariables.setLightArrayState(lightarray_state);
				//Graphics.Debug('RESET3','RESET3');

			}

			// **************************** RESET ALL SWITCHES ***********************
			if (args[0] === 'switch' && args[1] === 'reset') {
				// reset switches to false
				for (var i = 0; i < $dataMap.events.length; i++) {
					if ($dataMap.events[i]) {
						for (var j = 0; j < lightarray_id.length; j++) {
							if (lightarray_id[j] == lightid) {
								var mapid = $gameMap.mapId();
								var eventid = $dataMap.events[i].id;
								var key = [mapid, eventid, 'D'];
								$gameSelfSwitches.setValue(key, false);
							}
						}
					}
				}
				lightarray_id = [];
				lightarray_state = [];
				$gameVariables.setLightArrayId(lightarray_id);
				$gameVariables.setLightArrayState(lightarray_state);
			}
		}
		// *********************** TURN SCRIPT ON/OFF *********************
		if (command === 'light' && args[0] == 'deactivate') {
			scriptactive = false;
			$gameVariables.setScriptActive(false);
		}
		if (command === 'light' && args[0] == 'activate') {
			scriptactive = true;
			$gameVariables.setScriptActive(true);
		}

	}

	Spriteset_Map.prototype.createLightmask = function () {
		this._lightmask = new Lightmask();
		this.addChild(this._lightmask);
	};

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

	Lightmask.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
	Lightmask.prototype.constructor = Lightmask;

	Lightmask.prototype.initialize = function () {
		PIXI.DisplayObjectContainer.call(this);
		this._width = Graphics.width;
		this._height = Graphics.height;
		this._sprites = [];
		this._createBitmap();
	};

	//Updates the Lightmask for each frame.

	Lightmask.prototype.update = function () {
		this._updateMask();
	};

	//@method _createBitmaps

	Lightmask.prototype._createBitmap = function () {
		this._maskBitmap = new Bitmap(maxX, maxY);   // one big bitmap to fill the intire screen with black
		var canvas = this._maskBitmap.canvas;
	};

	/**
	 * @method _updateAllSprites
	 * @private
	 */
	Lightmask.prototype._updateMask = function () {

		// ****** DETECT MAP CHANGES ********
		var map_id = $gameMap.mapId();
		if (map_id != oldmap) {
			oldmap = map_id;

			// moving lightsources
			for (var i = 0; i < $dataMap.events.length; i++) {
				if ($dataMap.events[i]) {
					for (var j = 0; j < move_event_id.length; j++) {
						if (move_event_id[j] == i) {
							move_event_x[j] = $dataMap.events[i].x;
							move_event_y[j] = $dataMap.events[i].y;
							move_event_dir[j] = 2;
						}
					}
				}
			}

			if (reset_each_map == 'Yes' || reset_each_map == 'yes') {
				// reset switches to false
				for (var i = 0; i < $dataMap.events.length; i++) {
					if ($dataMap.events[i]) {
						for (var j = 0; j < lightarray_id.length; j++) {
							if (lightarray_id[j] == lightid) {
								var mapid = $gameMap.mapId();
								var eventid = $dataMap.events[i].id;
								var key = [mapid, eventid, 'D'];
								$gameSelfSwitches.setValue(key, false);
							}
						}
					}
				}
				Lightarray_id = [];
				lightarray_state = [];
				$gameVariables.setLightArrayId(lightarray_id);
				$gameVariables.setLightArrayState(lightarray_state);
			}
		}

		// remove old sprites
		for (var i = 0; i < this._sprites.length; i++) {	  // remove all old sprites
			this._removeSprite();
		}

		if (scriptactive == true) {
			// are there lightsources on this map?
			if ($dataMap.note.toLowerCase() == 'daynight') {
				this._addSprite(0, 0, this._maskBitmap); // daynight tag? yes.. then turn off the lights
			} else {
				for (var i = 0; i < $dataMap.events.length; i++) {
					if ($dataMap.events[i]) {
						var note = $dataMap.events[i].note
						var note_args = note.split(" ");
						var note_command = note_args.shift().toLowerCase();
						if (note_command == "light" || note_command == "fire" || note_command == "daynight" || note_command == "flashlight") {
							this._addSprite(0, 0, this._maskBitmap); // light event? yes.. then turn off the lights
							break;
						}
					}
				}
			}

			// ******** GROW OR SHRINK GLOBE *********

			if (lightgrow_value < lightgrow_target) {
				lightgrow_value = lightgrow_value + lightgrow_speed;
				if (lightgrow_value > lightgrow_target) {
					//other wise it can keep fliping back and forth between > and <
					lightgrow_value = lightgrow_target;
				}
				player_radius = Math.floor(lightgrow_value)
				$gameVariables.setRadiusSave(player_radius);
			}
			if (lightgrow_value > lightgrow_target) {
				lightgrow_value = lightgrow_value - lightgrow_speed;
				if (lightgrow_value < lightgrow_target) {
					//other wise it can keep fliping back and forth between > and <
					lightgrow_value = lightgrow_target;
				}
				player_radius = Math.floor(lightgrow_value)
				$gameVariables.setRadiusSave(player_radius);
			}

			// ****** PLAYER LIGHTGLOBE ********

			var canvas = this._maskBitmap.canvas;
			var ctx = canvas.getContext("2d");
			this._maskBitmap.fillRect(0, 0, maxX, maxY, 'black');

			//ctx.globalCompositeOperation = 'lighten';
			ctx.globalCompositeOperation = 'lighter';

			var pw = $gameMap.tileWidth()
			var ph = $gameMap.tileHeight();
			var dx = $gameMap.displayX();
			var dy = $gameMap.displayY();
			var px = $gamePlayer._realX;
			var py = $gamePlayer._realY;
			var pd = $gamePlayer._direction;

			var x1 = (pw / 2) + ((px - dx) * pw);
			var y1 = (ph / 2) + ((py - dy) * ph);
			var paralax = false;
			// paralax does something weird with coordinates.. recalc needed
			if (dx > $gamePlayer.x) {
				var xjump = $gameMap.width() - Math.floor(dx - px);
				x1 = (pw / 2) + (xjump * pw);
			}
			if (dy > $gamePlayer.y) {
				var yjump = $gameMap.height() - Math.floor(dy - py);
				y1 = (ph / 2) + (yjump * ph);
			}

			if (player_radius > 0) {
				if (playerflashlight == true) {
					this._maskBitmap.radialgradientFillRect2(x1, y1, 20, player_radius, playercolor, 'black', pd, flashlightlength, flashlightwidth);
				}
				if (player_radius < 100) {
					// dim the light a bit at lower lightradius for a less focused effect.
					var r = hexToRgb(playercolor).r;
					var g = hexToRgb(playercolor).g;
					var b = hexToRgb(playercolor).b;
					g = g - 60;
					r = r - 60;
					b = b - 60;
					if (g < 0) { g = 0; }
					if (r < 0) { r = 0; }
					if (b < 0) { b = 0; }
					var newcolor = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

					this._maskBitmap.radialgradientFillRect(x1, y1, 0, player_radius, newcolor, 'black', playerflicker, playerbrightness);
				} else {
					this._maskBitmap.radialgradientFillRect(x1, y1, 20, player_radius, playercolor, 'black', playerflicker, playerbrightness);
				}

			}

			// *********************************** DAY NIGHT CYCLE TIMER **************************

			if (daynightspeed > 0) {
				if (daynightstop == false) {
					var seconds;
					var datenow = new Date();
					var seconds = Math.floor(datenow.getTime() / 10);
					if (seconds > oldseconds) {
						oldseconds = seconds;
						daynighttimer = daynighttimer + 1;
						var daynightminutes = Math.floor(daynighttimer / daynightspeed)
						var daynighttimeover = daynighttimer - (daynightspeed * daynightminutes)
						var daynightseconds = Math.floor(daynighttimeover / daynightspeed * 60)
						if (daynightdebug == true) {
							var daynightseconds2 = daynightseconds;
							if (daynightseconds < 10) {
								daynightseconds2 = '0' + daynightseconds;
							}
							Graphics.Debug('Debug Daynight system', daynightcycle + ' ' + daynightminutes + ' ' + daynightseconds2);
						}
						if (daynightsavemin > 0) {
							$gameVariables.setValue(daynightsavemin, daynightminutes);
						}
						if (daynightsavesec > 0) {
							$gameVariables.setValue(daynightsavesec, daynightseconds);
						}
						$gameVariables.setDayNightSaveMin(daynightminutes);
						if (daynighttimer >= (daynightspeed * 60)) {

							daynightcycle = daynightcycle + 1;
							if (daynightcycle >= daynightHoursInDay) {
								daynightcycle = 0;
							}
							if (daynightsave > 0) {
								$gameVariables.setValue(daynightsave, daynightcycle);
							}
							$gameVariables.setDayNightSave(daynightcycle);
							daynighttimer = 0;
						}
					}
				}
			}

			// ********** OTHER LIGHTSOURCES **************
			var daynightset = false;
			for (var i = 0; i < $dataMap.events.length; i++) {
				if ($dataMap.events[i]) {
					var note = $dataMap.events[i].note;
					var evid = $dataMap.events[i].id;
					var note_args = note.split(" ");
					var note_command = note_args.shift().toLowerCase();
					if (note_command == "light" || note_command == "fire" || note_command == "flashlight") {

						var objectflicker = false;
						if (note_command == "fire") {
							objectflicker = true;
						}

						var light_radius = 1;
						var flashlength = 8;
						var flashwidth = 12;
						if (note_command == "flashlight") {
							flashlength = Number(note_args.shift());
							flashwidth = Number(note_args.shift());
							if (flashlength == 0) { flashlightlenth = 8 }
							if (flashwidth == 0) { flashlightlenth = 12 }
						} else {
							light_radius = note_args.shift();
						}
						// light radius
						if (light_radius >= 0) {

							// light color
							var colorvalue = note_args.shift();
							var isValidColor = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(colorvalue)
							if (!isValidColor) {
								colorvalue = '#FFFFFF'
							}

							// brightness and direction

							var brightness = 0.0;
							var direction = 0;
							var next_arg = note_args.shift();

							if (typeof next_arg != 'undefined') {
								var key = next_arg.substring(0, 1);
								if (key == 'b' || key == 'B') {
									brightness = Number(next_arg.substring(1)) / 100;
									next_arg = note_args.shift();
									if (typeof next_arg != 'undefined') {
										key = next_arg.substring(0, 1);
									}
								}
								if (key == 'd' || key == 'D') {
									direction = next_arg.substring(1);
									next_arg = note_args.shift();
								}
							}

							// conditional lighting
							if (typeof next_arg != 'undefined') {
								var lightid = next_arg;
							} else {
								var lightid = 0;
							}
							//var lightid = note_args.shift();

							var state = true;
							if (lightid > 0) {
								var state = false;
								for (var j = 0; j < lightarray_id.length; j++) {
									if (lightarray_id[j] == lightid) {
										idfound = true;
										state = lightarray_state[j];
										var mapid = $gameMap.mapId();
										var eventid = $dataMap.events[i].id;

										//Graphics.printError('test',mapid+' '+eventid);
										key = [mapid, eventid, 'D'];
										if (state == true) {
											$gameSelfSwitches.setValue(key, true);
										} else {
											$gameSelfSwitches.setValue(key, false);
										}
									}
								}
							}

							// kill switch
							if (killswitch == 'A' || killswitch == 'B' || killswitch == 'C' || killswitch == 'D') {
								key = [$gameMap.mapId(), $dataMap.events[i].id, killswitch];
								if ($gameSelfSwitches.value(key) == true) {
									state = false;
									//Graphics.Debug('Deathswitch',killswitch);
								}
							}

							// show light
							if (state == true) {

								var lpx = $dataMap.events[i].x;
								var lpy = $dataMap.events[i].y;
								ldir = 4
								// moving lightsources
								var flashlight = false;
								for (var j = 0; j < move_event_id.length; j++) {
									if (move_event_id[j] == evid) {
										lpx = move_event_x[j];
										lpy = move_event_y[j];
										ldir = move_event_dir[j];
										if (note_command === "flashlight") {
											flashlight = true;
										}
									}
								}
								if (note_command == "flashlight" && flashlight === false) {
									flashlight = true;
									// flashlight direction
									var tldir = Number(note_args.shift());
									if (!isNaN(tldir)) {
										if (tldir < 0 || ldir >= 5) { ldir = 4 }
										if (tldir == 1) { ldir = 8 }
										if (tldir == 2) { ldir = 6 }
										if (tldir == 3) { ldir = 2 }
										if (tldir == 4) { ldir = 4 }
									}

								}
								//Graphics.Debug('ldir',ldir);

								var lx1 = (pw / 2) + ((lpx - dx) * pw);
								var ly1 = (ph / 2) + ((lpy - dy) * ph);
								// paralaxloop does something weird with coordinates.. recalc needed

								if ($dataMap.scrollType === 2 || $dataMap.scrollType === 3) {
									if (dx - 10 > lpx) {
										var lxjump = $gameMap.width() - (dx - lpx);
										lx1 = (pw / 2) + (lxjump * pw);
									}
								}
								if ($dataMap.scrollType === 1 || $dataMap.scrollType === 3) {
									if (dy - 10 > lpy) {
										var lyjump = $gameMap.height() - (dy - lpy);
										ly1 = (ph / 2) + (lyjump * ph);
									}
								}
								if (flashlight == true) {
									this._maskBitmap.radialgradientFillRect2(lx1, ly1, 0, light_radius, colorvalue, 'black', ldir, flashlength, flashwidth);
								} else {
									this._maskBitmap.radialgradientFillRect(lx1, ly1, 0, light_radius, colorvalue, 'black', objectflicker, brightness, direction);
								}
							}
						}
					}

					// *********************************** DAY NIGHT CYCLE FILTER **************************
					if (daynightset == false) {
						var mapnote = $dataMap.note.toLowerCase()
						var searchnote = mapnote.search("daynight")
						if (searchnote >= 0 || note_command == "daynight") {
							daynightset = true;
							$gameVariables.setDayNightColorArray(daynightcolors);
						}
					}
				}
			}

			// *************************** TILE TAG *********************

			for (var i = 0; i < tilearray.length; i++) {
				tilestr = tilearray[i];
				var tileargs = tilestr.split(";");
				var tile_type = tileargs[0];
				var tile_number = tileargs[1];
				var tile_on = tileargs[2];
				var tile_color = tileargs[3];
				var tile_radius = tileargs[4];
				var brightness = 0.0;
				var b_arg = tileargs[5];
				if (typeof b_arg != 'undefined') {
					var key = b_arg.substring(0, 1);
					if (key == 'b' || key == 'B') {
						brightness = Number(b_arg.substring(1)) / 100;
					}
				}

				if (tile_on == 1) {

					if (tile_type >= 3) {
						// *************************** TILE TAG LIGHTSOURCES *********
						for (var y = 0; y < $dataMap.height; y++) {
							for (var x = 0; x < $dataMap.width; x++) {
								var tag = 0;
								if (tile_type == 3 || tile_type == 5) { tag = $gameMap.terrainTag(x, y); }          // tile light
								if (tile_type == 4 || tile_type == 6) { tag = $dataMap.data[(5 * $dataMap.height + y) * $dataMap.width + x]; }  // region light
								if (tag == tile_number) {
									var x1 = (pw / 2) + (x - dx) * pw;
									var y1 = (ph / 2) + (y - dy) * ph;

									if ($dataMap.scrollType === 2 || $dataMap.scrollType === 3) {
										if (dx - 5 > x) {
											var lxjump = $gameMap.width() - (dx - x);
											x1 = (pw / 2) + (lxjump * pw);
										}
									}
									if ($dataMap.scrollType === 1 || $dataMap.scrollType === 3) {
										if (dy - 5 > y) {
											var lyjump = $gameMap.height() - (dy - y);
											y1 = (ph / 2) + (lyjump * ph);
										}
									}

									if (tile_type == 3 || tile_type == 4) {
										this._maskBitmap.radialgradientFillRect(x1, y1, 0, tile_radius, tile_color, 'black', false, brightness); // Light
									} else {

										this._maskBitmap.radialgradientFillRect(x1, y1, 0, tile_radius, tile_color, 'black', true, brightness);  // Fire
									}
								}
							}
						}
					}

					// *************************** REDRAW MAPTILES FOR ROOFS ETC *********
					if (tile_type == 1 || tile_type == 2) {
						for (var y = 0; y < $dataMap.height; y++) {
							for (var x = 0; x < $dataMap.width; x++) {
								//var tag = $gameMap.terrainTag(x,y);
								var tag = 0;
								if (tile_type == 1) { tag = $gameMap.terrainTag(x, y); }                  // tile block
								if (tile_type == 2) { tag = $dataMap.data[(5 * $dataMap.height + y) * $dataMap.width + x]; }  // region block
								if (tag == tile_number) {
									ctx.globalCompositeOperation = 'darker';
									var x1 = (x - dx) * pw;
									var y1 = (y - dy) * ph;

									if ($dataMap.scrollType === 2 || $dataMap.scrollType === 3) {
										if (dx - 5 > x) {
											var lxjump = $gameMap.width() - (dx - x);
											x1 = (lxjump * pw);
										}
									}
									if ($dataMap.scrollType === 1 || $dataMap.scrollType === 3) {
										if (dy - 5 > y) {
											var lyjump = $gameMap.height() - (dy - y);
											y1 = (lyjump * ph);
										}
									}

									this._maskBitmap.FillRect(x1, y1, pw, ph, tile_color);
									ctx.globalCompositeOperation = 'lighter';
								}
							}
						}
					}
				}
			}

			// *********************************** DAY NIGHT CYCLE FILTER **************************

			if (daynightset == true) {

				var color1 = daynightcolors[daynightcycle];

				if (daynightspeed > 0) {
					var nextcolor = daynightcycle + 1;
					if (nextcolor >= daynightHoursInDay) {
						nextcolor = 0;
					}
					var color2 = daynightcolors[nextcolor];

					var r = hexToRgb(color1).r;
					var g = hexToRgb(color1).g;
					var b = hexToRgb(color1).b;

					var r2 = hexToRgb(color2).r;
					var g2 = hexToRgb(color2).g;
					var b2 = hexToRgb(color2).b;

					var stepR = (r2 - r) / (60 * daynightspeed);
					var stepG = (g2 - g) / (60 * daynightspeed);
					var stepB = (b2 - b) / (60 * daynightspeed);

					r = Math.floor(r + (stepR * daynighttimer));
					g = Math.floor(g + (stepG * daynighttimer));
					b = Math.floor(b + (stepB * daynighttimer));

				}
				color1 = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

				this._maskBitmap.FillRect(0, 0, maxX, maxY, color1);
			}

			// *********************************** TINT **************************

			if (daynightset == false) {

				color1 = tint_value;
				if (tint_value != Terrax_tint_target) {

					var tintdatenow = new Date();
					var tintseconds = Math.floor(tintdatenow.getTime() / 10);
					if (tintseconds > tint_oldseconds) {
						tint_oldseconds = tintseconds;
						tint_timer++;
					}

					var r = hexToRgb(tint_value).r;
					var g = hexToRgb(tint_value).g;
					var b = hexToRgb(tint_value).b;

					var r2 = hexToRgb(Terrax_tint_target).r;
					var g2 = hexToRgb(Terrax_tint_target).g;
					var b2 = hexToRgb(Terrax_tint_target).b;

					var stepR = (r2 - r) / (60 * Terrax_tint_speed);
					var stepG = (g2 - g) / (60 * Terrax_tint_speed);
					var stepB = (b2 - b) / (60 * Terrax_tint_speed);

					r3 = Math.floor(r + (stepR * tint_timer));
					g3 = Math.floor(g + (stepG * tint_timer));
					b3 = Math.floor(b + (stepB * tint_timer));
					if (r3 < 0) { r3 = 0 }
					if (g3 < 0) { g3 = 0 }
					if (b3 < 0) { b3 = 0 }
					if (r3 > 255) { r3 = 255 }
					if (g3 > 255) { g3 = 255 }
					if (b3 > 255) { b3 = 255 }
					var reddone = false;
					var greendone = false;
					var bluedone = false;
					if (stepR >= 0 && r3 >= r2) {
						reddone = true;
					}
					if (stepR <= 0 && r3 <= r2) {
						reddone = true;
					}
					if (stepG >= 0 && g3 >= g2) {
						greendone = true;
					}
					if (stepG <= 0 && g3 <= g2) {
						greendone = true;
					}
					if (stepB >= 0 && b3 >= b2) {
						bluedone = true;
					}
					if (stepB <= 0 && b3 <= b2) {
						bluedone = true;
					}
					if (reddone == true && bluedone == true && greendone == true) {
						tint_value = Terrax_tint_target;
					}
					color1 = "#" + ((1 << 24) + (r3 << 16) + (g3 << 8) + b3).toString(16).slice(1);
				} else {
					tint_timer = 0;
				}

				this._maskBitmap.FillRect(0, 0, maxX, maxY, color1);
			}

			// reset drawmode to normal
			ctx.globalCompositeOperation = 'source-over';
		}
	};

	/**
	 * @method _addSprite
	 * @private
	 */
	Lightmask.prototype._addSprite = function (x1, y1, selectedbitmap) {

		var sprite = new Sprite(this.viewport);
		sprite.bitmap = selectedbitmap;
		sprite.opacity = 255;
		sprite.blendMode = 2;
		sprite.x = x1;
		sprite.y = y1;
		this._sprites.push(sprite);
		this.addChild(sprite);
		sprite.rotation = 0;
		sprite.ax = 0
		sprite.ay = 0
		sprite.opacity = 255;
	};

	/**
	 * @method _removeSprite
	 * @private
	 */
	Lightmask.prototype._removeSprite = function () {
		this.removeChild(this._sprites.pop());
	};

	// *******************  NORMAL BOX SHAPE ***********************************
	// Fill gradient circle

	Bitmap.prototype.FillRect = function (x1, y1, x2, y2, color1) {
		var context = this._context;
		context.save();
		context.fillStyle = color1;
		context.fillRect(x1, y1, x2, y2);
		context.restore();
		this._setDirty();
	};

	// *******************  NORMAL LIGHT SHAPE ***********************************
	// Fill gradient circle

	Bitmap.prototype.radialgradientFillRect = function (x1, y1, r1, r2, color1, color2, flicker, brightness, direction) {
		if (!brightness) { brightness = 0.0; }
		if (!direction) { direction = 0; }
		var context = this._context;
		var grad;
		var wait = Math.floor((Math.random() * 8) + 1);
		if (flicker == true && wait == 1) {
			//var flickerradiusshift = 7;
			//var flickercolorshift = 10;
			var gradrnd = Math.floor((Math.random() * flickerradiusshift) + 1);
			var colorrnd = Math.floor((Math.random() * flickercolorshift) - (flickercolorshift / 2));

			var r = hexToRgb(color1).r;
			var g = hexToRgb(color1).g;
			var b = hexToRgb(color1).b;
			g = g + colorrnd;
			if (g < 0) { g = 0; }
			if (g > 255) { g = 255; }
			color1 = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
			r2 = r2 - gradrnd;
			if (r2 < 0) r2 = 0;
		}

		grad = context.createRadialGradient(x1, y1, r1, x1, y1, r2);
		grad.addColorStop(0, '#FFFFFF');
		grad.addColorStop(brightness, color1);
		grad.addColorStop(1, color2);

		context.save();
		context.fillStyle = grad;
		direction = Number(direction);
		var pw = $gameMap.tileWidth() / 2;
		var ph = $gameMap.tileHeight() / 2;
		switch (direction) {
			case 0:
				context.fillRect(x1 - r2, y1 - r2, r2 * 2, r2 * 2);
				break;
			case 1:
				context.fillRect(x1 - r2, y1 - ph, r2 * 2, r2 * 2);
				break;
			case 2:
				context.fillRect(x1 - r2, y1 - r2, r2 * 1 + pw, r2 * 2);
				break;
			case 3:
				context.fillRect(x1 - r2, y1 - r2, r2 * 2, r2 * 1 + ph);
				break;
			case 4:
				context.fillRect(x1 - pw, y1 - r2, r2 * 2, r2 * 2);
				break;
		}

		// context.fillRect(x1-r2, y1-r2, r2*2, r2*2);
		context.restore();
		this._setDirty();
	};

	// ********************************** FLASHLIGHT *************************************
	// Fill gradient Cone

	Bitmap.prototype.radialgradientFillRect2 = function (x1, y1, r1, r2, color1, color2, direction, flashlength, flashwidth) {
		var context = this._context;
		var grad;

		// smal dim glove around player
		context.save();
		y1 = y1 - flashlightoffset;

		r1 = 1;
		r2 = 40;
		grad = context.createRadialGradient(x1, y1, r1, x1, y1, r2);
		grad.addColorStop(0, '#999999');
		grad.addColorStop(1, color2);

		context.fillStyle = grad;
		context.fillRect(x1 - r2, y1 - r2, r2 * 2, r2 * 2);

		// flashlight

		for (var cone = 0; cone < flashlength; cone++) {
			r1 = cone * flashlightdensity;
			r2 = cone * flashwidth;

			switch (direction) {
				case 6:
					x1 = x1 + cone * 6;
					break;
				case 4:
					x1 = x1 - cone * 6;
					break;
				case 2:
					y1 = y1 + cone * 6;
					break;
				case 8:
					y1 = y1 - cone * 6;
					break;
			}

			grad = context.createRadialGradient(x1, y1, r1, x1, y1, r2);
			grad.addColorStop(0, color1);
			grad.addColorStop(1, color2);

			context.fillStyle = grad;
			context.fillRect(x1 - r2, y1 - r2, r2 * 2, r2 * 2);
		}
		context.fillStyle = grad;
		context.fillRect(x1 - r2, y1 - r2, r2 * 2, r2 * 2);

		context.restore();
		this._setDirty();
	};

	function hexToRgb(hex) {
		var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		return result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : null;
	}

	// Saving Variables in Game_Variables
	// Big thanks to Schlangan for the code.

	Game_Variables.prototype.valueRadiusSave = function () {
		return this._Terrax_Lighting_Radius || 0;
	};
	Game_Variables.prototype.valueDayNightSave = function () {
		return this._Terrax_Lighting_DayNight || 0;
	};
	Game_Variables.prototype.valueDayNightSaveMin = function () {
		return this._Terrax_Lighting_DayNightMin || 0;
	};
	Game_Variables.prototype.valueSpeedDayNightSave = function () {
		return this._Terrax_Lighting_SpeedDayNight || 0;
	};
	Game_Variables.prototype.valueFlashLightSave = function () {
		return this._Terrax_Lighting_FlashLight || false;
	};
	Game_Variables.prototype.valueFireSave = function () {
		return this._Terrax_Lighting_Fire || false;
	};
	Game_Variables.prototype.setDayNightSave = function (value) {
		this._Terrax_Lighting_DayNight = value;
	};
	Game_Variables.prototype.setDayNightSaveMin = function (value) {
		this._Terrax_Lighting_DayNightMin = value;
	};
	Game_Variables.prototype.setRadiusSave = function (value) {
		this._Terrax_Lighting_Radius = value;
	};
	Game_Variables.prototype.setSpeedDayNightSave = function (value) {
		this._Terrax_Lighting_SpeedDayNight = value;
	};
	Game_Variables.prototype.setFlashLight = function (value) {
		this._Terrax_Lighting_FlashLight = value;
	};
	Game_Variables.prototype.setFire = function (value) {
		this._Terrax_Lighting_Fire = value;
	};
	Game_Variables.prototype.setFireRadius = function (value) {
		this._Terrax_Lighting_FireRadius = value;
	};
	Game_Variables.prototype.valueFireRadiusSave = function () {
		return this._Terrax_Lighting_FireRadius || false;
	};
	Game_Variables.prototype.setFireColorshift = function (value) {
		this._Terrax_Lighting_FireColorshift = value;
	};
	Game_Variables.prototype.valueFireColorshiftSave = function () {
		return this._Terrax_Lighting_FireColorshift || false;
	};
	Game_Variables.prototype.setPlayerColor = function (value) {
		this._Terrax_Lighting_PlayerColor = value;
	};
	Game_Variables.prototype.valuePlayerColorSave = function () {
		return this._Terrax_Lighting_PlayerColor || '#FFFFFF';
	};
	Game_Variables.prototype.setPlayerBrightness = function (value) {
		this._Terrax_Lighting_PlayerBrightness = value;
	};
	Game_Variables.prototype.valuePlayerBrightnessSave = function () {
		return this._Terrax_Lighting_PlayerBrightness || 0.0;
	};
	Game_Variables.prototype.setTintValue = function (value) {
		this._Terrax_Tint_Value = value;
	};
	Game_Variables.prototype.valueTintValueSave = function () {
		return this._Terrax_Tint_Value || '#000000';
	};

	Game_Variables.prototype.setFlashlightDensity = function (value) {
		this._Terrax_Lighting_FlashlightDensity = value;
	};
	Game_Variables.prototype.valueFlashlightDensity = function () {
		return this._Terrax_Lighting_FlashlightDensity || 3;
	};
	Game_Variables.prototype.setFlashlightLength = function (value) {
		this._Terrax_Lighting_FlashlightLength = value;
	};
	Game_Variables.prototype.valueFlashlightLength = function () {
		return this._Terrax_Lighting_FlashlightLength || 8;
	};
	Game_Variables.prototype.setFlashlightWidth = function (value) {
		this._Terrax_Lighting_FlashlightWidth = value;
	};
	Game_Variables.prototype.valueFlashlightWidth = function () {
		return this._Terrax_Lighting_FlashlightWidth || 12;
	};

	Game_Variables.prototype.valueDayNightColor = function () {
		var default_color = ['#FF0000', '#FF0000', '#FF0000', '#FF0000',
			'#FF0000', '#FF0000', '#FF0000', '#FF0000',
			'#FF0000', '#FF0000', '#FF0000', '#FF0000',
			'#FF0000', '#FF0000', '#FF0000', '#FF0000',
			'#FF0000', '#FF0000', '#FF0000', '#FF0000',
			'#FF0000', '#FF0000', '#FF0000', '#FF0000'];
		return this._Terrax_Lighting_DayNightColor || default_color;
	};

	Game_Variables.prototype.setDayNightColorArray = function (value) {
		this._Terrax_Lighting_DayNightColor = value;
	};

	Game_Variables.prototype.valueLightArrayId = function () {
		var default_LAI = [];
		return this._Terrax_Lighting_LightArrayId || default_LAI;
	};

	Game_Variables.prototype.setLightArrayId = function (value) {
		this._Terrax_Lighting_LightArrayId = value;
	};

	Game_Variables.prototype.valueLightArrayState = function () {
		var default_LAS = [];
		return this._Terrax_Lighting_LightArrayState || default_LAS;
	};

	Game_Variables.prototype.setLightArrayState = function (value) {
		this._Terrax_Lighting_LightArrayState = value;
	};

	Game_Variables.prototype.valueTileArray = function () {
		var default_TA = [];
		return this._Terrax_Lighting_TileArray || default_TA;
	};

	Game_Variables.prototype.setTileArray = function (value) {
		this._Terrax_Lighting_TileArray = value;
	};

	Game_Variables.prototype.valueScriptActive = function () {
		if (typeof this._Terrax_Lighting_ScriptActive == 'undefined') {
			this._Terrax_Lighting_ScriptActive = true;
		}
		return this._Terrax_Lighting_ScriptActive || false;
	};

	Game_Variables.prototype.setScriptActive = function (value) {
		this._Terrax_Lighting_ScriptActive = value;
	};

	function SaveLightingVariables() {

		var storeddata = $gameVariables.valueRadiusSave();
		if (storeddata > 0) {
			player_radius = storeddata;
		}

		var storeddata = $gameVariables.valueDayNightSave();
		if (storeddata > 0) {
			daynightcycle = storeddata;
			if (daynightsave > 0) {
				$gameVariables.setValue(daynightsave, daynightcycle);
			}
		}
		daynightminutes = $gameVariables.valueDayNightSaveMin();
		daynighttimer = daynightminutes * daynightspeed;

		var storeddata = $gameVariables.valueSpeedDayNightSave();
		if (storeddata > 0) {
			daynightspeed = storeddata;

			if (daynightspeed == 0) {
				daynightspeed = 1000;
				daynightstop = true;
			} else {
				daynightstop = false;
			}
		}
		scriptactive = $gameVariables.valueScriptActive();
		playercolor = $gameVariables.valuePlayerColorSave();
		playerflicker = $gameVariables.valueFireSave();
		playerflashlight = $gameVariables.valueFlashLightSave();
		flashlightwidth = $gameVariables.valueFlashlightWidth();
		flashlightlength = $gameVariables.valueFlashlightLength();
		flashlightdensity = $gameVariables.valueFlashlightDensity();

		daynightcolors = $gameVariables.valueDayNightColor();
		lightarray_id = $gameVariables.valueLightArrayId();
		lightarray_state = $gameVariables.valueLightArrayState();
		flickerradiusshift = $gameVariables.valueFireRadiusSave();
		flickercolorshift = $gameVariables.valueFireColorshiftSave();
		tint_value = $gameVariables.valueTintValueSave();
		Terrax_tint_target = $gameVariables.valueTintValueSave();
		tilearray = $gameVariables.valueTileArray();
		playerbrightness = $gameVariables.valuePlayerBrightnessSave();
	};

	//****
	// Debug
	//****

	Graphics.Debug = function (name, message) {
		if (this._errorPrinter) {
			this._errorPrinter.innerHTML = this._makeErrorHtml(name, message);
		}
	}

	//****
	// This function is overwritten from rpg_sprites.js
	//****

	Spriteset_Map.prototype.createLowerLayer = function () {
		Spriteset_Base.prototype.createLowerLayer.call(this);
		this.createParallax();
		this.createTilemap();
		this.createCharacters();
		this.createShadow();
		this.createDestination();
		this.createLightmask();
		this.createWeather();

	}

	//****
	// These functions are overwritten from objects/sprites/scenes.
	//****

	Game_CharacterBase.prototype.updateMove = function () {

		var evid = this._eventId;    // Capture the realX and realY of moving events.
		if (evid) {
			var note = $dataMap.events[evid].note;
			var note_args = note.split(" ");
			var note_command = note_args.shift().toLowerCase();
			if (note_command == "light" || note_command == "fire" || note_command == "flashlight") {
				//Graphics.printError('test',evid + ' ' + this._realX + ' '+ this._realY);
				var idfound = false;
				for (var i = 0; i < move_event_id.length; i++) {
					if (move_event_id[i] == evid) {
						idfound = true;
						move_event_x[i] = this._realX;
						move_event_y[i] = this._realY;
						move_event_dir[i] = this._direction;
					}
				}
				if (idfound == false) {
					move_event_id.push(evid);
					move_event_x.push(this._realX);
					move_event_y.push(this._realY);
					move_event_dir.push(this._direction);
				}
			}
		}
		//Graphics.printError('test',evid + ' ' + this._realX + ' '+ this._realY);

		if (this._x < this._realX) {
			this._realX = Math.max(this._realX - this.distancePerFrame(), this._x);
		}
		if (this._x > this._realX) {
			this._realX = Math.min(this._realX + this.distancePerFrame(), this._x);
		}
		if (this._y < this._realY) {
			this._realY = Math.max(this._realY - this.distancePerFrame(), this._y);
		}
		if (this._y > this._realY) {
			this._realY = Math.min(this._realY + this.distancePerFrame(), this._y);
		}
		if (!this.isMoving()) {
			this.refreshBushDepth();
		}
	}

	Scene_Load.prototype.onSavefileOk = function () {
		Scene_File.prototype.onSavefileOk.call(this);
		if (DataManager.loadGame(this.savefileId())) {
			this.onLoadSuccess();

			if (Imported.TerraxLighting) {
				SaveLightingVariables();
			}
			if (Imported.TerraxPuzzle) {
				SavePuzzleVariables();
			}

		} else {
			this.onLoadFailure();
		}
	}

})();

repo_name: dazed/translations

license: unknown


code:
//=============================================================================
// ThrowMovingObject.js
//=============================================================================

/*:ja
 * @plugindesc プレイヤーから投擲物を射出します。
 * @author 村人A
 *
 * @help
 *
 * _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
 *
 * バージョン情報
 *
 * 23/01/08 バージョン1.1　 速度設定追加
 * 20/12/18 バージョン1.0　 試作品リリース
 *
 * _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
 *
 *
 *
 *
 *
 * @param n1
 * @text 速度設定
 * @desc 投擲物の速度を設定します。数値は移動ルートの「速度の変更」と同等です。
 * @type number
 * @default 4
 *
 *
 *
 *
 *
 *
 *
 */
{
	'use strict'

	String.prototype.toNumArray = function () {
		return this.split(',').map(str => Number(str));
	}

	const param = PluginManager.parameters('ThrowMovingObject');
	let _ = {};
	Object.keys(param).forEach(key => {
		if (key[0] == "n" && key[1] == "a") {
			_[key] = param[key].toNumArray();
		} else if (key[0] == "n") {
			_[key] = Number(param[key]);
		} else if (key[0] == "s" && key[1] == "a" && key[2] == "a") {
			_[key] = JSON.parse(param[key]).map(str => str.split(','));
		} else if (key[0] == "s" && key[1] == "a") {
			_[key] = JSON.parse(param[key]);
		} else if (key[0] == "s") {
			_[key] = param[key];
		} else if (key[0] == "a") {
			_[key] = param[key].toAudioParam();
		}
	})

	//-----------------------------------------------------------------------------
	// Game_CharacterBase
	//

	Game_CharacterBase.prototype.getTowardPosition = function () {
		const x = this.x;
		const y = this.y;
		const d = this.direction();
		const x2 = $gameMap.roundXWithDirection(x, d);
		const y2 = $gameMap.roundYWithDirection(y, d);
		return [x2, y2];
	}

	//-----------------------------------------------------------------------------
	// Game_Map
	//

	const _alias_Game_Map_initialize = Game_Map.prototype.initialize;
	Game_Map.prototype.initialize = function () {
		_alias_Game_Map_initialize.call(this);
		this.createThrowObject();
	}

	Game_Map.prototype.createThrowObject = function () {
		this._movingObjects = [];
		//23/01/08 追記
		for (let i = 0; i < 10; i++) {
			this._movingObjects.push(new Game_MovingObject());
		}
	}

	Game_Map.prototype.movingObjects = function () {
		return this._movingObjects;
	};

	Game_Map.prototype.setMovingObjects = function (image, distance) {
		for (let obj of this._movingObjects) {
			if (obj.isActivated) { continue }
			obj.setImage(image[0], Number(image[1]))
			obj.setPosition(...$gamePlayer.getTowardPosition())
			let route = [{ code: 26, indent: null }, { code: 40, indent: null }]
			for (let i = 0; i < distance; i++) {
				route.push({ code: 12, indent: null })
			}
			route.push({ code: 39, indent: null })
			//23/01/08 追記
			route.push({ code: 45, parameters: ['this.isActivated = false'], indent: null })
			route.push({ code: 0 })
			const rounteObj = { list: route, repeat: false, skippable: true, wait: false };
			obj.forceMoveRoute(rounteObj);
			obj.setMoveSpeed(_.n1);
			obj.isActivated = true;
			break
		}
	}

	const _alias_Game_Map_update = Game_Map.prototype.update;
	Game_Map.prototype.update = function (sceneActive) {
		_alias_Game_Map_update.call(this, sceneActive);
		this.updateMovingObjects();
	}

	Game_Map.prototype.updateMovingObjects = function () {
		this._movingObjects.forEach(obj => obj.update());
	}

	//-----------------------------------------------------------------------------
	// Game_MovingObject
	//

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

	Game_MovingObject.prototype = Object.create(Game_Character.prototype);
	Game_MovingObject.prototype.constructor = Game_MovingObject;

	Game_MovingObject.prototype.initialize = function () {
		Game_Character.prototype.initialize.call(this);
		this._mapId = 0;
		this.isActivated = false;
	};

	Game_MovingObject.prototype.isCollidedWithEventsAfter = function (d) {
		const x2 = $gameMap.roundXWithDirection(this.x, d);
		const y2 = $gameMap.roundYWithDirection(this.y, d);
		//const onEvent = this.isMoving() ? $gameMap.eventsXyNt(...this.preXy) : [];
		//23/01/04 修正
		const onEvent = $gameMap.eventsXyNt(...this.preXy);
		const forwardEvent = !this.isMoving() ? $gameMap.eventsXyNt(x2, y2) : [];
		const eventArray = onEvent.concat(forwardEvent);
		return eventArray.length > 0 && eventArray[0].isNormalPriority() ? eventArray[0] : false;
	};

	Game_MovingObject.prototype.moveStraight = function (d) {
		this.preXy = [this.x, this.y];
		Game_CharacterBase.prototype.moveStraight.call(this, d)
		const event = this.isCollidedWithEventsAfter(d);
		if (event) {
			const symb = $gamePlayer.gatheringAction().fetchCurrentModel().symbol;
			if (event.event().meta[symb]) {
				//23/01/04 修正
				this.setTransparent(true)
				this._moveRouteIndex = this._moveRoute.list.length - 3;
				$gamePlayer._gatheringAction._fireSelfSwitchEvent(event)
			}
		}
	}

	//-----------------------------------------------------------------------------
	// Spriteset_Map
	//

	const _alias_Spriteset_Map_createCharacters = Spriteset_Map.prototype.createCharacters;
	Spriteset_Map.prototype.createCharacters = function () {
		_alias_Spriteset_Map_createCharacters.call(this);
		$gameMap.movingObjects().forEach(obj => {
			const sprite = new Sprite_Character(obj);
			this._characterSprites.push(sprite);
			this._tilemap.addChild(sprite);
		})
	};
}


code:
//=============================================================================
// TitleCommandPosition.js
//=============================================================================

/*:
 * @plugindesc Changes the position of the title command window.
 * @author Yoji Ojima
 *
 * @param Offset X
 * @desc The offset value for the x coordinate.
 * @default 0
 *
 * @param Offset Y
 * @desc The offset value for the y coordinate.
 * @default 0
 *
 * @param Width
 * @desc The width of the command window.
 * @default 240
 *
 * @param Background
 * @desc The background type. 0: Normal, 1: Dim, 2: Transparent
 * @default 0
 *
 * @help This plugin does not provide plugin commands.
 */

/*:ja
 * @plugindesc タイトルコマンドウィンドウの位置を変更します。
 * @author Yoji Ojima
 *
 * @param Offset X
 * @desc X座標のオフセット値です。
 * @default 0
 *
 * @param Offset Y
 * @desc Y座標のオフセット値です。
 * @default 0
 *
 * @param Width
 * @desc コマンドウィンドウの幅です。
 * @default 240
 *
 * @param Background
 * @desc 背景タイプです。0: 通常、1: 暗くする、2: 透明
 * @default 0
 *
 * @help このプラグインには、プラグインコマンドはありません。
 */

(function () {

    var parameters = PluginManager.parameters('TitleCommandPosition');
    var offsetX = Number(parameters['Offset X'] || 0);
    var offsetY = Number(parameters['Offset Y'] || 0);
    var width = Number(parameters['Width'] || 240);
    var background = Number(parameters['Background'] || 0);

    var _Window_TitleCommand_updatePlacement =
        Window_TitleCommand.prototype.updatePlacement;
    Window_TitleCommand.prototype.updatePlacement = function () {
        _Window_TitleCommand_updatePlacement.call(this);
        this.x += offsetX;
        this.y += offsetY;
        this.setBackgroundType(background);
    };

    Window_TitleCommand.prototype.windowWidth = function () {
        return width;
    };

})();