/
FabricWorld.java
705 lines (632 loc) · 28.1 KB
/
FabricWorld.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/*
* 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.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.collect.Streams;
import com.google.common.util.concurrent.Futures;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.fabric.internal.ExtendedMinecraftServer;
import com.sk89q.worldedit.fabric.internal.FabricEditSessionDelegate;
import com.sk89q.worldedit.fabric.internal.FabricWorldNativeAccess;
import com.sk89q.worldedit.fabric.internal.NBTConverter;
import com.sk89q.worldedit.fabric.mixin.AccessorDerivedLevelData;
import com.sk89q.worldedit.fabric.mixin.AccessorPrimaryLevelData;
import com.sk89q.worldedit.fabric.mixin.AccessorServerChunkCache;
import com.sk89q.worldedit.function.mask.AbstractExtentMask;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.Mask2D;
import com.sk89q.worldedit.internal.Constants;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.TreeGenerator.TreeType;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.io.file.SafeFiles;
import com.sk89q.worldedit.world.AbstractWorld;
import com.sk89q.worldedit.world.RegenOptions;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.generation.ConfiguredFeatureType;
import com.sk89q.worldedit.world.item.ItemTypes;
import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.worldgen.features.EndFeatures;
import net.minecraft.data.worldgen.features.TreeFeatures;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.Clearable;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.LiquidBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkSource;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.WorldOptions;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
import net.minecraft.world.level.storage.LevelData;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import org.enginehub.linbus.common.LinTagId;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.lang.ref.WeakReference;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* An adapter to Minecraft worlds for WorldEdit.
*/
public class FabricWorld extends AbstractWorld {
private static final RandomSource random = RandomSource.create();
private static ResourceLocation getDimensionRegistryKey(Level world) {
return Objects.requireNonNull(world.getServer(), "server cannot be null")
.registryAccess()
.registryOrThrow(Registries.DIMENSION_TYPE)
.getKey(world.dimensionType());
}
private final WeakReference<Level> worldRef;
private final FabricWorldNativeAccess worldNativeAccess;
/**
* Construct a new world.
*
* @param world the world
*/
FabricWorld(Level world) {
checkNotNull(world);
this.worldRef = new WeakReference<>(world);
this.worldNativeAccess = new FabricWorldNativeAccess(worldRef);
}
/**
* Get the underlying handle to the world.
*
* @return the world
* @throws RuntimeException thrown if a reference to the world was lost (i.e. world was unloaded)
*/
public Level getWorld() {
Level world = worldRef.get();
if (world != null) {
return world;
} else {
throw new RuntimeException("The reference to the world was lost (i.e. the world may have been unloaded)");
}
}
@Override
public String getName() {
LevelData levelProperties = getWorld().getLevelData();
return ((ServerLevelData) levelProperties).getLevelName();
}
@Override
public String getId() {
return getName() + "_" + getDimensionRegistryKey(getWorld());
}
@Override
public Path getStoragePath() {
final Level world = getWorld();
MinecraftServer server = world.getServer();
checkState(server instanceof ExtendedMinecraftServer, "Need a server world");
return ((ExtendedMinecraftServer) server).getStoragePath(world);
}
@Override
public <B extends BlockStateHolder<B>> boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException {
clearContainerBlockContents(position);
return worldNativeAccess.setBlock(position, block, sideEffects);
}
@Override
public Set<SideEffect> applySideEffects(BlockVector3 position, BlockState previousType, SideEffectSet sideEffectSet) {
worldNativeAccess.applySideEffects(position, previousType, sideEffectSet);
return Sets.intersection(FabricWorldEdit.inst.getPlatform().getSupportedSideEffects(), sideEffectSet.getSideEffectsToApply());
}
@Override
public int getBlockLightLevel(BlockVector3 position) {
checkNotNull(position);
return getWorld().getMaxLocalRawBrightness(FabricAdapter.toBlockPos(position));
}
@Override
public boolean clearContainerBlockContents(BlockVector3 position) {
checkNotNull(position);
BlockEntity tile = getWorld().getBlockEntity(FabricAdapter.toBlockPos(position));
if ((tile instanceof Clearable)) {
((Clearable) tile).clearContent();
return true;
}
return false;
}
@Override
public BiomeType getBiome(BlockVector3 position) {
checkNotNull(position);
ChunkAccess chunk = getWorld().getChunk(position.getX() >> 4, position.getZ() >> 4);
return getBiomeInChunk(position, chunk);
}
private BiomeType getBiomeInChunk(BlockVector3 position, ChunkAccess chunk) {
return FabricAdapter.adapt(
chunk.getNoiseBiome(position.getX() >> 2, position.getY() >> 2, position.getZ() >> 2).value()
);
}
@Override
public boolean setBiome(BlockVector3 position, BiomeType biome) {
checkNotNull(position);
checkNotNull(biome);
ChunkAccess chunk = getWorld().getChunk(position.getBlockX() >> 4, position.getBlockZ() >> 4);
// Screw it, we know it's really mutable...
var biomeArray = (PalettedContainer<Holder<Biome>>) chunk.getSection(chunk.getSectionIndex(position.getY())).getBiomes();
biomeArray.getAndSetUnchecked(
position.getX() & 3, position.getY() & 3, position.getZ() & 3,
getWorld().registryAccess().registry(Registries.BIOME)
.orElseThrow()
.getHolderOrThrow(ResourceKey.create(Registries.BIOME, new ResourceLocation(biome.getId())))
);
chunk.setUnsaved(true);
return true;
}
private static final LoadingCache<ServerLevel, WorldEditFakePlayer> fakePlayers
= CacheBuilder.newBuilder().weakKeys().softValues().build(CacheLoader.from(WorldEditFakePlayer::new));
@Override
public boolean useItem(BlockVector3 position, BaseItem item, Direction face) {
ItemStack stack = FabricAdapter.adapt(new BaseItemStack(item.getType(), item.getNbtReference(), 1));
ServerLevel world = (ServerLevel) getWorld();
final WorldEditFakePlayer fakePlayer;
try {
fakePlayer = fakePlayers.get(world);
} catch (ExecutionException ignored) {
return false;
}
fakePlayer.setItemInHand(InteractionHand.MAIN_HAND, stack);
fakePlayer.absMoveTo(position.getBlockX(), position.getBlockY(), position.getBlockZ(),
(float) face.toVector().toYaw(), (float) face.toVector().toPitch());
final BlockPos blockPos = FabricAdapter.toBlockPos(position);
final BlockHitResult rayTraceResult = new BlockHitResult(FabricAdapter.toVec3(position),
FabricAdapter.adapt(face), blockPos, false);
UseOnContext itemUseContext = new UseOnContext(fakePlayer, InteractionHand.MAIN_HAND, rayTraceResult);
InteractionResult used = stack.useOn(itemUseContext);
if (used != InteractionResult.SUCCESS) {
// try activating the block
used = getWorld().getBlockState(blockPos).use(world, fakePlayer, InteractionHand.MAIN_HAND, rayTraceResult);
}
if (used != InteractionResult.SUCCESS) {
used = stack.use(world, fakePlayer, InteractionHand.MAIN_HAND).getResult();
}
return used == InteractionResult.SUCCESS;
}
@Override
public void dropItem(Vector3 position, BaseItemStack item) {
checkNotNull(position);
checkNotNull(item);
if (item.getType() == ItemTypes.AIR) {
return;
}
ItemEntity entity = new ItemEntity(getWorld(), position.getX(), position.getY(), position.getZ(), FabricAdapter.adapt(item));
entity.setPickUpDelay(10);
getWorld().addFreshEntity(entity);
}
@Override
public void simulateBlockMine(BlockVector3 position) {
BlockPos pos = FabricAdapter.toBlockPos(position);
getWorld().destroyBlock(pos, true);
}
@Override
public boolean canPlaceAt(BlockVector3 position, BlockState blockState) {
return FabricAdapter.adapt(blockState).canSurvive(getWorld(), FabricAdapter.toBlockPos(position));
}
@Override
public boolean regenerate(Region region, Extent extent, RegenOptions options) {
// Don't even try to regen if it's going to fail.
ChunkSource provider = getWorld().getChunkSource();
if (!(provider instanceof ServerChunkCache)) {
return false;
}
try {
doRegen(region, extent, options);
} catch (Exception e) {
throw new IllegalStateException("Regen failed", e);
}
return true;
}
private void doRegen(Region region, Extent extent, RegenOptions options) throws Exception {
Path tempDir = Files.createTempDirectory("WorldEditWorldGen");
LevelStorageSource levelStorage = LevelStorageSource.createDefault(tempDir);
try (LevelStorageSource.LevelStorageAccess session = levelStorage.createAccess("WorldEditTempGen")) {
ServerLevel originalWorld = (ServerLevel) getWorld();
AccessorPrimaryLevelData levelProperties;
if (originalWorld.getLevelData() instanceof AccessorDerivedLevelData derivedLevelData) {
levelProperties = (AccessorPrimaryLevelData) derivedLevelData.getWrapped();
} else {
levelProperties = (AccessorPrimaryLevelData) originalWorld.getLevelData();
}
WorldOptions originalOpts = levelProperties.worldGenOptions();
long seed = options.getSeed().orElse(originalWorld.getSeed());
WorldOptions newOpts = options.getSeed().isPresent()
? originalOpts.withSeed(OptionalLong.of(seed))
: originalOpts;
levelProperties.setWorldOptions(newOpts);
ResourceKey<Level> worldRegKey = originalWorld.dimension();
try (ServerLevel serverWorld = new ServerLevel(
originalWorld.getServer(), Util.backgroundExecutor(), session,
((ServerLevelData) originalWorld.getLevelData()),
worldRegKey,
new LevelStem(
originalWorld.dimensionTypeRegistration(),
originalWorld.getChunkSource().getGenerator()
),
new WorldEditGenListener(),
originalWorld.isDebug(),
seed,
// No spawners are needed for this world.
ImmutableList.of(),
// This controls ticking, we don't need it so set it to false.
false
)) {
regenForWorld(region, extent, serverWorld, options);
// drive the server executor until all tasks are popped off
while (originalWorld.getServer().pollTask()) {
Thread.yield();
}
} finally {
levelProperties.setWorldOptions(originalOpts);
}
} finally {
SafeFiles.tryHardToDeleteDir(tempDir);
}
}
private void regenForWorld(Region region, Extent extent, ServerLevel serverWorld,
RegenOptions options) throws WorldEditException {
List<CompletableFuture<ChunkAccess>> chunkLoadings = submitChunkLoadTasks(region, serverWorld);
// drive executor until loading finishes
((AccessorServerChunkCache) serverWorld.getChunkSource()).getMainThreadProcessor()
.managedBlock(() -> {
// bail out early if a future fails
if (chunkLoadings.stream().anyMatch(ftr ->
ftr.isDone() && Futures.getUnchecked(ftr) == null
)) {
return false;
}
return chunkLoadings.stream().allMatch(CompletableFuture::isDone);
});
Map<ChunkPos, ChunkAccess> chunks = new HashMap<>();
for (CompletableFuture<ChunkAccess> future : chunkLoadings) {
@Nullable
ChunkAccess chunk = future.getNow(null);
checkState(chunk != null, "Failed to generate a chunk, regen failed.");
chunks.put(chunk.getPos(), chunk);
}
for (BlockVector3 vec : region) {
BlockPos pos = FabricAdapter.toBlockPos(vec);
ChunkAccess chunk = chunks.get(new ChunkPos(pos));
BlockStateHolder<?> state = FabricAdapter.adapt(chunk.getBlockState(pos));
BlockEntity blockEntity = chunk.getBlockEntity(pos);
if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = blockEntity.saveWithId();
state = state.toBaseBlock(LazyReference.from(() -> NBTConverter.fromNative(tag)));
}
extent.setBlock(vec, state.toBaseBlock());
if (options.shouldRegenBiomes()) {
BiomeType biome = getBiomeInChunk(vec, chunk);
extent.setBiome(vec, biome);
}
}
}
private List<CompletableFuture<ChunkAccess>> submitChunkLoadTasks(Region region, ServerLevel world) {
AccessorServerChunkCache chunkManager = (AccessorServerChunkCache) world.getChunkSource();
List<CompletableFuture<ChunkAccess>> chunkLoadings = new ArrayList<>();
// Pre-gen all the chunks
for (BlockVector2 chunk : region.getChunks()) {
chunkLoadings.add(
chunkManager.callGetChunkFuture(chunk.getX(), chunk.getZ(), ChunkStatus.FEATURES, true)
.thenApply(either -> either.left().orElse(null))
);
}
return chunkLoadings;
}
@Nullable
private static ResourceKey<ConfiguredFeature<?, ?>> createTreeFeatureGenerator(TreeType type) {
return switch (type) {
// Based off of the SaplingGenerator class, as well as uses of DefaultBiomeFeatures fields
case TREE -> TreeFeatures.OAK;
case BIG_TREE -> TreeFeatures.FANCY_OAK;
case REDWOOD -> TreeFeatures.SPRUCE;
case TALL_REDWOOD -> TreeFeatures.MEGA_SPRUCE;
case MEGA_REDWOOD -> TreeFeatures.MEGA_PINE;
case BIRCH -> TreeFeatures.BIRCH;
case JUNGLE -> TreeFeatures.MEGA_JUNGLE_TREE;
case SMALL_JUNGLE -> TreeFeatures.JUNGLE_TREE;
case SHORT_JUNGLE -> TreeFeatures.JUNGLE_TREE_NO_VINE;
case JUNGLE_BUSH -> TreeFeatures.JUNGLE_BUSH;
case SWAMP -> TreeFeatures.SWAMP_OAK;
case ACACIA -> TreeFeatures.ACACIA;
case DARK_OAK -> TreeFeatures.DARK_OAK;
case TALL_BIRCH -> TreeFeatures.SUPER_BIRCH_BEES_0002;
case RED_MUSHROOM -> TreeFeatures.HUGE_RED_MUSHROOM;
case BROWN_MUSHROOM -> TreeFeatures.HUGE_BROWN_MUSHROOM;
case WARPED_FUNGUS -> TreeFeatures.WARPED_FUNGUS;
case CRIMSON_FUNGUS -> TreeFeatures.CRIMSON_FUNGUS;
case CHORUS_PLANT -> EndFeatures.CHORUS_PLANT;
case RANDOM -> createTreeFeatureGenerator(TreeType.values()[ThreadLocalRandom.current().nextInt(TreeType.values().length)]);
default -> null;
};
}
@Override
public boolean generateTree(TreeType type, EditSession editSession, BlockVector3 position) {
ServerLevel world = (ServerLevel) getWorld();
ConfiguredFeature<?, ?> generator = Optional.ofNullable(createTreeFeatureGenerator(type))
.map(k -> world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(k))
.orElse(null);
ServerChunkCache chunkManager = world.getChunkSource();
if (type == TreeType.CHORUS_PLANT) {
position = position.add(0, 1, 0);
}
return generator != null && generator.place(
new FabricEditSessionDelegate(editSession, world), chunkManager.getGenerator(), random,
FabricAdapter.toBlockPos(position)
);
}
public boolean generateFeature(ConfiguredFeatureType type, EditSession editSession, BlockVector3 position) {
ServerLevel world = (ServerLevel) getWorld();
ConfiguredFeature<?, ?> k = world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(ResourceLocation.tryParse(type.getId()));
ServerChunkCache chunkManager = world.getChunkSource();
return k != null && k.place(new FabricEditSessionDelegate(editSession, world), chunkManager.getGenerator(), random, FabricAdapter.toBlockPos(position));
}
@Override
public void checkLoadedChunk(BlockVector3 pt) {
getWorld().getChunk(FabricAdapter.toBlockPos(pt));
}
@Override
public void fixAfterFastMode(Iterable<BlockVector2> chunks) {
fixLighting(chunks);
}
@Override
public void fixLighting(Iterable<BlockVector2> chunks) {
Level world = getWorld();
for (BlockVector2 chunk : chunks) {
world.getChunkSource().getLightEngine().enableLightSources(
new ChunkPos(chunk.getBlockX(), chunk.getBlockZ()), true
);
}
}
@Override
public boolean playEffect(Vector3 position, int type, int data) {
// TODO update sound API
// getWorld().playSound(type, FabricAdapter.toBlockPos(position.toBlockPoint()), data);
return true;
}
@Override
public WeatherType getWeather() {
LevelData info = getWorld().getLevelData();
if (info.isThundering()) {
return WeatherTypes.THUNDER_STORM;
}
if (info.isRaining()) {
return WeatherTypes.RAIN;
}
return WeatherTypes.CLEAR;
}
@Override
public long getRemainingWeatherDuration() {
ServerLevelData info = (ServerLevelData) getWorld().getLevelData();
if (info.isThundering()) {
return info.getThunderTime();
}
if (info.isRaining()) {
return info.getRainTime();
}
return info.getClearWeatherTime();
}
@Override
public void setWeather(WeatherType weatherType) {
setWeather(weatherType, 0);
}
@Override
public void setWeather(WeatherType weatherType, long duration) {
ServerLevelData info = (ServerLevelData) getWorld().getLevelData();
if (weatherType == WeatherTypes.THUNDER_STORM) {
info.setClearWeatherTime(0);
info.setThundering(true);
info.setThunderTime((int) duration);
} else if (weatherType == WeatherTypes.RAIN) {
info.setClearWeatherTime(0);
info.setRaining(true);
info.setRainTime((int) duration);
} else if (weatherType == WeatherTypes.CLEAR) {
info.setRaining(false);
info.setThundering(false);
info.setClearWeatherTime((int) duration);
}
}
@Override
public int getMinY() {
return getWorld().getMinBuildHeight();
}
@Override
public int getMaxY() {
return getWorld().getMaxBuildHeight() - 1;
}
@Override
public BlockVector3 getSpawnPosition() {
LevelData worldProps = getWorld().getLevelData();
return BlockVector3.at(
worldProps.getXSpawn(),
worldProps.getYSpawn(),
worldProps.getZSpawn()
);
}
@Override
public BlockState getBlock(BlockVector3 position) {
net.minecraft.world.level.block.state.BlockState mcState = getWorld()
.getChunk(position.getBlockX() >> 4, position.getBlockZ() >> 4)
.getBlockState(FabricAdapter.toBlockPos(position));
return FabricAdapter.adapt(mcState);
}
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
BlockPos pos = new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ());
// Avoid creation by using the CHECK mode -- if it's needed, it'll be re-created anyways
BlockEntity tile = ((LevelChunk) getWorld().getChunk(pos)).getBlockEntity(pos, LevelChunk.EntityCreationType.CHECK);
if (tile != null) {
net.minecraft.nbt.CompoundTag tag = tile.saveWithId();
return getBlock(position).toBaseBlock(LazyReference.from(() -> NBTConverter.fromNative(tag)));
} else {
return getBlock(position).toBaseBlock();
}
}
@Override
public int hashCode() {
return getWorld().hashCode();
}
@Override
public boolean equals(Object o) {
if ((o instanceof FabricWorld other)) {
Level otherWorld = other.worldRef.get();
Level thisWorld = worldRef.get();
return otherWorld != null && otherWorld.equals(thisWorld);
} else if (o instanceof com.sk89q.worldedit.world.World) {
return ((com.sk89q.worldedit.world.World) o).getName().equals(getName());
} else {
return false;
}
}
@Override
public List<? extends Entity> getEntities(Region region) {
final Level world = getWorld();
AABB box = new AABB(
FabricAdapter.toBlockPos(region.getMinimumPoint()),
FabricAdapter.toBlockPos(region.getMaximumPoint().add(BlockVector3.ONE))
);
List<net.minecraft.world.entity.Entity> nmsEntities = world.getEntities(
(net.minecraft.world.entity.Entity) null,
box,
e -> region.contains(FabricAdapter.adapt(e.blockPosition()))
);
return nmsEntities.stream()
.map(FabricEntity::new)
.collect(ImmutableList.toImmutableList());
}
@Override
public List<? extends Entity> getEntities() {
final Level world = getWorld();
if (!(world instanceof ServerLevel)) {
return Collections.emptyList();
}
return Streams.stream(((ServerLevel) world).getAllEntities())
.map(FabricEntity::new)
.collect(ImmutableList.toImmutableList());
}
@Nullable
@Override
public Entity createEntity(Location location, BaseEntity entity) {
ServerLevel world = (ServerLevel) getWorld();
String entityId = entity.getType().getId();
final Optional<EntityType<?>> entityType = EntityType.byString(entityId);
if (entityType.isEmpty()) {
return null;
}
LinCompoundTag nativeTag = entity.getNbt();
net.minecraft.nbt.CompoundTag tag;
if (nativeTag != null) {
tag = NBTConverter.toNative(nativeTag);
removeUnwantedEntityTagsRecursively(tag);
} else {
tag = new net.minecraft.nbt.CompoundTag();
}
tag.putString("id", entityId);
net.minecraft.world.entity.Entity createdEntity = EntityType.loadEntityRecursive(tag, world, (loadedEntity) -> {
loadedEntity.absMoveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
return loadedEntity;
});
if (createdEntity != null) {
world.addFreshEntityWithPassengers(createdEntity);
return new FabricEntity(createdEntity);
}
return null;
}
private void removeUnwantedEntityTagsRecursively(net.minecraft.nbt.CompoundTag tag) {
for (String name : Constants.NO_COPY_ENTITY_NBT_FIELDS) {
tag.remove(name);
}
// Adapted from net.minecraft.world.entity.EntityType#loadEntityRecursive
if (tag.contains("Passengers", LinTagId.LIST.id())) {
net.minecraft.nbt.ListTag nbttaglist = tag.getList("Passengers", LinTagId.COMPOUND.id());
for (int i = 0; i < nbttaglist.size(); ++i) {
removeUnwantedEntityTagsRecursively(nbttaglist.getCompound(i));
}
}
}
@Override
public Mask createLiquidMask() {
return new AbstractExtentMask(this) {
@Override
public boolean test(BlockVector3 vector) {
return FabricAdapter.adapt(getExtent().getBlock(vector)).getBlock() instanceof LiquidBlock;
}
@Nullable
@Override
public Mask2D toMask2D() {
return null;
}
};
}
}