Fix whitespace [skip actions]

This commit is contained in:
github-actions
2022-07-21 07:21:22 +00:00
committed by Melledy
parent 510d564bcb
commit ae2d1fe438
166 changed files with 12928 additions and 12928 deletions

View File

@@ -1,24 +1,24 @@
package emu.grasscutter.utils;
public class ByteHelper {
public static byte[] changeBytes(byte[] a) {
byte[] b = new byte[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[a.length - i - 1];
}
return b;
}
public static byte[] longToBytes(long x) {
byte[] bytes = new byte[8];
bytes[0] = (byte) (x >> 56);
bytes[1] = (byte) (x >> 48);
bytes[2] = (byte) (x >> 40);
bytes[3] = (byte) (x >> 32);
bytes[4] = (byte) (x >> 24);
bytes[5] = (byte) (x >> 16);
bytes[6] = (byte) (x >> 8);
bytes[7] = (byte) (x);
return bytes;
}
}
package emu.grasscutter.utils;
public class ByteHelper {
public static byte[] changeBytes(byte[] a) {
byte[] b = new byte[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[a.length - i - 1];
}
return b;
}
public static byte[] longToBytes(long x) {
byte[] bytes = new byte[8];
bytes[0] = (byte) (x >> 56);
bytes[1] = (byte) (x >> 48);
bytes[2] = (byte) (x >> 40);
bytes[3] = (byte) (x >> 32);
bytes[4] = (byte) (x >> 24);
bytes[5] = (byte) (x >> 16);
bytes[6] = (byte) (x >> 8);
bytes[7] = (byte) (x);
return bytes;
}
}

View File

@@ -10,25 +10,25 @@ import java.security.spec.X509EncodedKeySpec;
import emu.grasscutter.Grasscutter;
public final class Crypto {
private static final SecureRandom secureRandom = new SecureRandom();
private static final SecureRandom secureRandom = new SecureRandom();
public static byte[] DISPATCH_KEY;
public static byte[] DISPATCH_SEED;
public static byte[] DISPATCH_KEY;
public static byte[] DISPATCH_SEED;
public static byte[] ENCRYPT_KEY;
public static long ENCRYPT_SEED = Long.parseUnsignedLong("11468049314633205968");
public static byte[] ENCRYPT_SEED_BUFFER = new byte[0];
public static byte[] ENCRYPT_KEY;
public static long ENCRYPT_SEED = Long.parseUnsignedLong("11468049314633205968");
public static byte[] ENCRYPT_SEED_BUFFER = new byte[0];
public static PublicKey CUR_OS_ENCRYPT_KEY;
public static PublicKey CUR_CN_ENCRYPT_KEY;
public static PrivateKey CUR_SIGNING_KEY;
public static void loadKeys() {
DISPATCH_KEY = FileUtils.readResource("/keys/dispatchKey.bin");
DISPATCH_SEED = FileUtils.readResource("/keys/dispatchSeed.bin");
public static void loadKeys() {
DISPATCH_KEY = FileUtils.readResource("/keys/dispatchKey.bin");
DISPATCH_SEED = FileUtils.readResource("/keys/dispatchSeed.bin");
ENCRYPT_KEY = FileUtils.readResource("/keys/secretKey.bin");
ENCRYPT_SEED_BUFFER = FileUtils.readResource("/keys/secretKeyBuffer.bin");
ENCRYPT_KEY = FileUtils.readResource("/keys/secretKey.bin");
ENCRYPT_SEED_BUFFER = FileUtils.readResource("/keys/secretKeyBuffer.bin");
try {
//These should be loaded from ChannelConfig_whatever.json
@@ -44,21 +44,21 @@ public final class Crypto {
catch (Exception e) {
Grasscutter.getLogger().error("An error occurred while loading keys.", e);
}
}
}
public static void xor(byte[] packet, byte[] key) {
try {
for (int i = 0; i < packet.length; i++) {
packet[i] ^= key[i % key.length];
}
} catch (Exception e) {
Grasscutter.getLogger().error("Crypto error.", e);
}
}
public static void xor(byte[] packet, byte[] key) {
try {
for (int i = 0; i < packet.length; i++) {
packet[i] ^= key[i % key.length];
}
} catch (Exception e) {
Grasscutter.getLogger().error("Crypto error.", e);
}
}
public static byte[] createSessionKey(int length) {
byte[] bytes = new byte[length];
secureRandom.nextBytes(bytes);
return bytes;
}
public static byte[] createSessionKey(int length) {
byte[] bytes = new byte[length];
secureRandom.nextBytes(bytes);
return bytes;
}
}

View File

@@ -15,7 +15,7 @@ import java.util.Map;
public final class Language {
private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
private final JsonObject languageData;
private final String languageCode;
private final Map<String, String> cachedTranslations = new ConcurrentHashMap<>();
@@ -54,7 +54,7 @@ public final class Language {
*/
public static String translate(String key, Object... args) {
String translated = Grasscutter.getLanguage().get(key);
try {
return translated.formatted(args);
} catch (Exception exception) {
@@ -77,7 +77,7 @@ public final class Language {
var langCode = Utils.getLanguageCode(player.getAccount().getLocale());
String translated = Grasscutter.getLanguage(langCode).get(key);
try {
return translated.formatted(args);
} catch (Exception exception) {
@@ -99,13 +99,13 @@ public final class Language {
private Language(LanguageStreamDescription description) {
@Nullable JsonObject languageData = null;
languageCode = description.getLanguageCode();
try {
languageData = Grasscutter.getGsonFactory().fromJson(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
} catch (Exception exception) {
Grasscutter.getLogger().warn("Failed to load language file: " + description.getLanguageCode(), exception);
}
this.languageData = languageData;
}
@@ -117,7 +117,7 @@ public final class Language {
private static LanguageStreamDescription getLanguageFileDescription(String languageCode, String fallbackLanguageCode) {
var fileName = languageCode + ".json";
var fallback = fallbackLanguageCode + ".json";
String actualLanguageCode = languageCode;
InputStream file = Grasscutter.class.getResourceAsStream("/languages/" + fileName);
@@ -127,21 +127,21 @@ public final class Language {
if (cachedLanguages.containsKey(actualLanguageCode)) {
return new LanguageStreamDescription(actualLanguageCode, null);
}
file = Grasscutter.class.getResourceAsStream("/languages/" + fallback);
}
if(file == null) { // Fallback the fallback language.
if (file == null) { // Fallback the fallback language.
Grasscutter.getLogger().warn("Failed to load language file: " + fallback + ", falling back to: en-US.json");
actualLanguageCode = "en-US";
if (cachedLanguages.containsKey(actualLanguageCode)) {
return new LanguageStreamDescription(actualLanguageCode, null);
}
file = Grasscutter.class.getResourceAsStream("/languages/en-US.json");
}
if(file == null)
if (file == null)
throw new RuntimeException("Unable to load the primary, fallback, and 'en-US' language files.");
return new LanguageStreamDescription(actualLanguageCode, file);
@@ -153,10 +153,10 @@ public final class Language {
* @return The value (as a string) from a nested key.
*/
public String get(String key) {
if(this.cachedTranslations.containsKey(key)) {
if (this.cachedTranslations.containsKey(key)) {
return this.cachedTranslations.get(key);
}
String[] keys = key.split("\\.");
JsonObject object = this.languageData;
@@ -166,12 +166,12 @@ public final class Language {
boolean isValueFound = false;
while (true) {
if(index == keys.length) break;
if (index == keys.length) break;
String currentKey = keys[index++];
if(object.has(currentKey)) {
if (object.has(currentKey)) {
JsonElement element = object.get(currentKey);
if(element.isJsonObject())
if (element.isJsonObject())
object = element.getAsJsonObject();
else {
isValueFound = true;
@@ -186,7 +186,7 @@ public final class Language {
result += "\nhere is english version:\n" + englishValue;
}
}
this.cachedTranslations.put(key, result); return result;
}

View File

@@ -26,387 +26,387 @@ import static emu.grasscutter.utils.Language.translate;
@SuppressWarnings({"UnusedReturnValue", "BooleanMethodIsAlwaysInverted"})
public final class Utils {
public static final Random random = new Random();
public static final Random random = new Random();
public static int randomRange(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
public static int randomRange(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
public static float randomFloatRange(float min, float max) {
return random.nextFloat() * (max - min) + min;
}
public static float randomFloatRange(float min, float max) {
return random.nextFloat() * (max - min) + min;
}
public static double getDist(Position pos1, Position pos2) {
double xs = pos1.getX() - pos2.getX();
xs = xs * xs;
public static double getDist(Position pos1, Position pos2) {
double xs = pos1.getX() - pos2.getX();
xs = xs * xs;
double ys = pos1.getY() - pos2.getY();
ys = ys * ys;
double ys = pos1.getY() - pos2.getY();
ys = ys * ys;
double zs = pos1.getZ() - pos2.getZ();
zs = zs * zs;
double zs = pos1.getZ() - pos2.getZ();
zs = zs * zs;
return Math.sqrt(xs + zs + ys);
}
return Math.sqrt(xs + zs + ys);
}
public static int getCurrentSeconds() {
return (int) (System.currentTimeMillis() / 1000.0);
}
public static int getCurrentSeconds() {
return (int) (System.currentTimeMillis() / 1000.0);
}
public static String lowerCaseFirstChar(String s) {
StringBuilder sb = new StringBuilder(s);
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
return sb.toString();
}
public static String lowerCaseFirstChar(String s) {
StringBuilder sb = new StringBuilder(s);
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
return sb.toString();
}
public static String toString(InputStream inputStream) throws IOException {
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (int result = bis.read(); result != -1; result = bis.read()) {
buf.write((byte) result);
}
return buf.toString();
}
public static String toString(InputStream inputStream) throws IOException {
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (int result = bis.read(); result != -1; result = bis.read()) {
buf.write((byte) result);
}
return buf.toString();
}
public static void logByteArray(byte[] array) {
ByteBuf b = Unpooled.wrappedBuffer(array);
Grasscutter.getLogger().info("\n" + ByteBufUtil.prettyHexDump(b));
b.release();
}
public static void logByteArray(byte[] array) {
ByteBuf b = Unpooled.wrappedBuffer(array);
Grasscutter.getLogger().info("\n" + ByteBufUtil.prettyHexDump(b));
b.release();
}
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
public static String bytesToHex(byte[] bytes) {
if (bytes == null) return "";
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
public static String bytesToHex(byte[] bytes) {
if (bytes == null) return "";
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
public static String bytesToHex(ByteBuf buf) {
return bytesToHex(byteBufToArray(buf));
}
public static String bytesToHex(ByteBuf buf) {
return bytesToHex(byteBufToArray(buf));
}
public static byte[] byteBufToArray(ByteBuf buf) {
byte[] bytes = new byte[buf.capacity()];
buf.getBytes(0, bytes);
return bytes;
}
public static byte[] byteBufToArray(ByteBuf buf) {
byte[] bytes = new byte[buf.capacity()];
buf.getBytes(0, bytes);
return bytes;
}
public static int abilityHash(String str) {
int v7 = 0;
int v8 = 0;
while (v8 < str.length()) {
v7 = str.charAt(v8++) + 131 * v7;
}
return v7;
}
public static int abilityHash(String str) {
int v7 = 0;
int v8 = 0;
while (v8 < str.length()) {
v7 = str.charAt(v8++) + 131 * v7;
}
return v7;
}
/**
* Creates a string with the path to a file.
* @param path The path to the file.
* @return A path using the operating system's file separator.
*/
public static String toFilePath(String path) {
return path.replace("/", File.separator);
}
/**
* Creates a string with the path to a file.
* @param path The path to the file.
* @return A path using the operating system's file separator.
*/
public static String toFilePath(String path) {
return path.replace("/", File.separator);
}
/**
* Checks if a file exists on the file system.
* @param path The path to the file.
* @return True if the file exists, false otherwise.
*/
public static boolean fileExists(String path) {
return new File(path).exists();
}
/**
* Checks if a file exists on the file system.
* @param path The path to the file.
* @return True if the file exists, false otherwise.
*/
public static boolean fileExists(String path) {
return new File(path).exists();
}
/**
* Creates a folder on the file system.
* @param path The path to the folder.
* @return True if the folder was created, false otherwise.
*/
public static boolean createFolder(String path) {
return new File(path).mkdirs();
}
/**
* Creates a folder on the file system.
* @param path The path to the folder.
* @return True if the folder was created, false otherwise.
*/
public static boolean createFolder(String path) {
return new File(path).mkdirs();
}
/**
* Copies a file from the archive's resources to the file system.
* @param resource The path to the resource.
* @param destination The path to copy the resource to.
* @return True if the file was copied, false otherwise.
*/
public static boolean copyFromResources(String resource, String destination) {
try (InputStream stream = Grasscutter.class.getResourceAsStream(resource)) {
if(stream == null) {
Grasscutter.getLogger().warn("Could not find resource: " + resource);
return false;
}
/**
* Copies a file from the archive's resources to the file system.
* @param resource The path to the resource.
* @param destination The path to copy the resource to.
* @return True if the file was copied, false otherwise.
*/
public static boolean copyFromResources(String resource, String destination) {
try (InputStream stream = Grasscutter.class.getResourceAsStream(resource)) {
if (stream == null) {
Grasscutter.getLogger().warn("Could not find resource: " + resource);
return false;
}
Files.copy(stream, new File(destination).toPath(), StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (Exception exception) {
Grasscutter.getLogger().warn("Unable to copy resource " + resource + " to " + destination, exception);
return false;
}
}
Files.copy(stream, new File(destination).toPath(), StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (Exception exception) {
Grasscutter.getLogger().warn("Unable to copy resource " + resource + " to " + destination, exception);
return false;
}
}
/**
* Logs an object to the console.
* @param object The object to log.
*/
public static void logObject(Object object) {
String asJson = Grasscutter.getGsonFactory().toJson(object);
Grasscutter.getLogger().info(asJson);
}
/**
* Logs an object to the console.
* @param object The object to log.
*/
public static void logObject(Object object) {
String asJson = Grasscutter.getGsonFactory().toJson(object);
Grasscutter.getLogger().info(asJson);
}
/**
* Checks for required files and folders before startup.
*/
public static void startupCheck() {
ConfigContainer config = Grasscutter.getConfig();
Logger logger = Grasscutter.getLogger();
boolean exit = false;
/**
* Checks for required files and folders before startup.
*/
public static void startupCheck() {
ConfigContainer config = Grasscutter.getConfig();
Logger logger = Grasscutter.getLogger();
boolean exit = false;
String resourcesFolder = config.folderStructure.resources;
String dataFolder = config.folderStructure.data;
String resourcesFolder = config.folderStructure.resources;
String dataFolder = config.folderStructure.data;
// Check for resources folder.
if(!fileExists(resourcesFolder)) {
logger.info(translate("messages.status.create_resources"));
logger.info(translate("messages.status.resources_error"));
createFolder(resourcesFolder); exit = true;
}
// Check for resources folder.
if (!fileExists(resourcesFolder)) {
logger.info(translate("messages.status.create_resources"));
logger.info(translate("messages.status.resources_error"));
createFolder(resourcesFolder); exit = true;
}
// Check for BinOutput + ExcelBinOutput.
if(!fileExists(resourcesFolder + "BinOutput") ||
!fileExists(resourcesFolder + "ExcelBinOutput")) {
logger.info(translate("messages.status.resources_error"));
exit = true;
}
// Check for BinOutput + ExcelBinOutput.
if (!fileExists(resourcesFolder + "BinOutput") ||
!fileExists(resourcesFolder + "ExcelBinOutput")) {
logger.info(translate("messages.status.resources_error"));
exit = true;
}
// Check for game data.
if(!fileExists(dataFolder))
createFolder(dataFolder);
// Check for game data.
if (!fileExists(dataFolder))
createFolder(dataFolder);
// Make sure the data folder is populated, if there are any missing files copy them from resources
DataLoader.checkAllFiles();
// Make sure the data folder is populated, if there are any missing files copy them from resources
DataLoader.checkAllFiles();
if(exit) System.exit(1);
}
if (exit) System.exit(1);
}
/**
* Gets the timestamp of the next hour.
* @return The timestamp in UNIX seconds.
*/
public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
for (int i = 0; i < param; i ++){
if (zonedDateTime.getHour() < hour) {
zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
} else {
zonedDateTime = zonedDateTime.plusDays(1).withHour(hour).withMinute(0).withSecond(0);
}
}
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
}
/**
* Gets the timestamp of the next hour.
* @return The timestamp in UNIX seconds.
*/
public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
for (int i = 0; i < param; i ++) {
if (zonedDateTime.getHour() < hour) {
zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
} else {
zonedDateTime = zonedDateTime.plusDays(1).withHour(hour).withMinute(0).withSecond(0);
}
}
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
}
/**
* Gets the timestamp of the next hour in a week.
* @return The timestamp in UNIX seconds.
*/
public static int getNextTimestampOfThisHourInNextWeek(int hour, String timeZone, int param) {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
for (int i = 0; i < param; i++) {
if (zonedDateTime.getDayOfWeek() == DayOfWeek.MONDAY && zonedDateTime.getHour() < hour) {
zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
} else {
zonedDateTime = zonedDateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).withHour(hour).withMinute(0).withSecond(0);
}
}
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
}
/**
* Gets the timestamp of the next hour in a week.
* @return The timestamp in UNIX seconds.
*/
public static int getNextTimestampOfThisHourInNextWeek(int hour, String timeZone, int param) {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
for (int i = 0; i < param; i++) {
if (zonedDateTime.getDayOfWeek() == DayOfWeek.MONDAY && zonedDateTime.getHour() < hour) {
zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
} else {
zonedDateTime = zonedDateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).withHour(hour).withMinute(0).withSecond(0);
}
}
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
}
/**
* Gets the timestamp of the next hour in a month.
* @return The timestamp in UNIX seconds.
*/
public static int getNextTimestampOfThisHourInNextMonth(int hour, String timeZone, int param) {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
for (int i = 0; i < param; i++) {
if (zonedDateTime.getDayOfMonth() == 1 && zonedDateTime.getHour() < hour) {
zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
} else {
zonedDateTime = zonedDateTime.with(TemporalAdjusters.firstDayOfNextMonth()).withHour(hour).withMinute(0).withSecond(0);
}
}
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
}
/**
* Gets the timestamp of the next hour in a month.
* @return The timestamp in UNIX seconds.
*/
public static int getNextTimestampOfThisHourInNextMonth(int hour, String timeZone, int param) {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
for (int i = 0; i < param; i++) {
if (zonedDateTime.getDayOfMonth() == 1 && zonedDateTime.getHour() < hour) {
zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
} else {
zonedDateTime = zonedDateTime.with(TemporalAdjusters.firstDayOfNextMonth()).withHour(hour).withMinute(0).withSecond(0);
}
}
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
}
/**
* Retrieves a string from an input stream.
* @param stream The input stream.
* @return The string.
*/
public static String readFromInputStream(@Nullable InputStream stream) {
if(stream == null) return "empty";
/**
* Retrieves a string from an input stream.
* @param stream The input stream.
* @return The string.
*/
public static String readFromInputStream(@Nullable InputStream stream) {
if (stream == null) return "empty";
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
String line; while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
} stream.close();
} catch (IOException e) {
Grasscutter.getLogger().warn("Failed to read from input stream.");
} catch (NullPointerException ignored) {
return "empty";
} return stringBuilder.toString();
}
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
String line; while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
} stream.close();
} catch (IOException e) {
Grasscutter.getLogger().warn("Failed to read from input stream.");
} catch (NullPointerException ignored) {
return "empty";
} return stringBuilder.toString();
}
/**
* Performs a linear interpolation using a table of fixed points to create an effective piecewise f(x) = y function.
* @param x The x value.
* @param xyArray Array of points in [[x0,y0], ... [xN, yN]] format
* @return f(x) = y
*/
public static int lerp(int x, int[][] xyArray) {
try {
if (x <= xyArray[0][0]){ // Clamp to first point
return xyArray[0][1];
} else if (x >= xyArray[xyArray.length-1][0]) { // Clamp to last point
return xyArray[xyArray.length-1][1];
}
// At this point we're guaranteed to have two lerp points, and pity be somewhere between them.
for (int i=0; i < xyArray.length-1; i++) {
if (x == xyArray[i+1][0]) {
return xyArray[i+1][1];
}
if (x < xyArray[i+1][0]) {
// We are between [i] and [i+1], interpolation time!
// Using floats would be slightly cleaner but we can just as easily use ints if we're careful with order of operations.
int position = x - xyArray[i][0];
int fullDist = xyArray[i+1][0] - xyArray[i][0];
int prevValue = xyArray[i][1];
int fullDelta = xyArray[i+1][1] - prevValue;
return prevValue + ( (position * fullDelta) / fullDist );
}
}
} catch (IndexOutOfBoundsException e) {
Grasscutter.getLogger().error("Malformed lerp point array. Must be of form [[x0, y0], ..., [xN, yN]].");
}
return 0;
}
/**
* Performs a linear interpolation using a table of fixed points to create an effective piecewise f(x) = y function.
* @param x The x value.
* @param xyArray Array of points in [[x0,y0], ... [xN, yN]] format
* @return f(x) = y
*/
public static int lerp(int x, int[][] xyArray) {
try {
if (x <= xyArray[0][0]) { // Clamp to first point
return xyArray[0][1];
} else if (x >= xyArray[xyArray.length-1][0]) { // Clamp to last point
return xyArray[xyArray.length-1][1];
}
// At this point we're guaranteed to have two lerp points, and pity be somewhere between them.
for (int i=0; i < xyArray.length-1; i++) {
if (x == xyArray[i+1][0]) {
return xyArray[i+1][1];
}
if (x < xyArray[i+1][0]) {
// We are between [i] and [i+1], interpolation time!
// Using floats would be slightly cleaner but we can just as easily use ints if we're careful with order of operations.
int position = x - xyArray[i][0];
int fullDist = xyArray[i+1][0] - xyArray[i][0];
int prevValue = xyArray[i][1];
int fullDelta = xyArray[i+1][1] - prevValue;
return prevValue + ( (position * fullDelta) / fullDist );
}
}
} catch (IndexOutOfBoundsException e) {
Grasscutter.getLogger().error("Malformed lerp point array. Must be of form [[x0, y0], ..., [xN, yN]].");
}
return 0;
}
/**
* Checks if an int is in an int[]
* @param key int to look for
* @param array int[] to look in
* @return key in array
*/
public static boolean intInArray(int key, int[] array) {
for (int i : array) {
if (i == key) {
return true;
}
}
return false;
}
/**
* Checks if an int is in an int[]
* @param key int to look for
* @param array int[] to look in
* @return key in array
*/
public static boolean intInArray(int key, int[] array) {
for (int i : array) {
if (i == key) {
return true;
}
}
return false;
}
/**
* Return a copy of minuend without any elements found in subtrahend.
* @param minuend The array we want elements from
* @param subtrahend The array whose elements we don't want
* @return The array with only the elements we want, in the order that minuend had them
*/
public static int[] setSubtract(int[] minuend, int[] subtrahend) {
IntList temp = new IntArrayList();
for (int i : minuend) {
if (!intInArray(i, subtrahend)) {
temp.add(i);
}
}
return temp.toIntArray();
}
/**
* Return a copy of minuend without any elements found in subtrahend.
* @param minuend The array we want elements from
* @param subtrahend The array whose elements we don't want
* @return The array with only the elements we want, in the order that minuend had them
*/
public static int[] setSubtract(int[] minuend, int[] subtrahend) {
IntList temp = new IntArrayList();
for (int i : minuend) {
if (!intInArray(i, subtrahend)) {
temp.add(i);
}
}
return temp.toIntArray();
}
/**
* Gets the language code from a given locale.
* @param locale A locale.
* @return A string in the format of 'XX-XX'.
*/
public static String getLanguageCode(Locale locale) {
return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
}
/**
* Gets the language code from a given locale.
* @param locale A locale.
* @return A string in the format of 'XX-XX'.
*/
public static String getLanguageCode(Locale locale) {
return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
}
/**
* Base64 encodes a given byte array.
* @param toEncode An array of bytes.
* @return A base64 encoded string.
*/
public static String base64Encode(byte[] toEncode) {
return Base64.getEncoder().encodeToString(toEncode);
}
/**
* Base64 encodes a given byte array.
* @param toEncode An array of bytes.
* @return A base64 encoded string.
*/
public static String base64Encode(byte[] toEncode) {
return Base64.getEncoder().encodeToString(toEncode);
}
/**
* Base64 decodes a given string.
* @param toDecode A base64 encoded string.
* @return An array of bytes.
*/
public static byte[] base64Decode(String toDecode) {
return Base64.getDecoder().decode(toDecode);
}
/**
* Base64 decodes a given string.
* @param toDecode A base64 encoded string.
* @return An array of bytes.
*/
public static byte[] base64Decode(String toDecode) {
return Base64.getDecoder().decode(toDecode);
}
/**
* Safely JSON decodes a given string.
* @param jsonData The JSON-encoded data.
* @return JSON decoded data, or null if an exception occurred.
*/
public static <T> T jsonDecode(String jsonData, Class<T> classType) {
try {
return Grasscutter.getGsonFactory().fromJson(jsonData, classType);
} catch (Exception ignored) {
return null;
}
}
/**
* Safely JSON decodes a given string.
* @param jsonData The JSON-encoded data.
* @return JSON decoded data, or null if an exception occurred.
*/
public static <T> T jsonDecode(String jsonData, Class<T> classType) {
try {
return Grasscutter.getGsonFactory().fromJson(jsonData, classType);
} catch (Exception ignored) {
return null;
}
}
/***
* Draws a random element from the given list, following the given probability distribution, if given.
* @param list The list from which to draw the element.
* @param probabilities The probability distribution. This is given as a list of probabilities of the same length it `list`.
* @return A randomly drawn element from the given list.
*/
public static <T> T drawRandomListElement(List<T> list, List<Integer> probabilities) {
// If we don't have a probability distribution, or the size of the distribution does not match
// the size of the list, we assume uniform distribution.
if (probabilities == null || probabilities.size() <= 1 || probabilities.size() != list.size()) {
int index = ThreadLocalRandom.current().nextInt(0, list.size());
return list.get(index);
}
/***
* Draws a random element from the given list, following the given probability distribution, if given.
* @param list The list from which to draw the element.
* @param probabilities The probability distribution. This is given as a list of probabilities of the same length it `list`.
* @return A randomly drawn element from the given list.
*/
public static <T> T drawRandomListElement(List<T> list, List<Integer> probabilities) {
// If we don't have a probability distribution, or the size of the distribution does not match
// the size of the list, we assume uniform distribution.
if (probabilities == null || probabilities.size() <= 1 || probabilities.size() != list.size()) {
int index = ThreadLocalRandom.current().nextInt(0, list.size());
return list.get(index);
}
// Otherwise, we roll with the given distribution.
int totalProbabilityMass = probabilities.stream().reduce(Integer::sum).get();
int roll = ThreadLocalRandom.current().nextInt(1, totalProbabilityMass + 1);
// Otherwise, we roll with the given distribution.
int totalProbabilityMass = probabilities.stream().reduce(Integer::sum).get();
int roll = ThreadLocalRandom.current().nextInt(1, totalProbabilityMass + 1);
int currentTotalChance = 0;
for (int i = 0; i < list.size(); i++) {
currentTotalChance += probabilities.get(i);
int currentTotalChance = 0;
for (int i = 0; i < list.size(); i++) {
currentTotalChance += probabilities.get(i);
if (roll <= currentTotalChance) {
return list.get(i);
}
}
if (roll <= currentTotalChance) {
return list.get(i);
}
}
// Should never happen.
return list.get(0);
}
// Should never happen.
return list.get(0);
}
/***
* Draws a random element from the given list, following a uniform probability distribution.
* @param list The list from which to draw the element.
* @return A randomly drawn element from the given list.
*/
public static <T> T drawRandomListElement(List<T> list) {
return drawRandomListElement(list, null);
}
/***
* Draws a random element from the given list, following a uniform probability distribution.
* @param list The list from which to draw the element.
* @return A randomly drawn element from the given list.
*/
public static <T> T drawRandomListElement(List<T> list) {
return drawRandomListElement(list, null);
}
}