GameServer.java 9.33 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.server.game;

3
import emu.grasscutter.GameConstants;
Melledy's avatar
Melledy committed
4
5
import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper;
Melledy's avatar
Melledy committed
6
import emu.grasscutter.game.Account;
7
import emu.grasscutter.game.battlepass.BattlePassSystem;
8
9
import emu.grasscutter.game.chat.ChatSystem;
import emu.grasscutter.game.chat.ChatSystemHandler;
Akka's avatar
Akka committed
10
import emu.grasscutter.game.combine.CombineManger;
11
12
import emu.grasscutter.game.drop.DropSystem;
import emu.grasscutter.game.dungeons.DungeonSystem;
AnimeGitB's avatar
AnimeGitB committed
13
import emu.grasscutter.game.dungeons.challenge.DungeonChallenge;
14
15
import emu.grasscutter.game.expedition.ExpeditionSystem;
import emu.grasscutter.game.gacha.GachaSystem;
16
import emu.grasscutter.game.managers.CookingManager;
AnimeGitB's avatar
AnimeGitB committed
17
18
import emu.grasscutter.game.managers.energy.EnergyManager;
import emu.grasscutter.game.managers.stamina.StaminaManager;
Melledy's avatar
Melledy committed
19
import emu.grasscutter.game.player.Player;
20
21
import emu.grasscutter.game.quest.QuestSystem;
import emu.grasscutter.game.shop.ShopSystem;
22
23
24
import emu.grasscutter.game.systems.AnnouncementSystem;
import emu.grasscutter.game.systems.InventorySystem;
import emu.grasscutter.game.systems.MultiplayerSystem;
25
import emu.grasscutter.game.tower.TowerSystem;
Melledy's avatar
Melledy committed
26
import emu.grasscutter.game.world.World;
27
import emu.grasscutter.game.world.WorldDataSystem;
Melledy's avatar
Melledy committed
28
29
import emu.grasscutter.net.packet.PacketHandler;
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
KingRainbow44's avatar
KingRainbow44 committed
30
import emu.grasscutter.server.event.types.ServerEvent;
KingRainbow44's avatar
KingRainbow44 committed
31
32
33
import emu.grasscutter.server.event.game.ServerTickEvent;
import emu.grasscutter.server.event.internal.ServerStartEvent;
import emu.grasscutter.server.event.internal.ServerStopEvent;
34
import emu.grasscutter.server.scheduler.ServerTaskScheduler;
Yazawazi's avatar
Yazawazi committed
35
import emu.grasscutter.task.TaskMap;
36
37
import kcp.highway.ChannelConfig;
import kcp.highway.KcpServer;
38
import lombok.Getter;
Melledy's avatar
Melledy committed
39

Kengxxiao's avatar
Kengxxiao committed
40
import java.net.InetSocketAddress;
41
import java.time.Instant;
Kengxxiao's avatar
Kengxxiao committed
42
43
44
45
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

46
import static emu.grasscutter.config.Configuration.*;
47
48
import static emu.grasscutter.utils.Language.translate;

49
@Getter
50
public final class GameServer extends KcpServer {
51
52
    // Game server base
    private final InetSocketAddress address;
github-actions's avatar
github-actions committed
53
    private final GameServerPacketHandler packetHandler;
54
55
56
57
    private final Map<Integer, Player> players;
    private final Set<World> worlds;

    // Server systems
github-actions's avatar
github-actions committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    private final InventorySystem inventorySystem;
    private final GachaSystem gachaSystem;
    private final ShopSystem shopSystem;
    private final MultiplayerSystem multiplayerSystem;
    private final DungeonSystem dungeonSystem;
    private final ExpeditionSystem expeditionSystem;
    private final DropSystem dropSystem;
    private final WorldDataSystem worldDataSystem;
    private final BattlePassSystem battlePassSystem;
    private final CombineManger combineSystem;
    private final TowerSystem towerSystem;
    private final AnnouncementSystem announcementSystem;
    private final QuestSystem questSystem;

    // Extra
    private final ServerTaskScheduler scheduler;
74
    private final TaskMap taskMap;
github-actions's avatar
github-actions committed
75

76
    private ChatSystemHandler chatManager;
github-actions's avatar
github-actions committed
77
78
79
80
81
82
83

    public GameServer() {
        this(getAdapterInetSocketAddress());
    }

    public GameServer(InetSocketAddress address) {
        ChannelConfig channelConfig = new ChannelConfig();
Melledy's avatar
Melledy committed
84
        channelConfig.nodelay(true, GAME_INFO.kcpInterval, 2, true);
github-actions's avatar
github-actions committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
        channelConfig.setMtu(1400);
        channelConfig.setSndwnd(256);
        channelConfig.setRcvwnd(256);
        channelConfig.setTimeoutMillis(30 * 1000);//30s
        channelConfig.setUseConvChannel(true);
        channelConfig.setAckNoDelay(false);

        this.init(GameSessionManager.getListener(),channelConfig,address);

        DungeonChallenge.initialize();
        EnergyManager.initialize();
        StaminaManager.initialize();
        CookingManager.initialize();
        CombineManger.initialize();

        // Game Server base
        this.address = address;
        this.packetHandler = new GameServerPacketHandler(PacketHandler.class);
        this.players = new ConcurrentHashMap<>();
        this.worlds = Collections.synchronizedSet(new HashSet<>());

        // Extra
        this.scheduler = new ServerTaskScheduler();
108
109
        this.taskMap = new TaskMap(true);

github-actions's avatar
github-actions committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        // Create game systems
        this.inventorySystem = new InventorySystem(this);
        this.gachaSystem = new GachaSystem(this);
        this.shopSystem = new ShopSystem(this);
        this.multiplayerSystem = new MultiplayerSystem(this);
        this.dungeonSystem = new DungeonSystem(this);
        this.dropSystem = new DropSystem(this);
        this.expeditionSystem = new ExpeditionSystem(this);
        this.combineSystem = new CombineManger(this);
        this.towerSystem = new TowerSystem(this);
        this.worldDataSystem = new WorldDataSystem(this);
        this.battlePassSystem = new BattlePassSystem(this);
        this.announcementSystem = new AnnouncementSystem(this);
        this.questSystem = new QuestSystem(this);

        // Chata manager
126
        this.chatManager = new ChatSystem(this);
github-actions's avatar
github-actions committed
127
128
129
130
131

        // Hook into shutdown event.
        Runtime.getRuntime().addShutdownHook(new Thread(this::onServerShutdown));
    }

132
    @Deprecated
133
    public ChatSystemHandler getChatManager() {
134
135
        return chatManager;
    }
github-actions's avatar
github-actions committed
136

137
    @Deprecated
138
    public void setChatManager(ChatSystemHandler chatManager) {
139
140
        this.chatManager = chatManager;
    }
github-actions's avatar
github-actions committed
141

142
    public ChatSystemHandler getChatSystem() {
143
144
145
        return chatManager;
    }

146
    public void setChatSystem(ChatSystemHandler chatManager) {
147
148
        this.chatManager = chatManager;
    }
149

github-actions's avatar
github-actions committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    private static InetSocketAddress getAdapterInetSocketAddress() {
        InetSocketAddress inetSocketAddress;
        if (GAME_INFO.bindAddress.equals("")) {
            inetSocketAddress=new InetSocketAddress(GAME_INFO.bindPort);
        }else {
            inetSocketAddress=new InetSocketAddress(
                    GAME_INFO.bindAddress,
                    GAME_INFO.bindPort
            );
        }
        return inetSocketAddress;
    }

    public void registerPlayer(Player player) {
        getPlayers().put(player.getUid(), player);
    }

    public Player getPlayerByUid(int id) {
        return this.getPlayerByUid(id, false);
    }

    public Player getPlayerByUid(int id, boolean allowOfflinePlayers) {
        // Console check
        if (id == GameConstants.SERVER_CONSOLE_UID) {
            return null;
        }

        // Get from online players
        Player player = this.getPlayers().get(id);

        if (!allowOfflinePlayers) {
            return player;
        }

        // Check database if character isnt here
        if (player == null) {
            player = DatabaseHelper.getPlayerByUid(id);
        }

        return player;
    }

    public Player getPlayerByAccountId(String accountId) {
        Optional<Player> playerOpt = getPlayers().values().stream().filter(player -> player.getAccount().getId().equals(accountId)).findFirst();
        return playerOpt.orElse(null);
    }

    public SocialDetail.Builder getSocialDetailByUid(int id) {
        // Get from online players
        Player player = this.getPlayerByUid(id, true);

        if (player == null) {
            return null;
        }

        return player.getSocialDetail();
    }

    public Account getAccountByName(String username) {
        Optional<Player> playerOpt = getPlayers().values().stream().filter(player -> player.getAccount().getUsername().equals(username)).findFirst();
        if (playerOpt.isPresent()) {
            return playerOpt.get().getAccount();
        }
        return DatabaseHelper.getAccountByName(username);
    }
215

216
217
    public synchronized void onTick() {
        var tickStart = Instant.now();
218

219
        // Tick worlds.
Luke H-W's avatar
Luke H-W committed
220
        this.worlds.removeIf(World::onTick);
221
222

        // Tick players.
Luke H-W's avatar
Luke H-W committed
223
        this.players.values().forEach(Player::onTick);
224
225
226
227
228
229
230
231

        // Tick scheduler.
        this.getScheduler().runTasks();

        // Call server tick event.
        ServerTickEvent event = new ServerTickEvent(tickStart, Instant.now());
        event.call();
    }
232

github-actions's avatar
github-actions committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    public void registerWorld(World world) {
        this.getWorlds().add(world);
    }

    public void deregisterWorld(World world) {
        // TODO Auto-generated method stub

    }

    public void start() {
        // Schedule game loop.
        Timer gameLoop = new Timer();
        gameLoop.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    onTick();
                } catch (Exception e) {
                    Grasscutter.getLogger().error(translate("messages.game.game_update_error"), e);
                }
            }
        }, new Date(), 1000L);
        Grasscutter.getLogger().info(translate("messages.status.free_software"));
        Grasscutter.getLogger().info(translate("messages.game.port_bind", Integer.toString(address.getPort())));
        ServerStartEvent event = new ServerStartEvent(ServerEvent.Type.GAME, OffsetDateTime.now());
        event.call();
    }

    public void onServerShutdown() {
        ServerStopEvent event = new ServerStopEvent(ServerEvent.Type.GAME, OffsetDateTime.now()); event.call();

        // Kick and save all players
        List<Player> list = new ArrayList<>(this.getPlayers().size());
        list.addAll(this.getPlayers().values());

        for (Player player : list) {
            player.getSession().close();
        }
    }
Melledy's avatar
Melledy committed
272
}