mirror of
https://github.com/huderlem/porymap.git
synced 2026-08-16 13:48:01 -05:00
Implement proof of concept for scripting capabilities
This commit is contained in:
69
src/scripting.cpp
Normal file
69
src/scripting.cpp
Normal file
@@ -0,0 +1,69 @@
|
||||
#include "scripting.h"
|
||||
#include "log.h"
|
||||
|
||||
QMap<CallbackType, QString> callbackFunctions = {
|
||||
{OnBlockChanged, "on_block_changed"},
|
||||
};
|
||||
|
||||
Scripting *instance = nullptr;
|
||||
|
||||
void Scripting::init(MainWindow *mainWindow) {
|
||||
instance = new Scripting(mainWindow);
|
||||
}
|
||||
|
||||
Scripting::Scripting(MainWindow *mainWindow) {
|
||||
this->engine = new QJSEngine(mainWindow);
|
||||
this->engine->installExtensions(QJSEngine::ConsoleExtension);
|
||||
this->engine->globalObject().setProperty("api", this->engine->newQObject(mainWindow));
|
||||
this->filepaths.append("D:\\devkitProOld\\msys\\home\\huder\\pretmap\\test_script.js");
|
||||
this->loadModules(this->filepaths);
|
||||
}
|
||||
|
||||
void Scripting::loadModules(QStringList moduleFiles) {
|
||||
for (QString filepath : moduleFiles) {
|
||||
QJSValue module = this->engine->importModule(filepath);
|
||||
if (module.isError()) {
|
||||
logError(QString("Failed to load custom script file '%1'").arg(filepath));
|
||||
continue;
|
||||
}
|
||||
|
||||
this->modules.append(module);
|
||||
}
|
||||
}
|
||||
|
||||
void Scripting::invokeCallback(CallbackType type, QJSValueList args) {
|
||||
for (QJSValue module : this->modules) {
|
||||
QString functionName = callbackFunctions[type];
|
||||
QJSValue callbackFunction = module.property(functionName);
|
||||
if (callbackFunction.isError()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
QJSValue result = callbackFunction.call(args);
|
||||
if (result.isError()) {
|
||||
logError(QString("Module %1 encountered an error when calling '%2'").arg(module.toString()).arg(functionName));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Scripting::cb_MetatileChanged(int x, int y, Block prevBlock, Block newBlock) {
|
||||
if (!instance) return;
|
||||
|
||||
QJSValueList args {
|
||||
x,
|
||||
y,
|
||||
instance->newBlockObject(prevBlock),
|
||||
instance->newBlockObject(newBlock),
|
||||
};
|
||||
instance->invokeCallback(OnBlockChanged, args);
|
||||
}
|
||||
|
||||
QJSValue Scripting::newBlockObject(Block block) {
|
||||
QJSValue obj = this->engine->newObject();
|
||||
obj.setProperty("tile", block.tile);
|
||||
obj.setProperty("collision", block.collision);
|
||||
obj.setProperty("elevation", block.elevation);
|
||||
obj.setProperty("rawValue", block.rawValue());
|
||||
return obj;
|
||||
}
|
||||
Reference in New Issue
Block a user