Skip to content

Commit

Permalink
Execute Lua scripts in syncronized thread
Browse files Browse the repository at this point in the history
  • Loading branch information
Sirius902 committed Aug 9, 2021
1 parent 1a682a1 commit 70d1aac
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion LuaBackendDLL/main_dll.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
#include <string_view>
#include <vector>

#include <condition_variable>
#include <thread>
#include <mutex>

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shlobj.h>
Expand All @@ -18,6 +22,13 @@ using DirectInput8CreateProc = HRESULT(WINAPI*)(HINSTANCE hinst, DWORD dwVersion

DirectInput8CreateProc createProc = nullptr;

std::mutex m;
std::condition_variable cv;
bool doScriptsFrame = false;
bool scriptsFrameDone = false;

std::thread luaThread;

extern "C"
{
using namespace std;
Expand Down Expand Up @@ -233,8 +244,32 @@ extern "C"
}
}

void LuaThread() {
while (true) {
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [] { return doScriptsFrame; });

ExecuteLUA();
doScriptsFrame = false;
scriptsFrameDone = true;

lk.unlock();
cv.notify_one();
}
}

extern "C" void onFrame() {
ExecuteLUA();
{
std::lock_guard<std::mutex> lk(m);
doScriptsFrame = true;
scriptsFrameDone = false;
}
cv.notify_one();

{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [] { return scriptsFrameDone; });
}
}

void hookGame(uint64_t moduleAddress) {
Expand Down Expand Up @@ -312,6 +347,9 @@ DWORD WINAPI entry(LPVOID lpParameter) {
SHGetFolderPathA(0, CSIDL_MYDOCUMENTS, nullptr, 0, scriptsPath);
std::strcat(scriptsPath, "\\KINGDOM HEARTS HD 1.5+2.5 ReMIX\\scripts");

luaThread = std::thread(LuaThread);
luaThread.detach();

if (std::filesystem::exists(scriptsPath)) {
if (EntryLUA(GetCurrentProcessId(), GetCurrentProcess(), baseAddress, scriptsPath) == 0) {
hookGame(moduleAddress);
Expand Down

0 comments on commit 70d1aac

Please sign in to comment.