SpreadPlayersCommand .java

net.minecraft.server.commands.SpreadPlayersCommand (class, 369 lines): members: ERROR_FAILED_TO_SPREAD_ENTITIES, ERROR_FAILED_TO_SPREAD_TEAMS, spreadDist.

net.minecraft.server.commandsclass369 linesserver12.1 KB

API Surface (9)

void register(final CommandDispatcher<CommandSourceStack> dispatcher)
double dist(final SpreadPlayersCommand.Position target)
void normalize()
double getLength()
void moveAway(final SpreadPlayersCommand.Position pos)
boolean clamp(final double minX, final double minZ, final double maxX, final double maxZ)
int getSpawnY(final BlockGetter level, final int maxHeight)
boolean isSafe(final BlockGetter level, final int maxHeight)
void randomize(final RandomSource random, final double minX, final double minZ, final double maxX, final double maxZ)

Fields & Constants (19)

MAX_ITERATION_COUNT
ERROR_FAILED_TO_SPREAD_TEAMS
ERROR_FAILED_TO_SPREAD_ENTITIES
ERROR_INVALID_MAX_HEIGHT
source
center
spreadDistance
maxRange
maxHeight
respectTeams
spreadDist
level
random
minX
minZ
maxX
maxZ
positions
entities

String literals (14)

"commands.spreadplayers.failed.teams"
"commands.spreadplayers.failed.entities"
"commands.spreadplayers.failed.invalid.height"
"spreadplayers"
"center"
"spreadDistance"
"maxRange"
"respectTeams"
"targets"
"under"
"maxHeight"
"commands.spreadplayers.success."
"teams"
"entities"

Full Source

SpreadPlayersCommand.java369 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.server.commands;
2
3
import com.google.common.collect.Maps;
4
import com.google.common.collect.Sets;
5
import com.mojang.brigadier.CommandDispatcher;
6
import com.mojang.brigadier.arguments.BoolArgumentType;
7
import com.mojang.brigadier.arguments.FloatArgumentType;
8
import com.mojang.brigadier.arguments.IntegerArgumentType;
9
import com.mojang.brigadier.exceptions.CommandSyntaxException;
10
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
11
import com.mojang.brigadier.exceptions.Dynamic4CommandExceptionType;
12
import java.util.Collection;
13
import java.util.Locale;
14
import java.util.Map;
15
import java.util.Set;
16
import net.minecraft.commands.CommandSourceStack;
17
import net.minecraft.commands.Commands;
18
import net.minecraft.commands.arguments.EntityArgument;
19
import net.minecraft.commands.arguments.coordinates.Vec2Argument;
20
import net.minecraft.core.BlockPos;
21
import net.minecraft.core.Direction;
22
import net.minecraft.network.chat.Component;
23
import net.minecraft.server.level.ServerLevel;
24
import net.minecraft.tags.BlockTags;
25
import net.minecraft.util.Mth;
26
import net.minecraft.util.RandomSource;
27
import net.minecraft.world.entity.Entity;
28
import net.minecraft.world.entity.player.Player;
29
import net.minecraft.world.level.BlockGetter;
30
import net.minecraft.world.level.block.state.BlockState;
31
import net.minecraft.world.phys.Vec2;
32
import net.minecraft.world.scores.Team;
33
34
public class SpreadPlayersCommand {
35
	private static final int MAX_ITERATION_COUNT = 10000;
36
	private static final Dynamic4CommandExceptionType ERROR_FAILED_TO_SPREAD_TEAMS = new Dynamic4CommandExceptionType(
37
		(count, x, z, recommended) -> Component.translatableEscape("commands.spreadplayers.failed.teams", count, x, z, recommended)
38
	);
39
	private static final Dynamic4CommandExceptionType ERROR_FAILED_TO_SPREAD_ENTITIES = new Dynamic4CommandExceptionType(
40
		(count, x, z, recommended) -> Component.translatableEscape("commands.spreadplayers.failed.entities", count, x, z, recommended)
41
	);
42
	private static final Dynamic2CommandExceptionType ERROR_INVALID_MAX_HEIGHT = new Dynamic2CommandExceptionType(
43
		(suppliedMaxHeight, worldMinHeight) -> Component.translatableEscape("commands.spreadplayers.failed.invalid.height", suppliedMaxHeight, worldMinHeight)
44
	);
45
46
	public static void register(final CommandDispatcher<CommandSourceStack> dispatcher) {
47
		dispatcher.register(
48
			Commands.literal("spreadplayers")
49
				.requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS))
50
				.then(
51
					Commands.argument("center", Vec2Argument.vec2())
52
						.then(
53
							Commands.argument("spreadDistance", FloatArgumentType.floatArg(0.0F))
54
								.then(
55
									Commands.argument("maxRange", FloatArgumentType.floatArg(1.0F))
56
										.then(
57
											Commands.argument("respectTeams", BoolArgumentType.bool())
58
												.then(
59
													Commands.argument("targets", EntityArgument.entities())
60
														.executes(
61
															c -> spreadPlayers(
62
																c.getSource(),
63
																Vec2Argument.getVec2(c, "center"),
64
																FloatArgumentType.getFloat(c, "spreadDistance"),
65
																FloatArgumentType.getFloat(c, "maxRange"),
66
																c.getSource().getLevel().getMaxY() + 1,
67
																BoolArgumentType.getBool(c, "respectTeams"),
68
																EntityArgument.getEntities(c, "targets")
69
															)
70
														)
71
												)
72
										)
73
										.then(
74
											Commands.literal("under")
75
												.then(
76
													Commands.argument("maxHeight", IntegerArgumentType.integer())
77
														.then(
78
															Commands.argument("respectTeams", BoolArgumentType.bool())
79
																.then(
80
																	Commands.argument("targets", EntityArgument.entities())
81
																		.executes(
82
																			c -> spreadPlayers(
83
																				c.getSource(),
84
																				Vec2Argument.getVec2(c, "center"),
85
																				FloatArgumentType.getFloat(c, "spreadDistance"),
86
																				FloatArgumentType.getFloat(c, "maxRange"),
87
																				IntegerArgumentType.getInteger(c, "maxHeight"),
88
																				BoolArgumentType.getBool(c, "respectTeams"),
89
																				EntityArgument.getEntities(c, "targets")
90
																			)
91
																		)
92
																)
93
														)
94
												)
95
										)
96
								)
97
						)
98
				)
99
		);
100
	}
101
102
	private static int spreadPlayers(
103
		final CommandSourceStack source,
104
		final Vec2 center,
105
		final float spreadDistance,
106
		final float maxRange,
107
		final int maxHeight,
108
		final boolean respectTeams,
109
		final Collection<? extends Entity> entities
110
	) throws CommandSyntaxException {
111
		ServerLevel level = source.getLevel();
112
		int minY = level.getMinY();
113
		if (maxHeight < minY) {
114
			throw ERROR_INVALID_MAX_HEIGHT.create(maxHeight, minY);
115
		}
116
117
		RandomSource random = RandomSource.createThreadLocalInstance();
118
		double minX = center.x - maxRange;
119
		double minZ = center.y - maxRange;
120
		double maxX = center.x + maxRange;
121
		double maxZ = center.y + maxRange;
122
		SpreadPlayersCommand.Position[] positions = createInitialPositions(
123
			random, respectTeams ? getNumberOfTeams(entities) : entities.size(), minX, minZ, maxX, maxZ
124
		);
125
		spreadPositions(center, spreadDistance, level, random, minX, minZ, maxX, maxZ, maxHeight, positions, respectTeams);
126
		double distance = setPlayerPositions(entities, level, positions, maxHeight, respectTeams);
127
		source.sendSuccess(
128
			() -> Component.translatable(
129
				"commands.spreadplayers.success." + (respectTeams ? "teams" : "entities"),
130
				positions.length,
131
				center.x,
132
				center.y,
133
				String.format(Locale.ROOT, "%.2f", distance)
134
			),
135
			true
136
		);
137
		return positions.length;
138
	}
139
140
	private static int getNumberOfTeams(final Collection<? extends Entity> players) {
141
		Set<Team> teams = Sets.newHashSet();
142
143
		for (Entity player : players) {
144
			if (player instanceof Player) {
145
				teams.add(player.getTeam());
146
			} else {
147
				teams.add(null);
148
			}
149
		}
150
151
		return teams.size();
152
	}
153
154
	private static void spreadPositions(
155
		final Vec2 center,
156
		final double spreadDist,
157
		final ServerLevel level,
158
		final RandomSource random,
159
		final double minX,
160
		final double minZ,
161
		final double maxX,
162
		final double maxZ,
163
		final int maxHeight,
164
		final SpreadPlayersCommand.Position[] positions,
165
		final boolean respectTeams
166
	) throws CommandSyntaxException {
167
		boolean hasCollisions = true;
168
		double minDistance = Float.MAX_VALUE;
169
170
		int iteration;
171
		for (iteration = 0; iteration < 10000 && hasCollisions; iteration++) {
172
			hasCollisions = false;
173
			minDistance = Float.MAX_VALUE;
174
175
			for (int i = 0; i < positions.length; i++) {
176
				SpreadPlayersCommand.Position position = positions[i];
177
				int neighbourCount = 0;
178
				SpreadPlayersCommand.Position averageNeighbourPos = new SpreadPlayersCommand.Position();
179
180
				for (int j = 0; j < positions.length; j++) {
181
					if (i != j) {
182
						SpreadPlayersCommand.Position neighbour = positions[j];
183
						double dist = position.dist(neighbour);
184
						minDistance = Math.min(dist, minDistance);
185
						if (dist < spreadDist) {
186
							neighbourCount++;
187
							averageNeighbourPos.x = averageNeighbourPos.x + (neighbour.x - position.x);
188
							averageNeighbourPos.z = averageNeighbourPos.z + (neighbour.z - position.z);
189
						}
190
					}
191
				}
192
193
				if (neighbourCount > 0) {
194
					averageNeighbourPos.x /= neighbourCount;
195
					averageNeighbourPos.z /= neighbourCount;
196
					double length = averageNeighbourPos.getLength();
197
					if (length > 0.0) {
198
						averageNeighbourPos.normalize();
199
						position.moveAway(averageNeighbourPos);
200
					} else {
201
						position.randomize(random, minX, minZ, maxX, maxZ);
202
					}
203
204
					hasCollisions = true;
205
				}
206
207
				if (position.clamp(minX, minZ, maxX, maxZ)) {
208
					hasCollisions = true;
209
				}
210
			}
211
212
			if (!hasCollisions) {
213
				for (SpreadPlayersCommand.Position position : positions) {
214
					if (!position.isSafe(level, maxHeight)) {
215
						position.randomize(random, minX, minZ, maxX, maxZ);
216
						hasCollisions = true;
217
					}
218
				}
219
			}
220
		}
221
222
		if (minDistance == Float.MAX_VALUE) {
223
			minDistance = 0.0;
224
		}
225
226
		if (iteration >= 10000) {
227
			if (respectTeams) {
228
				throw ERROR_FAILED_TO_SPREAD_TEAMS.create(positions.length, center.x, center.y, String.format(Locale.ROOT, "%.2f", minDistance));
229
			} else {
230
				throw ERROR_FAILED_TO_SPREAD_ENTITIES.create(positions.length, center.x, center.y, String.format(Locale.ROOT, "%.2f", minDistance));
231
			}
232
		}
233
	}
234
235
	private static double setPlayerPositions(
236
		final Collection<? extends Entity> entities,
237
		final ServerLevel level,
238
		final SpreadPlayersCommand.Position[] positions,
239
		final int maxHeight,
240
		final boolean respectTeams
241
	) {
242
		double avgDistance = 0.0;
243
		int positionIndex = 0;
244
		Map<Team, SpreadPlayersCommand.Position> teamPositions = Maps.newHashMap();
245
246
		for (Entity entity : entities) {
247
			SpreadPlayersCommand.Position position;
248
			if (respectTeams) {
249
				Team team = entity instanceof Player ? entity.getTeam() : null;
250
				if (!teamPositions.containsKey(team)) {
251
					teamPositions.put(team, positions[positionIndex++]);
252
				}
253
254
				position = teamPositions.get(team);
255
			} else {
256
				position = positions[positionIndex++];
257
			}
258
259
			entity.teleportTo(
260
				level, Mth.floor(position.x) + 0.5, position.getSpawnY(level, maxHeight), Mth.floor(position.z) + 0.5, Set.of(), entity.getYRot(), entity.getXRot(), true
261
			);
262
			double closest = Double.MAX_VALUE;
263
264
			for (SpreadPlayersCommand.Position testPosition : positions) {
265
				if (position != testPosition) {
266
					double dist = position.dist(testPosition);
267
					closest = Math.min(dist, closest);
268
				}
269
			}
270
271
			avgDistance += closest;
272
		}
273
274
		return entities.size() < 2 ? 0.0 : avgDistance / entities.size();
275
	}
276
277
	private static SpreadPlayersCommand.Position[] createInitialPositions(
278
		final RandomSource random, final int count, final double minX, final double minZ, final double maxX, final double maxZ
279
	) {
280
		SpreadPlayersCommand.Position[] result = new SpreadPlayersCommand.Position[count];
281
282
		for (int i = 0; i < result.length; i++) {
283
			SpreadPlayersCommand.Position position = new SpreadPlayersCommand.Position();
284
			position.randomize(random, minX, minZ, maxX, maxZ);
285
			result[i] = position;
286
		}
287
288
		return result;
289
	}
290
291
	private static class Position {
292
		private double x;
293
		private double z;
294
295
		public double dist(final SpreadPlayersCommand.Position target) {
296
			double dx = this.x - target.x;
297
			double dz = this.z - target.z;
298
			return Math.sqrt(dx * dx + dz * dz);
299
		}
300
301
		public void normalize() {
302
			double dist = this.getLength();
303
			this.x /= dist;
304
			this.z /= dist;
305
		}
306
307
		public double getLength() {
308
			return Math.sqrt(this.x * this.x + this.z * this.z);
309
		}
310
311
		public void moveAway(final SpreadPlayersCommand.Position pos) {
312
			this.x = this.x - pos.x;
313
			this.z = this.z - pos.z;
314
		}
315
316
		public boolean clamp(final double minX, final double minZ, final double maxX, final double maxZ) {
317
			boolean changed = false;
318
			if (this.x < minX) {
319
				this.x = minX;
320
				changed = true;
321
			} else if (this.x > maxX) {
322
				this.x = maxX;
323
				changed = true;
324
			}
325
326
			if (this.z < minZ) {
327
				this.z = minZ;
328
				changed = true;
329
			} else if (this.z > maxZ) {
330
				this.z = maxZ;
331
				changed = true;
332
			}
333
334
			return changed;
335
		}
336
337
		public int getSpawnY(final BlockGetter level, final int maxHeight) {
338
			BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(this.x, maxHeight + 1, this.z);
339
			boolean air2Above = level.getBlockState(pos).isAir();
340
			pos.move(Direction.DOWN);
341
			boolean air1Above = level.getBlockState(pos).isAir();
342
343
			while (pos.getY() > level.getMinY()) {
344
				pos.move(Direction.DOWN);
345
				boolean currentIsAir = level.getBlockState(pos).isAir();
346
				if (!currentIsAir && air1Above && air2Above) {
347
					return pos.getY() + 1;
348
				}
349
350
				air2Above = air1Above;
351
				air1Above = currentIsAir;
352
			}
353
354
			return maxHeight + 1;
355
		}
356
357
		public boolean isSafe(final BlockGetter level, final int maxHeight) {
358
			BlockPos pos = BlockPos.containing(this.x, this.getSpawnY(level, maxHeight) - 1, this.z);
359
			BlockState state = level.getBlockState(pos);
360
			return pos.getY() < maxHeight && !state.liquid() && state.is(BlockTags.ENTITIES_CAN_TELEPORT_TO);
361
		}
362
363
		public void randomize(final RandomSource random, final double minX, final double minZ, final double maxX, final double maxZ) {
364
			this.x = Mth.nextDouble(random, minX, maxX);
365
			this.z = Mth.nextDouble(random, minZ, maxZ);
366
		}
367
	}
368
}
369

Decompiled Minecraft 26.3 source of SpreadPlayersCommand (net/minecraft/server/commands/SpreadPlayersCommand.java) with Mojang official mappings, stored verbatim on the site.