SculkSpreader .java

net.minecraft.world.level.block.SculkSpreader (class, 373 lines): members: SHRIEKER_PLACEMENT_RATE, MAX_GROWTH_RATE_RADIUS, createWorldGenSpreader, load.

net.minecraft.world.level.blockclass373 linescommon13.7 KB

API Surface (18)

SculkSpreader createLevelSpreader()
SculkSpreader createWorldGenSpreader()
TagKey<Block> replaceableBlocks()
int growthSpawnCost()
int noGrowthRadius()
int chargeDecayRate()
int additionalDecayRate()
boolean isWorldGeneration()
List<SculkSpreader.ChargeCursor> getCursors()
void clear()
void load(final ValueInput input)
void save(final ValueOutput output)
void addCursors(final BlockPos startPos, int charge)
void updateCursors(final LevelAccessor level, final BlockPos originPos, final RandomSource random, final boolean spreadVeins)
BlockPos getPos()
int getCharge()
int getDecayDelay()
void update(final LevelAccessor level, final BlockPos originPos, final RandomSource random, final SculkSpreader spreader, final boolean spreadVeins)

Fields & Constants (13)

MAX_GROWTH_RATE_RADIUS
MAX_CHARGE
MAX_DECAY_FACTOR
MAX_CURSORS
SHRIEKER_PLACEMENT_RATE
MAX_CURSOR_DISTANCE
isWorldGeneration
replaceableBlocks
growthSpawnCost
noGrowthRadius
chargeDecayRate
additionalDecayRate
cursors

String literals (9)

"cursors"
"stats.total"
"stats.count"
"stats.max"
"stats.avg"
"charge"
"decay_delay"
"update_delay"
"facings"

Full Source

SculkSpreader.java373 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.block;
2
3
import com.google.common.annotations.VisibleForTesting;
4
import com.google.common.collect.Lists;
5
import com.google.common.collect.Sets;
6
import com.mojang.serialization.Codec;
7
import com.mojang.serialization.codecs.RecordCodecBuilder;
8
import it.unimi.dsi.fastutil.objects.Object2IntMap;
9
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
10
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
11
import it.unimi.dsi.fastutil.objects.Object2IntMap.Entry;
12
import java.util.ArrayList;
13
import java.util.Collection;
14
import java.util.HashMap;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Optional;
18
import java.util.Set;
19
import net.minecraft.SharedConstants;
20
import net.minecraft.core.BlockPos;
21
import net.minecraft.core.Direction;
22
import net.minecraft.core.Vec3i;
23
import net.minecraft.server.level.ServerLevel;
24
import net.minecraft.sounds.SoundEvents;
25
import net.minecraft.sounds.SoundSource;
26
import net.minecraft.tags.BlockTags;
27
import net.minecraft.tags.TagKey;
28
import net.minecraft.util.Mth;
29
import net.minecraft.util.RandomSource;
30
import net.minecraft.util.Util;
31
import net.minecraft.world.level.LevelAccessor;
32
import net.minecraft.world.level.block.state.BlockState;
33
import net.minecraft.world.level.storage.ValueInput;
34
import net.minecraft.world.level.storage.ValueOutput;
35
import org.jspecify.annotations.Nullable;
36
37
public class SculkSpreader {
38
	public static final int MAX_GROWTH_RATE_RADIUS = 24;
39
	public static final int MAX_CHARGE = 1000;
40
	public static final float MAX_DECAY_FACTOR = 0.5F;
41
	private static final int MAX_CURSORS = 32;
42
	public static final int SHRIEKER_PLACEMENT_RATE = 11;
43
	public static final int MAX_CURSOR_DISTANCE = 1024;
44
	private final boolean isWorldGeneration;
45
	private final TagKey<Block> replaceableBlocks;
46
	private final int growthSpawnCost;
47
	private final int noGrowthRadius;
48
	private final int chargeDecayRate;
49
	private final int additionalDecayRate;
50
	private List<SculkSpreader.ChargeCursor> cursors = new ArrayList<>();
51
52
	public SculkSpreader(
53
		final boolean isWorldGeneration,
54
		final TagKey<Block> replaceableBlocks,
55
		final int growthSpawnCost,
56
		final int noGrowthRadius,
57
		final int chargeDecayRate,
58
		final int additionalDecayRate
59
	) {
60
		this.isWorldGeneration = isWorldGeneration;
61
		this.replaceableBlocks = replaceableBlocks;
62
		this.growthSpawnCost = growthSpawnCost;
63
		this.noGrowthRadius = noGrowthRadius;
64
		this.chargeDecayRate = chargeDecayRate;
65
		this.additionalDecayRate = additionalDecayRate;
66
	}
67
68
	public static SculkSpreader createLevelSpreader() {
69
		return new SculkSpreader(false, BlockTags.SCULK_REPLACEABLE, 10, 4, 10, 5);
70
	}
71
72
	public static SculkSpreader createWorldGenSpreader() {
73
		return new SculkSpreader(true, BlockTags.SCULK_REPLACEABLE_WORLD_GEN, 50, 1, 5, 10);
74
	}
75
76
	public TagKey<Block> replaceableBlocks() {
77
		return this.replaceableBlocks;
78
	}
79
80
	public int growthSpawnCost() {
81
		return this.growthSpawnCost;
82
	}
83
84
	public int noGrowthRadius() {
85
		return this.noGrowthRadius;
86
	}
87
88
	public int chargeDecayRate() {
89
		return this.chargeDecayRate;
90
	}
91
92
	public int additionalDecayRate() {
93
		return this.additionalDecayRate;
94
	}
95
96
	public boolean isWorldGeneration() {
97
		return this.isWorldGeneration;
98
	}
99
100
	@VisibleForTesting
101
	public List<SculkSpreader.ChargeCursor> getCursors() {
102
		return this.cursors;
103
	}
104
105
	public void clear() {
106
		this.cursors.clear();
107
	}
108
109
	public void load(final ValueInput input) {
110
		this.cursors.clear();
111
		input.read("cursors", SculkSpreader.ChargeCursor.CODEC.sizeLimitedListOf(32)).orElse(List.of()).forEach(this::addCursor);
112
	}
113
114
	public void save(final ValueOutput output) {
115
		output.store("cursors", SculkSpreader.ChargeCursor.CODEC.listOf(), this.cursors);
116
		if (SharedConstants.DEBUG_SCULK_CATALYST) {
117
			int charge = this.getCursors().stream().map(SculkSpreader.ChargeCursor::getCharge).reduce(0, Integer::sum);
118
			int charges = this.getCursors().stream().map(c -> 1).reduce(0, Integer::sum);
119
			int max = this.getCursors().stream().map(SculkSpreader.ChargeCursor::getCharge).reduce(0, Math::max);
120
			output.putInt("stats.total", charge);
121
			output.putInt("stats.count", charges);
122
			output.putInt("stats.max", max);
123
			output.putInt("stats.avg", charge / (charges + 1));
124
		}
125
	}
126
127
	public void addCursors(final BlockPos startPos, int charge) {
128
		while (charge > 0) {
129
			int currentCharge = Math.min(charge, 1000);
130
			this.addCursor(new SculkSpreader.ChargeCursor(startPos, currentCharge));
131
			charge -= currentCharge;
132
		}
133
	}
134
135
	private void addCursor(final SculkSpreader.ChargeCursor cursor) {
136
		if (this.cursors.size() < 32) {
137
			this.cursors.add(cursor);
138
		}
139
	}
140
141
	public void updateCursors(final LevelAccessor level, final BlockPos originPos, final RandomSource random, final boolean spreadVeins) {
142
		if (!this.cursors.isEmpty()) {
143
			List<SculkSpreader.ChargeCursor> processedCursors = new ArrayList<>();
144
			Map<BlockPos, SculkSpreader.ChargeCursor> mergeableCursors = new HashMap<>();
145
			Object2IntMap<BlockPos> chargeMap = new Object2IntOpenHashMap<>();
146
147
			for (SculkSpreader.ChargeCursor cursor : this.cursors) {
148
				if (!cursor.isPosUnreasonable(originPos)) {
149
					cursor.update(level, originPos, random, this, spreadVeins);
150
					if (cursor.charge <= 0) {
151
						level.levelEvent(3006, cursor.getPos(), 0);
152
					} else {
153
						BlockPos pos = cursor.getPos();
154
						chargeMap.computeInt(pos, (k, count) -> (count == null ? 0 : count) + cursor.charge);
155
						SculkSpreader.ChargeCursor existing = mergeableCursors.get(pos);
156
						if (existing == null) {
157
							mergeableCursors.put(pos, cursor);
158
							processedCursors.add(cursor);
159
						} else if (!this.isWorldGeneration() && cursor.charge + existing.charge <= 1000) {
160
							existing.mergeWith(cursor);
161
						} else {
162
							processedCursors.add(cursor);
163
							if (cursor.charge < existing.charge) {
164
								mergeableCursors.put(pos, cursor);
165
							}
166
						}
167
					}
168
				}
169
			}
170
171
			for (Entry<BlockPos> entry : chargeMap.object2IntEntrySet()) {
172
				BlockPos pos = entry.getKey();
173
				int charge = entry.getIntValue();
174
				SculkSpreader.ChargeCursor cursor = mergeableCursors.get(pos);
175
				Collection<Direction> faces = cursor == null ? null : cursor.getFacingData();
176
				if (charge > 0 && faces != null) {
177
					int numParticles = (int)(Math.log1p(charge) / 2.3F) + 1;
178
					int data = (numParticles << 6) + MultifaceBlock.pack(faces);
179
					level.levelEvent(3006, pos, data);
180
				}
181
			}
182
183
			this.cursors = processedCursors;
184
		}
185
	}
186
187
	public static class ChargeCursor {
188
		private static final ObjectArrayList<Vec3i> NON_CORNER_NEIGHBOURS = Util.make(
189
			new ObjectArrayList<>(18),
190
			list -> BlockPos.betweenClosedStream(new BlockPos(-1, -1, -1), new BlockPos(1, 1, 1))
191
				.filter(position -> (position.getX() == 0 || position.getY() == 0 || position.getZ() == 0) && !position.equals(BlockPos.ZERO))
192
				.map(BlockPos::immutable)
193
				.forEach(list::add)
194
		);
195
		public static final int MAX_CURSOR_DECAY_DELAY = 1;
196
		private static final int MAX_WORLDGEN_SPREAD = 12;
197
		private BlockPos pos;
198
		private int charge;
199
		private int updateDelay;
200
		private int decayDelay;
201
		private @Nullable Set<Direction> facings;
202
		private static final Codec<Set<Direction>> DIRECTION_SET = Direction.CODEC.listOf().xmap(l -> Sets.newEnumSet(l, Direction.class), Lists::newArrayList);
203
		public static final Codec<SculkSpreader.ChargeCursor> CODEC = RecordCodecBuilder.create(
204
			i -> i.group(
205
					BlockPos.CODEC.fieldOf("pos").forGetter(SculkSpreader.ChargeCursor::getPos),
206
					Codec.intRange(0, 1000).optionalFieldOf("charge", 0).forGetter(SculkSpreader.ChargeCursor::getCharge),
207
					Codec.intRange(0, 1).optionalFieldOf("decay_delay", 1).forGetter(SculkSpreader.ChargeCursor::getDecayDelay),
208
					Codec.intRange(0, Integer.MAX_VALUE).optionalFieldOf("update_delay", 0).forGetter(o -> o.updateDelay),
209
					DIRECTION_SET.lenientOptionalFieldOf("facings").forGetter(o -> Optional.ofNullable(o.getFacingData()))
210
				)
211
				.apply(i, SculkSpreader.ChargeCursor::new)
212
		);
213
214
		private ChargeCursor(final BlockPos pos, final int charge, final int decayDelay, final int updateDelay, final Optional<Set<Direction>> facings) {
215
			this.pos = pos;
216
			this.charge = charge;
217
			this.decayDelay = decayDelay;
218
			this.updateDelay = updateDelay;
219
			this.facings = facings.orElse(null);
220
		}
221
222
		public ChargeCursor(final BlockPos pos, final int charge) {
223
			this(pos, charge, 1, 0, Optional.empty());
224
		}
225
226
		public BlockPos getPos() {
227
			return this.pos;
228
		}
229
230
		private boolean isPosUnreasonable(final BlockPos originPos) {
231
			return this.pos.distChessboard(originPos) > 1024;
232
		}
233
234
		public int getCharge() {
235
			return this.charge;
236
		}
237
238
		public int getDecayDelay() {
239
			return this.decayDelay;
240
		}
241
242
		public @Nullable Set<Direction> getFacingData() {
243
			return this.facings;
244
		}
245
246
		private boolean shouldUpdate(final LevelAccessor level, final BlockPos pos, final boolean isWorldGen) {
247
			if (this.charge <= 0) {
248
				return false;
249
			} else if (isWorldGen) {
250
				return true;
251
			} else {
252
				return level instanceof ServerLevel serverLevel ? serverLevel.shouldTickBlocksAt(pos) : false;
253
			}
254
		}
255
256
		public void update(final LevelAccessor level, final BlockPos originPos, final RandomSource random, final SculkSpreader spreader, final boolean spreadVeins) {
257
			if (this.shouldUpdate(level, originPos, spreader.isWorldGeneration)) {
258
				if (this.updateDelay > 0) {
259
					this.updateDelay--;
260
				} else {
261
					BlockState currentState = level.getBlockState(this.pos);
262
					SculkBehaviour sculkBehaviour = getBlockBehaviour(currentState);
263
					if (spreadVeins && sculkBehaviour.attemptSpreadVein(level, this.pos, currentState, this.facings, spreader.isWorldGeneration())) {
264
						if (sculkBehaviour.canChangeBlockStateOnSpread()) {
265
							currentState = level.getBlockState(this.pos);
266
							sculkBehaviour = getBlockBehaviour(currentState);
267
						}
268
269
						level.playSound(null, this.pos, SoundEvents.SCULK_BLOCK_SPREAD, SoundSource.BLOCKS, 1.0F, 1.0F);
270
					}
271
272
					this.charge = sculkBehaviour.attemptUseCharge(this, level, originPos, random, spreader, spreadVeins);
273
					if (this.charge <= 0) {
274
						sculkBehaviour.onDischarged(level, currentState, this.pos, random);
275
					} else {
276
						BlockPos transferPos = getValidMovementPos(level, this.pos, random, originPos, spreader);
277
						if (transferPos != null) {
278
							sculkBehaviour.onDischarged(level, currentState, this.pos, random);
279
							this.pos = transferPos.immutable();
280
							currentState = level.getBlockState(transferPos);
281
						} else if (spreader.isWorldGeneration()) {
282
							sculkBehaviour.onDischarged(level, currentState, this.pos, random);
283
							this.charge = 0;
284
							return;
285
						}
286
287
						if (currentState.getBlock() instanceof SculkBehaviour) {
288
							this.facings = MultifaceBlock.availableFaces(currentState);
289
						}
290
291
						this.decayDelay = sculkBehaviour.updateDecayDelay(this.decayDelay);
292
						this.updateDelay = sculkBehaviour.getSculkSpreadDelay();
293
					}
294
				}
295
			}
296
		}
297
298
		private void mergeWith(final SculkSpreader.ChargeCursor other) {
299
			this.charge = this.charge + other.charge;
300
			other.charge = 0;
301
			this.updateDelay = Math.min(this.updateDelay, other.updateDelay);
302
		}
303
304
		private static SculkBehaviour getBlockBehaviour(final BlockState state) {
305
			return state.getBlock() instanceof SculkBehaviour behaviour ? behaviour : SculkBehaviour.DEFAULT;
306
		}
307
308
		private static List<Vec3i> getRandomizedNonCornerNeighbourOffsets(final RandomSource random) {
309
			return Util.shuffledCopy(NON_CORNER_NEIGHBOURS, random);
310
		}
311
312
		private static @Nullable BlockPos getValidMovementPos(
313
			final LevelAccessor level, final BlockPos pos, final RandomSource random, final BlockPos originPos, final SculkSpreader spreader
314
		) {
315
			BlockPos.MutableBlockPos sculkPosition = pos.mutable();
316
			BlockPos.MutableBlockPos neighbour = pos.mutable();
317
318
			for (Vec3i offset : getRandomizedNonCornerNeighbourOffsets(random)) {
319
				neighbour.setWithOffset(pos, offset);
320
				if (canMoveToPos(originPos, neighbour, spreader)) {
321
					BlockState transferee = level.getBlockState(neighbour);
322
					if (transferee.getBlock() instanceof SculkBehaviour && isMovementUnobstructed(level, pos, neighbour)) {
323
						sculkPosition.set(neighbour);
324
						if (SculkVeinBlock.hasSubstrateAccess(level, transferee, neighbour)) {
325
							break;
326
						}
327
					}
328
				}
329
			}
330
331
			return sculkPosition.equals(pos) ? null : sculkPosition;
332
		}
333
334
		private static boolean canMoveToPos(final BlockPos origin, final BlockPos target, final SculkSpreader spreader) {
335
			if (!spreader.isWorldGeneration()) {
336
				return true;
337
			}
338
339
			int distanceSq = Mth.square(origin.getX() - target.getX()) + Mth.square(origin.getZ() - target.getZ());
340
			return distanceSq <= 144;
341
		}
342
343
		private static boolean isMovementUnobstructed(final LevelAccessor level, final BlockPos from, final BlockPos to) {
344
			if (from.distManhattan(to) == 1) {
345
				return true;
346
			} else {
347
				BlockPos delta = to.subtract(from);
348
				Direction directionX = Direction.fromAxisAndDirection(
349
					Direction.Axis.X, delta.getX() < 0 ? Direction.AxisDirection.NEGATIVE : Direction.AxisDirection.POSITIVE
350
				);
351
				Direction directionY = Direction.fromAxisAndDirection(
352
					Direction.Axis.Y, delta.getY() < 0 ? Direction.AxisDirection.NEGATIVE : Direction.AxisDirection.POSITIVE
353
				);
354
				Direction directionZ = Direction.fromAxisAndDirection(
355
					Direction.Axis.Z, delta.getZ() < 0 ? Direction.AxisDirection.NEGATIVE : Direction.AxisDirection.POSITIVE
356
				);
357
				if (delta.getX() == 0) {
358
					return isUnobstructed(level, from, directionY) || isUnobstructed(level, from, directionZ);
359
				} else {
360
					return delta.getY() == 0
361
						? isUnobstructed(level, from, directionX) || isUnobstructed(level, from, directionZ)
362
						: isUnobstructed(level, from, directionX) || isUnobstructed(level, from, directionY);
363
				}
364
			}
365
		}
366
367
		private static boolean isUnobstructed(final LevelAccessor level, final BlockPos from, final Direction direction) {
368
			BlockPos testPos = from.relative(direction);
369
			return !level.getBlockState(testPos).isFaceSturdy(level, testPos, direction.getOpposite());
370
		}
371
	}
372
}
373

Decompiled Minecraft 26.3 source of SculkSpreader (net/minecraft/world/level/block/SculkSpreader.java) with Mojang official mappings, stored verbatim on the site.