diff --git a/java-client/.gitignore b/java-client/.gitignore deleted file mode 100644 index 4ea31d4..0000000 --- a/java-client/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build/ -__pycache__/ diff --git a/java-client/CMakeLists.txt b/java-client/CMakeLists.txt deleted file mode 100644 index 0b60469..0000000 --- a/java-client/CMakeLists.txt +++ /dev/null @@ -1,57 +0,0 @@ -cmake_minimum_required(VERSION 3.24) -project(amnesia_java LANGUAGES C CXX) - -if(NOT WIN32 OR NOT CMAKE_SIZEOF_VOID_P EQUAL 8) - message(FATAL_ERROR "The late-loading client requires Windows x64") -endif() - -find_package(Python3 REQUIRED COMPONENTS Interpreter) -find_package(JNI REQUIRED) -set(MAPPINGS "${CMAKE_CURRENT_BINARY_DIR}/deps/client.txt" CACHE FILEPATH "Mojang client mappings for Java 1.21.1") -set(SHARED "${CMAKE_CURRENT_SOURCE_DIR}/../client") -set(IMGUI "${SHARED}/vendor/imgui") -set(MINHOOK "${SHARED}/vendor/minhook") -set(FREETYPE "${SHARED}/vendor/freetype") -set(BINDINGS "${CMAKE_CURRENT_BINARY_DIR}/bindings.h") -add_custom_command(OUTPUT "${BINDINGS}" - COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/bindings.py" - "${MAPPINGS}" "${CMAKE_CURRENT_SOURCE_DIR}/src/bindings.txt" "${BINDINGS}" - DEPENDS "${MAPPINGS}" tools/bindings.py src/bindings.txt - VERBATIM) -set(BEDROCK_UI "") -foreach(VIEW clickgui account_screen startup_intro music_player) - list(APPEND BEDROCK_UI "${CMAKE_CURRENT_BINARY_DIR}/bedrock_${VIEW}.h") -endforeach() -add_custom_command(OUTPUT ${BEDROCK_UI} - COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/reuse_ui.py" - "${SHARED}/src" "${CMAKE_CURRENT_BINARY_DIR}" - DEPENDS tools/reuse_ui.py "${SHARED}/src/gui/clickgui.h" "${SHARED}/src/gui/account_screen.h" - "${SHARED}/src/gui/startup_intro.h" "${SHARED}/src/modules/music_player.h" - VERBATIM) -add_library(amnesia-java SHARED - src/attach.cpp src/game.cpp src/overlay.cpp "${BINDINGS}" ${BEDROCK_UI} - "${SHARED}/src/font_data.cc" "${IMGUI}/misc/freetype/imgui_freetype.cpp" - "${IMGUI}/imgui.cpp" "${IMGUI}/imgui_draw.cpp" "${IMGUI}/imgui_tables.cpp" "${IMGUI}/imgui_widgets.cpp" - "${IMGUI}/backends/imgui_impl_opengl3.cpp" "${IMGUI}/backends/imgui_impl_win32.cpp" - "${MINHOOK}/src/buffer.c" "${MINHOOK}/src/hook.c" "${MINHOOK}/src/trampoline.c" "${MINHOOK}/src/hde/hde64.c") -target_compile_features(amnesia-java PRIVATE cxx_std_20) -target_compile_definitions(amnesia-java PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE IMGUI_ENABLE_FREETYPE) -target_compile_options(amnesia-java PRIVATE $<$:/utf-8>) -target_include_directories(amnesia-java PRIVATE src "${CMAKE_CURRENT_BINARY_DIR}" ${JNI_INCLUDE_DIRS} - "${IMGUI}" "${IMGUI}/backends" "${MINHOOK}/include" "${SHARED}/src" "${FREETYPE}/include") -target_link_libraries(amnesia-java PRIVATE opengl32 gdi32 comctl32 shell32 "${FREETYPE}/lib/freetype.lib") -target_link_options(amnesia-java PRIVATE /NODEFAULTLIB:LIBCMT /ignore:4099) - -add_executable(amnesia-java-loader src/loader.cpp) -target_compile_features(amnesia-java-loader PRIVATE cxx_std_20) -target_compile_definitions(amnesia-java-loader PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) - -include(CTest) -if(BUILD_TESTING) - add_executable(amnesia-gl-test tests/gl_state.cpp) - target_compile_features(amnesia-gl-test PRIVATE cxx_std_20) - target_compile_definitions(amnesia-gl-test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) - target_link_libraries(amnesia-gl-test PRIVATE opengl32 gdi32) - target_include_directories(amnesia-gl-test PRIVATE src) - add_test(NAME opengl_state COMMAND amnesia-gl-test) -endif() diff --git a/java-client/README.md b/java-client/README.md deleted file mode 100644 index 718f5df..0000000 --- a/java-client/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# amnesia for java 1.21.1 - -A separate Windows x64 DLL for the running Java Edition client. Java uses Bedrock's Dear ImGui views for ClickGUI, the account dialog, the intro and the music HUD. It also shares the Verdana/FreeType font system, widgets, theme controls, watermark, keystrokes and notifications. The Java bridge resolves Minecraft classes through the running JVM with bindings generated for 1.21.1. It supports the vanilla obfuscated names and NeoForge's Mojang names. - -## use - -1. Open Minecraft Java 1.21.1. -2. Run `amnesia-java-loader.exe` from the directory containing `amnesia-java.dll`. If multiple supported game windows are open, pass `--pid `. -3. Sign in with your existing amnesia account after the intro. The default API is `http://127.0.0.1:8787/api`. Expand **connection** on the login screen to use your HTTPS API. -4. Press **Right Shift** to open ClickGUI. Left-click module rows to toggle them and right-click to expand settings. The **hud editor** button opens the drag-and-grid editor. **Themes** and **Profiles** are in the utility panel. - -The Java profiles live in `%LOCALAPPDATA%\amnesia\java`. For an isolated profile, set `AMNESIA_JAVA_PROFILE_DIR` to an absolute path before launching the game. Remembered sign-in uses a separate Windows Credential Manager entry for each overridden profile directory. Startup and compatibility diagnostics are written to `amnesia-java.log` beside the DLL. - -To detach while the game is rendering, run `amnesia-java-loader.exe --detach`. The DLL stays resident to keep in-flight native callbacks safe. Restart Minecraft before attaching again or replacing that copy of the DLL. - -## features - -- HUD widgets for FPS, keystrokes, CPS, coordinates, time, speed, XP, armor, held items, effects, crosshair target, entity counts, tab list, player radar, active modules, compass, session stats, and diagnostics. -- Target HUD for mobs and players, with eased tracking, a two-second linger, and native skin portraits for players. -- Waypoints, breadcrumbs, tracers, logout spots, projectile previews, loaded-chunk fortress scans, positional sound markers, and a friend locator gated by Java's Realms connection type. -- FOV, hold-C zoom, fullbright, custom crosshair, block outlines, rain and thunder strength, local sky time and name, third-person freelook, particle reduction, and entity distance scaling. -- Custom chat on **T**, notification cards, durability alerts, inventory quick transfers with a name filter, tool and weapon selection, sprint, Enderman look-away, hold-to-click, mob-only attacks, and idle swings. -- Windows media controls, artwork, playback progress, and direct LRCLIB lookup for synced lyrics. - -The fortress scan searches loaded terrain for Nether-brick clusters and can find player-built structures. Java projectile previews use approximate block collisions and launch speeds. Chat opens with T or slash and uses Java's plain message text. The custom crosshair and block outline draw over the corresponding vanilla elements. Inventory tools have in-container steal and dump buttons with a right-click item picker and a stop button during transfers. Sorting is unavailable. The weather module uses Java's native rain and thunder. - -Bedrock's viewmodel and glint edits, villager macro, Auto Tree, Bridge Assist and custom weather shaders are outside this build. Java has no matching vanilla coordinates overlay. Module settings and HUD data are limited to what the Java bridge provides. Other loaders and Minecraft versions need their own bindings and verification. - -## build - -Install Visual Studio 2022 with Desktop development with C++, Windows SDK 10.0.26100, CMake, Python 3, and a 64-bit JDK. From this directory, set `JAVA_HOME` to the JDK and run: - -```powershell -./tools/fetch-mappings.ps1 -cmake -S . -B build -G "Visual Studio 17 2022" -A x64 -cmake --build build --config Release --parallel -ctest --test-dir build -C Release --output-on-failure -``` - -The loader and DLL go in `build/Release`. The mappings and test game files stay under the ignored build directory. diff --git a/java-client/src/attach.cpp b/java-client/src/attach.cpp deleted file mode 100644 index 7c8c3a4..0000000 --- a/java-client/src/attach.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "game.h" -#include "overlay.h" -#include "MinHook.h" -#include -#include -#include -#include -#include - -namespace { -using Swap = BOOL (WINAPI*)(HDC); -using GetVMs = jint (JNICALL*)(JavaVM**,jsize,jsize*); -Swap original; -void* hook; -jvmtiEnv* jvmti; -HMODULE self; -HWND window; -HGLRC context; -std::atomic stopping{}, finished{}; -std::atomic started{}; -std::atomic renderThread{}; -thread_local bool inside; -java::Clock::time_point nextAttach; - -void log(std::string_view message) { - OutputDebugStringA(("amnesia-java: "+std::string(message)+"\n").c_str()); - if (!self) return; - wchar_t path[32768]{}; - const auto length=GetModuleFileNameW(self,path,DWORD(std::size(path))); - if (length && lengthGetEnv(reinterpret_cast(&env),JNI_VERSION_1_8); - try { - if (env && stopping) { - if (started) java::overlay::cleanup(env); - java::release(env); - finished=true; - } else if (env && !started && java::Clock::now()>=nextAttach) { - nextAttach=java::Clock::now()+std::chrono::seconds(2); - if (!jvmti && java::vm->GetEnv(reinterpret_cast(&jvmti),JVMTI_VERSION_1_2)!=JNI_OK) { - log("could not initialize JVMTI on Minecraft's render thread"); - } else if (java::attach(env,jvmti) && java::overlay::start(target)) { - window=target; - context=wglGetCurrentContext(); - started=true; - log(java::data.status); - } else { - log(java::data.status); - } - } - if (env && started && !finished && target==window && context==wglGetCurrentContext()) - java::overlay::draw(env); - } catch (...) { - log("overlay stopped after a native exception"); - stopping=true; - } - inside=false; - return original(dc); -} - -DWORD WINAPI bootstrap(void*) { - auto jvm=GetModuleHandleW(L"jvm.dll"); - auto get=jvm ? reinterpret_cast(GetProcAddress(jvm,"JNI_GetCreatedJavaVMs")) : nullptr; - jsize count{}; - if (!get || get(&java::vm,1,&count)!=JNI_OK || count!=1 || !java::vm) { - log("no active HotSpot Java VM found"); - return 1; - } - auto gdi=GetModuleHandleW(L"gdi32.dll"); - hook=gdi ? reinterpret_cast(GetProcAddress(gdi,"SwapBuffers")) : nullptr; - if (!hook || MH_Initialize()!=MH_OK || - MH_CreateHook(hook,&present,reinterpret_cast(&original))!=MH_OK) { - log("could not install the OpenGL present hook"); - return 2; - } - // Retain the image while game callbacks may still be executing. - HMODULE pinned{}; - if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_PIN, - reinterpret_cast(&bootstrap),&pinned) || MH_EnableHook(hook)!=MH_OK) { - log("could not enable the OpenGL present hook"); - return 3; - } - log("attached to HotSpot, waiting for Minecraft's next OpenGL frame"); - return 0; -} -} - -void java::diagnostic(std::string_view message) { log(message); } - -extern "C" __declspec(dllexport) DWORD WINAPI unload(void*) { - stopping=true; - const auto deadline=GetTickCount64()+5000; - while (!finished && GetTickCount64() -#include -#include -#include -#include -#include - -namespace java { - -std::array modules{{ - {"fps","hud","current game frame rate",true},{"watermark","hud","account, uid and build",true}, - {"keystrokes","hud","movement keys and mouse buttons",true},{"cps","hud","clicks per second"}, - {"coordinates","hud","position and dimension"},{"clock","hud","local time"},{"speed","hud","horizontal speed"}, - {"xp progress","hud","level, experience and progress bar"},{"armor","hud","equipped armor and remaining durability"}, - {"tool info","hud","held items and durability"},{"status effects","hud","effect levels and timers"}, - {"looking at","hud","targeted block or entity"},{"entity counter","hud","counts entities in the client world"}, - {"tab list","hud","online players and latency while tab is held"},{"player radar","hud","nearby players and distance"}, - {"target hud","hud","health of the player or mob under your crosshair"},{"active modules","hud","enabled modules"}, - {"compass","hud","bearing and the nearest saved waypoint"},{"session stats","hud","distance, time and containers opened"}, - {"waypoints","world","save and project positions"},{"breadcrumbs","world","recent path through the world"}, - {"entity tracers","world","lines to nearby mobs and players"},{"logout spots","world","last known location of departing players"}, - {"trajectories","world","projectile path and first block impact"},{"block outlines","world","accent outline around the targeted block"}, - {"crosshair","visual","animated, customizable crosshair"},{"fullbright","visual","client lightmap brightness"}, - {"fov changer","visual","set the base field of view"},{"zoom","visual","hold c to zoom"}, - {"atmosphere","visual","client rain and thunder intensity"},{"client time","visual","set the client world sky time"}, - {"better nametags","visual","player names, health and distance"},{"name changer","visual","local player display name"}, - {"freelook","visual","hold left alt for third-person orbit"},{"optimizations","visual","lower entity render distance"}, - {"inventory tools","utility","quick-move matching stacks from an open container"}, - {"custom chat","utility","imGui chat with history and commands"},{"notifier","utility","game events and incoming chat"}, - {"durability alerts","utility","alert when a held tool is close to breaking"},{"fortress finder","world","scan loaded nether chunks"}, - {"music mini player","hud","windows media controls, album art and synced lrclib lyrics"}, - {"auto tool","utility","select the fastest hotbar tool for the block"},{"auto weapon","utility","choose a hotbar melee weapon on attack"}, - {"toggle sprint","utility","sprint while moving forward"},{"enderman look","utility","turn away from an enderman's eyes"}, - {"auto clicker","utility","repeat the selected held button"},{"mob auto attack","utility","attack nearby monsters and optional animals"}, - {"anti afk","utility","periodic swing while idle"},{"particle controls","visual","reduce vanilla particles"}, - {"friends locator","world","markers for configured names in Mojang Realms"}, - {"sound indicators","world","direction markers for nearby positional sounds"}, - {"diagnostics","hud","native frame and bridge metrics"} -}}; -Settings settings; -Data data; -JavaVM* vm = nullptr; - -namespace { -int naming = 0; -jobject loader; -jmethodID loadClass; -std::unordered_map classes; -struct Cached { jclass owner{}; jmethodID method{}; jfieldID field{}; bool resolved{}; }; -std::array cache{}; -jobject worldRef, cameraMode, cameraActor, lastMessage, savedName; -jobject transferMenu; -std::unordered_map lastPlayers; -std::unordered_map lastOnline; -std::unordered_map soundSeen; -std::array originals{}; -Clock::time_point nextSample, nextActors, nextClick, nextAttack, lastActivity = Clock::now(); -std::deque clicks[2]; -bool queuedFortress, chatHidden, nativeChatHidden, menuReleasedMouse, sprintForced, freeActive, dayOverride, weatherOverride; -bool armorWarned, toolPress, weaponPress, nameOverride, lastWindowContainer; -bool nightWarned, healthWarned, hungerWarned; -jlong oldDay; -float oldRain, oldThunder, freeYaw, freePitch; -double orbitX, orbitY; -std::string sentChat, transferFilter; -int transfer, nextSlot; -bool transferExact, inventoryPicker; -Clock::time_point nextTransfer, nextPicker; -struct Scan { - std::vector> chunks; - unsigned chunk{}, section{}, block{}; - int bricks{}; - bool palette{}; - Vec sum; -} scan; - -bool clear(JNIEnv* env) { - if (!env->ExceptionCheck()) return false; - env->ExceptionClear(); - return true; -} - -jclass classFor(JNIEnv* env, const char* name) { - if (auto found = classes.find(name); found != classes.end()) return found->second; - auto string = env->NewStringUTF(name); - auto local = static_cast(env->CallObjectMethod(loader, loadClass, string)); - env->DeleteLocalRef(string); - if (clear(env) || !local) { - classes.emplace(name, nullptr); - return nullptr; - } - auto global = static_cast(env->NewGlobalRef(local)); - env->DeleteLocalRef(local); - classes.emplace(name, global); - return global; -} - -const Cached& resolve(JNIEnv* env, Binding id) { - auto& cached = cache[id]; - if (cached.resolved) return cached; - cached.resolved = true; - const auto& decl = declarations[id]; - cached.owner = classFor(env, decl.owner[naming]); - if (!cached.owner || decl.kind == Kind::Class) return cached; - const char* name = decl.name[naming]; - const char* sig = decl.signature[naming]; - switch (decl.kind) { - case Kind::Field: cached.field = env->GetFieldID(cached.owner, name, sig); break; - case Kind::Staticfield: cached.field = env->GetStaticFieldID(cached.owner, name, sig); break; - case Kind::Staticmethod: cached.method = env->GetStaticMethodID(cached.owner, name, sig); break; - default: cached.method = env->GetMethodID(cached.owner, name, sig); break; - } - clear(env); - return cached; -} - -template -T call(JNIEnv* env, Binding id, jobject receiver, Args... args) { - const auto& b = resolve(env, id); - if (!b.method) return T{}; - const Kind kind = declarations[id].kind; - T value{}; - if (kind == Kind::Constructor) - value = [&]() -> T { if constexpr (std::is_same_v) return env->NewObject(b.owner,b.method,args...); return {}; }(); - else if (kind == Kind::Staticmethod) { - if constexpr (std::is_same_v) value = env->CallStaticObjectMethod(b.owner,b.method,args...); - } else if (receiver) { - if constexpr (std::is_same_v) value = env->CallObjectMethod(receiver,b.method,args...); - else if constexpr (std::is_same_v) value = env->CallDoubleMethod(receiver,b.method,args...); - else if constexpr (std::is_same_v) value = env->CallFloatMethod(receiver,b.method,args...); - else if constexpr (std::is_same_v) value = env->CallIntMethod(receiver,b.method,args...); - else if constexpr (std::is_same_v) value = env->CallLongMethod(receiver,b.method,args...); - else if constexpr (std::is_same_v) value = env->CallBooleanMethod(receiver,b.method,args...); - } - return clear(env) ? T{} : value; -} - -template -void act(JNIEnv* env, Binding id, jobject receiver, Args... args) { - const auto& b = resolve(env,id); - if (!b.method) return; - if (declarations[id].kind == Kind::Staticmethod) env->CallStaticVoidMethod(b.owner,b.method,args...); - else if (receiver) env->CallVoidMethod(receiver,b.method,args...); - clear(env); -} - -template -T field(JNIEnv* env, Binding id, jobject receiver = nullptr) { - const auto& b = resolve(env,id); - if (!b.field) return T{}; - if constexpr (std::is_same_v) { - if (declarations[id].kind == Kind::Staticfield) return env->GetStaticObjectField(b.owner,b.field); - } - if (!receiver) return T{}; - if constexpr (std::is_same_v) return env->GetObjectField(receiver,b.field); - if constexpr (std::is_same_v) return env->GetIntField(receiver,b.field); - if constexpr (std::is_same_v) return env->GetFloatField(receiver,b.field); - if constexpr (std::is_same_v) return env->GetDoubleField(receiver,b.field); - if constexpr (std::is_same_v) return env->GetBooleanField(receiver,b.field); -} - -template -void set(JNIEnv* env, Binding id, jobject receiver, T value) { - const auto& b = resolve(env,id); - if (!b.field || !receiver) return; - if constexpr (std::is_same_v) env->SetIntField(receiver,b.field,value); - if constexpr (std::is_same_v) env->SetDoubleField(receiver,b.field,value); - if constexpr (std::is_same_v) env->SetFloatField(receiver,b.field,value); - if constexpr (std::is_same_v) env->SetObjectField(receiver,b.field,value); - clear(env); -} - -bool is(JNIEnv* env, jobject value, Binding id) { - if (!value) return false; - auto owner = resolve(env,id).owner; - return owner && env->IsInstanceOf(value,owner); -} - -struct Local { - JNIEnv* env; - bool valid; - explicit Local(JNIEnv* value, int size = 32) : env(value), valid(env->PushLocalFrame(size) == JNI_OK) { - if (!valid) clear(env); - } - ~Local() { if (valid) env->PopLocalFrame(nullptr); } - explicit operator bool() const { return valid; } -}; - -jmethodID jmethod(JNIEnv* env, const char* owner, const char* name, const char* sig) { - auto cls = classFor(env,owner); - auto method = cls ? env->GetMethodID(cls,name,sig) : nullptr; - return clear(env) ? nullptr : method; -} -std::string string(JNIEnv* env, jobject value) { - if (!value) return {}; - auto text = static_cast(value); - auto chars = env->GetStringChars(text,nullptr); - if (!chars) { clear(env); return {}; } - const int length = env->GetStringLength(text); - const int size = WideCharToMultiByte(CP_UTF8,0,reinterpret_cast(chars),length,nullptr,0,nullptr,nullptr); - std::string result(size,'\0'); - if (size) WideCharToMultiByte(CP_UTF8,0,reinterpret_cast(chars),length,result.data(),size,nullptr,nullptr); - env->ReleaseStringChars(text,chars); - return result; -} -jstring newText(JNIEnv* env, std::string_view value) { - const int size = MultiByteToWideChar(CP_UTF8,0,value.data(),int(value.size()),nullptr,0); - std::wstring wide(size,L'\0'); - if (size) MultiByteToWideChar(CP_UTF8,0,value.data(),int(value.size()),wide.data(),size); - return env->NewString(reinterpret_cast(wide.data()),size); -} -std::string component(JNIEnv* env, jobject value) { return string(env,call(env,plain,value)); } -std::string objectText(JNIEnv* env, jobject value) { - static auto toString = jmethod(env,"java.lang.Object","toString","()Ljava/lang/String;"); - if (!value || !toString) return {}; - auto result = env->CallObjectMethod(value,toString); - return clear(env) ? std::string{} : string(env,result); -} -std::string localized(JNIEnv* env, const std::string& key) { - auto args = env->NewObjectArray(0,classFor(env,"java.lang.Object"),nullptr); - return string(env,call(env,translate,nullptr,newText(env,key),args)); -} -Vec coordinates(JNIEnv* env,jobject actor) { - return {call(env,playerX,actor),call(env,playerY,actor),call(env,playerZ,actor)}; -} -Vec vector(JNIEnv* env,jobject vec) { - return {field(env,vecX,vec),field(env,vecY,vec),field(env,vecZ,vec)}; -} - -template -void each(JNIEnv* env, jobject values, unsigned maximum, Function&& function) { - static auto iterator = jmethod(env,"java.lang.Iterable","iterator","()Ljava/util/Iterator;"); - static auto hasNext = jmethod(env,"java.util.Iterator","hasNext","()Z"); - static auto next = jmethod(env,"java.util.Iterator","next","()Ljava/lang/Object;"); - if (!values || !iterator || !hasNext || !next) return; - auto it = env->CallObjectMethod(values,iterator); - if (clear(env) || !it) return; - while (maximum-- && env->CallBooleanMethod(it,hasNext)) { - Local locals(env); - if (!locals) break; - auto entry = env->CallObjectMethod(it,next); - if (clear(env) || !entry || !function(entry)) break; - } - clear(env); -} - -Item item(JNIEnv* env,jobject stack) { - if (!stack || call(env,emptyStack,stack)) return {}; - return {component(env,call(env,itemName,stack)),string(env,call(env,itemDescription,stack)), - call(env,count,stack),call(env,itemDamage,stack),call(env,itemMaxDamage,stack)}; -} -Actor actor(JNIEnv* env,jobject value) { - Actor entry; - entry.id = call(env,entityId,value); - entry.pos = coordinates(env,value); - entry.name = component(env,call(env,entityName,value)); - entry.type = string(env,call(env,typeName,call(env,entityType,value))); - entry.height = call(env,entityHeight,value); - entry.hp = call(env,health,value); - entry.maxHp = call(env,maxHealth,value); - entry.player = is(env,value,Player); - entry.monster = is(env,value,Monster) || is(env,value,EnderMan); - return entry; -} - -double weaponScore(const Item& entry) { - const auto& type = entry.type; - const auto axe = type.ends_with("_axe"); - if (!axe && !type.ends_with("_sword") && !type.ends_with(".mace") && !type.ends_with(".trident")) return 0; - if (type.ends_with(".mace")) return 6; - if (type.ends_with(".trident")) return 9; - double tier = type.find("netherite") != std::string::npos ? 4 : type.find("diamond") != std::string::npos ? 3 : - type.find("iron") != std::string::npos ? 2 : type.find("stone") != std::string::npos ? 1 : 0; - return axe ? std::max(7.,6.+tier) : 4.+tier; -} - -void boxOption(JNIEnv* env,jobject options,Binding option,unsigned index,const char* wrapper,const char* sig,jvalue value,bool enabled) { - if (!enabled && !originals[index]) return; - auto setting = call(env,option,options); - if (!setting) return; - if (enabled) { - if (!originals[index]) originals[index] = env->NewGlobalRef(field(env,optRaw,setting)); - auto type = classFor(env,wrapper); - auto factory = type ? env->GetStaticMethodID(type,"valueOf",sig) : nullptr; - if (!clear(env) && factory) - set(env,optRaw,setting,env->CallStaticObjectMethodA(type,factory,&value)); - } else { - set(env,optRaw,setting,originals[index]); - env->DeleteGlobalRef(std::exchange(originals[index],nullptr)); - } -} - -bool sameLevel(JNIEnv* env,jobject world) { return worldRef && env->IsSameObject(worldRef,world); } -void changeWorld(JNIEnv* env,jobject world) { - if (sameLevel(env,world) || (!worldRef && !world)) return; - if (worldRef) env->DeleteGlobalRef(worldRef); - worldRef = world ? env->NewGlobalRef(world) : nullptr; - if (lastMessage) env->DeleteGlobalRef(std::exchange(lastMessage,nullptr)); - data.dimension.clear(); - data.realm=false; - data.online.clear(); - data.actors.clear(); - data.logouts.clear(); - data.trail.clear(); - data.chat.clear(); - data.sounds.clear(); - data.projectile.clear(); - data.targetTime = {}; - data.joined = Clock::now(); - data.worldChanged = true; - data.distance = 0; - data.speed = 0; - data.containers = 0; - data.foundFortress = data.scanning = false; - scan = {}; - lastPlayers.clear(); - lastOnline.clear(); - soundSeen.clear(); - dayOverride = weatherOverride = false; - nightWarned=healthWarned=hungerWarned=armorWarned=lastWindowContainer=false; - transfer = 0; - if (world) { - ++data.joins; - auto dimension = call(env,worldDim,world); - data.dimension = objectText(env,call(env,dimensionLocation,dimension)); - if (modules[Notifier].on) tell("world",data.dimension); - } -} - -void scanFortress(JNIEnv* env,jobject world) { - if (!modules[Fortress].on || data.dimension != "minecraft:the_nether") { - data.scanning = false; - data.foundFortress = false; - return; - } - if (std::exchange(queuedFortress,false)) { - data.scanning = true; - data.foundFortress = false; - data.scanned = 0; - scan = {}; - const int cx = int(std::floor(data.position.x/16)), cz = int(std::floor(data.position.z/16)); - const int radius = (settings.fortressRadius+15)/16; - for (int dx=-radius; dx<=radius; ++dx) - for (int dz=-radius; dz<=radius; ++dz) - if (dx*dx+dz*dz <= radius*radius) scan.chunks.emplace_back(cx+dx,cz+dz); - std::ranges::sort(scan.chunks,[&](auto a,auto b) { - auto distance = [&](auto p) { return std::hypot(p.first-cx,p.second-cz); }; - return distance(a)GetStaticMethodID(predicateClass,"isEqual","(Ljava/lang/Object;)Ljava/util/function/Predicate;") : nullptr; - if (!equal || !brickState || !source || clear(env)) { data.scanning = false; return; } - auto predicate = env->CallStaticObjectMethod(predicateClass,equal,brickState); - if (clear(env) || !predicate) return; - const int bottom = call(env,worldBottom,world); - const auto deadline = Clock::now()+std::chrono::microseconds(850); - while (scan.chunk < scan.chunks.size() && Clock::now()(call(env,chunkSections,chunk)); - const auto length = sections ? unsigned(env->GetArrayLength(sections)) : 0; - if (scan.section >= length) { - ++scan.chunk; - ++data.scanned; - scan.section = scan.block = 0; - scan.palette = false; - scan.bricks = 0; - scan.sum = {}; - continue; - } - auto section = env->GetObjectArrayElement(sections,scan.section); - if (!scan.palette && !call(env,sectionContains,section,predicate)) { - ++scan.section; - continue; - } - scan.palette = true; - while (scan.block < 4096 && Clock::now()>4)&15, y=scan.block>>8; - ++scan.block; - auto state = call(env,sectionBlock,section,x,y,z); - if (!env->IsSameObject(state,brickState)) continue; - scan.sum = scan.sum + Vec{cx*16+x+.5,bottom+int(scan.section)*16+y+.5,cz*16+z+.5}; - if (++scan.bricks >= 20) { - data.fortress = scan.sum*(1./scan.bricks); - data.foundFortress = true; - data.scanning = false; - tell("fortress finder","nether brick cluster found"); - return; - } - } - if (scan.block == 4096) { ++scan.section; scan.block=0; scan.palette=false; } - } - if (scan.chunk == scan.chunks.size()) { data.scanning = false; tell("fortress finder","no fortress blocks in the scanned chunks"); } -} - -} - -double Vec::length() const { return std::sqrt(x*x+y*y+z*z); } - -bool attach(JNIEnv* env,jvmtiEnv* jvmti) { - if (loader) return data.javaReady; - jint total{}; - jclass* loaded{}; - if (jvmti->GetLoadedClasses(&total,&loaded) != JVMTI_ERROR_NONE) return false; - for (int i=0; iGetClassSignature(loaded[i],&signature,nullptr) == JVMTI_ERROR_NONE) { - const auto name = std::string_view(signature); - if (name=="Lnet/minecraft/client/Minecraft;" || name=="Lfgo;") { - jobject instance{}; - if (jvmti->GetClassLoader(loaded[i],&instance) == JVMTI_ERROR_NONE && instance) { - naming = name=="Lfgo;"; - loader = env->NewGlobalRef(instance); - classes.emplace(declarations[Minecraft].owner[naming],static_cast(env->NewGlobalRef(loaded[i]))); - env->DeleteLocalRef(instance); - } - } - jvmti->Deallocate(reinterpret_cast(signature)); - } - } - env->DeleteLocalRef(loaded[i]); - } - jvmti->Deallocate(reinterpret_cast(loaded)); - if (!loader) { data.status="waiting for Java 1.21.1 classes"; return false; } - auto loaderClass = env->GetObjectClass(loader); - loadClass = env->GetMethodID(loaderClass,"loadClass","(Ljava/lang/String;)Ljava/lang/Class;"); - env->DeleteLocalRef(loaderClass); - if (clear(env) || !loadClass) return false; - Local refs(env); - if (!refs) return false; - auto version = call(env,worldVersion,nullptr); - const auto name = string(env,call(env,versionName,version)); - data.javaReady = name=="1.21.1" && resolve(env,mcGet).method && resolve(env,mcWorld).field && resolve(env,mcPlayer).field; - data.status = data.javaReady ? (naming ? "Java 1.21.1 / vanilla mappings" : "Java 1.21.1 / Mojang names") - : "unsupported Java build or runtime mappings"; - return data.javaReady; -} - -void mouse(JNIEnv* env,bool open) { - if (!data.javaReady) return; - Local refs(env); - if (!refs) return; - auto mc = call(env,mcGet,nullptr); - auto handler = field(env,mcMouse,mc); - if (open) { - menuReleasedMouse = call(env,mouseGrabbed,handler); - act(env,mouseRelease,handler); - act(env,releaseKeys,nullptr); - } else if (std::exchange(menuReleasedMouse,false) && !field(env,mcScreen,mc)) { - act(env,mouseGrab,handler); - } -} - -void setChatHidden(bool hidden) { chatHidden = hidden; } -void requestFortress() { queuedFortress = true; } -void requestTransfer(bool dump,std::string filter,bool exact) { - if (!data.containerTransfer || data.containerCursor) return; - transfer = dump ? 2 : 1; - transferFilter = std::move(filter); - transferExact=exact; - nextSlot = 0; - nextTransfer={}; -} -void stopTransfer() { transfer=0; } -void readInventoryPicker(bool open) { inventoryPicker=open; } -void submit(std::string line) { sentChat = std::move(line); } -void click(bool right) { clicks[right].push_back(Clock::now()); lastActivity=Clock::now(); } -void orbit(double dx,double dy) { orbitX+=dx; orbitY+=dy; } - -namespace { - -void syncChat(JNIEnv* env,jobject mc,jobject connection) { - if (!modules[Chat].on && !modules[Notifier].on && !nativeChatHidden) return; - auto gui = field(env,mcGui,mc); - auto chat = call(env,guiChat,gui); - auto history = field(env,chatMessages,chat); - std::vector fresh; - bool initialized = lastMessage != nullptr; - bool head = true; - jobject newHead{}; - each(env,history,initialized ? 40u : 100u,[&](jobject entry) { - if (lastMessage && env->IsSameObject(lastMessage,entry)) return false; - if (head) { newHead = env->NewGlobalRef(entry); head = false; } - fresh.push_back(component(env,call(env,chatContent,entry))); - return true; - }); - if (newHead) { - if (lastMessage) env->DeleteGlobalRef(lastMessage); - lastMessage = newHead; - } - for (auto it=fresh.rbegin(); it!=fresh.rend(); ++it) { - if (it->empty()) continue; - data.chat.push_back({*it,Clock::now()}); - if (data.chat.size()>120) data.chat.pop_front(); - if (initialized && modules[Notifier].on && settings.messages) - tell(it->starts_with('<') && it->find('>')!=std::string::npos ? "chat":"system",*it); - } - if (chatHidden && modules[Chat].on) { - auto visible = field(env,chatLines,chat); - static auto clearList = jmethod(env,"java.util.List","clear","()V"); - if (visible && clearList) { env->CallVoidMethod(visible,clearList); clear(env); } - nativeChatHidden=true; - } else if (std::exchange(nativeChatHidden,false)) { - act(env,restoreChatLines,chat); - } - if (modules[Chat].on && !sentChat.empty() && connection) { - auto text = std::exchange(sentChat,{}); - const bool command = text.front()=='/'; - if (command) text.erase(text.begin()); - if (!text.empty()) act(env,command ? sendCommand : sendChat,connection,newText(env,text)); - } -} - -void updateOnline(JNIEnv* env,jobject connection) { - if (!modules[Tab].on && !modules[Logout].on && !modules[Notifier].on) return; - static auto name = jmethod(env,"com.mojang.authlib.GameProfile","getName","()Ljava/lang/String;"); - if (!name) return; - std::unordered_map players; - data.online.clear(); - each(env,call(env,connectionPlayers,connection),512,[&](jobject value) { - auto info = call(env,profile,value); - auto text = info ? env->CallObjectMethod(info,name) : nullptr; - if (clear(env) || !text) return true; - auto username = string(env,text); - if (!username.empty()) { - auto ping = call(env,latency,value); - players.emplace(username,ping); - data.online.emplace_back(username,ping); - } - return true; - }); - if (!lastOnline.empty() && modules[Logout].on) - for (const auto& [id, player] : lastPlayers) - if (!players.contains(player.name) && lastOnline.contains(player.name)) { - std::erase_if(data.logouts,[&](const auto& old){return old.name==player.name;}); - data.logouts.push_back({player.name,data.dimension,player.pos}); - if (data.logouts.size()>64) data.logouts.erase(data.logouts.begin()); - if (modules[Notifier].on) tell("logout",player.name); - } - std::erase_if(data.logouts,[&](const auto& spot){return players.contains(spot.name);}); - lastOnline=std::move(players); - std::ranges::sort(data.online); -} - -void readActors(JNIEnv* env,jobject world,jobject player) { - data.actors.clear(); - if (!modules[EntityCount].on && !modules[Radar].on && !modules[Tracers].on && - !modules[Logout].on && !modules[BetterTags].on && !modules[Target].on && !(modules[FriendsLocator].on && data.realm)) return; - each(env,call(env,worldEntities,world),1024,[&](jobject value) { - if (env->IsSameObject(value,player) || !is(env,value,LivingEntity) || - !call(env,entityAlive,value) || call(env,entityInvisible,value)) return true; - if ((coordinates(env,value)-data.position).length()>128) return true; - auto entry = actor(env,value); - if (entry.player) lastPlayers.insert_or_assign(entry.id,entry); - if (entry.id==data.target.id && data.targetTime!=Clock::time_point{}) { - entry.portrait=data.target.portrait; - data.target=entry; - } - data.actors.push_back(std::move(entry)); - return true; - }); - if (lastPlayers.size()>1024) lastPlayers.clear(); -} - -void readSounds(JNIEnv* env,jobject mc) { - if (!modules[SoundIndicators].on) { data.sounds.clear(); soundSeen.clear(); return; } - const auto now=Clock::now(); - while (!data.sounds.empty() && now-data.sounds.front().heard>std::chrono::milliseconds(1500)) data.sounds.pop_front(); - auto engine=field(env,soundEngine,call(env,mcSound,mc)); - auto active=field(env,soundChannels,engine); - static auto keys=jmethod(env,"java.util.Map","keySet","()Ljava/util/Set;"); - static auto system=classFor(env,"java.lang.System"); - static auto identity=system ? env->GetStaticMethodID(system,"identityHashCode","(Ljava/lang/Object;)I") : nullptr; - if (!active || !keys || !identity || clear(env)) return; - auto values=env->CallObjectMethod(active,keys); - if (clear(env)) return; - each(env,values,160,[&](jobject value) { - if (!is(env,value,SoundInstance) || call(env,soundRelative,value)) return true; - const jint key=env->CallStaticIntMethod(system,identity,value); - if (clear(env)) return true; - const bool first=soundSeen.insert_or_assign(key,now).second; - if (!first) return true; - const Vec position{call(env,soundX,value),call(env,soundY,value),call(env,soundZ,value)}; - const auto distance=(position-data.position).length(); - if (distance<1.3 || distance>48) return true; - auto name=objectText(env,call(env,soundId,value)); - if (name.empty()) return true; - if (auto colon=name.find(':'); colon!=std::string::npos) name.erase(0,colon+1); - data.sounds.push_back({std::move(name),position,now}); - if (data.sounds.size()>16) data.sounds.pop_front(); - return true; - }); - std::erase_if(soundSeen,[&](const auto& entry){return now-entry.second>std::chrono::seconds(3);}); -} - -void readItems(JNIEnv* env,jobject player,jobject inventoryObject) { - data.selected=std::clamp(field(env,selected,inventoryObject),0,8); - if (modules[AutoWeapon].on || modules[MobAttack].on || modules[Trajectories].on) { - for (int slot=0;slot<9;++slot) { - Local refs(env); - if (!refs) break; - data.hotbar[slot]=item(env,call(env,inventoryStack,inventoryObject,slot)); - } - } - if (modules[Tool].on || modules[Durability].on) data.held=item(env,call(env,mainHand,player)); - if (modules[Tool].on) data.offhand=item(env,call(env,offHand,player)); - if (modules[Armor].on) { - data.armor.clear(); - each(env,call(env,armor,player),4,[&](jobject value) { data.armor.push_back(item(env,value)); return true; }); - } - if (modules[Effects].on) { - data.effects.clear(); - each(env,call(env,effects,player),32,[&](jobject value) { - const int duration=call(env,effectDuration,value); - const int level=call(env,effectAmplifier,value)+1; - const auto label=localized(env,string(env,call(env,effectName,value))); - data.effects.push_back(label+" "+std::to_string(level)+(duration<0 ? " infinite" : " "+std::to_string((duration+19)/20)+"s")); - return true; - }); - } - if (modules[Durability].on) { - const auto& held=data.held; - const bool worn=held.maximum>0 && held.maximum-held.used<=std::max(5,held.maximum/10); - if (worn && !armorWarned) tell("durability",held.name+" is almost broken"); - armorWarned=worn; - } -} - -void notifyWorld(JNIEnv* env,jobject world) { - if (!modules[Notifier].on) return; - const auto day=call(env,worldDay,world)%24000; - if (settings.notifyNight && !dayOverride && data.dimension=="minecraft:overworld") { - const bool night=day>=12542 && day<23460; - if (night && !nightWarned) tell("night","you can sleep now"); - nightWarned=night; - } - if (settings.notifyHealth && data.maxHp>0) { - if (data.hp>0 && data.hp<=data.maxHp*.25f && !healthWarned) { - tell("low health","health is below 25%"); - healthWarned=true; - } - if (data.hp>data.maxHp*.4f || data.hp<=0) healthWarned=false; - } - if (settings.notifyHunger) { - if (data.food<=6 && !hungerWarned) { tell("low hunger","sprinting is limited"); hungerWarned=true; } - if (data.food>8) hungerWarned=false; - } -} - -Vec direction(float yaw,float pitch) { - const auto y=yaw*std::numbers::pi/180, p=pitch*std::numbers::pi/180; - return {-std::sin(y)*std::cos(p),-std::sin(p),std::cos(y)*std::cos(p)}; -} - -void simulate(JNIEnv* env,jobject world) { - data.projectile.clear(); - const auto& type = data.hotbar[data.selected].type; - double speed{}, gravity=.03; - if (type.ends_with(".ender_pearl") || type.ends_with(".snowball") || type.ends_with(".egg")) speed=1.5; - if (type.ends_with(".experience_bottle")) { speed=.7; gravity=.07; } - if (type.ends_with(".splash_potion") || type.ends_with(".lingering_potion")) { speed=.5; gravity=.05; } - if (type.ends_with(".bow")) { speed=3; gravity=.05; } - if (type.ends_with(".crossbow")) { speed=3.15; gravity=.05; } - if (type.ends_with(".trident")) { speed=2.5; gravity=.05; } - if (!speed || !modules[Trajectories].on || data.orbiting) return; - auto pos=data.camera; - auto velocity=direction(data.yaw,data.pitch)*speed; - data.projectile.push_back(pos); - for (int i=0;i<55;++i) { - const auto step=velocity*(1./std::max(1,int(std::ceil(velocity.length()*3)))); - const int steps=std::max(1,int(std::ceil(velocity.length()*3))); - bool landed=false; - for (int j=0;j(env,stateAir,state)) { landed=true; break; } - pos=point; - } - data.projectile.push_back(pos); - if (landed) break; - velocity=velocity*.99; - velocity.y-=gravity; - } -} - -void inventoryScreen(JNIEnv* env,jobject mc,jobject screen,jobject player,jobject inventoryObject) { - auto menu=player && modules[InventoryTools].on && data.inContainer ? field(env,screenMenu,screen):nullptr; - if (menu && env->IsSameObject(menu,field(env,playerMenu,player))) menu=nullptr; - if (!env->IsSameObject(transferMenu,menu)) { - if (transferMenu) env->DeleteGlobalRef(transferMenu); - transferMenu=menu ? env->NewGlobalRef(menu):nullptr; - ++data.containerEpoch; - transfer=0; - nextPicker={}; - for (auto& choices:data.inventoryChoices) choices.clear(); - } - data.containerTransfer=menu!=nullptr; - auto carried=call(env,menuCarried,menu); - data.containerCursor=carried && !call(env,emptyStack,carried); - if (!menu || data.containerCursor) transfer=0; - data.containerBusy=transfer!=0; - const auto now=Clock::now(); - const bool sample=inventoryPicker && now>=nextPicker; - if (!menu || (!sample && (!transfer || nowCallIntMethod(slots,size); - if (clear(env)) { transfer=0; return; } - if (sample) { - nextPicker=now+std::chrono::milliseconds(175); - for (auto& choices:data.inventoryChoices) choices.clear(); - for (int i=0;iCallObjectMethod(slots,at,i); - if (clear(env) || !slot) continue; - const bool own=env->IsSameObject(field(env,slotContainer,slot),inventoryObject); - if (own && !settings.inventoryHotbar && call(env,slotNumber,slot)<9) continue; - auto value=item(env,call(env,slotItem,slot)); - if (!value.count || value.type.empty()) continue; - auto& choices=data.inventoryChoices[own]; - auto existing=std::ranges::find_if(choices,[&](const Item& entry){return entry.type==value.type;}); - if (existing==choices.end()) choices.push_back(std::move(value)); else existing->count+=value.count; - } - for (auto& choices:data.inventoryChoices) std::ranges::sort(choices,{},&Item::name); - } - if (!transfer || nowCallObjectMethod(slots,at,i); - if (clear(env) || !slot) continue; - if (bool(env->IsSameObject(field(env,slotContainer,slot),inventoryObject))!=(transfer==2)) continue; - if (transfer==2 && !settings.inventoryHotbar && call(env,slotNumber,slot)<9) continue; - auto stack=call(env,slotItem,slot); - if (!stack || call(env,emptyStack,stack)) continue; - if (!transferFilter.empty()) { - auto entry=item(env,stack); - if (transferExact) { - if (entry.type!=transferFilter) continue; - } else { - auto lower=[](std::string& value){for (char& c:value) if (c>='A' && c<='Z') c=char(c+32);}; - lower(entry.name); lower(transferFilter); - if (entry.name.find(transferFilter)==std::string::npos && entry.type.find(transferFilter)==std::string::npos) continue; - } - } - act(env,playerClick,field(env,mcGameMode,mc),field(env,menuId,menu),i,0,field(env,quickMove),player); - nextTransfer=now+std::chrono::milliseconds(settings.inventoryDelay); - return; - } - transfer=0; -} - -void optionsUpdate(JNIEnv* env,jobject options,jobject world,jobject player,bool active) { - const bool zooming=active && modules[Zoom].on && (GetAsyncKeyState('C')&0x8000); - jvalue value{}; - value.i=int(zooming ? settings.zoom : settings.fov); - boxOption(env,options,optFov,0,"java.lang.Integer","(I)Ljava/lang/Integer;",value,zooming || modules[Fov].on); - value.d=settings.gamma; - boxOption(env,options,optGamma,1,"java.lang.Double","(D)Ljava/lang/Double;",value,modules[Fullbright].on); - value.d=settings.entityDistance; - boxOption(env,options,optEntityDistance,2,"java.lang.Double","(D)Ljava/lang/Double;",value,modules[Optimize].on); - if (modules[ParticleControls].on || originals[3]) { - auto option=call(env,optParticles,options); - if (option && modules[ParticleControls].on) { - if (!originals[3]) originals[3]=env->NewGlobalRef(field(env,optRaw,option)); - if (auto status=field(env,settings.particleMode ? particlesMinimal : particlesLow)) - set(env,optRaw,option,status); - } else if (option && originals[3]) { - set(env,optRaw,option,originals[3]); - env->DeleteGlobalRef(std::exchange(originals[3],nullptr)); - } - } - if (!world || !player) return; - if (modules[ClientTime].on) { - if (!dayOverride) oldDay=call(env,worldDay,world); - dayOverride=true; - act(env,worldSetDay,world,jlong(settings.time)); - } else if (std::exchange(dayOverride,false)) act(env,worldSetDay,world,oldDay); - if (modules[Atmosphere].on) { - if (!weatherOverride) { - oldRain=call(env,worldRain,world,1.f); - oldThunder=call(env,worldThunder,world,1.f); - } - weatherOverride=true; - act(env,worldSetRain,world,settings.rain); - act(env,worldSetThunder,world,settings.thunder); - } else if (std::exchange(weatherOverride,false)) { - act(env,worldSetRain,world,oldRain); - act(env,worldSetThunder,world,oldThunder); - } - if (modules[NameChanger].on && *settings.displayName) { - if (!nameOverride) { - auto name=call(env,customName,player); - savedName=name ? env->NewGlobalRef(name) : nullptr; - } - nameOverride=true; - act(env,setName,player,call(env,literal,nullptr,newText(env,settings.displayName))); - } else if (std::exchange(nameOverride,false)) { - act(env,setName,player,savedName); - if (savedName) env->DeleteGlobalRef(std::exchange(savedName,nullptr)); - } -} - -void freelook(JNIEnv* env,jobject mc,jobject options,jobject world,jobject player,bool active) { - const bool holding=active && player && world && modules[Freelook].on && (GetAsyncKeyState(VK_LMENU)&0x8000); - if (holding && !freeActive) { - auto entity=call(env,newCameraActor,nullptr,field(env,armorStandType),world); - if (!entity) return; - auto mode=call(env,optCameraType,options); - if (!mode) return; - cameraMode=env->NewGlobalRef(mode); - cameraActor=env->NewGlobalRef(entity); - freeActive=data.orbiting=true; - freeYaw=data.yaw; - freePitch=data.pitch; - act(env,setCamera,mc,cameraActor); - act(env,optSetCameraType,options,field(env,thirdPerson)); - } - if (holding && freeActive) { - freeYaw=std::remainder(freeYaw+float(std::exchange(orbitX,0.)*.15),360.f); - freePitch=std::clamp(freePitch+float(std::exchange(orbitY,0.)*.15),-89.f,89.f); - act(env,entitySetPos,cameraActor,data.position.x,data.position.y,data.position.z); - set(env,oldX,cameraActor,data.position.x); - set(env,oldY,cameraActor,data.position.y); - set(env,oldZ,cameraActor,data.position.z); - set(env,oldYaw,cameraActor,freeYaw); - set(env,oldPitch,cameraActor,freePitch); - act(env,setYaw,cameraActor,freeYaw); - act(env,setPitch,cameraActor,freePitch); - } else if (std::exchange(freeActive,false)) { - data.orbiting=false; - if (env->IsSameObject(call(env,currentCamera,mc),cameraActor)) act(env,setCamera,mc,player); - if (cameraMode) { - act(env,optSetCameraType,options,cameraMode); - env->DeleteGlobalRef(std::exchange(cameraMode,nullptr)); - } - if (cameraActor) env->DeleteGlobalRef(std::exchange(cameraActor,nullptr)); - orbitX=orbitY=0; - } -} - -void actions(JNIEnv* env,jobject mc,jobject world,jobject player,jobject inventoryObject,jobject options,jobject hit,bool active) { - if (!active) { toolPress=weaponPress=false; } - const auto now=Clock::now(); - const bool left=active && (GetAsyncKeyState(VK_LBUTTON)&0x8000); - const bool right=active && (GetAsyncKeyState(VK_RBUTTON)&0x8000); - const bool forward=active && call(env,keyDown,field(env,forwardKey,options)); - if (left || right || forward || GetAsyncKeyState('A')&0x8000 || GetAsyncKeyState('D')&0x8000 || - GetAsyncKeyState('S')&0x8000 || GetAsyncKeyState(VK_SPACE)&0x8000) lastActivity=now; - if (modules[ToggleSprint].on && forward && data.food>6 && !data.usingItem) { - act(env,setSprint,player,true); - sprintForced=true; - } else if (std::exchange(sprintForced,false) && !call(env,keyDown,field(env,sprintKey,options))) { - act(env,setSprint,player,false); - } - if (!active || !player) return; - if (modules[AutoTool].on && left && data.blockTarget && !toolPress) { - auto state=call(env,worldBlock,world,call(env,targetBlock,hit)); - int best=data.selected; - float speed=1; - for (int i=0;i<9;++i) { - Local refs(env); - if (!refs) break; - auto stack=call(env,inventoryStack,inventoryObject,i); - const auto value=call(env,toolSpeed,stack,state); - if (value>speed) { best=i; speed=value; } - } - set(env,selected,inventoryObject,best); - toolPress=true; - } - if (!left) toolPress=weaponPress=false; - if (modules[AutoWeapon].on && left && is(env,hit,EntityHitResult) && !weaponPress) { - int best=data.selected; - for (int i=0;i<9;++i) - if (weaponScore(data.hotbar[i])>weaponScore(data.hotbar[best])) best=i; - set(env,selected,inventoryObject,best); - weaponPress=true; - } - if (modules[EndermanLook].on && !data.orbiting && is(env,hit,EntityHitResult)) { - auto aimed=call(env,targetEntity,hit); - if (is(env,aimed,EnderMan)) { - const auto delta=data.hitLocation-coordinates(env,aimed); - if (delta.y>call(env,entityHeight,aimed)*.79f) act(env,setPitch,player,std::min(85.f,data.pitch+28.f)); - } - } - if (modules[AutoClick].on && now>=nextClick && (settings.rightClick ? right : left) && !data.usingItem) { - if (settings.rightClick) act(env,mcUse,mc); - else call(env,mcAttack,mc); - nextClick=now+std::chrono::milliseconds(int(1000/std::max(1.f,settings.cps))); - } - if (modules[MobAttack].on && now>=nextAttack && !data.usingItem && weaponScore(data.hotbar[data.selected])>0 && - call(env,attackStrength,player,.5f)>=.95f) { - nextAttack=now+std::chrono::milliseconds(70); - const bool canCrit=!data.onGround && field(env,fallDistance,player)>0 && - !call(env,entityWater,player) && !call(env,entityPassenger,player); - if (!settings.critical || canCrit) { - double best=settings.mobRange; - jobject target{}; - each(env,call(env,worldEntities,world),512,[&](jobject candidate) { - if (is(env,candidate,Player) || !(is(env,candidate,Monster) || is(env,candidate,EnderMan) || - (settings.animals && is(env,candidate,Animal))) || !call(env,entityAlive,candidate)) return true; - const auto distance=(coordinates(env,candidate)-data.position).length(); - if (distance(env,entityVisible,player,candidate)) { - if (target) env->DeleteGlobalRef(target); - target=env->NewGlobalRef(candidate); - best=distance; - } - return true; - }); - if (target) { - act(env,playerAttack,field(env,mcGameMode,mc),player,target); - act(env,swing,player,field(env,handMain)); - env->DeleteGlobalRef(target); - } - } - } - if (modules[AntiAfk].on && now-lastActivity>std::chrono::seconds(settings.antiAfkSeconds)) { - act(env,swing,player,field(env,handMain)); - lastActivity=now; - } -} - -} // namespace - -void update(JNIEnv* env,bool active,bool menu) { - if (!data.javaReady) return; - Local refs(env,128); - if (!refs) return; - auto mc=call(env,mcGet,nullptr); - if (!mc) return; - auto world=field(env,mcWorld,mc), player=field(env,mcPlayer,mc), screen=field(env,mcScreen,mc); - auto options=field(env,mcOptions,mc); - data.inWorld=world && player; - data.inScreen=screen!=nullptr; - data.inContainer=is(env,screen,AbstractContainerScreen); - data.guiHidden=field(env,hideGui,options); - data.worldChanged=false; - if (!sameLevel(env,world) && nameOverride) { - if (savedName) env->DeleteGlobalRef(std::exchange(savedName,nullptr)); - nameOverride=false; - } - changeWorld(env,world); - const auto now=Clock::now(); - active=active && data.inWorld && !screen && !menu; - if (player) { - data.yaw=call(env,entityYaw,player); - data.pitch=call(env,entityPitch,player); - data.position=coordinates(env,player); - } - freelook(env,mc,options,world,player,active); - if (data.inWorld && (modules[Waypoints].on || modules[Target].on || modules[Trajectories].on || modules[Outlines].on || - modules[Tracers].on || modules[Breadcrumbs].on || modules[Logout].on || modules[BetterTags].on || modules[Fortress].on || - modules[FriendsLocator].on || modules[SoundIndicators].on)) { - auto renderer=field(env,mcRenderer,mc); - auto camera=call(env,rendererCamera,renderer); - data.camera=vector(env,call(env,camPos,camera)); - data.cameraYaw=call(env,camYaw,camera); - data.cameraPitch=call(env,camPitch,camera); - const auto view=call(env,rendererFov,renderer,camera,1.f,true); - data.cameraFov=view>1 ? float(view) : 70.f; - } - if (now(env,mcFps,mc); - if (data.playerName.empty()) data.playerName=string(env,call(env,userName,call(env,mcUser,mc))); - for (int i=0;i<2;++i) { - while (!clicks[i].empty() && now-clicks[i].front()>std::chrono::seconds(1)) clicks[i].pop_front(); - (i ? data.rightCps : data.leftCps)=int(clicks[i].size()); - } - if (!data.inWorld) { inventoryScreen(env,mc,nullptr,nullptr,nullptr); return; } - if (data.inContainer && !lastWindowContainer) ++data.containers; - lastWindowContainer=data.inContainer; - auto inventoryObject=call(env,inventory,player); - auto hit=field(env,mcHit,mc); - data.usingItem=call(env,usingItem,player); - data.onGround=call(env,entityGround,player); - data.food=call(env,foodLevel,call(env,food,player)); - data.xp=field(env,xpProgress,player); - data.xpLevel=field(env,xpLevel,player); - data.xpNext=call(env,xpNext,player); - if (modules[Xp].on && settings.xpLock) { - auto gui=field(env,mcGui,mc); - data.hotbarTextTicks=std::max(field(env,guiHeldTimer,gui),field(env,guiOverlayTimer,gui)); - } - data.hp=call(env,health,player); - data.maxHp=call(env,maxHealth,player); - notifyWorld(env,world); - static Vec previous; - static Clock::time_point last; - if (last!=Clock::time_point{} && !data.worldChanged && data.joined(now-last).count()); - if (distance<10) data.distance+=distance; - } - previous=data.position; - last=now; - if (modules[Breadcrumbs].on && (data.trail.empty() || (data.position-data.trail.back()).length()>.36)) { - data.trail.push_back(data.position); - if (data.trail.size()>512) data.trail.pop_front(); - } - data.blockTarget=is(env,hit,BlockHitResult) && objectText(env,call(env,hitType,hit))=="BLOCK"; - data.hitLocation=vector(env,call(env,hitLocation,hit)); - data.looking.clear(); - if (data.blockTarget && (modules[Outlines].on || modules[Looking].on)) { - auto pos=call(env,targetBlock,hit); - data.hitBlock={double(call(env,posX,pos)),double(call(env,posY,pos)),double(call(env,posZ,pos))}; - if (modules[Looking].on) { - auto block=call(env,stateBlock,call(env,worldBlock,world,pos)); - data.looking=localized(env,string(env,call(env,blockName,block))); - } - } - if (is(env,hit,EntityHitResult) && (modules[Looking].on || modules[Target].on)) { - auto entity=call(env,targetEntity,hit); - if (is(env,entity,LivingEntity) && call(env,entityAlive,entity)) { - data.target=actor(env,entity); - if (modules[Target].on && is(env,entity,AbstractClientPlayer)) { - auto location=call(env,skinResource,call(env,skin,entity)); - auto manager=call(env,textures,mc); - auto image=location ? call(env,texture,manager,location) : nullptr; - data.target.portrait=unsigned(call(env,textureId,image)); - } - data.targetTime=now; - data.looking=data.target.name; - } - } - readItems(env,player,inventoryObject); - auto connection=call(env,mcConn,mc); - syncChat(env,mc,connection); - if (now>=nextActors) { - nextActors=now+std::chrono::milliseconds(175); - data.realm=modules[FriendsLocator].on && call(env,realmServer,call(env,mcServer,mc)); - readActors(env,world,player); - readSounds(env,mc); - updateOnline(env,connection); - simulate(env,world); - } - inventoryScreen(env,mc,screen,player,inventoryObject); - actions(env,mc,world,player,inventoryObject,options,hit,active); - data.sprinting=sprintForced; - scanFortress(env,world); -} - -void restoreFeatures(JNIEnv* env) { - Local refs(env,96); - if (refs && data.javaReady) { - auto mc=call(env,mcGet,nullptr); - auto options=field(env,mcOptions,mc), world=field(env,mcWorld,mc), player=field(env,mcPlayer,mc); - std::array enabled{}; - for (int i=0;iDeleteGlobalRef(cls); - classes.clear(); - for (auto& value:originals) if (value) env->DeleteGlobalRef(std::exchange(value,nullptr)); - for (auto ptr : {&loader,&worldRef,&lastMessage,&savedName,&cameraMode,&cameraActor,&transferMenu}) - if (*ptr) env->DeleteGlobalRef(std::exchange(*ptr,nullptr)); - data.javaReady=false; -} - -} // namespace java diff --git a/java-client/src/game.h b/java-client/src/game.h deleted file mode 100644 index 7a9d601..0000000 --- a/java-client/src/game.h +++ /dev/null @@ -1,122 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace java { - -using Clock = std::chrono::steady_clock; -struct Vec { - double x{}, y{}, z{}; - Vec operator+(Vec other) const { return {x + other.x, y + other.y, z + other.z}; } - Vec operator-(Vec other) const { return {x - other.x, y - other.y, z - other.z}; } - Vec operator*(double factor) const { return {x * factor, y * factor, z * factor}; } - double length() const; -}; - -struct Module { - const char* title; - const char* category; - const char* detail; - bool on = false; -}; -enum ModuleId { - Fps, Watermark, Keystrokes, Cps, Coordinates, ClockHud, Speed, Xp, Armor, Tool, Effects, Looking, - EntityCount, Tab, Radar, Target, Active, Compass, Stats, Waypoints, Breadcrumbs, Tracers, - Logout, Trajectories, Outlines, Crosshair, Fullbright, Fov, Zoom, Atmosphere, ClientTime, - BetterTags, NameChanger, Freelook, Optimize, InventoryTools, Chat, Notifier, - Durability, Fortress, MiniPlayer, AutoTool, AutoWeapon, ToggleSprint, EndermanLook, AutoClick, - MobAttack, AntiAfk, ParticleControls, FriendsLocator, SoundIndicators, Diagnostics, ModuleCount -}; -extern std::array modules; - -struct Settings { - float fov = 90, zoom = 28, gamma = 8, tracking = 16, mobRange = 3, cps = 8, entityDistance = 0.75f; - float length = 6, width = 1, gap = 3, outlineWidth = 2, rain = 0, thunder = 0; - float gapSpeed = 4, lengthSpeed = 4, spinSpeed = 2, gapEase = 12, lengthEase = 12, spinEase = 12; - float crosshairColor[4]{1,1,1,1}, crosshairGradient[4]{0.65f,0.36f,0.85f,1}; - float outlineColor[4]{0.72f,0.44f,0.91f,1}; - int time = 1000, grid = 8, fortressRadius = 96, critical = 0, antiAfkSeconds = 120, particleMode = 0; - bool animals = false, rightClick = false, messages = true, crossOutline = true, blockBlack = false; - bool gradient = false, spin = false, dynamicLength = false, dynamicGap = false, reactive = false; - bool xpLock = false, remember = false, lyrics = true, hideChat = true; - bool notifyNight = true, notifyHealth = true, notifyHunger = true; - bool inventoryButtons = true, inventoryHotbar = false; - float inventoryX = .5f, inventoryY = .1f; - int inventoryDelay = 75; - char displayName[65]{}; - char friends[256]{}; -}; -extern Settings settings; - -struct Item { - std::string name, type; - int count{}, used{}, maximum{}; -}; -struct Actor { - int id{}; - unsigned portrait{}; - Vec pos; - std::string name, type; - float height{}, hp{}, maxHp{}; - bool player{}, monster{}; -}; -struct Waypoint { std::string name, dimension; Vec pos; }; -struct Message { std::string body; Clock::time_point received; }; -struct SoundMark { std::string name; Vec position; Clock::time_point heard; }; -struct Data { - bool inWorld{}, inScreen{}, inContainer{}, guiHidden{}, usingItem{}, onGround{}; - bool worldChanged{}, javaReady{}, orbiting{}, realm{}, sprinting{}; - int fps{}, xpLevel{}, xpNext{}, food{}, selected{}, hotbarTextTicks{}; - float xp{}, yaw{}, pitch{}, cameraYaw{}, cameraPitch{}, cameraFov = 70, hp{}, maxHp{}; - double distance{}, speed{}; - Vec position, camera, hitBlock, hitLocation; - bool blockTarget{}; - std::string playerName, dimension, looking, status; - std::array hotbar; - Item held, offhand; - std::vector armor; - std::vector effects; - std::vector> online; - std::vector actors; - std::array,2> inventoryChoices; - unsigned containerEpoch{}; - bool containerTransfer{}, containerCursor{}, containerBusy{}; - std::vector waypoints, logouts; - std::deque trail; - std::deque chat; - std::deque sounds; - std::vector projectile; - Actor target; - Clock::time_point targetTime{}; - bool foundFortress{}, scanning{}; - Vec fortress; - unsigned scanned{}, toScan{}; - int leftCps{}, rightCps{}, containers{}, joins{}; - Clock::time_point joined{}; -}; -extern Data data; -extern JavaVM* vm; -bool attach(JNIEnv* env, jvmtiEnv* jvmti); -void release(JNIEnv* env); -void restoreFeatures(JNIEnv* env); -void update(JNIEnv* env, bool active, bool menu); -void mouse(JNIEnv* env, bool open); -void setChatHidden(bool hidden); -void requestFortress(); -void requestTransfer(bool dump, std::string filter, bool exact=false); -void stopTransfer(); -void readInventoryPicker(bool open); -void submit(std::string line); -void tell(std::string title, std::string body); -void click(bool right); -void orbit(double dx, double dy); -void diagnostic(std::string_view message); - -} diff --git a/java-client/src/gl_state.h b/java-client/src/gl_state.h deleted file mode 100644 index 0f9e6da..0000000 --- a/java-client/src/gl_state.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -#include -#include -#include - -namespace java::overlay { - -// The game or a graphics mod can leave a pixel buffer, offsets, or a private -// framebuffer active across SwapBuffers. ImGui uploads ordinary CPU pointers. -class GlState { - using Bind = void (APIENTRY*)(GLenum,GLuint); - static constexpr GLenum unpackBuffer = 0x88EC, unpackBinding = 0x88EF; - static constexpr GLenum drawFramebuffer = 0x8CA9, drawBinding = 0x8CA6; - static constexpr std::array pixelKeys{ - GL_UNPACK_ALIGNMENT, GL_UNPACK_ROW_LENGTH, GL_UNPACK_SKIP_PIXELS, GL_UNPACK_SKIP_ROWS, - 0x806E, 0x806D, GL_UNPACK_SWAP_BYTES, GL_UNPACK_LSB_FIRST - }; - Bind bindBuffer{}, bindFramebuffer{}; - GLint buffer{}, framebuffer{}; - std::array unpack{}; - std::array colorMask{}; - -public: - GlState() { - bindBuffer=reinterpret_cast(wglGetProcAddress("glBindBuffer")); - bindFramebuffer=reinterpret_cast(wglGetProcAddress("glBindFramebuffer")); - if (bindBuffer) { - glGetIntegerv(unpackBinding,&buffer); - if (buffer) bindBuffer(unpackBuffer,0); - } - if (bindFramebuffer) { - glGetIntegerv(drawBinding,&framebuffer); - if (framebuffer) bindFramebuffer(drawFramebuffer,0); - } - glGetBooleanv(GL_COLOR_WRITEMASK,colorMask.data()); - if (colorMask!=std::array{1,1,1,1}) glColorMask(1,1,1,1); - for (size_t i=0;i{1,1,1,1}) glColorMask(colorMask[0],colorMask[1],colorMask[2],colorMask[3]); - } -}; -} diff --git a/java-client/src/loader.cpp b/java-client/src/loader.cpp deleted file mode 100644 index 78922ae..0000000 --- a/java-client/src/loader.cpp +++ /dev/null @@ -1,144 +0,0 @@ -#include -#include -#include -#include -#include -#include - -namespace { -class Handle { - HANDLE value; -public: - explicit Handle(HANDLE handle):value(handle) {} - ~Handle() { if (valid()) CloseHandle(value); } - Handle(const Handle&)=delete; - Handle& operator=(const Handle&)=delete; - bool valid() const { return value && value!=INVALID_HANDLE_VALUE; } - operator HANDLE() const { return value; } -}; -struct GameWindow { DWORD pid; HWND hwnd; }; -BOOL CALLBACK findGame(HWND hwnd,LPARAM output) { - wchar_t name[32]{},title[256]{}; - GetClassNameW(hwnd,name,int(std::size(name))); - GetWindowTextW(hwnd,title,int(std::size(title))); - if (wcscmp(name,L"GLFW30") || !wcsstr(title,L"Minecraft") || !wcsstr(title,L"1.21.1") || - (wcsstr(title,L"1.21.1") && iswdigit(wcsstr(title,L"1.21.1")[6]))) return TRUE; - DWORD pid{}; - GetWindowThreadProcessId(hwnd,&pid); - if (pid) reinterpret_cast*>(output)->push_back({pid,hwnd}); - return TRUE; -} -uintptr_t remoteModule(DWORD pid,const std::wstring& name,bool fullPath=false) { - Handle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,pid)); - if (!snapshot.valid()) return 0; - MODULEENTRY32W entry{sizeof(entry)}; - if (Module32FirstW(snapshot,&entry)) do { - if (_wcsicmp(fullPath ? entry.szExePath : entry.szModule,name.c_str())==0) - return reinterpret_cast(entry.modBaseAddr); - } while (Module32NextW(snapshot,&entry)); - return 0; -} -LPTHREAD_START_ROUTINE remoteFunction(DWORD pid,const void* function) { - HMODULE module{}; - if (!function || !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast(function),&module)) return nullptr; - wchar_t path[32768]{}; - if (!GetModuleFileNameW(module,path,DWORD(std::size(path)))) return nullptr; - const auto base=remoteModule(pid,std::filesystem::path(path).filename().wstring()); - if (!base) return nullptr; - return reinterpret_cast(base+(reinterpret_cast(function)-reinterpret_cast(module))); -} -int error(const wchar_t* reason) { - std::wcerr << reason << L" (Windows error " << GetLastError() << L")\n"; - return 1; -} -} - -int wmain(int argc,wchar_t** argv) { - bool detach=false; - DWORD requested{}; - for (int i=1;i games; - EnumWindows(findGame,reinterpret_cast(&games)); - if (requested) std::erase_if(games,[&](auto game){return game.pid!=requested;}); - if (games.size()!=1) { - std::wcerr << L"Expected one open Minecraft Java 1.21.1 window. Open the game or select a PID.\n"; - return 2; - } - const auto pid=games.front().pid; - wchar_t executable[32768]{}; - if (!GetModuleFileNameW(nullptr,executable,DWORD(std::size(executable)))) return error(L"Could not locate the loader"); - const auto path=(std::filesystem::path(executable).parent_path()/L"amnesia-java.dll").wstring(); - if (!std::filesystem::is_regular_file(path)) { std::wcerr << L"amnesia-java.dll must be beside the loader.\n"; return 2; } - Handle process(OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION| - PROCESS_VM_WRITE|PROCESS_VM_READ,FALSE,pid)); - if (!process.valid()) return error(L"Could not open the Minecraft process"); - wchar_t image[32768]{}; - DWORD length=DWORD(std::size(image)); - if (!QueryFullProcessImageNameW(process,0,image,&length)) return error(L"Could not verify the Java process"); - const auto filename=std::filesystem::path(image).filename().wstring(); - USHORT machine{}, native{}; - if ((_wcsicmp(filename.c_str(),L"javaw.exe") && _wcsicmp(filename.c_str(),L"java.exe")) || - !IsWow64Process2(process,&machine,&native) || machine!=IMAGE_FILE_MACHINE_UNKNOWN || native!=IMAGE_FILE_MACHINE_AMD64 || - !remoteModule(pid,L"jvm.dll")) { - std::wcerr << L"The target must be a native x64 HotSpot Java process.\n"; - return 2; - } - const auto installed=remoteModule(pid,path,true); - LPTHREAD_START_ROUTINE entry{}; - void* parameter{}; - if (detach) { - if (!installed) { std::wcerr << L"The Java client is not loaded.\n"; return 2; } - const auto local=LoadLibraryExW(path.c_str(),nullptr,DONT_RESOLVE_DLL_REFERENCES); - if (!local) return error(L"Could not open the DLL export table"); - const auto exported=GetProcAddress(local,"unload"); - if (exported) entry=reinterpret_cast(installed+ - reinterpret_cast(exported)-reinterpret_cast(local)); - FreeLibrary(local); - if (!entry) return error(L"Could not find the detach export"); - } else { - if (installed || remoteModule(pid,L"amnesia-java.dll")) { - std::wcerr << L"The DLL is already resident. Restart Minecraft before loading it again.\n"; return 2; - } - entry=remoteFunction(pid,reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"),"LoadLibraryW"))); - if (!entry) return error(L"Could not resolve the target loader"); - const auto bytes=(path.size()+1)*sizeof(wchar_t); - parameter=VirtualAllocEx(process,nullptr,bytes,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE); - if (!parameter) return error(L"Could not allocate the DLL path in Minecraft"); - if (!WriteProcessMemory(process,parameter,path.c_str(),bytes,nullptr)) { - const auto status=GetLastError(); - VirtualFreeEx(process,parameter,0,MEM_RELEASE); - SetLastError(status); - return error(L"Could not send the DLL path to Minecraft"); - } - } - Handle thread(CreateRemoteThread(process,nullptr,0,entry,parameter,0,nullptr)); - if (!thread.valid()) { - const auto status=GetLastError(); - if (parameter) VirtualFreeEx(process,parameter,0,MEM_RELEASE); - SetLastError(status); - return error(L"Could not start the client loader"); - } - if (WaitForSingleObject(thread,12000)!=WAIT_OBJECT_0) { - std::wcerr << L"The operation is still pending. Check the game and amnesia-java.log.\n"; - return 1; - } - if (parameter) VirtualFreeEx(process,parameter,0,MEM_RELEASE); - if (detach) { - DWORD result{}; - if (!GetExitCodeThread(thread,&result)) return error(L"Could not confirm detach"); - if (result) { SetLastError(result); return error(L"Could not detach while waiting for a rendered frame"); } - std::wcout << L"Detached. Restart Minecraft before attaching again.\n"; - } else { - if (!remoteModule(pid,path,true)) return error(L"Minecraft could not load the DLL"); - std::wcout << L"DLL loaded into Minecraft PID " << pid << L". Press Right Shift for the menu.\n"; - } - return 0; -} diff --git a/java-client/src/overlay.cpp b/java-client/src/overlay.cpp deleted file mode 100644 index 74791af..0000000 --- a/java-client/src/overlay.cpp +++ /dev/null @@ -1,1430 +0,0 @@ -#include "overlay.h" -#include "gl_state.h" -#include "game.h" -#include "bedrock_clickgui.h" -#include "bedrock_account_screen.h" -#include "bedrock_startup_intro.h" -#include "bedrock_music_player.h" -#include "modules/fps_counter.h" -#include "modules/keystrokes.h" -#include "modules/watermark.h" -#include "modules/themes.h" -#include "gui/target_hud_layout.h" -#include "game/chat_logic.h" -#include "imgui_impl_win32.h" -#include "imgui_impl_opengl3.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND,UINT,WPARAM,LPARAM); - -namespace java::overlay { -void addNote(std::string title,std::string body); -namespace { - -constexpr UINT_PTR subclass = 0x414d4a31; -constexpr ImGuiWindowFlags hudFlags=ImGuiWindowFlags_NoDecoration|ImGuiWindowFlags_AlwaysAutoResize| - ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoNav|ImGuiWindowFlags_NoFocusOnAppearing|ImGuiWindowFlags_NoBackground; -HWND hwnd; -ImGuiContext* context; -bool& menu=g_menu_open; -bool chat, pendingMenu, pendingChat, escapeRequested, closeRequested, capture, dirty; -bool chatFocus, chatScroll; -Clock::time_point nextSave, frameStart; -double frameMs{}, updateMs{}; -std::array positions{}; -std::array renderPositions{}; -std::array sizes{}; -std::array hasPosition{}, centerX{}, centerY{}; -std::filesystem::path dir; -std::wstring credentialTarget=L"amnesia/java/remembered-login/v1"; -std::string activeProfile="default"; -std::string profileError; -char filter[128]{}, waypointName[65]="waypoint", chatInput[257]{}; -int bindingKey{}; -java_ui_modules adapters; -std::array views{}; -theme_editor* themes{}; -music_player* musicView{}; -std::vector> controls; -chat_logic::sent_history sentHistory; -java_ui_texture customIcon; -float iconAspect=1; -std::string loadedIcon; -unsigned iconRevision=~0u; -licensing::service* license; -licensing::account account; -std::array defaults{}; -struct InventoryOverlay { - ImVec2 buttons{}, picker{}, pickerSize{}; - Clock::time_point shown{}; - unsigned epoch{}; - int mode=-1,scroll{},visible{}; - bool left{},right{}; -} inventoryUi; -std::vector> defaultUi; -float chatWidth=560,chatHeight=260,chatOpacity=.96f; -bool xpPercent=true,xpRemaining=true,xpBar=true,targetBar=true,targetFollow=true; -float xpWidth=220,targetOffsetX=24,targetOffsetY=0,targetSwitch=.24f,targetLinger=2; -float chatNameColor[]{.7f,.5f,.9f,1},chatMessageColor[]{1,1,1,1},chatSystemColor[]{.65f,.65f,.65f,1}; -bool sprintStatus=true,freelookStatus=true,fortressStatus=true,fortressMarker=true; - -template -std::string formatted(const char* format,Args... args) { - char buf[256]; - const int n=std::snprintf(buf,sizeof(buf),format,args...); - return std::string(buf,n<0 ? 0 : std::min(size_t(n),sizeof(buf)-1)); -} -template -void copy(char (&dest)[N],std::string_view src) { - const auto size=std::min(src.size(),N-1); - std::copy_n(src.begin(),size,dest); - dest[size]=0; -} -void change() { dirty=true; nextSave=Clock::now()+std::chrono::milliseconds(400); } -void addPoint(Vec pos,const char* name); -void initViews(); -void mirror(bool read); -void seedTheme(); -std::string uiState(); -void readUi(std::istream& row); -void readColor(std::istream& in,float* values); -struct java_hud : text_hud { - ModuleId id; - static const char* title(ModuleId id) { - switch (id) { - case Fps: return "fps counter"; - case Cps: return "cps counter"; - case Armor: return "armor hud"; - default: return java::modules[id].title; - } - } - explicit java_hud(ModuleId value,category group) - : text_hud(title(value),java::modules[value].detail,group),id(value) { - if (id==Diagnostics) background_->bool_value=false; - } - bool is_hud() const override { - if (id==ToggleSprint) return sprintStatus; - if (id==Freelook) return freelookStatus; - if (id==Fortress) return fortressStatus; - return cat()==category::hud; - } - ImVec2 hud_size() const override { return sizes[id]; } - ImVec2 hud_render_position() const override { return renderPositions[id]; } - bool hud_position_locked() const override { return id==Xp && java::settings.xpLock; } - float scale() const { return scale_->float_value; } - bool background() const { return background_->bool_value; } - ImU32 color() const { return setting_color(*color_); } - void renderText(const char* label,const std::string& value,const char* reserve="") { - label_=label; - text_=value; - reserve_=reserve; - sizes[id]=text_hud::hud_size(); - draw_text(); - } -}; -template -void option(module& view,const char* name,T& value,T low={},T high={}) { - setting* s; - if constexpr(std::is_same_v) s=&view.add_toggle(name,value); - if constexpr(std::is_same_v) s=&view.add_float(name,value,low,high); - if constexpr(std::is_same_v) s=&view.add_int(name,value,low,high); - controls.push_back([s,&value](bool read) { - auto& source=[&]() -> T& { - if constexpr(std::is_same_v) return s->bool_value; - if constexpr(std::is_same_v) return s->float_value; - if constexpr(std::is_same_v) return s->int_value; - }(); - if (read) source=value; - else value=source; - }); -} -void mode(module& view,const char* name,int& value,std::vector modes) { - auto* s=&view.add_mode(name,std::move(modes),value); - controls.push_back([s,&value](bool read) { - if (read) s->int_value=std::clamp(value,0,int(s->modes.size()-1)); - else value=s->int_value; - }); -} -template -void textOption(module& view,const char* name,char (&value)[N]) { - auto* s=&view.add_text(name,value,int(N-1)); - controls.push_back([s,&value](bool read) { if (read) s->text_value=value; else copy(value,s->text_value); }); -} -void colorOption(module& view,const char* name,float (&value)[4]) { - auto* s=&view.add_color(name,value[0],value[1],value[2],value[3]); - controls.push_back([s,&value](bool read) { if (read) std::copy_n(value,4,s->color); else std::copy_n(s->color,4,value); }); -} -void initViews() { - auto themeView=std::make_unique(); - themes=themeView.get(); - adapters.items.push_back(std::move(themeView)); - for (int i=0;i view; - if (id==Keystrokes) view=std::make_unique(); - else if (id==Watermark) view=std::make_unique(); - else if (id==MiniPlayer) { - auto media=std::make_unique(); - musicView=media.get(); - view=std::move(media); - } else if (group=="hud" || id==SoundIndicators) view=std::make_unique(id,category::hud); - else if (id==ToggleSprint || id==Freelook) view=std::make_unique(id,category::utility); - else if (id==Fortress) view=std::make_unique(id,category::visual); - else view=std::make_unique(id==ClientTime ? "time changer":java::modules[id].title,java::modules[id].detail, - group=="utility" || id==NameChanger ? category::utility : category::visual); - views[id]=view.get(); - auto& m=*view; - switch (id) { - case Fov: option(m,"field of view",settings.fov,30.f,145.f); break; - case Zoom: option(m,"hold c fov",settings.zoom,8.f,70.f); break; - case Fullbright: option(m,"gamma",settings.gamma,1.f,16.f); break; - case Optimize: option(m,"entity distance",settings.entityDistance,.5f,1.f); break; - case Atmosphere: - option(m,"rain",settings.rain,0.f,1.f); - option(m,"thunder",settings.thunder,0.f,1.f); - break; - case ClientTime: option(m,"sky time",settings.time,0,23999); break; - case NameChanger: textOption(m,"local display name",settings.displayName); break; - case Xp: - option(m,"width",xpWidth,150.f,400.f); option(m,"percentage",xpPercent); - option(m,"XP remaining",xpRemaining); option(m,"progress bar",xpBar); - option(m,"lock above vanilla xp bar",settings.xpLock); - break; - case Crosshair: - option(m,"length",settings.length,1.f,28.f); option(m,"width",settings.width,1.f,8.f); - option(m,"gap",settings.gap,0.f,22.f); colorOption(m,"color",settings.crosshairColor); - option(m,"black outline",settings.crossOutline); option(m,"gradient",settings.gradient); - colorOption(m,"gradient color",settings.crosshairGradient); - option(m,"dynamic gap",settings.dynamicGap); option(m,"gap speed",settings.gapSpeed,.5f,12.f); - option(m,"gap easing",settings.gapEase,1.f,30.f); - option(m,"dynamic length",settings.dynamicLength); option(m,"length speed",settings.lengthSpeed,.5f,12.f); - option(m,"length easing",settings.lengthEase,1.f,30.f); option(m,"reactive instead of pulse",settings.reactive); - option(m,"spin",settings.spin); option(m,"spin speed",settings.spinSpeed,.5f,12.f); - option(m,"spin easing",settings.spinEase,1.f,30.f); - break; - case Outlines: - colorOption(m,"color",settings.outlineColor); option(m,"width",settings.outlineWidth,1.f,6.f); - option(m,"black outline",settings.blockBlack); - break; - case Target: - option(m,"linger (seconds)",targetLinger,0.f,5.f); option(m,"health bar",targetBar); - option(m,"follow target",targetFollow); - option(m,"horizontal offset",targetOffsetX,-300.f,300.f); option(m,"vertical offset",targetOffsetY,-300.f,300.f); - option(m,"tracking speed",settings.tracking,8.f,60.f); option(m,"switch duration",targetSwitch,0.f,.8f); - break; - case Waypoints: - textOption(m,"label",waypointName); - m.add_action("save current position",[]{addPoint(data.position,waypointName);}); - break; - case Fortress: - option(m,"scan radius (blocks)",settings.fortressRadius,32,192); - option(m,"show status",fortressStatus); option(m,"world marker",fortressMarker); - m.add_action("rescan",[]{if (data.dimension=="minecraft:the_nether") requestFortress();}); - m.add_action("save fortress waypoint",[]{if (data.foundFortress) addPoint(data.fortress,"fortress candidate");}); - break; - case ToggleSprint: option(m,"show status",sprintStatus); break; - case Freelook: option(m,"show status",freelookStatus); break; - case InventoryTools: - option(m,"UI buttons",settings.inventoryButtons); option(m,"include hotbar when dumping",settings.inventoryHotbar); - option(m,"action delay (ms)",settings.inventoryDelay,30,500); - option(m,"buttons X (screen fraction)",settings.inventoryX,0.f,1.f); - option(m,"buttons Y (screen fraction)",settings.inventoryY,0.f,1.f); - textOption(m,"item filter",filter); - m.add_action("steal",[]{if (data.inContainer && java::modules[InventoryTools].on) requestTransfer(false,filter);}); - m.add_action("dump",[]{if (data.inContainer && java::modules[InventoryTools].on) requestTransfer(true,filter);}); - m.add_action("stop",[]{stopTransfer();}); - break; - case Chat: - option(m,"hide vanilla overlay",settings.hideChat); - option(m,"chat width",chatWidth,280.f,1000.f); option(m,"chat height",chatHeight,140.f,600.f); - option(m,"background opacity",chatOpacity,.3f,1.f); - colorOption(m,"name color",chatNameColor); colorOption(m,"message color",chatMessageColor); - colorOption(m,"system message color",chatSystemColor); - m.add_action("clear chat history",[]{data.chat.clear();}); - break; - case Notifier: - option(m,"incoming chat",settings.messages); option(m,"sleep time",settings.notifyNight); - option(m,"low health",settings.notifyHealth); option(m,"low hunger",settings.notifyHunger); - break; - case MiniPlayer: - for (auto& s:m.settings()) if (s.name=="lyrics") { - auto* setting=&s; - controls.push_back([setting](bool read){if (read) setting->bool_value=settings.lyrics; else settings.lyrics=setting->bool_value;}); - } - break; - case MobAttack: - option(m,"include animals",settings.animals); option(m,"range",settings.mobRange,1.f,3.f); - mode(m,"mode",settings.critical,{"normal","critical timing"}); - break; - case AutoClick: - option(m,"clicks per second",settings.cps,1.f,20.f); option(m,"right mouse instead of left",settings.rightClick); - break; - case AntiAfk: option(m,"idle seconds",settings.antiAfkSeconds,20,900); break; - case ParticleControls: mode(m,"particles",settings.particleMode,{"decreased","minimal"}); break; - case FriendsLocator: textOption(m,"friends",settings.friends); break; - default: break; - } - adapters.items.push_back(std::move(view)); - } - constexpr ModuleId bedrockOrder[]{Fps,Keystrokes,Watermark,Crosshair,Optimize,Fullbright,Fov,Zoom,MiniPlayer, - InventoryTools,AntiAfk,EndermanLook,Trajectories,AutoWeapon,AutoTool,AutoClick,MobAttack,Speed,Looking,EntityCount, - Breadcrumbs,Logout,Tracers,Radar,Active,Tab,Xp,ToggleSprint,Cps,ClockHud,Outlines,Atmosphere,Armor,NameChanger, - BetterTags,FriendsLocator,Target,ClientTime,Freelook,Coordinates,Waypoints,Fortress,Compass,Stats,Durability, - Notifier,Chat,Tool,Effects,ParticleControls,SoundIndicators,Diagnostics}; - const auto rank=[&](const auto& view) { - if (view.get()==themes) return 0; - for (int i=0;isettings()); -} -void mirror(bool read) { - for (auto& sync:controls) sync(read); - if (!read) { themes->synchronize(); settings.grid=hud_editor::options.grid_size; } -} -void seedTheme() { - for (auto& s:themes->settings()) { - for (size_t i=0;iname()) << ' ' << m->toggle_key() << '\n'; - for (const auto& s:m->settings()) { - if (s.type==setting_type::action) continue; - file << "ui " << std::quoted(m->name()) << ' ' << std::quoted(s.name) << ' '; - switch(s.type) { - case setting_type::toggle: file << s.bool_value; break; - case setting_type::slider_float: file << s.float_value; break; - case setting_type::color: for (float c:s.color) file << c << ' '; break; - case setting_type::text: file << std::quoted(s.text_value); break; - default: file << s.int_value; break; - } - file << '\n'; - } - } - return file.str(); -} -void readUi(std::istream& row) { - std::string type,name,key; - if (!(row >> type)) return; - if (type=="grid-options") { - auto& grid=hud_editor::options; - if (row >> grid.snap >> grid.show_grid >> grid.grid_size) grid.grid_size=std::clamp(grid.grid_size,4,64); - return; - } - if (!(row >> std::quoted(name))) return; - auto m=std::ranges::find_if(adapters.items,[&](const auto& item){return item->name()==name;}); - if (m==adapters.items.end()) return; - if (type=="bind") { - int vk{}; - if (row >> vk && vk>=0 && vk<255 && vk!=VK_RSHIFT) (*m)->set_toggle_key(vk); - return; - } - if (!(row >> std::quoted(key))) return; - for (auto& s:(*m)->settings()) { - if (key!=s.name) continue; - int integer{}; - float value{}; - switch (s.type) { - case setting_type::toggle: row >> s.bool_value; break; - case setting_type::slider_float: - if (row >> value && std::isfinite(value)) s.float_value=std::clamp(value,s.float_min,s.float_max); - break; - case setting_type::color: readColor(row,s.color); break; - case setting_type::text: if (row >> std::quoted(name)) s.text_value=name.substr(0,s.int_max); break; - case setting_type::mode: - if (row >> integer && integer>=0 && size_t(integer)> integer) s.int_value=std::clamp(integer,s.int_min,s.int_max); - break; - case setting_type::keybind: - if (row >> integer && integer>=0 && integer<255) s.int_value=integer; - break; - default: break; - } - break; - } -} - -// Keep the settings list shared by the profile reader and writer. -#define OPTIONS(F) F(fov) F(zoom) F(gamma) F(tracking) F(mobRange) F(cps) F(entityDistance) F(length) F(width) \ - F(gap) F(gapSpeed) F(lengthSpeed) F(spinSpeed) F(gapEase) F(lengthEase) F(spinEase) F(outlineWidth) F(rain) F(thunder) \ - F(time) F(grid) F(fortressRadius) F(critical) F(antiAfkSeconds) F(particleMode) \ - F(animals) F(rightClick) F(messages) F(crossOutline) F(blockBlack) F(gradient) F(spin) F(dynamicLength) F(dynamicGap) \ - F(reactive) F(xpLock) F(lyrics) F(hideChat) F(notifyNight) F(notifyHealth) F(notifyHunger) - -std::filesystem::path profilePath() { return dir/(activeProfile+".profile"); } -void save() { - if (dir.empty() || !dirty) return; - const auto path=profilePath(); - auto temp=path; temp+=L".tmp"; - std::ofstream file(temp,std::ios::trunc); - if (!file) { profileError="could not open the profile for saving"; return; } - file << "amnesia-java 1\n"; - for (int i=0;i result{}; - if (in >> result[0] >> result[1] >> result[2] >> result[3]) - for (size_t i=0;i<4;++i) values[i]=std::isfinite(result[i]) ? std::clamp(result[i],0.f,1.f) : 1.f; -} -void readProfile() { - settings={}; - theme::current={}; - for (size_t i=0;i uiRows; - unsigned limit=0; - while (++limit<=2000 && std::getline(file,text) && text.size()<2048) { - std::istringstream row(text); - std::string key, value; - row >> key; - if (key=="module" || key=="position") { - row >> std::quoted(value); - auto it=std::ranges::find_if(modules,[&](const Module& m){return value==m.title;}); - if (it==modules.end()) continue; - const auto i=it-modules.begin(); - if (key=="module") row >> it->on; - if (key=="position") row >> positions[i].x >> positions[i].y >> hasPosition[i] >> centerX[i] >> centerY[i]; - } else if (key=="theme") { - size_t i{}; - if (row >> i && i> std::quoted(point.name) >> std::quoted(point.dimension) >> point.pos.x >> point.pos.y >> point.pos.z && - data.waypoints.size()<128 && !point.name.empty() && std::isfinite(point.pos.length())) - data.waypoints.push_back(std::move(point)); - } else if (key=="name" || key=="friends" || key=="brand" || key=="api") { - if (!(row >> std::quoted(value))) continue; - if (key=="name") copy(settings.displayName,value); - if (key=="friends") copy(settings.friends,value); - if (key=="brand") theme::current.name=value; - if (key=="api" && !account_ui::configured) copy(account_ui::address,value); - } else if (key=="font") row >> theme::current.body_size; - else if (key=="ui" || key=="bind" || key=="grid-options") uiRows.push_back(text); - else if (key=="crosshairColor") readColor(row,settings.crosshairColor); - else if (key=="crosshairGradient") readColor(row,settings.crosshairGradient); - else if (key=="outlineColor") readColor(row,settings.outlineColor); -#define READ(name) else if (key==#name) row >> settings.name; - OPTIONS(READ) -#undef READ - } - settings.grid=std::clamp(settings.grid,1,64); - settings.fortressRadius=std::clamp(settings.fortressRadius,32,192); - settings.antiAfkSeconds=std::clamp(settings.antiAfkSeconds,20,900); - theme::current.body_size=std::clamp(theme::current.body_size,9,18); - hud_editor::options.grid_size=std::clamp(settings.grid,4,64); - mirror(true); - seedTheme(); - for (const auto& line:uiRows) { std::istringstream row(line); readUi(row); } - mirror(false); -} -#undef OPTIONS -bool validProfile(std::string_view name) { - return !name.empty() && name.size()<49 && name.front()!=' ' && name.back()!=' ' && std::ranges::all_of(name,[](char c) { - return (c>='a'&&c<='z') || (c>='A'&&c<='Z') || (c>='0'&&c<='9') || c=='_' || c=='-' || c==' '; - }); -} -bool switchProfile(const std::string& name,bool create) { - profileError.clear(); - if (dir.empty() || !validProfile(name)) { profileError="enter a valid profile name"; return false; } - save(); - if (dirty) return false; - const auto previous=activeProfile; - activeProfile=name; - if (create) { - change(); save(); - if (dirty) { activeProfile=previous; return false; } - } - else readProfile(); - std::ofstream(dir/"selected") << name; - return true; -} -void initConfig() { - wchar_t overridePath[32768]{}; - const auto length=GetEnvironmentVariableW(L"AMNESIA_JAVA_PROFILE_DIR",overridePath,DWORD(std::size(overridePath))); - if (length && length{}(dir.native()))+L"/v1"; - } - } - PWSTR path{}; - if (dir.empty() && SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData,0,nullptr,&path))) { - dir=std::filesystem::path(path)/"amnesia"/"java"; - CoTaskMemFree(path); - } - if (!dir.empty()) { - std::error_code error; - std::filesystem::create_directories(dir,error); - if (error) dir.clear(); - } - for (int i=0;i> remembered; - if (validProfile(remembered)) activeProfile=remembered; - readProfile(); -} - -bool inputMessage(UINT msg) { - return (msg>=WM_KEYFIRST && msg<=WM_KEYLAST) || (msg>=WM_MOUSEFIRST && msg<=WM_MOUSELAST) || - msg==WM_INPUT || msg==WM_SETCURSOR || msg==WM_UNICHAR; -} -void closePicker() { inventoryUi.mode=-1; readInventoryPicker(false); } -bool inventoryInput(UINT msg,WPARAM wp,LPARAM lp) { - auto& ui=inventoryUi; - if (msg==WM_LBUTTONUP && std::exchange(ui.left,false)) return true; - if (msg==WM_RBUTTONUP && std::exchange(ui.right,false)) return true; - if (capture || !account.allowed() || !data.inContainer || !settings.inventoryButtons || - !java::modules[InventoryTools].on || Clock::now()-ui.shown>std::chrono::milliseconds(150)) { - closePicker(); - return false; - } - if (ui.epoch!=data.containerEpoch || data.containerCursor) closePicker(); - if (ui.mode>=0 && msg==WM_KEYDOWN && wp==VK_ESCAPE) { closePicker(); return true; } - if (ui.mode>=0 && msg==WM_MOUSEWHEEL) { - const auto& items=data.inventoryChoices[ui.mode]; - ui.scroll=std::clamp(ui.scroll-short(HIWORD(wp))/WHEEL_DELTA,0,std::max(0,int(items.size())-ui.visible)); - return true; - } - const bool left=msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK; - const bool right=msg==WM_RBUTTONDOWN || msg==WM_RBUTTONDBLCLK; - if (!left && !right) return false; - const float x=short(LOWORD(lp)),y=short(HIWORD(lp)); - if (ui.mode>=0) { - const auto& p=ui.picker; - if (left && x>=p.x && x=p.y+28 && y=0 && size_t(row)=ui.buttons.y+26 || offset<0 || offset>=308 || int(offset)%104>=100) { - if (left && data.containerBusy) stopTransfer(); - return false; - } - const int button=int(offset)/104; - if (button==2 && !data.containerBusy) return false; - if (right && button==2) return false; - if (left) ui.left=true; else ui.right=true; - if (data.containerTransfer && !data.containerCursor) { - if (button==2) stopTransfer(); - else if (left) requestTransfer(button==1,{}); - else { - stopTransfer(); - ui.mode=button; - ui.scroll=ui.visible=0; - ui.epoch=data.containerEpoch; - readInventoryPicker(true); - } - } - return true; -} -LRESULT CALLBACK procedure(HWND window,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR, DWORD_PTR) { - if (!context) return DefSubclassProc(window,msg,wp,lp); - if (inventoryInput(msg,wp,lp)) return 0; - if (msg==WM_KILLFOCUS && (capture || chat)) closeRequested=true; - if (msg==WM_KEYDOWN && !(lp&(1L<<30))) { - const auto scan=UINT((lp>>16)&255); - if (wp==VK_RSHIFT || (wp==VK_SHIFT && MapVirtualKeyW(scan,MAPVK_VSC_TO_VK_EX)==VK_RSHIFT)) { - pendingMenu=true; - return 0; - } - if (capture && gui().binding()) { - bindingKey=wp==VK_SHIFT || wp==VK_CONTROL || wp==VK_MENU ? - int(MapVirtualKeyW(scan|((lp&(1L<<24)) ? 0xe000 : 0),MAPVK_VSC_TO_VK_EX)):int(wp); - return 0; - } - if (wp==VK_ESCAPE && capture) { - escapeRequested=true; - return 0; - } - if ((wp=='T' || wp==VK_OEM_2) && !capture && account.allowed() && data.inWorld && !data.inScreen && modules[Chat].on) { - if (wp==VK_OEM_2 && !*chatInput) copy(chatInput,"/"); - pendingChat=true; - return 0; - } - } - if (capture) { - if (msg==WM_INPUT) return DefWindowProcW(window,msg,wp,lp); - ImGui_ImplWin32_WndProcHandler(window,msg,wp,lp); - if (inputMessage(msg)) return 0; - } - if (data.orbiting && msg==WM_INPUT) { - RAWINPUT raw{}; - UINT size=sizeof(raw); - if (GetRawInputData(reinterpret_cast(lp),RID_INPUT,&raw,&size,sizeof(RAWINPUTHEADER))==sizeof(raw) && - raw.header.dwType==RIM_TYPEMOUSE && !(raw.data.mouse.usFlags&MOUSE_MOVE_ABSOLUTE)) { - orbit(raw.data.mouse.lLastX,raw.data.mouse.lLastY); - return DefWindowProcW(window,msg,wp,lp); - } - } - if (data.orbiting && msg==WM_MOUSEMOVE) return 0; - if (!capture && data.inWorld && !data.inScreen && (msg==WM_LBUTTONDOWN || msg==WM_RBUTTONDOWN)) - click(msg==WM_RBUTTONDOWN); - return DefSubclassProc(window,msg,wp,lp); -} - -ImVec2 place(int id,ImVec2 fallback,ImVec2 size) { - const auto display=ImGui::GetIO().DisplaySize; - auto p=hasPosition[id] ? positions[id] : fallback; - if (centerX[id]) p.x=(display.x-size.x)*.5f; - if (centerY[id]) p.y=(display.y-size.y)*.5f; - p=hud_editor::constrain(p,size,display,false,10); - sizes[id]=size; - views[id]->hud_pos=p; - renderPositions[id]=p; - return p; -} -bool screenPoint(Vec value,ImVec2& screen) { - const auto y=data.cameraYaw*std::numbers::pi/180,p=data.cameraPitch*std::numbers::pi/180; - const auto delta=value-data.camera; - const auto depth=-std::sin(y)*std::cos(p)*delta.x-std::sin(p)*delta.y+std::cos(y)*std::cos(p)*delta.z; - if (depth<.05) return false; - const auto horizontal=-std::cos(y)*delta.x-std::sin(y)*delta.z; - const auto vertical=-std::sin(y)*std::sin(p)*delta.x+std::cos(p)*delta.y+std::cos(y)*std::sin(p)*delta.z; - const auto size=ImGui::GetIO().DisplaySize; - const auto scale=size.y*.5/std::tan(std::clamp(double(data.cameraFov),5.,165.)*std::numbers::pi/360); - screen={float(size.x*.5+horizontal*scale/depth),float(size.y*.5-vertical*scale/depth)}; - return std::abs(screen.x)AddRectFilled({p.x-size.x*.5f-4,p.y-2},{p.x+size.x*.5f+4,p.y+size.y+2},IM_COL32(15,15,15,222)); - draw->AddText({p.x-size.x*.5f,p.y},color,text.c_str()); -} -void worldLine(Vec a,Vec b,ImU32 color,float width=1.5f) { - ImVec2 p,q; - if (screenPoint(a,p) && screenPoint(b,q)) ImGui::GetBackgroundDrawList()->AddLine(p,q,color,width); -} -bool isFriend(const std::string& name) { - std::string_view list(settings.friends); - while (!list.empty()) { - const auto end=list.find(','); - auto item=list.substr(0,end); - while (!item.empty() && item.front()==' ') item.remove_prefix(1); - while (!item.empty() && item.back()==' ') item.remove_suffix(1); - if (item.size()==name.size() && _strnicmp(item.data(),name.c_str(),item.size())==0) return true; - if (end==std::string_view::npos) break; - list.remove_prefix(end+1); - } - return false; -} -void worldDraw() { - const auto accent=theme::u32(theme::accent()); - const auto viewport=ImGui::GetIO().DisplaySize; - auto* draw=ImGui::GetBackgroundDrawList(); - if (modules[Waypoints].on) - for (const auto& point:data.waypoints) if (point.dimension==data.dimension) - pointLabel(point.pos,point.name+formatted(" %.0fm",(point.pos-data.position).length()),accent); - if (modules[Fortress].on && fortressMarker && data.foundFortress) - pointLabel(data.fortress,formatted("fortress candidate %.0fm",(data.fortress-data.position).length()),accent); - if (modules[Logout].on) - for (const auto& spot:data.logouts) pointLabel(spot.pos,spot.name+" / logout",accent); - if (modules[Breadcrumbs].on) - for (size_t i=1;i1) { - for (size_t i=1;iAddCircle(p,5,accent,20,2); - } - if (modules[Tracers].on || modules[BetterTags].on) - for (const auto& a:data.actors) { - ImVec2 point; - if (modules[Tracers].on && screenPoint(a.pos+Vec{0,a.height*.5,0},point)) - draw->AddLine({viewport.x*.5f,viewport.y*.9f},point,accent,1); - if (modules[BetterTags].on && a.player) - pointLabel(a.pos+Vec{0,a.height+.28,0},a.name+formatted(" %.0f hp / %.0fm",a.hp,(a.pos-data.position).length()),accent); - } - if (modules[FriendsLocator].on && data.realm) - for (const auto& a:data.actors) - if (a.player && isFriend(a.name)) { - ImVec2 head, feet; - if (screenPoint(a.pos+Vec{0,a.height,0},head) && screenPoint(a.pos,feet)) { - const float radius=std::max(3.f,std::abs(feet.y-head.y)*.23f); - draw->AddRect({head.x-radius,std::min(head.y,feet.y)},{head.x+radius,std::max(head.y,feet.y)},accent); - } - pointLabel(a.pos+Vec{0,a.height+.25,0},a.name+formatted(" %.0fm",(a.pos-data.position).length()),accent); - } - if (modules[SoundIndicators].on) - for (const auto& sound:data.sounds) - pointLabel(sound.position,sound.name+formatted(" %.0fm",(sound.position-data.position).length()),accent); - if (modules[Outlines].on && data.blockTarget) { - const auto color=ImGui::ColorConvertFloat4ToU32({settings.outlineColor[0],settings.outlineColor[1],settings.outlineColor[2],settings.outlineColor[3]}); - std::array corners; - for (int i=0;i<8;++i) corners[i]=data.hitBlock+Vec{double(i&1),double((i>>1)&1),double((i>>2)&1)}; - for (int i=0;i<8;++i) for (int axis:{1,2,4}) if (!(i&axis)) { - if (settings.blockBlack) worldLine(corners[i],corners[i|axis],IM_COL32_BLACK,settings.outlineWidth+2); - worldLine(corners[i],corners[i|axis],color,settings.outlineWidth); - } - } -} - -void crosshair() { - if (!modules[Crosshair].on) return; - const auto size=ImGui::GetIO().DisplaySize; - const ImVec2 center{size.x*.5f,size.y*.5f}; - const float t=float(ImGui::GetTime()); - const float dt=ImGui::GetIO().DeltaTime; - const float reactive=float(std::clamp(data.speed*.09+data.leftCps*.03,0.,1.)); - const auto pulse=[&](float speed){return settings.reactive ? reactive : .5f+.5f*std::sin(t*speed);}; - static float lengthOffset{}, gapOffset{}, rotation{}, spinRate{}; - lengthOffset+=((settings.dynamicLength ? pulse(settings.lengthSpeed)*5 : 0)-lengthOffset)*(1-std::exp(-settings.lengthEase*dt)); - gapOffset+=((settings.dynamicGap ? pulse(settings.gapSpeed)*4 : 0)-gapOffset)*(1-std::exp(-settings.gapEase*dt)); - spinRate+=((settings.spin ? settings.spinSpeed : 0)-spinRate)*(1-std::exp(-settings.spinEase*dt)); - rotation=settings.spin ? std::remainder(rotation+spinRate*dt,2*std::numbers::pi_v) : rotation*std::exp(-settings.spinEase*dt); - const float length=settings.length+lengthOffset; - const float gap=settings.gap+gapOffset; - const auto color=[](const float* c){return ImGui::ColorConvertFloat4ToU32({c[0],c[1],c[2],c[3]});}; - auto* draw=ImGui::GetBackgroundDrawList(); - for (int i=0;i<4;++i) { - const float angle=i*std::numbers::pi_v/2+rotation; - const ImVec2 v{std::cos(angle),std::sin(angle)}; - const ImVec2 a{center.x+v.x*gap,center.y+v.y*gap}; - const ImVec2 b{a.x+v.x*length,a.y+v.y*length}; - if (settings.crossOutline) draw->AddLine(a,b,IM_COL32_BLACK,settings.width+2); - if (settings.gradient) { - const auto c=ImGui::ColorConvertU32ToFloat4(color(settings.crosshairColor)); - const auto d=ImGui::ColorConvertU32ToFloat4(color(settings.crosshairGradient)); - for (int s=0;s<8;++s) { - const float l=float(s)/8,r=float(s+1)/8; - draw->AddLine({a.x+v.x*length*l,a.y+v.y*length*l},{a.x+v.x*length*r,a.y+v.y*length*r}, - ImGui::ColorConvertFloat4ToU32({c.x+(d.x-c.x)*l,c.y+(d.y-c.y)*l,c.z+(d.z-c.z)*l,c.w+(d.w-c.w)*l}),settings.width); - } - } else draw->AddLine(a,b,color(settings.crosshairColor),settings.width); - } -} - -std::string itemLabel(const Item& item) { - if (item.name.empty()) return "empty"; - return item.name+(item.maximum ? formatted(" %d/%d",item.maximum-item.used,item.maximum) : - item.count>1 ? formatted(" ×%d",item.count) : ""); -} -const Waypoint* closestWaypoint() { - const Waypoint* best=nullptr; - double distance=INFINITY; - for (const auto& point:data.waypoints) - if (point.dimension==data.dimension) { - const auto d=(point.pos-data.position).length(); - if (d(*views[Watermark]); - place(Watermark,{10,10},view.hud_size()); - view.draw(account); - sizes[Watermark]=view.hud_size(); - } - if (hudVisible(Keystrokes)) { - auto& view=static_cast(*views[Keystrokes]); - place(Keystrokes,{10,60},view.hud_size()); - view.on_render(); - } - if (hudVisible(MiniPlayer)) { - place(MiniPlayer,{10,560},musicView->hud_size()); - musicView->on_render(); - } - const auto one=[&](ModuleId id,ImVec2 fallback,const char* title,const std::string& value,const char* reserve="") { - if (!hudVisible(id)) return; - auto& m=static_cast(*views[id]); - place(id,fallback,hud_card::size(title,value.c_str(),m.scale(),reserve)); - m.renderText(title,value,reserve); - }; - const auto rows=[&](ModuleId id,ImVec2 fallback,const char* title,const std::vector& values,float width=0.f) { - auto& m=static_cast(*views[id]); - const float scale=m.scale(), font=fonts::k_body_size*scale; - if (!width) { - width=fonts::text_size(fonts::body,font,title).x; - for (const auto& row:values) width=std::max(width,fonts::text_size(fonts::semibold,font,row.c_str()).x); - width=width/scale+2*hud_card::pad_x; - } - const float count=float(values.size()+(*title ? 1:0)); - const ImVec2 size{width*scale,hud_card::rows_height(int(std::max(count,1.f)))*scale}; - const auto p=place(id,fallback,size); - hud_card::background(draw,p,size,scale,m.background()); - draw->PushClipRect(p,{p.x+size.x,p.y+size.y},true); - float y=p.y+hud_card::pad_y*scale; - const float x=p.x+hud_card::pad_x*scale; - if (*title) { - hud_card::text(draw,fonts::body,scale,{x,y},theme::u32(theme::muted()),title,m.background()); - y+=20*scale; - } - for (const auto& row:values) { - hud_card::text(draw,fonts::semibold,scale,{x,y},m.color(),row.c_str(),m.background()); - y+=20*scale; - } - draw->PopClipRect(); - }; - const float y0=10+sizes[Watermark].y+5; - one(Fps,{10,y0},"fps",std::to_string(data.fps),"000"); - one(Cps,{10,185},"cps",formatted("%d l / %d r",data.leftCps,data.rightCps)); - one(Coordinates,{10,515},"xyz",formatted("%.1f %.1f %.1f | %.1f blocks/s",data.position.x,data.position.y,data.position.z,data.speed)); - if (hudVisible(ClockHud)) { - SYSTEMTIME now{}; GetLocalTime(&now); - one(ClockHud,{10,220},"time",formatted("%02d:%02d:%02d",now.wHour,now.wMinute,now.wSecond)); - } - one(Speed,{10,250},"speed",formatted("%.1f blocks/s",data.speed)); - if (sprintStatus) one(ToggleSprint,{10,275},"sprint",data.sprinting ? "active":"ready","active"); - if (freelookStatus) one(Freelook,{10,470},"freelook",data.orbiting ? "active":"ready","active"); - if (fortressStatus && hudVisible(Fortress)) { - std::string text="enter the nether"; - if (data.dimension=="minecraft:the_nether") { - if (data.foundFortress) text=formatted("possible | %.0fm | %.0f %.0f %.0f",(data.fortress-data.position).length(), - data.fortress.x,data.fortress.y,data.fortress.z); - else if (data.scanning) text=formatted("scanning %u%%",data.toScan ? data.scanned*100/data.toScan : 0); - else text="none found nearby"; - } - one(Fortress,{10,265},"fortress finder",text); - } - one(Looking,{10,280},"looking at",data.looking.empty() ? "air" : data.looking); - one(EntityCount,{10,310},"entities",formatted("%zu nearby / %zu hostile / %zu players",data.actors.size(), - size_t(std::ranges::count_if(data.actors,[](const Actor& a){return a.monster;})), - size_t(std::ranges::count_if(data.actors,[](const Actor& a){return a.player;})))); - if (hudVisible(Armor)) { - std::vector items; - for (auto it=data.armor.rbegin();it!=data.armor.rend();++it) items.push_back(itemLabel(*it)); - if (items.empty()) items={"head","chest","legs","feet"}; - rows(Armor,{10,345},"armor",items,180); - } - if (hudVisible(Tool)) { - std::vector items{itemLabel(data.held)}; - if (data.offhand.count) items.push_back("offhand "+itemLabel(data.offhand)); - rows(Tool,{10,485},"tool",items); - } - if (hudVisible(Effects)) rows(Effects,{10,610},"status effects",data.effects.empty()?std::vector{"none"}:data.effects,180); - if (hudVisible(SoundIndicators)) { - std::vector values; - for (auto it=data.sounds.rbegin();it!=data.sounds.rend() && values.size()<4;++it) - values.push_back(it->name+formatted(" | %.0fm",(it->position-data.position).length())); - rows(SoundIndicators,{10,740},"sound indicators",values,230); - } - if (hudVisible(Radar)) { - std::vector players; - for (const auto& a:data.actors) if (a.player) players.push_back(&a); - std::ranges::sort(players,{},[](const Actor* a){return (a->pos-data.position).length();}); - std::vector roster; - for (size_t i=0;iname+formatted(" %.0fm",(players[i]->pos-data.position).length())); - rows(Radar,{10,700},"player radar",roster,180); - } - if (hudVisible(Tab)) { - std::vector roster; - for (size_t i=0;i names; - for (int i=0;iname()); - rows(Active,{screen.x-190,40},"active modules",names,180); - } - if (hudVisible(Compass)) { - constexpr const char* cardinal[]{"s","sw","w","nw","n","ne","e","se"}; - auto& m=static_cast(*views[Compass]); - const float s=m.scale(),w=320,h=57; - const auto origin=place(Compass,{(screen.x-w*s)*.5f,10},{w*s,h*s}); - const auto p=[&](float x,float y){return ImVec2(origin.x+x*s,origin.y+y*s);}; - hud_card::background(draw,origin,{w*s,h*s},s,m.background()); - const auto angle=std::remainder(data.yaw,360.f); - draw->PushClipRect(p(6,2),p(w-6,h-2),true); - for (int i=-7;i<=7;++i) { - const float tick=std::floor(angle/15)*15+15*i,x=w*.5f+(tick-angle)*3.4f; - draw->AddLine(p(x,24),p(x,tick==std::floor(tick/45)*45 ? 31.f:28.f),theme::u32(theme::muted())); - if (tick==std::floor(tick/45)*45) { - const auto* name=cardinal[(int(tick/45)+16)%8]; - const auto size=fonts::text_size(fonts::semibold,fonts::k_body_size*s,name); - hud_card::text(draw,fonts::semibold,s,p(x-size.x/s*.5f,8),m.color(),name,m.background()); - } - } - draw->AddTriangleFilled(p(w*.5f,33),p(w*.5f-3,38),p(w*.5f+3,38),theme::u32(theme::accent())); - hud_card::text(draw,fonts::body,.78f*s,p(12,40),theme::u32(theme::muted()),formatted("%03.0f",std::fmod(angle+360,360)).c_str(),m.background()); - if (const auto point=closestWaypoint()) { - const auto label=point->name+formatted(" %.0fm",(point->pos-data.position).length()); - hud_card::text(draw,fonts::body,.8f*s,p(w*.5f,41),m.color(),label.c_str(),m.background()); - } - draw->PopClipRect(); - } - if (hudVisible(Stats)) { - const auto minutes=std::chrono::duration_cast(Clock::now()-data.joined).count(); - rows(Stats,{10,650},"session stats",{formatted("%lldm / %.0fm travelled / %d containers",data.inWorld ? minutes : 0,data.distance,data.containers)}); - } - if (hudVisible(Diagnostics)) - rows(Diagnostics,{screen.x-310,10},"",{formatted("%.2f ms frame %.2f ms java sample",frameMs,updateMs), - formatted("%d fps %zu actors %zu chat %u chunks",data.fps,data.actors.size(),data.chat.size(),data.scanned),data.status}); - if (hudVisible(Xp)) { - auto& m=static_cast(*views[Xp]); - const float s=m.scale(),font=fonts::k_body_size*s; - const int level=data.inWorld ? data.xpLevel:28; - const float progress=data.inWorld ? std::clamp(data.xp,0.f,1.f):.3f; - std::string text=formatted("level %d",level); - if (xpPercent) text+=formatted(" %.1f%%",progress*100); - if (xpRemaining) text+=formatted(" %d XP to go",int(std::ceil((1-progress)*(data.inWorld ? data.xpNext:65)))); - const float inner=(xpWidth-24)*s; - fonts::push_font(fonts::semibold,font); - const auto textSize=ImGui::CalcTextSize(text.c_str(),nullptr,false,inner); - ImGui::PopFont(); - const ImVec2 size{xpWidth*s,(14+(xpBar ? 16.f:0.f))*s+textSize.y}; - auto p=place(Xp,{10,445},size); - if (settings.xpLock) { - static float lift{}; - lift+=((data.hotbarTextTicks>0 ? 23.f:0.f)-lift)*(1.f-std::exp(-14*ImGui::GetIO().DeltaTime)); - p=hud_editor::constrain({(screen.x-size.x)*.5f,screen.y-size.y-91-lift},size,screen,false,10); - renderPositions[Xp]=p; - } - hud_card::background(draw,p,size,s,m.background()); - draw->PushClipRect(p,{p.x+size.x,p.y+size.y},true); - draw->AddText(fonts::semibold,font,{std::floor(p.x+12*s),std::floor(p.y+7*s)},theme::display_color(m.color()),text.c_str(),nullptr,inner); - if (xpBar) theme::accent_bar(draw,{p.x+12*s,p.y+18*s+textSize.y},{p.x+size.x-12*s,p.y+23*s+textSize.y},progress); - draw->PopClipRect(); - } - static target_hud_layout::motion motion; - static float opacity{}; - if (hudVisible(Target)) { - const bool active=data.targetTime!=Clock::time_point{} && std::chrono::duration(Clock::now()-data.targetTime).count()<=targetLinger; - ImVec2 projected; - const bool show=menu || (active && (!targetFollow || screenPoint(data.target.pos+Vec{0,data.target.height*.5,0},projected))); - opacity=theme::approach(opacity,show ? 1.f:0.f,ImGui::GetIO().DeltaTime*10); - if (opacity>=.01f) { - auto& m=static_cast(*views[Target]); - const float s=m.scale(),font=fonts::k_body_size*s; - const bool preview=menu && !active; - const bool known=!preview && data.target.maxHp>0; - const auto name=preview || data.target.name.empty() ? "target preview":data.target.name.c_str(); - const auto health=known ? formatted("%.0f / %.0f hp | %.1fm",data.target.hp,data.target.maxHp,(data.target.pos-data.position).length()) : - std::string("health unknown | preview"); - const float fraction=known ? std::clamp(data.target.hp/data.target.maxHp,0.f,1.f):0; - const float width=std::max({240.f,fonts::text_size(fonts::semibold,font,name).x/s+76, - fonts::text_size(fonts::body,font*.8f,health.c_str()).x/s+68}); - const ImVec2 size{width*s,64*s}; - auto origin=place(Target,{320,365},size); - if (!menu && targetFollow && show) { - const auto goal=target_hud_layout::follow(projected,size,screen,{targetOffsetX,targetOffsetY},s); - origin=motion.update(goal,data.target.id,ImGui::GetIO().DeltaTime,settings.tracking,targetSwitch); - renderPositions[Target]=origin; - } else if (!menu && targetFollow && motion.valid) origin=motion.position; - else motion.reset(); - const auto p=[&](float x,float y){return ImVec2(origin.x+x*s,origin.y+y*s);}; - const auto base=ImGui::ColorConvertU32ToFloat4(m.color()); - const auto color=theme::u32(theme::with_alpha(base,base.w*opacity)); - hud_card::background(draw,origin,size,s,m.background(),opacity); - const auto a=p(10,10),b=p(46,46); - if (!preview && data.target.portrait) { - const ImVec2 crispA{std::round(a.x),std::round(a.y)},crispB{std::round(b.x),std::round(b.y)}; - const auto tint=theme::u32({1,1,1,opacity}); - draw->AddImage(ImTextureID(data.target.portrait),crispA,crispB,{.125f,.125f},{.25f,.25f},tint); - draw->AddImage(ImTextureID(data.target.portrait),crispA,crispB,{.625f,.125f},{.75f,.25f},tint); - } else { - static std::unordered_map portraits; - auto key=preview ? std::string("minecraft:player"):data.target.type; - if (key.starts_with("entity.")) { - key.erase(0,7); - if (auto dot=key.find('.');dot!=std::string::npos) key[dot]=':'; - } - if (portraits.size()>256) portraits.clear(); - auto [entry,added]=portraits.try_emplace(key); - if (added) entry->second=target_portraits::mob(key); - target_hud_layout::portrait(draw,entry->second,a,36*s,opacity); - } - hud_card::text(draw,fonts::semibold,s,p(56,8),color,name,m.background()); - const auto percent=known ? formatted("%.0f%%",fraction*100):"--%"; - const auto percentWidth=fonts::text_size(fonts::semibold,font*.7f,percent.c_str()).x/s; - hud_card::text(draw,fonts::semibold,s*.7f,p(width-12-percentWidth,27),color,percent.c_str(),m.background()); - if (targetBar) theme::accent_bar(draw,p(56,40),p(width-12,44),fraction,opacity); - hud_card::text(draw,fonts::body,s*.8f,p(56,49),theme::u32(theme::with_alpha(theme::muted(),opacity)),health.c_str(),m.background()); - } else motion.reset(); - } else { opacity=0; motion.reset(); } -} - -void addPoint(Vec pos,const char* name) { - if (!data.inWorld || data.waypoints.size()>=128) return; - data.waypoints.push_back({*name ? name : "waypoint",data.dimension,pos}); - modules[Waypoints].on=true; - change(); -} - -void inventoryDraw() { - auto& ui=inventoryUi; - if (!data.inContainer || !settings.inventoryButtons || !java::modules[InventoryTools].on || capture) { - ui.shown={}; - closePicker(); - return; - } - const auto screen=ImGui::GetIO().DisplaySize; - ui.buttons={std::clamp(screen.x*settings.inventoryX-156,0.f,std::max(0.f,screen.x-312)), - std::clamp(screen.y*settings.inventoryY,0.f,std::max(0.f,screen.y-28))}; - ui.shown=Clock::now(); - auto* draw=ImGui::GetForegroundDrawList(); - const char* labels[]{"steal","dump","stop"}; - for (int i=0;i<(data.containerBusy ? 3:2);++i) { - const ImVec2 at{ui.buttons.x+i*104.f,ui.buttons.y}; - hud_card::background(draw,at,{100,26},1,true); - const auto color=theme::u32(!data.containerTransfer || data.containerCursor ? theme::muted():theme::fg()); - const auto text=fonts::text_size(fonts::semibold,fonts::k_body_size,labels[i]); - hud_card::text(draw,fonts::semibold,1,{at.x+(100-text.x)*.5f,at.y+(26-text.y)*.5f},color,labels[i],true); - } - if (ui.mode<0) return; - if (ui.epoch!=data.containerEpoch || data.containerCursor) { closePicker(); return; } - const auto& choices=data.inventoryChoices[ui.mode]; - ui.visible=std::min(int(choices.size()),std::min(10,std::max(1,int((screen.y-64)/22)))); - ui.scroll=std::clamp(ui.scroll,0,std::max(0,int(choices.size())-ui.visible)); - ui.pickerSize={264,48.f+22*std::max(1,ui.visible)}; - const auto y=ui.buttons.y+32+ui.pickerSize.y<=screen.y ? ui.buttons.y+32:ui.buttons.y-ui.pickerSize.y-6; - ui.picker=hud_editor::constrain({ui.buttons.x+ui.mode*104,y},ui.pickerSize,screen,false,10); - const auto p=ui.picker; - theme::panel(draw,p,{p.x+ui.pickerSize.x,p.y+ui.pickerSize.y}); - hud_card::text(draw,fonts::semibold,1,{p.x+12,p.y+7},theme::u32(theme::fg()),ui.mode==0 ? "steal item":"dump item",true); - const auto mouse=ImGui::GetIO().MousePos; - if (choices.empty()) hud_card::text(draw,fonts::body,1,{p.x+12,p.y+31},theme::u32(theme::muted()),"no items available",true); - for (int i=0;i=p.x && mouse.x=top && mouse.yPushClipRect({p.x+12,top},{p.x+ui.pickerSize.x-58,top+22},true); - hud_card::text(draw,fonts::body,1,{p.x+12,top+5},theme::u32(theme::fg()),item.name.c_str(),true); - draw->PopClipRect(); - const auto count=std::to_string(item.count); - const auto width=fonts::text_size(fonts::body,fonts::k_body_size,count.c_str()).x; - hud_card::text(draw,fonts::body,1,{p.x+ui.pickerSize.x-12-width,top+5},theme::u32(theme::muted()),count.c_str(),true); - } - hud_card::text(draw,fonts::body,.8f,{p.x+12,p.y+ui.pickerSize.y-16},theme::u32(theme::muted()), - int(choices.size())>ui.visible ? "all matching stacks / wheel to scroll":"transfers all matching stacks",true); -} - -void drawChat() { - const auto display=ImGui::GetIO().DisplaySize; - if (display.x<120 || display.y<120) { chat=false; return; } - const float width=std::clamp(chatWidth,100.f,display.x-20.f),height=std::clamp(chatHeight,100.f,display.y-20.f); - ImGui::SetNextWindowPos({10,display.y-height-10}); - ImGui::SetNextWindowSize({width,height}); - ImGui::SetNextWindowBgAlpha(chatOpacity); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding,{10,8}); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing,{6,5}); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding,{6,3}); - ImGui::Begin("##amnesia_custom_chat",nullptr,ImGuiWindowFlags_NoDecoration|ImGuiWindowFlags_NoMove| - ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoNav); - const auto pos=ImGui::GetWindowPos(); - ImGui::GetWindowDrawList()->AddRectFilled({pos.x+1,pos.y+1},{pos.x+width-1,pos.y+3},theme::u32(theme::accent())); - ImGui::TextUnformatted("chat"); - ImGui::SameLine(); - ImGui::TextDisabled("/ enter to send / escape to close"); - ImGui::BeginChild("##chat_history",{0,-32}); - const bool atBottom=ImGui::GetScrollY()>=ImGui::GetScrollMaxY()-8; - if (data.chat.empty()) ImGui::TextDisabled("messages will appear here"); - fonts::push_font(fonts::media,fonts::k_body_size); - ImGui::PushTextWrapPos(0); - for (const auto& msg:data.chat) { - const auto tint=[](const float* c){return ImGui::ColorConvertFloat4ToU32({c[0],c[1],c[2],c[3]});}; - const auto end=msg.body.starts_with('<') ? msg.body.find('>'):std::string::npos; - auto text=rich_text::parse(msg.body,tint(end==std::string::npos ? chatSystemColor:chatMessageColor)); - if (end!=std::string::npos) rich_text::tint_range(text,1,end,tint(chatNameColor)); - rich_text::widget(text); - } - ImGui::PopTextWrapPos(); - ImGui::PopFont(); - if (atBottom || chatScroll) { ImGui::SetScrollHereY(1); chatScroll=false; } - ImGui::EndChild(); - if (std::exchange(chatFocus,false)) ImGui::SetKeyboardFocusHere(); - ImGui::SetNextItemWidth(std::max(40.f,ImGui::GetContentRegionAvail().x-66)); - fonts::push_font(fonts::media,fonts::k_body_size); - const auto history=[](ImGuiInputTextCallbackData* entry) { - const auto text=sentHistory.move(entry->EventKey==ImGuiKey_UpArrow ? -1:1,entry->Buf); - entry->DeleteChars(0,entry->BufTextLen); - entry->InsertChars(0,text.c_str()); - return 0; - }; - const bool enter=ImGui::InputTextWithHint("##chat_message","message or /command",chatInput,sizeof(chatInput), - ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackHistory,history); - ImGui::PopFont(); - ImGui::SameLine(); - if ((ImGui::Button("send",{60,0}) || enter) && chat_logic::valid_submission(chatInput)) { - sentHistory.remember(chatInput); - submit(chatInput); - chatInput[0]=0; - closeRequested=true; - } - ImGui::End(); - ImGui::PopStyleVar(3); -} - -bool drawIcon(ImDrawList* draw,ImVec2 at,float size,float alpha) { - if (!customIcon) return false; - const auto aspect=iconAspect; - const ImVec2 bounds{aspect>=1 ? size:size*aspect,aspect>=1 ? size/aspect:size}; - at={std::round(at.x+(size-bounds.x)*.5f),std::round(at.y+(size-bounds.y)*.5f)}; - draw->AddImage(ImTextureID(customIcon.Get()),at,{at.x+bounds.x,at.y+bounds.y},{0,0},{1,1},theme::u32({1,1,1,alpha})); - return true; -} -void updateIcon() { - theme::custom_icon=&drawIcon; - if (loadedIcon==theme::current.icon_path && iconRevision==theme::current.icon_revision) return; - loadedIcon=theme::current.icon_path; iconRevision=theme::current.icon_revision; - customIcon.Reset(); theme_assets::last_error.clear(); - if (loadedIcon.empty()) return; - std::ifstream file(client_files::path(loadedIcon),std::ios::binary|std::ios::ate); - const auto length=file ? file.tellg():std::streampos(-1); - if (length<=0 || length>4*1024*1024) { theme_assets::last_error="icon could not be loaded; choose an image up to 4 mb"; return; } - std::vector bytes(static_cast(length)); - file.seekg(0); - if (!file.read(reinterpret_cast(bytes.data()),std::streamsize(length))) { theme_assets::last_error="icon could not be read"; return; } - const HRESULT result=CoInitializeEx(nullptr,COINIT_MULTITHREADED); - const auto image=media::decode_art(bytes); - if (SUCCEEDED(result)) CoUninitialize(); - if (!image) { theme_assets::last_error="unsupported or damaged icon image"; return; } - iconAspect=float(image->width)/image->height; - customIcon.upload(image->width,image->height,image->rgba.data()); -} - -} // namespace - -bool start(HWND window) { - hwnd=window; - g_game_window=window; - context=ImGui::CreateContext(); - ImGui::SetCurrentContext(context); - if (!ImGui_ImplWin32_Init(hwnd)) { ImGui::DestroyContext(context); context=nullptr; return false; } - if (!ImGui_ImplOpenGL3_Init("#version 150")) { - ImGui_ImplWin32_Shutdown(); - ImGui::DestroyContext(context); context=nullptr; - return false; - } - if (!SetWindowSubclass(hwnd,procedure,subclass,0)) { - ImGui_ImplOpenGL3_Shutdown(); - ImGui_ImplWin32_Shutdown(); - ImGui::DestroyContext(context); context=nullptr; - return false; - } - initViews(); - initConfig(); - gui().init(); - license=new licensing::service(licensing::fingerprint,std::chrono::seconds(60),java_ui_credential()); - license->start(); - account_ui::load_config(); - startup_intro::loading_stage=startup_intro::stage::ready; - return true; -} - -void draw(JNIEnv* env) { - ImGui::SetCurrentContext(context); - const auto now=Clock::now(); - if (frameStart!=Clock::time_point{}) frameMs+=.10*(std::chrono::duration(now-frameStart).count()-frameMs); - frameStart=now; - static bool previousLicense; - if (license) account=license->latest(); - const bool allowed=account.allowed(); - if (previousLicense && !allowed) { - restoreFeatures(env); - stopTransfer(); - musicView->set_enabled(false); - gui().close(); - account_ui::dismissed=false; - } - previousLicense=allowed; - const bool intro=!startup_intro::animation.finished; - const bool shift=std::exchange(pendingMenu,false); - if (shift && !intro) { - if (!allowed) account_ui::dismissed=!account_ui::dismissed; - else if (menu) gui().close(); - else gui().open(); - chat=false; - } - if (std::exchange(pendingChat,false) && allowed && !intro) { - chat=chatFocus=chatScroll=true; - sentHistory.reset(); - gui().close(); - } - if (std::exchange(escapeRequested,false)) { - if (chat) chat=false; - else if (account_ui::requested || !allowed) { account_ui::requested=false; account_ui::dismissed=true; } - else gui().escape(); - } - if (std::exchange(closeRequested,false) || (!allowed && chat)) { - gui().close(); chat=false; - account_ui::requested=false; - if (!allowed && capture) account_ui::dismissed=true; - } - bool showAccount=!intro && (allowed ? account_ui::requested:!account_ui::dismissed); - const bool wanted=menu || chat || showAccount; - if (capture!=wanted) { - capture=wanted; - mouse(env,capture); - } - if (allowed && !intro) { - for (int i=0;i(Clock::now()-begin).count()-updateMs); - } - if (dirty && now>=nextSave) save(); - GlState graphics; - fonts::apply_selection(); - updateIcon(); - theme::apply(); - ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplWin32_NewFrame(); - ImGui::NewFrame(); - if (intro) { - startup_intro::initialize_texture(); - startup_intro::draw(true,shift,account.username.c_str()); - } else if (allowed) { - gui().update(); - if (data.inWorld && !data.inScreen && !capture && !data.guiHidden) { worldDraw(); crosshair(); } - gui().draw_backdrop(); - huds(); - if (menu) { - const auto profile=activeProfile; - const auto before=uiState(); - const auto originalPositions=renderPositions; - gui().draw(); - if (activeProfile==profile) { - for (int i=0;i0 && !(i==Xp && settings.xpLock) && - (view.hud_pos.x!=originalPositions[i].x || view.hud_pos.y!=originalPositions[i].y)) { - positions[i]=view.hud_pos; - hasPosition[i]=true; centerX[i]=centerY[i]=false; - change(); - } - } - mirror(false); - if (before!=uiState()) change(); - } - } else gui().draw(); - if (chat) drawChat(); - inventoryDraw(); - showAccount=account_ui::requested; - } - if (showAccount) account_ui::draw(allowed); - if (!intro) notifications::draw(); - CURSORINFO cursor{sizeof(cursor)}; - ImGui::GetIO().MouseDrawCursor=capture && !(GetCursorInfo(&cursor) && (cursor.flags&CURSOR_SHOWING)); - ImGui::Render(); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - bindingKey=0; - static bool firstMenu=true; - if ((menu || showAccount) && std::exchange(firstMenu,false)) diagnostic("rendered the shared Bedrock interface"); - static bool firstLicensedMenu=true,firstEditor=true; - if (menu && allowed && std::exchange(firstLicensedMenu,false)) diagnostic("rendered the licensed ClickGUI"); - if (menu && allowed && gui().editing_hud() && std::exchange(firstEditor,false)) diagnostic("rendered the HUD editor"); -} - -void addNote(std::string title,std::string body) { - const auto kind=title=="durability" || title.starts_with("low ") ? notifications::kind::warning:notifications::kind::info; - const bool chatNote=title=="chat" || title=="system"; - std::vector runs; - if (chatNote) { - const auto tint=[](const float* c){return ImGui::ColorConvertFloat4ToU32({c[0],c[1],c[2],c[3]});}; - runs=rich_text::parse(body,tint(title=="chat" ? chatMessageColor:chatSystemColor)); - const auto end=body.starts_with('<') ? body.find('>'):std::string::npos; - if (end!=std::string::npos) rich_text::tint_range(runs,1,end,tint(chatNameColor)); - runs=rich_text::shorten(runs,280); - } - notifications::push(std::move(title),std::move(body),kind,chatNote ? 4:3,{},-1,std::move(runs),chatNote); -} -void cleanup(JNIEnv*) { - save(); - RemoveWindowSubclass(hwnd,procedure,subclass); - ImGui::SetCurrentContext(context); - if (musicView) musicView->release_texture(); - customIcon.Reset(); - startup_intro::texture.Reset(); - theme::custom_icon=nullptr; - ImGui_ImplOpenGL3_Shutdown(); - ImGui_ImplWin32_Shutdown(); - ImGui::DestroyContext(context); - fonts::forget(); - context=nullptr; -} -void stopWorkers() { - if (license) { license->stop(); delete license; license=nullptr; } - lyrics::shutdown(); - media::shutdown(); -} - -} // namespace java::overlay - -java_ui_modules& modules() { return java::overlay::adapters; } -java_ui_profiles& profiles() { static java_ui_profiles storage; return storage; } -licensing::service& java_ui_account_service() { return *java::overlay::license; } -const wchar_t* java_ui_credential() { return java::overlay::credentialTarget.c_str(); } -std::filesystem::path java_ui_account_path() { - const auto& dir=java::overlay::dir; - return dir.empty() ? std::filesystem::path{} : dir/"licensing.ini"; -} -bool java_ui_binding_key(int key) { return java::overlay::bindingKey==key && key!=VK_RSHIFT; } -bool input::ui_open() { return java::overlay::capture; } -void java_ui_module_extra(module& view,float width) { - using namespace java; - using namespace java::overlay; - if (&view==views[Waypoints]) { - for (size_t i=0;i java_ui_profiles::names() const { - using namespace java::overlay; - std::vector values{"default"}; - if (dir.empty()) return values; - std::error_code error; - for (std::filesystem::directory_iterator it(dir,error),end;it!=end && !error;it.increment(error)) { - if (it->path().extension()!=".profile") continue; - const auto name=it->path().stem().string(); - if (name!="default" && validProfile(name)) values.push_back(name); - } - std::ranges::sort(values); - return values; -} -bool java_ui_profiles::create(const std::string& name) { - using namespace java::overlay; - const auto list=names(); - if (std::ranges::any_of(list,[&](const auto& item){return _stricmp(item.c_str(),name.c_str())==0;})) { - profileError="that profile already exists"; - return false; - } - return switchProfile(name,true); -} -bool java_ui_profiles::rename(const std::string& name) { - using namespace java::overlay; - if (active()=="default") { profileError="default is protected"; return false; } - const auto old=profilePath(); - if (!create(name)) return false; - std::error_code error; - std::filesystem::remove(old,error); - if (error) { profileError="copied profile, but the old file could not be removed"; return false; } - return true; -} -bool java_ui_profiles::remove_active() { - using namespace java::overlay; - if (active()=="default") { profileError="default is protected"; return false; } - const auto old=profilePath(); - if (!switchProfile("default",false)) return false; - std::error_code error; - std::filesystem::remove(old,error); - if (error) { profileError="profile file could not be removed"; return false; } - return true; -} - -void java::tell(std::string title,std::string body) { overlay::addNote(std::move(title),std::move(body)); } diff --git a/java-client/src/overlay.h b/java-client/src/overlay.h deleted file mode 100644 index a8395eb..0000000 --- a/java-client/src/overlay.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once -#include -#include - -namespace java::overlay { -bool start(HWND window); -void draw(JNIEnv* env); -void cleanup(JNIEnv* env); -void stopWorkers(); -} diff --git a/java-client/src/ui_bridge.h b/java-client/src/ui_bridge.h deleted file mode 100644 index 9afac0f..0000000 --- a/java-client/src/ui_bridge.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include "gui/fonts.h" -#include "gui/hud_editor.h" -#include "gui/indent_section.h" -#include "gui/widgets.h" -#include "modules/module.h" -#include "account/license.h" -#include "game/media.h" -#include "game/lyrics.h" - -inline bool g_menu_open{}; -const wchar_t* java_ui_credential(); -licensing::service& java_ui_account_service(); -std::filesystem::path java_ui_account_path(); -bool java_ui_binding_key(int key); -void java_ui_module_extra(module& value,float width); -namespace account_ui { extern bool requested; } -namespace input { - inline void release_cursor() {} - inline void restore_cursor() {} - bool ui_open(); -} -namespace config { inline void bootstrap_theme() {} } -namespace theme_assets { inline std::string last_error; } - -struct java_ui_modules { - std::vector> items; - auto& all() { return items; } -}; -java_ui_modules& modules(); - -struct java_ui_profiles { - const std::string& active() const; - const std::string& last_error() const; - std::vector names() const; - bool blocked() const; - bool dirty() const; - void refresh() const; - void switch_to(const std::string& name); - void save(); - bool create(const std::string& name); - bool rename(const std::string& name); - bool remove_active(); -}; -java_ui_profiles& profiles(); - -struct java_ui_texture { - GLuint id{}; - explicit operator bool() const { return id!=0; } - GLuint Get() const { return id; } - void Reset() { if (id) glDeleteTextures(1,&id); id=0; } - void upload(unsigned width,unsigned height,const void* pixels) { - GLint bound{}; - glGetIntegerv(GL_TEXTURE_BINDING_2D,&bound); - if (!id) glGenTextures(1,&id); - glBindTexture(GL_TEXTURE_2D,id); - glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); - glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,pixels); - glBindTexture(GL_TEXTURE_2D,GLuint(bound)); - } -}; diff --git a/java-client/tests/gl_state.cpp b/java-client/tests/gl_state.cpp deleted file mode 100644 index c89f1c6..0000000 --- a/java-client/tests/gl_state.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "gl_state.h" -#include -#include - -namespace { -void check(bool pass,const char* message) { - if (pass) return; - std::cerr << message << '\n'; - std::exit(1); -} -GLint integer(GLenum key) { GLint result{}; glGetIntegerv(key,&result); return result; } -} - -int main() { - auto window=CreateWindowExW(0,L"STATIC",L"Amnesia GL state test",WS_POPUP,0,0,32,32,nullptr,nullptr,nullptr,nullptr); - check(window!=nullptr,"could not create a test window"); - auto dc=GetDC(window); - PIXELFORMATDESCRIPTOR descriptor{sizeof(descriptor),1,PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER, - PFD_TYPE_RGBA,32}; - auto format=ChoosePixelFormat(dc,&descriptor); - check(format!=0 && SetPixelFormat(dc,format,&descriptor),"could not select a pixel format"); - auto gl=wglCreateContext(dc); - check(gl && wglMakeCurrent(dc,gl),"could not create an OpenGL context"); - constexpr GLenum unpackBuffer=0x88EC, unpackBinding=0x88EF, drawFramebuffer=0x8CA9, drawBinding=0x8CA6; - using Bind=void (APIENTRY*)(GLenum,GLuint); - using Generate=void (APIENTRY*)(GLsizei,GLuint*); - const auto genBuffer=reinterpret_cast(wglGetProcAddress("glGenBuffers")); - const auto bindBuffer=reinterpret_cast(wglGetProcAddress("glBindBuffer")); - const auto genFrame=reinterpret_cast(wglGetProcAddress("glGenFramebuffers")); - const auto bindFrame=reinterpret_cast(wglGetProcAddress("glBindFramebuffer")); - check(genBuffer && bindBuffer && genFrame && bindFrame,"driver has no modern buffer functions"); - GLuint buffer{}, frame{}; - genBuffer(1,&buffer); - genFrame(1,&frame); - bindBuffer(unpackBuffer,buffer); - bindFrame(drawFramebuffer,frame); - glPixelStorei(GL_UNPACK_ALIGNMENT,8); - glPixelStorei(GL_UNPACK_ROW_LENGTH,120); - glPixelStorei(GL_UNPACK_SKIP_ROWS,20); - glPixelStorei(GL_UNPACK_SKIP_PIXELS,35); - glPixelStorei(0x806E,50); - glPixelStorei(0x806D,4); - glPixelStorei(GL_UNPACK_SWAP_BYTES,1); - glPixelStorei(GL_UNPACK_LSB_FIRST,1); - glColorMask(0,1,0,0); - { - java::overlay::GlState guard; - check(!integer(unpackBinding) && !integer(drawBinding),"buffer and framebuffer must be released"); - check(integer(GL_UNPACK_ALIGNMENT)==1 && !integer(GL_UNPACK_ROW_LENGTH) && !integer(GL_UNPACK_SKIP_ROWS) && - !integer(GL_UNPACK_SKIP_PIXELS) && !integer(0x806E) && !integer(0x806D) && - !integer(GL_UNPACK_SWAP_BYTES) && !integer(GL_UNPACK_LSB_FIRST),"all unpack offsets must be reset"); - GLuint texture{}; - glGenTextures(1,&texture); - glBindTexture(GL_TEXTURE_2D,texture); - const unsigned color=0xff80ff40; - glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,1,1,0,GL_RGBA,GL_UNSIGNED_BYTE,&color); - check(glGetError()==GL_NO_ERROR,"CPU texture upload must succeed"); - glDeleteTextures(1,&texture); - } - check(integer(unpackBinding)==GLint(buffer) && integer(drawBinding)==GLint(frame),"buffer bindings must be restored"); - check(integer(GL_UNPACK_ALIGNMENT)==8 && integer(GL_UNPACK_ROW_LENGTH)==120 && integer(GL_UNPACK_SKIP_ROWS)==20 && - integer(GL_UNPACK_SKIP_PIXELS)==35 && integer(0x806E)==50 && integer(0x806D)==4 && - integer(GL_UNPACK_SWAP_BYTES)==1 && integer(GL_UNPACK_LSB_FIRST)==1,"all unpack state must be restored"); - GLboolean mask[4]{}; - glGetBooleanv(GL_COLOR_WRITEMASK,mask); - check(!mask[0] && mask[1] && !mask[2] && !mask[3],"color mask must be restored"); - wglMakeCurrent(nullptr,nullptr); - wglDeleteContext(gl); - ReleaseDC(window,dc); - DestroyWindow(window); -} diff --git a/java-client/tools/bindings.py b/java-client/tools/bindings.py deleted file mode 100644 index f91c3f1..0000000 --- a/java-client/tools/bindings.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Build the small JNI binding table from the official 1.21.1 client mapping.""" -import hashlib -import re -import sys -from pathlib import Path - -MAPPING_SHA1 = "2244b6f072256667bcd9a73df124d6c58de77992" -PRIMITIVES = dict(zip("void boolean byte char short int long float double".split(), "VZBCSIJFD")) - - -def descriptor(type_name, classes): - dimensions = 0 - while type_name.endswith("[]"): - dimensions += 1 - type_name = type_name[:-2] - if type_name in PRIMITIVES: - return "[" * dimensions + PRIMITIVES[type_name] - return "[" * dimensions + "L" + classes.get(type_name, type_name).replace(".", "/") + ";" - - -def read_mapping(raw): - classes, members = {}, {} - owner = None - for line in raw.decode("utf-8").splitlines(): - if not line or line.startswith("#") or " -> " not in line: - continue - left, right = line.strip().rsplit(" -> ", 1) - if not line[0].isspace(): - owner = left - classes[left] = right.removesuffix(":") - members[left] = {} - continue - match = re.fullmatch(r"(?:\d+:\d+:)?(\S+) (\S+?)(?::\d+(?::\d+)?)?", left) - if match: - result, member = match.groups() - members[owner].setdefault(member, set()).add((result, right)) - return classes, members - - -def main(mapping_path, spec_path, output_path): - raw = Path(mapping_path).read_bytes() - if hashlib.sha1(raw).hexdigest() != MAPPING_SHA1: - raise ValueError("expected the unmodified Mojang Java 1.21.1 client mappings") - classes, members = read_mapping(raw) - aliases, rows = {}, [] - for line in Path(spec_path).read_text().splitlines(): - if not line.strip() or line.startswith("#"): - continue - kind, alias, owner, *entry = line.split() - if kind == "class": - aliases[alias] = owner - rows.append((alias, "Class", owner, classes.get(owner, owner), "", "", "", "")) - continue - owner = aliases[owner] - if kind == "ctor": - member = "" + entry[0] - result, obfuscated = "void", "" - else: - member = entry[0] - variants = members[owner].get(member, ()) - if len(entry) == 2: - variants = [variant for variant in variants if variant[0] == entry[1]] - if len(variants) != 1: - raise ValueError(f"{alias}: expected one declaration of {owner}.{member}, found {variants}") - result, obfuscated = next(iter(variants)) - name, separator, arguments = member.partition("(") - signatures = [] - for class_map in ({}, classes): - signature = descriptor(result, class_map) - if separator: - arguments_list = arguments.removesuffix(")").split(",") if arguments != ")" else [] - signature = "(" + "".join(descriptor(arg, class_map) for arg in arguments_list) + ")" + signature - signatures.append(signature) - rows.append((alias, "Constructor" if kind == "ctor" else kind.title(), owner, - classes.get(owner, owner), name, obfuscated, *signatures)) - body = ["// Generated from Mojang Java 1.21.1 mappings.", "#pragma once", - "enum class Kind { Class, Field, Staticfield, Method, Staticmethod, Constructor };", - "enum Binding {"] - body.extend(f" {row[0]}," for row in rows) - body.extend([" BindingCount", "};", - "struct Declaration { Kind kind; const char* owner[2]; const char* name[2]; const char* signature[2]; };", - "inline constexpr Declaration declarations[] = {"]) - for _, kind, named_owner, obf_owner, named, obf, named_sig, obf_sig in rows: - body.append(f' {{Kind::{kind}, {{"{named_owner}", "{obf_owner}"}}, {{"{named}", "{obf}"}}, {{"{named_sig}", "{obf_sig}"}}}},') - body.extend(["};", ""]) - Path(output_path).write_text("\n".join(body), encoding="utf-8") - - -if __name__ == "__main__": - main(*sys.argv[1:]) diff --git a/java-client/tools/fetch-mappings.ps1 b/java-client/tools/fetch-mappings.ps1 deleted file mode 100644 index 24edf51..0000000 --- a/java-client/tools/fetch-mappings.ps1 +++ /dev/null @@ -1,13 +0,0 @@ -$ErrorActionPreference = 'Stop' -$root = Split-Path -Parent $PSScriptRoot -$deps = Join-Path $root 'build/deps' -New-Item -ItemType Directory -Path $deps -Force | Out-Null -$version = (Invoke-RestMethod 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json').versions | - Where-Object id -eq '1.21.1' | Select-Object -First 1 -if (-not $version) { throw 'Mojang did not list Java 1.21.1.' } -$mappings = (Invoke-RestMethod $version.url).downloads.client_mappings -$file = Join-Path $deps 'client.txt' -Invoke-WebRequest $mappings.url -OutFile $file -if ((Get-FileHash -LiteralPath $file -Algorithm SHA1).Hash -ne '2244b6f072256667bcd9a73df124d6c58de77992') { - throw 'The downloaded mappings did not match Mojang Java 1.21.1.' -} diff --git a/java-client/tools/reuse_ui.py b/java-client/tools/reuse_ui.py deleted file mode 100644 index aebfdae..0000000 --- a/java-client/tools/reuse_ui.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Stage Bedrock views with Java platform adapters. Rendering stays upstream.""" -from pathlib import Path -import sys - - -def replace(text, old, new): - if text.count(old) != 1: - raise ValueError(f"Bedrock UI adapter expected one occurrence of {old!r}") - return text.replace(old, new) - - -def region(text, start, end, content): - left = text.index(start) - right = text.index(end, left) - return text[:left] + content + text[right:] - - -def generate(src, out): - out.mkdir(parents=True, exist_ok=True) - for name, location in { - "clickgui": "gui", "account_screen": "gui", "startup_intro": "gui", "music_player": "modules" - }.items(): - content = (src / location / f"{name}.h").read_text(encoding="utf-8") - if name == "clickgui": - content = region(content, "#include \"imgui.h\"", "inline std::string key_name", '#include "ui_bridge.h"\n\n') - content = replace(content, "const bool menu_down = is_key_down(k_menu_key);", "const bool menu_down = false;") - content = replace(content, "const bool esc_down = is_key_down(VK_ESCAPE);", "const bool esc_down = false;") - content = replace(content, " void draw_backdrop() {", """ bool editing_hud() const { return editing_hud_; } - bool binding() const { return any_binding(); } - void escape() { - if (editing_hud_) editing_hud_ = false; - else close(); - } - void draw_backdrop() {""") - content = replace(content, "if (is_key_down(vk)) {\n m.set_toggle_key", - "if (java_ui_binding_key(vk)) {\n m.set_toggle_key") - content = replace(content, "if (is_key_down(vk)) {\n // Keep", - "if (java_ui_binding_key(vk)) {\n // Keep") - content = replace(content, "for (auto& s:m.settings()) if (!s.hidden) draw_setting(s,inner_w);", - "for (auto& s:m.settings()) if (!s.hidden) draw_setting(s,inner_w);\n java_ui_module_extra(m,inner_w);") - elif name == "account_screen": - content = region(content, "#include", "namespace account_ui", '#include "ui_bridge.h"\n\n') - content = content.replace("licensing::client()", "java_ui_account_service()") - content = content.replace("licensing::config_path()", "java_ui_account_path()") - content = content.replace("licensing::saved_login::load(saved)", "licensing::saved_login::load(saved, java_ui_credential())") - content = content.replace("licensing::saved_login::forget()", "licensing::saved_login::forget(java_ui_credential())") - content = replace(content, 'L"http://127.0.0.1:8787/api",value', 'winrt::to_hstring(address).c_str(),value') - elif name == "startup_intro": - content = region(content, "#include ", "namespace startup_intro", '#include "ui_bridge.h"\n\n') - content = replace(content, "Microsoft::WRL::ComPtr texture;", "java_ui_texture texture;") - content = replace(content, "void initialize_texture(ID3D11Device* device)", "void initialize_texture()") - content = replace(content, "if(!device || texture)return;", "if(texture)return;") - content = region(content, " D3D11_TEXTURE2D_DESC desc", " struct playback", - " texture.upload(128,128,pixels.data());\n }\n\n") - content = replace(content, "reinterpret_cast(texture.Get())", "ImTextureID(texture.Get())") - elif name == "music_player": - content = region(content, "#include", "class music_player", '#include "ui_bridge.h"\n#include "modules/text_hud.h"\n\n') - content = replace(content, "Microsoft::WRL::ComPtr image_;", "java_ui_texture image_;") - content = replace(content, "!art || !media_art::device || ", "!art || ") - content = region(content, " D3D11_TEXTURE2D_DESC desc", " }\n};", - " image_.upload(art->width,art->height,art->rgba.data());\n") - content = replace(content, " float text_font_size() const", " void release_texture() { image_.Reset(); }\n float text_font_size() const") - (out / f"bedrock_{name}.h").write_text(content, encoding="utf-8") - - -if __name__ == "__main__": - generate(*(Path(arg) for arg in sys.argv[1:]))