SignBlockEntity .java

net.minecraft.world.level.block.entity.SignBlockEntity (class, 312 lines): members: executeClickCommandsIfPresent, DEFAULT_ALLOW_OP_FEATURES, updateText.

net.minecraft.world.level.block.entityclass312 linescommonextends BlockEntity11.1 KB

API Surface (22)

SignTextSlot getSlotPlayerIsFacing(final Player player)
SignText getText(final SignTextSlot slot)
int getTextLineHeight()
int getMaxTextLineWidth()
void saveAdditional(final ValueOutput output)
void loadAdditional(final ValueInput input)
void updateSignText(final Player player, final SignTextSlot slot, final List<FilteredText> lines)
boolean updateText(final UnaryOperator<SignText> function, final SignTextSlot slot)
void setText(final SignText text, final SignTextSlot slot)
boolean canExecuteClickCommands(final SignTextSlot slot, final Player player)
boolean executeClickCommandsIfPresent(final ServerLevel level, final Player player, final BlockPos pos, final SignTextSlot slot)
ClientboundBlockEntityDataPacket getUpdatePacket()
CompoundTag getUpdateTag(final HolderLookup.Provider registries)
void setAllowedPlayerEditor(final @Nullable UUID playerUUID)
boolean isWaxed()
boolean setWaxed(final boolean isWaxed)
boolean playerIsTooFarAwayToEdit(final UUID player)
void tick(final Level level, final BlockPos blockPos, final BlockState blockState, final SignBlockEntity signBlockEntity)
SoundEvent getSignInteractionFailedSoundEvent()
void applyImplicitComponents(final DataComponentGetter components)
void collectImplicitComponents(final DataComponentMap.Builder components)
void removeComponentsFromTag(final ValueOutput output)

Fields & Constants (11)

LOGGER
MAX_TEXT_LINE_WIDTH
TEXT_LINE_HEIGHT
DEFAULT_IS_WAXED
DEFAULT_ALLOW_OP_FEATURES
CLICK_ACTIONS_DISABLED
playerWhoMayEdit
frontText
backText
isWaxed
allowOpFeatures

String literals (6)

"sign.click_actions_disabled"
"allow_op_features"
"front_text"
"back_text"
"is_waxed"
"Sign"

Full Source

SignBlockEntity.java312 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.block.entity;
2
3
import com.mojang.brigadier.exceptions.CommandSyntaxException;
4
import com.mojang.logging.LogUtils;
5
import java.util.List;
6
import java.util.UUID;
7
import java.util.function.UnaryOperator;
8
import net.minecraft.ChatFormatting;
9
import net.minecraft.commands.CommandSource;
10
import net.minecraft.commands.CommandSourceStack;
11
import net.minecraft.core.BlockPos;
12
import net.minecraft.core.HolderLookup;
13
import net.minecraft.core.component.DataComponentGetter;
14
import net.minecraft.core.component.DataComponentMap;
15
import net.minecraft.core.component.DataComponents;
16
import net.minecraft.nbt.CompoundTag;
17
import net.minecraft.network.chat.ClickEvent;
18
import net.minecraft.network.chat.Component;
19
import net.minecraft.network.chat.ComponentUtils;
20
import net.minecraft.network.chat.ResolutionContext;
21
import net.minecraft.network.chat.Style;
22
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
23
import net.minecraft.server.level.ServerLevel;
24
import net.minecraft.server.network.FilteredText;
25
import net.minecraft.server.permissions.LevelBasedPermissionSet;
26
import net.minecraft.sounds.SoundEvent;
27
import net.minecraft.sounds.SoundEvents;
28
import net.minecraft.util.Mth;
29
import net.minecraft.util.Unit;
30
import net.minecraft.world.entity.player.Player;
31
import net.minecraft.world.level.Level;
32
import net.minecraft.world.level.block.SignBlock;
33
import net.minecraft.world.level.block.state.BlockState;
34
import net.minecraft.world.level.storage.ValueInput;
35
import net.minecraft.world.level.storage.ValueOutput;
36
import net.minecraft.world.phys.Vec2;
37
import net.minecraft.world.phys.Vec3;
38
import org.jspecify.annotations.Nullable;
39
import org.slf4j.Logger;
40
41
public class SignBlockEntity extends BlockEntity {
42
	private static final Logger LOGGER = LogUtils.getLogger();
43
	private static final int MAX_TEXT_LINE_WIDTH = 90;
44
	private static final int TEXT_LINE_HEIGHT = 10;
45
	private static final boolean DEFAULT_IS_WAXED = false;
46
	private static final boolean DEFAULT_ALLOW_OP_FEATURES = false;
47
	private static final Component CLICK_ACTIONS_DISABLED = Component.translatable("sign.click_actions_disabled").withStyle(ChatFormatting.RED);
48
	private @Nullable UUID playerWhoMayEdit;
49
	private SignText frontText = SignText.EMPTY;
50
	private SignText backText = SignText.EMPTY;
51
	private boolean isWaxed = false;
52
	private boolean allowOpFeatures = false;
53
54
	public SignBlockEntity(final BlockPos worldPosition, final BlockState blockState) {
55
		this(BlockEntityTypes.SIGN, worldPosition, blockState);
56
	}
57
58
	public SignBlockEntity(final BlockEntityType<? extends SignBlockEntity> type, final BlockPos worldPosition, final BlockState blockState) {
59
		super(type, worldPosition, blockState);
60
	}
61
62
	public SignTextSlot getSlotPlayerIsFacing(final Player player) {
63
		if (this.getBlockState().getBlock() instanceof SignBlock sign) {
64
			Vec3 signPositionOffset = sign.getSignHitboxCenterPosition(this.getBlockState());
65
			double xd = player.getX() - (this.getBlockPos().getX() + signPositionOffset.x);
66
			double zd = player.getZ() - (this.getBlockPos().getZ() + signPositionOffset.z);
67
			float signYRot = sign.getYRotationDegrees(this.getBlockState());
68
			float playerYRot = (float)(Mth.atan2(zd, xd) * 180.0F / (float)Math.PI) - 90.0F;
69
			return Mth.degreesDifferenceAbs(signYRot, playerYRot) <= 90.0F ? SignTextSlot.FRONT : SignTextSlot.BACK;
70
		} else {
71
			return SignTextSlot.FRONT;
72
		}
73
	}
74
75
	public SignText getText(final SignTextSlot slot) {
76
		return switch (slot) {
77
			case FRONT -> this.frontText;
78
			case BACK -> this.backText;
79
		};
80
	}
81
82
	public int getTextLineHeight() {
83
		return 10;
84
	}
85
86
	public int getMaxTextLineWidth() {
87
		return 90;
88
	}
89
90
	@Override
91
	protected void saveAdditional(final ValueOutput output) {
92
		super.saveAdditional(output);
93
		if (this.allowOpFeatures) {
94
			output.putBoolean("allow_op_features", this.allowOpFeatures);
95
		}
96
97
		output.store("front_text", SignText.CODEC, this.frontText);
98
		output.store("back_text", SignText.CODEC, this.backText);
99
		output.putBoolean("is_waxed", this.isWaxed);
100
	}
101
102
	@Override
103
	protected void loadAdditional(final ValueInput input) {
104
		super.loadAdditional(input);
105
		this.allowOpFeatures = input.getBooleanOr("allow_op_features", false);
106
		this.frontText = input.read("front_text", SignText.CODEC).map(this::resolveLines).orElse(SignText.EMPTY);
107
		this.backText = input.read("back_text", SignText.CODEC).map(this::resolveLines).orElse(SignText.EMPTY);
108
		this.isWaxed = input.getBooleanOr("is_waxed", false);
109
	}
110
111
	private SignText resolveLines(final SignText data) {
112
		return !this.allowOpFeatures ? data : data.asMutable().modifyLines(this::resolveLine).asImmutable();
113
	}
114
115
	private Component resolveLine(final Component component) {
116
		if (this.level instanceof ServerLevel serverLevel) {
117
			try {
118
				return ComponentUtils.resolve(ResolutionContext.create(createCommandSourceStack(null, serverLevel, this.worldPosition)), component);
119
			} catch (CommandSyntaxException var4) {
120
			}
121
		}
122
123
		return component;
124
	}
125
126
	public void updateSignText(final Player player, final SignTextSlot slot, final List<FilteredText> lines) {
127
		if (!this.isWaxed() && player.getUUID().equals(this.getPlayerWhoMayEdit()) && this.level != null) {
128
			this.updateText(text -> updateMessages(lines, text, player.isTextFilteringEnabled()), slot);
129
			this.setAllowedPlayerEditor(null);
130
			this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), 3);
131
		} else {
132
			LOGGER.warn("Player {} just tried to change non-editable sign", player.getPlainTextName());
133
		}
134
	}
135
136
	public boolean updateText(final UnaryOperator<SignText> function, final SignTextSlot slot) {
137
		SignText currentText = this.getText(slot);
138
		SignText newText = function.apply(currentText);
139
		if (currentText != newText) {
140
			this.setText(newText, slot);
141
			return true;
142
		} else {
143
			return false;
144
		}
145
	}
146
147
	private static SignText updateMessages(final List<FilteredText> newLines, final SignText originalText, final boolean shouldFilter) {
148
		SignText.Mutable result = originalText.asMutable();
149
		List<Component> originalLines = originalText.getMessages(shouldFilter);
150
151
		for (int i = 0; i < newLines.size(); i++) {
152
			FilteredText line = newLines.get(i);
153
			Style currentTextStyle = originalLines.get(i).getStyle();
154
			if (shouldFilter) {
155
				result.setLine(i, Component.literal(line.filteredOrEmpty()).setStyle(currentTextStyle));
156
			} else {
157
				result.setLine(i, Component.literal(line.raw()).setStyle(currentTextStyle), Component.literal(line.filteredOrEmpty()).setStyle(currentTextStyle));
158
			}
159
		}
160
161
		return result.asImmutable();
162
	}
163
164
	public void setText(final SignText text, final SignTextSlot slot) {
165
		switch (slot) {
166
			case FRONT:
167
				this.frontText = text;
168
				break;
169
			case BACK:
170
				this.backText = text;
171
		}
172
173
		this.markUpdated();
174
	}
175
176
	public boolean canExecuteClickCommands(final SignTextSlot slot, final Player player) {
177
		return this.isWaxed() && this.getText(slot).hasAnyClickCommands(player.isTextFilteringEnabled());
178
	}
179
180
	public boolean executeClickCommandsIfPresent(final ServerLevel level, final Player player, final BlockPos pos, final SignTextSlot slot) {
181
		boolean hasAnyClickCommand = false;
182
183
		for (Component message : this.getText(slot).getMessages(player.isTextFilteringEnabled())) {
184
			Style style = message.getStyle();
185
			ClickEvent event = style.getClickEvent();
186
			switch (event) {
187
				case ClickEvent.RunCommand command:
188
					if (this.allowOpFeatures) {
189
						level.getServer().getCommands().performPrefixedCommand(createCommandSourceStack(player, level, pos), command.command());
190
					}
191
192
					hasAnyClickCommand = true;
193
					break;
194
				case ClickEvent.ShowDialog dialog:
195
					if (this.allowOpFeatures) {
196
						player.openDialog(dialog.dialog());
197
					}
198
199
					hasAnyClickCommand = true;
200
					break;
201
				case ClickEvent.Custom custom:
202
					if (this.allowOpFeatures) {
203
						level.getServer().handleCustomClickAction(custom.id(), custom.payload());
204
					}
205
206
					hasAnyClickCommand = true;
207
					continue;
208
				case null:
209
				default:
210
			}
211
		}
212
213
		if (!this.allowOpFeatures && hasAnyClickCommand) {
214
			player.sendOverlayMessage(CLICK_ACTIONS_DISABLED);
215
		}
216
217
		return hasAnyClickCommand;
218
	}
219
220
	private static CommandSourceStack createCommandSourceStack(final @Nullable Player player, final ServerLevel level, final BlockPos pos) {
221
		return player != null
222
			? new CommandSourceStack(CommandSource.NULL, Vec3.atCenterOf(pos), Vec2.ZERO, level, LevelBasedPermissionSet.GAMEMASTER, level.getServer(), player)
223
			: new CommandSourceStack(
224
				CommandSource.NULL, Vec3.atCenterOf(pos), Vec2.ZERO, level, LevelBasedPermissionSet.GAMEMASTER, Component.literal("Sign"), level.getServer()
225
			);
226
	}
227
228
	public ClientboundBlockEntityDataPacket getUpdatePacket() {
229
		return ClientboundBlockEntityDataPacket.create(this);
230
	}
231
232
	@Override
233
	public CompoundTag getUpdateTag(final HolderLookup.Provider registries) {
234
		return this.saveCustomOnly(registries);
235
	}
236
237
	public void setAllowedPlayerEditor(final @Nullable UUID playerUUID) {
238
		this.playerWhoMayEdit = playerUUID;
239
	}
240
241
	public @Nullable UUID getPlayerWhoMayEdit() {
242
		return this.playerWhoMayEdit;
243
	}
244
245
	private void markUpdated() {
246
		this.setChanged();
247
		this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), 3);
248
	}
249
250
	public boolean isWaxed() {
251
		return this.isWaxed;
252
	}
253
254
	public boolean setWaxed(final boolean isWaxed) {
255
		if (this.isWaxed != isWaxed) {
256
			this.isWaxed = isWaxed;
257
			this.markUpdated();
258
			return true;
259
		} else {
260
			return false;
261
		}
262
	}
263
264
	public boolean playerIsTooFarAwayToEdit(final UUID player) {
265
		Player editingPlayer = this.level.getPlayerByUUID(player);
266
		return editingPlayer == null || !editingPlayer.isWithinBlockInteractionRange(this.getBlockPos(), 4.0);
267
	}
268
269
	public static void tick(final Level level, final BlockPos blockPos, final BlockState blockState, final SignBlockEntity signBlockEntity) {
270
		UUID playerWhoMayEdit = signBlockEntity.getPlayerWhoMayEdit();
271
		if (playerWhoMayEdit != null) {
272
			signBlockEntity.clearInvalidPlayerWhoMayEdit(signBlockEntity, level, playerWhoMayEdit);
273
		}
274
	}
275
276
	private void clearInvalidPlayerWhoMayEdit(final SignBlockEntity signBlockEntity, final Level level, final UUID playerWhoMayEdit) {
277
		if (signBlockEntity.playerIsTooFarAwayToEdit(playerWhoMayEdit)) {
278
			signBlockEntity.setAllowedPlayerEditor(null);
279
		}
280
	}
281
282
	public SoundEvent getSignInteractionFailedSoundEvent() {
283
		return SoundEvents.WAXED_SIGN_INTERACT_FAIL;
284
	}
285
286
	@Override
287
	protected void applyImplicitComponents(final DataComponentGetter components) {
288
		super.applyImplicitComponents(components);
289
		this.frontText = components.getOrDefault(DataComponents.SIGN_TEXT_FRONT, SignText.EMPTY);
290
		this.backText = components.getOrDefault(DataComponents.SIGN_TEXT_BACK, SignText.EMPTY);
291
		this.isWaxed = components.get(DataComponents.WAXED) != null;
292
	}
293
294
	@Override
295
	protected void collectImplicitComponents(final DataComponentMap.Builder components) {
296
		super.collectImplicitComponents(components);
297
		components.set(DataComponents.SIGN_TEXT_FRONT, this.frontText);
298
		components.set(DataComponents.SIGN_TEXT_BACK, this.backText);
299
		if (this.isWaxed) {
300
			components.set(DataComponents.WAXED, Unit.INSTANCE);
301
		}
302
	}
303
304
	@Override
305
	public void removeComponentsFromTag(final ValueOutput output) {
306
		super.removeComponentsFromTag(output);
307
		output.discard("front_text");
308
		output.discard("back_text");
309
		output.discard("is_waxed");
310
	}
311
}
312

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