Archive eaglerforge-injector (tool, 1.8.8, clean-with-notes)

This commit is contained in:
2026-11-27 22:15:15 -06:00
parent 5f406cdc02
commit 606dab7e6e
91 changed files with 9667 additions and 0 deletions
@@ -0,0 +1,38 @@
## ModAPI.array
ModAPI.array contains the API for creating java arrays easily.
Methods:
- `ModAPI.array.object(class: Class|String, jsarray: object[]) : Object[]`
- Converts a javascript array of a class to a java array of a class.
- The class argument can be a raw java class (eg. `ModAPI.reflect.getClassByName(...).class`)
- It can also be a string `"java.util.String"`
- `ModAPI.array.object(class: Class, size: number) : Object[]`
- Creates a java array of a class with the specified size.
- `ModAPI.array.boolean(jsarray: boolean[]) : Boolean[]`
- Takes a java cript array of booleans (`true`/`false`) and converts it into a java array.
- `ModAPI.array.boolean(size: number) : Boolean[]`
- Creates a boolean array with the specified size.
- `ModAPI.array.byte(jsarray: number[]) : Byte[]`
- Takes a javascript array of numbers and converts it into a java byte array.
- `ModAPI.array.byte(size: number) : Byte[]`
- Creates a byte array with the specified size.
- `ModAPI.array.char(jsarray: number[]) : Char[]`
- Takes a javascript array of numbers and converts it into a java char array.
- `ModAPI.array.char(size: number) : Char[]`
- Creates a char array with the specified size.
- `ModAPI.array.short(jsarray: number[]) : Short[]`
- Takes a javascript array of numbers and converts it into a java short array.
- `ModAPI.array.short(size: number) : Short[]`
- Creates a short array with the specified size.
- `ModAPI.array.int(jsarray: number[]) : Int[]`
- Takes a javascript array of numbers and converts it into a java int array.
- `ModAPI.array.int(size: number) : Int[]`
- Creates a int array with the specified size.
- `ModAPI.array.float(jsarray: number[]) : Float[]`
- Takes a javascript array of numbers and converts it into a java float array.
- `ModAPI.array.float(size: number) : Float[]`
- Creates a float array with the specified size.
- `ModAPI.array.double(jsarray: number[]) : Float[]`
- Takes a javascript array of numbers and converts it into a java double array.
- `ModAPI.array.double(size: number) : Float[]`
- Creates a double array with the specified size.
@@ -0,0 +1,39 @@
## ModAPI.dedicatedServer
This is the dedicated server module, used for modding singleplayer in more powerful ways.
ModAPI.dedicatedServer has the following methods:
- `appendCode(code: Function | String) : void`
- Injects provided code into the dedicated server.
### Modding the dedicated server
Eaglercraft runs the dedicated server in a service worker. This means that in order to run code to mod the dedicated server, you have to change context into the service worker.
`ModAPI.dedicatedServer.appendCode()` allows you to inject code into the dedicates server before startup. The code injected will throw errors if it attempts to access resources outside the functions context.
For example, take a look at this mod, which will inject some code that does nothing into the dedicated server:
```javascript
var myVariable = 4;
function myServerSideModCode() {
function subfunction() {
console.log("serverside!!!");
}
subfunction();
//Successfully running serverside
//However, we cannot access `myVariable`
}
ModAPI.dedicatedServer.appendCode(myServerSideModCode);
```
You can check if a mod if running serverside using this:
```javascript
function myServerSideModCode(isServerSide) {
console.log(isServerSide);
}
myServerSideModCode(); //logs undefined
ModAPI.dedicatedServer.appendCode(myServerSideModCode); //when server starts, will log `true`
```
Once serverside, you can only access server side events, like `serverstart` or `tick`. [See serverside events](events.md#server-side-events)
@@ -0,0 +1,119 @@
## Events
Events broadcast data for use in mods.
- `ModAPI.addEventListener(eventName: String, callback: Function) : void`
- Used to register an event handler. Eg:
- ```javascript
function myHandler(event) {
console.log(event);
}
ModAPI.addEventListener("update", myHandler);
```
- `ModAPI.removeEventListener(eventName: String, callback: Function) : void`
- Used to unregister an event handler. Eg:
- ```javascript
function myHandler(event) {
console.log(event);
}
ModAPI.removeEventListener("update", myHandler);
```
### Basic Events
- `update`:
- Called every client side tick.
- Event object is blank.
- `load`:
- Called when all mods have finished loading.
- Event object is blank.
- `sendchatmessage`:
- Called just before the player sends a chat message.
- Passes an object with properties:
- `message: String`
- String representing the chat message.
- `preventDefault: Boolean`
- Boolean representing whether or not to cancel processing the chat message. Default is `false`.
- `event`:
- Called when any event is called. Passes an object with properties:
- Passes an object with properties:
- `event: String`
- String representing the type of event being fired.
- `data: Object`
- Object representing the original arguments to be passed to the callback.
- `frame`:
- Called just when a frame is rendered on the client.
- Event object is blank.
- `render`:
- Called when 3D is rendered.
- Event object is has one property:
- `partialTicks`: number representing the fraction of ticks passed at this frame.
### Server Side Events
Can only be used in the context of the dedicated server. More: [DedicatedServerDocumentation](dedicatedserver.md)
- `serverstart`:
- Called when the dedicated server starts.
- Event object is blank.
- `bootstrap`:
- Called when the dedicated server registers blocks, items, materials, enchantments, etc.
- This is when you should register cstom blocks and items.
- Event object is blank.
- `serverstop`:
- Called when the dedicated server stops.
- Event object is blank.
- `tick`:
- Called when the server ticks.
- Passes an object with properties:
- `preventDefault: Boolean`
- Boolean representing whether or not to cancel the tick. Default is `false`.
- `receivechatmessage`:
- Called when the server receives a chat message.
- Passes an object with properties:
- `message: String`
- String representing the chat message.
- `preventDefault: Boolean`
- Boolean representing whether or not to cancel processing the chat message. Default is `false`.
- `processcommand`:
- Called when the server receives a command.
- Passes an object with properties:
- `command: String`
- String representing the command.
- `sender: ICommandSender`
- Object that sent the command
- `preventDefault: Boolean`
- Boolean representing whether or not to cancel processing the command. Default is `false`.
### Events Global, adding new events
The events global, `ModAPI.events`, allows you to register new event types and call them.
#### ModAPI.events.newEvent(eventName: String)
You can register new events using ModAPI, as long as the event name starts with `custom:` (`lib:` is only useful for library loading). For example, if I want to add a new event that can be used by other mods, I can use `ModAPI.events.newEvent("custom:myevent")`.
#### ModAPI.events.callEvent(eventName: String, data: Object)
You can then call events via `ModAPI.events.callEvent`. For example, to trigger `custom:myevent` with a secret code value, I can run `ModAPI.events.callEvent("custom:myevent", {secretCode: "1234"});`.
Here is an example on using this:
```javascript
// Mod #1, registers event handler for custom event
ModAPI.addEventListener("custom:myevent", (e)=>{
alert(e.secretCode);
});
```
```javascript
// Mod #2, registers and calls custom event
ModAPI.events.newEvent("custom:myevent");
ModAPI.events.callEvent("custom:myevent", {
secretCode: "1234"
});
```
#### Using library load events
```javascript
// Mod #2, registers and calls lib event
ModAPI.events.newEvent("lib:mylibrary:loaded");
ModAPI.events.callEvent("lib:mylibrary:loaded", {});
```
```javascript
// Mod #1, registers event handler for lib event
ModAPI.addEventListener("lib:mylibrary:loaded", (e)=>{
//Lib events function differently to normal events, as when they are called once, any new event listener with automatically fire upon being registered.
});
```
@@ -0,0 +1,40 @@
## ModAPI.hooks
ModAPI.hooks is the global generated by actual code.
It has quite a few propeties, but most of them are just foundations for more user friendly parts of the ModAPI, so I won't explain them.
### Property: ModAPI.hooks.methods
`ModAPI.hooks.methods` is a String-to-method dictionary/object of every java method. This allows you to do pretty much whatever you want in terms of modifying and hooking into code.
It's properties are defined by the package of the java class, as well as that methods name. For example, `net.minecraft.world.World`'s `spawnEntityInWorld` method will be named `ModAPI.hooks.methods.nmw_World_spawnEntityInWorld`, where `nmw` is `net.minecraft.world`. You can automate finding this by using `ModAPI.util.getMethodFromPackage("com.package.abc.MyClass", "myMethod")`, which is an alorithm that automatically finds the key in `ModAPI.hooks.methods`.
Due to the injector's patches, all game code runs by calling these ModAPI.hooks.methods functions, which allows you to call, patch, replace and modify the game's source code in realtime.
To call a method, use `ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("com.package.abc.MyClass", "myMethod")](argument1, argument2, etc);`.
Complexities with calling methods:
Methods that are described in EaglercraftX's source code as `static` can be called by replacing boolean values `true`/`false` with `1` and `0`, respectively. Strings have to be converted by using `ModAPI.util.str("string")` or one of it's aliases. To pass data from a ModAPI proxy you have to use .getRef(), eg: `ModAPI.player.getRef(); //raw java player object`.
Non static methods must be called with the object they are running on (the value of the `this` keyword in the java source). Do this by using the object as the first argument. For example, look at this code:
```javascript
ModAPI.require("world");
ModAPI.hooks.methods.nmw_World_spawnEntityInWorld(ModAPI.world.getRef(), *an entity object*);
```
- To replace a method with another, you can use:
- `ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("com.package.abc.MyClass", "myMethod")] = function () {}`
- To intercept inputs to a method, you can us
- ```javascript
var myMethodName = ModAPI.util.getMethodFromPackage("com.package.abc.MyClass", "myMethod");
const originalMethod = ModAPI.hooks.methods[myMethodName];
ModAPI.hooks.methods[myMethodName] = function (...args) {
//args is the array of arguments passed in.
//on an instance method, this first (args[0]) will almost always
//be $this, ie: the object the method is being run on
return originalMethod.apply(this, args);
}
```
Please note that if you are just calling methods, I recommend attempting to call the method directly on the object. `Eg: ModAPI.world.spawnEntityInWorld(*an entity object*)` or using `ModAPI.reflect.getClassByName("MyClass").methods.methodName.method()`;
### Property: ModAPI.hooks._teavm
`ModAPI.hooks._teavm` is usually only used for internal purposes, but it is basically a collection of every internal TeaVM method. Keep in mind that this only stores references (for performance reasons), so modifying and editing it's contents will not affect the way the game runs.
@@ -0,0 +1,185 @@
# EaglerForge ModAPI Documentation
The EaglerForge ModAPI is housed in a global JavaScript object stored on `globalThis`, called `ModAPI` or `PluginAPI`. (both are identical)
### Important Notice!
From people used to the doc prior to EaglerForgeInjector, now, when you see something like `ModAPI.world`'s type is `World`, that literally means it is identical to an instance of `net.minecraft.world.World` from java. For easier modding, here are some online javadocs, that explain properties from each individual method and proerty of every 1.8 class:
https://nurmarvin.github.io/Minecraft-1.8-JavaDocs/overview-summary.html - Javadoc for vanilla 1.8
https://eaglerreborn.github.io/javadoc/ - EaglerReborn (EF precursor) javadoc, for EaglercraftX u17 (missing serverside classes, this version didn't have singleplayer)
An up-to-date javadoc for EaglercraftX is coming soon, in the meanwhile, I recommend modding with a local EaglercraftX workspace, so you can inspect the contents of each class.
Additionally, when you se that something like `ModAPI.mcinstance` is `Raw<Minecraft>` this means that it has a lot of TeaVM nonsense like '$' prefixes before everything, as well has making it difficult to call the objects methods.
### Global ModAPI Object:
The global object has the following properties:
- `ModAPI.player: EntityPlayerSP`
- Only accessible after `ModAPI.require("player")` is called, this is the local player entity. It is regenerated every time the `update` event is called.
- `ModAPI.world: WorldClient`
- Only accessible after `ModAPI.require("world")` is called, this is the client-side world. It is regenerated every time the `update` event is called.
- `ModAPI.network: NetHandlerPlayClient`
- Only accessible after `ModAPI.require("network")` is called, this is the client's networking handler. It is regenerated every time the `update` event is called.
- `ModAPI.settings: GameSettings`
- This is the Minecraft client's settings. It is generated upon init.
- `ModAPI.items: Map<String, Item>`
- This is a key-value dictionary of all of the items in the game. It is generated upon init from the static variables of the `Items` class.
- For example, to access the item class for `acacia_door`, you can use `ModAPI.items["acacia_door"]`
- `ModAPI.blocks: Map<String, Block>`
- This is a key-value dictionary of all of the blocks in the game. It is generated upon init from the static variables of the `Blocks` class.
- For example, to access the block class for `bedrock`, you can use `ModAPI.blocks["bedrock"]`
- `ModAPI.materials: Map<String, Material>`
- This is a key-value dictionary of all of the blocks in the game. It is generated upon init from the static variables of the `Material` class.
- For example, to access the material class for `portal`, you can use `ModAPI.materials["portal"]`
- `ModAPI.enchantments: Map<String, Enchantment|Object>`
- This is a key-value dictionary of all of the enchantments in the game. It is generated upon init from the static variables of the `Enchantment` class.
- For example, to access the enchantment class for `knockback`, you can use `ModAPI.enchantments["knockback"]`
- As the enchantment class has other static variables, `Object.keys` will also return non-enchantment keys such as `enchantmentsBookList`.
- `ModAPI.blockSounds: Map<String, SoundType>` (1.12 only)
- This is a key-value dictionary of `SoundType`s. Used in `.setSoundType(soundType)` when registering custom blocks in 1.12.
- `ModAPI.minecraft: Minecraft`
- This is the minecraft instance for the client, generated upon init.
- It can also be accessed using `ModAPI.mc`
- `ModAPI.mcinstance: Raw<Minecraft>`
- This is the raw minecraft instance for the client, generated upon init.
- It can also be accessed using `ModAPI.javaClient`
- It can also be accessed using `ModAPI.minecraft.getRef()`
- It can also be accessed using `Minecraft`
- Only here for compatibility
- `ModAPI.server: MinecraftServer`
- This is the dedicated minecraft server in the service worker, generated when the `serverstart`.
- It can only be accessed in the dedicated server's context. (See `ModAPI.dedicatedServer`)
- It can also be accessed using `ModAPI.serverInstance`
- `ModAPI.rawServer: MinecraftServer`
- This is the dedicated minecraft server in the service worker, generated when the `serverstart` event is fired.
- It can only be accessed in the dedicated server's context. (See `ModAPI.dedicatedServer`)
- It can also be accessed using `ModAPI.server.getRef()`
- `ModAPI.hooks`
- This is the internal hooking map for ModAPI and can be used to patch, intercept, or rewrite internal functions, and more.
- More: [HooksDocumentation](hooks.md)
- `ModAPI.util`
- This contains utilities for using `ModAPI.hooks`, `ModAPI.reflect`, and more.
- More: [UtilDocumentation](utils.md)
- `ModAPI.reflect`
- This is a wrapper around `ModAPI.hooks`, `ModAPI.hooks._teavm` and `ModAPI.hooks._classMap` that makes accessing and using internal java classes in mods much easier.
- More: [ReflectDocumentation](reflect.md)
- `ModAPI.dedicatedServer`
- This object is used to push code for use in the dedicated server.
- Once the dedicated server worker has started, it is unuseable.
- More: [DedicatedServerDocumentation](dedicatedserver.md)
- `ModAPI.meta`
- This module is used to register metadata for mods such as their title, credits, icon and description.
- More: [MetaDocumentation](meta.md)
- `ModAPI.array`
- This module is used to interact and create arrays easily.
- More: [ArrayDocumentation](array.md)
- `ModAPI.keygen`
- This module is used to get IDs for registering blocks and items without hardcoding an ID.
- More: [KeygenDocumentation](keygen.md)
- `ModAPI.resolution`
- This module is used to query information about GUI dimensions, to make drawing to the screen easier, generated when the `frame` event is fired.
- Deprecated alias (please do not use): `ModAPI.ScaledResolution`
- More: [ArrayDocumentation](array.md)
- `ModAPI.version: String`
- The version of ModAPI.
- `ModAPI.is_1_12: Boolean`
- Property defining wether or not ModAPI thinks the current version is 1.12-based.
- `ModAPI.isServer: Boolean`
- Property defining wether or not ModAPI thinks it is running on the dedicated server.
- `ModAPI.flavour: String`
- The flavour of ModAPI. Hardcoded to be `"injector"`.
The ModAPI object has the following methods:
- `addEventListener(eventName: String, callback: Function) : void`
- More: [EventDocumentation](events.md)
- `require(componentName: String) : void`
- Import required modules, such as `player` and `network`.
- Usage: `ModAPI.require("module")`
- `displayToChat(message: String) : void`
- Displays client-side message to user's ingame chat gui.
- Usage: `ModAPI.displayToChat("Hello World.")`
- `clickMouse() : void`
- Triggers a left click ingame.
- `rightClickMouse() : void`
- Triggers a right click ingame.
- `getFPS() : int`
- Gets the frames per second of the game
- `promisify(asyncJavaMethod: Method | Constructor) : PromisifiedJavaRunner`
- Allows running java methods that are @Async/@Async dependent.
- More: [PromisifyDocumentation](promisify.md)
- `addCredit(category: String, contributor: String, contents: String)`
- Lets you easily add credits to Eaglercraft's credits.txt
- eg: `ModAPI.addCredit("My Cool Mod", "Username", " - Coded the mod\n - Wrote somne credits")`
## Handling strings, numbers and booleans to and from java.
Java strings and JavaScript strings are not the same. Calling a method like this: `ModAPI.player.sendChatMessage("hello world")`, will not work, as you are running a Java method with a JavaScript string. To convert a JS string to a Java string, use `ModAPI.util.str(yourString)`. For example, the correct version of the above example is `ModAPI.player.sendChatMessage(ModAPI.util.str("hello world"))`. This problem is automatically mitigated on a few functions, namely `ModAPI.displayToChat()`.
---
Java numbers and JavaScript numbers are stored the same way, with no problems with having to cast, like with strings. This is why you can simply do something like `ModAPI.player.motionY = 99999`, without having to do any conversion.
---
Booleans in Java are stored as a number, where `1` means `true` and `0` means `false`. There are no functions for converting inbetween these, because it is very easy to do so (unlike strings). To convert a javascript boolean into a java boolean simply multiply you boolean by 1.
Eg:
```javascript
var myBool = true;
console.log(myBool * 1);
// logs '1'
var myBool = false;
console.log(myBool * 1);
// logs '0'
```
Better yet, if you need to use booleans very often, just store them as numbers directly in javascript. JavaScript if statements already recognise `0` as false, so something like:
```javascript
var condition = 0;
if (condition) {
console.log("yes");
} else {
console.log("no");
}
// outputs 'no'
```
will work out of the box.
## Accessing raw data
In ModAPI's architecture, when you request an object like `ModAPI.player`, instead of giving you `ModAPI.mcinstance.$thePlayer`, it will return a `TeaVM_to_Recursive_BaseData_ProxyConf` proxy. These automatically remove the `$` prefixes, make instance methods run with the actaul object, and a variety other features.
However, when calling methods via `ModAPI.hooks`, `ModAPI.reflect`, or even just running a method that takes in object arguments on something like `ModAPI.player`, passing in these ModAPI proxies will cause an error.
To pass in raw java data simply call `getRef()` on the proxy which will return the raw, unmodified version of it.
For example, take the method `setRenderViewEntity()` on `ModAPI.mcinstance`. Instead of passing an entity from `ModAPI.world.loadedEntityList.get(index)` directly, you need to use `ModAPI.world.loadedEntityList.get(index).getRef()`. Demo code:
```javascript
var entityIndex = 1; //Index of the entity to look for. 0 means first, which is usually the player, so 1 is usually a natural entity.
ModAPI.mc.setRenderViewEntity(ModAPI.world.loadedEntityList.get(entityIndex).getRef());
```
Note that an entry for `getRef` will not appear from `Object.keys` and similar web APIs.
## Checking if an object is a proxy
All proxied objects have a property `isModProxy` which is equal to true. Note that an entry for `isModProxy` will not appear from `Object.keys` and similar web APIs.
## Corrective Proxies
By default, accessing a global like `ModAPI.player` will return a proxy to the original player that removes $ prefixes, as well as making instance methods callable. TeaVM has a quirk where it adds numerical suffixes to some properties. For example `ModAPI.player.inGround0` instead of `ModAPI.player.inGround`. As this is a large issue due to these suffixes changing for every eaglercraft update, you can now bypass this by obtaining a corrective version of `ModAPI.player`, using `ModAPI.player.getCorrective()`.
For example:
```javascript
ModAPI.player.inGround //returns undefined
ModAPI.player.inGround0 //returns 1 or 0, the correct value
ModAPI.player.isCorrective() //returns false
var correctedPlayer = ModAPI.player.getCorrective();
correctedPlayer.inGround //returns 1 or 0, the correct value
correctedPlayer.inGround0 //returns 1 or 0, the correct value
correctedPlayer.isCorrective() //returns true
```
You can check if an object is corrective using `<object>.isCorrective()`;
Accessing children of a corrective object will also make them corrective. `correctedPlayer.fishEntity.isCorrective(); //true`
@@ -0,0 +1,14 @@
## ModAPI.keygen
ModAPI.keygen contains the API for getting numerical item, block and entity IDs from a string. It looks at registries to derive the IDs, so IDs will not be automatically reserved until a block/item is actually registered into the game. Ideally, you'd want to call a keygen method just before registering your block.
Methods:
- `ModAPI.keygen.item(itemId: String) : number`
- Example usage is: `var id = ModAPI.keygen.item("my_example_item");`
- `ModAPI.keygen.block(blockId: String) : number`
- Example usage is: `var id = ModAPI.keygen.block("my_example_block");`
- `ModAPI.keygen.entity(entityId: String) : number`
- Example usage is: `var id = ModAPI.keygen.entity("my_example_entity");`
- `ModAPI.keygen.sound(soundId: String) : number`
- Example usage is: `var id = ModAPI.keygen.sound("my.example.sound");`
- `ModAPI.keygen.enchantment(enchantmentId: String) : number`
- Example usage is: `var id = ModAPI.keygen.enchantment("sharpness_v2");`
@@ -0,0 +1,17 @@
## ModAPI.meta
ModAPI.meta contains the API for registering metadata on mods easily.
Methods:
- `ModAPI.meta.title(title: String)`
- Sets the title of the mod. This is mandatory if any metadata is to be displayed. Character limit of 16.
- `ModAPI.meta.credits(credits: String)`
- Sets the credits of the mod. Character limit of 36.
- `ModAPI.meta.description(desc: String)`
- Sets the description of the mod. Character limit of 160.
- `ModAPI.meta.icon(iconURL: String)`
- Sets the icon of the mod.
- It can be extremely low res, it will not appear blurry.
- `ModAPI.meta.version(versionCode: String)`
- Sets the version of the mod. Appended after the title.
- `ModAPI.meta.config(configFn: Function)`
- Once the client is fully loaded, creates a button in the mod manager GUI that runs the specified function when pressed.
@@ -0,0 +1,37 @@
## ModAPI.promisify()
Some methods in java are asynchronous, meaning that they don't return a value/modify state immediately. Calling them in an event or in a patch to a normal function will cause a stack implosion, characterised by the client/dedicated server hanging without any error messages.
In order to call them properly from javascript, you need to use the `ModAPI.promisify()` function.
For example, here we have a simple client-side command that will try to use the `PlatformRuntime` class to download data from a URI:
```javascript
ModAPI.addEventListener("sendchatmessage", function downloadSomething(e) {
if (e.message.toLowerCase().startsWith("/downloadtest")) {
var arraybuffer = ModAPI.hooks.methods.nlevi_PlatformRuntime_downloadRemoteURI(ModAPI.util.str("data:text/plain,hi"));
console.log(arraybuffer);
}
});
```
This will cause the client to hang. The correct way of calling this asynchronous method is like this:
```javascript
ModAPI.addEventListener("sendchatmessage", function downloadSomething(e) {
if (e.message.toLowerCase().startsWith("/downloadtest")) {
ModAPI.promisify(ModAPI.hooks.methods.nlevi_PlatformRuntime_downloadRemoteURI)(ModAPI.util.str("data:text/plain,hi")).then(arraybuffer => {
console.log(arraybuffer);
});
}
});
```
The way this promisify method works is by taking in a java method, and (effectively) converting it into a javascript async function.
For example, you can do:
```javascript
var asyncDownloadRemoteURI = ModAPI.promisify(ModAPI.hooks.methods.nlevi_PlatformRuntime_downloadRemoteURI);
console.log(typeof asyncDownloadRemoteURI); //Logs function
```
When it is called, like any other asyncronous function, it returns a `Promise` object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
You can replace the argument with any other method or constructor, including non asynchronous ones.
@@ -0,0 +1,84 @@
## ModAPI.reflect
ModAPI.reflect supplies a user friendly wrapper for accessing and interacting with java classes from javascript.
Properties:
- `classes: ReflectClass[]`
- `ModAPI.reflect.classes` is an array of ReflectClasses, representing (almost) every java class.
- `classMap: Map<String, ReflectClass>` is a map of every class.
Methods:
- `ModAPI.reflect.getClassById(classId: String) : ReflectClass`
- This method is used to find a class by its id.
- For example, to get the `Minecraft` class, you can use `ModAPI.reflect.getClassById("net.minecraft.client.Minecraft")`
- `ModAPI.reflect.getClassByName(className: String) : ReflectClass`
- This method is used to find a class by its id.
- For example, to get the `Minecraft` class, you can use `ModAPI.reflect.getClassById("Minecraft")`
- This runs slower than `getClassById` because it has to filter through all classes. Make sure to cache the result rather than calling it over and over again.
- `ModAPI.reflect.getSuper(rClass: ReflectClass, filter: Function?) : Function`
- Gets a super function from a reflect class. This is used to extend built in classes, like `Block`.
- For an example, see lines [29](https://github.com/eaglerforge/EaglerForgeInjector/blob/6e8598c180f96a65c0c101be72e6d0fa53195404/examplemods/unlucky_blocks.js#L29) and [33](https://github.com/eaglerforge/EaglerForgeInjector/blob/6e8598c180f96a65c0c101be72e6d0fa53195404/examplemods/unlucky_blocks.js#L33) in `unlucky_blocks.js`
- When called without a filter function, the filter defaults to `(fn)=>fn.length === 1`
- `ModAPI.reflect.prototypeStack(rClass: ReflectClass, target: Class/ConstructorFunction) : void`
- Copies methods from a reflect class and it's parents onto a target native JavaScript class. This allows TeaVM to use these objects normally, without you having to manually reimplement every method. In other words, this is the equivalent of extending a class.
- Also adds some metadata to make the class work with `ModAPI.util.asClass`
- [Example usage](https://github.com/eaglerforge/EaglerForgeInjector/blob/6e8598c180f96a65c0c101be72e6d0fa53195404/examplemods/unlucky_blocks.js#L37)
- `ModAPI.reflect.implements(target: Class/ConstructorFunction, interface: ReflectClass)`
- Marks the provided interface as a supertype of the target class.
- JavaScript equivalent of the `implements` keyword
### ReflectClass Definition
Each `ReflectClass` has the following properties:
- `binaryName: String?`
- The binary name of the class in question. Eg: `Lnet.minecraft.client.entity.EntityPlayerSP;`
- Will be `null` if `hasMeta` is equal to `false`
- `class: Class?`
- The actual class. Cannot be used easily with `new` keyword, this is mostly useful for extending using `prototype`.
- Will be `null` if `hasMeta` is equal to `false`
- `compiledName: String`
- The TeaVM compiled name of the class. It is equal to the first letters of the package, an underscore, and the class name. Eg: `nmce_EntityPlayerSP`
- `constructors: Function[]`
- The constructors for the class.
- `hasMeta: Boolean`
- Wether or not the class has metadata saved by TeaVM.
- `id: String?`
- The class id of the class. Eg: `net.minecraft.client.entity.EntityPlayerSP`
- Will be `null` if `hasMeta` is equal to `false`
- `name: String`
- The name of the class. Eg: `EntityPlayerSP`
- `methods: Map<String, ReflectMethod>`
- `staticMethods: Map<String, ReflectMethod>`
- `staticVariableNames: String[]`
- List of all the static variable names for the class.
- `staticVariables: Map<String, *>`
- key-value dictionary of all the static variables in a class.
- `superclass: ReflectClass?`
- The superclass.
Each `ReflectClass` has the following methods:
- `instanceOf(object: Object)`
- Checks if the `object` is an instance of the class.
- `getConstructorByArgs(...argumentNames) : Function`
- Finds a constructor that matches the specified argument names. Eg:
- `ModAPI.reflect.getClassByName("ItemStack").getConstructorByArgs("blockIn", "amount")`
### ReflectMethod Definition
Each `ReflectMethod` has the following properties:
- `methodName: String`
- The compiled method name of the method. Eg: `nmce_EntityPlayerSP_closeScreen`.
- `methodNameShort: String`
- The short name of the method. Eg: `closeScreen`.
Each `ReflectClass` has the following methods:
- `method(...)`
- This is the java method.
- If it is an instance method (accessed from a ReflectClasses' `methods` property), the first argument should be an instance of the class. Eg: `ModAPI.reflect.getClassByName("EntityPlayerSP").methods.closeScreen.method(ModAPI.player.getRef())`
- If it is a static method (accessed from a ReflectClasses' `staticMethods` property), call the method as usual. Eg: `ModAPI.reflect.getClassById("net.minecraft.init.Items").staticMethods.getRegisteredItem.method(ModAPI.util.str("apple"))`
Keep in mind that you need to wrap strings using `ModAPI.util.str("MyString")`, convert booleans into respective numbers (`true`->`1`, `false`->`0`), and get references of ModAPI proxies (`ModAPI.player`->`ModAPI.player.getRef()`);
@@ -0,0 +1,87 @@
## ModAPI.util
ModAPI.util provides and exposes a large number of utilities for interacting with ModAPI.
Properties:
- `StaticProps_ProxyConf: ProxyConfiguration`
- This is the proxy configuration used for exposing `ModAPI.items`, `ModAPI.blocks`, `ModAPI.enchantments` and `ModAPI.materials`
- See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy
- `TeaVM_to_BaseData_ProxyConf: ProxyConfiguration`
- This is a non-recursive proxy config for removing prefixes from java objects.
- `TeaVM_to_Recursive_BaseData_ProxyConf: ProxyConfiguration`
- This is a recursive proxy config for removing prefixes from java objects. It handles properties (both object and array) as well as function outputs. Used for `ModAPI.player`, `ModAPI.mc`, `ModAPI.world`, `ModAPI.network` and more.
- `TeaVMArray_To_Recursive_BaseData_ProxyConf: ProxyConfiguration`
- This is a recursive proxy config for handling arrays from `TeaVM_to_Recursive_BaseData_ProxyConf`
Methods:
- `ModAPI.util.str(jsString: String) : java.lang.String`
- Converts a javascript string to a java string, for use in java methods and constructors.
- Alias: `ModAPI.util.string()`
- `ModAPI.util.unstr(jclString: java.lang.String) : String`
- Converts a java string to a javascript string.
- Alias: `ModAPI.util.ustr()`
- Alias: `ModAPI.util.unstring()`
- Alias: `ModAPI.util.jclStrToJsStr()`
- `ModAPI.util.getMethodFromPackage(classId: String, methodName: String) : String`
- Takes a class id (eg: `net.minecraft.client.Minecraft`) and a method name (eg: `middleClickMouse`) and returns its key in `ModAPI.hooks.methods`.
- `ModAPI.util.stringToUint16Array(string: String) : Uint16Array`
- Encodes a string into a uint16array.
- `ModAPI.util.setStringContent(jclString: java.lang.String, contents: String) : void`
- Writes a new javascript string into the contents of a java string.
- `ModAPI.util.getMethodFromPackage(classId: String, methodName: String) : String`
- Takes a class id (eg: `net.minecraft.client.Minecraft`) and a method name (eg: `middleClickMouse`) and returns its key in `ModAPI.hooks.methods`.
- `ModAPI.util.hashCode(string: String) : String`
- Returns the hash of a string.
- `ModAPI.util.isCritical() : boolean`
- Checks wether the thread is in a critical state.
- When patching methods, it is good practice to allow the method to resume as usual if this is `true`, to avoid stack implosions. (yes, those are real)
- `ModAPI.util.bootstrap() : void`
- Regenerate proxies for ModAPI.items, .blocks, .materials, .enchantments
- `ModAPI.util.createArray(class, jsArray) : Object[]`
- Makes a java array from a class and a javascript array.
- The class parameter can be retrieved via reflect: `ModAPI.reflect.getClassById("net.minecraft.util.BlockPos").class`
- `ModAPI.util.wrap(obj: Object) : object`
- Returns a wrapper around native java objects, removing prefixes and fixing method outputs.
- `ModAPI.util.getNearestProperty(object: Object, property: string) : string`
- Finds the nearest property name to the one you specify (suffix based). This is used to mitigate teavm adding random suffixes to properties.
- `ModAPI.util.modifyFunction(fn: Function, patcherFunction: Function) : string`
- Returns a modifies version of a function, where the patcher function can be used to modify the contents of a function. Example:
```javascript
function add(a, b) {
return a + b;
}
var multiply = ModAPI.util.modifyFunction(add, (code)=>{
return code.replaceAll("a + b", "a * b");
});
console.log(multiply(2, 3));
//Logs 6
```
- `ModAPI.util.modifyFunction(fn: Function, patcherFunction: Function) : string`
- Returns a modifies version of a function, where the patcher function can be used to modify the contents of a function. Example:
```javascript
function add(a, b) {
return a + b;
}
var multiply = ModAPI.util.modifyFunction(add, (code)=>{
return code.replaceAll("a + b", "a * b");
});
console.log(multiply(2, 3));
//Logs 6
```
- `ModAPI.util.getIdFromItem(item: Item) : number`
- Gets the ID of an item
- `ModAPI.util.getItemById(id: number) : Item`
- Gets an item by it's ID
- `ModAPI.util.getItemFromBlock(block: Block) : ItemBlock`
- Gets an item from a block.
- `ModAPI.util.getIdFromBlock(block: Block) : number`
- Gets the ID of a block
- `ModAPI.util.getBlockById(id: number) : Block`
- Gets a block by it's ID
- `ModAPI.util.getBlockFromItem(item: Item) : Block`
- Gets a block from an ItemBlock instance.
- `ModAPI.util.asClass(class: Class) : Class`
- Converts a javascript class to a java class.
- Equivalent of using `MyClass.class` in java.
@@ -0,0 +1,26 @@
# EaglerForge Injector Architecture
The Injector has several layers (or steps) in it's patching process. These layers can be put into two seperate categories: pre-processing and post-processing. The injector patches the EaglercraftX build with the pre-processor ahead of time, and then the post-processor is appended to the EaglercraftX build.
## Preprocessing
The preprocessor's job is to find and hook into as many internal TeaVM / Minecraft methods as possible.
The first thing it does is it adds a piece of pre-initialisation code at the start of the TeaVM module, to define global varaibles such as `ModAPI` and `ModAPI.hooks`.
Then it:
Hooks into the `$rt_metadata` function, intercepting its arguments and storing them in the array `ModAPI.hooks._rippedData`.
Hooks into the the teavm threading shim and adds controls to freeze the callstack.
Looks for the `#game_frame` element, and then adds the post-processing codes after it (`modapi_postinit`, `modapi_modloader` and `modapi_guikit`). It also stores a copy of the `modapi_postinit` script into a fourth post init script, for the post-processing scripts to inject into the dedicated server.
Searches for constructors and appends them to the `ModAPI.hooks._rippedConstructors` dictionary.
Extracts and hooks into all class methods, storing their type (`instance` or `static`) into `ModAPI.hooks._rippedMethodTypeMap`, and storing the method itself in `ModAPI.hooks.methods`
Finds static class variables, and build a proxy object for them, to allow for readwrite access even though there is no way to expose their context. The keys for the static properties of a specific class are stored under `ModAPI.hooks._rippedStaticIndexer` and the proxy objects are stored in `ModAPI.hooks._rippedStaticProperties`.
Finally, it adds references (not hooks, as they would tank performance) to all TeaVM internal methods, most importantly `$rt_str` and `$rt_ustr`, used for interaction with jcl strings.
## Postprocessing
The post processor is much simpler than the preprocessor, but it effectively uses the data in `ModAPI.hooks` to create a (mostly) backwards compatible `ModAPI` global.
@@ -0,0 +1,53 @@
# Compiling Eaglercraft with support for EFI
In recent updates of eaglercraft, compiling for EaglerForgeInjector has become a great deal more complicated. To enable reflection and disable obfuscation, follow these steps once you have an EaglercraftX workspace set up:
1. In any files named `build.gradle`, set the `obfuscate` property to `false`.
2. In any files named `build.gradle`, find any code that looks like this:
```javascript
tasks.named("generateJavaScript") {
doLast {
// NOTE: This step may break at any time, and is not required for 99% of browsers
def phile = file(folder + "/" + name)
def dest = phile.getText("UTF-8")
def i = dest.substring(0, dest.indexOf("=\$rt_globals.Symbol('jsoClass');")).lastIndexOf("let ")
dest = dest.substring(0, i) + "var" + dest.substring(i + 3)
def j = dest.indexOf("function(\$rt_globals,\$rt_exports){")
dest = dest.substring(0, j + 34) + "\n" + file(folder + "/ES6ShimScript.txt").getText("UTF-8") + "\n" + dest.substring(j + 34)
phile.write(dest, "UTF-8")
}
}
```
and delete it.
3. Inside of the `src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/` folder, create a new file called `ForceReflection.java`, with these contents:
```java
package net.lax1dude.eaglercraft.v1_8.internal.teavm;
public class ForceReflection {
public static Object myObject;
public static Object forceInit(Class iClass) {
myObject = new ReflectiveClass();
try {
myObject = iClass.newInstance();
} catch (Exception e) {
// TODO: handle exception
}
return myObject;
}
public static class ReflectiveClass {
}
}
```
4. In the same folder, edit `MainClass.java` edit the start of the `main(String[] args)` method to look like this:
```java
public static void main(String[] args) {
ForceReflection.forceInit(ForceReflection.class);
if(args.length == 1) {
//... rest of method
```
5. Finally, build an offline download by using `CompileJS.bat`/`CompileJS.sh` and then `MakeOfflineDownload.bat`/`MakeOfflineDownload.sh`.
6. You can then upload the `EaglercraftX_1.8_Offline_en_US.html` into EaglerForgeInjector.
+15
View File
@@ -0,0 +1,15 @@
## eaglercraftXOpts and search parameters
### noInitialModGui
- `processed.html?noInitialModGui=true`
or inside eaglercraftXOpts
disables the mod gui display on startup
### Adding mods
Set eaglercraftXOpts.Mods to an array of mod urls.
You can also use search parameters, eg:
- `processed.html?mod=https://example.com/mod.js`
- `processed.html?mod=https://example.com/mod.js&mod=https://example.com/mod2.js`
+15
View File
@@ -0,0 +1,15 @@
# EaglerForgeInjector
EaglerForge Injector is a tool that uses regular expressions to attach itself to internal code inside of raw EaglercraftX offline downloads (sounds easy, isn't at all).
### Documentation fragments
[Injector Architecture](architecture.md)
[TeaVM quirks](quirks.md)
[Modding tutorials](tutorials/index.md)
[Modding API documentation](apidoc/index.md)
[Compiling the client for EaglerForgeInjector](compiling_client.md)
[eaglercraftXopts and search parameters](config.md)
+31
View File
@@ -0,0 +1,31 @@
## TeaVM Quirks and Caveats
When TeaVM compiles code, it sometimes does strange things.
#### Property Suffixes
TeaVM will add suffixes to some variables, seemingly randomly. An example is the property `inGround` of any entity. When accessing this on the `ModAPI.player.fishEntity` object, TeaVM has renamed it to `inGround2`. Can be mitigated with `ModAPI.util.getNearestProperty`, or, even better, using a corrective version of ModAPI.player.
#### Collapsing Methods
When I was trying to hook into the server-side processing of chat messages, I found that chat packets were handled by the method `processChatMessage` in `NetHandlerPlayServer`. However, in the compiled JavaScript, this method no longer exists. This is because it is only used once, in the `processPacket` method of `C01PacketChatMessage`. TeaVM automatically saw this, and collapsed one method into the other.
#### Dedicated Server Not Responding / Client Not Responding
Incorrectly patching methods with ModAPI.hooks (such as returning `false` instead of `0`, or a javascript string without using `ModAPI.str()`) will effectively cause the memory stack to implode, along with all crash handlers. I came across this when I was using the `processcommand` event with preventDefault set to true. I didn't return any value when patching methods for the event being `preventDefault`ed, when the output expected was a java boolean (`0`/`1`). This would cause the dedicated server to freeze/lock up, without triggering any form of crash.
Update 13/09/2024:
Any form of incorrect data type, even passing the wrong values, can cause this sort of hang. I encountered this when trying to set a block in the world to any form of wood or leaf block, without adding iproperties to the tree type.
Update 13/09/2024:
Calling methods while the TeaVM thread is in a critical transition state (see `ModAPI.util.isCritical()`) will shift the call stack, cause methods to access the incorrect values at runtime, and also cause the stack to implode. Gotta love TeaVM.
Update 22/09/2024:
See Asynchronous Code
Update 4/10/2024:
@Async issue solved, see [PromisifyDocumentation](apidoc/promisify.md)
#### TeaVM thread suspension/resumption
TeaVM allows for writing asynchronous callbacks, which eaglercraft uses for file operations and downloading from URIs. However, when a method that makes use of an async callback gets run from ModAPI, it triggers a stack implosion due to mismatches in value types upon return (as well as a whole other myriad of symptoms). Currently this is not supported by ModAPI, and it will take some time until it will be. In the meanwhile, avoid using constructors or methods that access a file or use other asynchronous apis. Examples:
- Constructing an EntityPlayerMP
- Setting blocks in the world in some occasions
Potential workarounds: This isn't confirmed yet, but there is a probable chance that overriding or patching methods in classes like VFile2 or PlatformFilesystem is a viable workaround. (22/09/2024).
I'll be verifying this is the future and if it is possible, releasing a library for it. (the maybe-library is going to be called AsyncSink if it will exist)
@@ -0,0 +1 @@
## Coming Soon / It's not done yet.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,127 @@
## Custom Item Tutorial with ModAPI
This tutorial will cover making custom items with ModAPI. It is recommended that you follow the [custom block tutorial](custom_block.md) first, as this tutorial is more fast-paced. The custom item we'll be adding will set the player's velocity to a random value when used, to demonstrate how methods can be overridden.
We'll begin with a constant item texture encoded into a data URI, as well as some metadata.
```javascript
(function CustomItemMod() {
const itemTexture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAKZJREFUOE9j/P//PxMDBIBoEP6HREOl4PLIciA2AyPIgMcM//7KgvWSDJjBBpx9/+YvJzc3Sbq12DhB6sEGsJ19/+YnmQawYhigzc7FcPXnN4KugbqAHWQAy9n3b34T4wJkw6EGYLqAoNVQBWS5ANlwZBfAvUCs/0EGkW0AzBKqGoCSDgh5A80F2KMRpAgfAKUT6kcjsfEPUycmKMQgy8AETkgUZWcAS3CPIf4oSPsAAAAASUVORK5CYII=";
ModAPI.meta.title("Custom Item Mod");
ModAPI.meta.icon(itemTexture);
ModAPI.meta.description("it's a custom item. what more do you want");
ModAPI.meta.credits("By <author_name>");
})();
```
Add a function that will contain the code to register the item called `CustomItem`. Inside it we'll do something really similar to the custom blocks tutorial, where we'll define a custom item class, and then register it (or, if on the server, wait until the `bootstrap` event fires). The reason it's contained in a function is to make the job of running the same code on the server and client easier.
```javascript
(function CustomItemMod() {
//...
function CustomItem() {
var creativeMiscTab = ModAPI.reflect.getClassById("net.minecraft.creativetab.CreativeTabs").staticVariables.tabMisc; //chuck it in the miscellaneous category ig
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item"); //Get the item class
var itemSuper = ModAPI.reflect.getSuper(itemClass, (x) => x.length === 1); //Get the super() function of the item class that has a length of 1
function CustomItem() {
itemSuper(this); //Use super function to get block properties on this class.
this.$setCreativeTab(creativeMiscTab); //Set the creative tab of the item to be the misc tab
}
ModAPI.reflect.prototypeStack(itemClass, CustomItem); // ModAPI equivalent of `extends` in java
CustomItem.prototype.$onItemRightClick = function ($itemstack, $world, $player) { //example of how to override a method
//use ModAPI.util.wrap to create a proxy of the player and the world without $ prefixes on the properties and methods
var player = ModAPI.util.wrap($player);
var world = ModAPI.util.wrap($world);
if (!world.isRemote) { //If we are on the server
// Math.random() returns a number from 0.0 to 1.0, so we subtract 0.5 and then multiply by 2 to make it become -1.0 to 1.0 instead
player.motionX += (Math.random() - 0.5) * 3;
player.motionZ += (Math.random() - 0.5) * 3;
player.motionY += Math.random() * 1.5; // gravity is a thing, so no negative numbers here otherwise it'll be boring
}
return $itemstack;
}
// Internal registration function. This will be used to actually register the item on both the client and the server.
function internal_reg() {
// Construct an instance of the CustomItem, and set it's unlocalized name (translation id)
var custom_item = (new CustomItem()).$setUnlocalizedName(
ModAPI.util.str("custom_item")
);
//Register it using ModAPI.keygen() to get the item id.
itemClass.staticMethods.registerItem.method(ModAPI.keygen.item("custom_item"), ModAPI.util.str("custom_item"), custom_item);
//Expose it to ModAPI
ModAPI.items["custom_item"] = custom_item;
//return the instance.
return custom_item;
}
//if the item global exists (and it will on the client), register the item and return the registered instance.
if (ModAPI.items) {
return internal_reg();
} else {
//Otherwise attatch the registration method to the bootstrap method.
ModAPI.addEventListener("bootstrap", internal_reg);
}
}
})();
```
Now let's run the `CustomItem` function on the server and the client, and then use [AsyncSink](../../examplemods/AsyncSink.js) to create an in-memory resource pack to load item textures and models!
```javascript
(function CustomItemMod() {
const itemTexture = "...";
ModAPI.meta.title("Custom Item Mod");
ModAPI.meta.icon(itemTexture);
ModAPI.meta.description("it's a custom item. what more do you want");
ModAPI.meta.credits("By <author_name>");
function CustomItem() {
// ...
}
// Run the function when the dedicated server loads.
ModAPI.dedicatedServer.appendCode(CustomItem);
// Run the function on the client
var custom_item = CustomItem();
ModAPI.addEventListener("lib:asyncsink", async () => {
ModAPI.addEventListener("lib:asyncsink:registeritems", (renderItem)=>{
renderItem.registerItem(custom_item, ModAPI.util.str("custom_item"));
});
AsyncSink.L10N.set("item.custom_item.name", "Cool Custom Item");
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/item/custom_item.json", JSON.stringify(
{
"parent": "builtin/generated",
"textures": {
"layer0": "items/custom_item"
},
"display": {
"thirdperson": {
"rotation": [ -90, 0, 0 ],
"translation": [ 0, 1, -3 ],
"scale": [ 0.55, 0.55, 0.55 ]
},
"firstperson": {
"rotation": [ 0, -135, 25 ],
"translation": [ 0, 4, 2 ],
"scale": [ 1.7, 1.7, 1.7 ]
}
}
}
));
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/items/custom_item.png", await (await fetch(
itemTexture
)).arrayBuffer());
});
})();
```
That's it! Upload your completed mod, run `.reload_tex` in chat in a singleplayer world and use your new item!\
[completed mod]()
@@ -0,0 +1,90 @@
## Disable All Particles
Particles in minecraft are really laggy, and there's a large chance you may want to disable them to boost your FPS when breaking blocks.
Let's look through the Eaglercraft 1.8 source code to find where particles are rendered. We can do this with a global search for `particle`. You'll find a lot of hits in the `EffectRenderer` class in the `net.minecraft.client.particle` package. We methods we'll want to patch are:
- `renderParticles`
- `addEffect`
- `addBlockDestroyEffects`
- `hasParticlesInAlphaLayer`
For the first 3 methods, you can see that they are defined something like:
```java
public void renderParticles() {
// render particles code.
}
```
The `void` in `public void` means that it does not expect a return value.
Using [`ModAPI.util.getMethodFromPackage`](../apidoc/utils.md) we can find the compiled method name, and look for it in [`ModAPI.hooks.methods`](../apidoc/hooks.md#property-modapihooksmethods).
```javascript
(function NoParticles() {
//Basic, boilerplate code
ModAPI.meta.title("No Particles");
ModAPI.meta.description("Disables all particles in game");
ModAPI.meta.credits("By <developer name>");
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "renderParticles")
] = function () {}; //Override renderParticles in EffectRenderer to an empty function that does nothing.
})();
```
We can also do this for `addEffect` and `addBlockDestroyEffects`.
```javascript
(function NoParticles() {
//Basic, boilerplate code
ModAPI.meta.title("No Particles");
ModAPI.meta.description("Disables all particles in game");
ModAPI.meta.credits("By <developer name>");
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "renderParticles")
] = function () {}; //Override renderParticles in EffectRenderer with an empty function that does nothing.
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "addEffect")
] = function () {}; //Override addEffect in EffectRenderer with an empty function that does nothing.
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "addBlockDestroyEffects")
] = function () {}; //Override addBlockDestroyEffects in EffectRenderer with an empty function that does nothing.
})();
```
For `hasParticlesInAlphaLayer`, it doesn't use `void`, but instead a `boolean`.
```java
public boolean hasParticlesInAlphaLayer() {
// hasParticlesInAlphaLayer code.
}
```
When TeaVM translates booleans, it converts booleans to integers:
- `false` turns into `0`
- `true` turns into `1`
So when we override `hasParticlesInAlphaLayer`, we'll need to return a `0` or a `1`. Since we want the game to think that there aren't any particles in the alpha layer, we'll return `0` (false).
```javascript
(function NoParticles() {
//Basic, boilerplate code
ModAPI.meta.title("No Particles");
ModAPI.meta.description("Disables all particles in game");
ModAPI.meta.credits("By <developer name>");
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "renderParticles")
] = function () {}; //Override renderParticles in EffectRenderer with an empty function that does nothing.
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "addEffect")
] = function () {}; //Override addEffect in EffectRenderer with an empty function that does nothing.
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "addBlockDestroyEffects")
] = function () {}; //Override addBlockDestroyEffects in EffectRenderer with an empty function that does nothing.
ModAPI.hooks.methods[
ModAPI.util.getMethodFromPackage("net.minecraft.client.particle.EffectRenderer", "hasParticlesInAlphaLayer")
] = function () {return 0}; //Override hasParticlesInAlphaLayer in EffectRenderer with a function that returns 0.
})();
```
@@ -0,0 +1,71 @@
## /hat with ModAPI
/hat is a common server-side plugin that lets you put any block/item on your head. This tutorial will explain how to register a server-side command, construct a packet, and send it to a player.
[`S09PacketHeldItemChange` constructors](https://nurmarvin.github.io/Minecraft-1.8-JavaDocs/net/minecraft/network/play/server/S09PacketHeldItemChange.html)
As always, start with the basic boilerplate IIFE with credits:
```javascript
(function HatMod() {
ModAPI.meta.title("Hat Mod");
ModAPI.meta.description("Use /hat to put anything on your head.");
ModAPI.meta.credits("By <author_name>");
})();
```
In order to add a server side command, we need to:
- Write a function to run on the server.
- In this function, we'll add a listener to the [`processcommand` event](../apidoc/events.md#server-side-events)
- We'll check if the command is `/hat`
- If it is, we'll swap their head and current hand inventory slots, and send a network packet.
- Finally, the function from step 1 is thrown into [`ModAPI.dedicatedServer.appendCode`](../apidoc/dedicatedserver.md)
Here's the completed code:
```javascript
(function HatMod() {
ModAPI.meta.title("Hat Mod");
ModAPI.meta.description("Use /hat to put anything on your head.");
ModAPI.meta.credits("By <author_name>");
ModAPI.dedicatedServer.appendCode(function serverSideCode() {
// Find the constructor for the held item change packet that has only one argument.
// This will be used to notify the client that their hotbar has been updated.
// Reference: https://nurmarvin.github.io/Minecraft-1.8-JavaDocs/net/minecraft/network/play/server/S09PacketHeldItemChange.html
var S09PacketHeldItemChange_Constructor = ModAPI.reflect.getClassByName("S09PacketHeldItemChange").constructors.find(x => x.length === 1);
//Add an event listener for when a command is processed on the server.
ModAPI.addEventListener("processcommand", (event) => {
// If the command starts with /hat
if (event.command.toLowerCase().startsWith("/hat")) {
// Exit if the sender isn't a player
if (
!ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP").instanceOf(
event.sender.getRef()
)
) {
return
};
// Get the current held item
var heldItem = event.sender.inventory.getCurrentItem();
// Get the contents of the helmet slot
var armorItem = event.sender.inventory.armorInventory[3];
// Get the inventory index of the current held item
var hotbarIdx = event.sender.inventory.currentItem;
// Set the helmet slot to heldItem.getRef() (raw java object) if heldItem exists, otherwise set it to null
event.sender.inventory.armorInventory[3] = heldItem ? heldItem.getRef() : null;
// Set the hotbar slot to the original value of the helmet slot if it has a value, otherwise set it to null
event.sender.inventory.mainInventory[hotbarIdx] = armorItem ? armorItem.getRef() : null;
// Make a packet to notify the client that the selected hotbar slot has been updated.
event.sender.playerNetServerHandler.sendPacket(makePacketItemChange(hotbarIdx));
// Prevent the 'unknown command' error
event.preventDefault = true;
}
}
});
})();
```
@@ -0,0 +1,38 @@
## Mod tutorials with ModAPI
### Beginner
Prerequisites:
- Basic knowledge of JavaScript
- A good code editor (recommended: https://vscode.dev)
Tutorials:
- [Step Hack](step.md)
- [Spider Hack](spider.md)
- [VClip Exploit](vclip.md)
### Intermediate
Prerequisites:
- Intermediate knowledge of JavaScript (functions, arrays, promises, callbacks, keys and values in objects)
- A good code editor (recommended: https://vscode.dev)
- A copy of the eaglercraft workspace (optional, get it at: https://git.eaglercraft.rip/eaglercraft/eaglercraft-1.8-workspace)
Tutorials:
- [Disable All Particles](disable_all_particles.md)
- [Slippery Mod](slippery.md)
- [/hat mod](hat.md)
- [/spawnxp command](spawnxp.md)
### Advanced
Prerequisites:
- Advanced knowledge of JavaScript (prototypes)
- A good code editor (recommended: https://vscode.dev)
- A copy of the eaglercraft workspace (get it at: https://git.eaglercraft.rip/eaglercraft/eaglercraft-1.8-workspace)
- Your EaglerForgeInjector processed.html opened in an editor (optional)
Tutorials:
- [Custom Blocks](custom_block.md)
- [Custom Items](custom_item.md)
- [Timescale Command](timescale.md)
@@ -0,0 +1,109 @@
## Slippery Mod with ModAPI
In this tutorial you will learn how to modify properties of blocks, and run the code that does this on both the dedicated server and the client.
We'll begin with the basic boilerplate mod code:
```javascript
(function SlipperyMod() {
ModAPI.meta.title("Slippery Mod");
ModAPI.meta.description("Makes everything turn into ice.");
ModAPI.meta.credits("By <author_name>");
//New code will go here!
})();
```
Let's write the client side part of the code first.
- We'll get the keys for the ModAPI.blocks object (ids of each block) using [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
- Then, we'll loop over those keys, and modify their respective block to be as slippery as ice.
```javascript
var blockKeys = Object.keys(ModAPI.blocks);
blockKeys.forEach(key => { //for each key (block id)
//make sure the block has a slipperiness property
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
if(ModAPI.blocks[key]?.slipperiness) {
ModAPI.blocks[key].slipperiness = 0.98; //Set the slipperiness value of the block at that key to 0.98
}
});
```
Your code should now look like this:
```javascript
(function SlipperyMod() {
ModAPI.meta.title("Slippery Mod");
ModAPI.meta.description("Makes everything turn into ice.");
ModAPI.meta.credits("By <author_name>");
var blockKeys = Object.keys(ModAPI.blocks);
blockKeys.forEach(key => {
if(ModAPI.blocks[key]?.slipperiness) {
ModAPI.blocks[key].slipperiness = 0.98;
}
});
})();
```
Your code should now look like this:
```javascript
(function SlipperyMod() {
ModAPI.meta.title("Slippery Mod");
ModAPI.meta.description("Makes everything turn into ice.");
ModAPI.meta.credits("By <author_name>");
var blockKeys = Object.keys(ModAPI.blocks);
blockKeys.forEach(key => {
if(ModAPI.blocks[key]?.slipperiness) {
ModAPI.blocks[key].slipperiness = 0.98;
}
});
//dedicated server code will be added here
})();
```
Currently this only runs on the client meaning in singleplayer, when you throw an item or punch a sheep, it still won't slide. Only you will.
We'll have to duplicate the code to run on the server using [`ModAPI.dedicatedServer`](../apidoc/dedicatedserver.md).
We also have to run the code after the `serverstart` event, as on the server, `ModAPI.blocks` is only created when it is needed.
```javascript
ModAPI.dedicatedServer.appendCode(function () {
//Code in here cannot reference outside variables.
ModAPI.addEventListener("serverstart", function () {
var blockKeys = Object.keys(ModAPI.blocks);
blockKeys.forEach(key => {
if(ModAPI.blocks[key]?.slipperiness) {
ModAPI.blocks[key].slipperiness = 0.98;
}
});
});
});
```
let's add this to the final mod, and we'll be finished!
```javascript
(function SlipperyMod() {
ModAPI.meta.title("Slippery Mod");
ModAPI.meta.description("Makes everything turn into ice.");
ModAPI.meta.credits("By <author_name>");
var blockKeys = Object.keys(ModAPI.blocks);
blockKeys.forEach(key => {
if(ModAPI.blocks[key]?.slipperiness) {
ModAPI.blocks[key].slipperiness = 0.98;
}
});
ModAPI.dedicatedServer.appendCode(function () {
//Code in here cannot reference outside variables.
ModAPI.addEventListener("serverstart", function () {
var blockKeys = Object.keys(ModAPI.blocks);
blockKeys.forEach(key => {
if(ModAPI.blocks[key]?.slipperiness) {
ModAPI.blocks[key].slipperiness = 0.98;
}
});
});
});
})();
```
@@ -0,0 +1,67 @@
## /spawnxp command
This tutorial will cover spawning in entities using the [`ModAPI.promisify()`](../apidoc/promisify.md) API.
As usual, we'll start with the boilerplate:
```javascript
(function SpawnXPMod() {
ModAPI.meta.title("Spawn XP");
ModAPI.meta.description("Adds a /spawnxp command.");
ModAPI.meta.credits("By <author_name>");
//future code
})();
```
We'll move context to the server, and add a command listener, and ensure the sender is a player:
```javascript
PluginAPI.dedicatedServer.appendCode(function () { //Run this code on the server
PluginAPI.addEventListener("processcommand", (event) => { //Command processing event
if (
!ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP")
.instanceOf(event.sender.getRef())
) {
return;
}
});
});
```
Next, we'll check that the command is /spawnxp. If it is, we'll get the current dimension of the player, and spawn an XP orb at the sender's position. To construct the XP orb, we'll get the `EntityXPOrb` class and get the [first constructor](https://nurmarvin.github.io/Minecraft-1.8-JavaDocs/net/minecraft/entity/EntityXPOrb.html)
```javascript
PluginAPI.dedicatedServer.appendCode(function () { //Run this code on the server
PluginAPI.addEventListener("processcommand", (event) => { //Command processing event
if (
!ModAPI.reflect.getClassById("net.minecraft.entity.player.EntityPlayerMP") //If it isn't a player, exit the method
.instanceOf(event.sender.getRef())
) {
return;
}
if (event.command.toLowerCase().startWith("/spawnxp")) {
const world = event.sender.getServerForPlayer(); //get the current dimension
const senderPos = event.sender.getPosition(); //get the player's current position
const EntityXP = ModAPI.reflect.getClassByName("EntityXPOrb"); // Get the entity xp orb class
const xporb = EntityXP.constructors[0](world.getRef(), senderPos.getX(), senderPos.getY(), senderPos.getZ(), 10); //Construct the first constructor, with arguments, World, x, y, z, xp value
//Get the spawn entity in world method
var spawnEntityInWorldMethod = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.world.World", "spawnEntityInWorld")];
//Because this method reads and writes data to chunks, it tries to save and load the eaglercraft state, which won't work if eaglercraft is also running its own code.
//To work around this issue, use ModAPI.promisify() to convert the method into one that returns a promise
spawnEntityInWorldMethod = ModAPI.promisify(spawnEntityInWorldMethod);
//we can now use the spawnEntityInWorld method
//wherever you see getRef(), it means to retrieve the raw, untouched data that TeaVM can use.
spawnEntityInWorldMethod(world.getRef(), xporb).then(result => {
// Get the chat component class
const ChatComponentTextClass = ModAPI.reflect.getClassById("net.minecraft.util.ChatComponentText");
// Construct the chat component and send it to the client.
event.sender.addChatMessage(ChatComponentTextClass.constructors[0](ModAPI.util.str("An xp orb has been spawned!")));
});
//Stop the unknown command error
event.preventDefault = true;
}
});
});
@@ -0,0 +1,41 @@
## Spider Hack with ModAPI
A spider hack allows players to climb up any wall like a spider.
Start by creating a new file in your code editor. Save it to a folder on your device, ensuring that the file extension is `.js`.
The spider hack has a lot of similarities to the step hack, so lets copy the step hack and rename the `stepHackUpdateCode` function to `spiderHackUpdateCode`:
```javascript
ModAPI.require("player");
function spiderHackUpdateCode() {
//We will add code here.
}
ModAPI.addEventListener("update", spiderHackUpdateCode);
```
Most spider hacks work by checking if the player is walking into a wall, and then setting their vertical velocity to a constant amount (usually `0.2`, for parity with ladders).
Let's start by checking if the player is walking into a wall, by adding an if statement inside the `spiderHackUpdateCode` function:
```javascript
if (ModAPI.player.isCollidedHorizontally) {
}
```
Now, let's set the player's vertical velocity:
```javascript
if (ModAPI.player.isCollidedHorizontally) {
ModAPI.player.motionY = 0.2; //Feel free to change this value to something bigger, smaller or even negative.
}
```
Time to see the final code:
```javascript
ModAPI.require("player");
function spiderHackUpdateCode() {
if (ModAPI.player.isCollidedHorizontally) {
ModAPI.player.motionY = 0.2; //Feel free to change this value to something bigger, smaller or even negative.
}
}
ModAPI.addEventListener("update", spiderHackUpdateCode);
```
@@ -0,0 +1,33 @@
## Step Hack with ModAPI
A step hack allows a player to walk up full blocks (or more) as if they were slabs.
Start by creating a new file in your code editor. Save it to a folder on your device, ensuring that the file extension is `.js`.
Let's start by requiring the player. This will allow us to change attributes on the player:
```javascript
ModAPI.require("player");
```
Now, we have to detect when the player in a world. This will be done with the `update` event, which runs every tick while the player is in a world. In EaglerForge's ModAPI, to run code on an event, you have to create a function. Then, you register the function to an event.
```javascript
ModAPI.require("player");
function stepHackUpdateCode() {
//We will add code here.
}
ModAPI.addEventListener("update", stepHackUpdateCode);
```
Inside this method, lets change the player's `stepHeight`, which controls how high they can step. By default this is `0.5`, to alow players to walk up slabs or stairs. I'll change it to `2` for demonstration purposes. You can also try any other number, like `0`, `6`, etc.
```javascript
ModAPI.require("player");
function stepHackUpdateCode() {
ModAPI.player.stepHeight = 2;
}
ModAPI.addEventListener("update", stepHackUpdateCode);
```
Now, to load this mod, open your EaglerForge build, and in the start screen select `Upload Mod (.js)`. Upload the mod you created, and you should now be able to walk up two block tall pillars, or more depending on what `stepHeight` you selected.
Disclaimer: using this on servers may get you banned/kicked for cheating!
@@ -0,0 +1,103 @@
## Timescale Mod with ModAPI
This mod will cover adding a new command that controls the speed that Eaglercraft runs at. This tutorial assumes that you have some knowledge on how to use [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) in JavaScript.
Let's get our basic template code down:
```javascript
(function TimescaleCommand() {
ModAPI.meta.title("Timescale Command");
ModAPI.meta.description("use /timescale to control time");
ModAPI.meta.credits("By <author_name>");
})()
```
Our mod is going to be split into 2 distinct parts: client-side and server-side. The client will modify `ModAPI.mc.timer.timerSpeed` when a `/timescale` command is sent, while the server will set the timescale to a global variable, and then modify `net.minecraft.server.MinecraftServer`'s `getCurrentTimeMillis()` to change the rate calculations happen at on the server.\
\
However, there is a slight logistical problem: the server gets the time in milliseconds as a JavaScript [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), which means we can't just multiply it by a number, we have to either multiply or divide it by another BigInt.
```javascript
var x = 1n * 1.0; //TypeError
var x = 1n * 1n; //Success
```
To allow us to both speed up and slow down time, we'll need to check if the speed inputted is greater or equal to 1. If it is, we round it and then convert it to a `BigInt`, which we'll store on the `globalThis` object. If it's less we'll need to find the speed to the power of -1, or `1 / speed`. We can then round this value and convert that to a `BigInt` to store on `globalThis`. We'll also set `globalThis.timeScaleDividing` to `true`, to signal to replaced `getCurrentTimeMillis()` to divide by the `BigInt` speed factor instead of multiply.\
\
Finally, due to our `BigInt` rounding shenanigans on the server, we have to replicate the rounding inaccuracy on the client.\
\
Let's implement the client side part.
```javascript
(function TimescaleCommand() {
ModAPI.meta.title("Timescale Command");
ModAPI.meta.description("use /timescale to control time");
ModAPI.meta.credits("By <author_name>");
ModAPI.addEventListener("sendchatmessage", (event) => { // before a message gets sent to the server
if (event.message.toLowerCase().startsWith("/timescale")) { //if it is the timescale command
var speed = parseFloat(event.message.split(" ")[1]); //get the part of the message after the space
if (!speed) { //If it doesn't exist, set it to 1.
speed = 1;
} else { //If it does exist:
if (speed < 1) { //When the speed is less than 1, round the denominator (1 over x)
speed = 1 / Math.round(1 / speed);
} else {
// When the speed is greater or equal to 1, round the numerator (x over 1)
speed = Math.round(speed);
}
// Set the speed
ModAPI.mc.timer.timerSpeed = speed;
}
// Log the speed to chat
ModAPI.displayToChat("[Timescale] Set world timescale to " + speed.toFixed(2) + ".");
}
});
})()
```
Now for the serverside part.
```javascript
(function TimescaleCommand() {
//...
ModAPI.dedicatedServer.appendCode(function () { // Run on the server
globalThis.timeScale = 1n; // Initialize globalThis.timeScale
globalThis.timeScaleDividing = false; // Initialize globalThis.timeScaleDividing
ModAPI.addEventListener("processcommand", (event) => { // when the server receives a command
if (event.command.toLowerCase().startsWith("/timescale")) { // if it is a timescale command
var speed = parseFloat(event.command.split(" ")[1]); // get the second part of the command (the speed of time)
if (!speed) { // If it doesn't exist, set it to 1.
globalThis.timeScale = 1n;
globalThis.timeScaleDividing = false;
} else { // If it does exist:
if (speed < 1) {
// When the speed is less than 1, round the denominator (1 over x)
// And enable division mode
globalThis.timeScaleDividing = true;
globalThis.timeScale = BigInt(Math.round(1 / speed));
} else {
// When the speed is greater or equal to 1, round the numerator (x over 1)
// And disable division mode
globalThis.timeScaleDividing = false;
globalThis.timeScale = BigInt(Math.round(speed));
}
}
if (ModAPI.server) { //If the server is initialized
//Bump the current time forward so the server doesn't try to play catch-up
ModAPI.server.currentTime = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.server.MinecraftServer", "getCurrentTimeMillis")]();
}
//Prevent the command not found error from appearing
event.preventDefault = true;
}
});
//Monkey patch the getCurrentTime function.
const original_getCurrentTime = ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.server.MinecraftServer", "getCurrentTimeMillis")];
ModAPI.hooks.methods[ModAPI.util.getMethodFromPackage("net.minecraft.server.MinecraftServer", "getCurrentTimeMillis")] = function () {
if (globalThis.timeScaleDividing) { //If we are in divide mode
return original_getCurrentTime() / globalThis.timeScale; //Return the current time divided by the time scale
} else {
return original_getCurrentTime() * globalThis.timeScale; //Else, return the current time multiplied by the time scale
}
};
});
})()
```
@@ -0,0 +1,82 @@
## VClip Exploit with ModAPI
Most minecraft servers have an exploit where you can trick the server into clipping you up to 10 blocks up or down through ceilings or floors.
### Part 1: Setup
Make a new file in your editor, and call it something like `vclip.js`
First, let's setup a basic [IIFE (immediately invoked function expression)](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) around our mod code. This ensures that we don't leak variables that can interfere wiht other mods.\
Example of the issue: if mod A and mod B both use `var myVariable = 0`, the value for myVariable will get overwritten.
```javascript
(function VClipExploit() {
//Future code here
})(); //We define a function, called VClipExploit, which we wrap in parantheses () and immediately execute.
```
This allows us to use variables without worrying about mod compatibility, as variables are scoped to the function.
\
Then, we'll add some basic [metadata](../apidoc/meta.md) for the mod loader (note that this is optional, but makes the mod look a lot better in the GUI once the game is loaded.)\
We'll also require the player, so the `ModAPI.player` global is generated.
```javascript
(function VClipExploit() {
ModAPI.meta.title("VClip Exploit");
ModAPI.meta.description("todo: add description.");
ModAPI.meta.credits("By author_name");
ModAPI.require("player");
})();
```
### Part 2: VClip Exploit
Our VClip exploit will be triggered by a client-side command, `.vclip <amount>`.
Let's start off with the vclip command by adding an event listener to when the player sends a chat message:
```javascript
(function VClipExploit() {
ModAPI.meta.title("VClip Exploit");
ModAPI.meta.description("todo: add description.");
ModAPI.meta.credits("By author_name");
ModAPI.require("player");
ModAPI.addEventListener("sendchatmessage", (ev) => {
// handler code here
});
})();
```
In this event handler, we can get the content of the message by using `event.message`, process it, and check whether it is using the `.vclip` command. We can do this by casting the string to lowercase, using [`string.toLowerCase()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase), checking if the result of that is a call to the `.vclip` command using [`string.startsWith()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith).
If it is a call to the VClip command, we can use [`string.split(" ")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) to get all the arguments, find the vclip amount, and change the player's position.
```javascript
(function VClipExploit() {
ModAPI.meta.title("VClip Exploit");
ModAPI.meta.description("todo: add description.");
ModAPI.meta.credits("By author_name");
ModAPI.require("player");
ModAPI.addEventListener("sendchatmessage", (ev) => {
var string = ev.message.toLowerCase(); //Get the lower case version of the command
if (string.startsWith(".vclip")) { //does the chat message start with .vclip?
ev.preventDefault = true; //we don't want this being sent into chat as a message
var yOffset = 1; //The offset on the y axis
var args = string.split(" ");
if (args[1]) { //If the second argument to .vclip exists (the vclip <amount>)
yOffset = parseFloat(args[1]) || 0; //Convert the second argument into a number. We use || to replace NaN (invalid numbers) with 0. Then, store it into the y offset.
} //This allows you to just type .vclip to clip upwards 1 block.
ModAPI.player.setPosition( //This function sets the players position to an XYZ coordinate
ModAPI.player.posX,
ModAPI.player.posY + yOffset, //All XYZ elements are the same, except we add the yOffset variable to the y axis.
ModAPI.player.posZ
);
//Finally, log the amount we've VClipped into the chat.
ModAPI.displayToChat("[VClip] VClipped " + yOffset + " blocks.");
}
});
})();
```