/
FabricWorldEdit.java
408 lines (354 loc) · 16.1 KB
/
FabricWorldEdit.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.fabric;
import com.mojang.brigadier.CommandDispatcher;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.util.PermissionCondition;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.event.platform.PlatformUnreadyEvent;
import com.sk89q.worldedit.event.platform.PlatformsRegisteredEvent;
import com.sk89q.worldedit.event.platform.SessionIdleEvent;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.PlatformManager;
import com.sk89q.worldedit.fabric.net.handler.WECUIPacketHandler;
import com.sk89q.worldedit.internal.anvil.ChunkDeleter;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.lifecycle.Lifecycled;
import com.sk89q.worldedit.util.lifecycle.SimpleLifecycled;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockCategory;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.generation.ConfiguredFeatureType;
import com.sk89q.worldedit.world.item.ItemCategory;
import com.sk89q.worldedit.world.item.ItemType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.event.player.AttackBlockCallback;
import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.fabricmc.fabric.api.event.player.UseItemCallback;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.tags.TagKey;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import org.apache.logging.log4j.Logger;
import org.enginehub.piston.Command;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.fabric.FabricAdapter.adaptPlayer;
import static com.sk89q.worldedit.internal.anvil.ChunkDeleter.DELCHUNKS_FILE_NAME;
/**
* The Fabric implementation of WorldEdit.
*/
public class FabricWorldEdit implements ModInitializer {
private static final Logger LOGGER = LogManagerCompat.getLogger();
public static final String MOD_ID = "worldedit";
public static final String CUI_PLUGIN_CHANNEL = "cui";
public static final Lifecycled<MinecraftServer> LIFECYCLED_SERVER;
static {
SimpleLifecycled<MinecraftServer> lifecycledServer = SimpleLifecycled.invalid();
ServerLifecycleEvents.SERVER_STARTED.register(lifecycledServer::newValue);
ServerLifecycleEvents.SERVER_STOPPING.register(__ -> lifecycledServer.invalidate());
LIFECYCLED_SERVER = lifecycledServer;
}
public static <T> Registry<T> getRegistry(ResourceKey<Registry<T>> key) {
return LIFECYCLED_SERVER.valueOrThrow().registryAccess().registryOrThrow(key);
}
private FabricPermissionsProvider provider;
public static FabricWorldEdit inst;
private FabricPlatform platform;
private FabricConfiguration config;
private Path workingDir;
private ModContainer container;
public FabricWorldEdit() {
inst = this;
}
@Override
public void onInitialize() {
this.container = FabricLoader.getInstance().getModContainer("worldedit").orElseThrow(
() -> new IllegalStateException("WorldEdit mod missing in Fabric")
);
// Setup working directory
workingDir = FabricLoader.getInstance().getConfigDir().resolve("worldedit");
if (!Files.exists(workingDir)) {
try {
Files.createDirectory(workingDir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
this.platform = new FabricPlatform(this);
WorldEdit.getInstance().getPlatformManager().register(platform);
config = new FabricConfiguration(this);
this.provider = getInitialPermissionsProvider();
WECUIPacketHandler.init();
ServerTickEvents.END_SERVER_TICK.register(ThreadSafeCache.getInstance());
CommandRegistrationCallback.EVENT.register(this::registerCommands);
ServerLifecycleEvents.SERVER_STARTING.register(this::onStartingServer);
ServerLifecycleEvents.SERVER_STARTED.register(this::onStartServer);
ServerLifecycleEvents.SERVER_STOPPING.register(this::onStopServer);
ServerPlayConnectionEvents.DISCONNECT.register(this::onPlayerDisconnect);
AttackBlockCallback.EVENT.register(this::onLeftClickBlock);
UseBlockCallback.EVENT.register(this::onRightClickBlock);
UseItemCallback.EVENT.register(this::onRightClickAir);
LOGGER.info("WorldEdit for Fabric (version " + getInternalVersion() + ") is loaded");
}
private void registerCommands(CommandDispatcher<CommandSourceStack> dispatcher, CommandBuildContext registryAccess, Commands.CommandSelection environment) {
WorldEdit.getInstance().getEventBus().post(new PlatformsRegisteredEvent());
PlatformManager manager = WorldEdit.getInstance().getPlatformManager();
Platform commandsPlatform = manager.queryCapability(Capability.USER_COMMANDS);
if (commandsPlatform != platform || !platform.isHookingEvents()) {
// We're not in control of commands/events -- do not register.
return;
}
List<Command> commands = manager.getPlatformCommandManager().getCommandManager()
.getAllCommands().toList();
for (Command command : commands) {
CommandWrapper.register(dispatcher, command);
Set<String> perms = command.getCondition().as(PermissionCondition.class)
.map(PermissionCondition::getPermissions)
.orElseGet(Collections::emptySet);
if (!perms.isEmpty()) {
perms.forEach(getPermissionsProvider()::registerPermission);
}
}
}
private FabricPermissionsProvider getInitialPermissionsProvider() {
try {
Class.forName("me.lucko.fabric.api.permissions.v0.Permissions", false, getClass().getClassLoader());
return new FabricPermissionsProvider.LuckoFabricPermissionsProvider(platform);
} catch (ClassNotFoundException ignored) {
// fallback to vanilla
}
return new FabricPermissionsProvider.VanillaPermissionsProvider(platform);
}
private void setupRegistries(MinecraftServer server) {
// Blocks
for (ResourceLocation name : server.registryAccess().registryOrThrow(Registries.BLOCK).keySet()) {
if (BlockType.REGISTRY.get(name.toString()) == null) {
BlockType.REGISTRY.register(name.toString(), new BlockType(name.toString(),
input -> FabricAdapter.adapt(FabricAdapter.adapt(input.getBlockType()).defaultBlockState())));
}
}
// Items
for (ResourceLocation name : server.registryAccess().registryOrThrow(Registries.ITEM).keySet()) {
if (ItemType.REGISTRY.get(name.toString()) == null) {
ItemType.REGISTRY.register(name.toString(), new ItemType(name.toString()));
}
}
// Entities
for (ResourceLocation name : server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).keySet()) {
if (EntityType.REGISTRY.get(name.toString()) == null) {
EntityType.REGISTRY.register(name.toString(), new EntityType(name.toString()));
}
}
// Biomes
for (ResourceLocation name : server.registryAccess().registryOrThrow(Registries.BIOME).keySet()) {
if (BiomeType.REGISTRY.get(name.toString()) == null) {
BiomeType.REGISTRY.register(name.toString(), new BiomeType(name.toString()));
}
}
// Tags
server.registryAccess().registryOrThrow(Registries.BLOCK).getTagNames().map(TagKey::location).forEach(name -> {
if (BlockCategory.REGISTRY.get(name.toString()) == null) {
BlockCategory.REGISTRY.register(name.toString(), new BlockCategory(name.toString()));
}
});
server.registryAccess().registryOrThrow(Registries.ITEM).getTagNames().map(TagKey::location).forEach(name -> {
if (ItemCategory.REGISTRY.get(name.toString()) == null) {
ItemCategory.REGISTRY.register(name.toString(), new ItemCategory(name.toString()));
}
});
// Features
for (ResourceLocation name: server.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).keySet()) {
if (ConfiguredFeatureType.REGISTRY.get(name.toString()) == null) {
ConfiguredFeatureType.REGISTRY.register(name.toString(), new ConfiguredFeatureType(name.toString()));
}
}
}
private void onStartingServer(MinecraftServer minecraftServer) {
final Path delChunks = workingDir.resolve(DELCHUNKS_FILE_NAME);
if (Files.exists(delChunks)) {
ChunkDeleter.runFromFile(delChunks, true);
}
}
private void onStartServer(MinecraftServer minecraftServer) {
setupRegistries(minecraftServer);
config.load();
WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent(platform));
}
private void onStopServer(MinecraftServer minecraftServer) {
WorldEdit worldEdit = WorldEdit.getInstance();
worldEdit.getSessionManager().unload();
WorldEdit.getInstance().getEventBus().post(new PlatformUnreadyEvent(platform));
}
private boolean shouldSkip() {
if (platform == null) {
return true;
}
return !platform.isHookingEvents(); // We have to be told to catch these events
}
private InteractionResult onLeftClickBlock(Player playerEntity, Level world, InteractionHand hand, BlockPos blockPos, Direction direction) {
if (shouldSkip() || hand == InteractionHand.OFF_HAND || world.isClientSide) {
return InteractionResult.PASS;
}
WorldEdit we = WorldEdit.getInstance();
FabricPlayer player = adaptPlayer((ServerPlayer) playerEntity);
FabricWorld localWorld = getWorld(world);
Location pos = new Location(localWorld,
blockPos.getX(),
blockPos.getY(),
blockPos.getZ()
);
com.sk89q.worldedit.util.Direction weDirection = FabricAdapter.adaptEnumFacing(direction);
if (we.handleBlockLeftClick(player, pos, weDirection)) {
return InteractionResult.SUCCESS;
}
if (we.handleArmSwing(player)) {
return InteractionResult.SUCCESS;
}
return InteractionResult.PASS;
}
private InteractionResult onRightClickBlock(Player playerEntity, Level world, InteractionHand hand, BlockHitResult blockHitResult) {
if (shouldSkip() || hand == InteractionHand.OFF_HAND || world.isClientSide) {
return InteractionResult.PASS;
}
WorldEdit we = WorldEdit.getInstance();
FabricPlayer player = adaptPlayer((ServerPlayer) playerEntity);
FabricWorld localWorld = getWorld(world);
Location pos = new Location(localWorld,
blockHitResult.getBlockPos().getX(),
blockHitResult.getBlockPos().getY(),
blockHitResult.getBlockPos().getZ()
);
com.sk89q.worldedit.util.Direction direction = FabricAdapter.adaptEnumFacing(blockHitResult.getDirection());
if (we.handleBlockRightClick(player, pos, direction)) {
return InteractionResult.SUCCESS;
}
if (we.handleRightClick(player)) {
return InteractionResult.SUCCESS;
}
return InteractionResult.PASS;
}
private InteractionResultHolder<ItemStack> onRightClickAir(Player playerEntity, Level world, InteractionHand hand) {
ItemStack stackInHand = playerEntity.getItemInHand(hand);
if (shouldSkip() || hand == InteractionHand.OFF_HAND || world.isClientSide) {
return InteractionResultHolder.pass(stackInHand);
}
WorldEdit we = WorldEdit.getInstance();
FabricPlayer player = adaptPlayer((ServerPlayer) playerEntity);
if (we.handleRightClick(player)) {
return InteractionResultHolder.success(stackInHand);
}
return InteractionResultHolder.pass(stackInHand);
}
// TODO Pass empty left click to server
private void onPlayerDisconnect(ServerGamePacketListenerImpl handler, MinecraftServer server) {
WorldEdit.getInstance().getEventBus()
.post(new SessionIdleEvent(new FabricPlayer.SessionKeyImpl(handler.player)));
}
/**
* Get the configuration.
*
* @return the Fabric configuration
*/
FabricConfiguration getConfig() {
return this.config;
}
/**
* Get the session for a player.
*
* @param player the player
* @return the session
*/
public LocalSession getSession(ServerPlayer player) {
checkNotNull(player);
return WorldEdit.getInstance().getSessionManager().get(adaptPlayer(player));
}
/**
* Get the WorldEdit proxy for the given world.
*
* @param world the world
* @return the WorldEdit world
*/
public FabricWorld getWorld(Level world) {
checkNotNull(world);
return new FabricWorld(world);
}
/**
* Get the WorldEdit proxy for the platform.
*
* @return the WorldEdit platform
*/
public Platform getPlatform() {
return this.platform;
}
/**
* Get the working directory where WorldEdit's files are stored.
*
* @return the working directory
*/
public Path getWorkingDir() {
return this.workingDir;
}
/**
* Get the version of the WorldEdit-Fabric implementation.
*
* @return a version string
*/
String getInternalVersion() {
return container.getMetadata().getVersion().getFriendlyString();
}
public void setPermissionsProvider(FabricPermissionsProvider provider) {
this.provider = provider;
}
public FabricPermissionsProvider getPermissionsProvider() {
return provider;
}
}