mirror of
https://github.com/Grasscutters/Grasscutter.git
synced 2025-09-10 17:33:55 +03:00
Fix whitespace [skip actions]
This commit is contained in:
@@ -217,7 +217,7 @@ public final class Grasscutter {
|
|||||||
*/
|
*/
|
||||||
private static void onShutdown() {
|
private static void onShutdown() {
|
||||||
// Disable all plugins.
|
// Disable all plugins.
|
||||||
if(pluginManager != null)
|
if (pluginManager != null)
|
||||||
pluginManager.disablePlugins();
|
pluginManager.disablePlugins();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -21,7 +21,7 @@ public final class DefaultAuthentication implements AuthenticationSystem {
|
|||||||
private OAuthAuthenticator oAuthAuthenticator = new OAuthAuthentication();
|
private OAuthAuthenticator oAuthAuthenticator = new OAuthAuthentication();
|
||||||
|
|
||||||
public DefaultAuthentication() {
|
public DefaultAuthentication() {
|
||||||
if(ACCOUNT.EXPERIMENTAL_RealPassword) {
|
if (ACCOUNT.EXPERIMENTAL_RealPassword) {
|
||||||
passwordAuthenticator = new ExperimentalPasswordAuthenticator();
|
passwordAuthenticator = new ExperimentalPasswordAuthenticator();
|
||||||
} else {
|
} else {
|
||||||
passwordAuthenticator = new PasswordAuthenticator();
|
passwordAuthenticator = new PasswordAuthenticator();
|
||||||
|
@@ -237,7 +237,7 @@ public final class CommandMap {
|
|||||||
Command annotation = this.annotations.get(label);
|
Command annotation = this.annotations.get(label);
|
||||||
|
|
||||||
// Resolve targetPlayer
|
// Resolve targetPlayer
|
||||||
try{
|
try {
|
||||||
targetPlayer = getTargetPlayer(playerId, player, targetPlayer, args);
|
targetPlayer = getTargetPlayer(playerId, player, targetPlayer, args);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return;
|
return;
|
||||||
|
@@ -39,8 +39,8 @@ public final class AccountCommand implements CommandHandler {
|
|||||||
int uid = 0;
|
int uid = 0;
|
||||||
String password = "";
|
String password = "";
|
||||||
|
|
||||||
if(Configuration.ACCOUNT.EXPERIMENTAL_RealPassword == true) {
|
if (Configuration.ACCOUNT.EXPERIMENTAL_RealPassword == true) {
|
||||||
if(args.size() < 3) {
|
if (args.size() < 3) {
|
||||||
CommandHandler.sendMessage(null, "EXPERIMENTAL_RealPassword requires a password argument");
|
CommandHandler.sendMessage(null, "EXPERIMENTAL_RealPassword requires a password argument");
|
||||||
CommandHandler.sendMessage(null, "Usage: account create <username> <password> [uid]");
|
CommandHandler.sendMessage(null, "Usage: account create <username> <password> [uid]");
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ public final class AccountCommand implements CommandHandler {
|
|||||||
uid = Integer.parseInt(args.get(3));
|
uid = Integer.parseInt(args.get(3));
|
||||||
} catch (NumberFormatException ignored) {
|
} catch (NumberFormatException ignored) {
|
||||||
CommandHandler.sendMessage(null, translate(sender, "commands.account.invalid"));
|
CommandHandler.sendMessage(null, translate(sender, "commands.account.invalid"));
|
||||||
if(Configuration.ACCOUNT.EXPERIMENTAL_RealPassword == true) {
|
if (Configuration.ACCOUNT.EXPERIMENTAL_RealPassword == true) {
|
||||||
CommandHandler.sendMessage(null, "EXPERIMENTAL_RealPassword requires argument 2 to be a password, not a uid");
|
CommandHandler.sendMessage(null, "EXPERIMENTAL_RealPassword requires argument 2 to be a password, not a uid");
|
||||||
CommandHandler.sendMessage(null, "Usage: account create <username> <password> [uid]");
|
CommandHandler.sendMessage(null, "Usage: account create <username> <password> [uid]");
|
||||||
}
|
}
|
||||||
@@ -76,7 +76,7 @@ public final class AccountCommand implements CommandHandler {
|
|||||||
CommandHandler.sendMessage(null, translate(sender, "commands.account.exists"));
|
CommandHandler.sendMessage(null, translate(sender, "commands.account.exists"));
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
if(Configuration.ACCOUNT.EXPERIMENTAL_RealPassword == true) {
|
if (Configuration.ACCOUNT.EXPERIMENTAL_RealPassword == true) {
|
||||||
account.setPassword(BCrypt.withDefaults().hashToString(12, password.toCharArray()));
|
account.setPassword(BCrypt.withDefaults().hashToString(12, password.toCharArray()));
|
||||||
}
|
}
|
||||||
account.addPermission("*");
|
account.addPermission("*");
|
||||||
@@ -106,12 +106,12 @@ public final class AccountCommand implements CommandHandler {
|
|||||||
CommandHandler.sendMessage(null, translate(sender, "commands.account.delete"));
|
CommandHandler.sendMessage(null, translate(sender, "commands.account.delete"));
|
||||||
return;
|
return;
|
||||||
case "resetpass":
|
case "resetpass":
|
||||||
if(Configuration.ACCOUNT.EXPERIMENTAL_RealPassword != true) {
|
if (Configuration.ACCOUNT.EXPERIMENTAL_RealPassword != true) {
|
||||||
CommandHandler.sendMessage(null, "resetpass requires EXPERIMENTAL_RealPassword to be true.");
|
CommandHandler.sendMessage(null, "resetpass requires EXPERIMENTAL_RealPassword to be true.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(args.size() != 3) {
|
if (args.size() != 3) {
|
||||||
CommandHandler.sendMessage(null, "Invalid Args");
|
CommandHandler.sendMessage(null, "Invalid Args");
|
||||||
CommandHandler.sendMessage(null, "Usage: account resetpass <username> <password>");
|
CommandHandler.sendMessage(null, "Usage: account resetpass <username> <password>");
|
||||||
return;
|
return;
|
||||||
|
@@ -28,7 +28,7 @@ public final class AnnounceCommand implements CommandHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (args.get(0)){
|
switch (args.get(0)) {
|
||||||
case "tpl":
|
case "tpl":
|
||||||
if (args.size() < 2) {
|
if (args.size() < 2) {
|
||||||
CommandHandler.sendTranslatedMessage(sender, "commands.announce.command_usage");
|
CommandHandler.sendTranslatedMessage(sender, "commands.announce.command_usage");
|
||||||
@@ -37,7 +37,7 @@ public final class AnnounceCommand implements CommandHandler {
|
|||||||
|
|
||||||
var templateId = Integer.parseInt(args.get(1));
|
var templateId = Integer.parseInt(args.get(1));
|
||||||
var tpl = manager.getAnnounceConfigItemMap().get(templateId);
|
var tpl = manager.getAnnounceConfigItemMap().get(templateId);
|
||||||
if(tpl == null){
|
if (tpl == null) {
|
||||||
CommandHandler.sendMessage(sender, translate(sender, "commands.announce.not_found", templateId));
|
CommandHandler.sendMessage(sender, translate(sender, "commands.announce.not_found", templateId));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@@ -257,7 +257,7 @@ public final class GiveCommand implements CommandHandler {
|
|||||||
if (avatar.getAvatarId() == GameConstants.MAIN_CHARACTER_MALE) {
|
if (avatar.getAvatarId() == GameConstants.MAIN_CHARACTER_MALE) {
|
||||||
avatar.setSkillDepotData(GameData.getAvatarSkillDepotDataMap().get(504));
|
avatar.setSkillDepotData(GameData.getAvatarSkillDepotDataMap().get(504));
|
||||||
}
|
}
|
||||||
else if(avatar.getAvatarId() == GameConstants.MAIN_CHARACTER_FEMALE) {
|
else if (avatar.getAvatarId() == GameConstants.MAIN_CHARACTER_FEMALE) {
|
||||||
avatar.setSkillDepotData(GameData.getAvatarSkillDepotDataMap().get(704));
|
avatar.setSkillDepotData(GameData.getAvatarSkillDepotDataMap().get(704));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -22,13 +22,13 @@ public final class HelpCommand implements CommandHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
builder.append("\n\t").append(translate(player, "commands.help.tip_need_permission"));
|
builder.append("\n\t").append(translate(player, "commands.help.tip_need_permission"));
|
||||||
if(annotation.permission().isEmpty() || annotation.permission().isBlank()) {
|
if (annotation.permission().isEmpty() || annotation.permission().isBlank()) {
|
||||||
builder.append(translate(player, "commands.help.tip_need_no_permission"));
|
builder.append(translate(player, "commands.help.tip_need_no_permission"));
|
||||||
} else {
|
} else {
|
||||||
builder.append(annotation.permission());
|
builder.append(annotation.permission());
|
||||||
}
|
}
|
||||||
|
|
||||||
if(!annotation.permissionTargeted().isEmpty() && !annotation.permissionTargeted().isBlank()) {
|
if (!annotation.permissionTargeted().isEmpty() && !annotation.permissionTargeted().isBlank()) {
|
||||||
String permissionTargeted = annotation.permissionTargeted();
|
String permissionTargeted = annotation.permissionTargeted();
|
||||||
builder.append(" ").append(translate(player, "commands.help.tip_permission_targeted", permissionTargeted));
|
builder.append(" ").append(translate(player, "commands.help.tip_permission_targeted", permissionTargeted));
|
||||||
}
|
}
|
||||||
|
@@ -27,7 +27,7 @@ public final class SendMailCommand implements CommandHandler {
|
|||||||
@Override
|
@Override
|
||||||
public void execute(Player sender, Player targetPlayer, List<String> args) {
|
public void execute(Player sender, Player targetPlayer, List<String> args) {
|
||||||
int senderId;
|
int senderId;
|
||||||
if(sender != null) {
|
if (sender != null) {
|
||||||
senderId = sender.getUid();
|
senderId = sender.getUid();
|
||||||
} else {
|
} else {
|
||||||
senderId = -1;
|
senderId = -1;
|
||||||
@@ -162,7 +162,7 @@ public final class SendMailCommand implements CommandHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String getConstructionArgs(int stage, Player sender) {
|
private String getConstructionArgs(int stage, Player sender) {
|
||||||
return switch(stage) {
|
return switch (stage) {
|
||||||
case 0 -> translate(sender, "commands.sendMail.title");
|
case 0 -> translate(sender, "commands.sendMail.title");
|
||||||
case 1 -> translate(sender, "commands.sendMail.message");
|
case 1 -> translate(sender, "commands.sendMail.message");
|
||||||
case 2 -> translate(sender, "commands.sendMail.sender");
|
case 2 -> translate(sender, "commands.sendMail.sender");
|
||||||
|
@@ -107,7 +107,7 @@ public final class SetPropCommand implements CommandHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
value = switch(valueStr.toLowerCase()) {
|
value = switch (valueStr.toLowerCase()) {
|
||||||
case "on", "true" -> 1;
|
case "on", "true" -> 1;
|
||||||
case "off", "false" -> 0;
|
case "off", "false" -> 0;
|
||||||
case "toggle" -> -1;
|
case "toggle" -> -1;
|
||||||
|
@@ -86,7 +86,7 @@ public final class SpawnCommand implements CommandHandler {
|
|||||||
double maxRadius = Math.sqrt(amount * 0.2 / Math.PI);
|
double maxRadius = Math.sqrt(amount * 0.2 / Math.PI);
|
||||||
for (int i = 0; i < amount; i++) {
|
for (int i = 0; i < amount; i++) {
|
||||||
Position pos = GetRandomPositionInCircle(targetPlayer.getPosition(), maxRadius).addY(3);
|
Position pos = GetRandomPositionInCircle(targetPlayer.getPosition(), maxRadius).addY(3);
|
||||||
if(x != 0 && y != 0 && z != 0) {
|
if (x != 0 && y != 0 && z != 0) {
|
||||||
pos = GetRandomPositionInCircle(new Position(x, y, z), maxRadius).addY(3);
|
pos = GetRandomPositionInCircle(new Position(x, y, z), maxRadius).addY(3);
|
||||||
}
|
}
|
||||||
GameEntity entity = null;
|
GameEntity entity = null;
|
||||||
@@ -120,7 +120,7 @@ public final class SpawnCommand implements CommandHandler {
|
|||||||
CommandHandler.sendMessage(sender, translate(sender, "commands.spawn.success", Integer.toString(amount), Integer.toString(id)));
|
CommandHandler.sendMessage(sender, translate(sender, "commands.spawn.success", Integer.toString(amount), Integer.toString(id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Position GetRandomPositionInCircle(Position origin, double radius){
|
private Position GetRandomPositionInCircle(Position origin, double radius) {
|
||||||
Position target = origin.clone();
|
Position target = origin.clone();
|
||||||
double angle = Math.random() * 360;
|
double angle = Math.random() * 360;
|
||||||
double r = Math.sqrt(Math.random() * radius * radius);
|
double r = Math.sqrt(Math.random() * radius * radius);
|
||||||
|
@@ -142,7 +142,7 @@ public final class TeamCommand implements CommandHandler {
|
|||||||
try {
|
try {
|
||||||
index = Integer.parseInt(args.get(1)) - 1;
|
index = Integer.parseInt(args.get(1)) - 1;
|
||||||
if (index < 0) index = 0;
|
if (index < 0) index = 0;
|
||||||
} catch(Exception e) {
|
} catch (Exception e) {
|
||||||
CommandHandler.sendTranslatedMessage(sender, "commands.team.failed_to_parse_index", args.get(1));
|
CommandHandler.sendTranslatedMessage(sender, "commands.team.failed_to_parse_index", args.get(1));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -155,7 +155,7 @@ public final class TeamCommand implements CommandHandler {
|
|||||||
int avatarId;
|
int avatarId;
|
||||||
try {
|
try {
|
||||||
avatarId = Integer.parseInt(args.get(2));
|
avatarId = Integer.parseInt(args.get(2));
|
||||||
} catch(Exception e) {
|
} catch (Exception e) {
|
||||||
CommandHandler.sendTranslatedMessage(sender, "commands.team.failed_parse_avatar_id", args.get(2));
|
CommandHandler.sendTranslatedMessage(sender, "commands.team.failed_parse_avatar_id", args.get(2));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@@ -28,7 +28,7 @@ public class ConfigContainer {
|
|||||||
try { // Check if the server is using a legacy config.
|
try { // Check if the server is using a legacy config.
|
||||||
JsonObject configObject = Grasscutter.getGsonFactory()
|
JsonObject configObject = Grasscutter.getGsonFactory()
|
||||||
.fromJson(new FileReader(Grasscutter.configFile), JsonObject.class);
|
.fromJson(new FileReader(Grasscutter.configFile), JsonObject.class);
|
||||||
if(!configObject.has("version")) {
|
if (!configObject.has("version")) {
|
||||||
Grasscutter.getLogger().info("Updating legacy ..");
|
Grasscutter.getLogger().info("Updating legacy ..");
|
||||||
Grasscutter.saveConfig(null);
|
Grasscutter.saveConfig(null);
|
||||||
}
|
}
|
||||||
@@ -37,7 +37,7 @@ public class ConfigContainer {
|
|||||||
var existing = config.version;
|
var existing = config.version;
|
||||||
var latest = version();
|
var latest = version();
|
||||||
|
|
||||||
if(existing == latest)
|
if (existing == latest)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// Create a new configuration instance.
|
// Create a new configuration instance.
|
||||||
|
@@ -105,7 +105,7 @@ public class ResourceLoader {
|
|||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
protected static void loadFromResource(Class<?> c, ResourceType type, Int2ObjectMap map, boolean doReload) throws Exception {
|
protected static void loadFromResource(Class<?> c, ResourceType type, Int2ObjectMap map, boolean doReload) throws Exception {
|
||||||
if(!loadedResources.contains(c.getSimpleName()) || doReload) {
|
if (!loadedResources.contains(c.getSimpleName()) || doReload) {
|
||||||
for (String name : type.name()) {
|
for (String name : type.name()) {
|
||||||
loadFromResource(c, name, map);
|
loadFromResource(c, name, map);
|
||||||
}
|
}
|
||||||
@@ -183,14 +183,14 @@ public class ResourceLoader {
|
|||||||
embryoList = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(embryoCache), TypeToken.getParameterized(Collection.class, AbilityEmbryoEntry.class).getType());
|
embryoList = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(embryoCache), TypeToken.getParameterized(Collection.class, AbilityEmbryoEntry.class).getType());
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {}
|
||||||
|
|
||||||
if(embryoList == null) {
|
if (embryoList == null) {
|
||||||
// Load from BinOutput
|
// Load from BinOutput
|
||||||
Pattern pattern = Pattern.compile("(?<=ConfigAvatar_)(.*?)(?=.json)");
|
Pattern pattern = Pattern.compile("(?<=ConfigAvatar_)(.*?)(?=.json)");
|
||||||
|
|
||||||
embryoList = new LinkedList<>();
|
embryoList = new LinkedList<>();
|
||||||
File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Avatar/")));
|
File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Avatar/")));
|
||||||
File[] files = folder.listFiles();
|
File[] files = folder.listFiles();
|
||||||
if(files == null) {
|
if (files == null) {
|
||||||
Grasscutter.getLogger().error("Error loading ability embryos: no files found in " + folder.getAbsolutePath());
|
Grasscutter.getLogger().error("Error loading ability embryos: no files found in " + folder.getAbsolutePath());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -333,7 +333,7 @@ public class ResourceLoader {
|
|||||||
s -> {
|
s -> {
|
||||||
s.setGroup(entry);
|
s.setGroup(entry);
|
||||||
GridBlockId point = s.getBlockId();
|
GridBlockId point = s.getBlockId();
|
||||||
if(!areaSort.containsKey(point)) {
|
if (!areaSort.containsKey(point)) {
|
||||||
areaSort.put(point, new ArrayList<>());
|
areaSort.put(point, new ArrayList<>());
|
||||||
}
|
}
|
||||||
areaSort.get(point).add(s);
|
areaSort.get(point).add(s);
|
||||||
@@ -347,7 +347,7 @@ public class ResourceLoader {
|
|||||||
// Read from cached file if exists
|
// Read from cached file if exists
|
||||||
List<OpenConfigEntry> list = null;
|
List<OpenConfigEntry> list = null;
|
||||||
|
|
||||||
try(InputStream openConfigCache = DataLoader.load("OpenConfig.json", false)) {
|
try (InputStream openConfigCache = DataLoader.load("OpenConfig.json", false)) {
|
||||||
list = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(openConfigCache), TypeToken.getParameterized(Collection.class, SpawnGroupEntry.class).getType());
|
list = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(openConfigCache), TypeToken.getParameterized(Collection.class, SpawnGroupEntry.class).getType());
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {}
|
||||||
|
|
||||||
@@ -359,7 +359,7 @@ public class ResourceLoader {
|
|||||||
for (String name : folderNames) {
|
for (String name : folderNames) {
|
||||||
File folder = new File(Utils.toFilePath(RESOURCE(name)));
|
File folder = new File(Utils.toFilePath(RESOURCE(name)));
|
||||||
File[] files = folder.listFiles();
|
File[] files = folder.listFiles();
|
||||||
if(files == null) {
|
if (files == null) {
|
||||||
Grasscutter.getLogger().error("Error loading open config: no files found in " + folder.getAbsolutePath()); return;
|
Grasscutter.getLogger().error("Error loading open config: no files found in " + folder.getAbsolutePath()); return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -421,13 +421,13 @@ public class ResourceLoader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@SneakyThrows
|
@SneakyThrows
|
||||||
private static void loadHomeworldDefaultSaveData(){
|
private static void loadHomeworldDefaultSaveData() {
|
||||||
var folder = Files.list(Path.of(RESOURCE("BinOutput/HomeworldDefaultSave"))).toList();
|
var folder = Files.list(Path.of(RESOURCE("BinOutput/HomeworldDefaultSave"))).toList();
|
||||||
var pattern = Pattern.compile("scene(.*)_home_config.json");
|
var pattern = Pattern.compile("scene(.*)_home_config.json");
|
||||||
|
|
||||||
for(var file : folder){
|
for (var file : folder) {
|
||||||
var matcher = pattern.matcher(file.getFileName().toString());
|
var matcher = pattern.matcher(file.getFileName().toString());
|
||||||
if(!matcher.find()){
|
if (!matcher.find()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
var sceneId = matcher.group(1);
|
var sceneId = matcher.group(1);
|
||||||
@@ -441,16 +441,16 @@ public class ResourceLoader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@SneakyThrows
|
@SneakyThrows
|
||||||
private static void loadNpcBornData(){
|
private static void loadNpcBornData() {
|
||||||
var folder = Files.list(Path.of(RESOURCE("BinOutput/Scene/SceneNpcBorn"))).toList();
|
var folder = Files.list(Path.of(RESOURCE("BinOutput/Scene/SceneNpcBorn"))).toList();
|
||||||
|
|
||||||
for(var file : folder){
|
for (var file : folder) {
|
||||||
if(file.toFile().isDirectory()){
|
if (file.toFile().isDirectory()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var data = Grasscutter.getGsonFactory().fromJson(Files.readString(file), SceneNpcBornData.class);
|
var data = Grasscutter.getGsonFactory().fromJson(Files.readString(file), SceneNpcBornData.class);
|
||||||
if(data.getBornPosList() == null || data.getBornPosList().size() == 0){
|
if (data.getBornPosList() == null || data.getBornPosList().size() == 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -21,11 +21,11 @@ public class EnvAnimalGatherConfigData extends GameResource {
|
|||||||
return animalId;
|
return animalId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getAnimalId(){
|
public int getAnimalId() {
|
||||||
return animalId;
|
return animalId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getEntityType(){
|
public String getEntityType() {
|
||||||
return entityType;
|
return entityType;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -49,7 +49,7 @@ public final class DatabaseManager {
|
|||||||
// Yes. I very dislike this method. However, this will be good for now.
|
// Yes. I very dislike this method. However, this will be good for now.
|
||||||
// TODO: Add dispatch routes for player account management
|
// TODO: Add dispatch routes for player account management
|
||||||
public static Datastore getAccountDatastore() {
|
public static Datastore getAccountDatastore() {
|
||||||
if(SERVER.runMode == ServerRunMode.GAME_ONLY) {
|
if (SERVER.runMode == ServerRunMode.GAME_ONLY) {
|
||||||
return dispatchDatastore;
|
return dispatchDatastore;
|
||||||
} else {
|
} else {
|
||||||
return gameDatastore;
|
return gameDatastore;
|
||||||
@@ -85,7 +85,7 @@ public final class DatabaseManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(SERVER.runMode == ServerRunMode.GAME_ONLY) {
|
if (SERVER.runMode == ServerRunMode.GAME_ONLY) {
|
||||||
MongoClient dispatchMongoClient = MongoClients.create(DATABASE.server.connectionUri);
|
MongoClient dispatchMongoClient = MongoClients.create(DATABASE.server.connectionUri);
|
||||||
dispatchDatastore = Morphia.createDatastore(dispatchMongoClient, DATABASE.server.collection);
|
dispatchDatastore = Morphia.createDatastore(dispatchMongoClient, DATABASE.server.collection);
|
||||||
|
|
||||||
|
@@ -81,7 +81,7 @@ public class Account {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getEmail() {
|
public String getEmail() {
|
||||||
if(email != null && !email.isEmpty()) {
|
if (email != null && !email.isEmpty()) {
|
||||||
return email;
|
return email;
|
||||||
} else {
|
} else {
|
||||||
return "";
|
return "";
|
||||||
@@ -158,7 +158,7 @@ public class Account {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean addPermission(String permission) {
|
public boolean addPermission(String permission) {
|
||||||
if(this.permissions.contains(permission)) return false;
|
if (this.permissions.contains(permission)) return false;
|
||||||
this.permissions.add(permission); return true;
|
this.permissions.add(permission); return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,7 +187,7 @@ public class Account {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasPermission(String permission) {
|
public boolean hasPermission(String permission) {
|
||||||
if(this.permissions.contains("*") && this.permissions.size() == 1) return true;
|
if (this.permissions.contains("*") && this.permissions.size() == 1) return true;
|
||||||
|
|
||||||
// Add default permissions if it doesn't exist
|
// Add default permissions if it doesn't exist
|
||||||
List<String> permissions = Stream.of(this.permissions, Arrays.asList(ACCOUNT.defaultPermissions))
|
List<String> permissions = Stream.of(this.permissions, Arrays.asList(ACCOUNT.defaultPermissions))
|
||||||
|
@@ -45,7 +45,7 @@ public class ActivityManager extends BasePlayerManager {
|
|||||||
activityWatcherTypeMap.put(typeName.value(), ConstructorAccess.get(item));
|
activityWatcherTypeMap.put(typeName.value(), ConstructorAccess.get(item));
|
||||||
});
|
});
|
||||||
|
|
||||||
try(Reader reader = DataLoader.loadReader("ActivityConfig.json")) {
|
try (Reader reader = DataLoader.loadReader("ActivityConfig.json")) {
|
||||||
List<ActivityConfigItem> activities = Grasscutter.getGsonFactory().fromJson(
|
List<ActivityConfigItem> activities = Grasscutter.getGsonFactory().fromJson(
|
||||||
reader,
|
reader,
|
||||||
TypeToken.getParameterized(List.class, ActivityConfigItem.class).getType());
|
TypeToken.getParameterized(List.class, ActivityConfigItem.class).getType());
|
||||||
@@ -53,16 +53,16 @@ public class ActivityManager extends BasePlayerManager {
|
|||||||
|
|
||||||
activities.forEach(item -> {
|
activities.forEach(item -> {
|
||||||
var activityData = GameData.getActivityDataMap().get(item.getActivityId());
|
var activityData = GameData.getActivityDataMap().get(item.getActivityId());
|
||||||
if(activityData == null){
|
if (activityData == null) {
|
||||||
Grasscutter.getLogger().warn("activity {} not exist.", item.getActivityId());
|
Grasscutter.getLogger().warn("activity {} not exist.", item.getActivityId());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var activityHandlerType = activityHandlerTypeMap.get(ActivityType.getTypeByName(activityData.getActivityType()));
|
var activityHandlerType = activityHandlerTypeMap.get(ActivityType.getTypeByName(activityData.getActivityType()));
|
||||||
ActivityHandler activityHandler;
|
ActivityHandler activityHandler;
|
||||||
|
|
||||||
if(activityHandlerType != null) {
|
if (activityHandlerType != null) {
|
||||||
activityHandler = (ActivityHandler) activityHandlerType.newInstance();
|
activityHandler = (ActivityHandler) activityHandlerType.newInstance();
|
||||||
}else{
|
}else {
|
||||||
activityHandler = new DefaultActivityHandler();
|
activityHandler = new DefaultActivityHandler();
|
||||||
}
|
}
|
||||||
activityHandler.setActivityConfigItem(item);
|
activityHandler.setActivityConfigItem(item);
|
||||||
@@ -79,14 +79,14 @@ public class ActivityManager extends BasePlayerManager {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public ActivityManager(Player player){
|
public ActivityManager(Player player) {
|
||||||
super(player);
|
super(player);
|
||||||
|
|
||||||
playerActivityDataMap = new ConcurrentHashMap<>();
|
playerActivityDataMap = new ConcurrentHashMap<>();
|
||||||
// load data for player
|
// load data for player
|
||||||
activityConfigItemMap.values().forEach(item -> {
|
activityConfigItemMap.values().forEach(item -> {
|
||||||
var data = PlayerActivityData.getByPlayer(player, item.getActivityId());
|
var data = PlayerActivityData.getByPlayer(player, item.getActivityId());
|
||||||
if(data == null){
|
if (data == null) {
|
||||||
data = item.getActivityHandler().initPlayerActivityData(player);
|
data = item.getActivityHandler().initPlayerActivityData(player);
|
||||||
data.save();
|
data.save();
|
||||||
}
|
}
|
||||||
@@ -116,34 +116,34 @@ public class ActivityManager extends BasePlayerManager {
|
|||||||
params));
|
params));
|
||||||
}
|
}
|
||||||
|
|
||||||
public ActivityInfoOuterClass.ActivityInfo getInfoProtoByActivityId(int activityId){
|
public ActivityInfoOuterClass.ActivityInfo getInfoProtoByActivityId(int activityId) {
|
||||||
var activityHandler = activityConfigItemMap.get(activityId).getActivityHandler();
|
var activityHandler = activityConfigItemMap.get(activityId).getActivityHandler();
|
||||||
var activityData = playerActivityDataMap.get(activityId);
|
var activityData = playerActivityDataMap.get(activityId);
|
||||||
|
|
||||||
return activityHandler.toProto(activityData);
|
return activityHandler.toProto(activityData);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<ActivityHandler> getActivityHandler(ActivityType type){
|
public Optional<ActivityHandler> getActivityHandler(ActivityType type) {
|
||||||
return activityConfigItemMap.values().stream()
|
return activityConfigItemMap.values().stream()
|
||||||
.map(ActivityConfigItem::getActivityHandler)
|
.map(ActivityConfigItem::getActivityHandler)
|
||||||
.filter(x -> type == x.getClass().getAnnotation(GameActivity.class).value())
|
.filter(x -> type == x.getClass().getAnnotation(GameActivity.class).value())
|
||||||
.findFirst();
|
.findFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T extends ActivityHandler> Optional<T> getActivityHandlerAs(ActivityType type, Class<T> clazz){
|
public <T extends ActivityHandler> Optional<T> getActivityHandlerAs(ActivityType type, Class<T> clazz) {
|
||||||
return getActivityHandler(type).map(x -> (T)x);
|
return getActivityHandler(type).map(x -> (T)x);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<Integer> getActivityIdByActivityType(ActivityType type){
|
public Optional<Integer> getActivityIdByActivityType(ActivityType type) {
|
||||||
return getActivityHandler(type)
|
return getActivityHandler(type)
|
||||||
.map(ActivityHandler::getActivityConfigItem)
|
.map(ActivityHandler::getActivityConfigItem)
|
||||||
.map(ActivityConfigItem::getActivityId);
|
.map(ActivityConfigItem::getActivityId);
|
||||||
}
|
}
|
||||||
public Optional<PlayerActivityData> getPlayerActivityDataByActivityType(ActivityType type){
|
public Optional<PlayerActivityData> getPlayerActivityDataByActivityType(ActivityType type) {
|
||||||
return getActivityIdByActivityType(type)
|
return getActivityIdByActivityType(type)
|
||||||
.map(playerActivityDataMap::get);
|
.map(playerActivityDataMap::get);
|
||||||
}
|
}
|
||||||
public Optional<ActivityInfoOuterClass.ActivityInfo> getInfoProtoByActivityType(ActivityType type){
|
public Optional<ActivityInfoOuterClass.ActivityInfo> getInfoProtoByActivityType(ActivityType type) {
|
||||||
return getActivityIdByActivityType(type)
|
return getActivityIdByActivityType(type)
|
||||||
.map(this::getInfoProtoByActivityId);
|
.map(this::getInfoProtoByActivityId);
|
||||||
}
|
}
|
||||||
|
@@ -41,8 +41,8 @@ public class MusicGameActivityHandler extends ActivityHandler {
|
|||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
public MusicGamePlayerData getMusicGamePlayerData(PlayerActivityData playerActivityData){
|
public MusicGamePlayerData getMusicGamePlayerData(PlayerActivityData playerActivityData) {
|
||||||
if(playerActivityData.getDetail() == null || playerActivityData.getDetail().isBlank()){
|
if (playerActivityData.getDetail() == null || playerActivityData.getDetail().isBlank()) {
|
||||||
onInitPlayerActivityData(playerActivityData);
|
onInitPlayerActivityData(playerActivityData);
|
||||||
playerActivityData.save();
|
playerActivityData.save();
|
||||||
}
|
}
|
||||||
@@ -51,7 +51,7 @@ public class MusicGameActivityHandler extends ActivityHandler {
|
|||||||
MusicGamePlayerData.class);
|
MusicGamePlayerData.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean setMusicGameRecord(PlayerActivityData playerActivityData, MusicGamePlayerData.MusicGameRecord newRecord){
|
public boolean setMusicGameRecord(PlayerActivityData playerActivityData, MusicGamePlayerData.MusicGameRecord newRecord) {
|
||||||
var musicGamePlayerData = getMusicGamePlayerData(playerActivityData);
|
var musicGamePlayerData = getMusicGamePlayerData(playerActivityData);
|
||||||
var saveRecord = musicGamePlayerData.getMusicGameRecord().get(newRecord.getMusicId());
|
var saveRecord = musicGamePlayerData.getMusicGameRecord().get(newRecord.getMusicId());
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ public class MusicGameActivityHandler extends ActivityHandler {
|
|||||||
|
|
||||||
return newRecord.getMaxScore() > saveRecord.getMaxScore();
|
return newRecord.getMaxScore() > saveRecord.getMaxScore();
|
||||||
}
|
}
|
||||||
public void setMusicGameCustomBeatmapRecord(PlayerActivityData playerActivityData, MusicGamePlayerData.CustomBeatmapRecord newRecord){
|
public void setMusicGameCustomBeatmapRecord(PlayerActivityData playerActivityData, MusicGamePlayerData.CustomBeatmapRecord newRecord) {
|
||||||
var musicGamePlayerData = getMusicGamePlayerData(playerActivityData);
|
var musicGamePlayerData = getMusicGamePlayerData(playerActivityData);
|
||||||
musicGamePlayerData.getOthersCustomBeatmapRecord().put(newRecord.getMusicShareId(), newRecord);
|
musicGamePlayerData.getOthersCustomBeatmapRecord().put(newRecord.getMusicShareId(), newRecord);
|
||||||
|
|
||||||
|
@@ -21,7 +21,7 @@ public class MusicGamePlayerData {
|
|||||||
Map<Long, CustomBeatmapRecord> personalCustomBeatmapRecord;
|
Map<Long, CustomBeatmapRecord> personalCustomBeatmapRecord;
|
||||||
Map<Long, CustomBeatmapRecord> othersCustomBeatmapRecord;
|
Map<Long, CustomBeatmapRecord> othersCustomBeatmapRecord;
|
||||||
|
|
||||||
public static MusicGamePlayerData create(){
|
public static MusicGamePlayerData create() {
|
||||||
return MusicGamePlayerData.of()
|
return MusicGamePlayerData.of()
|
||||||
.musicGameRecord(GameData.getMusicGameBasicDataMap().values().stream()
|
.musicGameRecord(GameData.getMusicGameBasicDataMap().values().stream()
|
||||||
.collect(Collectors.toMap(MusicGameBasicData::getId, MusicGamePlayerData.MusicGameRecord::create)))
|
.collect(Collectors.toMap(MusicGameBasicData::getId, MusicGamePlayerData.MusicGameRecord::create)))
|
||||||
@@ -38,13 +38,13 @@ public class MusicGamePlayerData {
|
|||||||
int maxCombo;
|
int maxCombo;
|
||||||
int maxScore;
|
int maxScore;
|
||||||
|
|
||||||
public static MusicGameRecord create(MusicGameBasicData musicGameBasicData){
|
public static MusicGameRecord create(MusicGameBasicData musicGameBasicData) {
|
||||||
return MusicGameRecord.of()
|
return MusicGameRecord.of()
|
||||||
.musicId(musicGameBasicData.getId())
|
.musicId(musicGameBasicData.getId())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public MusicGameRecordOuterClass.MusicGameRecord toProto(){
|
public MusicGameRecordOuterClass.MusicGameRecord toProto() {
|
||||||
return MusicGameRecordOuterClass.MusicGameRecord.newBuilder()
|
return MusicGameRecordOuterClass.MusicGameRecord.newBuilder()
|
||||||
.setIsUnlock(true)
|
.setIsUnlock(true)
|
||||||
.setMaxCombo(maxCombo)
|
.setMaxCombo(maxCombo)
|
||||||
@@ -61,7 +61,7 @@ public class MusicGamePlayerData {
|
|||||||
int score;
|
int score;
|
||||||
boolean settle;
|
boolean settle;
|
||||||
|
|
||||||
public MusicBriefInfoOuterClass.MusicBriefInfo.Builder toPersonalBriefProto(){
|
public MusicBriefInfoOuterClass.MusicBriefInfo.Builder toPersonalBriefProto() {
|
||||||
var musicGameBeatmap = MusicGameBeatmap.getByShareId(musicShareId);
|
var musicGameBeatmap = MusicGameBeatmap.getByShareId(musicShareId);
|
||||||
|
|
||||||
return MusicBriefInfoOuterClass.MusicBriefInfo.newBuilder()
|
return MusicBriefInfoOuterClass.MusicBriefInfo.newBuilder()
|
||||||
@@ -74,7 +74,7 @@ public class MusicGamePlayerData {
|
|||||||
.setMusicShareId(musicShareId);
|
.setMusicShareId(musicShareId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public MusicBriefInfoOuterClass.MusicBriefInfo.Builder toOthersBriefProto(){
|
public MusicBriefInfoOuterClass.MusicBriefInfo.Builder toOthersBriefProto() {
|
||||||
var musicGameBeatmap = MusicGameBeatmap.getByShareId(musicShareId);
|
var musicGameBeatmap = MusicGameBeatmap.getByShareId(musicShareId);
|
||||||
|
|
||||||
return musicGameBeatmap.toBriefProto()
|
return musicGameBeatmap.toBriefProto()
|
||||||
|
@@ -81,7 +81,7 @@ public class BattlePassManager extends BasePlayerDataManager {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addPoints(int points){
|
public void addPoints(int points) {
|
||||||
this.addPointsDirectly(points, false);
|
this.addPointsDirectly(points, false);
|
||||||
|
|
||||||
this.player.sendPacket(new PacketBattlePassCurScheduleUpdateNotify(player));
|
this.player.sendPacket(new PacketBattlePassCurScheduleUpdateNotify(player));
|
||||||
|
@@ -74,16 +74,16 @@ public class CombineManger extends BaseGameSystem {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public CombineResult combineItem(Player player, int cid, int count){
|
public CombineResult combineItem(Player player, int cid, int count) {
|
||||||
// check config exist
|
// check config exist
|
||||||
if(!GameData.getCombineDataMap().containsKey(cid)){
|
if (!GameData.getCombineDataMap().containsKey(cid)) {
|
||||||
player.getWorld().getHost().sendPacket(new PacketCombineRsp());
|
player.getWorld().getHost().sendPacket(new PacketCombineRsp());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
CombineData combineData = GameData.getCombineDataMap().get(cid);
|
CombineData combineData = GameData.getCombineDataMap().get(cid);
|
||||||
|
|
||||||
if(combineData.getPlayerLevel() > player.getLevel()){
|
if (combineData.getPlayerLevel() > player.getLevel()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -41,7 +41,7 @@ public class DropSystem extends BaseGameSystem {
|
|||||||
try (Reader fileReader = DataLoader.loadReader("Drop.json")) {
|
try (Reader fileReader = DataLoader.loadReader("Drop.json")) {
|
||||||
getDropData().clear();
|
getDropData().clear();
|
||||||
List<DropInfo> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, DropInfo.class).getType());
|
List<DropInfo> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, DropInfo.class).getType());
|
||||||
if(banners.size() > 0) {
|
if (banners.size() > 0) {
|
||||||
for (DropInfo di : banners) {
|
for (DropInfo di : banners) {
|
||||||
getDropData().put(di.getMonsterId(), di.getDropDataList());
|
getDropData().put(di.getMonsterId(), di.getDropDataList());
|
||||||
}
|
}
|
||||||
|
@@ -70,7 +70,7 @@ public class DungeonSystem extends BaseGameSystem {
|
|||||||
}
|
}
|
||||||
Grasscutter.getLogger().info("{}({}) is trying to enter tower dungeon {}" ,player.getNickname(),player.getUid(),dungeonId);
|
Grasscutter.getLogger().info("{}({}) is trying to enter tower dungeon {}" ,player.getNickname(),player.getUid(),dungeonId);
|
||||||
|
|
||||||
if(player.getWorld().transferPlayerToScene(player, data.getSceneId(), data)){
|
if (player.getWorld().transferPlayerToScene(player, data.getSceneId(), data)) {
|
||||||
dungeonSettleListeners.forEach(player.getScene()::addDungeonSettleObserver);
|
dungeonSettleListeners.forEach(player.getScene()::addDungeonSettleObserver);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
@@ -95,7 +95,7 @@ public class DungeonChallenge extends WorldChallenge {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void settle() {
|
private void settle() {
|
||||||
if(!stage){
|
if (!stage) {
|
||||||
getScene().getDungeonSettleObservers().forEach(o -> o.onDungeonSettle(getScene()));
|
getScene().getDungeonSettleObservers().forEach(o -> o.onDungeonSettle(getScene()));
|
||||||
getScene().getScriptManager().callEvent(EventType.EVENT_DUNGEON_SETTLE,
|
getScene().getScriptManager().callEvent(EventType.EVENT_DUNGEON_SETTLE,
|
||||||
new ScriptArgs(this.isSuccess() ? 1 : 0));
|
new ScriptArgs(this.isSuccess() ? 1 : 0));
|
||||||
|
@@ -97,7 +97,7 @@ public class EntityGadget extends EntityBaseGadget {
|
|||||||
this.state = state;
|
this.state = state;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateState(int state){
|
public void updateState(int state) {
|
||||||
this.setState(state);
|
this.setState(state);
|
||||||
this.getScene().broadcastPacket(new PacketGadgetStateNotify(this, state));
|
this.getScene().broadcastPacket(new PacketGadgetStateNotify(this, state));
|
||||||
getScene().getScriptManager().callEvent(EventType.EVENT_GADGET_STATE_CHANGE, new ScriptArgs(state, this.getConfigId()));
|
getScene().getScriptManager().callEvent(EventType.EVENT_GADGET_STATE_CHANGE, new ScriptArgs(state, this.getConfigId()));
|
||||||
|
@@ -166,13 +166,13 @@ public class EntityMonster extends GameEntity {
|
|||||||
getScene().getChallenge().onMonsterDeath(this);
|
getScene().getChallenge().onMonsterDeath(this);
|
||||||
}
|
}
|
||||||
if (getScene().getScriptManager().isInit() && this.getGroupId() > 0) {
|
if (getScene().getScriptManager().isInit() && this.getGroupId() > 0) {
|
||||||
if(getScene().getScriptManager().getScriptMonsterSpawnService() != null){
|
if (getScene().getScriptManager().getScriptMonsterSpawnService() != null) {
|
||||||
getScene().getScriptManager().getScriptMonsterSpawnService().onMonsterDead(this);
|
getScene().getScriptManager().getScriptMonsterSpawnService().onMonsterDead(this);
|
||||||
}
|
}
|
||||||
// prevent spawn monster after success
|
// prevent spawn monster after success
|
||||||
if(getScene().getChallenge() != null && getScene().getChallenge().inProgress()){
|
if (getScene().getChallenge() != null && getScene().getChallenge().inProgress()) {
|
||||||
getScene().getScriptManager().callEvent(EventType.EVENT_ANY_MONSTER_DIE, new ScriptArgs().setParam1(this.getConfigId()));
|
getScene().getScriptManager().callEvent(EventType.EVENT_ANY_MONSTER_DIE, new ScriptArgs().setParam1(this.getConfigId()));
|
||||||
}else if(getScene().getChallenge() == null){
|
}else if (getScene().getChallenge() == null) {
|
||||||
getScene().getScriptManager().callEvent(EventType.EVENT_ANY_MONSTER_DIE, new ScriptArgs().setParam1(this.getConfigId()));
|
getScene().getScriptManager().callEvent(EventType.EVENT_ANY_MONSTER_DIE, new ScriptArgs().setParam1(this.getConfigId()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -23,15 +23,15 @@ public class GadgetChest extends GadgetContent {
|
|||||||
public boolean onInteract(Player player, GadgetInteractReq req) {
|
public boolean onInteract(Player player, GadgetInteractReq req) {
|
||||||
var chestInteractHandlerMap = getGadget().getScene().getWorld().getServer().getWorldDataSystem().getChestInteractHandlerMap();
|
var chestInteractHandlerMap = getGadget().getScene().getWorld().getServer().getWorldDataSystem().getChestInteractHandlerMap();
|
||||||
var handler = chestInteractHandlerMap.get(getGadget().getGadgetData().getJsonName());
|
var handler = chestInteractHandlerMap.get(getGadget().getGadgetData().getJsonName());
|
||||||
if(handler == null){
|
if (handler == null) {
|
||||||
Grasscutter.getLogger().warn("Could not found the handler of this type of Chests {}", getGadget().getGadgetData().getJsonName());
|
Grasscutter.getLogger().warn("Could not found the handler of this type of Chests {}", getGadget().getGadgetData().getJsonName());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(req.getOpType() == InterOpType.INTER_OP_TYPE_START && handler.isTwoStep()){
|
if (req.getOpType() == InterOpType.INTER_OP_TYPE_START && handler.isTwoStep()) {
|
||||||
player.sendPacket(new PacketGadgetInteractRsp(getGadget(), InteractType.INTERACT_TYPE_OPEN_CHEST, InterOpType.INTER_OP_TYPE_START));
|
player.sendPacket(new PacketGadgetInteractRsp(getGadget(), InteractType.INTERACT_TYPE_OPEN_CHEST, InterOpType.INTER_OP_TYPE_START));
|
||||||
return false;
|
return false;
|
||||||
}else{
|
}else {
|
||||||
var success = handler.onInteract(this, player);
|
var success = handler.onInteract(this, player);
|
||||||
if (!success) {
|
if (!success) {
|
||||||
return false;
|
return false;
|
||||||
@@ -45,12 +45,12 @@ public class GadgetChest extends GadgetContent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void onBuildProto(SceneGadgetInfo.Builder gadgetInfo) {
|
public void onBuildProto(SceneGadgetInfo.Builder gadgetInfo) {
|
||||||
if(getGadget().getMetaGadget() == null){
|
if (getGadget().getMetaGadget() == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var bossChest = getGadget().getMetaGadget().boss_chest;
|
var bossChest = getGadget().getMetaGadget().boss_chest;
|
||||||
if(bossChest != null){
|
if (bossChest != null) {
|
||||||
var players = getGadget().getScene().getPlayers().stream().map(Player::getUid).toList();
|
var players = getGadget().getScene().getPlayers().stream().map(Player::getUid).toList();
|
||||||
|
|
||||||
gadgetInfo.setBossChest(BossChestInfo.newBuilder()
|
gadgetInfo.setBossChest(BossChestInfo.newBuilder()
|
||||||
|
@@ -23,7 +23,7 @@ public class BossChestInteractHandler implements ChestInteractHandler{
|
|||||||
var monster = chest.getGadget().getMetaGadget().group.monsters.get(chest.getGadget().getMetaGadget().boss_chest.monster_config_id);
|
var monster = chest.getGadget().getMetaGadget().group.monsters.get(chest.getGadget().getMetaGadget().boss_chest.monster_config_id);
|
||||||
var reward = worldDataManager.getRewardByBossId(monster.monster_id);
|
var reward = worldDataManager.getRewardByBossId(monster.monster_id);
|
||||||
|
|
||||||
if(reward == null){
|
if (reward == null) {
|
||||||
Grasscutter.getLogger().warn("Could not found the reward of boss monster {}", monster.monster_id);
|
Grasscutter.getLogger().warn("Could not found the reward of boss monster {}", monster.monster_id);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@@ -33,7 +33,7 @@ public class ExpeditionSystem extends BaseGameSystem {
|
|||||||
try (Reader fileReader = DataLoader.loadReader("ExpeditionReward.json")) {
|
try (Reader fileReader = DataLoader.loadReader("ExpeditionReward.json")) {
|
||||||
getExpeditionRewardDataList().clear();
|
getExpeditionRewardDataList().clear();
|
||||||
List<ExpeditionRewardInfo> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ExpeditionRewardInfo.class).getType());
|
List<ExpeditionRewardInfo> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ExpeditionRewardInfo.class).getType());
|
||||||
if(banners.size() > 0) {
|
if (banners.size() > 0) {
|
||||||
for (ExpeditionRewardInfo di : banners) {
|
for (ExpeditionRewardInfo di : banners) {
|
||||||
getExpeditionRewardDataList().put(di.getExpId(), di.getExpeditionRewardDataList());
|
getExpeditionRewardDataList().put(di.getExpId(), di.getExpeditionRewardDataList());
|
||||||
}
|
}
|
||||||
|
@@ -70,21 +70,21 @@ public class GachaBanner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public int getWeight(int rarity, int pity) {
|
public int getWeight(int rarity, int pity) {
|
||||||
return switch(rarity) {
|
return switch (rarity) {
|
||||||
case 4 -> Utils.lerp(pity, weights4);
|
case 4 -> Utils.lerp(pity, weights4);
|
||||||
default -> Utils.lerp(pity, weights5);
|
default -> Utils.lerp(pity, weights5);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getPoolBalanceWeight(int rarity, int pity) {
|
public int getPoolBalanceWeight(int rarity, int pity) {
|
||||||
return switch(rarity) {
|
return switch (rarity) {
|
||||||
case 4 -> Utils.lerp(pity, poolBalanceWeights4);
|
case 4 -> Utils.lerp(pity, poolBalanceWeights4);
|
||||||
default -> Utils.lerp(pity, poolBalanceWeights5);
|
default -> Utils.lerp(pity, poolBalanceWeights5);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getEventChance(int rarity) {
|
public int getEventChance(int rarity) {
|
||||||
return switch(rarity) {
|
return switch (rarity) {
|
||||||
case 4 -> eventChance4;
|
case 4 -> eventChance4;
|
||||||
default -> (eventChance > -1) ? eventChance : eventChance5;
|
default -> (eventChance > -1) ? eventChance : eventChance5;
|
||||||
};
|
};
|
||||||
@@ -107,7 +107,7 @@ public class GachaBanner {
|
|||||||
ItemParamData costItem1 = this.getCost(1);
|
ItemParamData costItem1 = this.getCost(1);
|
||||||
ItemParamData costItem10 = this.getCost(10);
|
ItemParamData costItem10 = this.getCost(10);
|
||||||
PlayerGachaBannerInfo gachaInfo = player.getGachaInfo().getBannerInfo(this);
|
PlayerGachaBannerInfo gachaInfo = player.getGachaInfo().getBannerInfo(this);
|
||||||
int leftGachaTimes = switch(gachaTimesLimit) {
|
int leftGachaTimes = switch (gachaTimesLimit) {
|
||||||
case Integer.MAX_VALUE -> Integer.MAX_VALUE;
|
case Integer.MAX_VALUE -> Integer.MAX_VALUE;
|
||||||
default -> Math.max(gachaTimesLimit - gachaInfo.getTotalPulls(), 0);
|
default -> Math.max(gachaTimesLimit - gachaInfo.getTotalPulls(), 0);
|
||||||
};
|
};
|
||||||
@@ -130,7 +130,7 @@ public class GachaBanner {
|
|||||||
.setGachaTimesLimit(gachaTimesLimit)
|
.setGachaTimesLimit(gachaTimesLimit)
|
||||||
.setGachaSortId(this.getSortId());
|
.setGachaSortId(this.getSortId());
|
||||||
|
|
||||||
if(hasEpitomized()) {
|
if (hasEpitomized()) {
|
||||||
info.setWishItemId(gachaInfo.getWishItemId())
|
info.setWishItemId(gachaInfo.getWishItemId())
|
||||||
.setWishProgress(gachaInfo.getFailedChosenItemPulls())
|
.setWishProgress(gachaInfo.getFailedChosenItemPulls())
|
||||||
.setWishMaxProgress(this.getWishMaxProgress());
|
.setWishMaxProgress(this.getWishMaxProgress());
|
||||||
|
@@ -79,7 +79,7 @@ public class GachaSystem extends BaseGameSystem {
|
|||||||
try (Reader fileReader = DataLoader.loadReader("Banners.json")) {
|
try (Reader fileReader = DataLoader.loadReader("Banners.json")) {
|
||||||
getGachaBanners().clear();
|
getGachaBanners().clear();
|
||||||
List<GachaBanner> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, GachaBanner.class).getType());
|
List<GachaBanner> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, GachaBanner.class).getType());
|
||||||
if(banners.size() > 0) {
|
if (banners.size() > 0) {
|
||||||
for (GachaBanner banner : banners) {
|
for (GachaBanner banner : banners) {
|
||||||
getGachaBanners().put(banner.getScheduleId(), banner);
|
getGachaBanners().put(banner.getScheduleId(), banner);
|
||||||
}
|
}
|
||||||
@@ -129,7 +129,7 @@ public class GachaSystem extends BaseGameSystem {
|
|||||||
|
|
||||||
private synchronized int checkPlayerAvatarConstellationLevel(Player player, int itemId) { // Maybe this would be useful in the Player class?
|
private synchronized int checkPlayerAvatarConstellationLevel(Player player, int itemId) { // Maybe this would be useful in the Player class?
|
||||||
ItemData itemData = GameData.getItemDataMap().get(itemId);
|
ItemData itemData = GameData.getItemDataMap().get(itemId);
|
||||||
if ((itemData == null) || (itemData.getMaterialType() != MaterialType.MATERIAL_AVATAR)){
|
if ((itemData == null) || (itemData.getMaterialType() != MaterialType.MATERIAL_AVATAR)) {
|
||||||
return -2; // Not an Avatar
|
return -2; // Not an Avatar
|
||||||
}
|
}
|
||||||
Avatar avatar = player.getAvatars().getAvatarById((itemId % 1000) + 10000000);
|
Avatar avatar = player.getAvatars().getAvatarById((itemId % 1000) + 10000000);
|
||||||
@@ -225,7 +225,7 @@ public class GachaSystem extends BaseGameSystem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (epitomized) {
|
if (epitomized) {
|
||||||
if(itemId == gachaInfo.getWishItemId()) { // Reset epitomized points when got wished item
|
if (itemId == gachaInfo.getWishItemId()) { // Reset epitomized points when got wished item
|
||||||
gachaInfo.setFailedChosenItemPulls(0);
|
gachaInfo.setFailedChosenItemPulls(0);
|
||||||
} else { // Add epitomized points if not get wished item
|
} else { // Add epitomized points if not get wished item
|
||||||
gachaInfo.addFailedChosenItemPulls(1);
|
gachaInfo.addFailedChosenItemPulls(1);
|
||||||
@@ -387,7 +387,7 @@ public class GachaSystem extends BaseGameSystem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private synchronized void startWatcher(GameServer server) {
|
private synchronized void startWatcher(GameServer server) {
|
||||||
if(this.watchService == null) {
|
if (this.watchService == null) {
|
||||||
try {
|
try {
|
||||||
this.watchService = FileSystems.getDefault().newWatchService();
|
this.watchService = FileSystems.getDefault().newWatchService();
|
||||||
Path path = new File(DATA()).toPath();
|
Path path = new File(DATA()).toPath();
|
||||||
@@ -403,7 +403,7 @@ public class GachaSystem extends BaseGameSystem {
|
|||||||
|
|
||||||
@Subscribe
|
@Subscribe
|
||||||
public synchronized void watchBannerJson(GameServerTickEvent tickEvent) {
|
public synchronized void watchBannerJson(GameServerTickEvent tickEvent) {
|
||||||
if(GAME_OPTIONS.watchGachaConfig) {
|
if (GAME_OPTIONS.watchGachaConfig) {
|
||||||
try {
|
try {
|
||||||
WatchKey watchKey = watchService.take();
|
WatchKey watchKey = watchService.take();
|
||||||
|
|
||||||
|
@@ -30,7 +30,7 @@ public class MailHandler extends BasePlayerManager {
|
|||||||
public void sendMail(Mail message) {
|
public void sendMail(Mail message) {
|
||||||
// Call mail receive event.
|
// Call mail receive event.
|
||||||
PlayerReceiveMailEvent event = new PlayerReceiveMailEvent(this.getPlayer(), message); event.call();
|
PlayerReceiveMailEvent event = new PlayerReceiveMailEvent(this.getPlayer(), message); event.call();
|
||||||
if(event.isCanceled()) return; message = event.getMessage();
|
if (event.isCanceled()) return; message = event.getMessage();
|
||||||
|
|
||||||
message.setOwnerUid(this.getPlayer().getUid());
|
message.setOwnerUid(this.getPlayer().getUid());
|
||||||
message.save();
|
message.save();
|
||||||
@@ -82,7 +82,7 @@ public class MailHandler extends BasePlayerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean replaceMailByIndex(int index, Mail message) {
|
public boolean replaceMailByIndex(int index, Mail message) {
|
||||||
if(getMailById(index) != null) {
|
if (getMailById(index) != null) {
|
||||||
this.mail.set(index, message);
|
this.mail.set(index, message);
|
||||||
message.save();
|
message.save();
|
||||||
return true;
|
return true;
|
||||||
|
@@ -20,20 +20,20 @@ public class FurnitureManager extends BasePlayerManager {
|
|||||||
super(player);
|
super(player);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void onLogin(){
|
public void onLogin() {
|
||||||
notifyUnlockFurniture();
|
notifyUnlockFurniture();
|
||||||
notifyUnlockFurnitureSuite();
|
notifyUnlockFurnitureSuite();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void notifyUnlockFurniture(){
|
public void notifyUnlockFurniture() {
|
||||||
player.getSession().send(new PacketUnlockedFurnitureFormulaDataNotify(player.getUnlockedFurniture()));
|
player.getSession().send(new PacketUnlockedFurnitureFormulaDataNotify(player.getUnlockedFurniture()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void notifyUnlockFurnitureSuite(){
|
public void notifyUnlockFurnitureSuite() {
|
||||||
player.getSession().send(new PacketUnlockedFurnitureSuiteDataNotify(player.getUnlockedFurnitureSuite()));
|
player.getSession().send(new PacketUnlockedFurnitureSuiteDataNotify(player.getUnlockedFurnitureSuite()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized boolean unlockFurnitureOrSuite(GameItem useItem){
|
public synchronized boolean unlockFurnitureOrSuite(GameItem useItem) {
|
||||||
// Check
|
// Check
|
||||||
if (!List.of("ITEM_USE_UNLOCK_FURNITURE_FORMULA", "ITEM_USE_UNLOCK_FURNITURE_SUITE")
|
if (!List.of("ITEM_USE_UNLOCK_FURNITURE_FORMULA", "ITEM_USE_UNLOCK_FURNITURE_SUITE")
|
||||||
.contains(useItem.getItemData().getItemUse().get(0).getUseOp())) {
|
.contains(useItem.getItemData().getItemUse().get(0).getUseOp())) {
|
||||||
@@ -45,10 +45,10 @@ public class FurnitureManager extends BasePlayerManager {
|
|||||||
// Remove first
|
// Remove first
|
||||||
player.getInventory().removeItem(useItem, 1);
|
player.getInventory().removeItem(useItem, 1);
|
||||||
|
|
||||||
if("ITEM_USE_UNLOCK_FURNITURE_FORMULA".equals(useItem.getItemData().getItemUse().get(0).getUseOp())){
|
if ("ITEM_USE_UNLOCK_FURNITURE_FORMULA".equals(useItem.getItemData().getItemUse().get(0).getUseOp())) {
|
||||||
player.getUnlockedFurniture().add(furnitureIdOrSuiteId);
|
player.getUnlockedFurniture().add(furnitureIdOrSuiteId);
|
||||||
notifyUnlockFurniture();
|
notifyUnlockFurniture();
|
||||||
}else{
|
}else {
|
||||||
player.getUnlockedFurnitureSuite().add(furnitureIdOrSuiteId);
|
player.getUnlockedFurnitureSuite().add(furnitureIdOrSuiteId);
|
||||||
notifyUnlockFurnitureSuite();
|
notifyUnlockFurnitureSuite();
|
||||||
}
|
}
|
||||||
@@ -57,19 +57,19 @@ public class FurnitureManager extends BasePlayerManager {
|
|||||||
|
|
||||||
public void startMake(int makeId, int avatarId) {
|
public void startMake(int makeId, int avatarId) {
|
||||||
var makeData = GameData.getFurnitureMakeConfigDataMap().get(makeId);
|
var makeData = GameData.getFurnitureMakeConfigDataMap().get(makeId);
|
||||||
if(makeData == null){
|
if (makeData == null) {
|
||||||
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, null));
|
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, null));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// check slot count
|
// check slot count
|
||||||
if (player.getHome().getLevelData().getFurnitureMakeSlotCount() <= player.getHome().getFurnitureMakeSlotItemList().size()){
|
if (player.getHome().getLevelData().getFurnitureMakeSlotCount() <= player.getHome().getFurnitureMakeSlotItemList().size()) {
|
||||||
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_SLOT_FULL_VALUE, null));
|
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_SLOT_FULL_VALUE, null));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// pay items first
|
// pay items first
|
||||||
if(!player.getInventory().payItems(makeData.getMaterialItems().toArray(new ItemParamData[0]))){
|
if (!player.getInventory().payItems(makeData.getMaterialItems().toArray(new ItemParamData[0]))) {
|
||||||
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_HOME_FURNITURE_COUNT_NOT_ENOUGH_VALUE, null));
|
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_HOME_FURNITURE_COUNT_NOT_ENOUGH_VALUE, null));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -93,7 +93,7 @@ public class FurnitureManager extends BasePlayerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void queryStatus() {
|
public void queryStatus() {
|
||||||
if (player.getHome().getFurnitureMakeSlotItemList() == null){
|
if (player.getHome().getFurnitureMakeSlotItemList() == null) {
|
||||||
player.getHome().setFurnitureMakeSlotItemList(new ArrayList<>());
|
player.getHome().setFurnitureMakeSlotItemList(new ArrayList<>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,7 +103,7 @@ public class FurnitureManager extends BasePlayerManager {
|
|||||||
|
|
||||||
public void take(int index, int makeId, boolean isFastFinish) {
|
public void take(int index, int makeId, boolean isFastFinish) {
|
||||||
var makeData = GameData.getFurnitureMakeConfigDataMap().get(makeId);
|
var makeData = GameData.getFurnitureMakeConfigDataMap().get(makeId);
|
||||||
if(makeData == null){
|
if (makeData == null) {
|
||||||
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, makeId, null, null));
|
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, makeId, null, null));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -112,19 +112,19 @@ public class FurnitureManager extends BasePlayerManager {
|
|||||||
.filter(x -> x.getIndex() == index && x.getMakeId() == makeId)
|
.filter(x -> x.getIndex() == index && x.getMakeId() == makeId)
|
||||||
.findFirst();
|
.findFirst();
|
||||||
|
|
||||||
if(slotItem.isEmpty()){
|
if (slotItem.isEmpty()) {
|
||||||
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_NO_MAKE_DATA_VALUE, makeId, null, null));
|
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_NO_MAKE_DATA_VALUE, makeId, null, null));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// pay the speedup item
|
// pay the speedup item
|
||||||
if(isFastFinish && !player.getInventory().payItem(107013,1)){
|
if (isFastFinish && !player.getInventory().payItem(107013,1)) {
|
||||||
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
|
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if player can take
|
// check if player can take
|
||||||
// if(slotItem.get().getBeginTime() + slotItem.get().getDurTime() >= Utils.getCurrentSeconds() && !isFastFinish){
|
// if (slotItem.get().getBeginTime() + slotItem.get().getDurTime() >= Utils.getCurrentSeconds() && !isFastFinish) {
|
||||||
// player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
|
// player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
|
@@ -38,16 +38,16 @@ public class DeforestationManager extends BasePlayerManager {
|
|||||||
ColliderTypeToWoodItemID.put(12,101312);
|
ColliderTypeToWoodItemID.put(12,101312);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DeforestationManager(Player player){
|
public DeforestationManager(Player player) {
|
||||||
super(player);
|
super(player);
|
||||||
this.currentRecord = new ArrayList<>();
|
this.currentRecord = new ArrayList<>();
|
||||||
}
|
}
|
||||||
public void resetWood(){
|
public void resetWood() {
|
||||||
synchronized (currentRecord) {
|
synchronized (currentRecord) {
|
||||||
currentRecord.clear();
|
currentRecord.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public void onDeforestationInvoke(HitTreeNotifyOuterClass.HitTreeNotify hit){
|
public void onDeforestationInvoke(HitTreeNotifyOuterClass.HitTreeNotify hit) {
|
||||||
synchronized (currentRecord) {
|
synchronized (currentRecord) {
|
||||||
//Grasscutter.getLogger().info("onDeforestationInvoke! Wood records {}", currentRecord);
|
//Grasscutter.getLogger().info("onDeforestationInvoke! Wood records {}", currentRecord);
|
||||||
VectorOuterClass.Vector hitPosition = hit.getTreePos();
|
VectorOuterClass.Vector hitPosition = hit.getTreePos();
|
||||||
@@ -59,14 +59,14 @@ public class DeforestationManager extends BasePlayerManager {
|
|||||||
HitTreeRecord record = searchRecord(positionHash);
|
HitTreeRecord record = searchRecord(positionHash);
|
||||||
if (record == null) {
|
if (record == null) {
|
||||||
record = new HitTreeRecord(positionHash);
|
record = new HitTreeRecord(positionHash);
|
||||||
}else{
|
}else {
|
||||||
currentRecord.remove(record);// move it to last position
|
currentRecord.remove(record);// move it to last position
|
||||||
}
|
}
|
||||||
currentRecord.add(record);
|
currentRecord.add(record);
|
||||||
if(currentRecord.size()>RECORD_MAX_TIMES_OTHER_HIT_TREE){
|
if (currentRecord.size()>RECORD_MAX_TIMES_OTHER_HIT_TREE) {
|
||||||
currentRecord.remove(0);
|
currentRecord.remove(0);
|
||||||
}
|
}
|
||||||
if(record.record()) {
|
if (record.record()) {
|
||||||
EntityItem entity = new EntityItem(scene,
|
EntityItem entity = new EntityItem(scene,
|
||||||
null,
|
null,
|
||||||
GameData.getItemDataMap().get(itemId),
|
GameData.getItemDataMap().get(itemId),
|
||||||
@@ -82,7 +82,7 @@ public class DeforestationManager extends BasePlayerManager {
|
|||||||
}
|
}
|
||||||
// unknown wood type
|
// unknown wood type
|
||||||
}
|
}
|
||||||
private HitTreeRecord searchRecord(int id){
|
private HitTreeRecord searchRecord(int id) {
|
||||||
for (HitTreeRecord record : currentRecord) {
|
for (HitTreeRecord record : currentRecord) {
|
||||||
if (record.getUnique() == id) {
|
if (record.getUnique() == id) {
|
||||||
return record;
|
return record;
|
||||||
|
@@ -826,7 +826,7 @@ public class Player {
|
|||||||
session.send(new PacketCardProductRewardNotify(getMoonCardRemainDays()));
|
session.send(new PacketCardProductRewardNotify(getMoonCardRemainDays()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addExpeditionInfo(long avaterGuid, int expId, int hourTime, int startTime){
|
public void addExpeditionInfo(long avaterGuid, int expId, int hourTime, int startTime) {
|
||||||
ExpeditionInfo exp = new ExpeditionInfo();
|
ExpeditionInfo exp = new ExpeditionInfo();
|
||||||
exp.setExpId(expId);
|
exp.setExpId(expId);
|
||||||
exp.setHourTime(hourTime);
|
exp.setHourTime(hourTime);
|
||||||
@@ -835,11 +835,11 @@ public class Player {
|
|||||||
expeditionInfo.put(avaterGuid, exp);
|
expeditionInfo.put(avaterGuid, exp);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeExpeditionInfo(long avaterGuid){
|
public void removeExpeditionInfo(long avaterGuid) {
|
||||||
expeditionInfo.remove(avaterGuid);
|
expeditionInfo.remove(avaterGuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ExpeditionInfo getExpeditionInfo(long avaterGuid){
|
public ExpeditionInfo getExpeditionInfo(long avaterGuid) {
|
||||||
return expeditionInfo.get(avaterGuid);
|
return expeditionInfo.get(avaterGuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1148,7 +1148,7 @@ public class Player {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public PlayerCollectionRecords getCollectionRecordStore() {
|
public PlayerCollectionRecords getCollectionRecordStore() {
|
||||||
if(this.collectionRecordStore==null){
|
if (this.collectionRecordStore==null) {
|
||||||
this.collectionRecordStore = new PlayerCollectionRecords();
|
this.collectionRecordStore = new PlayerCollectionRecords();
|
||||||
}
|
}
|
||||||
return collectionRecordStore;
|
return collectionRecordStore;
|
||||||
@@ -1208,14 +1208,14 @@ public class Player {
|
|||||||
var needNotify = false;
|
var needNotify = false;
|
||||||
for (Long key : expeditionInfo.keySet()) {
|
for (Long key : expeditionInfo.keySet()) {
|
||||||
ExpeditionInfo e = expeditionInfo.get(key);
|
ExpeditionInfo e = expeditionInfo.get(key);
|
||||||
if(e.getState() == 1){
|
if (e.getState() == 1) {
|
||||||
if(timeNow - e.getStartTime() >= e.getHourTime() * 60 * 60){
|
if (timeNow - e.getStartTime() >= e.getHourTime() * 60 * 60) {
|
||||||
e.setState(2);
|
e.setState(2);
|
||||||
needNotify = true;
|
needNotify = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(needNotify){
|
if (needNotify) {
|
||||||
this.save();
|
this.save();
|
||||||
this.sendPacket(new PacketAvatarExpeditionDataNotify(this));
|
this.sendPacket(new PacketAvatarExpeditionDataNotify(this));
|
||||||
}
|
}
|
||||||
@@ -1371,7 +1371,7 @@ public class Player {
|
|||||||
|
|
||||||
// Call join event.
|
// Call join event.
|
||||||
PlayerJoinEvent event = new PlayerJoinEvent(this); event.call();
|
PlayerJoinEvent event = new PlayerJoinEvent(this); event.call();
|
||||||
if(event.isCanceled()){ // If event is not cancelled, continue.
|
if (event.isCanceled()) { // If event is not cancelled, continue.
|
||||||
session.close();
|
session.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1382,7 +1382,7 @@ public class Player {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void onLogout() {
|
public void onLogout() {
|
||||||
try{
|
try {
|
||||||
// Clear chat history.
|
// Clear chat history.
|
||||||
this.getServer().getChatManager().clearHistoryOnLogout(this);
|
this.getServer().getChatManager().clearHistoryOnLogout(this);
|
||||||
|
|
||||||
@@ -1410,7 +1410,7 @@ public class Player {
|
|||||||
|
|
||||||
// Call quit event.
|
// Call quit event.
|
||||||
PlayerQuitEvent event = new PlayerQuitEvent(this); event.call();
|
PlayerQuitEvent event = new PlayerQuitEvent(this); event.call();
|
||||||
}catch (Throwable e){
|
}catch (Throwable e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
Grasscutter.getLogger().warn("Player (UID {}) save failure", getUid());
|
Grasscutter.getLogger().warn("Player (UID {}) save failure", getUid());
|
||||||
}finally {
|
}finally {
|
||||||
|
@@ -16,7 +16,7 @@ public class PlayerCollectionRecords {
|
|||||||
return records;
|
return records;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addRecord(int configId, long expiredMillisecond){
|
public void addRecord(int configId, long expiredMillisecond) {
|
||||||
Map<Integer, CollectionRecord> records;
|
Map<Integer, CollectionRecord> records;
|
||||||
synchronized (records = getRecords()) {
|
synchronized (records = getRecords()) {
|
||||||
records.put(configId, new CollectionRecord(configId, expiredMillisecond + System.currentTimeMillis()));
|
records.put(configId, new CollectionRecord(configId, expiredMillisecond + System.currentTimeMillis()));
|
||||||
|
@@ -49,14 +49,14 @@ public class PlayerOpenStateManager extends BasePlayerDataManager {
|
|||||||
|
|
||||||
public void setOpenState(OpenState openState, Integer value) {
|
public void setOpenState(OpenState openState, Integer value) {
|
||||||
Integer previousValue = this.map.getOrDefault(openState.getValue(),0);
|
Integer previousValue = this.map.getOrDefault(openState.getValue(),0);
|
||||||
if(value != previousValue) {
|
if (value != previousValue) {
|
||||||
this.map.put(openState.getValue(), value);
|
this.map.put(openState.getValue(), value);
|
||||||
player.getSession().send(new PacketOpenStateChangeNotify(openState.getValue(),value));
|
player.getSession().send(new PacketOpenStateChangeNotify(openState.getValue(),value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOpenStates(Map<OpenState,Integer> openStatesChanged) {
|
public void setOpenStates(Map<OpenState,Integer> openStatesChanged) {
|
||||||
for(Map.Entry<OpenState, Integer> entry : openStatesChanged.entrySet()) {
|
for (Map.Entry<OpenState, Integer> entry : openStatesChanged.entrySet()) {
|
||||||
setOpenState(entry.getKey(), entry.getValue());
|
setOpenState(entry.getKey(), entry.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -130,7 +130,7 @@ public class TeamManager extends BasePlayerDataManager {
|
|||||||
|
|
||||||
public TeamInfo getCurrentTeamInfo() {
|
public TeamInfo getCurrentTeamInfo() {
|
||||||
if (useTemporarilyTeamIndex >= 0 &&
|
if (useTemporarilyTeamIndex >= 0 &&
|
||||||
useTemporarilyTeamIndex < temporaryTeam.size()){
|
useTemporarilyTeamIndex < temporaryTeam.size()) {
|
||||||
return temporaryTeam.get(useTemporarilyTeamIndex);
|
return temporaryTeam.get(useTemporarilyTeamIndex);
|
||||||
}
|
}
|
||||||
if (this.getPlayer().isInMultiplayer()) {
|
if (this.getPlayer().isInMultiplayer()) {
|
||||||
@@ -208,7 +208,7 @@ public class TeamManager extends BasePlayerDataManager {
|
|||||||
* If the current team is temporary, returns false.
|
* If the current team is temporary, returns false.
|
||||||
*/
|
*/
|
||||||
public boolean canAddAvatarsToCurrentTeam(int avatars) {
|
public boolean canAddAvatarsToCurrentTeam(int avatars) {
|
||||||
if (this.useTemporarilyTeamIndex != -1){
|
if (this.useTemporarilyTeamIndex != -1) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return canAddAvatarsToTeam(this.getCurrentTeamInfo(), avatars);
|
return canAddAvatarsToTeam(this.getCurrentTeamInfo(), avatars);
|
||||||
@@ -264,7 +264,7 @@ public class TeamManager extends BasePlayerDataManager {
|
|||||||
* Try to add an avatar to a team.
|
* Try to add an avatar to a team.
|
||||||
* Returns true if successful.
|
* Returns true if successful.
|
||||||
*/
|
*/
|
||||||
public boolean addAvatarToTeam(TeamInfo team, Avatar avatar){
|
public boolean addAvatarToTeam(TeamInfo team, Avatar avatar) {
|
||||||
return addAvatarsToTeam(team, Collections.singleton(avatar));
|
return addAvatarsToTeam(team, Collections.singleton(avatar));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,7 +275,7 @@ public class TeamManager extends BasePlayerDataManager {
|
|||||||
* If some can not be added, returns false and does not add any.
|
* If some can not be added, returns false and does not add any.
|
||||||
*/
|
*/
|
||||||
public boolean addAvatarsToCurrentTeam(Collection<Avatar> avatars) {
|
public boolean addAvatarsToCurrentTeam(Collection<Avatar> avatars) {
|
||||||
if (this.useTemporarilyTeamIndex != -1){
|
if (this.useTemporarilyTeamIndex != -1) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return addAvatarsToTeam(this.getCurrentTeamInfo(), avatars);
|
return addAvatarsToTeam(this.getCurrentTeamInfo(), avatars);
|
||||||
@@ -481,7 +481,7 @@ public class TeamManager extends BasePlayerDataManager {
|
|||||||
|
|
||||||
public void cleanTemporaryTeam() {
|
public void cleanTemporaryTeam() {
|
||||||
// check if using temporary team
|
// check if using temporary team
|
||||||
if(useTemporarilyTeamIndex < 0){
|
if (useTemporarilyTeamIndex < 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -62,7 +62,7 @@ public class GameQuest {
|
|||||||
|
|
||||||
this.getOwner().getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_QUEST_STATE_EQUAL, this.questId, this.state.getValue());
|
this.getOwner().getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_QUEST_STATE_EQUAL, this.questId, this.state.getValue());
|
||||||
|
|
||||||
if (ChapterData.beginQuestChapterMap.containsKey(questId)){
|
if (ChapterData.beginQuestChapterMap.containsKey(questId)) {
|
||||||
mainQuest.getOwner().sendPacket(new PacketChapterStateNotify(
|
mainQuest.getOwner().sendPacket(new PacketChapterStateNotify(
|
||||||
ChapterData.beginQuestChapterMap.get(questId).getId(),
|
ChapterData.beginQuestChapterMap.get(questId).getId(),
|
||||||
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_BEGIN
|
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_BEGIN
|
||||||
@@ -175,7 +175,7 @@ public class GameQuest {
|
|||||||
|
|
||||||
this.getOwner().getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_QUEST_STATE_EQUAL, this.questId, this.state.getValue());
|
this.getOwner().getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_QUEST_STATE_EQUAL, this.questId, this.state.getValue());
|
||||||
|
|
||||||
if (ChapterData.endQuestChapterMap.containsKey(questId)){
|
if (ChapterData.endQuestChapterMap.containsKey(questId)) {
|
||||||
mainQuest.getOwner().sendPacket(new PacketChapterStateNotify(
|
mainQuest.getOwner().sendPacket(new PacketChapterStateNotify(
|
||||||
ChapterData.endQuestChapterMap.get(questId).getId(),
|
ChapterData.endQuestChapterMap.get(questId).getId(),
|
||||||
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_END
|
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_END
|
||||||
|
@@ -117,10 +117,10 @@ public class QuestManager extends BasePlayerManager {
|
|||||||
|
|
||||||
return quest;
|
return quest;
|
||||||
}
|
}
|
||||||
public void startMainQuest(int mainQuestId){
|
public void startMainQuest(int mainQuestId) {
|
||||||
var mainQuestData = GameData.getMainQuestDataMap().get(mainQuestId);
|
var mainQuestData = GameData.getMainQuestDataMap().get(mainQuestId);
|
||||||
|
|
||||||
if (mainQuestData == null){
|
if (mainQuestData == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -63,7 +63,7 @@ public class ShopSystem extends BaseGameSystem {
|
|||||||
try (Reader fileReader = DataLoader.loadReader("Shop.json")) {
|
try (Reader fileReader = DataLoader.loadReader("Shop.json")) {
|
||||||
getShopData().clear();
|
getShopData().clear();
|
||||||
List<ShopTable> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ShopTable.class).getType());
|
List<ShopTable> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ShopTable.class).getType());
|
||||||
if(banners.size() > 0) {
|
if (banners.size() > 0) {
|
||||||
for (ShopTable shopTable : banners) {
|
for (ShopTable shopTable : banners) {
|
||||||
for (ShopInfo cost : shopTable.getItems()) {
|
for (ShopInfo cost : shopTable.getItems()) {
|
||||||
if (cost.getCostItemList() != null) {
|
if (cost.getCostItemList() != null) {
|
||||||
|
@@ -23,7 +23,7 @@ import java.util.*;
|
|||||||
public class AnnouncementSystem extends BaseGameSystem {
|
public class AnnouncementSystem extends BaseGameSystem {
|
||||||
private final Map<Integer, AnnounceConfigItem> announceConfigItemMap;
|
private final Map<Integer, AnnounceConfigItem> announceConfigItemMap;
|
||||||
|
|
||||||
public AnnouncementSystem(GameServer server){
|
public AnnouncementSystem(GameServer server) {
|
||||||
super(server);
|
super(server);
|
||||||
this.announceConfigItemMap = new HashMap<>();
|
this.announceConfigItemMap = new HashMap<>();
|
||||||
loadConfig();
|
loadConfig();
|
||||||
@@ -51,7 +51,7 @@ public class AnnouncementSystem extends BaseGameSystem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void broadcast(List<AnnounceConfigItem> tpl) {
|
public void broadcast(List<AnnounceConfigItem> tpl) {
|
||||||
if(tpl == null || tpl.size() == 0){
|
if (tpl == null || tpl.size() == 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,7 +83,7 @@ public class AnnouncementSystem extends BaseGameSystem {
|
|||||||
boolean tick;
|
boolean tick;
|
||||||
int interval;
|
int interval;
|
||||||
|
|
||||||
public AnnounceDataOuterClass.AnnounceData.Builder toProto(){
|
public AnnounceDataOuterClass.AnnounceData.Builder toProto() {
|
||||||
var proto = AnnounceDataOuterClass.AnnounceData.newBuilder();
|
var proto = AnnounceDataOuterClass.AnnounceData.newBuilder();
|
||||||
|
|
||||||
proto.setConfigId(templateId)
|
proto.setConfigId(templateId)
|
||||||
@@ -91,11 +91,11 @@ public class AnnouncementSystem extends BaseGameSystem {
|
|||||||
.setBeginTime(Utils.getCurrentSeconds() + 1)
|
.setBeginTime(Utils.getCurrentSeconds() + 1)
|
||||||
.setEndTime(Utils.getCurrentSeconds() + 10);
|
.setEndTime(Utils.getCurrentSeconds() + 10);
|
||||||
|
|
||||||
if(type == AnnounceType.CENTER){
|
if (type == AnnounceType.CENTER) {
|
||||||
proto.setCenterSystemText(content)
|
proto.setCenterSystemText(content)
|
||||||
.setCenterSystemFrequency(frequency)
|
.setCenterSystemFrequency(frequency)
|
||||||
;
|
;
|
||||||
}else{
|
}else {
|
||||||
proto.setCountDownText(content)
|
proto.setCountDownText(content)
|
||||||
.setCountDownFrequency(frequency)
|
.setCountDownFrequency(frequency)
|
||||||
;
|
;
|
||||||
|
@@ -101,7 +101,7 @@ public class InventorySystem extends BaseGameSystem {
|
|||||||
List<ItemParamData> payList = new ArrayList<ItemParamData>();
|
List<ItemParamData> payList = new ArrayList<ItemParamData>();
|
||||||
for (ItemParam itemParam : list) {
|
for (ItemParam itemParam : list) {
|
||||||
int amount = itemParam.getCount(); // Previously this capped to inventory amount, but rejecting the payment makes more sense for an invalid order
|
int amount = itemParam.getCount(); // Previously this capped to inventory amount, but rejecting the payment makes more sense for an invalid order
|
||||||
int gain = amount * switch(itemParam.getItemId()) {
|
int gain = amount * switch (itemParam.getItemId()) {
|
||||||
case RELIC_MATERIAL_1 -> RELIC_MATERIAL_EXP_1;
|
case RELIC_MATERIAL_1 -> RELIC_MATERIAL_EXP_1;
|
||||||
case RELIC_MATERIAL_2 -> RELIC_MATERIAL_EXP_2;
|
case RELIC_MATERIAL_2 -> RELIC_MATERIAL_EXP_2;
|
||||||
default -> 0;
|
default -> 0;
|
||||||
@@ -211,7 +211,7 @@ public class InventorySystem extends BaseGameSystem {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (ItemParam param : itemParamList) {
|
for (ItemParam param : itemParamList) {
|
||||||
expGain += param.getCount() * switch(param.getItemId()) {
|
expGain += param.getCount() * switch (param.getItemId()) {
|
||||||
case WEAPON_ORE_1 -> WEAPON_ORE_EXP_1;
|
case WEAPON_ORE_1 -> WEAPON_ORE_EXP_1;
|
||||||
case WEAPON_ORE_2 -> WEAPON_ORE_EXP_2;
|
case WEAPON_ORE_2 -> WEAPON_ORE_EXP_2;
|
||||||
case WEAPON_ORE_3 -> WEAPON_ORE_EXP_3;
|
case WEAPON_ORE_3 -> WEAPON_ORE_EXP_3;
|
||||||
@@ -274,7 +274,7 @@ public class InventorySystem extends BaseGameSystem {
|
|||||||
List<ItemParamData> payList = new ArrayList<ItemParamData>();
|
List<ItemParamData> payList = new ArrayList<ItemParamData>();
|
||||||
for (ItemParam param : itemParamList) {
|
for (ItemParam param : itemParamList) {
|
||||||
int amount = param.getCount(); // Previously this capped to inventory amount, but rejecting the payment makes more sense for an invalid order
|
int amount = param.getCount(); // Previously this capped to inventory amount, but rejecting the payment makes more sense for an invalid order
|
||||||
int gain = amount * switch(param.getItemId()) {
|
int gain = amount * switch (param.getItemId()) {
|
||||||
case WEAPON_ORE_1 -> WEAPON_ORE_EXP_1;
|
case WEAPON_ORE_1 -> WEAPON_ORE_EXP_1;
|
||||||
case WEAPON_ORE_2 -> WEAPON_ORE_EXP_2;
|
case WEAPON_ORE_2 -> WEAPON_ORE_EXP_2;
|
||||||
case WEAPON_ORE_3 -> WEAPON_ORE_EXP_3;
|
case WEAPON_ORE_3 -> WEAPON_ORE_EXP_3;
|
||||||
@@ -545,7 +545,7 @@ public class InventorySystem extends BaseGameSystem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Calc exp
|
// Calc exp
|
||||||
int expGain = switch(itemId) {
|
int expGain = switch (itemId) {
|
||||||
case AVATAR_BOOK_1 -> AVATAR_BOOK_EXP_1 * count;
|
case AVATAR_BOOK_1 -> AVATAR_BOOK_EXP_1 * count;
|
||||||
case AVATAR_BOOK_2 -> AVATAR_BOOK_EXP_2 * count;
|
case AVATAR_BOOK_2 -> AVATAR_BOOK_EXP_2 * count;
|
||||||
case AVATAR_BOOK_3 -> AVATAR_BOOK_EXP_3 * count;
|
case AVATAR_BOOK_3 -> AVATAR_BOOK_EXP_3 * count;
|
||||||
@@ -868,7 +868,7 @@ public class InventorySystem extends BaseGameSystem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handle fragile/transient resin.
|
// Handle fragile/transient resin.
|
||||||
if (useItem.getItemId() == 107009 || useItem.getItemId() == 107012){
|
if (useItem.getItemId() == 107009 || useItem.getItemId() == 107012) {
|
||||||
// Add resin to the inventory.
|
// Add resin to the inventory.
|
||||||
ItemData resinItemData = GameData.getItemDataMap().get(106);
|
ItemData resinItemData = GameData.getItemDataMap().get(106);
|
||||||
player.getInventory().addItem(new GameItem(resinItemData, 60 * count), ActionReason.PlayerUseItem);
|
player.getInventory().addItem(new GameItem(resinItemData, 60 * count), ActionReason.PlayerUseItem);
|
||||||
|
@@ -26,21 +26,21 @@ public class TowerManager extends BasePlayerManager {
|
|||||||
return getTowerData().currentFloorId;
|
return getTowerData().currentFloorId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getCurrentLevelId(){
|
public int getCurrentLevelId() {
|
||||||
return getTowerData().currentLevelId + getTowerData().currentLevel;
|
return getTowerData().currentLevelId + getTowerData().currentLevel;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* form 1-3
|
* form 1-3
|
||||||
*/
|
*/
|
||||||
public int getCurrentLevel(){
|
public int getCurrentLevel() {
|
||||||
return getTowerData().currentLevel + 1;
|
return getTowerData().currentLevel + 1;
|
||||||
}
|
}
|
||||||
private static final List<DungeonSettleListener> towerDungeonSettleListener = List.of(new TowerDungeonSettleListener());
|
private static final List<DungeonSettleListener> towerDungeonSettleListener = List.of(new TowerDungeonSettleListener());
|
||||||
|
|
||||||
public Map<Integer, TowerLevelRecord> getRecordMap() {
|
public Map<Integer, TowerLevelRecord> getRecordMap() {
|
||||||
Map<Integer, TowerLevelRecord> recordMap = getTowerData().recordMap;
|
Map<Integer, TowerLevelRecord> recordMap = getTowerData().recordMap;
|
||||||
if(recordMap == null || recordMap.size()==0){
|
if (recordMap == null || recordMap.size()==0) {
|
||||||
recordMap = new HashMap<>();
|
recordMap = new HashMap<>();
|
||||||
recordMap.put(1001, new TowerLevelRecord(1001));
|
recordMap.put(1001, new TowerLevelRecord(1001));
|
||||||
getTowerData().recordMap = recordMap;
|
getTowerData().recordMap = recordMap;
|
||||||
@@ -58,7 +58,7 @@ public class TowerManager extends BasePlayerManager {
|
|||||||
.map(TowerLevelData::getId)
|
.map(TowerLevelData::getId)
|
||||||
.orElse(0);
|
.orElse(0);
|
||||||
|
|
||||||
if (getTowerData().entryScene == 0){
|
if (getTowerData().entryScene == 0) {
|
||||||
getTowerData().entryScene = player.getSceneId();
|
getTowerData().entryScene = player.getSceneId();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,37 +88,37 @@ public class TowerManager extends BasePlayerManager {
|
|||||||
player.getSession().send(new PacketTowerLevelStarCondNotify(getTowerData().currentFloorId, getCurrentLevel()));
|
player.getSession().send(new PacketTowerLevelStarCondNotify(getTowerData().currentFloorId, getCurrentLevel()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void notifyCurLevelRecordChange(){
|
public void notifyCurLevelRecordChange() {
|
||||||
player.getSession().send(new PacketTowerCurLevelRecordChangeNotify(getTowerData().currentFloorId, getCurrentLevel()));
|
player.getSession().send(new PacketTowerCurLevelRecordChangeNotify(getTowerData().currentFloorId, getCurrentLevel()));
|
||||||
}
|
}
|
||||||
public void notifyCurLevelRecordChangeWhenDone(int stars){
|
public void notifyCurLevelRecordChangeWhenDone(int stars) {
|
||||||
Map<Integer, TowerLevelRecord> recordMap = getRecordMap();
|
Map<Integer, TowerLevelRecord> recordMap = getRecordMap();
|
||||||
int currentFloorId = getTowerData().currentFloorId;
|
int currentFloorId = getTowerData().currentFloorId;
|
||||||
if(!recordMap.containsKey(currentFloorId)){
|
if (!recordMap.containsKey(currentFloorId)) {
|
||||||
recordMap.put(currentFloorId,
|
recordMap.put(currentFloorId,
|
||||||
new TowerLevelRecord(currentFloorId).setLevelStars(getCurrentLevelId(),stars));
|
new TowerLevelRecord(currentFloorId).setLevelStars(getCurrentLevelId(),stars));
|
||||||
}else{
|
}else {
|
||||||
recordMap.put(currentFloorId,
|
recordMap.put(currentFloorId,
|
||||||
recordMap.get(currentFloorId).setLevelStars(getCurrentLevelId(),stars));
|
recordMap.get(currentFloorId).setLevelStars(getCurrentLevelId(),stars));
|
||||||
}
|
}
|
||||||
|
|
||||||
getTowerData().currentLevel++;
|
getTowerData().currentLevel++;
|
||||||
|
|
||||||
if(!hasNextLevel()){
|
if (!hasNextLevel()) {
|
||||||
// set up the next floor
|
// set up the next floor
|
||||||
recordMap.putIfAbsent(getNextFloorId(), new TowerLevelRecord(getNextFloorId()));
|
recordMap.putIfAbsent(getNextFloorId(), new TowerLevelRecord(getNextFloorId()));
|
||||||
player.getSession().send(new PacketTowerCurLevelRecordChangeNotify(getNextFloorId(), 1));
|
player.getSession().send(new PacketTowerCurLevelRecordChangeNotify(getNextFloorId(), 1));
|
||||||
}else{
|
}else {
|
||||||
player.getSession().send(new PacketTowerCurLevelRecordChangeNotify(currentFloorId, getCurrentLevel()));
|
player.getSession().send(new PacketTowerCurLevelRecordChangeNotify(currentFloorId, getCurrentLevel()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public boolean hasNextLevel(){
|
public boolean hasNextLevel() {
|
||||||
return getTowerData().currentLevel < 3;
|
return getTowerData().currentLevel < 3;
|
||||||
}
|
}
|
||||||
public int getNextFloorId() {
|
public int getNextFloorId() {
|
||||||
return player.getServer().getTowerSystem().getNextFloorId(getTowerData().currentFloorId);
|
return player.getServer().getTowerSystem().getNextFloorId(getTowerData().currentFloorId);
|
||||||
}
|
}
|
||||||
public boolean hasNextFloor(){
|
public boolean hasNextFloor() {
|
||||||
return player.getServer().getTowerSystem().getNextFloorId(getTowerData().currentFloorId) > 0;
|
return player.getServer().getTowerSystem().getNextFloorId(getTowerData().currentFloorId) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,9 +126,9 @@ public class TowerManager extends BasePlayerManager {
|
|||||||
getTowerData().entryScene = 0;
|
getTowerData().entryScene = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean canEnterScheduleFloor(){
|
public boolean canEnterScheduleFloor() {
|
||||||
Map<Integer, TowerLevelRecord> recordMap = getRecordMap();
|
Map<Integer, TowerLevelRecord> recordMap = getRecordMap();
|
||||||
if(!recordMap.containsKey(player.getServer().getTowerSystem().getLastEntranceFloor())){
|
if (!recordMap.containsKey(player.getServer().getTowerSystem().getLastEntranceFloor())) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return recordMap.get(player.getServer().getTowerSystem().getLastEntranceFloor())
|
return recordMap.get(player.getServer().getTowerSystem().getLastEntranceFloor())
|
||||||
|
@@ -24,7 +24,7 @@ public class TowerSystem extends BaseGameSystem {
|
|||||||
|
|
||||||
private TowerScheduleConfig towerScheduleConfig;
|
private TowerScheduleConfig towerScheduleConfig;
|
||||||
|
|
||||||
public synchronized void load(){
|
public synchronized void load() {
|
||||||
try (Reader fileReader = DataLoader.loadReader("TowerSchedule.json")) {
|
try (Reader fileReader = DataLoader.loadReader("TowerSchedule.json")) {
|
||||||
towerScheduleConfig = Grasscutter.getGsonFactory().fromJson(fileReader, TowerScheduleConfig.class);
|
towerScheduleConfig = Grasscutter.getGsonFactory().fromJson(fileReader, TowerScheduleConfig.class);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -36,9 +36,9 @@ public class TowerSystem extends BaseGameSystem {
|
|||||||
return towerScheduleConfig;
|
return towerScheduleConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
public TowerScheduleData getCurrentTowerScheduleData(){
|
public TowerScheduleData getCurrentTowerScheduleData() {
|
||||||
var data = GameData.getTowerScheduleDataMap().get(towerScheduleConfig.getScheduleId());
|
var data = GameData.getTowerScheduleDataMap().get(towerScheduleConfig.getScheduleId());
|
||||||
if(data == null){
|
if (data == null) {
|
||||||
Grasscutter.getLogger().error("Could not get current tower schedule data by schedule id {}, please check your resource files",
|
Grasscutter.getLogger().error("Could not get current tower schedule data by schedule id {}, please check your resource files",
|
||||||
towerScheduleConfig.getScheduleId());
|
towerScheduleConfig.getScheduleId());
|
||||||
}
|
}
|
||||||
@@ -56,29 +56,29 @@ public class TowerSystem extends BaseGameSystem {
|
|||||||
return getCurrentTowerScheduleData().getSchedules().get(0).getFloorList();
|
return getCurrentTowerScheduleData().getSchedules().get(0).getFloorList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getNextFloorId(int floorId){
|
public int getNextFloorId(int floorId) {
|
||||||
var entranceFloors = getCurrentTowerScheduleData().getEntranceFloorId();
|
var entranceFloors = getCurrentTowerScheduleData().getEntranceFloorId();
|
||||||
var scheduleFloors = getScheduleFloors();
|
var scheduleFloors = getScheduleFloors();
|
||||||
var nextId = 0;
|
var nextId = 0;
|
||||||
|
|
||||||
// find in entrance floors first
|
// find in entrance floors first
|
||||||
for(int i=0;i<entranceFloors.size()-1;i++){
|
for (int i=0;i<entranceFloors.size()-1;i++) {
|
||||||
if(floorId == entranceFloors.get(i)){
|
if (floorId == entranceFloors.get(i)) {
|
||||||
nextId = entranceFloors.get(i+1);
|
nextId = entranceFloors.get(i+1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(floorId == entranceFloors.get(entranceFloors.size()-1)){
|
if (floorId == entranceFloors.get(entranceFloors.size()-1)) {
|
||||||
nextId = scheduleFloors.get(0);
|
nextId = scheduleFloors.get(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(nextId != 0){
|
if (nextId != 0) {
|
||||||
return nextId;
|
return nextId;
|
||||||
}
|
}
|
||||||
|
|
||||||
// find in schedule floors
|
// find in schedule floors
|
||||||
for(int i=0; i < scheduleFloors.size() - 1; i++){
|
for (int i=0; i < scheduleFloors.size() - 1; i++) {
|
||||||
if(floorId == scheduleFloors.get(i)){
|
if (floorId == scheduleFloors.get(i)) {
|
||||||
nextId = scheduleFloors.get(i + 1);
|
nextId = scheduleFloors.get(i + 1);
|
||||||
}
|
}
|
||||||
}return nextId;
|
}return nextId;
|
||||||
|
@@ -186,8 +186,8 @@ public class Scene {
|
|||||||
this.challenge = challenge;
|
this.challenge = challenge;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addDungeonSettleObserver(DungeonSettleListener dungeonSettleListener){
|
public void addDungeonSettleObserver(DungeonSettleListener dungeonSettleListener) {
|
||||||
if(dungeonSettleListeners == null){
|
if (dungeonSettleListeners == null) {
|
||||||
dungeonSettleListeners = new ArrayList<>();
|
dungeonSettleListeners = new ArrayList<>();
|
||||||
}
|
}
|
||||||
dungeonSettleListeners.add(dungeonSettleListener);
|
dungeonSettleListeners.add(dungeonSettleListener);
|
||||||
@@ -303,12 +303,12 @@ public class Scene {
|
|||||||
player.sendPacket(new PacketSceneEntityAppearNotify(entity));
|
player.sendPacket(new PacketSceneEntityAppearNotify(entity));
|
||||||
|
|
||||||
}
|
}
|
||||||
public void addEntities(Collection<? extends GameEntity> entities){
|
public void addEntities(Collection<? extends GameEntity> entities) {
|
||||||
addEntities(entities, VisionType.VISION_TYPE_BORN);
|
addEntities(entities, VisionType.VISION_TYPE_BORN);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void addEntities(Collection<? extends GameEntity> entities, VisionType visionType) {
|
public synchronized void addEntities(Collection<? extends GameEntity> entities, VisionType visionType) {
|
||||||
if(entities == null || entities.isEmpty()){
|
if (entities == null || entities.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (GameEntity entity : entities) {
|
for (GameEntity entity : entities) {
|
||||||
@@ -420,7 +420,7 @@ public class Scene {
|
|||||||
|
|
||||||
public void onTick() {
|
public void onTick() {
|
||||||
// disable script for home
|
// disable script for home
|
||||||
if (this.getSceneType() == SceneType.SCENE_HOME_WORLD || this.getSceneType() == SceneType.SCENE_HOME_ROOM){
|
if (this.getSceneType() == SceneType.SCENE_HOME_WORLD || this.getSceneType() == SceneType.SCENE_HOME_ROOM) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.getScriptManager().isInit()) {
|
if (this.getScriptManager().isInit()) {
|
||||||
@@ -432,7 +432,7 @@ public class Scene {
|
|||||||
// Triggers
|
// Triggers
|
||||||
this.scriptManager.checkRegions();
|
this.scriptManager.checkRegions();
|
||||||
|
|
||||||
if(challenge != null){
|
if (challenge != null) {
|
||||||
challenge.onCheckTimeOut();
|
challenge.onCheckTimeOut();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -446,7 +446,7 @@ public class Scene {
|
|||||||
|
|
||||||
return level;
|
return level;
|
||||||
}
|
}
|
||||||
public void checkNpcGroup(){
|
public void checkNpcGroup() {
|
||||||
Set<SceneNpcBornEntry> npcBornEntries = ConcurrentHashMap.newKeySet();
|
Set<SceneNpcBornEntry> npcBornEntries = ConcurrentHashMap.newKeySet();
|
||||||
for (Player player : this.getPlayers()) {
|
for (Player player : this.getPlayers()) {
|
||||||
npcBornEntries.addAll(loadNpcForPlayer(player));
|
npcBornEntries.addAll(loadNpcForPlayer(player));
|
||||||
@@ -458,7 +458,7 @@ public class Scene {
|
|||||||
.map(SceneNpcBornEntry::getGroupId)
|
.map(SceneNpcBornEntry::getGroupId)
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
if(toUnload.size() > 0){
|
if (toUnload.size() > 0) {
|
||||||
broadcastPacket(new PacketGroupUnloadNotify(toUnload));
|
broadcastPacket(new PacketGroupUnloadNotify(toUnload));
|
||||||
Grasscutter.getLogger().debug("Unload NPC Group {}", toUnload);
|
Grasscutter.getLogger().debug("Unload NPC Group {}", toUnload);
|
||||||
}
|
}
|
||||||
@@ -480,7 +480,7 @@ public class Scene {
|
|||||||
Set<SpawnDataEntry> visible = new HashSet<>();
|
Set<SpawnDataEntry> visible = new HashSet<>();
|
||||||
for (var block : loadedGridBlocks) {
|
for (var block : loadedGridBlocks) {
|
||||||
var spawns = spawnLists.get(block);
|
var spawns = spawnLists.get(block);
|
||||||
if(spawns!=null) {
|
if (spawns!=null) {
|
||||||
visible.addAll(spawns);
|
visible.addAll(spawns);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -524,7 +524,7 @@ public class Scene {
|
|||||||
gadget.setConfigId(entry.getConfigId());
|
gadget.setConfigId(entry.getConfigId());
|
||||||
gadget.setSpawnEntry(entry);
|
gadget.setSpawnEntry(entry);
|
||||||
int state = entry.getGadgetState();
|
int state = entry.getGadgetState();
|
||||||
if(state>0) {
|
if (state>0) {
|
||||||
gadget.setState(state);
|
gadget.setState(state);
|
||||||
}
|
}
|
||||||
gadget.buildContent();
|
gadget.buildContent();
|
||||||
@@ -562,7 +562,7 @@ public class Scene {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<SceneBlock> getPlayerActiveBlocks(Player player){
|
public List<SceneBlock> getPlayerActiveBlocks(Player player) {
|
||||||
// consider the borders' entities of blocks, so we check if contains by index
|
// consider the borders' entities of blocks, so we check if contains by index
|
||||||
return SceneIndexManager.queryNeighbors(getScriptManager().getBlocksIndex(),
|
return SceneIndexManager.queryNeighbors(getScriptManager().getBlocksIndex(),
|
||||||
player.getPosition().toXZDoubleArray(), Grasscutter.getConfig().server.game.loadEntitiesForPlayerRange);
|
player.getPosition().toXZDoubleArray(), Grasscutter.getConfig().server.game.loadEntitiesForPlayerRange);
|
||||||
@@ -585,11 +585,11 @@ public class Scene {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for(var block : visible){
|
for (var block : visible) {
|
||||||
if (!this.getLoadedBlocks().contains(block)) {
|
if (!this.getLoadedBlocks().contains(block)) {
|
||||||
this.onLoadBlock(block, this.getPlayers());
|
this.onLoadBlock(block, this.getPlayers());
|
||||||
this.getLoadedBlocks().add(block);
|
this.getLoadedBlocks().add(block);
|
||||||
}else{
|
}else {
|
||||||
// dynamic load the groups for players in a loaded block
|
// dynamic load the groups for players in a loaded block
|
||||||
var toLoad = this.getPlayers().stream()
|
var toLoad = this.getPlayers().stream()
|
||||||
.filter(p -> block.contains(p.getPosition()))
|
.filter(p -> block.contains(p.getPosition()))
|
||||||
@@ -601,7 +601,7 @@ public class Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
public List<SceneGroup> playerMeetGroups(Player player, SceneBlock block){
|
public List<SceneGroup> playerMeetGroups(Player player, SceneBlock block) {
|
||||||
List<SceneGroup> sceneGroups = SceneIndexManager.queryNeighbors(block.sceneGroupIndex, player.getPosition().toDoubleArray(),
|
List<SceneGroup> sceneGroups = SceneIndexManager.queryNeighbors(block.sceneGroupIndex, player.getPosition().toDoubleArray(),
|
||||||
Grasscutter.getConfig().server.game.loadEntitiesForPlayerRange);
|
Grasscutter.getConfig().server.game.loadEntitiesForPlayerRange);
|
||||||
|
|
||||||
@@ -631,8 +631,8 @@ public class Scene {
|
|||||||
Grasscutter.getLogger().info("Scene {} Block {} loaded.", this.getId(), block.id);
|
Grasscutter.getLogger().info("Scene {} Block {} loaded.", this.getId(), block.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void onLoadGroup(List<SceneGroup> groups){
|
public void onLoadGroup(List<SceneGroup> groups) {
|
||||||
if(groups == null || groups.isEmpty()){
|
if (groups == null || groups.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (SceneGroup group : groups) {
|
for (SceneGroup group : groups) {
|
||||||
@@ -690,10 +690,10 @@ public class Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (SceneGroup group : block.groups.values()) {
|
for (SceneGroup group : block.groups.values()) {
|
||||||
if(group.triggers != null){
|
if (group.triggers != null) {
|
||||||
group.triggers.values().forEach(getScriptManager()::deregisterTrigger);
|
group.triggers.values().forEach(getScriptManager()::deregisterTrigger);
|
||||||
}
|
}
|
||||||
if(group.regions != null){
|
if (group.regions != null) {
|
||||||
group.regions.values().forEach(getScriptManager()::deregisterRegion);
|
group.regions.values().forEach(getScriptManager()::deregisterRegion);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -763,7 +763,7 @@ public class Scene {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addItemEntity(int itemId, int amount, GameEntity bornForm){
|
public void addItemEntity(int itemId, int amount, GameEntity bornForm) {
|
||||||
ItemData itemData = GameData.getItemDataMap().get(itemId);
|
ItemData itemData = GameData.getItemDataMap().get(itemId);
|
||||||
if (itemData == null) {
|
if (itemData == null) {
|
||||||
return;
|
return;
|
||||||
@@ -780,13 +780,13 @@ public class Scene {
|
|||||||
addEntity(entity);
|
addEntity(entity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public void loadNpcForPlayerEnter(Player player){
|
public void loadNpcForPlayerEnter(Player player) {
|
||||||
this.npcBornEntrySet.addAll(loadNpcForPlayer(player));
|
this.npcBornEntrySet.addAll(loadNpcForPlayer(player));
|
||||||
}
|
}
|
||||||
private List<SceneNpcBornEntry> loadNpcForPlayer(Player player){
|
private List<SceneNpcBornEntry> loadNpcForPlayer(Player player) {
|
||||||
var pos = player.getPosition();
|
var pos = player.getPosition();
|
||||||
var data = GameData.getSceneNpcBornData().get(getId());
|
var data = GameData.getSceneNpcBornData().get(getId());
|
||||||
if(data == null){
|
if (data == null) {
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -797,7 +797,7 @@ public class Scene {
|
|||||||
.filter(i -> !this.npcBornEntrySet.contains(i))
|
.filter(i -> !this.npcBornEntrySet.contains(i))
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
if(sceneNpcBornEntries.size() > 0){
|
if (sceneNpcBornEntries.size() > 0) {
|
||||||
this.broadcastPacket(new PacketGroupSuiteNotify(sceneNpcBornEntries));
|
this.broadcastPacket(new PacketGroupSuiteNotify(sceneNpcBornEntries));
|
||||||
Grasscutter.getLogger().debug("Loaded Npc Group Suite {}", sceneNpcBornEntries);
|
Grasscutter.getLogger().debug("Loaded Npc Group Suite {}", sceneNpcBornEntries);
|
||||||
}
|
}
|
||||||
@@ -805,17 +805,17 @@ public class Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void loadGroupForQuest(List<QuestGroupSuite> sceneGroupSuite) {
|
public void loadGroupForQuest(List<QuestGroupSuite> sceneGroupSuite) {
|
||||||
if(!scriptManager.isInit()){
|
if (!scriptManager.isInit()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
sceneGroupSuite.forEach(i -> {
|
sceneGroupSuite.forEach(i -> {
|
||||||
var group = scriptManager.getGroupById(i.getGroup());
|
var group = scriptManager.getGroupById(i.getGroup());
|
||||||
if(group == null){
|
if (group == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var suite = group.getSuiteByIndex(i.getSuite());
|
var suite = group.getSuiteByIndex(i.getSuite());
|
||||||
if(suite == null){
|
if (suite == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
scriptManager.addGroupSuite(group, suite);
|
scriptManager.addGroupSuite(group, suite);
|
||||||
|
@@ -62,7 +62,7 @@ public class SpawnDataEntry {
|
|||||||
return rot;
|
return rot;
|
||||||
}
|
}
|
||||||
|
|
||||||
public GridBlockId getBlockId(){
|
public GridBlockId getBlockId() {
|
||||||
int scale = GridBlockId.getScale(gadgetId);
|
int scale = GridBlockId.getScale(gadgetId);
|
||||||
return new GridBlockId(group.sceneId,scale,
|
return new GridBlockId(group.sceneId,scale,
|
||||||
(int)(pos.getX() / GameDepot.BLOCK_SIZE[scale]),
|
(int)(pos.getX() / GameDepot.BLOCK_SIZE[scale]),
|
||||||
@@ -133,7 +133,7 @@ public class SpawnDataEntry {
|
|||||||
return Objects.hash(sceneId, scale, x, z);
|
return Objects.hash(sceneId, scale, x, z);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static GridBlockId[] getAdjacentGridBlockIds(int sceneId, Position pos){
|
public static GridBlockId[] getAdjacentGridBlockIds(int sceneId, Position pos) {
|
||||||
GridBlockId[] results = new GridBlockId[5*5*GameDepot.BLOCK_SIZE.length];
|
GridBlockId[] results = new GridBlockId[5*5*GameDepot.BLOCK_SIZE.length];
|
||||||
int t=0;
|
int t=0;
|
||||||
for (int scale = 0; scale < GameDepot.BLOCK_SIZE.length; scale++) {
|
for (int scale = 0; scale < GameDepot.BLOCK_SIZE.length; scale++) {
|
||||||
@@ -148,7 +148,7 @@ public class SpawnDataEntry {
|
|||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int getScale(int gadgetId){
|
public static int getScale(int gadgetId) {
|
||||||
return 0;//you should implement here,this is index of GameDepot.BLOCK_SIZE
|
return 0;//you should implement here,this is index of GameDepot.BLOCK_SIZE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -30,7 +30,7 @@ public class WorldDataSystem extends BaseGameSystem {
|
|||||||
private final Map<String, ChestInteractHandler> chestInteractHandlerMap; // chestType-Handler
|
private final Map<String, ChestInteractHandler> chestInteractHandlerMap; // chestType-Handler
|
||||||
private final Map<String, SceneGroup> sceneInvestigationGroupMap; // <sceneId_groupId, Group>
|
private final Map<String, SceneGroup> sceneInvestigationGroupMap; // <sceneId_groupId, Group>
|
||||||
|
|
||||||
public WorldDataSystem(GameServer server){
|
public WorldDataSystem(GameServer server) {
|
||||||
super(server);
|
super(server);
|
||||||
this.chestInteractHandlerMap = new HashMap<>();
|
this.chestInteractHandlerMap = new HashMap<>();
|
||||||
this.sceneInvestigationGroupMap = new ConcurrentHashMap<>();
|
this.sceneInvestigationGroupMap = new ConcurrentHashMap<>();
|
||||||
@@ -38,11 +38,11 @@ public class WorldDataSystem extends BaseGameSystem {
|
|||||||
loadChestConfig();
|
loadChestConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void loadChestConfig(){
|
public synchronized void loadChestConfig() {
|
||||||
// set the special chest first
|
// set the special chest first
|
||||||
chestInteractHandlerMap.put("SceneObj_Chest_Flora", new BossChestInteractHandler());
|
chestInteractHandlerMap.put("SceneObj_Chest_Flora", new BossChestInteractHandler());
|
||||||
|
|
||||||
try(Reader reader = DataLoader.loadReader("ChestReward.json")) {
|
try (Reader reader = DataLoader.loadReader("ChestReward.json")) {
|
||||||
List<ChestReward> chestReward = Grasscutter.getGsonFactory().fromJson(
|
List<ChestReward> chestReward = Grasscutter.getGsonFactory().fromJson(
|
||||||
reader,
|
reader,
|
||||||
TypeToken.getParameterized(List.class, ChestReward.class).getType());
|
TypeToken.getParameterized(List.class, ChestReward.class).getType());
|
||||||
@@ -60,21 +60,21 @@ public class WorldDataSystem extends BaseGameSystem {
|
|||||||
return chestInteractHandlerMap;
|
return chestInteractHandlerMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
public RewardPreviewData getRewardByBossId(int monsterId){
|
public RewardPreviewData getRewardByBossId(int monsterId) {
|
||||||
var investigationMonsterData = GameData.getInvestigationMonsterDataMap().values().parallelStream()
|
var investigationMonsterData = GameData.getInvestigationMonsterDataMap().values().parallelStream()
|
||||||
.filter(imd -> imd.getMonsterIdList() != null && !imd.getMonsterIdList().isEmpty())
|
.filter(imd -> imd.getMonsterIdList() != null && !imd.getMonsterIdList().isEmpty())
|
||||||
.filter(imd -> imd.getMonsterIdList().get(0) == monsterId)
|
.filter(imd -> imd.getMonsterIdList().get(0) == monsterId)
|
||||||
.findFirst();
|
.findFirst();
|
||||||
|
|
||||||
if(investigationMonsterData.isEmpty()){
|
if (investigationMonsterData.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return GameData.getRewardPreviewDataMap().get(investigationMonsterData.get().getRewardPreviewId());
|
return GameData.getRewardPreviewDataMap().get(investigationMonsterData.get().getRewardPreviewId());
|
||||||
}
|
}
|
||||||
|
|
||||||
private SceneGroup getInvestigationGroup(int sceneId, int groupId){
|
private SceneGroup getInvestigationGroup(int sceneId, int groupId) {
|
||||||
var key = sceneId + "_" + groupId;
|
var key = sceneId + "_" + groupId;
|
||||||
if(!sceneInvestigationGroupMap.containsKey(key)){
|
if (!sceneInvestigationGroupMap.containsKey(key)) {
|
||||||
var group = SceneGroup.of(groupId).load(sceneId);
|
var group = SceneGroup.of(groupId).load(sceneId);
|
||||||
sceneInvestigationGroupMap.putIfAbsent(key, group);
|
sceneInvestigationGroupMap.putIfAbsent(key, group);
|
||||||
return group;
|
return group;
|
||||||
@@ -82,7 +82,7 @@ public class WorldDataSystem extends BaseGameSystem {
|
|||||||
return sceneInvestigationGroupMap.get(key);
|
return sceneInvestigationGroupMap.get(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getMonsterLevel(SceneMonster monster, World world){
|
public int getMonsterLevel(SceneMonster monster, World world) {
|
||||||
// Calculate level
|
// Calculate level
|
||||||
int level = monster.level;
|
int level = monster.level;
|
||||||
WorldLevelData worldLevelData = GameData.getWorldLevelDataMap().get(world.getWorldLevel());
|
WorldLevelData worldLevelData = GameData.getWorldLevelDataMap().get(world.getWorldLevel());
|
||||||
@@ -98,14 +98,14 @@ public class WorldDataSystem extends BaseGameSystem {
|
|||||||
var sceneId = imd.getCityData().getSceneId();
|
var sceneId = imd.getCityData().getSceneId();
|
||||||
var group = getInvestigationGroup(sceneId, groupId);
|
var group = getInvestigationGroup(sceneId, groupId);
|
||||||
|
|
||||||
if(group == null || group.monsters == null){
|
if (group == null || group.monsters == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var monster = group.monsters.values().stream()
|
var monster = group.monsters.values().stream()
|
||||||
.filter(x -> x.monster_id == monsterId)
|
.filter(x -> x.monster_id == monsterId)
|
||||||
.findFirst();
|
.findFirst();
|
||||||
if(monster.isEmpty()){
|
if (monster.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,9 +122,9 @@ public class WorldDataSystem extends BaseGameSystem {
|
|||||||
.setRefreshInterval(Integer.MAX_VALUE)
|
.setRefreshInterval(Integer.MAX_VALUE)
|
||||||
.setPos(monster.get().pos.toProto());
|
.setPos(monster.get().pos.toProto());
|
||||||
|
|
||||||
if("Boss".equals(imd.getMonsterCategory())){
|
if ("Boss".equals(imd.getMonsterCategory())) {
|
||||||
var bossChest = group.searchBossChestInGroup();
|
var bossChest = group.searchBossChestInGroup();
|
||||||
if(bossChest.isPresent()){
|
if (bossChest.isPresent()) {
|
||||||
builder.setResin(bossChest.get().resin);
|
builder.setResin(bossChest.get().resin);
|
||||||
builder.setBossChestNum(bossChest.get().take_num);
|
builder.setBossChestNum(bossChest.get().take_num);
|
||||||
}
|
}
|
||||||
@@ -132,9 +132,9 @@ public class WorldDataSystem extends BaseGameSystem {
|
|||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<InvestigationMonsterOuterClass.InvestigationMonster> getInvestigationMonstersByCityId(Player player, int cityId){
|
public List<InvestigationMonsterOuterClass.InvestigationMonster> getInvestigationMonstersByCityId(Player player, int cityId) {
|
||||||
var cityData = GameData.getCityDataMap().get(cityId);
|
var cityData = GameData.getCityDataMap().get(cityId);
|
||||||
if(cityData == null){
|
if (cityData == null) {
|
||||||
Grasscutter.getLogger().warn("City not exist {}", cityId);
|
Grasscutter.getLogger().warn("City not exist {}", cityId);
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
@@ -37,7 +37,7 @@ public class PacketOpcodesUtils {
|
|||||||
Field[] fields = PacketOpcodes.class.getFields();
|
Field[] fields = PacketOpcodes.class.getFields();
|
||||||
|
|
||||||
for (Field f : fields) {
|
for (Field f : fields) {
|
||||||
if(f.getType().equals(int.class)) {
|
if (f.getType().equals(int.class)) {
|
||||||
try {
|
try {
|
||||||
opcodeMap.put(f.getInt(null), f.getName());
|
opcodeMap.put(f.getInt(null), f.getName());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
@@ -30,7 +30,7 @@ public abstract class Plugin {
|
|||||||
* @param identifier The plugin's identifier.
|
* @param identifier The plugin's identifier.
|
||||||
*/
|
*/
|
||||||
private void initializePlugin(PluginIdentifier identifier, URLClassLoader classLoader) {
|
private void initializePlugin(PluginIdentifier identifier, URLClassLoader classLoader) {
|
||||||
if(this.identifier != null) {
|
if (this.identifier != null) {
|
||||||
Grasscutter.getLogger().warn(this.identifier.name + " had a reinitialization attempt.");
|
Grasscutter.getLogger().warn(this.identifier.name + " had a reinitialization attempt.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,7 @@ public abstract class Plugin {
|
|||||||
this.dataFolder = new File(PLUGIN(), identifier.name);
|
this.dataFolder = new File(PLUGIN(), identifier.name);
|
||||||
this.logger = LoggerFactory.getLogger(identifier.name);
|
this.logger = LoggerFactory.getLogger(identifier.name);
|
||||||
|
|
||||||
if(!this.dataFolder.exists() && !this.dataFolder.mkdirs()) {
|
if (!this.dataFolder.exists() && !this.dataFolder.mkdirs()) {
|
||||||
Grasscutter.getLogger().warn("Failed to create plugin data folder for " + this.identifier.name);
|
Grasscutter.getLogger().warn("Failed to create plugin data folder for " + this.identifier.name);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,7 @@ public abstract class Plugin {
|
|||||||
* The plugin's identifier instance.
|
* The plugin's identifier instance.
|
||||||
* @return An instance of {@link PluginIdentifier}.
|
* @return An instance of {@link PluginIdentifier}.
|
||||||
*/
|
*/
|
||||||
public final PluginIdentifier getIdentifier(){
|
public final PluginIdentifier getIdentifier() {
|
||||||
return this.identifier;
|
return this.identifier;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -72,7 +72,7 @@ public final class PluginManager {
|
|||||||
List<PluginData> dependencies = new ArrayList<>();
|
List<PluginData> dependencies = new ArrayList<>();
|
||||||
|
|
||||||
// Initialize all plugins.
|
// Initialize all plugins.
|
||||||
for(var plugin : plugins) {
|
for (var plugin : plugins) {
|
||||||
try {
|
try {
|
||||||
URL url = plugin.toURI().toURL();
|
URL url = plugin.toURI().toURL();
|
||||||
try (URLClassLoader loader = new URLClassLoader(new URL[]{url})) {
|
try (URLClassLoader loader = new URLClassLoader(new URL[]{url})) {
|
||||||
@@ -109,7 +109,7 @@ public final class PluginManager {
|
|||||||
fileReader.close();
|
fileReader.close();
|
||||||
|
|
||||||
// Check if the plugin has alternate dependencies.
|
// Check if the plugin has alternate dependencies.
|
||||||
if(pluginConfig.loadAfter != null && pluginConfig.loadAfter.length > 0) {
|
if (pluginConfig.loadAfter != null && pluginConfig.loadAfter.length > 0) {
|
||||||
// Add the plugin to a "load later" list.
|
// Add the plugin to a "load later" list.
|
||||||
dependencies.add(new PluginData(
|
dependencies.add(new PluginData(
|
||||||
pluginInstance, PluginIdentifier.fromPluginConfig(pluginConfig),
|
pluginInstance, PluginIdentifier.fromPluginConfig(pluginConfig),
|
||||||
@@ -131,9 +131,9 @@ public final class PluginManager {
|
|||||||
|
|
||||||
// Load plugins with dependencies.
|
// Load plugins with dependencies.
|
||||||
int depth = 0; final int maxDepth = 30;
|
int depth = 0; final int maxDepth = 30;
|
||||||
while(!dependencies.isEmpty()) {
|
while (!dependencies.isEmpty()) {
|
||||||
// Check if the depth is too high.
|
// Check if the depth is too high.
|
||||||
if(depth >= maxDepth) {
|
if (depth >= maxDepth) {
|
||||||
Grasscutter.getLogger().error("Failed to load plugins with dependencies.");
|
Grasscutter.getLogger().error("Failed to load plugins with dependencies.");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -143,7 +143,7 @@ public final class PluginManager {
|
|||||||
var pluginData = dependencies.get(0);
|
var pluginData = dependencies.get(0);
|
||||||
|
|
||||||
// Check if the plugin's dependencies are loaded.
|
// Check if the plugin's dependencies are loaded.
|
||||||
if(!this.plugins.keySet().containsAll(List.of(pluginData.getDependencies()))) {
|
if (!this.plugins.keySet().containsAll(List.of(pluginData.getDependencies()))) {
|
||||||
depth++; // Increase depth counter.
|
depth++; // Increase depth counter.
|
||||||
continue; // Continue to next plugin.
|
continue; // Continue to next plugin.
|
||||||
}
|
}
|
||||||
|
@@ -45,8 +45,8 @@ public class SceneBlock {
|
|||||||
pos.getZ() <= this.max.getZ() && pos.getZ() >= this.min.getZ();
|
pos.getZ() <= this.max.getZ() && pos.getZ() >= this.min.getZ();
|
||||||
}
|
}
|
||||||
|
|
||||||
public SceneBlock load(int sceneId, Bindings bindings){
|
public SceneBlock load(int sceneId, Bindings bindings) {
|
||||||
if(this.loaded){
|
if (this.loaded) {
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
this.sceneId = sceneId;
|
this.sceneId = sceneId;
|
||||||
|
@@ -75,8 +75,8 @@ public class SceneGroup {
|
|||||||
return this.bindings;
|
return this.bindings;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized SceneGroup load(int sceneId){
|
public synchronized SceneGroup load(int sceneId) {
|
||||||
if(this.loaded){
|
if (this.loaded) {
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
// Set flag here so if there is no script, we don't call this function over and over again.
|
// Set flag here so if there is no script, we don't call this function over and over again.
|
||||||
|
@@ -33,7 +33,7 @@ public class SceneMeta {
|
|||||||
return new SceneMeta().load(sceneId);
|
return new SceneMeta().load(sceneId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public SceneMeta load(int sceneId){
|
public SceneMeta load(int sceneId) {
|
||||||
// Get compiled script if cached
|
// Get compiled script if cached
|
||||||
CompiledScript cs = ScriptLoader.getScriptByPath(
|
CompiledScript cs = ScriptLoader.getScriptByPath(
|
||||||
SCRIPT("Scene/" + sceneId + "/scene" + sceneId + "." + ScriptLoader.getScriptType()));
|
SCRIPT("Scene/" + sceneId + "/scene" + sceneId + "." + ScriptLoader.getScriptType()));
|
||||||
|
@@ -150,11 +150,11 @@ public final class GameServer extends KcpServer {
|
|||||||
this.chatManager = chatManager;
|
this.chatManager = chatManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static InetSocketAddress getAdapterInetSocketAddress(){
|
private static InetSocketAddress getAdapterInetSocketAddress() {
|
||||||
InetSocketAddress inetSocketAddress;
|
InetSocketAddress inetSocketAddress;
|
||||||
if(GAME_INFO.bindAddress.equals("")){
|
if (GAME_INFO.bindAddress.equals("")) {
|
||||||
inetSocketAddress=new InetSocketAddress(GAME_INFO.bindPort);
|
inetSocketAddress=new InetSocketAddress(GAME_INFO.bindPort);
|
||||||
}else{
|
}else {
|
||||||
inetSocketAddress=new InetSocketAddress(
|
inetSocketAddress=new InetSocketAddress(
|
||||||
GAME_INFO.bindAddress,
|
GAME_INFO.bindAddress,
|
||||||
GAME_INFO.bindPort
|
GAME_INFO.bindPort
|
||||||
|
@@ -84,7 +84,7 @@ public class GameServerPacketHandler {
|
|||||||
|
|
||||||
// Invoke event.
|
// Invoke event.
|
||||||
ReceivePacketEvent event = new ReceivePacketEvent(session, opcode, payload); event.call();
|
ReceivePacketEvent event = new ReceivePacketEvent(session, opcode, payload); event.call();
|
||||||
if(!event.isCanceled()) // If event is not canceled, continue.
|
if (!event.isCanceled()) // If event is not canceled, continue.
|
||||||
handler.handle(session, header, event.getPacketData());
|
handler.handle(session, header, event.getPacketData());
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
// TODO Remove this when no more needed
|
// TODO Remove this when no more needed
|
||||||
|
@@ -45,9 +45,9 @@ public class GameSession implements GameSessionManager.KcpChannel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public InetSocketAddress getAddress() {
|
public InetSocketAddress getAddress() {
|
||||||
try{
|
try {
|
||||||
return tunnel.getAddress();
|
return tunnel.getAddress();
|
||||||
}catch (Throwable ignore){
|
}catch (Throwable ignore) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -138,7 +138,7 @@ public class GameSession implements GameSessionManager.KcpChannel {
|
|||||||
|
|
||||||
// DO NOT REMOVE (unless we find a way to validate code before sending to client which I don't think we can)
|
// DO NOT REMOVE (unless we find a way to validate code before sending to client which I don't think we can)
|
||||||
// Stop WindSeedClientNotify from being sent for security purposes.
|
// Stop WindSeedClientNotify from being sent for security purposes.
|
||||||
if(PacketOpcodesUtils.BANNED_PACKETS.contains(packet.getOpcode())) {
|
if (PacketOpcodesUtils.BANNED_PACKETS.contains(packet.getOpcode())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,7 +169,7 @@ public class GameSession implements GameSessionManager.KcpChannel {
|
|||||||
|
|
||||||
// Invoke event.
|
// Invoke event.
|
||||||
SendPacketEvent event = new SendPacketEvent(this, packet); event.call();
|
SendPacketEvent event = new SendPacketEvent(this, packet); event.call();
|
||||||
if(!event.isCanceled()) { // If event is not cancelled, continue.
|
if (!event.isCanceled()) { // If event is not cancelled, continue.
|
||||||
tunnel.writeData(event.getPacket().build());
|
tunnel.writeData(event.getPacket().build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -200,7 +200,7 @@ public class GameSession implements GameSessionManager.KcpChannel {
|
|||||||
// Packet sanity check
|
// Packet sanity check
|
||||||
int const1 = packet.readShort();
|
int const1 = packet.readShort();
|
||||||
if (const1 != 17767) {
|
if (const1 != 17767) {
|
||||||
if(allDebug){
|
if (allDebug) {
|
||||||
Grasscutter.getLogger().error("Bad Data Package Received: got {} ,expect 17767",const1);
|
Grasscutter.getLogger().error("Bad Data Package Received: got {} ,expect 17767",const1);
|
||||||
}
|
}
|
||||||
return; // Bad packet
|
return; // Bad packet
|
||||||
@@ -217,7 +217,7 @@ public class GameSession implements GameSessionManager.KcpChannel {
|
|||||||
// Sanity check #2
|
// Sanity check #2
|
||||||
int const2 = packet.readShort();
|
int const2 = packet.readShort();
|
||||||
if (const2 != -30293) {
|
if (const2 != -30293) {
|
||||||
if(allDebug){
|
if (allDebug) {
|
||||||
Grasscutter.getLogger().error("Bad Data Package Received: got {} ,expect -30293",const2);
|
Grasscutter.getLogger().error("Bad Data Package Received: got {} ,expect -30293",const2);
|
||||||
}
|
}
|
||||||
return; // Bad packet
|
return; // Bad packet
|
||||||
@@ -267,7 +267,7 @@ public class GameSession implements GameSessionManager.KcpChannel {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
send(new BasePacket(PacketOpcodes.ServerDisconnectClientNotify));
|
send(new BasePacket(PacketOpcodes.ServerDisconnectClientNotify));
|
||||||
}catch (Throwable ignore){
|
}catch (Throwable ignore) {
|
||||||
Grasscutter.getLogger().warn("closing {} error",getAddress().getAddress().getHostAddress());
|
Grasscutter.getLogger().warn("closing {} error",getAddress().getAddress().getHostAddress());
|
||||||
}
|
}
|
||||||
tunnel = null;
|
tunnel = null;
|
||||||
|
@@ -35,7 +35,7 @@ public final class HttpServer {
|
|||||||
config.enforceSsl = HTTP_ENCRYPTION.useEncryption;
|
config.enforceSsl = HTTP_ENCRYPTION.useEncryption;
|
||||||
|
|
||||||
// Configure HTTP policies.
|
// Configure HTTP policies.
|
||||||
if(HTTP_POLICIES.cors.enabled) {
|
if (HTTP_POLICIES.cors.enabled) {
|
||||||
var allowedOrigins = HTTP_POLICIES.cors.allowedOrigins;
|
var allowedOrigins = HTTP_POLICIES.cors.allowedOrigins;
|
||||||
if (allowedOrigins.length > 0)
|
if (allowedOrigins.length > 0)
|
||||||
config.enableCorsForOrigin(allowedOrigins);
|
config.enableCorsForOrigin(allowedOrigins);
|
||||||
@@ -43,7 +43,7 @@ public final class HttpServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Configure debug logging.
|
// Configure debug logging.
|
||||||
if(DISPATCH_INFO.logRequests == ServerDebugMode.ALL)
|
if (DISPATCH_INFO.logRequests == ServerDebugMode.ALL)
|
||||||
config.enableDevLogging();
|
config.enableDevLogging();
|
||||||
|
|
||||||
// Disable compression on static files.
|
// Disable compression on static files.
|
||||||
@@ -61,11 +61,11 @@ public final class HttpServer {
|
|||||||
ServerConnector serverConnector
|
ServerConnector serverConnector
|
||||||
= new ServerConnector(server);
|
= new ServerConnector(server);
|
||||||
|
|
||||||
if(HTTP_ENCRYPTION.useEncryption) {
|
if (HTTP_ENCRYPTION.useEncryption) {
|
||||||
var sslContextFactory = new SslContextFactory.Server();
|
var sslContextFactory = new SslContextFactory.Server();
|
||||||
var keystoreFile = new File(HTTP_ENCRYPTION.keystore);
|
var keystoreFile = new File(HTTP_ENCRYPTION.keystore);
|
||||||
|
|
||||||
if(!keystoreFile.exists()) {
|
if (!keystoreFile.exists()) {
|
||||||
HTTP_ENCRYPTION.useEncryption = false;
|
HTTP_ENCRYPTION.useEncryption = false;
|
||||||
HTTP_ENCRYPTION.useInRouting = false;
|
HTTP_ENCRYPTION.useInRouting = false;
|
||||||
|
|
||||||
@@ -112,7 +112,7 @@ public final class HttpServer {
|
|||||||
public HttpServer addRouter(Class<? extends Router> router, Object... args) {
|
public HttpServer addRouter(Class<? extends Router> router, Object... args) {
|
||||||
// Get all constructor parameters.
|
// Get all constructor parameters.
|
||||||
Class<?>[] types = new Class<?>[args.length];
|
Class<?>[] types = new Class<?>[args.length];
|
||||||
for(var argument : args)
|
for (var argument : args)
|
||||||
types[args.length - 1] = argument.getClass();
|
types[args.length - 1] = argument.getClass();
|
||||||
|
|
||||||
try { // Create a router instance & apply routes.
|
try { // Create a router instance & apply routes.
|
||||||
@@ -130,9 +130,9 @@ public final class HttpServer {
|
|||||||
*/
|
*/
|
||||||
public void start() throws UnsupportedEncodingException {
|
public void start() throws UnsupportedEncodingException {
|
||||||
// Attempt to start the HTTP server.
|
// Attempt to start the HTTP server.
|
||||||
if(HTTP_INFO.bindAddress.equals("")){
|
if (HTTP_INFO.bindAddress.equals("")) {
|
||||||
this.express.listen(HTTP_INFO.bindPort);
|
this.express.listen(HTTP_INFO.bindPort);
|
||||||
}else{
|
}else {
|
||||||
this.express.listen(HTTP_INFO.bindAddress, HTTP_INFO.bindPort);
|
this.express.listen(HTTP_INFO.bindAddress, HTTP_INFO.bindPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,7 +147,7 @@ public final class HttpServer {
|
|||||||
@Override public void applyRoutes(Express express, Javalin handle) {
|
@Override public void applyRoutes(Express express, Javalin handle) {
|
||||||
express.get("/", (request, response) -> {
|
express.get("/", (request, response) -> {
|
||||||
File file = new File(HTTP_STATIC_FILES.indexFile);
|
File file = new File(HTTP_STATIC_FILES.indexFile);
|
||||||
if(!file.exists())
|
if (!file.exists())
|
||||||
response.send("""
|
response.send("""
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
@@ -173,12 +173,12 @@ public final class HttpServer {
|
|||||||
public static class UnhandledRequestRouter implements Router {
|
public static class UnhandledRequestRouter implements Router {
|
||||||
@Override public void applyRoutes(Express express, Javalin handle) {
|
@Override public void applyRoutes(Express express, Javalin handle) {
|
||||||
handle.error(404, context -> {
|
handle.error(404, context -> {
|
||||||
if(DISPATCH_INFO.logRequests == ServerDebugMode.MISSING)
|
if (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING)
|
||||||
Grasscutter.getLogger().info(translate("messages.dispatch.unhandled_request_error", context.method(), context.url()));
|
Grasscutter.getLogger().info(translate("messages.dispatch.unhandled_request_error", context.method(), context.url()));
|
||||||
context.contentType("text/html");
|
context.contentType("text/html");
|
||||||
|
|
||||||
File file = new File(HTTP_STATIC_FILES.errorFile);
|
File file = new File(HTTP_STATIC_FILES.errorFile);
|
||||||
if(!file.exists())
|
if (!file.exists())
|
||||||
context.result("""
|
context.result("""
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
|
@@ -60,7 +60,7 @@ public final class RegionHandler implements Router {
|
|||||||
List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts.
|
List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts.
|
||||||
|
|
||||||
var configuredRegions = new ArrayList<>(List.of(DISPATCH_INFO.regions));
|
var configuredRegions = new ArrayList<>(List.of(DISPATCH_INFO.regions));
|
||||||
if(SERVER.runMode != ServerRunMode.HYBRID && configuredRegions.size() == 0) {
|
if (SERVER.runMode != ServerRunMode.HYBRID && configuredRegions.size() == 0) {
|
||||||
Grasscutter.getLogger().error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
|
Grasscutter.getLogger().error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
} else if (configuredRegions.size() == 0)
|
} else if (configuredRegions.size() == 0)
|
||||||
@@ -136,11 +136,11 @@ public final class RegionHandler implements Router {
|
|||||||
// Get region data.
|
// Get region data.
|
||||||
String regionData = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
|
String regionData = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
|
||||||
if (request.query().values().size() > 0) {
|
if (request.query().values().size() > 0) {
|
||||||
if(region != null)
|
if (region != null)
|
||||||
regionData = region.getBase64();
|
regionData = region.getBase64();
|
||||||
}
|
}
|
||||||
|
|
||||||
if( versionName.contains("2.7.5") || versionName.contains("2.8.")) {
|
if ( versionName.contains("2.7.5") || versionName.contains("2.8.")) {
|
||||||
try {
|
try {
|
||||||
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(regionData); event.call();
|
QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(regionData); event.call();
|
||||||
|
|
||||||
|
@@ -46,7 +46,7 @@ public final class AnnouncementsHandler implements Router {
|
|||||||
try {
|
try {
|
||||||
data = FileUtils.readToString(DataLoader.load("GameAnnouncement.json"));
|
data = FileUtils.readToString(DataLoader.load("GameAnnouncement.json"));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if(e.getClass() == IOException.class) {
|
if (e.getClass() == IOException.class) {
|
||||||
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,7 @@ public final class AnnouncementsHandler implements Router {
|
|||||||
try {
|
try {
|
||||||
data = FileUtils.readToString(DataLoader.load("GameAnnouncementList.json"));
|
data = FileUtils.readToString(DataLoader.load("GameAnnouncementList.json"));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if(e.getClass() == IOException.class) {
|
if (e.getClass() == IOException.class) {
|
||||||
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
Grasscutter.getLogger().info("Unable to read file 'GameAnnouncementList.json'. \n" + e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,7 +78,7 @@ public final class AnnouncementsHandler implements Router {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void getPageResources(Request request, Response response) {
|
private static void getPageResources(Request request, Response response) {
|
||||||
try(InputStream filestream = DataLoader.load(request.path())) {
|
try (InputStream filestream = DataLoader.load(request.path())) {
|
||||||
String possibleFilename = Utils.toFilePath(DATA(request.path()));
|
String possibleFilename = Utils.toFilePath(DATA(request.path()));
|
||||||
|
|
||||||
MediaType fromExtension = MediaType.getByExtension(possibleFilename.substring(possibleFilename.lastIndexOf(".") + 1));
|
MediaType fromExtension = MediaType.getByExtension(possibleFilename.substring(possibleFilename.lastIndexOf(".") + 1));
|
||||||
|
@@ -48,7 +48,7 @@ public final class GachaHandler implements Router {
|
|||||||
|
|
||||||
String sessionKey = request.query("s");
|
String sessionKey = request.query("s");
|
||||||
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
||||||
if(account == null) {
|
if (account == null) {
|
||||||
response.status(403).send("Requested account was not found");
|
response.status(403).send("Requested account was not found");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -59,9 +59,9 @@ public final class GachaHandler implements Router {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int page = 0, gachaType = 0;
|
int page = 0, gachaType = 0;
|
||||||
if(request.query("p") != null)
|
if (request.query("p") != null)
|
||||||
page = Integer.parseInt(request.query("p"));
|
page = Integer.parseInt(request.query("p"));
|
||||||
if(request.query("gachaType") != null)
|
if (request.query("gachaType") != null)
|
||||||
gachaType = Integer.parseInt(request.query("gachaType"));
|
gachaType = Integer.parseInt(request.query("gachaType"));
|
||||||
|
|
||||||
String records = DatabaseHelper.getGachaRecords(player.getUid(), page, gachaType).toString();
|
String records = DatabaseHelper.getGachaRecords(player.getUid(), page, gachaType).toString();
|
||||||
@@ -87,7 +87,7 @@ public final class GachaHandler implements Router {
|
|||||||
|
|
||||||
String sessionKey = request.query("s");
|
String sessionKey = request.query("s");
|
||||||
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
Account account = DatabaseHelper.getAccountBySessionKey(sessionKey);
|
||||||
if(account == null) {
|
if (account == null) {
|
||||||
response.status(403).send("Requested account was not found");
|
response.status(403).send("Requested account was not found");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@@ -35,7 +35,7 @@ public final class HttpJsonResponse implements HttpContextHandler {
|
|||||||
@Override
|
@Override
|
||||||
public void handle(Request req, Response res) throws IOException {
|
public void handle(Request req, Response res) throws IOException {
|
||||||
// Checking for ALL here isn't required as when ALL is enabled enableDevLogging() gets enabled
|
// Checking for ALL here isn't required as when ALL is enabled enableDevLogging() gets enabled
|
||||||
if(DISPATCH_INFO.logRequests == ServerDebugMode.MISSING && Arrays.stream(missingRoutes).anyMatch(x -> Objects.equals(x, req.baseUrl()))) {
|
if (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING && Arrays.stream(missingRoutes).anyMatch(x -> Objects.equals(x, req.baseUrl()))) {
|
||||||
Grasscutter.getLogger().info(translate("messages.dispatch.request", req.ip(), req.method(), req.baseUrl()) + (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING ? "(MISSING)" : ""));
|
Grasscutter.getLogger().info(translate("messages.dispatch.request", req.ip(), req.method(), req.baseUrl()) + (DISPATCH_INFO.logRequests == ServerDebugMode.MISSING ? "(MISSING)" : ""));
|
||||||
}
|
}
|
||||||
res.send(response);
|
res.send(response);
|
||||||
|
@@ -27,13 +27,13 @@ public class WebStaticVersionResponse implements HttpContextHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void getPageResources(String path, Response response) {
|
private static void getPageResources(String path, Response response) {
|
||||||
try(InputStream filestream = FileUtils.readResourceAsStream(path)) {
|
try (InputStream filestream = FileUtils.readResourceAsStream(path)) {
|
||||||
|
|
||||||
MediaType fromExtension = MediaType.getByExtension(path.substring(path.lastIndexOf(".") + 1));
|
MediaType fromExtension = MediaType.getByExtension(path.substring(path.lastIndexOf(".") + 1));
|
||||||
response.type((fromExtension != null) ? fromExtension.getMIME() : "application/octet-stream");
|
response.type((fromExtension != null) ? fromExtension.getMIME() : "application/octet-stream");
|
||||||
response.send(filestream.readAllBytes());
|
response.send(filestream.readAllBytes());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if(DISPATCH_INFO.logRequests == Grasscutter.ServerDebugMode.MISSING) {
|
if (DISPATCH_INFO.logRequests == Grasscutter.ServerDebugMode.MISSING) {
|
||||||
Grasscutter.getLogger().warn("Webstatic File Missing: " + path);
|
Grasscutter.getLogger().warn("Webstatic File Missing: " + path);
|
||||||
}
|
}
|
||||||
response.status(404);
|
response.status(404);
|
||||||
|
@@ -36,11 +36,11 @@ public class HandlerAvatarExpeditionGetRewardReq extends PacketHandler {
|
|||||||
|
|
||||||
if (session.getServer().getExpeditionSystem().getExpeditionRewardDataList().containsKey(expInfo.getExpId())) {
|
if (session.getServer().getExpeditionSystem().getExpeditionRewardDataList().containsKey(expInfo.getExpId())) {
|
||||||
for (ExpeditionRewardDataList RewardDataList : session.getServer().getExpeditionSystem().getExpeditionRewardDataList().get(expInfo.getExpId())) {
|
for (ExpeditionRewardDataList RewardDataList : session.getServer().getExpeditionSystem().getExpeditionRewardDataList().get(expInfo.getExpId())) {
|
||||||
if(RewardDataList.getHourTime() == expInfo.getHourTime()){
|
if (RewardDataList.getHourTime() == expInfo.getHourTime()) {
|
||||||
if(!RewardDataList.getExpeditionRewardData().isEmpty()){
|
if (!RewardDataList.getExpeditionRewardData().isEmpty()) {
|
||||||
for (ExpeditionRewardData RewardData :RewardDataList.getExpeditionRewardData()) {
|
for (ExpeditionRewardData RewardData :RewardDataList.getExpeditionRewardData()) {
|
||||||
int num = RewardData.getMinCount();
|
int num = RewardData.getMinCount();
|
||||||
if(RewardData.getMinCount() != RewardData.getMaxCount()){
|
if (RewardData.getMinCount() != RewardData.getMaxCount()) {
|
||||||
num = Utils.randomRange(RewardData.getMinCount(), RewardData.getMaxCount());
|
num = Utils.randomRange(RewardData.getMinCount(), RewardData.getMaxCount());
|
||||||
}
|
}
|
||||||
items.add(new GameItem(RewardData.getItemId(), num));
|
items.add(new GameItem(RewardData.getItemId(), num));
|
||||||
|
@@ -24,7 +24,7 @@ public class HandlerCombineReq extends PacketHandler {
|
|||||||
var result = session.getServer().getCombineSystem()
|
var result = session.getServer().getCombineSystem()
|
||||||
.combineItem(session.getPlayer(), req.getCombineId(), req.getCombineCount());
|
.combineItem(session.getPlayer(), req.getCombineId(), req.getCombineCount());
|
||||||
|
|
||||||
if(result == null){
|
if (result == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ public class HandlerCombineReq extends PacketHandler {
|
|||||||
toItemParamList(result.getBack())));
|
toItemParamList(result.getBack())));
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<ItemParamOuterClass.ItemParam> toItemParamList(List<ItemParamData> list){
|
private List<ItemParamOuterClass.ItemParam> toItemParamList(List<ItemParamData> list) {
|
||||||
return list.stream()
|
return list.stream()
|
||||||
.map(item -> ItemParamOuterClass.ItemParam.newBuilder()
|
.map(item -> ItemParamOuterClass.ItemParam.newBuilder()
|
||||||
.setItemId(item.getId())
|
.setItemId(item.getId())
|
||||||
|
@@ -58,7 +58,7 @@ public class HandlerGetPlayerTokenReq extends PacketHandler {
|
|||||||
//NOTE: If there are 5 online players, max count of player is 5,
|
//NOTE: If there are 5 online players, max count of player is 5,
|
||||||
// a new client want to login by kicking one of them ,
|
// a new client want to login by kicking one of them ,
|
||||||
// I think it should be allowed
|
// I think it should be allowed
|
||||||
if(!kicked) {
|
if (!kicked) {
|
||||||
// Max players limit
|
// Max players limit
|
||||||
if (ACCOUNT.maxPlayer > -1 && Grasscutter.getGameServer().getPlayers().size() >= ACCOUNT.maxPlayer) {
|
if (ACCOUNT.maxPlayer > -1 && Grasscutter.getGameServer().getPlayers().size() >= ACCOUNT.maxPlayer) {
|
||||||
session.close();
|
session.close();
|
||||||
|
@@ -19,7 +19,7 @@ public class HandlerUnionCmdNotify extends PacketHandler {
|
|||||||
for (UnionCmd cmd : req.getCmdListList()) {
|
for (UnionCmd cmd : req.getCmdListList()) {
|
||||||
int cmdOpcode = cmd.getMessageId();
|
int cmdOpcode = cmd.getMessageId();
|
||||||
byte[] cmdPayload = cmd.getBody().toByteArray();
|
byte[] cmdPayload = cmd.getBody().toByteArray();
|
||||||
if(GAME_INFO.logPackets == ServerDebugMode.WHITELIST && SERVER.debugWhitelist.contains(cmd.getMessageId())) {
|
if (GAME_INFO.logPackets == ServerDebugMode.WHITELIST && SERVER.debugWhitelist.contains(cmd.getMessageId())) {
|
||||||
session.logPacket("RECV in Union", cmdOpcode, cmdPayload);
|
session.logPacket("RECV in Union", cmdOpcode, cmdPayload);
|
||||||
} else if (GAME_INFO.logPackets == ServerDebugMode.BLACKLIST && !SERVER.debugBlacklist.contains(cmd.getMessageId())) {
|
} else if (GAME_INFO.logPackets == ServerDebugMode.BLACKLIST && !SERVER.debugBlacklist.contains(cmd.getMessageId())) {
|
||||||
session.logPacket("RECV in Union", cmdOpcode, cmdPayload);
|
session.logPacket("RECV in Union", cmdOpcode, cmdPayload);
|
||||||
|
@@ -32,9 +32,9 @@ public class PacketGetAllMailRsp extends BasePacket {
|
|||||||
List<MailData> mailDataList = new ArrayList<MailData>();
|
List<MailData> mailDataList = new ArrayList<MailData>();
|
||||||
|
|
||||||
for (Mail message : player.getAllMail()) {
|
for (Mail message : player.getAllMail()) {
|
||||||
if(message.stateValue == 1) { // Make sure it isn't a gift
|
if (message.stateValue == 1) { // Make sure it isn't a gift
|
||||||
if (message.expireTime > (int) Instant.now().getEpochSecond()) { // Make sure the message isn't expired (The game won't show expired mail, but I don't want to send unnecessary information).
|
if (message.expireTime > (int) Instant.now().getEpochSecond()) { // Make sure the message isn't expired (The game won't show expired mail, but I don't want to send unnecessary information).
|
||||||
if(mailDataList.size() <= 1000) { // Make sure that there isn't over 1000 messages in the mailbox. (idk what will happen if there is but the game probably won't like it.)
|
if (mailDataList.size() <= 1000) { // Make sure that there isn't over 1000 messages in the mailbox. (idk what will happen if there is but the game probably won't like it.)
|
||||||
MailTextContent.Builder mailTextContent = MailTextContent.newBuilder();
|
MailTextContent.Builder mailTextContent = MailTextContent.newBuilder();
|
||||||
mailTextContent.setTitle(message.mailContent.title);
|
mailTextContent.setTitle(message.mailContent.title);
|
||||||
mailTextContent.setContent(message.mailContent.content);
|
mailTextContent.setContent(message.mailContent.content);
|
||||||
|
@@ -14,7 +14,7 @@ import java.util.List;
|
|||||||
public class PacketMailChangeNotify extends BasePacket {
|
public class PacketMailChangeNotify extends BasePacket {
|
||||||
|
|
||||||
public PacketMailChangeNotify(Player player, Mail message) {
|
public PacketMailChangeNotify(Player player, Mail message) {
|
||||||
this (player, new ArrayList<Mail>(){{add(message);}});
|
this (player, new ArrayList<Mail>() {{add(message);}});
|
||||||
}
|
}
|
||||||
|
|
||||||
public PacketMailChangeNotify(Player player, List<Mail> mailList) {
|
public PacketMailChangeNotify(Player player, List<Mail> mailList) {
|
||||||
@@ -60,7 +60,7 @@ public class PacketMailChangeNotify extends BasePacket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(delMailIdList != null) {
|
if (delMailIdList != null) {
|
||||||
proto.addAllDelMailIdList(delMailIdList);
|
proto.addAllDelMailIdList(delMailIdList);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -61,7 +61,7 @@ public class PacketPlayerEnterSceneNotify extends BasePacket {
|
|||||||
.setWorldType(1)
|
.setWorldType(1)
|
||||||
.setSceneTransaction(newScene + "-" + target.getUid() + "-" + (int) (System.currentTimeMillis() / 1000) + "-" + 18402);
|
.setSceneTransaction(newScene + "-" + target.getUid() + "-" + (int) (System.currentTimeMillis() / 1000) + "-" + 18402);
|
||||||
|
|
||||||
for(int i = 0; i < 3000; i++) {
|
for (int i = 0; i < 3000; i++) {
|
||||||
proto.addSceneTagIdList(i);
|
proto.addSceneTagIdList(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -61,7 +61,7 @@ public class PacketPlayerWorldSceneInfoListNotify extends BasePacket {
|
|||||||
.setSceneId(9)
|
.setSceneId(9)
|
||||||
.setIsLocked(false);
|
.setIsLocked(false);
|
||||||
|
|
||||||
for(int i = 0; i < 3000; i++) {
|
for (int i = 0; i < 3000; i++) {
|
||||||
gaa.addSceneTagIdList(i);
|
gaa.addSceneTagIdList(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -51,7 +51,7 @@ public class PacketTowerAllDataRsp extends BasePacket {
|
|||||||
this.setData(proto);
|
this.setData(proto);
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<TowerLevelRecordOuterClass.TowerLevelRecord> buildFromPassedLevelMap(Map<Integer, Integer> map){
|
private List<TowerLevelRecordOuterClass.TowerLevelRecord> buildFromPassedLevelMap(Map<Integer, Integer> map) {
|
||||||
return map.entrySet().stream()
|
return map.entrySet().stream()
|
||||||
.map(item -> TowerLevelRecordOuterClass.TowerLevelRecord.newBuilder()
|
.map(item -> TowerLevelRecordOuterClass.TowerLevelRecord.newBuilder()
|
||||||
.setLevelId(item.getKey())
|
.setLevelId(item.getKey())
|
||||||
|
@@ -60,7 +60,7 @@ public final class Tools {
|
|||||||
StringBuilder groupedLangList = new StringBuilder(">\t"); String input;
|
StringBuilder groupedLangList = new StringBuilder(">\t"); String input;
|
||||||
int groupedLangCount = 0;
|
int groupedLangCount = 0;
|
||||||
|
|
||||||
for (String availableLanguage: availableLangList){
|
for (String availableLanguage: availableLangList) {
|
||||||
groupedLangCount++;
|
groupedLangCount++;
|
||||||
groupedLangList.append(availableLanguage).append("\t");
|
groupedLangList.append(availableLanguage).append("\t");
|
||||||
|
|
||||||
@@ -237,7 +237,7 @@ final class ToolsWithLanguageOption {
|
|||||||
}
|
}
|
||||||
String color;
|
String color;
|
||||||
|
|
||||||
switch (data.getRankLevel()){
|
switch (data.getRankLevel()) {
|
||||||
case 3:
|
case 3:
|
||||||
color = "blue";
|
color = "blue";
|
||||||
break;
|
break;
|
||||||
|
@@ -131,7 +131,7 @@ public final class Language {
|
|||||||
file = Grasscutter.class.getResourceAsStream("/languages/" + fallback);
|
file = Grasscutter.class.getResourceAsStream("/languages/" + fallback);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(file == null) { // Fallback the fallback language.
|
if (file == null) { // Fallback the fallback language.
|
||||||
Grasscutter.getLogger().warn("Failed to load language file: " + fallback + ", falling back to: en-US.json");
|
Grasscutter.getLogger().warn("Failed to load language file: " + fallback + ", falling back to: en-US.json");
|
||||||
actualLanguageCode = "en-US";
|
actualLanguageCode = "en-US";
|
||||||
if (cachedLanguages.containsKey(actualLanguageCode)) {
|
if (cachedLanguages.containsKey(actualLanguageCode)) {
|
||||||
@@ -141,7 +141,7 @@ public final class Language {
|
|||||||
file = Grasscutter.class.getResourceAsStream("/languages/en-US.json");
|
file = Grasscutter.class.getResourceAsStream("/languages/en-US.json");
|
||||||
}
|
}
|
||||||
|
|
||||||
if(file == null)
|
if (file == null)
|
||||||
throw new RuntimeException("Unable to load the primary, fallback, and 'en-US' language files.");
|
throw new RuntimeException("Unable to load the primary, fallback, and 'en-US' language files.");
|
||||||
|
|
||||||
return new LanguageStreamDescription(actualLanguageCode, file);
|
return new LanguageStreamDescription(actualLanguageCode, file);
|
||||||
@@ -153,7 +153,7 @@ public final class Language {
|
|||||||
* @return The value (as a string) from a nested key.
|
* @return The value (as a string) from a nested key.
|
||||||
*/
|
*/
|
||||||
public String get(String key) {
|
public String get(String key) {
|
||||||
if(this.cachedTranslations.containsKey(key)) {
|
if (this.cachedTranslations.containsKey(key)) {
|
||||||
return this.cachedTranslations.get(key);
|
return this.cachedTranslations.get(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,12 +166,12 @@ public final class Language {
|
|||||||
boolean isValueFound = false;
|
boolean isValueFound = false;
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
if(index == keys.length) break;
|
if (index == keys.length) break;
|
||||||
|
|
||||||
String currentKey = keys[index++];
|
String currentKey = keys[index++];
|
||||||
if(object.has(currentKey)) {
|
if (object.has(currentKey)) {
|
||||||
JsonElement element = object.get(currentKey);
|
JsonElement element = object.get(currentKey);
|
||||||
if(element.isJsonObject())
|
if (element.isJsonObject())
|
||||||
object = element.getAsJsonObject();
|
object = element.getAsJsonObject();
|
||||||
else {
|
else {
|
||||||
isValueFound = true;
|
isValueFound = true;
|
||||||
|
@@ -140,7 +140,7 @@ public final class Utils {
|
|||||||
*/
|
*/
|
||||||
public static boolean copyFromResources(String resource, String destination) {
|
public static boolean copyFromResources(String resource, String destination) {
|
||||||
try (InputStream stream = Grasscutter.class.getResourceAsStream(resource)) {
|
try (InputStream stream = Grasscutter.class.getResourceAsStream(resource)) {
|
||||||
if(stream == null) {
|
if (stream == null) {
|
||||||
Grasscutter.getLogger().warn("Could not find resource: " + resource);
|
Grasscutter.getLogger().warn("Could not find resource: " + resource);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -174,27 +174,27 @@ public final class Utils {
|
|||||||
String dataFolder = config.folderStructure.data;
|
String dataFolder = config.folderStructure.data;
|
||||||
|
|
||||||
// Check for resources folder.
|
// Check for resources folder.
|
||||||
if(!fileExists(resourcesFolder)) {
|
if (!fileExists(resourcesFolder)) {
|
||||||
logger.info(translate("messages.status.create_resources"));
|
logger.info(translate("messages.status.create_resources"));
|
||||||
logger.info(translate("messages.status.resources_error"));
|
logger.info(translate("messages.status.resources_error"));
|
||||||
createFolder(resourcesFolder); exit = true;
|
createFolder(resourcesFolder); exit = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for BinOutput + ExcelBinOutput.
|
// Check for BinOutput + ExcelBinOutput.
|
||||||
if(!fileExists(resourcesFolder + "BinOutput") ||
|
if (!fileExists(resourcesFolder + "BinOutput") ||
|
||||||
!fileExists(resourcesFolder + "ExcelBinOutput")) {
|
!fileExists(resourcesFolder + "ExcelBinOutput")) {
|
||||||
logger.info(translate("messages.status.resources_error"));
|
logger.info(translate("messages.status.resources_error"));
|
||||||
exit = true;
|
exit = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for game data.
|
// Check for game data.
|
||||||
if(!fileExists(dataFolder))
|
if (!fileExists(dataFolder))
|
||||||
createFolder(dataFolder);
|
createFolder(dataFolder);
|
||||||
|
|
||||||
// Make sure the data folder is populated, if there are any missing files copy them from resources
|
// Make sure the data folder is populated, if there are any missing files copy them from resources
|
||||||
DataLoader.checkAllFiles();
|
DataLoader.checkAllFiles();
|
||||||
|
|
||||||
if(exit) System.exit(1);
|
if (exit) System.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -203,7 +203,7 @@ public final class Utils {
|
|||||||
*/
|
*/
|
||||||
public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
|
public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
|
||||||
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
|
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) {
|
if (zonedDateTime.getHour() < hour) {
|
||||||
zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
|
zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
|
||||||
} else {
|
} else {
|
||||||
@@ -251,7 +251,7 @@ public final class Utils {
|
|||||||
* @return The string.
|
* @return The string.
|
||||||
*/
|
*/
|
||||||
public static String readFromInputStream(@Nullable InputStream stream) {
|
public static String readFromInputStream(@Nullable InputStream stream) {
|
||||||
if(stream == null) return "empty";
|
if (stream == null) return "empty";
|
||||||
|
|
||||||
StringBuilder stringBuilder = new StringBuilder();
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
|
||||||
@@ -273,7 +273,7 @@ public final class Utils {
|
|||||||
*/
|
*/
|
||||||
public static int lerp(int x, int[][] xyArray) {
|
public static int lerp(int x, int[][] xyArray) {
|
||||||
try {
|
try {
|
||||||
if (x <= xyArray[0][0]){ // Clamp to first point
|
if (x <= xyArray[0][0]) { // Clamp to first point
|
||||||
return xyArray[0][1];
|
return xyArray[0][1];
|
||||||
} else if (x >= xyArray[xyArray.length-1][0]) { // Clamp to last point
|
} else if (x >= xyArray[xyArray.length-1][0]) { // Clamp to last point
|
||||||
return xyArray[xyArray.length-1][1];
|
return xyArray[xyArray.length-1][1];
|
||||||
|
Reference in New Issue
Block a user