Skip to content

Commit

Permalink
Update from Upstream (#68)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
1 parent c90b7d5 commit acb9b86
Show file tree
Hide file tree
Showing 751 changed files with 24,130 additions and 13,139 deletions.
6 changes: 0 additions & 6 deletions bom/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ dependencies {
// Libraries
api(libs.gson)
api(libs.jcTools)
// Path finding
api(libs.hydrazine)

// Adventure, for user-interface
api(libs.bundles.adventure)
Expand All @@ -45,10 +43,6 @@ dependencies {
// Minestom Data (From MinestomDataGenerator)
api(libs.minestomData)

// NBT parsing/manipulation/saving
api("io.github.jglrxavpok.hephaistos:common:${libs.versions.hephaistos.get()}")
api("io.github.jglrxavpok.hephaistos:gson:${libs.versions.hephaistos.get()}")

// BStats
api(libs.bstats.base)
}
Expand Down
47 changes: 19 additions & 28 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ plugins {

group = "net.onelitefeather.microtus"

version = System.getenv("TAG_VERSION") ?: "1.4.3-SNAPSHOT"
version = System.getenv("TAG_VERSION") ?: "1.4.0-SNAPSHOT"

allprojects {
group = "net.onelitefeather.microtus"
Expand Down Expand Up @@ -58,7 +58,7 @@ tasks {
addStringOption("-release", "21")
// Links to external javadocs
links("https://docs.oracle.com/en/java/javase/21/docs/api/")
links("https://jd.advntr.dev/api/${libs.versions.adventure.get()}/")
links("https://jd.adventure.kyori.net/api/${libs.versions.adventure.get()}/")
}
}
withType<Zip> {
Expand All @@ -78,11 +78,11 @@ tasks {
}

dependencies {
// Testing Framework
testImplementation(project(mapOf("path" to ":testing")))
// Only here to ensure J9 module support for extensions and our classloaders
testCompileOnly(libs.mockito.core)

// Core dependencies
api(libs.slf4j)
api(libs.jetbrainsAnnotations)
api(libs.bundles.adventure)
implementation(libs.minestomData)

// Logging
implementation(libs.bundles.logging)
Expand All @@ -93,31 +93,22 @@ dependencies {
implementation(libs.caffeine)
api(libs.fastutil)
implementation(libs.bundles.flare)

// Libraries
api(libs.gson)
implementation(libs.jcTools)
// Path finding
api(libs.hydrazine)

// Adventure, for user-interface
api(libs.bundles.adventure)

// Kotlin Libraries
api(libs.bundles.kotlin)

// BStats
api(libs.bstats.base)
// Maven
api(libs.maven.resolver)
api(libs.maven.connector)
api(libs.maven.transport.http)

// Minestom Data (From MinestomDataGenerator)
implementation(libs.minestomData)

// NBT parsing/manipulation/saving
api("io.github.jglrxavpok.hephaistos:common:${libs.versions.hephaistos.get()}")
api("io.github.jglrxavpok.hephaistos:gson:${libs.versions.hephaistos.get()}")
// Libraries
api(libs.gson)
implementation(libs.jcTools)

// BStats
api(libs.bstats.base)
// Testing
testImplementation(libs.bundles.junit)
testImplementation(project(":testing"))
// Only here to ensure J9 module support for extensions and our classloaders
testCompileOnly(libs.mockito.core)
}


105 changes: 79 additions & 26 deletions code-generators/src/main/java/net/minestom/codegen/CodeGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,75 +3,128 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import org.jetbrains.annotations.ApiStatus;
import com.squareup.javapoet.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.lang.model.SourceVersion;
import javax.lang.model.element.Modifier;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Locale;

import static net.minestom.codegen.MinestomCodeGenerator.DEFAULT_INDENT;
import static net.minestom.codegen.MinestomCodeGenerator.extractNamespaces;

@ApiStatus.Internal
public class CodeGenerator implements CodeExporter {
public class CodeGenerator {
protected static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final Logger LOGGER = LoggerFactory.getLogger(CodeGenerator.class);

private final File outputFolder;

public CodeGenerator(@NotNull File outputFolder) {
public CodeGenerator(File outputFolder) {
this.outputFolder = outputFolder;
}

public void generate(InputStream resourceFile, String packageName, String typeName, String loaderName, String generatedName) {
if (resourceFile == null) {
LOGGER.error("Failed to find resource file for {}", typeName);
LOGGER.error("Failed to find resource file for " + typeName);
return;
}
ClassName typeClass = ClassName.get(packageName, typeName);
ClassName loaderClass = ClassName.get(packageName, loaderName);

JsonObject json = GSON.fromJson(new InputStreamReader(resourceFile), JsonObject.class);
JsonObject json;
json = GSON.fromJson(new InputStreamReader(resourceFile), JsonObject.class);
ClassName materialsCN = ClassName.get(packageName, generatedName);
// BlockConstants class
TypeSpec.Builder blockConstantsClass = TypeSpec.interfaceBuilder(materialsCN)
// Add @SuppressWarnings("unused")
.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unused").build())
.addJavadoc("Code autogenerated, do not edit!");

Map<String, String> replacementOptions = new HashMap<>();
replacementOptions.put("minecraft:", "");
replacementOptions.put(".", "_");
// Use data
json.keySet().forEach(namespace -> {
final String constantName = extractNamespaces(namespace, replacementOptions);
final String constantName = namespace
.replace("minecraft:", "")
.replace(".", "_")
.toUpperCase(Locale.ROOT);
blockConstantsClass.addField(
FieldSpec.builder(typeClass, constantName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer(
// TypeClass.STONE = MaterialLoader.fromNamespaceId("minecraft:stone")
"$T.get($S)",
loaderClass,
namespace
)
.build()
);
});
writeFile(
JavaFile.builder(packageName, blockConstantsClass.build())
.indent(DEFAULT_INDENT)
writeFiles(
List.of(JavaFile.builder(packageName, blockConstantsClass.build())
.indent(" ")
.skipJavaLangImports(true)
.build()),
outputFolder);
}

public void generateKeys(InputStream resourceFile, String packageName, String typeName, String generatedName) {
if (resourceFile == null) {
LOGGER.error("Failed to find resource file for " + typeName);
return;
}

ClassName typeClass = ClassName.bestGuess(packageName + "." + typeName); // Use bestGuess to handle nested class
ClassName registryKeyClass = ClassName.get("net.minestom.server.registry", "DynamicRegistry", "Key");
ParameterizedTypeName typedRegistryKeyClass = ParameterizedTypeName.get(registryKeyClass, typeClass);

JsonObject json;
json = GSON.fromJson(new InputStreamReader(resourceFile), JsonObject.class);
ClassName materialsCN = ClassName.get(packageName, generatedName);
// BlockConstants class
TypeSpec.Builder blockConstantsClass = TypeSpec.interfaceBuilder(materialsCN)
// Add @SuppressWarnings("unused")
.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unused").build())
.addJavadoc("Code autogenerated, do not edit!");

// Use data
json.keySet().forEach(namespace -> {
String constantName = namespace
.replace("minecraft:", "")
.replace(".", "_")
.toUpperCase(Locale.ROOT);
if (!SourceVersion.isName(constantName)) {
constantName = "_" + constantName;
}
blockConstantsClass.addField(
FieldSpec.builder(typedRegistryKeyClass, constantName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer(
// TypeClass.STONE = NamespaceID.from("minecraft:stone")
"$T.of($S)",
registryKeyClass,
namespace
)
.build()
);
});
writeFiles(
List.of(JavaFile.builder(packageName, blockConstantsClass.build())
.indent(" ")
.skipJavaLangImports(true)
.build(),
outputFolder
);
.build()),
outputFolder);
}

private void writeFiles(@NotNull List<JavaFile> fileList, File outputFolder) {
for (JavaFile javaFile : fileList) {
try {
javaFile.writeTo(outputFolder);
} catch (IOException e) {
LOGGER.error("An error occured while writing source code to the file system.", e);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package net.minestom.codegen;

import com.google.gson.JsonObject;
import com.squareup.javapoet.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.lang.model.element.Modifier;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public class ConstantsGenerator extends MinestomCodeGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(ConstantsGenerator.class);
private final InputStream constantsFile;
private final File outputFolder;

public ConstantsGenerator(@Nullable InputStream constantsFile, @NotNull File outputFolder) {
this.constantsFile = constantsFile;
this.outputFolder = outputFolder;
}

@Override
public void generate() {
if (constantsFile == null) {
LOGGER.error("Failed to find constants.json.");
LOGGER.error("Stopped code generation for recipe types.");
return;
}
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
LOGGER.error("Output folder for code generation does not exist and could not be created.");
return;
}

// Important classes we use alot
JsonObject constants = GSON.fromJson(new InputStreamReader(constantsFile), JsonObject.class);
ClassName minecraftConstantsCN = ClassName.get("net.minestom.server", "MinecraftConstants");
TypeSpec.Builder constantsInterface = TypeSpec.interfaceBuilder(minecraftConstantsCN)
.addJavadoc("AUTOGENERATED by " + getClass().getSimpleName());

constantsInterface.addField(FieldSpec.builder(String.class, "VERSION_NAME")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$S", constants.get("name").getAsString())
.build()
);
constantsInterface.addField(FieldSpec.builder(TypeName.INT, "PROTOCOL_VERSION")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$L", constants.get("protocol").getAsInt())
.build()
);
constantsInterface.addField(FieldSpec.builder(TypeName.INT, "DATA_VERSION")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$L", constants.get("world").getAsInt())
.build()
);
constantsInterface.addField(FieldSpec.builder(TypeName.INT, "RESOURCE_PACK_VERSION")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$L", constants.get("resourcepack").getAsInt())
.build()
);
constantsInterface.addField(FieldSpec.builder(TypeName.INT, "DATA_PACK_VERSION")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$L", constants.get("datapack").getAsInt())
.build()
);

// Write files to outputFolder
writeFiles(
List.of(
JavaFile.builder("net.minestom.server", constantsInterface.build())
.indent(" ")
.skipJavaLangImports(true)
.build()
),
outputFolder
);
}

}
Loading

0 comments on commit acb9b86

Please sign in to comment.