Changes

1,433 bytes added ,  17:22, 23 November 2023
Line 267: Line 267:  
* BlockPlacer and BlockPlacerType
 
* BlockPlacer and BlockPlacerType
 
* ConfiguredDecorator and FeatureDecorator
 
* ConfiguredDecorator and FeatureDecorator
 +
 +
=== Registering MapCodecCodecs for Dispatch Subcodecs ===
 +
 +
When registering a subcodec to any dispatch codec registry, the registered subcodec should be an instance of MapCodecCodec, or the subcodec will be nested in its own object when serialized.
 +
 +
For example, suppose we register a single-field subcodec, where we use fieldOf-and-xmap to convert an int to our int-holding Thing:
 +
 +
<syntaxhighlight lang="java">
 +
public record Thing(int n){}
 +
public static Codec<Thing> CODEC = Codec.INT.fieldOf("n").codec().xmap(Thing::new, Thing::n);
 +
</syntaxhighlight>
 +
 +
This results in this json when serialized:
 +
 +
<syntaxhighlight lang="json">
 +
"some_thing":
 +
{
 +
"type": "ourmod:thing",
 +
"value": {
 +
"n": 5
 +
}
 +
}
 +
</syntaxhighlight>
 +
 +
This occurs because xmap does not produce a MapCodecCodec, and if this nested object is not desired, then our registered subcodec must be a MapCodecCodec.
 +
 +
However, fieldOf() produces a MapCodec, which has a codec() method, which does produce a MapCodecCodec. We can rearrange our codec builder, which then produces a cleaner json:
 +
 +
<syntaxhighlight lang="java">
 +
public static Codec<Thing> CODEC = Codec.INT // Primitive codec
 +
.fieldOf("n") // MapCodec
 +
.xmap(Thing::new, Thing::n) // MapCodec
 +
.codec(); // MapCodecCodec! That's what we want.
 +
</syntaxhighlight>
 +
 +
<syntaxhighlight lang="json">
 +
"some_thing":
 +
{
 +
"type": "ourmod:thing",
 +
"n": 5
 +
}
 +
</syntaxhighlight>
 +
 +
RecordCodecBuilder also produces MapCodecCodecs.
    
=External Links=
 
=External Links=
 
* [https://github.com/Mojang/DataFixerUpper/blob/master/src/main/java/com/mojang/serialization/Codec.java Codecs in Mojang's official public DataFixerUpper repository]
 
* [https://github.com/Mojang/DataFixerUpper/blob/master/src/main/java/com/mojang/serialization/Codec.java Codecs in Mojang's official public DataFixerUpper repository]
 
* [https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec.html#flatXmap-java.util.function.Function-java.util.function.Function- Unofficial Codec Javadocs]
 
* [https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec.html#flatXmap-java.util.function.Function-java.util.function.Function- Unofficial Codec Javadocs]
22

edits