MZ Adding a condition to a plugin

Hi folks,

Let's say I am using a plugin (in my case, it adds a screen filter). I'd like to make the plugin only run when a certain switch is enabled.

Is it possible to wrap the plugin's code in an "if" statement that checks a switch? And if so, how would I format that? I know how I'd add a condition like this to an existing script in the editor, but know very little about JS to add this to a plugin directly. I'm honestly not even sure if you can reference script calls like $gameVariable in a plugin's code, or if that is for in the actual editor only.

Thanks!
Is it possible to wrap the plugin's code in an "if" statement that checks a switch?
yes
I know how I'd add a condition like this to an existing script in the editor... I'm honestly not even sure if you can reference script calls like $gameVariable in a plugin's code, or if that is for in the actual editor only.
Scriptcalls function the same way within plugin code as it does within script boxes. as long as youre writing valid javascript, you can use them in either place.

You just need to be able to identify what function would be the ideal place to place a script call to check if a specific game switch is active. that being said...
but know very little about JS to add this to a plugin directly.
Id suggest finding a javascript tutorial first and going through the basics before you go about editing existing plugins just so that you have a better idea of what youre looking at/for and can understand what you need to get done easier
yes

Scriptcalls function the same way within plugin code as it does within script boxes. as long as youre writing valid javascript, you can use them in either place.

You just need to be able to identify what function would be the ideal place to place a script call to check if a specific game switch is active. that being said...

Id suggest finding a javascript tutorial first and going through the basics before you go about editing existing plugins just so that you have a better idea of what youre looking at/for and can understand what you need to get done easier

Thanks for the reply! This is all good to know and helps a lot with my problem.
I'd like to make the plugin only run when a certain switch is enabled.
While the answer above is not wrong, it only works for specific cases.

as soon as a plugin requires to store its data into the savefiles, a wrapper like discussed above will faile to function.

if the plugin stores data, that data needs to be always stored and always loaded, otherwise you'll get type errors from incompatible save files as soon as the plugin is disabled.

with plugins that store data, you can only disable specific functions but never the entire plugin - and finding the specific functions that can be savely disabled will require analyzing and understanding the plugin code itself.

That is by the way the same reason why we always say that after any change in the plugin manager you need to start a new playtest game, because adding a plugin that changes the savfefiles is the same - it makers older savefiles incompatible.
Is it possible to wrap the plugin's code in an "if" statement that checks a switch?
I'm going to be contradictory and say it's much more like "no" 😛

To be clear: you can absolutely write code so that portions of it are different depending on whether a switch is on or not.

But you cannot simply make the entire plugin function or not depending on the state of a game switch.

For one thing, a plugin's code is loaded when the game starts, and at that time game switches don't exist.

For another thing, even if you base the condition on something other than a game switch, if you simply wrap a condition around functions in your plugin, their existence or not will be set at that time. If you change that condition later during the game, it won't re-read the code in your plugin to pick up any now-effective function declarations.

You have to have it either intentionally set when the game boots (the common use for this is to have different functionality between MV and MZ, or different operating systems), or you place your conditionals inside the functions with different options for the code there.
What plugin is it? Maybe it already has some plugin commands?
I'm going to be contradictory and say it's much more like "no"
ah. i misinterpreted what they wanted. when i read
Let's say I am using a plugin (in my case, it adds a screen filter). I'd like to make the plugin only run when a certain switch is enabled.
i figured that they just wanted to just disable the function that applies the screen filter and that it has some call for it, but i see now that they wanted to disable the entire plugin. placing a check inside a function and having it return early wont get that done 🤣
i figured that they just wanted to just disable the function that applies the screen filter and that it has some call for it, but i see now that they wanted to disable the entire plugin.
Well, that's how I interpret the post, anyway. It's possible that you're more right than I am, but that's how the words came across to me.
What plugin is it? Maybe it already has some plugin commands?

The plugin is this:

Spoiler
Code:
/** /*:
 * @author TheUnpropro
 * @plugindesc A thing for a dude on the inter webs
 *
 * @target MZ
 *
 * @command Chrom
 * @text Chroma Level
 * @desc Sets the intensity of the chroma effect
 *
 * @arg value
 * @text Intensity
 * @type number
 * @decimals 2
 * @default 2
 * @desc Adjusts the intensity
 */
    (function () {
    const pi60 = Math.PI / 60;
    PluginManager.registerCommand('chroma_color', "Chrom", args => {
        args.value = parseFloat(args.value);
        window.__ChromaIntensConfig(args.value);
    });

    window.__ChromaIntensConfig = function (value) {
        try {
            const oldData = JSON.parse(localStorage.getItem('chroma_data'));
            oldData.intensity = value;
            oldData.view[0] = Graphics._width;
            oldData.view[1] = Graphics._height;
            window._globalChromaFilter.uniforms.view[0] = Graphics._width;
            window._globalChromaFilter.uniforms.view[1] = Graphics._height;
            window._globalChromaFilter.uniforms.intensity = value;

            SceneManager._scene._chromaFilter.uniforms.view = window._globalChromaFilter.uniforms.view;
            SceneManager._scene._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity;


            console.log(oldData);
            SceneManager._scene._writeChromaData(oldData);
        } catch (e) {
            throw e;
        }
    }

    async function FilterFragShader(frag, src) {
        try {
            let ret = await Promise.all(frag.match(/\/\*\@file:(.*?)\*\//gm).map(async (match) => {
                try {
                    const filename = match.replace('/*@file:', '').replace('*/', '').trim();
                    const fileContents = await fetch(`./data/filters/${src}/${filename}`).then(response => response.text());
                    return { match, replacement: fileContents };
                } catch (error) {
                    console.error(`Error loading file ${filename}:`, error);
                    return { match, replacement: "" }; // Return empty string if file loading fails
                }
            }));

            ret.forEach(({ match, replacement }) => {
                frag = frag.replace(match, replacement);
            });

        } catch (e) {
        }
        return frag;
    }
    async function checkCompile(src, vert, frag) {
        if (buildMode) {
            const path = require('path');
            const fs = require('fs');
            const corePath = `./data/filters/${src}/`;
            try {
                const flags = await fetch(`${corePath}/flags.json`).then(f => f.json());
                if (flags.compile.output_dir) {
                    try {
                        const mainPath = path.resolve(`${flags.compile.output_dir}/${src}`);
                        fs.mkdirSync(mainPath, { recursive: true });
                        if (flags.compile.vert) fs.writeFileSync(`${mainPath}/main.vert`, vert);
                        if (flags.compile.frag) fs.writeFileSync(`${mainPath}/main.frag`, frag);
                    } catch (e) {
                        throw e;
                    }
                }
            } catch (e) {
                console.log(`No flags.json file set`)
            }
        }
    }

    const buildMode = false;

    const __filterCache = {};
    async function loadFilter(src) {
        PIXI.settings.ROUND_PIXELS = true;
        return new Promise((resolve, reject) => {
            if (__filterCache[src]) resolve({ vert: __filterCache[src].vert, frag: __filterCache[src].frag })
            var frag = "";
            var vert = "";

            fetch(`/js/plugins/filters/${src}/main.vert`)
                .then(a => a.text())
                .then(_vert => {
                    vert = _vert;
                    return fetch(`/js/plugins/filters/${src}/main.frag`);
                })
                .then(a => a.text())
                .then(async _frag => {
                    frag = await FilterFragShader(_frag, src);

                    vert = `#version 300 es \nprecision highp float;\n${vert}`;
                    frag = `#version 300 es \nprecision highp float;\n${frag}`;


                    checkCompile(src, vert, frag);
                    resolve({ vert, frag });
                    __filterCache[src] = { vert, frag }
                })
                .catch(error => reject(error));
        });
    }

    const osb = Scene_Boot.prototype.initialize;

    Scene_Boot.prototype.initialize = function () {
        osb.call(this, arguments);

        (async () => {
            try {
                const data = await loadFilter('chroma');
                if (!data) {
                    throw new Error("Failed to load filter data");
                }
                const { vert, frag } = data;
                const _uniformData = this._getChromaData()

                const uniformBase =  {
                    delta: 0,
                    intensity: 2.25,
                    view: [Graphics._width, Graphics._height],
                    state: 1
                };
                const uniforms = _uniformData ?? uniformBase;
                for(let key in uniformBase) {
                    if(!uniforms[key]) uniforms[key] = uniformBase[key];
                }
               
                window._globalChromaFilter = new PIXI.Filter(vert, frag, uniforms);
                if (!_uniformData) this._writeChromaData(uniforms);
            } catch (error) {
                console.error("Error loading filter:", error);
            }
        })();
    };

    Scene_Base.prototype._getChromaData = function () {
        const data = localStorage.getItem('chroma_data');
        if (data) try {
            return JSON.parse(data);
        } catch (e) {
            return data;
        }
        return data;
    }

    Scene_Base.prototype._writeChromaData = function (data) {
        localStorage.setItem('chroma_data', JSON.stringify(data));
    }

    const osc = Scene_Base.prototype.create;
    Scene_Base.prototype.create = function () {
        osc.call(this, arguments);
        this._chromaFilter = window._globalChromaFilter;
        if (this._chromaFilter) {
            if (!this.filters) this.filters = [];
            this.filters.push(this._chromaFilter);
        }
    }
   
    const osu = Scene_Base.prototype.update;
    Scene_Base.prototype.update = function () {
        osu.call(this, arguments);
        if (this._chromaFilter) {
            this._chromaFilter.uniforms.delta += pi60;
            this._chromaFilter.uniforms.view[0] = Graphics._width;
            this._chromaFilter.uniforms.view[1] = Graphics._height;
            if(this.constructor.name==`Scene_Map`) {
                this._chromaFilter.uniforms.state = 1;
            this._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity*0.15;
        } else {
                this._chromaFilter.uniforms.state = 0;
            this._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity;
        }
        }
    }

})();

It's a custom screen filter plugin that I commissioned. It does have a plugin command, but setting the strength to 0 does not disable the screen filter, just sets the intensity of certain aspects low. I am looking for a way to make this filter not apply if a certain switch is on.

ah. i misinterpreted what they wanted. when i read

i figured that they just wanted to just disable the function that applies the screen filter and that it has some call for it, but i see now that they wanted to disable the entire plugin. placing a check inside a function and having it return early wont get that done 🤣

I do know that putting the whole plugin in a condition will break it, but I had phrased it that way just to get the general formatting of that condition. Now that I am trying to apply it though, I can see that I have another problem - this script runs before the map loads (as it applies to all scenes), so there is no switch loaded to reference, crashing the game at the menu.

Since I only care about disabling the plugin after a save is loaded, I guess I need a way to check if I am "in game" so there will be a switch, then check that switch, and if not then run the plugin's filters normally?

I am quickly getting further out of my depth, haha.


While the answer above is not wrong, it only works for specific cases.

as soon as a plugin requires to store its data into the savefiles, a wrapper like discussed above will faile to function.

if the plugin stores data, that data needs to be always stored and always loaded, otherwise you'll get type errors from incompatible save files as soon as the plugin is disabled.

with plugins that store data, you can only disable specific functions but never the entire plugin - and finding the specific functions that can be savely disabled will require analyzing and understanding the plugin code itself.

That is by the way the same reason why we always say that after any change in the plugin manager you need to start a new playtest game, because adding a plugin that changes the savfefiles is the same - it makers older savefiles incompatible.

I have no idea if it is doing that, but it is posted above, so perhaps you can tell? I am grasping in the dark.


I'm going to be contradictory and say it's much more like "no" 😛

To be clear: you can absolutely write code so that portions of it are different depending on whether a switch is on or not.

But you cannot simply make the entire plugin function or not depending on the state of a game switch.

For one thing, a plugin's code is loaded when the game starts, and at that time game switches don't exist.

For another thing, even if you base the condition on something other than a game switch, if you simply wrap a condition around functions in your plugin, their existence or not will be set at that time. If you change that condition later during the game, it won't re-read the code in your plugin to pick up any now-effective function declarations.

You have to have it either intentionally set when the game boots (the common use for this is to have different functionality between MV and MZ, or different operating systems), or you place your conditionals inside the functions with different options for the code there.

My intention was to ask a broad question just to see how to format the statement, but to actually apply it to the parts of the plugin code which actually update the filter effect. That said, I still have no clue what I am doing or where it is best to apply it.
That said, I still have no clue what I am doing or where it is best to apply it, haha.
That was really my point - the answer to this kind of question is really "no" unless you know pretty well what you're doing (and, in many cases, how to write alternate code for the stuff you want to turn off).

Isn't this the second time you've asked about modifying one of these commissioned plugins? You didn't include the toggling bit in the original specifications? The author, who's familiar with the plugin's code, wouldn't add it in for a small additional fee?
That was really my point - the answer to this kind of question is really "no" unless you know pretty well what you're doing (and, in many cases, how to write alternate code for the stuff you want to turn off).

Isn't this the second time you've asked about modifying one of these commissioned plugins? You didn't include the toggling bit in the original specifications? The author, who's familiar with the plugin's code, wouldn't add it in for a small additional fee?

I did post another thread before (about this same plugin), but didn't get any replies to it, so figured I'd wait a while and ask again.

Ideally I would have the original author add the feature, but that doesn't seem to be going anywhere for right now, so I figured I'd see if I can somehow implement the change myself if it could be done in a simple way (which it seems it can't unfortunately).

The ability to scale the effect of the filter was in the original commission, but not to completely disable the plugin. At that point, I wasn't really thinking of adding graphics/performance options to my game yet, which I am adding now.

Original thread: https://forums.rpgmakerweb.com/threads/adding-a-condition-to-a-plugin.171433/