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>
This commit is contained in:
Magix
2023-05-31 20:48:16 -07:00
committed by GitHub
parent f46fd372d2
commit 9e5b57a043
3839 changed files with 1841548 additions and 37533 deletions

View File

@@ -9,7 +9,6 @@ import emu.grasscutter.net.proto.ItemParamOuterClass;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
import emu.grasscutter.server.packet.send.*;
import emu.grasscutter.utils.Utils;
import java.util.ArrayList;
import java.util.List;
@@ -25,16 +24,20 @@ public class FurnitureManager extends BasePlayerManager {
}
public void notifyUnlockFurniture() {
player.getSession().send(new PacketUnlockedFurnitureFormulaDataNotify(player.getUnlockedFurniture()));
player
.getSession()
.send(new PacketUnlockedFurnitureFormulaDataNotify(player.getUnlockedFurniture()));
}
public void notifyUnlockFurnitureSuite() {
player.getSession().send(new PacketUnlockedFurnitureSuiteDataNotify(player.getUnlockedFurnitureSuite()));
player
.getSession()
.send(new PacketUnlockedFurnitureSuiteDataNotify(player.getUnlockedFurnitureSuite()));
}
public boolean unlockFurnitureFormula(int id) {
if (!player.getUnlockedFurniture().add(id)) {
return false; // Already unlocked!
return false; // Already unlocked!
}
notifyUnlockFurniture();
return true;
@@ -42,7 +45,7 @@ public class FurnitureManager extends BasePlayerManager {
public boolean unlockFurnitureSuite(int id) {
if (!player.getUnlockedFurnitureSuite().add(id)) {
return false; // Already unlocked!
return false; // Already unlocked!
}
notifyUnlockFurnitureSuite();
return true;
@@ -51,36 +54,50 @@ public class FurnitureManager extends BasePlayerManager {
public void startMake(int makeId, int avatarId) {
var makeData = GameData.getFurnitureMakeConfigDataMap().get(makeId);
if (makeData == null) {
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, null));
player
.getSession()
.send(
new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, null));
return;
}
// check slot count
if (player.getHome().getLevelData().getFurnitureMakeSlotCount() <= player.getHome().getFurnitureMakeSlotItemList().size()) {
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_SLOT_FULL_VALUE, null));
if (player.getHome().getLevelData().getFurnitureMakeSlotCount()
<= player.getHome().getFurnitureMakeSlotItemList().size()) {
player
.getSession()
.send(new PacketFurnitureMakeStartRsp(Retcode.RET_FURNITURE_MAKE_SLOT_FULL_VALUE, null));
return;
}
// pay items first
if (!player.getInventory().payItems(makeData.getMaterialItems())) {
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_HOME_FURNITURE_COUNT_NOT_ENOUGH_VALUE, null));
player
.getSession()
.send(
new PacketFurnitureMakeStartRsp(
Retcode.RET_HOME_FURNITURE_COUNT_NOT_ENOUGH_VALUE, null));
return;
}
var furnitureSlot = FurnitureMakeSlotItem.of()
.avatarId(avatarId)
.makeId(makeId)
.beginTime(Utils.getCurrentSeconds())
.durTime(makeData.getMakeTime())
.build();
var furnitureSlot =
FurnitureMakeSlotItem.of()
.avatarId(avatarId)
.makeId(makeId)
.beginTime(Utils.getCurrentSeconds())
.durTime(makeData.getMakeTime())
.build();
// add furniture make task
player.getHome().getFurnitureMakeSlotItemList().add(furnitureSlot);
player.getSession().send(new PacketFurnitureMakeStartRsp(Retcode.RET_SUCC_VALUE,
player.getHome().getFurnitureMakeSlotItemList().stream()
.map(FurnitureMakeSlotItem::toProto)
.toList()
));
player
.getSession()
.send(
new PacketFurnitureMakeStartRsp(
Retcode.RET_SUCC_VALUE,
player.getHome().getFurnitureMakeSlotItemList().stream()
.map(FurnitureMakeSlotItem::toProto)
.toList()));
player.getHome().save();
}
@@ -93,34 +110,48 @@ public class FurnitureManager extends BasePlayerManager {
player.sendPacket(new PacketFurnitureMakeRsp(player.getHome()));
}
public void take(int index, int makeId, boolean isFastFinish) {
var makeData = GameData.getFurnitureMakeConfigDataMap().get(makeId);
if (makeData == null) {
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, makeId, null, null));
player
.getSession()
.send(
new PacketTakeFurnitureMakeRsp(
Retcode.RET_FURNITURE_MAKE_CONFIG_ERROR_VALUE, makeId, null, null));
return;
}
var slotItem = player.getHome().getFurnitureMakeSlotItemList().stream()
.filter(x -> x.getIndex() == index && x.getMakeId() == makeId)
.findFirst();
var slotItem =
player.getHome().getFurnitureMakeSlotItemList().stream()
.filter(x -> x.getIndex() == index && x.getMakeId() == makeId)
.findFirst();
if (slotItem.isEmpty()) {
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_NO_MAKE_DATA_VALUE, makeId, null, null));
player
.getSession()
.send(
new PacketTakeFurnitureMakeRsp(
Retcode.RET_FURNITURE_MAKE_NO_MAKE_DATA_VALUE, makeId, null, null));
return;
}
// pay the speedup item
if (isFastFinish && !player.getInventory().payItem(107013,1)) {
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
if (isFastFinish && !player.getInventory().payItem(107013, 1)) {
player
.getSession()
.send(
new PacketTakeFurnitureMakeRsp(
Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
return;
}
// check if player can take
// if (slotItem.get().getBeginTime() + slotItem.get().getDurTime() >= Utils.getCurrentSeconds() && !isFastFinish) {
// player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
// return;
// }
// if (slotItem.get().getBeginTime() + slotItem.get().getDurTime() >=
// Utils.getCurrentSeconds() && !isFastFinish) {
// player.getSession().send(new
// PacketTakeFurnitureMakeRsp(Retcode.RET_FURNITURE_MAKE_UNFINISH_VALUE, makeId, null, null));
// return;
// }
player.getInventory().addItem(makeData.getFurnitureItemID(), makeData.getCount());
player.getHome().getFurnitureMakeSlotItemList().remove(slotItem.get());
@@ -128,15 +159,20 @@ public class FurnitureManager extends BasePlayerManager {
// Should be for first craft, but until first craft check exists add exp for each item crafted
player.getInventory().addItem(121, makeData.getExp(), ActionReason.FurnitureMakeTake);
player.getSession().send(new PacketTakeFurnitureMakeRsp(Retcode.RET_SUCC_VALUE, makeId,
List.of(ItemParamOuterClass.ItemParam.newBuilder()
.setItemId(makeData.getFurnitureItemID())
.setCount(makeData.getCount())
.build()),
player.getHome().getFurnitureMakeSlotItemList().stream()
.map(FurnitureMakeSlotItem::toProto)
.toList()
));
player
.getSession()
.send(
new PacketTakeFurnitureMakeRsp(
Retcode.RET_SUCC_VALUE,
makeId,
List.of(
ItemParamOuterClass.ItemParam.newBuilder()
.setItemId(makeData.getFurnitureItemID())
.setCount(makeData.getCount())
.build()),
player.getHome().getFurnitureMakeSlotItemList().stream()
.map(FurnitureMakeSlotItem::toProto)
.toList()));
player.getHome().save();
}
}

View File

@@ -1,5 +1,7 @@
package emu.grasscutter.game.managers;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import emu.grasscutter.game.inventory.GameItem;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
@@ -11,12 +13,10 @@ import emu.grasscutter.server.packet.send.PacketItemAddHintNotify;
import emu.grasscutter.server.packet.send.PacketResinChangeNotify;
import emu.grasscutter.utils.Utils;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
public class ResinManager extends BasePlayerManager {
public static final int MAX_RESIN_BUYING_COUNT = 6;
public static final int AMOUNT_TO_ADD = 60;
public static final int[] HCOIN_NUM_TO_BUY_RESIN = new int[]{50, 100, 100, 150, 200, 200};
public static final int[] HCOIN_NUM_TO_BUY_RESIN = new int[] {50, 100, 100, 150, 200, 200};
public ResinManager(Player player) {
super(player);
@@ -53,7 +53,10 @@ public class ResinManager extends BasePlayerManager {
this.player.sendPacket(new PacketResinChangeNotify(this.player));
// Battle Pass trigger
this.player.getBattlePassManager().triggerMission(WatcherTriggerType.TRIGGER_COST_MATERIAL, 106, amount); // Resin item id = 106
this.player
.getBattlePassManager()
.triggerMission(
WatcherTriggerType.TRIGGER_COST_MATERIAL, 106, amount); // Resin item id = 106
return true;
}
@@ -110,7 +113,11 @@ public class ResinManager extends BasePlayerManager {
// Calculate how much resin we need to refill and update player.
// Note that this can be more than one in case the player
// logged off with uncapped resin and is now logging in again.
int recharge = 1 + (int)((currentTime - this.player.getNextResinRefresh()) / GAME_OPTIONS.resinOptions.rechargeTime);
int recharge =
1
+ (int)
((currentTime - this.player.getNextResinRefresh())
/ GAME_OPTIONS.resinOptions.rechargeTime);
int newResin = Math.min(GAME_OPTIONS.resinOptions.cap, currentResin + recharge);
int resinChange = newResin - currentResin;
@@ -120,9 +127,9 @@ public class ResinManager extends BasePlayerManager {
// Set to zero to disable recharge (because on/over cap.)
if (newResin >= GAME_OPTIONS.resinOptions.cap) {
this.player.setNextResinRefresh(0);
}
else {
int nextRecharge = this.player.getNextResinRefresh() + resinChange * GAME_OPTIONS.resinOptions.rechargeTime;
} else {
int nextRecharge =
this.player.getNextResinRefresh() + resinChange * GAME_OPTIONS.resinOptions.rechargeTime;
this.player.setNextResinRefresh(nextRecharge);
}
@@ -158,7 +165,10 @@ public class ResinManager extends BasePlayerManager {
return RetcodeOuterClass.Retcode.RET_RESIN_BOUGHT_COUNT_EXCEEDED_VALUE;
}
var res = this.player.getInventory().payItem(201, HCOIN_NUM_TO_BUY_RESIN[this.player.getResinBuyCount()]);
var res =
this.player
.getInventory()
.payItem(201, HCOIN_NUM_TO_BUY_RESIN[this.player.getResinBuyCount()]);
if (!res) {
return RetcodeOuterClass.Retcode.RET_HCOIN_NOT_ENOUGH_VALUE;
}
@@ -166,7 +176,8 @@ public class ResinManager extends BasePlayerManager {
this.player.setResinBuyCount(this.player.getResinBuyCount() + 1);
this.player.setProperty(PlayerProperty.PROP_PLAYER_WAIT_SUB_HCOIN, 0);
this.addResin(AMOUNT_TO_ADD);
this.player.sendPacket(new PacketItemAddHintNotify(new GameItem(106, AMOUNT_TO_ADD), ActionReason.BuyResin));
this.player.sendPacket(
new PacketItemAddHintNotify(new GameItem(106, AMOUNT_TO_ADD), ActionReason.BuyResin));
return 0;
}

View File

@@ -1,16 +1,15 @@
package emu.grasscutter.game.managers;
import java.util.HashMap;
import java.util.Map;
import emu.grasscutter.game.avatar.Avatar;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.PlayerProperty;
import emu.grasscutter.server.packet.send.PacketAvatarPropNotify;
import emu.grasscutter.server.packet.send.PacketAvatarSatiationDataNotify;
import emu.grasscutter.server.packet.send.PacketPlayerGameTimeNotify;
import emu.grasscutter.server.packet.send.PacketPlayerTimeNotify;
import emu.grasscutter.server.packet.send.PacketAvatarPropNotify;
import java.util.HashMap;
import java.util.Map;
public class SatiationManager extends BasePlayerManager {
@@ -38,7 +37,7 @@ public class SatiationManager extends BasePlayerManager {
// Penalty
long penaltyTime = playerTime;
long penaltyValue = avatar.getSatiationPenalty();
if(totalSatiation + avatar.getSatiation() > 10000 && penaltyValue == 0) {
if (totalSatiation + avatar.getSatiation() > 10000 && penaltyValue == 0) {
// Penalty is always 30sec
penaltyTime += 30;
penaltyValue = 3000;
@@ -56,8 +55,7 @@ public class SatiationManager extends BasePlayerManager {
}
public synchronized boolean addSatiationDirectly(Avatar avatar, int value) {
if (!avatar.addSatiation(value))
return false;
if (!avatar.addSatiation(value)) return false;
// Update avatar
avatar.save();
return true;
@@ -74,28 +72,31 @@ public class SatiationManager extends BasePlayerManager {
public synchronized void reduceSatiation() {
/* Satiation may not reduce while paused on official but it will here */
// Get all avatars with satiation
player.getAvatars().forEach(avatar -> {
// Ensure avatar isn't stuck in penalty
if (avatar.getSatiationPenalty() > 0 && avatar.getSatiation() == 0) {
avatar.reduceSatiationPenalty(3000);
}
player
.getAvatars()
.forEach(
avatar -> {
// Ensure avatar isn't stuck in penalty
if (avatar.getSatiationPenalty() > 0 && avatar.getSatiation() == 0) {
avatar.reduceSatiationPenalty(3000);
}
// Reduce satiation
if (avatar.getSatiation() > 0) {
// Reduce penalty first
if (avatar.getSatiationPenalty() > 0) {
// Penalty reduction rate is 1/s
avatar.reduceSatiationPenalty(100);
} else {
// Satiation reduction rate is 0.3/s
avatar.reduceSatiation(30);
// Reduce satiation
if (avatar.getSatiation() > 0) {
// Reduce penalty first
if (avatar.getSatiationPenalty() > 0) {
// Penalty reduction rate is 1/s
avatar.reduceSatiationPenalty(100);
} else {
// Satiation reduction rate is 0.3/s
avatar.reduceSatiation(30);
// Update all packets every tick else it won't work
// Surely there is a better way to handle this
addSatiation(avatar, 0, 0);
}
}
});
// Update all packets every tick else it won't work
// Surely there is a better way to handle this
addSatiation(avatar, 0, 0);
}
}
});
}
/********************
@@ -111,5 +112,4 @@ public class SatiationManager extends BasePlayerManager {
player.getSession().send(new PacketPlayerGameTimeNotify(player));
player.getSession().send(new PacketPlayerTimeNotify(player));
}
}

View File

@@ -11,7 +11,6 @@ import emu.grasscutter.net.proto.ChangeHpReasonOuterClass.ChangeHpReason;
import emu.grasscutter.net.proto.PropChangeReasonOuterClass.PropChangeReason;
import emu.grasscutter.server.packet.send.PacketEntityFightPropChangeReasonNotify;
import emu.grasscutter.server.packet.send.PacketEntityFightPropUpdateNotify;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
@@ -21,11 +20,11 @@ public class SotSManager extends BasePlayerManager {
// NOTE: Spring volume balance *1 = fight prop HP *100
public static final int GlobalMaximumSpringVolume =
PlayerProperty.PROP_MAX_SPRING_VOLUME.getMax();
private final Logger logger = Grasscutter.getLogger();
private Timer autoRecoverTimer;
private final boolean enablePriorityHealing = false;
public final static int GlobalMaximumSpringVolume = PlayerProperty.PROP_MAX_SPRING_VOLUME.getMax();
private Timer autoRecoverTimer;
public SotSManager(Player player) {
super(player);
@@ -96,42 +95,19 @@ public class SotSManager extends BasePlayerManager {
// autoRevive automatically revives all team members.
public void autoRevive() {
player.getTeamManager().getActiveTeam().forEach(entity -> {
boolean isAlive = entity.isAlive();
if (isAlive) {
return;
}
logger.trace("Reviving avatar " + entity.getAvatar().getAvatarData().getName());
player.getTeamManager().reviveAvatar(entity.getAvatar());
player.getTeamManager().healAvatar(entity.getAvatar(), 30, 0);
});
}
private class AutoRecoverTimerTick extends TimerTask {
// autoRecover checks player setting to see if auto recover is enabled, and refill HP to the predefined level.
public void run() {
refillSpringVolume();
logger.trace("isAutoRecoveryEnabled: " + getIsAutoRecoveryEnabled() + "\tautoRecoverPercentage: " + getAutoRecoveryPercentage());
if (getIsAutoRecoveryEnabled()) {
List<EntityAvatar> activeTeam = player.getTeamManager().getActiveTeam();
// When the statue does not have enough remaining volume:
// Enhanced experience: Enable priority healing
// The current active character will get healed first, then sequential.
// Vanilla experience: Disable priority healing
// Sequential healing based on character index.
int priorityIndex = enablePriorityHealing ? player.getTeamManager().getCurrentCharacterIndex() : -1;
if (priorityIndex >= 0) {
checkAndHealAvatar(activeTeam.get(priorityIndex));
}
for (int i = 0; i < activeTeam.size(); i++) {
if (i != priorityIndex) {
checkAndHealAvatar(activeTeam.get(i));
}
}
}
}
player
.getTeamManager()
.getActiveTeam()
.forEach(
entity -> {
boolean isAlive = entity.isAlive();
if (isAlive) {
return;
}
logger.trace("Reviving avatar " + entity.getAvatar().getAvatarData().getName());
player.getTeamManager().reviveAvatar(entity.getAvatar());
player.getTeamManager().healAvatar(entity.getAvatar(), 30, 0);
});
}
public void checkAndHealAvatar(EntityAvatar entity) {
@@ -154,19 +130,29 @@ public class SotSManager extends BasePlayerManager {
setCurrentVolume(0);
}
if (needHP > 0) {
logger.trace("Healing avatar " + entity.getAvatar().getAvatarData().getName() + " +" + needHP);
logger.trace(
"Healing avatar " + entity.getAvatar().getAvatarData().getName() + " +" + needHP);
player.getTeamManager().healAvatar(entity.getAvatar(), 0, needHP);
player.getSession().send(new PacketEntityFightPropChangeReasonNotify(entity, FightProperty.FIGHT_PROP_CUR_HP,
((float) needHP / 100), List.of(3), PropChangeReason.PROP_CHANGE_REASON_STATUE_RECOVER,
ChangeHpReason.CHANGE_HP_REASON_ADD_STATUE));
player.getSession().send(new PacketEntityFightPropUpdateNotify(entity, FightProperty.FIGHT_PROP_CUR_HP));
player
.getSession()
.send(
new PacketEntityFightPropChangeReasonNotify(
entity,
FightProperty.FIGHT_PROP_CUR_HP,
((float) needHP / 100),
List.of(3),
PropChangeReason.PROP_CHANGE_REASON_STATUE_RECOVER,
ChangeHpReason.CHANGE_HP_REASON_ADD_STATUE));
player
.getSession()
.send(new PacketEntityFightPropUpdateNotify(entity, FightProperty.FIGHT_PROP_CUR_HP));
}
}
}
public void refillSpringVolume() {
// Temporary: Max spring volume depends on level of the statues in Mondstadt and Liyue. Override until we have statue level.
// Temporary: Max spring volume depends on level of the statues in Mondstadt and Liyue. Override
// until we have statue level.
// TODO: remove
// https://genshin-impact.fandom.com/wiki/Statue_of_The_Seven#:~:text=region%20of%20Inazuma.-,Statue%20Levels,-Upon%20first%20unlocking
setMaxVolume(8500000);
@@ -188,4 +174,38 @@ public class SotSManager extends BasePlayerManager {
setCurrentVolume(currentVolume);
}
}
private class AutoRecoverTimerTick extends TimerTask {
// autoRecover checks player setting to see if auto recover is enabled, and refill HP to the
// predefined level.
public void run() {
refillSpringVolume();
logger.trace(
"isAutoRecoveryEnabled: "
+ getIsAutoRecoveryEnabled()
+ "\tautoRecoverPercentage: "
+ getAutoRecoveryPercentage());
if (getIsAutoRecoveryEnabled()) {
List<EntityAvatar> activeTeam = player.getTeamManager().getActiveTeam();
// When the statue does not have enough remaining volume:
// Enhanced experience: Enable priority healing
// The current active character will get healed first, then
// sequential.
// Vanilla experience: Disable priority healing
// Sequential healing based on character index.
int priorityIndex =
enablePriorityHealing ? player.getTeamManager().getCurrentCharacterIndex() : -1;
if (priorityIndex >= 0) {
checkAndHealAvatar(activeTeam.get(priorityIndex));
}
for (int i = 0; i < activeTeam.size(); i++) {
if (i != priorityIndex) {
checkAndHealAvatar(activeTeam.get(i));
}
}
}
}
}
}

View File

@@ -1,27 +1,24 @@
package emu.grasscutter.game.managers.blossom;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.MonsterData;
import emu.grasscutter.data.excels.WorldLevelData;
import emu.grasscutter.game.dungeons.challenge.WorldChallenge;
import emu.grasscutter.game.dungeons.challenge.trigger.ChallengeTrigger;
import emu.grasscutter.game.dungeons.challenge.trigger.KillMonsterTrigger;
import emu.grasscutter.game.dungeons.challenge.trigger.KillMonsterCountTrigger;
import emu.grasscutter.game.entity.EntityGadget;
import emu.grasscutter.game.entity.EntityMonster;
import emu.grasscutter.game.props.FightProperty;
import emu.grasscutter.game.world.Position;
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.scripts.data.SceneBossChest;
import emu.grasscutter.scripts.data.SceneGadget;
import emu.grasscutter.scripts.data.SceneGroup;
import emu.grasscutter.utils.Position;
import emu.grasscutter.utils.Utils;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class BlossomActivity {
public final class BlossomActivity {
private final SceneGroup tempSceneGroup;
private final WorldChallenge challenge;
@@ -31,32 +28,39 @@ public class BlossomActivity {
private final int goal;
private int generatedCount;
private final int worldLevel;
private boolean pass=false;
private boolean pass = false;
private final List<EntityMonster> activeMonsters = new ArrayList<>();
private final Queue<Integer> candidateMonsters = new ArrayDeque<>();
private static final int BLOOMING_GADGET_ID = 70210109;
public BlossomActivity(EntityGadget entityGadget, List<Integer> monsters, int timeout, int worldLevel) {
public BlossomActivity(
EntityGadget entityGadget, List<Integer> monsters, int timeout, int worldLevel) {
this.tempSceneGroup = new SceneGroup();
this.tempSceneGroup.id = entityGadget.getId();
this.gadget=entityGadget;
this.step=0;
this.gadget = entityGadget;
this.step = 0;
this.goal = monsters.size();
this.candidateMonsters.addAll(monsters);
this.worldLevel = worldLevel;
ArrayList<ChallengeTrigger> challengeTriggers = new ArrayList<>();
this.challenge = new WorldChallenge(entityGadget.getScene(),
tempSceneGroup,
1,
1,
List.of(goal, timeout),
timeout,
goal, challengeTriggers);
challengeTriggers.add(new KillMonsterTrigger());
//this.challengeTriggers.add(new InTimeTrigger());
this.challenge =
new WorldChallenge(
entityGadget.getScene(),
tempSceneGroup,
1,
1,
List.of(goal, timeout),
timeout,
goal,
challengeTriggers);
challengeTriggers.add(new KillMonsterCountTrigger());
// this.challengeTriggers.add(new InTimeTrigger());
}
public WorldChallenge getChallenge() {
return this.challenge;
}
public void setMonsters(List<EntityMonster> monsters) {
this.activeMonsters.clear();
this.activeMonsters.addAll(monsters);
@@ -64,49 +68,56 @@ public class BlossomActivity {
monster.setGroupId(this.tempSceneGroup.id);
}
}
public int getAliveMonstersCount() {
int count=0;
for (EntityMonster monster: activeMonsters) {
int count = 0;
for (EntityMonster monster : activeMonsters) {
if (monster.isAlive()) {
count++;
}
}
return count;
}
public boolean getPass() {
return pass;
}
public void start() {
challenge.start();
}
public void onTick() {
Scene scene = gadget.getScene();
Position pos = gadget.getPosition();
if (getAliveMonstersCount() <= 2) {
if (generatedCount<goal) {
if (generatedCount < goal) {
step++;
WorldLevelData worldLevelData = GameData.getWorldLevelDataMap().get(worldLevel);
var worldLevelData = GameData.getWorldLevelDataMap().get(worldLevel);
int worldLevelOverride = 0;
if (worldLevelData != null) {
worldLevelOverride = worldLevelData.getMonsterLevel();
}
List<EntityMonster> newMonsters = new ArrayList<>();
int willSpawn = Utils.randomRange(3,5);
if (generatedCount+willSpawn>goal) {
int willSpawn = Utils.randomRange(3, 5);
if (generatedCount + willSpawn > goal) {
willSpawn = goal - generatedCount;
}
generatedCount+=willSpawn;
generatedCount += willSpawn;
for (int i = 0; i < willSpawn; i++) {
MonsterData monsterData = GameData.getMonsterDataMap().get(candidateMonsters.poll());
int level = scene.getEntityLevel(1, worldLevelOverride);
EntityMonster entity = new EntityMonster(scene, monsterData, pos.nearby2d(4f), level);
var entry = candidateMonsters.poll();
if (entry == null) continue;
var monsterData = GameData.getMonsterDataMap().get((int) entry);
var level = scene.getEntityLevel(1, worldLevelOverride);
var entity = new EntityMonster(scene, monsterData, pos.nearby2d(4f), level);
scene.addEntity(entity);
newMonsters.add(entity);
}
setMonsters(newMonsters);
}else {
} else {
if (getAliveMonstersCount() == 0) {
this.pass = true;
this.challenge.done();
@@ -114,12 +125,15 @@ public class BlossomActivity {
}
}
}
public EntityGadget getGadget() {
return gadget;
}
public EntityGadget getChest() {
if (chest==null) {
EntityGadget rewardGadget = new EntityGadget(gadget.getScene(), BLOOMING_GADGET_ID, gadget.getPosition());
if (chest == null) {
EntityGadget rewardGadget =
new EntityGadget(gadget.getScene(), BLOOMING_GADGET_ID, gadget.getPosition());
SceneGadget metaGadget = new SceneGadget();
metaGadget.boss_chest = new SceneBossChest();
metaGadget.boss_chest.resin = 20;

View File

@@ -2,11 +2,11 @@ package emu.grasscutter.game.managers.blossom;
import java.util.List;
import java.util.Map;
import lombok.Getter;
public class BlossomConfig {
@Getter private int monsterFightingVolume;
// @Getter private Int2ObjectMap<IntList> monsterIdsPerDifficulty; // Need to wrangle Gson for this
// @Getter private Int2ObjectMap<IntList> monsterIdsPerDifficulty; // Need to wrangle Gson for
// this
@Getter private Map<Integer, List<Integer>> monsterIdsPerDifficulty;
}

View File

@@ -1,8 +1,5 @@
package emu.grasscutter.game.managers.blossom;
import java.util.ArrayList;
import java.util.List;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.GameDepot;
@@ -22,12 +19,10 @@ import emu.grasscutter.server.packet.send.PacketBlossomBriefInfoNotify;
import emu.grasscutter.utils.Utils;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import java.util.ArrayList;
import java.util.List;
public class BlossomManager {
public BlossomManager(Scene scene) {
this.scene = scene;
}
private final Scene scene;
private final List<BlossomActivity> blossomActivities = new ArrayList<>();
private final List<BlossomActivity> activeChests = new ArrayList<>();
@@ -35,6 +30,10 @@ public class BlossomManager {
private final List<SpawnDataEntry> blossomConsumed = new ArrayList<>();
public BlossomManager(Scene scene) {
this.scene = scene;
}
public void onTick() {
synchronized (blossomActivities) {
var it = blossomActivities.iterator();
@@ -69,55 +68,56 @@ public class BlossomManager {
return;
}
var id = gadget.getGadgetId();
if (BlossomType.valueOf(id)==null) {
if (BlossomType.valueOf(id) == null) {
return;
}
gadget.buildContent();
gadget.setState(204);
int worldLevel = getWorldLevel();
GadgetWorktop gadgetWorktop = ((GadgetWorktop) gadget.getContent());
gadgetWorktop.addWorktopOptions(new int[]{187});
gadgetWorktop.setOnSelectWorktopOptionEvent((GadgetWorktop context, int option) -> {
BlossomActivity activity;
EntityGadget entityGadget = context.getGadget();
synchronized (blossomActivities) {
for (BlossomActivity i : this.blossomActivities) {
if (i.getGadget() == entityGadget) {
return false;
}
}
gadgetWorktop.addWorktopOptions(new int[] {187});
gadgetWorktop.setOnSelectWorktopOptionEvent(
(GadgetWorktop context, int option) -> {
BlossomActivity activity;
EntityGadget entityGadget = context.getGadget();
synchronized (blossomActivities) {
for (BlossomActivity i : this.blossomActivities) {
if (i.getGadget() == entityGadget) {
return false;
}
}
int volume=0;
IntList monsters = new IntArrayList();
while (true) {
var remain = GameDepot.getBlossomConfig().getMonsterFightingVolume() - volume;
if (remain<=0) {
break;
}
var rand = Utils.randomRange(1,100);
if (rand>85 && remain>=50) {//15% ,generate strong monster
monsters.addAll(getRandomMonstersID(2,1));
volume+=50;
}else if (rand>50 && remain>=20) {//35% ,generate normal monster
monsters.addAll(getRandomMonstersID(1,1));
volume+=20;
}else {//50% ,generate weak monster
monsters.addAll(getRandomMonstersID(0,1));
volume+=10;
}
}
int volume = 0;
IntList monsters = new IntArrayList();
while (true) {
var remain = GameDepot.getBlossomConfig().getMonsterFightingVolume() - volume;
if (remain <= 0) {
break;
}
var rand = Utils.randomRange(1, 100);
if (rand > 85 && remain >= 50) { // 15% ,generate strong monster
monsters.addAll(getRandomMonstersID(2, 1));
volume += 50;
} else if (rand > 50 && remain >= 20) { // 35% ,generate normal monster
monsters.addAll(getRandomMonstersID(1, 1));
volume += 20;
} else { // 50% ,generate weak monster
monsters.addAll(getRandomMonstersID(0, 1));
volume += 10;
}
}
Grasscutter.getLogger().info("Blossom Monsters:"+monsters);
Grasscutter.getLogger().info("Blossom Monsters:" + monsters);
activity = new BlossomActivity(entityGadget, monsters, -1, worldLevel);
blossomActivities.add(activity);
}
entityGadget.updateState(201);
scene.setChallenge(activity.getChallenge());
scene.removeEntity(entityGadget, VisionTypeOuterClass.VisionType.VISION_TYPE_REMOVE);
activity.start();
return true;
});
activity = new BlossomActivity(entityGadget, monsters, -1, worldLevel);
blossomActivities.add(activity);
}
entityGadget.updateState(201);
scene.setChallenge(activity.getChallenge());
scene.removeEntity(entityGadget, VisionTypeOuterClass.VisionType.VISION_TYPE_REMOVE);
activity.start();
return true;
});
createdEntity.add(gadget);
notifyIcon();
}
@@ -128,29 +128,34 @@ public class BlossomManager {
final var worldLevelData = GameData.getWorldLevelDataMap().get(worldLevel);
final int monsterLevel = (worldLevelData != null) ? worldLevelData.getMonsterLevel() : 1;
List<BlossomBriefInfoOuterClass.BlossomBriefInfo> blossoms = new ArrayList<>();
GameDepot.getSpawnLists().forEach((gridBlockId, spawnDataEntryList) -> {
int sceneId = gridBlockId.getSceneId();
spawnDataEntryList.stream()
.map(SpawnDataEntry::getGroup)
.map(SpawnGroupEntry::getSpawns)
.flatMap(List::stream)
.filter(spawn -> !blossomConsumed.contains(spawn))
.filter(spawn -> BlossomType.valueOf(spawn.getGadgetId()) != null)
.forEach(spawn -> {
var type = BlossomType.valueOf(spawn.getGadgetId());
int previewReward = getPreviewReward(type, worldLevel);
blossoms.add(BlossomBriefInfoOuterClass.BlossomBriefInfo.newBuilder()
.setSceneId(sceneId)
.setPos(spawn.getPos().toProto())
.setResin(20)
.setMonsterLevel(monsterLevel)
.setRewardId(previewReward)
.setCircleCampId(type.getCircleCampId())
.setRefreshId(type.getBlossomChestId()) // TODO: replace when using actual leylines
.build()
);
});
});
GameDepot.getSpawnLists()
.forEach(
(gridBlockId, spawnDataEntryList) -> {
int sceneId = gridBlockId.getSceneId();
spawnDataEntryList.stream()
.map(SpawnDataEntry::getGroup)
.map(SpawnGroupEntry::getSpawns)
.flatMap(List::stream)
.filter(spawn -> !blossomConsumed.contains(spawn))
.filter(spawn -> BlossomType.valueOf(spawn.getGadgetId()) != null)
.forEach(
spawn -> {
var type = BlossomType.valueOf(spawn.getGadgetId());
int previewReward = getPreviewReward(type, worldLevel);
blossoms.add(
BlossomBriefInfoOuterClass.BlossomBriefInfo.newBuilder()
.setSceneId(sceneId)
.setPos(spawn.getPos().toProto())
.setResin(20)
.setMonsterLevel(monsterLevel)
.setRewardId(previewReward)
.setCircleCampId(type.getCircleCampId())
.setRefreshId(
type.getBlossomChestId()) // TODO: replace when using actual
// leylines
.build());
});
});
scene.broadcastPacket(new PacketBlossomBriefInfoNotify(blossoms));
}
@@ -161,7 +166,7 @@ public class BlossomManager {
private static Integer getPreviewReward(BlossomType type, int worldLevel) {
// TODO: blossoms should be based on their city
if (type == null) {
Grasscutter.getLogger().error("Illegal blossom type {}",type);
Grasscutter.getLogger().error("Illegal blossom type {}", type);
return null;
}
@@ -177,7 +182,7 @@ public class BlossomManager {
return dropVecList[worldLevel].getPreviewReward();
}
}
Grasscutter.getLogger().error("Cannot find blossom type {}",type);
Grasscutter.getLogger().error("Cannot find blossom type {}", type);
return null;
}
@@ -194,7 +199,8 @@ public class BlossomManager {
while (it.hasNext()) {
var activeChest = it.next();
if (activeChest.getChest() == chest) {
boolean pay = useCondensedResin ? resinManager.useCondensedResin(1) : resinManager.useResin(20);
boolean pay =
useCondensedResin ? resinManager.useCondensedResin(1) : resinManager.useResin(20);
if (pay) {
int worldLevel = getWorldLevel();
List<GameItem> items = new ArrayList<>();
@@ -202,16 +208,17 @@ public class BlossomManager {
var type = BlossomType.valueOf(gadget.getGadgetId());
RewardPreviewData blossomRewards = getRewardList(type, worldLevel);
if (blossomRewards == null) {
Grasscutter.getLogger().error("Blossom could not support world level : "+worldLevel);
Grasscutter.getLogger()
.error("Blossom could not support world level : " + worldLevel);
return null;
}
var rewards = blossomRewards.getPreviewItems();
for (ItemParamData blossomReward : rewards) {
int rewardCount = blossomReward.getCount();
if (useCondensedResin) {
rewardCount += blossomReward.getCount(); // Double!
rewardCount += blossomReward.getCount(); // Double!
}
items.add(new GameItem(blossomReward.getItemId(),rewardCount));
items.add(new GameItem(blossomReward.getItemId(), rewardCount));
}
it.remove();
recycleGadgetEntity(List.of(gadget));
@@ -225,11 +232,12 @@ public class BlossomManager {
return null;
}
public static IntList getRandomMonstersID(int difficulty,int count) {
IntList result = new IntArrayList();
List<Integer> monsters = GameDepot.getBlossomConfig().getMonsterIdsPerDifficulty().get(difficulty);
for (int i=0; i<count; i++) {
result.add((int) monsters.get(Utils.randomRange(0, monsters.size()-1)));
public static IntList getRandomMonstersID(int difficulty, int count) {
IntList result = new IntArrayList();
List<Integer> monsters =
GameDepot.getBlossomConfig().getMonsterIdsPerDifficulty().get(difficulty);
for (int i = 0; i < count; i++) {
result.add((int) monsters.get(Utils.randomRange(0, monsters.size() - 1)));
}
return result;
}

View File

@@ -1,17 +1,19 @@
package emu.grasscutter.game.managers.blossom;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import emu.grasscutter.utils.Utils;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.Getter;
public enum BlossomType {
GOLD(70360056, 101001001, 1),
BLUE(70360057, 101002003, 2);
private static final Int2ObjectMap<BlossomType> map =
new Int2ObjectOpenHashMap<>(
Stream.of(values()).collect(Collectors.toMap(x -> x.getGadgetId(), x -> x)));
@Getter private final int gadgetId;
@Getter private final int circleCampId;
@Getter private final int blossomChestId;
@@ -22,10 +24,6 @@ public enum BlossomType {
this.blossomChestId = blossomChestId;
}
private static final Int2ObjectMap<BlossomType> map = new Int2ObjectOpenHashMap<>(
Stream.of(values()).collect(Collectors.toMap(x -> x.getGadgetId(), x -> x))
);
public static BlossomType valueOf(int i) {
return map.get(i);
}

View File

@@ -3,14 +3,11 @@ package emu.grasscutter.game.managers.cooking;
import dev.morphia.annotations.Entity;
import lombok.Getter;
@Entity
public class ActiveCookCompoundData {
private final int costTime;
@Getter
private final int compoundId;
@Getter
private int totalCount;
@Getter private final int compoundId;
@Getter private int totalCount;
private int startTime;
public ActiveCookCompoundData(int compoundId, int processTime, int count, int startTime) {
@@ -30,10 +27,7 @@ public class ActiveCookCompoundData {
return totalCount - getOutputCount(currentTime);
}
/**
* Get the timestamp of next output.
* If all finished,return 0
*/
/** Get the timestamp of next output. If all finished,return 0 */
public int getOutputTime(int currentTime) {
int cnt = getOutputCount(currentTime);
if (cnt == totalCount) return 0;

View File

@@ -18,13 +18,12 @@ import emu.grasscutter.server.packet.send.PacketCompoundDataNotify;
import emu.grasscutter.server.packet.send.PacketGetCompoundDataRsp;
import emu.grasscutter.server.packet.send.PacketPlayerCompoundMaterialRsp;
import emu.grasscutter.utils.Utils;
import java.util.*;
public class CookingCompoundManager extends BasePlayerManager {
private static Set<Integer> defaultUnlockedCompounds;
private static Map<Integer, Set<Integer>> compoundGroups;
//TODO:bind it to player
// TODO:bind it to player
private static Set<Integer> unlocked;
public CookingCompoundManager(Player player) {
@@ -34,23 +33,33 @@ public class CookingCompoundManager extends BasePlayerManager {
public static void initialize() {
defaultUnlockedCompounds = new HashSet<>();
compoundGroups = new HashMap<>();
GameData.getCompoundDataMap().forEach((id, compound) -> {
if (compound.isDefaultUnlocked()) {
defaultUnlockedCompounds.add(id);
}
compoundGroups.computeIfAbsent(compound.getGroupID(), gid -> new HashSet<>()).add(id);
});
//TODO:Because we haven't implemented fishing feature,unlock all compounds related to fish.Besides,it should be bound to player rather than manager.
GameData.getCompoundDataMap()
.forEach(
(id, compound) -> {
if (compound.isDefaultUnlocked()) {
defaultUnlockedCompounds.add(id);
}
compoundGroups.computeIfAbsent(compound.getGroupId(), gid -> new HashSet<>()).add(id);
});
// TODO:Because we haven't implemented fishing feature,unlock all compounds related to
// fish.Besides,it should be bound to player rather than manager.
unlocked = new HashSet<>(defaultUnlockedCompounds);
if (compoundGroups.containsKey(3)) // Avoid NPE from Resources error
unlocked.addAll(compoundGroups.get(3));
if (compoundGroups.containsKey(3)) // Avoid NPE from Resources error
unlocked.addAll(compoundGroups.get(3));
}
private synchronized List<CompoundQueueData> getCompoundQueueData() {
List<CompoundQueueData> compoundQueueData = new ArrayList<>(player.getActiveCookCompounds().size());
List<CompoundQueueData> compoundQueueData =
new ArrayList<>(player.getActiveCookCompounds().size());
int currentTime = Utils.getCurrentSeconds();
for (var item : player.getActiveCookCompounds().values()) {
var data = CompoundQueueData.newBuilder().setCompoundId(item.getCompoundId()).setOutputCount(item.getOutputCount(currentTime)).setOutputTime(item.getOutputTime(currentTime)).setWaitCount(item.getWaitCount(currentTime)).build();
var data =
CompoundQueueData.newBuilder()
.setCompoundId(item.getCompoundId())
.setOutputCount(item.getOutputCount(currentTime))
.setOutputTime(item.getOutputTime(currentTime))
.setWaitCount(item.getWaitCount(currentTime))
.build();
compoundQueueData.add(data);
}
return compoundQueueData;
@@ -65,21 +74,23 @@ public class CookingCompoundManager extends BasePlayerManager {
CompoundData compound = GameData.getCompoundDataMap().get(id);
var activeCompounds = player.getActiveCookCompounds();
//check whether the compound is available
//TODO:add other compounds,see my pr for detail
// check whether the compound is available
// TODO:add other compounds,see my pr for detail
if (!unlocked.contains(id)) {
player.sendPacket(new PacketPlayerCompoundMaterialRsp(Retcode.RET_FAIL_VALUE));
return;
}
//check whether the queue is full
if (activeCompounds.containsKey(id) && activeCompounds.get(id).getTotalCount() + count > compound.getQueueSize()) {
// check whether the queue is full
if (activeCompounds.containsKey(id)
&& activeCompounds.get(id).getTotalCount() + count > compound.getQueueSize()) {
player.sendPacket(new PacketPlayerCompoundMaterialRsp(Retcode.RET_COMPOUND_QUEUE_FULL_VALUE));
return;
}
//try to consume raw materials
// try to consume raw materials
if (!player.getInventory().payItems(compound.getInputVec(), count)) {
//TODO:I'm not sure whether retcode is correct.
player.sendPacket(new PacketPlayerCompoundMaterialRsp(Retcode.RET_ITEM_COUNT_NOT_ENOUGH_VALUE));
// TODO:I'm not sure whether retcode is correct.
player.sendPacket(
new PacketPlayerCompoundMaterialRsp(Retcode.RET_ITEM_COUNT_NOT_ENOUGH_VALUE));
return;
}
ActiveCookCompoundData c;
@@ -91,16 +102,22 @@ public class CookingCompoundManager extends BasePlayerManager {
c = new ActiveCookCompoundData(id, compound.getCostTime(), count, currentTime);
activeCompounds.put(id, c);
}
var data = CompoundQueueData.newBuilder().setCompoundId(id).setOutputCount(c.getOutputCount(currentTime)).setOutputTime(c.getOutputTime(currentTime)).setWaitCount(c.getWaitCount(currentTime)).build();
var data =
CompoundQueueData.newBuilder()
.setCompoundId(id)
.setOutputCount(c.getOutputCount(currentTime))
.setOutputTime(c.getOutputTime(currentTime))
.setWaitCount(c.getWaitCount(currentTime))
.build();
player.sendPacket(new PacketPlayerCompoundMaterialRsp(data));
}
public synchronized void handleTakeCompoundOutputReq(TakeCompoundOutputReq req) {
//Client won't set compound_id and will set group_id instead.
// Client won't set compound_id and will set group_id instead.
int groupId = req.getCompoundGroupId();
var activeCompounds = player.getActiveCookCompounds();
int now = Utils.getCurrentSeconds();
//check available queues
// check available queues
boolean success = false;
Map<Integer, GameItem> allRewards = new HashMap<>();
for (int id : compoundGroups.get(groupId)) {
@@ -115,21 +132,32 @@ public class CookingCompoundManager extends BasePlayerManager {
GameItem item = allRewards.get(i.getId());
item.setCount(item.getCount() + i.getCount() * quantity);
} else {
allRewards.put(i.getId(), new GameItem(i.getId(), i.getCount()*quantity));
allRewards.put(i.getId(), new GameItem(i.getId(), i.getCount() * quantity));
}
}
success = true;
}
//give player the rewards
// give player the rewards
if (success) {
player.getInventory().addItems(allRewards.values(), ActionReason.Compound);
player.sendPacket(new PackageTakeCompoundOutputRsp(allRewards.values().stream().map(i -> ItemParam.newBuilder().setItemId(i.getItemId()).setCount(i.getCount()).build()).toList(), Retcode.RET_SUCC_VALUE));
player.sendPacket(
new PackageTakeCompoundOutputRsp(
allRewards.values().stream()
.map(
i ->
ItemParam.newBuilder()
.setItemId(i.getItemId())
.setCount(i.getCount())
.build())
.toList(),
Retcode.RET_SUCC_VALUE));
} else {
player.sendPacket(new PackageTakeCompoundOutputRsp(null, Retcode.RET_COMPOUND_NOT_FINISH_VALUE));
player.sendPacket(
new PackageTakeCompoundOutputRsp(null, Retcode.RET_COMPOUND_NOT_FINISH_VALUE));
}
}
public void onPlayerLogin() {
player.sendPacket(new PacketCompoundDataNotify(unlocked,getCompoundQueueData()));
player.sendPacket(new PacketCompoundDataNotify(unlocked, getCompoundQueueData()));
}
}

View File

@@ -1,10 +1,5 @@
package emu.grasscutter.game.managers.cooking;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.common.ItemParamData;
import emu.grasscutter.data.excels.ItemData;
@@ -21,6 +16,10 @@ import emu.grasscutter.server.packet.send.PacketCookRecipeDataNotify;
import emu.grasscutter.server.packet.send.PacketPlayerCookArgsRsp;
import emu.grasscutter.server.packet.send.PacketPlayerCookRsp;
import io.netty.util.internal.ThreadLocalRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CookingManager extends BasePlayerManager {
private static final int MANUAL_PERFECT_COOK_QUALITY = 3;
@@ -46,7 +45,7 @@ public class CookingManager extends BasePlayerManager {
********************/
public boolean unlockRecipe(int id) {
if (this.player.getUnlockedRecipies().containsKey(id)) {
return false; // Recipe already unlocked
return false; // Recipe already unlocked
}
// Tell the client that this blueprint is now unlocked and add the unlocked item to the player.
this.player.getUnlockedRecipies().put(id, 0);
@@ -86,16 +85,14 @@ public class CookingManager extends BasePlayerManager {
int proficiency = this.player.getUnlockedRecipies().getOrDefault(recipeId, 0);
// Try consuming materials.
boolean success = player.getInventory().payItems(recipeData.getInputVec(), count, ActionReason.Cook);
boolean success =
player.getInventory().payItems(recipeData.getInputVec(), count, ActionReason.Cook);
if (!success) {
this.player.sendPacket(new PacketPlayerCookRsp(Retcode.RET_FAIL));
}
// Get result item information.
int qualityIndex =
quality == 0
? 2
: quality - 1;
int qualityIndex = quality == 0 ? 2 : quality - 1;
ItemParamData resultParam = recipeData.getQualityOutputVec().get(qualityIndex);
ItemData resultItemData = GameData.getItemDataMap().get(resultParam.getItemId());
@@ -124,7 +121,8 @@ public class CookingManager extends BasePlayerManager {
if (specialtyCount > 0) {
ItemData specialtyItemData = GameData.getItemDataMap().get(bonusData.getReplacementItemId());
GameItem cookResultSpecialty = new GameItem(specialtyItemData, resultParam.getCount() * specialtyCount);
GameItem cookResultSpecialty =
new GameItem(specialtyItemData, resultParam.getCount() * specialtyCount);
cookResults.add(cookResultSpecialty);
this.player.getInventory().addItem(cookResultSpecialty);
}
@@ -136,7 +134,8 @@ public class CookingManager extends BasePlayerManager {
}
// Send response.
this.player.sendPacket(new PacketPlayerCookRsp(cookResults, quality, count, recipeId, proficiency));
this.player.sendPacket(
new PacketPlayerCookRsp(cookResults, quality, count, recipeId, proficiency));
}
/********************
@@ -146,7 +145,7 @@ public class CookingManager extends BasePlayerManager {
this.player.sendPacket(new PacketPlayerCookArgsRsp());
}
/********************
/********************
* Notify unlocked recipies.
********************/
private void addDefaultUnlocked() {
@@ -172,11 +171,13 @@ public class CookingManager extends BasePlayerManager {
// Construct CookRecipeData protos.
List<CookRecipeDataOuterClass.CookRecipeData> data = new ArrayList<>();
unlockedRecipes.forEach((recipeId, proficiency) ->
data.add(CookRecipeDataOuterClass.CookRecipeData.newBuilder()
.setRecipeId(recipeId)
.setProficiency(proficiency)
.build()));
unlockedRecipes.forEach(
(recipeId, proficiency) ->
data.add(
CookRecipeDataOuterClass.CookRecipeData.newBuilder()
.setRecipeId(recipeId)
.setProficiency(proficiency)
.build()));
// Send packet.
this.player.sendPacket(new PacketCookDataNotify(data));

View File

@@ -1,92 +1,95 @@
package emu.grasscutter.game.managers.deforestation;
import java.util.ArrayList;
import java.util.HashMap;
import dev.morphia.annotations.Transient;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.game.entity.EntityItem;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.world.Position;
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.net.proto.HitTreeNotifyOuterClass;
import emu.grasscutter.net.proto.VectorOuterClass;
import emu.grasscutter.utils.Position;
import java.util.ArrayList;
import java.util.HashMap;
public class DeforestationManager extends BasePlayerManager {
final static int RECORD_EXPIRED_SECONDS = 60*5; // 5 min
final static int RECORD_MAX_TIMES = 3; // max number of wood
final static int RECORD_MAX_TIMES_OTHER_HIT_TREE = 10; // if hit 10 times other trees, reset wood
private final ArrayList<HitTreeRecord> currentRecord;
private final static HashMap<Integer, Integer> ColliderTypeToWoodItemID = new HashMap<>();
static final int RECORD_EXPIRED_SECONDS = 60 * 5; // 5 min
static final int RECORD_MAX_TIMES = 3; // max number of wood
static final int RECORD_MAX_TIMES_OTHER_HIT_TREE = 10; // if hit 10 times other trees, reset wood
private static final HashMap<Integer, Integer> ColliderTypeToWoodItemID = new HashMap<>();
static {
/* define wood types which reflected to item id*/
ColliderTypeToWoodItemID.put(1,101301);
ColliderTypeToWoodItemID.put(2,101302);
ColliderTypeToWoodItemID.put(3,101303);
ColliderTypeToWoodItemID.put(4,101304);
ColliderTypeToWoodItemID.put(5,101305);
ColliderTypeToWoodItemID.put(6,101306);
ColliderTypeToWoodItemID.put(7,101307);
ColliderTypeToWoodItemID.put(8,101308);
ColliderTypeToWoodItemID.put(9,101309);
ColliderTypeToWoodItemID.put(10,101310);
ColliderTypeToWoodItemID.put(11,101311);
ColliderTypeToWoodItemID.put(12,101312);
ColliderTypeToWoodItemID.put(13,101313);
ColliderTypeToWoodItemID.put(14,101314);
ColliderTypeToWoodItemID.put(15,101315);
ColliderTypeToWoodItemID.put(16,101316);
ColliderTypeToWoodItemID.put(17,101317);
ColliderTypeToWoodItemID.put(1, 101301);
ColliderTypeToWoodItemID.put(2, 101302);
ColliderTypeToWoodItemID.put(3, 101303);
ColliderTypeToWoodItemID.put(4, 101304);
ColliderTypeToWoodItemID.put(5, 101305);
ColliderTypeToWoodItemID.put(6, 101306);
ColliderTypeToWoodItemID.put(7, 101307);
ColliderTypeToWoodItemID.put(8, 101308);
ColliderTypeToWoodItemID.put(9, 101309);
ColliderTypeToWoodItemID.put(10, 101310);
ColliderTypeToWoodItemID.put(11, 101311);
ColliderTypeToWoodItemID.put(12, 101312);
ColliderTypeToWoodItemID.put(13, 101313);
ColliderTypeToWoodItemID.put(14, 101314);
ColliderTypeToWoodItemID.put(15, 101315);
ColliderTypeToWoodItemID.put(16, 101316);
ColliderTypeToWoodItemID.put(17, 101317);
}
private final ArrayList<HitTreeRecord> currentRecord;
public DeforestationManager(Player player) {
super(player);
this.currentRecord = new ArrayList<>();
}
public void resetWood() {
synchronized (currentRecord) {
currentRecord.clear();
}
}
public void onDeforestationInvoke(HitTreeNotifyOuterClass.HitTreeNotify hit) {
synchronized (currentRecord) {
//Grasscutter.getLogger().info("onDeforestationInvoke! Wood records {}", currentRecord);
// Grasscutter.getLogger().info("onDeforestationInvoke! Wood records {}", currentRecord);
VectorOuterClass.Vector hitPosition = hit.getTreePos();
int woodType = hit.getTreeType();
if (ColliderTypeToWoodItemID.containsKey(woodType)) {// is a available wood type
if (ColliderTypeToWoodItemID.containsKey(woodType)) { // is a available wood type
Scene scene = player.getScene();
int itemId = ColliderTypeToWoodItemID.get(woodType);
int positionHash = hitPosition.hashCode();
HitTreeRecord record = searchRecord(positionHash);
if (record == null) {
record = new HitTreeRecord(positionHash);
}else {
currentRecord.remove(record);// move it to last position
} else {
currentRecord.remove(record); // move it to last position
}
currentRecord.add(record);
if (currentRecord.size()>RECORD_MAX_TIMES_OTHER_HIT_TREE) {
if (currentRecord.size() > RECORD_MAX_TIMES_OTHER_HIT_TREE) {
currentRecord.remove(0);
}
if (record.record()) {
EntityItem entity = new EntityItem(scene,
null,
GameData.getItemDataMap().get(itemId),
new Position(hitPosition.getX(), hitPosition.getY(), hitPosition.getZ()),
1,
false);
EntityItem entity =
new EntityItem(
scene,
null,
GameData.getItemDataMap().get(itemId),
new Position(hitPosition.getX(), hitPosition.getY(), hitPosition.getZ()),
1,
false);
scene.addEntity(entity);
}
//record.record()=false : too many wood they have deforested, no more wood dropped!
// record.record()=false : too many wood they have deforested, no more wood dropped!
} else {
Grasscutter.getLogger().warn("No wood type {} found.", woodType);
}
}
// unknown wood type
}
private HitTreeRecord searchRecord(int id) {
for (HitTreeRecord record : currentRecord) {
if (record.getUnique() == id) {

View File

@@ -1,57 +1,48 @@
package emu.grasscutter.game.managers.deforestation;
public class HitTreeRecord {
private final int unique;
private short count; // hit this tree times
private long time; // last available hitting time
HitTreeRecord(int unique){
HitTreeRecord(int unique) {
this.count = 0;
this.time = 0;
this.unique = unique;
}
/**
* reset hit time
*/
private void resetTime(){
/** reset hit time */
private void resetTime() {
this.time = System.currentTimeMillis();
}
/**
* commit hit behavior
*/
public boolean record(){
/** commit hit behavior */
public boolean record() {
if (this.count < DeforestationManager.RECORD_MAX_TIMES) {
this.count++;
resetTime();
return true;
}
// check expired
boolean isWaiting = System.currentTimeMillis() - this.time < DeforestationManager.RECORD_EXPIRED_SECONDS * 1000L;
if(isWaiting){
boolean isWaiting =
System.currentTimeMillis() - this.time
< DeforestationManager.RECORD_EXPIRED_SECONDS * 1000L;
if (isWaiting) {
return false;
}else{
} else {
this.count = 1;
resetTime();
return true;
}
}
/**
* get unique id
*/
public int getUnique(){
/** get unique id */
public int getUnique() {
return unique;
}
@Override
public String toString() {
return "HitTreeRecord{" +
"unique=" + unique +
", count=" + count +
", time=" + time +
'}';
return "HitTreeRecord{" + "unique=" + unique + ", count=" + count + ", time=" + time + '}';
}
}

View File

@@ -1,29 +1,23 @@
package emu.grasscutter.game.managers.energy;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import com.google.protobuf.InvalidProtocolBufferException;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.AvatarSkillDepotData;
import emu.grasscutter.data.excels.ItemData;
import emu.grasscutter.data.excels.MonsterData.HpDrops;
import emu.grasscutter.data.excels.avatar.AvatarSkillDepotData;
import emu.grasscutter.data.excels.monster.MonsterData.HpDrops;
import emu.grasscutter.game.avatar.Avatar;
import emu.grasscutter.game.entity.EntityAvatar;
import emu.grasscutter.game.entity.EntityClientGadget;
import emu.grasscutter.game.entity.EntityItem;
import emu.grasscutter.game.entity.EntityMonster;
import emu.grasscutter.game.entity.GameEntity;
import emu.grasscutter.game.inventory.GameItem;
import emu.grasscutter.game.inventory.MaterialType;
import emu.grasscutter.game.entity.*;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.ElementType;
import emu.grasscutter.game.props.FightProperty;
import emu.grasscutter.game.props.ItemUseOp;
import emu.grasscutter.game.props.ItemUseTarget;
import emu.grasscutter.game.props.MonsterType;
import emu.grasscutter.game.props.WeaponType;
import emu.grasscutter.game.props.ItemUseAction.ItemUseAction;
import emu.grasscutter.game.props.ItemUseAction.ItemUseAddEnergy;
import emu.grasscutter.game.world.Position;
import emu.grasscutter.net.proto.AbilityActionGenerateElemBallOuterClass.AbilityActionGenerateElemBall;
import emu.grasscutter.net.proto.AbilityIdentifierOuterClass.AbilityIdentifier;
import emu.grasscutter.net.proto.AbilityInvokeEntryOuterClass.AbilityInvokeEntry;
@@ -32,62 +26,58 @@ import emu.grasscutter.net.proto.ChangeEnergyReasonOuterClass.ChangeEnergyReason
import emu.grasscutter.net.proto.EvtBeingHitInfoOuterClass.EvtBeingHitInfo;
import emu.grasscutter.net.proto.PropChangeReasonOuterClass.PropChangeReason;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.utils.Position;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.Getter;
public class EnergyManager extends BasePlayerManager {
private static final Int2ObjectMap<List<EnergyDropInfo>> energyDropData =
new Int2ObjectOpenHashMap<>();
private static final Int2ObjectMap<List<SkillParticleGenerationInfo>>
skillParticleGenerationData = new Int2ObjectOpenHashMap<>();
private final Object2IntMap<EntityAvatar> avatarNormalProbabilities;
private boolean energyUsage; // Should energy usage be enabled for this player?
private final static Int2ObjectMap<List<EnergyDropInfo>> energyDropData = new Int2ObjectOpenHashMap<>();
private final static Int2ObjectMap<List<SkillParticleGenerationInfo>> skillParticleGenerationData = new Int2ObjectOpenHashMap<>();
@Getter private boolean energyUsage; // Should energy usage be enabled for this player?
public EnergyManager(Player player) {
super(player);
this.avatarNormalProbabilities = new Object2IntOpenHashMap<>();
this.energyUsage=GAME_OPTIONS.energyUsage;
this.energyUsage = GAME_OPTIONS.energyUsage;
}
public static void initialize() {
// Read the data we need for monster energy drops.
try {
DataLoader.loadList("EnergyDrop.json", EnergyDropEntry.class).forEach(entry -> {
energyDropData.put(entry.getDropId(), entry.getDropList());
});
DataLoader.loadList("EnergyDrop.json", EnergyDropEntry.class)
.forEach(
entry -> {
energyDropData.put(entry.getDropId(), entry.getDropList());
});
Grasscutter.getLogger().debug("Energy drop data successfully loaded.");
}
catch (Exception ex) {
} catch (Exception ex) {
Grasscutter.getLogger().error("Unable to load energy drop data.", ex);
}
// Read the data for particle generation from skills
try {
DataLoader.loadList("SkillParticleGeneration.json", SkillParticleGenerationEntry.class).forEach(entry -> {
skillParticleGenerationData.put(entry.getAvatarId(), entry.getAmountList());
});
DataLoader.loadList("SkillParticleGeneration.json", SkillParticleGenerationEntry.class)
.forEach(
entry -> {
skillParticleGenerationData.put(entry.getAvatarId(), entry.getAmountList());
});
Grasscutter.getLogger().debug("Skill particle generation data successfully loaded.");
}
catch (Exception ex) {
} catch (Exception ex) {
Grasscutter.getLogger().error("Unable to load skill particle generation data data.", ex);
}
}
/**
* Particle creation for elemental skills.
*/
/** Particle creation for elemental skills. */
private int getBallCountForAvatar(int avatarId) {
// We default to two particles.
int count = 2;
@@ -133,13 +123,16 @@ public class EnergyManager extends BasePlayerManager {
};
}
public void handleGenerateElemBall(AbilityInvokeEntry invoke) throws InvalidProtocolBufferException {
public void handleGenerateElemBall(AbilityInvokeEntry invoke)
throws InvalidProtocolBufferException {
// ToDo:
// This is also called when a weapon like Favonius Warbow etc. creates energy through its passive.
// This is also called when a weapon like Favonius Warbow etc. creates energy through its
// passive.
// We are not handling this correctly at the moment.
// Get action info.
AbilityActionGenerateElemBall action = AbilityActionGenerateElemBall.parseFrom(invoke.getAbilityData());
AbilityActionGenerateElemBall action =
AbilityActionGenerateElemBall.parseFrom(invoke.getAbilityData());
if (action == null) {
return;
}
@@ -151,7 +144,8 @@ public class EnergyManager extends BasePlayerManager {
int amount = 2;
// Try to get the casting avatar from the player's party.
Optional<EntityAvatar> avatarEntity = this.getCastingAvatarEntityForEnergy(invoke.getEntityId());
Optional<EntityAvatar> avatarEntity =
this.getCastingAvatarEntityForEnergy(invoke.getEntityId());
// Bug: invokes twice sometimes, Ayato, Keqing
// ToDo: deal with press, hold difference. deal with charge(Beidou, Yunjin)
@@ -183,6 +177,7 @@ public class EnergyManager extends BasePlayerManager {
/**
* Energy generation for NAs/CAs.
*
* @param avatar The avatar.
*/
private void generateEnergyForNormalAndCharged(EntityAvatar avatar) {
@@ -214,7 +209,8 @@ public class EnergyManager extends BasePlayerManager {
}
// Otherwise, we increase the probability for the next hit.
else {
this.avatarNormalProbabilities.put(avatar, currentProbability + weaponType.getEnergyGainIncreaseProbability());
this.avatarNormalProbabilities.put(
avatar, currentProbability + weaponType.getEnergyGainIncreaseProbability());
}
}
@@ -223,8 +219,11 @@ public class EnergyManager extends BasePlayerManager {
AttackResult attackRes = hitInfo.getAttackResult();
// Make sure the attack was performed by the currently active avatar. If not, we ignore the hit.
Optional<EntityAvatar> attackerEntity = this.getCastingAvatarEntityForEnergy(attackRes.getAttackerId());
if (attackerEntity.isEmpty() || this.player.getTeamManager().getCurrentAvatarEntity().getId() != attackerEntity.get().getId()) {
Optional<EntityAvatar> attackerEntity =
this.getCastingAvatarEntityForEnergy(attackRes.getAttackerId());
if (attackerEntity.isEmpty()
|| this.player.getTeamManager().getCurrentAvatarEntity().getId()
!= attackerEntity.get().getId()) {
return;
}
@@ -276,9 +275,10 @@ public class EnergyManager extends BasePlayerManager {
public void handleEvtDoSkillSuccNotify(GameSession session, int skillId, int casterId) {
// Determine the entity that has cast the skill. Cancel if we can't find that avatar.
Optional<EntityAvatar> caster = this.player.getTeamManager().getActiveTeam().stream()
.filter(character -> character.getId() == casterId)
.findFirst();
Optional<EntityAvatar> caster =
this.player.getTeamManager().getActiveTeam().stream()
.filter(character -> character.getId() == casterId)
.findFirst();
if (caster.isEmpty()) {
return;
@@ -306,7 +306,8 @@ public class EnergyManager extends BasePlayerManager {
}
}
public void handleMonsterEnergyDrop(EntityMonster monster, float hpBeforeDamage, float hpAfterDamage) {
public void handleMonsterEnergyDrop(
EntityMonster monster, float hpBeforeDamage, float hpAfterDamage) {
// Make sure this is actually a monster.
// Note that some wildlife also has that type, like boars or birds.
MonsterType type = monster.getMonsterData().getType();
@@ -348,13 +349,16 @@ public class EnergyManager extends BasePlayerManager {
return;
}
EntityItem energyBall = new EntityItem(this.getPlayer().getScene(), this.getPlayer(), itemData, position, count);
EntityItem energyBall =
new EntityItem(this.getPlayer().getScene(), this.getPlayer(), itemData, position, count);
this.getPlayer().getScene().addEntity(energyBall);
}
private Optional<EntityAvatar> getCastingAvatarEntityForEnergy(int invokeEntityId) {
// To determine the avatar that has cast the skill that caused the energy particle to be generated,
// we have to look at the entity that has invoked the ability. This can either be that avatar directly,
// To determine the avatar that has cast the skill that caused the energy particle to be
// generated,
// we have to look at the entity that has invoked the ability. This can either be that avatar
// directly,
// or it can be an `EntityClientGadget`, owned (some way up the owner hierarchy) by the avatar
// that cast the skill.
@@ -364,30 +368,51 @@ public class EnergyManager extends BasePlayerManager {
// Determine the ID of the entity that originally cast this skill. If the scene entity is null,
// or not an `EntityClientGadget`, we assume that we are directly looking at the casting avatar
// (the null case will happen if the avatar was switched out between casting the skill and the
// particle being generated). If the scene entity is an `EntityClientGadget`, we need to find the
// particle being generated). If the scene entity is an `EntityClientGadget`, we need to find
// the
// ID of the original owner of that gadget.
int avatarEntityId =
(!(entity instanceof EntityClientGadget))
? invokeEntityId
: ((EntityClientGadget)entity).getOriginalOwnerEntityId();
: ((EntityClientGadget) entity).getOriginalOwnerEntityId();
// Finally, find the avatar entity in the player's team.
return this.player.getTeamManager().getActiveTeam()
.stream()
return this.player.getTeamManager().getActiveTeam().stream()
.filter(character -> character.getId() == avatarEntityId)
.findFirst();
}
public boolean getEnergyUsage() {
return this.energyUsage;
/**
* Refills the energy of the active avatar.
*
* @return True if the energy was refilled, false otherwise.
*/
public boolean refillActiveEnergy() {
var activeEntity = this.player.getTeamManager().getCurrentAvatarEntity();
return activeEntity.addEnergy(
activeEntity.getAvatar().getSkillDepot().getEnergySkillData().getCostElemVal());
}
/**
* Refills the energy of the entire team.
*
* @param changeReason The reason for the energy change.
* @param isFlat Whether the energy should be added as a flat value.
*/
public void refillTeamEnergy(PropChangeReason changeReason, boolean isFlat) {
for (var entityAvatar : this.player.getTeamManager().getActiveTeam()) {
// giving the exact amount read off the AvatarSkillData.json
entityAvatar.addEnergy(
entityAvatar.getAvatar().getSkillDepot().getEnergySkillData().getCostElemVal(),
changeReason,
isFlat);
}
}
public void setEnergyUsage(boolean energyUsage) {
this.energyUsage = energyUsage;
if (!energyUsage) { // Refill team energy if usage is disabled
for (EntityAvatar entityAvatar : this.player.getTeamManager().getActiveTeam()) {
entityAvatar.addEnergy(1000, PropChangeReason.PROP_CHANGE_REASON_GM,true);
}
if (!energyUsage) { // Refill team energy if usage is disabled
this.refillTeamEnergy(PropChangeReason.PROP_CHANGE_REASON_GM, true);
}
}
}

View File

@@ -3,14 +3,14 @@ package emu.grasscutter.game.managers.energy;
import java.util.List;
public class SkillParticleGenerationEntry {
private int avatarId;
private List<SkillParticleGenerationInfo> amountList;
private int avatarId;
private List<SkillParticleGenerationInfo> amountList;
public int getAvatarId() {
return this.avatarId;
}
public int getAvatarId() {
return this.avatarId;
}
public List<SkillParticleGenerationInfo> getAmountList() {
return this.amountList;
}
public List<SkillParticleGenerationInfo> getAmountList() {
return this.amountList;
}
}

View File

@@ -1,14 +1,14 @@
package emu.grasscutter.game.managers.energy;
public class SkillParticleGenerationInfo {
private int value;
private int chance;
private int value;
private int chance;
public int getValue() {
return this.value;
}
public int getValue() {
return this.value;
}
public int getChance() {
return this.chance;
}
public int getChance() {
return this.chance;
}
}

View File

@@ -26,10 +26,9 @@ public class ActiveForgeData {
}
public int getNextFinishTimestamp(int currentTime) {
return
(currentTime >= this.getTotalFinishTimestamp())
? this.getTotalFinishTimestamp()
: (this.getFinishedCount(currentTime) * this.forgeTime + this.forgeTime + this.startTime);
return (currentTime >= this.getTotalFinishTimestamp())
? this.getTotalFinishTimestamp()
: (this.getFinishedCount(currentTime) * this.forgeTime + this.forgeTime + this.startTime);
}
public int getTotalFinishTimestamp() {
@@ -39,6 +38,7 @@ public class ActiveForgeData {
public int getForgeId() {
return this.forgeId;
}
public void setForgeId(int value) {
this.forgeId = value;
}
@@ -46,6 +46,7 @@ public class ActiveForgeData {
public int getAvatarId() {
return this.avatarId;
}
public void setAvatarId(int value) {
this.avatarId = value;
}
@@ -53,6 +54,7 @@ public class ActiveForgeData {
public int getCount() {
return count;
}
public void setCount(int value) {
this.count = value;
}
@@ -60,6 +62,7 @@ public class ActiveForgeData {
public int getStartTime() {
return this.startTime;
}
public void setStartTime(int value) {
this.startTime = value;
}
@@ -67,6 +70,7 @@ public class ActiveForgeData {
public int getForgeTime() {
return this.forgeTime;
}
public void setForgeTime(int value) {
this.forgeTime = value;
}
@@ -74,6 +78,7 @@ public class ActiveForgeData {
public boolean isChanged() {
return this.changed;
}
public void setChanged(boolean value) {
this.changed = value;
}

View File

@@ -1,10 +1,5 @@
package emu.grasscutter.game.managers.forging;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.common.ItemParamData;
import emu.grasscutter.data.excels.ForgeData;
@@ -19,13 +14,12 @@ import emu.grasscutter.net.proto.ForgeQueueManipulateReqOuterClass.ForgeQueueMan
import emu.grasscutter.net.proto.ForgeQueueManipulateTypeOuterClass.ForgeQueueManipulateType;
import emu.grasscutter.net.proto.ForgeStartReqOuterClass.ForgeStartReq;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
import emu.grasscutter.server.packet.send.PacketForgeDataNotify;
import emu.grasscutter.server.packet.send.PacketForgeFormulaDataNotify;
import emu.grasscutter.server.packet.send.PacketForgeGetQueueDataRsp;
import emu.grasscutter.server.packet.send.PacketForgeQueueDataNotify;
import emu.grasscutter.server.packet.send.PacketForgeQueueManipulateRsp;
import emu.grasscutter.server.packet.send.PacketForgeStartRsp;
import emu.grasscutter.server.packet.send.*;
import emu.grasscutter.utils.Utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ForgingManager extends BasePlayerManager {
@@ -34,27 +28,23 @@ public class ForgingManager extends BasePlayerManager {
}
/**********
Blueprint unlocking.
**********/
* Blueprint unlocking.
**********/
public boolean unlockForgingBlueprint(int id) {
// Tell the client that this blueprint is now unlocked and add the unlocked item to the player.
if (!this.player.getUnlockedForgingBlueprints().add(id)) {
return false; // Already unlocked
return false; // Already unlocked
}
this.player.sendPacket(new PacketForgeFormulaDataNotify(id));
return true;
}
/**********
Communicate forging information to the client.
**********/
* Communicate forging information to the client.
**********/
private synchronized int determineNumberOfQueues() {
int adventureRank = player.getLevel();
return
(adventureRank >= 15) ? 4
: (adventureRank >= 10) ? 3
: (adventureRank >= 5) ? 2
: 1;
return (adventureRank >= 15) ? 4 : (adventureRank >= 10) ? 3 : (adventureRank >= 5) ? 2 : 1;
}
private synchronized Map<Integer, ForgeQueueData> determineCurrentForgeQueueData() {
@@ -65,15 +55,16 @@ public class ForgingManager extends BasePlayerManager {
for (int i = 0; i < this.player.getActiveForges().size(); i++) {
ActiveForgeData activeForge = this.player.getActiveForges().get(i);
ForgeQueueData data = ForgeQueueData.newBuilder()
.setQueueId(i + 1)
.setForgeId(activeForge.getForgeId())
.setFinishCount(activeForge.getFinishedCount(currentTime))
.setUnfinishCount(activeForge.getUnfinishedCount(currentTime))
.setTotalFinishTimestamp(activeForge.getTotalFinishTimestamp())
.setNextFinishTimestamp(activeForge.getNextFinishTimestamp(currentTime))
.setAvatarId(activeForge.getAvatarId())
.build();
ForgeQueueData data =
ForgeQueueData.newBuilder()
.setQueueId(i + 1)
.setForgeId(activeForge.getForgeId())
.setFinishCount(activeForge.getFinishedCount(currentTime))
.setUnfinishCount(activeForge.getUnfinishedCount(currentTime))
.setTotalFinishTimestamp(activeForge.getTotalFinishTimestamp())
.setNextFinishTimestamp(activeForge.getNextFinishTimestamp(currentTime))
.setAvatarId(activeForge.getAvatarId())
.build();
res.put(i + 1, data);
}
@@ -101,12 +92,13 @@ public class ForgingManager extends BasePlayerManager {
}
/**********
Initiate forging process.
**********/
* Initiate forging process.
**********/
private synchronized void sendForgeQueueDataNotify() {
var queueData = this.determineCurrentForgeQueueData();
this.player.sendPacket(new PacketForgeQueueDataNotify(queueData, List.of()));
}
private synchronized void sendForgeQueueDataNotify(boolean hasRemoved) {
var queueData = this.determineCurrentForgeQueueData();
@@ -126,13 +118,14 @@ public class ForgingManager extends BasePlayerManager {
// Get the required forging information for the target item.
if (!GameData.getForgeDataMap().containsKey(req.getForgeId())) {
this.player.sendPacket(new PacketForgeStartRsp(Retcode.RET_FAIL)); //ToDo: Probably the wrong return code.
this.player.sendPacket(
new PacketForgeStartRsp(Retcode.RET_FAIL)); // ToDo: Probably the wrong return code.
return;
}
ForgeData forgeData = GameData.getForgeDataMap().get(req.getForgeId());
//Check if the player has sufficient forge points.
// Check if the player has sufficient forge points.
int requiredPoints = forgeData.getForgePoint() * req.getForgeCount();
if (requiredPoints > this.player.getForgePoints()) {
this.player.sendPacket(new PacketForgeStartRsp(Retcode.RET_FORGE_POINT_NOT_ENOUGH));
@@ -143,11 +136,14 @@ public class ForgingManager extends BasePlayerManager {
List<ItemParamData> material = new ArrayList<>(forgeData.getMaterialItems());
material.add(new ItemParamData(202, forgeData.getScoinCost()));
boolean success = player.getInventory().payItems(material, req.getForgeCount(), ActionReason.ForgeCost);
boolean success =
player.getInventory().payItems(material, req.getForgeCount(), ActionReason.ForgeCost);
if (!success) {
//TODO:I'm not sure this one is correct.
this.player.sendPacket(new PacketForgeStartRsp(Retcode.RET_ITEM_COUNT_NOT_ENOUGH)); //ToDo: Probably the wrong return code.
// TODO:I'm not sure this one is correct.
this.player.sendPacket(
new PacketForgeStartRsp(
Retcode.RET_ITEM_COUNT_NOT_ENOUGH)); // ToDo: Probably the wrong return code.
}
// Consume forge points.
@@ -169,8 +165,8 @@ public class ForgingManager extends BasePlayerManager {
}
/**********
Forge queue manipulation (obtaining results and cancelling forges).
**********/
* Forge queue manipulation (obtaining results and cancelling forges).
**********/
private synchronized void obtainItems(int queueId) {
// Determine how many items are finished.
int currentTime = Utils.getCurrentSeconds();
@@ -193,7 +189,9 @@ public class ForgingManager extends BasePlayerManager {
this.player.getInventory().addItem(addItem);
// Battle pass trigger handler
this.player.getBattlePassManager().triggerMission(WatcherTriggerType.TRIGGER_DO_FORGE, 0, finished);
this.player
.getBattlePassManager()
.triggerMission(WatcherTriggerType.TRIGGER_DO_FORGE, 0, finished);
// Replace active forge with a new one for the unfinished items, if there are any.
if (unfinished > 0) {
@@ -216,7 +214,13 @@ public class ForgingManager extends BasePlayerManager {
}
// Send response.
this.player.sendPacket(new PacketForgeQueueManipulateRsp(Retcode.RET_SUCC, ForgeQueueManipulateType.FORGE_QUEUE_MANIPULATE_TYPE_RECEIVE_OUTPUT, List.of(addItem), List.of(), List.of()));
this.player.sendPacket(
new PacketForgeQueueManipulateRsp(
Retcode.RET_SUCC,
ForgeQueueManipulateType.FORGE_QUEUE_MANIPULATE_TYPE_RECEIVE_OUTPUT,
List.of(addItem),
List.of(),
List.of()));
}
private synchronized void cancelForge(int queueId) {
@@ -238,7 +242,8 @@ public class ForgingManager extends BasePlayerManager {
}
ItemData resultItemData = GameData.getItemDataMap().get(material.getItemId());
GameItem returnItem = new GameItem(resultItemData, material.getItemCount() * forge.getCount());
GameItem returnItem =
new GameItem(resultItemData, material.getItemCount() * forge.getCount());
this.player.getInventory().addItem(returnItem);
returnItems.add(returnItem);
@@ -262,7 +267,13 @@ public class ForgingManager extends BasePlayerManager {
this.sendForgeQueueDataNotify(true);
// Send response.
this.player.sendPacket(new PacketForgeQueueManipulateRsp(Retcode.RET_SUCC, ForgeQueueManipulateType.FORGE_QUEUE_MANIPULATE_TYPE_STOP_FORGE, List.of(), returnItems, List.of()));
this.player.sendPacket(
new PacketForgeQueueManipulateRsp(
Retcode.RET_SUCC,
ForgeQueueManipulateType.FORGE_QUEUE_MANIPULATE_TYPE_STOP_FORGE,
List.of(),
returnItems,
List.of()));
}
public synchronized void handleForgeQueueManipulateReq(ForgeQueueManipulateReq req) {
@@ -274,14 +285,13 @@ public class ForgingManager extends BasePlayerManager {
switch (manipulateType) {
case FORGE_QUEUE_MANIPULATE_TYPE_RECEIVE_OUTPUT -> this.obtainItems(queueId);
case FORGE_QUEUE_MANIPULATE_TYPE_STOP_FORGE -> this.cancelForge(queueId);
default -> {
} //Should never happen.
default -> {} // Should never happen.
}
}
/**********
Periodic forging updates.
**********/
* Periodic forging updates.
**********/
public synchronized void sendPlayerForgingUpdate() {
int currentTime = Utils.getCurrentSeconds();
@@ -292,8 +302,8 @@ public class ForgingManager extends BasePlayerManager {
return;
}
boolean hasChanges = this.player.getActiveForges().stream()
.anyMatch(forge -> forge.updateChanged(currentTime));
boolean hasChanges =
this.player.getActiveForges().stream().anyMatch(forge -> forge.updateChanged(currentTime));
if (!hasChanges) {
return;
@@ -303,7 +313,6 @@ public class ForgingManager extends BasePlayerManager {
this.sendForgeQueueDataNotify();
// Reset changed flags.
this.player.getActiveForges().stream()
.forEach(forge -> forge.setChanged(false));
this.player.getActiveForges().stream().forEach(forge -> forge.setChanged(false));
}
}

View File

@@ -1,10 +1,10 @@
package emu.grasscutter.game.managers.mapmark;
import dev.morphia.annotations.Entity;
import emu.grasscutter.game.world.Position;
import emu.grasscutter.net.proto.MapMarkFromTypeOuterClass.MapMarkFromType;
import emu.grasscutter.net.proto.MapMarkPointOuterClass.MapMarkPoint;
import emu.grasscutter.net.proto.MapMarkPointTypeOuterClass.MapMarkPointType;
import emu.grasscutter.utils.Position;
@Entity
public class MapMark {

View File

@@ -3,14 +3,13 @@ package emu.grasscutter.game.managers.mapmark;
import emu.grasscutter.config.Configuration;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.world.Position;
import emu.grasscutter.net.proto.MapMarkPointTypeOuterClass.MapMarkPointType;
import emu.grasscutter.net.proto.MarkMapReqOuterClass.MarkMapReq;
import emu.grasscutter.net.proto.MarkMapReqOuterClass.MarkMapReq.Operation;
import emu.grasscutter.server.event.player.PlayerTeleportEvent.TeleportType;
import emu.grasscutter.server.packet.send.PacketMarkMapRsp;
import emu.grasscutter.server.packet.send.PacketSceneEntityAppearNotify;
import emu.grasscutter.utils.Position;
import java.util.Map;
public class MapMarksManager extends BasePlayerManager {
@@ -30,7 +29,8 @@ public class MapMarksManager extends BasePlayerManager {
case OPERATION_ADD -> {
MapMark createMark = new MapMark(req.getMark());
// keep teleporting functionality on fishhook mark.
if (Configuration.GAME_OPTIONS.fishhookTeleport && createMark.getMapMarkPointType() == MapMarkPointType.MAP_MARK_POINT_TYPE_FISH_POOL) {
if (Configuration.GAME_OPTIONS.fishhookTeleport
&& createMark.getMapMarkPointType() == MapMarkPointType.MAP_MARK_POINT_TYPE_FISH_POOL) {
this.teleport(player, createMark);
return;
}
@@ -54,7 +54,7 @@ public class MapMarksManager extends BasePlayerManager {
}
public String getMapMarkKey(Position position) {
return "x" + (int)position.getX()+ "z" + (int)position.getZ();
return "x" + (int) position.getX() + "z" + (int) position.getZ();
}
public void removeMapMark(Position position) {
@@ -76,7 +76,13 @@ public class MapMarksManager extends BasePlayerManager {
}
Position pos = mapMark.getPosition();
player.getWorld().transferPlayerToScene(player, mapMark.getSceneId(), TeleportType.MAP, new Position(pos.getX(), y, pos.getZ()));
player
.getWorld()
.transferPlayerToScene(
player,
mapMark.getSceneId(),
TeleportType.MAP,
new Position(pos.getX(), y, pos.getZ()));
player.getScene().broadcastPacket(new PacketSceneEntityAppearNotify(player));
}
}

View File

@@ -2,10 +2,10 @@ package emu.grasscutter.game.managers.stamina;
public interface AfterUpdateStaminaListener {
/**
* onBeforeUpdateStamina() will be called before StaminaManager attempt to update the player's current stamina.
* This gives listeners a chance to intercept this update.
* onBeforeUpdateStamina() will be called before StaminaManager attempt to update the player's
* current stamina. This gives listeners a chance to intercept this update.
*
* @param reason Why updating stamina.
* @param reason Why updating stamina.
* @param newStamina New Stamina value.
*/
void onAfterUpdateStamina(String reason, int newStamina, boolean isCharacterStamina);

View File

@@ -2,19 +2,23 @@ package emu.grasscutter.game.managers.stamina;
public interface BeforeUpdateStaminaListener {
/**
* onBeforeUpdateStamina() will be called before StaminaManager attempt to update the player's current stamina.
* This gives listeners a chance to intercept this update.
* onBeforeUpdateStamina() will be called before StaminaManager attempt to update the player's
* current stamina. This gives listeners a chance to intercept this update.
*
* @param reason Why updating stamina.
* @param newStamina New ABSOLUTE stamina value.
* @return true if you want to cancel this update, otherwise false.
*/
int onBeforeUpdateStamina(String reason, int newStamina, boolean isCharacterStamina);
/**
* onBeforeUpdateStamina() will be called before StaminaManager attempt to update the player's current stamina.
* This gives listeners a chance to intercept this update.
* onBeforeUpdateStamina() will be called before StaminaManager attempt to update the player's
* current stamina. This gives listeners a chance to intercept this update.
*
* @param reason Why updating stamina.
* @param consumption ConsumptionType and RELATIVE stamina change amount.
* @return true if you want to cancel this update, otherwise false.
*/
Consumption onBeforeUpdateStamina(String reason, Consumption consumption, boolean isCharacterStamina);
}
Consumption onBeforeUpdateStamina(
String reason, Consumption consumption, boolean isCharacterStamina);
}

View File

@@ -13,6 +13,5 @@ public class Consumption {
this(type, type.amount);
}
public Consumption() {
}
public Consumption() {}
}

View File

@@ -34,4 +34,4 @@ public enum ConsumptionType {
ConsumptionType(int amount) {
this.amount = amount;
}
}
}

View File

@@ -1,28 +1,36 @@
# Stamina Manager
---
## UpdateStamina
```java
// will use consumption.consumptionType as reason
public int updateStaminaRelative(GameSession session, Consumption consumption);
```
```java
public int updateStaminaAbsolute(GameSession session, String reason, int newStamina)
```
---
## Pause and Resume
```java
public void startSustainedStaminaHandler()
```
```java
public void stopSustainedStaminaHandler()
```
---
## Stamina change listeners and intercepting
### BeforeUpdateStaminaListener
```java
import emu.grasscutter.game.managers.StaminaManager.BeforeUpdateStaminaListener;
@@ -44,15 +52,14 @@ private class MyClass implements BeforeUpdateStaminaListener {
@Override
public boolean onBeforeUpdateStamina(String reason, Consumption consumption) {
// Try to intercept if this update is CLIMB_JUMP
if (consumption.consumptionType == ConsumptionType.CLIMB_JUMP) {
return true;
}
return consumption.consumptionType == ConsumptionType.CLIMB_JUMP;
// If it is not CLIMB_JUMP, do not intercept.
return false;
}
}
```
### AfterUpdateStaminaListener
```java
import emu.grasscutter.game.managers.StaminaManager.AfterUpdateStaminaListener;
@@ -70,4 +77,4 @@ private class MyClass implements AfterUpdateStaminaListener {
// ...
}
}
```
```

View File

@@ -3,130 +3,107 @@ package emu.grasscutter.game.managers.stamina;
import ch.qos.logback.classic.Logger;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.avatar.Avatar;
import emu.grasscutter.game.entity.EntityAvatar;
import emu.grasscutter.game.entity.GameEntity;
import emu.grasscutter.game.player.BasePlayerManager;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.FightProperty;
import emu.grasscutter.game.props.LifeState;
import emu.grasscutter.game.props.PlayerProperty;
import emu.grasscutter.game.props.WeaponType;
import emu.grasscutter.game.entity.*;
import emu.grasscutter.game.player.*;
import emu.grasscutter.game.props.*;
import emu.grasscutter.game.world.Position;
import emu.grasscutter.net.proto.EntityMoveInfoOuterClass.EntityMoveInfo;
import emu.grasscutter.net.proto.MotionInfoOuterClass.MotionInfo;
import emu.grasscutter.net.proto.MotionStateOuterClass.MotionState;
import emu.grasscutter.net.proto.PlayerDieTypeOuterClass.PlayerDieType;
import emu.grasscutter.net.proto.VectorOuterClass.Vector;
import emu.grasscutter.net.proto.VehicleInteractTypeOuterClass.VehicleInteractType;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.server.packet.send.*;
import emu.grasscutter.utils.Position;
import org.jetbrains.annotations.NotNull;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import java.util.*;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
public class StaminaManager extends BasePlayerManager {
public final static int GlobalCharacterMaximumStamina = PlayerProperty.PROP_MAX_STAMINA.getMax();
public final static int GlobalVehicleMaxStamina = PlayerProperty.PROP_MAX_STAMINA.getMax();
// TODO: Skiff state detection?
private static final Map<String, Set<MotionState>> MotionStatesCategorized = new HashMap<>() {{
put("CLIMB", Set.of(
MotionState.MOTION_STATE_CLIMB, // sustained, when not moving no cost no recover
MotionState.MOTION_STATE_STANDBY_TO_CLIMB // NOT OBSERVED, see MOTION_JUMP_UP_WALL_FOR_STANDBY
MotionState.MOTION_STATE_CLIMB, // sustained, when not moving no cost no recover
MotionState.MOTION_STATE_STANDBY_TO_CLIMB // NOT OBSERVED, see MOTION_JUMP_UP_WALL_FOR_STANDBY
));
put("DASH", Set.of(
MotionState.MOTION_STATE_DANGER_DASH, // sustained
MotionState.MOTION_STATE_DASH // sustained
MotionState.MOTION_STATE_DANGER_DASH, // sustained
MotionState.MOTION_STATE_DASH // sustained
));
put("FLY", Set.of(
MotionState.MOTION_STATE_FLY, // sustained
MotionState.MOTION_STATE_FLY_FAST, // sustained
MotionState.MOTION_STATE_FLY_SLOW, // sustained
MotionState.MOTION_STATE_POWERED_FLY // sustained, recover
MotionState.MOTION_STATE_FLY, // sustained
MotionState.MOTION_STATE_FLY_FAST, // sustained
MotionState.MOTION_STATE_FLY_SLOW, // sustained
MotionState.MOTION_STATE_POWERED_FLY // sustained, recover
));
put("RUN", Set.of(
MotionState.MOTION_STATE_DANGER_RUN, // sustained, recover
MotionState.MOTION_STATE_RUN // sustained, recover
MotionState.MOTION_STATE_DANGER_RUN, // sustained, recover
MotionState.MOTION_STATE_RUN // sustained, recover
));
put("SKIFF", Set.of(
MotionState.MOTION_STATE_SKIFF_BOARDING, // NOT OBSERVED even when boarding
MotionState.MOTION_STATE_SKIFF_DASH, // sustained, observed with waverider entity ID.
MotionState.MOTION_STATE_SKIFF_NORMAL, // sustained, OBSERVED when both normal and dashing
MotionState.MOTION_STATE_SKIFF_POWERED_DASH // sustained, recover
MotionState.MOTION_STATE_SKIFF_BOARDING, // NOT OBSERVED even when boarding
MotionState.MOTION_STATE_SKIFF_DASH, // sustained, observed with waverider entity ID.
MotionState.MOTION_STATE_SKIFF_NORMAL, // sustained, OBSERVED when both normal and dashing
MotionState.MOTION_STATE_SKIFF_POWERED_DASH // sustained, recover
));
put("STANDBY", Set.of(
MotionState.MOTION_STATE_DANGER_STANDBY_MOVE, // sustained, recover
MotionState.MOTION_STATE_DANGER_STANDBY, // sustained, recover
MotionState.MOTION_STATE_LADDER_TO_STANDBY, // NOT OBSERVED
MotionState.MOTION_STATE_STANDBY_MOVE, // sustained, recover
MotionState.MOTION_STATE_STANDBY // sustained, recover
MotionState.MOTION_STATE_DANGER_STANDBY_MOVE, // sustained, recover
MotionState.MOTION_STATE_DANGER_STANDBY, // sustained, recover
MotionState.MOTION_STATE_LADDER_TO_STANDBY, // NOT OBSERVED
MotionState.MOTION_STATE_STANDBY_MOVE, // sustained, recover
MotionState.MOTION_STATE_STANDBY // sustained, recover
));
put("SWIM", Set.of(
MotionState.MOTION_STATE_SWIM_IDLE, // sustained
MotionState.MOTION_STATE_SWIM_DASH, // immediate and sustained
MotionState.MOTION_STATE_SWIM_JUMP, // NOT OBSERVED
MotionState.MOTION_STATE_SWIM_MOVE // sustained
MotionState.MOTION_STATE_SWIM_IDLE, // sustained
MotionState.MOTION_STATE_SWIM_DASH, // immediate and sustained
MotionState.MOTION_STATE_SWIM_JUMP, // NOT OBSERVED
MotionState.MOTION_STATE_SWIM_MOVE // sustained
));
put("WALK", Set.of(
MotionState.MOTION_STATE_DANGER_WALK, // sustained, recover
MotionState.MOTION_STATE_WALK // sustained, recover
MotionState.MOTION_STATE_DANGER_WALK, // sustained, recover
MotionState.MOTION_STATE_WALK // sustained, recover
));
put("OTHER", Set.of(
MotionState.MOTION_STATE_CLIMB_JUMP, // cost only once if repeated without switching state
MotionState.MOTION_STATE_DASH_BEFORE_SHAKE, // immediate one time sprint charge.
MotionState.MOTION_STATE_FIGHT, // immediate, if sustained then subsequent will be MOTION_NOTIFY
MotionState.MOTION_STATE_JUMP_UP_WALL_FOR_STANDBY, // immediate, observed when RUN/WALK->CLIMB
MotionState.MOTION_STATE_NOTIFY, // can be either cost or recover - check previous state and check skill casting
MotionState.MOTION_STATE_SIT_IDLE, // sustained, recover
MotionState.MOTION_STATE_JUMP // recover
MotionState.MOTION_STATE_CLIMB_JUMP, // cost only once if repeated without switching state
MotionState.MOTION_STATE_DASH_BEFORE_SHAKE, // immediate one time sprint charge.
MotionState.MOTION_STATE_FIGHT, // immediate, if sustained then subsequent will be MOTION_NOTIFY
MotionState.MOTION_STATE_JUMP_UP_WALL_FOR_STANDBY, // immediate, observed when RUN/WALK->CLIMB
MotionState.MOTION_STATE_NOTIFY, // can be either cost or recover - check previous state and check skill casting
MotionState.MOTION_STATE_SIT_IDLE, // sustained, recover
MotionState.MOTION_STATE_JUMP // recover
));
put("NOCOST_NORECOVER", Set.of(
MotionState.MOTION_STATE_LADDER_SLIP, // NOT OBSERVED
MotionState.MOTION_STATE_SLIP, // sustained, no cost no recover
MotionState.MOTION_STATE_FLY_IDLE // NOT OBSERVED
MotionState.MOTION_STATE_LADDER_SLIP, // NOT OBSERVED
MotionState.MOTION_STATE_SLIP, // sustained, no cost no recover
MotionState.MOTION_STATE_FLY_IDLE // NOT OBSERVED
));
put("IGNORE", Set.of(
// these states have no impact on stamina
MotionState.MOTION_STATE_CROUCH_IDLE,
MotionState.MOTION_STATE_CROUCH_MOVE,
MotionState.MOTION_STATE_CROUCH_ROLL,
MotionState.MOTION_STATE_DESTROY_VEHICLE,
MotionState.MOTION_STATE_FALL_ON_GROUND,
MotionState.MOTION_STATE_FOLLOW_ROUTE,
MotionState.MOTION_STATE_FORCE_SET_POS,
MotionState.MOTION_STATE_GO_UPSTAIRS,
MotionState.MOTION_STATE_JUMP_OFF_WALL,
MotionState.MOTION_STATE_LADDER_IDLE,
MotionState.MOTION_STATE_LADDER_MOVE,
MotionState.MOTION_STATE_LAND_SPEED,
MotionState.MOTION_STATE_MOVE_FAIL_ACK,
MotionState.MOTION_STATE_NONE,
MotionState.MOTION_STATE_NUM,
MotionState.MOTION_STATE_QUEST_FORCE_DRAG,
MotionState.MOTION_STATE_RESET,
MotionState.MOTION_STATE_STANDBY_TO_LADDER,
MotionState.MOTION_STATE_WATERFALL
// these states have no impact on stamina
MotionState.MOTION_STATE_CROUCH_IDLE,
MotionState.MOTION_STATE_CROUCH_MOVE,
MotionState.MOTION_STATE_CROUCH_ROLL,
MotionState.MOTION_STATE_DESTROY_VEHICLE,
MotionState.MOTION_STATE_FALL_ON_GROUND,
MotionState.MOTION_STATE_FOLLOW_ROUTE,
MotionState.MOTION_STATE_FORCE_SET_POS,
MotionState.MOTION_STATE_GO_UPSTAIRS,
MotionState.MOTION_STATE_JUMP_OFF_WALL,
MotionState.MOTION_STATE_LADDER_IDLE,
MotionState.MOTION_STATE_LADDER_MOVE,
MotionState.MOTION_STATE_LAND_SPEED,
MotionState.MOTION_STATE_MOVE_FAIL_ACK,
MotionState.MOTION_STATE_NONE,
MotionState.MOTION_STATE_NUM,
MotionState.MOTION_STATE_QUEST_FORCE_DRAG,
MotionState.MOTION_STATE_RESET,
MotionState.MOTION_STATE_STANDBY_TO_LADDER,
MotionState.MOTION_STATE_WATERFALL
));
}};
private final Logger logger = Grasscutter.getLogger();
public final static int GlobalCharacterMaximumStamina = PlayerProperty.PROP_MAX_STAMINA.getMax();
public final static int GlobalVehicleMaxStamina = PlayerProperty.PROP_MAX_STAMINA.getMax();
private Position currentCoordinates = new Position(0, 0, 0);
private Position previousCoordinates = new Position(0, 0, 0);
private MotionState currentState = MotionState.MOTION_STATE_STANDBY;
private MotionState previousState = MotionState.MOTION_STATE_STANDBY;
private Timer sustainedStaminaHandlerTimer;
private GameSession cachedSession = null;
private GameEntity cachedEntity = null;
private int staminaRecoverDelay = 0;
private final HashMap<String, BeforeUpdateStaminaListener> beforeUpdateStaminaListeners = new HashMap<>();
private final HashMap<String, AfterUpdateStaminaListener> afterUpdateStaminaListeners = new HashMap<>();
private int lastSkillId = 0;
private int lastSkillCasterId = 0;
private boolean lastSkillFirstTick = true;
private int vehicleId = -1;
private int vehicleStamina = GlobalVehicleMaxStamina;
private static final Set<Integer> TalentMovements = Set.of(10013, 10413);
private static final HashMap<Integer, Float> ClimbFoodReductionMap = new HashMap<>() {{
// TODO: get real food id
@@ -156,14 +133,31 @@ public class StaminaManager extends BasePlayerManager {
put(542301, 0.8f);
}};
public static void initialize() {
// TODO: Initialize foods etc.
}
private final Logger logger = Grasscutter.getLogger();
private final HashMap<String, BeforeUpdateStaminaListener> beforeUpdateStaminaListeners = new HashMap<>();
private final HashMap<String, AfterUpdateStaminaListener> afterUpdateStaminaListeners = new HashMap<>();
private Position currentCoordinates = new Position(0, 0, 0);
private Position previousCoordinates = new Position(0, 0, 0);
private MotionState currentState = MotionState.MOTION_STATE_STANDBY;
private MotionState previousState = MotionState.MOTION_STATE_STANDBY;
private Timer sustainedStaminaHandlerTimer;
private GameSession cachedSession = null;
private GameEntity cachedEntity = null;
private int staminaRecoverDelay = 0;
private int lastSkillId = 0;
private int lastSkillCasterId = 0;
private boolean lastSkillFirstTick = true;
private int vehicleId = -1;
private int vehicleStamina = GlobalVehicleMaxStamina;
public StaminaManager(Player player) {
super(player);
}
public static void initialize() {
// TODO: Initialize foods etc.
}
// Accessors
public void setSkillCast(int skillId, int skillCasterId) {
@@ -236,7 +230,7 @@ public class StaminaManager extends BasePlayerManager {
float diffY = currentCoordinates.getY() - previousCoordinates.getY();
float diffZ = currentCoordinates.getZ() - previousCoordinates.getZ();
logger.trace("isPlayerMoving: " + previousCoordinates + ", " + currentCoordinates +
", " + diffX + ", " + diffY + ", " + diffZ);
", " + diffX + ", " + diffY + ", " + diffZ);
return Math.abs(diffX) > 0.3 || Math.abs(diffY) > 0.2 || Math.abs(diffZ) > 0.3;
}
@@ -245,26 +239,30 @@ public class StaminaManager extends BasePlayerManager {
if (consumption.amount == 0) {
return currentStamina;
}
// notify will update
for (Map.Entry<String, BeforeUpdateStaminaListener> listener : beforeUpdateStaminaListeners.entrySet()) {
Consumption overriddenConsumption = listener.getValue().onBeforeUpdateStamina(consumption.type.toString(), consumption, isCharacterStamina);
if ((overriddenConsumption.type != consumption.type) && (overriddenConsumption.amount != consumption.amount)) {
logger.debug("Stamina update relative(" +
consumption.type.toString() + ", " + consumption.amount + ") overridden to relative(" +
consumption.type.toString() + ", " + consumption.amount + ") by: " + listener.getKey());
consumption.type.toString() + ", " + consumption.amount + ") overridden to relative(" +
consumption.type.toString() + ", " + consumption.amount + ") by: " + listener.getKey());
return currentStamina;
}
}
int maxStamina = isCharacterStamina ? getMaxCharacterStamina() : getMaxVehicleStamina();
logger.trace((isCharacterStamina ? "C " : "V ") + currentStamina + "/" + maxStamina + "\t" + currentState + "\t" +
(isPlayerMoving() ? "moving" : " ") + "\t(" + consumption.type + "," +
consumption.amount + ")");
(isPlayerMoving() ? "moving" : " ") + "\t(" + consumption.type + "," +
consumption.amount + ")");
int newStamina = currentStamina + consumption.amount;
if (newStamina < 0) {
newStamina = 0;
} else if (newStamina > maxStamina) {
newStamina = maxStamina;
}
return setStamina(session, consumption.type.toString(), newStamina, isCharacterStamina);
}
@@ -275,8 +273,8 @@ public class StaminaManager extends BasePlayerManager {
int overriddenNewStamina = listener.getValue().onBeforeUpdateStamina(reason, newStamina, isCharacterStamina);
if (overriddenNewStamina != newStamina) {
logger.debug("Stamina update absolute(" +
reason + ", " + newStamina + ") overridden to absolute(" +
reason + ", " + newStamina + ") by: " + listener.getKey());
reason + ", " + newStamina + ") overridden to absolute(" +
reason + ", " + newStamina + ") by: " + listener.getKey());
return currentStamina;
}
}
@@ -292,7 +290,7 @@ public class StaminaManager extends BasePlayerManager {
// Returns new stamina and sends PlayerPropNotify or VehicleStaminaNotify
public int setStamina(GameSession session, String reason, int newStamina, boolean isCharacterStamina) {
// Target Player
if (!GAME_OPTIONS.staminaUsage || session.getPlayer().getUnlimitedStamina()) {
if (!GAME_OPTIONS.staminaUsage || session.getPlayer().isUnlimitedStamina()) {
newStamina = getMaxCharacterStamina();
}
@@ -313,7 +311,7 @@ public class StaminaManager extends BasePlayerManager {
// TODO: Probably move this to Avatar class? since other components may also need to kill avatar.
public void killAvatar(GameSession session, GameEntity entity, PlayerDieType dieType) {
session.send(new PacketAvatarLifeStateChangeNotify(player.getTeamManager().getCurrentAvatarEntity().getAvatar(),
LifeState.LIFE_DEAD, dieType));
LifeState.LIFE_DEAD, dieType));
session.send(new PacketLifeStateChangeNotify(entity, LifeState.LIFE_DEAD, dieType));
entity.setFightProperty(FightProperty.FIGHT_PROP_CUR_HP, 0);
entity.getWorld().broadcastPacket(new PacketEntityFightPropUpdateNotify(entity, FightProperty.FIGHT_PROP_CUR_HP));
@@ -326,7 +324,7 @@ public class StaminaManager extends BasePlayerManager {
if (!player.isPaused() && sustainedStaminaHandlerTimer == null) {
sustainedStaminaHandlerTimer = new Timer();
sustainedStaminaHandlerTimer.scheduleAtFixedRate(new SustainedStaminaHandler(), 0, 200);
logger.debug("[MovementManager] SustainedStaminaHandlerTimer started");
logger.trace("[MovementManager] SustainedStaminaHandlerTimer started");
}
}
@@ -334,7 +332,7 @@ public class StaminaManager extends BasePlayerManager {
if (sustainedStaminaHandlerTimer != null) {
sustainedStaminaHandlerTimer.cancel();
sustainedStaminaHandlerTimer = null;
logger.debug("[MovementManager] SustainedStaminaHandlerTimer stopped");
logger.trace("[MovementManager] SustainedStaminaHandlerTimer stopped");
}
}
@@ -352,7 +350,6 @@ public class StaminaManager extends BasePlayerManager {
Avatar currentAvatar = player.getTeamManager().getCurrentAvatarEntity().getAvatar();
if (currentAvatar.getAvatarData().getWeaponType() == WeaponType.WEAPON_CLAYMORE) {
// Exclude claymore as their stamina cost starts when MixinStaminaCost gets in
return;
}
// TODO: Differentiate normal attacks from charged attacks and exclude
// TODO: Temporary: Exclude non-claymore attacks for now
@@ -378,22 +375,27 @@ public class StaminaManager extends BasePlayerManager {
public void handleCombatInvocationsNotify(@NotNull GameSession session, @NotNull EntityMoveInfo moveInfo, @NotNull GameEntity entity) {
// cache info for later use in SustainedStaminaHandler tick
cachedSession = session;
cachedEntity = entity;
MotionInfo motionInfo = moveInfo.getMotionInfo();
MotionState motionState = motionInfo.getState();
int notifyEntityId = entity.getId();
int currentAvatarEntityId = session.getPlayer().getTeamManager().getCurrentAvatarEntity().getId();
this.cachedSession = session;
this.cachedEntity = entity;
// Get the motion data.
var motionInfo = moveInfo.getMotionInfo();
var motionState = motionInfo.getState();
var notifyEntityId = entity.getId();
var currentAvatarEntityId = session.getPlayer().getTeamManager().getCurrentAvatarEntity().getId();
if (notifyEntityId != currentAvatarEntityId && notifyEntityId != vehicleId) {
return;
}
currentState = motionState;
// Update the current state.
this.currentState = motionState;
// logger.trace(currentState + "\t" + (notifyEntityId == currentAvatarEntityId ? "character" : "vehicle"));
Vector posVector = motionInfo.getPos();
Position newPos = new Position(posVector.getX(), posVector.getY(), posVector.getZ());
if (newPos.getX() != 0 && newPos.getY() != 0 && newPos.getZ() != 0) {
currentCoordinates = newPos;
}
startSustainedStaminaHandler();
handleImmediateStamina(session, motionState);
}
@@ -413,23 +415,15 @@ public class StaminaManager extends BasePlayerManager {
// Internal handler
private void handleImmediateStamina(GameSession session, @NotNull MotionState motionState) {
if (currentState == motionState) {
if (motionState.equals(MotionState.MOTION_STATE_CLIMB_JUMP)) {
updateStaminaRelative(session, new Consumption(ConsumptionType.CLIMB_JUMP), true);
}
return;
}
switch (motionState) {
case MOTION_STATE_CLIMB ->
updateStaminaRelative(session, new Consumption(ConsumptionType.CLIMB_START), true);
updateStaminaRelative(session, new Consumption(ConsumptionType.CLIMB_START), true);
case MOTION_STATE_DASH_BEFORE_SHAKE ->
updateStaminaRelative(session, new Consumption(ConsumptionType.SPRINT), true);
updateStaminaRelative(session, new Consumption(ConsumptionType.SPRINT), true);
case MOTION_STATE_CLIMB_JUMP ->
updateStaminaRelative(session, new Consumption(ConsumptionType.CLIMB_JUMP), true);
updateStaminaRelative(session, new Consumption(ConsumptionType.CLIMB_JUMP), true);
case MOTION_STATE_SWIM_DASH ->
updateStaminaRelative(session, new Consumption(ConsumptionType.SWIM_DASH_START), true);
default -> {}
updateStaminaRelative(session, new Consumption(ConsumptionType.SWIM_DASH_START), true);
}
}
@@ -450,6 +444,7 @@ public class StaminaManager extends BasePlayerManager {
(currentCharacterStamina >= maxCharacterStamina) + ", recalculate stamina");
boolean isCharacterStamina = true;
Consumption consumption;
if (MotionStatesCategorized.get("CLIMB").contains(currentState)) {
consumption = getClimbConsumption();
} else if (MotionStatesCategorized.get("DASH").contains(currentState)) {
@@ -510,7 +505,7 @@ public class StaminaManager extends BasePlayerManager {
int stamina = getCurrentCharacterStamina();
if (stamina < 10) {
logger.trace(getCurrentCharacterStamina() + "/" +
getMaxCharacterStamina() + "\t" + currentState);
getMaxCharacterStamina() + "\t" + currentState);
if (currentState != MotionState.MOTION_STATE_SWIM_IDLE) {
killAvatar(cachedSession, cachedEntity, PlayerDieType.PLAYER_DIE_TYPE_DRAWN);
}
@@ -603,18 +598,10 @@ public class StaminaManager extends BasePlayerManager {
}
private Consumption getOtherConsumptions() {
switch (currentState) {
case MOTION_STATE_NOTIFY:
// if (BowSkills.contains(lastSkillId)) {
// return new Consumption(ConsumptionType.FIGHT, 500);
// }
break;
case MOTION_STATE_FIGHT:
// TODO: what if charged attack
return new Consumption(ConsumptionType.FIGHT, 500);
}
return new Consumption();
return switch (this.currentState) {
default -> new Consumption();
case MOTION_STATE_FIGHT -> new Consumption(ConsumptionType.FIGHT, 500);
};
}
// Reduction getter