Skip to content

Commit c17b56b

Browse files
TheMeinerLPMiniklooniam4722202468mudkipdevItsFelix5
committed
Update from Upstream (#68)
* Offer more control over LightingChunk invalidations (Minestom#2156) * Offer more control over LightingChunk invalidations * Respect freezeInvalidation on this other invalidate method * Rename to invalidateNeighborsSection and remove redundant null check * fix light invalidation issue * Fix Entity::getEffectLevel having two meanings when returning 0 (Minestom#2163) * add more command conditions * Add signum operator to Vec * Refactor lighting code, fix loaded chunks (Minestom#2164) * Switch to the new adventure domain (Minestom#2165) * fix: do not test block collision on entities without collision * Make PlayerProjectile extend Entity instead of LivingEntity * feat: initial conversion to adventure nbt. no tests, no anvil * chore: basic nbt reader/writer for protocol while waiting for adventure * feat: joinable server * fix: oops, health is before potion still * chore: rebase on adventure-nbt * feat: first version of a bunch of components * chore: delete all old metadata classes for now, may return compatibility later * chore: more components * chore: more components * chore: trying to fix nightmare loop * feat: functional components, but at what cost * chore: cleanup itemcomponenttype, update to datagen changes * feat: more components * feat: even more components (only 2 missing ones) * feat: first draft of cookies * feat: simplify sound events, fix update explosion packet * feat: generate RecipeType (for ids) * fix: do not send close inventory packet when opening a new inventory while one is open * feat: anvil reading, other minor fixes * feat: partial anvil writing, update tests (still many broken) * chore: 1.20.5, disable some failing tests to get a functional build * chore: cicd trigger * chore: update datagenerator * fix: anvil not loading locations properly * fix: particle packet reorder * fix: do not allow writing air in declare recipes packet (added ItemStack.STRICT_NETWORK_TYPE to represent this) * feat: initial ArgumentItemStack reader, other minor fixes * fix: light test and update eye height in view direction test * chore: cleanup anvil test * fix: dont oom reading item component, stub banner pattern component * fix: circular init :| * fix: correctly handle eating potions, time eating using ticks, default to correct drink/eat time from component, send damage event on living entity damage * fix: do not convert optchat metadata to chat * chore: rebase, add stack size 99 test case * chore: another stack size test * feat: block predicate impl & some more tests * feat: initial anvilloader writer implementation * fix: correctly read declared recipes * chore: generalize ItemComponent to DataComponent (item component defs are still in ItemComponent) * fix: update from lighting fix 35 rebase * chore: add PlayerAnvilInputEvent, other minor tweaks from self review * fix: sync position after sending first chunk * chore: start testing components, fix valueless components * chore: allow chunk subclasses to override heightmap generation * feat: first pass of standardizing dynamic registries * feat: add DynamicRegistry.Key and reference it instead of the underlying type. add wolf variant meta field * chore: cleanup & some component impl utility methods * chore: depend on published version of data, not local * chore: minor tweaks * chore: cleanup networkbuffer additions * chore: missing entity metas & extract shooter to abstractwindchargemeta * fix: correct handling of known packs exchange * chore: merge datacomponentmap and datacomponentpatch to simplify api. Preemptively diff with material prototype when constructing itemstack * chore: more tests for components * chore: one more * fix: setTimeUpdate transition from duration to ticks, renamed to avoid ambiguation with setTimeRate (Minestom#2067) * feat: LivingEntity fire overhaul (Minestom#2122) * feat: LivingEntity fire overhaul * chore: missed method change * feat: world border overhaul, turned into a record and handled by the instance (Minestom#2062) * feat: world border overhaul, turned into a record and handled by instance * chore: replace WorldBorder#defaultBorder() with a DEFAULT_BORDER constant * Pathfinding 1.20.5 (Minestom#2153) * pathfinding * mutablepoint fix in player * feat: cya later jitpack * chore: remove some weird internal/experimental annotations * Item usage duration (Minestom#2128) Fix build error Move item usage completed to a different event Add a way to check if the item usage has completed, or is aborted by the player Only process animation when the item use time is not instant Update javadoc Re-add Player#isEating Remove deprecated Player#callItemUpdateStateEvent Allow specifying item usage duration inside PlayerUseItemEvent * fix: fixes from merging Minestom#2128 * feat: improve particle api * feat: generate particle data names automatically * chore: make all impls records + inner classes of Particle * chore: minor cleanup, block display meta to use Block directly * fix: default zero use item time * Move static Entity lookup maps to EntityTracker (Minestom#2167) * Move static Entity lookup maps to EntityTracker * Specific method for changeUuid to keep thread-safety * Fix bug from not recording position on register * Exception on duplicate IDs in the EntityTracker * Oops, expected stateCondition to behave like assert * Didn't mean to make Entity::remove(boolean) public * More descriptive EntityView::register error * Warn when attempting to move untracked entity * chore: delete `Entity#setUuid` and `AsyncPlayerPreLoginEvent#setUuid` * chore: delete a deprecated Audience#sendMessage variant * chore: javadocs and remove experimental pose update flag * fix: fixes from rug pull * fix: tag escape * fix: inventory rebase fixes * Fix Attribute Read/Write due to initialization shenanagins (Minestom#2174) * Only consider online players for unregisterInstance (Minestom#2171) * Add new navigator generator & follower * Include ourself as a viewer when sending SWING_MAIN_ARM animation (Minestom#2173) * Include ourself as a viewer when sending SWING_MAIN_ARM animation * Added API annotations * fix: re-add deprecated Audience#sendMessage variant which was actually required * Fix ITEM_NAME component translation in SetSlotPacket (Minestom#2176) * Fix ITEM_NAME component translation in SetSlotPacket * Add test for item stack translation when automatic component translation is enabled * Fix the NBT representation of Unit (Minestom#2177) * Call UuidProvider in async (Minestom#2181) Co-authored-by: Spliterash <me@spliterash.ru> * [RE] Update PlayerChangeHeldSlotEvent.java (Minestom#2179) * Update PlayerChangeHeldSlotEvent.java Slight changes in the docs since they were mis-leading.. Took me a while to realise what was wrong in my algorithm * Update src/main/java/net/minestom/server/event/player/PlayerChangeHeldSlotEvent.java Co-authored-by: Matz Hilven <48355802+MatzHilven@users.noreply.github.com> --------- Co-authored-by: Matz Hilven <48355802+MatzHilven@users.noreply.github.com> * fix: correctly account for global biome palette * fix: incorrect region metatable offset when writing * Add Instance::getPlayerByUuid because for convenience (Minestom#2190) * feat: hello, 1.21 * feat: new packets, new registries except stubbed out enchantments, other minor changes * chore: 1.21-pre2 * chore: start on enchantments * chore: start on enchant effect components * chore: protocol set * chore: start on effect types * feat: mostly functional enchants, needs cleanup * feat: add some ItemStack convenience methods * feat: minor improvements, 1.21 release * fix inventory packet for global translator * fix full light data is not sent (Minestom#2191) * fix full light data is not sent * remove fullLightCache * Add feature flags to AsyncPlayerConfigurationEvent * fix player health update animation (Minestom#2183) * fix projectile remove * Update Player.java (Minestom#2195) * Update Player.java * Update PlayerConnection.java * fix: deserialize `extra` correctly in component serializer * Fix add transaction * Fix events not triggering for bows, crossbows, etc. (Minestom#2199) * Fix item update for bow, crossbow, shield, trident, spyglass, goat horn, brush * fix: inverted vanilla exclusion * fix: nbt byte for `sections[].Y` in anvil chunk data (fixes Minestom#2207) * Drop eventnode listener ref on invalidate (Minestom#2212) * Fixed bug in LargeFramebuffer#preparePacket(int,int,int) (Minestom#2213) * Fix LivingEntity Damage Event Packet (Minestom#2209) * fix: correctly disconnect player if resource pack is not applied successfully (for required resource pack) * Ability to teleport player without teleport confirm (Minestom#2222) * optional teleport confirm * rename flag to shouldConfirm * oops, this change is no longer needed * fix last line formatting * fix: preserve handler in block placement rule neighbor updates * fix: do not overwrite default movement speed attribute * Revert "fix: do not overwrite default movement speed attribute" This reverts commit 66dc936. * fix: update sprinting movement speed modifier serverside to keep synced with client state * fix: concurrent region file creation * fix: adding an existing viewer to a scoreboard kicks them (Minestom#2231) * fix: DustColorTransition packet reading/writing (Minestom#2236) * fix: DustColorTransition packet reading/writing * chore: fix tests * Add Player#getCurrentItemUseTime (Minestom#2235) * Add Player#getCurrentItemUseTime * Use player ticks as reference instead of world age * Fix infinite recursion. (Minestom#2230) * chore: int flags potion constructor (Minestom#2238) * chore: send keepalive packets immediately, simplify PacketProcessor#process (Minestom#2218) * chore: send keepalive packets immediately, simplify PacketProcessor#process * chore: make latency volatile * Autogenerate Feature Flags (Minestom#2201) * Autogenerate Feature Flags (Won't work until MinestomDataGen 1.21-rev2 is released with datagen changes.) * Rewrite feature flag auto-generation, add example in demo. * Update data gen * Remove dead code and fix access modifier on FeatureFlagImpl * feat: Improvements to AttributeInstance API (Minestom#2221) * feat: method to compute the value of an AttributeInstance with a given base instead of its stored one, add return values to AttributeInstance#removeModifier and AttributeInstance#addModifier * chore: getValueWithBase -> applyModifiers * feat: Acquirable, ThreadDispatcher usage improvements (Minestom#2237) * feat: fewer casts needed when working with Acquirable, ThreadDispatcher now usable with non-Entity tickables, AcquirableSource for synchronizing items added to dispatcher * chore: rename AcquirableSource#getAcquirable -> AcquirableSource#acquirable, re-add getAcquirable to Entity with old signature, deprecate it * fix: incorrect camel case in item component nbt (fixes Minestom#2233) * Add material setter in builder * feat: ShapeImpl#collisionBoundingBoxes, ShapeImpl#occlusionBoundingBoxes + documentation (Minestom#2248) * Automatically update an entity's attributes when changing equipment (Minestom#2228) * Automatically update an entity's attributes when changing equipment * fix merge conflict * Update attributes for players when their items change * Add attribute tests * chore: add AlphaColor, convert Color to class, fix entity_effect particle (Minestom#2240) * chore: add AlphaColor, convert Color to class, fix entity_effect particle * chore: add `Particle.EntityEffect#withColor(RGBLike)`, `Color#withAlpha` --------- Co-authored-by: mworzala <mattheworzala@gmail.com> * fix: AttributeInstance#addModifier not refreshing cachedValue for new modifier values (Minestom#2234) * fix blunder * fix: use equals check for modifier difference when adding --------- Co-authored-by: mworzala <mattheworzala@gmail.com> * chore: add doc about kicking player during config * chore: enforce and document notnull chunk loader, add noop impl * Fix chunk lighting optimization (Minestom#2244) * Fix chunk lighting optimization * Apply requested changes * Add a few useful methods to Direction (Minestom#2254) * Add Block::original so it's easier to compare by block type (Minestom#2255) * Add Block::original so it's easier to compare by block type * Requested changes * fix: geyser keepalive incompatibility * Fix NullPointer when changing equipment before checking attributes * get back jmh/jcstress * Add getAndSetTag to TagWritable * Remove Instance/PlayerUtils * Move all flags to ServerFlag * MetadataHolder (Minestom#2263) * Move entity meta map to MetadataHolder * Fix biome sounds + particles (Minestom#2265) * fix biome sounds + particles * Fix tests * Call ItemUpdateStateEvent before clearing item use (Minestom#2258) * feat: allow changing the number of threads used by the server process ThreadDispatcher (Minestom#2268) * fix: optional world pos in lodestone tracker item component (fixes Minestom#2270) * chore: add cursor position to `PlayerBlockPlaceEvent` * fix: node followers using the speed attribute base value instead of value + modifiers * feat: thread safety for AttributeInstance (Minestom#2297) * feat: thread safety for AttributeInstance * fix: refreshCachedValue now takes the new baseValue rather than reading from the field internally * Remove cursor items from individual inventories (Minestom#2294) * Remove cursor items from individual inventories * Remove unused method and re-add but deprecate old cursor methods * Fix links and remove unused import * feat: add ability to clear modifiers from an AttributeInstance (Minestom#2296) * feat: add ability to clear modifiers from an AttributeInstance, as well as get all AttributeInstances from LivingEntity * chore: getAttributeInstances -> getAttributes, protect certain modifiers from being cleared by AttributeInstance#clearModifiers * fix: call refreshCachedValue properly * Make loyalty level a byte (Minestom#2300) * Remove static biome registry, simplify unit generation * fix attribute packet (Minestom#2305) * chore: bump data gen to fix light[level=0] emission value * chore: Remove a bunch of Experimental annotations * Direct writer for Adventure components (Minestom#2306) * feat: direct writer for adventure components * chore: tests and fixes to score & translatable * chore: explicitly use nbt serializer for reading so the dependency is obvious * fix: lower case click/hover action types * fix: Round up total sectors in region file * fix: send attribute base value not computed. * Apply microtus patches 1-20 (cherry picked from commit ab0874c) * Fix build grade * Add missing adventure nbt lib * Add missing dependencies * Remove old biome, banner, shield, particle, attribute system * Fix forward data generator * Disable stress tester for compile reasons * Remove old network stack * Remove no longer exists api form player * Fix forward bstats * Fix forward server flags * Fix forward terminal color converter * Fix forward inventory tests * Fix forward frog meta test * Update files like in microtus main (cherry picked from commit d3ad5af) * Apply better workflow (cherry picked from commit ccf63cb) * Move miss landed classes after patching source (cherry picked from commit 2f2dec2) * Fix workflows for java 21 (cherry picked from commit b501f93) * Fix workflows for java 21 (cherry picked from commit f35341a) * [Chore] Update gradle to 8.7 (cherry picked from commit cf0f73c) * [Chore] Remove preview feature (cherry picked from commit ab6a351) * [Bugfix] Improve version string for bstats (cherry picked from commit d63c883) * Update README.md (cherry picked from commit 9fd02fd) * Update snapshot and release version (cherry picked from commit 18cfbad) * [Chore] Replace e.printstacktrace with exception manager call or logger (cherry picked from commit c61f7c5) * Create CNAME (cherry picked from commit 0a8f6dd) * Bump snapshot version (#31) (cherry picked from commit 0c32b88) * Update build.gradle.kts (cherry picked from commit 4023e8a) * Improve license usage (cherry picked from commit e7298d4) * Improve license usage (cherry picked from commit 9574b21) * [#30] Release 1.4.0 (cherry picked from commit fee81f4) * [#30] Re-Release 1.4.1 (cherry picked from commit 994ecce) * Go back to snapshot (cherry picked from commit 57b6303) * Ignore bstats file (cherry picked from commit e327192) * [#34] Better Notification System (#35) * [#34] Implement new notification system with tests * [#34] Update demo to use new notification system * [#34] Add deprecation text to old notification system * [#34] Improve javadocs and rename builder implementation * [#34] Improve javadocs and fix tests * [#34] Remove empty lines * [#34] Add package description (cherry picked from commit 29ec3fe) * Add bom (cherry picked from commit 7c69238) * Improve bom (cherry picked from commit f9b2374) * Remove java version from bom (cherry picked from commit 772203b) * Change bom deployment (cherry picked from commit f418602) * Change bom deployment (cherry picked from commit 37576d2) * [Feature] Improved Testing Lib (#42) * Deprecate env test * Improve environment * Create new environment annotation * Use new environment annotation (cherry picked from commit 3d93b94) * Add missing dependencies (cherry picked from commit e295f99) * Add missing dependencies (cherry picked from commit 7765729) * Improve release workflow (cherry picked from commit c298674) * Improve release workflow (cherry picked from commit da01e8a) * Bump version (cherry picked from commit e715ad9) * Update dependency com.google.code.gson:gson to v2.11.0 (cherry picked from commit c7095d6) * Update dependency org.mockito:mockito-core to v5.12.0 (cherry picked from commit 77ccf9f) * Update actions/cache action to v4 (cherry picked from commit 38ad8aa) * Update gradle/wrapper-validation-action action to v3 (cherry picked from commit ad84891) * Update kotlin monorepo to v2 (cherry picked from commit af9be49) * [Chore] Update gradle to version 8.8 (#58) (cherry picked from commit 9373005) * Update CODEOWNERS (cherry picked from commit 026aa27) * Update CODEOWNERS (cherry picked from commit 5be4573) * Update README.md (cherry picked from commit c90b7d5) * Bump version to 1.5.0 * Add missing import * Add support for older as 1.21 minecraft worlds * Update BOM dependencies * Remove no longer needed classes * Fix forward compile issues --------- Co-authored-by: Samuel <pifnpafnpouf@gmail.com> Co-authored-by: iam4722202468 <aceparent@gmail.com> Co-authored-by: mudkipdev <mudkip@mudkip.dev> Co-authored-by: iam <iam4722202468@users.noreply.github.com> Co-authored-by: felix <60808107+ItsFelix5@users.noreply.github.com> Co-authored-by: mworzala <mattheworzala@gmail.com> Co-authored-by: FluxCapacitor2 <31071265+FluxCapacitor2@users.noreply.github.com> Co-authored-by: DeidaraMC <117625071+DeidaraMC@users.noreply.github.com> Co-authored-by: TogAr2 <59421074+togar2@users.noreply.github.com> Co-authored-by: DeidaraMC <DeidaraJuice@gmail.com> Co-authored-by: GreatWyrm <alecmusante@gmail.com> Co-authored-by: kubbi <nicoladelaroche@gmail.com> Co-authored-by: MelonHell <53826469+MelonHell@users.noreply.github.com> Co-authored-by: Spliterash <me@spliterash.ru> Co-authored-by: unjoinable <135444615+unjoinable@users.noreply.github.com> Co-authored-by: Matz Hilven <48355802+MatzHilven@users.noreply.github.com> Co-authored-by: bea4dev <bea0224@outlook.jp> Co-authored-by: bea4dev <34712108+bea4dev@users.noreply.github.com> Co-authored-by: Not Flamgop <76978462+flopgop@users.noreply.github.com> Co-authored-by: ItsAnnie <crazysqueak@gmail.com> Co-authored-by: ItsAnnie <ctrlaltcs@gmail.com> Co-authored-by: Steank <dnd.initiative.tracker@gmail.com> Co-authored-by: themode <themode@outlook.fr> Co-authored-by: Am Gone <67794767+Am-Gone@users.noreply.github.com> Co-authored-by: AmGone_ <hygon806@gmail.com> Co-authored-by: GoldenStack <goldenfire64yt@gmail.com> Co-authored-by: Matt Worzala <35708499+mworzala@users.noreply.github.com> Co-authored-by: Aeltumn <daniel@goossens.ch> Co-authored-by: OneLiteFeather <seelenretterin@onelitefeather.net> Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Steffen Wonning <steffenwx@gmail.com>
1 parent 998cfdb commit c17b56b

File tree

7 files changed

+411
-1
lines changed

7 files changed

+411
-1
lines changed

code-generators/src/main/java/net/minestom/codegen/MinestomCodeGenerator.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,8 @@ protected static String toConstant(String namespace) {
4343
protected static String toConstant(String namespace) {
4444
return namespace.replace("minecraft:", "").toUpperCase(Locale.ROOT);
4545
}
46+
47+
protected static String toConstant(String namespace) {
48+
return namespace.replace("minecraft:", "").toUpperCase(Locale.ROOT);
49+
}
4650
}
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
package net.minestom.codegen.entity;
2+
3+
import com.google.gson.JsonArray;
4+
import com.google.gson.JsonElement;
5+
import com.google.gson.JsonObject;
6+
import com.squareup.javapoet.*;
7+
import net.minestom.codegen.MinestomCodeGenerator;
8+
import org.jetbrains.annotations.ApiStatus;
9+
import org.jetbrains.annotations.NotNull;
10+
import org.jetbrains.annotations.Nullable;
11+
import org.slf4j.Logger;
12+
import org.slf4j.LoggerFactory;
13+
import net.minestom.codegen.util.GenerationHelper;
14+
15+
import javax.lang.model.element.Modifier;
16+
import java.io.File;
17+
import java.io.InputStream;
18+
import java.io.InputStreamReader;
19+
import java.util.List;
20+
21+
import static net.minestom.codegen.util.GenerationHelper.*;
22+
23+
@ApiStatus.NonExtendable
24+
@ApiStatus.Internal
25+
public final class VillagerProfessionGenerator extends MinestomCodeGenerator {
26+
27+
private static final String VILLAGER_PROFESSION_DATE = "villagerProfessionData";
28+
private static final Logger LOGGER = LoggerFactory.getLogger(VillagerProfessionGenerator.class);
29+
private final InputStream villagerProfessionsFile;
30+
private final File outputFolder;
31+
32+
33+
public VillagerProfessionGenerator(@Nullable InputStream villagerProfessionsFile, @NotNull File outputFolder) {
34+
this.villagerProfessionsFile = villagerProfessionsFile;
35+
this.outputFolder = outputFolder;
36+
}
37+
38+
@Override
39+
public void generate() {
40+
if (villagerProfessionsFile == null) {
41+
LOGGER.error("Failed to find villager_professions.json.");
42+
LOGGER.error("Stopped code generation for villager professions.");
43+
return;
44+
}
45+
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
46+
LOGGER.error("Output folder for code generation does not exist and could not be created.");
47+
return;
48+
}
49+
// Important classes we use alot
50+
ClassName rawVillagerProfessionDataClassName = ClassName.get("net.minestom.server.raw_data", "RawVillagerProfessionData");
51+
52+
JsonArray villagerProfessions = GSON.fromJson(new InputStreamReader(villagerProfessionsFile), JsonArray.class);
53+
ClassName villagerProfessionClassName = ClassName.get("net.minestom.server.entity.metadata.villager", "VillagerProfession");
54+
55+
// Particle
56+
TypeSpec.Builder villagerProfessionClass = TypeSpec.classBuilder(villagerProfessionClassName)
57+
.addSuperinterface(KEYORI_ADVENTURE_KEY)
58+
.addModifiers(Modifier.PUBLIC).addJavadoc("AUTOGENERATED by " + getClass().getSimpleName());
59+
villagerProfessionClass.addField(
60+
FieldSpec.builder(NAMESPACE_ID_CLASS, "id")
61+
.addModifiers(Modifier.PRIVATE, Modifier.FINAL).addAnnotation(NotNull.class).build()
62+
);
63+
villagerProfessionClass.addField(
64+
FieldSpec.builder(rawVillagerProfessionDataClassName, VILLAGER_PROFESSION_DATE)
65+
.addModifiers(Modifier.PRIVATE, Modifier.VOLATILE)
66+
.addAnnotation(NotNull.class)
67+
.build()
68+
);
69+
villagerProfessionClass.addMethod(
70+
MethodSpec.constructorBuilder()
71+
.addParameter(ParameterSpec.builder(NAMESPACE_ID_CLASS, "id").addAnnotation(NotNull.class).build())
72+
.addParameter(ParameterSpec.builder(rawVillagerProfessionDataClassName, VILLAGER_PROFESSION_DATE).addAnnotation(NotNull.class).build())
73+
.addStatement(VARIABLE_SETTER, "id")
74+
.addStatement(VARIABLE_SETTER, VILLAGER_PROFESSION_DATE)
75+
.addModifiers(Modifier.PROTECTED)
76+
.build()
77+
);
78+
// Override key method (adventure)
79+
villagerProfessionClass.addMethod(GenerationHelper.ADVENTURE_KEY_METHOD);
80+
// getId method
81+
villagerProfessionClass.addMethod(GenerationHelper.ID_GETTER);
82+
// getVillagerProfessionData method
83+
villagerProfessionClass.addMethod(
84+
MethodSpec.methodBuilder("getVillagerProfessionData")
85+
.returns(rawVillagerProfessionDataClassName)
86+
.addAnnotation(NotNull.class)
87+
.addStatement("return this.villagerProfessionData")
88+
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
89+
.build()
90+
);
91+
// setVillagerProfessionData method
92+
villagerProfessionClass.addMethod(
93+
MethodSpec.methodBuilder("setVillagerProfessionData")
94+
.addParameter(ParameterSpec.builder(rawVillagerProfessionDataClassName, VILLAGER_PROFESSION_DATE).addAnnotation(NotNull.class).build())
95+
.addStatement("this.$L1 = $L1", VILLAGER_PROFESSION_DATE)
96+
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
97+
.build()
98+
);
99+
// getNumericalId
100+
villagerProfessionClass.addMethod(
101+
MethodSpec.methodBuilder("getNumericalId")
102+
.returns(TypeName.INT)
103+
.addStatement("return $T.VILLAGER_PROFESSION_REGISTRY.getId(this)", REGISTRY_CLASS)
104+
.addModifiers(Modifier.PUBLIC)
105+
.build()
106+
);
107+
// fromId Method
108+
villagerProfessionClass.addMethod(
109+
MethodSpec.methodBuilder("fromId")
110+
.returns(villagerProfessionClassName)
111+
.addAnnotation(Nullable.class)
112+
.addParameter(TypeName.INT, "id")
113+
.addStatement("return $T.VILLAGER_PROFESSION_REGISTRY.get((short) id)", REGISTRY_CLASS)
114+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
115+
.build()
116+
);
117+
// fromId Method
118+
villagerProfessionClass.addMethod(
119+
MethodSpec.methodBuilder("fromId")
120+
.returns(villagerProfessionClassName)
121+
.addAnnotation(NotNull.class)
122+
.addParameter(ADVENTURE_KEY, "id")
123+
.addStatement("return $T.VILLAGER_PROFESSION_REGISTRY.get(id)", REGISTRY_CLASS)
124+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
125+
.build()
126+
);
127+
// toString method
128+
villagerProfessionClass.addMethod(GenerationHelper.TO_STRING);
129+
// values method
130+
villagerProfessionClass.addMethod(
131+
MethodSpec.methodBuilder("values")
132+
.addAnnotation(NotNull.class)
133+
.returns(ParameterizedTypeName.get(ClassName.get(List.class), villagerProfessionClassName))
134+
.addStatement("return $T.VILLAGER_PROFESSION_REGISTRY.values()", REGISTRY_CLASS)
135+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
136+
.build()
137+
);
138+
CodeBlock.Builder staticBlock = CodeBlock.builder();
139+
// Use data
140+
for (JsonElement vp : villagerProfessions) {
141+
JsonObject villagerProfession = vp.getAsJsonObject();
142+
143+
String villagerProfessionName = villagerProfession.get("name").getAsString();
144+
JsonElement workSound = villagerProfession.get("workSound");
145+
if (workSound == null) {
146+
villagerProfessionClass.addField(
147+
FieldSpec.builder(
148+
villagerProfessionClassName,
149+
villagerProfessionName
150+
).initializer(
151+
"new $T($T.from($S), new $T(() -> null))",
152+
villagerProfessionClassName,
153+
NAMESPACE_ID_CLASS,
154+
villagerProfession.get("id").getAsString(),
155+
156+
rawVillagerProfessionDataClassName
157+
).addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).build()
158+
);
159+
} else {
160+
villagerProfessionClass.addField(
161+
FieldSpec.builder(
162+
villagerProfessionClassName,
163+
villagerProfessionName
164+
).initializer(
165+
"new $T($T.from($S), new $T(() -> $T.SOUND_EVENT_REGISTRY.get($S)))",
166+
villagerProfessionClassName,
167+
NAMESPACE_ID_CLASS,
168+
villagerProfession.get("id").getAsString(),
169+
170+
rawVillagerProfessionDataClassName,
171+
REGISTRY_CLASS,
172+
workSound.getAsString()
173+
).addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).build()
174+
);
175+
}
176+
177+
// Add to static init.
178+
staticBlock.addStatement("$T.VILLAGER_PROFESSION_REGISTRY.register($N)", REGISTRY_CLASS, villagerProfessionName);
179+
}
180+
181+
villagerProfessionClass.addStaticBlock(staticBlock.build());
182+
183+
// Write files to outputFolder
184+
writeFiles(
185+
List.of(
186+
JavaFile.builder("net.minestom.server.entity.metadata.villager", villagerProfessionClass.build())
187+
.indent(DEFAULT_INDENT)
188+
.skipJavaLangImports(true)
189+
.build()
190+
),
191+
outputFolder
192+
);
193+
}
194+
}
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
package net.minestom.codegen.entity;
2+
3+
import com.google.gson.JsonArray;
4+
import com.google.gson.JsonElement;
5+
import com.google.gson.JsonObject;
6+
import com.squareup.javapoet.*;
7+
import net.minestom.codegen.MinestomCodeGenerator;
8+
import net.minestom.codegen.util.GenerationHelper;
9+
import org.jetbrains.annotations.ApiStatus;
10+
import org.jetbrains.annotations.NotNull;
11+
import org.jetbrains.annotations.Nullable;
12+
import org.slf4j.Logger;
13+
import org.slf4j.LoggerFactory;
14+
15+
import javax.lang.model.element.Modifier;
16+
import java.io.File;
17+
import java.io.InputStream;
18+
import java.io.InputStreamReader;
19+
import java.util.List;
20+
21+
import static net.minestom.codegen.util.GenerationHelper.ADVENTURE_KEY;
22+
import static net.minestom.codegen.util.GenerationHelper.TO_STRING;
23+
24+
@ApiStatus.NonExtendable
25+
@ApiStatus.Internal
26+
public final class VillagerTypeGenerator extends MinestomCodeGenerator {
27+
private static final Logger LOGGER = LoggerFactory.getLogger(VillagerTypeGenerator.class);
28+
private final InputStream villagerTypesFile;
29+
private final File outputFolder;
30+
31+
public VillagerTypeGenerator(@Nullable InputStream villagerTypesFile, @NotNull File outputFolder) {
32+
this.villagerTypesFile = villagerTypesFile;
33+
this.outputFolder = outputFolder;
34+
}
35+
36+
@Override
37+
public void generate() {
38+
if (villagerTypesFile == null) {
39+
LOGGER.error("Failed to find villager_types.json.");
40+
LOGGER.error("Stopped code generation for villager types.");
41+
return;
42+
}
43+
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
44+
LOGGER.error("Output folder for code generation does not exist and could not be created.");
45+
return;
46+
}
47+
// Important classes we use alot
48+
JsonArray villagerTypes = GSON.fromJson(new InputStreamReader(villagerTypesFile), JsonArray.class);
49+
ClassName villagerTypeClassName = ClassName.get("net.minestom.server.entity.metadata.villager", "VillagerType");
50+
51+
// Particle
52+
TypeSpec.Builder villagerTypeClass = TypeSpec.classBuilder(villagerTypeClassName)
53+
.addSuperinterface(KEYORI_ADVENTURE_KEY)
54+
.addModifiers(Modifier.PUBLIC).addJavadoc("AUTOGENERATED by " + getClass().getSimpleName());
55+
villagerTypeClass.addField(
56+
FieldSpec.builder(NAMESPACE_ID_CLASS, "id")
57+
.addModifiers(Modifier.PRIVATE, Modifier.FINAL).addAnnotation(NotNull.class).build()
58+
);
59+
villagerTypeClass.addMethod(
60+
MethodSpec.constructorBuilder()
61+
.addParameter(ParameterSpec.builder(NAMESPACE_ID_CLASS, "id").addAnnotation(NotNull.class).build())
62+
.addStatement("this.id = id")
63+
.addModifiers(Modifier.PROTECTED)
64+
.build()
65+
);
66+
// Override key method (adventure)
67+
villagerTypeClass.addMethod(GenerationHelper.ID_GETTER);
68+
// getId method
69+
villagerTypeClass.addMethod(
70+
MethodSpec.methodBuilder("getId")
71+
.returns(NAMESPACE_ID_CLASS)
72+
.addAnnotation(NotNull.class)
73+
.addStatement("return this.id")
74+
.addModifiers(Modifier.PUBLIC)
75+
.build()
76+
);
77+
// getNumericalId
78+
villagerTypeClass.addMethod(
79+
MethodSpec.methodBuilder("getNumericalId")
80+
.returns(TypeName.INT)
81+
.addStatement("return $T.VILLAGER_TYPE_REGISTRY.getId(this)", REGISTRY_CLASS)
82+
.addModifiers(Modifier.PUBLIC)
83+
.build()
84+
);
85+
// fromId Method
86+
villagerTypeClass.addMethod(
87+
MethodSpec.methodBuilder("fromId")
88+
.returns(villagerTypeClassName)
89+
.addAnnotation(Nullable.class)
90+
.addParameter(TypeName.INT, "id")
91+
.addStatement("return $T.VILLAGER_TYPE_REGISTRY.get((short) id)", REGISTRY_CLASS)
92+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
93+
.build()
94+
);
95+
// fromId Method
96+
villagerTypeClass.addMethod(
97+
MethodSpec.methodBuilder("fromId")
98+
.returns(villagerTypeClassName)
99+
.addAnnotation(NotNull.class)
100+
.addParameter(ADVENTURE_KEY, "id")
101+
.addStatement("return $T.VILLAGER_TYPE_REGISTRY.get(id)", REGISTRY_CLASS)
102+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
103+
.build()
104+
);
105+
// toString method
106+
villagerTypeClass.addMethod(TO_STRING);
107+
// values method
108+
villagerTypeClass.addMethod(
109+
MethodSpec.methodBuilder("values")
110+
.addAnnotation(NotNull.class)
111+
.returns(ParameterizedTypeName.get(ClassName.get(List.class), villagerTypeClassName))
112+
.addStatement("return $T.VILLAGER_TYPE_REGISTRY.values()", REGISTRY_CLASS)
113+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
114+
.build()
115+
);
116+
CodeBlock.Builder staticBlock = CodeBlock.builder();
117+
// Use data
118+
for (JsonElement vp : villagerTypes) {
119+
JsonObject villagerProfession = vp.getAsJsonObject();
120+
121+
String villagerProfessionName = villagerProfession.get("name").getAsString();
122+
123+
villagerTypeClass.addField(
124+
FieldSpec.builder(
125+
villagerTypeClassName,
126+
villagerProfessionName
127+
).initializer(
128+
"new $T($T.from($S))",
129+
villagerTypeClassName,
130+
NAMESPACE_ID_CLASS,
131+
villagerProfession.get("id").getAsString()
132+
).addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).build()
133+
);
134+
// Add to static init.
135+
staticBlock.addStatement("$T.VILLAGER_TYPE_REGISTRY.register($N)", REGISTRY_CLASS, villagerProfessionName);
136+
}
137+
138+
villagerTypeClass.addStaticBlock(staticBlock.build());
139+
140+
// Write files to outputFolder
141+
writeFiles(
142+
List.of(
143+
JavaFile.builder("net.minestom.server.entity.metadata.villager", villagerTypeClass.build())
144+
.indent(DEFAULT_INDENT)
145+
.skipJavaLangImports(true)
146+
.build()
147+
),
148+
outputFolder
149+
);
150+
}
151+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package net.minestom.server.feature;
2+
3+
import net.minestom.server.utils.NamespaceID;
4+
import org.jetbrains.annotations.NotNull;
5+
import org.jetbrains.annotations.Nullable;
6+
7+
/**
8+
* AUTOGENERATED by FeatureFlagGenerator
9+
*/
10+
public enum FeatureFlags {
11+
UPDATE_1_21(NamespaceID.from("minecraft:update_1_21")),
12+
13+
BUNDLE(NamespaceID.from("minecraft:bundle")),
14+
15+
VANILLA(NamespaceID.from("minecraft:vanilla")),
16+
17+
TRADE_REBALANCE(NamespaceID.from("minecraft:trade_rebalance"));
18+
19+
private static final FeatureFlags[] VALUES = FeatureFlags.values();
20+
21+
private final NamespaceID feature;
22+
23+
FeatureFlags(@NotNull NamespaceID feature) {
24+
this.feature = feature;
25+
}
26+
27+
public @NotNull NamespaceID feature() {
28+
return this.feature;
29+
}
30+
31+
@Nullable
32+
public static FeatureFlags getValue(int id) {
33+
return VALUES[id];
34+
}
35+
}

0 commit comments

Comments
 (0)