Files
Grasscutter/src/main/java/emu/grasscutter/game/quest/QuestManager.java
T
Magix 9e5b57a043 Merge unstable into development (#2173)
* Remove more scene synchronized

* Fix worktop options not appearing

* Format code [skip actions]

* Fix delay with server tasks

* Format code [skip actions]

* Fully fix fairy clock (#2146)

* Fix scene transition

* fully fix fairy clock

* Re-add call to `Player#updatePlayerGameTime`

* Format code [skip actions]

* Initialize the script loader in `ResourceLoader#loadAll`

* Fix region removal checking

* Format code [skip actions]

* Use Lombok's `EqualsAndHashCode` for comparing scene regions

* Format code [skip actions]

* Move 'invalid gather object' to `trace`

* Add more information to the 'unknown condition handler' message

* Move invalid ability action to trace

* Make `KcpTunnel` public

* Validate the NPC being talked to

* Format code [skip actions]

* NPCs are not spawned server side; change logic to handle it

* Format code [skip actions]

* unload scene when there are no players (#2147)

* unload scene when there are no players

* Update src/main/java/emu/grasscutter/game/world/Scene.java

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

---------

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

* Check if a command should be copied or HTTP should be used

* Lint Code [skip actions]

* Fix character names rendering incorrectly

* Add basic troubleshooting command

* Implement handbook teleporting

also a few formatting changes and sort data by logical sense

* Fix listener `ConcurrentModificationException` issue

* Add color change to `Join the Community!`

* Lint Code [skip actions]

* Make clickable buttons appear clickable

* Remove 'Mechanicus' entities from the list of entities

* Format code [skip actions]

* Fix going back returning a blank screen

* Implement entity spawning

* Add setting level to entity card

* Add support for 'plain text' mode

* Make descriptions of objects scrollable

* Lint Code [skip actions]

* Format code [skip actions]

* Change the way existing hooks work

* Format code [skip actions]

* Upgrade Javalin to 5.5.0 & Fix project warnings

* Upgrade logging libraries

* Fix gacha mappings static file issue

* Add temporary backwards compatability for `ServerHelper`

* Format code [skip actions]

* Remove artifact signatures from VCS

* Fix forge queue data protocol definition

* Run `spotlessApply`

* Format code [skip actions]

* Download data required for building artifacts

* Add call for Facebook logins

* Add the wiki page as a submodule

* Format code [skip actions]

* Update translation (#2150)

* Update translation

* Update translation

* Separate the dispatch and game servers (pt. 1)

gacha is still broken, handbook still needs to be done

* Format code [skip actions]

* Separate the dispatch and game servers (pt. 2)

this commit fixes the gacha page

* Add description for '/troubleshoot'

* Set default avatar talent level to 10

* Separate the dispatch and game servers (pt. 3)

implement handbook across servers!

* Format code [skip actions]

* Update GitHub Actions to use 'download-file' over 'wget'

* Gm handbook lmao (#2149)

* Fix font issue

* Fix avatars

* Fix text overflow in commands

* Fix virtualized lists and items page 😭😭

* magix why 💀

* use hover style in all minicards

* button

* remove console.log

* lint

* Add icons

* magix asked

* Fix overflow padding issue

* Fix achievement text overflow

* remove icons from repo

* Change command icon

* Add the wiki page as a submodule

* total magix moment

* fix text overflow in commands

* Fix discord button

* Make text scale on Minicard

* import icons and font from another source

* Add hover effects to siebar buttons

* move font and readme to submodule repo

* Make data folder a submodule

* import icons and font from data submodule

* Update README.md

* total magix moment

* magix moment v2

* submodule change

* Import `.webp` files

* Resize `HomeButton`

* Fix 'Copy Command' reappearing after changing pages

---------

Co-authored-by: KingRainbow44 <kobedo11@gmail.com>

* Lint Code [skip actions]

* Download data for the build, not for the lint

* format imports

this is really just to see if build handbook works kek

* Implement proper handbook authentication (pt. 1)

* Implement proper handbook authentication (pt. 2)

* Format code [skip actions]

* Add quest data dumping for the handbook

* Change colors to fit _something suitable_

* Format code [skip actions]

* Fix force pushing to branches after linting

* Fix logic of `SetPlayerPropReq`

* Move more group loading to `trace`

* Add handbook IP authentication in hybrid mode

* Fix player level up not displaying on the client properly

* Format code [skip actions]

* Fix game time locking

* Format code [skip actions]

* Update player properties

* Format code [skip actions]

* Move `warn`s for groups to `debug`

* Fix player pausing

* Move more logs to `trace`

* Use `removeItemById` for deleting items via quests

* Clean up logger more

* Pause in-game time when the world is paused

* Format code [skip actions]

* More player property documentation

* Multi-threaded resource loading

* Format code [skip actions]

* Add quest widgets

* Add quests page (basic impl.)

* Add/fix colors

also fix tailwind

* Remove banned packets

client modifications already perform the job of blocking malicious packets from being executed, no point in having this if self-windy is wanted

* Re-add `BeginCameraSceneLookNotify`

* Fix being unable to attack (#2157)

* Add `PlayerOpenChestEvent`

* Add methods to get players from the server

* Add static methods to register an event handler

* Add `PlayerEnterDungeonEvent`

* Remove legacy documentation from `PlayerMoveEvent`

* Add `PlayerChatEvent`

* Add defaults to `Position`

* Clean up `.utils`

* Revert `Multi-threaded resource loading`

* Fix changing target UID when talking to the server

* Lint Code [skip actions]

* Format code [skip actions]

* fix NPC talk triggering main quest in 46101 (#2158)

Make it so that only talks where the param matches the talkId are checked.

* Format code [skip actions]

* Partially fix Chasing Shadows (#2159)

* Partially fix Chasing Shadows

* Go ahead and move it before the return before Magix tells me to.

* Format code [skip actions]

* Bring back period lol (#2160)

* Disable SNI for the HTTPS server

* Add `EntityCreationEvent`

* Add initial startup message

this is so the server appears like its preparing to start

* Format code [skip actions]

* Enable debug mode for plugin loggers if enabled for the primary logger

* Add documentation about `WorldAreaConfigData`

* Make more fields in excels accessible

* Remove deprecated fields from `GetShopRsp`

* Run `spotlessApply` on definitions

* Add `PlayerEnterAreaEvent`

* Optimize event calls

* Fix event invokes

* Format code [skip actions]

* Remove manual autofinish for main quests. (#2162)

* Add world areas to the textmap cache

* Format code [skip actions]

* Don't overdefine variables in extended classes (#2163)

* Add dumper for world areas

* Format code [skip actions]

* instantiate personalLineList (#2165)

* Fix protocol definitions

thank you Nazrin! (+ hiro for raw definitions)

* Fix the background color leaking from the character widget

* Change HTML spacing to 2 spaces

* Implement hiding widgets

* Change scrollbar to a vibrant color

* Add _some_ scaling to the home buttons and its text

* Build the handbook with Gradle

* Fix the 'finer details' with the handbook UI

* Lint Code [skip actions]

* Fix target destination for the Gradle-built handbook

* Implement fetching a player across servers & Add a chainable JsonObject

useful for plugins! might be used in grasscutter eventually

* Fix GitHub actions

* Fix event calling & canceling

* Run `spotlessApply`

* Rename fields (might be wrong)

* Add/update all/more protocol definitions

* Add/update all/more protocol definitions

* Remove outdated packet

* Fix protocol definitions

* Format code [skip actions]

* Implement some lua variables for less console spam (#2172)

* Implement some lua variables for less console spam

* Add GetHostQuestState

This fixes some chapter 3 stuff.

* Format code [skip actions]

* Fix merge import

* Format code [skip actions]

* Fully fix fairy clock for real this time (#2167)

* Fully fix fairy clock For real this time

* Make it so relogging keeps the time lock state.

* Refactor out questLockTime

* Per Hartie, the client packet needs to be changed too

* Update src/main/java/emu/grasscutter/game/world/World.java

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

* Update src/main/java/emu/grasscutter/server/packet/recv/HandlerClientLockGameTimeNotify.java

* Remove all code not needed to get clock working

---------

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

* Implement a proper ability system (#2166)

* Apply fix `21dec2fe`

* Apply fix `89d01d5f`

* Apply fix `d900f154`

this one was already implemented; updated to use call from previous commit

* Ability changing commit

TODO: change info to debug

* Remove use of deprecated methods/fields

* Temp commit v2
(Adding LoseHP and some fixes)

* Oopsie

* Probably fix monster battle

* Fix issue with reflecting into fields

* Fix some things

* Fix ability names for 3.6 resources

* Improve logging

---------

Co-authored-by: StartForKiller <jesussanz2003@gmail.com>

* Format code [skip actions]

* Add system for sending messages between servers

* Format some code

* Remove protocol definitions from Spotless

* Default debug to false; enable with `-debug`

* Implement completely useless global value copying

* HACK: Return the avatar which holds the weapon when the weapon is referred to by ID

* Add properties to `AbilityModifier`

* Change the way HTML is served after authentication

* Use thread executors to speed up the database loading process

* Format code [skip actions]

* Add system for setting handbook address and port

* Lint Code [skip actions]

* Format code [skip actions]

* Fix game-related data not saving

* Format code [skip actions]

* Fix handbook server details

* Lint Code [skip actions]

* Format code [skip actions]

* Use the headers provided by a context to get the IP address

should acknowledge #1975

* Format code [skip actions]

* Move more logs to `trace`

* Format code [skip actions]

* more trace

* Fix something and implement weapon entities

* Format code [skip actions]

* Fix `EntityWeapon`

* Remove deprecated API & Fix resource checking

* Fix unnecessary warning for first-time setup

* Implement handbook request limiting

* Format code [skip actions]

* Fix new avatar weapons being null

* Format code [skip actions]

* Fix issue with 35303 being un-completable & Try to fix fulfilled quest conditions being met

* Load activity config on server startup

* Require plugins to specify an API version and match with the server

* Add default open state ignore list

* Format code [skip actions]

* Quick fix for questing, needs more investigation
This would make the questing work again

* Remove existing hack for 35303

* Fix ignored open states from being set

* Format code [skip actions]

* fix the stupidest bug ive ever seen

* Optimize player kicking on server close

* Format code [skip actions]

* Re-add hack to fix 35303

* Update GitHub actions

* Format code [skip actions]

* Potentially fix issues with regions

* Download additional handbook data

* Revert "Potentially fix issues with regions"

This reverts commit 84e3823695.

---------

Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: scooterboo <lewasite@yahoo.com>
Co-authored-by: Tesutarin <105267106+Tesutarin@users.noreply.github.com>
Co-authored-by: Scald <104459145+Arikatsu@users.noreply.github.com>
Co-authored-by: StartForKiller <jesussanz2003@gmail.com>
2023-05-31 23:48:16 -04:00

562 lines
23 KiB
Java

package emu.grasscutter.game.quest;
import dev.morphia.annotations.Transient;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.binout.MainQuestData;
import emu.grasscutter.data.binout.ScenePointEntry;
import emu.grasscutter.data.excels.quest.QuestData;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.quest.enums.*;
import emu.grasscutter.server.packet.send.PacketFinishedParentQuestUpdateNotify;
import emu.grasscutter.server.packet.send.PacketQuestGlobalVarNotify;
import emu.grasscutter.game.world.Position;
import io.netty.util.concurrent.FastThreadLocalThread;
import it.unimi.dsi.fastutil.ints.*;
import lombok.Getter;
import lombok.val;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static emu.grasscutter.GameConstants.DEBUG;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import static emu.grasscutter.config.Configuration.SERVER;
public class QuestManager extends BasePlayerManager {
@Getter private final Player player;
@Getter private final Int2ObjectMap<GameMainQuest> mainQuests;
@Transient @Getter private final List<Integer> loggedQuests;
private long lastHourCheck = 0;
private long lastDayCheck = 0;
public static final ExecutorService eventExecutor;
static {
eventExecutor = new ThreadPoolExecutor(4, 4,
60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1000),
FastThreadLocalThread::new, new ThreadPoolExecutor.AbortPolicy());
}
/*
On SetPlayerBornDataReq, the server sends FinishedParentQuestNotify, with this exact
parentQuestList. Captured on Game version 2.7
Note: quest 40063 is already set to finished, with childQuest 4006406's state set to 3
*/
private static Set<Integer> newPlayerMainQuests = Set.of(303,318,348,349,350,351,416,500,
501,502,503,504,505,506,507,508,509,20000,20507,20509,21004,21005,21010,21011,21016,21017,
21020,21021,21025,40063,70121,70124,70511,71010,71012,71013,71015,71016,71017,71555);
/*
On SetPlayerBornDataReq, the server sends ServerCondMeetQuestListUpdateNotify, with this exact
addQuestIdList. Captured on Game version 2.7
Total of 161...
*/
/*
private static Set<Integer> newPlayerServerCondMeetQuestListUpdateNotify = Set.of(3100101, 7104405, 2201601,
7100801, 1907002, 7293301, 7193801, 7293401, 7193901, 7091001, 7190501, 7090901, 7190401, 7090801, 7190301,
7195301, 7294801, 7195201, 7293001, 7094001, 7193501, 7293501, 7194001, 7293701, 7194201, 7194301, 7293801,
7194901, 7194101, 7195001, 7294501, 7294101, 7194601, 7294301, 7194801, 7091301, 7290301, 2102401, 7216801,
7190201, 7090701, 7093801, 7193301, 7292801, 7227828, 7093901, 7193401, 7292901, 7093701, 7193201, 7292701,
7082402, 7093601, 7292601, 7193101, 2102301, 7093501, 7292501, 7193001, 7093401, 7292401, 7192901, 7093301,
7292301, 7192801, 7294201, 7194701, 2100301, 7093201, 7212402, 7292201, 7192701, 7280001, 7293901, 7194401,
7093101, 7212302, 7292101, 7192601, 7093001, 7292001, 7192501, 7216001, 7195101, 7294601, 2100900, 7092901,
7291901, 7192401, 7092801, 7291801, 7192301, 2101501, 7092701, 7291701, 7192201, 7106401, 2100716, 7091801,
7290801, 7191301, 7293201, 7193701, 7094201, 7294001, 7194501, 2102290, 7227829, 7193601, 7094101, 7091401,
7290401, 7190901, 7106605, 7291601, 7192101, 7092601, 7291501, 7192001, 7092501, 7291401, 7191901, 7092401,
7291301, 7191801, 7092301, 7211402, 7291201, 7191701, 7092201, 7291101, 7191601, 7092101, 7291001, 7191501,
7092001, 7290901, 7191401, 7091901, 7290701, 7191201, 7091701, 7290601, 7191101, 7091601, 7290501, 7191001,
7091501, 7290201, 7190701, 7091201, 7190601, 7091101, 7190101, 7090601, 7090501, 7090401, 7010701, 7090301,
7090201, 7010103, 7090101
);
*/
public static long getQuestKey(int mainQuestId) {
QuestEncryptionKey questEncryptionKey = GameData.getMainQuestEncryptionMap().get(mainQuestId);
return questEncryptionKey != null ? questEncryptionKey.getEncryptionKey() : 0L;
}
public QuestManager(Player player) {
super(player);
this.player = player;
this.mainQuests = new Int2ObjectOpenHashMap<>();
this.loggedQuests = new ArrayList<>();
if (DEBUG) {
this.loggedQuests.addAll(List.of(
31101, // Quest which holds talks 30902 and 30904.
35001, // Quest which unlocks world border & starts act 2.
30901, // Quest which is completed upon finishing all 3 initial dungeons.
30903, // Quest which is finished when re-entering scene 3. (home world)
30904, // Quest which unlocks the Adventurers' Guild
46904, // Quest which is required to be started, but not completed for 31101's talks to begin.
// This quest is related to obtaining your first Anemoculus.
35104, // Quest which is required to be finished for 46904 to begin.
// This quest requires 31101 not be finished.
// This quest should be accepted when the account is created.
// These quests currently have bugged triggers.
30700, // Quest which is responsible for unlocking Crash Course.
30800, // Quest which is responsible for unlocking Sparks Amongst the Pages.
47001, 47002, 47003, 47004
));
}
}
/**
* Checks if questing can be enabled.
*/
public boolean isQuestingEnabled() {
// Check if scripts are enabled.
if (!SERVER.game.enableScriptInBigWorld) {
Grasscutter.getLogger().warn("Questing is disabled without scripts enabled.");
return false;
}
return GAME_OPTIONS.questing.enabled;
}
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
if (this.isQuestingEnabled()) {
this.enableQuests();
}
// this.getPlayer().sendPacket(new PacketFinishedParentQuestUpdateNotify(newQuests));
// this.getPlayer().sendPacket(new PacketQuestListNotify(subQuests));
// this.getPlayer().sendPacket(new PacketServerCondMeetQuestListUpdateNotify(newPlayerServerCondMeetQuestListUpdateNotify));
}
public void onLogin() {
List<GameMainQuest> activeQuests = getActiveMainQuests();
List<GameQuest> activeSubs = new ArrayList<>(activeQuests.size());
for (GameMainQuest quest : activeQuests) {
List<Position> rewindPos = quest.rewind(); // <pos, rotation>
var activeQuest = quest.getActiveQuests();
if (rewindPos != null) {
getPlayer().getPosition().set(rewindPos.get(0));
getPlayer().getRotation().set(rewindPos.get(1));
}
if(activeQuest!=null && rewindPos!=null){
//activeSubs.add(activeQuest);
//player.sendPacket(new PacketQuestProgressUpdateNotify(activeQuest));
}
quest.checkProgress();
}
if (this.player.getActivityManager() != null)
this.player.getActivityManager().triggerActivityConditions();
}
public void onTick() {
var world = this.getPlayer().getWorld();
if (world == null) return;
this.checkTimeVars();
// trigger game time tick for quests
this.queueEvent(QuestContent.QUEST_CONTENT_GAME_TIME_TICK);
}
private void checkTimeVars() {
val currentDays = player.getWorld().getTotalGameTimeDays();
val currentHours = player.getWorld().getTotalGameTimeHours();
boolean checkDays = currentDays != lastDayCheck;
boolean checkHours = currentHours != lastHourCheck;
if(!checkDays && !checkHours){
return;
}
this.lastDayCheck = currentDays;
this.lastHourCheck = currentHours;
player.getActiveQuestTimers().forEach(mainQuestId -> {
if (checkHours) {
this.queueEvent(QuestCond.QUEST_COND_TIME_VAR_GT_EQ, mainQuestId);
this.queueEvent(QuestContent.QUEST_CONTENT_TIME_VAR_GT_EQ, mainQuestId);
}
if (checkDays) {
this.queueEvent(QuestCond.QUEST_COND_TIME_VAR_PASS_DAY, mainQuestId);
this.queueEvent(QuestContent.QUEST_CONTENT_TIME_VAR_PASS_DAY, mainQuestId);
}
});
}
private List<GameMainQuest> addMultMainQuests(Set<Integer> mainQuestIds) {
List<GameMainQuest> newQuests = new ArrayList<>();
for (Integer id : mainQuestIds) {
getMainQuests().put(id.intValue(),new GameMainQuest(this.player, id));
getMainQuestById(id).save();
newQuests.add(getMainQuestById(id));
}
return newQuests;
}
public void enableQuests() {
this.triggerEvent(QuestCond.QUEST_COND_NONE, null, 0);
this.triggerEvent(QuestCond.QUEST_COND_PLAYER_LEVEL_EQUAL_GREATER, null, 1);
}
/**
* Returns the default value of a global variable.
*
* @param variable The variable ID.
* @return The default value.
*/
public int getGlobalVarDefault(int variable) {
var questGlobalVarData = GameData.getQuestGlobalVarDataMap().get(variable);
return questGlobalVarData != null ? questGlobalVarData.getDefaultValue() : 0;
}
/*
* Looking through mainQuests 72201-72208 and 72174, we can infer that a questGlobalVar's default value is 0
*/
public Integer getQuestGlobalVarValue(Integer variable) {
return getPlayer().getQuestGlobalVariables()
.computeIfAbsent(variable, k -> this.getGlobalVarDefault(variable));
}
public void setQuestGlobalVarValue(int variable, int setVal) {
var prevVal = this.getPlayer().getQuestGlobalVariables().put(variable, setVal);
if (prevVal == null){
prevVal = this.getGlobalVarDefault(variable);
}
var newVal = this.getQuestGlobalVarValue(variable);
Grasscutter.getLogger().debug("Changed questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
this.triggerQuestGlobalVarAction(variable, setVal);
}
public void incQuestGlobalVarValue(int variable, int inc) {
var prevVal = getQuestGlobalVarValue(variable);
var newVal = getPlayer().getQuestGlobalVariables()
.compute(variable, (k, v) -> prevVal + inc);
Grasscutter.getLogger().debug("Incremented questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
this.triggerQuestGlobalVarAction(variable, newVal);
}
// In MainQuest 998, dec is passed as a positive integer
public void decQuestGlobalVarValue(int variable, int dec) {
var prevVal = getQuestGlobalVarValue(variable);
this.getPlayer().getQuestGlobalVariables().put(variable, prevVal - dec);
var newVal = getQuestGlobalVarValue(variable);
Grasscutter.getLogger().debug("Decremented questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
this.triggerQuestGlobalVarAction(variable, newVal);
}
public void triggerQuestGlobalVarAction(int variable, int value) {
this.queueEvent(QuestCond.QUEST_COND_QUEST_GLOBAL_VAR_EQUAL, variable, value);
this.queueEvent(QuestCond.QUEST_COND_QUEST_GLOBAL_VAR_GREATER, variable, value);
this.queueEvent(QuestCond.QUEST_COND_QUEST_GLOBAL_VAR_LESS, variable, value);
this.getPlayer().sendPacket(new PacketQuestGlobalVarNotify(getPlayer()));
}
public GameMainQuest getMainQuestById(int mainQuestId) {
return getMainQuests().get(mainQuestId);
}
public GameMainQuest getMainQuestByTalkId(int talkId) {
int mainQuestId = GameData.getQuestTalkMap().getOrDefault(talkId, talkId / 100);
return getMainQuestById(mainQuestId);
}
public GameQuest getQuestById(int questId) {
var questConfig = GameData.getQuestDataMap().get(questId);
if (questConfig == null) {
return null;
}
var mainQuest = getMainQuests().get(questConfig.getMainId());
if (mainQuest == null) {
return null;
}
return mainQuest.getChildQuests().get(questId);
}
public void forEachQuest(Consumer<GameQuest> callback) {
for (var mainQuest : getMainQuests().values()) {
for (var quest : mainQuest.getChildQuests().values()) {
callback.accept(quest);
}
}
}
public void forEachMainQuest(Consumer<GameMainQuest> callback) {
for (var mainQuest : getMainQuests().values()) {
callback.accept(mainQuest);
}
}
// TODO
public void forEachActiveQuest(Consumer<GameQuest> callback) {
for (var mainQuest : getMainQuests().values()) {
for (var quest : mainQuest.getChildQuests().values()) {
if (quest.getState() != QuestState.QUEST_STATE_FINISHED) {
callback.accept(quest);
}
}
}
}
public GameMainQuest addMainQuest(QuestData questConfig) {
var mainQuest = new GameMainQuest(getPlayer(), questConfig.getMainId());
this.getMainQuests().put(mainQuest.getParentQuestId(), mainQuest);
this.getPlayer().sendPacket(new PacketFinishedParentQuestUpdateNotify(mainQuest));
return mainQuest;
}
public GameQuest addQuest(int questId) {
var questConfig = GameData.getQuestDataMap().get(questId);
if (questConfig == null) {
return null;
}
return this.addQuest(questConfig);
}
public GameQuest addQuest(@Nonnull QuestData questConfig) {
// Main quest
var mainQuest = this.getMainQuestById(questConfig.getMainId());
// Create main quest if it doesnt exist
if (mainQuest == null) {
mainQuest = addMainQuest(questConfig);
}
// Sub quest
var quest = mainQuest.getChildQuestById(questConfig.getSubId());
// Forcefully start
quest.start();
// Check conditions.
this.checkQuestAlreadyFulfilled(quest);
return quest;
}
public void startMainQuest(int mainQuestId) {
var mainQuestData = GameData.getMainQuestDataMap().get(mainQuestId);
if (mainQuestData == null) {
return;
}
Arrays.stream(mainQuestData.getSubQuests())
.min(Comparator.comparingInt(MainQuestData.SubQuestData::getOrder))
.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);
// }
}
public void queueEvent(QuestCond condType, int... params) {
queueEvent(condType, "", params);
}
public void queueEvent(QuestContent condType, int... params) {
queueEvent(condType, "", params);
}
public void queueEvent(QuestContent condType, String paramStr, int... params) {
eventExecutor.submit(() -> triggerEvent(condType, paramStr, params));
}
public void queueEvent(QuestCond condType, String paramStr, int... params) {
eventExecutor.submit(() -> triggerEvent(condType, paramStr, params));
}
//QUEST_EXEC are handled directly by each subQuest
public void triggerEvent(QuestCond condType, String paramStr, int... params) {
Grasscutter.getLogger().trace("Trigger Event {}, {}, {}", 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 (this.loggedQuests.contains(questData.getId())) {
Grasscutter.getLogger().debug(">>> Quest {} will be {} as a result of event trigger {} ({}, {}).",
questData.getId(), shouldAccept ? "accepted" : "not accepted", condType.name(), paramStr,
Arrays.stream(params).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
for (var i = 0; i < accept.length; i++) {
var condition = acceptCond.get(i);
Grasscutter.getLogger().debug("^ Condition {} has params {} with result {}.",
condition.getType().name(),
Arrays.stream(condition.getParam())
.filter(value -> value > 0)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ")),
accept[i] == 1 ? "success" : "failure");
}
}
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().trace("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.tryFailSubQuests(condType, paramStr, params);
mainQuest.tryFinishSubQuests(condType, paramStr, params);
}
}
/**
* 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 The ID of the quest.
*/
public void checkQuestAlreadyFulfilled(GameQuest quest){
Grasscutter.getThreadPool().submit(() -> {
for (var condition : quest.getQuestData().getFinishCond()){
switch (condition.getType()) {
case QUEST_CONTENT_OBTAIN_ITEM, QUEST_CONTENT_ITEM_LESS_THAN -> {
//check if we already own enough of the item
var item = getPlayer().getInventory().getItemByGuid(condition.getParam()[0]);
queueEvent(condition.getType(), condition.getParam()[0], item != null ? item.getCount() : 0);
}
case QUEST_CONTENT_UNLOCK_TRANS_POINT -> {
var scenePoints = getPlayer().getUnlockedScenePoints().get(condition.getParam()[0]);
if (scenePoints != null && scenePoints.contains(condition.getParam()[1])) {
queueEvent(condition.getType(), condition.getParam()[0], condition.getParam()[1]);
}
}
case QUEST_CONTENT_UNLOCK_AREA -> {
var sceneAreas = getPlayer().getUnlockedSceneAreas().get(condition.getParam()[0]);
if (sceneAreas != null && sceneAreas.contains(condition.getParam()[1])) {
queueEvent(condition.getType(), condition.getParam()[0], condition.getParam()[1]);
}
}
case QUEST_CONTENT_PLAYER_LEVEL_UP -> queueEvent(condition.getType(), player.getLevel());
}
}
});
}
public List<QuestGroupSuite> getSceneGroupSuite(int sceneId) {
return getMainQuests().values().stream()
.filter(i -> i.getState() != ParentQuestState.PARENT_QUEST_STATE_FINISHED)
.map(GameMainQuest::getQuestGroupSuites)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(i -> i.getScene() == sceneId)
.toList();
}
public void loadFromDatabase() {
List<GameMainQuest> quests = DatabaseHelper.getAllQuests(getPlayer());
for (GameMainQuest mainQuest : quests) {
boolean cancelAdd = false;
mainQuest.setOwner(this.getPlayer());
for (GameQuest quest : mainQuest.getChildQuests().values()) {
QuestData questConfig = GameData.getQuestDataMap().get(quest.getSubQuestId());
if (questConfig == null) {
mainQuest.delete();
cancelAdd = true;
break;
}
quest.setMainQuest(mainQuest);
quest.setConfig(questConfig);
}
if (!cancelAdd) {
this.getMainQuests().put(mainQuest.getParentQuestId(), mainQuest);
}
}
}
public List<GameMainQuest> getActiveMainQuests() {
return getMainQuests().values().stream().filter(p -> !p.isFinished()).toList();
}
/**
* Fetches dungeon IDs for quests which have a dungeon.
*
* @param point The associated scene point of the dungeon.
* @return A list of dungeon IDs, or an empty list if none are found.
*/
public List<Integer> questsForDungeon(ScenePointEntry point) {
var pointId = point.getPointData().getId();
// Get the active quests.
return this.getActiveMainQuests().stream()
// Get the sub-quests of the main quest.
.map(GameMainQuest::getChildQuests)
// Get the values of the sub-quests map.
.map(Map::values)
.map(quests -> quests.stream()
// Get the dungeon IDs of each quest.
.map(GameQuest::getDungeonIds)
.map(ids -> ids.stream()
// Find entry points which match this dungeon.
.filter(id -> id.rightInt() == pointId)
.toList())
.map(ids -> ids.stream()
// Of the remaining dungeons, find the ID of the quest dungeon.
.map(IntIntImmutablePair::leftInt)
.toList())
.flatMap(Collection::stream)
.toList())
.flatMap(Collection::stream)
.toList();
}
}