mirror of
https://github.com/Grasscutters/Grasscutter.git
synced 2025-12-19 10:24:47 +01:00
Run IntelliJ IDEA code formatter
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.io.File;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
@@ -8,12 +9,10 @@ import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
|
||||
public final class Crypto {
|
||||
private static final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
@@ -45,8 +44,7 @@ public final class Crypto {
|
||||
|
||||
var m = pattern.matcher(path.getFileName().toString());
|
||||
|
||||
if (m.matches())
|
||||
{
|
||||
if (m.matches()) {
|
||||
var key = KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(FileUtils.read(path)));
|
||||
|
||||
@@ -54,8 +52,7 @@ public final class Crypto {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("An error occurred while loading keys.", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public final class DateHelper {
|
||||
public static Date onlyYearMonthDay(Date now) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(now);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static int getUnixTime(Date localDateTime){
|
||||
return (int)(localDateTime.getTime() / 1000L);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public final class DateHelper {
|
||||
public static Date onlyYearMonthDay(Date now) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(now);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static int getUnixTime(Date localDateTime) {
|
||||
return (int) (localDateTime.getTime() / 1000L);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -21,6 +24,8 @@ public final class FileUtils {
|
||||
private static final Path PLUGINS_PATH = Path.of(Grasscutter.config.folderStructure.plugins);
|
||||
private static final Path RESOURCES_PATH;
|
||||
private static final Path SCRIPTS_PATH;
|
||||
private static final String[] TSJ_JSON_TSV = {"tsj", "json", "tsv"};
|
||||
|
||||
static {
|
||||
FileSystem fs = null;
|
||||
Path path = null;
|
||||
@@ -36,7 +41,7 @@ public final class FileUtils {
|
||||
path = Path.of(uri); // Can access directly
|
||||
break;
|
||||
default:
|
||||
Grasscutter.getLogger().error("Invalid URI scheme for class resources: "+uri.getScheme());
|
||||
Grasscutter.getLogger().error("Invalid URI scheme for class resources: " + uri.getScheme());
|
||||
break;
|
||||
}
|
||||
} catch (URISyntaxException | IOException e) {
|
||||
@@ -44,7 +49,7 @@ public final class FileUtils {
|
||||
Grasscutter.getLogger().error("Failed to load jar?!");
|
||||
} finally {
|
||||
DATA_DEFAULT_PATH = path;
|
||||
Grasscutter.getLogger().debug("Setting path for default data: "+path.toAbsolutePath());
|
||||
Grasscutter.getLogger().debug("Setting path for default data: " + path.toAbsolutePath());
|
||||
}
|
||||
|
||||
// Setup Resources path
|
||||
@@ -62,16 +67,16 @@ public final class FileUtils {
|
||||
if (fs != null) {
|
||||
var root = fs.getPath("");
|
||||
try (Stream<Path> pathStream = Files.find(root, 3, (p, a) -> {
|
||||
var filename = p.getFileName();
|
||||
if (filename == null) return false;
|
||||
return filename.toString().equals("ExcelBinOutput");
|
||||
var filename = p.getFileName();
|
||||
if (filename == null) return false;
|
||||
return filename.toString().equals("ExcelBinOutput");
|
||||
})) {
|
||||
var excelBinOutput = pathStream.findFirst();
|
||||
if (excelBinOutput.isPresent()) {
|
||||
path = excelBinOutput.get().getParent();
|
||||
if (path == null)
|
||||
path = root;
|
||||
Grasscutter.getLogger().debug("Resources will be loaded from \"" + resources + "/" + path.toString() + "\"");
|
||||
Grasscutter.getLogger().debug("Resources will be loaded from \"" + resources + "/" + path + "\"");
|
||||
} else {
|
||||
Grasscutter.getLogger().error("Failed to find ExcelBinOutput in resources zip \"" + resources + "\"");
|
||||
}
|
||||
@@ -86,13 +91,15 @@ public final class FileUtils {
|
||||
SCRIPTS_PATH = (scripts.startsWith("resources:"))
|
||||
? RESOURCES_PATH.resolve(scripts.substring("resources:".length()))
|
||||
: Path.of(scripts);
|
||||
};
|
||||
}
|
||||
|
||||
private static final String[] TSJ_JSON_TSV = {"tsj", "json", "tsv"};
|
||||
/* Apply after initialization. */
|
||||
private static final Path[] DATA_PATHS = {DATA_USER_PATH, DATA_DEFAULT_PATH};
|
||||
|
||||
public static Path getDataPathTsjJsonTsv(String filename) {
|
||||
return getDataPathTsjJsonTsv(filename, true);
|
||||
}
|
||||
|
||||
public static Path getDataPathTsjJsonTsv(String filename, boolean fallback) {
|
||||
val name = getFilenameWithoutExtension(filename);
|
||||
for (val data_path : DATA_PATHS) {
|
||||
@@ -204,6 +211,7 @@ public final class FileUtils {
|
||||
public static String getFilenameWithoutPath(String filename) {
|
||||
return getFilenameWithoutExtension(filename);
|
||||
}
|
||||
|
||||
public static String getFilenameWithoutExtension(String filename) {
|
||||
int i = filename.lastIndexOf(".");
|
||||
return (i < 0) ? filename : filename.substring(0, i);
|
||||
@@ -212,21 +220,21 @@ public final class FileUtils {
|
||||
public static String getFileExtension(Path path) {
|
||||
val filename = path.toString();
|
||||
int i = filename.lastIndexOf(".");
|
||||
return (i < 0) ? "" : filename.substring(i+1);
|
||||
return (i < 0) ? "" : filename.substring(i + 1);
|
||||
}
|
||||
|
||||
public static List<Path> getPathsFromResource(String folder) throws URISyntaxException {
|
||||
try {
|
||||
// file walks JAR
|
||||
return Files.walk(Path.of(Grasscutter.class.getResource(folder).toURI()))
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
// Eclipse puts resources in its bin folder
|
||||
try {
|
||||
return Files.walk(Path.of(System.getProperty("user.dir"), folder))
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException ignored) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package emu.grasscutter.utils;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.ConsoleAppender;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import org.jline.reader.LineReader;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@@ -14,7 +13,7 @@ public class JlineLogbackAppender extends ConsoleAppender<ILoggingEvent> {
|
||||
return;
|
||||
}
|
||||
Arrays.stream(
|
||||
new String(encoder.encode(eventObject)).split("\n\r")
|
||||
new String(encoder.encode(eventObject)).split("\n\r")
|
||||
).forEach(Grasscutter.getConsole()::printAbove);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.TypeAdapterFactory;
|
||||
@@ -12,16 +7,17 @@ import com.google.gson.reflect.TypeToken;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import lombok.val;
|
||||
|
||||
import static com.google.gson.stream.JsonToken.BEGIN_ARRAY;
|
||||
import static com.google.gson.stream.JsonToken.BEGIN_OBJECT;
|
||||
import static emu.grasscutter.utils.JsonUtils.gson;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
|
||||
public class JsonAdapters {
|
||||
static class DynamicFloatAdapter extends TypeAdapter<DynamicFloat> {
|
||||
@@ -42,7 +38,8 @@ public class JsonAdapters {
|
||||
case STRING -> new DynamicFloat.StackOp(reader.nextString());
|
||||
case NUMBER -> new DynamicFloat.StackOp((float) reader.nextDouble());
|
||||
case BOOLEAN -> new DynamicFloat.StackOp(reader.nextBoolean());
|
||||
default -> throw new IOException("Invalid DynamicFloat definition - " + reader.peek().name());
|
||||
default ->
|
||||
throw new IOException("Invalid DynamicFloat definition - " + reader.peek().name());
|
||||
});
|
||||
}
|
||||
reader.endArray();
|
||||
@@ -53,24 +50,24 @@ public class JsonAdapters {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, DynamicFloat f) {};
|
||||
public void write(JsonWriter writer, DynamicFloat f) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class IntListAdapter extends TypeAdapter<IntList> {
|
||||
@Override
|
||||
public IntList read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case BEGIN_ARRAY:
|
||||
reader.beginArray();
|
||||
val i = new IntArrayList();
|
||||
while (reader.hasNext())
|
||||
i.add(reader.nextInt());
|
||||
reader.endArray();
|
||||
i.trim(); // We might have a ton of these from resources and almost all of them immutable, don't overprovision!
|
||||
return i;
|
||||
default:
|
||||
throw new IOException("Invalid IntList definition - " + reader.peek().name());
|
||||
if (Objects.requireNonNull(reader.peek()) == JsonToken.BEGIN_ARRAY) {
|
||||
reader.beginArray();
|
||||
val i = new IntArrayList();
|
||||
while (reader.hasNext())
|
||||
i.add(reader.nextInt());
|
||||
reader.endArray();
|
||||
i.trim(); // We might have a ton of these from resources and almost all of them immutable, don't overprovision!
|
||||
return i;
|
||||
}
|
||||
throw new IOException("Invalid IntList definition - " + reader.peek().name());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -79,7 +76,8 @@ public class JsonAdapters {
|
||||
for (val i : l) // .forEach() doesn't appreciate exceptions
|
||||
writer.value(i);
|
||||
writer.endArray();
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class PositionAdapter extends TypeAdapter<Position> {
|
||||
@@ -121,7 +119,8 @@ public class JsonAdapters {
|
||||
writer.value(i.getY());
|
||||
writer.value(i.getZ());
|
||||
writer.endArray();
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class EnumTypeAdapterFactory implements TypeAdapterFactory {
|
||||
@@ -139,7 +138,10 @@ public class JsonAdapters {
|
||||
// If the enum also has a numeric value, map those to the constants too
|
||||
// System.out.println("Looking for enum value field");
|
||||
for (Field f : enumClass.getDeclaredFields()) {
|
||||
if (switch (f.getName()) {case "value", "id" -> true; default -> false;}) {
|
||||
if (switch (f.getName()) {
|
||||
case "value", "id" -> true;
|
||||
default -> false;
|
||||
}) {
|
||||
// System.out.println("Enum value field found - " + f.getName());
|
||||
boolean acc = f.isAccessible();
|
||||
f.setAccessible(true);
|
||||
@@ -165,6 +167,7 @@ public class JsonAdapters {
|
||||
throw new IOException("Invalid Enum definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
public void write(JsonWriter writer, T value) throws IOException {
|
||||
writer.value(value.toString());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import emu.grasscutter.utils.JsonAdapters.DynamicFloatAdapter;
|
||||
import emu.grasscutter.utils.JsonAdapters.EnumTypeAdapterFactory;
|
||||
import emu.grasscutter.utils.JsonAdapters.IntListAdapter;
|
||||
import emu.grasscutter.utils.JsonAdapters.PositionAdapter;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
@@ -11,17 +23,6 @@ import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import emu.grasscutter.utils.JsonAdapters.*;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
|
||||
public final class JsonUtils {
|
||||
static final Gson gson = new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
@@ -76,18 +77,18 @@ public final class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public static <T1,T2> Map<T1,T2> loadToMap(Reader fileReader, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(Reader fileReader, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
return gson.fromJson(fileReader, TypeToken.getParameterized(Map.class, keyType, valueType).getType());
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static <T1,T2> Map<T1,T2> loadToMap(String filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(String filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
try (InputStreamReader fileReader = new InputStreamReader(new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToMap(fileReader, keyType, valueType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T1,T2> Map<T1,T2> loadToMap(Path filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(Path filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return loadToMap(fileReader, keyType, valueType);
|
||||
}
|
||||
@@ -95,6 +96,7 @@ public final class JsonUtils {
|
||||
|
||||
/**
|
||||
* Safely JSON decodes a given string.
|
||||
*
|
||||
* @param jsonData The JSON-encoded data.
|
||||
* @return JSON decoded data, or null if an exception occurred.
|
||||
*/
|
||||
|
||||
@@ -15,41 +15,52 @@ import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.FALLBACK_LANGUAGE;
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
|
||||
public final class Language {
|
||||
private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
|
||||
|
||||
private static final int TEXTMAP_CACHE_VERSION = 0x9CCACE04;
|
||||
private static final Pattern textMapKeyValueRegex = Pattern.compile("\"(\\d+)\": \"(.+)\"");
|
||||
private static final Path TEXTMAP_CACHE_PATH = Path.of(Utils.toFilePath("cache/TextMapCache.bin"));
|
||||
private static boolean scannedTextmaps = false; // Ensure that we don't infinitely rescan on cache misses that don't exist
|
||||
private static Int2ObjectMap<TextStrings> textMapStrings;
|
||||
private final String languageCode;
|
||||
private final Map<String, String> translations = new ConcurrentHashMap<>();
|
||||
private static boolean scannedTextmaps = false; // Ensure that we don't infinitely rescan on cache misses that don't exist
|
||||
|
||||
/**
|
||||
* Reads a file and creates a language instance.
|
||||
*/
|
||||
private Language(LanguageStreamDescription description) {
|
||||
languageCode = description.getLanguageCode();
|
||||
|
||||
try {
|
||||
var object = JsonUtils.decode(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
|
||||
object.entrySet().forEach(entry -> putFlattenedKey(translations, entry.getKey(), entry.getValue()));
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to load language file: " + description.getLanguageCode(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a language instance from a code.
|
||||
*
|
||||
* @param langCode The language code.
|
||||
* @return A language instance.
|
||||
*/
|
||||
@@ -76,7 +87,8 @@ public final class Language {
|
||||
|
||||
/**
|
||||
* Returns the translated value from the key while substituting arguments.
|
||||
* @param key The key of the translated value to return.
|
||||
*
|
||||
* @param key The key of the translated value to return.
|
||||
* @param args The arguments to substitute.
|
||||
* @return A translated value with arguments substituted.
|
||||
*/
|
||||
@@ -86,7 +98,8 @@ public final class Language {
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] = switch (args[i].getClass().getSimpleName()) {
|
||||
case "String" -> args[i];
|
||||
case "TextStrings" -> ((TextStrings) args[i]).get(0).replace("\\\\n", "\\n"); // TODO: Change this to server language
|
||||
case "TextStrings" ->
|
||||
((TextStrings) args[i]).get(0).replace("\\\\n", "\\n"); // TODO: Change this to server language
|
||||
default -> args[i].toString();
|
||||
};
|
||||
}
|
||||
@@ -101,9 +114,10 @@ public final class Language {
|
||||
|
||||
/**
|
||||
* Returns the translated value from the key while substituting arguments.
|
||||
*
|
||||
* @param player Target player
|
||||
* @param key The key of the translated value to return.
|
||||
* @param args The arguments to substitute.
|
||||
* @param key The key of the translated value to return.
|
||||
* @param args The arguments to substitute.
|
||||
* @return A translated value with arguments substituted.
|
||||
*/
|
||||
public static String translate(Player player, String key, Object... args) {
|
||||
@@ -117,7 +131,8 @@ public final class Language {
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] = switch (args[i].getClass().getSimpleName()) {
|
||||
case "String" -> args[i];
|
||||
case "TextStrings" -> ((TextStrings) args[i]).getGC(langCode).replace("\\\\n", "\n"); // Note that we don't unescape \n for server console
|
||||
case "TextStrings" ->
|
||||
((TextStrings) args[i]).getGC(langCode).replace("\\\\n", "\n"); // Note that we don't unescape \n for server console
|
||||
default -> args[i].toString();
|
||||
};
|
||||
}
|
||||
@@ -130,21 +145,15 @@ public final class Language {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get language code
|
||||
*/
|
||||
public String getLanguageCode() {
|
||||
return languageCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive helper function to flatten a Json tree
|
||||
* Converts input like {"foo": {"bar": "baz"}} to {"foo.bar": "baz"}
|
||||
* @param map The map to insert the keys into
|
||||
* @param key The flattened key of the current element
|
||||
*
|
||||
* @param map The map to insert the keys into
|
||||
* @param key The flattened key of the current element
|
||||
* @param element The current element
|
||||
*/
|
||||
private static void putFlattenedKey(Map<String,String> map, String key, JsonElement element) {
|
||||
private static void putFlattenedKey(Map<String, String> map, String key, JsonElement element) {
|
||||
if (element.isJsonObject()) {
|
||||
element.getAsJsonObject().entrySet().forEach(entry -> {
|
||||
String keyPrefix = key.isEmpty() ? "" : key + ".";
|
||||
@@ -155,23 +164,10 @@ public final class Language {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a file and creates a language instance.
|
||||
*/
|
||||
private Language(LanguageStreamDescription description) {
|
||||
languageCode = description.getLanguageCode();
|
||||
|
||||
try {
|
||||
var object = JsonUtils.decode(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
|
||||
object.entrySet().forEach(entry -> putFlattenedKey(translations, entry.getKey(), entry.getValue()));
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to load language file: " + description.getLanguageCode(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* create a LanguageStreamDescription
|
||||
* @param languageCode The name of the language code.
|
||||
*
|
||||
* @param languageCode The name of the language code.
|
||||
* @param fallbackLanguageCode The name of the fallback language code.
|
||||
*/
|
||||
private static LanguageStreamDescription getLanguageFileDescription(String languageCode, String fallbackLanguageCode) {
|
||||
@@ -207,8 +203,164 @@ public final class Language {
|
||||
return new LanguageStreamDescription(actualLanguageCode, file);
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<String> loadTextMapFile(String language, IntSet nameHashes) {
|
||||
Int2ObjectMap<String> output = new Int2ObjectOpenHashMap<>();
|
||||
try (BufferedReader file = Files.newBufferedReader(getResourcePath("TextMap/TextMap" + language + ".json"), StandardCharsets.UTF_8)) {
|
||||
Matcher matcher = textMapKeyValueRegex.matcher("");
|
||||
return new Int2ObjectOpenHashMap<>(
|
||||
file.lines()
|
||||
.sequential()
|
||||
.map(matcher::reset) // Side effects, but it's faster than making a new one
|
||||
.filter(Matcher::find)
|
||||
.filter(m -> nameHashes.contains((int) Long.parseLong(m.group(1)))) // TODO: Cache this parse somehow
|
||||
.collect(Collectors.toMap(
|
||||
m -> (int) Long.parseLong(m.group(1)),
|
||||
m -> m.group(2).replace("\\\"", "\""))));
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("Error loading textmap: " + language);
|
||||
Grasscutter.getLogger().error(e.toString());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapFiles(IntSet nameHashes) {
|
||||
Map<Integer, Int2ObjectMap<String>> mapLanguageMaps = // Separate step to process the textmaps in parallel
|
||||
TextStrings.LIST_LANGUAGES.parallelStream().collect(
|
||||
Collectors.toConcurrentMap(s -> TextStrings.MAP_LANGUAGES.getInt(s), s -> loadTextMapFile(s, nameHashes)));
|
||||
List<Int2ObjectMap<String>> languageMaps =
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> mapLanguageMaps.get(i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Map<TextStrings, TextStrings> canonicalTextStrings = new HashMap<>();
|
||||
return new Int2ObjectOpenHashMap<TextStrings>(
|
||||
nameHashes
|
||||
.intStream()
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(key -> key, key -> {
|
||||
TextStrings t = new TextStrings(
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> languageMaps.get(i).get((int) key))
|
||||
.collect(Collectors.toList()), key);
|
||||
return canonicalTextStrings.computeIfAbsent(t, x -> t);
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapsCache() throws Exception {
|
||||
try (ObjectInputStream file = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(TEXTMAP_CACHE_PATH), 0x100000))) {
|
||||
final int fileVersion = file.readInt();
|
||||
if (fileVersion != TEXTMAP_CACHE_VERSION)
|
||||
throw new Exception("Invalid cache version");
|
||||
return (Int2ObjectMap<TextStrings>) file.readObject();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveTextMapsCache(Int2ObjectMap<TextStrings> input) throws IOException {
|
||||
try {
|
||||
Files.createDirectory(Path.of("cache"));
|
||||
} catch (FileAlreadyExistsException ignored) {
|
||||
}
|
||||
try (ObjectOutputStream file = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(TEXTMAP_CACHE_PATH, StandardOpenOption.CREATE), 0x100000))) {
|
||||
file.writeInt(TEXTMAP_CACHE_VERSION);
|
||||
file.writeObject(input);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static Int2ObjectMap<TextStrings> getTextMapStrings() {
|
||||
if (textMapStrings == null)
|
||||
loadTextMaps();
|
||||
return textMapStrings;
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(int key) {
|
||||
if ((textMapStrings == null) || (!scannedTextmaps && !textMapStrings.containsKey(key)))
|
||||
loadTextMaps();
|
||||
return textMapStrings.get(key);
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(long hash) {
|
||||
return getTextMapKey((int) hash);
|
||||
}
|
||||
|
||||
public static void loadTextMaps() {
|
||||
// Check system timestamps on cache and resources
|
||||
try {
|
||||
long cacheModified = Files.getLastModifiedTime(TEXTMAP_CACHE_PATH).toMillis();
|
||||
|
||||
long textmapsModified = Files.list(getResourcePath("TextMap"))
|
||||
.filter(path -> path.toString().endsWith(".json"))
|
||||
.map(path -> {
|
||||
try {
|
||||
return Files.getLastModifiedTime(path).toMillis();
|
||||
} catch (Exception ignored) {
|
||||
Grasscutter.getLogger().debug("Exception while checking modified time: ", path);
|
||||
return Long.MAX_VALUE; // Don't use cache, something has gone wrong
|
||||
}
|
||||
})
|
||||
.max(Long::compare)
|
||||
.get();
|
||||
|
||||
Grasscutter.getLogger().debug("Cache modified %d, textmap modified %d".formatted(cacheModified, textmapsModified));
|
||||
if (textmapsModified < cacheModified) {
|
||||
// Try loading from cache
|
||||
Grasscutter.getLogger().info("Loading cached 'TextMaps'...");
|
||||
textMapStrings = loadTextMapsCache();
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().debug("Exception while checking cache: ", e);
|
||||
}
|
||||
|
||||
// Regenerate cache
|
||||
Grasscutter.getLogger().debug("Generating TextMaps cache");
|
||||
ResourceLoader.loadAll();
|
||||
IntSet usedHashes = new IntOpenHashSet();
|
||||
GameData.getAchievementDataMap().values().stream()
|
||||
.filter(AchievementData::isUsed)
|
||||
.forEach(a -> {
|
||||
usedHashes.add((int) a.getTitleTextMapHash());
|
||||
usedHashes.add((int) a.getDescTextMapHash());
|
||||
});
|
||||
GameData.getAvatarDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getAvatarSkillDataMap().forEach((k, v) -> {
|
||||
usedHashes.add((int) v.getNameTextMapHash());
|
||||
usedHashes.add((int) v.getDescTextMapHash());
|
||||
});
|
||||
GameData.getItemDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getHomeWorldBgmDataMap().forEach((k, v) -> usedHashes.add((int) v.getBgmNameTextMapHash()));
|
||||
GameData.getMonsterDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getMainQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getTitleTextMapHash()));
|
||||
GameData.getQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getDescTextMapHash()));
|
||||
// Incidental strings
|
||||
usedHashes.add((int) 4233146695L); // Character
|
||||
usedHashes.add((int) 4231343903L); // Weapon
|
||||
usedHashes.add((int) 332935371L); // Standard Wish
|
||||
usedHashes.add((int) 2272170627L); // Character Event Wish
|
||||
usedHashes.add((int) 3352513147L); // Character Event Wish-2
|
||||
usedHashes.add((int) 2864268523L); // Weapon Event Wish
|
||||
|
||||
textMapStrings = loadTextMapFiles(usedHashes);
|
||||
scannedTextmaps = true;
|
||||
try {
|
||||
saveTextMapsCache(textMapStrings);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to save TextMap cache: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get language code
|
||||
*/
|
||||
public String getLanguageCode() {
|
||||
return languageCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value (as a string) from a nested key.
|
||||
*
|
||||
* @param key The key to look for.
|
||||
* @return The value (as a string) from a nested key.
|
||||
*/
|
||||
@@ -243,8 +395,8 @@ public final class Language {
|
||||
}
|
||||
}
|
||||
|
||||
private static final int TEXTMAP_CACHE_VERSION = 0x9CCACE04;
|
||||
@EqualsAndHashCode public static class TextStrings implements Serializable {
|
||||
@EqualsAndHashCode
|
||||
public static class TextStrings implements Serializable {
|
||||
public static final String[] ARR_LANGUAGES = {"EN", "CHS", "CHT", "JP", "KR", "DE", "ES", "FR", "ID", "PT", "RU", "TH", "VI"};
|
||||
public static final String[] ARR_GC_LANGUAGES = {"en-US", "zh-CN", "zh-TW", "ja-JP", "ko-KR", "en-US", "es-ES", "fr-FR", "en-US", "en-US", "ru-RU", "en-US", "en-US"}; // TODO: Update the placeholder en-US entries if we ever add GC translations for the missing client languages
|
||||
public static final int NUM_LANGUAGES = ARR_LANGUAGES.length;
|
||||
@@ -252,21 +404,22 @@ public final class Language {
|
||||
public static final Object2IntMap<String> MAP_LANGUAGES = // Map "EN": 0, "CHS": 1, ..., "VI": 12
|
||||
new Object2IntOpenHashMap<>(
|
||||
IntStream.range(0, ARR_LANGUAGES.length)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(i -> ARR_LANGUAGES[i], i -> i)));
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(i -> ARR_LANGUAGES[i], i -> i)));
|
||||
public static final Object2IntMap<String> MAP_GC_LANGUAGES = // Map "en-US": 0, "zh-CN": 1, ...
|
||||
new Object2IntOpenHashMap<>(
|
||||
IntStream.range(0, ARR_GC_LANGUAGES.length)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(i -> ARR_GC_LANGUAGES[i], i -> i, (i1, i2) -> i1))); // Have to handle duplicates referring back to the first
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(i -> ARR_GC_LANGUAGES[i], i -> i, (i1, i2) -> i1))); // Have to handle duplicates referring back to the first
|
||||
public String[] strings = new String[ARR_LANGUAGES.length];
|
||||
|
||||
public TextStrings() {};
|
||||
public TextStrings() {
|
||||
}
|
||||
|
||||
public TextStrings(String init) {
|
||||
for (int i = 0; i < NUM_LANGUAGES; i++)
|
||||
this.strings[i] = init;
|
||||
};
|
||||
}
|
||||
|
||||
public TextStrings(List<String> strings, int key) {
|
||||
// Some hashes don't have strings for some languages :(
|
||||
@@ -310,156 +463,4 @@ public final class Language {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Pattern textMapKeyValueRegex = Pattern.compile("\"(\\d+)\": \"(.+)\"");
|
||||
|
||||
private static Int2ObjectMap<String> loadTextMapFile(String language, IntSet nameHashes) {
|
||||
Int2ObjectMap<String> output = new Int2ObjectOpenHashMap<>();
|
||||
try (BufferedReader file = Files.newBufferedReader(getResourcePath("TextMap/TextMap"+language+".json"), StandardCharsets.UTF_8)) {
|
||||
Matcher matcher = textMapKeyValueRegex.matcher("");
|
||||
return new Int2ObjectOpenHashMap<>(
|
||||
file.lines()
|
||||
.sequential()
|
||||
.map(matcher::reset) // Side effects, but it's faster than making a new one
|
||||
.filter(Matcher::find)
|
||||
.filter(m -> nameHashes.contains((int) Long.parseLong(m.group(1)))) // TODO: Cache this parse somehow
|
||||
.collect(Collectors.toMap(
|
||||
m -> (int) Long.parseLong(m.group(1)),
|
||||
m -> m.group(2).replace("\\\"", "\""))));
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("Error loading textmap: " + language);
|
||||
Grasscutter.getLogger().error(e.toString());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapFiles(IntSet nameHashes) {
|
||||
Map<Integer, Int2ObjectMap<String>> mapLanguageMaps = // Separate step to process the textmaps in parallel
|
||||
TextStrings.LIST_LANGUAGES.parallelStream().collect(
|
||||
Collectors.toConcurrentMap(s -> TextStrings.MAP_LANGUAGES.getInt(s), s -> loadTextMapFile(s, nameHashes)));
|
||||
List<Int2ObjectMap<String>> languageMaps =
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> mapLanguageMaps.get(i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Map<TextStrings, TextStrings> canonicalTextStrings = new HashMap<>();
|
||||
return new Int2ObjectOpenHashMap<TextStrings>(
|
||||
nameHashes
|
||||
.intStream()
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(key -> key, key -> {
|
||||
TextStrings t = new TextStrings(
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> languageMaps.get(i).get((int) key))
|
||||
.collect(Collectors.toList()), (int) key);
|
||||
return canonicalTextStrings.computeIfAbsent(t, x -> t);
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapsCache() throws Exception {
|
||||
try (ObjectInputStream file = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(TEXTMAP_CACHE_PATH), 0x100000))) {
|
||||
final int fileVersion = file.readInt();
|
||||
if (fileVersion != TEXTMAP_CACHE_VERSION)
|
||||
throw new Exception("Invalid cache version");
|
||||
return (Int2ObjectMap<TextStrings>) file.readObject();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveTextMapsCache(Int2ObjectMap<TextStrings> input) throws IOException {
|
||||
try {
|
||||
Files.createDirectory(Path.of("cache"));
|
||||
} catch (FileAlreadyExistsException ignored) {};
|
||||
try (ObjectOutputStream file = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(TEXTMAP_CACHE_PATH, StandardOpenOption.CREATE), 0x100000))) {
|
||||
file.writeInt(TEXTMAP_CACHE_VERSION);
|
||||
file.writeObject(input);
|
||||
}
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<TextStrings> textMapStrings;
|
||||
private static final Path TEXTMAP_CACHE_PATH = Path.of(Utils.toFilePath("cache/TextMapCache.bin"));
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static Int2ObjectMap<TextStrings> getTextMapStrings() {
|
||||
if (textMapStrings == null)
|
||||
loadTextMaps();
|
||||
return textMapStrings;
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(int key) {
|
||||
if ((textMapStrings == null) || (!scannedTextmaps && !textMapStrings.containsKey(key)))
|
||||
loadTextMaps();
|
||||
return textMapStrings.get(key);
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(long hash) {
|
||||
return getTextMapKey((int) hash);
|
||||
}
|
||||
|
||||
public static void loadTextMaps() {
|
||||
// Check system timestamps on cache and resources
|
||||
try {
|
||||
long cacheModified = Files.getLastModifiedTime(TEXTMAP_CACHE_PATH).toMillis();
|
||||
|
||||
long textmapsModified = Files.list(getResourcePath("TextMap"))
|
||||
.filter(path -> path.toString().endsWith(".json"))
|
||||
.map(path -> {
|
||||
try {
|
||||
return Files.getLastModifiedTime(path).toMillis();
|
||||
} catch (Exception ignored) {
|
||||
Grasscutter.getLogger().debug("Exception while checking modified time: ", path);
|
||||
return Long.MAX_VALUE; // Don't use cache, something has gone wrong
|
||||
}
|
||||
})
|
||||
.max(Long::compare)
|
||||
.get();
|
||||
|
||||
Grasscutter.getLogger().debug("Cache modified %d, textmap modified %d".formatted(cacheModified, textmapsModified));
|
||||
if (textmapsModified < cacheModified) {
|
||||
// Try loading from cache
|
||||
Grasscutter.getLogger().info("Loading cached 'TextMaps'...");
|
||||
textMapStrings = loadTextMapsCache();
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().debug("Exception while checking cache: ", e);
|
||||
};
|
||||
|
||||
// Regenerate cache
|
||||
Grasscutter.getLogger().debug("Generating TextMaps cache");
|
||||
ResourceLoader.loadAll();
|
||||
IntSet usedHashes = new IntOpenHashSet();
|
||||
GameData.getAchievementDataMap().values().stream()
|
||||
.filter(AchievementData::isUsed)
|
||||
.forEach(a -> {
|
||||
usedHashes.add((int) a.getTitleTextMapHash());
|
||||
usedHashes.add((int) a.getDescTextMapHash());
|
||||
});
|
||||
GameData.getAvatarDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getAvatarSkillDataMap().forEach((k, v) -> {
|
||||
usedHashes.add((int) v.getNameTextMapHash());
|
||||
usedHashes.add((int) v.getDescTextMapHash());
|
||||
});
|
||||
GameData.getItemDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getHomeWorldBgmDataMap().forEach((k, v) -> usedHashes.add((int) v.getBgmNameTextMapHash()));
|
||||
GameData.getMonsterDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getMainQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getTitleTextMapHash()));
|
||||
GameData.getQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getDescTextMapHash()));
|
||||
// Incidental strings
|
||||
usedHashes.add((int) 4233146695L); // Character
|
||||
usedHashes.add((int) 4231343903L); // Weapon
|
||||
usedHashes.add((int) 332935371L); // Standard Wish
|
||||
usedHashes.add((int) 2272170627L); // Character Event Wish
|
||||
usedHashes.add((int) 3352513147L); // Character Event Wish-2
|
||||
usedHashes.add((int) 2864268523L); // Weapon Event Wish
|
||||
|
||||
textMapStrings = loadTextMapFiles(usedHashes);
|
||||
scannedTextmaps = true;
|
||||
try {
|
||||
saveTextMapsCache(textMapStrings);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to save TextMap cache: ", e);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
public class Location extends Position {
|
||||
@Transient @Getter @Setter
|
||||
@Transient
|
||||
@Getter
|
||||
@Setter
|
||||
private Scene scene;
|
||||
|
||||
public Location(Scene scene, Position position) {
|
||||
|
||||
@@ -3,19 +3,19 @@ package emu.grasscutter.utils;
|
||||
public class MessageHandler {
|
||||
private String message;
|
||||
|
||||
public MessageHandler(){
|
||||
public MessageHandler() {
|
||||
this.message = "";
|
||||
}
|
||||
|
||||
public void append(String message){
|
||||
public void append(String message) {
|
||||
this.message += message + "\r\n\r\n";
|
||||
}
|
||||
|
||||
public String getMessage(){
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
public void setMessage(String message){
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,36 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import com.github.davidmoten.rtreemulti.geometry.Point;
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import dev.morphia.annotations.Entity;
|
||||
import emu.grasscutter.net.proto.VectorOuterClass.Vector;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Position implements Serializable {
|
||||
private static final long serialVersionUID = -2001232313615923575L;
|
||||
|
||||
@SerializedName(value="x", alternate={"_x", "X"})
|
||||
@Getter @Setter private float x;
|
||||
@SerializedName(value = "x", alternate = {"_x", "X"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float x;
|
||||
|
||||
@SerializedName(value="y", alternate={"_y", "Y"})
|
||||
@Getter @Setter private float y;
|
||||
@SerializedName(value = "y", alternate = {"_y", "Y"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float y;
|
||||
|
||||
@SerializedName(value="z", alternate={"_z", "Z"})
|
||||
@Getter @Setter private float z;
|
||||
@SerializedName(value = "z", alternate = {"_z", "Z"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float z;
|
||||
|
||||
public Position() {}
|
||||
public Position() {
|
||||
}
|
||||
|
||||
public Position(float x, float y) {
|
||||
set(x, y);
|
||||
@@ -117,8 +124,9 @@ public class Position implements Serializable {
|
||||
return this;
|
||||
}
|
||||
|
||||
/** In radians
|
||||
* */
|
||||
/**
|
||||
* In radians
|
||||
*/
|
||||
public Position translate(float dist, float angle) {
|
||||
this.x += dist * Math.sin(angle);
|
||||
this.y += dist * Math.cos(angle);
|
||||
@@ -135,10 +143,10 @@ public class Position implements Serializable {
|
||||
}
|
||||
|
||||
public double computeDistance(Position b) {
|
||||
double detX = getX()-b.getX();
|
||||
double detY = getY()-b.getY();
|
||||
double detZ = getZ()-b.getZ();
|
||||
return Math.sqrt(detX*detX+detY*detY+detZ*detZ);
|
||||
double detX = getX() - b.getX();
|
||||
double detY = getY() - b.getY();
|
||||
double detZ = getZ() - b.getZ();
|
||||
return Math.sqrt(detX * detX + detY * detY + detZ * detZ);
|
||||
}
|
||||
|
||||
public Position nearby2d(float range) {
|
||||
@@ -147,6 +155,7 @@ public class Position implements Serializable {
|
||||
position.x += Utils.randomFloatRange(-range, range);
|
||||
return position;
|
||||
}
|
||||
|
||||
public Position translateWithDegrees(float dist, float angle) {
|
||||
angle = (float) Math.toRadians(angle);
|
||||
this.x += dist * Math.sin(angle);
|
||||
@@ -171,16 +180,18 @@ public class Position implements Serializable {
|
||||
.setZ(this.getZ())
|
||||
.build();
|
||||
}
|
||||
|
||||
public Point toPoint() {
|
||||
return Point.create(x,y,z);
|
||||
return Point.create(x, y, z);
|
||||
}
|
||||
|
||||
/**
|
||||
* To XYZ array for Spatial Index
|
||||
*/
|
||||
public double[] toDoubleArray() {
|
||||
return new double[]{ x, y, z};
|
||||
return new double[]{x, y, z};
|
||||
}
|
||||
|
||||
/**
|
||||
* To XZ array for Spatial Index (Blocks)
|
||||
*/
|
||||
|
||||
@@ -4,7 +4,7 @@ import emu.grasscutter.game.props.PlayerProperty;
|
||||
import emu.grasscutter.net.proto.PropValueOuterClass.PropValue;
|
||||
|
||||
public final class ProtoHelper {
|
||||
public static PropValue newPropValue(PlayerProperty key, int value) {
|
||||
return PropValue.newBuilder().setType(key.getId()).setIval(value).setVal(value).build();
|
||||
}
|
||||
public static PropValue newPropValue(PlayerProperty key, int value) {
|
||||
return PropValue.newBuilder().setType(key.getId()).setIval(value).setVal(value).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,8 @@ package emu.grasscutter.utils;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
import ch.qos.logback.core.encoder.Encoder;
|
||||
import ch.qos.logback.core.spi.DeferredProcessingAware;
|
||||
import ch.qos.logback.core.status.ErrorStatus;
|
||||
import emu.grasscutter.server.event.internal.ServerLogEvent;
|
||||
import emu.grasscutter.server.event.types.ServerEvent;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class ServerLogEventAppender<E> extends AppenderBase<E> {
|
||||
|
||||
@@ -6,30 +6,8 @@ import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
public final class SparseSet {
|
||||
/*
|
||||
* A convenience class for constructing integer sets out of large ranges
|
||||
* Designed to be fed literal strings from this project only -
|
||||
* can and will throw exceptions to tell you to fix your code if you feed it garbage. :)
|
||||
*/
|
||||
private static class Range {
|
||||
private final int min, max;
|
||||
|
||||
public Range(int min, int max) {
|
||||
if (min > max) {
|
||||
throw new IllegalArgumentException("Range passed minimum higher than maximum - " + Integer.toString(min) + " > " + Integer.toString(max));
|
||||
}
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public boolean check(int value) {
|
||||
return value >= this.min && value <= this.max;
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Range> rangeEntries;
|
||||
private final Set<Integer> denseEntries;
|
||||
|
||||
public SparseSet(String csv) {
|
||||
this.rangeEntries = new ArrayList<>();
|
||||
this.denseEntries = new TreeSet<>();
|
||||
@@ -44,7 +22,7 @@ public final class SparseSet {
|
||||
this.rangeEntries.add(new Range(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])));
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid token passed to SparseSet initializer - " + token + " (split length " + Integer.toString(tokens.length) + ")");
|
||||
throw new IllegalArgumentException("Invalid token passed to SparseSet initializer - " + token + " (split length " + tokens.length + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,4 +35,25 @@ public final class SparseSet {
|
||||
}
|
||||
return this.denseEntries.contains(i);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* A convenience class for constructing integer sets out of large ranges
|
||||
* Designed to be fed literal strings from this project only -
|
||||
* can and will throw exceptions to tell you to fix your code if you feed it garbage. :)
|
||||
*/
|
||||
private static class Range {
|
||||
private final int min, max;
|
||||
|
||||
public Range(int min, int max) {
|
||||
if (min > max) {
|
||||
throw new IllegalArgumentException("Range passed minimum higher than maximum - " + min + " > " + max);
|
||||
}
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public boolean check(int value) {
|
||||
return value >= this.min && value <= this.max;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,34 +17,40 @@ import static emu.grasscutter.config.Configuration.*;
|
||||
* A parser for start-up arguments.
|
||||
*/
|
||||
public final class StartupArguments {
|
||||
private StartupArguments() {
|
||||
// This class is not meant to be instantiated.
|
||||
}
|
||||
|
||||
/* A map of parameter -> argument handler. */
|
||||
private static final Map<String, Function<String, Boolean>> argumentHandlers = Map.of(
|
||||
"-dumppacketids", parameter -> {
|
||||
PacketOpcodesUtils.dumpPacketIds(); return true;
|
||||
PacketOpcodesUtils.dumpPacketIds();
|
||||
return true;
|
||||
},
|
||||
"-version", StartupArguments::printVersion,
|
||||
"-debug", StartupArguments::enableDebug,
|
||||
"-lang", parameter -> {
|
||||
Grasscutter.setPreferredLanguage(parameter); return false;
|
||||
},"-game", parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.GAME_ONLY); return false;
|
||||
},"-dispatch", parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.DISPATCH_ONLY); return false;
|
||||
Grasscutter.setPreferredLanguage(parameter);
|
||||
return false;
|
||||
}, "-game", parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.GAME_ONLY);
|
||||
return false;
|
||||
}, "-dispatch", parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.DISPATCH_ONLY);
|
||||
return false;
|
||||
},
|
||||
|
||||
// Aliases.
|
||||
"-v", StartupArguments::printVersion,
|
||||
"-debugall", parameter -> {
|
||||
StartupArguments.enableDebug("all"); return false;
|
||||
StartupArguments.enableDebug("all");
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
private StartupArguments() {
|
||||
// This class is not meant to be instantiated.
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the provided start-up arguments.
|
||||
*
|
||||
* @param args The application start-up arguments.
|
||||
* @return If the application should exit.
|
||||
*/
|
||||
@@ -68,15 +74,18 @@ public final class StartupArguments {
|
||||
|
||||
/**
|
||||
* Prints the server version.
|
||||
*
|
||||
* @param parameter Additional parameters.
|
||||
* @return True to exit early.
|
||||
*/
|
||||
private static boolean printVersion(String parameter) {
|
||||
System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH); return true;
|
||||
System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables debug logging.
|
||||
*
|
||||
* @param parameter Additional parameters.
|
||||
* @return False to continue execution.
|
||||
*/
|
||||
|
||||
@@ -1,34 +1,7 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import it.unimi.dsi.fastutil.Pair;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectRBTreeMap;
|
||||
@@ -36,6 +9,17 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectSortedMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntArrayMap;
|
||||
import lombok.val;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static emu.grasscutter.utils.Utils.nonRegexSplit;
|
||||
|
||||
// Throughout this file, commented System.out.println debug log calls are left in.
|
||||
@@ -59,7 +43,8 @@ public class TsvUtils {
|
||||
private static final Function<String, Object> parseString = value -> value;
|
||||
private static final Function<String, Object> parseInt = value -> (int) Double.parseDouble(value); //Integer::parseInt;
|
||||
private static final Function<String, Object> parseLong = value -> (long) Double.parseDouble(value); //Long::parseLong;
|
||||
private static Map<Type, Function<String, Object>> primitiveTypeParsers = Map.ofEntries(
|
||||
private static final Map<Class<?>, Function<String, Object>> enumTypeParsers = new HashMap<>();
|
||||
private static final Map<Type, Function<String, Object>> primitiveTypeParsers = Map.ofEntries(
|
||||
Map.entry(String.class, parseString),
|
||||
Map.entry(Integer.class, parseInt),
|
||||
Map.entry(int.class, parseInt),
|
||||
@@ -73,17 +58,20 @@ public class TsvUtils {
|
||||
Map.entry(boolean.class, Boolean::parseBoolean)
|
||||
);
|
||||
private static final Map<Type, Function<String, Object>> typeParsers = new HashMap<>(primitiveTypeParsers);
|
||||
private static final Map<Class<?>, Map<String, FieldParser>> cachedClassFieldMaps = new HashMap<>();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> T parsePrimitive(Class<T> type, String string) {
|
||||
if (string == null || string.isEmpty()) return (T) defaultValues.get(type);
|
||||
return (T) primitiveTypeParsers.get(type).apply(string);
|
||||
}
|
||||
|
||||
// This is more expensive than parsing as the correct types, but it is more tolerant of mismatched data like ints with .0
|
||||
private static double parseNumber(String string) {
|
||||
if (string == null || string.isEmpty()) return 0d;
|
||||
return Double.parseDouble(string);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> T parseEnum(Class<T> enumType, String string) {
|
||||
if (string == null || string.isEmpty()) return null;
|
||||
@@ -99,8 +87,8 @@ public class TsvUtils {
|
||||
}
|
||||
}
|
||||
|
||||
private static final Map<Class<?>, Function<String, Object>> enumTypeParsers = new HashMap<>();
|
||||
@SuppressWarnings("deprecated") // Field::isAccessible is deprecated because it doesn't do what people think it does. It does what we want it to, however.
|
||||
@SuppressWarnings("deprecated")
|
||||
// Field::isAccessible is deprecated because it doesn't do what people think it does. It does what we want it to, however.
|
||||
private static Function<String, Object> makeEnumTypeParser(Class<?> enumClass) {
|
||||
if (!enumClass.isEnum()) {
|
||||
// System.out.println("Called makeEnumTypeParser with non-enum enumClass "+enumClass);
|
||||
@@ -116,7 +104,10 @@ public class TsvUtils {
|
||||
// If the enum also has a numeric value, map those to the constants too
|
||||
// System.out.println("Looking for enum value field");
|
||||
for (Field f : enumClass.getDeclaredFields()) {
|
||||
if (switch (f.getName()) {case "value", "id" -> true; default -> false;}) {
|
||||
if (switch (f.getName()) {
|
||||
case "value", "id" -> true;
|
||||
default -> false;
|
||||
}) {
|
||||
// System.out.println("Enum value field found - " + f.getName());
|
||||
boolean acc = f.isAccessible();
|
||||
f.setAccessible(true);
|
||||
@@ -132,6 +123,7 @@ public class TsvUtils {
|
||||
}
|
||||
return map::get;
|
||||
}
|
||||
|
||||
private static synchronized Function<String, Object> getEnumTypeParser(Class<?> enumType) {
|
||||
if (enumType == null) {
|
||||
// System.out.println("Called getEnumTypeParser with null enumType");
|
||||
@@ -146,8 +138,9 @@ public class TsvUtils {
|
||||
}
|
||||
|
||||
private static Type class2Type(Class<?> classType) {
|
||||
return (Type) classType.getGenericSuperclass();
|
||||
return classType.getGenericSuperclass();
|
||||
}
|
||||
|
||||
private static Class<?> type2Class(Type type) {
|
||||
if (type instanceof Class) {
|
||||
return (Class<?>) type;
|
||||
@@ -158,29 +151,6 @@ public class TsvUtils {
|
||||
}
|
||||
}
|
||||
|
||||
// A helper object that contains a Field and the function to parse a String to create the value for the Field.
|
||||
private static class FieldParser {
|
||||
public final Field field;
|
||||
public final Type type;
|
||||
public final Class<?> classType;
|
||||
public final Function<String, Object> parser;
|
||||
|
||||
FieldParser(Field field) {
|
||||
this.field = field;
|
||||
this.type = field.getGenericType(); // returns specialized type info e.g. java.util.List<java.lang.Integer>
|
||||
this.classType = field.getType();
|
||||
this.parser = getTypeParser(this.type);
|
||||
}
|
||||
|
||||
public Object parse(String token) {
|
||||
return this.parser.apply(token);
|
||||
}
|
||||
|
||||
public void parse(Object obj, String token) throws IllegalAccessException {
|
||||
this.field.set(obj, this.parser.apply(token));
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, FieldParser> makeClassFieldMap(Class<?> classType) {
|
||||
val fieldMap = new HashMap<String, FieldParser>();
|
||||
for (Field field : classType.getDeclaredFields()) {
|
||||
@@ -200,205 +170,10 @@ public class TsvUtils {
|
||||
return fieldMap;
|
||||
}
|
||||
|
||||
private static Map<Class<?>, Map<String, FieldParser>> cachedClassFieldMaps = new HashMap<>();
|
||||
private static synchronized Map<String, FieldParser> getClassFieldMap(Class<?> classType) {
|
||||
return cachedClassFieldMaps.computeIfAbsent(classType, TsvUtils::makeClassFieldMap);
|
||||
}
|
||||
|
||||
private static class StringTree {
|
||||
public final Map<String, StringTree> children = new TreeMap<>();
|
||||
|
||||
public void addPath(String path) {
|
||||
if (path.isEmpty()) return;
|
||||
|
||||
val firstDot = path.indexOf('.');
|
||||
val fieldPath = (firstDot < 0) ? path : path.substring(0, firstDot);
|
||||
val remainder = (firstDot < 0) ? "" : path.substring(firstDot+1);
|
||||
this.children.computeIfAbsent(fieldPath, k -> new StringTree()).addPath(remainder);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static class StringValueTree {
|
||||
public final SortedMap<String, StringValueTree> children = new TreeMap<>();
|
||||
public final Int2ObjectSortedMap<StringValueTree> arrayChildren = new Int2ObjectRBTreeMap<>();
|
||||
public String value;
|
||||
|
||||
public StringValueTree(StringTree from) {
|
||||
from.children.forEach((k,v) -> {
|
||||
try {
|
||||
this.arrayChildren.put(Integer.parseInt(k), new StringValueTree(v));
|
||||
} catch (NumberFormatException e) {
|
||||
this.children.put(k, new StringValueTree(v));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setValue(String path, String value) {
|
||||
if (path.isEmpty()) {
|
||||
this.value = value;
|
||||
return;
|
||||
}
|
||||
|
||||
val firstDot = path.indexOf('.');
|
||||
val fieldPath = (firstDot < 0) ? path : path.substring(0, firstDot);
|
||||
val remainder = (firstDot < 0) ? "" : path.substring(firstDot+1);
|
||||
try {
|
||||
this.arrayChildren.get(Integer.parseInt(fieldPath)).setValue(remainder, value);
|
||||
} catch (NumberFormatException e) {
|
||||
this.children.get(fieldPath).setValue(remainder, value);
|
||||
}
|
||||
}
|
||||
|
||||
public JsonElement toJson() {
|
||||
// Determine if this is an object, an array, or a value
|
||||
if (this.value != null) { //
|
||||
return new JsonPrimitive(this.value);
|
||||
}
|
||||
if (!this.arrayChildren.isEmpty()) {
|
||||
val arr = new JsonArray(this.arrayChildren.lastIntKey()+1);
|
||||
arrayChildren.forEach((k,v) -> arr.set(k, v.toJson()));
|
||||
return arr;
|
||||
} else if (this.children.isEmpty()) {
|
||||
return JsonNull.INSTANCE;
|
||||
} else {
|
||||
val obj = new JsonObject();
|
||||
children.forEach((k,v) -> {
|
||||
val j = v.toJson();
|
||||
if (j != JsonNull.INSTANCE)
|
||||
obj.add(k, v.toJson());
|
||||
});
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T toClass(Class<T> classType, Type type) {
|
||||
// System.out.println("toClass called with Class: "+classType+" \tType: "+type);
|
||||
if (type == null)
|
||||
type = class2Type(classType);
|
||||
|
||||
if (primitiveTypeParsers.containsKey(classType)) {
|
||||
return parsePrimitive(classType, this.value);
|
||||
} else if (classType.isEnum()) {
|
||||
return parseEnum(classType, this.value);
|
||||
} else if (classType.isArray()) {
|
||||
return this.toArray(classType);
|
||||
} else if (List.class.isAssignableFrom(classType)) {
|
||||
// if (type instanceof ParameterizedType)
|
||||
val elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
|
||||
return (T) this.toList(type2Class(elementType), elementType);
|
||||
} else if (Map.class.isAssignableFrom(classType)) {
|
||||
// System.out.println("Class: "+classType+" \tClassTypeParams: "+Arrays.toString(classType.getTypeParameters())+" \tType: "+type+" \tTypeArguments: "+Arrays.toString(((ParameterizedType) type).getActualTypeArguments()));
|
||||
// if (type instanceof ParameterizedType)
|
||||
val keyType = ((ParameterizedType) type).getActualTypeArguments()[0];
|
||||
val valueType = ((ParameterizedType) type).getActualTypeArguments()[1];
|
||||
return (T) this.toMap(type2Class(keyType), type2Class(valueType), valueType);
|
||||
} else {
|
||||
return this.toObj(classType, type);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T toObj(Class<T> objClass, Type objType) {
|
||||
try {
|
||||
// val obj = objClass.getDeclaredConstructor().newInstance();
|
||||
val obj = newObj(objClass);
|
||||
val fieldMap = getClassFieldMap(objClass);
|
||||
this.children.forEach((name, tree) -> {
|
||||
val field = fieldMap.get(name);
|
||||
if (field == null) return;
|
||||
try {
|
||||
if (primitiveTypes.contains(field.type)) {
|
||||
if ((tree.value != null) && !tree.value.isEmpty())
|
||||
field.parse(obj, tree.value);
|
||||
} else {
|
||||
val value = tree.toClass(field.classType, field.type);
|
||||
// System.out.println("Setting field "+name+" to "+value);
|
||||
field.field.set(obj, value);
|
||||
// field.field.set(obj, tree.toClass(field.classType, field.type));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// System.out.println("Exception while setting field "+name+" for class "+objClass+" - "+e);
|
||||
Grasscutter.getLogger().error("Exception while setting field "+name+" ("+field.classType+")"+" for class "+objClass+" - ",e);
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
} catch (Exception e) {
|
||||
// System.out.println("Exception while creating object of class "+objClass+" - "+e);
|
||||
Grasscutter.getLogger().error("Exception while creating object of class "+objClass+" - ",e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T toArray(Class<T> classType) {
|
||||
// Primitives don't play so nice with generics, so we handle all of them individually.
|
||||
val containedClass = classType.getComponentType();
|
||||
// val arraySize = this.arrayChildren.size(); // Assume dense 0-indexed
|
||||
val arraySize = this.arrayChildren.lastIntKey()+1; // Could be sparse!
|
||||
// System.out.println("toArray called with Class: "+classType+" \tContains: "+containedClass+" \tof size: "+arraySize);
|
||||
if (containedClass == int.class) {
|
||||
val output = new int[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (int) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == long.class) {
|
||||
val output = new long[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (long) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == float.class) {
|
||||
val output = new float[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (float) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == double.class) {
|
||||
val output = new double[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (double) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == byte.class) {
|
||||
val output = new byte[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (byte) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == char.class) {
|
||||
val output = new char[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (char) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == short.class) {
|
||||
val output = new short[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (short) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == boolean.class) {
|
||||
val output = new boolean[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> {
|
||||
val value = ((tree.value == null) || tree.value.isEmpty()) ? false : Boolean.parseBoolean(tree.value);
|
||||
output[idx] = value;
|
||||
});
|
||||
return (T) output;
|
||||
} else {
|
||||
val output = Array.newInstance(containedClass, arraySize);
|
||||
this.arrayChildren.forEach((idx, tree) -> ((Object[]) output)[idx] = tree.toClass(containedClass, null));
|
||||
return (T) output;
|
||||
}
|
||||
}
|
||||
|
||||
private <E> List<E> toList(Class<E> valueClass, Type valueType) {
|
||||
val arraySize = this.arrayChildren.lastIntKey()+1; // Could be sparse!
|
||||
// System.out.println("toList called with valueClass: "+valueClass+" \tvalueType: "+valueType+" \tof size: "+arraySize);
|
||||
val list = new ArrayList<E>(arraySize);
|
||||
// Safe sparse version
|
||||
for (int i = 0; i < arraySize; i++)
|
||||
list.add(null);
|
||||
this.arrayChildren.forEach((idx, tree) -> list.set(idx, tree.toClass(valueClass, valueType)));
|
||||
return list;
|
||||
}
|
||||
|
||||
private <K,V> Map<K,V> toMap(Class<K> keyClass, Class<V> valueClass, Type valueType) {
|
||||
val map = new HashMap<K,V>();
|
||||
val keyParser = getTypeParser(keyClass);
|
||||
this.children.forEach((key, tree) -> {
|
||||
if ((key != null) && !key.isEmpty())
|
||||
map.put((K) keyParser.apply(key), tree.toClass(valueClass, valueType));
|
||||
});
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
// Flat tab-separated value tables.
|
||||
// Arrays are represented as arrayName.0, arrayName.1, etc. columns.
|
||||
// Maps/POJOs are represented as objName.fieldOneName, objName.fieldTwoName, etc. columns.
|
||||
@@ -416,7 +191,7 @@ public class TsvUtils {
|
||||
headerNames.forEach(stringTree::addPath);
|
||||
|
||||
return fileReader.lines().parallel().map(line -> {
|
||||
// return fileReader.lines().map(line -> {
|
||||
// return fileReader.lines().map(line -> {
|
||||
// System.out.println("Processing line of "+filename+" - "+line);
|
||||
val tokens = nonRegexSplit(line, '\t');
|
||||
val m = Math.min(tokens.size(), columns);
|
||||
@@ -432,10 +207,10 @@ public class TsvUtils {
|
||||
// return JsonUtils.decode(tree.toJson(), classType);
|
||||
return tree.toClass(classType, null);
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().warn("Error deserializing an instance of class "+classType.getCanonicalName());
|
||||
Grasscutter.getLogger().warn("At token #"+t+" of #"+m);
|
||||
Grasscutter.getLogger().warn("Header names are: "+headerNames.toString());
|
||||
Grasscutter.getLogger().warn("Tokens are: "+tokens.toString());
|
||||
Grasscutter.getLogger().warn("Error deserializing an instance of class " + classType.getCanonicalName());
|
||||
Grasscutter.getLogger().warn("At token #" + t + " of #" + m);
|
||||
Grasscutter.getLogger().warn("Header names are: " + headerNames);
|
||||
Grasscutter.getLogger().warn("Tokens are: " + tokens);
|
||||
Grasscutter.getLogger().warn("Stacktrace is: ", e);
|
||||
// System.out.println("Error deserializing an instance of class "+classType.getCanonicalName());
|
||||
// System.out.println("At token #"+t+" of #"+m);
|
||||
@@ -447,7 +222,7 @@ public class TsvUtils {
|
||||
}
|
||||
}).toList();
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("Error loading file '"+filename+"' - Stacktrace is: ", e);
|
||||
Grasscutter.getLogger().error("Error loading file '" + filename + "' - Stacktrace is: ", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -480,28 +255,26 @@ public class TsvUtils {
|
||||
}
|
||||
return obj;
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().warn("Error deserializing an instance of class "+classType.getCanonicalName());
|
||||
Grasscutter.getLogger().warn("At token #"+t+" of #"+m);
|
||||
Grasscutter.getLogger().warn("Header names are: "+headerNames.toString());
|
||||
Grasscutter.getLogger().warn("Tokens are: "+tokens.toString());
|
||||
Grasscutter.getLogger().warn("Error deserializing an instance of class " + classType.getCanonicalName());
|
||||
Grasscutter.getLogger().warn("At token #" + t + " of #" + m);
|
||||
Grasscutter.getLogger().warn("Header names are: " + headerNames);
|
||||
Grasscutter.getLogger().warn("Tokens are: " + tokens);
|
||||
Grasscutter.getLogger().warn("Stacktrace is: ", e);
|
||||
return null;
|
||||
}
|
||||
}).toList();
|
||||
} catch (NoSuchFileException e) {
|
||||
Grasscutter.getLogger().error("Error loading file '"+filename+"' - File does not exist. You are missing resources. Note that this file may exist in JSON, TSV, or TSJ format, any of which are suitable.");
|
||||
Grasscutter.getLogger().error("Error loading file '" + filename + "' - File does not exist. You are missing resources. Note that this file may exist in JSON, TSV, or TSJ format, any of which are suitable.");
|
||||
return null;
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Error loading file '"+filename+"' - Stacktrace is: ", e);
|
||||
Grasscutter.getLogger().error("Error loading file '" + filename + "' - Stacktrace is: ", e);
|
||||
return null;
|
||||
} catch (NoSuchMethodException e) {
|
||||
Grasscutter.getLogger().error("Error loading file '"+filename+"' - Class is missing NoArgsConstructor");
|
||||
Grasscutter.getLogger().error("Error loading file '" + filename + "' - Class is missing NoArgsConstructor");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Everything below here is for the AllArgsConstructor TSJ parser
|
||||
// -----------------------------------------------------------------
|
||||
@@ -521,7 +294,7 @@ public class TsvUtils {
|
||||
public static <T> List<List<T>> loadTsjsToListsConstructor(Class<T> classType, Path... filenames) throws Exception {
|
||||
val pair = getAllArgsConstructor(classType);
|
||||
if (pair == null) {
|
||||
Grasscutter.getLogger().error("No AllArgsContructor found for class: "+classType);
|
||||
Grasscutter.getLogger().error("No AllArgsContructor found for class: " + classType);
|
||||
return null;
|
||||
}
|
||||
val constructor = pair.left();
|
||||
@@ -576,25 +349,242 @@ public class TsvUtils {
|
||||
args[argIndex] = argParsers.get(argIndex).apply(token);
|
||||
}
|
||||
}
|
||||
return (T) constructor.newInstance(args);
|
||||
return constructor.newInstance(args);
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().warn("Error deserializing an instance of class "+classType.getCanonicalName()+" : "+constructor.getName());
|
||||
Grasscutter.getLogger().warn("At token #"+t+" of #"+m);
|
||||
Grasscutter.getLogger().warn("Arg names are: "+Arrays.toString(conArgNames));
|
||||
Grasscutter.getLogger().warn("Arg types are: "+Arrays.toString(argTypes));
|
||||
Grasscutter.getLogger().warn("Default Args are: "+Arrays.toString(defaultArgs));
|
||||
Grasscutter.getLogger().warn("Args are: "+Arrays.toString(args));
|
||||
Grasscutter.getLogger().warn("Header names are: "+headerNames.toString());
|
||||
Grasscutter.getLogger().warn("Header types are: "+IntStream.of(argPositions).mapToObj(i -> (i >= 0) ? argTypes[i] : null).toList());
|
||||
Grasscutter.getLogger().warn("Tokens are: "+tokens.toString());
|
||||
Grasscutter.getLogger().warn("Error deserializing an instance of class " + classType.getCanonicalName() + " : " + constructor.getName());
|
||||
Grasscutter.getLogger().warn("At token #" + t + " of #" + m);
|
||||
Grasscutter.getLogger().warn("Arg names are: " + Arrays.toString(conArgNames));
|
||||
Grasscutter.getLogger().warn("Arg types are: " + Arrays.toString(argTypes));
|
||||
Grasscutter.getLogger().warn("Default Args are: " + Arrays.toString(defaultArgs));
|
||||
Grasscutter.getLogger().warn("Args are: " + Arrays.toString(args));
|
||||
Grasscutter.getLogger().warn("Header names are: " + headerNames);
|
||||
Grasscutter.getLogger().warn("Header types are: " + IntStream.of(argPositions).mapToObj(i -> (i >= 0) ? argTypes[i] : null).toList());
|
||||
Grasscutter.getLogger().warn("Tokens are: " + tokens);
|
||||
Grasscutter.getLogger().warn("Stacktrace is: ", e);
|
||||
return null;
|
||||
}
|
||||
}).toList();
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Error loading file '"+filename+"' - Stacktrace is: ", e);
|
||||
Grasscutter.getLogger().error("Error loading file '" + filename + "' - Stacktrace is: ", e);
|
||||
return null;
|
||||
}
|
||||
}).toList();
|
||||
}
|
||||
|
||||
// A helper object that contains a Field and the function to parse a String to create the value for the Field.
|
||||
private static class FieldParser {
|
||||
public final Field field;
|
||||
public final Type type;
|
||||
public final Class<?> classType;
|
||||
public final Function<String, Object> parser;
|
||||
|
||||
FieldParser(Field field) {
|
||||
this.field = field;
|
||||
this.type = field.getGenericType(); // returns specialized type info e.g. java.util.List<java.lang.Integer>
|
||||
this.classType = field.getType();
|
||||
this.parser = getTypeParser(this.type);
|
||||
}
|
||||
|
||||
public Object parse(String token) {
|
||||
return this.parser.apply(token);
|
||||
}
|
||||
|
||||
public void parse(Object obj, String token) throws IllegalAccessException {
|
||||
this.field.set(obj, this.parser.apply(token));
|
||||
}
|
||||
}
|
||||
|
||||
private static class StringTree {
|
||||
public final Map<String, StringTree> children = new TreeMap<>();
|
||||
|
||||
public void addPath(String path) {
|
||||
if (path.isEmpty()) return;
|
||||
|
||||
val firstDot = path.indexOf('.');
|
||||
val fieldPath = (firstDot < 0) ? path : path.substring(0, firstDot);
|
||||
val remainder = (firstDot < 0) ? "" : path.substring(firstDot + 1);
|
||||
this.children.computeIfAbsent(fieldPath, k -> new StringTree()).addPath(remainder);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static class StringValueTree {
|
||||
public final SortedMap<String, StringValueTree> children = new TreeMap<>();
|
||||
public final Int2ObjectSortedMap<StringValueTree> arrayChildren = new Int2ObjectRBTreeMap<>();
|
||||
public String value;
|
||||
|
||||
public StringValueTree(StringTree from) {
|
||||
from.children.forEach((k, v) -> {
|
||||
try {
|
||||
this.arrayChildren.put(Integer.parseInt(k), new StringValueTree(v));
|
||||
} catch (NumberFormatException e) {
|
||||
this.children.put(k, new StringValueTree(v));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setValue(String path, String value) {
|
||||
if (path.isEmpty()) {
|
||||
this.value = value;
|
||||
return;
|
||||
}
|
||||
|
||||
val firstDot = path.indexOf('.');
|
||||
val fieldPath = (firstDot < 0) ? path : path.substring(0, firstDot);
|
||||
val remainder = (firstDot < 0) ? "" : path.substring(firstDot + 1);
|
||||
try {
|
||||
this.arrayChildren.get(Integer.parseInt(fieldPath)).setValue(remainder, value);
|
||||
} catch (NumberFormatException e) {
|
||||
this.children.get(fieldPath).setValue(remainder, value);
|
||||
}
|
||||
}
|
||||
|
||||
public JsonElement toJson() {
|
||||
// Determine if this is an object, an array, or a value
|
||||
if (this.value != null) { //
|
||||
return new JsonPrimitive(this.value);
|
||||
}
|
||||
if (!this.arrayChildren.isEmpty()) {
|
||||
val arr = new JsonArray(this.arrayChildren.lastIntKey() + 1);
|
||||
arrayChildren.forEach((k, v) -> arr.set(k, v.toJson()));
|
||||
return arr;
|
||||
} else if (this.children.isEmpty()) {
|
||||
return JsonNull.INSTANCE;
|
||||
} else {
|
||||
val obj = new JsonObject();
|
||||
children.forEach((k, v) -> {
|
||||
val j = v.toJson();
|
||||
if (j != JsonNull.INSTANCE)
|
||||
obj.add(k, v.toJson());
|
||||
});
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T toClass(Class<T> classType, Type type) {
|
||||
// System.out.println("toClass called with Class: "+classType+" \tType: "+type);
|
||||
if (type == null)
|
||||
type = class2Type(classType);
|
||||
|
||||
if (primitiveTypeParsers.containsKey(classType)) {
|
||||
return parsePrimitive(classType, this.value);
|
||||
} else if (classType.isEnum()) {
|
||||
return parseEnum(classType, this.value);
|
||||
} else if (classType.isArray()) {
|
||||
return this.toArray(classType);
|
||||
} else if (List.class.isAssignableFrom(classType)) {
|
||||
// if (type instanceof ParameterizedType)
|
||||
val elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
|
||||
return (T) this.toList(type2Class(elementType), elementType);
|
||||
} else if (Map.class.isAssignableFrom(classType)) {
|
||||
// System.out.println("Class: "+classType+" \tClassTypeParams: "+Arrays.toString(classType.getTypeParameters())+" \tType: "+type+" \tTypeArguments: "+Arrays.toString(((ParameterizedType) type).getActualTypeArguments()));
|
||||
// if (type instanceof ParameterizedType)
|
||||
val keyType = ((ParameterizedType) type).getActualTypeArguments()[0];
|
||||
val valueType = ((ParameterizedType) type).getActualTypeArguments()[1];
|
||||
return (T) this.toMap(type2Class(keyType), type2Class(valueType), valueType);
|
||||
} else {
|
||||
return this.toObj(classType, type);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T toObj(Class<T> objClass, Type objType) {
|
||||
try {
|
||||
// val obj = objClass.getDeclaredConstructor().newInstance();
|
||||
val obj = newObj(objClass);
|
||||
val fieldMap = getClassFieldMap(objClass);
|
||||
this.children.forEach((name, tree) -> {
|
||||
val field = fieldMap.get(name);
|
||||
if (field == null) return;
|
||||
try {
|
||||
if (primitiveTypes.contains(field.type)) {
|
||||
if ((tree.value != null) && !tree.value.isEmpty())
|
||||
field.parse(obj, tree.value);
|
||||
} else {
|
||||
val value = tree.toClass(field.classType, field.type);
|
||||
// System.out.println("Setting field "+name+" to "+value);
|
||||
field.field.set(obj, value);
|
||||
// field.field.set(obj, tree.toClass(field.classType, field.type));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// System.out.println("Exception while setting field "+name+" for class "+objClass+" - "+e);
|
||||
Grasscutter.getLogger().error("Exception while setting field " + name + " (" + field.classType + ")" + " for class " + objClass + " - ", e);
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
} catch (Exception e) {
|
||||
// System.out.println("Exception while creating object of class "+objClass+" - "+e);
|
||||
Grasscutter.getLogger().error("Exception while creating object of class " + objClass + " - ", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T toArray(Class<T> classType) {
|
||||
// Primitives don't play so nice with generics, so we handle all of them individually.
|
||||
val containedClass = classType.getComponentType();
|
||||
// val arraySize = this.arrayChildren.size(); // Assume dense 0-indexed
|
||||
val arraySize = this.arrayChildren.lastIntKey() + 1; // Could be sparse!
|
||||
// System.out.println("toArray called with Class: "+classType+" \tContains: "+containedClass+" \tof size: "+arraySize);
|
||||
if (containedClass == int.class) {
|
||||
val output = new int[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (int) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == long.class) {
|
||||
val output = new long[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (long) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == float.class) {
|
||||
val output = new float[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (float) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == double.class) {
|
||||
val output = new double[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == byte.class) {
|
||||
val output = new byte[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (byte) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == char.class) {
|
||||
val output = new char[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (char) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == short.class) {
|
||||
val output = new short[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> output[idx] = (short) parseNumber(tree.value));
|
||||
return (T) output;
|
||||
} else if (containedClass == boolean.class) {
|
||||
val output = new boolean[arraySize];
|
||||
this.arrayChildren.forEach((idx, tree) -> {
|
||||
val value = (tree.value != null) && !tree.value.isEmpty() && Boolean.parseBoolean(tree.value);
|
||||
output[idx] = value;
|
||||
});
|
||||
return (T) output;
|
||||
} else {
|
||||
val output = Array.newInstance(containedClass, arraySize);
|
||||
this.arrayChildren.forEach((idx, tree) -> ((Object[]) output)[idx] = tree.toClass(containedClass, null));
|
||||
return (T) output;
|
||||
}
|
||||
}
|
||||
|
||||
private <E> List<E> toList(Class<E> valueClass, Type valueType) {
|
||||
val arraySize = this.arrayChildren.lastIntKey() + 1; // Could be sparse!
|
||||
// System.out.println("toList called with valueClass: "+valueClass+" \tvalueType: "+valueType+" \tof size: "+arraySize);
|
||||
val list = new ArrayList<E>(arraySize);
|
||||
// Safe sparse version
|
||||
for (int i = 0; i < arraySize; i++)
|
||||
list.add(null);
|
||||
this.arrayChildren.forEach((idx, tree) -> list.set(idx, tree.toClass(valueClass, valueType)));
|
||||
return list;
|
||||
}
|
||||
|
||||
private <K, V> Map<K, V> toMap(Class<K> keyClass, Class<V> valueClass, Type valueType) {
|
||||
val map = new HashMap<K, V>();
|
||||
val keyParser = getTypeParser(keyClass);
|
||||
this.children.forEach((key, tree) -> {
|
||||
if ((key != null) && !key.isEmpty())
|
||||
map.put((K) keyParser.apply(key), tree.toClass(valueClass, valueType));
|
||||
});
|
||||
return map;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.*;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.config.ConfigContainer;
|
||||
import emu.grasscutter.data.DataLoader;
|
||||
@@ -17,10 +8,20 @@ import io.netty.buffer.ByteBufUtil;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
@@ -28,6 +29,7 @@ import static emu.grasscutter.utils.Language.translate;
|
||||
@SuppressWarnings({"UnusedReturnValue", "BooleanMethodIsAlwaysInverted"})
|
||||
public final class Utils {
|
||||
public static final Random random = new Random();
|
||||
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
|
||||
|
||||
public static int randomRange(int min, int max) {
|
||||
return random.nextInt(max - min + 1) + min;
|
||||
@@ -75,7 +77,6 @@ public final class Utils {
|
||||
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];
|
||||
@@ -108,6 +109,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@@ -117,6 +119,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Checks if a file exists on the file system.
|
||||
*
|
||||
* @param path The path to the file.
|
||||
* @return True if the file exists, false otherwise.
|
||||
*/
|
||||
@@ -126,6 +129,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Creates a folder on the file system.
|
||||
*
|
||||
* @param path The path to the folder.
|
||||
* @return True if the folder was created, false otherwise.
|
||||
*/
|
||||
@@ -135,7 +139,8 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Copies a file from the archive's resources to the file system.
|
||||
* @param resource The path to the resource.
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
@@ -156,6 +161,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Logs an object to the console.
|
||||
*
|
||||
* @param object The object to log.
|
||||
*/
|
||||
public static void logObject(Object object) {
|
||||
@@ -176,7 +182,8 @@ public final class Utils {
|
||||
if (!Files.exists(getResourcePath(""))) {
|
||||
logger.info(translate("messages.status.create_resources"));
|
||||
logger.info(translate("messages.status.resources_error"));
|
||||
createFolder(config.folderStructure.resources); exit = true;
|
||||
createFolder(config.folderStructure.resources);
|
||||
exit = true;
|
||||
}
|
||||
|
||||
// Check for BinOutput + ExcelBinOutput.
|
||||
@@ -198,11 +205,12 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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 ++) {
|
||||
for (int i = 0; i < param; i++) {
|
||||
if (zonedDateTime.getHour() < hour) {
|
||||
zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
|
||||
} else {
|
||||
@@ -214,6 +222,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
@@ -230,6 +239,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
@@ -246,6 +256,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Retrieves a string from an input stream.
|
||||
*
|
||||
* @param stream The input stream.
|
||||
* @return The string.
|
||||
*/
|
||||
@@ -254,19 +265,23 @@ public final class Utils {
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
|
||||
String line; while ((line = reader.readLine()) != null) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
stringBuilder.append(line);
|
||||
} stream.close();
|
||||
}
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read from input stream.");
|
||||
} catch (NullPointerException ignored) {
|
||||
return "empty";
|
||||
} return stringBuilder.toString();
|
||||
}
|
||||
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 x The x value.
|
||||
* @param xyArray Array of points in [[x0,y0], ... [xN, yN]] format
|
||||
* @return f(x) = y
|
||||
*/
|
||||
@@ -274,22 +289,22 @@ public final class Utils {
|
||||
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];
|
||||
} 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];
|
||||
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]) {
|
||||
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 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 );
|
||||
int fullDelta = xyArray[i + 1][1] - prevValue;
|
||||
return prevValue + ((position * fullDelta) / fullDist);
|
||||
}
|
||||
}
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
@@ -300,7 +315,8 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Checks if an int is in an int[]
|
||||
* @param key int to look for
|
||||
*
|
||||
* @param key int to look for
|
||||
* @param array int[] to look in
|
||||
* @return key in array
|
||||
*/
|
||||
@@ -315,7 +331,8 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Return a copy of minuend without any elements found in subtrahend.
|
||||
* @param minuend The array we want elements from
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
@@ -331,6 +348,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Gets the language code from a given locale.
|
||||
*
|
||||
* @param locale A locale.
|
||||
* @return A string in the format of 'XX-XX'.
|
||||
*/
|
||||
@@ -340,6 +358,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Base64 encodes a given byte array.
|
||||
*
|
||||
* @param toEncode An array of bytes.
|
||||
* @return A base64 encoded string.
|
||||
*/
|
||||
@@ -349,6 +368,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Base64 decodes a given string.
|
||||
*
|
||||
* @param toDecode A base64 encoded string.
|
||||
* @return An array of bytes.
|
||||
*/
|
||||
|
||||
@@ -9,7 +9,7 @@ public class WeightedList<E> {
|
||||
private double total = 0;
|
||||
|
||||
public WeightedList() {
|
||||
|
||||
|
||||
}
|
||||
|
||||
public WeightedList<E> add(double weight, E result) {
|
||||
@@ -24,7 +24,7 @@ public class WeightedList<E> {
|
||||
return map.higherEntry(value).getValue();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
}
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user