├── .github ├── FUNDING.yml └── workflows │ └── minecraft.yml ├── src └── main │ ├── resources │ ├── icon.png │ ├── fabric.mod.json │ ├── lotas.mixin.json │ └── lotas.accesswidener │ └── java │ └── com │ └── minecrafttas │ └── lotas │ ├── ClientLoTAS.java │ ├── mixin │ ├── tickratechanger │ │ ├── MixinDedicatedServer.java │ │ └── MixinMinecraftServer.java │ ├── client │ │ ├── tickratechanger │ │ │ ├── MixinItemRenderer.java │ │ │ ├── MixinToastInstance.java │ │ │ ├── MixinLevelRenderer.java │ │ │ ├── MixinSoundEngine.java │ │ │ ├── MixinTimer.java │ │ │ └── MixinSubtitleOverlay.java │ │ └── events │ │ │ ├── HookClientPlayNetworkHandler.java │ │ │ ├── HookOptions.java │ │ │ └── HookMinecraft.java │ ├── events │ │ ├── HookPlayNetworkHandler.java │ │ ├── HookPlayerList.java │ │ └── HookMinecraftServer.java │ └── dragonmanipulation │ │ ├── MixinDragonTakeoffPhase.java │ │ ├── MixinDragonStrafePlayerPhase.java │ │ ├── MixinDragonLandingApproachPhase.java │ │ └── MixinDragonHoldingPatternPhase.java │ ├── LoTAS.java │ ├── mods │ ├── savestatemod │ │ └── StateData.java │ ├── DragonManipulation.java │ ├── TickAdvance.java │ ├── DupeMod.java │ ├── TickrateChanger.java │ └── SavestateMod.java │ └── system │ ├── KeybindSystem.java │ ├── ModSystem.java │ └── ConfigurationSystem.java ├── gradle.properties ├── .gitignore ├── settings.gradle ├── README.md └── LICENSE.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | patreon: pancaketas 2 | -------------------------------------------------------------------------------- /src/main/resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MinecraftTAS/LoTAS/HEAD/src/main/resources/icon.png -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # require 2 gb memory for decompiling 2 | org.gradle.jvmargs=-Xmx2G 3 | 4 | # configure fabric 5 | loader_version=0.15.3 6 | loom_version=1.5-SNAPSHOT 7 | 8 | # configure lotas 9 | lotas_version=3.0.0-SNAPSHOT 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle files 2 | .gradle/ 3 | build/ 4 | 5 | # IntelliJ files 6 | .idea/ 7 | 8 | # Eclipse files 9 | .settings/ 10 | .metadata/ 11 | .factorypath 12 | .classpath 13 | .project 14 | 15 | # Minecraft files 16 | run-server/ 17 | run/ 18 | *.launch -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | // configure plugin management 2 | pluginManagement { 3 | // add repositories for plugins 4 | repositories { 5 | // add mgnetwork repository 6 | maven { url = 'https://maven.mgnet.work/main' } 7 | 8 | // add fabric repository 9 | maven { url = 'https://maven.fabricmc.net/' } 10 | 11 | // add other main repositories 12 | mavenCentral() 13 | gradlePluginPortal() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/ClientLoTAS.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas; 2 | 3 | import com.minecrafttas.lotas.system.ModSystem; 4 | import net.fabricmc.api.ClientModInitializer; 5 | import net.fabricmc.api.EnvType; 6 | import net.fabricmc.api.Environment; 7 | 8 | /** 9 | * LoTAS fabric mod core for the client 10 | * 11 | * @author Pancake 12 | */ 13 | @Environment(EnvType.CLIENT) 14 | public class ClientLoTAS implements ClientModInitializer { 15 | 16 | @Override 17 | public void onInitializeClient() { 18 | ModSystem.onClientsideInitialize(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/tickratechanger/MixinDedicatedServer.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.tickratechanger; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.Overwrite; 5 | 6 | import net.minecraft.server.dedicated.DedicatedServer; 7 | 8 | /** 9 | * This mixin disables the max tick length preventing a crash that occurs when in tickrate zero for too long. 10 | * 11 | * @author Pancake 12 | */ 13 | @Mixin(DedicatedServer.class) 14 | public class MixinDedicatedServer { 15 | 16 | /** 17 | * Disable max tick length 18 | * 19 | * @reason Prevent crash 20 | * @author Pancake 21 | * @return Max tick length 22 | */ 23 | @Overwrite 24 | public long getMaxTickLength() { 25 | return Long.MAX_VALUE; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "lotas", 4 | "version": "${mod_version}", 5 | "name": "LoTAS", 6 | "description": "Low optimization Tool-Assisted Speedrun Mod! A mod that allows players to create tool assisted speedruns/superplays in Minecraft.", 7 | "authors": [ 8 | "Pancake", 9 | "Scribble" 10 | ], 11 | "contact": { 12 | "homepage": "https://minecrafttas.com", 13 | "sources": "https://github.com/MinecraftTAS/LoTAS" 14 | }, 15 | "license": "GPLv3", 16 | "icon": "icon.png", 17 | "environment": "*", 18 | "accessWidener": "lotas.accesswidener", 19 | "entrypoints": { 20 | "main": [ 21 | "com.minecrafttas.lotas.LoTAS" 22 | ], 23 | "client": [ 24 | "com.minecrafttas.lotas.ClientLoTAS" 25 | ] 26 | }, 27 | "mixins": [ 28 | "lotas.mixin.json" 29 | ], 30 | "depends": { 31 | "fabricloader": ">=0.15.3", 32 | "minecraft": "1.16.1", 33 | "java": ">=8" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/tickratechanger/MixinItemRenderer.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.tickratechanger; 2 | 3 | import net.fabricmc.api.EnvType; 4 | import net.fabricmc.api.Environment; 5 | import net.minecraft.client.renderer.RenderStateShard; 6 | import org.spongepowered.asm.mixin.Mixin; 7 | import org.spongepowered.asm.mixin.injection.At; 8 | import org.spongepowered.asm.mixin.injection.Redirect; 9 | 10 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 11 | 12 | /** 13 | * This mixin slows down the Foil renderer to the tickrate 14 | * 15 | * @author Pancake 16 | */ 17 | @Mixin(RenderStateShard.class) 18 | @Environment(EnvType.CLIENT) 19 | public class MixinItemRenderer { 20 | 21 | /** 22 | * Slow down the getMillis 23 | * 24 | * @return Manipulated value 25 | */ 26 | @Redirect(method = "setupGlintTexturing", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J")) 27 | private static long modifyrenderEffect() { 28 | return TICKRATE_CHANGER.getMilliseconds(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/tickratechanger/MixinToastInstance.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.tickratechanger; 2 | 3 | import net.fabricmc.api.EnvType; 4 | import net.fabricmc.api.Environment; 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.injection.At; 7 | import org.spongepowered.asm.mixin.injection.Redirect; 8 | 9 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 10 | 11 | /** 12 | * This mixin slows down the toast in the top right to the tickrate 13 | * 14 | * @author Pancake 15 | */ 16 | @Mixin(targets = "net/minecraft/client/gui/components/toasts/ToastComponent$ToastInstance") 17 | @Environment(EnvType.CLIENT) 18 | public class MixinToastInstance { 19 | 20 | /** 21 | * Slow down toast timer 22 | * 23 | * @return Manipulated value 24 | */ 25 | @Redirect(method = "render(IILcom/mojang/blaze3d/vertex/PoseStack;)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J")) 26 | public long modifyAnimationTime() { 27 | return TICKRATE_CHANGER.getMilliseconds(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/resources/lotas.mixin.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "package": "com.minecrafttas.lotas.mixin", 4 | "compatibilityLevel": "JAVA_8", 5 | "mixins": [ 6 | "dragonmanipulation.MixinDragonHoldingPatternPhase", 7 | "dragonmanipulation.MixinDragonLandingApproachPhase", 8 | "dragonmanipulation.MixinDragonStrafePlayerPhase", 9 | "dragonmanipulation.MixinDragonTakeoffPhase", 10 | "events.HookMinecraftServer", 11 | "events.HookPlayNetworkHandler", 12 | "events.HookPlayerList", 13 | "tickratechanger.MixinDedicatedServer", 14 | "tickratechanger.MixinMinecraftServer" 15 | ], 16 | "client": [ 17 | "client.events.HookClientPlayNetworkHandler", 18 | "client.events.HookMinecraft", 19 | "client.events.HookOptions", 20 | "client.tickratechanger.MixinItemRenderer", 21 | "client.tickratechanger.MixinLevelRenderer", 22 | "client.tickratechanger.MixinSoundEngine", 23 | "client.tickratechanger.MixinSubtitleOverlay", 24 | "client.tickratechanger.MixinTimer", 25 | "client.tickratechanger.MixinToastInstance" 26 | ], 27 | "injectors": { 28 | "defaultRequire": 1 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/tickratechanger/MixinLevelRenderer.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.tickratechanger; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.injection.At; 5 | import org.spongepowered.asm.mixin.injection.ModifyVariable; 6 | 7 | import net.fabricmc.api.EnvType; 8 | import net.fabricmc.api.Environment; 9 | import net.minecraft.client.renderer.LevelRenderer; 10 | 11 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 12 | 13 | /** 14 | * This mixin slows down the world border renderer to the tickrate 15 | * 16 | * @author Pancake 17 | */ 18 | @Mixin(LevelRenderer.class) 19 | @Environment(EnvType.CLIENT) 20 | public class MixinLevelRenderer { 21 | 22 | /** 23 | * Slow down getMillis 24 | * 25 | * @param f Ignored original value 26 | * @return Manipulated value 27 | */ 28 | @ModifyVariable(method = "renderWorldBounds", at = @At(value = "STORE"), index = 19, ordinal = 3) 29 | public float injectf3(float f) { 30 | return TICKRATE_CHANGER.getMilliseconds() % 3000L / 3000.0F; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /.github/workflows/minecraft.yml: -------------------------------------------------------------------------------- 1 | name: Compile LoTAS 2 | 3 | on: 4 | push: 5 | branches: [ "dev" ] 6 | 7 | jobs: 8 | fabric: 9 | permissions: write-all 10 | runs-on: ubuntu-latest 11 | if: github.repository == 'MinecraftTAS/LoTAS' 12 | steps: 13 | - name: Check out repository 14 | uses: actions/checkout@v4 15 | - name: Set up JDK 21 16 | uses: actions/setup-java@v4 17 | with: 18 | java-version: '21' 19 | distribution: 'corretto' 20 | cache: gradle 21 | - name: Build with Gradle 22 | uses: gradle/gradle-build-action@v2 23 | with: 24 | arguments: remapJar --no-daemon 25 | gradle-version: 8.5 26 | cache-disabled: true 27 | - name: Upload Build Artifact 28 | uses: actions/upload-artifact@v4 29 | with: 30 | name: LoTAS 31 | path: build/libs/*.jar 32 | - name: Upload to discord 33 | uses: sinshutu/upload-to-discord@master 34 | env: 35 | DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} 36 | with: 37 | args: build/libs/*.jar 38 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/events/HookPlayNetworkHandler.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.events; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.injection.At; 5 | import org.spongepowered.asm.mixin.injection.Inject; 6 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 7 | 8 | import com.minecrafttas.lotas.system.ModSystem; 9 | 10 | import net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket; 11 | import net.minecraft.server.network.ServerGamePacketListenerImpl; 12 | 13 | /** 14 | * This mixin is purely responsible for the hooking up the events in {@link ModSystem}. 15 | * 16 | * @author Pancake 17 | */ 18 | @Mixin(ServerGamePacketListenerImpl.class) 19 | public class HookPlayNetworkHandler { 20 | 21 | /** 22 | * Trigger event in {@link ModSystem#onServerPayload(ServerboundCustomPayloadPacket)} when a custom payload packet is received. 23 | * 24 | * @param ci Callback Info 25 | */ 26 | @Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true) 27 | public void hookCustomPayloadEvent(ServerboundCustomPayloadPacket packet, CallbackInfo ci) { 28 | ModSystem.onServerPayload(packet); 29 | ci.cancel(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/events/HookPlayerList.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.events; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.injection.At; 5 | import org.spongepowered.asm.mixin.injection.Inject; 6 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 7 | 8 | import com.minecrafttas.lotas.system.ModSystem; 9 | 10 | import net.minecraft.network.Connection; 11 | import net.minecraft.server.level.ServerPlayer; 12 | import net.minecraft.server.players.PlayerList; 13 | 14 | /** 15 | * This mixin is purely responsible for the hooking up the events in {@link ModSystem}. 16 | * 17 | * @author Pancake 18 | */ 19 | @Mixin(PlayerList.class) 20 | public class HookPlayerList { 21 | 22 | /** 23 | * Trigger event in {@link ModSystem#onClientConnect(ServerPlayer)} when a player connects 24 | * 25 | * @param connection Connection to the client 26 | * @param serverPlayer Player associated with this connection 27 | * @param ci Callback Info 28 | */ 29 | @Inject(method = "placeNewPlayer", at = @At("RETURN")) 30 | public void hookConnectEvent(Connection connection, ServerPlayer serverPlayer, CallbackInfo ci) { 31 | ModSystem.onClientConnect(serverPlayer); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/events/HookClientPlayNetworkHandler.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.events; 2 | 3 | import com.minecrafttas.lotas.system.ModSystem; 4 | import net.fabricmc.api.EnvType; 5 | import net.fabricmc.api.Environment; 6 | import net.minecraft.client.multiplayer.ClientPacketListener; 7 | import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.injection.At; 10 | import org.spongepowered.asm.mixin.injection.Inject; 11 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 12 | 13 | /** 14 | * This mixin is purely responsible for the hooking up the events in {@link ModSystem}. 15 | * 16 | * @author Pancake 17 | */ 18 | @Mixin(ClientPacketListener.class) 19 | @Environment(EnvType.CLIENT) 20 | public class HookClientPlayNetworkHandler { 21 | 22 | /** 23 | * Trigger event in {@link ModSystem#onClientsidePayload(ClientboundCustomPayloadPacket)} )} when a custom payload packet is received 24 | * 25 | * @param ci Callback Info 26 | */ 27 | @Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true) 28 | public void hookCustomPayloadEvent(ClientboundCustomPayloadPacket packet, CallbackInfo ci) { 29 | ModSystem.onClientsidePayload(packet); 30 | ci.cancel(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/tickratechanger/MixinSoundEngine.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.tickratechanger; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.injection.At; 5 | import org.spongepowered.asm.mixin.injection.Inject; 6 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 7 | 8 | import net.fabricmc.api.EnvType; 9 | import net.fabricmc.api.Environment; 10 | import net.minecraft.client.resources.sounds.SoundInstance; 11 | import net.minecraft.client.sounds.SoundEngine; 12 | import net.minecraft.util.Mth; 13 | 14 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 15 | 16 | /** 17 | * This mixin adjusts the pitch of audio to the tickrate 18 | * 19 | * @author Pancake 20 | */ 21 | @Mixin(SoundEngine.class) 22 | @Environment(EnvType.CLIENT) 23 | public class MixinSoundEngine { 24 | 25 | /** 26 | * Calculate new pitch to play based on tickrate 27 | * 28 | * @param soundInstance Sound to play 29 | * @param ci Returnable 30 | */ 31 | @Inject(method = "calculatePitch", at = @At(value = "HEAD"), cancellable = true) 32 | public void redosetPitch(SoundInstance soundInstance, CallbackInfoReturnable ci) { 33 | ci.setReturnValue((float) (Mth.clamp(soundInstance.getPitch(), 0.5F, 2.0F) * TICKRATE_CHANGER.getGamespeed())); 34 | ci.cancel(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > [!CAUTION] 2 | > You are reading the README.md for **LoTAS 3!** You most likely want to read [this](https://github.com/MinecraftTAS/LoTAS/tree/latest) instead. 3 | > LoTAS 3 is currently in early development and not ready for use. 4 | 5 | # LoTAS 6 | LoTAS is a mod used for creating **L**ow **o**ptimization **T**ool **A**ssisted **S**peedruns in Minecraft. 7 | This mod contains a bunch of tools that can be used to manipulate the game in various ways, allowing for the creation of TASes. 8 | 9 | > [!NOTE] 10 | > TASes created with LoTAS cannot be played back, therefore you have to use a [recording software](https://obsproject.com/) to record and speed up your TAS. 11 | 12 | ## Tools 13 | The tools available in LoTAS 3 are currently very limited, but we are working on adding more tools in the future. 14 | - **Tickrate Changer**: Slow down the game to any speed. 15 | - **Tick Advance**: Pause and advance the game by individual ticks 16 | - **Savestates**: Revert the game to a previous state. 17 | - **Dragon Manipulation**: Manipulate the ender dragons flight path and phase. 18 | - **Dupe Mod**: Duplicate items according to the [dupe glitch](https://bugs.mojang.com/browse/MC-63), but without forcefully crashing your game. 19 | 20 | ## Bugs / Feature Requests 21 | Due to LoTAS not being actively maintained, we do not accept bug reports or feature requests. You are however free to create a pull request with your changes. 22 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/events/HookMinecraftServer.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.events; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.injection.At; 5 | import org.spongepowered.asm.mixin.injection.Inject; 6 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 7 | 8 | import com.minecrafttas.lotas.system.ModSystem; 9 | 10 | import net.minecraft.server.MinecraftServer; 11 | 12 | /** 13 | * This mixin is purely responsible for the hooking up the events in {@link ModSystem}. 14 | * 15 | * @author Pancake 16 | */ 17 | @Mixin(MinecraftServer.class) 18 | public class HookMinecraftServer { 19 | 20 | /** 21 | * Trigger event in {@link ModSystem#onServerTick()} after the server has ticked 22 | * 23 | * @param ci Callback Info 24 | */ 25 | @Inject(method = "runServer", at = @At(value = "INVOKE", shift = At.Shift.AFTER, target = "Lnet/minecraft/util/profiling/ProfilerFiller;pop()V")) 26 | public void hookTickEvent(CallbackInfo ci) { 27 | ModSystem.onServerTick(); 28 | } 29 | 30 | /** 31 | * Trigger event in {@link ModSystem#onServerLoad(MinecraftServer)} before the server enters the tick loop 32 | * 33 | * @param ci Callback Info 34 | */ 35 | @Inject(method = "", at = @At("RETURN")) 36 | public void hookInitEvent(CallbackInfo ci) { 37 | ModSystem.onServerLoad((MinecraftServer) (Object) this); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/tickratechanger/MixinTimer.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.tickratechanger; 2 | 3 | import net.fabricmc.api.EnvType; 4 | import net.fabricmc.api.Environment; 5 | import net.minecraft.client.Timer; 6 | import org.spongepowered.asm.mixin.Final; 7 | import org.spongepowered.asm.mixin.Mixin; 8 | import org.spongepowered.asm.mixin.Mutable; 9 | import org.spongepowered.asm.mixin.Shadow; 10 | import org.spongepowered.asm.mixin.injection.At; 11 | import org.spongepowered.asm.mixin.injection.Inject; 12 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 13 | 14 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 15 | import static com.minecrafttas.lotas.LoTAS.TICK_ADVANCE; 16 | 17 | /** 18 | * This mixin slows down the integrated Timer making the game run slower 19 | * 20 | * @author Pancake 21 | */ 22 | @Mixin(Timer.class) 23 | @Environment(EnvType.CLIENT) 24 | public class MixinTimer { 25 | 26 | @Shadow @Final @Mutable 27 | private float msPerTick; 28 | 29 | /** 30 | * Slow down the timer 31 | * 32 | * @param cir Returnable 33 | */ 34 | @Inject(method = "advanceTime", at = @At("HEAD")) 35 | public void onAdvanceTime(CallbackInfoReturnable cir) { 36 | this.msPerTick = (float) (TICK_ADVANCE.isTickadvance() && !TICK_ADVANCE.shouldTickClient ? Float.MAX_VALUE : TICKRATE_CHANGER.getMsPerTick()); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/events/HookOptions.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.events; 2 | 3 | import com.minecrafttas.lotas.system.KeybindSystem; 4 | import net.fabricmc.api.EnvType; 5 | import net.fabricmc.api.Environment; 6 | import net.minecraft.client.KeyMapping; 7 | import net.minecraft.client.Options; 8 | import org.spongepowered.asm.mixin.Final; 9 | import org.spongepowered.asm.mixin.Mixin; 10 | import org.spongepowered.asm.mixin.Mutable; 11 | import org.spongepowered.asm.mixin.Shadow; 12 | import org.spongepowered.asm.mixin.injection.At; 13 | import org.spongepowered.asm.mixin.injection.Inject; 14 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 15 | 16 | /** 17 | * This mixin is purely responsible for the hooking up the events in {@link KeybindSystem}. 18 | * 19 | * @author Pancake 20 | */ 21 | @Mixin(Options.class) 22 | @Environment(EnvType.CLIENT) 23 | public class HookOptions { 24 | 25 | /** List of Key Mappings that are being registered once loaded */ 26 | @Mutable @Final @Shadow 27 | public KeyMapping[] keyMappings; 28 | 29 | /** 30 | * Trigger event in {@link KeybindSystem#onKeybindInitialize(KeyMapping[])} before keybinds are initialized and replace them with a custom array. 31 | * @param ci Callback Info 32 | */ 33 | @Inject(method = "load", at = @At("HEAD")) 34 | public void hookLoadEvent(CallbackInfo ci) { 35 | this.keyMappings = KeybindSystem.onKeybindInitialize(this.keyMappings); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/LoTAS.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas; 2 | 3 | import com.minecrafttas.lotas.mods.*; 4 | import com.minecrafttas.lotas.system.ConfigurationSystem; 5 | import com.minecrafttas.lotas.system.ModSystem; 6 | import net.fabricmc.api.ModInitializer; 7 | import org.apache.logging.log4j.LogManager; 8 | import org.apache.logging.log4j.Logger; 9 | 10 | import java.io.File; 11 | 12 | /** 13 | * LoTAS fabric mod core. 14 | * 15 | * @author Pancake 16 | */ 17 | public class LoTAS implements ModInitializer { 18 | 19 | /** Logger instance */ 20 | public static final Logger LOGGER = LogManager.getLogger("lotas"); 21 | 22 | /** Dupe mod instance */ 23 | public static final DupeMod DUPE_MOD = new DupeMod(); 24 | /** Tick advance mod instance */ 25 | public static final TickAdvance TICK_ADVANCE = new TickAdvance(); 26 | /** Tickrate changer mod instance */ 27 | public static final TickrateChanger TICKRATE_CHANGER = new TickrateChanger(); 28 | /** Dragon manipulation mod instance */ 29 | public static final DragonManipulation DRAGON_MANIPULATION = new DragonManipulation(); 30 | /** Savestate mod instance */ 31 | public static final SavestateMod SAVESTATE_MOD = new SavestateMod(); 32 | 33 | static { 34 | ModSystem.registerMods(DUPE_MOD, TICK_ADVANCE, TICKRATE_CHANGER, DRAGON_MANIPULATION, SAVESTATE_MOD); 35 | } 36 | 37 | @Override 38 | public void onInitialize() { 39 | ConfigurationSystem.load(new File("lotas_dev.properties")); 40 | ModSystem.onInitialize(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/tickratechanger/MixinSubtitleOverlay.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.tickratechanger; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.injection.Constant; 5 | import org.spongepowered.asm.mixin.injection.ModifyConstant; 6 | 7 | import net.fabricmc.api.EnvType; 8 | import net.fabricmc.api.Environment; 9 | import net.minecraft.client.gui.components.SubtitleOverlay; 10 | 11 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 12 | 13 | /** 14 | * This mixin slows down the subtitle overlay to the tickrate 15 | * 16 | * @author Scribble 17 | */ 18 | @Mixin(SubtitleOverlay.class) 19 | @Environment(EnvType.CLIENT) 20 | public class MixinSubtitleOverlay { 21 | 22 | /** 23 | * Slow down animation speed by multiplying with the gamespeed 24 | * 25 | * @param threethousand 3000, well 26 | * @return Slowed down 3000 27 | */ 28 | @ModifyConstant(method = "render", constant = @Constant(longValue = 3000L)) 29 | public long applyTickrate(long threethousand) { 30 | return (long) (threethousand * (20.0 / TICKRATE_CHANGER.getTickrate())); 31 | } 32 | 33 | /** 34 | * Slow down animation speed by multiplying with the gamespeed 35 | * 36 | * @param threethousand 3000, well 37 | * @return Slowed down 3000 38 | */ 39 | @ModifyConstant(method = "render", constant = @Constant(floatValue = 3000F)) 40 | public float applyTickrate2(float threethousand) { 41 | return (float) (threethousand * (20.0 / TICKRATE_CHANGER.getTickrate())); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/dragonmanipulation/MixinDragonTakeoffPhase.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.dragonmanipulation; 2 | 3 | import java.util.Random; 4 | 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.injection.At; 7 | import org.spongepowered.asm.mixin.injection.ModifyArgs; 8 | import org.spongepowered.asm.mixin.injection.Redirect; 9 | 10 | import com.minecrafttas.lotas.mods.DragonManipulation.Phase; 11 | 12 | import net.minecraft.world.entity.boss.enderdragon.EnderDragon; 13 | import net.minecraft.world.entity.boss.enderdragon.phases.AbstractDragonPhaseInstance; 14 | import net.minecraft.world.entity.boss.enderdragon.phases.DragonTakeoffPhase; 15 | import org.spongepowered.asm.mixin.injection.invoke.arg.Args; 16 | 17 | import static com.minecrafttas.lotas.LoTAS.DRAGON_MANIPULATION; 18 | 19 | /** 20 | * This mixin manipulates the rng of the dragon takeoff phase 21 | * 22 | * @author Pancake 23 | */ 24 | @Mixin(DragonTakeoffPhase.class) 25 | public abstract class MixinDragonTakeoffPhase extends AbstractDragonPhaseInstance { 26 | public MixinDragonTakeoffPhase(EnderDragon enderDragon) { super(enderDragon); } 27 | 28 | /** 29 | * Force optimal dragon path by (step 1) removing the 20 block addend 30 | * 31 | * @param r Random source 32 | * @return Multiplier 33 | */ 34 | @Redirect(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextFloat()F")) 35 | public float redirect_nextFloat(Random r) { 36 | return DRAGON_MANIPULATION.getPhase() == Phase.OFF ? r.nextFloat() : 0.0f; 37 | } 38 | 39 | /** 40 | * Force optimal dragon path by (step 2) calculating the optimal block addend depending on the dragons position 41 | * 42 | * @param args Arguments 43 | */ 44 | @ModifyArgs(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/phys/Vec3;(DDD)V")) 45 | public void navigate_nodeInit(Args args) { 46 | if (DRAGON_MANIPULATION.getPhase() == Phase.OFF) 47 | return; 48 | 49 | double distance = Math.max(0, Math.min(20, dragon.position().y - (double) args.get(1))); 50 | args.set(1, (double) args.get(1) + distance); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/dragonmanipulation/MixinDragonStrafePlayerPhase.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.dragonmanipulation; 2 | 3 | import java.util.Random; 4 | 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.injection.At; 7 | import org.spongepowered.asm.mixin.injection.ModifyArgs; 8 | import org.spongepowered.asm.mixin.injection.Redirect; 9 | 10 | import com.minecrafttas.lotas.mods.DragonManipulation.Phase; 11 | 12 | import net.minecraft.world.entity.boss.enderdragon.EnderDragon; 13 | import net.minecraft.world.entity.boss.enderdragon.phases.AbstractDragonPhaseInstance; 14 | import net.minecraft.world.entity.boss.enderdragon.phases.DragonStrafePlayerPhase; 15 | import org.spongepowered.asm.mixin.injection.invoke.arg.Args; 16 | 17 | import static com.minecrafttas.lotas.LoTAS.DRAGON_MANIPULATION; 18 | 19 | /** 20 | * This mixin manipulates the rng of the dragon strafe player phase 21 | * 22 | * @author Pancake 23 | */ 24 | @Mixin(DragonStrafePlayerPhase.class) 25 | public abstract class MixinDragonStrafePlayerPhase extends AbstractDragonPhaseInstance { 26 | public MixinDragonStrafePlayerPhase(EnderDragon enderDragon) { super(enderDragon); } 27 | 28 | /** 29 | * Force optimal dragon path by (step 1) removing the 20 block addend 30 | * 31 | * @param r Random source 32 | * @return Multiplier 33 | */ 34 | @Redirect(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextFloat()F")) 35 | public float redirect_nextFloat(Random r) { 36 | return DRAGON_MANIPULATION.getPhase() == Phase.OFF ? r.nextFloat() : 0.0f; 37 | } 38 | 39 | /** 40 | * Force optimal dragon path by (step 2) calculating the optimal block addend depending on the dragons position 41 | * 42 | * @param args Arguments 43 | */ 44 | @ModifyArgs(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/phys/Vec3;(DDD)V")) 45 | public void navigate_nodeInit(Args args) { 46 | if (DRAGON_MANIPULATION.getPhase() == Phase.OFF) 47 | return; 48 | 49 | double distance = Math.max(0, Math.min(20, dragon.position().y - (double) args.get(1))); 50 | args.set(1, (double) args.get(1) + distance); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/dragonmanipulation/MixinDragonLandingApproachPhase.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.dragonmanipulation; 2 | 3 | import java.util.Random; 4 | 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.injection.At; 7 | import org.spongepowered.asm.mixin.injection.ModifyArgs; 8 | import org.spongepowered.asm.mixin.injection.Redirect; 9 | 10 | import com.minecrafttas.lotas.mods.DragonManipulation.Phase; 11 | 12 | import net.minecraft.world.entity.boss.enderdragon.EnderDragon; 13 | import net.minecraft.world.entity.boss.enderdragon.phases.AbstractDragonPhaseInstance; 14 | import net.minecraft.world.entity.boss.enderdragon.phases.DragonLandingApproachPhase; 15 | import org.spongepowered.asm.mixin.injection.invoke.arg.Args; 16 | 17 | import static com.minecrafttas.lotas.LoTAS.DRAGON_MANIPULATION; 18 | 19 | /** 20 | * This mixin manipulates the rng of the dragon landing approach phase 21 | * 22 | * @author Pancake 23 | */ 24 | @Mixin(DragonLandingApproachPhase.class) 25 | public abstract class MixinDragonLandingApproachPhase extends AbstractDragonPhaseInstance { 26 | public MixinDragonLandingApproachPhase(EnderDragon enderDragon) { super(enderDragon); } 27 | 28 | /** 29 | * Force optimal dragon path by (step 1) removing the 20 block addend 30 | * 31 | * @param r Random source 32 | * @return Multiplier 33 | */ 34 | @Redirect(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextFloat()F")) 35 | public float redirect_nextFloat(Random r) { 36 | return DRAGON_MANIPULATION.getPhase() == Phase.OFF ? r.nextFloat() : 0.0f; 37 | } 38 | 39 | /** 40 | * Force optimal dragon path by (step 2) calculating the optimal block addend depending on the dragons position 41 | * 42 | * @param args Arguments 43 | */ 44 | @ModifyArgs(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/phys/Vec3;(DDD)V")) 45 | public void navigate_nodeInit(Args args) { 46 | if (DRAGON_MANIPULATION.getPhase() == Phase.OFF) 47 | return; 48 | 49 | double distance = Math.max(0, Math.min(20, dragon.position().y - (double) args.get(1))); 50 | args.set(1, (double) args.get(1) + distance); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/client/events/HookMinecraft.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.client.events; 2 | 3 | import com.minecrafttas.lotas.system.KeybindSystem; 4 | import com.minecrafttas.lotas.system.ModSystem; 5 | import net.fabricmc.api.EnvType; 6 | import net.fabricmc.api.Environment; 7 | import net.minecraft.client.Minecraft; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.injection.At; 10 | import org.spongepowered.asm.mixin.injection.At.Shift; 11 | import org.spongepowered.asm.mixin.injection.Inject; 12 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 13 | 14 | /** 15 | * This mixin is purely responsible for the hooking up the events in {@link ModSystem}. 16 | * 17 | * @author Pancake 18 | */ 19 | @Mixin(Minecraft.class) 20 | @Environment(EnvType.CLIENT) 21 | public class HookMinecraft { 22 | 23 | /** 24 | * Trigger event in {@link ModSystem#onClientsideRenderInitialize(Minecraft)} before the game enters the game loop. 25 | * 26 | * @param ci Callback Info 27 | */ 28 | @Inject(method = "run", at = @At("HEAD")) 29 | public void hookGameInitEvent(CallbackInfo ci) { 30 | ModSystem.onClientsideRenderInitialize((Minecraft) (Object) this); 31 | } 32 | 33 | /** 34 | * Trigger event in {@link ModSystem#onClientsideShutdown()} before the JVM shuts down. 35 | * 36 | * @param ci Callback Info 37 | */ 38 | @Inject(method = "close", at = @At("RETURN")) 39 | public void hookGameCloseEvent(CallbackInfo ci) { 40 | ModSystem.onClientsideShutdown(); 41 | } 42 | 43 | /** 44 | * Trigger event in {@link ModSystem#onClientsideTick()} every tick. 45 | * 46 | * @param ci Callback Info 47 | */ 48 | @Inject(method = "tick", at = @At("HEAD")) 49 | public void hookTickEvent(CallbackInfo ci) { 50 | ModSystem.onClientsideTick(); 51 | } 52 | 53 | /** 54 | * Trigger event in {@link ModSystem#onClientsideGameLoop()} every game logic loop and updates the keybind system in {@link KeybindSystem#onGameLoop(Minecraft)} 55 | * 56 | * @param ci Callback Info 57 | */ 58 | @Inject(method = "runTick", at = @At("HEAD")) 59 | public void hookGameLoopEvent(CallbackInfo ci) { 60 | ModSystem.onClientsideGameLoop(); 61 | KeybindSystem.onGameLoop((Minecraft) (Object) this); 62 | } 63 | 64 | /** 65 | * Trigger event in {@link ModSystem#onClientsideDisconnect()} when a player disconnects 66 | * 67 | * @param ci Callback Info 68 | */ 69 | @Inject(method = "clearLevel(Lnet/minecraft/client/gui/screens/Screen;)V", at = @At("HEAD")) 70 | public void hookDisconnectEvent(CallbackInfo ci) { 71 | ModSystem.onClientsideDisconnect(); 72 | } 73 | 74 | /** 75 | * Trigger event in {@link ModSystem#onClientsidePostRender()} after the game has rendered the frame 76 | * 77 | * @param ci Callback Info 78 | */ 79 | @Inject(method = "runTick", at = @At(value = "INVOKE", shift = Shift.AFTER, target = "Lnet/minecraft/client/gui/components/toasts/ToastComponent;render(Lcom/mojang/blaze3d/vertex/PoseStack;)V")) 80 | public void hookPostRenderEvent(CallbackInfo ci) { 81 | ModSystem.onClientsidePostRender(); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mods/savestatemod/StateData.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mods.savestatemod; 2 | 3 | import lombok.Data; 4 | import lombok.Getter; 5 | import net.fabricmc.api.EnvType; 6 | import net.fabricmc.api.Environment; 7 | import net.minecraft.server.MinecraftServer; 8 | import org.apache.commons.lang3.ArrayUtils; 9 | import org.apache.commons.lang3.SerializationUtils; 10 | 11 | import java.io.File; 12 | import java.io.IOException; 13 | import java.io.Serializable; 14 | import java.nio.file.Files; 15 | import java.nio.file.StandardOpenOption; 16 | 17 | import static com.minecrafttas.lotas.LoTAS.LOGGER; 18 | 19 | /** 20 | * This class represents the state data of a world. 21 | * 22 | * @author Pancake 23 | */ 24 | @Getter 25 | public class StateData { 26 | 27 | /** Location of the world */ 28 | private File worldDir; 29 | 30 | /** Location of the savestates folder */ 31 | private File worldSavestateDir; 32 | 33 | /** Location of the states.dat file */ 34 | private File worldStatesFile; 35 | 36 | /** List of all savestates mirrored between client and server */ 37 | private State[] states = {}; 38 | 39 | /** 40 | * Initialize state data 41 | * 42 | * @param mcserver Minecraft server instance 43 | */ 44 | public void onServerInitialize(MinecraftServer mcserver) { 45 | this.worldDir = mcserver.getWorldPath(net.minecraft.world.level.storage.LevelResource.ROOT).toFile().getParentFile(); 46 | this.worldSavestateDir = new File(this.worldDir.getParentFile(), this.worldDir.getName() + " Savestates"); 47 | this.worldStatesFile = new File(this.worldSavestateDir, "states.dat"); 48 | } 49 | 50 | /** 51 | * Load states data of world 52 | * 53 | * @throws IOException If an exception occurs while loading 54 | */ 55 | public void loadData() throws IOException { 56 | this.states = new State[0]; 57 | if (!this.worldStatesFile.exists()) 58 | return; 59 | 60 | this.deserializeData(Files.readAllBytes(this.worldStatesFile.toPath())); 61 | 62 | // verify that no states are missing 63 | for (State state : this.states) 64 | if (!new File(this.worldSavestateDir, state.getIndex() + "").exists()) 65 | LOGGER.error("Savestate " + state.getIndex() + " was not found in " + this.worldSavestateDir.getAbsolutePath() + "!"); 66 | } 67 | 68 | /** 69 | * Save state data of world 70 | * 71 | * @throws IOException If an exception occurs while saving 72 | */ 73 | public void saveData() throws IOException { 74 | if (!this.worldSavestateDir.exists()) 75 | this.worldSavestateDir.mkdirs(); 76 | 77 | Files.write(this.worldStatesFile.toPath(), SerializationUtils.serialize(this.states), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); 78 | } 79 | 80 | /** 81 | * Deserialize state data from byte array 82 | * 83 | * @param data Serialized Data 84 | */ 85 | public void deserializeData(byte[] data) { 86 | this.states = SerializationUtils.deserialize(data); 87 | } 88 | 89 | /** 90 | * Clear state data 91 | * (Clientside only) 92 | */ 93 | @Environment(EnvType.CLIENT) 94 | public void clearStates() { 95 | this.states = new State[0]; 96 | } 97 | 98 | /** 99 | * Add state to list of states 100 | * 101 | * @param state State 102 | */ 103 | public void addState(State state) { 104 | this.states = ArrayUtils.add(this.states, state); 105 | } 106 | 107 | /** 108 | * Verify state exists 109 | * 110 | * @param i Index 111 | * @return Is state valid 112 | */ 113 | public boolean isValid(int i) { 114 | if (i >= this.states.length) 115 | return false; 116 | 117 | return new File(this.worldSavestateDir, this.states[i].getIndex() + "").exists(); 118 | } 119 | 120 | /** 121 | * Remove state from list of states 122 | * 123 | * @param i Index 124 | */ 125 | public void removeState(int i) { 126 | this.states = ArrayUtils.remove(this.states, i); 127 | } 128 | 129 | /** 130 | * This class represents a state 131 | * 132 | * @author Pancake 133 | */ 134 | @Data 135 | public static class State implements Serializable { 136 | /** Name of the state */ 137 | private final String name; 138 | /** Timestamp */ 139 | private final long timestamp; 140 | /** Index */ 141 | private final int index; 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mods/DragonManipulation.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Here is the logic of the dragon manipulation mod: 3 | * 4 | * The enderdragon has a net of notes which are chained to build a path that the ender dragon follows. Two nodes are placed fairly high up while the others are just above the ground. 5 | * After finishing a path of 4 nodes (or in the inital perch 1) the dragon can switch phases. Additionally the nodes have a random height increase of up to 20 blocks where the dragon will fly to. 6 | * To make the ender dragon optimal we need to skip the high nodes and have the height bonus equal the height of the ender dragon rn. Then we can force a phase switch with rng manipulation. Additionally we can modify the path 7 | * to go into the direction the ender dragon is already facing. 8 | * 9 | * Once the dragon manipulation is enabled, "phase" will be set to something other than null and the dragon will be fully optimized. 10 | * 11 | * As noted by the @Environment annotations in front of methods, this code works on both client and server. 12 | * 13 | * Every time the clients wants to change the manipulation phase it sends a request update packet to the server. #requestPhaseChange 14 | * The server proceeds sending a update packet to the clients causing them to process the packet on their own. The server processes the packet too. #onServerPayload 15 | * The clients listener finally updates the phase locally. #onClientPayload 16 | */ 17 | package com.minecrafttas.lotas.mods; 18 | 19 | import com.minecrafttas.lotas.system.ModSystem.Mod; 20 | import io.netty.buffer.Unpooled; 21 | import lombok.Getter; 22 | import net.fabricmc.api.EnvType; 23 | import net.fabricmc.api.Environment; 24 | import net.minecraft.network.FriendlyByteBuf; 25 | import net.minecraft.resources.ResourceLocation; 26 | import net.minecraft.server.level.ServerPlayer; 27 | 28 | /** 29 | * Dragon manipulation mod 30 | * 31 | * @author Pancake 32 | */ 33 | @Getter 34 | public class DragonManipulation extends Mod { 35 | public DragonManipulation() { 36 | super(new ResourceLocation("lotas", "dragonmanipulation")); 37 | } 38 | 39 | /** Current manipulation phase or OFF */ 40 | private Phase phase = Phase.OFF; 41 | 42 | /** 43 | * Request phase change by sending a packet to the server 44 | * (Clientside only) 45 | * 46 | * @param phase New phase or null 47 | */ 48 | @Environment(EnvType.CLIENT) 49 | public void requestPhaseChange(Phase phase) { 50 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 51 | buf.writeInt(phase.ordinal()); 52 | this.sendPacketToServer(buf); 53 | } 54 | 55 | /** 56 | * Update phase on server and send packet to clients when receiving packet 57 | * 58 | * @param buf Packet 59 | */ 60 | @Override 61 | protected void onServerPayload(FriendlyByteBuf buf) { 62 | this.phase = Phase.values()[buf.readInt()]; 63 | 64 | // send packet to client 65 | for (ServerPlayer player : this.mcserver.getPlayerList().getPlayers()) { 66 | FriendlyByteBuf data = new FriendlyByteBuf(Unpooled.buffer()); 67 | data.writeInt(this.phase.ordinal()); 68 | this.sendPacketToClient(player, data); 69 | } 70 | } 71 | 72 | /** 73 | * Update mirrored phase on packet receive 74 | * 75 | * @param buf Packet 76 | */ 77 | @Override 78 | @Environment(EnvType.CLIENT) 79 | protected void onClientsidePayload(FriendlyByteBuf buf) { 80 | this.phase = Phase.values()[buf.readInt()]; 81 | } 82 | 83 | public enum Phase { 84 | OFF, LANDINGAPPROACH, STRAFING, HOLDINGPATTERN 85 | } 86 | 87 | } 88 | 89 | /* 90 | * Let me write down how the ender dragon ai works for future reference. 91 | * 92 | * The dragon has a set of 24 nodes placed in determinated spots at a height depending on the terrain. Two nodes are generated higher then all others. 93 | * The dragon then creates a path through these nodes with a somewhat deteministic path. The beginning of the path is where the dragon is at. 94 | * The length of the path is the shortest possible (shortest possible through minecrafts algorithm, 4 max it seems) and the end of the path is different depending on the orientation and phase of the dragon. 95 | * The path is also different if there are 0 end crystals remaining. The only actual RNG in the path is the end node, during the holding pattern phase. After finishing the previous path, 96 | * the dragon has a 1/8 chance to switch rotation, which then changes the last node of the path. 97 | * 98 | * Therefore EnderDragon#findPath takes the start node, end node and optionally a custom end node, being around the player during strafing phase. 99 | * 100 | * Now that the path is clear (no pun intended), lets look at the phases of the dragon. 101 | * At the end of every one of the holding pattern phase, the dragon does some math together with some randomness to decide which phase it goes to next... and that's it 102 | */ 103 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mods/TickAdvance.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mods; 2 | 3 | import com.minecrafttas.lotas.system.ConfigurationSystem; 4 | import com.minecrafttas.lotas.system.ModSystem.Mod; 5 | 6 | import io.netty.buffer.Unpooled; 7 | import lombok.Getter; 8 | import net.fabricmc.api.EnvType; 9 | import net.fabricmc.api.Environment; 10 | import net.minecraft.network.FriendlyByteBuf; 11 | import net.minecraft.resources.ResourceLocation; 12 | import net.minecraft.server.level.ServerPlayer; 13 | 14 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 15 | 16 | /** 17 | * Tick advance mod 18 | * ~ same logic as tickrate changer 19 | * 20 | * @author Pancake 21 | */ 22 | public class TickAdvance extends Mod { 23 | public TickAdvance() { 24 | super(new ResourceLocation("lotas", "tickadvance")); 25 | } 26 | 27 | /** Should tick advance when a player joins the server */ 28 | private boolean freezeOnJoin; 29 | 30 | /** Is tick advance enabled */ 31 | @Getter 32 | private boolean tickadvance; 33 | 34 | /** Should tick advance clientside */ 35 | @Environment(EnvType.CLIENT) 36 | public boolean shouldTickClient; 37 | 38 | /** Should tick advance serverside */ 39 | public boolean shouldTickServer; 40 | 41 | /** 42 | * Initializes tick advance mod 43 | */ 44 | @Override 45 | protected void onInitialize() { 46 | this.freezeOnJoin = ConfigurationSystem.getBoolean("tickadvance_freezeonjoin", false); 47 | } 48 | 49 | /** 50 | * Request tick advance toggle by sending packet to server 51 | * (Clientside only) 52 | */ 53 | @Environment(EnvType.CLIENT) 54 | public void requestTickadvanceToggle() { 55 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 56 | buf.writeInt(0); // status update 57 | buf.writeBoolean(!this.tickadvance); // new status 58 | this.sendPacketToServer(buf); 59 | } 60 | 61 | /** 62 | * Request tick advance by sending packet to server 63 | * (Clientside only) 64 | */ 65 | @Environment(EnvType.CLIENT) 66 | public void requestTickadvance() { 67 | if (!this.tickadvance || this.shouldTickClient) 68 | return; 69 | 70 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 71 | buf.writeInt(1); // tick update 72 | this.sendPacketToServer(buf); 73 | } 74 | 75 | /** 76 | * Update server tickadvance status and resend packet when receiving a request 77 | * 78 | * @param buf Packet 79 | */ 80 | @Override 81 | protected void onServerPayload(FriendlyByteBuf buf) { 82 | if (buf.readInt() == 0) 83 | this.updateTickadvanceStatus(buf.readBoolean()); 84 | else 85 | this.updateTickadvance(); 86 | } 87 | 88 | /** 89 | * Update server tickadvance status and update clients 90 | * (Serverside only) 91 | * 92 | * @param tickadvance Tickadvance status 93 | */ 94 | public void updateTickadvanceStatus(boolean tickadvance) { 95 | this.tickadvance = tickadvance; 96 | 97 | // update tick advance for all clients 98 | this.mcserver.getPlayerList().getPlayers().forEach(player -> { 99 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 100 | buf.writeInt(0); // status update 101 | buf.writeBoolean(tickadvance); // new status 102 | this.sendPacketToClient(player, buf); 103 | }); 104 | } 105 | 106 | /** 107 | * Advance server tick and update clients 108 | * (Serverside only) 109 | */ 110 | public void updateTickadvance() { 111 | this.shouldTickServer = true; 112 | 113 | // tick all clients 114 | this.mcserver.getPlayerList().getPlayers().forEach(player -> { 115 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 116 | buf.writeInt(1); // tick update 117 | this.sendPacketToClient(player, buf); 118 | }); 119 | } 120 | 121 | /** 122 | * Update client tickadvance status when receiving packet 123 | * 124 | * @param buf Packet 125 | */ 126 | @Override 127 | @Environment(EnvType.CLIENT) 128 | protected void onClientsidePayload(FriendlyByteBuf buf) { 129 | if (buf.readInt() == 0) { // toggle tickadvance 130 | this.tickadvance = buf.readBoolean(); 131 | 132 | TICKRATE_CHANGER.updateGameTime(TICKRATE_CHANGER.getGamespeed()); 133 | } else { 134 | this.shouldTickClient = true; // tick client 135 | } 136 | } 137 | 138 | /** 139 | * Reset tick advance state after tick passed 140 | */ 141 | @Environment(EnvType.CLIENT) 142 | @Override 143 | protected void onClientsideTick() { 144 | this.shouldTickClient = false; 145 | TICKRATE_CHANGER.advanceGameTime(50L); 146 | } 147 | 148 | /** 149 | * Reset tick advance on disconnect clientside 150 | */ 151 | @Override 152 | @Environment(EnvType.CLIENT) 153 | protected void onClientsideDisconnect() { 154 | this.tickadvance = false; 155 | } 156 | 157 | /** 158 | * Update client tick advance status on connect 159 | * 160 | * @param player Player 161 | */ 162 | @Override 163 | protected void onClientConnect(ServerPlayer player) { 164 | // freeze client if enabled in config 165 | if (this.freezeOnJoin && !this.tickadvance) 166 | this.updateTickadvanceStatus(true); 167 | 168 | // update tick advance status 169 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 170 | buf.writeInt(0); // status update 171 | buf.writeBoolean(this.tickadvance); // new status 172 | this.sendPacketToClient(player, buf); 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mods/DupeMod.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Here is the logic of the dupe mod: 3 | * 4 | * As noted by the @Environment annotations in front of methods, this code works on both client and server. 5 | * 6 | * Every time the clients wants to load or save playerdata it sends a request playerdata update packet to the server. #requestDupe 7 | * The server proceeds sending a update packet to the clients causing them to process the packet on their own. The server processes the packet too. #onServerPacket 8 | * The clients listener finally saves or loads the playerdata. #onClientPayload 9 | */ 10 | package com.minecrafttas.lotas.mods; 11 | 12 | import com.minecrafttas.lotas.system.ModSystem.Mod; 13 | import io.netty.buffer.Unpooled; 14 | import net.fabricmc.api.EnvType; 15 | import net.fabricmc.api.Environment; 16 | import net.minecraft.nbt.CompoundTag; 17 | import net.minecraft.network.FriendlyByteBuf; 18 | import net.minecraft.resources.ResourceLocation; 19 | import net.minecraft.server.level.ServerPlayer; 20 | import net.minecraft.world.level.GameType; 21 | import net.minecraft.world.phys.Vec3; 22 | 23 | import java.util.HashMap; 24 | import java.util.List; 25 | 26 | import static com.minecrafttas.lotas.LoTAS.LOGGER; 27 | 28 | /** 29 | * Dupe mod 30 | * 31 | * @author Pancake 32 | */ 33 | public class DupeMod extends Mod { 34 | public DupeMod() { 35 | super(new ResourceLocation("lotas", "dupemod")); 36 | } 37 | 38 | /** Copy of the clients local players playerdata */ 39 | @Environment(EnvType.CLIENT) 40 | private CompoundTag localPlayer; 41 | 42 | /** Copy of all serverside players */ 43 | private final HashMap onlineClients = new HashMap<>(); 44 | 45 | /** 46 | * Request dupe by sending a packet to the server 47 | * (Clientside only) 48 | * 49 | * @param saveOLoad Whether player data should be loaded or saved 50 | */ 51 | @Environment(EnvType.CLIENT) 52 | public void requestDupe(boolean saveOLoad) { 53 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 54 | buf.writeBoolean(saveOLoad); 55 | this.sendPacketToServer(buf); 56 | } 57 | 58 | /** 59 | * Trigger dupe and resend packet to all clients when receiving packet 60 | * 61 | * @param buf Packet 62 | */ 63 | @Override 64 | protected void onServerPayload(FriendlyByteBuf buf) { 65 | boolean saveOLoad = buf.readBoolean(); 66 | List players = this.mcserver.getPlayerList().getPlayers(); 67 | if (saveOLoad) { 68 | // save all client data in the hash map 69 | this.onlineClients.clear(); 70 | for (ServerPlayer player : players) { 71 | // save playerdata 72 | CompoundTag tag = new CompoundTag(); 73 | player.saveWithoutId(tag); 74 | this.onlineClients.put(player, tag); 75 | 76 | // send packet to client 77 | FriendlyByteBuf data = new FriendlyByteBuf(Unpooled.buffer()); 78 | data.writeBoolean(true); 79 | data.writeInt(tag.getInt("playerGameType")); 80 | this.sendPacketToClient(player, data); 81 | } 82 | } else 83 | // load all client data from the hash map 84 | for (ServerPlayer player : players) { 85 | CompoundTag tag = this.onlineClients.get(player); 86 | if (tag == null) { 87 | LOGGER.warn("No playerdata stored for {}.", player.getName().getString()); 88 | continue; 89 | } 90 | 91 | if (!tag.getString("Dimension").equals(player.getLevel().dimension().location().toString())) { 92 | LOGGER.warn("Unable to load playerdata for {} as they are in a different dimension!", player.getName().getString()); 93 | continue; 94 | } 95 | 96 | if (!player.isAlive()) { // instead of reviving the player just don't load playerdata - this will be multiplayer safe 97 | LOGGER.warn("Unable to load playerdata for {} as they are not alive.", player.getName().getString()); 98 | continue; 99 | } 100 | 101 | // load playerdata 102 | player.load(tag); 103 | Vec3 pos = player.position(); 104 | player.teleportTo(pos.x(), pos.y(), pos.z()); 105 | 106 | // send packet to client 107 | FriendlyByteBuf data = new FriendlyByteBuf(Unpooled.buffer()); 108 | data.writeBoolean(false); 109 | this.sendPacketToClient(player, data); 110 | } 111 | } 112 | 113 | /** 114 | * Save or load when receiving packet 115 | * 116 | * @param buf Packet 117 | */ 118 | @Override 119 | @Environment(EnvType.CLIENT) 120 | protected void onClientsidePayload(FriendlyByteBuf buf) { 121 | boolean saveOLoad = buf.readBoolean(); 122 | if (saveOLoad) { 123 | this.localPlayer = new CompoundTag(); 124 | this.mc.player.saveWithoutId(this.localPlayer); 125 | this.localPlayer.putInt("lotas_playerGameType", buf.readInt()); 126 | } else if (this.localPlayer != null) { 127 | this.mc.player.load(this.localPlayer); 128 | Vec3 pos = this.mc.player.position(); 129 | this.mc.player.teleportTo(pos.x(), pos.y(), pos.z()); 130 | this.mc.gameMode.setLocalMode(GameType.byId(this.localPlayer.getInt("lotas_playerGameType"))); 131 | } 132 | } 133 | 134 | /** 135 | * Save client data on connect 136 | * 137 | * @param player Player 138 | */ 139 | @Override 140 | protected void onClientConnect(ServerPlayer player) { 141 | CompoundTag tag = new CompoundTag(); 142 | player.saveWithoutId(tag); 143 | this.onlineClients.put(player, tag); 144 | } 145 | 146 | /** 147 | * Clear local data on disconnect 148 | */ 149 | @Override 150 | @Environment(EnvType.CLIENT) 151 | protected void onClientsideDisconnect() { 152 | this.localPlayer = null; 153 | } 154 | 155 | } 156 | -------------------------------------------------------------------------------- /src/main/resources/lotas.accesswidener: -------------------------------------------------------------------------------- 1 | accessWidener v1 named 2 | 3 | # Savestate Mod 4 | accessible field net/minecraft/world/level/lighting/LevelLightEngine blockEngine Lnet/minecraft/world/level/lighting/LayerLightEngine; 5 | accessible field net/minecraft/world/level/lighting/LevelLightEngine skyEngine Lnet/minecraft/world/level/lighting/LayerLightEngine; 6 | mutable field net/minecraft/world/level/lighting/LevelLightEngine blockEngine Lnet/minecraft/world/level/lighting/LayerLightEngine; 7 | mutable field net/minecraft/world/level/lighting/LevelLightEngine skyEngine Lnet/minecraft/world/level/lighting/LayerLightEngine; 8 | 9 | accessible field net/minecraft/server/level/ServerLevel toAddAfterTick Ljava/util/Queue; 10 | accessible field net/minecraft/server/level/ServerLevel entitiesById Lit/unimi/dsi/fastutil/ints/Int2ObjectMap; 11 | 12 | accessible field net/minecraft/server/level/ServerChunkCache distanceManager Lnet/minecraft/server/level/DistanceManager; 13 | accessible field net/minecraft/server/level/DistanceManager tickets Lit/unimi/dsi/fastutil/longs/Long2ObjectOpenHashMap; 14 | accessible field net/minecraft/server/level/DistanceManager chunksToUpdateFutures Ljava/util/Set; 15 | accessible field net/minecraft/server/level/DistanceManager ticketsToRelease Lit/unimi/dsi/fastutil/longs/LongSet; 16 | accessible field net/minecraft/server/level/ChunkMap pendingUnloads Lit/unimi/dsi/fastutil/longs/Long2ObjectLinkedOpenHashMap; 17 | accessible field net/minecraft/server/level/ChunkMap updatingChunkMap Lit/unimi/dsi/fastutil/longs/Long2ObjectLinkedOpenHashMap; 18 | accessible field net/minecraft/server/level/ChunkMap visibleChunkMap Lit/unimi/dsi/fastutil/longs/Long2ObjectLinkedOpenHashMap; 19 | accessible field net/minecraft/server/level/ChunkMap entitiesInLevel Lit/unimi/dsi/fastutil/longs/LongSet; 20 | accessible method net/minecraft/server/level/ChunkMap processUnloads (Ljava/util/function/BooleanSupplier;)V 21 | 22 | accessible method net/minecraft/server/level/ServerChunkCache clearCache ()V 23 | accessible field net/minecraft/world/level/chunk/storage/RegionFileStorage regionCache Lit/unimi/dsi/fastutil/longs/Long2ObjectLinkedOpenHashMap; 24 | 25 | accessible field net/minecraft/server/level/ServerLevel dragonFight Lnet/minecraft/world/level/dimension/end/EndDragonFight; 26 | mutable field net/minecraft/server/level/ServerLevel dragonFight Lnet/minecraft/world/level/dimension/end/EndDragonFight; 27 | accessible field net/minecraft/server/level/ServerLevel serverLevelData Lnet/minecraft/world/level/storage/ServerLevelData; 28 | mutable field net/minecraft/server/level/ServerLevel serverLevelData Lnet/minecraft/world/level/storage/ServerLevelData; 29 | accessible field net/minecraft/world/level/Level levelData Lnet/minecraft/world/level/storage/WritableLevelData; 30 | mutable field net/minecraft/world/level/Level levelData Lnet/minecraft/world/level/storage/WritableLevelData; 31 | 32 | accessible field net/minecraft/server/players/PlayerList stats Ljava/util/Map; 33 | accessible field net/minecraft/server/level/ServerPlayer stats Lnet/minecraft/stats/ServerStatsCounter; 34 | mutable field net/minecraft/server/level/ServerPlayer stats Lnet/minecraft/stats/ServerStatsCounter; 35 | accessible field net/minecraft/server/level/ChunkMap poiManager Lnet/minecraft/world/entity/ai/village/poi/PoiManager; 36 | accessible field net/minecraft/client/particle/ParticleEngine particles Ljava/util/Map; 37 | accessible field net/minecraft/world/item/ItemCooldowns cooldowns Ljava/util/Map; 38 | accessible field net/minecraft/world/entity/LivingEntity attackStrengthTicker I 39 | accessible field net/minecraft/world/entity/player/Player lastItemInMainHand Lnet/minecraft/world/item/ItemStack; 40 | 41 | accessible field net/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess levelPath Ljava/nio/file/Path; 42 | accessible field net/minecraft/server/MinecraftServer storageSource Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess; 43 | accessible field net/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess lock Lnet/minecraft/util/DirectoryLock; 44 | mutable field net/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess lock Lnet/minecraft/util/DirectoryLock; 45 | accessible field net/minecraft/server/MinecraftServer worldData Lnet/minecraft/world/level/storage/WorldData; 46 | mutable field net/minecraft/server/MinecraftServer worldData Lnet/minecraft/world/level/storage/WorldData; 47 | 48 | accessible field net/minecraft/world/level/chunk/storage/SectionStorage worker Lnet/minecraft/world/level/chunk/storage/IOWorker; 49 | accessible field net/minecraft/world/level/chunk/storage/IOWorker storage Lnet/minecraft/world/level/chunk/storage/RegionFileStorage; 50 | accessible field net/minecraft/world/entity/ai/village/poi/PoiManager loadedChunks Lit/unimi/dsi/fastutil/longs/LongSet; 51 | accessible field net/minecraft/world/level/chunk/storage/IOWorker pendingWrites Ljava/util/Map; 52 | accessible field net/minecraft/world/level/chunk/storage/ChunkStorage worker Lnet/minecraft/world/level/chunk/storage/IOWorker; 53 | accessible field net/minecraft/world/level/chunk/storage/SectionStorage storage Lit/unimi/dsi/fastutil/longs/Long2ObjectMap; 54 | 55 | accessible method net/minecraft/util/thread/BlockableEventLoop runAllTasks ()V 56 | 57 | # Dragon Manipulation 58 | accessible field net/minecraft/world/level/pathfinder/Path nodes Ljava/util/List; 59 | 60 | # Keybind System 61 | accessible field net/minecraft/client/KeyMapping CATEGORY_SORT_ORDER Ljava/util/Map; 62 | accessible field net/minecraft/client/KeyMapping key Lcom/mojang/blaze3d/platform/InputConstants$Key; 63 | 64 | # Mod System 65 | accessible field net/minecraft/network/protocol/game/ServerboundCustomPayloadPacket identifier Lnet/minecraft/resources/ResourceLocation; 66 | accessible field net/minecraft/network/protocol/game/ServerboundCustomPayloadPacket data Lnet/minecraft/network/FriendlyByteBuf; 67 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/tickratechanger/MixinMinecraftServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * These mixins exploit some weirdness in the runServer() method of the MinecraftServer. (As always,) I don't fully understand it, or if there is a better way, 3 | * but this code is probably the least intrusive way of making tickrate 0 work. 4 | * 5 | * How vanilla works: 6 | * 7 | * Util.getMillis() is the current time in milliseconds. For this example we will use 1000 8 | * 9 | * nextTickTime is the targeted millisecond time for the next tick 10 | * 11 | * if (l > 2000L && this.nextTickTime - this.lastOverloadWarning >= 15000L) { 12 | * long m = l / 50L; 13 | * LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", (Object)l, (Object)m); 14 | * this.nextTickTime += m * 50L; 15 | * this.lastOverloadWarning = this.nextTickTime; 16 | * } 17 | * 18 | * Here the server checks if the server is running behind on ticks and tries to correct that by adding more than one tick to the nextTickTime 19 | * 20 | * this.nextTickTime += 50L; 21 | * 22 | * The nextTickTime is increased by one tick. Let's say if the current time was 1000, then nextTickTime is 1050. 23 | * 24 | * this.tickServer(this::haveTime); 25 | * 26 | * Here is the tick function of the server with a big difference compared to the 1.12.2 version. A "haveTime" function that basically waits until the 27 | * Util.getMillis() is smaller than the nextTickTime. 28 | * So in our case if the current time is 1000 and the nextTickTime 1050, the haveTime returns false until the current time is 1051, then the tick is ended and the nextTickTime increases again. 29 | * 30 | * Problem: Idk about you, but I don't like screwing with the system time, in the following mixins, I am redirecting all Util.getMillis() in the run() and haveTime() and return the things I want 31 | */ 32 | 33 | package com.minecrafttas.lotas.mixin.tickratechanger; 34 | 35 | import java.util.function.BooleanSupplier; 36 | 37 | import org.spongepowered.asm.mixin.Mixin; 38 | import org.spongepowered.asm.mixin.Shadow; 39 | import org.spongepowered.asm.mixin.Unique; 40 | import org.spongepowered.asm.mixin.injection.At; 41 | import org.spongepowered.asm.mixin.injection.Constant; 42 | import org.spongepowered.asm.mixin.injection.Inject; 43 | import org.spongepowered.asm.mixin.injection.ModifyConstant; 44 | import org.spongepowered.asm.mixin.injection.Redirect; 45 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 46 | 47 | import net.minecraft.Util; 48 | import net.minecraft.server.MinecraftServer; 49 | 50 | import static com.minecrafttas.lotas.LoTAS.TICKRATE_CHANGER; 51 | import static com.minecrafttas.lotas.LoTAS.TICK_ADVANCE; 52 | 53 | /** 54 | * This mixin slows down the server 55 | * TODO: understand this mess properly 56 | * @author Scribble 57 | */ 58 | @Mixin(MinecraftServer.class) 59 | public abstract class MixinMinecraftServer { 60 | 61 | @Shadow 62 | private long nextTickTime; 63 | 64 | @Unique 65 | private long offset = 0; 66 | 67 | @Unique 68 | private long currentTime = 0; 69 | 70 | /** 71 | * Replaces all 50L values in MinecraftServer.runServer() to the desired milliseconds 72 | * per tick which is obtained by the tickratechanger 73 | * @param ignored the value that was originally used, in this case 50L 74 | * @return Milliseconds per tick 75 | */ 76 | @ModifyConstant(method = "runServer", constant = @Constant(longValue = 50L)) 77 | private long serverTickWaitTime(long ignored) { 78 | return (long) TICKRATE_CHANGER.getMsPerTick(); 79 | } 80 | 81 | /** 82 | * Redirects all Util.getMillis() in the run method of the minecraft server and 83 | * returns {@link #getCurrentTime()} 84 | * @return Modified measuring time 85 | */ 86 | @Redirect(method = "runServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J")) 87 | public long redirectGetMillis() { 88 | return this.getCurrentTime(); 89 | } 90 | 91 | /** 92 | * Redirects all Util.getMillis() in the shouldKeepTicking method of the 93 | * minecraft server and returns {@link #getCurrentTime()} 94 | * @return Modified measuring time 95 | */ 96 | @Redirect(method = "haveTime", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J")) 97 | public long redirectGetMillisInHaveTime() { 98 | return this.getCurrentTime(); 99 | } 100 | 101 | /** 102 | * Returns the time dependant on if the current tickrate is tickrate 0 103 | * @return In tickrates > 0 the vanilla time - offset else the current time in tickrate 0 104 | */ 105 | @Unique 106 | private long getCurrentTime() { 107 | if (!TICK_ADVANCE.isTickadvance() || TICK_ADVANCE.shouldTickServer) { 108 | this.currentTime = Util.getMillis(); // Set the current time that will be returned if the player decides to activate 109 | // tickrate 0 110 | return Util.getMillis() - this.offset; // Returns the Current time - offset which was set while tickrate 0 was active 111 | } 112 | this.offset = Util.getMillis() - this.currentTime; // Creating the offset from the measured time and the stopped time 113 | this.nextTickTime = this.currentTime + 50L; 114 | // Without this, the time reference would still increase by every tick in 115 | // vanilla, meaning that if you stop tickrate 0, the time reference would be 116 | // like nothing ever happened. The server realises this and just catches up with 117 | // the ticks. Now the time reference is always one tick ahead of the current 118 | // time, tricking shouldKeepTicking in forever catching up to one tick, creating 119 | // a loop. And if we unpause this, the offset is applied. 120 | 121 | return this.currentTime; 122 | } 123 | 124 | /** 125 | * Resets the Tick Advance status 126 | * @param supplier Parameters 127 | * @param ci Callback Info 128 | */ 129 | @Inject(method = "tickServer", at = @At("HEAD")) 130 | public void injectrunTick(BooleanSupplier supplier, CallbackInfo ci) { 131 | TICK_ADVANCE.shouldTickServer = false; 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mixin/dragonmanipulation/MixinDragonHoldingPatternPhase.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.mixin.dragonmanipulation; 2 | 3 | import com.minecrafttas.lotas.mods.DragonManipulation.Phase; 4 | import net.minecraft.world.entity.boss.enderdragon.EnderDragon; 5 | import net.minecraft.world.entity.boss.enderdragon.phases.AbstractDragonPhaseInstance; 6 | import net.minecraft.world.entity.boss.enderdragon.phases.DragonHoldingPatternPhase; 7 | import net.minecraft.world.level.pathfinder.Path; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.Shadow; 10 | import org.spongepowered.asm.mixin.Unique; 11 | import org.spongepowered.asm.mixin.injection.At; 12 | import org.spongepowered.asm.mixin.injection.ModifyArgs; 13 | import org.spongepowered.asm.mixin.injection.Redirect; 14 | import org.spongepowered.asm.mixin.injection.invoke.arg.Args; 15 | 16 | import java.util.Random; 17 | 18 | import static com.minecrafttas.lotas.LoTAS.DRAGON_MANIPULATION; 19 | 20 | /** 21 | * This mixin manipulates the rng of the dragon holding pattern phase 22 | * 23 | * @author Pancake 24 | */ 25 | @Mixin(DragonHoldingPatternPhase.class) 26 | public abstract class MixinDragonHoldingPatternPhase extends AbstractDragonPhaseInstance { 27 | public MixinDragonHoldingPatternPhase(EnderDragon enderDragon) { super(enderDragon); } 28 | 29 | /** 30 | * Force optimal dragon path by (step 1) removing the 20 block addend 31 | * 32 | * @param r Random source 33 | * @return Multiplier 34 | */ 35 | @Redirect(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextFloat()F")) 36 | public float redirect_nextFloat(Random r) { 37 | return DRAGON_MANIPULATION.getPhase() == Phase.OFF ? r.nextFloat() : 0.0f; 38 | } 39 | 40 | /** 41 | * Force optimal dragon path by (step 2) calculating the optimal block addend depending on the dragons position 42 | * 43 | * @param args Arguments 44 | */ 45 | @ModifyArgs(method = "navigateToNextPathNode", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/phys/Vec3;(DDD)V")) 46 | public void navigate_nodeInit(Args args) { 47 | if (DRAGON_MANIPULATION.getPhase() == Phase.OFF) 48 | return; 49 | 50 | double distance = Math.max(0, Math.min(20, dragon.position().y - (double) args.get(1))); 51 | args.set(1, (double) args.get(1) + distance); 52 | } 53 | 54 | @Unique 55 | public int shouldCCWCWC = 1; // should counter clock wise clock wise change, lol. 0 == switch, anything else == no switch 56 | 57 | @Shadow 58 | private boolean clockwise; 59 | 60 | /** 61 | * Force optimal dragon path by (step 3) calculating whether a direction change would result in the more optimal path. 62 | * Coincidentally the length of the path does not need to be checked, because for some odd mathematical reason the path length will always be 1 in the outer circle 63 | * 64 | * @param dragon Ender Dragon 65 | * @return Closest node 66 | */ 67 | @Redirect(method = "findNewTarget", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/boss/enderdragon/EnderDragon;findClosestNode()I")) 68 | public int redirect_findClosestNode(EnderDragon dragon) { 69 | int j, closestNodeA, closestNodeB; 70 | closestNodeA = closestNodeB = j = dragon.findClosestNode(); 71 | 72 | closestNodeB += 6; 73 | 74 | closestNodeA = this.clockwise ? ++closestNodeA : --closestNodeA; 75 | closestNodeB = this.clockwise ? --closestNodeB : ++closestNodeB; 76 | 77 | if ((closestNodeA %= 12) < 0) 78 | closestNodeA += 12; 79 | 80 | if ((closestNodeB %= 12) < 0) 81 | closestNodeB += 12; 82 | 83 | // get path and node 84 | Path noSwitchPath = dragon.findPath(j, closestNodeA, null); 85 | Path switchPath = dragon.findPath(j, closestNodeB, null); 86 | 87 | this.shouldCCWCWC = (noSwitchPath.nodes.size() <= switchPath.nodes.size()) ? 1 : 0; 88 | return j; 89 | } 90 | 91 | /** 92 | * Force optimal dragon path by (step 4) applying the calculated math from redirect_findClosestNode 93 | * 94 | * @param r Random source 95 | * @param i Bound 96 | * @return Random int 97 | */ 98 | @Redirect(method = "findNewTarget", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextInt(I)I", ordinal = 3)) 99 | public int redirect_nextInt(Random r, int i) { 100 | return DRAGON_MANIPULATION.getPhase() == Phase.OFF ? r.nextInt(i) : this.shouldCCWCWC; 101 | } 102 | 103 | /** 104 | * Force dragon to enter landing approach phase after finishing its path 105 | * 106 | * @param r Random source 107 | * @param i Bound 108 | * @return Random int 109 | */ 110 | @Redirect(method = "findNewTarget", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextInt(I)I", ordinal = 0)) 111 | public int redirect_nextInt_perching(Random r, int i) { 112 | switch (DRAGON_MANIPULATION.getPhase()) { 113 | case LANDINGAPPROACH: 114 | return 0; 115 | case HOLDINGPATTERN: 116 | case STRAFING: 117 | return 1; 118 | default: 119 | return r.nextInt(i); 120 | } 121 | } 122 | 123 | /** 124 | * Force dragon to enter strafing phase after finishing its path 125 | * 126 | * @param r Random source 127 | * @param i Bound 128 | * @return Random int 129 | */ 130 | @Redirect(method = "findNewTarget", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextInt(I)I", ordinal = 1)) 131 | public int redirect_nextInt_strafing(Random r, int i) { 132 | switch (DRAGON_MANIPULATION.getPhase()) { 133 | case STRAFING: 134 | return 0; 135 | case LANDINGAPPROACH: 136 | case HOLDINGPATTERN: 137 | return 1; 138 | default: 139 | return r.nextInt(i); 140 | } 141 | } 142 | 143 | /** 144 | * Force dragon to enter strafing phase after finishing its path 145 | * 146 | * @param r Random source 147 | * @param i Bound 148 | * @return Random int 149 | */ 150 | @Redirect(method = "findNewTarget", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextInt(I)I", ordinal = 2)) 151 | public int redirect_nextInt_strafing2(Random r, int i) { 152 | switch (DRAGON_MANIPULATION.getPhase()) { 153 | case STRAFING: 154 | return 0; 155 | case LANDINGAPPROACH: 156 | case HOLDINGPATTERN: 157 | return 1; 158 | default: 159 | return r.nextInt(i); 160 | } 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/system/KeybindSystem.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.system; 2 | 3 | import com.minecrafttas.lotas.mods.DragonManipulation.Phase; 4 | import lombok.Getter; 5 | import net.fabricmc.api.EnvType; 6 | import net.fabricmc.api.Environment; 7 | import net.minecraft.client.KeyMapping; 8 | import net.minecraft.client.Minecraft; 9 | import net.minecraft.client.gui.components.EditBox; 10 | import net.minecraft.client.gui.screens.Screen; 11 | import net.minecraft.client.gui.screens.recipebook.RecipeBookComponent; 12 | import org.apache.commons.lang3.ArrayUtils; 13 | import org.lwjgl.glfw.GLFW; 14 | 15 | import java.util.Arrays; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | import static com.minecrafttas.lotas.LoTAS.*; 20 | 21 | /** 22 | * This class manages keybinds and their categories. 23 | * 24 | * @author Pancake 25 | */ 26 | @Environment(EnvType.CLIENT) 27 | public class KeybindSystem { 28 | 29 | /** List of keybinds */ 30 | private static final Keybind[] KEYBINDS = { 31 | new Keybind("Advance a tick", "Tickrate Changer", GLFW.GLFW_KEY_F9, true, TICK_ADVANCE::requestTickadvance), 32 | new Keybind("Toggle tick advance", "Tickrate Changer", GLFW.GLFW_KEY_F8, true, TICK_ADVANCE::requestTickadvanceToggle), 33 | new Keybind("Decrease Tickrate", "Tickrate Changer", GLFW.GLFW_KEY_COMMA, true, TICKRATE_CHANGER::decreaseTickrate), 34 | new Keybind("Increase Tickrate", "Tickrate Changer", GLFW.GLFW_KEY_PERIOD, true, TICKRATE_CHANGER::increaseTickrate), 35 | new Keybind("Save playerdata", "Duplication", GLFW.GLFW_KEY_N, true, () -> 36 | DUPE_MOD.requestDupe(true)), 37 | new Keybind("Load playerdata", "Duplication", GLFW.GLFW_KEY_M, true, () -> 38 | DUPE_MOD.requestDupe(false)), 39 | new Keybind("Manipulate to holding pattern phase", "Dragon Manipulation", GLFW.GLFW_KEY_Y, true, () -> // hotkey just for testing, will be removed with gui 40 | DRAGON_MANIPULATION.requestPhaseChange(Phase.HOLDINGPATTERN)), 41 | new Keybind("Manipulate to landing approach phase", "Dragon Manipulation", GLFW.GLFW_KEY_X, true, () -> // hotkey just for testing, will be removed with gui 42 | DRAGON_MANIPULATION.requestPhaseChange(Phase.LANDINGAPPROACH)), 43 | new Keybind("Manipulate to strafing phase", "Dragon Manipulation", GLFW.GLFW_KEY_C, true, () -> // hotkey just for testing, will be removed with gui 44 | DRAGON_MANIPULATION.requestPhaseChange(Phase.STRAFING)), 45 | new Keybind("Disable manipulation", "Dragon Manipulation", GLFW.GLFW_KEY_V, true, () -> // hotkey just for testing, will be removed with gui 46 | DRAGON_MANIPULATION.requestPhaseChange(Phase.OFF)), 47 | new Keybind("Savestate", "Savestates", GLFW.GLFW_KEY_J, true, () -> 48 | SAVESTATE_MOD.requestState(0, -1, "Test")), 49 | new Keybind("Loadstate", "Savestates", GLFW.GLFW_KEY_K, true, () -> 50 | SAVESTATE_MOD.requestState(1, 0, null)), 51 | new Keybind("Deletestate", "Savestates", GLFW.GLFW_KEY_I, true, () -> 52 | SAVESTATE_MOD.requestState(2, 0, null)), 53 | }; 54 | 55 | /** 56 | * This class represents a keybind 57 | * 58 | * @author Pancake 59 | */ 60 | private static class Keybind { 61 | 62 | /** Minecraft key mapping */ 63 | @Getter 64 | private final KeyMapping keyMapping; 65 | 66 | /** Category of the keybind in the controls menu */ 67 | private final String category; 68 | 69 | /** Should the keybind only be available if mc.level is not null */ 70 | private final boolean isInGame; 71 | 72 | /** Ran when keybind is pressed */ 73 | private final Runnable onKeyDown; 74 | 75 | /** 76 | * Initialize keybind 77 | * 78 | * @param name Name of the keybind 79 | * @param category Category of the keybind 80 | * @param defaultKey Default key of the keybind 81 | * @param isInGame Should the keybind only be available if mc.level is not null 82 | * @param onKeyDown Will be run when the keybind is pressed 83 | */ 84 | public Keybind(String name, String category, int defaultKey, boolean isInGame, Runnable onKeyDown) { 85 | this.keyMapping = new KeyMapping(name, defaultKey, category); 86 | this.category = category; 87 | this.isInGame = isInGame; 88 | this.onKeyDown = onKeyDown; 89 | } 90 | 91 | } 92 | 93 | /** 94 | * Initialize keybind system and register categories and key binds. 95 | * 96 | * @param keyMappings Array of key mappings 97 | */ 98 | public static KeyMapping[] onKeybindInitialize(KeyMapping[] keyMappings) { 99 | // initialize categories 100 | Map categories = KeyMapping.CATEGORY_SORT_ORDER; 101 | for (int i = 0; i < KEYBINDS.length; i++) 102 | if (!categories.containsKey(KEYBINDS[i].category)) 103 | categories.put(KEYBINDS[i].category, i + 8); 104 | 105 | // add keybinds 106 | return ArrayUtils.addAll(keyMappings, Arrays.stream(KEYBINDS).map(Keybind::getKeyMapping).toArray(KeyMapping[]::new)); // convert Keybind array to KeyMapping on the fly 107 | } 108 | 109 | /** 110 | * Trigger keybinds on key press 111 | * 112 | * @param mc Instance of minecraft 113 | */ 114 | public static void onGameLoop(Minecraft mc) { 115 | for (Keybind keybind : KEYBINDS) { 116 | if (keybind.isInGame && mc.level == null || !isKeyDown(mc, keybind.getKeyMapping())) 117 | continue; 118 | keybind.onKeyDown.run(); 119 | } 120 | } 121 | 122 | /** Map of pressed/non-pressed keys. */ 123 | private static final Map keys = new HashMap<>(); 124 | 125 | /** 126 | * Check whether key has been pressed this frame. 127 | * @param mc Instance of minecraft 128 | * @param map Key mapping to check 129 | * @return Key has been pressed in this frame 130 | */ 131 | private static boolean isKeyDown(Minecraft mc, KeyMapping map) { 132 | // check if in a text field 133 | Screen screen = mc.screen; 134 | if (screen != null && ((screen.getFocused() instanceof EditBox && ((EditBox) screen.getFocused()).canConsumeInput()) || screen.getFocused() instanceof RecipeBookComponent)) 135 | return false; 136 | 137 | // check if key is just pressed 138 | boolean wasPressed = keys.getOrDefault(map, false); 139 | boolean isPressed = GLFW.glfwGetKey(mc.getWindow().getWindow(), map.key.getValue()) == GLFW.GLFW_PRESS; 140 | keys.put(map, isPressed); 141 | return !wasPressed && isPressed; 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/system/ModSystem.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.system; 2 | 3 | import net.fabricmc.api.EnvType; 4 | import net.fabricmc.api.Environment; 5 | import net.minecraft.client.Minecraft; 6 | import net.minecraft.network.FriendlyByteBuf; 7 | import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; 8 | import net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket; 9 | import net.minecraft.resources.ResourceLocation; 10 | import net.minecraft.server.MinecraftServer; 11 | import net.minecraft.server.level.ServerPlayer; 12 | 13 | import java.util.ArrayList; 14 | import java.util.Arrays; 15 | import java.util.List; 16 | 17 | /** 18 | * Mod manager managing events for mods 19 | * 20 | * @author Pancake 21 | */ 22 | public class ModSystem { 23 | 24 | /** Registered mods */ 25 | private static final List MODS = new ArrayList<>(); 26 | 27 | /** 28 | * Register a list of mods 29 | * 30 | * @param m Mods 31 | */ 32 | public static void registerMods(Mod... m) { 33 | MODS.addAll(Arrays.asList(m)); 34 | } 35 | 36 | // 1: event handlers that update the mod 37 | 38 | public static void onServerLoad(MinecraftServer minecraftServer) { 39 | for (Mod mod : MODS) { 40 | mod.mcserver = minecraftServer; 41 | mod.onServerLoad(); 42 | } 43 | } 44 | 45 | @Environment(EnvType.CLIENT) 46 | public static void onClientsideRenderInitialize(Minecraft minecraft) { 47 | for (Mod mod : MODS) { 48 | mod.mc = minecraft; 49 | mod.onClientsideRenderInitialize(); 50 | } 51 | } 52 | 53 | // 2: event handlers that check for id 54 | 55 | public static void onServerPayload(ServerboundCustomPayloadPacket buf) { 56 | for (Mod mod : MODS) 57 | if (mod.id.equals(buf.identifier)) 58 | mod.onServerPayload(buf.data); 59 | } 60 | 61 | @Environment(EnvType.CLIENT) 62 | public static void onClientsidePayload(ClientboundCustomPayloadPacket buf) { 63 | for (Mod mod : MODS) 64 | if (mod.id.equals(buf.getIdentifier())) 65 | mod.onClientsidePayload(buf.getData()); 66 | } 67 | 68 | // 3: simple event handlers 69 | 70 | public static void onInitialize() { 71 | for (Mod mod : MODS) 72 | mod.onInitialize(); 73 | } 74 | 75 | public static void onServerTick() { 76 | for (Mod mod : MODS) 77 | mod.onServerTick(); 78 | } 79 | 80 | public static void onClientConnect(ServerPlayer player) { 81 | for (Mod mod : MODS) 82 | mod.onClientConnect(player); 83 | } 84 | 85 | @Environment(EnvType.CLIENT) 86 | public static void onClientsideInitialize() { 87 | for (Mod mod : MODS) 88 | mod.onClientsideInitialize(); 89 | } 90 | 91 | @Environment(EnvType.CLIENT) 92 | public static void onClientsideShutdown() { 93 | for (Mod mod : MODS) 94 | mod.onClientsideShutdown(); 95 | } 96 | 97 | @Environment(EnvType.CLIENT) 98 | public static void onClientsideTick() { 99 | for (Mod mod : MODS) 100 | mod.onClientsideTick(); 101 | } 102 | 103 | @Environment(EnvType.CLIENT) 104 | public static void onClientsideGameLoop() { 105 | for (Mod mod : MODS) 106 | mod.onClientsideGameLoop(); 107 | } 108 | 109 | @Environment(EnvType.CLIENT) 110 | public static void onClientsideDisconnect() { 111 | for (Mod mod : MODS) 112 | mod.onClientsideDisconnect(); 113 | } 114 | 115 | @Environment(EnvType.CLIENT) 116 | public static void onClientsidePostRender() { 117 | for (Mod mod : MODS) 118 | mod.onClientsidePostRender(); 119 | } 120 | 121 | /** 122 | * Hull of a mod containing all events for the mod 123 | * 124 | * @author Pancake 125 | */ 126 | public static abstract class Mod { 127 | 128 | /** Instance of Minecraft */ 129 | @Environment(EnvType.CLIENT) 130 | protected Minecraft mc; 131 | 132 | /** Instance of server or null */ 133 | protected MinecraftServer mcserver; 134 | 135 | /** Id of the mod */ 136 | protected final ResourceLocation id; 137 | 138 | /** 139 | * Initialize a mod 140 | * 141 | * @param id Id of this mod 142 | */ 143 | public Mod(ResourceLocation id) { 144 | this.id = id; 145 | } 146 | 147 | /** 148 | * Executed after the fabric launcher 149 | * (mc and mcserver will still be null!) 150 | */ 151 | protected void onInitialize() { 152 | 153 | } 154 | 155 | /** 156 | * Executed after the server launches. 157 | * (mcserver will be set) 158 | */ 159 | protected void onServerLoad() { 160 | 161 | } 162 | 163 | /** 164 | * Executed inbetween every tick on the server 165 | */ 166 | protected void onServerTick() { 167 | 168 | } 169 | 170 | /** 171 | * Executed every time the server receives a custom payload packet. 172 | * 173 | * @param buf Packet 174 | */ 175 | protected void onServerPayload(FriendlyByteBuf buf) { 176 | 177 | } 178 | 179 | /** 180 | * Executed if a client connects to the server 181 | * 182 | * @param player Client connected 183 | */ 184 | protected void onClientConnect(ServerPlayer player) { 185 | 186 | } 187 | 188 | /** 189 | * Executed after the client initializes. mc is not set yet 190 | */ 191 | @Environment(EnvType.CLIENT) 192 | protected void onClientsideInitialize() { 193 | 194 | } 195 | 196 | /** 197 | * Executed after the rendering engine launches. 198 | * (mc will be set) 199 | */ 200 | @Environment(EnvType.CLIENT) 201 | protected void onClientsideRenderInitialize() { 202 | 203 | } 204 | 205 | /** 206 | * Executed before the JVM stops on the clientside. 207 | */ 208 | @Environment(EnvType.CLIENT) 209 | protected void onClientsideShutdown() { 210 | 211 | } 212 | 213 | /** 214 | * Executed every tick of the client. 215 | */ 216 | @Environment(EnvType.CLIENT) 217 | protected void onClientsideTick() { 218 | 219 | } 220 | 221 | /** 222 | * Executed every time the clients game logic loops. 223 | */ 224 | @Environment(EnvType.CLIENT) 225 | protected void onClientsideGameLoop() { 226 | 227 | } 228 | 229 | /** 230 | * Executed every time the client receives a custom payload packet. 231 | * 232 | * @param buf Packet 233 | */ 234 | @Environment(EnvType.CLIENT) 235 | protected void onClientsidePayload(FriendlyByteBuf buf) { 236 | 237 | } 238 | 239 | /** 240 | * Executed if the client disconnects from a world or server 241 | */ 242 | @Environment(EnvType.CLIENT) 243 | protected void onClientsideDisconnect() { 244 | 245 | } 246 | 247 | /** 248 | * Executed every time the client renders a frame 249 | */ 250 | @Environment(EnvType.CLIENT) 251 | protected void onClientsidePostRender() { 252 | 253 | } 254 | 255 | /** 256 | * Send packet to a client 257 | * 258 | * @param player Player 259 | * @param buf Data 260 | */ 261 | protected void sendPacketToClient(ServerPlayer player, FriendlyByteBuf buf) { 262 | player.connection.send(new ClientboundCustomPayloadPacket(this.id, buf)); 263 | } 264 | 265 | /** 266 | * Send packet from to server 267 | * 268 | * @param buf Data 269 | */ 270 | @Environment(EnvType.CLIENT) 271 | protected void sendPacketToServer(FriendlyByteBuf buf) { 272 | this.mc.getConnection().send(new ServerboundCustomPayloadPacket(this.id, buf)); 273 | } 274 | 275 | } 276 | 277 | } 278 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mods/TickrateChanger.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Here is the logic of the tickrate changer: 3 | * 4 | * As noted by the @Environment annotations in front of methods, this code works on both client and server. 5 | * 6 | * Every time the clients wants to change the tickrate it sends a request tickrate change packet to the server. #requestTickrateUpdate ~~> #requestTickrateUpdate 7 | * The server proceeds by changing it's tickrate and sends a tickrate change packet to the client from it's listener. #onServerPacket -> #updateTickrate 8 | * The clients listener finally updates the client tickrate too. #onClientPacket -> #internallyUpdateTickrate 9 | */ 10 | package com.minecrafttas.lotas.mods; 11 | 12 | import com.minecrafttas.lotas.system.ConfigurationSystem; 13 | import com.minecrafttas.lotas.system.ModSystem.Mod; 14 | 15 | import io.netty.buffer.Unpooled; 16 | import lombok.Getter; 17 | import net.fabricmc.api.EnvType; 18 | import net.fabricmc.api.Environment; 19 | import net.minecraft.network.FriendlyByteBuf; 20 | import net.minecraft.resources.ResourceLocation; 21 | import net.minecraft.server.level.ServerPlayer; 22 | 23 | import static com.minecrafttas.lotas.LoTAS.TICK_ADVANCE; 24 | 25 | /** 26 | * Tickrate changer mod 27 | * 28 | * @author Pancake 29 | */ 30 | public class TickrateChanger extends Mod { 31 | public TickrateChanger() { 32 | super(new ResourceLocation("lotas", "tickratechanger")); 33 | } 34 | 35 | /** Array of the most common tickrates available via decrease and increase tickrate keybinds */ 36 | @Environment(EnvType.CLIENT) 37 | private static final double[] TICKRATES = { 0.5f, 1.0f, 2.0f, 4.0f, 5.0f, 10.0f, 20.0f }; 38 | 39 | 40 | /** Should the game remember the tickrate in-between different levels */ 41 | private boolean restoreLastSession; 42 | 43 | /** Tickrate of the last session, used for restoring tickrate (static for integrated server) */ 44 | private static double lastSessionTickrate = 20.0; 45 | 46 | /** Current speed of the game */ 47 | @Getter 48 | private double tickrate = 20.0, msPerTick = 50.0, gamespeed = 1.0; 49 | 50 | /** Previous game speed, clientside */ 51 | @Environment(EnvType.CLIENT) 52 | private double prevGamespeed = 1.0; 53 | 54 | /** System time since last tickrate change (in milliseconds) */ 55 | @Environment(EnvType.CLIENT) 56 | private long systemTimeSinceUpdate = System.currentTimeMillis(); 57 | 58 | /** Game time since last tickrate change (in milliseconds) */ 59 | @Environment(EnvType.CLIENT) 60 | private long gameTime = 0L; 61 | 62 | /** 63 | * Initialize tickrate changer mod 64 | */ 65 | @Override 66 | protected void onInitialize() { 67 | this.restoreLastSession = ConfigurationSystem.getBoolean("tickratechanger_remembertickrate", true); 68 | } 69 | 70 | /** 71 | * Request tickrate update by sendiong a packet to the server updating the tickrate. 72 | * (Clientside only) 73 | * 74 | * @param tickrate Tickrate to update to 75 | */ 76 | @Environment(EnvType.CLIENT) 77 | public void requestTickrateUpdate(double tickrate) { 78 | // request tickrate update 79 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 80 | buf.writeDouble(tickrate); 81 | this.sendPacketToServer(buf); 82 | } 83 | 84 | /** 85 | * Update server tickrate on packet receive 86 | * 87 | * @param buf Packet 88 | */ 89 | @Override 90 | protected void onServerPayload(FriendlyByteBuf buf) { 91 | this.updateTickrate(buf.readDouble()); 92 | } 93 | 94 | /** 95 | * Update tickrate and send a packet to all players 96 | * (Serverside only) 97 | * 98 | * @param tickrate Tickrate 99 | */ 100 | public void updateTickrate(double tickrate) { 101 | if (tickrate < 0.1) 102 | return; 103 | 104 | // change tickrate 105 | lastSessionTickrate = tickrate; 106 | this.internallyUpdateTickrate(tickrate); 107 | 108 | // update tickrate for all clients 109 | this.mcserver.getPlayerList().getPlayers().forEach(player -> { 110 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 111 | buf.writeDouble(tickrate); 112 | this.sendPacketToClient(player, buf); 113 | }); 114 | } 115 | 116 | /** 117 | * Internally update tickrate of game 118 | * 119 | * @param tickrate Tickrate 120 | */ 121 | private void internallyUpdateTickrate(double tickrate) { 122 | this.tickrate = tickrate; 123 | this.msPerTick = 1000.0 / tickrate; 124 | this.gamespeed = tickrate / 20; 125 | } 126 | 127 | /** 128 | * Update client tickrate on packet receive 129 | * 130 | * @param buf Packet Data 131 | */ 132 | @Override 133 | protected void onClientsidePayload(FriendlyByteBuf buf) { 134 | this.updateGameTime(this.prevGamespeed); 135 | this.internallyUpdateTickrate(buf.readDouble()); 136 | this.prevGamespeed = this.gamespeed; 137 | } 138 | 139 | /** 140 | * Update game time using gamespeed 141 | * 142 | * @param gamespeed Speed of game 143 | */ 144 | @Environment(EnvType.CLIENT) 145 | public void updateGameTime(double gamespeed) { 146 | this.gameTime += (long) ((System.currentTimeMillis() - this.systemTimeSinceUpdate) * gamespeed); 147 | this.systemTimeSinceUpdate = System.currentTimeMillis(); 148 | } 149 | 150 | /** 151 | * Send tickrate to newly connected client 152 | * 153 | * @param player Client connected 154 | */ 155 | @Override 156 | protected void onClientConnect(ServerPlayer player) { 157 | // update server tickrate on singleplayer connect 158 | if (this.mcserver.isSingleplayer() && this.restoreLastSession) 159 | this.internallyUpdateTickrate(lastSessionTickrate); 160 | 161 | // update client tickrate on connect 162 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 163 | buf.writeDouble(this.tickrate); 164 | this.sendPacketToClient(player, buf); 165 | } 166 | 167 | /** 168 | * Reset tickrate on disconnect 169 | */ 170 | @Override @Environment(EnvType.CLIENT) 171 | public void onClientsideDisconnect() { 172 | this.internallyUpdateTickrate(20.0); 173 | } 174 | 175 | /** 176 | * Advance game time by millis 177 | * 178 | * @param millis Milliseconds 179 | */ 180 | @Environment(EnvType.CLIENT) 181 | public void advanceGameTime(long millis) { 182 | this.gameTime += millis; 183 | this.systemTimeSinceUpdate = System.currentTimeMillis(); 184 | } 185 | 186 | /** 187 | * Get current game time in milliseconds. This is the time that the game would be at if the game was running at 20 tps. 188 | * (Clientside only) 189 | * 190 | * @return Milliseconds passed in game time 191 | */ 192 | @Environment(EnvType.CLIENT) 193 | public long getMilliseconds() { 194 | // ignore time passed if tick advance is enabled and client is not ticking 195 | if (TICK_ADVANCE.isTickadvance() && !TICK_ADVANCE.shouldTickClient) { 196 | this.systemTimeSinceUpdate = System.currentTimeMillis(); 197 | return this.gameTime; 198 | } 199 | 200 | // update game time 201 | long gameTimePassed = System.currentTimeMillis() - this.systemTimeSinceUpdate; 202 | gameTimePassed = (long) (gameTimePassed * this.gamespeed); 203 | return this.gameTime + gameTimePassed; 204 | } 205 | 206 | /** 207 | * Decrease tickrate to nearest recommended value 208 | */ 209 | @Environment(EnvType.CLIENT) 210 | public void decreaseTickrate() { 211 | double newTickrate = this.tickrate; 212 | for (int i = TICKRATES.length - 1; i >= 0; i--) { 213 | newTickrate = TICKRATES[i]; 214 | if (newTickrate < this.tickrate) 215 | break; 216 | } 217 | 218 | this.requestTickrateUpdate(newTickrate); 219 | } 220 | 221 | /** 222 | * Increase tickrate to nearest recommended value 223 | */ 224 | @Environment(EnvType.CLIENT) 225 | public void increaseTickrate() { 226 | double newTickrate = this.tickrate; 227 | for (double tickrate2 : TICKRATES) { 228 | newTickrate = tickrate2; 229 | if (newTickrate > this.tickrate) 230 | break; 231 | } 232 | 233 | this.requestTickrateUpdate(newTickrate); 234 | } 235 | 236 | } 237 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/system/ConfigurationSystem.java: -------------------------------------------------------------------------------- 1 | package com.minecrafttas.lotas.system; 2 | 3 | import java.io.File; 4 | import java.io.FileReader; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | import java.util.Properties; 8 | 9 | import static com.minecrafttas.lotas.LoTAS.LOGGER; 10 | 11 | /** 12 | * Configuration system that can read and store keys in a file using java properties. 13 | * 14 | * @author Pancake 15 | */ 16 | public class ConfigurationSystem { 17 | 18 | /** Configuration object */ 19 | private static Properties props = new Properties(); 20 | 21 | /** Configuration file */ 22 | private static File configurationFile; 23 | 24 | /** 25 | * Load configuration from file 26 | * 27 | * @param configuration Configuration file 28 | */ 29 | public static void load(File configuration) { 30 | try { 31 | configurationFile = configuration; 32 | 33 | if (!configuration.exists()) 34 | configuration.createNewFile(); 35 | 36 | FileReader reader = new FileReader(configuration); 37 | props = new Properties(); 38 | props.load(reader); 39 | reader.close(); 40 | } catch (IOException e) { 41 | LOGGER.error("Could not load configuration file!", e); 42 | } 43 | } 44 | 45 | /** 46 | * Save configuration to file 47 | */ 48 | public static void save() { 49 | try { 50 | FileWriter writer = new FileWriter(configurationFile); 51 | props.store(writer, "LoTAS Configuration File"); 52 | writer.close(); 53 | } catch (Exception e) { 54 | LOGGER.error("Could not save configuration file!", e); 55 | } 56 | } 57 | 58 | /** 59 | * Store something in configuration. 60 | * 61 | * @param key Name of the variable 62 | * @param value Value of the variable 63 | */ 64 | private static void setProperty(String key, String value) { 65 | props.setProperty(key, value); 66 | } 67 | 68 | /** 69 | * Obtain something from configuration 70 | * 71 | * @param key Name of the variable 72 | * @param def Default value 73 | */ 74 | private static String getProperty(String key, String def) { 75 | return props.getProperty(key, def); 76 | } 77 | 78 | /** 79 | * Verify property is present in configuration 80 | * 81 | * @param key Name of the variable 82 | * @return Value present 83 | */ 84 | public static boolean hasProperty(String key) { 85 | return props.containsKey(key); 86 | } 87 | 88 | // generic set methods 89 | 90 | /** 91 | * Store string in configuration 92 | * 93 | * @param key Name of the variable 94 | * @param value Value of the variable 95 | */ 96 | public static void setString(String key, String value) { 97 | setProperty(key, value); 98 | } 99 | 100 | /** 101 | * Store char in configuration 102 | * 103 | * @param key Name of the variable 104 | * @param value Value of the variable 105 | */ 106 | public static void setChar(String key, char value) { 107 | setProperty(key, (short) value + ""); 108 | } 109 | 110 | /** 111 | * Store byte in configuration 112 | * 113 | * @param key Name of the variable 114 | * @param value Value of the variable 115 | */ 116 | public static void setByte(String key, byte value) { 117 | setProperty(key, value + ""); 118 | } 119 | 120 | /** 121 | * Store short in configuration 122 | * 123 | * @param key Name of the variable 124 | * @param value Value of the variable 125 | */ 126 | public static void setShort(String key, short value) { 127 | setProperty(key, value + ""); 128 | } 129 | 130 | /** 131 | * Store int in configuration 132 | * 133 | * @param key Name of the variable 134 | * @param value Value of the variable 135 | */ 136 | public static void setInt(String key, int value) { 137 | setProperty(key, value + ""); 138 | } 139 | 140 | /** 141 | * Store long in configuration 142 | * 143 | * @param key Name of the variable 144 | * @param value Value of the variable 145 | */ 146 | public static void setLong(String key, long value) { 147 | setProperty(key, value + ""); 148 | } 149 | 150 | /** 151 | * Store double in configuration 152 | * 153 | * @param key Name of the variable 154 | * @param value Value of the variable 155 | */ 156 | public static void setDouble(String key, double value) { 157 | setProperty(key, Double.doubleToLongBits(value) + ""); 158 | } 159 | 160 | /** 161 | * Store float in configuration 162 | * 163 | * @param key Name of the variable 164 | * @param value Value of the variable 165 | */ 166 | public static void setFloat(String key, float value) { 167 | setProperty(key, Float.floatToIntBits(value) + ""); 168 | } 169 | 170 | /** 171 | * Store boolean in configuration 172 | * 173 | * @param key Name of the variable 174 | * @param value Value of the variable 175 | */ 176 | public static void setBoolean(String key, boolean value) { 177 | setProperty(key, value + ""); 178 | } 179 | 180 | // generic get methods 181 | 182 | /** 183 | * Obtain string from configuration 184 | * 185 | * @param key Name of the variable 186 | * @param def Default value 187 | * @return Value or default 188 | */ 189 | public static String getString(String key, String def) { 190 | return getProperty(key, def); 191 | } 192 | 193 | /** 194 | * Obtain char from configuration 195 | * 196 | * @param key Name of the variable 197 | * @param def Default value 198 | * @return Value or default 199 | */ 200 | public static char getChar(String key, char def) { 201 | String stringVal = getProperty(key, (short) def + ""); 202 | try { 203 | return (char) Short.parseShort(stringVal); 204 | } catch (NumberFormatException e) { 205 | LOGGER.warn("Configuration file for key \"{}\" contains invalid char value \"{}\".", key, stringVal); 206 | } 207 | return def; 208 | } 209 | 210 | /** 211 | * Obtain byte from configuration 212 | * 213 | * @param key Name of the variable 214 | * @param def Default value 215 | * @return Value or default 216 | */ 217 | public static byte getByte(String key, byte def) { 218 | String stringVal = getProperty(key, def + ""); 219 | try { 220 | return Byte.parseByte(stringVal); 221 | } catch (NumberFormatException e) { 222 | LOGGER.warn("Configuration file for key \"{}\" contains invalid byte value \"{}\".", key, stringVal); 223 | } 224 | return def; 225 | } 226 | 227 | /** 228 | * Obtain short from configuration 229 | * 230 | * @param key Name of the variable 231 | * @param def Default value 232 | * @return Value or default 233 | */ 234 | public static short getShort(String key, short def) { 235 | String stringVal = getProperty(key, def + ""); 236 | try { 237 | return Short.parseShort(stringVal); 238 | } catch (NumberFormatException e) { 239 | LOGGER.warn("Configuration file for key \"{}\" contains invalid short value \"{}\".", key, stringVal); 240 | } 241 | return def; 242 | } 243 | 244 | /** 245 | * Obtain int from configuration 246 | * 247 | * @param key Name of the variable 248 | * @param def Default value 249 | * @return Value or default 250 | */ 251 | public static int getInt(String key, int def) { 252 | String stringVal = getProperty(key, def + ""); 253 | try { 254 | return Integer.parseInt(stringVal); 255 | } catch (NumberFormatException e) { 256 | LOGGER.warn("Configuration file for key \"{}\" contains invalid int value \"{}\".", key, stringVal); 257 | } 258 | return def; 259 | } 260 | 261 | /** 262 | * Obtain long from configuration 263 | * 264 | * @param key Name of the variable 265 | * @param def Default value 266 | * @return Value or default 267 | */ 268 | public static long getLong(String key, long def) { 269 | String stringVal = getProperty(key, def + ""); 270 | try { 271 | return Long.parseLong(stringVal); 272 | } catch (NumberFormatException e) { 273 | LOGGER.warn("Configuration file for key \"{}\" contains invalid long value \"{}\".", key, stringVal); 274 | } 275 | return def; 276 | } 277 | 278 | /** 279 | * Obtain double from configuration 280 | * 281 | * @param key Name of the variable 282 | * @param def Default value 283 | * @return Value or default 284 | */ 285 | public static double getDouble(String key, double def) { 286 | String stringVal = getProperty(key, Double.doubleToLongBits(def) + ""); 287 | try { 288 | return Double.longBitsToDouble(Long.parseLong(stringVal)); 289 | } catch (NumberFormatException e) { 290 | LOGGER.warn("Configuration file for key \"{}\" contains invalid double value \"{}\".", key, stringVal); 291 | } 292 | return def; 293 | } 294 | 295 | /** 296 | * Obtain float from configuration 297 | * 298 | * @param key Name of the variable 299 | * @param def Default value 300 | * @return Value or default 301 | */ 302 | public static float getFloat(String key, float def) { 303 | String stringVal = getProperty(key, Float.floatToIntBits(def) + ""); 304 | try { 305 | return Float.intBitsToFloat(Integer.parseInt(stringVal)); 306 | } catch (NumberFormatException e) { 307 | LOGGER.warn("Configuration file for key \"{}\" contains invalid float value \"{}\".", key, stringVal); 308 | } 309 | return def; 310 | } 311 | 312 | /** 313 | * Obtain boolean from configuration 314 | * 315 | * @param key Name of the variable 316 | * @param def Default value 317 | * @return Value or default 318 | */ 319 | public static boolean getBoolean(String key, boolean def) { 320 | String stringVal = getProperty(key, def + ""); 321 | try { 322 | return Boolean.parseBoolean(stringVal); 323 | } catch (NumberFormatException e) { 324 | LOGGER.warn("Configuration file for key \"{}\" contains invalid boolean value \"{}\".", key, stringVal); 325 | } 326 | return def; 327 | } 328 | 329 | } 330 | -------------------------------------------------------------------------------- /src/main/java/com/minecrafttas/lotas/mods/SavestateMod.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Here is the logic of the savestate mod.. 3 | * 4 | * The class 'state' represents a savestate. It contains some data such as name, timestamp and more. 5 | * There is a list of states, which is being synchronized between the client and the server whenever a state action occurs (save load delete) 6 | * 7 | * in onClientsidePayload the client reacts to the server, once it sends a packet. The packet contains all states of a server. 8 | * 9 | * The client can request and action in requestState(). 10 | */ 11 | package com.minecrafttas.lotas.mods; 12 | 13 | import com.minecrafttas.lotas.mods.savestatemod.StateData; 14 | import com.minecrafttas.lotas.mods.savestatemod.StateData.State; 15 | import com.minecrafttas.lotas.system.ModSystem.Mod; 16 | import com.mojang.serialization.Dynamic; 17 | import io.netty.buffer.Unpooled; 18 | import net.fabricmc.api.EnvType; 19 | import net.fabricmc.api.Environment; 20 | import net.minecraft.Util; 21 | import net.minecraft.commands.Commands; 22 | import net.minecraft.core.RegistryAccess; 23 | import net.minecraft.nbt.CompoundTag; 24 | import net.minecraft.nbt.NbtOps; 25 | import net.minecraft.nbt.Tag; 26 | import net.minecraft.network.FriendlyByteBuf; 27 | import net.minecraft.network.protocol.game.*; 28 | import net.minecraft.resources.RegistryReadOps; 29 | import net.minecraft.resources.ResourceLocation; 30 | import net.minecraft.server.MinecraftServer; 31 | import net.minecraft.server.PlayerAdvancements; 32 | import net.minecraft.server.ServerResources; 33 | import net.minecraft.server.level.*; 34 | import net.minecraft.server.packs.repository.*; 35 | import net.minecraft.server.players.PlayerList; 36 | import net.minecraft.stats.ServerStatsCounter; 37 | import net.minecraft.util.DirectoryLock; 38 | import net.minecraft.world.effect.MobEffectInstance; 39 | import net.minecraft.world.entity.Entity; 40 | import net.minecraft.world.entity.EquipmentSlot; 41 | import net.minecraft.world.entity.boss.enderdragon.EnderDragon; 42 | import net.minecraft.world.level.DataPackConfig; 43 | import net.minecraft.world.level.Level; 44 | import net.minecraft.world.level.biome.BiomeManager; 45 | import net.minecraft.world.level.chunk.storage.RegionFile; 46 | import net.minecraft.world.level.dimension.DimensionType; 47 | import net.minecraft.world.level.dimension.end.EndDragonFight; 48 | import net.minecraft.world.level.lighting.BlockLightEngine; 49 | import net.minecraft.world.level.lighting.SkyLightEngine; 50 | import net.minecraft.world.level.storage.*; 51 | import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; 52 | import net.minecraft.world.phys.AABB; 53 | import net.minecraft.world.phys.Vec3; 54 | import org.apache.commons.io.FileUtils; 55 | import org.apache.commons.lang3.SerializationUtils; 56 | 57 | import java.io.File; 58 | import java.io.IOException; 59 | import java.nio.file.Path; 60 | import java.time.Instant; 61 | import java.util.ArrayList; 62 | import java.util.concurrent.CompletableFuture; 63 | 64 | import static com.minecrafttas.lotas.LoTAS.*; 65 | 66 | /** 67 | * Savestate mod 68 | * 69 | * @author Pancake 70 | */ 71 | public class SavestateMod extends Mod { 72 | public SavestateMod() { 73 | super(new ResourceLocation("lotas", "savestatemod")); 74 | } 75 | 76 | /** Mirrored state data */ 77 | private final StateData data = new StateData(); 78 | 79 | /** Task to execute next tick */ 80 | private Task task; 81 | 82 | /** 83 | * Load save data on initialize 84 | */ 85 | @Override 86 | protected void onServerLoad() { 87 | this.data.onServerInitialize(this.mcserver); 88 | } 89 | 90 | /** 91 | * Request state action by sending a packet to the server 92 | * 93 | * @param state State action (state 0 is save, state 1 is load, state 2 is delete) 94 | * @param index Index of state to load/delete (only used for state 1 and 2) 95 | * @param name Name of the state (only used for state 0) 96 | */ 97 | @Environment(EnvType.CLIENT) 98 | public void requestState(int state, int index, String name) { 99 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 100 | buf.writeInt(state); 101 | if (state == 0) 102 | buf.writeUtf(name); 103 | else 104 | buf.writeInt(index); 105 | 106 | this.sendPacketToServer(buf); 107 | } 108 | 109 | /** 110 | * Trigger load/delete/savestate when client packet is incoming and then inform every client 111 | * 112 | * @param buf Packet 113 | */ 114 | @Override 115 | protected void onServerPayload(FriendlyByteBuf buf) { 116 | // prepare task for next tick 117 | switch (buf.readInt()) { 118 | case 0: 119 | String s = buf.readUtf(Short.MAX_VALUE); 120 | this.task = () -> this.savestate(s); 121 | break; 122 | case 1: 123 | int i = buf.readInt(); 124 | this.task = () -> this.loadstate(i); 125 | break; 126 | case 2: 127 | int j = buf.readInt(); 128 | this.task = () -> this.deletestate(j); 129 | break; 130 | } 131 | 132 | // tick the server 133 | if (TICK_ADVANCE.isTickadvance()) 134 | TICK_ADVANCE.updateTickadvance(); 135 | } 136 | 137 | /** 138 | * Execute task on next tick 139 | */ 140 | @Override 141 | protected void onServerTick() { 142 | 143 | if (this.task != null) { 144 | boolean tickAdvanceState = TICK_ADVANCE.isTickadvance(); 145 | TICK_ADVANCE.updateTickadvanceStatus(true); // enable tick advance to freeze clients 146 | 147 | try { 148 | // load state data and execute task 149 | this.data.loadData(); 150 | this.task.run(); 151 | } catch (IOException e) { 152 | LOGGER.error("State task failed!", e); 153 | } 154 | 155 | TICK_ADVANCE.updateTickadvanceStatus(tickAdvanceState); // restore tick advance state 156 | this.task = null; 157 | } 158 | 159 | } 160 | 161 | /** 162 | * Send all states to client 163 | */ 164 | public void sendStates() { 165 | byte[] serialized = SerializationUtils.serialize(this.data.getStates()); 166 | this.mcserver.getPlayerList().getPlayers().forEach(player -> { 167 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 168 | buf.writeInt(0); 169 | buf.writeByteArray(serialized); 170 | this.sendPacketToClient(player, buf); 171 | }); 172 | } 173 | 174 | /** 175 | * Save new state of the world 176 | * 177 | * @param name Savestate Name 178 | * @throws IOException If an exception occurs while saving 179 | */ 180 | private void savestate(String name) throws IOException { 181 | for (ServerPlayer player : this.mcserver.getPlayerList().getPlayers()) { 182 | if (!player.isAlive()) { 183 | LOGGER.warn("Unable to create savestate because {} is not alive.", player.getName().getString()); 184 | return; 185 | } 186 | } 187 | 188 | // save world 189 | this.mcserver.getPlayerList().saveAll(); 190 | this.mcserver.saveAllChunks(false, true, false); 191 | 192 | // disable Session Lock 193 | Path levelPath = this.mcserver.storageSource.levelPath; 194 | this.mcserver.storageSource.lock.close(); 195 | 196 | // make state 197 | State[] states = this.data.getStates(); 198 | int latestStateIndex = states.length - 1; 199 | int index = latestStateIndex == -1 ? 0 : states[latestStateIndex].getIndex() + 1; 200 | File stateDir = new File(this.data.getWorldSavestateDir(), index + ""); 201 | FileUtils.copyDirectory(this.data.getWorldDir(), stateDir); 202 | this.data.addState(new State(name == null ? "Untitled State" : name, Instant.now().getEpochSecond(), index)); 203 | 204 | // re-enable session lock 205 | this.mcserver.storageSource.lock = DirectoryLock.create(levelPath); 206 | 207 | // save data and send to client 208 | this.data.saveData(); 209 | this.sendStates(); 210 | } 211 | 212 | /** 213 | * Load state of the world 214 | * 215 | * @param i Index to load 216 | * @throws IOException If an exception occurs while loading 217 | */ 218 | private void loadstate(int i) throws IOException { 219 | if (!this.data.isValid(i)) { 220 | LOGGER.warn("Trying to load a state that does not exist: " + i); 221 | return; 222 | } 223 | 224 | // revive every player to prevent a freeze 225 | for (ServerPlayer player : this.mcserver.getPlayerList().getPlayers()) 226 | if (!player.isAlive()) 227 | player.setHealth(20.0f); 228 | 229 | // unload level 230 | this.unloadServerLevel(); 231 | 232 | // unlock session.lock 233 | File worldDir = this.data.getWorldDir(); 234 | Path levelPath = this.unlockSessionLock(); 235 | 236 | // delete world 237 | FileUtils.deleteDirectory(worldDir); 238 | 239 | // copy state 240 | File worldSavestateDir = new File(this.data.getWorldSavestateDir(), this.data.getStates()[i].getIndex() + ""); 241 | FileUtils.copyDirectory(worldSavestateDir, worldDir); 242 | 243 | // lock session.lock 244 | this.lockSessionLock(levelPath); 245 | 246 | // reload level 247 | this.loadWorldData(); 248 | this.loadWorldLighting(); 249 | this.loadPlayers(); 250 | } 251 | 252 | /** 253 | * Unload all levels 254 | * 255 | * @throws IOException If an exception occurs while unloading 256 | */ 257 | private void unloadServerLevel() throws IOException { 258 | for (ServerLevel level : this.mcserver.getAllLevels()) { 259 | ServerChunkCache chunkCache = level.getChunkSource(); 260 | DistanceManager distanceManager = chunkCache.distanceManager; 261 | ChunkMap map = chunkCache.chunkMap; 262 | 263 | // clear future entities 264 | level.toAddAfterTick.clear(); 265 | 266 | // kill ender dragons (only mob with sub entities) 267 | if (level.dragonFight != null) 268 | for (EnderDragon dragon : level.getEntitiesOfClass(EnderDragon.class, new AABB(-256, 0, -256, 256, 256, 256))) 269 | dragon.kill(); 270 | 271 | // despawn existing entities 272 | for (Entity entity : new ArrayList<>(level.entitiesById.values())) 273 | if (entity != null) 274 | level.despawn(entity); 275 | 276 | // remove chunk loading requests 277 | distanceManager.tickets.clear(); 278 | distanceManager.chunksToUpdateFutures.clear(); 279 | distanceManager.ticketsToRelease.clear(); 280 | 281 | // unload chunks 282 | map.pendingUnloads.clear(); 283 | map.updatingChunkMap.clear(); 284 | map.visibleChunkMap.clear(); 285 | map.entitiesInLevel.clear(); 286 | map.processUnloads(() -> true); 287 | 288 | // clear lighting engine 289 | chunkCache.getLightEngine().blockEngine = null; 290 | chunkCache.getLightEngine().skyEngine = null; 291 | 292 | // clear chunk cache 293 | chunkCache.clearCache(); 294 | 295 | // close files 296 | for (RegionFile file : map.poiManager.worker.storage.regionCache.values()) 297 | file.close(); 298 | 299 | map.poiManager.loadedChunks.clear(); 300 | map.poiManager.storage.clear(); 301 | map.poiManager.worker.storage.regionCache.clear(); 302 | map.poiManager.worker.pendingWrites.clear(); 303 | 304 | for (RegionFile file : map.worker.storage.regionCache.values()) 305 | file.close(); 306 | 307 | map.worker.storage.regionCache.clear(); 308 | map.worker.pendingWrites.clear(); 309 | } 310 | } 311 | 312 | /** 313 | * Unlock session lock 314 | * 315 | * @return Path to level 316 | * @throws IOException If an exception occurs while unlocking 317 | */ 318 | private Path unlockSessionLock() throws IOException { 319 | Path levelPath = this.mcserver.storageSource.levelPath; 320 | this.mcserver.storageSource.lock.close(); 321 | return levelPath; 322 | } 323 | 324 | /** 325 | * Create session lock 326 | * 327 | * @param levelPath Path to level 328 | * @throws IOException If an exception occurs while locking 329 | */ 330 | private void lockSessionLock(Path levelPath) throws IOException { 331 | this.mcserver.storageSource.lock = DirectoryLock.create(levelPath); 332 | } 333 | 334 | /** 335 | * Load world lighting 336 | */ 337 | private void loadWorldLighting() { 338 | for (ServerLevel level : this.mcserver.getAllLevels()) { 339 | ServerChunkCache chunkCache = level.getChunkSource(); 340 | chunkCache.getLightEngine().blockEngine = new BlockLightEngine(chunkCache); 341 | chunkCache.getLightEngine().skyEngine = level.dimensionType().hasSkyLight() ? new SkyLightEngine(chunkCache) : null; 342 | } 343 | } 344 | 345 | /** 346 | * Load all players 347 | */ 348 | private void loadPlayers() { 349 | PlayerList playerList = this.mcserver.getPlayerList(); 350 | for (ServerPlayer player : new ArrayList<>(playerList.getPlayers())) { 351 | 352 | // load player data 353 | CompoundTag compoundTag = playerList.load(player); 354 | @SuppressWarnings("deprecation") 355 | ServerLevel newLevel = this.mcserver.getLevel(compoundTag != null ? DimensionType.parseLegacy(new Dynamic<>(NbtOps.INSTANCE, compoundTag.get("Dimension"))).result().orElse(Level.OVERWORLD) : Level.OVERWORLD); 356 | 357 | // update client before spawning 358 | LevelData levelData = newLevel.getLevelData(); 359 | player.connection.send(new ClientboundRespawnPacket(newLevel.dimensionTypeKey(), newLevel.dimension(), BiomeManager.obfuscateSeed(newLevel.getSeed()), player.gameMode.getGameModeForPlayer(), player.gameMode.getPreviousGameModeForPlayer(), newLevel.isDebug(), newLevel.isFlat(), true)); 360 | player.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked())); 361 | player.server.getPlayerList().sendPlayerPermissionLevel(player); 362 | 363 | // add player to level 364 | Vec3 pos = player.position(); 365 | player.moveTo(pos.x(), pos.y(), pos.z(), player.yRot, player.xRot); 366 | player.setLevel(newLevel); 367 | newLevel.addDuringPortalTeleport(player); 368 | 369 | // update client level 370 | player.connection.teleport(pos.x(), pos.y(), pos.z(), player.yRot, player.xRot); 371 | player.gameMode.setLevel(newLevel); 372 | player.connection.send(new ClientboundPlayerAbilitiesPacket(player.abilities)); 373 | player.server.getPlayerList().sendLevelInfo(player, newLevel); 374 | player.server.getPlayerList().sendAllPlayerInfo(player); 375 | player.connection.send(new ClientboundSetHealthPacket(player.getHealth(), player.getFoodData().getFoodLevel(), player.getFoodData().getSaturationLevel())); 376 | player.connection.send(new ClientboundSetExperiencePacket(player.experienceProgress, player.totalExperience, player.experienceLevel)); 377 | for (MobEffectInstance mobEffectInstance : player.getActiveEffects()) 378 | player.connection.send(new ClientboundUpdateMobEffectPacket(player.getId(), mobEffectInstance)); 379 | 380 | // update player advancements 381 | PlayerAdvancements adv = player.getAdvancements(); 382 | adv.reload(this.mcserver.getAdvancements()); 383 | adv.flushDirty(player); 384 | 385 | // update player stats 386 | playerList.stats.remove(player.getUUID()); 387 | ServerStatsCounter stats = playerList.getPlayerStats(player); 388 | player.stats = stats; 389 | stats.sendStats(player); 390 | 391 | // update dupe mod data 392 | FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); 393 | buf.writeBoolean(true); 394 | DUPE_MOD.onServerPayload(buf); 395 | 396 | // run quality of life stuff 397 | player.getCooldowns().cooldowns.clear(); 398 | 399 | // run quality of life stuff on the client 400 | FriendlyByteBuf buf2 = new FriendlyByteBuf(Unpooled.buffer()); 401 | buf2.writeInt(-1); 402 | this.sendPacketToClient(player, buf2); 403 | } 404 | } 405 | 406 | /** 407 | * Load world data 408 | */ 409 | private void loadWorldData() { 410 | WorldData worldData = this.loadWorldData(this.mcserver.storageSource); 411 | this.mcserver.worldData = worldData; 412 | for (ServerLevel level : this.mcserver.getAllLevels()) { 413 | ServerLevelData data = worldData.overworldData(); 414 | if (level.dimension() != Level.OVERWORLD) 415 | data = new DerivedLevelData(worldData, data); 416 | 417 | level.levelData = data; 418 | level.serverLevelData = data; 419 | 420 | if (level.dragonFight != null) 421 | level.dragonFight = new EndDragonFight(level, this.mcserver.getWorldData().worldGenSettings().seed(), this.mcserver.getWorldData().endDragonFightData()); 422 | } 423 | } 424 | 425 | /** 426 | * Load world data from level storage access 427 | * 428 | * @param levelStorageAccess Level Storage Access 429 | * @return World Data 430 | */ 431 | private WorldData loadWorldData(LevelStorageAccess levelStorageAccess) { 432 | ServerResources serverResources; 433 | DataPackConfig dataPackConfig = levelStorageAccess.getDataPacks(); 434 | PackRepository packRepository = new PackRepository<>(Pack::new, new ServerPacksSource(), new FolderRepositorySource(levelStorageAccess.getLevelPath(LevelResource.DATAPACK_DIR).toFile(), PackSource.WORLD)); 435 | DataPackConfig dataPackConfig2 = MinecraftServer.configurePackRepository(packRepository, dataPackConfig == null ? DataPackConfig.DEFAULT : dataPackConfig, false); 436 | CompletableFuture completableFuture = ServerResources.loadResources(packRepository.openAllSelected(), Commands.CommandSelection.DEDICATED, 2, Util.backgroundExecutor(), Runnable::run); 437 | try { 438 | serverResources = completableFuture.get(); 439 | } catch (Exception exception) { 440 | packRepository.close(); 441 | return null; 442 | } 443 | serverResources.updateGlobals(); 444 | RegistryReadOps registryReadOps = RegistryReadOps.create(NbtOps.INSTANCE, serverResources.getResourceManager(), RegistryAccess.builtin()); 445 | return levelStorageAccess.getDataTag(registryReadOps, dataPackConfig2); 446 | } 447 | 448 | /** 449 | * Delete state of the world 450 | * 451 | * @param i Index to delete 452 | * @throws IOException If an exception occurs while deleting 453 | */ 454 | private void deletestate(int i) throws IOException { 455 | if (!this.data.isValid(i)) { 456 | LOGGER.warn("Trying to delete a state that does not exist: " + i); 457 | return; 458 | } 459 | 460 | // delete State 461 | FileUtils.deleteDirectory(new File(this.data.getWorldSavestateDir(), this.data.getStates()[i].getIndex() + "")); 462 | this.data.removeState(i); 463 | 464 | // save data and send to client 465 | this.data.saveData(); 466 | this.sendStates(); 467 | } 468 | 469 | 470 | /** 471 | * Update state list on incoming packet 472 | * 473 | * @param buf Packet 474 | */ 475 | @Override 476 | @Environment(EnvType.CLIENT) 477 | protected void onClientsidePayload(FriendlyByteBuf buf) { 478 | switch (buf.readInt()) { 479 | case -1: // update after loadstate 480 | this.mc.gui.getChat().clearMessages(false); 481 | this.mc.getToasts().clear(); 482 | this.mc.particleEngine.particles.clear(); 483 | this.mc.player.getCooldowns().cooldowns.clear(); 484 | this.mc.player.attackStrengthTicker = 100; 485 | this.mc.player.lastItemInMainHand = this.mc.player.getItemBySlot(EquipmentSlot.MAINHAND); 486 | break; 487 | case 1: // load states 488 | this.data.deserializeData(buf.readByteArray()); 489 | break; 490 | } 491 | } 492 | 493 | /** 494 | * Update client data on connect 495 | */ 496 | public void onClientConnect(ServerPlayer c) { 497 | try { 498 | this.data.loadData(); 499 | this.sendStates(); 500 | } catch (IOException e) { 501 | LOGGER.warn("Unable to send states to client.", e); 502 | } 503 | } 504 | 505 | public interface Task { 506 | void run() throws IOException; 507 | } 508 | } 509 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------