mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Add BlockState.parse, the inverse of key(), for hosts that read block states from JSON
This commit is contained in:
1 parent
c5a54558fa
commit
09df1af88e
2 files changed
+37
-1
No files matched your search
@@ -12,6 +12,10 @@ import java.util.stream.Collectors;
|
||||
* Resolve through BlockRegistry before writing. Custom-content IDs are allowed.
|
||||
*/
|
||||
public record BlockState(ResourceId material, Map<String, String> properties) {
|
||||
private static final String PROPERTIES_START = "[";
|
||||
private static final String PROPERTIES_END = "]";
|
||||
private static final String PROPERTY_SEPARATOR = ",";
|
||||
|
||||
public BlockState {
|
||||
Objects.requireNonNull(material, "material");
|
||||
var copy = new TreeMap<String, String>();
|
||||
@@ -27,6 +31,24 @@ public record BlockState(ResourceId material, Map<String, String> properties) {
|
||||
|
||||
public BlockState(String material) { this(ResourceId.parse(material), Map.of()); }
|
||||
|
||||
/** Reads what {@link #key()} writes: {@code minecraft:oak_log} or {@code minecraft:oak_log[axis=y]}. */
|
||||
public static BlockState parse(String key) {
|
||||
Objects.requireNonNull(key, "key");
|
||||
int open = key.indexOf(PROPERTIES_START);
|
||||
if (open < 0) return new BlockState(key);
|
||||
if (!key.endsWith(PROPERTIES_END)) throw new IllegalArgumentException("Unclosed block properties: " + key);
|
||||
var properties = new TreeMap<String, String>();
|
||||
var list = key.substring(open + 1, key.length() - 1);
|
||||
for (var property : list.isEmpty() ? new String[0] : list.split(PROPERTY_SEPARATOR, -1)) {
|
||||
int equals = property.indexOf('=');
|
||||
if (equals < 0) throw new IllegalArgumentException("Block property without value: " + property + " in " + key);
|
||||
if (properties.put(property.substring(0, equals), property.substring(equals + 1)) != null) {
|
||||
throw new IllegalArgumentException("Block property set twice: " + property + " in " + key);
|
||||
}
|
||||
}
|
||||
return new BlockState(ResourceId.parse(key.substring(0, open)), properties);
|
||||
}
|
||||
|
||||
public BlockState withProperty(String name, String value) {
|
||||
var changed = new TreeMap<>(properties);
|
||||
changed.put(name, value);
|
||||
@@ -38,6 +60,6 @@ public record BlockState(ResourceId material, Map<String, String> properties) {
|
||||
if (properties.isEmpty()) return material.toString();
|
||||
return material + properties.entrySet().stream()
|
||||
.map(entry -> entry.getKey() + "=" + entry.getValue())
|
||||
.collect(Collectors.joining(",", "[", "]"));
|
||||
.collect(Collectors.joining(PROPERTY_SEPARATOR, PROPERTIES_START, PROPERTIES_END));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user