-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHypixelModAPITweaker.java
More file actions
225 lines (203 loc) · 7.73 KB
/
HypixelModAPITweaker.java
File metadata and controls
225 lines (203 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package net.hypixel.modapi.tweaker;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.CoreModManager;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
/**
* A tweaker class to automatically load the hypixel mod api while resolving conflicts
* from multiple mods providing a copy. This saves users from having to download the
* mod api separately.
*/
public class HypixelModAPITweaker implements ITweaker {
private static Logger LOGGER = LogManager.getLogger();
public static final String VERSION_NAME;
public static final long VERSION;
static {
// Load version information from the .properties generated by the gradle task generateVersionInfo
Properties properties = new Properties();
try {
properties.load(HypixelModAPITweaker.class.getResourceAsStream("hypixel-mod-api-bundled.properties"));
} catch (IOException e) {
LOGGER.error("Could not load version information for bundled hypixel mod API", e);
}
VERSION_NAME = properties.getProperty("version", "0.0.0.0");
LOGGER.info("Loaded bundled hypixel mod API version as {}", VERSION_NAME);
String[] versionComponents = VERSION_NAME.split("\\.");
assert versionComponents.length == 4;
// We pack each of the four version components into a long.
// To do so we use the biggest number that can fit 4 times into a long:
//noinspection ConstantValue
assert Math.pow(10000, 4) < Long.MAX_VALUE;
long version = 0;
for (int i = 0; i < 4; i++) {
version *= 10000;
version += Long.parseLong(versionComponents[i]);
}
VERSION = version;
LOGGER.info("Loaded bundled hypixel mod API numeric version as {}", VERSION);
}
public static final String BUNDLED_JAR_NAME = "HypixelModAPI-" + VERSION_NAME + ".jar";
/**
* This is the key which is used in the {@link Launch#blackboard} to perform
* version negotiation.
*
* @see #getBlackboardVersion()
* @see #offerVersionToBlackboard()
*/
public static final String VERSION_KEY = "net.hypixel.mod-api.version:1";
private boolean hasOfferedVersion = false;
/**
* Get the current version declared on the blackboard.
* The blackboard allows us to store arbitrary values. We store an int indicating the max version installed.
*
* @see #VERSION_KEY
*/
public static long getBlackboardVersion() {
Object blackboardVersion = Launch.blackboard.get(VERSION_KEY);
// In case nobody has declared a version on the blackboard yet, we return an incredibly outdated past version
if (blackboardVersion == null) return Long.MIN_VALUE;
// In case we later switch to another version format we declare any non-integer as an incredibly advanced future version
if (!(blackboardVersion instanceof Long)) return Long.MAX_VALUE;
return (Long) blackboardVersion;
}
/**
* Inject our API jar into forge if we are the highest available version.
*
* @see #injectAPI()
*/
private void tryInjectAPI() {
// If the maximum installed version isn't our version return
if (getBlackboardVersion() != VERSION) {
LOGGER.info("Blackboard version newer than our version {}. Skipping injecting API.", VERSION);
return;
}
// If we didn't offer to install this version return
if (!hasOfferedVersion) {
LOGGER.info("Someone else with the same version number {} offered to inject themselves first. Skipping injecting API.", VERSION);
return;
}
injectAPI();
}
/**
* Unpacks the actual API file into a temporary folder from where it can be loaded.
*
* @return the location of the extracted API
*/
private File unpackAPI() {
File extractedFile = new File("hypixel-mod-api/" + BUNDLED_JAR_NAME).getAbsoluteFile();
LOGGER.info("Unpacking mod API to {}", extractedFile);
//noinspection ResultOfMethodCallIgnored
extractedFile.getParentFile().mkdirs();
try (InputStream bundledJar = Objects.requireNonNull(
getClass().getResourceAsStream("/" + BUNDLED_JAR_NAME),
"Could not find bundled hypixel mod api");
OutputStream outputStream = Files.newOutputStream(extractedFile.toPath())) {
IOUtils.copy(bundledJar, outputStream);
LOGGER.info("Successfully extracted mod API file");
return extractedFile;
} catch (IOException e) {
LOGGER.error("Could not extract mod API file", e);
throw new RuntimeException(e);
}
}
/**
* @return the jar containing this class
*/
private File getThisJar() {
URL thisJarURL = getClass().getProtectionDomain().getCodeSource().getLocation();
if (thisJarURL == null) return null;
if (!"file".equals(thisJarURL.getProtocol())) return null;
try {
return new File(thisJarURL.toURI()).getAbsoluteFile();
} catch (URISyntaxException ignored) {
}
return null;
}
/**
* Inject the API into Forge to be loaded as a mod. This will also extract the JAR.
*/
private void injectAPI() {
LOGGER.info("Injecting mod API of version {}", VERSION_NAME);
try {
Launch.classLoader.addURL(unpackAPI().toURI().toURL());
LOGGER.info("Added mod API to classpath");
} catch (MalformedURLException e) {
LOGGER.error("Could not add mod API to classpath", e);
}
}
/**
* Instruct Forge to load the current JAR as a mod.
* By default, Forge does not load mods if they contain a tweaker, only loading the tweaker instead.
* This function will remove this JAR from the list of ignored mods and schedule it to be scanned for mods.
*/
private void allowModLoading() {
File file = getThisJar();
if (file != null) {
CoreModManager.getReparseableCoremods()
.add(file.getPath());
CoreModManager.getIgnoredMods()
.remove(file.getPath());
LOGGER.info("Re-added mod {} to the mod candidate list.", file);
} else {
LOGGER.warn("Did not find JAR including this tweaker, cannot re-add mod.");
}
}
/**
* Offers our bundled version to the {@link Launch#blackboard}. If there is already a
* higher version than ours installed then this will not do anything. Otherwise, it
* will set {@link #hasOfferedVersion} and increment the version in the blackboard.
*
* @see #VERSION_KEY
*/
private void offerVersionToBlackboard() {
if (getBlackboardVersion() < VERSION) {
LOGGER.info("Offering newer version {} > {}", VERSION, getBlackboardVersion());
hasOfferedVersion = true;
Launch.blackboard.put(VERSION_KEY, VERSION);
}
}
/*
Below here are all the ITweaker methods. The tweaker methods are executed in rounds.
1. Run class init and init (constructor) for each tweaker
2. Run acceptOptions for each tweaker
3. Run injectIntoClassLoader for each tweaker
4. If any cascading tweakers have been registered, go back to step 1
5. After there are no new tweakers after an entire round:
6. Run getLaunchArguments for each tweaker
7. Run getLaunchTarget only on the first tweaker found (and execute that class)
By first offering our version negotiation in acceptOptions or injectIntoClassloader and
then injection our JARs in getLaunchArguments, we can ensure that every tweaker had time
to make their version announcement heard.
*/
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
offerVersionToBlackboard();
allowModLoading();
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
}
@Override
public String getLaunchTarget() {
return null;
}
@Override
public String[] getLaunchArguments() {
tryInjectAPI();
return new String[0];
}
}