Continue merging quests (pt. 2)

This commit is contained in:
KingRainbow44 2023-04-09 14:35:45 -04:00
parent 97ee71bcf4
commit 644f1b3ab9
No known key found for this signature in database
GPG Key ID: FC2CB64B00D257BE
31 changed files with 4392 additions and 3984 deletions

View File

@ -1,57 +1,59 @@
package emu.grasscutter.command;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
public class CommandHelpers {
public static final Pattern lvlRegex =
Pattern.compile("(?<!\\w)l(?:vl?)?(\\d+)"); // Java doesn't have raw string literals :(
public static final Pattern amountRegex =
Pattern.compile("((?<=(?<!\\w)x)\\d+|\\d+(?=x)(?!x\\d))");
public static final Pattern refineRegex = Pattern.compile("(?<!\\w)r(\\d+)");
public static final Pattern rankRegex = Pattern.compile("(\\d+)\\*");
public static final Pattern constellationRegex = Pattern.compile("(?<!\\w)c(\\d+)");
public static final Pattern skillLevelRegex = Pattern.compile("sl(\\d+)");
public static final Pattern stateRegex = Pattern.compile("state(\\d+)");
public static final Pattern blockRegex = Pattern.compile("blk(\\d+)");
public static final Pattern groupRegex = Pattern.compile("grp(\\d+)");
public static final Pattern configRegex = Pattern.compile("cfg(\\d+)");
public static final Pattern hpRegex = Pattern.compile("(?<!\\w)hp(\\d+)");
public static final Pattern maxHPRegex = Pattern.compile("maxhp(\\d+)");
public static final Pattern atkRegex = Pattern.compile("atk(\\d+)");
public static final Pattern defRegex = Pattern.compile("def(\\d+)");
public static final Pattern aiRegex = Pattern.compile("ai(\\d+)");
public static int matchIntOrNeg(Pattern pattern, String arg) {
Matcher match = pattern.matcher(arg);
if (match.find()) {
return Integer.parseInt(
match.group(
1)); // This should be exception-safe as only \d+ can be passed to it (i.e. non-empty
// string of pure digits)
}
return -1;
}
public static <T> List<String> parseIntParameters(
List<String> args, @Nonnull T params, Map<Pattern, BiConsumer<T, Integer>> map) {
args.removeIf(
arg -> {
var argL = arg.toLowerCase();
boolean deleteArg = false;
for (var entry : map.entrySet()) {
int argNum = matchIntOrNeg(entry.getKey(), argL);
if (argNum != -1) {
entry.getValue().accept(params, argNum);
deleteArg = true;
}
}
return deleteArg;
});
return args;
}
}
package emu.grasscutter.command;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
public class CommandHelpers {
public static final Pattern lvlRegex =
Pattern.compile("(?<!\\w)l(?:vl?)?(\\d+)"); // Java doesn't have raw string literals :(
public static final Pattern amountRegex =
Pattern.compile("((?<=(?<!\\w)x)\\d+|\\d+(?=x)(?!x\\d))");
public static final Pattern refineRegex = Pattern.compile("(?<!\\w)r(\\d+)");
public static final Pattern rankRegex = Pattern.compile("(\\d+)\\*");
public static final Pattern constellationRegex = Pattern.compile("(?<!\\w)c(\\d+)");
public static final Pattern skillLevelRegex = Pattern.compile("sl(\\d+)");
public static final Pattern stateRegex = Pattern.compile("state(\\d+)");
public static final Pattern blockRegex = Pattern.compile("blk(\\d+)");
public static final Pattern groupRegex = Pattern.compile("grp(\\d+)");
public static final Pattern configRegex = Pattern.compile("cfg(\\d+)");
public static final Pattern hpRegex = Pattern.compile("(?<!\\w)hp(\\d+)");
public static final Pattern maxHPRegex = Pattern.compile("maxhp(\\d+)");
public static final Pattern atkRegex = Pattern.compile("atk(\\d+)");
public static final Pattern defRegex = Pattern.compile("def(\\d+)");
public static final Pattern aiRegex = Pattern.compile("ai(\\d+)");
public static final Pattern sceneRegex = Pattern.compile("scene(\\d+)");
public static final Pattern suiteRegex = Pattern.compile("suite(\\d+)");
public static int matchIntOrNeg(Pattern pattern, String arg) {
Matcher match = pattern.matcher(arg);
if (match.find()) {
return Integer.parseInt(
match.group(
1)); // This should be exception-safe as only \d+ can be passed to it (i.e. non-empty
// string of pure digits)
}
return -1;
}
public static <T> List<String> parseIntParameters(
List<String> args, @Nonnull T params, Map<Pattern, BiConsumer<T, Integer>> map) {
args.removeIf(
arg -> {
var argL = arg.toLowerCase();
boolean deleteArg = false;
for (var entry : map.entrySet()) {
int argNum = matchIntOrNeg(entry.getKey(), argL);
if (argNum != -1) {
entry.getValue().accept(params, argNum);
deleteArg = true;
}
}
return deleteArg;
});
return args;
}
}

View File

@ -0,0 +1,27 @@
package emu.grasscutter.command.commands;
import emu.grasscutter.command.Command;
import emu.grasscutter.command.CommandHandler;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.server.packet.send.PacketCutsceneBeginNotify;
import java.util.List;
import lombok.val;
@Command(
label = "cutscene",
aliases = {"c"},
usage = {"[<cutsceneId>]"},
permission = "player.group",
permissionTargeted = "player.group.others")
public final class CutsceneCommand implements CommandHandler {
@Override
public void execute(Player sender, Player targetPlayer, List<String> args) {
if (args.isEmpty()) {
sendUsageMessage(sender);
return;
}
val cutSceneId = Integer.parseInt(args.get(0));
targetPlayer.sendPacket(new PacketCutsceneBeginNotify(cutSceneId));
}
}

View File

@ -0,0 +1,48 @@
package emu.grasscutter.command.commands;
import static emu.grasscutter.utils.Language.translate;
import emu.grasscutter.command.Command;
import emu.grasscutter.command.CommandHandler;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.server.packet.send.PacketScenePlayerSoundNotify;
import emu.grasscutter.utils.Position;
import java.util.List;
import lombok.val;
@Command(
label = "sound",
aliases = {"s", "audio"},
usage = {"[<audioname>] [<x><y><z>]"},
permission = "player.group",
permissionTargeted = "player.group.others")
public final class SoundCommand implements CommandHandler {
@Override
public void execute(Player sender, Player targetPlayer, List<String> args) {
if (args.isEmpty()) {
sendUsageMessage(sender);
return;
}
val soundName = args.get(0);
var playPosition = targetPlayer.getPosition();
if (args.size() == 4) {
try {
float x, y, z;
x = Float.parseFloat(args.get(1));
y = Float.parseFloat(args.get(2));
z = Float.parseFloat(args.get(3));
playPosition = new Position(x, y, z);
} catch (NumberFormatException ignored) {
CommandHandler.sendMessage(sender, translate(sender, "commands.execution.argument_error"));
return;
}
} else if (args.size() > 1) {
sendUsageMessage(sender);
return;
}
targetPlayer
.getScene()
.broadcastPacket(new PacketScenePlayerSoundNotify(playPosition, soundName, 1));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,13 @@
package emu.grasscutter.game.dungeons.challenge.trigger;
import emu.grasscutter.game.dungeons.challenge.WorldChallenge;
public class InTimeTrigger extends ChallengeTrigger {
@Override
public void onCheckTimeout(WorldChallenge challenge) {
var current = System.currentTimeMillis();
if (current - challenge.getStartedAt() > challenge.getTimeLimit() * 1000L) {
challenge.fail();
}
}
}
package emu.grasscutter.game.dungeons.challenge.trigger;
import emu.grasscutter.game.dungeons.challenge.WorldChallenge;
public class InTimeTrigger extends ChallengeTrigger {
@Override
public void onCheckTimeout(WorldChallenge challenge) {
var current = challenge.getScene().getSceneTimeSeconds();
if (current - challenge.getStartedAt() > challenge.getTimeLimit()) {
challenge.fail();
}
}
}

View File

@ -15,6 +15,7 @@ import emu.grasscutter.game.activity.ActivityManager;
import emu.grasscutter.game.avatar.Avatar;
import emu.grasscutter.game.avatar.AvatarStorage;
import emu.grasscutter.game.battlepass.BattlePassManager;
import emu.grasscutter.game.entity.EntityAvatar;
import emu.grasscutter.game.entity.GameEntity;
import emu.grasscutter.game.expedition.ExpeditionInfo;
import emu.grasscutter.game.friends.FriendsList;
@ -44,6 +45,7 @@ import emu.grasscutter.game.props.ClimateType;
import emu.grasscutter.game.props.PlayerProperty;
import emu.grasscutter.game.props.WatcherTriggerType;
import emu.grasscutter.game.quest.QuestManager;
import emu.grasscutter.game.quest.enums.QuestCond;
import emu.grasscutter.game.quest.enums.QuestContent;
import emu.grasscutter.game.shop.ShopLimit;
import emu.grasscutter.game.tower.TowerData;
@ -51,20 +53,18 @@ import emu.grasscutter.game.tower.TowerManager;
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.game.world.World;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.proto.*;
import emu.grasscutter.net.proto.AbilityInvokeEntryOuterClass.AbilityInvokeEntry;
import emu.grasscutter.net.proto.AttackResultOuterClass.AttackResult;
import emu.grasscutter.net.proto.CombatInvokeEntryOuterClass.CombatInvokeEntry;
import emu.grasscutter.net.proto.GadgetInteractReqOuterClass.GadgetInteractReq;
import emu.grasscutter.net.proto.MpSettingTypeOuterClass.MpSettingType;
import emu.grasscutter.net.proto.OnlinePlayerInfoOuterClass.OnlinePlayerInfo;
import emu.grasscutter.net.proto.PlayerApplyEnterMpResultNotifyOuterClass;
import emu.grasscutter.net.proto.PlayerLocationInfoOuterClass.PlayerLocationInfo;
import emu.grasscutter.net.proto.PlayerWorldLocationInfoOuterClass;
import emu.grasscutter.net.proto.ProfilePictureOuterClass.ProfilePicture;
import emu.grasscutter.net.proto.PropChangeReasonOuterClass.PropChangeReason;
import emu.grasscutter.net.proto.ShowAvatarInfoOuterClass;
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
import emu.grasscutter.net.proto.SocialShowAvatarInfoOuterClass;
import emu.grasscutter.net.proto.TrialAvatarGrantRecordOuterClass.TrialAvatarGrantRecord.GrantReason;
import emu.grasscutter.scripts.data.SceneRegion;
import emu.grasscutter.server.event.player.PlayerJoinEvent;
import emu.grasscutter.server.event.player.PlayerQuitEvent;
@ -88,6 +88,7 @@ import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Stream;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
@ -472,6 +473,8 @@ public class Player {
// Handle open state unlocks from level-up.
this.getProgressManager().tryUnlockOpenStates();
this.getQuestManager().queueEvent(QuestContent.QUEST_CONTENT_PLAYER_LEVEL_UP, level);
this.getQuestManager().queueEvent(QuestCond.QUEST_COND_PLAYER_LEVEL_EQUAL_GREATER, level);
return true;
}
@ -613,7 +616,7 @@ public class Player {
public void onEnterRegion(SceneRegion region) {
getQuestManager().forEachActiveQuest(quest -> {
if (quest.getTriggers().containsKey("ENTER_REGION_" + region.config_id)) {
if (quest.getTriggerData() != null && quest.getTriggers().containsKey("ENTER_REGION_"+ region.config_id)) {
// If trigger hasn't been fired yet
if (!Boolean.TRUE.equals(quest.getTriggers().put("ENTER_REGION_" + region.config_id, true))) {
//getSession().send(new PacketServerCondMeetQuestListUpdateNotify());
@ -824,6 +827,85 @@ public class Player {
addAvatar(avatar, true);
}
public void addAvatar(int avatarId) {
// I dont see why we cant do this lolz
addAvatar(new Avatar(avatarId), true);
}
public List<Integer> getTrialAvatarParam (int trialAvatarId) {
if (GameData.getTrialAvatarCustomData().isEmpty()) { // use default data if custom data not available
if (GameData.getTrialAvatarDataMap().get(trialAvatarId) == null) return List.of();
return GameData.getTrialAvatarDataMap().get(trialAvatarId)
.getTrialAvatarParamList();
}
// use custom data
if (GameData.getTrialAvatarCustomData().get(trialAvatarId) == null) return List.of();
var trialCustomParams = GameData.getTrialAvatarCustomData().get(trialAvatarId).getTrialAvatarParamList();
return trialCustomParams.isEmpty() ? List.of() : Stream.of(trialCustomParams.get(0).split(";")).map(Integer::parseInt).toList();
}
public boolean addTrialAvatar(int trialAvatarId, GrantReason reason, int questMainId){
List<Integer> trialAvatarBasicParam = getTrialAvatarParam(trialAvatarId);
if (trialAvatarBasicParam.isEmpty()) return false;
Avatar avatar = new Avatar(trialAvatarBasicParam.get(0));
if (avatar.getAvatarData() == null || !hasSentLoginPackets()) return false;
avatar.setOwner(this);
// Add trial weapons and relics
avatar.setTrialAvatarInfo(trialAvatarBasicParam.get(1), trialAvatarId, reason, questMainId);
avatar.equipTrialItems();
// Recalc stats
avatar.recalcStats();
// Packet, mimic official server behaviour, add to player's bag but not saving to db
sendPacket(new PacketAvatarAddNotify(avatar, false));
// add to avatar to temporary trial team
getTeamManager().addAvatarToTrialTeam(avatar);
return true;
}
public boolean addTrialAvatarForQuest(int trialAvatarId, int questMainId) {
// TODO: Find method for 'setupTrialAvatarTeamForQuest'.
getTeamManager().setupTrialAvatars(true);
if (!addTrialAvatar(
trialAvatarId,
GrantReason.GRANT_REASON_BY_QUEST,
questMainId)) return false;
getTeamManager().trialAvatarTeamPostUpdate();
// Packet, mimic official server behaviour, neccessary to stop player from modifying team
sendPacket(new PacketAvatarTeamUpdateNotify(this));
return true;
}
public void addTrialAvatarsForActivity(List<Integer> trialAvatarIds) {
getTeamManager().setupTrialAvatars(false);
trialAvatarIds.forEach(trialAvatarId -> addTrialAvatar(
trialAvatarId,
GrantReason.GRANT_REASON_BY_TRIAL_AVATAR_ACTIVITY,
0));
getTeamManager().trialAvatarTeamPostUpdate(0);
}
public boolean removeTrialAvatarForQuest(int trialAvatarId) {
if (!getTeamManager().isUsingTrialTeam()) return false;
sendPacket(new PacketAvatarDelNotify(List.of(getTeamManager().getTrialAvatarGuid(trialAvatarId))));
getTeamManager().removeTrialAvatarTeam(trialAvatarId);
sendPacket(new PacketAvatarTeamUpdateNotify());
return true;
}
public void removeTrialAvatarForActivity() {
if (!getTeamManager().isUsingTrialTeam()) return;
sendPacket(new PacketAvatarDelNotify(getTeamManager().getActiveTeam().stream()
.map(x -> x.getAvatar().getGuid()).toList()));
getTeamManager().removeTrialAvatarTeam();
}
public void addFlycloak(int flycloakId) {
this.getFlyCloakList().add(flycloakId);
this.sendPacket(new PacketAvatarGainFlycloakNotify(flycloakId));
@ -834,6 +916,11 @@ public class Player {
this.sendPacket(new PacketAvatarGainCostumeNotify(costumeId));
}
public void addPersonalLine(int personalLineId) {
this.getPersonalLineList().add(personalLineId);
session.getPlayer().getQuestManager().queueEvent(QuestCond.QUEST_COND_PERSONAL_LINE_UNLOCK, personalLineId);
}
public void addNameCard(int nameCardId) {
this.getNameCardList().add(nameCardId);
this.sendPacket(new PacketUnlockNameCardNotify(nameCardId));
@ -863,6 +950,46 @@ public class Player {
this.getServer().getChatSystem().sendPrivateMessageFromServer(getUid(), message.toString());
}
public void setAvatarsAbilityForScene(Scene scene) {
try {
var levelEntityConfig = scene.getSceneData().getLevelEntityConfig();
var config = GameData.getConfigLevelEntityDataMap().get(levelEntityConfig);
if (config == null){
return;
}
List<Integer> avatarIds = scene.getSceneData().getSpecifiedAvatarList();
List<EntityAvatar> specifiedAvatarList = getTeamManager().getActiveTeam();
if (avatarIds != null && avatarIds.size() > 0){
// certain scene could limit specifc avatars' entry
specifiedAvatarList.clear();
for (int id : avatarIds){
var avatar = getAvatars().getAvatarById(id);
if (avatar == null){
continue;
}
specifiedAvatarList.add(new EntityAvatar(scene, avatar));
}
}
for (EntityAvatar entityAvatar : specifiedAvatarList){
var avatarData = entityAvatar.getAvatar().getAvatarData();
if (avatarData == null){
continue;
}
avatarData.buildEmbryo();
if (config.getAvatarAbilities() == null){
continue; // continue and not break because has to rebuild ability for the next avatar if any
}
for (var abilities : config.getAvatarAbilities()){
avatarData.getAbilities().add(Utils.abilityHash(abilities.getAbilityName()));
}
}
} catch (Exception e){
Grasscutter.getLogger().error("Error applying level entity config for scene {}", scene.getSceneData().getId(), e);
}
}
/**
* Sends a message to another player.
*
@ -982,7 +1109,7 @@ public class Player {
}
}
SocialDetail.Builder social = SocialDetail.newBuilder()
return SocialDetail.newBuilder()
.setUid(this.getUid())
.setProfilePicture(ProfilePicture.newBuilder().setAvatarId(this.getHeadImage()))
.setNickname(this.getNickname())
@ -996,7 +1123,6 @@ public class Player {
.addAllShowNameCardIdList(this.getShowNameCardInfoList())
.setFinishAchievementNum(this.getFinishedAchievementNum())
.setFriendEnterHomeOptionValue(this.getHome() == null ? 0 : this.getHome().getEnterHomeOption());
return social;
}
public int getFinishedAchievementNum() {
@ -1135,6 +1261,8 @@ public class Player {
// Home resources
this.getHome().updateHourlyResources(this);
this.getQuestManager().onTick();
}
private synchronized void doDailyReset() {
@ -1200,12 +1328,17 @@ public class Player {
this.achievements = Achievements.getByPlayer(this);
this.getAvatars().loadFromDatabase();
this.getInventory().loadFromDatabase();
this.loadBattlePassManager(); // Call before avatar postLoad to avoid null pointer
this.getAvatars().postLoad(); // Needs to be called after inventory is handled
this.getFriendsList().loadFromDatabase();
this.getMailHandler().loadFromDatabase();
this.getQuestManager().loadFromDatabase();
this.loadBattlePassManager();
this.getAvatars().postLoad(); // Needs to be called after inventory is handled
}
public void onPlayerBorn() {
getQuestManager().onPlayerBorn();
}
public void onLogin() {

View File

@ -1,108 +1,109 @@
package emu.grasscutter.game.props;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public enum EntityType {
None(0),
Avatar(1),
Monster(2),
Bullet(3),
AttackPhyisicalUnit(4),
AOE(5),
Camera(6),
EnviroArea(7),
Equip(8),
MonsterEquip(9),
Grass(10),
Level(11),
NPC(12),
TransPointFirst(13),
TransPointFirstGadget(14),
TransPointSecond(15),
TransPointSecondGadget(16),
DropItem(17),
Field(18),
Gadget(19),
Water(20),
GatherPoint(21),
GatherObject(22),
AirflowField(23),
SpeedupField(24),
Gear(25),
Chest(26),
EnergyBall(27),
ElemCrystal(28),
Timeline(29),
Worktop(30),
Team(31),
Platform(32),
AmberWind(33),
EnvAnimal(34),
SealGadget(35),
Tree(36),
Bush(37),
QuestGadget(38),
Lightning(39),
RewardPoint(40),
RewardStatue(41),
MPLevel(42),
WindSeed(43),
MpPlayRewardPoint(44),
ViewPoint(45),
RemoteAvatar(46),
GeneralRewardPoint(47),
PlayTeam(48),
OfferingGadget(49),
EyePoint(50),
MiracleRing(51),
Foundation(52),
WidgetGadget(53),
Vehicle(54),
SubEquip(55),
FishRod(56),
CustomTile(57),
FishPool(58),
CustomGadget(59),
BlackMud(60),
RoguelikeOperatorGadget(61),
NightCrowGadget(62),
Projector(63),
Screen(64),
EchoShell(65),
UIInteractGadget(66),
PlaceHolder(99);
private static final Int2ObjectMap<EntityType> map = new Int2ObjectOpenHashMap<>();
private static final Map<String, EntityType> stringMap = new HashMap<>();
static {
Stream.of(values())
.forEach(
e -> {
map.put(e.getValue(), e);
stringMap.put(e.name(), e);
});
}
private final int value;
EntityType(int value) {
this.value = value;
}
public static EntityType getTypeByValue(int value) {
return map.getOrDefault(value, None);
}
public static EntityType getTypeByName(String name) {
return stringMap.getOrDefault(name, None);
}
public int getValue() {
return value;
}
}
package emu.grasscutter.game.props;
import emu.grasscutter.scripts.constants.IntValueEnum;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public enum EntityType implements IntValueEnum {
None(0),
Avatar(1),
Monster(2),
Bullet(3),
AttackPhyisicalUnit(4),
AOE(5),
Camera(6),
EnviroArea(7),
Equip(8),
MonsterEquip(9),
Grass(10),
Level(11),
NPC(12),
TransPointFirst(13),
TransPointFirstGadget(14),
TransPointSecond(15),
TransPointSecondGadget(16),
DropItem(17),
Field(18),
Gadget(19),
Water(20),
GatherPoint(21),
GatherObject(22),
AirflowField(23),
SpeedupField(24),
Gear(25),
Chest(26),
EnergyBall(27),
ElemCrystal(28),
Timeline(29),
Worktop(30),
Team(31),
Platform(32),
AmberWind(33),
EnvAnimal(34),
SealGadget(35),
Tree(36),
Bush(37),
QuestGadget(38),
Lightning(39),
RewardPoint(40),
RewardStatue(41),
MPLevel(42),
WindSeed(43),
MpPlayRewardPoint(44),
ViewPoint(45),
RemoteAvatar(46),
GeneralRewardPoint(47),
PlayTeam(48),
OfferingGadget(49),
EyePoint(50),
MiracleRing(51),
Foundation(52),
WidgetGadget(53),
Vehicle(54),
SubEquip(55),
FishRod(56),
CustomTile(57),
FishPool(58),
CustomGadget(59),
BlackMud(60),
RoguelikeOperatorGadget(61),
NightCrowGadget(62),
Projector(63),
Screen(64),
EchoShell(65),
UIInteractGadget(66),
PlaceHolder(99);
private static final Int2ObjectMap<EntityType> map = new Int2ObjectOpenHashMap<>();
private static final Map<String, EntityType> stringMap = new HashMap<>();
static {
Stream.of(values())
.forEach(
e -> {
map.put(e.getValue(), e);
stringMap.put(e.name(), e);
});
}
private final int value;
EntityType(int value) {
this.value = value;
}
public static EntityType getTypeByValue(int value) {
return map.getOrDefault(value, None);
}
public static EntityType getTypeByName(String name) {
return stringMap.getOrDefault(name, None);
}
public int getValue() {
return value;
}
}

View File

@ -16,7 +16,6 @@ import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.ActionReason;
import emu.grasscutter.game.quest.enums.*;
import emu.grasscutter.game.world.World;
import emu.grasscutter.net.proto.ChildQuestOuterClass.ChildQuest;
import emu.grasscutter.net.proto.ParentQuestOuterClass.ParentQuest;
import emu.grasscutter.server.packet.send.PacketCodexDataUpdateNotify;
@ -41,7 +40,7 @@ public class GameMainQuest {
@Getter private int[] questVars;
@Getter private long[] timeVar;
//QuestUpdateQuestVarReq is sent in two stages...
@Getter private List<Integer> questVarsUpdate;
private List<Integer> questVarsUpdate;
@Getter private ParentQuestState state;
@Getter private boolean isFinished;
@Getter List<QuestGroupSuite> questGroupSuites;
@ -67,6 +66,13 @@ public class GameMainQuest {
addAllChildQuests();
}
public List<Integer> getQuestVarsUpdate() {
if(questVarsUpdate == null){
questVarsUpdate = new ArrayList<>();
}
return questVarsUpdate;
}
private void addAllChildQuests() {
List<Integer> subQuestIds = Arrays.stream(GameData.getMainQuestDataMap().get(this.parentQuestId).getSubQuests()).map(SubQuestData::getSubId).toList();
for (Integer subQuestId : subQuestIds) {
@ -166,10 +172,10 @@ public class GameMainQuest {
}
// handoff main quest
if (mainQuestData.getSuggestTrackMainQuestList() != null) {
Arrays.stream(mainQuestData.getSuggestTrackMainQuestList())
.forEach(getQuestManager()::startMainQuest);
}
// if (mainQuestData.getSuggestTrackMainQuestList() != null) {
// Arrays.stream(mainQuestData.getSuggestTrackMainQuestList())
// .forEach(getQuestManager()::startMainQuest);
// }
}
//TODO
public void fail() {}
@ -181,9 +187,9 @@ public class GameMainQuest {
return null;
}
/*if(rewindPositions.isEmpty()){
addRewindPoints();
}*/
// if(rewindPositions.isEmpty()){
// this.addRewindPoints();
// }
List<Position> posAndRot = new ArrayList<>();
if(hasRewindPosition(targetQuest.getSubQuestId(), posAndRot)){
@ -198,8 +204,8 @@ public class GameMainQuest {
if (hasRewindPosition(quest.getSubQuestId(), posAndRot)) {
return posAndRot;
}
}
return null;
}

View File

@ -1,308 +1,312 @@
package emu.grasscutter.game.quest;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Transient;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.ChapterData;
import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.data.excels.TriggerExcelConfigData;
import emu.grasscutter.game.dungeons.enums.DungeonPassConditionType;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.ActionReason;
import emu.grasscutter.game.quest.enums.QuestCond;
import emu.grasscutter.game.quest.enums.QuestContent;
import emu.grasscutter.game.quest.enums.QuestState;
import emu.grasscutter.net.proto.ChapterStateOuterClass;
import emu.grasscutter.net.proto.QuestOuterClass.Quest;
import emu.grasscutter.scripts.data.SceneGroup;
import emu.grasscutter.server.packet.send.PacketChapterStateNotify;
import emu.grasscutter.server.packet.send.PacketDelQuestNotify;
import emu.grasscutter.server.packet.send.PacketQuestListUpdateNotify;
import emu.grasscutter.utils.Utils;
import java.util.HashMap;
import java.util.Map;
import javax.script.Bindings;
import lombok.Getter;
import lombok.Setter;
import lombok.val;
@Entity
public class GameQuest {
@Transient @Getter @Setter private GameMainQuest mainQuest;
@Transient @Getter private QuestData questData;
@Getter private int subQuestId;
@Getter private int mainQuestId;
@Getter @Setter public QuestState state;
@Getter @Setter private int startTime;
@Getter @Setter private int acceptTime;
@Getter @Setter private int finishTime;
@Getter @Setter private long startGameDay;
@Getter private int[] finishProgressList;
@Getter private int[] failProgressList;
@Transient @Getter private Map<String, TriggerExcelConfigData> triggerData;
@Getter private Map<String, Boolean> triggers;
private transient Bindings bindings;
@Deprecated // Morphia only. Do not use.
public GameQuest() {}
public GameQuest(GameMainQuest mainQuest, QuestData questData) {
this.mainQuest = mainQuest;
this.subQuestId = questData.getId();
this.mainQuestId = questData.getMainId();
this.questData = questData;
this.state = QuestState.QUEST_STATE_UNSTARTED;
this.triggerData = new HashMap<>();
this.triggers = new HashMap<>();
}
public void start() {
clearProgress(false);
this.acceptTime = Utils.getCurrentSeconds();
this.startTime = this.acceptTime;
this.startGameDay = getOwner().getWorld().getTotalGameTimeDays();
this.state = QuestState.QUEST_STATE_UNFINISHED;
val triggerCond =
questData.getFinishCond().stream()
.filter(p -> p.getType() == QuestContent.QUEST_CONTENT_TRIGGER_FIRE)
.toList();
if (triggerCond.size() > 0) {
for (val cond : triggerCond) {
TriggerExcelConfigData newTrigger =
GameData.getTriggerExcelConfigDataMap().get(cond.getParam()[0]);
if (newTrigger != null) {
if (this.triggerData == null) {
this.triggerData = new HashMap<>();
}
triggerData.put(newTrigger.getTriggerName(), newTrigger);
triggers.put(newTrigger.getTriggerName(), false);
SceneGroup group = SceneGroup.of(newTrigger.getGroupId()).load(newTrigger.getSceneId());
getOwner()
.getWorld()
.getSceneById(newTrigger.getSceneId())
.loadTriggerFromGroup(group, newTrigger.getTriggerName());
}
}
}
getOwner().sendPacket(new PacketQuestListUpdateNotify(this));
if (ChapterData.beginQuestChapterMap.containsKey(subQuestId)) {
getOwner()
.sendPacket(
new PacketChapterStateNotify(
ChapterData.beginQuestChapterMap.get(subQuestId).getId(),
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_BEGIN));
}
// Some subQuests and talks become active when some other subQuests are unfinished (even from
// different MainQuests)
getOwner()
.getQuestManager()
.queueEvent(
QuestContent.QUEST_CONTENT_QUEST_STATE_EQUAL,
getSubQuestId(),
getState().getValue(),
0,
0,
0);
getOwner()
.getQuestManager()
.queueEvent(
QuestCond.QUEST_COND_STATE_EQUAL, getSubQuestId(), getState().getValue(), 0, 0, 0);
getQuestData()
.getBeginExec()
.forEach(e -> getOwner().getServer().getQuestSystem().triggerExec(this, e, e.getParam()));
getOwner().getQuestManager().checkQuestAlreadyFullfilled(this);
Grasscutter.getLogger().debug("Quest {} is started", subQuestId);
}
public String getTriggerNameById(int id) {
TriggerExcelConfigData trigger = GameData.getTriggerExcelConfigDataMap().get(id);
if (trigger != null) {
String triggerName = trigger.getTriggerName();
return triggerName;
}
// return empty string if can't find trigger
return "";
}
public Player getOwner() {
return this.getMainQuest().getOwner();
}
public void setConfig(QuestData config) {
if (config == null || getSubQuestId() != config.getId()) return;
this.questData = config;
}
public void setFinishProgress(int index, int value) {
finishProgressList[index] = value;
}
public void setFailProgress(int index, int value) {
failProgressList[index] = value;
}
public boolean clearProgress(boolean notifyDelete) {
// TODO improve
var oldState = state;
if (questData.getFinishCond() != null && questData.getFinishCond().size() != 0) {
this.finishProgressList = new int[questData.getFinishCond().size()];
}
if (questData.getFailCond() != null && questData.getFailCond().size() != 0) {
this.failProgressList = new int[questData.getFailCond().size()];
}
setState(QuestState.QUEST_STATE_UNSTARTED);
finishTime = 0;
acceptTime = 0;
startTime = 0;
if (oldState == QuestState.QUEST_STATE_UNSTARTED) {
return false;
}
if (notifyDelete) {
getOwner().sendPacket(new PacketDelQuestNotify(getSubQuestId()));
}
save();
return true;
}
public void finish() {
this.state = QuestState.QUEST_STATE_FINISHED;
this.finishTime = Utils.getCurrentSeconds();
getOwner().sendPacket(new PacketQuestListUpdateNotify(this));
if (getQuestData().isFinishParent()) {
// This quest finishes the questline - the main quest will also save the quest to db, so we
// don't have to call save() here
getMainQuest().finish();
}
getQuestData()
.getFinishExec()
.forEach(e -> getOwner().getServer().getQuestSystem().triggerExec(this, e, e.getParam()));
// Some subQuests have conditions that subQuests are finished (even from different MainQuests)
getOwner()
.getQuestManager()
.queueEvent(
QuestContent.QUEST_CONTENT_QUEST_STATE_EQUAL,
this.subQuestId,
this.state.getValue(),
0,
0,
0);
getOwner()
.getQuestManager()
.queueEvent(QuestContent.QUEST_CONTENT_FINISH_PLOT, this.subQuestId, 0);
getOwner()
.getQuestManager()
.queueEvent(
QuestCond.QUEST_COND_STATE_EQUAL, this.subQuestId, this.state.getValue(), 0, 0, 0);
getOwner()
.getScene()
.triggerDungeonEvent(DungeonPassConditionType.DUNGEON_COND_FINISH_QUEST, getSubQuestId());
getOwner().getProgressManager().tryUnlockOpenStates();
if (ChapterData.endQuestChapterMap.containsKey(subQuestId)) {
mainQuest
.getOwner()
.sendPacket(
new PacketChapterStateNotify(
ChapterData.endQuestChapterMap.get(subQuestId).getId(),
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_END));
}
// hard coding to give amber
if (getQuestData().getSubId() == 35402) {
getOwner().getInventory().addItem(1021, 1, ActionReason.QuestItem); // amber item id
}
Grasscutter.getLogger().debug("Quest {} is finished", subQuestId);
}
// TODO
public void fail() {
this.state = QuestState.QUEST_STATE_FAILED;
this.finishTime = Utils.getCurrentSeconds();
this.getOwner().sendPacket(new PacketQuestListUpdateNotify(this));
// Some subQuests have conditions that subQuests fail (even from different MainQuests)
this.getOwner()
.getQuestManager()
.queueEvent(
QuestContent.QUEST_CONTENT_QUEST_STATE_EQUAL,
this.subQuestId,
this.state.getValue(),
0,
0,
0);
this.getOwner()
.getQuestManager()
.queueEvent(
QuestCond.QUEST_COND_STATE_EQUAL, this.subQuestId, this.state.getValue(), 0, 0, 0);
this.getQuestData()
.getFailExec()
.forEach(e -> getOwner().getServer().getQuestSystem().triggerExec(this, e, e.getParam()));
if (this.getQuestData().getTrialAvatarList() != null) {
this.getQuestData()
.getTrialAvatarList()
.forEach(t -> this.getOwner().getTeamManager().removeTrialAvatar(t));
}
Grasscutter.getLogger().debug("Quest {} is failed", subQuestId);
}
// Return true if it did the rewind
public boolean rewind(boolean notifyDelete) {
getMainQuest().getChildQuests().values().stream()
.filter(p -> p.getQuestData().getOrder() > this.getQuestData().getOrder())
.forEach(
q -> {
q.clearProgress(notifyDelete);
});
clearProgress(notifyDelete);
this.start();
return true;
}
public void save() {
getMainQuest().save();
}
public Quest toProto() {
Quest.Builder proto =
Quest.newBuilder()
.setQuestId(getSubQuestId())
.setState(getState().getValue())
.setParentQuestId(getMainQuestId())
.setStartTime(getStartTime())
.setStartGameTime(438)
.setAcceptTime(getAcceptTime());
if (getFinishProgressList() != null) {
for (int i : getFinishProgressList()) {
proto.addFinishProgressList(i);
}
}
if (getFailProgressList() != null) {
for (int i : getFailProgressList()) {
proto.addFailProgressList(i);
}
}
return proto.build();
}
}
package emu.grasscutter.game.quest;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Transient;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.ChapterData;
import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.data.excels.TriggerExcelConfigData;
import emu.grasscutter.game.dungeons.enums.DungeonPassConditionType;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.ActionReason;
import emu.grasscutter.game.quest.enums.QuestCond;
import emu.grasscutter.game.quest.enums.QuestContent;
import emu.grasscutter.game.quest.enums.QuestState;
import emu.grasscutter.net.proto.ChapterStateOuterClass;
import emu.grasscutter.net.proto.QuestOuterClass.Quest;
import emu.grasscutter.scripts.data.SceneGroup;
import emu.grasscutter.server.packet.send.PacketChapterStateNotify;
import emu.grasscutter.server.packet.send.PacketDelQuestNotify;
import emu.grasscutter.server.packet.send.PacketQuestListUpdateNotify;
import emu.grasscutter.utils.Utils;
import java.util.HashMap;
import java.util.Map;
import javax.script.Bindings;
import lombok.Getter;
import lombok.Setter;
import lombok.val;
@Entity
public class GameQuest {
@Transient @Getter @Setter private GameMainQuest mainQuest;
@Transient @Getter private QuestData questData;
@Getter private int subQuestId;
@Getter private int mainQuestId;
@Getter @Setter public QuestState state;
@Getter @Setter private int startTime;
@Getter @Setter private int acceptTime;
@Getter @Setter private int finishTime;
@Getter @Setter private long startGameDay;
@Getter private int[] finishProgressList;
@Getter private int[] failProgressList;
@Transient @Getter private Map<String, TriggerExcelConfigData> triggerData;
@Getter private Map<String, Boolean> triggers;
private transient Bindings bindings;
@Deprecated // Morphia only. Do not use.
public GameQuest() {}
public GameQuest(GameMainQuest mainQuest, QuestData questData) {
this.mainQuest = mainQuest;
this.subQuestId = questData.getId();
this.mainQuestId = questData.getMainId();
this.questData = questData;
this.state = QuestState.QUEST_STATE_UNSTARTED;
this.triggerData = new HashMap<>();
this.triggers = new HashMap<>();
}
public void start() {
clearProgress(false);
this.acceptTime = Utils.getCurrentSeconds();
this.startTime = this.acceptTime;
this.startGameDay = getOwner().getWorld().getTotalGameTimeDays();
this.state = QuestState.QUEST_STATE_UNFINISHED;
val triggerCond =
questData.getFinishCond().stream()
.filter(p -> p.getType() == QuestContent.QUEST_CONTENT_TRIGGER_FIRE)
.toList();
if (triggerCond.size() > 0) {
for (val cond : triggerCond) {
TriggerExcelConfigData newTrigger =
GameData.getTriggerExcelConfigDataMap().get(cond.getParam()[0]);
if (newTrigger != null) {
if (this.triggerData == null) {
this.triggerData = new HashMap<>();
}
triggerData.put(newTrigger.getTriggerName(), newTrigger);
triggers.put(newTrigger.getTriggerName(), false);
SceneGroup group = SceneGroup.of(newTrigger.getGroupId()).load(newTrigger.getSceneId());
getOwner()
.getWorld()
.getSceneById(newTrigger.getSceneId())
.loadTriggerFromGroup(group, newTrigger.getTriggerName());
}
}
}
getOwner().sendPacket(new PacketQuestListUpdateNotify(this));
if (ChapterData.beginQuestChapterMap.containsKey(subQuestId)) {
getOwner()
.sendPacket(
new PacketChapterStateNotify(
ChapterData.beginQuestChapterMap.get(subQuestId).getId(),
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_BEGIN));
}
// Some subQuests and talks become active when some other subQuests are unfinished (even from
// different MainQuests)
getOwner()
.getQuestManager()
.queueEvent(
QuestContent.QUEST_CONTENT_QUEST_STATE_EQUAL,
getSubQuestId(),
getState().getValue(),
0,
0,
0);
getOwner()
.getQuestManager()
.queueEvent(
QuestCond.QUEST_COND_STATE_EQUAL, getSubQuestId(), getState().getValue(), 0, 0, 0);
getQuestData()
.getBeginExec()
.forEach(e -> getOwner().getServer().getQuestSystem().triggerExec(this, e, e.getParam()));
getOwner().getQuestManager().checkQuestAlreadyFullfilled(this);
Grasscutter.getLogger().debug("Quest {} is started", subQuestId);
this.save();
}
public String getTriggerNameById(int id) {
TriggerExcelConfigData trigger = GameData.getTriggerExcelConfigDataMap().get(id);
if (trigger != null) {
String triggerName = trigger.getTriggerName();
return triggerName;
}
// return empty string if can't find trigger
return "";
}
public Player getOwner() {
return this.getMainQuest().getOwner();
}
public void setConfig(QuestData config) {
if (config == null || getSubQuestId() != config.getId()) return;
this.questData = config;
}
public void setFinishProgress(int index, int value) {
finishProgressList[index] = value;
}
public void setFailProgress(int index, int value) {
failProgressList[index] = value;
}
public boolean clearProgress(boolean notifyDelete) {
// TODO improve
var oldState = state;
if (questData.getFinishCond() != null && questData.getFinishCond().size() != 0) {
this.finishProgressList = new int[questData.getFinishCond().size()];
}
if (questData.getFailCond() != null && questData.getFailCond().size() != 0) {
this.failProgressList = new int[questData.getFailCond().size()];
}
setState(QuestState.QUEST_STATE_UNSTARTED);
finishTime = 0;
acceptTime = 0;
startTime = 0;
if (oldState == QuestState.QUEST_STATE_UNSTARTED) {
return false;
}
if (notifyDelete) {
getOwner().sendPacket(new PacketDelQuestNotify(getSubQuestId()));
}
save();
return true;
}
public void finish() {
this.state = QuestState.QUEST_STATE_FINISHED;
this.finishTime = Utils.getCurrentSeconds();
getOwner().sendPacket(new PacketQuestListUpdateNotify(this));
if (getQuestData().isFinishParent()) {
// This quest finishes the questline - the main quest will also save the quest to db, so we
// don't have to call save() here
getMainQuest().finish();
}
getQuestData()
.getFinishExec()
.forEach(e -> getOwner().getServer().getQuestSystem().triggerExec(this, e, e.getParam()));
// Some subQuests have conditions that subQuests are finished (even from different MainQuests)
getOwner()
.getQuestManager()
.queueEvent(
QuestContent.QUEST_CONTENT_QUEST_STATE_EQUAL,
this.subQuestId,
this.state.getValue(),
0,
0,
0);
getOwner()
.getQuestManager()
.queueEvent(QuestContent.QUEST_CONTENT_FINISH_PLOT, this.subQuestId, 0);
getOwner()
.getQuestManager()
.queueEvent(
QuestCond.QUEST_COND_STATE_EQUAL, this.subQuestId, this.state.getValue(), 0, 0, 0);
getOwner()
.getScene()
.triggerDungeonEvent(DungeonPassConditionType.DUNGEON_COND_FINISH_QUEST, getSubQuestId());
getOwner().getProgressManager().tryUnlockOpenStates();
if (ChapterData.endQuestChapterMap.containsKey(subQuestId)) {
mainQuest
.getOwner()
.sendPacket(
new PacketChapterStateNotify(
ChapterData.endQuestChapterMap.get(subQuestId).getId(),
ChapterStateOuterClass.ChapterState.CHAPTER_STATE_END));
}
// hard coding to give amber
if (getQuestData().getSubId() == 35402) {
getOwner().getInventory().addItem(1021, 1, ActionReason.QuestItem); // amber item id
}
this.save();
Grasscutter.getLogger().debug("Quest {} is finished", subQuestId);
}
// TODO
public void fail() {
this.state = QuestState.QUEST_STATE_FAILED;
this.finishTime = Utils.getCurrentSeconds();
this.getOwner().sendPacket(new PacketQuestListUpdateNotify(this));
// Some subQuests have conditions that subQuests fail (even from different MainQuests)
this.getOwner()
.getQuestManager()
.queueEvent(
QuestContent.QUEST_CONTENT_QUEST_STATE_EQUAL,
this.subQuestId,
this.state.getValue(),
0,
0,
0);
this.getOwner()
.getQuestManager()
.queueEvent(
QuestCond.QUEST_COND_STATE_EQUAL, this.subQuestId, this.state.getValue(), 0, 0, 0);
this.getQuestData()
.getFailExec()
.forEach(e -> getOwner().getServer().getQuestSystem().triggerExec(this, e, e.getParam()));
if (this.getQuestData().getTrialAvatarList() != null) {
this.getQuestData()
.getTrialAvatarList()
.forEach(t -> this.getOwner().getTeamManager().removeTrialAvatar(t));
}
Grasscutter.getLogger().debug("Quest {} is failed", subQuestId);
}
// Return true if it did the rewind
public boolean rewind(boolean notifyDelete) {
getMainQuest().getChildQuests().values().stream()
.filter(p -> p.getQuestData().getOrder() > this.getQuestData().getOrder())
.forEach(
q -> {
q.clearProgress(notifyDelete);
});
clearProgress(notifyDelete);
this.start();
return true;
}
public void save() {
getMainQuest().save();
}
public Quest toProto() {
Quest.Builder proto =
Quest.newBuilder()
.setQuestId(getSubQuestId())
.setState(getState().getValue())
.setParentQuestId(getMainQuestId())
.setStartTime(getStartTime())
.setStartGameTime(438)
.setAcceptTime(getAcceptTime());
if (getFinishProgressList() != null) {
for (int i : getFinishProgressList()) {
proto.addFinishProgressList(i);
}
}
if (getFailProgressList() != null) {
for (int i : getFailProgressList()) {
proto.addFailProgressList(i);
}
}
return proto.build();
}
}

View File

@ -7,10 +7,7 @@ import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.quest.enums.ParentQuestState;
import emu.grasscutter.game.quest.enums.QuestCond;
import emu.grasscutter.game.quest.enums.QuestContent;
import emu.grasscutter.game.quest.enums.QuestState;
import emu.grasscutter.game.quest.enums.*;
import emu.grasscutter.server.packet.send.PacketFinishedParentQuestUpdateNotify;
import emu.grasscutter.utils.Position;
import io.netty.util.concurrent.FastThreadLocalThread;
@ -19,6 +16,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import lombok.Getter;
import lombok.val;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
@ -86,13 +84,17 @@ public class QuestManager extends BasePlayerManager {
this.mainQuests = new Int2ObjectOpenHashMap<>();
}
// TODO store user value set on enable
public boolean isQuestingEnabled() {
return Grasscutter.getConfig().server.game.gameOptions.questing;
}
public void onPlayerBorn() {
// TODO scan the quest and start the quest with acceptCond fulfilled
// The off send 3 request in that order: 1. FinishedParentQuestNotify, 2. QuestListNotify, 3. ServerCondMeetQuestListUpdateNotify
List<GameMainQuest> newQuests = this.addMultMainQuests(newPlayerMainQuests);
for (GameMainQuest mainQuest : newQuests) {
startMainQuest(mainQuest.getParentQuestId());
if(this.isQuestingEnabled()) {
this.enableQuests();
}
//getPlayer().sendPacket(new PacketFinishedParentQuestUpdateNotify(newQuests));
@ -117,6 +119,8 @@ public class QuestManager extends BasePlayerManager {
}
quest.checkProgress();
}
player.getActivityManager().triggerActivityConditions();
}
public void onTick(){
@ -163,7 +167,8 @@ public class QuestManager extends BasePlayerManager {
}
public void enableQuests() {
onPlayerBorn();
this.triggerEvent(QuestCond.QUEST_COND_NONE, null, 0);
this.triggerEvent(QuestCond.QUEST_COND_PLAYER_LEVEL_EQUAL_GREATER, null, 1);
}
/*
@ -256,6 +261,11 @@ public class QuestManager extends BasePlayerManager {
return null;
}
return addQuest(questConfig);
}
public GameQuest addQuest(@Nonnull QuestData questConfig) {
// Main quest
GameMainQuest mainQuest = this.getMainQuestById(questConfig.getMainId());
@ -265,7 +275,7 @@ public class QuestManager extends BasePlayerManager {
}
// Sub quest
GameQuest quest = mainQuest.getChildQuestById(questId);
GameQuest quest = mainQuest.getChildQuestById(questConfig.getSubId());
// Forcefully start
quest.start();
@ -286,13 +296,12 @@ public class QuestManager extends BasePlayerManager {
.map(MainQuestData.SubQuestData::getSubId)
.ifPresent(this::addQuest);
//TODO find a better way then hardcoding to detect needed required quests
if(mainQuestId == 355){
startMainQuest(361);
startMainQuest(418);
startMainQuest(423);
startMainQuest(20509);
}
// if (mainQuestId == 355){
// startMainQuest(361);
// startMainQuest(418);
// startMainQuest(423);
// startMainQuest(20509);
// }
}
public void queueEvent(QuestCond condType, int... params) {
queueEvent(condType, "", params);
@ -312,13 +321,42 @@ public class QuestManager extends BasePlayerManager {
public void triggerEvent(QuestCond condType, String paramStr, int... params) {
Grasscutter.getLogger().debug("Trigger Event {}, {}, {}", condType, paramStr, params);
List<GameMainQuest> checkMainQuests = this.getMainQuests().values().stream()
.filter(i -> i.getState() != ParentQuestState.PARENT_QUEST_STATE_FINISHED)
.toList();
for (GameMainQuest mainquest : checkMainQuests) {
mainquest.tryAcceptSubQuests(condType, paramStr, params);
var potentialQuests = GameData.getQuestDataByConditions(condType, params[0], paramStr);
if(potentialQuests == null){
return;
}
var questSystem = getPlayer().getServer().getQuestSystem();
var owner = getPlayer();
potentialQuests.forEach(questData -> {
if(this.wasSubQuestStarted(questData)){
return;
}
val acceptCond = questData.getAcceptCond();
int[] accept = new int[acceptCond.size()];
for (int i = 0; i < acceptCond.size(); i++) {
val condition = acceptCond.get(i);
boolean result = questSystem.triggerCondition(owner, questData, condition, paramStr, params);
accept[i] = result ? 1 : 0;
}
boolean shouldAccept = LogicType.calculate(questData.getAcceptCondComb(), accept);
if (shouldAccept){
GameQuest quest = owner.getQuestManager().addQuest(questData);
Grasscutter.getLogger().debug("Added quest {} result {}", questData.getSubId(), quest !=null);
}
});
}
public boolean wasSubQuestStarted(QuestData questData) {
var quest = getQuestById(questData.getId());
if(quest == null) return false;
return quest.state != QuestState.QUEST_STATE_UNSTARTED;
}
public void triggerEvent(QuestContent condType, String paramStr, int... params) {
Grasscutter.getLogger().debug("Trigger Event {}, {}, {}", condType, paramStr, params);
List<GameMainQuest> checkMainQuests = this.getMainQuests().values().stream()
@ -332,6 +370,7 @@ public class QuestManager extends BasePlayerManager {
/**
* TODO maybe trigger them delayed to allow basic communication finish first
* TODO move content checks to use static informations where possible to allow direct already fulfilled checking
* @param quest
*/
public void checkQuestAlreadyFullfilled(GameQuest quest){
@ -355,6 +394,7 @@ public class QuestManager extends BasePlayerManager {
queueEvent(condition.getType(), condition.getParam()[0], condition.getParam()[1]);
}
}
case QUEST_CONTENT_PLAYER_LEVEL_UP -> queueEvent(condition.getType(), player.getLevel());
}
}
}, 1);

View File

@ -1,16 +1,19 @@
package emu.grasscutter.game.quest.content;
import static emu.grasscutter.game.quest.enums.QuestContent.QUEST_CONTENT_UNLOCK_TRANS_POINT;
import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.game.quest.GameQuest;
import emu.grasscutter.game.quest.QuestValueContent;
@QuestValueContent(QUEST_CONTENT_UNLOCK_TRANS_POINT)
public class ContentUnlockTransPoint extends BaseContent {
@Override
public boolean execute(
GameQuest quest, QuestData.QuestContentCondition condition, String paramStr, int... params) {
return condition.getParam()[0] == params[0] && condition.getParam()[1] == params[1];
}
}
package emu.grasscutter.game.quest.content;
import static emu.grasscutter.game.quest.enums.QuestContent.QUEST_CONTENT_UNLOCK_TRANS_POINT;
import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.game.quest.GameQuest;
import emu.grasscutter.game.quest.QuestValueContent;
@QuestValueContent(QUEST_CONTENT_UNLOCK_TRANS_POINT)
public class ContentUnlockTransPoint extends BaseContent {
@Override
public boolean execute(
GameQuest quest, QuestData.QuestContentCondition condition, String paramStr, int... params) {
var sceneId = condition.getParam()[0];
var scenePointId = condition.getParam()[1];
var scenePoints = quest.getOwner().getUnlockedScenePoints().get(sceneId);
return scenePoints != null && scenePoints.contains(scenePointId);
}
}

View File

@ -1,17 +1,17 @@
package emu.grasscutter.game.quest.exec;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.game.quest.GameQuest;
import emu.grasscutter.game.quest.QuestValueExec;
import emu.grasscutter.game.quest.enums.QuestExec;
import emu.grasscutter.game.quest.handlers.QuestExecHandler;
@QuestValueExec(QuestExec.QUEST_EXEC_ADD_CUR_AVATAR_ENERGY)
public class ExecAddCurAvatarEnergy extends QuestExecHandler {
@Override
public boolean execute(GameQuest quest, QuestData.QuestExecParam condition, String... paramStr) {
Grasscutter.getLogger().info("Energy refilled");
return quest.getOwner().getEnergyManager().refillActiveEnergy();
}
}
package emu.grasscutter.game.quest.exec;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.game.quest.GameQuest;
import emu.grasscutter.game.quest.QuestValueExec;
import emu.grasscutter.game.quest.enums.QuestExec;
import emu.grasscutter.game.quest.handlers.QuestExecHandler;
@QuestValueExec(QuestExec.QUEST_EXEC_ADD_CUR_AVATAR_ENERGY)
public class ExecAddCurAvatarEnergy extends QuestExecHandler {
@Override
public boolean execute(GameQuest quest, QuestData.QuestExecParam condition, String... paramStr) {
Grasscutter.getLogger().debug("Energy refilled");
return quest.getOwner().getEnergyManager().refillActiveEnergy();
}
}

View File

@ -319,12 +319,14 @@ public class World implements Iterable<Player> {
var newScene = this.getSceneById(teleportProperties.getSceneId());
newScene.addPlayer(player);
player.setAvatarsAbilityForScene(newScene);
// Dungeon
// Dungeon system is handling this already
// if(dungeonData!=null){
// var dungeonManager = new DungeonManager(newScene, dungeonData);
// dungeonManager.startDungeon();
// }
SceneConfig config = newScene.getScriptManager().getConfig();
if (teleportProperties.getTeleportTo() == null && config != null) {
if (config.born_pos != null) {

View File

@ -1,153 +1,160 @@
package emu.grasscutter.game.world;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.InvestigationMonsterData;
import emu.grasscutter.data.excels.RewardPreviewData;
import emu.grasscutter.data.excels.world.WorldLevelData;
import emu.grasscutter.game.entity.gadget.chest.BossChestInteractHandler;
import emu.grasscutter.game.entity.gadget.chest.ChestInteractHandler;
import emu.grasscutter.game.entity.gadget.chest.NormalChestInteractHandler;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.net.proto.InvestigationMonsterOuterClass;
import emu.grasscutter.scripts.data.SceneGroup;
import emu.grasscutter.scripts.data.SceneMonster;
import emu.grasscutter.server.game.BaseGameSystem;
import emu.grasscutter.server.game.GameServer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
public class WorldDataSystem extends BaseGameSystem {
private final Map<String, ChestInteractHandler> chestInteractHandlerMap; // chestType-Handler
private final Map<String, SceneGroup> sceneInvestigationGroupMap; // <sceneId_groupId, Group>
public WorldDataSystem(GameServer server) {
super(server);
this.chestInteractHandlerMap = new HashMap<>();
this.sceneInvestigationGroupMap = new ConcurrentHashMap<>();
loadChestConfig();
}
public synchronized void loadChestConfig() {
// set the special chest first
chestInteractHandlerMap.put("SceneObj_Chest_Flora", new BossChestInteractHandler());
try {
DataLoader.loadList("ChestReward.json", ChestReward.class)
.forEach(
reward ->
reward
.getObjNames()
.forEach(
name ->
chestInteractHandlerMap.computeIfAbsent(
name, x -> new NormalChestInteractHandler(reward))));
} catch (Exception e) {
Grasscutter.getLogger().error("Unable to load chest reward config.", e);
}
}
public Map<String, ChestInteractHandler> getChestInteractHandlerMap() {
return chestInteractHandlerMap;
}
public RewardPreviewData getRewardByBossId(int monsterId) {
var investigationMonsterData =
GameData.getInvestigationMonsterDataMap().values().parallelStream()
.filter(imd -> imd.getMonsterIdList() != null && !imd.getMonsterIdList().isEmpty())
.filter(imd -> imd.getMonsterIdList().get(0) == monsterId)
.findFirst();
if (investigationMonsterData.isEmpty()) {
return null;
}
return GameData.getRewardPreviewDataMap()
.get(investigationMonsterData.get().getRewardPreviewId());
}
private SceneGroup getInvestigationGroup(int sceneId, int groupId) {
var key = sceneId + "_" + groupId;
if (!sceneInvestigationGroupMap.containsKey(key)) {
var group = SceneGroup.of(groupId).load(sceneId);
sceneInvestigationGroupMap.putIfAbsent(key, group);
return group;
}
return sceneInvestigationGroupMap.get(key);
}
public int getMonsterLevel(SceneMonster monster, World world) {
// Calculate level
int level = monster.level;
WorldLevelData worldLevelData = GameData.getWorldLevelDataMap().get(world.getWorldLevel());
if (worldLevelData != null) {
level = worldLevelData.getMonsterLevel();
}
return level;
}
private InvestigationMonsterOuterClass.InvestigationMonster getInvestigationMonster(
Player player, InvestigationMonsterData imd) {
if (imd.getGroupIdList().isEmpty() || imd.getMonsterIdList().isEmpty()) {
return null;
}
var groupId = imd.getGroupIdList().get(0);
var monsterId = imd.getMonsterIdList().get(0);
var sceneId = imd.getCityData().getSceneId();
var group = getInvestigationGroup(sceneId, groupId);
if (group == null || group.monsters == null) {
return null;
}
var monster =
group.monsters.values().stream().filter(x -> x.monster_id == monsterId).findFirst();
if (monster.isEmpty()) {
return null;
}
var builder = InvestigationMonsterOuterClass.InvestigationMonster.newBuilder();
builder
.setId(imd.getId())
.setCityId(imd.getCityId())
.setSceneId(imd.getCityData().getSceneId())
.setGroupId(groupId)
.setMonsterId(monsterId)
.setLevel(getMonsterLevel(monster.get(), player.getWorld()))
.setIsAlive(true)
.setNextRefreshTime(Integer.MAX_VALUE)
.setRefreshInterval(Integer.MAX_VALUE)
.setPos(monster.get().pos.toProto());
if ("Boss".equals(imd.getMonsterCategory())) {
var bossChest = group.searchBossChestInGroup();
if (bossChest.isPresent()) {
builder.setResin(bossChest.get().resin);
builder.setMaxBossChestNum(bossChest.get().take_num);
}
}
return builder.build();
}
public List<InvestigationMonsterOuterClass.InvestigationMonster> getInvestigationMonstersByCityId(
Player player, int cityId) {
var cityData = GameData.getCityDataMap().get(cityId);
if (cityData == null) {
Grasscutter.getLogger().warn("City not exist {}", cityId);
return List.of();
}
return GameData.getInvestigationMonsterDataMap().values().parallelStream()
.filter(imd -> imd.getCityId() == cityId)
.map(imd -> this.getInvestigationMonster(player, imd))
.filter(Objects::nonNull)
.toList();
}
}
package emu.grasscutter.game.world;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.InvestigationMonsterData;
import emu.grasscutter.data.excels.RewardPreviewData;
import emu.grasscutter.data.excels.world.WorldLevelData;
import emu.grasscutter.game.entity.gadget.chest.BossChestInteractHandler;
import emu.grasscutter.game.entity.gadget.chest.ChestInteractHandler;
import emu.grasscutter.game.entity.gadget.chest.NormalChestInteractHandler;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.net.proto.InvestigationMonsterOuterClass;
import emu.grasscutter.scripts.data.SceneGroup;
import emu.grasscutter.scripts.data.SceneMonster;
import emu.grasscutter.server.game.BaseGameSystem;
import emu.grasscutter.server.game.GameServer;
import org.luaj.vm2.LuaError;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
public class WorldDataSystem extends BaseGameSystem {
private final Map<String, ChestInteractHandler> chestInteractHandlerMap; // chestType-Handler
private final Map<String, SceneGroup> sceneInvestigationGroupMap; // <sceneId_groupId, Group>
public WorldDataSystem(GameServer server) {
super(server);
this.chestInteractHandlerMap = new HashMap<>();
this.sceneInvestigationGroupMap = new ConcurrentHashMap<>();
loadChestConfig();
}
public synchronized void loadChestConfig() {
// set the special chest first
chestInteractHandlerMap.put("SceneObj_Chest_Flora", new BossChestInteractHandler());
try {
DataLoader.loadList("ChestReward.json", ChestReward.class)
.forEach(
reward ->
reward
.getObjNames()
.forEach(
name ->
chestInteractHandlerMap.computeIfAbsent(
name, x -> new NormalChestInteractHandler(reward))));
} catch (Exception e) {
Grasscutter.getLogger().error("Unable to load chest reward config.", e);
}
}
public Map<String, ChestInteractHandler> getChestInteractHandlerMap() {
return chestInteractHandlerMap;
}
public RewardPreviewData getRewardByBossId(int monsterId) {
var investigationMonsterData =
GameData.getInvestigationMonsterDataMap().values().parallelStream()
.filter(imd -> imd.getMonsterIdList() != null && !imd.getMonsterIdList().isEmpty())
.filter(imd -> imd.getMonsterIdList().get(0) == monsterId)
.findFirst();
if (investigationMonsterData.isEmpty()) {
return null;
}
return GameData.getRewardPreviewDataMap()
.get(investigationMonsterData.get().getRewardPreviewId());
}
private SceneGroup getInvestigationGroup(int sceneId, int groupId) {
var key = sceneId + "_" + groupId;
if (!sceneInvestigationGroupMap.containsKey(key)) {
try {
var group = SceneGroup.of(groupId).load(sceneId);
sceneInvestigationGroupMap.putIfAbsent(key, group);
return group;
} catch (LuaError luaError) {
Grasscutter.getLogger()
.error("failed to get investigationGroup {} in scene{}:", groupId, sceneId, luaError);
}
}
return sceneInvestigationGroupMap.get(key);
}
public int getMonsterLevel(SceneMonster monster, World world) {
// Calculate level
int level = monster.level;
WorldLevelData worldLevelData = GameData.getWorldLevelDataMap().get(world.getWorldLevel());
if (worldLevelData != null) {
level = worldLevelData.getMonsterLevel();
}
return level;
}
private InvestigationMonsterOuterClass.InvestigationMonster getInvestigationMonster(
Player player, InvestigationMonsterData imd) {
if (imd.getGroupIdList().isEmpty() || imd.getMonsterIdList().isEmpty()) {
return null;
}
var groupId = imd.getGroupIdList().get(0);
var monsterId = imd.getMonsterIdList().get(0);
var sceneId = imd.getCityData().getSceneId();
var group = getInvestigationGroup(sceneId, groupId);
if (group == null || group.monsters == null) {
return null;
}
var monster =
group.monsters.values().stream().filter(x -> x.monster_id == monsterId).findFirst();
if (monster.isEmpty()) {
return null;
}
var builder = InvestigationMonsterOuterClass.InvestigationMonster.newBuilder();
builder
.setId(imd.getId())
.setCityId(imd.getCityId())
.setSceneId(imd.getCityData().getSceneId())
.setGroupId(groupId)
.setMonsterId(monsterId)
.setLevel(getMonsterLevel(monster.get(), player.getWorld()))
.setIsAlive(true)
.setNextRefreshTime(Integer.MAX_VALUE)
.setRefreshInterval(Integer.MAX_VALUE)
.setPos(monster.get().pos.toProto());
if ("Boss".equals(imd.getMonsterCategory())) {
var bossChest = group.searchBossChestInGroup();
if (bossChest.isPresent()) {
builder.setResin(bossChest.get().resin);
builder.setMaxBossChestNum(bossChest.get().take_num);
}
}
return builder.build();
}
public List<InvestigationMonsterOuterClass.InvestigationMonster> getInvestigationMonstersByCityId(
Player player, int cityId) {
var cityData = GameData.getCityDataMap().get(cityId);
if (cityData == null) {
Grasscutter.getLogger().warn("City not exist {}", cityId);
return List.of();
}
return GameData.getInvestigationMonsterDataMap().values().parallelStream()
.filter(imd -> imd.getCityId() == cityId)
.map(imd -> this.getInvestigationMonster(player, imd))
.filter(Objects::nonNull)
.toList();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,152 +1,176 @@
package emu.grasscutter.scripts;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.props.EntityType;
import emu.grasscutter.game.quest.enums.QuestState;
import emu.grasscutter.scripts.constants.EventType;
import emu.grasscutter.scripts.constants.ScriptGadgetState;
import emu.grasscutter.scripts.constants.ScriptRegionShape;
import emu.grasscutter.scripts.data.SceneMeta;
import emu.grasscutter.scripts.serializer.LuaSerializer;
import emu.grasscutter.scripts.serializer.Serializer;
import emu.grasscutter.utils.FileUtils;
import java.io.File;
import java.io.FileReader;
import java.lang.ref.SoftReference;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.script.*;
import lombok.Getter;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import org.luaj.vm2.script.LuajContext;
public class ScriptLoader {
private static ScriptEngineManager sm;
@Getter private static ScriptEngine engine;
private static ScriptEngineFactory factory;
@Getter private static Serializer serializer;
@Getter private static ScriptLib scriptLib;
@Getter private static LuaValue scriptLibLua;
/** suggest GC to remove it if the memory is less */
private static final Map<String, SoftReference<CompiledScript>> scriptsCache =
new ConcurrentHashMap<>();
/** sceneId - SceneMeta */
private static final Map<Integer, SoftReference<SceneMeta>> sceneMetaCache =
new ConcurrentHashMap<>();
public static synchronized void init() throws Exception {
if (sm != null) {
throw new Exception("Script loader already initialized");
}
// Create script engine
sm = new ScriptEngineManager();
engine = sm.getEngineByName("luaj");
factory = getEngine().getFactory();
// Lua stuff
serializer = new LuaSerializer();
// Set engine to replace require as a temporary fix to missing scripts
LuajContext ctx = (LuajContext) engine.getContext();
ctx.globals.set(
"require",
new OneArgFunction() {
@Override
public LuaValue call(LuaValue arg0) {
return LuaValue.ZERO;
}
});
LuaTable table = new LuaTable();
Arrays.stream(EntityType.values())
.forEach(e -> table.set(e.name().toUpperCase(), e.getValue()));
ctx.globals.set("EntityType", table);
LuaTable table1 = new LuaTable();
Arrays.stream(QuestState.values())
.forEach(e -> table1.set(e.name().toUpperCase(), e.getValue()));
ctx.globals.set("QuestState", table1);
ctx.globals.set(
"EventType",
CoerceJavaToLua.coerce(
new EventType())); // TODO - make static class to avoid instantiating a new class every
// scene
ctx.globals.set("GadgetState", CoerceJavaToLua.coerce(new ScriptGadgetState()));
ctx.globals.set("RegionShape", CoerceJavaToLua.coerce(new ScriptRegionShape()));
scriptLib = new ScriptLib();
scriptLibLua = CoerceJavaToLua.coerce(scriptLib);
ctx.globals.set("ScriptLib", scriptLibLua);
}
public static <T> Optional<T> tryGet(SoftReference<T> softReference) {
try {
return Optional.ofNullable(softReference.get());
} catch (NullPointerException npe) {
return Optional.empty();
}
}
@Deprecated(forRemoval = true)
public static CompiledScript getScriptByPath(String path) {
var sc = tryGet(scriptsCache.get(path));
if (sc.isPresent()) {
return sc.get();
}
Grasscutter.getLogger().debug("Loading script " + path);
File file = new File(path);
if (!file.exists()) return null;
try (FileReader fr = new FileReader(file)) {
var script = ((Compilable) getEngine()).compile(fr);
scriptsCache.put(path, new SoftReference<>(script));
return script;
} catch (Exception e) {
Grasscutter.getLogger().error("Loading script {} failed!", path, e);
return null;
}
}
public static CompiledScript getScript(String path) {
var sc = tryGet(scriptsCache.get(path));
if (sc.isPresent()) {
return sc.get();
}
Grasscutter.getLogger().debug("Loading script " + path);
final Path scriptPath = FileUtils.getScriptPath(path);
if (!Files.exists(scriptPath)) return null;
try {
var script = ((Compilable) getEngine()).compile(Files.newBufferedReader(scriptPath));
scriptsCache.put(path, new SoftReference<>(script));
return script;
} catch (Exception e) {
Grasscutter.getLogger()
.error("Loading script {} failed! - {}", path, e.getLocalizedMessage());
return null;
}
}
public static SceneMeta getSceneMeta(int sceneId) {
return tryGet(sceneMetaCache.get(sceneId))
.orElseGet(
() -> {
var instance = SceneMeta.of(sceneId);
sceneMetaCache.put(sceneId, new SoftReference<>(instance));
return instance;
});
}
}
package emu.grasscutter.scripts;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.dungeons.challenge.enums.ChallengeEventMarkType;
import emu.grasscutter.game.dungeons.challenge.enums.FatherChallengeProperty;
import emu.grasscutter.game.props.ElementType;
import emu.grasscutter.game.props.EntityType;
import emu.grasscutter.game.quest.enums.QuestState;
import emu.grasscutter.scripts.constants.*;
import emu.grasscutter.scripts.data.SceneMeta;
import emu.grasscutter.scripts.serializer.LuaSerializer;
import emu.grasscutter.scripts.serializer.Serializer;
import emu.grasscutter.utils.FileUtils;
import java.io.File;
import java.io.FileReader;
import java.lang.ref.SoftReference;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.script.*;
import lombok.Getter;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import org.luaj.vm2.script.LuajContext;
public class ScriptLoader {
private static ScriptEngineManager sm;
@Getter private static ScriptEngine engine;
private static ScriptEngineFactory factory;
@Getter private static Serializer serializer;
@Getter private static ScriptLib scriptLib;
@Getter private static LuaValue scriptLibLua;
/** suggest GC to remove it if the memory is less */
private static final Map<String, SoftReference<CompiledScript>> scriptsCache =
new ConcurrentHashMap<>();
/** sceneId - SceneMeta */
private static final Map<Integer, SoftReference<SceneMeta>> sceneMetaCache =
new ConcurrentHashMap<>();
public static synchronized void init() throws Exception {
if (sm != null) {
throw new Exception("Script loader already initialized");
}
// Create script engine
sm = new ScriptEngineManager();
engine = sm.getEngineByName("luaj");
factory = getEngine().getFactory();
// Lua stuff
serializer = new LuaSerializer();
// Set engine to replace require as a temporary fix to missing scripts
LuajContext ctx = (LuajContext) engine.getContext();
ctx.globals.set(
"require",
new OneArgFunction() {
@Override
public LuaValue call(LuaValue arg0) {
return LuaValue.ZERO;
}
});
addEnumByIntValue(ctx, EntityType.values(), "EntityType");
addEnumByIntValue(ctx, QuestState.values(), "QuestState");
addEnumByIntValue(ctx, ElementType.values(), "ElementType");
addEnumByOrdinal(ctx, GroupKillPolicy.values(), "GroupKillPolicy");
addEnumByOrdinal(ctx, SealBattleType.values(), "SealBattleType");
addEnumByOrdinal(ctx, FatherChallengeProperty.values(), "FatherChallengeProperty");
addEnumByOrdinal(ctx, ChallengeEventMarkType.values(), "ChallengeEventMarkType");
ctx.globals.set(
"EventType",
CoerceJavaToLua.coerce(
new EventType())); // TODO - make static class to avoid instantiating a new class every
// scene
ctx.globals.set("GadgetState", CoerceJavaToLua.coerce(new ScriptGadgetState()));
ctx.globals.set("RegionShape", CoerceJavaToLua.coerce(new ScriptRegionShape()));
scriptLib = new ScriptLib();
scriptLibLua = CoerceJavaToLua.coerce(scriptLib);
ctx.globals.set("ScriptLib", scriptLibLua);
}
private static <T extends Enum<T>> void addEnumByOrdinal(
LuajContext ctx, T[] enumArray, String name) {
LuaTable table = new LuaTable();
Arrays.stream(enumArray)
.forEach(
e -> {
table.set(e.name(), e.ordinal());
table.set(e.name().toUpperCase(), e.ordinal());
});
ctx.globals.set(name, table);
}
private static <T extends Enum<T> & IntValueEnum> void addEnumByIntValue(
LuajContext ctx, T[] enumArray, String name) {
LuaTable table = new LuaTable();
Arrays.stream(enumArray)
.forEach(
e -> {
table.set(e.name(), e.getValue());
table.set(e.name().toUpperCase(), e.getValue());
});
ctx.globals.set(name, table);
}
public static <T> Optional<T> tryGet(SoftReference<T> softReference) {
try {
return Optional.ofNullable(softReference.get());
} catch (NullPointerException npe) {
return Optional.empty();
}
}
@Deprecated(forRemoval = true)
public static CompiledScript getScriptByPath(String path) {
var sc = tryGet(scriptsCache.get(path));
if (sc.isPresent()) {
return sc.get();
}
// Grasscutter.getLogger().debug("Loading script " + path);
File file = new File(path);
if (!file.exists()) return null;
try (FileReader fr = new FileReader(file)) {
var script = ((Compilable) getEngine()).compile(fr);
scriptsCache.put(path, new SoftReference<>(script));
return script;
} catch (Exception e) {
Grasscutter.getLogger().error("Loading script {} failed!", path, e);
return null;
}
}
public static CompiledScript getScript(String path) {
var sc = tryGet(scriptsCache.get(path));
if (sc.isPresent()) {
return sc.get();
}
// Grasscutter.getLogger().debug("Loading script " + path);
final Path scriptPath = FileUtils.getScriptPath(path);
if (!Files.exists(scriptPath)) return null;
try {
var script = ((Compilable) getEngine()).compile(Files.newBufferedReader(scriptPath));
scriptsCache.put(path, new SoftReference<>(script));
return script;
} catch (Exception e) {
Grasscutter.getLogger()
.error("Loading script {} failed! - {}", path, e.getLocalizedMessage());
return null;
}
}
public static SceneMeta getSceneMeta(int sceneId) {
return tryGet(sceneMetaCache.get(sceneId))
.orElseGet(
() -> {
var instance = SceneMeta.of(sceneId);
sceneMetaCache.put(sceneId, new SoftReference<>(instance));
return instance;
});
}
}

View File

@ -1,86 +1,87 @@
package emu.grasscutter.scripts.data;
import com.github.davidmoten.rtreemulti.RTree;
import com.github.davidmoten.rtreemulti.geometry.Geometry;
import com.github.davidmoten.rtreemulti.geometry.Rectangle;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.scripts.SceneIndexManager;
import emu.grasscutter.scripts.ScriptLoader;
import emu.grasscutter.utils.Position;
import java.util.Map;
import java.util.stream.Collectors;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptException;
import lombok.Setter;
import lombok.ToString;
@ToString
@Setter
public class SceneBlock {
public int id;
public Position max;
public Position min;
public int sceneId;
public Map<Integer, SceneGroup> groups;
public RTree<SceneGroup, Geometry> sceneGroupIndex;
private transient boolean loaded; // Not an actual variable in the scripts either
public boolean isLoaded() {
return this.loaded;
}
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
public boolean contains(Position pos) {
return pos.getX() <= this.max.getX()
&& pos.getX() >= this.min.getX()
&& pos.getZ() <= this.max.getZ()
&& pos.getZ() >= this.min.getZ();
}
public SceneBlock load(int sceneId, Bindings bindings) {
if (this.loaded) {
return this;
}
this.sceneId = sceneId;
this.setLoaded(true);
CompiledScript cs =
ScriptLoader.getScript(
"Scene/" + sceneId + "/scene" + sceneId + "_block" + this.id + ".lua");
if (cs == null) {
return null;
}
// Eval script
try {
cs.eval(bindings);
// Set groups
this.groups =
ScriptLoader.getSerializer().toList(SceneGroup.class, bindings.get("groups")).stream()
.collect(Collectors.toMap(x -> x.id, y -> y, (a, b) -> a));
this.groups.values().forEach(g -> g.block_id = this.id);
this.sceneGroupIndex =
SceneIndexManager.buildIndex(3, this.groups.values(), g -> g.pos.toPoint());
} catch (ScriptException exception) {
Grasscutter.getLogger()
.error(
"An error occurred while loading block " + this.id + " in scene " + sceneId,
exception);
}
Grasscutter.getLogger().debug("Successfully loaded block {} in scene {}.", this.id, sceneId);
return this;
}
public Rectangle toRectangle() {
return Rectangle.create(this.min.toXZDoubleArray(), this.max.toXZDoubleArray());
}
}
package emu.grasscutter.scripts.data;
import com.github.davidmoten.rtreemulti.RTree;
import com.github.davidmoten.rtreemulti.geometry.Geometry;
import com.github.davidmoten.rtreemulti.geometry.Rectangle;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.scripts.SceneIndexManager;
import emu.grasscutter.scripts.ScriptLoader;
import emu.grasscutter.utils.Position;
import java.util.Map;
import java.util.stream.Collectors;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptException;
import lombok.Setter;
import lombok.ToString;
@ToString
@Setter
public class SceneBlock {
public int id;
public Position max;
public Position min;
public int sceneId;
public Map<Integer, SceneGroup> groups;
public RTree<SceneGroup, Geometry> sceneGroupIndex;
private transient boolean loaded; // Not an actual variable in the scripts either
public boolean isLoaded() {
return this.loaded;
}
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
public boolean contains(Position pos) {
int range = Grasscutter.getConfig().server.game.loadEntitiesForPlayerRange;
return pos.getX() <= (this.max.getX() + range)
&& pos.getX() >= (this.min.getX() - range)
&& pos.getZ() <= (this.max.getZ() + range)
&& pos.getZ() >= (this.min.getZ() - range);
}
public SceneBlock load(int sceneId, Bindings bindings) {
if (this.loaded) {
return this;
}
this.sceneId = sceneId;
this.setLoaded(true);
CompiledScript cs =
ScriptLoader.getScript(
"Scene/" + sceneId + "/scene" + sceneId + "_block" + this.id + ".lua");
if (cs == null) {
return null;
}
// Eval script
try {
cs.eval(bindings);
// Set groups
this.groups =
ScriptLoader.getSerializer().toList(SceneGroup.class, bindings.get("groups")).stream()
.collect(Collectors.toMap(x -> x.id, y -> y, (a, b) -> a));
this.groups.values().forEach(g -> g.block_id = this.id);
this.sceneGroupIndex =
SceneIndexManager.buildIndex(3, this.groups.values(), g -> g.pos.toPoint());
} catch (ScriptException exception) {
Grasscutter.getLogger()
.error(
"An error occurred while loading block " + this.id + " in scene " + sceneId,
exception);
}
Grasscutter.getLogger().debug("Successfully loaded block {} in scene {}.", this.id, sceneId);
return this;
}
public Rectangle toRectangle() {
return Rectangle.create(this.min.toXZDoubleArray(), this.max.toXZDoubleArray());
}
}

View File

@ -1,246 +1,268 @@
package emu.grasscutter.scripts.serializer;
import com.esotericsoftware.reflectasm.ConstructorAccess;
import com.esotericsoftware.reflectasm.MethodAccess;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.scripts.ScriptUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.FieldDefaults;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
public class LuaSerializer implements Serializer {
private static final Map<Class<?>, MethodAccess> methodAccessCache = new ConcurrentHashMap<>();
private static final Map<Class<?>, ConstructorAccess<?>> constructorCache =
new ConcurrentHashMap<>();
private static final Map<Class<?>, Map<String, FieldMeta>> fieldMetaCache =
new ConcurrentHashMap<>();
@Override
public <T> List<T> toList(Class<T> type, Object obj) {
return serializeList(type, (LuaTable) obj);
}
@Override
public <T> T toObject(Class<T> type, Object obj) {
return serialize(type, (LuaTable) obj);
}
@Override
public <T> Map<String, T> toMap(Class<T> type, Object obj) {
return serializeMap(type, (LuaTable) obj);
}
private <T> Map<String, T> serializeMap(Class<T> type, LuaTable table) {
Map<String, T> map = new HashMap<>();
if (table == null) {
return map;
}
try {
LuaValue[] keys = table.keys();
for (LuaValue k : keys) {
try {
LuaValue keyValue = table.get(k);
T object = null;
if (keyValue.istable()) {
object = serialize(type, keyValue.checktable());
} else if (keyValue.isint()) {
object = (T) (Integer) keyValue.toint();
} else if (keyValue.isnumber()) {
object = (T) (Float) keyValue.tofloat(); // terrible...
} else if (keyValue.isstring()) {
object = (T) keyValue.tojstring();
} else if (keyValue.isboolean()) {
object = (T) (Boolean) keyValue.toboolean();
} else {
object = (T) keyValue;
}
if (object != null) {
map.put(String.valueOf(k), object);
}
} catch (Exception ex) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public <T> List<T> serializeList(Class<T> type, LuaTable table) {
List<T> list = new ArrayList<>();
if (table == null) {
return list;
}
try {
LuaValue[] keys = table.keys();
for (LuaValue k : keys) {
try {
LuaValue keyValue = table.get(k);
T object = null;
if (keyValue.istable()) {
object = serialize(type, keyValue.checktable());
} else if (keyValue.isint()) {
object = (T) (Integer) keyValue.toint();
} else if (keyValue.isnumber()) {
object = (T) (Float) keyValue.tofloat(); // terrible...
} else if (keyValue.isstring()) {
object = (T) keyValue.tojstring();
} else if (keyValue.isboolean()) {
object = (T) (Boolean) keyValue.toboolean();
} else {
object = (T) keyValue;
}
if (object != null) {
list.add(object);
}
} catch (Exception ex) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public <T> T serialize(Class<T> type, LuaTable table) {
T object = null;
if (type == List.class) {
try {
Class<T> listType = (Class<T>) type.getTypeParameters()[0].getClass();
return (T) serializeList(listType, table);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
try {
if (!methodAccessCache.containsKey(type)) {
cacheType(type);
}
var methodAccess = methodAccessCache.get(type);
var fieldMetaMap = fieldMetaCache.get(type);
object = (T) constructorCache.get(type).newInstance();
if (table == null) {
return object;
}
LuaValue[] keys = table.keys();
for (LuaValue k : keys) {
try {
var keyName = k.checkjstring();
if (!fieldMetaMap.containsKey(keyName)) {
continue;
}
var fieldMeta = fieldMetaMap.get(keyName);
LuaValue keyValue = table.get(k);
if (keyValue.istable()) {
methodAccess.invoke(
object, fieldMeta.index, serialize(fieldMeta.getType(), keyValue.checktable()));
} else if (fieldMeta.getType().equals(float.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.tofloat());
} else if (fieldMeta.getType().equals(int.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.toint());
} else if (fieldMeta.getType().equals(String.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.tojstring());
} else if (fieldMeta.getType().equals(boolean.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.toboolean());
} else {
methodAccess.invoke(object, fieldMeta.index, keyValue.tojstring());
}
} catch (Exception ex) {
// ex.printStackTrace();
continue;
}
}
} catch (Exception e) {
Grasscutter.getLogger().debug(ScriptUtils.toMap(table).toString());
e.printStackTrace();
}
return object;
}
public <T> Map<String, FieldMeta> cacheType(Class<T> type) {
if (fieldMetaCache.containsKey(type)) {
return fieldMetaCache.get(type);
}
if (!constructorCache.containsKey(type)) {
constructorCache.putIfAbsent(type, ConstructorAccess.get(type));
}
var methodAccess =
Optional.ofNullable(methodAccessCache.get(type)).orElse(MethodAccess.get(type));
methodAccessCache.putIfAbsent(type, methodAccess);
var fieldMetaMap = new HashMap<String, FieldMeta>();
var methodNameSet = new HashSet<>(Arrays.stream(methodAccess.getMethodNames()).toList());
Arrays.stream(type.getDeclaredFields())
.filter(field -> methodNameSet.contains(getSetterName(field.getName())))
.forEach(
field -> {
var setter = getSetterName(field.getName());
var index = methodAccess.getIndex(setter);
fieldMetaMap.put(
field.getName(), new FieldMeta(field.getName(), setter, index, field.getType()));
});
Arrays.stream(type.getFields())
.filter(field -> !fieldMetaMap.containsKey(field.getName()))
.filter(field -> methodNameSet.contains(getSetterName(field.getName())))
.forEach(
field -> {
var setter = getSetterName(field.getName());
var index = methodAccess.getIndex(setter);
fieldMetaMap.put(
field.getName(), new FieldMeta(field.getName(), setter, index, field.getType()));
});
fieldMetaCache.put(type, fieldMetaMap);
return fieldMetaMap;
}
public String getSetterName(String fieldName) {
if (fieldName == null || fieldName.length() == 0) {
return null;
}
if (fieldName.length() == 1) {
return "set" + fieldName.toUpperCase();
}
return "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
}
@Data
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
static class FieldMeta {
String name;
String setter;
int index;
Class<?> type;
}
}
package emu.grasscutter.scripts.serializer;
import com.esotericsoftware.reflectasm.ConstructorAccess;
import com.esotericsoftware.reflectasm.MethodAccess;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.scripts.ScriptUtils;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.FieldDefaults;
import org.jetbrains.annotations.Nullable;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
public class LuaSerializer implements Serializer {
private static final Map<Class<?>, MethodAccess> methodAccessCache = new ConcurrentHashMap<>();
private static final Map<Class<?>, ConstructorAccess<?>> constructorCache =
new ConcurrentHashMap<>();
private static final Map<Class<?>, Map<String, FieldMeta>> fieldMetaCache =
new ConcurrentHashMap<>();
@Override
public <T> List<T> toList(Class<T> type, Object obj) {
return serializeList(type, (LuaTable) obj);
}
@Override
public <T> T toObject(Class<T> type, Object obj) {
return serialize(type, null, (LuaTable) obj);
}
@Override
public <T> Map<String, T> toMap(Class<T> type, Object obj) {
return serializeMap(type, (LuaTable) obj);
}
private <T> Map<String, T> serializeMap(Class<T> type, LuaTable table) {
Map<String, T> map = new HashMap<>();
if (table == null) {
return map;
}
try {
LuaValue[] keys = table.keys();
for (LuaValue k : keys) {
try {
LuaValue keyValue = table.get(k);
T object = null;
if (keyValue.istable()) {
object = serialize(type, null, keyValue.checktable());
} else if (keyValue.isint()) {
object = (T) (Integer) keyValue.toint();
} else if (keyValue.isnumber()) {
object = (T) (Float) keyValue.tofloat(); // terrible...
} else if (keyValue.isstring()) {
object = (T) keyValue.tojstring();
} else if (keyValue.isboolean()) {
object = (T) (Boolean) keyValue.toboolean();
} else {
object = (T) keyValue;
}
if (object != null) {
map.put(String.valueOf(k), object);
}
} catch (Exception ex) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public <T> List<T> serializeList(Class<T> type, LuaTable table) {
List<T> list = new ArrayList<>();
if (table == null) {
return list;
}
try {
LuaValue[] keys = table.keys();
for (LuaValue k : keys) {
try {
LuaValue keyValue = table.get(k);
T object = null;
if (keyValue.istable()) {
object = serialize(type, null, keyValue.checktable());
} else if (keyValue.isint()) {
object = (T) (Integer) keyValue.toint();
} else if (keyValue.isnumber()) {
object = (T) (Float) keyValue.tofloat(); // terrible...
} else if (keyValue.isstring()) {
object = (T) keyValue.tojstring();
} else if (keyValue.isboolean()) {
object = (T) (Boolean) keyValue.toboolean();
} else {
object = (T) keyValue;
}
if (object != null) {
list.add(object);
}
} catch (Exception ex) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
private Class<?> getListType(Class<?> type, @Nullable Field field) {
if (field == null) {
return type.getTypeParameters()[0].getClass();
}
Type fieldType = field.getGenericType();
if (fieldType instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) fieldType).getActualTypeArguments()[0];
}
return null;
}
public <T> T serialize(Class<T> type, @Nullable Field field, LuaTable table) {
T object = null;
if (type == List.class) {
try {
Class<?> listType = getListType(type, field);
return (T) serializeList(listType, table);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
try {
if (!methodAccessCache.containsKey(type)) {
cacheType(type);
}
var methodAccess = methodAccessCache.get(type);
var fieldMetaMap = fieldMetaCache.get(type);
object = (T) constructorCache.get(type).newInstance();
if (table == null) {
return object;
}
LuaValue[] keys = table.keys();
for (LuaValue k : keys) {
try {
var keyName = k.checkjstring();
if (!fieldMetaMap.containsKey(keyName)) {
continue;
}
var fieldMeta = fieldMetaMap.get(keyName);
LuaValue keyValue = table.get(k);
if (keyValue.istable()) {
methodAccess.invoke(
object,
fieldMeta.index,
serialize(fieldMeta.getType(), fieldMeta.getField(), keyValue.checktable()));
} else if (fieldMeta.getType().equals(float.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.tofloat());
} else if (fieldMeta.getType().equals(int.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.toint());
} else if (fieldMeta.getType().equals(String.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.tojstring());
} else if (fieldMeta.getType().equals(boolean.class)) {
methodAccess.invoke(object, fieldMeta.index, keyValue.toboolean());
} else {
methodAccess.invoke(object, fieldMeta.index, keyValue.tojstring());
}
} catch (Exception ex) {
// ex.printStackTrace();
continue;
}
}
} catch (Exception e) {
Grasscutter.getLogger().debug(ScriptUtils.toMap(table).toString());
e.printStackTrace();
}
return object;
}
public <T> Map<String, FieldMeta> cacheType(Class<T> type) {
if (fieldMetaCache.containsKey(type)) {
return fieldMetaCache.get(type);
}
if (!constructorCache.containsKey(type)) {
constructorCache.putIfAbsent(type, ConstructorAccess.get(type));
}
var methodAccess =
Optional.ofNullable(methodAccessCache.get(type)).orElse(MethodAccess.get(type));
methodAccessCache.putIfAbsent(type, methodAccess);
var fieldMetaMap = new HashMap<String, FieldMeta>();
var methodNameSet = new HashSet<>(Arrays.stream(methodAccess.getMethodNames()).toList());
Arrays.stream(type.getDeclaredFields())
.filter(field -> methodNameSet.contains(getSetterName(field.getName())))
.forEach(
field -> {
var setter = getSetterName(field.getName());
var index = methodAccess.getIndex(setter);
fieldMetaMap.put(
field.getName(),
new FieldMeta(field.getName(), setter, index, field.getType(), field));
});
Arrays.stream(type.getFields())
.filter(field -> !fieldMetaMap.containsKey(field.getName()))
.filter(field -> methodNameSet.contains(getSetterName(field.getName())))
.forEach(
field -> {
var setter = getSetterName(field.getName());
var index = methodAccess.getIndex(setter);
fieldMetaMap.put(
field.getName(),
new FieldMeta(field.getName(), setter, index, field.getType(), field));
});
fieldMetaCache.put(type, fieldMetaMap);
return fieldMetaMap;
}
public String getSetterName(String fieldName) {
if (fieldName == null || fieldName.length() == 0) {
return null;
}
if (fieldName.length() == 1) {
return "set" + fieldName.toUpperCase();
}
return "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
}
@Data
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
static class FieldMeta {
String name;
String setter;
int index;
Class<?> type;
@Nullable Field field;
}
}

View File

@ -1,279 +1,281 @@
package emu.grasscutter.server.game;
import static emu.grasscutter.config.Configuration.GAME_INFO;
import static emu.grasscutter.utils.Language.translate;
import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.game.battlepass.BattlePassSystem;
import emu.grasscutter.game.chat.ChatSystem;
import emu.grasscutter.game.chat.ChatSystemHandler;
import emu.grasscutter.game.combine.CombineManger;
import emu.grasscutter.game.drop.DropSystem;
import emu.grasscutter.game.dungeons.DungeonSystem;
import emu.grasscutter.game.expedition.ExpeditionSystem;
import emu.grasscutter.game.gacha.GachaSystem;
import emu.grasscutter.game.managers.cooking.CookingCompoundManager;
import emu.grasscutter.game.managers.cooking.CookingManager;
import emu.grasscutter.game.managers.energy.EnergyManager;
import emu.grasscutter.game.managers.stamina.StaminaManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.quest.QuestSystem;
import emu.grasscutter.game.shop.ShopSystem;
import emu.grasscutter.game.systems.AnnouncementSystem;
import emu.grasscutter.game.systems.InventorySystem;
import emu.grasscutter.game.systems.MultiplayerSystem;
import emu.grasscutter.game.tower.TowerSystem;
import emu.grasscutter.game.world.World;
import emu.grasscutter.game.world.WorldDataSystem;
import emu.grasscutter.net.packet.PacketHandler;
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
import emu.grasscutter.server.event.game.ServerTickEvent;
import emu.grasscutter.server.event.internal.ServerStartEvent;
import emu.grasscutter.server.event.internal.ServerStopEvent;
import emu.grasscutter.server.event.types.ServerEvent;
import emu.grasscutter.server.scheduler.ServerTaskScheduler;
import emu.grasscutter.task.TaskMap;
import java.net.InetSocketAddress;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import kcp.highway.ChannelConfig;
import kcp.highway.KcpServer;
import lombok.Getter;
@Getter
public final class GameServer extends KcpServer {
// Game server base
private final InetSocketAddress address;
private final GameServerPacketHandler packetHandler;
private final Map<Integer, Player> players;
private final Set<World> worlds;
// Server systems
private final InventorySystem inventorySystem;
private final GachaSystem gachaSystem;
private final ShopSystem shopSystem;
private final MultiplayerSystem multiplayerSystem;
private final DungeonSystem dungeonSystem;
private final ExpeditionSystem expeditionSystem;
private final DropSystem dropSystem;
private final WorldDataSystem worldDataSystem;
private final BattlePassSystem battlePassSystem;
private final CombineManger combineSystem;
private final TowerSystem towerSystem;
private final AnnouncementSystem announcementSystem;
private final QuestSystem questSystem;
// Extra
private final ServerTaskScheduler scheduler;
private final TaskMap taskMap;
private ChatSystemHandler chatManager;
public GameServer() {
this(getAdapterInetSocketAddress());
}
public GameServer(InetSocketAddress address) {
ChannelConfig channelConfig = new ChannelConfig();
channelConfig.nodelay(true, GAME_INFO.kcpInterval, 2, true);
channelConfig.setMtu(1400);
channelConfig.setSndwnd(256);
channelConfig.setRcvwnd(256);
channelConfig.setTimeoutMillis(30 * 1000); // 30s
channelConfig.setUseConvChannel(true);
channelConfig.setAckNoDelay(false);
this.init(GameSessionManager.getListener(), channelConfig, address);
EnergyManager.initialize();
StaminaManager.initialize();
CookingManager.initialize();
CookingCompoundManager.initialize();
CombineManger.initialize();
// Game Server base
this.address = address;
this.packetHandler = new GameServerPacketHandler(PacketHandler.class);
this.players = new ConcurrentHashMap<>();
this.worlds = Collections.synchronizedSet(new HashSet<>());
// Extra
this.scheduler = new ServerTaskScheduler();
this.taskMap = new TaskMap(true);
// Create game systems
this.inventorySystem = new InventorySystem(this);
this.gachaSystem = new GachaSystem(this);
this.shopSystem = new ShopSystem(this);
this.multiplayerSystem = new MultiplayerSystem(this);
this.dungeonSystem = new DungeonSystem(this);
this.dropSystem = new DropSystem(this);
this.expeditionSystem = new ExpeditionSystem(this);
this.combineSystem = new CombineManger(this);
this.towerSystem = new TowerSystem(this);
this.worldDataSystem = new WorldDataSystem(this);
this.battlePassSystem = new BattlePassSystem(this);
this.announcementSystem = new AnnouncementSystem(this);
this.questSystem = new QuestSystem(this);
// Chata manager
this.chatManager = new ChatSystem(this);
// Hook into shutdown event.
Runtime.getRuntime().addShutdownHook(new Thread(this::onServerShutdown));
}
private static InetSocketAddress getAdapterInetSocketAddress() {
InetSocketAddress inetSocketAddress;
if (GAME_INFO.bindAddress.equals("")) {
inetSocketAddress = new InetSocketAddress(GAME_INFO.bindPort);
} else {
inetSocketAddress = new InetSocketAddress(GAME_INFO.bindAddress, GAME_INFO.bindPort);
}
return inetSocketAddress;
}
@Deprecated
public ChatSystemHandler getChatManager() {
return chatManager;
}
@Deprecated
public void setChatManager(ChatSystemHandler chatManager) {
this.chatManager = chatManager;
}
public ChatSystemHandler getChatSystem() {
return chatManager;
}
public void setChatSystem(ChatSystemHandler chatManager) {
this.chatManager = chatManager;
}
public void registerPlayer(Player player) {
getPlayers().put(player.getUid(), player);
}
public Player getPlayerByUid(int id) {
return this.getPlayerByUid(id, false);
}
public Player getPlayerByUid(int id, boolean allowOfflinePlayers) {
// Console check
if (id == GameConstants.SERVER_CONSOLE_UID) {
return null;
}
// Get from online players
Player player = this.getPlayers().get(id);
if (!allowOfflinePlayers) {
return player;
}
// Check database if character isnt here
if (player == null) {
player = DatabaseHelper.getPlayerByUid(id);
}
return player;
}
public Player getPlayerByAccountId(String accountId) {
Optional<Player> playerOpt =
getPlayers().values().stream()
.filter(player -> player.getAccount().getId().equals(accountId))
.findFirst();
return playerOpt.orElse(null);
}
public SocialDetail.Builder getSocialDetailByUid(int id) {
// Get from online players
Player player = this.getPlayerByUid(id, true);
if (player == null) {
return null;
}
return player.getSocialDetail();
}
public Account getAccountByName(String username) {
Optional<Player> playerOpt =
getPlayers().values().stream()
.filter(player -> player.getAccount().getUsername().equals(username))
.findFirst();
if (playerOpt.isPresent()) {
return playerOpt.get().getAccount();
}
return DatabaseHelper.getAccountByName(username);
}
public synchronized void onTick() {
var tickStart = Instant.now();
// Tick worlds.
this.worlds.removeIf(World::onTick);
// Tick players.
this.players.values().forEach(Player::onTick);
// Tick scheduler.
this.getScheduler().runTasks();
// Call server tick event.
ServerTickEvent event = new ServerTickEvent(tickStart, Instant.now());
event.call();
}
public void registerWorld(World world) {
this.getWorlds().add(world);
}
public void deregisterWorld(World world) {
// TODO Auto-generated method stub
}
public void start() {
// Schedule game loop.
Timer gameLoop = new Timer();
gameLoop.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
try {
onTick();
} catch (Exception e) {
Grasscutter.getLogger().error(translate("messages.game.game_update_error"), e);
}
}
},
new Date(),
1000L);
Grasscutter.getLogger().info(translate("messages.status.free_software"));
Grasscutter.getLogger()
.info(translate("messages.game.address_bind", GAME_INFO.accessAddress, address.getPort()));
ServerStartEvent event = new ServerStartEvent(ServerEvent.Type.GAME, OffsetDateTime.now());
event.call();
}
public void onServerShutdown() {
ServerStopEvent event = new ServerStopEvent(ServerEvent.Type.GAME, OffsetDateTime.now());
event.call();
// Kick and save all players
List<Player> list = new ArrayList<>(this.getPlayers().size());
list.addAll(this.getPlayers().values());
for (Player player : list) {
player.getSession().close();
}
}
}
package emu.grasscutter.server.game;
import static emu.grasscutter.config.Configuration.GAME_INFO;
import static emu.grasscutter.utils.Language.translate;
import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.game.battlepass.BattlePassSystem;
import emu.grasscutter.game.chat.ChatSystem;
import emu.grasscutter.game.chat.ChatSystemHandler;
import emu.grasscutter.game.combine.CombineManger;
import emu.grasscutter.game.drop.DropSystem;
import emu.grasscutter.game.dungeons.DungeonSystem;
import emu.grasscutter.game.expedition.ExpeditionSystem;
import emu.grasscutter.game.gacha.GachaSystem;
import emu.grasscutter.game.managers.cooking.CookingCompoundManager;
import emu.grasscutter.game.managers.cooking.CookingManager;
import emu.grasscutter.game.managers.energy.EnergyManager;
import emu.grasscutter.game.managers.stamina.StaminaManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.quest.QuestSystem;
import emu.grasscutter.game.shop.ShopSystem;
import emu.grasscutter.game.systems.AnnouncementSystem;
import emu.grasscutter.game.systems.InventorySystem;
import emu.grasscutter.game.systems.MultiplayerSystem;
import emu.grasscutter.game.tower.TowerSystem;
import emu.grasscutter.game.world.World;
import emu.grasscutter.game.world.WorldDataSystem;
import emu.grasscutter.net.packet.PacketHandler;
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
import emu.grasscutter.server.event.game.ServerTickEvent;
import emu.grasscutter.server.event.internal.ServerStartEvent;
import emu.grasscutter.server.event.internal.ServerStopEvent;
import emu.grasscutter.server.event.types.ServerEvent;
import emu.grasscutter.server.scheduler.ServerTaskScheduler;
import emu.grasscutter.task.TaskMap;
import java.net.InetSocketAddress;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import kcp.highway.ChannelConfig;
import kcp.highway.KcpServer;
import lombok.Getter;
@Getter
public final class GameServer extends KcpServer {
// Game server base
private final InetSocketAddress address;
private final GameServerPacketHandler packetHandler;
private final Map<Integer, Player> players;
private final Set<World> worlds;
// Server systems
private final InventorySystem inventorySystem;
private final GachaSystem gachaSystem;
private final ShopSystem shopSystem;
private final MultiplayerSystem multiplayerSystem;
private final DungeonSystem dungeonSystem;
private final ExpeditionSystem expeditionSystem;
private final DropSystem dropSystem;
private final WorldDataSystem worldDataSystem;
private final BattlePassSystem battlePassSystem;
private final CombineManger combineSystem;
private final TowerSystem towerSystem;
private final AnnouncementSystem announcementSystem;
private final QuestSystem questSystem;
// Extra
private final ServerTaskScheduler scheduler;
private final TaskMap taskMap;
private ChatSystemHandler chatManager;
public GameServer() {
this(getAdapterInetSocketAddress());
}
public GameServer(InetSocketAddress address) {
ChannelConfig channelConfig = new ChannelConfig();
channelConfig.nodelay(true, GAME_INFO.kcpInterval, 2, true);
channelConfig.setMtu(1400);
channelConfig.setSndwnd(256);
channelConfig.setRcvwnd(256);
channelConfig.setTimeoutMillis(30 * 1000); // 30s
channelConfig.setUseConvChannel(true);
channelConfig.setAckNoDelay(false);
this.init(GameSessionManager.getListener(), channelConfig, address);
EnergyManager.initialize();
StaminaManager.initialize();
CookingManager.initialize();
CookingCompoundManager.initialize();
CombineManger.initialize();
// Game Server base
this.address = address;
this.packetHandler = new GameServerPacketHandler(PacketHandler.class);
this.players = new ConcurrentHashMap<>();
this.worlds = Collections.synchronizedSet(new HashSet<>());
// Extra
this.scheduler = new ServerTaskScheduler();
this.taskMap = new TaskMap(true);
// Create game systems
this.inventorySystem = new InventorySystem(this);
this.gachaSystem = new GachaSystem(this);
this.shopSystem = new ShopSystem(this);
this.multiplayerSystem = new MultiplayerSystem(this);
this.dungeonSystem = new DungeonSystem(this);
this.dropSystem = new DropSystem(this);
this.expeditionSystem = new ExpeditionSystem(this);
this.combineSystem = new CombineManger(this);
this.towerSystem = new TowerSystem(this);
this.worldDataSystem = new WorldDataSystem(this);
this.battlePassSystem = new BattlePassSystem(this);
this.announcementSystem = new AnnouncementSystem(this);
this.questSystem = new QuestSystem(this);
// Chata manager
this.chatManager = new ChatSystem(this);
// Hook into shutdown event.
Runtime.getRuntime().addShutdownHook(new Thread(this::onServerShutdown));
}
private static InetSocketAddress getAdapterInetSocketAddress() {
InetSocketAddress inetSocketAddress;
if (GAME_INFO.bindAddress.equals("")) {
inetSocketAddress = new InetSocketAddress(GAME_INFO.bindPort);
} else {
inetSocketAddress = new InetSocketAddress(GAME_INFO.bindAddress, GAME_INFO.bindPort);
}
return inetSocketAddress;
}
@Deprecated
public ChatSystemHandler getChatManager() {
return chatManager;
}
@Deprecated
public void setChatManager(ChatSystemHandler chatManager) {
this.chatManager = chatManager;
}
public ChatSystemHandler getChatSystem() {
return chatManager;
}
public void setChatSystem(ChatSystemHandler chatManager) {
this.chatManager = chatManager;
}
public void registerPlayer(Player player) {
getPlayers().put(player.getUid(), player);
}
public Player getPlayerByUid(int id) {
return this.getPlayerByUid(id, false);
}
public Player getPlayerByUid(int id, boolean allowOfflinePlayers) {
// Console check
if (id == GameConstants.SERVER_CONSOLE_UID) {
return null;
}
// Get from online players
Player player = this.getPlayers().get(id);
if (!allowOfflinePlayers) {
return player;
}
// Check database if character isnt here
if (player == null) {
player = DatabaseHelper.getPlayerByUid(id);
}
return player;
}
public Player getPlayerByAccountId(String accountId) {
Optional<Player> playerOpt =
getPlayers().values().stream()
.filter(player -> player.getAccount().getId().equals(accountId))
.findFirst();
return playerOpt.orElse(null);
}
public SocialDetail.Builder getSocialDetailByUid(int id) {
// Get from online players
Player player = this.getPlayerByUid(id, true);
if (player == null) {
return null;
}
return player.getSocialDetail();
}
public Account getAccountByName(String username) {
Optional<Player> playerOpt =
getPlayers().values().stream()
.filter(player -> player.getAccount().getUsername().equals(username))
.findFirst();
if (playerOpt.isPresent()) {
return playerOpt.get().getAccount();
}
return DatabaseHelper.getAccountByName(username);
}
public synchronized void onTick() {
var tickStart = Instant.now();
// Tick worlds.
this.worlds.removeIf(World::onTick);
// Tick players.
this.players.values().forEach(Player::onTick);
// Tick scheduler.
this.getScheduler().runTasks();
// Call server tick event.
ServerTickEvent event = new ServerTickEvent(tickStart, Instant.now());
event.call();
}
public void registerWorld(World world) {
this.getWorlds().add(world);
}
public void deregisterWorld(World world) {
// TODO Auto-generated method stub
world.save(); //Save the player's world
}
public void start() {
// Schedule game loop.
Timer gameLoop = new Timer();
gameLoop.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
try {
onTick();
} catch (Exception e) {
Grasscutter.getLogger().error(translate("messages.game.game_update_error"), e);
}
}
},
new Date(),
1000L);
Grasscutter.getLogger().info(translate("messages.status.free_software"));
Grasscutter.getLogger()
.info(translate("messages.game.address_bind", GAME_INFO.accessAddress, address.getPort()));
ServerStartEvent event = new ServerStartEvent(ServerEvent.Type.GAME, OffsetDateTime.now());
event.call();
}
public void onServerShutdown() {
ServerStopEvent event = new ServerStopEvent(ServerEvent.Type.GAME, OffsetDateTime.now());
event.call();
// Kick and save all players
List<Player> list = new ArrayList<>(this.getPlayers().size());
list.addAll(this.getPlayers().values());
for (Player player : list) {
player.getSession().close();
}
getWorlds().forEach(World::save);
}
}

View File

@ -1,45 +1,61 @@
package emu.grasscutter.server.packet.recv;
import emu.grasscutter.game.quest.GameMainQuest;
import emu.grasscutter.net.packet.Opcodes;
import emu.grasscutter.net.packet.PacketHandler;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.QuestUpdateQuestVarReqOuterClass;
import emu.grasscutter.net.proto.QuestVarOpOuterClass;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.server.packet.send.PacketQuestUpdateQuestVarRsp;
import java.util.List;
@Opcodes(PacketOpcodes.QuestUpdateQuestVarReq)
public class HandlerQuestUpdateQuestVarReq extends PacketHandler {
@Override
public void handle(GameSession session, byte[] header, byte[] payload) throws Exception {
// Client sends packets. One with the value, and one with the index and the new value to
// set/inc/dec
var req = QuestUpdateQuestVarReqOuterClass.QuestUpdateQuestVarReq.parseFrom(payload);
GameMainQuest mainQuest =
session.getPlayer().getQuestManager().getMainQuestById(req.getQuestId() / 100);
List<QuestVarOpOuterClass.QuestVarOp> questVars = req.getQuestVarOpListList();
if (mainQuest.getQuestVarsUpdate().size() == 0) {
for (QuestVarOpOuterClass.QuestVarOp questVar : questVars) {
mainQuest.getQuestVarsUpdate().add(questVar.getValue());
}
} else {
for (QuestVarOpOuterClass.QuestVarOp questVar : questVars) {
if (questVar.getIsAdd()) {
if (questVar.getValue() >= 0) {
mainQuest.incQuestVar(questVar.getIndex(), questVar.getValue());
} else {
mainQuest.decQuestVar(questVar.getIndex(), questVar.getValue());
}
} else {
mainQuest.setQuestVar(questVar.getIndex(), mainQuest.getQuestVarsUpdate().get(0));
}
// remove the first element from the update list
mainQuest.getQuestVarsUpdate().remove(0);
}
}
session.send(new PacketQuestUpdateQuestVarRsp(req.getQuestId()));
}
}
package emu.grasscutter.server.packet.recv;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.net.packet.Opcodes;
import emu.grasscutter.net.packet.PacketHandler;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.QuestUpdateQuestVarReqOuterClass.QuestUpdateQuestVarReq;
import emu.grasscutter.net.proto.QuestVarOpOuterClass.QuestVarOp;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.server.packet.send.PacketQuestUpdateQuestVarRsp;
import java.util.List;
@Opcodes(PacketOpcodes.QuestUpdateQuestVarReq)
public class HandlerQuestUpdateQuestVarReq extends PacketHandler {
@Override
public void handle(GameSession session, byte[] header, byte[] payload) throws Exception {
// Client sends packets. One with the value, and one with the index and the new value to
// set/inc/dec
var req = QuestUpdateQuestVarReq.parseFrom(payload);
var questManager = session.getPlayer().getQuestManager();
var subQuest = questManager.getQuestById(req.getQuestId());
var mainQuest = questManager.getMainQuestById(req.getParentQuestId());
if (mainQuest == null && subQuest != null) {
mainQuest = subQuest.getMainQuest();
}
if (mainQuest == null) {
session.send(new PacketQuestUpdateQuestVarRsp(req, Retcode.RET_QUEST_NOT_EXIST));
Grasscutter.getLogger()
.debug(
"trying to update QuestVar for non existing quest s{} m{}",
req.getQuestId(),
req.getParentQuestId());
return;
}
List<QuestVarOp> questVars = req.getQuestVarOpListList();
var questVarUpdate = mainQuest.getQuestVarsUpdate();
if (questVarUpdate.size() == 0) {
for (var questVar : questVars) {
questVarUpdate.add(questVar.getValue());
}
} else {
for (QuestVarOp questVar : questVars) {
if (questVar.getIsAdd()) {
if (questVar.getValue() >= 0) {
mainQuest.incQuestVar(questVar.getIndex(), questVar.getValue());
} else {
mainQuest.decQuestVar(questVar.getIndex(), questVar.getValue());
}
} else {
mainQuest.setQuestVar(questVar.getIndex(), questVarUpdate.get(0));
}
// remove the first element from the update list
questVarUpdate.remove(0);
}
}
session.send(new PacketQuestUpdateQuestVarRsp(req));
}
}

View File

@ -1,17 +1,25 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.PlayerEnterDungeonRspOuterClass.PlayerEnterDungeonRsp;
public class PacketPlayerEnterDungeonRsp extends BasePacket {
public PacketPlayerEnterDungeonRsp(int pointId, int dungeonId) {
super(PacketOpcodes.PlayerEnterDungeonRsp);
PlayerEnterDungeonRsp proto =
PlayerEnterDungeonRsp.newBuilder().setPointId(pointId).setDungeonId(dungeonId).build();
this.setData(proto);
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.PlayerEnterDungeonRspOuterClass.PlayerEnterDungeonRsp;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
public class PacketPlayerEnterDungeonRsp extends BasePacket {
public PacketPlayerEnterDungeonRsp(int pointId, int dungeonId, boolean success) {
super(PacketOpcodes.PlayerEnterDungeonRsp);
PlayerEnterDungeonRsp proto =
PlayerEnterDungeonRsp.newBuilder()
.setPointId(pointId)
.setDungeonId(dungeonId)
.setRetcode(
success
? Retcode.RET_SUCC_VALUE
: Retcode.RET_FAIL_VALUE)
.build();
this.setData(proto);
}
}

View File

@ -1,32 +1,33 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.PlayerHomeCompInfoNotifyOuterClass;
import emu.grasscutter.net.proto.PlayerHomeCompInfoOuterClass;
public class PacketPlayerHomeCompInfoNotify extends BasePacket {
public PacketPlayerHomeCompInfoNotify(Player player) {
super(PacketOpcodes.PlayerHomeCompInfoNotify);
if (player.getRealmList() == null) {
// Do not send
return;
}
PlayerHomeCompInfoNotifyOuterClass.PlayerHomeCompInfoNotify proto =
PlayerHomeCompInfoNotifyOuterClass.PlayerHomeCompInfoNotify.newBuilder()
.setCompInfo(
PlayerHomeCompInfoOuterClass.PlayerHomeCompInfo.newBuilder()
.addAllUnlockedModuleIdList(player.getRealmList())
.addAllSeenModuleIdList(player.getSeenRealmList())
.addAllLevelupRewardGotLevelList(player.getHomeRewardedLevels())
.setFriendEnterHomeOptionValue(player.getHome().getEnterHomeOption())
.build())
.build();
this.setData(proto);
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.PlayerHomeCompInfoNotifyOuterClass;
import emu.grasscutter.net.proto.PlayerHomeCompInfoOuterClass;
import java.util.List;
public class PacketPlayerHomeCompInfoNotify extends BasePacket {
public PacketPlayerHomeCompInfoNotify(Player player) {
super(PacketOpcodes.PlayerHomeCompInfoNotify);
if (player.getRealmList() == null) {
// Do not send
return;
}
PlayerHomeCompInfoNotifyOuterClass.PlayerHomeCompInfoNotify proto =
PlayerHomeCompInfoNotifyOuterClass.PlayerHomeCompInfoNotify.newBuilder()
.setCompInfo(
PlayerHomeCompInfoOuterClass.PlayerHomeCompInfo.newBuilder()
.addAllUnlockedModuleIdList(player.getRealmList())
.addAllLevelupRewardGotLevelList(List.of(1)) // Hardcoded
.setFriendEnterHomeOptionValue(player.getHome().getEnterHomeOption())
.build())
.build();
this.setData(proto);
}
}

View File

@ -1,13 +1,16 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
public class PacketPlayerSetPauseRsp extends BasePacket {
public PacketPlayerSetPauseRsp(int clientSequence) {
super(PacketOpcodes.PlayerSetPauseRsp);
this.buildHeader(clientSequence);
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.PlayerSetPauseRspOuterClass.PlayerSetPauseRsp;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
public class PacketPlayerSetPauseRsp extends BasePacket {
public PacketPlayerSetPauseRsp() {
super(PacketOpcodes.PlayerSetPauseRsp);
this.setData(PlayerSetPauseRsp.newBuilder()
.setRetcode(Retcode.RET_SUCC_VALUE));
}
}

View File

@ -1,19 +1,27 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.Opcodes;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.QuestUpdateQuestVarRspOuterClass;
@Opcodes(PacketOpcodes.QuestUpdateQuestVarReq)
public class PacketQuestUpdateQuestVarRsp extends BasePacket {
public PacketQuestUpdateQuestVarRsp(int questId) {
super(PacketOpcodes.QuestUpdateQuestVarRsp);
var rsp =
QuestUpdateQuestVarRspOuterClass.QuestUpdateQuestVarRsp.newBuilder()
.setQuestId(questId)
.build();
this.setData(rsp);
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.Opcodes;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.QuestUpdateQuestVarReqOuterClass.QuestUpdateQuestVarReq;
import emu.grasscutter.net.proto.QuestUpdateQuestVarRspOuterClass;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
@Opcodes(PacketOpcodes.QuestUpdateQuestVarReq)
public class PacketQuestUpdateQuestVarRsp extends BasePacket {
public PacketQuestUpdateQuestVarRsp(QuestUpdateQuestVarReq req) {
this(req, Retcode.RET_SUCC);
}
public PacketQuestUpdateQuestVarRsp(QuestUpdateQuestVarReq req, Retcode retcode) {
super(PacketOpcodes.QuestUpdateQuestVarRsp);
var rsp =
QuestUpdateQuestVarRspOuterClass.QuestUpdateQuestVarRsp.newBuilder()
.setQuestId(req.getQuestId())
.setParentQuestId(req.getParentQuestId())
.setRetcode(retcode.getNumber())
.build();
this.setData(rsp);
}
}

View File

@ -1,31 +1,29 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.ScenePointUnlockNotifyOuterClass.ScenePointUnlockNotify;
public class PacketScenePointUnlockNotify extends BasePacket {
public PacketScenePointUnlockNotify(int sceneId, int pointId) {
super(PacketOpcodes.ScenePointUnlockNotify);
ScenePointUnlockNotify.Builder p =
ScenePointUnlockNotify.newBuilder()
.setSceneId(sceneId)
.addPointList(pointId)
.addUnhidePointList(pointId);
this.setData(p);
}
public PacketScenePointUnlockNotify(int sceneId, Iterable<Integer> pointIds) {
super(PacketOpcodes.ScenePointUnlockNotify);
ScenePointUnlockNotify.Builder p =
ScenePointUnlockNotify.newBuilder()
.setSceneId(sceneId)
.addAllPointList(pointIds)
.addAllUnhidePointList(pointIds);
this.setData(p);
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.ScenePointUnlockNotifyOuterClass.ScenePointUnlockNotify;
public class PacketScenePointUnlockNotify extends BasePacket {
public PacketScenePointUnlockNotify(int sceneId, int pointId) {
super(PacketOpcodes.ScenePointUnlockNotify);
ScenePointUnlockNotify.Builder p =
ScenePointUnlockNotify.newBuilder()
.setSceneId(sceneId)
.addPointList(pointId);
this.setData(p);
}
public PacketScenePointUnlockNotify(int sceneId, Iterable<Integer> pointIds) {
super(PacketOpcodes.ScenePointUnlockNotify);
ScenePointUnlockNotify.Builder p =
ScenePointUnlockNotify.newBuilder()
.setSceneId(sceneId)
.addAllPointList(pointIds);
this.setData(p);
}
}

View File

@ -1,36 +1,27 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.SceneTimeNotifyOuterClass.SceneTimeNotify;
public class PacketSceneTimeNotify extends BasePacket {
public PacketSceneTimeNotify(Player player) {
super(PacketOpcodes.SceneTimeNotify);
var proto =
SceneTimeNotify.newBuilder()
.setIsPaused(player.isPaused())
.setSceneId(player.getSceneId())
.setSceneTime(player.getScene().getSceneTime())
.build();
this.setData(proto);
}
public PacketSceneTimeNotify(Scene scene) {
super(PacketOpcodes.SceneTimeNotify);
var proto =
SceneTimeNotify.newBuilder()
.setSceneId(scene.getId())
.setSceneTime(scene.getSceneTime())
.setIsPaused(scene.isPaused())
.build();
this.setData(proto);
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.SceneTimeNotifyOuterClass.SceneTimeNotify;
public class PacketSceneTimeNotify extends BasePacket {
public PacketSceneTimeNotify(Player player) {
this(player.getScene());
}
public PacketSceneTimeNotify(Scene scene) {
super(PacketOpcodes.SceneTimeNotify);
var proto =
SceneTimeNotify.newBuilder()
.setSceneId(scene.getId())
.setSceneTime(scene.getSceneTime())
.setIsPaused(scene.isPaused())
.build();
this.setData(proto);
}
}

View File

@ -1,18 +1,29 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.UnlockPersonalLineRspOuterClass;
public class PacketUnlockPersonalLineRsp extends BasePacket {
public PacketUnlockPersonalLineRsp(int id, int level, int chapterId) {
super(PacketOpcodes.UnlockPersonalLineRsp);
var proto = UnlockPersonalLineRspOuterClass.UnlockPersonalLineRsp.newBuilder();
proto.setPersonalLineId(id).setLevel(level).setChapterId(chapterId);
this.setData(proto);
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
import emu.grasscutter.net.proto.UnlockPersonalLineRspOuterClass;
public class PacketUnlockPersonalLineRsp extends BasePacket {
public PacketUnlockPersonalLineRsp(int id, int level, int chapterId) {
super(PacketOpcodes.UnlockPersonalLineRsp);
var proto = UnlockPersonalLineRspOuterClass.UnlockPersonalLineRsp.newBuilder();
proto.setPersonalLineId(id).setLevel(level).setChapterId(chapterId);
this.setData(proto);
}
public PacketUnlockPersonalLineRsp(int id, Retcode retCode) {
super(PacketOpcodes.UnlockPersonalLineRsp);
var proto = UnlockPersonalLineRspOuterClass.UnlockPersonalLineRsp.newBuilder();
proto.setPersonalLineId(id).setRetcode(retCode.getNumber());
this.setData(proto);
}
}

View File

@ -1,67 +1,73 @@
package emu.grasscutter.server.packet.send;
import emu.grasscutter.game.entity.EntityVehicle;
import emu.grasscutter.game.entity.GameEntity;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.VehicleInteractRspOuterClass.VehicleInteractRsp;
import emu.grasscutter.net.proto.VehicleInteractTypeOuterClass.VehicleInteractType;
import emu.grasscutter.net.proto.VehicleMemberOuterClass.VehicleMember;
public class PacketVehicleInteractRsp extends BasePacket {
public PacketVehicleInteractRsp(Player player, int entityId, VehicleInteractType interactType) {
super(PacketOpcodes.VehicleInteractRsp);
VehicleInteractRsp.Builder proto = VehicleInteractRsp.newBuilder();
GameEntity vehicle = player.getScene().getEntityById(entityId);
if (vehicle instanceof EntityVehicle) {
proto.setEntityId(vehicle.getId());
VehicleMember vehicleMember =
VehicleMember.newBuilder()
.setUid(player.getUid())
.setAvatarGuid(player.getTeamManager().getCurrentCharacterGuid())
.build();
proto.setInteractType(interactType);
proto.setMember(vehicleMember);
switch (interactType) {
case VEHICLE_INTERACT_TYPE_IN -> {
((EntityVehicle) vehicle).getVehicleMembers().add(vehicleMember);
}
case VEHICLE_INTERACT_TYPE_OUT -> {
((EntityVehicle) vehicle).getVehicleMembers().remove(vehicleMember);
}
default -> {}
}
}
this.setData(proto.build());
}
public PacketVehicleInteractRsp(
EntityVehicle vehicle, VehicleMember vehicleMember, VehicleInteractType interactType) {
super(PacketOpcodes.VehicleInteractRsp);
VehicleInteractRsp.Builder proto = VehicleInteractRsp.newBuilder();
if (vehicle != null) {
proto.setEntityId(vehicle.getId());
proto.setInteractType(interactType);
proto.setMember(vehicleMember);
switch (interactType) {
case VEHICLE_INTERACT_TYPE_IN -> {
vehicle.getVehicleMembers().add(vehicleMember);
}
case VEHICLE_INTERACT_TYPE_OUT -> {
vehicle.getVehicleMembers().remove(vehicleMember);
}
default -> {}
}
}
this.setData(proto.build());
}
}
package emu.grasscutter.server.packet.send;
import emu.grasscutter.game.entity.EntityVehicle;
import emu.grasscutter.game.entity.GameEntity;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.quest.enums.QuestContent;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.VehicleInteractRspOuterClass.VehicleInteractRsp;
import emu.grasscutter.net.proto.VehicleInteractTypeOuterClass.VehicleInteractType;
import emu.grasscutter.net.proto.VehicleMemberOuterClass.VehicleMember;
public class PacketVehicleInteractRsp extends BasePacket {
public PacketVehicleInteractRsp(Player player, int entityId, VehicleInteractType interactType) {
super(PacketOpcodes.VehicleInteractRsp);
VehicleInteractRsp.Builder proto = VehicleInteractRsp.newBuilder();
GameEntity vehicle = player.getScene().getEntityById(entityId);
if (vehicle instanceof EntityVehicle) {
proto.setEntityId(vehicle.getId());
VehicleMember vehicleMember =
VehicleMember.newBuilder()
.setUid(player.getUid())
.setAvatarGuid(player.getTeamManager().getCurrentCharacterGuid())
.build();
proto.setInteractType(interactType);
proto.setMember(vehicleMember);
switch (interactType) {
case VEHICLE_INTERACT_TYPE_IN -> {
((EntityVehicle) vehicle).getVehicleMembers().add(vehicleMember);
player
.getQuestManager()
.queueEvent(
QuestContent.QUEST_CONTENT_ENTER_VEHICLE,
((EntityVehicle) vehicle).getGadgetId());
}
case VEHICLE_INTERACT_TYPE_OUT -> {
((EntityVehicle) vehicle).getVehicleMembers().remove(vehicleMember);
}
default -> {}
}
}
this.setData(proto.build());
}
public PacketVehicleInteractRsp(
EntityVehicle vehicle, VehicleMember vehicleMember, VehicleInteractType interactType) {
super(PacketOpcodes.VehicleInteractRsp);
VehicleInteractRsp.Builder proto = VehicleInteractRsp.newBuilder();
if (vehicle != null) {
proto.setEntityId(vehicle.getId());
proto.setInteractType(interactType);
proto.setMember(vehicleMember);
switch (interactType) {
case VEHICLE_INTERACT_TYPE_IN -> {
vehicle.getVehicleMembers().add(vehicleMember);
}
case VEHICLE_INTERACT_TYPE_OUT -> {
vehicle.getVehicleMembers().remove(vehicleMember);
}
default -> {}
}
}
this.setData(proto.build());
}
}

View File

@ -1,62 +1,66 @@
package emu.grasscutter.server.scheduler;
import emu.grasscutter.Grasscutter;
import lombok.Getter;
/** This class works the same as a runnable, except with more information. */
public final class ServerTask implements Runnable {
/* The runnable to run. */
private final Runnable runnable;
/* This ID is assigned by the scheduler. */
@Getter private final int taskId;
/* The period at which the task should be run. */
/* The delay between the first execute. */
private final int period, delay;
/* The amount of times the task has been run. */
@Getter private int ticks = 0;
/* Should the check consider delay? */
private boolean considerDelay = true;
public ServerTask(Runnable runnable, int taskId, int period, int delay) {
this.runnable = runnable;
this.taskId = taskId;
this.period = period;
this.delay = delay;
}
/** Cancels the task from running the next time. */
public void cancel() {
Grasscutter.getGameServer().getScheduler().cancelTask(this.taskId);
}
/**
* Checks if the task should run at the current tick.
*
* @return True if the task should run, false otherwise.
*/
public boolean shouldRun() {
if (this.delay != -1 && this.considerDelay) {
this.considerDelay = false;
return this.ticks == this.delay;
} else if (this.period != -1) return this.ticks % this.period == 0;
else return true;
}
/**
* Checks if the task should be canceled.
*
* @return True if the task should be canceled, false otherwise.
*/
public boolean shouldCancel() {
return this.period == -1;
}
/** Runs the task. */
@Override
public void run() {
// Run the runnable.
this.runnable.run();
// Increase tick count.
this.ticks++;
}
}
package emu.grasscutter.server.scheduler;
import emu.grasscutter.Grasscutter;
import lombok.Getter;
/** This class works the same as a runnable, except with more information. */
public final class ServerTask implements Runnable {
/* The runnable to run. */
private final Runnable runnable;
/* This ID is assigned by the scheduler. */
@Getter private final int taskId;
/* The period at which the task should be run. */
/* The delay between the first execute. */
private final int period, delay;
/* The amount of times the task has been run. */
@Getter private int ticks = 0;
/* Should the check consider delay? */
private boolean considerDelay = true;
public ServerTask(Runnable runnable, int taskId, int period, int delay) {
this.runnable = runnable;
this.taskId = taskId;
this.period = period;
this.delay = delay;
}
/** Cancels the task from running the next time. */
public void cancel() {
Grasscutter.getGameServer().getScheduler().cancelTask(this.taskId);
}
/**
* Checks if the task should run at the current tick.
*
* @return True if the task should run, false otherwise.
*/
public boolean shouldRun() {
// Increase tick count.
var ticks = this.ticks++;
if (this.delay != -1 && this.considerDelay) {
this.considerDelay = false;
return ticks == this.delay;
} else if (this.period != -1) return ticks % this.period == 0;
else return true;
}
/**
* Checks if the task should be canceled.
*
* @return True if the task should be canceled, false otherwise.
*/
public boolean shouldCancel() {
return this.period == -1 && ticks >= delay;
}
/** Runs the task. */
@Override
public void run() {
// Run the runnable.
try {
this.runnable.run();
} catch (Exception ex) {
Grasscutter.getLogger().error("Exception during task: ", ex);
}
}
}

View File

@ -1,16 +1,14 @@
package emu.grasscutter.task;
import org.quartz.Job;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
@PersistJobDataAfterExecution
public abstract class TaskHandler implements Job {
public void restartExecute() throws JobExecutionException {
execute(null);
}
public abstract void onEnable();
public abstract void onDisable();
}
package emu.grasscutter.task;
import org.quartz.*;
@PersistJobDataAfterExecution
public abstract class TaskHandler implements Job {
public void restartExecute() throws JobExecutionException {
execute(null);
}
public abstract void onEnable();
public abstract void onDisable();
}

View File

@ -1,391 +1,394 @@
package emu.grasscutter.tools;
import static emu.grasscutter.utils.FileUtils.getResourcePath;
import static emu.grasscutter.utils.Language.getTextMapKey;
import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.command.CommandHandler;
import emu.grasscutter.command.CommandMap;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.ResourceLoader;
import emu.grasscutter.data.excels.ItemData;
import emu.grasscutter.data.excels.achievement.AchievementData;
import emu.grasscutter.data.excels.avatar.AvatarData;
import emu.grasscutter.game.inventory.MaterialType;
import emu.grasscutter.utils.Language;
import emu.grasscutter.utils.Language.TextStrings;
import it.unimi.dsi.fastutil.ints.Int2IntRBTreeMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectRBTreeMap;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import lombok.val;
public final class Tools {
/**
* This generates the GM handbooks with a message by default.
*
* @throws Exception If an error occurs while generating the handbooks.
*/
public static void createGmHandbooks() throws Exception {
Tools.createGmHandbooks(true);
}
/**
* Generates a GM handbook for each language.
*
* @param message Should a message be printed to the console?
* @throws Exception If an error occurs while generating the handbooks.
*/
public static void createGmHandbooks(boolean message) throws Exception {
val languages = Language.TextStrings.getLanguages();
ResourceLoader.loadAll();
val mainQuestTitles =
new Int2IntRBTreeMap(
GameData.getMainQuestDataMap().int2ObjectEntrySet().stream()
.collect(
Collectors.toMap(
e -> e.getIntKey(), e -> (int) e.getValue().getTitleTextMapHash())));
// val questDescs = new
// Int2IntRBTreeMap(GameData.getQuestDataMap().int2ObjectEntrySet().stream().collect(Collectors.toMap(e -> (int) e.getIntKey(), e -> (int) e.getValue().getDescTextMapHash())));
val avatarDataMap = new Int2ObjectRBTreeMap<>(GameData.getAvatarDataMap());
val itemDataMap = new Int2ObjectRBTreeMap<>(GameData.getItemDataMap());
val monsterDataMap = new Int2ObjectRBTreeMap<>(GameData.getMonsterDataMap());
val sceneDataMap = new Int2ObjectRBTreeMap<>(GameData.getSceneDataMap());
val questDataMap = new Int2ObjectRBTreeMap<>(GameData.getQuestDataMap());
val achievementDataMap = new Int2ObjectRBTreeMap<>(GameData.getAchievementDataMap());
Function<SortedMap<?, ?>, String> getPad = m -> "%" + m.lastKey().toString().length() + "s : ";
// Create builders and helper functions
val handbookBuilders =
IntStream.range(0, TextStrings.NUM_LANGUAGES).mapToObj(i -> new StringBuilder()).toList();
var h =
new Object() {
void newLine(String line) {
handbookBuilders.forEach(b -> b.append(line + "\n"));
}
void newSection(String title) {
newLine("\n\n// " + title);
}
void newTranslatedLine(String template, TextStrings... textstrings) {
for (int i = 0; i < TextStrings.NUM_LANGUAGES; i++) {
String s = template;
for (int j = 0; j < textstrings.length; j++)
s = s.replace("{" + j + "}", textstrings[j].strings[i]);
handbookBuilders.get(i).append(s + "\n");
}
}
void newTranslatedLine(String template, long... hashes) {
newTranslatedLine(
template,
LongStream.of(hashes)
.mapToObj(hash -> getTextMapKey(hash))
.toArray(TextStrings[]::new));
}
};
// Preamble
h.newLine("// Grasscutter " + GameConstants.VERSION + " GM Handbook");
h.newLine(
"// Created "
+ DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now()));
// Commands
h.newSection("Commands");
final List<CommandHandler> cmdList = CommandMap.getInstance().getHandlersAsList();
final String padCmdLabel =
"%"
+ cmdList.stream()
.map(CommandHandler::getLabel)
.map(String::length)
.max(Integer::compare)
.get()
+ "s : ";
for (CommandHandler cmd : cmdList) {
final String label = padCmdLabel.formatted(cmd.getLabel());
final String descKey = cmd.getDescriptionKey();
for (int i = 0; i < TextStrings.NUM_LANGUAGES; i++) {
String desc =
languages.get(i).get(descKey).replace("\n", "\n\t\t\t\t").replace("\t", " ");
handbookBuilders.get(i).append(label + desc + "\n");
}
}
// Avatars
h.newSection("Avatars");
val avatarPre = getPad.apply(avatarDataMap);
avatarDataMap.forEach(
(id, data) ->
h.newTranslatedLine(avatarPre.formatted(id) + "{0}", data.getNameTextMapHash()));
// Items
h.newSection("Items");
val itemPre = getPad.apply(itemDataMap);
itemDataMap.forEach(
(id, data) -> {
val name = getTextMapKey(data.getNameTextMapHash());
if (Objects.requireNonNull(data.getMaterialType()) == MaterialType.MATERIAL_BGM) {
val bgmName =
Optional.ofNullable(data.getItemUse())
.map(u -> u.get(0))
.map(u -> u.getUseParam())
.filter(u -> u.length > 0)
.map(u -> Integer.parseInt(u[0]))
.map(bgmId -> GameData.getHomeWorldBgmDataMap().get(bgmId))
.map(bgm -> bgm.getBgmNameTextMapHash())
.map(hash -> getTextMapKey(hash));
if (bgmName.isPresent()) {
h.newTranslatedLine(itemPre.formatted(id) + "{0} - {1}", name, bgmName.get());
return;
} // Fall-through
}
h.newTranslatedLine(itemPre.formatted(id) + "{0}", name);
});
// Monsters
h.newSection("Monsters");
val monsterPre = getPad.apply(monsterDataMap);
monsterDataMap.forEach(
(id, data) ->
h.newTranslatedLine(
monsterPre.formatted(id) + data.getMonsterName() + " - {0}",
data.getNameTextMapHash()));
// Scenes - no translations
h.newSection("Scenes");
val padSceneId = getPad.apply(sceneDataMap);
sceneDataMap.forEach((id, data) -> h.newLine(padSceneId.formatted(id) + data.getScriptData()));
// Quests
h.newSection("Quests");
val padQuestId = getPad.apply(questDataMap);
questDataMap.forEach(
(id, data) ->
h.newTranslatedLine(
padQuestId.formatted(id) + "{0} - {1}",
mainQuestTitles.get(data.getMainId()),
data.getDescTextMapHash()));
// Achievements
h.newSection("Achievements");
val padAchievementId = getPad.apply(achievementDataMap);
achievementDataMap.values().stream()
.filter(AchievementData::isUsed)
.forEach(
data -> {
h.newTranslatedLine(
padAchievementId.formatted(data.getId()) + "{0} - {1}",
data.getTitleTextMapHash(),
data.getDescTextMapHash());
});
// Write txt files
for (int i = 0; i < TextStrings.NUM_LANGUAGES; i++) {
File GMHandbookOutputpath = new File("./GM Handbook");
GMHandbookOutputpath.mkdir();
final String fileName =
"./GM Handbook/GM Handbook - %s.txt".formatted(TextStrings.ARR_LANGUAGES[i]);
try (PrintWriter writer =
new PrintWriter(
new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8),
false)) {
writer.write(handbookBuilders.get(i).toString());
}
}
if (message) Grasscutter.getLogger().info("GM Handbooks generated!");
}
public static List<String> createGachaMappingJsons() {
final int NUM_LANGUAGES = Language.TextStrings.NUM_LANGUAGES;
final Language.TextStrings CHARACTER = Language.getTextMapKey(4233146695L); // "Character" in EN
final Language.TextStrings WEAPON = Language.getTextMapKey(4231343903L); // "Weapon" in EN
final Language.TextStrings STANDARD_WISH =
Language.getTextMapKey(332935371L); // "Standard Wish" in EN
final Language.TextStrings CHARACTER_EVENT_WISH =
Language.getTextMapKey(2272170627L); // "Character Event Wish" in EN
final Language.TextStrings CHARACTER_EVENT_WISH_2 =
Language.getTextMapKey(3352513147L); // "Character Event Wish-2" in EN
final Language.TextStrings WEAPON_EVENT_WISH =
Language.getTextMapKey(2864268523L); // "Weapon Event Wish" in EN
final List<StringBuilder> sbs = new ArrayList<>(NUM_LANGUAGES);
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
sbs.add(new StringBuilder("{\n")); // Web requests should never need Windows line endings
// Avatars
GameData.getAvatarDataMap()
.keySet()
.intStream()
.sorted()
.forEach(
id -> {
AvatarData data = GameData.getAvatarDataMap().get(id);
int avatarID = data.getId();
if (avatarID >= 11000000) { // skip test avatar
return;
}
String color =
switch (data.getQualityType()) {
case "QUALITY_PURPLE" -> "purple";
case "QUALITY_ORANGE" -> "yellow";
case "QUALITY_BLUE" -> "blue";
default -> "";
};
Language.TextStrings avatarName = Language.getTextMapKey(data.getNameTextMapHash());
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
sbs.get(langIdx)
.append("\t\"")
.append(avatarID % 1000 + 1000)
.append("\": [\"")
.append(avatarName.get(langIdx))
.append(" (")
.append(CHARACTER.get(langIdx))
.append(")\", \"")
.append(color)
.append("\"],\n");
}
});
// Weapons
GameData.getItemDataMap()
.keySet()
.intStream()
.sorted()
.forEach(
id -> {
ItemData data = GameData.getItemDataMap().get(id);
if (data.getId() <= 11101 || data.getId() >= 20000) {
return; // skip non weapon items
}
String color =
switch (data.getRankLevel()) {
case 3 -> "blue";
case 4 -> "purple";
case 5 -> "yellow";
default -> null;
};
if (color == null) return; // skip unnecessary entries
Language.TextStrings weaponName = Language.getTextMapKey(data.getNameTextMapHash());
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
sbs.get(langIdx)
.append("\t\"")
.append(data.getId())
.append("\": [\"")
.append(weaponName.get(langIdx).replaceAll("\"", "\\\\\""))
.append(" (")
.append(WEAPON.get(langIdx))
.append(")\", \"")
.append(color)
.append("\"],\n");
}
});
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
sbs.get(langIdx)
.append("\t\"200\": \"")
.append(STANDARD_WISH.get(langIdx))
.append("\",\n\t\"301\": \"")
.append(CHARACTER_EVENT_WISH.get(langIdx))
.append("\",\n\t\"400\": \"")
.append(CHARACTER_EVENT_WISH_2.get(langIdx))
.append("\",\n\t\"302\": \"")
.append(WEAPON_EVENT_WISH.get(langIdx))
.append("\"\n}");
}
return sbs.stream().map(StringBuilder::toString).toList();
}
public static void createGachaMappings(Path location) throws IOException {
ResourceLoader.loadResources();
List<String> jsons = createGachaMappingJsons();
var usedLocales = new HashSet<String>();
StringBuilder sb = new StringBuilder("mappings = {\n");
for (int i = 0; i < Language.TextStrings.NUM_LANGUAGES; i++) {
String locale =
Language.TextStrings.ARR_GC_LANGUAGES[i]
.toLowerCase(); // TODO: change the templates to not use lowercased locale codes
if (usedLocales.add(
locale)) { // Some locales fallback to en-us, we don't want to redefine en-us with
// vietnamese strings
sb.append("\t\"%s\": ".formatted(locale));
sb.append(jsons.get(i).replace("\n", "\n\t") + ",\n");
}
}
sb.setLength(sb.length() - 2); // Delete trailing ",\n"
sb.append("\n}");
Files.createDirectories(location.getParent());
Files.writeString(location, sb);
Grasscutter.getLogger().debug("Mappings generated to " + location);
}
public static List<String> getAvailableLanguage() {
List<String> availableLangList = new ArrayList<>();
try {
Files.newDirectoryStream(getResourcePath("TextMap"), "TextMap*.json")
.forEach(
path -> {
availableLangList.add(
path.getFileName()
.toString()
.replace("TextMap", "")
.replace(".json", "")
.toLowerCase());
});
} catch (IOException e) {
Grasscutter.getLogger().error("Failed to get available languages:", e);
}
return availableLangList;
}
@Deprecated(forRemoval = true, since = "1.2.3")
public static String getLanguageOption() {
List<String> availableLangList = getAvailableLanguage();
// Use system out for better format
if (availableLangList.size() == 1) {
return availableLangList.get(0).toUpperCase();
}
StringBuilder stagedMessage = new StringBuilder();
stagedMessage.append(
"The following languages mappings are available, please select one: [default: EN] \n");
StringBuilder groupedLangList = new StringBuilder(">\t");
String input;
int groupedLangCount = 0;
for (String availableLanguage : availableLangList) {
groupedLangCount++;
groupedLangList.append(availableLanguage).append("\t");
if (groupedLangCount == 6) {
stagedMessage.append(groupedLangList).append("\n");
groupedLangCount = 0;
groupedLangList = new StringBuilder(">\t");
}
}
if (groupedLangCount > 0) {
stagedMessage.append(groupedLangList).append("\n");
}
stagedMessage.append("\nYour choice: [EN] ");
input = Grasscutter.getConsole().readLine(stagedMessage.toString());
if (availableLangList.contains(input.toLowerCase())) {
return input.toUpperCase();
}
Grasscutter.getLogger().info("Invalid option. Will use EN (English) as fallback.");
return "EN";
}
}
package emu.grasscutter.tools;
import static emu.grasscutter.utils.FileUtils.getResourcePath;
import static emu.grasscutter.utils.Language.getTextMapKey;
import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.command.CommandHandler;
import emu.grasscutter.command.CommandMap;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.ResourceLoader;
import emu.grasscutter.data.excels.ItemData;
import emu.grasscutter.data.excels.achievement.AchievementData;
import emu.grasscutter.data.excels.avatar.AvatarData;
import emu.grasscutter.game.inventory.MaterialType;
import emu.grasscutter.utils.Language;
import emu.grasscutter.utils.Language.TextStrings;
import it.unimi.dsi.fastutil.ints.Int2IntRBTreeMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectRBTreeMap;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import lombok.val;
public final class Tools {
/**
* This generates the GM handbooks with a message by default.
*
* @throws Exception If an error occurs while generating the handbooks.
*/
public static void createGmHandbooks() throws Exception {
Tools.createGmHandbooks(true);
}
/**
* Generates a GM handbook for each language.
*
* @param message Should a message be printed to the console?
* @throws Exception If an error occurs while generating the handbooks.
*/
public static void createGmHandbooks(boolean message) throws Exception {
val languages = Language.TextStrings.getLanguages();
ResourceLoader.loadAll();
val mainQuestTitles =
new Int2IntRBTreeMap(
GameData.getMainQuestDataMap().int2ObjectEntrySet().stream()
.collect(
Collectors.toMap(
e -> e.getIntKey(), e -> (int) e.getValue().getTitleTextMapHash())));
// val questDescs = new
// Int2IntRBTreeMap(GameData.getQuestDataMap().int2ObjectEntrySet().stream().collect(Collectors.toMap(e -> (int) e.getIntKey(), e -> (int) e.getValue().getDescTextMapHash())));
val avatarDataMap = new Int2ObjectRBTreeMap<>(GameData.getAvatarDataMap());
val itemDataMap = new Int2ObjectRBTreeMap<>(GameData.getItemDataMap());
val monsterDataMap = new Int2ObjectRBTreeMap<>(GameData.getMonsterDataMap());
val sceneDataMap = new Int2ObjectRBTreeMap<>(GameData.getSceneDataMap());
val questDataMap = new Int2ObjectRBTreeMap<>(GameData.getQuestDataMap());
val achievementDataMap = new Int2ObjectRBTreeMap<>(GameData.getAchievementDataMap());
Function<SortedMap<?, ?>, String> getPad = m -> "%" + m.lastKey().toString().length() + "s : ";
// Create builders and helper functions
val handbookBuilders =
IntStream.range(0, TextStrings.NUM_LANGUAGES).mapToObj(i -> new StringBuilder()).toList();
var h =
new Object() {
void newLine(String line) {
handbookBuilders.forEach(b -> b.append(line + "\n"));
}
void newSection(String title) {
newLine("\n\n// " + title);
}
void newTranslatedLine(String template, TextStrings... textstrings) {
for (int i = 0; i < TextStrings.NUM_LANGUAGES; i++) {
String s = template;
for (int j = 0; j < textstrings.length; j++)
s = s.replace("{" + j + "}", textstrings[j].strings[i]);
handbookBuilders.get(i).append(s + "\n");
}
}
void newTranslatedLine(String template, long... hashes) {
newTranslatedLine(
template,
LongStream.of(hashes)
.mapToObj(hash -> getTextMapKey(hash))
.toArray(TextStrings[]::new));
}
};
// Preamble
h.newLine("// Grasscutter " + GameConstants.VERSION + " GM Handbook");
h.newLine(
"// Created "
+ DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now()));
// Commands
h.newSection("Commands");
final List<CommandHandler> cmdList = CommandMap.getInstance().getHandlersAsList();
final String padCmdLabel =
"%"
+ cmdList.stream()
.map(CommandHandler::getLabel)
.map(String::length)
.max(Integer::compare)
.get()
+ "s : ";
for (CommandHandler cmd : cmdList) {
final String label = padCmdLabel.formatted(cmd.getLabel());
final String descKey = cmd.getDescriptionKey();
for (int i = 0; i < TextStrings.NUM_LANGUAGES; i++) {
String desc =
languages.get(i).get(descKey).replace("\n", "\n\t\t\t\t").replace("\t", " ");
handbookBuilders.get(i).append(label + desc + "\n");
}
}
// Avatars
h.newSection("Avatars");
val avatarPre = getPad.apply(avatarDataMap);
avatarDataMap.forEach(
(id, data) ->
h.newTranslatedLine(avatarPre.formatted(id) + "{0}", data.getNameTextMapHash()));
// Items
h.newSection("Items");
val itemPre = getPad.apply(itemDataMap);
itemDataMap.forEach(
(id, data) -> {
val name = getTextMapKey(data.getNameTextMapHash());
switch (data.getMaterialType()) {
case MATERIAL_BGM:
val bgmName =
Optional.ofNullable(data.getItemUse())
.map(u -> u.get(0))
.map(u -> u.getUseParam())
.filter(u -> u.length > 0)
.map(u -> Integer.parseInt(u[0]))
.map(bgmId -> GameData.getHomeWorldBgmDataMap().get(bgmId))
.map(bgm -> bgm.getBgmNameTextMapHash())
.map(hash -> getTextMapKey(hash));
if (bgmName.isPresent()) {
h.newTranslatedLine(itemPre.formatted(id) + "{0} - {1}", name, bgmName.get());
return;
} // Fall-through
default:
h.newTranslatedLine(itemPre.formatted(id) + "{0}", name);
return;
}
});
// Monsters
h.newSection("Monsters");
val monsterPre = getPad.apply(monsterDataMap);
monsterDataMap.forEach(
(id, data) ->
h.newTranslatedLine(
monsterPre.formatted(id) + data.getMonsterName() + " - {0}",
data.getNameTextMapHash()));
// Scenes - no translations
h.newSection("Scenes");
val padSceneId = getPad.apply(sceneDataMap);
sceneDataMap.forEach((id, data) -> h.newLine(padSceneId.formatted(id) + data.getScriptData()));
// Quests
h.newSection("Quests");
val padQuestId = getPad.apply(questDataMap);
questDataMap.forEach(
(id, data) ->
h.newTranslatedLine(
padQuestId.formatted(id) + "{0} - {1}",
mainQuestTitles.get(data.getMainId()),
data.getDescTextMapHash()));
// Achievements
h.newSection("Achievements");
val padAchievementId = getPad.apply(achievementDataMap);
achievementDataMap.values().stream()
.filter(AchievementData::isUsed)
.forEach(
data -> {
h.newTranslatedLine(
padAchievementId.formatted(data.getId()) + "{0} - {1}",
data.getTitleTextMapHash(),
data.getDescTextMapHash());
});
// Write txt files
for (int i = 0; i < TextStrings.NUM_LANGUAGES; i++) {
File GMHandbookOutputpath = new File("./GM Handbook");
GMHandbookOutputpath.mkdir();
final String fileName =
"./GM Handbook/GM Handbook - %s.txt".formatted(TextStrings.ARR_LANGUAGES[i]);
try (PrintWriter writer =
new PrintWriter(
new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8),
false)) {
writer.write(handbookBuilders.get(i).toString());
}
}
if (message) Grasscutter.getLogger().info("GM Handbooks generated!");
}
public static List<String> createGachaMappingJsons() {
final int NUM_LANGUAGES = Language.TextStrings.NUM_LANGUAGES;
final Language.TextStrings CHARACTER = Language.getTextMapKey(4233146695L); // "Character" in EN
final Language.TextStrings WEAPON = Language.getTextMapKey(4231343903L); // "Weapon" in EN
final Language.TextStrings STANDARD_WISH =
Language.getTextMapKey(332935371L); // "Standard Wish" in EN
final Language.TextStrings CHARACTER_EVENT_WISH =
Language.getTextMapKey(2272170627L); // "Character Event Wish" in EN
final Language.TextStrings CHARACTER_EVENT_WISH_2 =
Language.getTextMapKey(3352513147L); // "Character Event Wish-2" in EN
final Language.TextStrings WEAPON_EVENT_WISH =
Language.getTextMapKey(2864268523L); // "Weapon Event Wish" in EN
final List<StringBuilder> sbs = new ArrayList<>(NUM_LANGUAGES);
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++)
sbs.add(new StringBuilder("{\n")); // Web requests should never need Windows line endings
// Avatars
GameData.getAvatarDataMap()
.keySet()
.intStream()
.sorted()
.forEach(
id -> {
AvatarData data = GameData.getAvatarDataMap().get(id);
int avatarID = data.getId();
if (avatarID >= 11000000) { // skip test avatar
return;
}
String color =
switch (data.getQualityType()) {
case "QUALITY_PURPLE" -> "purple";
case "QUALITY_ORANGE" -> "yellow";
case "QUALITY_BLUE" -> "blue";
default -> "";
};
Language.TextStrings avatarName = Language.getTextMapKey(data.getNameTextMapHash());
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
sbs.get(langIdx)
.append("\t\"")
.append(avatarID % 1000 + 1000)
.append("\": [\"")
.append(avatarName.get(langIdx))
.append(" (")
.append(CHARACTER.get(langIdx))
.append(")\", \"")
.append(color)
.append("\"],\n");
}
});
// Weapons
GameData.getItemDataMap()
.keySet()
.intStream()
.sorted()
.forEach(
id -> {
ItemData data = GameData.getItemDataMap().get(id);
if (data.getId() <= 11101 || data.getId() >= 20000) {
return; // skip non weapon items
}
String color =
switch (data.getRankLevel()) {
case 3 -> "blue";
case 4 -> "purple";
case 5 -> "yellow";
default -> null;
};
if (color == null) return; // skip unnecessary entries
Language.TextStrings weaponName = Language.getTextMapKey(data.getNameTextMapHash());
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
sbs.get(langIdx)
.append("\t\"")
.append(data.getId())
.append("\": [\"")
.append(weaponName.get(langIdx).replaceAll("\"", "\\\\\""))
.append(" (")
.append(WEAPON.get(langIdx))
.append(")\", \"")
.append(color)
.append("\"],\n");
}
});
for (int langIdx = 0; langIdx < NUM_LANGUAGES; langIdx++) {
sbs.get(langIdx)
.append("\t\"200\": \"")
.append(STANDARD_WISH.get(langIdx))
.append("\",\n\t\"301\": \"")
.append(CHARACTER_EVENT_WISH.get(langIdx))
.append("\",\n\t\"400\": \"")
.append(CHARACTER_EVENT_WISH_2.get(langIdx))
.append("\",\n\t\"302\": \"")
.append(WEAPON_EVENT_WISH.get(langIdx))
.append("\"\n}");
}
return sbs.stream().map(StringBuilder::toString).toList();
}
public static void createGachaMappings(Path location) throws IOException {
ResourceLoader.loadResources();
List<String> jsons = createGachaMappingJsons();
var usedLocales = new HashSet<String>();
StringBuilder sb = new StringBuilder("mappings = {\n");
for (int i = 0; i < Language.TextStrings.NUM_LANGUAGES; i++) {
String locale =
Language.TextStrings.ARR_GC_LANGUAGES[i]
.toLowerCase(); // TODO: change the templates to not use lowercased locale codes
if (usedLocales.add(
locale)) { // Some locales fallback to en-us, we don't want to redefine en-us with
// vietnamese strings
sb.append("\t\"%s\": ".formatted(locale));
sb.append(jsons.get(i).replace("\n", "\n\t") + ",\n");
}
}
sb.setLength(sb.length() - 2); // Delete trailing ",\n"
sb.append("\n}");
Files.createDirectories(location.getParent());
Files.writeString(location, sb);
Grasscutter.getLogger().debug("Mappings generated to " + location);
}
public static List<String> getAvailableLanguage() {
List<String> availableLangList = new ArrayList<>();
try {
Files.newDirectoryStream(getResourcePath("TextMap"), "TextMap*.json")
.forEach(
path -> {
availableLangList.add(
path.getFileName()
.toString()
.replace("TextMap", "")
.replace(".json", "")
.toLowerCase());
});
} catch (IOException e) {
Grasscutter.getLogger().error("Failed to get available languages:", e);
}
return availableLangList;
}
@Deprecated(forRemoval = true, since = "1.2.3")
public static String getLanguageOption() {
List<String> availableLangList = getAvailableLanguage();
// Use system out for better format
if (availableLangList.size() == 1) {
return availableLangList.get(0).toUpperCase();
}
StringBuilder stagedMessage = new StringBuilder();
stagedMessage.append(
"The following languages mappings are available, please select one: [default: EN] \n");
StringBuilder groupedLangList = new StringBuilder(">\t");
String input;
int groupedLangCount = 0;
for (String availableLanguage : availableLangList) {
groupedLangCount++;
groupedLangList.append(availableLanguage).append("\t");
if (groupedLangCount == 6) {
stagedMessage.append(groupedLangList).append("\n");
groupedLangCount = 0;
groupedLangList = new StringBuilder(">\t");
}
}
if (groupedLangCount > 0) {
stagedMessage.append(groupedLangList).append("\n");
}
stagedMessage.append("\nYour choice: [EN] ");
input = Grasscutter.getConsole().readLine(stagedMessage.toString());
if (availableLangList.contains(input.toLowerCase())) {
return input.toUpperCase();
}
Grasscutter.getLogger().info("Invalid option. Will use EN (English) as fallback.");
return "EN";
}
}