StateDefinition .java

net.minecraft.world.level.block.state.StateDefinition (class): members: getPossibleStates, propertiesByName, EMPTY_NEIGHBORS, StateCollection, EMPTY_KEYS.

net.minecraft.world.level.block.stateclass276 linescommonextends StateHolder<O10.7 KB

API Surface (10)

ImmutableList<S> getPossibleStates()
S any()
MapCodec<S> propertiesCodec()
O getOwner()
Collection<Property<?>> getProperties()
String toString()
boolean isSingletonState()
StateDefinition.Builder<O, S> add(final Property<?>... properties)
StateDefinition<O, S> create(final Function<O, S> defaultState, final StateDefinition.Factory<O, S> factory)
S[][] fillNeighborsForState(final Property<?>[] propertyKeys, final List<Comparable<?>> propertyValues)

Fields & Constants (11)

NAME_PATTERN
EMPTY_VALUES
EMPTY_KEYS
EMPTY_NEIGHBORS
owner
propertiesByName
states
propertiesCodec
factory
defaultState
name

String literals (8)

"block"
"properties"
" has invalidly named property: "
" attempted use property "
" with <= 1 possible values"
" has property: "
" with invalidly named value: "
" has duplicate property: "

Code Graph: Dependencies (2)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

StateDefinition.java276 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.block.state;
2
3
import com.google.common.base.MoreObjects;
4
import com.google.common.collect.ImmutableList;
5
import com.google.common.collect.ImmutableSortedMap;
6
import com.google.common.collect.Iterables;
7
import com.google.common.collect.Lists;
8
import com.google.common.collect.Maps;
9
import com.mojang.datafixers.util.Pair;
10
import com.mojang.serialization.Codec;
11
import com.mojang.serialization.MapCodec;
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.Objects;
18
import java.util.Map.Entry;
19
import java.util.function.Function;
20
import java.util.function.Supplier;
21
import java.util.regex.Pattern;
22
import java.util.stream.Collectors;
23
import net.minecraft.world.level.block.state.properties.Property;
24
import org.jspecify.annotations.Nullable;
25
26
public class StateDefinition<O, S extends StateHolder<O, S>> {
27
	private static final Pattern NAME_PATTERN = Pattern.compile("^[a-z0-9_]+$");
28
	private static final Comparable<?>[] EMPTY_VALUES = new Comparable[0];
29
	private static final Property<?>[] EMPTY_KEYS = new Property[0];
30
	private static final StateHolder<?, ?>[][] EMPTY_NEIGHBORS = new StateHolder[0][];
31
	private final O owner;
32
	private final ImmutableSortedMap<String, Property<?>> propertiesByName;
33
	private final ImmutableList<S> states;
34
	private final MapCodec<S> propertiesCodec;
35
36
	protected StateDefinition(
37
		final Function<O, S> defaultState, final O owner, final StateDefinition.Factory<O, S> factory, final Map<String, Property<?>> properties
38
	) {
39
		this.owner = owner;
40
		int propertyCount = properties.size();
41
		if (propertyCount == 0) {
42
			this.propertiesByName = ImmutableSortedMap.of();
43
			this.propertiesCodec = createCodec(owner, defaultState, this.propertiesByName);
44
			this.states = createSingletonState(owner, factory);
45
		} else {
46
			this.propertiesByName = ImmutableSortedMap.copyOf(properties);
47
			this.propertiesCodec = createCodec(owner, defaultState, this.propertiesByName);
48
			if (propertyCount == 1) {
49
				this.states = createSinglePropertyStates(owner, factory, this.propertiesByName);
50
			} else {
51
				this.states = createMultiPropertyStates(owner, factory, this.propertiesByName);
52
			}
53
		}
54
	}
55
56
	private static <O, S extends StateHolder<O, S>> MapCodec<S> createCodec(
57
		final O owner, final Function<O, S> defaultState, final Map<String, Property<?>> propertiesByName
58
	) {
59
		Supplier<S> defaultSupplier = () -> defaultState.apply(owner);
60
		MapCodec<S> codec = MapCodec.unit(defaultSupplier);
61
62
		for (Entry<String, Property<?>> entry : propertiesByName.entrySet()) {
63
			codec = appendPropertyCodec(codec, defaultSupplier, entry.getKey(), entry.getValue());
64
		}
65
66
		return codec;
67
	}
68
69
	private static <O, S extends StateHolder<O, S>> ImmutableList<S> createSingletonState(final O owner, final StateDefinition.Factory<O, S> factory) {
70
		S singletonState = (S)factory.create(owner, EMPTY_KEYS, EMPTY_VALUES);
71
		singletonState.initializeNeighbors((S[][])emptyNeighbors());
72
		return ImmutableList.of(singletonState);
73
	}
74
75
	private static <O, S extends StateHolder<O, S>> ImmutableList<S> createSinglePropertyStates(
76
		final O owner, final StateDefinition.Factory<O, S> factory, final Map<String, Property<?>> propertiesByName
77
	) {
78
		return createSinglePropertyStates(owner, factory, Iterables.getOnlyElement(propertiesByName.values()));
79
	}
80
81
	private static <O, S extends StateHolder<O, S>, T extends Comparable<T>> ImmutableList<S> createSinglePropertyStates(
82
		final O owner, final StateDefinition.Factory<O, S> factory, final Property<T> property
83
	) {
84
		Property<?>[] propertyKeys = new Property[]{property};
85
		List<T> propertyValues = property.getPossibleValues();
86
		int valueCount = propertyValues.size();
87
		ImmutableList.Builder<S> states = ImmutableList.builderWithExpectedSize(valueCount);
88
		S[] propertyNeighbours = (S[])(new StateHolder[valueCount]);
89
		S[][] neighbours = (S[][])(new StateHolder[][]{propertyNeighbours});
90
91
		for (int i = 0; i < valueCount; i++) {
92
			T propertyValue = (T)propertyValues.get(i);
93
			assert property.getInternalIndex(propertyValue) == i;
94
			S blockState = (S)factory.create(owner, propertyKeys, new Comparable[]{propertyValue});
95
			states.add(blockState);
96
			propertyNeighbours[i] = blockState;
97
			blockState.initializeNeighbors(neighbours);
98
		}
99
100
		return states.build();
101
	}
102
103
	private static <O, S extends StateHolder<O, S>> ImmutableList<S> createMultiPropertyStates(
104
		final O owner, final StateDefinition.Factory<O, S> factory, final Map<String, Property<?>> propertiesByName
105
	) {
106
		Property<?>[] propertyKeys = propertiesByName.values().toArray(EMPTY_KEYS);
107
		List<List<? extends Comparable<?>>> allPropertyValues = new ArrayList<>(propertyKeys.length);
108
109
		for (Property<?> property : propertyKeys) {
110
			allPropertyValues.add((List<? extends Comparable<?>>)property.getPossibleValues());
111
		}
112
113
		List<List<Comparable<?>>> stateValues = Lists.cartesianProduct(allPropertyValues);
114
		Map<List<Comparable<?>>, S> statesByValues = new HashMap<>();
115
		ImmutableList.Builder<S> states = ImmutableList.builderWithExpectedSize(stateValues.size());
116
117
		for (List<Comparable<?>> values : stateValues) {
118
			List<Comparable<?>> valuesCopy = List.copyOf(values);
119
			S blockState = (S)factory.create(owner, propertyKeys, valuesCopy.toArray(EMPTY_VALUES));
120
			statesByValues.put(valuesCopy, blockState);
121
			states.add(blockState);
122
		}
123
124
		StateDefinition.StateCollection<S> stateCollection = new StateDefinition.StateCollection<>(statesByValues, new HashMap<>());
125
		statesByValues.forEach((valuesx, state) -> state.initializeNeighbors(stateCollection.fillNeighborsForState(propertyKeys, valuesx)));
126
		return states.build();
127
	}
128
129
	private static <S extends StateHolder<?, ?>> S[][] emptyNeighbors() {
130
		return (S[][])EMPTY_NEIGHBORS;
131
	}
132
133
	private static <S extends StateHolder<?, S>, T extends Comparable<T>> MapCodec<S> appendPropertyCodec(
134
		final MapCodec<S> codec, final Supplier<S> defaultSupplier, final String name, final Property<T> property
135
	) {
136
		return Codec.mapPair(codec, property.valueCodec().fieldOf(name).orElseGet(var0 -> {}, () -> property.value(defaultSupplier.get())))
137
			.xmap(pair -> pair.getFirst().setValue(property, pair.getSecond().value()), state -> Pair.of((S)state, property.value(state)));
138
	}
139
140
	public ImmutableList<S> getPossibleStates() {
141
		return this.states;
142
	}
143
144
	public S any() {
145
		return this.states.getFirst();
146
	}
147
148
	public MapCodec<S> propertiesCodec() {
149
		return this.propertiesCodec;
150
	}
151
152
	public O getOwner() {
153
		return this.owner;
154
	}
155
156
	public Collection<Property<?>> getProperties() {
157
		return this.propertiesByName.values();
158
	}
159
160
	@Override
161
	public String toString() {
162
		return MoreObjects.toStringHelper(this)
163
			.add("block", this.owner)
164
			.add("properties", this.propertiesByName.values().stream().map(Property::getName).collect(Collectors.toList()))
165
			.toString();
166
	}
167
168
	public @Nullable Property<?> getProperty(final String name) {
169
		return this.propertiesByName.get(name);
170
	}
171
172
	public boolean isSingletonState() {
173
		return this.propertiesByName.isEmpty();
174
	}
175
176
	public static class Builder<O, S extends StateHolder<O, S>> {
177
		private final O owner;
178
		private final Map<String, Property<?>> properties = Maps.newHashMap();
179
180
		public Builder(final O owner) {
181
			this.owner = owner;
182
		}
183
184
		public StateDefinition.Builder<O, S> add(final Property<?>... properties) {
185
			for (Property<?> property : properties) {
186
				this.validateProperty(property);
187
				this.properties.put(property.getName(), property);
188
			}
189
190
			return this;
191
		}
192
193
		private <T extends Comparable<T>> void validateProperty(final Property<T> property) {
194
			String name = property.getName();
195
			if (!StateDefinition.NAME_PATTERN.matcher(name).matches()) {
196
				throw new IllegalArgumentException(this.owner + " has invalidly named property: " + name);
197
			}
198
199
			Collection<T> values = property.getPossibleValues();
200
			if (values.size() <= 1) {
201
				throw new IllegalArgumentException(this.owner + " attempted use property " + name + " with <= 1 possible values");
202
			}
203
204
			for (T comparable : values) {
205
				String valueName = property.getName(comparable);
206
				if (!StateDefinition.NAME_PATTERN.matcher(valueName).matches()) {
207
					throw new IllegalArgumentException(this.owner + " has property: " + name + " with invalidly named value: " + valueName);
208
				}
209
			}
210
211
			if (this.properties.containsKey(name)) {
212
				throw new IllegalArgumentException(this.owner + " has duplicate property: " + name);
213
			}
214
		}
215
216
		public StateDefinition<O, S> create(final Function<O, S> defaultState, final StateDefinition.Factory<O, S> factory) {
217
			return new StateDefinition<>(defaultState, this.owner, factory, this.properties);
218
		}
219
	}
220
221
	public interface Factory<O, S> {
222
		S create(O type, Property<?>[] propertyKeys, Comparable<?>[] propertyValues);
223
	}
224
225
	record StateCollection<S extends StateHolder<?, ?>>(Map<List<Comparable<?>>, S> statesByValues, Map<List<Comparable<?>>, S[]> statesByPivotCache) {
226
		public S[][] fillNeighborsForState(final Property<?>[] propertyKeys, final List<Comparable<?>> propertyValues) {
227
			S[][] neighbors = (S[][])(new StateHolder[propertyKeys.length][]);
228
			List<Comparable<?>> valuesKey = new ArrayList<>(propertyValues);
229
230
			for (int i = 0; i < propertyKeys.length; i++) {
231
				neighbors[i] = this.fillStatesForPivot(valuesKey, propertyKeys[i], i);
232
			}
233
234
			return neighbors;
235
		}
236
237
		private <T extends Comparable<T>> S[] fillStatesForPivot(final List<Comparable<?>> valuesKey, final Property<T> pivot, final int pivotIndex) {
238
			Comparable<?> ownPivotValue = valuesKey.set(pivotIndex, StateDefinition.StateCollection.Wildcard.INSTANCE);
239
240
			try {
241
				S[] cachedResult = (S[])((StateHolder[])this.statesByPivotCache.get(valuesKey));
242
				if (cachedResult != null) {
243
					return cachedResult;
244
				}
245
246
				S[] neighbourStatesForPivot = this.computeStatesForPivot(valuesKey, pivot, pivotIndex);
247
				valuesKey.set(pivotIndex, StateDefinition.StateCollection.Wildcard.INSTANCE);
248
				this.statesByPivotCache.put(List.copyOf(valuesKey), neighbourStatesForPivot);
249
				return neighbourStatesForPivot;
250
			} finally {
251
				valuesKey.set(pivotIndex, ownPivotValue);
252
			}
253
		}
254
255
		private <T extends Comparable<T>> S[] computeStatesForPivot(final List<Comparable<?>> valuesKey, final Property<T> pivot, final int pivotIndex) {
256
			List<T> possiblePivotValues = pivot.getPossibleValues();
257
			int pivotValuesCount = possiblePivotValues.size();
258
			S[] result = (S[])(new StateHolder[pivotValuesCount]);
259
260
			for (int pivotValueIndex = 0; pivotValueIndex < pivotValuesCount; pivotValueIndex++) {
261
				T possiblePivotValue = (T)possiblePivotValues.get(pivotValueIndex);
262
				assert pivot.getInternalIndex(possiblePivotValue) == pivotValueIndex;
263
				valuesKey.set(pivotIndex, possiblePivotValue);
264
				S neighbourState = Objects.requireNonNull(this.statesByValues.get(valuesKey));
265
				result[pivotValueIndex] = neighbourState;
266
			}
267
268
			return result;
269
		}
270
271
		private enum Wildcard {
272
			INSTANCE;
273
		}
274
	}
275
}
276

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