add java client source
This commit is contained in:
commit
c7a15fdc7d
98 files changed
+80145
No files matched your search
@@ -0,0 +1,2 @@
|
||||
/build/
|
||||
__pycache__/
|
||||
@@ -0,0 +1,57 @@
|
||||
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 $<$<COMPILE_LANGUAGE:CXX>:/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()
|
||||
@@ -0,0 +1,40 @@
|
||||
# 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 <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.
|
||||
@@ -0,0 +1,123 @@
|
||||
#include "game.h"
|
||||
#include "overlay.h"
|
||||
#include "MinHook.h"
|
||||
#include <windows.h>
|
||||
#include <gl/GL.h>
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
|
||||
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<bool> stopping{}, finished{};
|
||||
std::atomic<bool> started{};
|
||||
std::atomic<DWORD> 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 && length<std::size(path)) {
|
||||
auto file=std::filesystem::path(path).parent_path()/"amnesia-java.log";
|
||||
std::ofstream(file,std::ios::app) << message << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
BOOL WINAPI present(HDC dc) {
|
||||
if (inside || finished || !dc || !wglGetCurrentContext()) return original(dc);
|
||||
auto target=WindowFromDC(dc);
|
||||
if (!target) return original(dc);
|
||||
wchar_t name[24]{};
|
||||
if (!GetClassNameW(target,name,int(std::size(name))) || wcscmp(name,L"GLFW30")!=0) return original(dc);
|
||||
const auto current=GetCurrentThreadId();
|
||||
DWORD owner{};
|
||||
renderThread.compare_exchange_strong(owner,current);
|
||||
if (renderThread!=current) return original(dc);
|
||||
inside=true;
|
||||
JNIEnv* env{};
|
||||
java::vm->GetEnv(reinterpret_cast<void**>(&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<void**>(&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<GetVMs>(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<void*>(GetProcAddress(gdi,"SwapBuffers")) : nullptr;
|
||||
if (!hook || MH_Initialize()!=MH_OK ||
|
||||
MH_CreateHook(hook,&present,reinterpret_cast<void**>(&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<LPCWSTR>(&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()<deadline) Sleep(20);
|
||||
if (!finished) return ERROR_TIMEOUT;
|
||||
if (hook) MH_DisableHook(hook);
|
||||
java::overlay::stopWorkers();
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE dll,DWORD reason,LPVOID) {
|
||||
if (reason==DLL_PROCESS_ATTACH) {
|
||||
self=dll;
|
||||
DisableThreadLibraryCalls(dll);
|
||||
if (auto thread=CreateThread(nullptr,0,&bootstrap,nullptr,0,nullptr)) CloseHandle(thread);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
class Minecraft net.minecraft.client.Minecraft
|
||||
class SharedConstants net.minecraft.SharedConstants
|
||||
class WorldVersion net.minecraft.WorldVersion
|
||||
class KeyMapping net.minecraft.client.KeyMapping
|
||||
class BlockHitResult net.minecraft.world.phys.BlockHitResult
|
||||
class EntityHitResult net.minecraft.world.phys.EntityHitResult
|
||||
class LivingEntity net.minecraft.world.entity.LivingEntity
|
||||
class Player net.minecraft.world.entity.player.Player
|
||||
class Monster net.minecraft.world.entity.monster.Monster
|
||||
class Animal net.minecraft.world.entity.animal.Animal
|
||||
class EnderMan net.minecraft.world.entity.monster.EnderMan
|
||||
class Vec3 net.minecraft.world.phys.Vec3
|
||||
class Blocks net.minecraft.world.level.block.Blocks
|
||||
class InteractionHand net.minecraft.world.InteractionHand
|
||||
class CameraType net.minecraft.client.CameraType
|
||||
class MouseHandler net.minecraft.client.MouseHandler
|
||||
class ClientLevel net.minecraft.client.multiplayer.ClientLevel
|
||||
class ChunkSource net.minecraft.world.level.chunk.ChunkSource
|
||||
class ChunkAccess net.minecraft.world.level.chunk.ChunkAccess
|
||||
class LevelChunkSection net.minecraft.world.level.chunk.LevelChunkSection
|
||||
class Block net.minecraft.world.level.block.Block
|
||||
class State net.minecraft.world.level.block.state.BlockBehaviour$BlockStateBase
|
||||
class Entity net.minecraft.world.entity.Entity
|
||||
class EntityType net.minecraft.world.entity.EntityType
|
||||
class PlayerInfo net.minecraft.client.multiplayer.PlayerInfo
|
||||
class GameMode net.minecraft.client.multiplayer.MultiPlayerGameMode
|
||||
class PacketListener net.minecraft.client.multiplayer.ClientPacketListener
|
||||
class Options net.minecraft.client.Options
|
||||
class OptionInstance net.minecraft.client.OptionInstance
|
||||
class Level net.minecraft.world.level.Level
|
||||
class HeightAccessor net.minecraft.world.level.LevelHeightAccessor
|
||||
class ResourceKey net.minecraft.resources.ResourceKey
|
||||
class Renderer net.minecraft.client.renderer.GameRenderer
|
||||
class Camera net.minecraft.client.Camera
|
||||
class Component net.minecraft.network.chat.Component
|
||||
class Gui net.minecraft.client.gui.Gui
|
||||
class ChatComponent net.minecraft.client.gui.components.ChatComponent
|
||||
class GuiMessage net.minecraft.client.GuiMessage
|
||||
class Inventory net.minecraft.world.entity.player.Inventory
|
||||
class ItemStack net.minecraft.world.item.ItemStack
|
||||
class MobEffectInstance net.minecraft.world.effect.MobEffectInstance
|
||||
class HitResult net.minecraft.world.phys.HitResult
|
||||
class Vec3i net.minecraft.core.Vec3i
|
||||
class BlockPos net.minecraft.core.BlockPos
|
||||
class FoodData net.minecraft.world.food.FoodData
|
||||
class I18n net.minecraft.client.resources.language.I18n
|
||||
class LocalPlayer net.minecraft.client.player.LocalPlayer
|
||||
class AbstractContainerScreen net.minecraft.client.gui.screens.inventory.AbstractContainerScreen
|
||||
class AbstractContainerMenu net.minecraft.world.inventory.AbstractContainerMenu
|
||||
class Slot net.minecraft.world.inventory.Slot
|
||||
class ClickType net.minecraft.world.inventory.ClickType
|
||||
class User net.minecraft.client.User
|
||||
class ArmorStand net.minecraft.world.entity.decoration.ArmorStand
|
||||
class ParticleStatus net.minecraft.client.ParticleStatus
|
||||
class AbstractClientPlayer net.minecraft.client.player.AbstractClientPlayer
|
||||
class PlayerSkin net.minecraft.client.resources.PlayerSkin
|
||||
class TextureManager net.minecraft.client.renderer.texture.TextureManager
|
||||
class AbstractTexture net.minecraft.client.renderer.texture.AbstractTexture
|
||||
class ServerData net.minecraft.client.multiplayer.ServerData
|
||||
class SoundManager net.minecraft.client.sounds.SoundManager
|
||||
class SoundEngine net.minecraft.client.sounds.SoundEngine
|
||||
class SoundInstance net.minecraft.client.resources.sounds.SoundInstance
|
||||
|
||||
staticmethod mcGet Minecraft getInstance()
|
||||
staticmethod worldVersion SharedConstants getCurrentVersion()
|
||||
method versionName WorldVersion getName()
|
||||
method mcFps Minecraft getFps()
|
||||
method mcConn Minecraft getConnection()
|
||||
method mcUser Minecraft getUser()
|
||||
method mcAttack Minecraft startAttack()
|
||||
method mcUse Minecraft startUseItem()
|
||||
method mcServer Minecraft getCurrentServer()
|
||||
method mcSound Minecraft getSoundManager()
|
||||
method realmServer ServerData isRealm()
|
||||
field soundEngine SoundManager soundEngine
|
||||
field soundChannels SoundEngine instanceToChannel
|
||||
method soundId SoundInstance getLocation()
|
||||
method soundX SoundInstance getX()
|
||||
method soundY SoundInstance getY()
|
||||
method soundZ SoundInstance getZ()
|
||||
method soundRelative SoundInstance isRelative()
|
||||
method textures Minecraft getTextureManager()
|
||||
method setCamera Minecraft setCameraEntity(net.minecraft.world.entity.Entity)
|
||||
method currentCamera Minecraft getCameraEntity()
|
||||
field mcPlayer Minecraft player
|
||||
field mcWorld Minecraft level
|
||||
field mcScreen Minecraft screen
|
||||
field mcMouse Minecraft mouseHandler
|
||||
field mcOptions Minecraft options
|
||||
field mcGameMode Minecraft gameMode
|
||||
field mcHit Minecraft hitResult
|
||||
field mcGui Minecraft gui
|
||||
field mcRenderer Minecraft gameRenderer
|
||||
method userName User getName()
|
||||
method mouseGrabbed MouseHandler isMouseGrabbed()
|
||||
method mouseGrab MouseHandler grabMouse()
|
||||
method mouseRelease MouseHandler releaseMouse()
|
||||
staticmethod releaseKeys KeyMapping releaseAll()
|
||||
method keyDown KeyMapping isDown()
|
||||
method keySet KeyMapping setDown(boolean)
|
||||
field sprintKey Options keySprint
|
||||
field forwardKey Options keyUp
|
||||
field hideGui Options hideGui
|
||||
method optFov Options fov()
|
||||
method optGamma Options gamma()
|
||||
method optEntityDistance Options entityDistanceScaling()
|
||||
method optParticles Options particles()
|
||||
staticfield particlesLow ParticleStatus DECREASED
|
||||
staticfield particlesMinimal ParticleStatus MINIMAL
|
||||
method optCameraType Options getCameraType()
|
||||
method optSetCameraType Options setCameraType(net.minecraft.client.CameraType)
|
||||
field optRaw OptionInstance value
|
||||
staticfield thirdPerson CameraType THIRD_PERSON_BACK
|
||||
method worldEntities ClientLevel entitiesForRendering()
|
||||
method worldChunks ClientLevel getChunkSource() net.minecraft.client.multiplayer.ClientChunkCache
|
||||
method worldSetDay ClientLevel setDayTime(long)
|
||||
method worldDim Level dimension()
|
||||
method worldDay Level getDayTime()
|
||||
method worldBlock Level getBlockState(net.minecraft.core.BlockPos)
|
||||
method worldRain Level getRainLevel(float)
|
||||
method worldThunder Level getThunderLevel(float)
|
||||
method worldSetRain Level setRainLevel(float)
|
||||
method worldSetThunder Level setThunderLevel(float)
|
||||
method worldBottom HeightAccessor getMinBuildHeight()
|
||||
method dimensionLocation ResourceKey location()
|
||||
method chunkNow ChunkSource getChunkNow(int,int)
|
||||
method chunkSections ChunkAccess getSections()
|
||||
method sectionBlock LevelChunkSection getBlockState(int,int,int)
|
||||
method sectionContains LevelChunkSection maybeHas(java.util.function.Predicate)
|
||||
staticfield netherBricks Blocks NETHER_BRICKS
|
||||
method defaultState Block defaultBlockState()
|
||||
method stateBlock State getBlock()
|
||||
method stateAir State isAir()
|
||||
method blockName Block getDescriptionId()
|
||||
ctor newPos BlockPos (int,int,int)
|
||||
method posX Vec3i getX()
|
||||
method posY Vec3i getY()
|
||||
method posZ Vec3i getZ()
|
||||
method targetBlock BlockHitResult getBlockPos()
|
||||
method hitLocation HitResult getLocation()
|
||||
method hitType HitResult getType()
|
||||
method targetEntity EntityHitResult getEntity()
|
||||
method playerAttack GameMode attack(net.minecraft.world.entity.player.Player,net.minecraft.world.entity.Entity)
|
||||
method playerClick GameMode handleInventoryMouseClick(int,int,int,net.minecraft.world.inventory.ClickType,net.minecraft.world.entity.player.Player)
|
||||
method connectionPlayers PacketListener getOnlinePlayers()
|
||||
method sendChat PacketListener sendChat(java.lang.String)
|
||||
method sendCommand PacketListener sendCommand(java.lang.String)
|
||||
method profile PlayerInfo getProfile()
|
||||
method latency PlayerInfo getLatency()
|
||||
method playerX Entity getX()
|
||||
method playerY Entity getY()
|
||||
method playerZ Entity getZ()
|
||||
method entityId Entity getId()
|
||||
method entityName Entity getName()
|
||||
method entityAlive Entity isAlive()
|
||||
method entityGround Entity onGround()
|
||||
method entityWater Entity isInWater()
|
||||
method entityPassenger Entity isPassenger()
|
||||
method entityInvisible Entity isInvisible()
|
||||
method entityVisible LivingEntity hasLineOfSight(net.minecraft.world.entity.Entity)
|
||||
method entityHeight Entity getBbHeight()
|
||||
method entityYaw Entity getYRot()
|
||||
method entityPitch Entity getXRot()
|
||||
method entitySetPos Entity setPos(double,double,double)
|
||||
method setYaw Entity setYRot(float)
|
||||
method setPitch Entity setXRot(float)
|
||||
method setSprint Entity setSprinting(boolean)
|
||||
method setName Entity setCustomName(net.minecraft.network.chat.Component)
|
||||
method customName Entity getCustomName()
|
||||
method entityType Entity getType()
|
||||
method typeName EntityType getDescriptionId()
|
||||
field fallDistance Entity fallDistance
|
||||
method health LivingEntity getHealth()
|
||||
method maxHealth LivingEntity getMaxHealth()
|
||||
method mainHand LivingEntity getMainHandItem()
|
||||
method offHand LivingEntity getOffhandItem()
|
||||
method armor LivingEntity getArmorSlots()
|
||||
method effects LivingEntity getActiveEffects()
|
||||
method swing LivingEntity swing(net.minecraft.world.InteractionHand)
|
||||
method usingItem LivingEntity isUsingItem()
|
||||
method attackStrength Player getAttackStrengthScale(float)
|
||||
method inventory Player getInventory()
|
||||
method food Player getFoodData()
|
||||
method foodLevel FoodData getFoodLevel()
|
||||
field xpLevel Player experienceLevel
|
||||
field xpProgress Player experienceProgress
|
||||
method xpNext Player getXpNeededForNextLevel()
|
||||
field selected Inventory selected
|
||||
method inventoryStack Inventory getItem(int)
|
||||
method emptyStack ItemStack isEmpty()
|
||||
method itemName ItemStack getHoverName()
|
||||
method count ItemStack getCount()
|
||||
method itemDescription ItemStack getDescriptionId()
|
||||
method itemDamage ItemStack getDamageValue()
|
||||
method itemMaxDamage ItemStack getMaxDamage()
|
||||
method toolSpeed ItemStack getDestroySpeed(net.minecraft.world.level.block.state.BlockState)
|
||||
method effectName MobEffectInstance getDescriptionId()
|
||||
method effectDuration MobEffectInstance getDuration()
|
||||
method effectAmplifier MobEffectInstance getAmplifier()
|
||||
method rendererCamera Renderer getMainCamera()
|
||||
method rendererFov Renderer getFov(net.minecraft.client.Camera,float,boolean)
|
||||
method camPos Camera getPosition()
|
||||
method camYaw Camera getYRot()
|
||||
method camPitch Camera getXRot()
|
||||
field vecX Vec3 x
|
||||
field vecY Vec3 y
|
||||
field vecZ Vec3 z
|
||||
method plain Component getString()
|
||||
staticmethod literal Component literal(java.lang.String)
|
||||
staticmethod translate I18n get(java.lang.String,java.lang.Object[])
|
||||
method guiChat Gui getChat()
|
||||
field guiHeldTimer Gui toolHighlightTimer
|
||||
field guiOverlayTimer Gui overlayMessageTime
|
||||
field chatMessages ChatComponent allMessages
|
||||
field chatLines ChatComponent trimmedMessages
|
||||
method restoreChatLines ChatComponent refreshTrimmedMessages()
|
||||
method chatContent GuiMessage content()
|
||||
staticfield handMain InteractionHand MAIN_HAND
|
||||
field screenMenu AbstractContainerScreen menu
|
||||
field playerMenu Player inventoryMenu
|
||||
field menuSlots AbstractContainerMenu slots
|
||||
field menuId AbstractContainerMenu containerId
|
||||
method menuCarried AbstractContainerMenu getCarried()
|
||||
field slotContainer Slot container
|
||||
method slotItem Slot getItem()
|
||||
method slotNumber Slot getContainerSlot()
|
||||
staticfield quickMove ClickType QUICK_MOVE
|
||||
staticfield armorStandType EntityType ARMOR_STAND
|
||||
ctor newCameraActor ArmorStand (net.minecraft.world.entity.EntityType,net.minecraft.world.level.Level)
|
||||
field oldX Entity xo
|
||||
field oldY Entity yo
|
||||
field oldZ Entity zo
|
||||
field oldYaw Entity yRotO
|
||||
field oldPitch Entity xRotO
|
||||
method skin AbstractClientPlayer getSkin()
|
||||
method skinResource PlayerSkin texture()
|
||||
method texture TextureManager getTexture(net.minecraft.resources.ResourceLocation)
|
||||
method textureId AbstractTexture getId()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
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<Module, ModuleCount> 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<Item, 9> hotbar;
|
||||
Item held, offhand;
|
||||
std::vector<Item> armor;
|
||||
std::vector<std::string> effects;
|
||||
std::vector<std::pair<std::string,int>> online;
|
||||
std::vector<Actor> actors;
|
||||
std::array<std::vector<Item>,2> inventoryChoices;
|
||||
unsigned containerEpoch{};
|
||||
bool containerTransfer{}, containerCursor{}, containerBusy{};
|
||||
std::vector<Waypoint> waypoints, logouts;
|
||||
std::deque<Vec> trail;
|
||||
std::deque<Message> chat;
|
||||
std::deque<SoundMark> sounds;
|
||||
std::vector<Vec> 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);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <gl/GL.h>
|
||||
#include <array>
|
||||
|
||||
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<GLenum,8> 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<GLint,pixelKeys.size()> unpack{};
|
||||
std::array<GLboolean,4> colorMask{};
|
||||
|
||||
public:
|
||||
GlState() {
|
||||
bindBuffer=reinterpret_cast<Bind>(wglGetProcAddress("glBindBuffer"));
|
||||
bindFramebuffer=reinterpret_cast<Bind>(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<GLboolean,4>{1,1,1,1}) glColorMask(1,1,1,1);
|
||||
for (size_t i=0;i<pixelKeys.size();++i) {
|
||||
glGetIntegerv(pixelKeys[i],&unpack[i]);
|
||||
if (unpack[i]!=int(!i)) glPixelStorei(pixelKeys[i],int(!i));
|
||||
}
|
||||
}
|
||||
GlState(const GlState&)=delete;
|
||||
GlState& operator=(const GlState&)=delete;
|
||||
~GlState() {
|
||||
for (size_t i=0;i<pixelKeys.size();++i)
|
||||
if (unpack[i]!=int(!i)) glPixelStorei(pixelKeys[i],unpack[i]);
|
||||
if (buffer) bindBuffer(unpackBuffer,GLuint(buffer));
|
||||
if (framebuffer) bindFramebuffer(drawFramebuffer,GLuint(framebuffer));
|
||||
if (colorMask!=std::array<GLboolean,4>{1,1,1,1}) glColorMask(colorMask[0],colorMask[1],colorMask[2],colorMask[3]);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#include <windows.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::vector<GameWindow>*>(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<uintptr_t>(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<LPCWSTR>(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<LPTHREAD_START_ROUTINE>(base+(reinterpret_cast<uintptr_t>(function)-reinterpret_cast<uintptr_t>(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<argc;++i) {
|
||||
if (wcscmp(argv[i],L"--detach")==0) detach=true;
|
||||
else if (wcscmp(argv[i],L"--pid")==0 && i+1<argc) {
|
||||
wchar_t* end{};
|
||||
requested=wcstoul(argv[++i],&end,10);
|
||||
if (!requested || *end) return 2;
|
||||
} else { std::wcerr << L"Usage: amnesia-java-loader [--pid PID] [--detach]\n"; return 2; }
|
||||
}
|
||||
std::vector<GameWindow> games;
|
||||
EnumWindows(findGame,reinterpret_cast<LPARAM>(&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<LPTHREAD_START_ROUTINE>(installed+
|
||||
reinterpret_cast<uintptr_t>(exported)-reinterpret_cast<uintptr_t>(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<const void*>(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;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <jni.h>
|
||||
|
||||
namespace java::overlay {
|
||||
bool start(HWND window);
|
||||
void draw(JNIEnv* env);
|
||||
void cleanup(JNIEnv* env);
|
||||
void stopWorkers();
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <gl/GL.h>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#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<std::unique_ptr<module>> 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<std::string> 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));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
#include "gl_state.h"
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
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<Generate>(wglGetProcAddress("glGenBuffers"));
|
||||
const auto bindBuffer=reinterpret_cast<Bind>(wglGetProcAddress("glBindBuffer"));
|
||||
const auto genFrame=reinterpret_cast<Generate>(wglGetProcAddress("glGenFramebuffers"));
|
||||
const auto bindFrame=reinterpret_cast<Bind>(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);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"""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 = "<init>" + entry[0]
|
||||
result, obfuscated = "void", "<init>"
|
||||
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:])
|
||||
@@ -0,0 +1,13 @@
|
||||
$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.'
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""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 <d3d11.h>", "namespace startup_intro", '#include "ui_bridge.h"\n\n')
|
||||
content = replace(content, "Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> 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<ImTextureID>(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<ID3D11ShaderResourceView> 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:]))
|
||||
Reference in new issue
Block a user