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

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

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

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

    // Server systems
github-actions's avatar
github-actions committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    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;
75
    private final TaskMap taskMap;
github-actions's avatar
github-actions committed
76
77
78
79
80
81
82
83
84

    private ChatManagerHandler chatManager;

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

    public GameServer(InetSocketAddress address) {
        ChannelConfig channelConfig = new ChannelConfig();
Melledy's avatar
Melledy committed
85
        channelConfig.nodelay(true, GAME_INFO.kcpInterval, 2, true);
github-actions's avatar
github-actions committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
        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();
109
110
        this.taskMap = new TaskMap(true);

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

        // Chata manager
        this.chatManager = new ChatManager(this);

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

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

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

143
144
145
146
147
148
149
    public ChatManagerHandler getChatSystem() {
        return chatManager;
    }

    public void setChatSystem(ChatManagerHandler chatManager) {
        this.chatManager = chatManager;
    }
150

github-actions's avatar
github-actions committed
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
215
    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);
    }
216

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

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

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

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

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

github-actions's avatar
github-actions committed
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
272
    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
273
}