StructureTemplate .java

net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate (class, 882 lines): loads. members: getZeroPositionWithTransform, SIZE_TAG.

net.minecraft.world.level.levelgen.structure.templatesystemclass882 linescommon34.4 KB

API Surface (37)

Vec3i getSize()
void setAuthor(final String author)
String getAuthor()
void fillFromWorld(final Level level, final BlockPos position, final Vec3i size, final boolean inludeEntities, final List<Block> ignoreBlocks)
List<StructureTemplate.StructureBlockInfo> filterBlocks(final BlockPos position, final StructurePlaceSettings settings, final Block block)
List<StructureTemplate.JigsawBlockInfo> getJigsaws(final BlockPos position, final Rotation rotation)
ObjectArrayList<StructureTemplate.StructureBlockInfo> filterBlocks(final BlockPos position, final StructurePlaceSettings settings, final Block block, final boolean absolute)
BlockPos calculateConnectedPosition(final StructurePlaceSettings settings1, final BlockPos connection1, final StructurePlaceSettings settings2, final BlockPos connection2)
BlockPos calculateRelativePosition(final StructurePlaceSettings settings, final BlockPos pos)
boolean placeInWorld(final ServerLevelAccessor level, final BlockPos position, final BlockPos referencePos, final StructurePlaceSettings settings, final RandomSource random, final @Block.UpdateFlags int updateMode)
void updateShapeAtEdge(final LevelAccessor level, final @Block.UpdateFlags int updateMode, final DiscreteVoxelShape shape, final BlockPos pos)
void updateShapeAtEdge(final LevelAccessor level, final @Block.UpdateFlags int updateMode, final DiscreteVoxelShape shape, final int startX, final int startY, final int startZ)
List<StructureTemplate.StructureBlockInfo> processBlockInfos(final ServerLevelAccessor level, final BlockPos position, final BlockPos referencePos, final StructurePlaceSettings settings, final List<StructureTemplate.StructureBlockInfo> blockInfoList)
Vec3i getSize(final Rotation rotation)
BlockPos transform(final BlockPos pos, final Mirror mirror, final Rotation rotation, final BlockPos pivot)
Vec3 transform(final Vec3 pos, final Mirror mirror, final Rotation rotation, final BlockPos pivot)
BlockPos getZeroPositionWithTransform(final BlockPos zeroPos, final Mirror mirror, final Rotation rotation)
BlockPos getZeroPositionWithTransform(final BlockPos zeroPos, final Mirror mirror, final Rotation rotation, int sizeX, int sizeZ)
BoundingBox getBoundingBox(final StructurePlaceSettings settings, final BlockPos position)
BoundingBox getBoundingBox(final BlockPos position, final Rotation rotation, final BlockPos pivot, final Mirror mirror)
BoundingBox getBoundingBox(final BlockPos position, final Rotation rotation, final BlockPos pivot, final Mirror mirror, final Vec3i size)
CompoundTag save(final CompoundTag tag)
void load(final HolderGetter<Block> blockLookup, final CompoundTag tag)
JigsawBlockEntity.JointType getJointType(final CompoundTag nbt, final BlockState state)
JigsawBlockEntity.JointType getDefaultJointType(final BlockState state)
record JigsawBlockInfo(BlockPos pos, BlockState state, JigsawBlockEntity.JointType jointType, @Nullable Identifier name, ResourceKey<StructureTemplatePool> pool, Identifier target, int placementPriority, int selectionPriority)
StructureTemplate.JigsawBlockInfo parse(final StructureTemplate.StructureBlockInfo info)
String toString()
StructureTemplate.JigsawBlockInfo withInfo(final BlockPos pos, final BlockState state)
List<StructureTemplate.JigsawBlockInfo> jigsaws()
List<StructureTemplate.StructureBlockInfo> blocks()
List<StructureTemplate.StructureBlockInfo> blocks(final Block filter)
int idFor(final BlockState state)
Iterator<BlockState> iterator()
void addMapping(final BlockState state, final int id)
record StructureBlockInfo(BlockPos pos, BlockState state, @Nullable CompoundTag nbt)
String toString()

Fields & Constants (39)

LOGGER
PALETTE_TAG
PALETTE_LIST_TAG
ENTITIES_TAG
BLOCKS_TAG
BLOCK_TAG_POS
BLOCK_TAG_STATE
BLOCK_TAG_NBT
ENTITY_TAG_POS
ENTITY_TAG_BLOCKPOS
ENTITY_TAG_NBT
SIZE_TAG
palettes
entityInfoList
size
author
info
fullBlockList
blockEntitiesList
block
settings2
level
position
referencePos
settings
random
startY
mirror
rotation
pivot
boundingBox
finalizeEntities
pos
state
jointType
name

…and 3 more (see full source).

String literals (16)

"palette"
"palettes"
"entities"
"blocks"
"state"
"blockPos"
"size"
"LootTableSeed"
"UUID"
"block_pos"
"joint"
" nbt was null"
"pool"
"target"
"placement_priority"
"selection_priority"

Full Source

StructureTemplate.java882 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.levelgen.structure.templatesystem;
2
3
import com.google.common.annotations.VisibleForTesting;
4
import com.google.common.collect.Lists;
5
import com.google.common.collect.Maps;
6
import com.mojang.datafixers.util.Pair;
7
import com.mojang.logging.LogUtils;
8
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
9
import java.util.ArrayList;
10
import java.util.Comparator;
11
import java.util.Iterator;
12
import java.util.List;
13
import java.util.Locale;
14
import java.util.Map;
15
import java.util.Objects;
16
import java.util.Optional;
17
import java.util.stream.Collectors;
18
import net.minecraft.SharedConstants;
19
import net.minecraft.core.BlockPos;
20
import net.minecraft.core.Direction;
21
import net.minecraft.core.HolderGetter;
22
import net.minecraft.core.IdMapper;
23
import net.minecraft.core.Vec3i;
24
import net.minecraft.data.worldgen.Pools;
25
import net.minecraft.nbt.CompoundTag;
26
import net.minecraft.nbt.DoubleTag;
27
import net.minecraft.nbt.IntTag;
28
import net.minecraft.nbt.ListTag;
29
import net.minecraft.nbt.NbtUtils;
30
import net.minecraft.resources.Identifier;
31
import net.minecraft.resources.ResourceKey;
32
import net.minecraft.util.ProblemReporter;
33
import net.minecraft.util.RandomSource;
34
import net.minecraft.world.RandomizableContainer;
35
import net.minecraft.world.entity.Entity;
36
import net.minecraft.world.entity.EntitySpawnReason;
37
import net.minecraft.world.entity.EntitySpawnRequest;
38
import net.minecraft.world.entity.EntityType;
39
import net.minecraft.world.entity.Mob;
40
import net.minecraft.world.entity.decoration.painting.Painting;
41
import net.minecraft.world.entity.player.Player;
42
import net.minecraft.world.level.EmptyBlockGetter;
43
import net.minecraft.world.level.Level;
44
import net.minecraft.world.level.LevelAccessor;
45
import net.minecraft.world.level.ServerLevelAccessor;
46
import net.minecraft.world.level.block.Block;
47
import net.minecraft.world.level.block.Blocks;
48
import net.minecraft.world.level.block.JigsawBlock;
49
import net.minecraft.world.level.block.LiquidBlockContainer;
50
import net.minecraft.world.level.block.Mirror;
51
import net.minecraft.world.level.block.Rotation;
52
import net.minecraft.world.level.block.entity.BlockEntity;
53
import net.minecraft.world.level.block.entity.JigsawBlockEntity;
54
import net.minecraft.world.level.block.state.BlockState;
55
import net.minecraft.world.level.levelgen.structure.BoundingBox;
56
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
57
import net.minecraft.world.level.material.FluidState;
58
import net.minecraft.world.level.storage.TagValueInput;
59
import net.minecraft.world.level.storage.TagValueOutput;
60
import net.minecraft.world.phys.AABB;
61
import net.minecraft.world.phys.Vec3;
62
import net.minecraft.world.phys.shapes.BitSetDiscreteVoxelShape;
63
import net.minecraft.world.phys.shapes.DiscreteVoxelShape;
64
import org.jspecify.annotations.Nullable;
65
import org.slf4j.Logger;
66
67
public class StructureTemplate {
68
	private static final Logger LOGGER = LogUtils.getLogger();
69
	public static final String PALETTE_TAG = "palette";
70
	public static final String PALETTE_LIST_TAG = "palettes";
71
	public static final String ENTITIES_TAG = "entities";
72
	public static final String BLOCKS_TAG = "blocks";
73
	public static final String BLOCK_TAG_POS = "pos";
74
	public static final String BLOCK_TAG_STATE = "state";
75
	public static final String BLOCK_TAG_NBT = "nbt";
76
	public static final String ENTITY_TAG_POS = "pos";
77
	public static final String ENTITY_TAG_BLOCKPOS = "blockPos";
78
	public static final String ENTITY_TAG_NBT = "nbt";
79
	public static final String SIZE_TAG = "size";
80
	private final List<StructureTemplate.Palette> palettes = Lists.newArrayList();
81
	private final List<StructureTemplate.StructureEntityInfo> entityInfoList = Lists.newArrayList();
82
	private Vec3i size = Vec3i.ZERO;
83
	private String author = "?";
84
85
	public Vec3i getSize() {
86
		return this.size;
87
	}
88
89
	public void setAuthor(final String author) {
90
		this.author = author;
91
	}
92
93
	public String getAuthor() {
94
		return this.author;
95
	}
96
97
	public void fillFromWorld(final Level level, final BlockPos position, final Vec3i size, final boolean inludeEntities, final List<Block> ignoreBlocks) {
98
		if (size.getX() >= 1 && size.getY() >= 1 && size.getZ() >= 1) {
99
			BlockPos corner2 = position.offset(size).offset(-1, -1, -1);
100
			List<StructureTemplate.StructureBlockInfo> fullBlockList = Lists.newArrayList();
101
			List<StructureTemplate.StructureBlockInfo> blockEntitiesList = Lists.newArrayList();
102
			List<StructureTemplate.StructureBlockInfo> otherBlocksList = Lists.newArrayList();
103
			BlockPos minCorner = new BlockPos(
104
				Math.min(position.getX(), corner2.getX()), Math.min(position.getY(), corner2.getY()), Math.min(position.getZ(), corner2.getZ())
105
			);
106
			BlockPos maxCorner = new BlockPos(
107
				Math.max(position.getX(), corner2.getX()), Math.max(position.getY(), corner2.getY()), Math.max(position.getZ(), corner2.getZ())
108
			);
109
			this.size = size;
110
111
			try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(LOGGER)) {
112
				level.findBlocksIn(minCorner, maxCorner).filterState(state -> !ignoreBlocks.contains(state.getBlock())).forEach((pos, state) -> {
113
					BlockPos relativePos = pos.subtract(minCorner);
114
					BlockEntity blockEntity = level.getBlockEntity(pos);
115
					StructureTemplate.StructureBlockInfo info;
116
					if (blockEntity != null) {
117
						TagValueOutput output = TagValueOutput.createWithContext(reporter, level.registryAccess());
118
						blockEntity.saveWithId(output);
119
						info = new StructureTemplate.StructureBlockInfo(relativePos, state, output.buildResult());
120
					} else {
121
						info = new StructureTemplate.StructureBlockInfo(relativePos, state, null);
122
					}
123
124
					addToLists(info, fullBlockList, blockEntitiesList, otherBlocksList);
125
				});
126
				List<StructureTemplate.StructureBlockInfo> blockInfoList = buildInfoList(fullBlockList, blockEntitiesList, otherBlocksList);
127
				this.palettes.clear();
128
				this.palettes.add(new StructureTemplate.Palette(blockInfoList));
129
				if (inludeEntities) {
130
					this.fillEntityList(level, minCorner, maxCorner, reporter);
131
				} else {
132
					this.entityInfoList.clear();
133
				}
134
			}
135
		}
136
	}
137
138
	private static void addToLists(
139
		final StructureTemplate.StructureBlockInfo info,
140
		final List<StructureTemplate.StructureBlockInfo> fullBlockList,
141
		final List<StructureTemplate.StructureBlockInfo> blockEntitiesList,
142
		final List<StructureTemplate.StructureBlockInfo> otherBlocksList
143
	) {
144
		if (info.nbt != null) {
145
			blockEntitiesList.add(info);
146
		} else if (!info.state.getBlock().hasDynamicShape() && info.state.isCollisionShapeFullBlock(EmptyBlockGetter.INSTANCE, BlockPos.ZERO)) {
147
			fullBlockList.add(info);
148
		} else {
149
			otherBlocksList.add(info);
150
		}
151
	}
152
153
	private static List<StructureTemplate.StructureBlockInfo> buildInfoList(
154
		final List<StructureTemplate.StructureBlockInfo> fullBlockList,
155
		final List<StructureTemplate.StructureBlockInfo> blockEntitiesList,
156
		final List<StructureTemplate.StructureBlockInfo> otherBlocksList
157
	) {
158
		Comparator<StructureTemplate.StructureBlockInfo> comparator = Comparator.<StructureTemplate.StructureBlockInfo>comparingInt(o -> o.pos.getY())
159
			.thenComparingInt(o -> o.pos.getX())
160
			.thenComparingInt(o -> o.pos.getZ());
161
		fullBlockList.sort(comparator);
162
		otherBlocksList.sort(comparator);
163
		blockEntitiesList.sort(comparator);
164
		List<StructureTemplate.StructureBlockInfo> blockInfoList = Lists.newArrayList();
165
		blockInfoList.addAll(fullBlockList);
166
		blockInfoList.addAll(otherBlocksList);
167
		blockInfoList.addAll(blockEntitiesList);
168
		return blockInfoList;
169
	}
170
171
	private void fillEntityList(final Level level, final BlockPos minCorner, final BlockPos maxCorner, final ProblemReporter reporter) {
172
		List<Entity> entities = level.getEntitiesOfClass(Entity.class, AABB.encapsulatingFullBlocks(minCorner, maxCorner), input -> !(input instanceof Player));
173
		this.entityInfoList.clear();
174
175
		for (Entity entity : entities) {
176
			Vec3 pos = new Vec3(entity.getX() - minCorner.getX(), entity.getY() - minCorner.getY(), entity.getZ() - minCorner.getZ());
177
			TagValueOutput output = TagValueOutput.createWithContext(reporter.forChild(entity.problemPath()), entity.registryAccess());
178
			entity.save(output);
179
			BlockPos blockPos;
180
			if (entity instanceof Painting painting) {
181
				blockPos = painting.getPos().subtract(minCorner);
182
			} else {
183
				blockPos = BlockPos.containing(pos);
184
			}
185
186
			this.entityInfoList.add(new StructureTemplate.StructureEntityInfo(pos, blockPos, output.buildResult().copy()));
187
		}
188
	}
189
190
	public List<StructureTemplate.StructureBlockInfo> filterBlocks(final BlockPos position, final StructurePlaceSettings settings, final Block block) {
191
		return this.filterBlocks(position, settings, block, true);
192
	}
193
194
	public List<StructureTemplate.JigsawBlockInfo> getJigsaws(final BlockPos position, final Rotation rotation) {
195
		if (this.palettes.isEmpty()) {
196
			return new ArrayList<>();
197
		}
198
199
		StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(rotation);
200
		List<StructureTemplate.JigsawBlockInfo> jigsaws = settings.getRandomPalette(this.palettes, position).jigsaws();
201
		List<StructureTemplate.JigsawBlockInfo> result = new ArrayList<>(jigsaws.size());
202
203
		for (StructureTemplate.JigsawBlockInfo jigsaw : jigsaws) {
204
			result.add(jigsaw.withInfo(calculateRelativePosition(settings, jigsaw.pos).offset(position), jigsaw.state.rotate(settings.getRotation())));
205
		}
206
207
		return result;
208
	}
209
210
	public ObjectArrayList<StructureTemplate.StructureBlockInfo> filterBlocks(
211
		final BlockPos position, final StructurePlaceSettings settings, final Block block, final boolean absolute
212
	) {
213
		ObjectArrayList<StructureTemplate.StructureBlockInfo> result = new ObjectArrayList<>();
214
		BoundingBox boundingBox = settings.getBoundingBox();
215
		if (this.palettes.isEmpty()) {
216
			return result;
217
		}
218
219
		for (StructureTemplate.StructureBlockInfo blockInfo : settings.getRandomPalette(this.palettes, position).blocks(block)) {
220
			BlockPos blockPos = absolute ? calculateRelativePosition(settings, blockInfo.pos).offset(position) : blockInfo.pos;
221
			if (boundingBox == null || boundingBox.isInside(blockPos)) {
222
				result.add(new StructureTemplate.StructureBlockInfo(blockPos, blockInfo.state.rotate(settings.getRotation()), blockInfo.nbt));
223
			}
224
		}
225
226
		return result;
227
	}
228
229
	public BlockPos calculateConnectedPosition(
230
		final StructurePlaceSettings settings1, final BlockPos connection1, final StructurePlaceSettings settings2, final BlockPos connection2
231
	) {
232
		BlockPos markerPos1 = calculateRelativePosition(settings1, connection1);
233
		BlockPos markerPos2 = calculateRelativePosition(settings2, connection2);
234
		return markerPos1.subtract(markerPos2);
235
	}
236
237
	public static BlockPos calculateRelativePosition(final StructurePlaceSettings settings, final BlockPos pos) {
238
		return transform(pos, settings.getMirror(), settings.getRotation(), settings.getRotationPivot());
239
	}
240
241
	public boolean placeInWorld(
242
		final ServerLevelAccessor level,
243
		final BlockPos position,
244
		final BlockPos referencePos,
245
		final StructurePlaceSettings settings,
246
		final RandomSource random,
247
		final @Block.UpdateFlags int updateMode
248
	) {
249
		if (this.palettes.isEmpty()) {
250
			return false;
251
		}
252
253
		List<StructureTemplate.StructureBlockInfo> blockInfoList = settings.getRandomPalette(this.palettes, position).blocks();
254
		if ((!blockInfoList.isEmpty() || !settings.isIgnoreEntities() && !this.entityInfoList.isEmpty())
255
			&& this.size.getX() >= 1
256
			&& this.size.getY() >= 1
257
			&& this.size.getZ() >= 1) {
258
			BoundingBox boundingBox = settings.getBoundingBox();
259
			List<BlockPos> toFill = Lists.newArrayListWithCapacity(settings.shouldApplyWaterlogging() ? blockInfoList.size() : 0);
260
			List<BlockPos> lockedFluids = Lists.newArrayListWithCapacity(settings.shouldApplyWaterlogging() ? blockInfoList.size() : 0);
261
			List<Pair<BlockPos, CompoundTag>> placed = Lists.newArrayListWithCapacity(blockInfoList.size());
262
			int minX = Integer.MAX_VALUE;
263
			int minY = Integer.MAX_VALUE;
264
			int minZ = Integer.MAX_VALUE;
265
			int maxX = Integer.MIN_VALUE;
266
			int maxY = Integer.MIN_VALUE;
267
			int maxZ = Integer.MIN_VALUE;
268
			List<StructureTemplate.StructureBlockInfo> processedBlockInfoList = processBlockInfos(level, position, referencePos, settings, blockInfoList);
269
270
			try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(LOGGER)) {
271
				for (StructureTemplate.StructureBlockInfo blockInfo : processedBlockInfoList) {
272
					BlockPos blockPos = blockInfo.pos;
273
					if (boundingBox == null || boundingBox.isInside(blockPos)) {
274
						FluidState previousFluidState = settings.shouldApplyWaterlogging() ? level.getFluidState(blockPos) : null;
275
						BlockState state = blockInfo.state.mirror(settings.getMirror()).rotate(settings.getRotation());
276
						if (blockInfo.nbt != null) {
277
							level.setBlock(blockPos, Blocks.BARRIER.defaultBlockState(), 820);
278
						}
279
280
						if (level.setBlock(blockPos, state, updateMode)) {
281
							minX = Math.min(minX, blockPos.getX());
282
							minY = Math.min(minY, blockPos.getY());
283
							minZ = Math.min(minZ, blockPos.getZ());
284
							maxX = Math.max(maxX, blockPos.getX());
285
							maxY = Math.max(maxY, blockPos.getY());
286
							maxZ = Math.max(maxZ, blockPos.getZ());
287
							placed.add(Pair.of(blockPos, blockInfo.nbt));
288
							if (blockInfo.nbt != null) {
289
								BlockEntity blockEntity = level.getBlockEntity(blockPos);
290
								if (blockEntity != null) {
291
									if (!SharedConstants.DEBUG_STRUCTURE_EDIT_MODE && blockEntity instanceof RandomizableContainer) {
292
										blockInfo.nbt.putLong("LootTableSeed", random.nextLong());
293
									}
294
295
									blockEntity.loadWithComponents(TagValueInput.create(reporter.forChild(blockEntity.problemPath()), level.registryAccess(), blockInfo.nbt));
296
								}
297
							}
298
299
							if (previousFluidState != null) {
300
								if (state.getFluidState().isSource()) {
301
									lockedFluids.add(blockPos);
302
								} else if (state.getBlock() instanceof LiquidBlockContainer) {
303
									((LiquidBlockContainer)state.getBlock()).placeLiquid(level, blockPos, state, previousFluidState);
304
									if (!previousFluidState.isSource()) {
305
										toFill.add(blockPos);
306
									}
307
								}
308
							}
309
						}
310
					}
311
				}
312
313
				boolean filled = true;
314
				Direction[] directions = new Direction[]{Direction.UP, Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST};
315
316
				while (filled && !toFill.isEmpty()) {
317
					filled = false;
318
					Iterator<BlockPos> iterator = toFill.iterator();
319
320
					while (iterator.hasNext()) {
321
						BlockPos pos = iterator.next();
322
						FluidState toPlace = level.getFluidState(pos);
323
324
						for (int i = 0; i < directions.length && !toPlace.isSource(); i++) {
325
							BlockPos neighborPos = pos.relative(directions[i]);
326
							FluidState neighbor = level.getFluidState(neighborPos);
327
							if (neighbor.isSource() && !lockedFluids.contains(neighborPos)) {
328
								toPlace = neighbor;
329
							}
330
						}
331
332
						if (toPlace.isSource()) {
333
							BlockState state = level.getBlockState(pos);
334
							if (state.getBlock() instanceof LiquidBlockContainer liquidBlockContainer) {
335
								liquidBlockContainer.placeLiquid(level, pos, state, toPlace);
336
								filled = true;
337
								iterator.remove();
338
							}
339
						}
340
					}
341
				}
342
343
				if (minX <= maxX) {
344
					if (!settings.getKnownShape()) {
345
						DiscreteVoxelShape shape = new BitSetDiscreteVoxelShape(maxX - minX + 1, maxY - minY + 1, maxZ - minZ + 1);
346
						int startX = minX;
347
						int startY = minY;
348
						int startZ = minZ;
349
350
						for (Pair<BlockPos, CompoundTag> blockInfo : placed) {
351
							BlockPos blockPos = blockInfo.getFirst();
352
							shape.fill(blockPos.getX() - startX, blockPos.getY() - startY, blockPos.getZ() - startZ);
353
						}
354
355
						updateShapeAtEdge(level, updateMode, shape, startX, startY, startZ);
356
					}
357
358
					for (Pair<BlockPos, CompoundTag> blockInfo : placed) {
359
						BlockPos blockPos = blockInfo.getFirst();
360
						if (!settings.getKnownShape()) {
361
							BlockState state = level.getBlockState(blockPos);
362
							BlockState newState = Block.updateFromNeighbourShapes(state, level, blockPos);
363
							if (state != newState) {
364
								level.setBlock(blockPos, newState, updateMode & -2 | 16);
365
							}
366
367
							level.updateNeighborsAt(blockPos, newState.getBlock());
368
						}
369
370
						if (blockInfo.getSecond() != null) {
371
							BlockEntity blockEntity = level.getBlockEntity(blockPos);
372
							if (blockEntity != null) {
373
								blockEntity.setChanged();
374
							}
375
						}
376
					}
377
				}
378
379
				if (!settings.isIgnoreEntities()) {
380
					this.placeEntities(
381
						level, position, settings.getMirror(), settings.getRotation(), settings.getRotationPivot(), boundingBox, settings.shouldFinalizeEntities(), reporter
382
					);
383
				}
384
			}
385
386
			return true;
387
		} else {
388
			return false;
389
		}
390
	}
391
392
	public static void updateShapeAtEdge(final LevelAccessor level, final @Block.UpdateFlags int updateMode, final DiscreteVoxelShape shape, final BlockPos pos) {
393
		updateShapeAtEdge(level, updateMode, shape, pos.getX(), pos.getY(), pos.getZ());
394
	}
395
396
	public static void updateShapeAtEdge(
397
		final LevelAccessor level, final @Block.UpdateFlags int updateMode, final DiscreteVoxelShape shape, final int startX, final int startY, final int startZ
398
	) {
399
		BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
400
		BlockPos.MutableBlockPos neighborPos = new BlockPos.MutableBlockPos();
401
		shape.forAllFaces((direction, x, y, z) -> {
402
			pos.set(startX + x, startY + y, startZ + z);
403
			neighborPos.setWithOffset(pos, direction);
404
			BlockState state = level.getBlockState(pos);
405
			BlockState neighborState = level.getBlockState(neighborPos);
406
			BlockState newState = state.updateShape(level, level, pos, direction, neighborPos, neighborState, level.getRandom());
407
			if (state != newState) {
408
				level.setBlock(pos, newState, updateMode & -2);
409
			}
410
411
			BlockState newNeighborState = neighborState.updateShape(level, level, neighborPos, direction.getOpposite(), pos, newState, level.getRandom());
412
			if (neighborState != newNeighborState) {
413
				level.setBlock(neighborPos, newNeighborState, updateMode & -2);
414
			}
415
		});
416
	}
417
418
	public static List<StructureTemplate.StructureBlockInfo> processBlockInfos(
419
		final ServerLevelAccessor level,
420
		final BlockPos position,
421
		final BlockPos referencePos,
422
		final StructurePlaceSettings settings,
423
		final List<StructureTemplate.StructureBlockInfo> blockInfoList
424
	) {
425
		List<StructureTemplate.StructureBlockInfo> originalBlockInfoList = new ArrayList<>();
426
		List<StructureTemplate.StructureBlockInfo> processedBlockInfoList = new ArrayList<>();
427
		boolean processOnlyInCurrentChunk = true;
428
429
		for (StructureProcessor processor : settings.getProcessors()) {
430
			if (processor.evaluatesEntirePieceState()) {
431
				processOnlyInCurrentChunk = false;
432
				break;
433
			}
434
		}
435
436
		BoundingBox chunkBb = settings.getBoundingBox();
437
438
		for (StructureTemplate.StructureBlockInfo blockInfo : blockInfoList) {
439
			BlockPos blockPos = calculateRelativePosition(settings, blockInfo.pos).offset(position);
440
			if (!processOnlyInCurrentChunk || chunkBb == null || chunkBb.isInside(blockPos)) {
441
				StructureTemplate.StructureBlockInfo processedBlockInfo = new StructureTemplate.StructureBlockInfo(
442
					blockPos, blockInfo.state, blockInfo.nbt != null ? blockInfo.nbt.copy() : null
443
				);
444
				Iterator<StructureProcessor> iterator = settings.getProcessors().iterator();
445
446
				while (processedBlockInfo != null && iterator.hasNext()) {
447
					processedBlockInfo = iterator.next().processBlock(level, position, referencePos, blockInfo.pos, processedBlockInfo, settings);
448
				}
449
450
				if (processedBlockInfo != null) {
451
					processedBlockInfoList.add(processedBlockInfo);
452
					originalBlockInfoList.add(blockInfo);
453
				}
454
			}
455
		}
456
457
		for (StructureProcessor processor : settings.getProcessors()) {
458
			processedBlockInfoList = processor.finalizeProcessing(level, position, referencePos, originalBlockInfoList, processedBlockInfoList, settings);
459
		}
460
461
		return processedBlockInfoList;
462
	}
463
464
	private void placeEntities(
465
		final ServerLevelAccessor level,
466
		final BlockPos position,
467
		final Mirror mirror,
468
		final Rotation rotation,
469
		final BlockPos pivot,
470
		final @Nullable BoundingBox boundingBox,
471
		final boolean finalizeEntities,
472
		final ProblemReporter problemReporter
473
	) {
474
		for (StructureTemplate.StructureEntityInfo entityInfo : this.entityInfoList) {
475
			BlockPos blockPos = transform(entityInfo.blockPos, mirror, rotation, pivot).offset(position);
476
			if (boundingBox == null || boundingBox.isInside(blockPos)) {
477
				CompoundTag tag = entityInfo.nbt.copy();
478
				Vec3 relativePos = transform(entityInfo.pos, mirror, rotation, pivot);
479
				Vec3 pos = relativePos.add(position.getX(), position.getY(), position.getZ());
480
				ListTag posTag = new ListTag();
481
				posTag.add(DoubleTag.valueOf(pos.x));
482
				posTag.add(DoubleTag.valueOf(pos.y));
483
				posTag.add(DoubleTag.valueOf(pos.z));
484
				tag.put("Pos", posTag);
485
				tag.remove("UUID");
486
				if (tag.contains("block_pos")) {
487
					tag.store("block_pos", BlockPos.CODEC, blockPos);
488
				}
489
490
				createEntityIgnoreException(problemReporter, level, tag).ifPresent(entity -> {
491
					float yRot = entity.rotate(rotation);
492
					yRot += entity.mirror(mirror) - entity.getYRot();
493
					entity.snapTo(pos.x, pos.y, pos.z, yRot, entity.getXRot());
494
					entity.setYBodyRot(yRot);
495
					entity.setYHeadRot(yRot);
496
					if (finalizeEntities && entity instanceof Mob mob) {
497
						mob.finalizeSpawn(level, level.getCurrentDifficultyAt(BlockPos.containing(pos)), EntitySpawnReason.STRUCTURE, null);
498
					}
499
500
					level.addFreshEntityWithPassengers(entity);
501
				});
502
			}
503
		}
504
	}
505
506
	private static Optional<Entity> createEntityIgnoreException(final ProblemReporter reporter, final ServerLevelAccessor level, final CompoundTag tag) {
507
		try {
508
			return EntityType.create(
509
				TagValueInput.create(reporter, level.registryAccess(), tag), level.getLevel(), new EntitySpawnRequest(EntitySpawnReason.STRUCTURE, false)
510
			);
511
		} catch (Exception ignored) {
512
			return Optional.empty();
513
		}
514
	}
515
516
	public Vec3i getSize(final Rotation rotation) {
517
		return switch (rotation) {
518
			case COUNTERCLOCKWISE_90, CLOCKWISE_90 -> new Vec3i(this.size.getZ(), this.size.getY(), this.size.getX());
519
			default -> this.size;
520
		};
521
	}
522
523
	public static BlockPos transform(final BlockPos pos, final Mirror mirror, final Rotation rotation, final BlockPos pivot) {
524
		int x = pos.getX();
525
		int y = pos.getY();
526
		int z = pos.getZ();
527
		boolean wasMirrored = true;
528
		switch (mirror) {
529
			case LEFT_RIGHT:
530
				z = -z;
531
				break;
532
			case FRONT_BACK:
533
				x = -x;
534
				break;
535
			default:
536
				wasMirrored = false;
537
		}
538
539
		int pivotX = pivot.getX();
540
		int pivotZ = pivot.getZ();
541
542
		return switch (rotation) {
543
			case COUNTERCLOCKWISE_90 -> new BlockPos(pivotX - pivotZ + z, y, pivotX + pivotZ - x);
544
			case CLOCKWISE_90 -> new BlockPos(pivotX + pivotZ - z, y, pivotZ - pivotX + x);
545
			case CLOCKWISE_180 -> new BlockPos(pivotX + pivotX - x, y, pivotZ + pivotZ - z);
546
			default -> wasMirrored ? new BlockPos(x, y, z) : pos;
547
		};
548
	}
549
550
	public static Vec3 transform(final Vec3 pos, final Mirror mirror, final Rotation rotation, final BlockPos pivot) {
551
		double x = pos.x;
552
		double y = pos.y;
553
		double z = pos.z;
554
		boolean wasMirrored = true;
555
		switch (mirror) {
556
			case LEFT_RIGHT:
557
				z = 1.0 - z;
558
				break;
559
			case FRONT_BACK:
560
				x = 1.0 - x;
561
				break;
562
			default:
563
				wasMirrored = false;
564
		}
565
566
		int pivotX = pivot.getX();
567
		int pivotZ = pivot.getZ();
568
569
		return switch (rotation) {
570
			case COUNTERCLOCKWISE_90 -> new Vec3(pivotX - pivotZ + z, y, pivotX + pivotZ + 1 - x);
571
			case CLOCKWISE_90 -> new Vec3(pivotX + pivotZ + 1 - z, y, pivotZ - pivotX + x);
572
			case CLOCKWISE_180 -> new Vec3(pivotX + pivotX + 1 - x, y, pivotZ + pivotZ + 1 - z);
573
			default -> wasMirrored ? new Vec3(x, y, z) : pos;
574
		};
575
	}
576
577
	public BlockPos getZeroPositionWithTransform(final BlockPos zeroPos, final Mirror mirror, final Rotation rotation) {
578
		return getZeroPositionWithTransform(zeroPos, mirror, rotation, this.getSize().getX(), this.getSize().getZ());
579
	}
580
581
	public static BlockPos getZeroPositionWithTransform(final BlockPos zeroPos, final Mirror mirror, final Rotation rotation, int sizeX, int sizeZ) {
582
		sizeX--;
583
		sizeZ--;
584
		int mirrorDeltaX = mirror == Mirror.FRONT_BACK ? sizeX : 0;
585
		int mirrorDeltaZ = mirror == Mirror.LEFT_RIGHT ? sizeZ : 0;
586
587
		return switch (rotation) {
588
			case COUNTERCLOCKWISE_90 -> zeroPos.offset(mirrorDeltaZ, 0, sizeX - mirrorDeltaX);
589
			case CLOCKWISE_90 -> zeroPos.offset(sizeZ - mirrorDeltaZ, 0, mirrorDeltaX);
590
			case CLOCKWISE_180 -> zeroPos.offset(sizeX - mirrorDeltaX, 0, sizeZ - mirrorDeltaZ);
591
			case NONE -> zeroPos.offset(mirrorDeltaX, 0, mirrorDeltaZ);
592
		};
593
	}
594
595
	public BoundingBox getBoundingBox(final StructurePlaceSettings settings, final BlockPos position) {
596
		return this.getBoundingBox(position, settings.getRotation(), settings.getRotationPivot(), settings.getMirror());
597
	}
598
599
	public BoundingBox getBoundingBox(final BlockPos position, final Rotation rotation, final BlockPos pivot, final Mirror mirror) {
600
		return getBoundingBox(position, rotation, pivot, mirror, this.size);
601
	}
602
603
	@VisibleForTesting
604
	protected static BoundingBox getBoundingBox(final BlockPos position, final Rotation rotation, final BlockPos pivot, final Mirror mirror, final Vec3i size) {
605
		Vec3i delta = size.offset(-1, -1, -1);
606
		BlockPos corner1 = transform(BlockPos.ZERO, mirror, rotation, pivot);
607
		BlockPos corner2 = transform(BlockPos.ZERO.offset(delta), mirror, rotation, pivot);
608
		return BoundingBox.fromCorners(corner1, corner2).move(position);
609
	}
610
611
	public CompoundTag save(final CompoundTag tag) {
612
		if (this.palettes.isEmpty()) {
613
			tag.put("blocks", new ListTag());
614
			tag.put("palette", new ListTag());
615
		} else {
616
			List<StructureTemplate.SimplePalette> palettes = Lists.newArrayList();
617
			StructureTemplate.SimplePalette mainPalette = new StructureTemplate.SimplePalette();
618
			palettes.add(mainPalette);
619
620
			for (int p = 1; p < this.palettes.size(); p++) {
621
				palettes.add(new StructureTemplate.SimplePalette());
622
			}
623
624
			ListTag blockList = new ListTag();
625
			List<StructureTemplate.StructureBlockInfo> mainPaletteBlocks = this.palettes.get(0).blocks();
626
627
			for (int i = 0; i < mainPaletteBlocks.size(); i++) {
628
				StructureTemplate.StructureBlockInfo blockInfo = mainPaletteBlocks.get(i);
629
				CompoundTag blockTag = new CompoundTag();
630
				blockTag.put("pos", this.newIntegerList(blockInfo.pos.getX(), blockInfo.pos.getY(), blockInfo.pos.getZ()));
631
				int id = mainPalette.idFor(blockInfo.state);
632
				blockTag.putInt("state", id);
633
				if (blockInfo.nbt != null) {
634
					blockTag.put("nbt", blockInfo.nbt);
635
				}
636
637
				blockList.add(blockTag);
638
639
				for (int p = 1; p < this.palettes.size(); p++) {
640
					StructureTemplate.SimplePalette palette = palettes.get(p);
641
					palette.addMapping(this.palettes.get(p).blocks().get(i).state, id);
642
				}
643
			}
644
645
			tag.put("blocks", blockList);
646
			if (palettes.size() == 1) {
647
				ListTag paletteList = new ListTag();
648
649
				for (BlockState state : mainPalette) {
650
					paletteList.add(NbtUtils.writeBlockState(state));
651
				}
652
653
				tag.put("palette", paletteList);
654
			} else {
655
				ListTag paletteListList = new ListTag();
656
657
				for (StructureTemplate.SimplePalette palette : palettes) {
658
					ListTag paletteList = new ListTag();
659
660
					for (BlockState state : palette) {
661
						paletteList.add(NbtUtils.writeBlockState(state));
662
					}
663
664
					paletteListList.add(paletteList);
665
				}
666
667
				tag.put("palettes", paletteListList);
668
			}
669
		}
670
671
		ListTag entityList = new ListTag();
672
673
		for (StructureTemplate.StructureEntityInfo entityInfo : this.entityInfoList) {
674
			CompoundTag entityTag = new CompoundTag();
675
			entityTag.put("pos", this.newDoubleList(entityInfo.pos.x, entityInfo.pos.y, entityInfo.pos.z));
676
			entityTag.put("blockPos", this.newIntegerList(entityInfo.blockPos.getX(), entityInfo.blockPos.getY(), entityInfo.blockPos.getZ()));
677
			if (entityInfo.nbt != null) {
678
				entityTag.put("nbt", entityInfo.nbt);
679
			}
680
681
			entityList.add(entityTag);
682
		}
683
684
		tag.put("entities", entityList);
685
		tag.put("size", this.newIntegerList(this.size.getX(), this.size.getY(), this.size.getZ()));
686
		return NbtUtils.addCurrentDataVersion(tag);
687
	}
688
689
	public void load(final HolderGetter<Block> blockLookup, final CompoundTag tag) {
690
		this.palettes.clear();
691
		this.entityInfoList.clear();
692
		ListTag sizeTag = tag.getListOrEmpty("size");
693
		this.size = new Vec3i(sizeTag.getIntOr(0, 0), sizeTag.getIntOr(1, 0), sizeTag.getIntOr(2, 0));
694
		ListTag blockList = tag.getListOrEmpty("blocks");
695
		Optional<ListTag> paletteListList = tag.getList("palettes");
696
		if (paletteListList.isPresent()) {
697
			for (int p = 0; p < paletteListList.get().size(); p++) {
698
				this.loadPalette(blockLookup, paletteListList.get().getListOrEmpty(p), blockList);
699
			}
700
		} else {
701
			this.loadPalette(blockLookup, tag.getListOrEmpty("palette"), blockList);
702
		}
703
704
		tag.getListOrEmpty("entities").compoundStream().forEach(entityTag -> {
705
			ListTag posTag = entityTag.getListOrEmpty("pos");
706
			Vec3 pos = new Vec3(posTag.getDoubleOr(0, 0.0), posTag.getDoubleOr(1, 0.0), posTag.getDoubleOr(2, 0.0));
707
			ListTag blockPosTag = entityTag.getListOrEmpty("blockPos");
708
			BlockPos blockPos = new BlockPos(blockPosTag.getIntOr(0, 0), blockPosTag.getIntOr(1, 0), blockPosTag.getIntOr(2, 0));
709
			entityTag.getCompound("nbt").ifPresent(nbt -> this.entityInfoList.add(new StructureTemplate.StructureEntityInfo(pos, blockPos, nbt)));
710
		});
711
	}
712
713
	private void loadPalette(final HolderGetter<Block> blockLookup, final ListTag paletteList, final ListTag blockList) {
714
		StructureTemplate.SimplePalette palette = new StructureTemplate.SimplePalette();
715
716
		for (int i = 0; i < paletteList.size(); i++) {
717
			palette.addMapping(NbtUtils.readBlockState(blockLookup, paletteList.getCompoundOrEmpty(i)), i);
718
		}
719
720
		List<StructureTemplate.StructureBlockInfo> fullBlockList = Lists.newArrayList();
721
		List<StructureTemplate.StructureBlockInfo> blockEntitiesList = Lists.newArrayList();
722
		List<StructureTemplate.StructureBlockInfo> otherBlocksList = Lists.newArrayList();
723
		blockList.compoundStream().forEach(blockTag -> {
724
			ListTag posTag = blockTag.getListOrEmpty("pos");
725
			BlockPos pos = new BlockPos(posTag.getIntOr(0, 0), posTag.getIntOr(1, 0), posTag.getIntOr(2, 0));
726
			BlockState state = palette.stateFor(blockTag.getIntOr("state", 0));
727
			CompoundTag nbt = blockTag.getCompound("nbt").orElse(null);
728
			StructureTemplate.StructureBlockInfo info = new StructureTemplate.StructureBlockInfo(pos, state, nbt);
729
			addToLists(info, fullBlockList, blockEntitiesList, otherBlocksList);
730
		});
731
		List<StructureTemplate.StructureBlockInfo> blockInfoList = buildInfoList(fullBlockList, blockEntitiesList, otherBlocksList);
732
		this.palettes.add(new StructureTemplate.Palette(blockInfoList));
733
	}
734
735
	private ListTag newIntegerList(final int... values) {
736
		ListTag res = new ListTag();
737
738
		for (int value : values) {
739
			res.add(IntTag.valueOf(value));
740
		}
741
742
		return res;
743
	}
744
745
	private ListTag newDoubleList(final double... values) {
746
		ListTag res = new ListTag();
747
748
		for (double value : values) {
749
			res.add(DoubleTag.valueOf(value));
750
		}
751
752
		return res;
753
	}
754
755
	public static JigsawBlockEntity.JointType getJointType(final CompoundTag nbt, final BlockState state) {
756
		return nbt.read("joint", JigsawBlockEntity.JointType.CODEC).orElseGet(() -> getDefaultJointType(state));
757
	}
758
759
	public static JigsawBlockEntity.JointType getDefaultJointType(final BlockState state) {
760
		return JigsawBlock.getFrontFacing(state).getAxis().isHorizontal() ? JigsawBlockEntity.JointType.ALIGNED : JigsawBlockEntity.JointType.ROLLABLE;
761
	}
762
763
	public record JigsawBlockInfo(
764
		BlockPos pos,
765
		BlockState state,
766
		JigsawBlockEntity.JointType jointType,
767
		@Nullable Identifier name,
768
		ResourceKey<StructureTemplatePool> pool,
769
		Identifier target,
770
		int placementPriority,
771
		int selectionPriority
772
	) {
773
		public static StructureTemplate.JigsawBlockInfo parse(final StructureTemplate.StructureBlockInfo info) {
774
			CompoundTag nbt = Objects.requireNonNull(info.nbt(), () -> info + " nbt was null");
775
			return new StructureTemplate.JigsawBlockInfo(
776
				info.pos(),
777
				info.state(),
778
				StructureTemplate.getJointType(nbt, info.state()),
779
				nbt.read("name", Identifier.CODEC).orElse(JigsawBlockEntity.EMPTY_ID),
780
				nbt.read("pool", JigsawBlockEntity.POOL_CODEC).orElse(Pools.EMPTY),
781
				nbt.read("target", Identifier.CODEC).orElse(JigsawBlockEntity.EMPTY_ID),
782
				nbt.getIntOr("placement_priority", 0),
783
				nbt.getIntOr("selection_priority", 0)
784
			);
785
		}
786
787
		@Override
788
		public String toString() {
789
			return String.format(
790
				Locale.ROOT,
791
				"<JigsawBlockInfo | %s | %s | name: %s | pool: %s | target: %s | placement: %d | selection: %d>",
792
				this.pos,
793
				this.state,
794
				this.name,
795
				this.pool.identifier(),
796
				this.target,
797
				this.placementPriority,
798
				this.selectionPriority
799
			);
800
		}
801
802
		public StructureTemplate.JigsawBlockInfo withInfo(final BlockPos pos, final BlockState state) {
803
			return new StructureTemplate.JigsawBlockInfo(pos, state, this.jointType, this.name, this.pool, this.target, this.placementPriority, this.selectionPriority);
804
		}
805
	}
806
807
	public static final class Palette {
808
		private final List<StructureTemplate.StructureBlockInfo> blocks;
809
		private final Map<Block, List<StructureTemplate.StructureBlockInfo>> cache = Maps.newHashMap();
810
		private @Nullable List<StructureTemplate.JigsawBlockInfo> cachedJigsaws;
811
812
		private Palette(final List<StructureTemplate.StructureBlockInfo> blocks) {
813
			this.blocks = blocks;
814
		}
815
816
		public List<StructureTemplate.JigsawBlockInfo> jigsaws() {
817
			if (this.cachedJigsaws == null) {
818
				this.cachedJigsaws = this.blocks(Blocks.JIGSAW).stream().map(StructureTemplate.JigsawBlockInfo::parse).toList();
819
			}
820
821
			return this.cachedJigsaws;
822
		}
823
824
		public List<StructureTemplate.StructureBlockInfo> blocks() {
825
			return this.blocks;
826
		}
827
828
		public List<StructureTemplate.StructureBlockInfo> blocks(final Block filter) {
829
			return this.cache.computeIfAbsent(filter, block -> this.blocks.stream().filter(b -> b.state.is(block)).collect(Collectors.toList()));
830
		}
831
	}
832
833
	private static class SimplePalette implements Iterable<BlockState> {
834
		public static final BlockState DEFAULT_BLOCK_STATE = Blocks.AIR.defaultBlockState();
835
		private final IdMapper<BlockState> ids = new IdMapper<>(16);
836
		private int lastId;
837
838
		public int idFor(final BlockState state) {
839
			int id = this.ids.getId(state);
840
			if (id == -1) {
841
				id = this.lastId++;
842
				this.ids.addMapping(state, id);
843
			}
844
845
			return id;
846
		}
847
848
		public @Nullable BlockState stateFor(final int index) {
849
			BlockState blockState = this.ids.byId(index);
850
			return blockState == null ? DEFAULT_BLOCK_STATE : blockState;
851
		}
852
853
		@Override
854
		public Iterator<BlockState> iterator() {
855
			return this.ids.iterator();
856
		}
857
858
		public void addMapping(final BlockState state, final int id) {
859
			this.ids.addMapping(state, id);
860
		}
861
	}
862
863
	public record StructureBlockInfo(BlockPos pos, BlockState state, @Nullable CompoundTag nbt) {
864
		@Override
865
		public String toString() {
866
			return String.format(Locale.ROOT, "<StructureBlockInfo | %s | %s | %s>", this.pos, this.state, this.nbt);
867
		}
868
	}
869
870
	public static class StructureEntityInfo {
871
		public final Vec3 pos;
872
		public final BlockPos blockPos;
873
		public final CompoundTag nbt;
874
875
		public StructureEntityInfo(final Vec3 pos, final BlockPos blockPos, final CompoundTag nbt) {
876
			this.pos = pos;
877
			this.blockPos = blockPos;
878
			this.nbt = nbt;
879
		}
880
	}
881
}
882

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