diff --git a/.gitignore b/.gitignore index 71c5e30ae..27677c1fa 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,12 @@ build # other eclipse run +runs/ +.worktrees/ +resume.txt +.agents +.codex + # Files from Forge MDK forge*changelog.txt diff --git a/README.md b/README.md new file mode 100644 index 000000000..961485507 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# Passive Skill Tree + +Passive skill tree mod for Minecraft. + +This repository is a fork port made by marneilx to update Passive Skill Tree to Minecraft 1.21.1 on NeoForge. + +Original mod page: https://www.curseforge.com/minecraft/mc-mods/passive-skill-tree diff --git a/build.gradle b/build.gradle index b405f2838..b5231f262 100644 --- a/build.gradle +++ b/build.gradle @@ -1,159 +1,94 @@ plugins { + id 'java-library' + id 'maven-publish' id 'eclipse' id 'idea' - id 'maven-publish' - id 'net.minecraftforge.gradle' version '[6.0,6.2)' - id 'org.spongepowered.mixin' version '0.7-SNAPSHOT' - id 'org.parchmentmc.librarian.forgegradle' version '1.+' + id 'net.neoforged.gradle.userdev' version '7.1.26' } version = mod_version group = mod_group_id base { - archivesName = "${mod_file_name}" + archivesName = mod_file_name } -java.toolchain.languageVersion = JavaLanguageVersion.of(17) - -println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" -minecraft { - mappings channel: mapping_channel, version: mapping_version - - copyIdeResources = true - - runs { - client { - workingDirectory project.file('run') - - arg "-mixin.config=${mod_id}.mixins.json" - - property 'forge.logging.markers', 'REGISTRIES' - property 'forge.logging.console.level', 'debug' - property 'forge.enabledGameTestNamespaces', mod_id - - property 'mixin.env.remapRefMap', 'true' - property 'mixin.env.refMapRemappingFile', "${buildDir}/createSrgToMcp/output.srg" - - mods { - "${mod_id}" { - source sourceSets.main - } - } - } - - server { - workingDirectory project.file('run') - - arg "-mixin.config=${mod_id}.mixins.json" - - property 'forge.logging.markers', 'REGISTRIES' - property 'forge.logging.console.level', 'debug' - property 'forge.enabledGameTestNamespaces', mod_id - - property 'mixin.env.remapRefMap', 'true' - property 'mixin.env.refMapRemappingFile', "${buildDir}/createSrgToMcp/output.srg" - - mods { - "${mod_id}" { - source sourceSets.main - } - } - - - } - - gameTestServer { - workingDirectory project.file('run') - - property 'forge.logging.markers', 'REGISTRIES' - property 'forge.logging.console.level', 'debug' - property 'forge.enabledGameTestNamespaces', mod_id - - mods { - "${mod_id}" { - source sourceSets.main - } - } +repositories { + maven { + url "https://www.cursemaven.com" + content { + includeGroup "curse.maven" } + } + mavenCentral() +} - data { - workingDirectory project.file('run') +tasks.named('wrapper', Wrapper).configure { + distributionType = Wrapper.DistributionType.BIN +} - arg "-mixin.config=${mod_id}.mixins.json" +java.toolchain.languageVersion = JavaLanguageVersion.of(21) - property 'forge.logging.markers', 'REGISTRIES' - property 'forge.logging.console.level', 'debug' +sourceSets.main.resources { + srcDir('src/generated/resources') +} - args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') +println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" - mods { - "${mod_id}" { - source sourceSets.main - } - } - } +runs { + configureEach { + workingDirectory project.layout.projectDirectory.dir('runs').dir(name) + modSource project.sourceSets.main } -} -sourceSets.main.resources { srcDir 'src/generated/resources' } - -repositories { - maven { - url "https://www.cursemaven.com" - content { - includeGroup "curse.maven" - } + data { + arguments.addAll '--mod', mod_id, '--all', + '--output', file('src/generated/resources/').absolutePath, + '--existing', file('src/main/resources/').absolutePath } } -dependencies { - minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" - // mixin - annotationProcessor 'org.spongepowered:mixin:0.8.4:processor' - implementation(annotationProcessor("io.github.llamalad7:mixinextras-common:0.3.2")) - implementation(jarJar("io.github.llamalad7:mixinextras-forge:0.3.2")) { - jarJar.ranged(it, "[0.3.2,)") - } - // curios - implementation fg.deobf("curse.maven:curios-309927:6418456") - // attribute fix - implementation fg.deobf("curse.maven:attributefix-280510:4648448") - // max health fix - implementation fg.deobf("curse.maven:max-health-fix-492246:4648479") - // dummy target - implementation fg.deobf("curse.maven:mmmmmmmmmmmm-225738:4602101") - implementation fg.deobf("curse.maven:selene-499980:4656567") - // jei - implementation fg.deobf("curse.maven:jei-238222:4644453") - // apple skin - implementation fg.deobf("curse.maven:appleskin-248787:4605078") - // apotheosis - implementation fg.deobf("curse.maven:placebo-283644:5414631") - implementation fg.deobf("curse.maven:apothic-attributes-898963:5529789") - // spells and spellbooks - implementation fg.deobf("curse.maven:irons-spells-n-spellbooks-855414:7605614") - implementation fg.deobf("curse.maven:geckolib-388172:7553267") - implementation fg.deobf("curse.maven:playeranimator-658587:4587214") +configurations { + runtimeClasspath.extendsFrom localRuntime } -mixin { - add sourceSets.main, "${mod_id}.refmap.json" +dependencies { + implementation "net.neoforged:neoforge:${neo_version}" + compileOnly "org.spongepowered:mixin:0.8.5" + annotationProcessor "org.spongepowered:mixin:0.8.5:processor" + compileOnly "io.github.llamalad7:mixinextras-common:0.5.3" + implementation "curse.maven:curios-309927:6529130" + implementation "curse.maven:attributefix-280510:7115922" + implementation "curse.maven:max-health-fix-492246:5824111" + runtimeOnly "curse.maven:bookshelf-228525:7606240" + runtimeOnly "curse.maven:prickle-1023259:6961457" + implementation "curse.maven:selene-499980:8065893" + implementation "curse.maven:jei-238222:7416540" + implementation "curse.maven:appleskin-248787:7854442" + implementation "curse.maven:placebo-283644:6926281" + implementation "curse.maven:apothic-attributes-898963:7445079" + implementation "curse.maven:irons-spells-n-spellbooks-855414:7907341" + runtimeOnly "curse.maven:irons-lib-1492763:7907336" + implementation "curse.maven:geckolib-388172:7707149" + implementation "curse.maven:playeranimator-658587:6024462" } -def resourceTargets = ['META-INF/mods.toml', 'pack.mcmeta'] -def replaceProperties = [ - minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range, - forge_version: forge_version, forge_version_range: forge_version_range, +tasks.withType(ProcessResources).configureEach { + def replaceProperties = [ + minecraft_version: minecraft_version, + minecraft_version_range: minecraft_version_range, + neo_version: neo_version, loader_version_range: loader_version_range, - mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version, - mod_authors: mod_authors, mod_description: mod_description -] -processResources { + mod_id: mod_id, + mod_name: mod_name, + mod_license: mod_license, + mod_version: mod_version, + mod_authors: mod_authors, + mod_description: mod_description + ] inputs.properties replaceProperties - replaceProperties.put 'project', project - filesMatching(resourceTargets) { + filesMatching(['META-INF/neoforge.mods.toml', 'pack.mcmeta']) { expand replaceProperties } } @@ -167,14 +102,11 @@ jar { "Implementation-Title" : project.name, "Implementation-Version" : project.jar.archiveVersion, "Implementation-Vendor" : mod_authors, - "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), - "MixinConfigs" : "${mod_id}.mixins.json" + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") ]) } } -jar.finalizedBy('reobfJar') - tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' } diff --git a/docs/superpowers/plans/2026-05-15-passive-skill-tree-neoforge-1211-port.md b/docs/superpowers/plans/2026-05-15-passive-skill-tree-neoforge-1211-port.md new file mode 100644 index 000000000..3a027f07a --- /dev/null +++ b/docs/superpowers/plans/2026-05-15-passive-skill-tree-neoforge-1211-port.md @@ -0,0 +1,515 @@ +# Passive Skill Tree NeoForge 1.21.1 Port Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended) or `superpowers:executing-plans` to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Port Passive Skill Tree from Minecraft 1.20.1 Forge to Minecraft 1.21.1 NeoForge with full feature parity. + +**Architecture:** Treat this as a staged platform migration, not a rewrite. First move the build onto the NeoForge 1.21.1 toolchain, then swap Forge persistence/networking/runtime hooks for NeoForge equivalents, then fix the vanilla 1.21.1 API breaks, and finally refresh compat and generated data so the runtime behavior matches the old mod. + +**Tech Stack:** Java 21, NeoForge 1.21.1, NeoGradle / Gradle 9.2.1, Sponge Mixin, NeoForge data attachments, NeoForge payload networking, JUnit 5 for regression tests, Curse Maven dependencies. + +--- + +### Task 1: Move the project onto the NeoForge 1.21.1 toolchain + +**Files:** +- Modify `build.gradle` +- Modify `settings.gradle` +- Modify `gradle.properties` +- Modify `gradle/wrapper/gradle-wrapper.properties` +- Create `src/main/resources/META-INF/neoforge.mods.toml` +- Delete `src/main/resources/META-INF/mods.toml` +- Modify `src/main/resources/pack.mcmeta` + +- [ ] **Step 1: Replace the Forge build bootstrap with the NeoForge MDK shape** + +```gradle +plugins { + id 'java-library' + id 'maven-publish' + id 'net.neoforged.gradle.userdev' version '7.1.27' + id 'org.spongepowered.mixin' version '0.7-SNAPSHOT' +} + +java.toolchain.languageVersion = JavaLanguageVersion.of(21) + +dependencies { + implementation "net.neoforged:neoforge:${neo_version}" +} +``` + +Set `minecraft_version=1.21.1`, `neo_version=21.1.229`, and `mod_file_name=PassiveSkillTree-1.21.1-BETA` in `gradle.properties`. Update `settings.gradle` to use `maven.neoforged.net/releases`, and update the wrapper to Gradle `9.2.1`. + +- [ ] **Step 2: Replace `mods.toml` with NeoForge metadata** + +```toml +modLoader="javafml" +loaderVersion="${loader_version_range}" +license="${mod_license}" + +[[mods]] +modId="${mod_id}" +version="${mod_version}" +displayName="${mod_name}" +authors="${mod_authors}" +description='''${mod_description}''' + +[[dependencies.${mod_id}]] +modId="neoforge" +mandatory=true +versionRange="[${neo_version},)" +ordering="NONE" +side="BOTH" +``` + +Keep the existing required `minecraft` and `attributefix` dependency blocks, and keep `curios` optional. + +- [ ] **Step 3: Update the resource pack metadata** + +```json +{ + "pack": { + "description": { "text": "${mod_id} resources" }, + "pack_format": 34 + } +} +``` + +Keep the same description expansion, just change the 1.20.1 pack format to the 1.21.1 value. + +- [ ] **Step 4: Run the build once to prove the failure moved from the toolchain into source-level API errors** + +Run: `bash gradlew compileJava` + +Expected: the wrapper and dependency resolution should work; any failure should now be actual source migration errors, not the Java 26 / Gradle 8.1.1 cache failure seen before. + +- [ ] **Step 5: Commit** + +```bash +git add build.gradle settings.gradle gradle.properties gradle/wrapper/gradle-wrapper.properties src/main/resources/META-INF/neoforge.mods.toml src/main/resources/pack.mcmeta src/main/resources/META-INF/mods.toml +git commit -m "build: bootstrap NeoForge 1.21.1" +``` + +### Task 2: Lock down player-skill persistence with a small regression test + +**Files:** +- Modify `build.gradle` +- Create `src/main/java/daripher/skilltree/capability/skill/PlayerSkillsCodec.java` +- Modify `src/main/java/daripher/skilltree/capability/skill/PlayerSkills.java` +- Create `src/test/java/daripher/skilltree/capability/skill/PlayerSkillsCodecTest.java` + +- [ ] **Step 1: Add the failing test first** + +```java +package daripher.skilltree.capability.skill; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.UUID; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.StringTag; +import org.junit.jupiter.api.Test; + +class PlayerSkillsCodecTest { + @Test + void staleTreeVersion_refundsOnePointPerStoredSkill_andMarksReset() { + CompoundTag tag = new CompoundTag(); + tag.putUUID("TreeVersion", UUID.fromString("00000000-0000-0000-0000-000000000000")); + tag.putInt("Points", 3); + ListTag skills = new ListTag(); + skills.add(StringTag.valueOf("skilltree:hunter_1")); + skills.add(StringTag.valueOf("skilltree:hunter_2")); + tag.put("Skills", skills); + + PlayerSkills state = new PlayerSkills(); + PlayerSkillsCodec.read(state, tag); + + assertEquals(5, state.getSkillPoints()); + assertTrue(state.isTreeReset()); + assertTrue(state.getPlayerSkills().isEmpty()); + } +} +``` + +- [ ] **Step 2: Run the test and watch it fail for the right reason** + +Run: `bash gradlew test --tests daripher.skilltree.capability.skill.PlayerSkillsCodecTest -v` + +Expected: the test should fail because `PlayerSkillsCodec` does not exist yet, or because the codec methods are not wired yet. Do not accept a green run here. + +- [ ] **Step 3: Extract the pure persistence logic into `PlayerSkillsCodec`** + +```java +public final class PlayerSkillsCodec { + private PlayerSkillsCodec() {} + + public static CompoundTag write(PlayerSkills skills) { /* serialize points, reset flag, tree version, and learned skills */ } + + public static void read(PlayerSkills skills, CompoundTag tag) { /* preserve the current tree-version invalidation behavior */ } +} +``` + +Make `PlayerSkills` delegate to this helper so the persistence rules stay in one place and can be tested without touching NeoForge runtime code. + +- [ ] **Step 4: Re-run the test until it passes cleanly** + +Run: `bash gradlew test --tests daripher.skilltree.capability.skill.PlayerSkillsCodecTest -v` + +Expected: PASS with no new warnings from the test harness. + +- [ ] **Step 5: Commit** + +```bash +git add build.gradle src/main/java/daripher/skilltree/capability/skill/PlayerSkillsCodec.java src/main/java/daripher/skilltree/capability/skill/PlayerSkills.java src/test/java/daripher/skilltree/capability/skill/PlayerSkillsCodecTest.java +git commit -m "test: lock down player skill persistence" +``` + +### Task 3: Replace the player capability with a NeoForge attachment + +**Files:** +- Create `src/main/java/daripher/skilltree/init/PSTAttachments.java` +- Modify `src/main/java/daripher/skilltree/SkillTreeMod.java` +- Modify `src/main/java/daripher/skilltree/capability/skill/PlayerSkillsProvider.java` +- Modify all call sites that still read through `PlayerSkillsProvider` if the helper method names change + +- [ ] **Step 1: Register the attachment type** + +```java +public final class PSTAttachments { + public static final DeferredRegister> REGISTRY = + DeferredRegister.create(NeoForgeRegistries.ATTACHMENT_TYPES, SkillTreeMod.MOD_ID); + + public static final Supplier> PLAYER_SKILLS = + REGISTRY.register( + "player_skills", + () -> AttachmentType.serializable(PlayerSkills::new).copyOnDeath().build()); + + private PSTAttachments() {} +} +``` + +Register this deferred register from `SkillTreeMod` on the mod event bus next to the existing item, recipe, menu, and loot registries. + +- [ ] **Step 2: Rework `PlayerSkillsProvider` into attachment-backed access helpers** + +Keep the public `get(Player)` / `hasSkills(Player)` helpers, but make them read from the attachment instead of `CapabilityManager`, `LazyOptional`, or `ICapabilitySerializable`. + +```java +public static @NotNull IPlayerSkills get(Player player) { + return player.getData(PSTAttachments.PLAYER_SKILLS.get()); +} +``` + +Keep the existing login, clone, and join event hooks, but make them use attachment-backed data and preserve the current tree-reset message and bonus reapplication flow. + +- [ ] **Step 3: Re-run a build after removing the capability APIs** + +Run: `bash gradlew compileJava` + +Expected: no remaining references to `CapabilityManager`, `CapabilityToken`, `LazyOptional`, `ICapabilitySerializable`, or `AttachCapabilitiesEvent` in the player-skill storage path. + +- [ ] **Step 4: Commit** + +```bash +git add src/main/java/daripher/skilltree/init/PSTAttachments.java src/main/java/daripher/skilltree/SkillTreeMod.java src/main/java/daripher/skilltree/capability/skill/PlayerSkillsProvider.java +git commit -m "refactor: move player skills to attachments" +``` + +### Task 4: Convert the network layer to NeoForge payloads + +**Files:** +- Modify `src/main/java/daripher/skilltree/network/NetworkDispatcher.java` +- Modify `src/main/java/daripher/skilltree/network/message/SyncServerDataMessage.java` +- Modify `src/main/java/daripher/skilltree/network/message/SyncPlayerSkillsMessage.java` +- Modify `src/main/java/daripher/skilltree/network/message/LearnSkillMessage.java` +- Modify `src/main/java/daripher/skilltree/network/message/GainSkillPointMessage.java` +- Modify `src/main/java/daripher/skilltree/network/NetworkHelper.java` +- Modify `src/main/java/daripher/skilltree/client/widget/SkillTreeWidgets.java` +- Modify `src/main/java/daripher/skilltree/item/AmnesiaScrollItem.java` +- Modify `src/main/java/daripher/skilltree/item/WisdomScrollItem.java` +- Modify `src/main/java/daripher/skilltree/command/PSTCommands.java` + +- [ ] **Step 1: Replace `SimpleChannel` registration with payload registration** + +```java +@EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Bus.MOD) +public final class NetworkDispatcher { + @SubscribeEvent + public static void register(final RegisterPayloadHandlersEvent event) { + PayloadRegistrar registrar = event.registrar("1"); + registrar.playToClient(SyncServerDataMessage.TYPE, SyncServerDataMessage.STREAM_CODEC, SyncServerDataMessage::handle); + registrar.playToClient(SyncPlayerSkillsMessage.TYPE, SyncPlayerSkillsMessage.STREAM_CODEC, SyncPlayerSkillsMessage::handle); + registrar.playToServer(LearnSkillMessage.TYPE, LearnSkillMessage.STREAM_CODEC, LearnSkillMessage::handle); + registrar.playToServer(GainSkillPointMessage.TYPE, GainSkillPointMessage.STREAM_CODEC, GainSkillPointMessage::handle); + } +} +``` + +Keep the current message names if that makes the call-site migration smaller, but make each message a `CustomPacketPayload`. + +- [ ] **Step 2: Convert the four message classes to payload records or payload objects** + +Use the existing `NetworkHelper` methods for the custom data fields so the wire format stays stable. A minimal payload shape looks like this: + +```java +public record LearnSkillMessage(ResourceLocation skillId) implements CustomPacketPayload { + public static final Type TYPE = + new Type<>(ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "learn_skill")); + public static final StreamCodec STREAM_CODEC = /* wrap existing encode/decode */; + + @Override + public Type type() { return TYPE; } + + public static void handle(LearnSkillMessage message, IPayloadContext context) { /* server-side validation */ } +} +``` + +Do the same for the sync payloads and the gain-skill-point request. + +- [ ] **Step 3: Update every send site to the NeoForge `PacketDistributor` helpers** + +Replace: + +```java +NetworkDispatcher.network_channel.sendToServer(new LearnSkillMessage(skill)); +``` + +with the NeoForge payload send helper: + +```java +PacketDistributor.sendToServer(new LearnSkillMessage(skill)); +``` + +Replace player-targeted sends with `PacketDistributor.sendToPlayer(player, new SyncPlayerSkillsMessage(player));`. + +- [ ] **Step 4: Smoke test the new transport on both sides** + +Run: + +```bash +bash gradlew runClient +bash gradlew runServer +``` + +Expected: the client can still open the skill UI and the dedicated server starts without network registration or payload codec errors. + +- [ ] **Step 5: Commit** + +```bash +git add src/main/java/daripher/skilltree/network/NetworkDispatcher.java src/main/java/daripher/skilltree/network/message/SyncServerDataMessage.java src/main/java/daripher/skilltree/network/message/SyncPlayerSkillsMessage.java src/main/java/daripher/skilltree/network/message/LearnSkillMessage.java src/main/java/daripher/skilltree/network/message/GainSkillPointMessage.java src/main/java/daripher/skilltree/network/NetworkHelper.java src/main/java/daripher/skilltree/client/widget/SkillTreeWidgets.java src/main/java/daripher/skilltree/item/AmnesiaScrollItem.java src/main/java/daripher/skilltree/item/WisdomScrollItem.java src/main/java/daripher/skilltree/command/PSTCommands.java +git commit -m "refactor: move networking to NeoForge payloads" +``` + +### Task 5: Port the server-side 1.21.1 API breaks + +**Files:** +- Modify `src/main/java/daripher/skilltree/data/serializers/SerializationHelper.java` +- Modify `src/main/java/daripher/skilltree/init/PSTTags.java` +- Modify `src/main/java/daripher/skilltree/init/PSTBlocks.java` +- Modify `src/main/java/daripher/skilltree/init/PSTItems.java` +- Modify `src/main/java/daripher/skilltree/init/PSTRecipeSerializers.java` +- Modify `src/main/java/daripher/skilltree/init/PSTRecipeTypes.java` +- Modify `src/main/java/daripher/skilltree/init/PSTLootModifiers.java` +- Modify `src/main/java/daripher/skilltree/init/PSTDamageTypes.java` +- Modify `src/main/java/daripher/skilltree/init/PSTMobEffects.java` +- Modify `src/main/java/daripher/skilltree/init/PSTPotions.java` +- Modify `src/main/java/daripher/skilltree/recipe/**` +- Modify `src/main/java/daripher/skilltree/skill/**` server-side bonus, requirement, and predicate classes +- Modify `src/main/java/daripher/skilltree/data/reloader/**` +- Modify `src/main/java/daripher/skilltree/event/PSTEvents.java` +- Modify `src/main/java/daripher/skilltree/command/PSTCommands.java` +- Modify `src/main/java/daripher/skilltree/entity/player/PlayerHelper.java` + +- [ ] **Step 1: Replace old Forge registry and resource-location calls with the 1.21.1 equivalents** + +Use `BuiltInRegistries` / NeoForge registries where the code currently hard-depends on `ForgeRegistries`, and convert string-based `new ResourceLocation(...)` calls to `ResourceLocation.fromNamespaceAndPath(...)` where the 1.21.1 API prefers it. + +- [ ] **Step 2: Fix the attribute and recipe serialization surfaces** + +`SerializationHelper`, the recipe builders, and the skill bonus serializers should preserve the current wire/data format unless 1.21.1 forces a new shape. If the attribute modifier ID format has to change, keep the old UUID/name fields readable so existing skill JSON still loads. + +- [ ] **Step 3: Resolve the event/package mismatches that show up during compile** + +Fix the imports and method signatures for the event classes touched by: +- grindstone logic +- reload listeners +- anvil logic +- tooltip logic +- movement input logic +- living damage / heal / attack logic + +- [ ] **Step 4: Re-run compilation** + +Run: `bash gradlew compileJava` + +Expected: this should now fail only on remaining client/mixin/compat issues, not on the core server/data layer. + +- [ ] **Step 5: Commit** + +```bash +git add src/main/java/daripher/skilltree/data/serializers/SerializationHelper.java src/main/java/daripher/skilltree/init/PSTTags.java src/main/java/daripher/skilltree/init/PSTBlocks.java src/main/java/daripher/skilltree/init/PSTItems.java src/main/java/daripher/skilltree/init/PSTRecipeSerializers.java src/main/java/daripher/skilltree/init/PSTRecipeTypes.java src/main/java/daripher/skilltree/init/PSTLootModifiers.java src/main/java/daripher/skilltree/init/PSTDamageTypes.java src/main/java/daripher/skilltree/init/PSTMobEffects.java src/main/java/daripher/skilltree/init/PSTPotions.java src/main/java/daripher/skilltree/recipe src/main/java/daripher/skilltree/skill src/main/java/daripher/skilltree/data/reloader src/main/java/daripher/skilltree/event/PSTEvents.java src/main/java/daripher/skilltree/command/PSTCommands.java src/main/java/daripher/skilltree/entity/player/PlayerHelper.java +git commit -m "refactor: port server gameplay APIs to 1.21.1" +``` + +### Task 6: Port the client, GUI, and mixin surface + +**Files:** +- Modify `src/main/java/daripher/skilltree/client/init/PSTKeybinds.java` +- Modify `src/main/java/daripher/skilltree/init/PSTMenuTypes.java` +- Modify `src/main/java/daripher/skilltree/client/screen/**` +- Modify `src/main/java/daripher/skilltree/client/widget/**` +- Modify `src/main/java/daripher/skilltree/client/tooltip/TooltipHelper.java` +- Modify `src/main/java/daripher/skilltree/mixin/**` +- Modify `src/main/resources/skilltree.mixins.json` + +- [ ] **Step 1: Replace the old client menu registration path with `RegisterMenuScreensEvent`** + +```java +@SubscribeEvent +public static void registerScreens(RegisterMenuScreensEvent event) { + event.register(ARTISAN_WORKBENCH.get(), WorkbenchScreen::new); +} +``` + +Move keybind registration to the NeoForge client event bus and keep the screen/widget classes client-only. + +- [ ] **Step 2: Update the mixin config for the Java 21 runtime** + +```json +{ + "required": true, + "minVersion": "0.8", + "compatibilityLevel": "JAVA_21" +} +``` + +Then fix the accessor and injector signatures in: +- `AbstractArrowAccessor` +- `ClientAdvancementsAccessor` +- `EditBoxAccessor` +- `MobEffectInstanceAccessor` +- `ArmorSlotMixin` +- `ItemStackMixin` +- `LivingEntityMixin` +- `MobEffectMixin` +- `PlayerMixin` +- `ThrownPotionMixin` + +- [ ] **Step 3: Run the client smoke test and fix whatever still fails to render or register** + +Run: `bash gradlew runClient` + +Expected: the skill tree UI opens, keybinds register, menus/screens open, and the mixins apply without classloading errors. + +- [ ] **Step 4: Commit** + +```bash +git add src/main/java/daripher/skilltree/client/init/PSTKeybinds.java src/main/java/daripher/skilltree/init/PSTMenuTypes.java src/main/java/daripher/skilltree/client/screen src/main/java/daripher/skilltree/client/widget src/main/java/daripher/skilltree/client/tooltip/TooltipHelper.java src/main/java/daripher/skilltree/mixin src/main/resources/skilltree.mixins.json +git commit -m "refactor: port client ui and mixins to 1.21.1" +``` + +### Task 7: Refresh datagen, tag namespaces, and optional compat dependencies + +**Files:** +- Modify `src/main/java/daripher/skilltree/data/generation/**` +- Modify `src/main/java/daripher/skilltree/init/PSTTags.java` +- Modify `src/main/java/daripher/skilltree/compat/**` +- Modify `build.gradle` +- Modify `src/main/resources/META-INF/neoforge.mods.toml` +- Replace generated resources under `src/generated/resources/**` + +- [ ] **Step 1: Move shared tags and damage tags into the NeoForge namespaces** + +```java +public class PSTTags { + public static class DamageTypes { + public static final TagKey IS_MAGIC = + TagKey.create(Registries.DAMAGE_TYPE, new ResourceLocation("neoforge", "is_magic")); + } + + public static class Items { + public static final TagKey JEWELRY = + ItemTags.create(new ResourceLocation("c", "curios/jewelry")); + public static final TagKey MELEE_WEAPON = ItemTags.create(new ResourceLocation("skilltree", "melee_weapon")); + public static final TagKey RANGED_WEAPON = ItemTags.create(new ResourceLocation("skilltree", "ranged_weapon")); + public static final TagKey LEATHER_ARMOR = ItemTags.create(new ResourceLocation("skilltree", "armors/leather")); + } +} +``` + +Update the item and damage tags providers so the generated files land in `data/c/...` and `data/neoforge/...` instead of the old Forge paths. + +- [ ] **Step 2: Regenerate the data outputs** + +Run: `bash gradlew runData` + +Replace the generated outputs under `src/generated/resources/` so these files match the NeoForge namespace layout: +- `data/neoforge/loot_modifiers/global_loot_modifiers.json` +- `data/neoforge/tags/damage_type/is_magic.json` +- `data/c/tags/items/tools.json` and any other shared item tags produced by the providers + +- [ ] **Step 3: Re-scope the optional dependency declarations** + +In `build.gradle`, keep direct API mods available to the compiler, but move purely runtime companions to the NeoForge 1.21.1 runtime setup: +- `compileOnly` / `localRuntime` for API-backed integrations used in source +- `localRuntime` for optional helpers that are only needed to run the mod in a dev instance +- preserve the existing required/optional split in `neoforge.mods.toml` + +Refresh the 1.21.1 NeoForge versions for: +- Curios +- AttributeFix +- Max Health Fix +- Apothic Attributes +- Iron’s Spells and Spellbooks +- JEI +- AppleSkin +- Selene, Placebo, Geckolib, and PlayerAnimator where the build still needs them + +- [ ] **Step 4: Run the full verification set** + +Run: + +```bash +bash gradlew compileJava +bash gradlew test +bash gradlew runClient +bash gradlew runServer +bash gradlew runData +``` + +Expected: the project builds cleanly, the UI opens, the dedicated server starts, and the generated resources match the new NeoForge namespaces. + +- [ ] **Step 5: Commit** + +```bash +git add src/main/java/daripher/skilltree/data/generation src/main/java/daripher/skilltree/init/PSTTags.java src/main/java/daripher/skilltree/compat build.gradle src/main/resources/META-INF/neoforge.mods.toml src/generated/resources +git commit -m "refactor: refresh datagen and compat for NeoForge" +``` + +### Task 8: Final pass and branch completion + +**Files:** +- All files touched in the tasks above + +- [ ] **Step 1: Do one last clean status check** + +Run: `git status --short` + +Expected: only the intended port files remain changed. + +- [ ] **Step 2: Re-run the highest-risk checks after the last merge of changes** + +Run: + +```bash +bash gradlew compileJava +bash gradlew test +``` + +Expected: both pass without reintroducing Forge imports, capability leftovers, or broken tests. + +- [ ] **Step 3: Prepare the branch for handoff** + +Summarize the final changed file groups and note any remaining follow-up work, if any, before calling the port complete. + diff --git a/docs/superpowers/specs/2026-05-15-passive-skill-tree-neoforge-1211-port-design.md b/docs/superpowers/specs/2026-05-15-passive-skill-tree-neoforge-1211-port-design.md new file mode 100644 index 000000000..2bf51dbdd --- /dev/null +++ b/docs/superpowers/specs/2026-05-15-passive-skill-tree-neoforge-1211-port-design.md @@ -0,0 +1,145 @@ +# Passive Skill Tree NeoForge 1.21.1 Port Design + +## Summary +Port Passive Skill Tree from Minecraft 1.20.1 Forge to Minecraft 1.21.1 NeoForge while preserving full feature parity. + +The mod should keep the current gameplay surface intact: skill trees, point progression, player skill persistence, skill UI, editor UI, data-driven skills/recipes/loot modifiers, commands, and optional compat integrations. + +## Goals +- Build and run on Minecraft 1.21.1 NeoForge. +- Preserve core gameplay and save data behavior. +- Preserve optional compat support for the modded ecosystem already used by the project. +- Keep existing JSON/data-driven content usable with minimal disruption. + +## Non-Goals +- No gameplay redesign. +- No content rebalance unless a 1.21.1 API break forces a targeted fix. +- No multi-loader abstraction work. + +## Migration Strategy +Use a staged full-parity port: +1. Update the build and NeoForge toolchain. +2. Migrate Forge platform APIs to NeoForge equivalents. +3. Replace player capability storage with NeoForge attachment-based storage. +4. Replace SimpleChannel networking with NeoForge payload networking. +5. Update vanilla 1.21.1 API breakpoints and mixin targets. +6. Restore optional compat modules and verify they still load. + +This keeps the scope full-featured, but avoids mixing every classpath and runtime break into one unreadable failure. + +## Platform Changes +- Move from ForgeGradle to the NeoForge userdev/NeoGradle setup used by 1.21.1 MDKs. +- Target Java 21. +- Update the wrapper to a NeoForge-compatible Gradle version. +- Replace `META-INF/mods.toml` with `META-INF/neoforge.mods.toml`. +- Update metadata properties and dependency declarations for NeoForge 1.21.1. + +## Core Runtime Changes + +### Player skill state +Replace the Forge player capability provider with a NeoForge entity attachment for `PlayerSkills`. + +Why: +- `PlayerSkills` already serializes to NBT. +- The data is persistent per-player state and maps cleanly to an attachment. +- Player respawn handling can stay behaviorally identical by copying or restoring the saved skill state on clone. + +Required behavior: +- Persist learned skills, skill points, and tree reset state. +- Preserve the current tree-version invalidation behavior. +- Preserve the current “refund points and mark reset” fallback when the tree version or skill IDs are invalid. + +### Networking +Replace the current `SimpleChannel` message stack with NeoForge payload registration. + +Required payloads: +- server sync data +- player skill sync +- learn skill request +- gain skill point request + +Rules: +- server validates every client-originated request +- payload handlers stay side-safe +- client UI still receives the same sync information it expects today + +### Registries and events +Keep the existing `PST*` registration classes where possible, but swap their Forge-specific APIs to NeoForge equivalents. + +The following areas need attention: +- mod bootstrap and event bus wiring +- deferred registry usage +- config registration +- reload listeners +- client keybind registration +- loot modifier registration +- recipe, menu, block/item, effect, and tag registration + +## 1.21.1 API Breakpoints +Update the code where 1.21.1 vanilla or NeoForge signatures changed: +- `ResourceLocation` construction and parsing usage +- attribute modifier handling +- recipe and menu APIs +- item stack and component/data handling +- event classes and event package names +- mixin targets and accessor names +- client screen/widget bindings + +The migration should preserve the current data formats where possible, with adapters only where the version change requires them. + +## Compat Modules +Preserve the current optional integrations, but swap them to the 1.21.1 NeoForge versions already available in the ecosystem. + +Current compat surface to keep: +- Curios +- AttributeFix / max health handling +- Apothic Attributes +- Iron’s Spells and Spellbooks +- JEI +- AppleSkin +- the current development/runtime support dependencies already present in the build, including Selene, mmmmmmmmmmmm, Placebo, Geckolib, and PlayerAnimator + +Dependency policy should mirror the current mod: +- required integrations stay required when the existing metadata says they are required +- optional compat stays optional +- dev/runtime support libs stay present for testing and local launch, but do not become hard dependencies unless the code truly needs them + +## Data Flow +1. Server loads skill trees, skills, recipes, loot modifiers, tags, and configs. +2. Player joins and receives persistent skill state from the attachment-backed storage. +3. Server syncs trees and player data to the client. +4. Client sends learn/reset/editor actions through payloads. +5. Server validates the request, mutates saved skill state, applies or removes bonuses, then resyncs. +6. Gameplay listeners and compat hooks apply the active bonuses during combat, crafting, movement, potion, damage, and loot events. + +## Error Handling +- Missing optional compat mods should not crash the base mod. +- Missing required mods should fail through mod metadata, not late during gameplay. +- Invalid skill IDs or malformed data should log clearly and fail safe on the server. +- Dedicated server startup must not touch client-only classes. + +## Verification +Acceptance criteria: +- project compiles on the NeoForge 1.21.1 toolchain +- client launches and opens the skill tree UI +- dedicated server launches without classloading failures +- learned skills persist across relog and death +- learn/reset/sync requests work over the new payload channel +- optional compat modules compile and load with their 1.21.1 NeoForge dependencies +- datagen outputs remain valid for the existing data model + +Recommended check order: +1. `compileJava` +2. client smoke run +3. dedicated server smoke run +4. data generation / resource validation +5. targeted gameplay checks for learn skill, reset tree, and compat-triggered bonuses + +## References +- NeoForge getting started: https://docs.neoforged.net/docs/1.21.1/gettingstarted/ +- NeoForge mod files: https://docs.neoforged.net/docs/1.21.4/gettingstarted/modfiles/ +- NeoForge data attachments: https://docs.neoforged.net/docs/1.21.1/datastorage/attachments/ +- NeoForge networking payloads: https://docs.neoforged.net/docs/1.21.1/networking/payload/ +- Curios 1.21.1 NeoForge files: https://www.curseforge.com/minecraft/mc-mods/curios/files/all?page=1&version=1.21.1 +- AttributeFix 1.21.1 NeoForge files: https://www.curseforge.com/minecraft/mc-mods/attributefix/files/all?page=1&version=1.21.1 +- Apothic Attributes 1.21.1 NeoForge files: https://www.curseforge.com/minecraft/mc-mods/apothic-attributes/files/all?page=1&pageSize=20&version=1.21.1 diff --git a/gradle.properties b/gradle.properties index 1567a82b7..a731eb063 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,20 +1,19 @@ org.gradle.jvmargs=-Xmx3G org.gradle.daemon=false -minecraft_version=1.20.1 -minecraft_version_range=[1.20.1,1.21) -forge_version=47.4.0 -forge_version_range=[47,) -loader_version_range=[47,) +minecraft_version=1.21.1 +minecraft_version_range=[1.21.1,1.21.2) +neo_version=21.1.228 +loader_version_range=[1,) -mapping_channel=parchment -mapping_version=2023.09.03-1.20.1 +neogradle.subsystems.parchment.minecraftVersion=1.21.1 +neogradle.subsystems.parchment.mappingsVersion=2024.11.17 mod_id=skilltree mod_name=Passive Skill Tree -mod_file_name=PassiveSkillTree-1.20.1-BETA +mod_file_name=PassiveSkillTree-1.21.1-NeoForge-BETA mod_license=GNU GENERAL PUBLIC LICENSE -mod_version=0.7.4 +mod_version=0.7.5 mod_group_id=daripher.skilltree mod_authors=Daripher mod_description=Adds passive skill tree with player class system diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37aef8d3f..cd4b7aa89 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/settings.gradle b/settings.gradle index 995ba247c..38951cbbf 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,10 +1,7 @@ pluginManagement { repositories { gradlePluginPortal() - maven { - name = 'MinecraftForge' - url = 'https://maven.minecraftforge.net/' - } + maven { url = 'https://maven.neoforged.net/releases' } maven { url = 'https://repo.spongepowered.org/repository/maven-public/' } maven { url = 'https://maven.parchmentmc.org' } } @@ -12,4 +9,4 @@ pluginManagement { plugins { id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' -} \ No newline at end of file +} diff --git a/src/generated/resources/.cache/1d26861f3a64eed7dae44a273d274697b05c1fc4 b/src/generated/resources/.cache/1d26861f3a64eed7dae44a273d274697b05c1fc4 index dfadfeb2f..73bc522b1 100644 --- a/src/generated/resources/.cache/1d26861f3a64eed7dae44a273d274697b05c1fc4 +++ b/src/generated/resources/.cache/1d26861f3a64eed7dae44a273d274697b05c1fc4 @@ -1,3 +1,3 @@ -// 1.20.1 2025-10-22T07:17:07.2904207 Item Models: skilltree +// 1.21.1 2026-05-18T00:43:08.191382652 Item Models: skilltree 7f105626d8a7ca598d2b0804d3cf871e12ebf6c0 assets/skilltree/models/item/amnesia_scroll.json b2dda19d8e8f5cd65954cc60490f1dab8dade95a assets/skilltree/models/item/wisdom_scroll.json diff --git a/src/generated/resources/.cache/265b1abcd389b09ac070519c3b0d2d138f2517e3 b/src/generated/resources/.cache/265b1abcd389b09ac070519c3b0d2d138f2517e3 index 83f12b359..5449a620a 100644 --- a/src/generated/resources/.cache/265b1abcd389b09ac070519c3b0d2d138f2517e3 +++ b/src/generated/resources/.cache/265b1abcd389b09ac070519c3b0d2d138f2517e3 @@ -1,4 +1,4 @@ -// 1.20.1 2025-10-26T16:48:47.5812598 Block States: skilltree +// 1.21.1 2026-05-18T00:43:08.193125639 Block States: skilltree 3ca796a712684fed5e66b4cbc1511b5d199e560b assets/skilltree/blockstates/workbench.json bd8dc90ed6b3c8e8f656639be0233c16235c0c8e assets/skilltree/models/block/workbench.json fb4201ed570e04e7af6f20428123cbda6b4860d3 assets/skilltree/models/item/workbench.json diff --git a/src/generated/resources/.cache/59eb3dbb5f86130e09b3c62d89b9525ee01cf52d b/src/generated/resources/.cache/59eb3dbb5f86130e09b3c62d89b9525ee01cf52d index 542df3edc..0ff339e48 100644 --- a/src/generated/resources/.cache/59eb3dbb5f86130e09b3c62d89b9525ee01cf52d +++ b/src/generated/resources/.cache/59eb3dbb5f86130e09b3c62d89b9525ee01cf52d @@ -1,2 +1,2 @@ -// 1.20.1 2025-11-23T02:06:11.4978159 Loot Tables -fcc19e38ec1489878995d2889c753b8424c75375 data/skilltree/loot_tables/blocks/workbench.json +// 1.21.1 2026-05-18T00:43:08.192057629 Loot Tables +fcc19e38ec1489878995d2889c753b8424c75375 data/skilltree/loot_table/blocks/workbench.json diff --git a/src/generated/resources/.cache/659799cd61a162f980db6f811289946f676add6e b/src/generated/resources/.cache/659799cd61a162f980db6f811289946f676add6e index ce29ec336..5616edcb2 100644 --- a/src/generated/resources/.cache/659799cd61a162f980db6f811289946f676add6e +++ b/src/generated/resources/.cache/659799cd61a162f980db6f811289946f676add6e @@ -1,3 +1,3 @@ -// 1.20.1 2025-08-25T03:21:23.1718624 Global Loot Modifiers : skilltree -ffce943a570605f3af7c8319abef8b1ce6b89027 data/forge/loot_modifiers/global_loot_modifiers.json +// 1.21.1 2026-05-18T00:43:08.190980678 Global Loot Modifiers : skilltree +ffce943a570605f3af7c8319abef8b1ce6b89027 data/neoforge/loot_modifiers/global_loot_modifiers.json 738a5197cb0b0cb73b64f238c5d1285b73babe06 data/skilltree/loot_modifiers/skill_bonuses.json diff --git a/src/generated/resources/.cache/67667cb51994a49b68e560431391360e3828f1f8 b/src/generated/resources/.cache/67667cb51994a49b68e560431391360e3828f1f8 new file mode 100644 index 000000000..92951666b --- /dev/null +++ b/src/generated/resources/.cache/67667cb51994a49b68e560431391360e3828f1f8 @@ -0,0 +1,2 @@ +// 1.21.1 2026-05-18T00:43:08.191635745 Languages: ru_ru for mod: skilltree +52ab7ac9d906fc0a1aaa5e0b843f8a386cb19ad5 assets/skilltree/lang/ru_ru.json diff --git a/src/generated/resources/.cache/7dbdaff3a029567dee918985a82fb9fa3198261b b/src/generated/resources/.cache/7dbdaff3a029567dee918985a82fb9fa3198261b new file mode 100644 index 000000000..37a72463a --- /dev/null +++ b/src/generated/resources/.cache/7dbdaff3a029567dee918985a82fb9fa3198261b @@ -0,0 +1,2 @@ +// 1.21.1 2026-05-18T00:43:08.189908601 Languages: en_us for mod: skilltree +d0e33df33a885c08e08435c2449bfe5ee8d9b95e assets/skilltree/lang/en_us.json diff --git a/src/generated/resources/.cache/9fb1092f32d4fcbf9e061ffd718d4ec689c6c95e b/src/generated/resources/.cache/9fb1092f32d4fcbf9e061ffd718d4ec689c6c95e index 326146f34..ef07f0c30 100644 --- a/src/generated/resources/.cache/9fb1092f32d4fcbf9e061ffd718d4ec689c6c95e +++ b/src/generated/resources/.cache/9fb1092f32d4fcbf9e061ffd718d4ec689c6c95e @@ -1,12 +1,12 @@ -// 1.20.1 2025-11-23T05:44:42.6591809 Recipes -258773ac1397798964811e76a2085e8330253224 data/skilltree/advancements/recipes/misc/workbench.json -8f027c912a6e9ff99ea990597e59be875e21e054 data/skilltree/recipes/armor_defence_bonus.json -40d7d0f0eee8937211f26e51dfea84d93b8466ec data/skilltree/recipes/boots_movement_speed_bonus.json -ac106ea360ca11919cdc9e922caf78c0cda6c206 data/skilltree/recipes/chestplates_toughness_bonus.json -18ea796238c48d6753df9448e18cd8e53d91d163 data/skilltree/recipes/melee_weapon_attack_damage_bonus.json -f8eadfd2e5bd9120873d38b8fb9245166b71425d data/skilltree/recipes/melee_weapon_attack_speed_bonus.json -44063add865a52abab7aab7dbe8ae483eaf868ea data/skilltree/recipes/name_tag_crafting.json -fb891c9bff37b9dc916cdeabd812005dc16c26dc data/skilltree/recipes/saddle_crafting.json -62179e9b4fe0de4191ebcfec33cea5155084f6cd data/skilltree/recipes/shields_defence_bonus.json -fa8f7c7fdf5f27c13d49c560a7bd584e8c287b42 data/skilltree/recipes/shields_thorns_bonus.json -74a0ea07a063f047e4ac913512e7e9b15d6d4b13 data/skilltree/recipes/workbench.json +// 1.21.1 2026-05-18T00:52:15.507138894 Recipes +b086cb56f600af1f93b1147a080a735b3b386dbe data/skilltree/advancement/recipes/misc/workbench.json +9061f942f1b8a6fc6bdd02fbc4d2455f22ce714f data/skilltree/recipe/armor_defence_bonus.json +2e7971d31572e4bd80effdada1f4b800d47b4d75 data/skilltree/recipe/boots_movement_speed_bonus.json +ffc8a2ded8f930353386f26cd515076135335d85 data/skilltree/recipe/chestplates_toughness_bonus.json +a589eb79301713bb79542ff780d2c3e1ebb73c6b data/skilltree/recipe/melee_weapon_attack_damage_bonus.json +1098326d8f3f3b74fd3a37e393696c123ecfa56e data/skilltree/recipe/melee_weapon_attack_speed_bonus.json +41f143ac4e1d2e1f092c3c0fd7dadd504ca01ccd data/skilltree/recipe/name_tag_crafting.json +499be68e01ac84c97641a01b7b9ef305f12fcfed data/skilltree/recipe/saddle_crafting.json +d6464714203854bf6873d27b6889b5c14c347d6d data/skilltree/recipe/shields_defence_bonus.json +ec5ba1337cedbe8c273fe5552064448e20fe2711 data/skilltree/recipe/shields_thorns_bonus.json +534cd9d0a492b3660d923ec14cc94d6412cf98e6 data/skilltree/recipe/workbench.json diff --git a/src/generated/resources/.cache/ac82fa81ecb87290ed4da89250d9328159ba79a7 b/src/generated/resources/.cache/ac82fa81ecb87290ed4da89250d9328159ba79a7 index cca767295..02c28cfbc 100644 --- a/src/generated/resources/.cache/ac82fa81ecb87290ed4da89250d9328159ba79a7 +++ b/src/generated/resources/.cache/ac82fa81ecb87290ed4da89250d9328159ba79a7 @@ -1,5 +1,5 @@ -// 1.20.1 2025-10-31T14:48:06.5457769 Tags for minecraft:item mod id skilltree -62a08dbba8d31146be8d8adf446c9ba6f0544444 data/forge/tags/items/tools.json -b9be800558c6cd2dcd4d1ab3458903f1a58713f5 data/skilltree/tags/items/armors/leather.json -01d06e1c3cd6ee881097875b179c1f9f014e3457 data/skilltree/tags/items/melee_weapon.json -b66e5136e9f0246d08fbf8e91dc9e7d6d2217e00 data/skilltree/tags/items/ranged_weapon.json +// 1.21.1 2026-05-18T00:44:23.028695519 Tags for minecraft:item mod id skilltree +a5300361cba7b13940b80cba01a3950a1b5ed562 data/c/tags/item/tools.json +b9be800558c6cd2dcd4d1ab3458903f1a58713f5 data/skilltree/tags/item/armors/leather.json +e15072206c5b86c4d73384ae7c68817d0b01f862 data/skilltree/tags/item/melee_weapon.json +de75671f136ad29ecb1fee30fc8326bbb0cce33f data/skilltree/tags/item/ranged_weapon.json diff --git a/src/generated/resources/.cache/bbadd38514984779cb458d3b239b2d2db47d89d8 b/src/generated/resources/.cache/bbadd38514984779cb458d3b239b2d2db47d89d8 index 337240071..4028571c7 100644 --- a/src/generated/resources/.cache/bbadd38514984779cb458d3b239b2d2db47d89d8 +++ b/src/generated/resources/.cache/bbadd38514984779cb458d3b239b2d2db47d89d8 @@ -1,2 +1,2 @@ -// 1.20.1 2024-10-26T15:16:13.3550154 Tags for minecraft:damage_type mod id skilltree -83f6b588e0e5b15205f9a88cd92b8c7062b99b4c data/forge/tags/damage_type/is_magic.json +// 1.21.1 2026-05-18T00:43:08.191850096 Tags for minecraft:damage_type mod id skilltree +83f6b588e0e5b15205f9a88cd92b8c7062b99b4c data/neoforge/tags/damage_type/is_magic.json diff --git a/src/generated/resources/.cache/c622617f6fabf890a00b9275cd5f643584a8a2c8 b/src/generated/resources/.cache/c622617f6fabf890a00b9275cd5f643584a8a2c8 deleted file mode 100644 index b952c8f76..000000000 --- a/src/generated/resources/.cache/c622617f6fabf890a00b9275cd5f643584a8a2c8 +++ /dev/null @@ -1,2 +0,0 @@ -// 1.20.1 2025-11-26T06:38:08.6199444 Languages: en_us -626378a11f0cc97fd00fa9a0167fe9782b78f0cc assets/skilltree/lang/en_us.json diff --git a/src/generated/resources/.cache/c6bfbdbd11640551297f5f527cc502a708e6926a b/src/generated/resources/.cache/c6bfbdbd11640551297f5f527cc502a708e6926a index 953370aec..35b05bf26 100644 --- a/src/generated/resources/.cache/c6bfbdbd11640551297f5f527cc502a708e6926a +++ b/src/generated/resources/.cache/c6bfbdbd11640551297f5f527cc502a708e6926a @@ -1 +1 @@ -// 1.20.1 2023-08-05T02:47:20.0481985 Tags for minecraft:block mod id skilltree +// 1.21.1 2026-05-18T00:43:08.192583389 Tags for minecraft:block mod id skilltree diff --git a/src/generated/resources/.cache/cc4a2989348227984ebea88deca578b68e58344e b/src/generated/resources/.cache/cc4a2989348227984ebea88deca578b68e58344e deleted file mode 100644 index 62870dd24..000000000 --- a/src/generated/resources/.cache/cc4a2989348227984ebea88deca578b68e58344e +++ /dev/null @@ -1,2 +0,0 @@ -// 1.20.1 2025-11-26T06:38:08.6209463 Languages: ru_ru -55ac734fd859fa8f19c5649f74e47ef10c60a879 assets/skilltree/lang/ru_ru.json diff --git a/src/generated/resources/assets/skilltree/lang/en_us.json b/src/generated/resources/assets/skilltree/lang/en_us.json index fa256154e..f48d064fc 100644 --- a/src/generated/resources/assets/skilltree/lang/en_us.json +++ b/src/generated/resources/assets/skilltree/lang/en_us.json @@ -107,11 +107,11 @@ "item_condition.skilltree.potion.harmful.plural": "Harmful Potions", "item_condition.skilltree.potion.neutral": "Neutral Potion", "item_condition.skilltree.potion.neutral.plural": "Neutral Potions", + "item_tag.curios:jewelry": "Jewelry", "item_tag.curios:necklace": "Necklace", "item_tag.curios:necklace.plural": "Necklaces", "item_tag.curios:ring": "Ring", "item_tag.curios:ring.plural": "Rings", - "item_tag.forge:curios/jewelry": "Jewelry", "item_tag.skilltree:armors/leather": "Leather Armor", "item_tag.skilltree:armors/leather.plural": "Leather Armor", "key.categories.skilltree": "Passive Skill Tree", diff --git a/src/generated/resources/assets/skilltree/lang/ru_ru.json b/src/generated/resources/assets/skilltree/lang/ru_ru.json index 757cd9230..60a455d7c 100644 --- a/src/generated/resources/assets/skilltree/lang/ru_ru.json +++ b/src/generated/resources/assets/skilltree/lang/ru_ru.json @@ -179,6 +179,11 @@ "item_condition.skilltree.potion.neutral.adjective": "ое Нейтральное Зелье", "item_condition.skilltree.potion.neutral.plural": "Нейтральные Зелья", "item_condition.skilltree.potion.neutral.plural.adjective": "ые Нейтральные Зелья", + "item_tag.curios:jewelry": "Бижутерия", + "item_tag.curios:jewelry.plural": "Бижутерия", + "item_tag.curios:jewelry.plural.adjective": "ая Бижутерия", + "item_tag.curios:jewelry.type": "ая Бижутерия", + "item_tag.curios:jewelry.where": "Бижутерии", "item_tag.curios:necklace": "Ожерелье", "item_tag.curios:necklace.plural": "Ожерелья", "item_tag.curios:necklace.plural.adjective": "ые Ожерелья", @@ -188,11 +193,6 @@ "item_tag.curios:ring.plural.adjective": "ые Кольца", "item_tag.curios:ring.type": "ое Кольцо", "item_tag.curios:ring.where": "Кольцах", - "item_tag.forge:curios/jewelry": "Бижутерия", - "item_tag.forge:curios/jewelry.plural": "Бижутерия", - "item_tag.forge:curios/jewelry.plural.adjective": "ая Бижутерия", - "item_tag.forge:curios/jewelry.type": "ая Бижутерия", - "item_tag.forge:curios/jewelry.where": "Бижутерии", "item_tag.skilltree:armors/leather": "Кожаная броня", "item_tag.skilltree:armors/leather.plural": "Кожаная броня", "key.categories.skilltree": "Древо пассивных умений", diff --git a/src/generated/resources/data/forge/tags/items/tools.json b/src/generated/resources/data/c/tags/item/tools.json similarity index 61% rename from src/generated/resources/data/forge/tags/items/tools.json rename to src/generated/resources/data/c/tags/item/tools.json index 931e27684..679e53c42 100644 --- a/src/generated/resources/data/forge/tags/items/tools.json +++ b/src/generated/resources/data/c/tags/item/tools.json @@ -1,7 +1,7 @@ { "values": [ { - "id": "#forge:tools/knives", + "id": "#c:tools/knives", "required": false } ] diff --git a/src/generated/resources/data/forge/loot_modifiers/global_loot_modifiers.json b/src/generated/resources/data/neoforge/loot_modifiers/global_loot_modifiers.json similarity index 100% rename from src/generated/resources/data/forge/loot_modifiers/global_loot_modifiers.json rename to src/generated/resources/data/neoforge/loot_modifiers/global_loot_modifiers.json diff --git a/src/generated/resources/data/forge/tags/damage_type/is_magic.json b/src/generated/resources/data/neoforge/tags/damage_type/is_magic.json similarity index 100% rename from src/generated/resources/data/forge/tags/damage_type/is_magic.json rename to src/generated/resources/data/neoforge/tags/damage_type/is_magic.json diff --git a/src/generated/resources/data/skilltree/advancements/recipes/misc/workbench.json b/src/generated/resources/data/skilltree/advancement/recipes/misc/workbench.json similarity index 74% rename from src/generated/resources/data/skilltree/advancements/recipes/misc/workbench.json rename to src/generated/resources/data/skilltree/advancement/recipes/misc/workbench.json index 7313e2b94..b5e3d73d7 100644 --- a/src/generated/resources/data/skilltree/advancements/recipes/misc/workbench.json +++ b/src/generated/resources/data/skilltree/advancement/recipes/misc/workbench.json @@ -5,9 +5,7 @@ "conditions": { "items": [ { - "items": [ - "minecraft:smithing_table" - ] + "items": "minecraft:smithing_table" } ] }, @@ -22,14 +20,13 @@ }, "requirements": [ [ - "has_smithing_table", - "has_the_recipe" + "has_the_recipe", + "has_smithing_table" ] ], "rewards": { "recipes": [ "skilltree:workbench" ] - }, - "sends_telemetry_event": false + } } \ No newline at end of file diff --git a/src/generated/resources/data/skilltree/loot_tables/blocks/workbench.json b/src/generated/resources/data/skilltree/loot_table/blocks/workbench.json similarity index 100% rename from src/generated/resources/data/skilltree/loot_tables/blocks/workbench.json rename to src/generated/resources/data/skilltree/loot_table/blocks/workbench.json diff --git a/src/generated/resources/data/skilltree/recipes/armor_defence_bonus.json b/src/generated/resources/data/skilltree/recipe/armor_defence_bonus.json similarity index 71% rename from src/generated/resources/data/skilltree/recipes/armor_defence_bonus.json rename to src/generated/resources/data/skilltree/recipe/armor_defence_bonus.json index b629f7128..cb5c62311 100644 --- a/src/generated/resources/data/skilltree/recipes/armor_defence_bonus.json +++ b/src/generated/resources/data/skilltree/recipe/armor_defence_bonus.json @@ -4,10 +4,11 @@ "type": "skilltree:equipment_type", "equipment_type": "armor" }, + "id": "skilltree:armor_defence_bonus", "ingredients": [ { "ingredient": { - "tag": "forge:ingots/copper" + "tag": "c:ingots/copper" }, "required_amount": 2 } @@ -16,10 +17,10 @@ "type": "skilltree:skill_bonus", "skill_bonus": { "type": "skilltree:attribute", - "amount": 1.0, + "amount": 1, "attribute": "minecraft:generic.armor", - "id": "afbd1a0a-3000-432c-b0ad-e04adb044577", - "name": "Workbench Upgrade", + "id": "skilltree:armor_defence_bonus", + "name": "skilltree:armor_defence_bonus", "operation": 0 } }, diff --git a/src/generated/resources/data/skilltree/recipes/boots_movement_speed_bonus.json b/src/generated/resources/data/skilltree/recipe/boots_movement_speed_bonus.json similarity index 72% rename from src/generated/resources/data/skilltree/recipes/boots_movement_speed_bonus.json rename to src/generated/resources/data/skilltree/recipe/boots_movement_speed_bonus.json index f2d470773..f9483523e 100644 --- a/src/generated/resources/data/skilltree/recipes/boots_movement_speed_bonus.json +++ b/src/generated/resources/data/skilltree/recipe/boots_movement_speed_bonus.json @@ -4,16 +4,17 @@ "type": "skilltree:equipment_type", "equipment_type": "boots" }, + "id": "skilltree:boots_movement_speed_bonus", "ingredients": [ { "ingredient": { - "tag": "forge:leather" + "tag": "c:leathers" }, "required_amount": 4 }, { "ingredient": { - "tag": "forge:nuggets/iron" + "tag": "c:nuggets/iron" }, "required_amount": 3 } @@ -24,8 +25,8 @@ "type": "skilltree:attribute", "amount": 0.15, "attribute": "minecraft:generic.movement_speed", - "id": "7bd455d9-cfb4-45a1-8334-ece7eca1c8bd", - "name": "Workbench Upgrade", + "id": "skilltree:boots_movement_speed_bonus", + "name": "skilltree:boots_movement_speed_bonus", "operation": 1 } }, diff --git a/src/generated/resources/data/skilltree/recipes/chestplates_toughness_bonus.json b/src/generated/resources/data/skilltree/recipe/chestplates_toughness_bonus.json similarity index 69% rename from src/generated/resources/data/skilltree/recipes/chestplates_toughness_bonus.json rename to src/generated/resources/data/skilltree/recipe/chestplates_toughness_bonus.json index f38692a42..69e0180d7 100644 --- a/src/generated/resources/data/skilltree/recipes/chestplates_toughness_bonus.json +++ b/src/generated/resources/data/skilltree/recipe/chestplates_toughness_bonus.json @@ -4,16 +4,17 @@ "type": "skilltree:equipment_type", "equipment_type": "chestplate" }, + "id": "skilltree:chestplates_toughness_bonus", "ingredients": [ { "ingredient": { - "tag": "forge:gems/diamond" + "tag": "c:gems/diamond" }, "required_amount": 3 }, { "ingredient": { - "tag": "forge:ores/netherite_scrap" + "tag": "c:ores/netherite_scrap" }, "required_amount": 2 } @@ -22,10 +23,10 @@ "type": "skilltree:skill_bonus", "skill_bonus": { "type": "skilltree:attribute", - "amount": 1.0, + "amount": 1, "attribute": "minecraft:generic.armor_toughness", - "id": "2b3db227-661d-47bb-8a0d-3f9cda8e4551", - "name": "Workbench Upgrade", + "id": "skilltree:chestplates_toughness_bonus", + "name": "skilltree:chestplates_toughness_bonus", "operation": 0 } }, diff --git a/src/generated/resources/data/skilltree/recipes/melee_weapon_attack_damage_bonus.json b/src/generated/resources/data/skilltree/recipe/melee_weapon_attack_damage_bonus.json similarity index 68% rename from src/generated/resources/data/skilltree/recipes/melee_weapon_attack_damage_bonus.json rename to src/generated/resources/data/skilltree/recipe/melee_weapon_attack_damage_bonus.json index 07b6580c2..4b2d2bcef 100644 --- a/src/generated/resources/data/skilltree/recipes/melee_weapon_attack_damage_bonus.json +++ b/src/generated/resources/data/skilltree/recipe/melee_weapon_attack_damage_bonus.json @@ -4,10 +4,11 @@ "type": "skilltree:equipment_type", "equipment_type": "melee_weapon" }, + "id": "skilltree:melee_weapon_attack_damage_bonus", "ingredients": [ { "ingredient": { - "tag": "forge:gems/diamond" + "tag": "c:gems/diamond" }, "required_amount": 1 } @@ -16,10 +17,10 @@ "type": "skilltree:skill_bonus", "skill_bonus": { "type": "skilltree:attribute", - "amount": 1.0, + "amount": 1, "attribute": "minecraft:generic.attack_damage", - "id": "40a1542a-fdc7-4dcf-bc9c-ac96501b75df", - "name": "Workbench Upgrade", + "id": "skilltree:melee_weapon_attack_damage_bonus", + "name": "skilltree:melee_weapon_attack_damage_bonus", "operation": 0 } }, diff --git a/src/generated/resources/data/skilltree/recipes/melee_weapon_attack_speed_bonus.json b/src/generated/resources/data/skilltree/recipe/melee_weapon_attack_speed_bonus.json similarity index 71% rename from src/generated/resources/data/skilltree/recipes/melee_weapon_attack_speed_bonus.json rename to src/generated/resources/data/skilltree/recipe/melee_weapon_attack_speed_bonus.json index d0986ad12..579ebe189 100644 --- a/src/generated/resources/data/skilltree/recipes/melee_weapon_attack_speed_bonus.json +++ b/src/generated/resources/data/skilltree/recipe/melee_weapon_attack_speed_bonus.json @@ -4,18 +4,19 @@ "type": "skilltree:equipment_type", "equipment_type": "melee_weapon" }, + "id": "skilltree:melee_weapon_attack_speed_bonus", "ingredients": [ { "ingredient": { - "tag": "forge:nuggets/iron" + "tag": "c:leathers" }, - "required_amount": 5 + "required_amount": 3 }, { "ingredient": { - "tag": "forge:leather" + "tag": "c:nuggets/iron" }, - "required_amount": 3 + "required_amount": 5 } ], "item_bonus": { @@ -24,8 +25,8 @@ "type": "skilltree:attribute", "amount": 0.1, "attribute": "minecraft:generic.attack_speed", - "id": "1578f12c-1951-48ef-8d96-8ac08332036b", - "name": "Workbench Upgrade", + "id": "skilltree:melee_weapon_attack_speed_bonus", + "name": "skilltree:melee_weapon_attack_speed_bonus", "operation": 1 } }, diff --git a/src/generated/resources/data/skilltree/recipes/name_tag_crafting.json b/src/generated/resources/data/skilltree/recipe/name_tag_crafting.json similarity index 71% rename from src/generated/resources/data/skilltree/recipes/name_tag_crafting.json rename to src/generated/resources/data/skilltree/recipe/name_tag_crafting.json index ccfd11e4b..30f047851 100644 --- a/src/generated/resources/data/skilltree/recipes/name_tag_crafting.json +++ b/src/generated/resources/data/skilltree/recipe/name_tag_crafting.json @@ -1,5 +1,6 @@ { "type": "skilltree:workbench_crafting", + "id": "skilltree:name_tag_crafting", "ingredients": [ { "ingredient": { @@ -9,19 +10,20 @@ }, { "ingredient": { - "tag": "forge:ingots/iron" + "tag": "c:nuggets/iron" }, - "required_amount": 1 + "required_amount": 2 }, { "ingredient": { - "tag": "forge:nuggets/iron" + "tag": "c:ingots/iron" }, - "required_amount": 2 + "required_amount": 1 } ], "requires_passive_skill": true, "result": { - "item": "minecraft:name_tag" + "count": 1, + "id": "minecraft:name_tag" } } \ No newline at end of file diff --git a/src/generated/resources/data/skilltree/recipes/saddle_crafting.json b/src/generated/resources/data/skilltree/recipe/saddle_crafting.json similarity index 65% rename from src/generated/resources/data/skilltree/recipes/saddle_crafting.json rename to src/generated/resources/data/skilltree/recipe/saddle_crafting.json index 84352cc80..28e8cfa6f 100644 --- a/src/generated/resources/data/skilltree/recipes/saddle_crafting.json +++ b/src/generated/resources/data/skilltree/recipe/saddle_crafting.json @@ -1,27 +1,29 @@ { "type": "skilltree:workbench_crafting", + "id": "skilltree:saddle_crafting", "ingredients": [ { "ingredient": { - "tag": "forge:ingots/iron" + "tag": "c:leathers" }, - "required_amount": 2 + "required_amount": 8 }, { "ingredient": { - "tag": "forge:leather" + "tag": "c:nuggets/iron" }, - "required_amount": 8 + "required_amount": 4 }, { "ingredient": { - "tag": "forge:nuggets/iron" + "tag": "c:ingots/iron" }, - "required_amount": 4 + "required_amount": 2 } ], "requires_passive_skill": true, "result": { - "item": "minecraft:saddle" + "count": 1, + "id": "minecraft:saddle" } } \ No newline at end of file diff --git a/src/generated/resources/data/skilltree/recipes/shields_defence_bonus.json b/src/generated/resources/data/skilltree/recipe/shields_defence_bonus.json similarity index 71% rename from src/generated/resources/data/skilltree/recipes/shields_defence_bonus.json rename to src/generated/resources/data/skilltree/recipe/shields_defence_bonus.json index ec6d7c3bd..8718e79ef 100644 --- a/src/generated/resources/data/skilltree/recipes/shields_defence_bonus.json +++ b/src/generated/resources/data/skilltree/recipe/shields_defence_bonus.json @@ -4,10 +4,11 @@ "type": "skilltree:equipment_type", "equipment_type": "shield" }, + "id": "skilltree:shields_defence_bonus", "ingredients": [ { "ingredient": { - "tag": "forge:ingots/copper" + "tag": "c:ingots/copper" }, "required_amount": 2 } @@ -16,10 +17,10 @@ "type": "skilltree:skill_bonus", "skill_bonus": { "type": "skilltree:attribute", - "amount": 2.0, + "amount": 2, "attribute": "minecraft:generic.armor", - "id": "b89916e4-d2bf-4cc9-ad5b-1f48742cb607", - "name": "Workbench Upgrade", + "id": "skilltree:shields_defence_bonus", + "name": "skilltree:shields_defence_bonus", "operation": 0 } }, diff --git a/src/generated/resources/data/skilltree/recipes/shields_thorns_bonus.json b/src/generated/resources/data/skilltree/recipe/shields_thorns_bonus.json similarity index 84% rename from src/generated/resources/data/skilltree/recipes/shields_thorns_bonus.json rename to src/generated/resources/data/skilltree/recipe/shields_thorns_bonus.json index 968e566f6..1554d8804 100644 --- a/src/generated/resources/data/skilltree/recipes/shields_thorns_bonus.json +++ b/src/generated/resources/data/skilltree/recipe/shields_thorns_bonus.json @@ -4,18 +4,19 @@ "type": "skilltree:equipment_type", "equipment_type": "shield" }, + "id": "skilltree:shields_thorns_bonus", "ingredients": [ { "ingredient": { - "tag": "forge:nuggets/iron" + "tag": "c:ingots/iron" }, - "required_amount": 9 + "required_amount": 5 }, { "ingredient": { - "tag": "forge:ingots/iron" + "tag": "c:nuggets/iron" }, - "required_amount": 5 + "required_amount": 9 } ], "item_bonus": { diff --git a/src/generated/resources/data/skilltree/recipes/workbench.json b/src/generated/resources/data/skilltree/recipe/workbench.json similarity index 60% rename from src/generated/resources/data/skilltree/recipes/workbench.json rename to src/generated/resources/data/skilltree/recipe/workbench.json index d9b2b39cb..e5dc10d53 100644 --- a/src/generated/resources/data/skilltree/recipes/workbench.json +++ b/src/generated/resources/data/skilltree/recipe/workbench.json @@ -6,13 +6,13 @@ "item": "minecraft:smithing_table" }, "C": { - "tag": "forge:ingots/copper" + "tag": "c:ingots/copper" }, "G": { - "tag": "forge:ingots/gold" + "tag": "c:ingots/gold" }, "I": { - "tag": "forge:ingots/iron" + "tag": "c:ingots/iron" } }, "pattern": [ @@ -21,7 +21,7 @@ "CCC" ], "result": { - "item": "skilltree:workbench" - }, - "show_notification": true + "count": 1, + "id": "skilltree:workbench" + } } \ No newline at end of file diff --git a/src/generated/resources/data/skilltree/tags/items/armors/leather.json b/src/generated/resources/data/skilltree/tags/item/armors/leather.json similarity index 100% rename from src/generated/resources/data/skilltree/tags/items/armors/leather.json rename to src/generated/resources/data/skilltree/tags/item/armors/leather.json diff --git a/src/generated/resources/data/skilltree/tags/items/melee_weapon.json b/src/generated/resources/data/skilltree/tags/item/melee_weapon.json similarity index 71% rename from src/generated/resources/data/skilltree/tags/items/melee_weapon.json rename to src/generated/resources/data/skilltree/tags/item/melee_weapon.json index d32b3b3cb..ef44b05b4 100644 --- a/src/generated/resources/data/skilltree/tags/items/melee_weapon.json +++ b/src/generated/resources/data/skilltree/tags/item/melee_weapon.json @@ -2,6 +2,6 @@ "values": [ "#minecraft:swords", "#minecraft:axes", - "#forge:tools/tridents" + "#c:tools/spear" ] } \ No newline at end of file diff --git a/src/generated/resources/data/skilltree/tags/item/ranged_weapon.json b/src/generated/resources/data/skilltree/tags/item/ranged_weapon.json new file mode 100644 index 000000000..23f0816a5 --- /dev/null +++ b/src/generated/resources/data/skilltree/tags/item/ranged_weapon.json @@ -0,0 +1,6 @@ +{ + "values": [ + "#c:tools/bow", + "#c:tools/crossbow" + ] +} \ No newline at end of file diff --git a/src/generated/resources/data/skilltree/tags/items/ranged_weapon.json b/src/generated/resources/data/skilltree/tags/items/ranged_weapon.json deleted file mode 100644 index fc931e62c..000000000 --- a/src/generated/resources/data/skilltree/tags/items/ranged_weapon.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "values": [ - "#forge:tools/bows", - "#forge:tools/crossbows" - ] -} \ No newline at end of file diff --git a/src/main/java/daripher/skilltree/SkillTreeMod.java b/src/main/java/daripher/skilltree/SkillTreeMod.java index 0c31718b9..9b4a85146 100644 --- a/src/main/java/daripher/skilltree/SkillTreeMod.java +++ b/src/main/java/daripher/skilltree/SkillTreeMod.java @@ -6,12 +6,11 @@ import daripher.skilltree.config.ClientConfig; import daripher.skilltree.config.ServerConfig; import daripher.skilltree.init.*; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.fml.ModLoadingContext; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.config.ModConfig; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.ModList; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.config.ModConfig; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -20,14 +19,15 @@ public class SkillTreeMod { public static final String MOD_ID = "skilltree"; public static final Logger LOGGER = LogManager.getLogger(SkillTreeMod.MOD_ID); - public SkillTreeMod() { - registerModRegistries(); - registerConfigs(); + public SkillTreeMod(IEventBus eventBus, ModContainer modContainer) { + registerModRegistries(eventBus); + registerConfigs(modContainer); registerCompatibilities(); } - private static void registerModRegistries() { - IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus(); + private static void registerModRegistries(IEventBus eventBus) { + PSTRegistries.bootstrap(); + PSTAttachments.REGISTRY.register(eventBus); PSTItems.REGISTRY.register(eventBus); PSTMobEffects.REGISTRY.register(eventBus); PSTCreativeTabs.REGISTRY.register(eventBus); @@ -49,9 +49,9 @@ private static void registerModRegistries() { PSTRecipeTypes.REGISTRY.register(eventBus); } - private static void registerConfigs() { - ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, ServerConfig.SPEC); - ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ClientConfig.SPEC); + private static void registerConfigs(ModContainer modContainer) { + modContainer.registerConfig(ModConfig.Type.SERVER, ServerConfig.SPEC); + modContainer.registerConfig(ModConfig.Type.CLIENT, ClientConfig.SPEC); } private static void registerCompatibilities() { diff --git a/src/main/java/daripher/skilltree/attribute/AttributesHelper.java b/src/main/java/daripher/skilltree/attribute/AttributesHelper.java index 0a18a33b8..997202898 100644 --- a/src/main/java/daripher/skilltree/attribute/AttributesHelper.java +++ b/src/main/java/daripher/skilltree/attribute/AttributesHelper.java @@ -2,17 +2,17 @@ import java.util.Collection; import java.util.Objects; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.ai.attributes.Attribute; -import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.world.entity.player.Player; +import daripher.skilltree.util.ForgeRegistries; public class AttributesHelper { public static Collection attributeList() { //noinspection deprecation return ForgeRegistries.ATTRIBUTES.getValues().stream() - .filter(ForgeHooks.getAttributesView().get(EntityType.PLAYER)::hasAttribute) + .filter(attribute -> Player.createAttributes().build().hasAttribute(BuiltInRegistries.ATTRIBUTE.wrapAsHolder(attribute))) .toList(); } diff --git a/src/main/java/daripher/skilltree/block/WorkbenchBlock.java b/src/main/java/daripher/skilltree/block/WorkbenchBlock.java index 99efa1afa..9862f5842 100644 --- a/src/main/java/daripher/skilltree/block/WorkbenchBlock.java +++ b/src/main/java/daripher/skilltree/block/WorkbenchBlock.java @@ -5,10 +5,12 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.ContainerLevelAccess; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; @@ -34,19 +36,37 @@ public WorkbenchBlock() { @SuppressWarnings("deprecation") @Override - public @NotNull InteractionResult use( + protected @NotNull ItemInteractionResult useItemOn( + @NotNull ItemStack stack, @NotNull BlockState blockState, Level level, @NotNull BlockPos blockPos, @NotNull Player player, @NotNull InteractionHand interactionHand, @NotNull BlockHitResult blockHitResult) { + openWorkbench(blockState, level, blockPos, player); + return ItemInteractionResult.sidedSuccess(level.isClientSide); + } + + @SuppressWarnings("deprecation") + @Override + protected @NotNull InteractionResult useWithoutItem( + @NotNull BlockState blockState, + Level level, + @NotNull BlockPos blockPos, + @NotNull Player player, + @NotNull BlockHitResult blockHitResult) { + openWorkbench(blockState, level, blockPos, player); + return InteractionResult.sidedSuccess(level.isClientSide); + } + + private void openWorkbench( + BlockState blockState, Level level, BlockPos blockPos, Player player) { if (level.isClientSide) { - return InteractionResult.SUCCESS; + return; } else { player.openMenu(blockState.getMenuProvider(level, blockPos)); // add custom stat awarded for block usage? - return InteractionResult.CONSUME; } } diff --git a/src/main/java/daripher/skilltree/capability/skill/IPlayerSkills.java b/src/main/java/daripher/skilltree/capability/skill/IPlayerSkills.java index 0c1a8a5d7..9b749e5a0 100644 --- a/src/main/java/daripher/skilltree/capability/skill/IPlayerSkills.java +++ b/src/main/java/daripher/skilltree/capability/skill/IPlayerSkills.java @@ -4,10 +4,8 @@ import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerPlayer; -import net.minecraftforge.common.capabilities.AutoRegisterCapability; -import net.minecraftforge.common.util.INBTSerializable; +import net.neoforged.neoforge.common.util.INBTSerializable; -@AutoRegisterCapability public interface IPlayerSkills extends INBTSerializable { NonNullList getPlayerSkills(); diff --git a/src/main/java/daripher/skilltree/capability/skill/PlayerSkills.java b/src/main/java/daripher/skilltree/capability/skill/PlayerSkills.java index 885cc06b3..ceeefc50e 100644 --- a/src/main/java/daripher/skilltree/capability/skill/PlayerSkills.java +++ b/src/main/java/daripher/skilltree/capability/skill/PlayerSkills.java @@ -4,6 +4,7 @@ import daripher.skilltree.skill.PassiveSkill; import java.util.UUID; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -66,7 +67,7 @@ public void resetTree(ServerPlayer player) { } @Override - public CompoundTag serializeNBT() { + public CompoundTag serializeNBT(HolderLookup.Provider provider) { CompoundTag tag = new CompoundTag(); tag.putUUID("TreeVersion", TREE_VERSION); tag.putInt("Points", skillPoints); @@ -78,7 +79,7 @@ public CompoundTag serializeNBT() { } @Override - public void deserializeNBT(CompoundTag tag) { + public void deserializeNBT(HolderLookup.Provider provider, CompoundTag tag) { skills.clear(); UUID treeVersion = tag.hasUUID("TreeVersion") ? tag.getUUID("TreeVersion") : null; skillPoints = tag.getInt("Points"); @@ -89,7 +90,7 @@ public void deserializeNBT(CompoundTag tag) { return; } for (Tag skillTag : skillsTag) { - ResourceLocation skillId = new ResourceLocation(skillTag.getAsString()); + ResourceLocation skillId = ResourceLocation.parse(skillTag.getAsString()); PassiveSkill passiveSkill = SkillsReloader.getSkillById(skillId); if (passiveSkill == null || passiveSkill.isInvalid()) { skills.clear(); diff --git a/src/main/java/daripher/skilltree/capability/skill/PlayerSkillsProvider.java b/src/main/java/daripher/skilltree/capability/skill/PlayerSkillsProvider.java index 9555ebc27..5e1195135 100644 --- a/src/main/java/daripher/skilltree/capability/skill/PlayerSkillsProvider.java +++ b/src/main/java/daripher/skilltree/capability/skill/PlayerSkillsProvider.java @@ -1,64 +1,38 @@ package daripher.skilltree.capability.skill; import daripher.skilltree.SkillTreeMod; -import daripher.skilltree.network.NetworkDispatcher; +import daripher.skilltree.init.PSTAttachments; import daripher.skilltree.network.message.SyncPlayerSkillsMessage; import daripher.skilltree.network.message.SyncServerDataMessage; import net.minecraft.ChatFormatting; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.CapabilityManager; -import net.minecraftforge.common.capabilities.CapabilityToken; -import net.minecraftforge.common.capabilities.ICapabilitySerializable; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.event.AttachCapabilitiesEvent; -import net.minecraftforge.event.entity.EntityJoinLevelEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.event.entity.player.PlayerEvent.PlayerLoggedInEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent.PlayerLoggedInEvent; +import net.neoforged.neoforge.network.PacketDistributor; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID) -public class PlayerSkillsProvider implements ICapabilitySerializable { - private static final ResourceLocation CAPABILITY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "player_skills"); - private static final Capability CAPABILITY = - CapabilityManager.get(new CapabilityToken<>() {}); - private final LazyOptional optionalCapability = LazyOptional.of(PlayerSkills::new); - - @SubscribeEvent - public static void attachCapability(AttachCapabilitiesEvent event) { - if (!(event.getObject() instanceof Player)) return; - PlayerSkillsProvider provider = new PlayerSkillsProvider(); - event.addCapability(CAPABILITY_ID, provider); - } - +public class PlayerSkillsProvider { @SubscribeEvent - public static void persistThroughDeath(PlayerEvent.Clone event) { + public static void copySkills(PlayerEvent.Clone event) { if (event.getEntity().level().isClientSide) return; - event.getOriginal().reviveCaps(); - IPlayerSkills originalData = get(event.getOriginal()); - IPlayerSkills cloneData = get(event.getEntity()); - cloneData.deserializeNBT(originalData.serializeNBT()); - event.getOriginal().invalidateCaps(); + PlayerSkills originalData = get(event.getOriginal()); + PlayerSkills cloneData = get(event.getEntity()); + cloneData.deserializeNBT( + event.getEntity().level().registryAccess(), + originalData.serializeNBT(event.getOriginal().level().registryAccess())); } @SubscribeEvent - public static void syncSkills(PlayerLoggedInEvent event) { + public static void syncServerData(PlayerLoggedInEvent event) { if (event.getEntity().level().isClientSide) return; - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> (ServerPlayer) event.getEntity()), - new SyncServerDataMessage()); + sendServerData((ServerPlayer) event.getEntity()); } @SubscribeEvent(priority = EventPriority.LOWEST) @@ -82,31 +56,22 @@ public static void sendTreeResetMessage(EntityJoinLevelEvent event) { @SubscribeEvent public static void syncPlayerSkills(EntityJoinLevelEvent event) { if (!(event.getEntity() instanceof ServerPlayer player)) return; - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> player), new SyncPlayerSkillsMessage(player)); + sendPlayerSkills(player); } - public static @NotNull IPlayerSkills get(Player player) { - return player.getCapability(CAPABILITY).orElseThrow(NullPointerException::new); + public static void sendServerData(ServerPlayer player) { + PacketDistributor.sendToPlayer(player, new SyncServerDataMessage()); } - public static boolean hasSkills(@NotNull Player player) { - return player.getCapability(CAPABILITY).isPresent(); - } - - @Override - public @NotNull LazyOptional getCapability( - @NotNull Capability cap, @Nullable Direction side) { - return cap == CAPABILITY ? optionalCapability.cast() : LazyOptional.empty(); + public static void sendPlayerSkills(ServerPlayer player) { + PacketDistributor.sendToPlayer(player, new SyncPlayerSkillsMessage(player)); } - @Override - public CompoundTag serializeNBT() { - return optionalCapability.orElseThrow(NullPointerException::new).serializeNBT(); + public static @NotNull PlayerSkills get(Player player) { + return player.getData(PSTAttachments.PLAYER_SKILLS.get()); } - @Override - public void deserializeNBT(CompoundTag compoundTag) { - optionalCapability.orElseThrow(NullPointerException::new).deserializeNBT(compoundTag); + public static boolean hasSkills(@NotNull Player player) { + return player.hasData(PSTAttachments.PLAYER_SKILLS.get()); } } diff --git a/src/main/java/daripher/skilltree/client/command/PSTClientCommands.java b/src/main/java/daripher/skilltree/client/command/PSTClientCommands.java index baed82774..8b2767584 100644 --- a/src/main/java/daripher/skilltree/client/command/PSTClientCommands.java +++ b/src/main/java/daripher/skilltree/client/command/PSTClientCommands.java @@ -14,11 +14,11 @@ import net.minecraft.commands.Commands; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RegisterClientCommandsEvent; -import net.minecraftforge.event.TickEvent.ClientTickEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.RegisterClientCommandsEvent; import org.jetbrains.annotations.NotNull; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID, value = Dist.CLIENT) @@ -51,7 +51,7 @@ public static void registerCommands(RegisterClientCommandsEvent event) { } @SubscribeEvent - public static void delayedCommandExecution(ClientTickEvent event) { + public static void delayedCommandExecution(ClientTickEvent.Post event) { if (timer > 0) { timer--; return; @@ -64,7 +64,7 @@ public static void delayedCommandExecution(ClientTickEvent event) { private static int displaySkillTreeEditor(CommandContext ctx) { String treeIdArg = ctx.getArgument("treeId", String.class).toLowerCase(); - PSTClientCommands.tree_to_display = new ResourceLocation(treeIdArg); + PSTClientCommands.tree_to_display = ResourceLocation.parse(treeIdArg); PSTClientCommands.timer = 1; return 1; } diff --git a/src/main/java/daripher/skilltree/client/data/SkillTexturesData.java b/src/main/java/daripher/skilltree/client/data/SkillTexturesData.java index 28ddfde82..44af8a787 100644 --- a/src/main/java/daripher/skilltree/client/data/SkillTexturesData.java +++ b/src/main/java/daripher/skilltree/client/data/SkillTexturesData.java @@ -5,16 +5,16 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -@Mod.EventBusSubscriber( +@EventBusSubscriber( modid = SkillTreeMod.MOD_ID, - bus = Mod.EventBusSubscriber.Bus.MOD, + bus = EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public class SkillTexturesData implements ResourceManagerReloadListener { private static final Map> FOLDER_TO_TEXTURES = new HashMap<>(); diff --git a/src/main/java/daripher/skilltree/client/data/SkillTreeEditorData.java b/src/main/java/daripher/skilltree/client/data/SkillTreeEditorData.java index c55e6cbe5..00b0fccdb 100644 --- a/src/main/java/daripher/skilltree/client/data/SkillTreeEditorData.java +++ b/src/main/java/daripher/skilltree/client/data/SkillTreeEditorData.java @@ -16,7 +16,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.fml.loading.FMLPaths; +import net.neoforged.fml.loading.FMLPaths; public class SkillTreeEditorData { private static final Map EDITOR_PASSIVE_SKILLS = new HashMap<>(); @@ -244,7 +244,7 @@ public static Set getEditorTreesIDs() { String skillTreeFileName = skillTreeFile.getName(); if (!skillTreeFileName.endsWith(".json")) continue; String skillTreeName = skillTreeFileName.substring(0, skillTreeFileName.lastIndexOf('.')); - EDITOR_TREES_IDS.add(new ResourceLocation(namespace, skillTreeName)); + EDITOR_TREES_IDS.add(ResourceLocation.fromNamespaceAndPath(namespace, skillTreeName)); } } loadedIDs = true; diff --git a/src/main/java/daripher/skilltree/client/init/PSTKeybinds.java b/src/main/java/daripher/skilltree/client/init/PSTKeybinds.java index 8b50fde95..699fd0bea 100644 --- a/src/main/java/daripher/skilltree/client/init/PSTKeybinds.java +++ b/src/main/java/daripher/skilltree/client/init/PSTKeybinds.java @@ -11,12 +11,12 @@ import net.minecraft.client.KeyMapping; import net.minecraft.client.Minecraft; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.client.event.RegisterKeyMappingsEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.neoforge.client.event.InputEvent; +import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.EventBusSubscriber.Bus; import org.lwjgl.glfw.GLFW; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Bus.MOD, value = Dist.CLIENT) diff --git a/src/main/java/daripher/skilltree/client/network/ClientNetworkPayloadHandlers.java b/src/main/java/daripher/skilltree/client/network/ClientNetworkPayloadHandlers.java new file mode 100644 index 000000000..6cff7b0fc --- /dev/null +++ b/src/main/java/daripher/skilltree/client/network/ClientNetworkPayloadHandlers.java @@ -0,0 +1,14 @@ +package daripher.skilltree.client.network; + +import daripher.skilltree.client.screen.SkillTreeScreen; +import net.minecraft.client.Minecraft; + +public class ClientNetworkPayloadHandlers { + public static void refreshSkillTreeScreen(int skillPoints) { + Minecraft minecraft = Minecraft.getInstance(); + if (minecraft.screen instanceof SkillTreeScreen screen) { + screen.updateSkillPoints(skillPoints); + screen.init(); + } + } +} diff --git a/src/main/java/daripher/skilltree/client/screen/ScreenHelper.java b/src/main/java/daripher/skilltree/client/screen/ScreenHelper.java index 2adb7aedc..d03caa026 100644 --- a/src/main/java/daripher/skilltree/client/screen/ScreenHelper.java +++ b/src/main/java/daripher/skilltree/client/screen/ScreenHelper.java @@ -122,7 +122,7 @@ public static void renderGatewayConnection( float zoom, float animation) { ResourceLocation texture = - new ResourceLocation("skilltree:textures/screen/long_connection.png"); + ResourceLocation.parse("skilltree:textures/screen/long_connection.png"); graphics.pose().pushPose(); SkillButton button1 = connection.getFirstButton(); SkillButton button2 = connection.getSecondButton(); @@ -145,7 +145,7 @@ public static void renderOneWayConnection( float zoom, float animation) { ResourceLocation texture = - new ResourceLocation("skilltree:textures/screen/one_way_connection.png"); + ResourceLocation.parse("skilltree:textures/screen/one_way_connection.png"); graphics.pose().pushPose(); SkillButton button1 = connection.getFirstButton(); SkillButton button2 = connection.getSecondButton(); @@ -163,7 +163,7 @@ public static void renderOneWayConnection( public static void renderConnection( GuiGraphics graphics, SkillConnection connection, float zoom, float animation) { ResourceLocation texture = - new ResourceLocation("skilltree:textures/screen/direct_connection.png"); + ResourceLocation.parse("skilltree:textures/screen/direct_connection.png"); graphics.pose().pushPose(); SkillButton button1 = connection.getFirstButton(); SkillButton button2 = connection.getSecondButton(); diff --git a/src/main/java/daripher/skilltree/client/screen/SkillTreeEditorScreen.java b/src/main/java/daripher/skilltree/client/screen/SkillTreeEditorScreen.java index 95142e66d..ccf0695fe 100644 --- a/src/main/java/daripher/skilltree/client/screen/SkillTreeEditorScreen.java +++ b/src/main/java/daripher/skilltree/client/screen/SkillTreeEditorScreen.java @@ -12,7 +12,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.achievement.StatsUpdateListener; +import daripher.skilltree.client.screen.StatsUpdateListener; import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ServerboundClientCommandPacket; @@ -91,7 +91,7 @@ private void calculateMaxScroll() { @Override public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { - renderBackground(graphics); + renderBackground(graphics, mouseX, mouseY, partialTick); skillButtons.render(graphics, mouseX, mouseY, partialTick); renderOverlay(graphics); editorWidgets.render(graphics, mouseX, mouseY, partialTick); @@ -105,9 +105,9 @@ public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float } private void createBlankSkill() { - ResourceLocation background = new ResourceLocation(SkillTreeMod.MOD_ID, "textures/icons/background/lesser.png"); - ResourceLocation icon = new ResourceLocation(SkillTreeMod.MOD_ID, "textures/icons/void.png"); - ResourceLocation border = new ResourceLocation(SkillTreeMod.MOD_ID, "textures/tooltip/lesser.png"); + ResourceLocation background = ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/icons/background/lesser.png"); + ResourceLocation icon = ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/icons/void.png"); + ResourceLocation border = ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/tooltip/lesser.png"); ResourceLocation skillId = SkillNodeEditor.createNewSkillId(skillTree.getId()); PassiveSkill skill = new PassiveSkill(skillId, 16, background, icon, border, false); skill.setPosition(0, 0); @@ -134,15 +134,15 @@ public void tick() { } private void renderOverlay(GuiGraphics graphics) { - ResourceLocation texture = new ResourceLocation("skilltree:textures/screen/skill_tree_overlay.png"); + ResourceLocation texture = ResourceLocation.parse("skilltree:textures/screen/skill_tree_overlay.png"); RenderSystem.enableBlend(); graphics.blit(texture, 0, 0, 0, 0F, 0F, width, height, width, height); RenderSystem.disableBlend(); } @Override - public void renderBackground(GuiGraphics graphics) { - ResourceLocation texture = new ResourceLocation("skilltree:textures/screen/skill_tree_background.png"); + public void renderBackground(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { + ResourceLocation texture = ResourceLocation.parse("skilltree:textures/screen/skill_tree_background.png"); PoseStack poseStack = graphics.pose(); poseStack.pushPose(); poseStack.translate(skillButtons.getScrollX() / 3F, skillButtons.getScrollY() / 3F, 0); @@ -162,8 +162,8 @@ public boolean mouseReleased(double mouseX, double mouseY, int button) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double amount) { - return editorWidgets.mouseScrolled(mouseX, mouseY, amount) || skillButtons.mouseScrolled(mouseX, mouseY, amount); + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return editorWidgets.mouseScrolled(mouseX, mouseY, scrollX, scrollY) || skillButtons.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } @Override diff --git a/src/main/java/daripher/skilltree/client/screen/SkillTreeScreen.java b/src/main/java/daripher/skilltree/client/screen/SkillTreeScreen.java index db41a5bfb..edb8b35fd 100644 --- a/src/main/java/daripher/skilltree/client/screen/SkillTreeScreen.java +++ b/src/main/java/daripher/skilltree/client/screen/SkillTreeScreen.java @@ -15,7 +15,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.achievement.StatsUpdateListener; +import daripher.skilltree.client.screen.StatsUpdateListener; import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.player.LocalPlayer; import net.minecraft.network.chat.Component; @@ -98,7 +98,7 @@ private void calculateMaxScroll() { @Override public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { renderAnimation += partialTick; - renderBackground(graphics); + renderBackground(graphics, mouseX, mouseY, partialTick); skillButtons.render(graphics, mouseX, mouseY, partialTick); renderOverlay(graphics); skillTreeWidgets.render(graphics, mouseX, mouseY, partialTick); @@ -150,16 +150,16 @@ public boolean charTyped(char character, int keyCode) { private void renderOverlay(GuiGraphics graphics) { ResourceLocation texture = - new ResourceLocation("skilltree:textures/screen/skill_tree_overlay.png"); + ResourceLocation.parse("skilltree:textures/screen/skill_tree_overlay.png"); RenderSystem.enableBlend(); graphics.blit(texture, 0, 0, 0, 0F, 0F, width, height, width, height); RenderSystem.disableBlend(); } @Override - public void renderBackground(GuiGraphics graphics) { + public void renderBackground(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { ResourceLocation texture = - new ResourceLocation("skilltree:textures/screen/skill_tree_background.png"); + ResourceLocation.parse("skilltree:textures/screen/skill_tree_background.png"); PoseStack poseStack = graphics.pose(); poseStack.pushPose(); float x = skillButtons.getScrollX(); @@ -182,8 +182,8 @@ public boolean mouseDragged( } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double amount) { - return skillButtons.mouseScrolled(mouseX, mouseY, amount); + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return skillButtons.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } private @Nonnull LocalPlayer getLocalPlayer() { diff --git a/src/main/java/daripher/skilltree/client/screen/SkillTreeSelectionScreen.java b/src/main/java/daripher/skilltree/client/screen/SkillTreeSelectionScreen.java index 3a8724810..1098603b4 100644 --- a/src/main/java/daripher/skilltree/client/screen/SkillTreeSelectionScreen.java +++ b/src/main/java/daripher/skilltree/client/screen/SkillTreeSelectionScreen.java @@ -49,7 +49,7 @@ private static List getNonEmptySkillTrees() { @Override public void render(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) { - renderBackground(guiGraphics); + renderBackground(guiGraphics, mouseX, mouseY, partialTick); super.render(guiGraphics, mouseX, mouseY, partialTick); for (Renderable widget : renderables) { if (!(widget instanceof SkillTreeSelectionButton button)) continue; @@ -59,9 +59,9 @@ public void render(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, flo } @Override - public void renderBackground(GuiGraphics guiGraphics) { + public void renderBackground(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) { ResourceLocation texture = - new ResourceLocation("skilltree:textures/screen/skill_tree_background.png"); + ResourceLocation.parse("skilltree:textures/screen/skill_tree_background.png"); int size = SkillTreeScreen.BACKGROUND_SIZE; guiGraphics.blit( texture, (width - size) / 2, (height - size) / 2, 0, 0F, 0F, size, size, size, size); diff --git a/src/main/java/daripher/skilltree/client/screen/StatsUpdateListener.java b/src/main/java/daripher/skilltree/client/screen/StatsUpdateListener.java new file mode 100644 index 000000000..89ed6f926 --- /dev/null +++ b/src/main/java/daripher/skilltree/client/screen/StatsUpdateListener.java @@ -0,0 +1,5 @@ +package daripher.skilltree.client.screen; + +public interface StatsUpdateListener { + void onStatsUpdated(); +} diff --git a/src/main/java/daripher/skilltree/client/screen/menu/WorkbenchScreen.java b/src/main/java/daripher/skilltree/client/screen/menu/WorkbenchScreen.java index 2b4d91a9a..9c1b3e3de 100644 --- a/src/main/java/daripher/skilltree/client/screen/menu/WorkbenchScreen.java +++ b/src/main/java/daripher/skilltree/client/screen/menu/WorkbenchScreen.java @@ -30,9 +30,9 @@ public class WorkbenchScreen extends AbstractContainerScreen { private static final ResourceLocation BACKGROUND_TEXTURE = - new ResourceLocation(SkillTreeMod.MOD_ID, "textures/gui/container/workbench.png"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/gui/container/workbench.png"); private static final ResourceLocation RECIPES_TEXTURE = - new ResourceLocation(SkillTreeMod.MOD_ID, "textures/gui/container/workbench_recipes.png"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/gui/container/workbench_recipes.png"); private static final int SCROLLER_WIDTH = 12; private static final int SCROLLER_HEIGHT = 15; private static final int SCROLLER_FULL_HEIGHT = 90; @@ -74,7 +74,7 @@ public void resize(@NotNull Minecraft minecraft, int width, int height) { @Override protected void renderBg( @NotNull GuiGraphics guiGraphics, float partialTicks, int mouseX, int mouseY) { - renderBackground(guiGraphics); + renderBackground(guiGraphics, mouseX, mouseY, partialTicks); guiGraphics.blit(BACKGROUND_TEXTURE, leftPos, topPos, 0, 0, imageWidth, imageHeight); renderScroll(guiGraphics); renderRecipes(guiGraphics, mouseX, mouseY); @@ -250,7 +250,6 @@ protected void renderLabels(@NotNull GuiGraphics guiGraphics, int mouseX, int mo @Override protected void containerTick() { super.containerTick(); - searchBox.tick(); } @Override @@ -308,11 +307,11 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { if (isScrollBarActive()) { - amountScrolled = (int) Mth.clamp(amountScrolled - delta, 0, getMaxScroll()); + amountScrolled = (int) Mth.clamp(amountScrolled - scrollY, 0, getMaxScroll()); } - return super.mouseScrolled(mouseX, mouseY, delta); + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } private Pair getRecipeInSlot(int slot) { diff --git a/src/main/java/daripher/skilltree/client/tooltip/TooltipHelper.java b/src/main/java/daripher/skilltree/client/tooltip/TooltipHelper.java index cca51fb75..77afa9dc2 100644 --- a/src/main/java/daripher/skilltree/client/tooltip/TooltipHelper.java +++ b/src/main/java/daripher/skilltree/client/tooltip/TooltipHelper.java @@ -21,6 +21,7 @@ import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemAttributeModifiers; import net.minecraft.world.item.crafting.RecipeManager; import org.jetbrains.annotations.NotNull; @@ -40,7 +41,7 @@ public class TooltipHelper { public static Component getEffectTooltip(MobEffectInstance effect) { Component effectDescription; - if (effect.getEffect() instanceof SkillBonusEffect skillEffect) { + if (effect.getEffect().value() instanceof SkillBonusEffect skillEffect) { effectDescription = skillEffect .getBonus() @@ -49,7 +50,7 @@ public static Component getEffectTooltip(MobEffectInstance effect) { .getTooltip() .setStyle(Style.EMPTY); } else { - effectDescription = effect.getEffect().getDisplayName(); + effectDescription = effect.getEffect().value().getDisplayName(); if (effect.getAmplifier() == 0) return effectDescription; Component amplifier = Component.translatable("potion.potency." + effect.getAmplifier()); effectDescription = @@ -61,9 +62,9 @@ public static Component getEffectTooltip(MobEffectInstance effect) { public static Component getOperationName(AttributeModifier.Operation operation) { return Component.literal( switch (operation) { - case ADDITION -> "Addition"; - case MULTIPLY_BASE -> "Multiply Base"; - case MULTIPLY_TOTAL -> "Multiply Total"; + case ADD_VALUE -> "Addition"; + case ADD_MULTIPLIED_BASE -> "Multiply Base"; + case ADD_MULTIPLIED_TOTAL -> "Multiply Total"; }); } @@ -87,7 +88,7 @@ public static void consumeTranslated(String descriptionId, Consumer recipes = - recipeManager.getAllRecipesFor(PSTRecipeTypes.WORKBENCH); AbstractWorkbenchRecipe recipe = - recipes.stream().filter(r -> r.getId().equals(recipeId)).findAny().orElse(null); + recipeManager.getAllRecipesFor(PSTRecipeTypes.WORKBENCH.get()).stream() + .filter(holder -> holder.id().equals(recipeId)) + .map(holder -> (AbstractWorkbenchRecipe) holder.value()) + .findAny() + .orElse(null); if (recipe == null) { return Component.literal("Unknown Recipe: " + recipeId.toString()) .withStyle(ChatFormatting.RED); diff --git a/src/main/java/daripher/skilltree/client/widget/Button.java b/src/main/java/daripher/skilltree/client/widget/Button.java index e108f35a5..5683d8a85 100644 --- a/src/main/java/daripher/skilltree/client/widget/Button.java +++ b/src/main/java/daripher/skilltree/client/widget/Button.java @@ -34,7 +34,7 @@ public void renderWidget( } protected void renderBackground(@NotNull GuiGraphics graphics) { - ResourceLocation texture = new ResourceLocation("skilltree:textures/screen/widgets.png"); + ResourceLocation texture = ResourceLocation.parse("skilltree:textures/screen/widgets.png"); int v = getTextureVariant() * 14; graphics.blit(texture, getX(), getY(), 0, v, width / 2, height); graphics.blit(texture, getX() + width / 2, getY(), -width / 2, v, width / 2, height); diff --git a/src/main/java/daripher/skilltree/client/widget/CheckBox.java b/src/main/java/daripher/skilltree/client/widget/CheckBox.java index 7b3cd14b5..4926605d4 100644 --- a/src/main/java/daripher/skilltree/client/widget/CheckBox.java +++ b/src/main/java/daripher/skilltree/client/widget/CheckBox.java @@ -24,7 +24,7 @@ public void onPress() { @Override protected void renderBackground(@NotNull GuiGraphics graphics) { super.renderBackground(graphics); - ResourceLocation texture = new ResourceLocation("skilltree:textures/screen/widgets.png"); + ResourceLocation texture = ResourceLocation.parse("skilltree:textures/screen/widgets.png"); if (value) { graphics.blit(texture, getX(), getY(), 0, 242, width, height); } diff --git a/src/main/java/daripher/skilltree/client/widget/Label.java b/src/main/java/daripher/skilltree/client/widget/Label.java index 101dab406..30613cc6b 100644 --- a/src/main/java/daripher/skilltree/client/widget/Label.java +++ b/src/main/java/daripher/skilltree/client/widget/Label.java @@ -12,7 +12,7 @@ public class Label extends AbstractWidget { public static final ResourceLocation WIDGETS_TEXTURE = - new ResourceLocation("skilltree:textures/screen/widgets.png"); + ResourceLocation.parse("skilltree:textures/screen/widgets.png"); private boolean hasBackground; public Label(int x, int y, Component message) { diff --git a/src/main/java/daripher/skilltree/client/widget/ProgressBar.java b/src/main/java/daripher/skilltree/client/widget/ProgressBar.java index d5841cb37..8ea9fbdc7 100644 --- a/src/main/java/daripher/skilltree/client/widget/ProgressBar.java +++ b/src/main/java/daripher/skilltree/client/widget/ProgressBar.java @@ -47,7 +47,7 @@ public void renderWidget(@NotNull GuiGraphics graphics, int mouseX, int mouseY, protected void renderBackground(GuiGraphics graphics) { float experienceProgress = getExperienceProgress(); int filledBarWidth = (int) (experienceProgress * 183); - ResourceLocation texture = new ResourceLocation("skilltree:textures/screen/progress_bars.png"); + ResourceLocation texture = ResourceLocation.parse("skilltree:textures/screen/progress_bars.png"); graphics.blit(texture, getX() + 26, getY() + 7, 0, 0, 182, 5); if (filledBarWidth == 0) { return; diff --git a/src/main/java/daripher/skilltree/client/widget/ScrollableComponentList.java b/src/main/java/daripher/skilltree/client/widget/ScrollableComponentList.java index a9506722b..3436658bf 100644 --- a/src/main/java/daripher/skilltree/client/widget/ScrollableComponentList.java +++ b/src/main/java/daripher/skilltree/client/widget/ScrollableComponentList.java @@ -57,10 +57,10 @@ private void renderScrollBar(@NotNull GuiGraphics graphics) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double amount) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { int maxScroll = components.size() - maxLines; - if (amount < 0 && scroll < maxScroll) scroll++; - if (amount > 0 && scroll > 0) scroll--; + if (scrollY < 0 && scroll < maxScroll) scroll++; + if (scrollY > 0 && scroll > 0) scroll--; return true; } diff --git a/src/main/java/daripher/skilltree/client/widget/SkillTreeWidgets.java b/src/main/java/daripher/skilltree/client/widget/SkillTreeWidgets.java index 0841263a2..4971b0d66 100644 --- a/src/main/java/daripher/skilltree/client/widget/SkillTreeWidgets.java +++ b/src/main/java/daripher/skilltree/client/widget/SkillTreeWidgets.java @@ -10,7 +10,6 @@ import daripher.skilltree.config.ClientConfig; import daripher.skilltree.config.ServerConfig; import daripher.skilltree.data.reloader.SkillsReloader; -import daripher.skilltree.network.NetworkDispatcher; import daripher.skilltree.network.message.GainSkillPointMessage; import daripher.skilltree.network.message.LearnSkillMessage; import daripher.skilltree.skill.PassiveSkill; @@ -33,6 +32,7 @@ import net.minecraft.network.chat.Style; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvents; +import net.neoforged.neoforge.network.PacketDistributor; import org.jetbrains.annotations.NotNull; public class SkillTreeWidgets extends WidgetGroup { @@ -273,7 +273,7 @@ private void buySkillPoint() { int currentLevel = getCurrentLevel(); if (!canBuySkillPoint(currentLevel)) return; int cost = ServerConfig.getSkillPointCost(currentLevel); - NetworkDispatcher.network_channel.sendToServer(new GainSkillPointMessage()); + PacketDistributor.sendToServer(new GainSkillPointMessage()); player.giveExperiencePoints(-cost); } @@ -315,7 +315,7 @@ protected void skillButtonPressed(SkillButton button) { protected void learnSkill(PassiveSkill skill) { learnedSkills.add(skill.getId()); - NetworkDispatcher.network_channel.sendToServer(new LearnSkillMessage(skill)); + PacketDistributor.sendToServer(new LearnSkillMessage(skill)); rebuildWidgets(); } diff --git a/src/main/java/daripher/skilltree/client/widget/TextArea.java b/src/main/java/daripher/skilltree/client/widget/TextArea.java index c3582463f..923491a1c 100644 --- a/src/main/java/daripher/skilltree/client/widget/TextArea.java +++ b/src/main/java/daripher/skilltree/client/widget/TextArea.java @@ -18,8 +18,8 @@ public boolean keyPressed(int keyCode, int scanCode, int modifiers) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { - return isFocused() && super.mouseScrolled(mouseX, mouseY, delta); + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return isFocused() && super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } @Override @@ -34,7 +34,5 @@ public TextArea setResponder(@NotNull Consumer responder) { } @Override - public void onWidgetTick() { - this.tick(); - } + public void onWidgetTick() {} } diff --git a/src/main/java/daripher/skilltree/client/widget/TextField.java b/src/main/java/daripher/skilltree/client/widget/TextField.java index 0d147fc7d..8c5e4baf1 100644 --- a/src/main/java/daripher/skilltree/client/widget/TextField.java +++ b/src/main/java/daripher/skilltree/client/widget/TextField.java @@ -76,7 +76,7 @@ public void renderWidget( @NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { EditBoxAccessor accessor = (EditBoxAccessor) this; if (!isVisible()) return; - ResourceLocation texture = new ResourceLocation("skilltree:textures/screen/widgets.png"); + ResourceLocation texture = ResourceLocation.parse("skilltree:textures/screen/widgets.png"); int v = isHoveredOrFocused() ? 42 : 56; graphics.blit(texture, getX(), getY(), 0, v, width / 2, height); graphics.blit(texture, getX() + width / 2, getY(), -width / 2, v, width / 2, height); @@ -90,7 +90,7 @@ public void renderWidget( boolean isTextSplitByCursor = cursorVisiblePosition >= 0 && cursorVisiblePosition <= visibleText.length(); boolean isCursorVisible = - isFocused() && accessor.getFrame() / 6 % 2 == 0 && isTextSplitByCursor; + isFocused() && minecraft.gui.getGuiTicks() / 6 % 2 == 0 && isTextSplitByCursor; if (visibleText.isEmpty() && hint != null && !isFocused()) { visibleText = hint; } @@ -167,9 +167,7 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { } @Override - public void onWidgetTick() { - this.tick(); - } + public void onWidgetTick() {} public TextField setFocused() { setFocused(true); diff --git a/src/main/java/daripher/skilltree/client/widget/editor/SkillTreeEditor.java b/src/main/java/daripher/skilltree/client/widget/editor/SkillTreeEditor.java index ef56ea25d..0ecfc9a09 100644 --- a/src/main/java/daripher/skilltree/client/widget/editor/SkillTreeEditor.java +++ b/src/main/java/daripher/skilltree/client/widget/editor/SkillTreeEditor.java @@ -38,7 +38,7 @@ import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import net.minecraftforge.registries.ForgeRegistries; +import daripher.skilltree.util.ForgeRegistries; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; @@ -74,13 +74,13 @@ public void init() { } @Override - public void render(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { + protected void renderWidget(@NotNull GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { skillMirrorer.render(graphics, mouseX, mouseY, partialTick); skillDragger.render(graphics, mouseX, mouseY, partialTick); if (height > 0) { graphics.fill(getX(), getY(), getX() + width, getY() + height, 0xDD000000); } - super.render(graphics, mouseX, mouseY, partialTick); + super.renderWidget(graphics, mouseX, mouseY, partialTick); } @Override diff --git a/src/main/java/daripher/skilltree/client/widget/editor/menu/SkillNodeEditor.java b/src/main/java/daripher/skilltree/client/widget/editor/menu/SkillNodeEditor.java index 83d8dfff1..3cd70bcdf 100644 --- a/src/main/java/daripher/skilltree/client/widget/editor/menu/SkillNodeEditor.java +++ b/src/main/java/daripher/skilltree/client/widget/editor/menu/SkillNodeEditor.java @@ -96,10 +96,10 @@ private void createSkillCopy(float x, float y, PassiveSkill original) { private void createNewSkill(float x, float y, @Nullable PassiveSkill original) { ResourceLocation background = - new ResourceLocation(SkillTreeMod.MOD_ID, "textures/icons/background/lesser.png"); - ResourceLocation icon = new ResourceLocation(SkillTreeMod.MOD_ID, "textures/icons/void.png"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/icons/background/lesser.png"); + ResourceLocation icon = ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/icons/void.png"); ResourceLocation border = - new ResourceLocation(SkillTreeMod.MOD_ID, "textures/tooltip/lesser.png"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "textures/tooltip/lesser.png"); ResourceLocation skillTreeId = editor.getSkillTree().getId(); PassiveSkill skill = new PassiveSkill(createNewSkillId(skillTreeId), 16, background, icon, border, false); @@ -117,7 +117,8 @@ public static ResourceLocation createNewSkillId(ResourceLocation skillTreeId) { ResourceLocation id; int counter = 1; do { - id = new ResourceLocation("skilltree", skillTreeId.getPath() + "_" + counter++); + id = ResourceLocation.fromNamespaceAndPath( + SkillTreeMod.MOD_ID, skillTreeId.getPath() + "_" + counter++); } while (SkillTreeEditorData.getEditorSkill(id) != null); return id; } diff --git a/src/main/java/daripher/skilltree/client/widget/editor/menu/selection/SelectionList.java b/src/main/java/daripher/skilltree/client/widget/editor/menu/selection/SelectionList.java index 8681b31b5..a6b37ee69 100644 --- a/src/main/java/daripher/skilltree/client/widget/editor/menu/selection/SelectionList.java +++ b/src/main/java/daripher/skilltree/client/widget/editor/menu/selection/SelectionList.java @@ -17,7 +17,7 @@ public abstract class SelectionList extends AbstractButton { public static final ResourceLocation WIDGETS_TEXTURE = - new ResourceLocation("skilltree:textures/screen/widgets.png"); + ResourceLocation.parse("skilltree:textures/screen/widgets.png"); private Function nameGetter = t -> Component.literal(t.toString()); private Consumer responder = t -> {}; private List elementsList; @@ -159,9 +159,9 @@ public void mouseMoved(double mouseX, double mouseY) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { if (isMouseOver(mouseX, mouseY)) { - setScroll(scroll - Mth.sign(delta)); + setScroll(scroll - Mth.sign(scrollY)); return true; } return false; diff --git a/src/main/java/daripher/skilltree/client/widget/group/ScrollableZoomableWidgetGroup.java b/src/main/java/daripher/skilltree/client/widget/group/ScrollableZoomableWidgetGroup.java index a9302eebf..4d8840243 100644 --- a/src/main/java/daripher/skilltree/client/widget/group/ScrollableZoomableWidgetGroup.java +++ b/src/main/java/daripher/skilltree/client/widget/group/ScrollableZoomableWidgetGroup.java @@ -53,16 +53,16 @@ public boolean mouseDragged( } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { - if (delta > 0 && zoom < 2F) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + if (scrollY > 0 && zoom < 2F) { zoom += 0.05f; - scrollX *= 1.05f; - scrollY *= 1.05f; + this.scrollX *= 1.05f; + this.scrollY *= 1.05f; } - if (delta < 0 && zoom > 0.25F) { + if (scrollY < 0 && zoom > 0.25F) { zoom -= 0.05f; - scrollX *= 0.95f; - scrollY *= 0.95f; + this.scrollX *= 0.95f; + this.scrollY *= 0.95f; } rebuildFunc.run(); return true; diff --git a/src/main/java/daripher/skilltree/client/widget/group/WidgetGroup.java b/src/main/java/daripher/skilltree/client/widget/group/WidgetGroup.java index 777f99647..b1c6ab2a2 100644 --- a/src/main/java/daripher/skilltree/client/widget/group/WidgetGroup.java +++ b/src/main/java/daripher/skilltree/client/widget/group/WidgetGroup.java @@ -88,10 +88,10 @@ public boolean mouseReleased(double mouseX, double mouseY, int button) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { boolean result = false; for (T widget : widgetsCopy()) { - if (widget.mouseScrolled(mouseX, mouseY, delta)) { + if (widget.mouseScrolled(mouseX, mouseY, scrollX, scrollY)) { result = true; } } diff --git a/src/main/java/daripher/skilltree/client/widget/skill/SkillButton.java b/src/main/java/daripher/skilltree/client/widget/skill/SkillButton.java index 9a12dae0f..9caeedb0c 100644 --- a/src/main/java/daripher/skilltree/client/widget/skill/SkillButton.java +++ b/src/main/java/daripher/skilltree/client/widget/skill/SkillButton.java @@ -95,7 +95,7 @@ public void renderWidget( private void renderFavoriteSkillHighlight(GuiGraphics graphics) { if (!ClientConfig.favorite_skills.contains(skill.getId())) return; - ResourceLocation texture = new ResourceLocation("skilltree:textures/screen/favorite_skill.png"); + ResourceLocation texture = ResourceLocation.parse("skilltree:textures/screen/favorite_skill.png"); int color; if (ClientConfig.favorite_color_is_rainbow) { color = Color.getHSBColor(animationFunction.get() / 240f, 1f, 1f).getRGB(); diff --git a/src/main/java/daripher/skilltree/command/PSTCommands.java b/src/main/java/daripher/skilltree/command/PSTCommands.java index 500f00b73..b64f0b9d9 100644 --- a/src/main/java/daripher/skilltree/command/PSTCommands.java +++ b/src/main/java/daripher/skilltree/command/PSTCommands.java @@ -7,18 +7,15 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.capability.skill.IPlayerSkills; import daripher.skilltree.capability.skill.PlayerSkillsProvider; -import daripher.skilltree.network.NetworkDispatcher; -import daripher.skilltree.network.message.SyncPlayerSkillsMessage; import net.minecraft.ChatFormatting; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.EntityArgument; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; -import net.minecraftforge.event.RegisterCommandsEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.RegisterCommandsEvent; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID) public class PSTCommands { @@ -68,8 +65,7 @@ private static int executeResetCommand(CommandContext ctx) skillsCapability.resetTree(player); player.sendSystemMessage( Component.translatable("skilltree.message.reset_command").withStyle(ChatFormatting.YELLOW)); - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> player), new SyncPlayerSkillsMessage(player)); + PlayerSkillsProvider.sendPlayerSkills(player); return 1; } @@ -81,8 +77,7 @@ private static int executeAddPointsCommand(CommandContext ct skillsCapability.setSkillPoints(amount + skillsCapability.getSkillPoints()); player.sendSystemMessage( Component.translatable("skilltree.message.point_command").withStyle(ChatFormatting.YELLOW)); - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> player), new SyncPlayerSkillsMessage(player)); + PlayerSkillsProvider.sendPlayerSkills(player); return 1; } @@ -92,8 +87,7 @@ private static int executeSetPointsCommand(CommandContext ct int amount = IntegerArgumentType.getInteger(ctx, "amount"); IPlayerSkills skillsCapability = PlayerSkillsProvider.get(player); skillsCapability.setSkillPoints(amount); - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> player), new SyncPlayerSkillsMessage(player)); + PlayerSkillsProvider.sendPlayerSkills(player); return 1; } diff --git a/src/main/java/daripher/skilltree/compat/attributeslib/AttributesLibCompatibility.java b/src/main/java/daripher/skilltree/compat/attributeslib/AttributesLibCompatibility.java index b1e41fd00..1830f0e8b 100644 --- a/src/main/java/daripher/skilltree/compat/attributeslib/AttributesLibCompatibility.java +++ b/src/main/java/daripher/skilltree/compat/attributeslib/AttributesLibCompatibility.java @@ -1,7 +1,7 @@ package daripher.skilltree.compat.attributeslib; import daripher.skilltree.skill.PassiveSkill; -import dev.shadowsoffire.attributeslib.client.ModifierSourceType; +import dev.shadowsoffire.apothic_attributes.client.ModifierSourceType; public enum AttributesLibCompatibility { INSTANCE; diff --git a/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSource.java b/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSource.java index 8be6d138d..bf8b4d505 100644 --- a/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSource.java +++ b/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSource.java @@ -2,7 +2,7 @@ import com.mojang.blaze3d.vertex.PoseStack; import daripher.skilltree.skill.PassiveSkill; -import dev.shadowsoffire.attributeslib.client.ModifierSource; +import dev.shadowsoffire.apothic_attributes.client.ModifierSource; import java.util.Comparator; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; diff --git a/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSourceType.java b/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSourceType.java index 0c2a1b906..8b8d69626 100644 --- a/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSourceType.java +++ b/src/main/java/daripher/skilltree/compat/attributeslib/SkillModifierSourceType.java @@ -3,8 +3,8 @@ import daripher.skilltree.capability.skill.PlayerSkillsProvider; import daripher.skilltree.skill.PassiveSkill; import daripher.skilltree.skill.bonus.player.AttributeBonus; -import dev.shadowsoffire.attributeslib.client.ModifierSource; -import dev.shadowsoffire.attributeslib.client.ModifierSourceType; +import dev.shadowsoffire.apothic_attributes.client.ModifierSource; +import dev.shadowsoffire.apothic_attributes.client.ModifierSourceType; import java.util.function.BiConsumer; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.AttributeModifier; diff --git a/src/main/java/daripher/skilltree/compat/curios/CuriosCompatibility.java b/src/main/java/daripher/skilltree/compat/curios/CuriosCompatibility.java index d044c0c4d..6577cd5a6 100644 --- a/src/main/java/daripher/skilltree/compat/curios/CuriosCompatibility.java +++ b/src/main/java/daripher/skilltree/compat/curios/CuriosCompatibility.java @@ -8,11 +8,11 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.common.util.TriState; +import net.neoforged.neoforge.registries.DeferredHolder; import top.theillusivec4.curios.api.CuriosApi; -import top.theillusivec4.curios.api.event.CurioEquipEvent; +import top.theillusivec4.curios.api.event.CurioCanEquipEvent; import top.theillusivec4.curios.api.type.capability.ICuriosItemHandler; import java.util.ArrayList; @@ -22,11 +22,11 @@ public enum CuriosCompatibility { INSTANCE; - public static final RegistryObject CURIO_SLOTS_BONUS = + public static final DeferredHolder CURIO_SLOTS_BONUS = PSTSkillBonuses.REGISTRY.register("curio_slots", CurioSlotsBonus.Serializer::new); public void register() { - MinecraftForge.EVENT_BUS.addListener(INSTANCE::applyCantUseItemBonus); + NeoForge.EVENT_BUS.addListener(INSTANCE::applyCantUseItemBonus); } public Stream getCurios(LivingEntity living) { @@ -43,13 +43,13 @@ public Stream getCurios(LivingEntity living) { } - private void applyCantUseItemBonus(CurioEquipEvent event) { + private void applyCantUseItemBonus(CurioCanEquipEvent event) { if (!(event.getEntity() instanceof Player player)) { return; } for (CantUseItemBonus bonus : SkillBonusHandler.getSkillBonuses(player, CantUseItemBonus.class)) { if (bonus.getItemCondition().test(event.getStack())) { - event.setResult(Event.Result.DENY); + event.setEquipResult(TriState.FALSE); return; } } diff --git a/src/main/java/daripher/skilltree/compat/curios/skill/bonus/CurioSlotsBonus.java b/src/main/java/daripher/skilltree/compat/curios/skill/bonus/CurioSlotsBonus.java index d24a39624..3a78b1bbb 100644 --- a/src/main/java/daripher/skilltree/compat/curios/skill/bonus/CurioSlotsBonus.java +++ b/src/main/java/daripher/skilltree/compat/curios/skill/bonus/CurioSlotsBonus.java @@ -3,6 +3,7 @@ import com.google.common.collect.HashMultimap; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import daripher.skilltree.SkillTreeMod; import daripher.skilltree.client.tooltip.TooltipHelper; import daripher.skilltree.client.widget.editor.SkillTreeEditor; import daripher.skilltree.compat.curios.CuriosCompatibility; @@ -13,6 +14,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import top.theillusivec4.curios.api.CuriosApi; @@ -46,7 +48,7 @@ public void onSkillLearned(ServerPlayer player, boolean firstTime) { HashMultimap modifiers = HashMultimap.create(); AttributeModifier modifier = new AttributeModifier( - modifierId, "SkillBonus", amount, AttributeModifier.Operation.ADDITION); + getModifierId(), amount, AttributeModifier.Operation.ADD_VALUE); modifiers.put(slotName, modifier); inv.addPermanentSlotModifiers(modifiers); }); @@ -61,7 +63,7 @@ public void onSkillRemoved(ServerPlayer player) { HashMultimap modifiers = HashMultimap.create(); AttributeModifier modifier = new AttributeModifier( - modifierId, "SkillBonus", amount, AttributeModifier.Operation.ADDITION); + getModifierId(), amount, AttributeModifier.Operation.ADD_VALUE); modifiers.put(slotName, modifier); inv.removeSlotModifiers(modifiers); }); @@ -72,6 +74,11 @@ public SkillBonus.Serializer getSerializer() { return CuriosCompatibility.CURIO_SLOTS_BONUS.get(); } + private ResourceLocation getModifierId() { + return ResourceLocation.fromNamespaceAndPath( + SkillTreeMod.MOD_ID, "curio_slots/" + modifierId); + } + @Override public CurioSlotsBonus copy() { return new CurioSlotsBonus(slotName, amount, modifierId); @@ -102,7 +109,7 @@ public MutableComponent getTooltip() { } MutableComponent tooltip = TooltipHelper.getSkillBonusTooltip( - slotDescription, amount, AttributeModifier.Operation.ADDITION); + slotDescription, amount, AttributeModifier.Operation.ADD_VALUE); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); } diff --git a/src/main/java/daripher/skilltree/compat/ironsspellbooks/IronsSpellbooksCompat.java b/src/main/java/daripher/skilltree/compat/ironsspellbooks/IronsSpellbooksCompat.java index a7ff1ad16..445e886ee 100644 --- a/src/main/java/daripher/skilltree/compat/ironsspellbooks/IronsSpellbooksCompat.java +++ b/src/main/java/daripher/skilltree/compat/ironsspellbooks/IronsSpellbooksCompat.java @@ -11,8 +11,8 @@ import io.redspace.ironsspellbooks.api.events.ModifySpellLevelEvent; import io.redspace.ironsspellbooks.api.magic.SpellSelectionManager; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.registries.DeferredHolder; import java.util.*; @@ -20,16 +20,16 @@ public enum IronsSpellbooksCompat { INSTANCE; private static final Map> PLAYER_SPELLS_MAP = new HashMap<>(); - public static final RegistryObject GRANT_SPELL_BONUS = + public static final DeferredHolder GRANT_SPELL_BONUS = PSTSkillBonuses.REGISTRY.register("grant_spell", GrantSpellSkillBonus.Serializer::new); - public static final RegistryObject SPELL_LEVEL_BONUS = + public static final DeferredHolder SPELL_LEVEL_BONUS = PSTSkillBonuses.REGISTRY.register("spell_level", SpellLevelSkillBonus.Serializer::new); - public static final RegistryObject MANA_LEVEL_FUNCTION = + public static final DeferredHolder MANA_LEVEL_FUNCTION = PSTFloatFunctions.REGISTRY.register("mana_level", ManaLevelFunction.Serializer::new); public void register() { - MinecraftForge.EVENT_BUS.addListener(INSTANCE::applyGrantSpellBonus); - MinecraftForge.EVENT_BUS.addListener(INSTANCE::applySpellLevelBonus); + NeoForge.EVENT_BUS.addListener(INSTANCE::applyGrantSpellBonus); + NeoForge.EVENT_BUS.addListener(INSTANCE::applySpellLevelBonus); } public void addPlayerSpell(Player player, UUID uuid) { diff --git a/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/GrantSpellSkillBonus.java b/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/GrantSpellSkillBonus.java index 2bcf050e0..cb3d253b6 100644 --- a/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/GrantSpellSkillBonus.java +++ b/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/GrantSpellSkillBonus.java @@ -15,7 +15,6 @@ import io.redspace.ironsspellbooks.api.spells.AbstractSpell; import io.redspace.ironsspellbooks.api.spells.SpellData; import io.redspace.ironsspellbooks.network.EquipmentChangedPacket; -import io.redspace.ironsspellbooks.setup.PacketDistributor; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; @@ -25,6 +24,7 @@ import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/SpellLevelSkillBonus.java b/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/SpellLevelSkillBonus.java index 78f4bcf41..95a10da89 100644 --- a/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/SpellLevelSkillBonus.java +++ b/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/SpellLevelSkillBonus.java @@ -94,7 +94,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { LocalPlayer clientPlayer = Minecraft.getInstance().player; Component spellName = SpellRegistry.getSpell(spellId).getDisplayName(clientPlayer); - AttributeModifier.Operation operation = AttributeModifier.Operation.ADDITION; + AttributeModifier.Operation operation = AttributeModifier.Operation.ADD_VALUE; MutableComponent tooltip = Component.translatable(getDescriptionId(), spellName); tooltip = TooltipHelper.getSkillBonusTooltip(tooltip, bonusLevels, operation); tooltip = playerCondition.getTooltip(tooltip, Target.PLAYER); diff --git a/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/function/ManaLevelFunction.java b/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/function/ManaLevelFunction.java index b5ed0fbad..dc3899cd2 100644 --- a/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/function/ManaLevelFunction.java +++ b/src/main/java/daripher/skilltree/compat/ironsspellbooks/skill/bonus/function/ManaLevelFunction.java @@ -31,7 +31,7 @@ public ManaLevelFunction(boolean percentage, boolean missing) { @Override public float apply(LivingEntity entity) { MagicData magicData = MagicData.getPlayerMagicData(entity); - float maxMana = (float) entity.getAttributeValue(AttributeRegistry.MAX_MANA.get()); + float maxMana = (float) entity.getAttributeValue(AttributeRegistry.MAX_MANA); float value = magicData.getMana(); if (missing) { value = maxMana - value; diff --git a/src/main/java/daripher/skilltree/config/ClientConfig.java b/src/main/java/daripher/skilltree/config/ClientConfig.java index 22e79552f..2efa80dac 100644 --- a/src/main/java/daripher/skilltree/config/ClientConfig.java +++ b/src/main/java/daripher/skilltree/config/ClientConfig.java @@ -7,17 +7,17 @@ import java.util.Set; import java.util.stream.Collectors; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; -import net.minecraftforge.fml.event.config.ModConfigEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.EventBusSubscriber.Bus; +import net.neoforged.fml.event.config.ModConfigEvent; +import net.neoforged.neoforge.common.ModConfigSpec; +import net.neoforged.neoforge.common.ModConfigSpec.ConfigValue; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Bus.MOD) public class ClientConfig { - public static final ForgeConfigSpec SPEC; - private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); + public static final ModConfigSpec SPEC; + private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder(); private static final ConfigValue> FAVORITE_SKILLS; private static final ConfigValue FAVORITE_COLOR_HEX; private static final ConfigValue SKILL_TREE_BACKGROUND_PARALLAX; @@ -37,7 +37,7 @@ public class ClientConfig { } private static boolean isValidSkillId(Object o) { - return o instanceof String s && ResourceLocation.isValidResourceLocation(s); + return o instanceof String s && ResourceLocation.tryParse(s) != null; } @SuppressWarnings("ResultOfMethodCallIgnored") @@ -56,7 +56,7 @@ private static boolean isValidHexColor(Object o) { static void load(ModConfigEvent.Loading event) { if (event.getConfig().getSpec() != SPEC) return; favorite_skills = - FAVORITE_SKILLS.get().stream().map(ResourceLocation::new).collect(Collectors.toSet()); + FAVORITE_SKILLS.get().stream().map(ResourceLocation::parse).collect(Collectors.toSet()); favorite_color_is_rainbow = FAVORITE_COLOR_HEX.get().equals("rainbow"); skill_tree_background_parallax = SKILL_TREE_BACKGROUND_PARALLAX.get(); if (!favorite_color_is_rainbow) { diff --git a/src/main/java/daripher/skilltree/config/ServerConfig.java b/src/main/java/daripher/skilltree/config/ServerConfig.java index 1897fa3ad..694fb2390 100644 --- a/src/main/java/daripher/skilltree/config/ServerConfig.java +++ b/src/main/java/daripher/skilltree/config/ServerConfig.java @@ -3,17 +3,17 @@ import daripher.skilltree.SkillTreeMod; import java.util.ArrayList; import java.util.List; -import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; -import net.minecraftforge.fml.event.config.ModConfigEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.EventBusSubscriber.Bus; +import net.neoforged.fml.event.config.ModConfigEvent; +import net.neoforged.neoforge.common.ModConfigSpec; +import net.neoforged.neoforge.common.ModConfigSpec.ConfigValue; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Bus.MOD) public class ServerConfig { - public static final ForgeConfigSpec SPEC; - private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); + public static final ModConfigSpec SPEC; + private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder(); private static final ConfigValue MAX_SKILL_POINTS; private static final ConfigValue FIRST_SKILL_COST; private static final ConfigValue LAST_SKILL_COST; diff --git a/src/main/java/daripher/skilltree/data/generation/PSTBlockStatesProvider.java b/src/main/java/daripher/skilltree/data/generation/PSTBlockStatesProvider.java index 90b2d87af..9b1da3d39 100644 --- a/src/main/java/daripher/skilltree/data/generation/PSTBlockStatesProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/PSTBlockStatesProvider.java @@ -6,11 +6,11 @@ import net.minecraft.data.DataGenerator; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.model.generators.BlockStateProvider; -import net.minecraftforge.client.model.generators.ConfiguredModel; -import net.minecraftforge.client.model.generators.ModelFile; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.client.model.generators.BlockStateProvider; +import net.neoforged.neoforge.client.model.generators.ConfiguredModel; +import net.neoforged.neoforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.registries.DeferredHolder; import org.jetbrains.annotations.NotNull; public class PSTBlockStatesProvider extends BlockStateProvider { @@ -25,7 +25,7 @@ protected void registerStatesAndModels() { } private void simpleBlockState( - RegistryObject blockRegistryObject, + DeferredHolder blockRegistryObject, Function modelFileProvider) { ResourceLocation blockId = blockRegistryObject.getId(); ModelFile modelFile = modelFileProvider.apply(blockId); diff --git a/src/main/java/daripher/skilltree/data/generation/PSTBlockTagsProvider.java b/src/main/java/daripher/skilltree/data/generation/PSTBlockTagsProvider.java index f250305be..42c4de5eb 100644 --- a/src/main/java/daripher/skilltree/data/generation/PSTBlockTagsProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/PSTBlockTagsProvider.java @@ -4,8 +4,8 @@ import java.util.concurrent.CompletableFuture; import net.minecraft.core.HolderLookup; import net.minecraft.data.DataGenerator; -import net.minecraftforge.common.data.BlockTagsProvider; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.common.data.BlockTagsProvider; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import org.jetbrains.annotations.NotNull; public class PSTBlockTagsProvider extends BlockTagsProvider { diff --git a/src/main/java/daripher/skilltree/data/generation/PSTDamageTagsProvider.java b/src/main/java/daripher/skilltree/data/generation/PSTDamageTagsProvider.java index e0c0b831f..7d7b537cc 100644 --- a/src/main/java/daripher/skilltree/data/generation/PSTDamageTagsProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/PSTDamageTagsProvider.java @@ -11,7 +11,7 @@ import net.minecraft.tags.TagKey; import net.minecraft.world.damagesource.DamageType; import net.minecraft.world.damagesource.DamageTypes; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/daripher/skilltree/data/generation/PSTDataGenerator.java b/src/main/java/daripher/skilltree/data/generation/PSTDataGenerator.java index 7495dfa63..019ff90c7 100644 --- a/src/main/java/daripher/skilltree/data/generation/PSTDataGenerator.java +++ b/src/main/java/daripher/skilltree/data/generation/PSTDataGenerator.java @@ -8,11 +8,11 @@ import java.util.concurrent.CompletableFuture; import net.minecraft.core.HolderLookup; import net.minecraft.data.DataGenerator; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.data.event.GatherDataEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; +import net.neoforged.neoforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.data.event.GatherDataEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.EventBusSubscriber.Bus; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Bus.MOD) public class PSTDataGenerator { @@ -30,11 +30,12 @@ public static void onGatherData(GatherDataEvent event) { includeServer, new PSTItemTagsProvider(dataGenerator, lookupProvider, blockTagsProvider, existingFileHelper)); dataGenerator.addProvider( - includeServer, new PSTLootTablesProvider(dataGenerator)); - dataGenerator.addProvider(includeServer, new PSTGlobalLootModifierProvider(dataGenerator)); + includeServer, new PSTLootTablesProvider(dataGenerator, lookupProvider)); + dataGenerator.addProvider(includeServer, new PSTGlobalLootModifierProvider(dataGenerator, lookupProvider)); dataGenerator.addProvider( includeServer, new PSTDamageTagsProvider(dataGenerator, lookupProvider, existingFileHelper)); - dataGenerator.addProvider(includeServer, new PSTRecipesProvider(dataGenerator)); + dataGenerator.addProvider( + includeServer, new PSTRecipesProvider(dataGenerator.getPackOutput(), lookupProvider)); boolean includeClient = event.includeClient(); dataGenerator.addProvider(includeClient, new PSTEnglishTranslationProvider(dataGenerator)); diff --git a/src/main/java/daripher/skilltree/data/generation/PSTItemModelsProvider.java b/src/main/java/daripher/skilltree/data/generation/PSTItemModelsProvider.java index cd89eb5d9..c9cafa800 100644 --- a/src/main/java/daripher/skilltree/data/generation/PSTItemModelsProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/PSTItemModelsProvider.java @@ -3,8 +3,8 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.init.PSTItems; import net.minecraft.data.DataGenerator; -import net.minecraftforge.client.model.generators.ItemModelProvider; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.client.model.generators.ItemModelProvider; +import net.neoforged.neoforge.common.data.ExistingFileHelper; public class PSTItemModelsProvider extends ItemModelProvider { public PSTItemModelsProvider(DataGenerator dataGenerator, ExistingFileHelper existingFileHelper) { diff --git a/src/main/java/daripher/skilltree/data/generation/PSTItemTagsProvider.java b/src/main/java/daripher/skilltree/data/generation/PSTItemTagsProvider.java index 7aa01f481..0028b7b6d 100644 --- a/src/main/java/daripher/skilltree/data/generation/PSTItemTagsProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/PSTItemTagsProvider.java @@ -9,14 +9,14 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.ItemTags; import net.minecraft.world.item.Items; -import net.minecraftforge.common.Tags; -import net.minecraftforge.common.data.BlockTagsProvider; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.common.data.BlockTagsProvider; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class PSTItemTagsProvider extends ItemTagsProvider { - public static final ResourceLocation KNIVES = new ResourceLocation("forge", "tools/knives"); + public static final ResourceLocation KNIVES = ResourceLocation.fromNamespaceAndPath("c", "tools/knives"); public PSTItemTagsProvider( DataGenerator dataGenerator, @@ -35,8 +35,8 @@ public PSTItemTagsProvider( protected void addTags(HolderLookup.@NotNull Provider provider) { tag(Tags.Items.TOOLS).addOptionalTag(KNIVES); tag(PSTTags.Items.MELEE_WEAPON) - .addTags(ItemTags.SWORDS, ItemTags.AXES, Tags.Items.TOOLS_TRIDENTS); - tag(PSTTags.Items.RANGED_WEAPON).addTags(Tags.Items.TOOLS_BOWS, Tags.Items.TOOLS_CROSSBOWS); + .addTags(ItemTags.SWORDS, ItemTags.AXES, Tags.Items.TOOLS_SPEAR); + tag(PSTTags.Items.RANGED_WEAPON).addTags(Tags.Items.TOOLS_BOW, Tags.Items.TOOLS_CROSSBOW); tag(PSTTags.Items.LEATHER_ARMOR) .add( Items.LEATHER_BOOTS, diff --git a/src/main/java/daripher/skilltree/data/generation/PSTRecipesProvider.java b/src/main/java/daripher/skilltree/data/generation/PSTRecipesProvider.java index 907176f80..021d04f7f 100644 --- a/src/main/java/daripher/skilltree/data/generation/PSTRecipesProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/PSTRecipesProvider.java @@ -8,10 +8,11 @@ import daripher.skilltree.skill.bonus.player.DamageBonus; import daripher.skilltree.skill.bonus.predicate.damage.ThornsDamageCondition; import daripher.skilltree.skill.bonus.predicate.item.EquipmentPredicate; -import java.util.function.Consumer; -import net.minecraft.data.DataGenerator; -import net.minecraft.data.recipes.FinishedRecipe; +import java.util.concurrent.CompletableFuture; +import net.minecraft.core.HolderLookup; +import net.minecraft.data.PackOutput; import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.recipes.RecipeOutput; import net.minecraft.data.recipes.RecipeProvider; import net.minecraft.data.recipes.ShapedRecipeBuilder; import net.minecraft.resources.ResourceLocation; @@ -20,22 +21,24 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; import org.jetbrains.annotations.NotNull; public class PSTRecipesProvider extends RecipeProvider { - public PSTRecipesProvider(DataGenerator dataGenerator) { - super(dataGenerator.getPackOutput()); + public PSTRecipesProvider( + PackOutput packOutput, CompletableFuture lookupProvider) { + super(packOutput, lookupProvider); } @Override - protected void buildRecipes(@NotNull Consumer consumer) { + protected void buildRecipes( + @NotNull RecipeOutput consumer, @NotNull HolderLookup.Provider lookupProvider) { addCraftingTableRecipes(consumer); addUpgradeRecipes(consumer); addWorkbenchCraftingRecipes(consumer); } - private static void addCraftingTableRecipes(@NotNull Consumer consumer) { + private static void addCraftingTableRecipes(@NotNull RecipeOutput consumer) { ShapedRecipeBuilder.shaped(RecipeCategory.MISC, PSTItems.WORKBENCH.get()) .define('I', Tags.Items.INGOTS_IRON) .define('G', Tags.Items.INGOTS_GOLD) @@ -48,13 +51,13 @@ private static void addCraftingTableRecipes(@NotNull Consumer co .save(consumer); } - private static void addUpgradeRecipes(@NotNull Consumer consumer) { + private static void addUpgradeRecipes(@NotNull RecipeOutput consumer) { WorkbenchItemBonusRecipeBuilder.create(modRecipeId("shields_thorns_bonus")) .setBaseItemCondition(new EquipmentPredicate(EquipmentPredicate.Type.SHIELD)) .addIngredients(Ingredient.of(Tags.Items.INGOTS_IRON), 5) .addIngredients(Ingredient.of(Tags.Items.NUGGETS_IRON), 9) .setItemBonus( - new DamageBonus(0.25f, AttributeModifier.Operation.MULTIPLY_BASE) + new DamageBonus(0.25f, AttributeModifier.Operation.ADD_MULTIPLIED_BASE) .setDamageCondition(new ThornsDamageCondition())) .setRequiresPassiveSkill() .save(consumer); @@ -63,9 +66,9 @@ private static void addUpgradeRecipes(@NotNull Consumer consumer .addIngredients(Ingredient.of(Tags.Items.INGOTS_COPPER), 2) .setItemBonus( new AttributeBonus( - Attributes.ARMOR, + Attributes.ARMOR.value(), new AttributeModifier( - "Workbench Upgrade", 1, AttributeModifier.Operation.ADDITION))) + modRecipeId("armor_defence_bonus"), 1, AttributeModifier.Operation.ADD_VALUE))) .setRequiresPassiveSkill() .save(consumer); WorkbenchItemBonusRecipeBuilder.create(modRecipeId("shields_defence_bonus")) @@ -73,31 +76,31 @@ private static void addUpgradeRecipes(@NotNull Consumer consumer .addIngredients(Ingredient.of(Tags.Items.INGOTS_COPPER), 2) .setItemBonus( new AttributeBonus( - Attributes.ARMOR, + Attributes.ARMOR.value(), new AttributeModifier( - "Workbench Upgrade", 2, AttributeModifier.Operation.ADDITION))) + modRecipeId("shields_defence_bonus"), 2, AttributeModifier.Operation.ADD_VALUE))) .setRequiresPassiveSkill() .save(consumer); WorkbenchItemBonusRecipeBuilder.create(modRecipeId("melee_weapon_attack_speed_bonus")) .setBaseItemCondition(new EquipmentPredicate(EquipmentPredicate.Type.MELEE_WEAPON)) - .addIngredients(Ingredient.of(Tags.Items.LEATHER), 3) + .addIngredients(Ingredient.of(Tags.Items.LEATHERS), 3) .addIngredients(Ingredient.of(Tags.Items.NUGGETS_IRON), 5) .setItemBonus( new AttributeBonus( - Attributes.ATTACK_SPEED, + Attributes.ATTACK_SPEED.value(), new AttributeModifier( - "Workbench Upgrade", 0.1, AttributeModifier.Operation.MULTIPLY_BASE))) + modRecipeId("melee_weapon_attack_speed_bonus"), 0.1, AttributeModifier.Operation.ADD_MULTIPLIED_BASE))) .setRequiresPassiveSkill() .save(consumer); WorkbenchItemBonusRecipeBuilder.create(modRecipeId("boots_movement_speed_bonus")) .setBaseItemCondition(new EquipmentPredicate(EquipmentPredicate.Type.BOOTS)) - .addIngredients(Ingredient.of(Tags.Items.LEATHER), 4) + .addIngredients(Ingredient.of(Tags.Items.LEATHERS), 4) .addIngredients(Ingredient.of(Tags.Items.NUGGETS_IRON), 3) .setItemBonus( new AttributeBonus( - Attributes.MOVEMENT_SPEED, + Attributes.MOVEMENT_SPEED.value(), new AttributeModifier( - "Workbench Upgrade", 0.15, AttributeModifier.Operation.MULTIPLY_BASE))) + modRecipeId("boots_movement_speed_bonus"), 0.15, AttributeModifier.Operation.ADD_MULTIPLIED_BASE))) .setRequiresPassiveSkill() .save(consumer); WorkbenchItemBonusRecipeBuilder.create(modRecipeId("melee_weapon_attack_damage_bonus")) @@ -105,9 +108,9 @@ private static void addUpgradeRecipes(@NotNull Consumer consumer .addIngredients(Ingredient.of(Tags.Items.GEMS_DIAMOND), 1) .setItemBonus( new AttributeBonus( - Attributes.ATTACK_DAMAGE, + Attributes.ATTACK_DAMAGE.value(), new AttributeModifier( - "Workbench Upgrade", 1, AttributeModifier.Operation.ADDITION))) + modRecipeId("melee_weapon_attack_damage_bonus"), 1, AttributeModifier.Operation.ADD_VALUE))) .setRequiresPassiveSkill() .save(consumer); WorkbenchItemBonusRecipeBuilder.create(modRecipeId("chestplates_toughness_bonus")) @@ -116,16 +119,16 @@ private static void addUpgradeRecipes(@NotNull Consumer consumer .addIngredients(Ingredient.of(Tags.Items.GEMS_DIAMOND), 3) .setItemBonus( new AttributeBonus( - Attributes.ARMOR_TOUGHNESS, + Attributes.ARMOR_TOUGHNESS.value(), new AttributeModifier( - "Workbench Upgrade", 1, AttributeModifier.Operation.ADDITION))) + modRecipeId("chestplates_toughness_bonus"), 1, AttributeModifier.Operation.ADD_VALUE))) .setRequiresPassiveSkill() .save(consumer); } - private static void addWorkbenchCraftingRecipes(@NotNull Consumer consumer) { + private static void addWorkbenchCraftingRecipes(@NotNull RecipeOutput consumer) { WorkbenchCraftingRecipeBuilder.create(modRecipeId("saddle_crafting")) - .addIngredients(Ingredient.of(Tags.Items.LEATHER), 8) + .addIngredients(Ingredient.of(Tags.Items.LEATHERS), 8) .addIngredients(Ingredient.of(Tags.Items.NUGGETS_IRON), 4) .addIngredients(Ingredient.of(Tags.Items.INGOTS_IRON), 2) .setResult(new ItemStack(Items.SADDLE)) @@ -141,6 +144,6 @@ private static void addWorkbenchCraftingRecipes(@NotNull Consumer getKnownBlocks() { - return PSTBlocks.REGISTRY.getEntries().stream().map(RegistryObject::get)::iterator; + return PSTBlocks.REGISTRY.getEntries().stream().map(DeferredHolder::get)::iterator; } } diff --git a/src/main/java/daripher/skilltree/data/generation/loot/PSTGlobalLootModifierProvider.java b/src/main/java/daripher/skilltree/data/generation/loot/PSTGlobalLootModifierProvider.java index e431dc795..601fed4e7 100644 --- a/src/main/java/daripher/skilltree/data/generation/loot/PSTGlobalLootModifierProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/loot/PSTGlobalLootModifierProvider.java @@ -2,12 +2,15 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.loot.modifier.SkillBonusesModifier; +import java.util.concurrent.CompletableFuture; +import net.minecraft.core.HolderLookup; import net.minecraft.data.DataGenerator; -import net.minecraftforge.common.data.GlobalLootModifierProvider; +import net.neoforged.neoforge.common.data.GlobalLootModifierProvider; public class PSTGlobalLootModifierProvider extends GlobalLootModifierProvider { - public PSTGlobalLootModifierProvider(DataGenerator generator) { - super(generator.getPackOutput(), SkillTreeMod.MOD_ID); + public PSTGlobalLootModifierProvider( + DataGenerator generator, CompletableFuture lookupProvider) { + super(generator.getPackOutput(), lookupProvider, SkillTreeMod.MOD_ID); } @Override diff --git a/src/main/java/daripher/skilltree/data/generation/loot/PSTLootTablesProvider.java b/src/main/java/daripher/skilltree/data/generation/loot/PSTLootTablesProvider.java index 608438d74..c5826d2cf 100644 --- a/src/main/java/daripher/skilltree/data/generation/loot/PSTLootTablesProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/loot/PSTLootTablesProvider.java @@ -3,19 +3,24 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; +import net.minecraft.core.HolderLookup; import net.minecraft.data.DataGenerator; import net.minecraft.data.loot.LootTableProvider; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.storage.loot.BuiltInLootTables; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.ValidationContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import org.jetbrains.annotations.NotNull; public class PSTLootTablesProvider extends LootTableProvider { - public static final Set REQUIRED_TABLES = Set.of(); + public static final Set> REQUIRED_TABLES = Set.of(); - public PSTLootTablesProvider(DataGenerator generator) { - super(generator.getPackOutput(), REQUIRED_TABLES, List.of(createBlockLootProvider())); + public PSTLootTablesProvider( + DataGenerator generator, CompletableFuture lookupProvider) { + super(generator.getPackOutput(), REQUIRED_TABLES, List.of(createBlockLootProvider()), lookupProvider); } @NotNull @@ -25,5 +30,7 @@ private static SubProviderEntry createBlockLootProvider() { @Override protected void validate( - @NotNull Map map, @NotNull ValidationContext ctx) {} + @NotNull net.minecraft.core.WritableRegistry registry, + @NotNull ValidationContext ctx, + @NotNull net.minecraft.util.ProblemReporter.Collector problemReporter) {} } diff --git a/src/main/java/daripher/skilltree/data/generation/translation/PSTEnglishTranslationProvider.java b/src/main/java/daripher/skilltree/data/generation/translation/PSTEnglishTranslationProvider.java index bfe393814..522e6c4c7 100644 --- a/src/main/java/daripher/skilltree/data/generation/translation/PSTEnglishTranslationProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/translation/PSTEnglishTranslationProvider.java @@ -5,6 +5,8 @@ import daripher.skilltree.init.*; import daripher.skilltree.skill.bonus.player.GainedExperienceBonus; import daripher.skilltree.skill.bonus.player.LootDuplicationBonus; +import java.util.Optional; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.data.DataGenerator; import net.minecraft.world.item.Items; import net.minecraft.world.item.alchemy.Potion; @@ -293,12 +295,12 @@ protected void addTranslations() { add(PSTItemConditions.EQUIPMENT_TYPE.get(), "sword.plural", "Swords"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "trident", "Trident"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "trident.plural", "Tridents"); - add(PSTTags.Items.RINGS, "Ring"); - add(PSTTags.Items.RINGS, "plural", "Rings"); - add(PSTTags.Items.NECKLACES, "Necklace"); - add(PSTTags.Items.NECKLACES, "plural", "Necklaces"); - add(PSTTags.Items.LEATHER_ARMOR, "Leather Armor"); - add(PSTTags.Items.LEATHER_ARMOR, "plural", "Leather Armor"); + addItemTag(PSTTags.Items.RINGS, "Ring"); + addItemTag(PSTTags.Items.RINGS, "plural", "Rings"); + addItemTag(PSTTags.Items.NECKLACES, "Necklace"); + addItemTag(PSTTags.Items.NECKLACES, "plural", "Necklaces"); + addItemTag(PSTTags.Items.LEATHER_ARMOR, "Leather Armor"); + addItemTag(PSTTags.Items.LEATHER_ARMOR, "plural", "Leather Armor"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "armor", "Armor"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "helmet", "Helmet"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "helmet.plural", "Helmets"); @@ -318,7 +320,7 @@ protected void addTranslations() { add(PSTItemConditions.POTIONS.get(), "neutral", "Neutral Potion"); add(PSTItemConditions.POTIONS.get(), "neutral.plural", "Neutral Potions"); add(PSTItemConditions.FOOD.get(), "Food"); - add(PSTTags.Items.JEWELRY, "Jewelry"); + addItemTag(PSTTags.Items.JEWELRY, "Jewelry"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "tool", "Tool"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "tool.plural", "Tools"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "axe", "Axe"); @@ -536,8 +538,9 @@ protected void addTranslations() { } protected void add(Potion potion, String name) { - add(potion.getName(Items.POTION.getDescriptionId() + ".effect."), "Potion of " + name); - add(potion.getName(Items.SPLASH_POTION.getDescriptionId() + ".effect."), "Splash Potion of " + name); - add(potion.getName(Items.LINGERING_POTION.getDescriptionId() + ".effect."), "Lingering Potion of " + name); + var potionHolder = Optional.of(BuiltInRegistries.POTION.wrapAsHolder(potion)); + add(Potion.getName(potionHolder, Items.POTION.getDescriptionId() + ".effect."), "Potion of " + name); + add(Potion.getName(potionHolder, Items.SPLASH_POTION.getDescriptionId() + ".effect."), "Splash Potion of " + name); + add(Potion.getName(potionHolder, Items.LINGERING_POTION.getDescriptionId() + ".effect."), "Lingering Potion of " + name); } } diff --git a/src/main/java/daripher/skilltree/data/generation/translation/PSTRussianTranslationProvider.java b/src/main/java/daripher/skilltree/data/generation/translation/PSTRussianTranslationProvider.java index e728527da..d9b99190f 100644 --- a/src/main/java/daripher/skilltree/data/generation/translation/PSTRussianTranslationProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/translation/PSTRussianTranslationProvider.java @@ -5,6 +5,8 @@ import daripher.skilltree.init.*; import daripher.skilltree.skill.bonus.player.GainedExperienceBonus; import daripher.skilltree.skill.bonus.player.LootDuplicationBonus; +import java.util.Optional; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.data.DataGenerator; import net.minecraft.world.item.Items; import net.minecraft.world.item.alchemy.Potion; @@ -313,17 +315,17 @@ protected void addTranslations() { add(PSTItemConditions.EQUIPMENT_TYPE.get(), "trident.adjective", "ый Трезубец"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "trident.plural.adjective", "ые Трезубцы"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "trident.plural", "Трезубцы"); - add(PSTTags.Items.RINGS, "Кольцо"); - add(PSTTags.Items.RINGS, "where", "Кольцах"); - add(PSTTags.Items.RINGS, "type", "ое Кольцо"); - add(PSTTags.Items.RINGS, "plural.adjective", "ые Кольца"); - add(PSTTags.Items.RINGS, "plural", "Кольца"); - add(PSTTags.Items.NECKLACES, "Ожерелье"); - add(PSTTags.Items.NECKLACES, "type", "ое Ожерелье"); - add(PSTTags.Items.NECKLACES, "plural.adjective", "ые Ожерелья"); - add(PSTTags.Items.NECKLACES, "plural", "Ожерелья"); - add(PSTTags.Items.LEATHER_ARMOR, "Кожаная броня"); - add(PSTTags.Items.LEATHER_ARMOR, "plural", "Кожаная броня"); + addItemTag(PSTTags.Items.RINGS, "Кольцо"); + addItemTag(PSTTags.Items.RINGS, "where", "Кольцах"); + addItemTag(PSTTags.Items.RINGS, "type", "ое Кольцо"); + addItemTag(PSTTags.Items.RINGS, "plural.adjective", "ые Кольца"); + addItemTag(PSTTags.Items.RINGS, "plural", "Кольца"); + addItemTag(PSTTags.Items.NECKLACES, "Ожерелье"); + addItemTag(PSTTags.Items.NECKLACES, "type", "ое Ожерелье"); + addItemTag(PSTTags.Items.NECKLACES, "plural.adjective", "ые Ожерелья"); + addItemTag(PSTTags.Items.NECKLACES, "plural", "Ожерелья"); + addItemTag(PSTTags.Items.LEATHER_ARMOR, "Кожаная броня"); + addItemTag(PSTTags.Items.LEATHER_ARMOR, "plural", "Кожаная броня"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "armor", "Броня"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "armor.prepositional", "Броне"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "armor.adjective", "ая Броня"); @@ -379,11 +381,11 @@ protected void addTranslations() { add(PSTItemConditions.FOOD.get(), "type", "ая Еда"); add(PSTItemConditions.FOOD.get(), "plural.adjective", "ая Еда"); add(PSTItemConditions.FOOD.get(), "plural", "Еда"); - add(PSTTags.Items.JEWELRY, "Бижутерия"); - add(PSTTags.Items.JEWELRY, "where", "Бижутерии"); - add(PSTTags.Items.JEWELRY, "type", "ая Бижутерия"); - add(PSTTags.Items.JEWELRY, "plural.adjective", "ая Бижутерия"); - add(PSTTags.Items.JEWELRY, "plural", "Бижутерия"); + addItemTag(PSTTags.Items.JEWELRY, "Бижутерия"); + addItemTag(PSTTags.Items.JEWELRY, "where", "Бижутерии"); + addItemTag(PSTTags.Items.JEWELRY, "type", "ая Бижутерия"); + addItemTag(PSTTags.Items.JEWELRY, "plural.adjective", "ая Бижутерия"); + addItemTag(PSTTags.Items.JEWELRY, "plural", "Бижутерия"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "tool", "Инструмент"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "tool.prepositional", "Инструменте"); add(PSTItemConditions.EQUIPMENT_TYPE.get(), "tool.adjective", "ый Инструмент"); @@ -608,8 +610,9 @@ protected void addTranslations() { } protected void add(Potion potion, String name) { - add(potion.getName(Items.POTION.getDescriptionId() + ".effect."), "Зелье " + name); - add(potion.getName(Items.SPLASH_POTION.getDescriptionId() + ".effect."), "Взрывное зелье " + name); - add(potion.getName(Items.LINGERING_POTION.getDescriptionId() + ".effect."), "Туманное зелье " + name); + var potionHolder = Optional.of(BuiltInRegistries.POTION.wrapAsHolder(potion)); + add(Potion.getName(potionHolder, Items.POTION.getDescriptionId() + ".effect."), "Зелье " + name); + add(Potion.getName(potionHolder, Items.SPLASH_POTION.getDescriptionId() + ".effect."), "Взрывное зелье " + name); + add(Potion.getName(potionHolder, Items.LINGERING_POTION.getDescriptionId() + ".effect."), "Туманное зелье " + name); } } diff --git a/src/main/java/daripher/skilltree/data/generation/translation/PSTTranslationProvider.java b/src/main/java/daripher/skilltree/data/generation/translation/PSTTranslationProvider.java index 199993b3b..67a12d77f 100644 --- a/src/main/java/daripher/skilltree/data/generation/translation/PSTTranslationProvider.java +++ b/src/main/java/daripher/skilltree/data/generation/translation/PSTTranslationProvider.java @@ -17,8 +17,8 @@ import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.item.Item; import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.common.data.LanguageProvider; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.data.LanguageProvider; +import daripher.skilltree.util.ForgeRegistries; public abstract class PSTTranslationProvider extends LanguageProvider { public PSTTranslationProvider(DataGenerator dataGenerator, String modId, String locale) { @@ -153,13 +153,13 @@ protected void add(ItemStackPredicate.Serializer serializer, String value) { add(key, value); } - protected void add(TagKey itemTag, String value) { + protected void addItemTag(TagKey itemTag, String value) { ResourceLocation id = itemTag.location(); String key = "item_tag.%s".formatted(id.toString()); add(key, value); } - protected void add(TagKey itemTag, String type, String value) { + protected void addItemTag(TagKey itemTag, String type, String value) { ResourceLocation id = itemTag.location(); String key = "item_tag.%s.%s".formatted(id.toString(), type); add(key, value); diff --git a/src/main/java/daripher/skilltree/data/reloader/SkillTreesReloader.java b/src/main/java/daripher/skilltree/data/reloader/SkillTreesReloader.java index 35b5eb3d0..88076c9fb 100644 --- a/src/main/java/daripher/skilltree/data/reloader/SkillTreesReloader.java +++ b/src/main/java/daripher/skilltree/data/reloader/SkillTreesReloader.java @@ -13,9 +13,9 @@ import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener; import net.minecraft.util.profiling.ProfilerFiller; -import net.minecraftforge.event.AddReloadListenerEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.neoforge.event.AddReloadListenerEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/daripher/skilltree/data/reloader/SkillsReloader.java b/src/main/java/daripher/skilltree/data/reloader/SkillsReloader.java index 82869f755..c4922c356 100644 --- a/src/main/java/daripher/skilltree/data/reloader/SkillsReloader.java +++ b/src/main/java/daripher/skilltree/data/reloader/SkillsReloader.java @@ -14,6 +14,7 @@ import javax.annotation.Nullable; import daripher.skilltree.skill.requirement.SkillRequirement; +import net.minecraft.core.RegistryAccess; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; @@ -21,9 +22,9 @@ import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener; import net.minecraft.util.profiling.ProfilerFiller; -import net.minecraftforge.event.AddReloadListenerEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.neoforge.event.AddReloadListenerEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; import org.jetbrains.annotations.NotNull; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID) @@ -33,7 +34,8 @@ public class SkillsReloader extends SimpleJsonResourceReloadListener { .registerTypeAdapter(ResourceLocation.class, new ResourceLocation.Serializer()) .registerTypeAdapter(SkillBonus.class, new SkillBonusSerializer()) .registerTypeAdapter(SkillRequirement.class, new SkillRequirementSerializer()) - .registerTypeAdapter(MutableComponent.class, new Component.Serializer()) + .registerTypeAdapter( + MutableComponent.class, new Component.SerializerAdapter(RegistryAccess.EMPTY)) .setPrettyPrinting() .create(); private static final Map SKILLS = new HashMap<>(); diff --git a/src/main/java/daripher/skilltree/data/serializers/SerializationHelper.java b/src/main/java/daripher/skilltree/data/serializers/SerializationHelper.java index 8f87ee34c..ed545af7b 100644 --- a/src/main/java/daripher/skilltree/data/serializers/SerializationHelper.java +++ b/src/main/java/daripher/skilltree/data/serializers/SerializationHelper.java @@ -17,22 +17,23 @@ import daripher.skilltree.skill.bonus.multiplier.LivingMultiplier; import daripher.skilltree.skill.bonus.multiplier.NoneLivingMultiplier; import java.util.Objects; -import java.util.UUID; +import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import net.minecraftforge.registries.ForgeRegistries; +import daripher.skilltree.util.ForgeRegistries; import org.jetbrains.annotations.NotNull; public class SerializationHelper { @NotNull public static Attribute deserializeAttribute(JsonObject json) { - ResourceLocation attributeId = new ResourceLocation(json.get("attribute").getAsString()); + ResourceLocation attributeId = ResourceLocation.parse(json.get("attribute").getAsString()); Attribute attribute; attribute = ForgeRegistries.ATTRIBUTES.getValue(attributeId); if (attribute == null) { @@ -50,34 +51,33 @@ public static void serializeAttribute(JsonObject json, Attribute attribute) { @NotNull public static AttributeModifier deserializeAttributeModifier(JsonObject json) { - UUID id = UUID.fromString(json.get("id").getAsString()); - String name = json.get("name").getAsString(); + ResourceLocation id = deserializeModifierId(json.get("id").getAsString()); double amount = json.get("amount").getAsDouble(); AttributeModifier.Operation operation = deserializeOperation(json); - return new AttributeModifier(id, name, amount, operation); + return new AttributeModifier(id, amount, operation); } public static void serializeAttributeModifier(JsonObject json, AttributeModifier modifier) { - json.addProperty("id", modifier.getId().toString()); - json.addProperty("name", modifier.getName()); - json.addProperty("amount", modifier.getAmount()); - serializeOperation(json, modifier.getOperation()); + json.addProperty("id", modifier.id().toString()); + json.addProperty("name", modifier.id().toString()); + json.addProperty("amount", modifier.amount()); + serializeOperation(json, modifier.operation()); } @NotNull public static AttributeModifier.Operation deserializeOperation(JsonObject json) { - return AttributeModifier.Operation.fromValue(json.get("operation").getAsInt()); + return AttributeModifier.Operation.BY_ID.apply(json.get("operation").getAsInt()); } public static void serializeOperation(JsonObject json, AttributeModifier.Operation operation) { - json.addProperty("operation", operation.toValue()); + json.addProperty("operation", operation.id()); } public static @Nonnull LivingMultiplier deserializeLivingMultiplier( JsonObject json, String name) { if (!json.has(name)) return NoneLivingMultiplier.INSTANCE; JsonObject multiplierJson = json.getAsJsonObject(name); - ResourceLocation serializerId = new ResourceLocation(multiplierJson.get("type").getAsString()); + ResourceLocation serializerId = ResourceLocation.parse(multiplierJson.get("type").getAsString()); LivingMultiplier.Serializer serializer = PSTRegistries.LIVING_MULTIPLIERS.get().getValue(serializerId); String errorMessage = "Unknown living multiplier: " + serializerId; @@ -99,7 +99,7 @@ public static void serializeLivingMultiplier( public static @Nonnull LivingEntityPredicate deserializeLivingCondition(JsonObject json, String name) { if (!json.has(name)) return NoneLivingEntityPredicate.INSTANCE; JsonObject conditionJson = json.getAsJsonObject(name); - ResourceLocation serializerId = new ResourceLocation(conditionJson.get("type").getAsString()); + ResourceLocation serializerId = ResourceLocation.parse(conditionJson.get("type").getAsString()); LivingEntityPredicate.Serializer serializer = PSTRegistries.LIVING_CONDITIONS.get().getValue(serializerId); String errorMessage = "Unknown living condition: " + serializerId; @@ -127,7 +127,7 @@ public static DamageCondition deserializeDamageCondition(JsonObject json) { public static DamageCondition deserializeDamageCondition(JsonObject json, String name) { if (!json.has(name)) return NoneDamageCondition.INSTANCE; JsonObject conditionJson = json.getAsJsonObject(name); - ResourceLocation serializerId = new ResourceLocation(conditionJson.get("type").getAsString()); + ResourceLocation serializerId = ResourceLocation.parse(conditionJson.get("type").getAsString()); DamageCondition.Serializer serializer = PSTRegistries.DAMAGE_CONDITIONS.get().getValue(serializerId); String errorMessage = "Unknown damage condition: " + serializerId; @@ -155,7 +155,7 @@ public static void serializeDamageCondition( public static @Nonnull ItemStackPredicate deserializeItemCondition(JsonObject json, String name) { if (!json.has(name)) return NoneItemStackPredicate.INSTANCE; JsonObject conditionJson = json.getAsJsonObject(name); - ResourceLocation serializerId = new ResourceLocation(conditionJson.get("type").getAsString()); + ResourceLocation serializerId = ResourceLocation.parse(conditionJson.get("type").getAsString()); ItemStackPredicate.Serializer serializer = PSTRegistries.ITEM_CONDITIONS.get().getValue(serializerId); String errorMessage = "Unknown item condition: " + serializerId; @@ -178,7 +178,7 @@ public static void serializeItemCondition(JsonObject json, @Nonnull ItemStackPre public static @Nonnull SkillEventListener deserializeEventListener(JsonObject json) { JsonObject eventJson = json.getAsJsonObject("event_listener"); - ResourceLocation serializerId = new ResourceLocation(eventJson.get("type").getAsString()); + ResourceLocation serializerId = ResourceLocation.parse(eventJson.get("type").getAsString()); SkillEventListener.Serializer serializer = PSTRegistries.EVENT_LISTENERS.get().getValue(serializerId); String errorMessage = "Unknown event listener: " + serializerId; @@ -197,7 +197,7 @@ public static void serializeEventListener( public static @Nullable MobEffect deserializeEffect(JsonObject json) { if (!json.has("effect")) return null; - ResourceLocation effectId = new ResourceLocation(json.get("effect").getAsString()); + ResourceLocation effectId = ResourceLocation.parse(json.get("effect").getAsString()); return ForgeRegistries.MOB_EFFECTS.getValue(effectId); } @@ -218,11 +218,12 @@ public static MobEffectInstance deserializeEffectInstance(JsonObject json) { MobEffect effect = deserializeEffect(json); int duration = json.get("duration").getAsInt(); int amplifier = json.get("amplifier").getAsInt(); - return new MobEffectInstance(Objects.requireNonNull(effect), duration, amplifier); + return new MobEffectInstance( + BuiltInRegistries.MOB_EFFECT.wrapAsHolder(Objects.requireNonNull(effect)), duration, amplifier); } public static void serializeEffectInstance(JsonObject json, MobEffectInstance effect) { - serializeEffect(json, effect.getEffect()); + serializeEffect(json, effect.getEffect().value()); json.addProperty("duration", effect.getDuration()); json.addProperty("amplifier", effect.getAmplifier()); } @@ -230,7 +231,7 @@ public static void serializeEffectInstance(JsonObject json, MobEffectInstance ef public static FloatFunction deserializeValueProvider(JsonObject json) { JsonObject providerJson = json.getAsJsonObject("value_provider"); String type = providerJson.get("type").getAsString(); - ResourceLocation serializerId = new ResourceLocation(type); + ResourceLocation serializerId = ResourceLocation.parse(type); FloatFunction.Serializer serializer = PSTRegistries.FLOAT_FUNCTIONS.get().getValue(serializerId); String errorMessage = "Unknown value provider: " + serializerId; @@ -248,7 +249,7 @@ public static void serializeValueProvider(JsonObject json, FloatFunction prov @Nullable public static Attribute deserializeAttribute(CompoundTag tag) { - ResourceLocation attributeId = new ResourceLocation(tag.getString("attribute")); + ResourceLocation attributeId = ResourceLocation.parse(tag.getString("attribute")); Attribute attribute = ForgeRegistries.ATTRIBUTES.getValue(attributeId); if (attribute == null) { SkillTreeMod.LOGGER.error("Attribute {} doesn't exist!", attributeId); @@ -264,34 +265,33 @@ public static void serializeAttribute(CompoundTag tag, Attribute attribute) { @NotNull public static AttributeModifier deserializeAttributeModifier(CompoundTag tag) { - UUID modifierId = UUID.fromString(tag.getString("id")); - String name = tag.getString("name"); + ResourceLocation modifierId = deserializeModifierId(tag.getString("id")); double amount = tag.getDouble("amount"); AttributeModifier.Operation operation = deserializeOperation(tag); - return new AttributeModifier(modifierId, name, amount, operation); + return new AttributeModifier(modifierId, amount, operation); } public static void serializeAttributeModifier(CompoundTag tag, AttributeModifier modifier) { - tag.putString("id", modifier.getId().toString()); - tag.putString("name", modifier.getName()); - tag.putDouble("amount", modifier.getAmount()); - serializeOperation(tag, modifier.getOperation()); + tag.putString("id", modifier.id().toString()); + tag.putString("name", modifier.id().toString()); + tag.putDouble("amount", modifier.amount()); + serializeOperation(tag, modifier.operation()); } @NotNull public static AttributeModifier.Operation deserializeOperation(CompoundTag tag) { - return AttributeModifier.Operation.fromValue(tag.getInt("operation")); + return AttributeModifier.Operation.BY_ID.apply(tag.getInt("operation")); } public static void serializeOperation(CompoundTag tag, AttributeModifier.Operation operation) { - tag.putInt("operation", operation.toValue()); + tag.putInt("operation", operation.id()); } public static @Nonnull LivingMultiplier deserializeLivingMultiplier( CompoundTag tag, String name) { if (!tag.contains(name)) return NoneLivingMultiplier.INSTANCE; CompoundTag multiplierTag = tag.getCompound(name); - ResourceLocation serializerId = new ResourceLocation(multiplierTag.getString("type")); + ResourceLocation serializerId = ResourceLocation.parse(multiplierTag.getString("type")); LivingMultiplier.Serializer serializer = PSTRegistries.LIVING_MULTIPLIERS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(multiplierTag); @@ -308,7 +308,7 @@ public static void serializeLivingMultiplier( public static @Nonnull LivingEntityPredicate deserializeLivingCondition(CompoundTag tag, String name) { CompoundTag conditionTag = tag.getCompound(name); - ResourceLocation serializerId = new ResourceLocation(conditionTag.getString("type")); + ResourceLocation serializerId = ResourceLocation.parse(conditionTag.getString("type")); LivingEntityPredicate.Serializer serializer = PSTRegistries.LIVING_CONDITIONS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(conditionTag); @@ -330,7 +330,7 @@ public static void serializeLivingCondition( public static @Nonnull DamageCondition deserializeDamageCondition(CompoundTag tag, String name) { CompoundTag conditionTag = tag.getCompound(name); - ResourceLocation serializerId = new ResourceLocation(conditionTag.getString("type")); + ResourceLocation serializerId = ResourceLocation.parse(conditionTag.getString("type")); DamageCondition.Serializer serializer = PSTRegistries.DAMAGE_CONDITIONS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(conditionTag); @@ -351,7 +351,7 @@ public static void serializeDamageCondition( public static @Nonnull ItemStackPredicate deserializeItemCondition(CompoundTag tag) { CompoundTag conditionTag = tag.getCompound("item_condition"); - ResourceLocation serializerId = new ResourceLocation(conditionTag.getString("type")); + ResourceLocation serializerId = ResourceLocation.parse(conditionTag.getString("type")); ItemStackPredicate.Serializer serializer = PSTRegistries.ITEM_CONDITIONS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(conditionTag); @@ -367,7 +367,7 @@ public static void serializeItemCondition(CompoundTag tag, @Nonnull ItemStackPre public static @Nonnull SkillEventListener deserializeEventListener(CompoundTag tag) { CompoundTag conditionTag = tag.getCompound("event_listener"); - ResourceLocation serializerId = new ResourceLocation(conditionTag.getString("type")); + ResourceLocation serializerId = ResourceLocation.parse(conditionTag.getString("type")); SkillEventListener.Serializer serializer = PSTRegistries.EVENT_LISTENERS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(conditionTag); @@ -385,7 +385,7 @@ public static void serializeEventListener( @Nullable public static MobEffect deserializeEffect(CompoundTag tag) { if (!tag.contains("effect")) return null; - ResourceLocation effectId = new ResourceLocation(tag.getString("effect")); + ResourceLocation effectId = ResourceLocation.parse(tag.getString("effect")); return ForgeRegistries.MOB_EFFECTS.getValue(effectId); } @@ -406,11 +406,11 @@ public static MobEffectInstance deserializeEffectInstance(CompoundTag tag) { MobEffect effect = Objects.requireNonNull(deserializeEffect(tag)); int duration = tag.getInt("duration"); int amplifier = tag.getInt("amplifier"); - return new MobEffectInstance(effect, duration, amplifier); + return new MobEffectInstance(BuiltInRegistries.MOB_EFFECT.wrapAsHolder(effect), duration, amplifier); } public static void serializeEffectInstance(CompoundTag tag, MobEffectInstance effect) { - serializeEffect(tag, effect.getEffect()); + serializeEffect(tag, effect.getEffect().value()); tag.putInt("duration", effect.getDuration()); tag.putInt("amplifier", effect.getAmplifier()); } @@ -418,7 +418,7 @@ public static void serializeEffectInstance(CompoundTag tag, MobEffectInstance ef public static FloatFunction deserializeValueProvider(CompoundTag tag) { CompoundTag providerTag = tag.getCompound("value_provider"); String type = providerTag.getString("type"); - ResourceLocation serializerId = new ResourceLocation(type); + ResourceLocation serializerId = ResourceLocation.parse(type); FloatFunction.Serializer serializer = PSTRegistries.FLOAT_FUNCTIONS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(providerTag); @@ -454,9 +454,18 @@ public static void serializeItemBonus(JsonObject jsonObject, ItemBonus itemBo public static ItemBonus deserializeItemBonus(JsonObject jsonObject) { JsonObject itemBonusJson = jsonObject.get("item_bonus").getAsJsonObject(); - ResourceLocation serializerId = new ResourceLocation(itemBonusJson.get("type").getAsString()); + ResourceLocation serializerId = ResourceLocation.parse(itemBonusJson.get("type").getAsString()); ItemBonus.Serializer serializer = PSTRegistries.ITEM_BONUSES.get().getValue(serializerId); Objects.requireNonNull(serializer); return serializer.deserialize(itemBonusJson); } + + private static ResourceLocation deserializeModifierId(String rawId) { + ResourceLocation parsed = ResourceLocation.tryParse(rawId); + if (parsed != null && rawId.contains(":")) { + return parsed; + } + return ResourceLocation.fromNamespaceAndPath( + SkillTreeMod.MOD_ID, "modifier/" + rawId.toLowerCase(Locale.ROOT)); + } } diff --git a/src/main/java/daripher/skilltree/data/serializers/SkillBonusSerializer.java b/src/main/java/daripher/skilltree/data/serializers/SkillBonusSerializer.java index 3d29bdf72..6afe27e0e 100644 --- a/src/main/java/daripher/skilltree/data/serializers/SkillBonusSerializer.java +++ b/src/main/java/daripher/skilltree/data/serializers/SkillBonusSerializer.java @@ -15,7 +15,7 @@ public SkillBonus deserialize( throws JsonParseException { JsonObject jsonObj = (JsonObject) json; String type = jsonObj.get("type").getAsString(); - ResourceLocation serializerId = new ResourceLocation(type); + ResourceLocation serializerId = ResourceLocation.parse(type); SkillBonus.Serializer serializer = PSTRegistries.SKILL_BONUSES.get().getValue(serializerId); Objects.requireNonNull(serializer, "Unknown skill bonus: " + serializerId); return serializer.deserialize(jsonObj); diff --git a/src/main/java/daripher/skilltree/data/serializers/SkillRequirementSerializer.java b/src/main/java/daripher/skilltree/data/serializers/SkillRequirementSerializer.java index 0942eab62..90a839760 100644 --- a/src/main/java/daripher/skilltree/data/serializers/SkillRequirementSerializer.java +++ b/src/main/java/daripher/skilltree/data/serializers/SkillRequirementSerializer.java @@ -23,7 +23,7 @@ public SkillRequirement deserialize( } else { type = jsonObj.get("type").getAsString(); } - ResourceLocation serializerId = new ResourceLocation(type); + ResourceLocation serializerId = ResourceLocation.parse(type); SkillRequirement.Serializer serializer = PSTRegistries.SKILL_REQUIREMENTS.get().getValue(serializerId); Objects.requireNonNull(serializer, "Unknown skill requirement: " + serializerId); diff --git a/src/main/java/daripher/skilltree/effect/LiquidFireEffect.java b/src/main/java/daripher/skilltree/effect/LiquidFireEffect.java index 83b1a2164..f5e038d54 100644 --- a/src/main/java/daripher/skilltree/effect/LiquidFireEffect.java +++ b/src/main/java/daripher/skilltree/effect/LiquidFireEffect.java @@ -40,6 +40,6 @@ public void applyInstantenousEffect(@Nullable Entity source, @Nullable Entity in DamageSource damageSource = new DamageSource(damageType, source, indirectSource); target.hurt(damageSource, damage); } - target.setSecondsOnFire((int) damage / 2); + target.igniteForSeconds((int) damage / 2f); } } diff --git a/src/main/java/daripher/skilltree/effect/SkillBonusEffect.java b/src/main/java/daripher/skilltree/effect/SkillBonusEffect.java index e95a7dba9..a5f0509b0 100644 --- a/src/main/java/daripher/skilltree/effect/SkillBonusEffect.java +++ b/src/main/java/daripher/skilltree/effect/SkillBonusEffect.java @@ -18,33 +18,26 @@ public SkillBonusEffect(MobEffectCategory category, int color, SkillBonus bon } @Override - public void removeAttributeModifiers( - @NotNull LivingEntity entity, @NotNull AttributeMap attributeMap, int amplifier) { - super.removeAttributeModifiers(entity, attributeMap, amplifier); - if (entity instanceof ServerPlayer player) { - bonus.onSkillRemoved(player); - } + public void removeAttributeModifiers(@NotNull AttributeMap attributeMap) { + super.removeAttributeModifiers(attributeMap); } @Override - public void addAttributeModifiers( - @NotNull LivingEntity entity, @NotNull AttributeMap attributeMap, int amplifier) { - super.addAttributeModifiers(entity, attributeMap, amplifier); - if (entity instanceof ServerPlayer player) { - bonus.onSkillLearned(player, true); - } + public void addAttributeModifiers(@NotNull AttributeMap attributeMap, int amplifier) { + super.addAttributeModifiers(attributeMap, amplifier); } @Override - public boolean isDurationEffectTick(int duration, int amplifier) { + public boolean shouldApplyEffectTickThisTick(int duration, int amplifier) { return bonus instanceof TickingSkillBonus; } @Override - public void applyEffectTick(@NotNull LivingEntity entity, int amplifier) { + public boolean applyEffectTick(@NotNull LivingEntity entity, int amplifier) { if (entity instanceof ServerPlayer player && bonus instanceof TickingSkillBonus ticking) { ticking.tick(player); } + return true; } public SkillBonus getBonus() { diff --git a/src/main/java/daripher/skilltree/enchantment/EnchantmentCategory.java b/src/main/java/daripher/skilltree/enchantment/EnchantmentCategory.java new file mode 100644 index 000000000..2e77336ee --- /dev/null +++ b/src/main/java/daripher/skilltree/enchantment/EnchantmentCategory.java @@ -0,0 +1,81 @@ +package daripher.skilltree.enchantment; + +import java.util.Objects; +import java.util.function.Predicate; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.item.ArmorItem; +import net.minecraft.world.item.AxeItem; +import net.minecraft.world.item.BowItem; +import net.minecraft.world.item.CrossbowItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.PotionItem; +import net.minecraft.world.item.ShieldItem; +import net.minecraft.world.item.SwordItem; +import net.minecraft.world.item.TridentItem; + +public final class EnchantmentCategory { + public static final EnchantmentCategory ARMOR = + new EnchantmentCategory("armor", item -> item instanceof ArmorItem); + public static final EnchantmentCategory ARMOR_CHEST = + new EnchantmentCategory( + "armor_chest", + item -> item instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.CHEST); + public static final EnchantmentCategory ARMOR_FEET = + new EnchantmentCategory( + "armor_feet", + item -> item instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.FEET); + public static final EnchantmentCategory ARMOR_HEAD = + new EnchantmentCategory( + "armor_head", + item -> item instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.HEAD); + public static final EnchantmentCategory ARMOR_LEGS = + new EnchantmentCategory( + "armor_legs", + item -> item instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.LEGS); + public static final EnchantmentCategory WEAPON = + new EnchantmentCategory( + "weapon", item -> item instanceof SwordItem || item instanceof AxeItem || item instanceof TridentItem); + public static final EnchantmentCategory BOW = + new EnchantmentCategory("bow", item -> item instanceof BowItem); + public static final EnchantmentCategory CROSSBOW = + new EnchantmentCategory("crossbow", item -> item instanceof CrossbowItem); + public static final EnchantmentCategory TRIDENT = + new EnchantmentCategory("trident", item -> item instanceof TridentItem); + + private final String name; + private final Predicate predicate; + + private EnchantmentCategory(String name, Predicate predicate) { + this.name = name; + this.predicate = predicate; + } + + public static EnchantmentCategory create(String name, Predicate predicate) { + return new EnchantmentCategory(name, predicate); + } + + public boolean canEnchant(Item item) { + return predicate.test(item); + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof EnchantmentCategory that)) return false; + return Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } +} diff --git a/src/main/java/daripher/skilltree/entity/player/PlayerHelper.java b/src/main/java/daripher/skilltree/entity/player/PlayerHelper.java index 4b4ec4e35..8ce42348d 100644 --- a/src/main/java/daripher/skilltree/entity/player/PlayerHelper.java +++ b/src/main/java/daripher/skilltree/entity/player/PlayerHelper.java @@ -6,7 +6,7 @@ import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; import org.jetbrains.annotations.NotNull; import java.util.Arrays; diff --git a/src/main/java/daripher/skilltree/event/ModEvents.java b/src/main/java/daripher/skilltree/event/ModEvents.java index 2086690d3..de87475ff 100644 --- a/src/main/java/daripher/skilltree/event/ModEvents.java +++ b/src/main/java/daripher/skilltree/event/ModEvents.java @@ -7,9 +7,9 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.event.entity.living.LivingDropsEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.living.LivingDropsEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID) public class ModEvents { diff --git a/src/main/java/daripher/skilltree/event/PSTEvents.java b/src/main/java/daripher/skilltree/event/PSTEvents.java index 493e6cdbe..ddebb7d0d 100644 --- a/src/main/java/daripher/skilltree/event/PSTEvents.java +++ b/src/main/java/daripher/skilltree/event/PSTEvents.java @@ -2,9 +2,9 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.config.ServerConfig; -import net.minecraftforge.event.GrindstoneEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.neoforge.event.GrindstoneEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; @EventBusSubscriber(modid = SkillTreeMod.MOD_ID) public class PSTEvents { diff --git a/src/main/java/daripher/skilltree/init/PSTAttachments.java b/src/main/java/daripher/skilltree/init/PSTAttachments.java new file mode 100644 index 000000000..92b5fc9c1 --- /dev/null +++ b/src/main/java/daripher/skilltree/init/PSTAttachments.java @@ -0,0 +1,17 @@ +package daripher.skilltree.init; + +import daripher.skilltree.SkillTreeMod; +import daripher.skilltree.capability.skill.PlayerSkills; +import java.util.function.Supplier; +import net.neoforged.neoforge.attachment.AttachmentType; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; + +public class PSTAttachments { + public static final DeferredRegister> REGISTRY = + DeferredRegister.create(NeoForgeRegistries.ATTACHMENT_TYPES, SkillTreeMod.MOD_ID); + + public static final Supplier> PLAYER_SKILLS = + REGISTRY.register( + "player_skills", () -> AttachmentType.serializable(PlayerSkills::new).copyOnDeath().build()); +} diff --git a/src/main/java/daripher/skilltree/init/PSTBlocks.java b/src/main/java/daripher/skilltree/init/PSTBlocks.java index 5c277c241..254355169 100644 --- a/src/main/java/daripher/skilltree/init/PSTBlocks.java +++ b/src/main/java/daripher/skilltree/init/PSTBlocks.java @@ -3,15 +3,15 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.block.WorkbenchBlock; import net.minecraft.world.level.block.Block; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries; public class PSTBlocks { public static final DeferredRegister REGISTRY = DeferredRegister.create(ForgeRegistries.BLOCKS, SkillTreeMod.MOD_ID); // crafting stations - public static final RegistryObject WORKBENCH = + public static final DeferredHolder WORKBENCH = REGISTRY.register("workbench", WorkbenchBlock::new); } diff --git a/src/main/java/daripher/skilltree/init/PSTBrewingRecipes.java b/src/main/java/daripher/skilltree/init/PSTBrewingRecipes.java index c89d17fa4..a7b4df4fb 100644 --- a/src/main/java/daripher/skilltree/init/PSTBrewingRecipes.java +++ b/src/main/java/daripher/skilltree/init/PSTBrewingRecipes.java @@ -1,57 +1,64 @@ package daripher.skilltree.init; import daripher.skilltree.SkillTreeMod; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.alchemy.Potion; -import net.minecraft.world.item.alchemy.PotionUtils; +import net.minecraft.world.item.alchemy.PotionContents; import net.minecraft.world.item.alchemy.Potions; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.brewing.BrewingRecipeRegistry; -import net.minecraftforge.common.crafting.StrictNBTIngredient; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.neoforge.common.crafting.DataComponentIngredient; +import net.neoforged.neoforge.event.brewing.RegisterBrewingRecipesEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.EventBusSubscriber.Bus; import org.jetbrains.annotations.NotNull; -@Mod.EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD) +@EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Bus.GAME) public class PSTBrewingRecipes { @SubscribeEvent - public static void addRecipes(FMLCommonSetupEvent event) { - addRecipe(Potions.FIRE_RESISTANCE, Items.FERMENTED_SPIDER_EYE, PSTPotions.LIQUID_FIRE_1.get()); - addSplashRecipe(PSTPotions.LIQUID_FIRE_1.get()); - addLingeringRecipe(PSTPotions.LIQUID_FIRE_1.get()); - addRecipe(PSTPotions.LIQUID_FIRE_1.get(), Items.GLOWSTONE_DUST, PSTPotions.LIQUID_FIRE_2.get()); - addSplashRecipe(PSTPotions.LIQUID_FIRE_2.get()); - addLingeringRecipe(PSTPotions.LIQUID_FIRE_2.get()); + public static void addRecipes(RegisterBrewingRecipesEvent event) { + addRecipe(event, Potions.FIRE_RESISTANCE.value(), Items.FERMENTED_SPIDER_EYE, PSTPotions.LIQUID_FIRE_1.get()); + addSplashRecipe(event, PSTPotions.LIQUID_FIRE_1.get()); + addLingeringRecipe(event, PSTPotions.LIQUID_FIRE_1.get()); + addRecipe(event, PSTPotions.LIQUID_FIRE_1.get(), Items.GLOWSTONE_DUST, PSTPotions.LIQUID_FIRE_2.get()); + addSplashRecipe(event, PSTPotions.LIQUID_FIRE_2.get()); + addLingeringRecipe(event, PSTPotions.LIQUID_FIRE_2.get()); } - private static void addRecipe(Potion inputPotion, Item ingredient, @NotNull Potion outputPotion) { + private static void addRecipe( + RegisterBrewingRecipesEvent event, Potion inputPotion, Item ingredient, @NotNull Potion outputPotion) { Item[] potionItems = new Item[]{Items.POTION, Items.SPLASH_POTION, Items.LINGERING_POTION}; for (Item potionItem : potionItems) { - addRecipe(inputPotion, potionItem, ingredient, outputPotion, potionItem); + addRecipe(event, inputPotion, potionItem, ingredient, outputPotion, potionItem); } } - private static void addLingeringRecipe(@NotNull Potion potion) { - addRecipe(potion, Items.SPLASH_POTION, Items.DRAGON_BREATH, potion, Items.LINGERING_POTION); + private static void addLingeringRecipe(RegisterBrewingRecipesEvent event, @NotNull Potion potion) { + addRecipe(event, potion, Items.SPLASH_POTION, Items.DRAGON_BREATH, potion, Items.LINGERING_POTION); } - private static void addSplashRecipe(@NotNull Potion potion) { - addRecipe(potion, Items.POTION, Items.GUNPOWDER, potion, Items.SPLASH_POTION); + private static void addSplashRecipe(RegisterBrewingRecipesEvent event, @NotNull Potion potion) { + addRecipe(event, potion, Items.POTION, Items.GUNPOWDER, potion, Items.SPLASH_POTION); } - private static void addRecipe(Potion inputPotion, Item inputItem, Item ingredient, @NotNull Potion outputPotion, Item outputItem) { + private static void addRecipe( + RegisterBrewingRecipesEvent event, + Potion inputPotion, + Item inputItem, + Item ingredient, + @NotNull Potion outputPotion, + Item outputItem) { ItemStack input = getPotionStack(inputItem, inputPotion); ItemStack output = getPotionStack(outputItem, outputPotion); - BrewingRecipeRegistry.addRecipe(StrictNBTIngredient.of(input), Ingredient.of(ingredient), output); + event.getBuilder().addRecipe(DataComponentIngredient.of(true, input), Ingredient.of(ingredient), output); } @NotNull private static ItemStack getPotionStack(Item potionItem, @NotNull Potion outputPotion) { - ItemStack output = new ItemStack(potionItem); - PotionUtils.setPotion(output, outputPotion); - return output; + return PotionContents.createItemStack( + potionItem, BuiltInRegistries.POTION.wrapAsHolder(outputPotion)); } } diff --git a/src/main/java/daripher/skilltree/init/PSTCreativeTabs.java b/src/main/java/daripher/skilltree/init/PSTCreativeTabs.java index 45633f85b..b1805f56e 100644 --- a/src/main/java/daripher/skilltree/init/PSTCreativeTabs.java +++ b/src/main/java/daripher/skilltree/init/PSTCreativeTabs.java @@ -7,8 +7,8 @@ import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTCreativeTabs { public static final DeferredRegister REGISTRY = @@ -29,6 +29,6 @@ public class PSTCreativeTabs { } private static void collectModItems(CreativeModeTab.Output output) { - PSTItems.REGISTRY.getEntries().stream().map(RegistryObject::get).forEach(output::accept); + PSTItems.REGISTRY.getEntries().stream().map(DeferredHolder::get).forEach(output::accept); } } diff --git a/src/main/java/daripher/skilltree/init/PSTDamageConditions.java b/src/main/java/daripher/skilltree/init/PSTDamageConditions.java index d77838fdc..87a7b4cba 100644 --- a/src/main/java/daripher/skilltree/init/PSTDamageConditions.java +++ b/src/main/java/daripher/skilltree/init/PSTDamageConditions.java @@ -8,30 +8,30 @@ import daripher.skilltree.skill.bonus.predicate.damage.*; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTDamageConditions { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "damage_conditions"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "damage_conditions"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject NONE = + public static final DeferredHolder NONE = REGISTRY.register("none", NoneDamageCondition.Serializer::new); - public static final RegistryObject PROJECTILE = + public static final DeferredHolder PROJECTILE = REGISTRY.register("projectile", ProjectileDamageCondition.Serializer::new); - public static final RegistryObject MELEE = + public static final DeferredHolder MELEE = REGISTRY.register("melee", MeleeDamageCondition.Serializer::new); - public static final RegistryObject MAGIC = + public static final DeferredHolder MAGIC = REGISTRY.register("magic", MagicDamageCondition.Serializer::new); - public static final RegistryObject FALL = + public static final DeferredHolder FALL = REGISTRY.register("fall", FallDamageCondition.Serializer::new); - public static final RegistryObject FIRE = + public static final DeferredHolder FIRE = REGISTRY.register("fire", FireDamageCondition.Serializer::new); - public static final RegistryObject POISON = + public static final DeferredHolder POISON = REGISTRY.register("poison", PoisonDamageCondition.Serializer::new); - public static final RegistryObject THORNS = + public static final DeferredHolder THORNS = REGISTRY.register("thorns", ThornsDamageCondition.Serializer::new); public static List conditionsList() { diff --git a/src/main/java/daripher/skilltree/init/PSTDamageTypes.java b/src/main/java/daripher/skilltree/init/PSTDamageTypes.java index 10681bf71..9d577b685 100644 --- a/src/main/java/daripher/skilltree/init/PSTDamageTypes.java +++ b/src/main/java/daripher/skilltree/init/PSTDamageTypes.java @@ -7,5 +7,5 @@ import net.minecraft.world.damagesource.DamageType; public class PSTDamageTypes { - public static ResourceKey POISON = ResourceKey.create(Registries.DAMAGE_TYPE, new ResourceLocation(SkillTreeMod.MOD_ID, "poison")); + public static ResourceKey POISON = ResourceKey.create(Registries.DAMAGE_TYPE, ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "poison")); } diff --git a/src/main/java/daripher/skilltree/init/PSTEnchantmentCategories.java b/src/main/java/daripher/skilltree/init/PSTEnchantmentCategories.java index bcda7d9da..5734156c2 100644 --- a/src/main/java/daripher/skilltree/init/PSTEnchantmentCategories.java +++ b/src/main/java/daripher/skilltree/init/PSTEnchantmentCategories.java @@ -3,7 +3,7 @@ import daripher.skilltree.skill.bonus.predicate.item.EquipmentPredicate; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.PotionItem; -import net.minecraft.world.item.enchantment.EnchantmentCategory; +import daripher.skilltree.enchantment.EnchantmentCategory; public class PSTEnchantmentCategories { public static EnchantmentCategory SHIELD = EnchantmentCategory.create("shield", item -> EquipmentPredicate.isShield(new ItemStack(item))); diff --git a/src/main/java/daripher/skilltree/init/PSTEnchantmentConditions.java b/src/main/java/daripher/skilltree/init/PSTEnchantmentConditions.java index c955858d8..586e7bc62 100644 --- a/src/main/java/daripher/skilltree/init/PSTEnchantmentConditions.java +++ b/src/main/java/daripher/skilltree/init/PSTEnchantmentConditions.java @@ -9,20 +9,20 @@ import java.util.List; import java.util.Objects; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTEnchantmentConditions { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "enchantment_conditions"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "enchantment_conditions"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject NONE = + public static final DeferredHolder NONE = REGISTRY.register("none", NoneEnchantmentCondition.Serializer::new); - public static final RegistryObject ARMOR = + public static final DeferredHolder ARMOR = REGISTRY.register("armor", ArmorEnchantmentCondition.Serializer::new); - public static final RegistryObject WEAPON = + public static final DeferredHolder WEAPON = REGISTRY.register("weapon", WeaponEnchantmentCondition.Serializer::new); public static List conditionsList() { diff --git a/src/main/java/daripher/skilltree/init/PSTEventListeners.java b/src/main/java/daripher/skilltree/init/PSTEventListeners.java index 2d175a1f9..ab4142fba 100644 --- a/src/main/java/daripher/skilltree/init/PSTEventListeners.java +++ b/src/main/java/daripher/skilltree/init/PSTEventListeners.java @@ -6,34 +6,34 @@ import java.util.List; import java.util.Objects; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTEventListeners { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "event_listeners"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "event_listeners"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject ATTACK = + public static final DeferredHolder ATTACK = REGISTRY.register("attack", AttackEventListener.Serializer::new); - public static final RegistryObject BLOCK = + public static final DeferredHolder BLOCK = REGISTRY.register("block", BlockEventListener.Serializer::new); - public static final RegistryObject EVASION = + public static final DeferredHolder EVASION = REGISTRY.register("evasion", EvasionEventListener.Serializer::new); - public static final RegistryObject ITEM_USED = + public static final DeferredHolder ITEM_USED = REGISTRY.register("item_used", ItemUsedEventListener.Serializer::new); - public static final RegistryObject DAMAGE_TAKEN = + public static final DeferredHolder DAMAGE_TAKEN = REGISTRY.register("damage_taken", DamageTakenEventListener.Serializer::new); - public static final RegistryObject ON_KILL = + public static final DeferredHolder ON_KILL = REGISTRY.register("on_kill", KillEventListener.Serializer::new); - public static final RegistryObject SKILL_LEARNED = + public static final DeferredHolder SKILL_LEARNED = REGISTRY.register("skill_learned", SkillLearnedEventListener.Serializer::new); - public static final RegistryObject SKILL_REMOVED = + public static final DeferredHolder SKILL_REMOVED = REGISTRY.register("skill_removed", SkillRemovedEventListener.Serializer::new); - public static final RegistryObject TICKING = + public static final DeferredHolder TICKING = REGISTRY.register("ticking", TickingEventListener.Serializer::new); - public static final RegistryObject CRITICAL_HIT = + public static final DeferredHolder CRITICAL_HIT = REGISTRY.register("critical_hit", CritEventListener.Serializer::new); public static List eventsList() { diff --git a/src/main/java/daripher/skilltree/init/PSTFloatFunctions.java b/src/main/java/daripher/skilltree/init/PSTFloatFunctions.java index 242b1bf2e..f302836d2 100644 --- a/src/main/java/daripher/skilltree/init/PSTFloatFunctions.java +++ b/src/main/java/daripher/skilltree/init/PSTFloatFunctions.java @@ -8,31 +8,31 @@ import java.util.Objects; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.*; +import net.neoforged.neoforge.registries.*; public class PSTFloatFunctions { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "numeric_value_providers"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "numeric_value_providers"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject ATTRIBUTE_VALUE = + public static final DeferredHolder ATTRIBUTE_VALUE = REGISTRY.register("attribute_value", AttributeValueFunction.Serializer::new); - public static final RegistryObject EFFECT_AMOUNT = + public static final DeferredHolder EFFECT_AMOUNT = REGISTRY.register("effect_amount", EffectAmountFunction.Serializer::new); - public static final RegistryObject FOOD_LEVEL = + public static final DeferredHolder FOOD_LEVEL = REGISTRY.register("food_level", FoodLevelFunction.Serializer::new); - public static final RegistryObject HEALTH_LEVEL = + public static final DeferredHolder HEALTH_LEVEL = REGISTRY.register("health_level", HealthLevelFunction.Serializer::new); - public static final RegistryObject EQUIPMENT_DURABILITY = + public static final DeferredHolder EQUIPMENT_DURABILITY = REGISTRY.register("equipment_durability", EquipmentDurabilityFunction.Serializer::new); - public static final RegistryObject ENCHANTMENT_AMOUNT = + public static final DeferredHolder ENCHANTMENT_AMOUNT = REGISTRY.register("enchantment_amount", EnchantmentAmountFunction.Serializer::new); - public static final RegistryObject ENCHANTMENT_LEVELS = + public static final DeferredHolder ENCHANTMENT_LEVELS = REGISTRY.register("enchantment_levels", EnchantmentLevelsFunction.Serializer::new); - public static final RegistryObject DISTANCE_TO_TARGET = + public static final DeferredHolder DISTANCE_TO_TARGET = REGISTRY.register("distance_to_target", DistanceToTargetFunction.Serializer::new); - public static final RegistryObject LEARNED_SKILLS_AMOUNT = + public static final DeferredHolder LEARNED_SKILLS_AMOUNT = REGISTRY.register("learned_skills_amount", LearnedSkillsNumberFunction.Serializer::new); @SuppressWarnings("rawtypes") diff --git a/src/main/java/daripher/skilltree/init/PSTItemBonuses.java b/src/main/java/daripher/skilltree/init/PSTItemBonuses.java index cabd78e80..38e555af1 100644 --- a/src/main/java/daripher/skilltree/init/PSTItemBonuses.java +++ b/src/main/java/daripher/skilltree/init/PSTItemBonuses.java @@ -3,17 +3,17 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.skill.bonus.item.*; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTItemBonuses { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "item_bonuses"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "item_bonuses"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject SKILL_BONUS = + public static final DeferredHolder SKILL_BONUS = REGISTRY.register("skill_bonus", SkillBonusItemBonus.Serializer::new); - public static final RegistryObject ITEM_BONUS_LIST = + public static final DeferredHolder ITEM_BONUS_LIST = REGISTRY.register("item_bonus_list", ItemBonusListItemBonus.Serializer::new); } diff --git a/src/main/java/daripher/skilltree/init/PSTItemConditions.java b/src/main/java/daripher/skilltree/init/PSTItemConditions.java index 572d506e9..e35143c94 100644 --- a/src/main/java/daripher/skilltree/init/PSTItemConditions.java +++ b/src/main/java/daripher/skilltree/init/PSTItemConditions.java @@ -7,28 +7,28 @@ import daripher.skilltree.skill.bonus.predicate.item.*; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTItemConditions { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "item_conditions"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "item_conditions"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject NONE = + public static final DeferredHolder NONE = REGISTRY.register("none", NoneItemStackPredicate.Serializer::new); - public static final RegistryObject POTIONS = + public static final DeferredHolder POTIONS = REGISTRY.register("potion", PotionStackPredicate.Serializer::new); - public static final RegistryObject FOOD = + public static final DeferredHolder FOOD = REGISTRY.register("food", FoodStackPredicate.Serializer::new); - public static final RegistryObject ITEM_ID = + public static final DeferredHolder ITEM_ID = REGISTRY.register("item_id", ItemIdPredicate.Serializer::new); - public static final RegistryObject ENCHANTED = + public static final DeferredHolder ENCHANTED = REGISTRY.register("enchanted", EnchantedStackPredicate.Serializer::new); - public static final RegistryObject TAG = + public static final DeferredHolder TAG = REGISTRY.register("tag", ItemTagPredicate.Serializer::new); - public static final RegistryObject EQUIPMENT_TYPE = + public static final DeferredHolder EQUIPMENT_TYPE = REGISTRY.register("equipment_type", EquipmentPredicate.Serializer::new); public static List conditionsList() { diff --git a/src/main/java/daripher/skilltree/init/PSTItems.java b/src/main/java/daripher/skilltree/init/PSTItems.java index 60cfc2f29..7e0f62307 100644 --- a/src/main/java/daripher/skilltree/init/PSTItems.java +++ b/src/main/java/daripher/skilltree/init/PSTItems.java @@ -5,21 +5,21 @@ import daripher.skilltree.item.ModBlockItem; import daripher.skilltree.item.WisdomScrollItem; import net.minecraft.world.item.Item; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries; public class PSTItems { public static final DeferredRegister REGISTRY = DeferredRegister.create(ForgeRegistries.ITEMS, SkillTreeMod.MOD_ID); // scrolls - public static final RegistryObject WISDOM_SCROLL = + public static final DeferredHolder WISDOM_SCROLL = REGISTRY.register("wisdom_scroll", WisdomScrollItem::new); - public static final RegistryObject AMNESIA_SCROLL = + public static final DeferredHolder AMNESIA_SCROLL = REGISTRY.register("amnesia_scroll", AmnesiaScrollItem::new); // blocks - public static final RegistryObject WORKBENCH = + public static final DeferredHolder WORKBENCH = REGISTRY.register("workbench", () -> new ModBlockItem(PSTBlocks.WORKBENCH)); } diff --git a/src/main/java/daripher/skilltree/init/PSTLivingConditions.java b/src/main/java/daripher/skilltree/init/PSTLivingConditions.java index ba61ec06c..89046079d 100644 --- a/src/main/java/daripher/skilltree/init/PSTLivingConditions.java +++ b/src/main/java/daripher/skilltree/init/PSTLivingConditions.java @@ -7,38 +7,38 @@ import daripher.skilltree.skill.bonus.predicate.living.*; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTLivingConditions { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "living_conditions"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "living_conditions"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject NONE = + public static final DeferredHolder NONE = REGISTRY.register("none", NoneLivingEntityPredicate.Serializer::new); - public static final RegistryObject HAS_ITEM_EQUIPPED = + public static final DeferredHolder HAS_ITEM_EQUIPPED = REGISTRY.register("has_item_equipped", HasItemEquippedEntityPredicate.Serializer::new); - public static final RegistryObject HAS_EFFECT = + public static final DeferredHolder HAS_EFFECT = REGISTRY.register("has_effect", HasEffectEntityPredicate.Serializer::new); - public static final RegistryObject BURNING = + public static final DeferredHolder BURNING = REGISTRY.register("burning", BurningEntityPredicate.Serializer::new); - public static final RegistryObject FISHING = + public static final DeferredHolder FISHING = REGISTRY.register("fishing", FishingEntityPredicate.Serializer::new); - public static final RegistryObject UNDERWATER = + public static final DeferredHolder UNDERWATER = REGISTRY.register("underwater", UnderwaterEntityPredicate.Serializer::new); - public static final RegistryObject DUAL_WIELDING = + public static final DeferredHolder DUAL_WIELDING = REGISTRY.register("dual_wielding", DualWieldingEntityPredicate.Serializer::new); - public static final RegistryObject HAS_ITEM_IN_HAND = + public static final DeferredHolder HAS_ITEM_IN_HAND = REGISTRY.register("has_item_in_hand", HasItemInHandEntityPredicate.Serializer::new); - public static final RegistryObject CROUCHING = + public static final DeferredHolder CROUCHING = REGISTRY.register("crouching", CrouchingEntityPredicate.Serializer::new); - public static final RegistryObject UNARMED = + public static final DeferredHolder UNARMED = REGISTRY.register("unarmed", UnarmedEntityPredicate.Serializer::new); - public static final RegistryObject NUMERIC_VALUE = + public static final DeferredHolder NUMERIC_VALUE = REGISTRY.register("numeric_value", FloatFunctionEntityPredicate.Serializer::new); - public static final RegistryObject ALL_ARMOR = + public static final DeferredHolder ALL_ARMOR = REGISTRY.register("all_armor", AllArmorEntityPredicate.Serializer::new); public static List conditionsList() { diff --git a/src/main/java/daripher/skilltree/init/PSTLivingMultipliers.java b/src/main/java/daripher/skilltree/init/PSTLivingMultipliers.java index 731c14e3d..123257ccf 100644 --- a/src/main/java/daripher/skilltree/init/PSTLivingMultipliers.java +++ b/src/main/java/daripher/skilltree/init/PSTLivingMultipliers.java @@ -6,18 +6,18 @@ import java.util.List; import java.util.Objects; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTLivingMultipliers { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "skill_bonus_multipliers"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "skill_bonus_multipliers"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject NONE = + public static final DeferredHolder NONE = REGISTRY.register("none", NoneLivingMultiplier.Serializer::new); - public static final RegistryObject NUMERIC_VALUE = + public static final DeferredHolder NUMERIC_VALUE = REGISTRY.register("numeric_value", FloatFunctionMultiplier.Serializer::new); public static List multiplierList() { diff --git a/src/main/java/daripher/skilltree/init/PSTLootModifiers.java b/src/main/java/daripher/skilltree/init/PSTLootModifiers.java index 0e4ebc1dc..8a4bad992 100644 --- a/src/main/java/daripher/skilltree/init/PSTLootModifiers.java +++ b/src/main/java/daripher/skilltree/init/PSTLootModifiers.java @@ -1,18 +1,18 @@ package daripher.skilltree.init; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import daripher.skilltree.SkillTreeMod; import daripher.skilltree.loot.modifier.AddItemModifier; import daripher.skilltree.loot.modifier.SkillBonusesModifier; -import net.minecraftforge.common.loot.IGlobalLootModifier; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.loot.IGlobalLootModifier; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; public class PSTLootModifiers { - public static final DeferredRegister> REGISTRY = DeferredRegister.create( - ForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, - SkillTreeMod.MOD_ID); + public static final DeferredRegister> REGISTRY = + DeferredRegister.create( + NeoForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, SkillTreeMod.MOD_ID); static { REGISTRY.register("add_item", AddItemModifier.CODEC); diff --git a/src/main/java/daripher/skilltree/init/PSTMenuTypes.java b/src/main/java/daripher/skilltree/init/PSTMenuTypes.java index 0c9619ac8..70718c042 100644 --- a/src/main/java/daripher/skilltree/init/PSTMenuTypes.java +++ b/src/main/java/daripher/skilltree/init/PSTMenuTypes.java @@ -3,28 +3,25 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.client.screen.menu.WorkbenchScreen; import daripher.skilltree.inventory.menu.WorkbenchMenu; -import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.inventory.MenuType; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries; -@Mod.EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD) +@EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = EventBusSubscriber.Bus.MOD) public class PSTMenuTypes { public static final DeferredRegister> REGISTRY = DeferredRegister.create(ForgeRegistries.MENU_TYPES, SkillTreeMod.MOD_ID); - public static final RegistryObject> ARTISAN_WORKBENCH = + public static final DeferredHolder, ? extends MenuType> ARTISAN_WORKBENCH = REGISTRY.register("artisan_workbench", () -> new MenuType<>(WorkbenchMenu::new, FeatureFlags.DEFAULT_FLAGS)); @SubscribeEvent - public static void clientSetup(FMLClientSetupEvent event) { - event.enqueueWork( - () -> MenuScreens.register(ARTISAN_WORKBENCH.get(), WorkbenchScreen::new) - ); + public static void registerScreens(RegisterMenuScreensEvent event) { + event.register(ARTISAN_WORKBENCH.get(), WorkbenchScreen::new); } } diff --git a/src/main/java/daripher/skilltree/init/PSTMobEffects.java b/src/main/java/daripher/skilltree/init/PSTMobEffects.java index ce7057efa..2169f673b 100644 --- a/src/main/java/daripher/skilltree/init/PSTMobEffects.java +++ b/src/main/java/daripher/skilltree/init/PSTMobEffects.java @@ -3,12 +3,13 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.effect.LiquidFireEffect; import net.minecraft.world.effect.MobEffect; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries; public class PSTMobEffects { public static final DeferredRegister REGISTRY = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, SkillTreeMod.MOD_ID); - public static final RegistryObject LIQUID_FIRE = REGISTRY.register("liquid_fire", LiquidFireEffect::new); + public static final DeferredHolder LIQUID_FIRE = + REGISTRY.register("liquid_fire", LiquidFireEffect::new); } diff --git a/src/main/java/daripher/skilltree/init/PSTPotions.java b/src/main/java/daripher/skilltree/init/PSTPotions.java index f2bff18a9..d1cf4b2a2 100644 --- a/src/main/java/daripher/skilltree/init/PSTPotions.java +++ b/src/main/java/daripher/skilltree/init/PSTPotions.java @@ -3,15 +3,15 @@ import daripher.skilltree.SkillTreeMod; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.item.alchemy.Potion; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries; public class PSTPotions { public static final DeferredRegister REGISTRY = DeferredRegister.create(ForgeRegistries.POTIONS, SkillTreeMod.MOD_ID); - public static final RegistryObject LIQUID_FIRE_1 = REGISTRY.register("liquid_fire_1", - () -> new Potion(new MobEffectInstance(PSTMobEffects.LIQUID_FIRE.get()))); - public static final RegistryObject LIQUID_FIRE_2 = REGISTRY.register("liquid_fire_2", - () -> new Potion(new MobEffectInstance(PSTMobEffects.LIQUID_FIRE.get(), 0, 1))); + public static final DeferredHolder LIQUID_FIRE_1 = REGISTRY.register("liquid_fire_1", + () -> new Potion(new MobEffectInstance(PSTMobEffects.LIQUID_FIRE))); + public static final DeferredHolder LIQUID_FIRE_2 = REGISTRY.register("liquid_fire_2", + () -> new Potion(new MobEffectInstance(PSTMobEffects.LIQUID_FIRE, 0, 1))); } diff --git a/src/main/java/daripher/skilltree/init/PSTRecipeSerializers.java b/src/main/java/daripher/skilltree/init/PSTRecipeSerializers.java index 32b14810d..a8da2212c 100644 --- a/src/main/java/daripher/skilltree/init/PSTRecipeSerializers.java +++ b/src/main/java/daripher/skilltree/init/PSTRecipeSerializers.java @@ -4,16 +4,18 @@ import daripher.skilltree.recipe.workbench.WorkbenchCraftingRecipe; import daripher.skilltree.recipe.workbench.WorkbenchItemBonusRecipe; import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries; public class PSTRecipeSerializers { public static final DeferredRegister> REGISTRY = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, SkillTreeMod.MOD_ID); - public static final RegistryObject WORKBENCH_ITEM_BONUS = + public static final DeferredHolder, ? extends WorkbenchItemBonusRecipe.Serializer> + WORKBENCH_ITEM_BONUS = REGISTRY.register("workbench_item_bonus", WorkbenchItemBonusRecipe.Serializer::new); - public static final RegistryObject WORKBENCH_CRAFTING = + public static final DeferredHolder, ? extends WorkbenchCraftingRecipe.Serializer> + WORKBENCH_CRAFTING = REGISTRY.register("workbench_crafting", WorkbenchCraftingRecipe.Serializer::new); } diff --git a/src/main/java/daripher/skilltree/init/PSTRecipeTypes.java b/src/main/java/daripher/skilltree/init/PSTRecipeTypes.java index 58c5d7a73..16902bc0f 100644 --- a/src/main/java/daripher/skilltree/init/PSTRecipeTypes.java +++ b/src/main/java/daripher/skilltree/init/PSTRecipeTypes.java @@ -2,25 +2,22 @@ import daripher.skilltree.SkillTreeMod; import daripher.skilltree.recipe.workbench.AbstractWorkbenchRecipe; -import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries; public class PSTRecipeTypes { public static final DeferredRegister> REGISTRY = DeferredRegister.create(ForgeRegistries.RECIPE_TYPES, SkillTreeMod.MOD_ID); - public static final RecipeType WORKBENCH = register("workbench"); - - private static > RecipeType register(final String identifier) { - RecipeType recipeType = - new RecipeType<>() { - public String toString() { - return identifier; - } - }; - ForgeRegistries.RECIPE_TYPES.register(identifier, recipeType); - return recipeType; - } + public static final DeferredHolder, RecipeType> WORKBENCH = + REGISTRY.register( + "workbench", + () -> + new RecipeType<>() { + public String toString() { + return SkillTreeMod.MOD_ID + ":workbench"; + } + }); } diff --git a/src/main/java/daripher/skilltree/init/PSTRegistries.java b/src/main/java/daripher/skilltree/init/PSTRegistries.java index a10b69c99..e0ef6b7b1 100644 --- a/src/main/java/daripher/skilltree/init/PSTRegistries.java +++ b/src/main/java/daripher/skilltree/init/PSTRegistries.java @@ -12,51 +12,36 @@ import daripher.skilltree.skill.bonus.multiplier.LivingMultiplier; import daripher.skilltree.skill.requirement.SkillRequirement; import java.util.function.Supplier; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.registries.IForgeRegistry; -import net.minecraftforge.registries.NewRegistryEvent; -import net.minecraftforge.registries.RegistryBuilder; +import net.minecraft.core.Registry; +import net.neoforged.neoforge.registries.DeferredRegister; +import daripher.skilltree.util.ForgeRegistries.ForgeRegistry; -@Mod.EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD) public class PSTRegistries { - public static final Supplier> SKILL_BONUSES = - PSTSkillBonuses.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> LIVING_MULTIPLIERS = - PSTLivingMultipliers.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> LIVING_CONDITIONS = - PSTLivingConditions.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> DAMAGE_CONDITIONS = - PSTDamageConditions.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> ITEM_CONDITIONS = - PSTItemConditions.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> - ENCHANTMENT_CONDITIONS = PSTEnchantmentConditions.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> EVENT_LISTENERS = - PSTEventListeners.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> FLOAT_FUNCTIONS = - PSTFloatFunctions.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> SKILL_REQUIREMENTS = - PSTSkillRequirements.REGISTRY.makeRegistry(RegistryBuilder::new); - public static final Supplier> ITEM_BONUSES = - PSTItemBonuses.REGISTRY.makeRegistry(RegistryBuilder::new); + public static final Supplier> SKILL_BONUSES = + createRegistry(PSTSkillBonuses.REGISTRY); + public static final Supplier> LIVING_MULTIPLIERS = + createRegistry(PSTLivingMultipliers.REGISTRY); + public static final Supplier> LIVING_CONDITIONS = + createRegistry(PSTLivingConditions.REGISTRY); + public static final Supplier> DAMAGE_CONDITIONS = + createRegistry(PSTDamageConditions.REGISTRY); + public static final Supplier> ITEM_CONDITIONS = + createRegistry(PSTItemConditions.REGISTRY); + public static final Supplier> + ENCHANTMENT_CONDITIONS = createRegistry(PSTEnchantmentConditions.REGISTRY); + public static final Supplier> EVENT_LISTENERS = + createRegistry(PSTEventListeners.REGISTRY); + public static final Supplier> FLOAT_FUNCTIONS = + createRegistry(PSTFloatFunctions.REGISTRY); + public static final Supplier> SKILL_REQUIREMENTS = + createRegistry(PSTSkillRequirements.REGISTRY); + public static final Supplier> ITEM_BONUSES = + createRegistry(PSTItemBonuses.REGISTRY); - @SubscribeEvent - public static void registerRegistries(NewRegistryEvent event) { - createRegistry(event, PSTSkillBonuses.REGISTRY_ID); - createRegistry(event, PSTLivingMultipliers.REGISTRY_ID); - createRegistry(event, PSTLivingConditions.REGISTRY_ID); - createRegistry(event, PSTDamageConditions.REGISTRY_ID); - createRegistry(event, PSTItemConditions.REGISTRY_ID); - createRegistry(event, PSTEnchantmentConditions.REGISTRY_ID); - createRegistry(event, PSTEventListeners.REGISTRY_ID); - createRegistry(event, PSTFloatFunctions.REGISTRY_ID); - createRegistry(event, PSTSkillRequirements.REGISTRY_ID); - createRegistry(event, PSTItemBonuses.REGISTRY_ID); - } + public static void bootstrap() {} - private static void createRegistry(NewRegistryEvent event, ResourceLocation id) { - event.create(new RegistryBuilder().setName(id)); + private static Supplier> createRegistry(DeferredRegister deferredRegister) { + Registry registry = deferredRegister.makeRegistry(builder -> {}); + return () -> new ForgeRegistry<>(registry); } } diff --git a/src/main/java/daripher/skilltree/init/PSTSkillBonuses.java b/src/main/java/daripher/skilltree/init/PSTSkillBonuses.java index efa77fb73..a70d5ec1e 100644 --- a/src/main/java/daripher/skilltree/init/PSTSkillBonuses.java +++ b/src/main/java/daripher/skilltree/init/PSTSkillBonuses.java @@ -5,89 +5,89 @@ import daripher.skilltree.skill.bonus.SkillBonus; import daripher.skilltree.skill.bonus.player.*; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; import java.util.List; import java.util.Objects; public class PSTSkillBonuses { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "skill_bonuses"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "skill_bonuses"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject ATTRIBUTE = + public static final DeferredHolder ATTRIBUTE = REGISTRY.register("attribute", AttributeBonus.Serializer::new); - public static final RegistryObject COMMAND = + public static final DeferredHolder COMMAND = REGISTRY.register("command", CommandBonus.Serializer::new); - public static final RegistryObject DAMAGE = + public static final DeferredHolder DAMAGE = REGISTRY.register("damage", DamageBonus.Serializer::new); - public static final RegistryObject CRIT_DAMAGE = + public static final DeferredHolder CRIT_DAMAGE = REGISTRY.register("crit_damage", CritDamageBonus.Serializer::new); - public static final RegistryObject CRIT_CHANCE = + public static final DeferredHolder CRIT_CHANCE = REGISTRY.register("crit_chance", CritChanceBonus.Serializer::new); - public static final RegistryObject REPAIR_EFFICIENCY = + public static final DeferredHolder REPAIR_EFFICIENCY = REGISTRY.register("repair_efficiency", RepairEfficiencyBonus.Serializer::new); - public static final RegistryObject BLOCK_BREAK_SPEED = + public static final DeferredHolder BLOCK_BREAK_SPEED = REGISTRY.register("block_break_speed", BlockBreakSpeedBonus.Serializer::new); - public static final RegistryObject FREE_ENCHANTMENT = + public static final DeferredHolder FREE_ENCHANTMENT = REGISTRY.register("free_enchantment", FreeEnchantmentBonus.Serializer::new); - public static final RegistryObject JUMP_HEIGHT = + public static final DeferredHolder JUMP_HEIGHT = REGISTRY.register("jump_height", JumpHeightBonus.Serializer::new); - public static final RegistryObject INCOMING_HEALING = + public static final DeferredHolder INCOMING_HEALING = REGISTRY.register("incoming_healing", IncomingHealingBonus.Serializer::new); - public static final RegistryObject LOOT_DUPLICATION = + public static final DeferredHolder LOOT_DUPLICATION = REGISTRY.register("loot_duplication", LootDuplicationBonus.Serializer::new); - public static final RegistryObject GAINED_EXPERIENCE = + public static final DeferredHolder GAINED_EXPERIENCE = REGISTRY.register("gained_experience", GainedExperienceBonus.Serializer::new); - public static final RegistryObject INFLICT_IGNITE = + public static final DeferredHolder INFLICT_IGNITE = REGISTRY.register("inflict_ignite", InflictIgniteBonus.Serializer::new); - public static final RegistryObject ARROW_RETRIEVAL = + public static final DeferredHolder ARROW_RETRIEVAL = REGISTRY.register("arrow_retrieval", ArrowRetrievalBonus.Serializer::new); - public static final RegistryObject HEALTH_RESERVATION = + public static final DeferredHolder HEALTH_RESERVATION = REGISTRY.register("health_reservation", HealthReservationBonus.Serializer::new); - public static final RegistryObject ALL_ATTRIBUTES = + public static final DeferredHolder ALL_ATTRIBUTES = REGISTRY.register("all_attributes", AllAttributesBonus.Serializer::new); - public static final RegistryObject INFLICT_EFFECT = + public static final DeferredHolder INFLICT_EFFECT = REGISTRY.register("inflict_effect", InflictEffectBonus.Serializer::new); - public static final RegistryObject CANT_USE_ITEM = + public static final DeferredHolder CANT_USE_ITEM = REGISTRY.register("cant_use_item", CantUseItemBonus.Serializer::new); - public static final RegistryObject HEALING = + public static final DeferredHolder HEALING = REGISTRY.register("healing", HealingBonus.Serializer::new); - public static final RegistryObject INFLICT_DAMAGE = + public static final DeferredHolder INFLICT_DAMAGE = REGISTRY.register("inflict_damage", InflictDamageBonus.Serializer::new); - public static final RegistryObject CAN_POISON_ANYONE = + public static final DeferredHolder CAN_POISON_ANYONE = REGISTRY.register("can_poison_anyone", CanPoisonAnyoneBonus.Serializer::new); - public static final RegistryObject LETHAL_POISON = + public static final DeferredHolder LETHAL_POISON = REGISTRY.register("lethal_poison", LethalPoisonBonus.Serializer::new); - public static final RegistryObject DAMAGE_TAKEN = + public static final DeferredHolder DAMAGE_TAKEN = REGISTRY.register("damage_taken", DamageTakenBonus.Serializer::new); - public static final RegistryObject DAMAGE_AVOIDANCE = + public static final DeferredHolder DAMAGE_AVOIDANCE = REGISTRY.register("damage_avoidance", DamageAvoidanceBonus.Serializer::new); - public static final RegistryObject DAMAGE_CONVERSION = + public static final DeferredHolder DAMAGE_CONVERSION = REGISTRY.register("damage_conversion", DamageConversionBonus.Serializer::new); - public static final RegistryObject GRANT_ITEM = + public static final DeferredHolder GRANT_ITEM = REGISTRY.register("grant_item", GrantItemBonus.Serializer::new); - public static final RegistryObject EFFECT_DURATION = + public static final DeferredHolder EFFECT_DURATION = REGISTRY.register("effect_duration", EffectDurationBonus.Serializer::new); - public static final RegistryObject PROJECTILE_DUPLICATION = + public static final DeferredHolder PROJECTILE_DUPLICATION = REGISTRY.register("projectile_duplication", ProjectileDuplicationBonus.Serializer::new); - public static final RegistryObject SELF_SPLASH_IMMUNE = + public static final DeferredHolder SELF_SPLASH_IMMUNE = REGISTRY.register("self_splash_immune", SelfSplashImmuneBonus.Serializer::new); - public static final RegistryObject PROJECTILE_SPEED = + public static final DeferredHolder PROJECTILE_SPEED = REGISTRY.register("projectile_speed", ProjectileSpeedBonus.Serializer::new); - public static final RegistryObject ITEM_DURABILITY_LOSS_AVOIDANCE = + public static final DeferredHolder ITEM_DURABILITY_LOSS_AVOIDANCE = REGISTRY.register("item_durability_loss_avoidance", ItemDurabilityLossAvoidanceBonus.Serializer::new); - public static final RegistryObject ITEM_USAGE_SPEED = + public static final DeferredHolder ITEM_USAGE_SPEED = REGISTRY.register("item_usage_speed", ItemUsageSpeedBonus.Serializer::new); - public static final RegistryObject ITEM_USE_MOVEMENT_SPEED = + public static final DeferredHolder ITEM_USE_MOVEMENT_SPEED = REGISTRY.register("item_use_movement_speed", ItemUseMovementSpeedBonus.Serializer::new); - public static final RegistryObject RECIPE_UNLOCK = + public static final DeferredHolder RECIPE_UNLOCK = REGISTRY.register("recipe_unlock", RecipeUnlockBonus.Serializer::new); - public static final RegistryObject MORE_ITEM_BONUSES = + public static final DeferredHolder MORE_ITEM_BONUSES = REGISTRY.register("more_item_bonuses", MoreItemBonusesBonus.Serializer::new); - public static final RegistryObject GAIN_EXPERIENCE = + public static final DeferredHolder GAIN_EXPERIENCE = REGISTRY.register("gain_experience", GainExperienceBonus.Serializer::new); @SuppressWarnings("rawtypes") diff --git a/src/main/java/daripher/skilltree/init/PSTSkillRequirements.java b/src/main/java/daripher/skilltree/init/PSTSkillRequirements.java index faf4bebe9..4eca897a0 100644 --- a/src/main/java/daripher/skilltree/init/PSTSkillRequirements.java +++ b/src/main/java/daripher/skilltree/init/PSTSkillRequirements.java @@ -8,22 +8,22 @@ import daripher.skilltree.skill.requirement.*; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredHolder; public class PSTSkillRequirements { public static final ResourceLocation REGISTRY_ID = - new ResourceLocation(SkillTreeMod.MOD_ID, "skill_requirements"); + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "skill_requirements"); public static final DeferredRegister REGISTRY = DeferredRegister.create(REGISTRY_ID, SkillTreeMod.MOD_ID); - public static final RegistryObject STAT_VALUE = + public static final DeferredHolder STAT_VALUE = REGISTRY.register("stat_value", StatRequirement.Serializer::new); - public static final RegistryObject NUMERIC_VALUE = + public static final DeferredHolder NUMERIC_VALUE = REGISTRY.register("numeric_value", NumericValueRequirement.Serializer::new); - public static final RegistryObject ADVANCEMENT = + public static final DeferredHolder ADVANCEMENT = REGISTRY.register("advancement", AdvancementRequirement.Serializer::new); - public static final RegistryObject LEARNED_SKILL = + public static final DeferredHolder LEARNED_SKILL = REGISTRY.register("learned_skill", LearnedSkillRequirement.Serializer::new); @SuppressWarnings("rawtypes") diff --git a/src/main/java/daripher/skilltree/init/PSTTags.java b/src/main/java/daripher/skilltree/init/PSTTags.java index 430d49bea..3d564f44c 100644 --- a/src/main/java/daripher/skilltree/init/PSTTags.java +++ b/src/main/java/daripher/skilltree/init/PSTTags.java @@ -6,25 +6,25 @@ import net.minecraft.tags.TagKey; import net.minecraft.world.damagesource.DamageType; import net.minecraft.world.item.Item; +import net.neoforged.neoforge.common.Tags; public class PSTTags { public static class DamageTypes { - public static final TagKey IS_MAGIC = - TagKey.create(Registries.DAMAGE_TYPE, new ResourceLocation("forge", "is_magic")); + public static final TagKey IS_MAGIC = Tags.DamageTypes.IS_MAGIC; } public static class Items { public static final TagKey RINGS = - ItemTags.create(new ResourceLocation("curios", "ring")); + ItemTags.create(ResourceLocation.fromNamespaceAndPath("curios", "ring")); public static final TagKey NECKLACES = - ItemTags.create(new ResourceLocation("curios", "necklace")); + ItemTags.create(ResourceLocation.fromNamespaceAndPath("curios", "necklace")); public static final TagKey JEWELRY = - ItemTags.create(new ResourceLocation("forge", "curios/jewelry")); + ItemTags.create(ResourceLocation.fromNamespaceAndPath("curios", "jewelry")); public static final TagKey MELEE_WEAPON = - ItemTags.create(new ResourceLocation("skilltree", "melee_weapon")); + ItemTags.create(ResourceLocation.fromNamespaceAndPath("skilltree", "melee_weapon")); public static final TagKey RANGED_WEAPON = - ItemTags.create(new ResourceLocation("skilltree", "ranged_weapon")); + ItemTags.create(ResourceLocation.fromNamespaceAndPath("skilltree", "ranged_weapon")); public static final TagKey LEATHER_ARMOR = - ItemTags.create(new ResourceLocation("skilltree", "armors/leather")); + ItemTags.create(ResourceLocation.fromNamespaceAndPath("skilltree", "armors/leather")); } } diff --git a/src/main/java/daripher/skilltree/inventory/menu/WorkbenchContainer.java b/src/main/java/daripher/skilltree/inventory/menu/WorkbenchContainer.java index 584dda440..4c2a392e9 100644 --- a/src/main/java/daripher/skilltree/inventory/menu/WorkbenchContainer.java +++ b/src/main/java/daripher/skilltree/inventory/menu/WorkbenchContainer.java @@ -6,8 +6,9 @@ import net.minecraft.world.inventory.TransientCraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeInput; -public class WorkbenchContainer extends TransientCraftingContainer { +public class WorkbenchContainer extends TransientCraftingContainer implements RecipeInput { public final WorkbenchMenu menu; public WorkbenchContainer(WorkbenchMenu menu) { @@ -23,6 +24,11 @@ public ItemStack getBaseItem() { return getItem(0); } + @Override + public int size() { + return getContainerSize(); + } + public boolean hasIngredients(Map ingredients) { Map remaining = new HashMap<>(ingredients); for (int i = 1; i < getContainerSize(); i++) { diff --git a/src/main/java/daripher/skilltree/inventory/menu/WorkbenchMenu.java b/src/main/java/daripher/skilltree/inventory/menu/WorkbenchMenu.java index 3a1d64d0a..2e354df42 100644 --- a/src/main/java/daripher/skilltree/inventory/menu/WorkbenchMenu.java +++ b/src/main/java/daripher/skilltree/inventory/menu/WorkbenchMenu.java @@ -15,6 +15,7 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.*; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -160,7 +161,7 @@ private void updateSelectedRecipe() { updateCraftingResult(selectedRecipe); return; } - if (!ItemStack.isSameItemSameTags(input, prevInput)) { + if (!ItemStack.isSameItemSameComponents(input, prevInput)) { setupRecipeList(); prevInput = input.copy(); } @@ -181,7 +182,7 @@ private void updateCraftingResult(AbstractWorkbenchRecipe selectedRecipe) { else { if (!level.isClientSide) { ItemStack craftResult = selectedRecipe.assemble(workbenchContainer, level.registryAccess()); - resultSlots.setRecipeUsed(selectedRecipe); + resultSlots.setRecipeUsed(new RecipeHolder<>(selectedRecipe.getId(), selectedRecipe)); resultSlots.setItem(0, craftResult); } } @@ -191,7 +192,8 @@ private void setupRecipeList() { selectedRecipeIndex.set(-1); resultSlots.setItem(0, ItemStack.EMPTY); selectedRecipes = - level.getRecipeManager().getAllRecipesFor(PSTRecipeTypes.WORKBENCH).stream() + level.getRecipeManager().getAllRecipesFor(PSTRecipeTypes.WORKBENCH.get()).stream() + .map(RecipeHolder::value) .filter(this::shouldDisplayRecipe) .sorted(Comparator.comparing(AbstractWorkbenchRecipe::getId)) .toList(); diff --git a/src/main/java/daripher/skilltree/inventory/slot/WorkbenchResultSlot.java b/src/main/java/daripher/skilltree/inventory/slot/WorkbenchResultSlot.java index 975fec4c8..a5dbff880 100644 --- a/src/main/java/daripher/skilltree/inventory/slot/WorkbenchResultSlot.java +++ b/src/main/java/daripher/skilltree/inventory/slot/WorkbenchResultSlot.java @@ -9,7 +9,7 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.event.ForgeEventFactory; +import net.neoforged.neoforge.event.EventHooks; import org.jetbrains.annotations.NotNull; public class WorkbenchResultSlot extends Slot { @@ -84,7 +84,7 @@ protected void onSwapCraft(int numItemsCrafted) { protected void checkTakeAchievements(@NotNull ItemStack itemStack) { if (removeCount > 0) { itemStack.onCraftedBy(player.level(), player, removeCount); - ForgeEventFactory.firePlayerCraftingEvent(player, itemStack, workbenchContainer); + EventHooks.firePlayerCraftingEvent(player, itemStack, workbenchContainer); consumeMaterials(); } removeCount = 0; diff --git a/src/main/java/daripher/skilltree/item/AmnesiaScrollItem.java b/src/main/java/daripher/skilltree/item/AmnesiaScrollItem.java index df859c311..92ce427b5 100644 --- a/src/main/java/daripher/skilltree/item/AmnesiaScrollItem.java +++ b/src/main/java/daripher/skilltree/item/AmnesiaScrollItem.java @@ -3,8 +3,6 @@ import daripher.skilltree.capability.skill.IPlayerSkills; import daripher.skilltree.capability.skill.PlayerSkillsProvider; import daripher.skilltree.config.ServerConfig; -import daripher.skilltree.network.NetworkDispatcher; -import daripher.skilltree.network.message.SyncPlayerSkillsMessage; import java.util.List; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; @@ -17,7 +15,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; -import net.minecraftforge.network.PacketDistributor; import org.jetbrains.annotations.NotNull; public class AmnesiaScrollItem extends Item { @@ -53,9 +50,7 @@ public AmnesiaScrollItem() { player.sendSystemMessage( Component.translatable("skilltree.message.reset_command") .withStyle(ChatFormatting.YELLOW)); - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), - new SyncPlayerSkillsMessage(player)); + PlayerSkillsProvider.sendPlayerSkills((ServerPlayer) player); } return InteractionResultHolder.sidedSuccess(scroll, level.isClientSide); } @@ -63,7 +58,7 @@ public AmnesiaScrollItem() { @Override public void appendHoverText( @NotNull ItemStack itemStack, - Level level, + Item.TooltipContext context, List components, @NotNull TooltipFlag tooltipFlag) { components.add( diff --git a/src/main/java/daripher/skilltree/item/ModBlockItem.java b/src/main/java/daripher/skilltree/item/ModBlockItem.java index ca3432f5e..d6aac68aa 100644 --- a/src/main/java/daripher/skilltree/item/ModBlockItem.java +++ b/src/main/java/daripher/skilltree/item/ModBlockItem.java @@ -2,10 +2,10 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.level.block.Block; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; public class ModBlockItem extends BlockItem { - public ModBlockItem(RegistryObject blockRegistryObject) { + public ModBlockItem(DeferredHolder blockRegistryObject) { super(blockRegistryObject.get(), new Properties()); } } diff --git a/src/main/java/daripher/skilltree/item/WisdomScrollItem.java b/src/main/java/daripher/skilltree/item/WisdomScrollItem.java index ef15ac8ce..d15d5d1bb 100644 --- a/src/main/java/daripher/skilltree/item/WisdomScrollItem.java +++ b/src/main/java/daripher/skilltree/item/WisdomScrollItem.java @@ -3,8 +3,6 @@ import daripher.skilltree.capability.skill.IPlayerSkills; import daripher.skilltree.capability.skill.PlayerSkillsProvider; import daripher.skilltree.config.ServerConfig; -import daripher.skilltree.network.NetworkDispatcher; -import daripher.skilltree.network.message.SyncPlayerSkillsMessage; import java.util.List; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; @@ -17,7 +15,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; -import net.minecraftforge.network.PacketDistributor; import org.jetbrains.annotations.NotNull; public class WisdomScrollItem extends Item { @@ -54,9 +51,7 @@ public WisdomScrollItem() { 0.4F, 0.2F + player.getRandom().nextFloat() * 0.3F); skillsCapability.grantSkillPoints(1); - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), - new SyncPlayerSkillsMessage(player)); + PlayerSkillsProvider.sendPlayerSkills((ServerPlayer) player); if (ServerConfig.show_chat_messages) { player.sendSystemMessage( Component.translatable("skilltree.message.point_command") @@ -69,7 +64,7 @@ public WisdomScrollItem() { @Override public void appendHoverText( @NotNull ItemStack itemStack, - Level level, + Item.TooltipContext context, List components, @NotNull TooltipFlag tooltipFlag) { components.add( diff --git a/src/main/java/daripher/skilltree/loot/modifier/AddItemModifier.java b/src/main/java/daripher/skilltree/loot/modifier/AddItemModifier.java index 2838e3098..ea46dfb80 100644 --- a/src/main/java/daripher/skilltree/loot/modifier/AddItemModifier.java +++ b/src/main/java/daripher/skilltree/loot/modifier/AddItemModifier.java @@ -1,15 +1,14 @@ package daripher.skilltree.loot.modifier; import com.google.common.base.Suppliers; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.function.Supplier; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraftforge.common.loot.IGlobalLootModifier; -import net.minecraftforge.common.loot.LootModifier; +import net.neoforged.neoforge.common.loot.LootModifier; import org.jetbrains.annotations.NotNull; public class AddItemModifier extends LootModifier { @@ -20,10 +19,10 @@ public AddItemModifier(ItemStack item, LootItemCondition... conditionsIn) { this.itemStack = item; } - public static final Supplier> CODEC = + public static final Supplier> CODEC = Suppliers.memoize( () -> - RecordCodecBuilder.create( + RecordCodecBuilder.mapCodec( inst -> codecStart(inst) .and(ItemStack.CODEC.fieldOf("item").forGetter(m -> m.itemStack)) @@ -44,7 +43,7 @@ public AddItemModifier(ItemStack item, LootItemCondition... conditionsIn) { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC.get(); } } diff --git a/src/main/java/daripher/skilltree/loot/modifier/SkillBonusesModifier.java b/src/main/java/daripher/skilltree/loot/modifier/SkillBonusesModifier.java index 446992cd3..e7b206d27 100644 --- a/src/main/java/daripher/skilltree/loot/modifier/SkillBonusesModifier.java +++ b/src/main/java/daripher/skilltree/loot/modifier/SkillBonusesModifier.java @@ -1,7 +1,7 @@ package daripher.skilltree.loot.modifier; import com.google.common.base.Suppliers; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import daripher.skilltree.skill.bonus.SkillBonusHandler; import daripher.skilltree.skill.bonus.player.LootDuplicationBonus; @@ -11,8 +11,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraftforge.common.loot.IGlobalLootModifier; -import net.minecraftforge.common.loot.LootModifier; +import net.neoforged.neoforge.common.loot.LootModifier; import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; @@ -25,8 +24,8 @@ public SkillBonusesModifier(LootItemCondition... conditionsIn) { super(conditionsIn); } - public static final Supplier> CODEC = - Suppliers.memoize(() -> RecordCodecBuilder.create(inst -> codecStart(inst).apply(inst, SkillBonusesModifier::new))); + public static final Supplier> CODEC = + Suppliers.memoize(() -> RecordCodecBuilder.mapCodec(inst -> codecStart(inst).apply(inst, SkillBonusesModifier::new))); @Override protected @NotNull ObjectArrayList doApply(ObjectArrayList generatedLoot, LootContext lootContext) { @@ -93,7 +92,7 @@ private static Map getLootMultipliers(Player player, LootDuplicati } @Override - public Codec codec() { + public MapCodec codec() { return CODEC.get(); } } diff --git a/src/main/java/daripher/skilltree/mixin/ClientAdvancementsAccessor.java b/src/main/java/daripher/skilltree/mixin/ClientAdvancementsAccessor.java index 7771b4f11..98bbb57f8 100644 --- a/src/main/java/daripher/skilltree/mixin/ClientAdvancementsAccessor.java +++ b/src/main/java/daripher/skilltree/mixin/ClientAdvancementsAccessor.java @@ -1,6 +1,6 @@ package daripher.skilltree.mixin; -import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.AdvancementProgress; import net.minecraft.client.multiplayer.ClientAdvancements; import org.spongepowered.asm.mixin.Mixin; @@ -11,5 +11,5 @@ @Mixin(ClientAdvancements.class) public interface ClientAdvancementsAccessor { @Accessor - Map getProgress(); + Map getProgress(); } diff --git a/src/main/java/daripher/skilltree/mixin/EditBoxAccessor.java b/src/main/java/daripher/skilltree/mixin/EditBoxAccessor.java index 880351022..258af0bc0 100644 --- a/src/main/java/daripher/skilltree/mixin/EditBoxAccessor.java +++ b/src/main/java/daripher/skilltree/mixin/EditBoxAccessor.java @@ -22,9 +22,6 @@ public interface EditBoxAccessor { @Accessor int getHighlightPos(); - @Accessor - int getFrame(); - @Accessor int getMaxLength(); diff --git a/src/main/java/daripher/skilltree/mixin/minecraft/ArmorSlotMixin.java b/src/main/java/daripher/skilltree/mixin/minecraft/ArmorSlotMixin.java index 11f73d7f7..371a26a49 100644 --- a/src/main/java/daripher/skilltree/mixin/minecraft/ArmorSlotMixin.java +++ b/src/main/java/daripher/skilltree/mixin/minecraft/ArmorSlotMixin.java @@ -10,7 +10,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(targets = "net.minecraft.world.inventory.InventoryMenu$1") +@Mixin(targets = "net.minecraft.world.inventory.ArmorSlot") public abstract class ArmorSlotMixin extends Slot { @SuppressWarnings("DataFlowIssue") public ArmorSlotMixin() { diff --git a/src/main/java/daripher/skilltree/mixin/minecraft/ClientPacketListenerMixin.java b/src/main/java/daripher/skilltree/mixin/minecraft/ClientPacketListenerMixin.java new file mode 100644 index 000000000..6bc878757 --- /dev/null +++ b/src/main/java/daripher/skilltree/mixin/minecraft/ClientPacketListenerMixin.java @@ -0,0 +1,25 @@ +package daripher.skilltree.mixin.minecraft; + +import net.minecraft.client.Minecraft; +import daripher.skilltree.client.screen.StatsUpdateListener; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.protocol.game.ClientboundAwardStatsPacket; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ClientPacketListener.class) +public abstract class ClientPacketListenerMixin { + @Inject( + method = "handleAwardStats(Lnet/minecraft/network/protocol/game/ClientboundAwardStatsPacket;)V", + at = @At("TAIL"), + remap = false) + private void notifyStatsScreen(ClientboundAwardStatsPacket packet, CallbackInfo ci) { + Screen screen = Minecraft.getInstance().screen; + if (screen instanceof StatsUpdateListener statsUpdateListener) { + statsUpdateListener.onStatsUpdated(); + } + } +} diff --git a/src/main/java/daripher/skilltree/mixin/minecraft/ItemStackMixin.java b/src/main/java/daripher/skilltree/mixin/minecraft/ItemStackMixin.java index 3dd6fb22e..10d9cd6ff 100644 --- a/src/main/java/daripher/skilltree/mixin/minecraft/ItemStackMixin.java +++ b/src/main/java/daripher/skilltree/mixin/minecraft/ItemStackMixin.java @@ -2,35 +2,44 @@ import daripher.skilltree.skill.bonus.SkillBonusHandler; import daripher.skilltree.skill.bonus.player.ItemDurabilityLossAvoidanceBonus; +import java.util.function.Consumer; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.RandomSource; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ItemStack.class) public class ItemStackMixin { - @Inject(method = "hurt", at = @At("HEAD"), cancellable = true) + @Inject( + method = + "hurtAndBreak(ILnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/LivingEntity;Ljava/util/function/Consumer;)V", + at = @At("HEAD"), + cancellable = true, + remap = false) public void preventDurabilityLoss( int amount, - RandomSource random, - @Nullable ServerPlayer user, - CallbackInfoReturnable callbackInfo) { - if (user == null) { + ServerLevel level, + @Nullable LivingEntity user, + Consumer onBreak, + CallbackInfo callbackInfo) { + if (!(user instanceof ServerPlayer player)) { return; } @SuppressWarnings("DataFlowIssue") ItemStack itemStack = (ItemStack) (Object) this; float chance = - SkillBonusHandler.getSkillBonuses(user, ItemDurabilityLossAvoidanceBonus.class).stream() - .map(bonus -> bonus.getChance(user, itemStack)) + SkillBonusHandler.getSkillBonuses(player, ItemDurabilityLossAvoidanceBonus.class).stream() + .map(bonus -> bonus.getChance(player, itemStack)) .reduce(Float::sum) .orElse(0f); - if (random.nextFloat() < chance) { - callbackInfo.setReturnValue(false); + if (level.getRandom().nextFloat() < chance) { + callbackInfo.cancel(); } } } diff --git a/src/main/java/daripher/skilltree/mixin/minecraft/LivingEntityMixin.java b/src/main/java/daripher/skilltree/mixin/minecraft/LivingEntityMixin.java index 02a89b622..620300922 100644 --- a/src/main/java/daripher/skilltree/mixin/minecraft/LivingEntityMixin.java +++ b/src/main/java/daripher/skilltree/mixin/minecraft/LivingEntityMixin.java @@ -5,6 +5,7 @@ import daripher.skilltree.skill.bonus.SkillBonusHandler; import java.util.ArrayList; import java.util.List; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; @@ -21,8 +22,12 @@ public abstract class LivingEntityMixin implements EquippedEntity { private final List equippedItems = new ArrayList<>(); @SuppressWarnings("unused") - @Inject(method = "dropAllDeathLoot", at = @At("HEAD")) - private void storeEquipmentBeforeDeath(DamageSource damageSource, CallbackInfo callbackInfo) { + @Inject( + method = "dropAllDeathLoot(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;)V", + at = @At("HEAD"), + remap = false) + private void storeEquipmentBeforeDeath( + ServerLevel level, DamageSource damageSource, CallbackInfo callbackInfo) { for (EquipmentSlot slot : EquipmentSlot.values()) { ItemStack itemInSlot = getItemBySlot(slot); if (itemInSlot.isEmpty()) continue; @@ -31,7 +36,7 @@ private void storeEquipmentBeforeDeath(DamageSource damageSource, CallbackInfo c } @SuppressWarnings({"ConstantValue", "unused"}) - @ModifyReturnValue(method = "getJumpPower", at = @At("RETURN")) + @ModifyReturnValue(method = "getJumpPower()F", at = @At("RETURN"), remap = false) private float applyJumpHeightBonus(float original) { boolean isPlayer = (Object) this instanceof Player; if (!isPlayer) return original; diff --git a/src/main/java/daripher/skilltree/mixin/minecraft/MobEffectMixin.java b/src/main/java/daripher/skilltree/mixin/minecraft/MobEffectMixin.java index 3d7b7eb79..ccd36bb2f 100644 --- a/src/main/java/daripher/skilltree/mixin/minecraft/MobEffectMixin.java +++ b/src/main/java/daripher/skilltree/mixin/minecraft/MobEffectMixin.java @@ -13,20 +13,24 @@ import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.extensions.IForgeMobEffect; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(MobEffect.class) -public abstract class MobEffectMixin implements IForgeMobEffect { - @Inject(method = "applyEffectTick", at = @At("HEAD"), cancellable = true) - public void inflictPoisonDamage(LivingEntity livingEntity, int amplifier, CallbackInfo callbackInfo) { +public abstract class MobEffectMixin { + @Inject( + method = "applyEffectTick(Lnet/minecraft/world/entity/LivingEntity;I)Z", + at = @At("HEAD"), + cancellable = true, + remap = false) + public void inflictPoisonDamage( + LivingEntity livingEntity, int amplifier, CallbackInfoReturnable callbackInfo) { //noinspection ConstantValue if (((Object) this) != MobEffects.POISON) return; handlePoisonDamage(livingEntity); - callbackInfo.cancel(); + callbackInfo.setReturnValue(true); } private static void handlePoisonDamage(LivingEntity livingEntity) { diff --git a/src/main/java/daripher/skilltree/mixin/minecraft/PlayerMixin.java b/src/main/java/daripher/skilltree/mixin/minecraft/PlayerMixin.java index b8d05038d..3756b416b 100644 --- a/src/main/java/daripher/skilltree/mixin/minecraft/PlayerMixin.java +++ b/src/main/java/daripher/skilltree/mixin/minecraft/PlayerMixin.java @@ -18,7 +18,10 @@ protected PlayerMixin() { } @SuppressWarnings("DataFlowIssue") - @Inject(method = "onEnchantmentPerformed", at = @At("HEAD")) + @Inject( + method = "onEnchantmentPerformed(Lnet/minecraft/world/item/ItemStack;I)V", + at = @At("HEAD"), + remap = false) private void restoreEnchantmentExperience( ItemStack itemStack, int enchantmentCost, CallbackInfo callbackInfo) { Player player = (Player) (Object) this; diff --git a/src/main/java/daripher/skilltree/mixin/minecraft/ThrownPotionMixin.java b/src/main/java/daripher/skilltree/mixin/minecraft/ThrownPotionMixin.java index c69b01e16..acacd7a2a 100644 --- a/src/main/java/daripher/skilltree/mixin/minecraft/ThrownPotionMixin.java +++ b/src/main/java/daripher/skilltree/mixin/minecraft/ThrownPotionMixin.java @@ -24,13 +24,14 @@ private ThrownPotionMixin() { super(null, null); } - @Redirect(method = "applySplash", + @Redirect(method = "applySplash(Ljava/lang/Iterable;Lnet/minecraft/world/entity/Entity;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;" + "addEffect(" + "Lnet/minecraft/world/effect/MobEffectInstance;" + "Lnet/minecraft/world/entity/Entity;" + - ")Z")) + ")Z"), + remap = false) private boolean setAttackerOnHit(LivingEntity entity, MobEffectInstance effectInstance, Entity effectSource) { if (getOwner() instanceof Player player) { entity.setLastHurtByPlayer(player); @@ -38,13 +39,14 @@ private boolean setAttackerOnHit(LivingEntity entity, MobEffectInstance effectIn return entity.addEffect(effectInstance, effectSource); } - @Redirect(method = "applySplash", + @Redirect(method = "applySplash(Ljava/lang/Iterable;Lnet/minecraft/world/entity/Entity;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;" + "getEntitiesOfClass(" + "Ljava/lang/Class;" + "Lnet/minecraft/world/phys/AABB;" + - ")Ljava/util/List;")) + ")Ljava/util/List;"), + remap = false) private List removePlayerTarget(Level level, Class entityClass, AABB area) { List targets = level.getEntitiesOfClass(entityClass, area); Entity owner = getOwner(); @@ -63,4 +65,3 @@ private List removePlayerTarget(Level level, Class enti return targets; } } - diff --git a/src/main/java/daripher/skilltree/network/NetworkDispatcher.java b/src/main/java/daripher/skilltree/network/NetworkDispatcher.java index cd46fc2fc..f368ceaef 100644 --- a/src/main/java/daripher/skilltree/network/NetworkDispatcher.java +++ b/src/main/java/daripher/skilltree/network/NetworkDispatcher.java @@ -5,55 +5,26 @@ import daripher.skilltree.network.message.LearnSkillMessage; import daripher.skilltree.network.message.SyncPlayerSkillsMessage; import daripher.skilltree.network.message.SyncServerDataMessage; -import java.util.Optional; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkRegistry; -import net.minecraftforge.network.simple.SimpleChannel; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.EventBusSubscriber.Bus; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; @EventBusSubscriber(bus = Bus.MOD, modid = SkillTreeMod.MOD_ID) public class NetworkDispatcher { - public static SimpleChannel network_channel; - @SubscribeEvent - public static void registerNetworkChannel(FMLCommonSetupEvent event) { - network_channel = - NetworkRegistry.newSimpleChannel( - new ResourceLocation(SkillTreeMod.MOD_ID, "channel"), - () -> "1.0", - s -> true, - s -> true); - network_channel.registerMessage( - 1, - SyncServerDataMessage.class, - SyncServerDataMessage::encode, - SyncServerDataMessage::decode, - SyncServerDataMessage::receive, - Optional.of(NetworkDirection.PLAY_TO_CLIENT)); - network_channel.registerMessage( - 2, - SyncPlayerSkillsMessage.class, - SyncPlayerSkillsMessage::encode, - SyncPlayerSkillsMessage::decode, - SyncPlayerSkillsMessage::receive, - Optional.of(NetworkDirection.PLAY_TO_CLIENT)); - network_channel.registerMessage( - 3, - LearnSkillMessage.class, - LearnSkillMessage::encode, - LearnSkillMessage::decode, - LearnSkillMessage::receive, - Optional.of(NetworkDirection.PLAY_TO_SERVER)); - network_channel.registerMessage( - 4, - GainSkillPointMessage.class, - (msg, buf) -> {}, - (buf) -> new GainSkillPointMessage(), - (msg, ctx) -> GainSkillPointMessage.receive(ctx), - Optional.of(NetworkDirection.PLAY_TO_SERVER)); + public static void registerPayloadHandlers(RegisterPayloadHandlersEvent event) { + PayloadRegistrar registrar = event.registrar("1"); + registrar.playToClient( + SyncServerDataMessage.TYPE, SyncServerDataMessage.STREAM_CODEC, SyncServerDataMessage::handle); + registrar.playToClient( + SyncPlayerSkillsMessage.TYPE, + SyncPlayerSkillsMessage.STREAM_CODEC, + SyncPlayerSkillsMessage::handle); + registrar.playToServer( + LearnSkillMessage.TYPE, LearnSkillMessage.STREAM_CODEC, LearnSkillMessage::handle); + registrar.playToServer( + GainSkillPointMessage.TYPE, GainSkillPointMessage.STREAM_CODEC, GainSkillPointMessage::handle); } } diff --git a/src/main/java/daripher/skilltree/network/NetworkHelper.java b/src/main/java/daripher/skilltree/network/NetworkHelper.java index 97d621028..d697bd8a5 100644 --- a/src/main/java/daripher/skilltree/network/NetworkHelper.java +++ b/src/main/java/daripher/skilltree/network/NetworkHelper.java @@ -16,6 +16,7 @@ import java.util.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; @@ -26,7 +27,7 @@ import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import net.minecraftforge.registries.ForgeRegistries; +import daripher.skilltree.util.ForgeRegistries; import org.jetbrains.annotations.NotNull; public class NetworkHelper { @@ -51,11 +52,11 @@ public static void writePassiveSkill(FriendlyByteBuf buf, PassiveSkill skill) { } public static PassiveSkill readPassiveSkill(FriendlyByteBuf buf) { - ResourceLocation id = new ResourceLocation(buf.readUtf()); + ResourceLocation id = ResourceLocation.parse(buf.readUtf()); int size = buf.readInt(); - ResourceLocation background = new ResourceLocation(buf.readUtf()); - ResourceLocation icon = new ResourceLocation(buf.readUtf()); - ResourceLocation border = new ResourceLocation(buf.readUtf()); + ResourceLocation background = ResourceLocation.parse(buf.readUtf()); + ResourceLocation icon = ResourceLocation.parse(buf.readUtf()); + ResourceLocation border = ResourceLocation.parse(buf.readUtf()); boolean startingPoint = buf.readBoolean(); PassiveSkill skill = new PassiveSkill(id, size, background, icon, border, startingPoint); skill.setPosition(buf.readFloat(), buf.readFloat()); @@ -79,7 +80,7 @@ public static void writeAttribute(FriendlyByteBuf buf, Attribute attribute) { public static @Nullable Attribute readAttribute(FriendlyByteBuf buf) { String attributeId = buf.readUtf(); - Attribute attribute = ForgeRegistries.ATTRIBUTES.getValue(new ResourceLocation(attributeId)); + Attribute attribute = ForgeRegistries.ATTRIBUTES.getValue(ResourceLocation.parse(attributeId)); if (attribute == null) { SkillTreeMod.LOGGER.error("Attribute {} does not exist", attributeId); } @@ -87,20 +88,17 @@ public static void writeAttribute(FriendlyByteBuf buf, Attribute attribute) { } public static void writeAttributeModifier(FriendlyByteBuf buf, AttributeModifier modifier) { - buf.writeLong(modifier.getId().getMostSignificantBits()); - buf.writeLong(modifier.getId().getLeastSignificantBits()); - buf.writeUtf(modifier.getName()); - buf.writeDouble(modifier.getAmount()); - writeOperation(buf, modifier.getOperation()); + buf.writeResourceLocation(modifier.id()); + buf.writeDouble(modifier.amount()); + writeOperation(buf, modifier.operation()); } @Nonnull public static AttributeModifier readAttributeModifier(FriendlyByteBuf buf) { - UUID id = new UUID(buf.readLong(), buf.readLong()); - String name = buf.readUtf(); + ResourceLocation id = buf.readResourceLocation(); double amount = buf.readDouble(); AttributeModifier.Operation operation = readOperation(buf); - return new AttributeModifier(id, name, amount, operation); + return new AttributeModifier(id, amount, operation); } public static void writeResourceLocations(FriendlyByteBuf buf, List locations) { @@ -111,7 +109,7 @@ public static void writeResourceLocations(FriendlyByteBuf buf, List readResourceLocations(FriendlyByteBuf buf) { int count = buf.readInt(); List locations = new ArrayList<>(); - for (int i = 0; i < count; i++) locations.add(new ResourceLocation(buf.readUtf())); + for (int i = 0; i < count; i++) locations.add(ResourceLocation.parse(buf.readUtf())); return locations; } @@ -183,7 +181,7 @@ public static void writeSkillBonus(FriendlyByteBuf buf, SkillBonus bonus) { } public static SkillBonus readSkillBonus(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); SkillBonus.Serializer serializer = PSTRegistries.SKILL_BONUSES.get().getValue(serializerId); Objects.requireNonNull(serializer); return serializer.deserialize(buf); @@ -198,7 +196,7 @@ public static void writeSkillRequirement(FriendlyByteBuf buf, SkillRequirement readSkillRequirement(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); SkillRequirement.Serializer serializer = PSTRegistries.SKILL_REQUIREMENTS.get().getValue(serializerId); Objects.requireNonNull(serializer); @@ -275,7 +273,7 @@ public static void writePassiveSkillTree(FriendlyByteBuf buf, PassiveSkillTree s } public static PassiveSkillTree readPassiveSkillTree(FriendlyByteBuf buf) { - ResourceLocation id = new ResourceLocation(buf.readUtf()); + ResourceLocation id = ResourceLocation.parse(buf.readUtf()); PassiveSkillTree skillTree = new PassiveSkillTree(id); readResourceLocations(buf).forEach(skillTree.getSkillIds()::add); readTagLimits(buf).forEach(skillTree.getSkillLimitations()::put); @@ -308,7 +306,7 @@ public static void writeLivingMultiplier( } public static @Nonnull LivingMultiplier readLivingMultiplier(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); LivingMultiplier.Serializer serializer = PSTRegistries.LIVING_MULTIPLIERS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(buf); @@ -322,7 +320,7 @@ public static void writeLivingCondition(FriendlyByteBuf buf, @Nonnull LivingEnti } public static @Nonnull LivingEntityPredicate readLivingCondition(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); LivingEntityPredicate.Serializer serializer = PSTRegistries.LIVING_CONDITIONS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(buf); @@ -337,7 +335,7 @@ public static void writeDamageCondition(FriendlyByteBuf buf, @Nonnull DamageCond } public static @Nonnull DamageCondition readDamageCondition(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); DamageCondition.Serializer serializer = PSTRegistries.DAMAGE_CONDITIONS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(buf); @@ -351,7 +349,7 @@ public static void writeItemCondition(FriendlyByteBuf buf, @Nonnull ItemStackPre } public static @Nonnull ItemStackPredicate readItemCondition(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); ItemStackPredicate.Serializer serializer = PSTRegistries.ITEM_CONDITIONS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(buf); @@ -366,7 +364,7 @@ public static void writeEventListener( } public static @Nonnull SkillEventListener readEventListener(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); SkillEventListener.Serializer serializer = PSTRegistries.EVENT_LISTENERS.get().getValue(serializerId); return Objects.requireNonNull(serializer).deserialize(buf); @@ -378,7 +376,7 @@ public static void writeEffect(FriendlyByteBuf buf, MobEffect effect) { } public static @Nullable MobEffect readEffect(FriendlyByteBuf buf) { - ResourceLocation effectId = new ResourceLocation(buf.readUtf()); + ResourceLocation effectId = ResourceLocation.parse(buf.readUtf()); return ForgeRegistries.MOB_EFFECTS.getValue(effectId); } @@ -391,16 +389,16 @@ public static > void writeEnum(FriendlyByteBuf buf, T anEnum) } public static void writeOperation(FriendlyByteBuf buf, AttributeModifier.Operation operation) { - buf.writeInt(operation.toValue()); + buf.writeInt(operation.id()); } @NotNull public static AttributeModifier.Operation readOperation(FriendlyByteBuf buf) { - return AttributeModifier.Operation.fromValue(buf.readInt()); + return AttributeModifier.Operation.BY_ID.apply(buf.readInt()); } public static void writeEffectInstance(FriendlyByteBuf buf, MobEffectInstance effect) { - writeEffect(buf, effect.getEffect()); + writeEffect(buf, effect.getEffect().value()); buf.writeInt(effect.getDuration()); buf.writeInt(effect.getAmplifier()); } @@ -409,7 +407,7 @@ public static void writeEffectInstance(FriendlyByteBuf buf, MobEffectInstance ef public static MobEffectInstance readEffectInstance(FriendlyByteBuf buf) { MobEffect effect = readEffect(buf); Objects.requireNonNull(effect); - return new MobEffectInstance(effect, buf.readInt(), buf.readInt()); + return new MobEffectInstance(BuiltInRegistries.MOB_EFFECT.wrapAsHolder(effect), buf.readInt(), buf.readInt()); } public static void writeValueProvider(FriendlyByteBuf buf, FloatFunction provider) { @@ -421,7 +419,7 @@ public static void writeValueProvider(FriendlyByteBuf buf, FloatFunction prov } public static FloatFunction readValueProvider(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); FloatFunction.Serializer serializer = PSTRegistries.FLOAT_FUNCTIONS.get().getValue(serializerId); Objects.requireNonNull(serializer); @@ -437,7 +435,7 @@ public static void writeItemBonus(FriendlyByteBuf buf, ItemBonus itemBonus) { } public static ItemBonus readItemBonus(FriendlyByteBuf buf) { - ResourceLocation serializerId = new ResourceLocation(buf.readUtf()); + ResourceLocation serializerId = ResourceLocation.parse(buf.readUtf()); ItemBonus.Serializer serializer = PSTRegistries.ITEM_BONUSES.get().getValue(serializerId); Objects.requireNonNull(serializer); return serializer.deserialize(buf); diff --git a/src/main/java/daripher/skilltree/network/message/GainSkillPointMessage.java b/src/main/java/daripher/skilltree/network/message/GainSkillPointMessage.java index 15b608d43..638224427 100644 --- a/src/main/java/daripher/skilltree/network/message/GainSkillPointMessage.java +++ b/src/main/java/daripher/skilltree/network/message/GainSkillPointMessage.java @@ -4,33 +4,42 @@ import daripher.skilltree.capability.skill.PlayerSkillsProvider; import daripher.skilltree.config.ServerConfig; import daripher.skilltree.exp.ExpHelper; -import daripher.skilltree.network.NetworkDispatcher; -import java.util.Objects; -import java.util.function.Supplier; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkEvent.Context; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class GainSkillPointMessage { - public static void receive(Supplier ctxSupplier) { - Context ctx = ctxSupplier.get(); - ctx.setPacketHandled(true); - ServerPlayer player = Objects.requireNonNull(ctx.getSender()); - IPlayerSkills capability = PlayerSkillsProvider.get(player); - int skills = capability.getPlayerSkills().size(); - int points = capability.getSkillPoints(); - int level = skills + points; - if (level >= ServerConfig.max_skill_points) { - return; - } - int cost = ServerConfig.getSkillPointCost(level); - if (ExpHelper.getPlayerExp(player) < cost) { - return; - } - player.giveExperiencePoints(-cost); - capability.grantSkillPoints(1); - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> player), new SyncPlayerSkillsMessage(player)); +public record GainSkillPointMessage() implements CustomPacketPayload { + public static final Type TYPE = + new Type<>(ResourceLocation.fromNamespaceAndPath("skilltree", "gain_skill_point")); + public static final StreamCodec STREAM_CODEC = + StreamCodec.unit(new GainSkillPointMessage()); + + @Override + public Type type() { + return TYPE; + } + + public static void handle(GainSkillPointMessage message, IPayloadContext context) { + context.enqueueWork( + () -> { + ServerPlayer player = (ServerPlayer) context.player(); + IPlayerSkills capability = PlayerSkillsProvider.get(player); + int skills = capability.getPlayerSkills().size(); + int points = capability.getSkillPoints(); + int level = skills + points; + if (level >= ServerConfig.max_skill_points) { + return; + } + int cost = ServerConfig.getSkillPointCost(level); + if (ExpHelper.getPlayerExp(player) < cost) { + return; + } + player.giveExperiencePoints(-cost); + capability.grantSkillPoints(1); + PlayerSkillsProvider.sendPlayerSkills(player); + }); } } diff --git a/src/main/java/daripher/skilltree/network/message/LearnSkillMessage.java b/src/main/java/daripher/skilltree/network/message/LearnSkillMessage.java index be492e7d0..a94676020 100644 --- a/src/main/java/daripher/skilltree/network/message/LearnSkillMessage.java +++ b/src/main/java/daripher/skilltree/network/message/LearnSkillMessage.java @@ -3,49 +3,40 @@ import daripher.skilltree.capability.skill.IPlayerSkills; import daripher.skilltree.capability.skill.PlayerSkillsProvider; import daripher.skilltree.data.reloader.SkillsReloader; -import daripher.skilltree.network.NetworkDispatcher; import daripher.skilltree.skill.PassiveSkill; +import io.netty.buffer.ByteBuf; import java.util.Objects; -import java.util.function.Supplier; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkEvent.Context; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class LearnSkillMessage { - private ResourceLocation skillId; +public record LearnSkillMessage(ResourceLocation skillId) implements CustomPacketPayload { + public static final Type TYPE = + new Type<>(ResourceLocation.fromNamespaceAndPath("skilltree", "learn_skill")); + public static final StreamCodec STREAM_CODEC = + ResourceLocation.STREAM_CODEC.map(LearnSkillMessage::new, LearnSkillMessage::skillId); public LearnSkillMessage(PassiveSkill passiveSkill) { - skillId = passiveSkill.getId(); + this(passiveSkill.getId()); } - private LearnSkillMessage() {} - - public static LearnSkillMessage decode(FriendlyByteBuf buf) { - LearnSkillMessage message = new LearnSkillMessage(); - message.skillId = new ResourceLocation(buf.readUtf()); - return message; - } - - public static void receive( - LearnSkillMessage message, Supplier ctxSupplier) { - Context ctx = ctxSupplier.get(); - ctx.setPacketHandled(true); - ServerPlayer player = ctx.getSender(); - Objects.requireNonNull(player); - IPlayerSkills capability = PlayerSkillsProvider.get(player); - PassiveSkill skill = SkillsReloader.getSkillById(message.skillId); - Objects.requireNonNull(skill); - if (capability.learnSkill(skill)) { - skill.learn(player, true); - } - NetworkDispatcher.network_channel.send( - PacketDistributor.PLAYER.with(() -> player), new SyncPlayerSkillsMessage(player)); + @Override + public Type type() { + return TYPE; } - public void encode(FriendlyByteBuf buf) { - buf.writeUtf(skillId.toString()); + public static void handle(LearnSkillMessage message, IPayloadContext context) { + context.enqueueWork( + () -> { + ServerPlayer player = (ServerPlayer) context.player(); + IPlayerSkills capability = PlayerSkillsProvider.get(player); + PassiveSkill skill = Objects.requireNonNull(SkillsReloader.getSkillById(message.skillId())); + if (capability.learnSkill(skill)) { + skill.learn(player, true); + } + PlayerSkillsProvider.sendPlayerSkills(player); + }); } } diff --git a/src/main/java/daripher/skilltree/network/message/SyncPlayerSkillsMessage.java b/src/main/java/daripher/skilltree/network/message/SyncPlayerSkillsMessage.java index 9eca8a93f..4c82cc904 100644 --- a/src/main/java/daripher/skilltree/network/message/SyncPlayerSkillsMessage.java +++ b/src/main/java/daripher/skilltree/network/message/SyncPlayerSkillsMessage.java @@ -2,73 +2,70 @@ import daripher.skilltree.capability.skill.IPlayerSkills; import daripher.skilltree.capability.skill.PlayerSkillsProvider; -import daripher.skilltree.client.screen.SkillTreeScreen; import daripher.skilltree.data.reloader.SkillsReloader; import daripher.skilltree.skill.PassiveSkill; -import java.util.ArrayList; +import io.netty.buffer.ByteBuf; import java.util.List; import java.util.Objects; -import java.util.function.Supplier; -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class SyncPlayerSkillsMessage { - private List learnedSkills = new ArrayList<>(); - private int skillPoints; +public record SyncPlayerSkillsMessage(List learnedSkills, int skillPoints) + implements CustomPacketPayload { + private static final String CLIENT_HANDLERS_CLASS = + "daripher.skilltree.client.network.ClientNetworkPayloadHandlers"; - private SyncPlayerSkillsMessage() {} + public static final Type TYPE = + new Type<>(ResourceLocation.fromNamespaceAndPath("skilltree", "sync_player_skills")); + public static final StreamCodec STREAM_CODEC = + StreamCodec.composite( + ResourceLocation.STREAM_CODEC.apply(ByteBufCodecs.list()), + SyncPlayerSkillsMessage::learnedSkills, + ByteBufCodecs.VAR_INT, + SyncPlayerSkillsMessage::skillPoints, + SyncPlayerSkillsMessage::new); public SyncPlayerSkillsMessage(Player player) { - IPlayerSkills skillsCapability = PlayerSkillsProvider.get(player); - learnedSkills = skillsCapability.getPlayerSkills().stream().map(PassiveSkill::getId).toList(); - skillPoints = skillsCapability.getSkillPoints(); + this( + PlayerSkillsProvider.get(player).getPlayerSkills().stream().map(PassiveSkill::getId).toList(), + PlayerSkillsProvider.get(player).getSkillPoints()); } - public static SyncPlayerSkillsMessage decode(FriendlyByteBuf buf) { - SyncPlayerSkillsMessage result = new SyncPlayerSkillsMessage(); - int learnedSkillsCount = buf.readInt(); - for (int i = 0; i < learnedSkillsCount; i++) { - result.learnedSkills.add(new ResourceLocation(buf.readUtf())); - } - result.skillPoints = buf.readInt(); - return result; + @Override + public Type type() { + return TYPE; } - public static void receive( - SyncPlayerSkillsMessage message, Supplier ctxSupplier) { - NetworkEvent.Context ctx = ctxSupplier.get(); - ctx.setPacketHandled(true); - ctx.enqueueWork( - () -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> handlePacket(message, ctx))); + public static void handle(SyncPlayerSkillsMessage message, IPayloadContext context) { + context.enqueueWork( + () -> { + Player player = context.player(); + if (player == null) return; + IPlayerSkills capability = PlayerSkillsProvider.get(player); + capability.getPlayerSkills().clear(); + message.learnedSkills().stream() + .map(SkillsReloader::getSkillById) + .filter(Objects::nonNull) + .forEach(capability.getPlayerSkills()::add); + capability.setSkillPoints(message.skillPoints()); + refreshSkillTreeScreen(capability.getSkillPoints()); + }); } - @OnlyIn(value = Dist.CLIENT) - private static void handlePacket(SyncPlayerSkillsMessage message, NetworkEvent.Context ctx) { - ctx.setPacketHandled(true); - Minecraft minecraft = Minecraft.getInstance(); - assert minecraft.player != null; - IPlayerSkills capability = PlayerSkillsProvider.get(minecraft.player); - capability.getPlayerSkills().clear(); - message.learnedSkills.stream() - .map(SkillsReloader::getSkillById) - .filter(Objects::nonNull) - .forEach(capability.getPlayerSkills()::add); - capability.setSkillPoints(message.skillPoints); - if (minecraft.screen instanceof SkillTreeScreen screen) { - screen.updateSkillPoints(capability.getSkillPoints()); - screen.init(); + private static void refreshSkillTreeScreen(int skillPoints) { + if (FMLEnvironment.dist != Dist.CLIENT) return; + try { + Class.forName(CLIENT_HANDLERS_CLASS) + .getMethod("refreshSkillTreeScreen", int.class) + .invoke(null, skillPoints); + } catch (ReflectiveOperationException exception) { + throw new IllegalStateException("Failed to refresh skill tree screen", exception); } } - - public void encode(FriendlyByteBuf buf) { - buf.writeInt(learnedSkills.size()); - learnedSkills.stream().map(ResourceLocation::toString).forEach(buf::writeUtf); - buf.writeInt(skillPoints); - } } diff --git a/src/main/java/daripher/skilltree/network/message/SyncServerDataMessage.java b/src/main/java/daripher/skilltree/network/message/SyncServerDataMessage.java index 593a93aa2..ef977073c 100644 --- a/src/main/java/daripher/skilltree/network/message/SyncServerDataMessage.java +++ b/src/main/java/daripher/skilltree/network/message/SyncServerDataMessage.java @@ -3,24 +3,55 @@ import daripher.skilltree.data.reloader.SkillTreesReloader; import daripher.skilltree.data.reloader.SkillsReloader; import daripher.skilltree.network.NetworkHelper; -import java.util.function.Supplier; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.network.NetworkEvent; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class SyncServerDataMessage { - public static SyncServerDataMessage decode(FriendlyByteBuf buf) { - SkillsReloader.loadFromByteBuf(buf); - SkillTreesReloader.loadFromByteBuf(buf); - return new SyncServerDataMessage(); +public class SyncServerDataMessage implements CustomPacketPayload { + public static final Type TYPE = + new Type<>(ResourceLocation.fromNamespaceAndPath("skilltree", "sync_server_data")); + public static final StreamCodec STREAM_CODEC = + ByteBufCodecs.BYTE_ARRAY.map(SyncServerDataMessage::new, SyncServerDataMessage::payload); + + private final byte[] payload; + + public SyncServerDataMessage() { + this(encodeServerData()); + } + + public SyncServerDataMessage(byte[] payload) { + this.payload = payload; + } + + public byte[] payload() { + return payload; + } + + @Override + public Type type() { + return TYPE; } - public static void receive( - SyncServerDataMessage message, Supplier ctxSupplier) { - ctxSupplier.get().setPacketHandled(true); + public static void handle(SyncServerDataMessage message, IPayloadContext context) { + context.enqueueWork( + () -> { + FriendlyByteBuf buffer = new FriendlyByteBuf(Unpooled.wrappedBuffer(message.payload)); + SkillsReloader.loadFromByteBuf(buffer); + SkillTreesReloader.loadFromByteBuf(buffer); + }); } - public void encode(FriendlyByteBuf buf) { - NetworkHelper.writePassiveSkills(buf, SkillsReloader.getSkills().values()); - NetworkHelper.writePassiveSkillTrees(buf, SkillTreesReloader.getSkillTrees().values()); + private static byte[] encodeServerData() { + FriendlyByteBuf buffer = new FriendlyByteBuf(Unpooled.buffer()); + NetworkHelper.writePassiveSkills(buffer, SkillsReloader.getSkills().values()); + NetworkHelper.writePassiveSkillTrees(buffer, SkillTreesReloader.getSkillTrees().values()); + byte[] payload = new byte[buffer.readableBytes()]; + buffer.readBytes(payload); + return payload; } } diff --git a/src/main/java/daripher/skilltree/recipe/builder/WorkbenchCraftingRecipeBuilder.java b/src/main/java/daripher/skilltree/recipe/builder/WorkbenchCraftingRecipeBuilder.java index 36609a06e..6837cd172 100644 --- a/src/main/java/daripher/skilltree/recipe/builder/WorkbenchCraftingRecipeBuilder.java +++ b/src/main/java/daripher/skilltree/recipe/builder/WorkbenchCraftingRecipeBuilder.java @@ -1,19 +1,12 @@ package daripher.skilltree.recipe.builder; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import daripher.skilltree.init.PSTRecipeSerializers; +import daripher.skilltree.recipe.workbench.WorkbenchCraftingRecipe; import java.util.HashMap; import java.util.Map; -import java.util.Objects; -import java.util.function.Consumer; -import net.minecraft.data.recipes.FinishedRecipe; +import net.minecraft.data.recipes.RecipeOutput; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -53,10 +46,12 @@ public WorkbenchCraftingRecipeBuilder setResult(@NotNull ItemStack result) { return this; } - public void save(Consumer finishedRecipeConsumer) { + public void save(RecipeOutput output) { validate(); - finishedRecipeConsumer.accept( - new Result(id, baseIngredient, ingredients, requiresPassiveSkill, result)); + output.accept( + id, + new WorkbenchCraftingRecipe(id, baseIngredient, ingredients, requiresPassiveSkill, result), + null); } private void validate() { @@ -71,77 +66,4 @@ private void validate() { } } - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final Map ingredients; - private final @Nullable Pair baseIngredient; - private final boolean requiresPassiveSkill; - private final ItemStack result; - - private Result( - ResourceLocation id, - @Nullable Pair baseIngredient, - Map ingredients, - boolean requiresPassiveSkill, - ItemStack result) { - this.id = id; - this.baseIngredient = baseIngredient; - this.ingredients = ingredients; - this.requiresPassiveSkill = requiresPassiveSkill; - this.result = result; - } - - @Override - public void serializeRecipeData(@NotNull JsonObject jsonObject) { - JsonArray ingredientsJson = new JsonArray(); - ingredients.forEach( - ((ingredient, requiredAmount) -> { - JsonObject ingredientJson = new JsonObject(); - ingredientJson.add("ingredient", ingredient.toJson()); - ingredientJson.addProperty("required_amount", requiredAmount); - ingredientsJson.add(ingredientJson); - })); - jsonObject.addProperty("requires_passive_skill", requiresPassiveSkill); - jsonObject.add("ingredients", ingredientsJson); - if (baseIngredient != null) { - JsonObject baseIngredientJson = new JsonObject(); - baseIngredientJson.add("ingredient", baseIngredient.getLeft().toJson()); - baseIngredientJson.addProperty("required_amount", baseIngredient.getRight()); - jsonObject.add("base_ingredient", baseIngredientJson); - } - JsonObject resultJson = new JsonObject(); - Item resultItem = this.result.getItem(); - ResourceLocation itemId = Objects.requireNonNull(ForgeRegistries.ITEMS.getKey(resultItem)); - resultJson.addProperty("item", itemId.toString()); - if (result.getCount() > 1) { - resultJson.addProperty("count", result.getCount()); - } - if (result.getTag() != null) { - resultJson.addProperty("nbt", result.getTag().toString()); - } - jsonObject.add("result", resultJson); - } - - @Override - public @NotNull ResourceLocation getId() { - return id; - } - - @Override - public @NotNull RecipeSerializer getType() { - return PSTRecipeSerializers.WORKBENCH_CRAFTING.get(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } } diff --git a/src/main/java/daripher/skilltree/recipe/builder/WorkbenchItemBonusRecipeBuilder.java b/src/main/java/daripher/skilltree/recipe/builder/WorkbenchItemBonusRecipeBuilder.java index 42a9d674d..258586762 100644 --- a/src/main/java/daripher/skilltree/recipe/builder/WorkbenchItemBonusRecipeBuilder.java +++ b/src/main/java/daripher/skilltree/recipe/builder/WorkbenchItemBonusRecipeBuilder.java @@ -1,22 +1,15 @@ package daripher.skilltree.recipe.builder; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import daripher.skilltree.data.serializers.SerializationHelper; -import daripher.skilltree.init.PSTRecipeSerializers; +import daripher.skilltree.recipe.workbench.WorkbenchItemBonusRecipe; import daripher.skilltree.skill.bonus.SkillBonus; import daripher.skilltree.skill.bonus.item.ItemBonus; import daripher.skilltree.skill.bonus.item.SkillBonusItemBonus; import daripher.skilltree.skill.bonus.predicate.item.ItemStackPredicate; import java.util.HashMap; import java.util.Map; -import java.util.function.Consumer; -import net.minecraft.data.recipes.FinishedRecipe; +import net.minecraft.data.recipes.RecipeOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class WorkbenchItemBonusRecipeBuilder { private final ResourceLocation id; @@ -59,10 +52,13 @@ public WorkbenchItemBonusRecipeBuilder setItemBonus(SkillBonus skillBonus) { return this; } - public void save(Consumer finishedRecipeConsumer) { + public void save(RecipeOutput output) { validate(); - finishedRecipeConsumer.accept( - new Result(id, baseItemStackPredicate, ingredients, requiresPassiveSkill, itemBonus)); + output.accept( + id, + new WorkbenchItemBonusRecipe( + id, baseItemStackPredicate, ingredients, requiresPassiveSkill, itemBonus), + null); } private void validate() { @@ -80,63 +76,4 @@ private void validate() { } } - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final ItemStackPredicate baseItemStackPredicate; - private final Map ingredients; - private final boolean requiresPassiveSkill; - private final ItemBonus itemBonus; - - private Result( - ResourceLocation id, - ItemStackPredicate baseItemStackPredicate, - Map ingredients, - boolean requiresPassiveSkill, - ItemBonus itemBonus) { - this.id = id; - this.baseItemStackPredicate = baseItemStackPredicate; - this.ingredients = ingredients; - this.requiresPassiveSkill = requiresPassiveSkill; - this.itemBonus = itemBonus; - } - - @Override - public void serializeRecipeData(@NotNull JsonObject jsonObject) { - JsonArray ingredientsJson = new JsonArray(); - ingredients.forEach( - ((ingredient, requiredAmount) -> { - JsonObject ingredientJson = new JsonObject(); - ingredientJson.add("ingredient", ingredient.toJson()); - ingredientJson.addProperty("required_amount", requiredAmount); - ingredientsJson.add(ingredientJson); - })); - SerializationHelper.serializeItemCondition( - jsonObject, baseItemStackPredicate, "base_item_condition"); - SerializationHelper.serializeItemBonus(jsonObject, itemBonus); - jsonObject.addProperty("requires_passive_skill", requiresPassiveSkill); - jsonObject.add("ingredients", ingredientsJson); - } - - @Override - public @NotNull ResourceLocation getId() { - return id; - } - - @Override - public @NotNull RecipeSerializer getType() { - return PSTRecipeSerializers.WORKBENCH_ITEM_BONUS.get(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } } diff --git a/src/main/java/daripher/skilltree/recipe/workbench/AbstractWorkbenchRecipe.java b/src/main/java/daripher/skilltree/recipe/workbench/AbstractWorkbenchRecipe.java index be6bca8df..e463befd0 100644 --- a/src/main/java/daripher/skilltree/recipe/workbench/AbstractWorkbenchRecipe.java +++ b/src/main/java/daripher/skilltree/recipe/workbench/AbstractWorkbenchRecipe.java @@ -9,7 +9,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.HolderLookup; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; @@ -18,7 +18,7 @@ import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; -import net.minecraftforge.registries.ForgeRegistries; +import daripher.skilltree.util.ForgeRegistries; import org.jetbrains.annotations.NotNull; public abstract class AbstractWorkbenchRecipe @@ -87,20 +87,19 @@ public boolean canCraftInDimensions(int width, int height) { return width == 7 && height == 1; } - @Override public @NotNull ResourceLocation getId() { return id; } @Deprecated @Override - public @NotNull ItemStack getResultItem(@NotNull RegistryAccess registryAccess) { + public @NotNull ItemStack getResultItem(@NotNull HolderLookup.Provider registryAccess) { return ItemStack.EMPTY; } @Override public @NotNull RecipeType getType() { - return PSTRecipeTypes.WORKBENCH; + return PSTRecipeTypes.WORKBENCH.get(); } @Override diff --git a/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchCraftingRecipe.java b/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchCraftingRecipe.java index 70fc7abfb..1de85e721 100644 --- a/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchCraftingRecipe.java +++ b/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchCraftingRecipe.java @@ -1,21 +1,22 @@ package daripher.skilltree.recipe.workbench; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import daripher.skilltree.SkillTreeMod; import daripher.skilltree.init.PSTRecipeSerializers; import daripher.skilltree.inventory.menu.WorkbenchContainer; -import java.util.HashMap; import java.util.Map; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; +import java.util.Optional; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.common.crafting.CraftingHelper; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -37,7 +38,7 @@ public WorkbenchCraftingRecipe( @Override public @NotNull ItemStack assemble( - @NotNull WorkbenchContainer container, @NotNull RegistryAccess registryAccess) { + @NotNull WorkbenchContainer container, @NotNull HolderLookup.Provider registryAccess) { return getResult(container); } @@ -71,68 +72,90 @@ public int requiredBaseItemAmount() { } public static class Serializer implements RecipeSerializer { + private static final ResourceLocation UNKNOWN_ID = + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "unknown"); + + private static final MapCodec CODEC = + RecordCodecBuilder.mapCodec( + instance -> + instance + .group( + ResourceLocation.CODEC + .optionalFieldOf("id", UNKNOWN_ID) + .forGetter(AbstractWorkbenchRecipe::getId), + WorkbenchRecipeCodecs.IngredientEntry.CODEC + .optionalFieldOf("base_ingredient") + .forGetter(recipe -> optionalBaseIngredient(recipe.baseIngredient)), + WorkbenchRecipeCodecs.IngredientEntry.CODEC + .listOf() + .fieldOf("ingredients") + .xmap(WorkbenchRecipeCodecs::toMap, WorkbenchRecipeCodecs::toEntries) + .forGetter(AbstractWorkbenchRecipe::getAdditionalIngredients), + Codec.BOOL + .optionalFieldOf("requires_passive_skill", false) + .forGetter(AbstractWorkbenchRecipe::requiresPassiveSkill), + ItemStack.CODEC.fieldOf("result").forGetter(recipe -> recipe.result)) + .apply( + instance, + (id, baseIngredient, ingredients, requiresPassiveSkill, result) -> + new WorkbenchCraftingRecipe( + id, + baseIngredient + .map( + entry -> + Pair.of(entry.ingredient(), entry.requiredAmount())) + .orElse(null), + ingredients, + requiresPassiveSkill, + result))); + + private static final StreamCodec + STREAM_CODEC = StreamCodec.of(Serializer::encode, Serializer::decode); + @Override - public @NotNull WorkbenchCraftingRecipe fromJson( - @NotNull ResourceLocation id, @NotNull JsonObject jsonObject) { - boolean requiresPassiveSkill = jsonObject.get("requires_passive_skill").getAsBoolean(); - Map ingredients = new HashMap<>(); - JsonArray ingredientsJson = jsonObject.getAsJsonArray("ingredients"); - for (JsonElement jsonElement : ingredientsJson) { - JsonObject ingredientJson = jsonElement.getAsJsonObject(); - Ingredient ingredient = Ingredient.fromJson(ingredientJson.get("ingredient")); - int requiredAmount = ingredientJson.get("required_amount").getAsInt(); - ingredients.put(ingredient, requiredAmount); - } - Pair baseIngredient = null; - if (jsonObject.has("base_ingredient")) { - JsonObject baseIngredientJson = jsonObject.get("base_ingredient").getAsJsonObject(); - Ingredient ingredient = Ingredient.fromJson(baseIngredientJson.get("ingredient")); - int requiredAmount = baseIngredientJson.get("required_amount").getAsInt(); - baseIngredient = Pair.of(ingredient, requiredAmount); - } - JsonObject resultJson = jsonObject.getAsJsonObject("result"); - ItemStack result = CraftingHelper.getItemStack(resultJson, true, true); - return new WorkbenchCraftingRecipe( - id, baseIngredient, ingredients, requiresPassiveSkill, result); + public @NotNull MapCodec codec() { + return CODEC; } @Override - public @Nullable WorkbenchCraftingRecipe fromNetwork( - @NotNull ResourceLocation id, @NotNull FriendlyByteBuf buf) { + public @NotNull StreamCodec streamCodec() { + return STREAM_CODEC; + } + + private static WorkbenchCraftingRecipe decode(RegistryFriendlyByteBuf buf) { + ResourceLocation id = buf.readResourceLocation(); boolean requiresPassiveSkill = buf.readBoolean(); - Map ingredients = new HashMap<>(); - int ingredientsCount = buf.readInt(); - for (int i = 0; i < ingredientsCount; i++) { - ingredients.put(Ingredient.fromNetwork(buf), buf.readInt()); - } + Map ingredients = WorkbenchRecipeCodecs.readIngredientMap(buf); Pair baseIngredient = null; boolean hasBaseIngredient = buf.readBoolean(); if (hasBaseIngredient) { - baseIngredient = Pair.of(Ingredient.fromNetwork(buf), buf.readInt()); + baseIngredient = Pair.of(Ingredient.CONTENTS_STREAM_CODEC.decode(buf), buf.readInt()); } - ItemStack result = buf.readItem(); + ItemStack result = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); return new WorkbenchCraftingRecipe( id, baseIngredient, ingredients, requiresPassiveSkill, result); } - @Override - public void toNetwork(@NotNull FriendlyByteBuf buf, @NotNull WorkbenchCraftingRecipe recipe) { + private static void encode(RegistryFriendlyByteBuf buf, WorkbenchCraftingRecipe recipe) { + buf.writeResourceLocation(recipe.getId()); buf.writeBoolean(recipe.requiresPassiveSkill()); - int ingredientsCount = recipe.getAdditionalIngredients().size(); - buf.writeInt(ingredientsCount); - recipe - .getAdditionalIngredients() - .forEach( - (ingredient, requiredAmount) -> { - ingredient.toNetwork(buf); - buf.writeInt(requiredAmount); - }); + WorkbenchRecipeCodecs.writeIngredientMap(buf, recipe.getAdditionalIngredients()); buf.writeBoolean(recipe.baseIngredient != null); if (recipe.baseIngredient != null) { - recipe.baseIngredient.getLeft().toNetwork(buf); + Ingredient.CONTENTS_STREAM_CODEC.encode(buf, recipe.baseIngredient.getLeft()); buf.writeInt(recipe.baseIngredient.getRight()); } - buf.writeItem(recipe.result); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, recipe.result); + } + + private static Optional optionalBaseIngredient( + @Nullable Pair baseIngredient) { + if (baseIngredient == null) { + return Optional.empty(); + } + return Optional.of( + new WorkbenchRecipeCodecs.IngredientEntry( + baseIngredient.getLeft(), baseIngredient.getRight())); } } } diff --git a/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchItemBonusRecipe.java b/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchItemBonusRecipe.java index 753c3911f..868303e1d 100644 --- a/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchItemBonusRecipe.java +++ b/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchItemBonusRecipe.java @@ -1,8 +1,10 @@ package daripher.skilltree.recipe.workbench; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import daripher.skilltree.SkillTreeMod; import daripher.skilltree.client.tooltip.TooltipHelper; import daripher.skilltree.data.serializers.SerializationHelper; import daripher.skilltree.init.PSTRecipeSerializers; @@ -12,11 +14,11 @@ import daripher.skilltree.skill.bonus.item.ItemBonusHandler; import daripher.skilltree.skill.bonus.predicate.item.ItemStackPredicate; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; @@ -26,7 +28,6 @@ import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class WorkbenchItemBonusRecipe extends AbstractWorkbenchRecipe { private final ItemStackPredicate baseItemStackPredicate; @@ -45,7 +46,7 @@ public WorkbenchItemBonusRecipe( @Override public @NotNull ItemStack assemble( - @NotNull WorkbenchContainer container, @NotNull RegistryAccess registryAccess) { + @NotNull WorkbenchContainer container, @NotNull HolderLookup.Provider registryAccess) { return getResult(container); } @@ -101,54 +102,101 @@ public int requiredBaseItemAmount() { } public static class Serializer implements RecipeSerializer { + private static final ResourceLocation UNKNOWN_ID = + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "unknown"); + + private static final Codec ITEM_CONDITION_CODEC = + WorkbenchRecipeCodecs.JSON_OBJECT.xmap( + Serializer::deserializeItemCondition, Serializer::serializeItemCondition); + + private static final Codec> ITEM_BONUS_CODEC = + WorkbenchRecipeCodecs.JSON_OBJECT.xmap( + Serializer::deserializeItemBonus, Serializer::serializeItemBonus); + + private static final MapCodec CODEC = + RecordCodecBuilder.mapCodec( + instance -> + instance + .group( + ResourceLocation.CODEC + .optionalFieldOf("id", UNKNOWN_ID) + .forGetter(AbstractWorkbenchRecipe::getId), + ITEM_CONDITION_CODEC + .fieldOf("base_item_condition") + .forGetter(recipe -> recipe.baseItemStackPredicate), + ITEM_BONUS_CODEC.fieldOf("item_bonus").forGetter(recipe -> recipe.itemBonus), + WorkbenchRecipeCodecs.IngredientEntry.CODEC + .listOf() + .fieldOf("ingredients") + .xmap(WorkbenchRecipeCodecs::toMap, WorkbenchRecipeCodecs::toEntries) + .forGetter(AbstractWorkbenchRecipe::getAdditionalIngredients), + Codec.BOOL + .optionalFieldOf("requires_passive_skill", false) + .forGetter(AbstractWorkbenchRecipe::requiresPassiveSkill)) + .apply( + instance, + (id, baseItemStackPredicate, itemBonus, ingredients, requiresPassiveSkill) -> + new WorkbenchItemBonusRecipe( + id, + baseItemStackPredicate, + ingredients, + requiresPassiveSkill, + itemBonus))); + + private static final StreamCodec + STREAM_CODEC = StreamCodec.of(Serializer::encode, Serializer::decode); + @Override - public @NotNull WorkbenchItemBonusRecipe fromJson( - @NotNull ResourceLocation id, @NotNull JsonObject jsonObject) { - ItemStackPredicate baseItemStackPredicate = - SerializationHelper.deserializeItemCondition(jsonObject, "base_item_condition"); - ItemBonus itemBonus = SerializationHelper.deserializeItemBonus(jsonObject); - boolean requiresPassiveSkill = jsonObject.get("requires_passive_skill").getAsBoolean(); - Map ingredients = new HashMap<>(); - JsonArray ingredientsJson = jsonObject.getAsJsonArray("ingredients"); - for (JsonElement jsonElement : ingredientsJson) { - Ingredient ingredient = - Ingredient.fromJson(jsonElement.getAsJsonObject().get("ingredient")); - int requiredAmount = jsonElement.getAsJsonObject().get("required_amount").getAsInt(); - ingredients.put(ingredient, requiredAmount); - } - return new WorkbenchItemBonusRecipe( - id, baseItemStackPredicate, ingredients, requiresPassiveSkill, itemBonus); + public @NotNull MapCodec codec() { + return CODEC; } @Override - public @Nullable WorkbenchItemBonusRecipe fromNetwork( - @NotNull ResourceLocation id, @NotNull FriendlyByteBuf buf) { + public @NotNull StreamCodec streamCodec() { + return STREAM_CODEC; + } + + private static WorkbenchItemBonusRecipe decode(RegistryFriendlyByteBuf buf) { + ResourceLocation id = buf.readResourceLocation(); ItemStackPredicate baseItemStackPredicate = NetworkHelper.readItemCondition(buf); ItemBonus itemBonus = NetworkHelper.readItemBonus(buf); boolean requiresPassiveSkill = buf.readBoolean(); - Map ingredients = new HashMap<>(); - int ingredientsCount = buf.readInt(); - for (int i = 0; i < ingredientsCount; i++) { - ingredients.put(Ingredient.fromNetwork(buf), buf.readInt()); - } + Map ingredients = WorkbenchRecipeCodecs.readIngredientMap(buf); return new WorkbenchItemBonusRecipe( id, baseItemStackPredicate, ingredients, requiresPassiveSkill, itemBonus); } - @Override - public void toNetwork(@NotNull FriendlyByteBuf buf, @NotNull WorkbenchItemBonusRecipe recipe) { + private static void encode(RegistryFriendlyByteBuf buf, WorkbenchItemBonusRecipe recipe) { + buf.writeResourceLocation(recipe.getId()); NetworkHelper.writeItemCondition(buf, recipe.baseItemStackPredicate); NetworkHelper.writeItemBonus(buf, recipe.itemBonus); buf.writeBoolean(recipe.requiresPassiveSkill()); - int ingredientsCount = recipe.getAdditionalIngredients().size(); - buf.writeInt(ingredientsCount); - recipe - .getAdditionalIngredients() - .forEach( - (ingredient, requiredAmount) -> { - ingredient.toNetwork(buf); - buf.writeInt(requiredAmount); - }); + WorkbenchRecipeCodecs.writeIngredientMap(buf, recipe.getAdditionalIngredients()); + } + + private static ItemStackPredicate deserializeItemCondition(JsonObject conditionJson) { + JsonObject recipeJson = new JsonObject(); + recipeJson.add("base_item_condition", conditionJson); + return SerializationHelper.deserializeItemCondition(recipeJson, "base_item_condition"); + } + + private static JsonObject serializeItemCondition(ItemStackPredicate itemStackPredicate) { + JsonObject recipeJson = new JsonObject(); + SerializationHelper.serializeItemCondition( + recipeJson, itemStackPredicate, "base_item_condition"); + return recipeJson.getAsJsonObject("base_item_condition"); + } + + private static ItemBonus deserializeItemBonus(JsonObject itemBonusJson) { + JsonObject recipeJson = new JsonObject(); + recipeJson.add("item_bonus", itemBonusJson); + return SerializationHelper.deserializeItemBonus(recipeJson); + } + + private static JsonObject serializeItemBonus(ItemBonus itemBonus) { + JsonObject recipeJson = new JsonObject(); + SerializationHelper.serializeItemBonus(recipeJson, itemBonus); + return recipeJson.getAsJsonObject("item_bonus"); } } } diff --git a/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchRecipeCodecs.java b/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchRecipeCodecs.java new file mode 100644 index 000000000..8ed2e9d50 --- /dev/null +++ b/src/main/java/daripher/skilltree/recipe/workbench/WorkbenchRecipeCodecs.java @@ -0,0 +1,72 @@ +package daripher.skilltree.recipe.workbench; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.Dynamic; +import com.mojang.serialization.JsonOps; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.world.item.crafting.Ingredient; + +final class WorkbenchRecipeCodecs { + static final Codec JSON_OBJECT = + Codec.PASSTHROUGH.flatXmap( + dynamic -> { + JsonElement element = dynamic.convert(JsonOps.INSTANCE).getValue(); + if (element.isJsonObject()) { + return DataResult.success(element.getAsJsonObject()); + } + return DataResult.error(() -> "Expected JSON object"); + }, + jsonObject -> DataResult.success(new Dynamic<>(JsonOps.INSTANCE, jsonObject))); + + private WorkbenchRecipeCodecs() {} + + static List toEntries(Map ingredients) { + return ingredients.entrySet().stream().map(IngredientEntry::from).toList(); + } + + static Map toMap(List ingredients) { + Map map = new HashMap<>(); + ingredients.forEach(entry -> map.put(entry.ingredient(), entry.requiredAmount())); + return map; + } + + static void writeIngredientMap(RegistryFriendlyByteBuf buf, Map ingredients) { + buf.writeInt(ingredients.size()); + ingredients.forEach( + (ingredient, amount) -> { + Ingredient.CONTENTS_STREAM_CODEC.encode(buf, ingredient); + buf.writeInt(amount); + }); + } + + static Map readIngredientMap(RegistryFriendlyByteBuf buf) { + Map ingredients = new HashMap<>(); + int ingredientsCount = buf.readInt(); + for (int i = 0; i < ingredientsCount; i++) { + ingredients.put(Ingredient.CONTENTS_STREAM_CODEC.decode(buf), buf.readInt()); + } + return ingredients; + } + + record IngredientEntry(Ingredient ingredient, int requiredAmount) { + static final Codec CODEC = + RecordCodecBuilder.create( + instance -> + instance + .group( + Ingredient.CODEC_NONEMPTY.fieldOf("ingredient").forGetter(IngredientEntry::ingredient), + Codec.INT.fieldOf("required_amount").forGetter(IngredientEntry::requiredAmount)) + .apply(instance, IngredientEntry::new)); + + static IngredientEntry from(Map.Entry entry) { + return new IngredientEntry(entry.getKey(), entry.getValue()); + } + } +} diff --git a/src/main/java/daripher/skilltree/skill/bonus/SkillBonusHandler.java b/src/main/java/daripher/skilltree/skill/bonus/SkillBonusHandler.java index 815eb5323..88270b9fd 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/SkillBonusHandler.java +++ b/src/main/java/daripher/skilltree/skill/bonus/SkillBonusHandler.java @@ -20,6 +20,7 @@ import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.player.Input; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; @@ -44,27 +45,28 @@ import net.minecraft.world.entity.projectile.ThrownPotion; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.MovementInputUpdateEvent; -import net.minecraftforge.client.event.RenderTooltipEvent; -import net.minecraftforge.common.Tags; -import net.minecraftforge.event.AnvilUpdateEvent; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.event.entity.EntityJoinLevelEvent; -import net.minecraftforge.event.entity.living.*; -import net.minecraftforge.event.entity.player.*; -import net.minecraftforge.event.level.BlockEvent; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.LogicalSide; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.event.MovementInputUpdateEvent; +import net.neoforged.neoforge.client.event.RenderTooltipEvent; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.event.AnvilUpdateEvent; +import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent; +import net.neoforged.neoforge.event.entity.living.*; +import net.neoforged.neoforge.event.entity.player.*; +import net.neoforged.neoforge.event.level.BlockEvent; +import net.neoforged.neoforge.event.level.BlockDropsEvent; +import net.neoforged.bus.api.Event; +import net.neoforged.bus.api.ICancellableEvent; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.tick.PlayerTickEvent; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -@Mod.EventBusSubscriber(modid = SkillTreeMod.MOD_ID) +@EventBusSubscriber(modid = SkillTreeMod.MOD_ID) public class SkillBonusHandler { @SubscribeEvent public static void applyBreakSpeedMultiplier(PlayerEvent.BreakSpeed event) { @@ -111,11 +113,11 @@ public static void applyRepairEfficiency(AnvilUpdateEvent event) { if (event.getName() != null && !StringUtils.isBlank(event.getName())) { if (!event.getName().equals(stack.getHoverName().getString())) { cost++; - result.setHoverName(Component.literal(event.getName())); + result.set(DataComponents.CUSTOM_NAME, Component.literal(event.getName())); } - } else if (stack.hasCustomHoverName()) { + } else if (stack.has(DataComponents.CUSTOM_NAME)) { cost++; - result.resetHoverName(); + result.remove(DataComponents.CUSTOM_NAME); } event.setMaterialCost(materialsUsed); event.setCost(cost); @@ -133,21 +135,22 @@ private static float getRepairEfficiency(Player player, ItemStack stack) { } @SubscribeEvent - public static void tickSkillBonuses(TickEvent.PlayerTickEvent event) { - if (event.player.isDeadOrDying()) return; - if (!(event.player instanceof ServerPlayer player)) return; - if (event.phase == TickEvent.Phase.END) return; - getSkillBonuses(player, TickingSkillBonus.class).forEach(bonus -> bonus.tick(player)); + public static void tickSkillBonuses(PlayerTickEvent.Post event) { + Player player = event.getEntity(); + if (player.level().isClientSide) return; + if (player.isDeadOrDying()) return; + if (!(player instanceof ServerPlayer serverPlayer)) return; + getSkillBonuses(serverPlayer, TickingSkillBonus.class).forEach(bonus -> bonus.tick(serverPlayer)); } @SubscribeEvent(priority = EventPriority.HIGH) - public static void applyFlatDamageBonus(LivingHurtEvent event) { + public static void applyFlatDamageBonus(LivingIncomingDamageEvent event) { Player attacker = getPlayerAttacker(event); if (attacker == null) return; LivingEntity target = event.getEntity(); setLastTarget(attacker, target); float bonus = - getDamageBonus(attacker, event.getSource(), target, AttributeModifier.Operation.ADDITION); + getDamageBonus(attacker, event.getSource(), target, AttributeModifier.Operation.ADD_VALUE); event.setAmount(event.getAmount() + bonus); } @@ -157,7 +160,7 @@ private static void setLastTarget(Player attacker, LivingEntity target) { } @SubscribeEvent - public static void applyBaseDamageMultipliers(LivingHurtEvent event) { + public static void applyBaseDamageMultipliers(LivingIncomingDamageEvent event) { Player attacker = getPlayerAttacker(event); if (attacker == null) return; float bonus = @@ -165,12 +168,12 @@ public static void applyBaseDamageMultipliers(LivingHurtEvent event) { attacker, event.getSource(), event.getEntity(), - AttributeModifier.Operation.MULTIPLY_BASE); + AttributeModifier.Operation.ADD_MULTIPLIED_BASE); event.setAmount(event.getAmount() * (1 + bonus)); } @SubscribeEvent(priority = EventPriority.LOW) - public static void applyTotalDamageMultipliers(LivingHurtEvent event) { + public static void applyTotalDamageMultipliers(LivingIncomingDamageEvent event) { Player attacker = getPlayerAttacker(event); if (attacker == null) return; float bonus = @@ -178,11 +181,11 @@ public static void applyTotalDamageMultipliers(LivingHurtEvent event) { attacker, event.getSource(), event.getEntity(), - AttributeModifier.Operation.MULTIPLY_TOTAL); + AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL); event.setAmount(event.getAmount() * (1 + bonus)); } - private static @Nullable Player getPlayerAttacker(LivingHurtEvent event) { + private static @Nullable Player getPlayerAttacker(LivingIncomingDamageEvent event) { Player attacker = null; if (event.getSource().getEntity() instanceof Player player) { attacker = player; @@ -213,17 +216,17 @@ public static void applyCritBonuses(CriticalHitEvent event) { if (player.getRandom().nextFloat() >= critChance) { return; } - float critMultiplier = event.getDamageModifier(); + float critMultiplier = event.getDamageMultiplier(); critMultiplier += getCritDamageMultiplier(player, damageSource, target); if (!event.isVanillaCritical()) { critMultiplier += 0.5f; - event.setResult(Event.Result.ALLOW); + event.setCriticalHit(true); } - event.setDamageModifier(critMultiplier); + event.setDamageMultiplier(critMultiplier); } @SubscribeEvent(priority = EventPriority.LOW) - public static void applyCritBonuses(LivingHurtEvent event) { + public static void applyCritBonuses(LivingIncomingDamageEvent event) { // direct damage, ignoring if (event.getSource().getDirectEntity() instanceof Player) { return; @@ -278,14 +281,17 @@ public static void applyExperienceFromMobsBonus(LivingExperienceDropEvent event) } @SubscribeEvent - public static void applyExperienceFromOreBonus(BlockEvent.BreakEvent event) { + public static void applyExperienceFromOreBonus(BlockDropsEvent event) { if (!event.getState().is(Tags.Blocks.ORES)) { return; } + if (!(event.getBreaker() instanceof Player player)) { + return; + } float multiplier = 1f; multiplier += - getExperienceMultiplier(event.getPlayer(), GainedExperienceBonus.ExperienceSource.ORE); - event.setExpToDrop((int) (event.getExpToDrop() * multiplier)); + getExperienceMultiplier(player, GainedExperienceBonus.ExperienceSource.ORE); + event.setDroppedExperience((int) (event.getDroppedExperience() * multiplier)); } @SubscribeEvent @@ -314,7 +320,7 @@ private static float getExperienceMultiplier( } @SubscribeEvent - public static void applyEventListenerEffect(LivingHurtEvent event) { + public static void applyEventListenerEffect(LivingIncomingDamageEvent event) { Entity sourceEntity = event.getSource().getEntity(); if (sourceEntity instanceof Player player) { for (EventListenerBonus bonus : getMergedSkillBonuses(player, EventListenerBonus.class)) { @@ -349,7 +355,7 @@ public static void applyEventListenerEffect(CriticalHitEvent event) { } @SubscribeEvent - public static void applyEventListenerEffect(ShieldBlockEvent event) { + public static void applyEventListenerEffect(LivingShieldBlockEvent event) { if (!(event.getEntity() instanceof Player player)) { return; } @@ -394,7 +400,7 @@ public static void applyEventListenerEffect(LivingDeathEvent event) { } @SubscribeEvent - public static void applyArrowRetrievalBonus(LivingHurtEvent event) { + public static void applyArrowRetrievalBonus(LivingIncomingDamageEvent event) { if (!(event.getSource().getDirectEntity() instanceof AbstractArrow arrow)) { return; } @@ -414,7 +420,7 @@ public static void applyArrowRetrievalBonus(LivingHurtEvent event) { LivingEntity target = event.getEntity(); CompoundTag targetData = target.getPersistentData(); ListTag stuckArrowsTag = targetData.getList("StuckArrows", new CompoundTag().getId()); - stuckArrowsTag.add(arrowStack.save(new CompoundTag())); + stuckArrowsTag.add(arrowStack.save(player.level().registryAccess())); targetData.put("StuckArrows", stuckArrowsTag); } @@ -425,18 +431,20 @@ public static void retrieveArrows(LivingDeathEvent event) { entity.getPersistentData().getList("StuckArrows", new CompoundTag().getId()); if (arrowsTag.isEmpty()) return; for (Tag tag : arrowsTag) { - ItemStack arrowStack = ItemStack.of((CompoundTag) tag); + ItemStack arrowStack = + ItemStack.parseOptional(entity.level().registryAccess(), (CompoundTag) tag); entity.spawnAtLocation(arrowStack); } } @SubscribeEvent - public static void applyHealthReservationEffect(TickEvent.PlayerTickEvent event) { - if (event.phase == TickEvent.Phase.END || event.side == LogicalSide.CLIENT) return; - float reservation = getHealthReservation(event.player); + public static void applyHealthReservationEffect(PlayerTickEvent.Post event) { + Player player = event.getEntity(); + if (player.level().isClientSide) return; + float reservation = getHealthReservation(player); if (reservation == 0) return; - if (event.player.getHealth() / event.player.getMaxHealth() > 1 - reservation) { - event.player.setHealth(event.player.getMaxHealth() * (1 - reservation)); + if (player.getHealth() / player.getMaxHealth() > 1 - reservation) { + player.setHealth(player.getMaxHealth() * (1 - reservation)); } } @@ -470,18 +478,54 @@ public static void applyCantUseItemBonus(AttackEntityEvent event) { } @SubscribeEvent - public static void applyCantUseItemBonus(PlayerInteractEvent event) { + public static void applyCantUseItemBonus(PlayerInteractEvent.LeftClickBlock event) { + applyCantUseItemBonusToInteraction(event); + } + + @SubscribeEvent + public static void applyCantUseItemBonus(PlayerInteractEvent.RightClickItem event) { + applyCantUseItemBonusToInteraction(event); + } + + @SubscribeEvent + public static void applyCantUseItemBonus(PlayerInteractEvent.RightClickBlock event) { + applyCantUseItemBonusToInteraction(event); + } + + @SubscribeEvent + public static void applyCantUseItemBonus(PlayerInteractEvent.EntityInteract event) { + applyCantUseItemBonusToInteraction(event); + } + + @SubscribeEvent + public static void applyCantUseItemBonus(PlayerInteractEvent.EntityInteractSpecific event) { + applyCantUseItemBonusToInteraction(event); + } + + private static void applyCantUseItemBonusToInteraction(PlayerInteractEvent event) { for (CantUseItemBonus bonus : getSkillBonuses(event.getEntity(), CantUseItemBonus.class)) { if (bonus.getItemCondition().test(event.getItemStack())) { - event.setCancellationResult(InteractionResult.FAIL); - if (event.isCancelable()) { - event.setCanceled(true); + setCancellationResult(event, InteractionResult.FAIL); + if (event instanceof ICancellableEvent cancellableEvent) { + cancellableEvent.setCanceled(true); } return; } } } + private static void setCancellationResult(PlayerInteractEvent event, InteractionResult result) { + if (event instanceof PlayerInteractEvent.RightClickItem rightClickItem) { + rightClickItem.setCancellationResult(result); + } else if (event instanceof PlayerInteractEvent.RightClickBlock rightClickBlock) { + rightClickBlock.setCancellationResult(result); + } else if (event instanceof PlayerInteractEvent.EntityInteract entityInteract) { + entityInteract.setCancellationResult(result); + } else if (event instanceof PlayerInteractEvent.EntityInteractSpecific entityInteractSpecific) { + entityInteractSpecific.setCancellationResult(result); + } + } + @OnlyIn(Dist.CLIENT) @SubscribeEvent(priority = EventPriority.LOWEST) public static void addCantUseItemTooltip(RenderTooltipEvent.GatherComponents event) { @@ -508,29 +552,29 @@ public static void inflictPoisonForcefully(MobEffectEvent.Applicable event) { if (getSkillBonuses(player, CanPoisonAnyoneBonus.class).isEmpty()) { return; } - event.setResult(Event.Result.ALLOW); + event.setResult(MobEffectEvent.Applicable.Result.APPLY); } @SubscribeEvent(priority = EventPriority.LOWEST) - public static void applyDamageTakenBonuses(LivingHurtEvent event) { + public static void applyDamageTakenBonuses(LivingIncomingDamageEvent event) { if (!(event.getEntity() instanceof Player player)) return; DamageSource damageSource = event.getSource(); if (!(damageSource.getEntity() instanceof LivingEntity attacker)) return; float damageTaken = event.getAmount(); float addition = - getDamageTaken(player, attacker, damageSource, AttributeModifier.Operation.ADDITION); + getDamageTaken(player, attacker, damageSource, AttributeModifier.Operation.ADD_VALUE); damageTaken += addition; float multiplier = - getDamageTaken(player, attacker, damageSource, AttributeModifier.Operation.MULTIPLY_BASE); + getDamageTaken(player, attacker, damageSource, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); damageTaken *= 1 + multiplier; float multiplierTotal = - getDamageTaken(player, attacker, damageSource, AttributeModifier.Operation.MULTIPLY_TOTAL); + getDamageTaken(player, attacker, damageSource, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL); damageTaken *= 1 + multiplierTotal; event.setAmount(damageTaken); } @SubscribeEvent(priority = EventPriority.LOWEST) - public static void applyDamageAvoidanceBonuses(LivingAttackEvent event) { + public static void applyDamageAvoidanceBonuses(LivingIncomingDamageEvent event) { if (!(event.getEntity() instanceof Player player)) { return; } @@ -568,7 +612,7 @@ private static void applyEventListenerEffect(Player player, LivingEntity attacke } @SubscribeEvent(priority = EventPriority.LOWEST) - public static void applyDamageConversionBonuses(LivingHurtEvent event) { + public static void applyDamageConversionBonuses(LivingIncomingDamageEvent event) { DamageSource originalDamageSource = event.getSource(); if (!(originalDamageSource.getEntity() instanceof Player player)) return; if (getDamageConversionBonuses(player, originalDamageSource).findAny().isEmpty()) { @@ -645,7 +689,7 @@ public static void applyProjectileDuplicationBonuses(EntityJoinLevelEvent event) } @SubscribeEvent(priority = EventPriority.HIGH) - public static void forcefullyInflictDuplicatedProjectileDamage(LivingAttackEvent event) { + public static void forcefullyInflictDuplicatedProjectileDamage(LivingIncomingDamageEvent event) { DamageSource damageSource = event.getSource(); if (!(damageSource.getDirectEntity() instanceof Projectile projectile && projectile.getOwner() instanceof Player)) return; @@ -760,8 +804,6 @@ private static void duplicateProjectileWithOffset( if (duplicate instanceof AbstractArrow duplicateArrow) { AbstractArrow originalArrow = (AbstractArrow) original; duplicateArrow.pickup = AbstractArrow.Pickup.DISALLOWED; - float velocity = (float) movementVector.length(); - duplicateArrow.setEnchantmentEffectsFromEntity(player, velocity); duplicateArrow.setBaseDamage(originalArrow.getBaseDamage()); } else if (duplicate instanceof ThrownPotion potion) { ThrownPotion originalPotion = (ThrownPotion) original; @@ -789,7 +831,7 @@ private static float getConvertedDamagePercentage( @NotNull private static Map getDamageConversionMap( - LivingHurtEvent event, Player player, DamageSource originalDamageSource) { + LivingIncomingDamageEvent event, Player player, DamageSource originalDamageSource) { Map conversions = new HashMap<>(); getDamageConversionBonuses(player, originalDamageSource) .forEach( @@ -898,7 +940,7 @@ private static List getPlayerBonuses(Player player, Class type) { private static List getEffectBonuses(Player player, Class type) { List bonuses = new ArrayList<>(); for (MobEffectInstance e : player.getActiveEffects()) { - if (e.getEffect() instanceof SkillBonusEffect skillEffect) { + if (e.getEffect().value() instanceof SkillBonusEffect skillEffect) { SkillBonus bonus = skillEffect.getBonus().copy(); if (type.isInstance(bonus)) { bonus = bonus.copy().multiply(e.getAmplifier()); diff --git a/src/main/java/daripher/skilltree/skill/bonus/function/AttributeValueFunction.java b/src/main/java/daripher/skilltree/skill/bonus/function/AttributeValueFunction.java index 277adc65e..2b6ca9f04 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/function/AttributeValueFunction.java +++ b/src/main/java/daripher/skilltree/skill/bonus/function/AttributeValueFunction.java @@ -9,6 +9,8 @@ import daripher.skilltree.skill.bonus.SkillBonus; import daripher.skilltree.skill.bonus.predicate.living.FloatFunctionEntityPredicate; import net.minecraft.ChatFormatting; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; @@ -30,7 +32,8 @@ public AttributeValueFunction(Attribute attribute) { @Override public float apply(LivingEntity entity) { AttributeMap attributes = entity.getAttributes(); - return attributes.hasAttribute(attribute) ? (float) attributes.getValue(attribute) : 0f; + Holder attributeHolder = getAttributeHolder(); + return attributes.hasAttribute(attributeHolder) ? (float) attributes.getValue(attributeHolder) : 0f; } @Override @@ -90,6 +93,10 @@ public Attribute getAttribute() { return attribute; } + private Holder getAttributeHolder() { + return BuiltInRegistries.ATTRIBUTE.wrapAsHolder(attribute); + } + public static class Serializer implements FloatFunction.Serializer { @Override public FloatFunction deserialize(JsonObject json) throws JsonParseException { @@ -137,7 +144,7 @@ public void serialize(FriendlyByteBuf buf, FloatFunction provider) { @Override public FloatFunction createDefaultInstance() { - return new AttributeValueFunction(Attributes.MAX_HEALTH); + return new AttributeValueFunction(Attributes.MAX_HEALTH.value()); } } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/function/EffectAmountFunction.java b/src/main/java/daripher/skilltree/skill/bonus/function/EffectAmountFunction.java index b3e8227eb..e7dc60a4f 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/function/EffectAmountFunction.java +++ b/src/main/java/daripher/skilltree/skill/bonus/function/EffectAmountFunction.java @@ -29,7 +29,7 @@ public EffectAmountFunction(EffectType effectType) { @Override public float apply(LivingEntity entity) { - List effects = entity.getActiveEffects().stream().map(MobEffectInstance::getEffect).toList(); + List effects = entity.getActiveEffects().stream().map(effect -> effect.getEffect().value()).toList(); return switch (effectType) { case ANY -> effects.size(); case NEUTRAL -> effects.stream().filter(e -> e.getCategory() == MobEffectCategory.NEUTRAL).count(); diff --git a/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentAmountFunction.java b/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentAmountFunction.java index 83dca4eef..2d4a51cc1 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentAmountFunction.java +++ b/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentAmountFunction.java @@ -39,7 +39,7 @@ public float apply(LivingEntity entity) { } private int getEnchants(Stream items) { - return items.map(EnchantmentHelper::getEnchantments).map(Map::size).reduce(Integer::sum).orElse(0); + return items.map(ItemStack::getEnchantments).mapToInt(enchantments -> enchantments.size()).sum(); } @Override diff --git a/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentLevelsFunction.java b/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentLevelsFunction.java index a52b7f7a6..2889a5d12 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentLevelsFunction.java +++ b/src/main/java/daripher/skilltree/skill/bonus/function/EnchantmentLevelsFunction.java @@ -38,7 +38,12 @@ public float apply(LivingEntity entity) { } private int getEnchantLevels(Stream items) { - return items.map(EnchantmentHelper::getEnchantments).mapToInt(m -> m.values().stream().reduce(Integer::sum).orElse(0)).reduce(Integer::sum).orElse(0); + return items + .map(ItemStack::getEnchantments) + .mapToInt( + enchantments -> + enchantments.entrySet().stream().mapToInt(entry -> entry.getIntValue()).sum()) + .sum(); } @Override diff --git a/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusHandler.java b/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusHandler.java index 0adb56f60..92329e1b7 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusHandler.java +++ b/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusHandler.java @@ -14,18 +14,23 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Style; import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.event.entity.living.LivingEquipmentChangeEvent; -import net.minecraftforge.event.entity.player.ItemTooltipEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.minecraft.world.item.component.CustomData; +import net.neoforged.neoforge.event.entity.living.LivingEquipmentChangeEvent; +import net.neoforged.neoforge.event.entity.player.ItemTooltipEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.EventBusSubscriber.Bus; import org.jetbrains.annotations.Nullable; -@Mod.EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE) +@EventBusSubscriber(modid = SkillTreeMod.MOD_ID, bus = Bus.GAME) public class ItemBonusHandler { + private static final String SKILL_BONUSES_TAG = "SkillBonuses"; + @SubscribeEvent public static void addItemBonusTooltips(ItemTooltipEvent event) { List components = event.getToolTip(); @@ -48,11 +53,11 @@ public static void addCraftedItemAttributeBonuses(LivingEquipmentChangeEvent eve if (!(bonus.skillBonus() instanceof AttributeBonus attributeBonus)) { continue; } - AttributeInstance attributeInstance = entity.getAttribute(attributeBonus.getAttribute()); + AttributeInstance attributeInstance = entity.getAttribute(attributeBonus.getAttributeHolder()); if (attributeInstance == null) { continue; } - attributeInstance.removeModifier(attributeBonus.getModifier().getId()); + attributeInstance.removeModifier(attributeBonus.getModifier().id()); } for (ItemBonus itemBonus : getItemBonuses(event.getTo(), SkillBonusItemBonus.class)) { SkillBonusItemBonus bonus = (SkillBonusItemBonus) itemBonus; @@ -62,11 +67,11 @@ public static void addCraftedItemAttributeBonuses(LivingEquipmentChangeEvent eve if (attributeBonus.isDynamic()) { continue; } - AttributeInstance attributeInstance = entity.getAttribute(attributeBonus.getAttribute()); + AttributeInstance attributeInstance = entity.getAttribute(attributeBonus.getAttributeHolder()); if (attributeInstance == null) { continue; } - if (attributeInstance.hasModifier(attributeBonus.getModifier())) { + if (attributeInstance.hasModifier(attributeBonus.getModifier().id())) { continue; } attributeInstance.addTransientModifier(attributeBonus.getModifier()); @@ -74,10 +79,10 @@ public static void addCraftedItemAttributeBonuses(LivingEquipmentChangeEvent eve } public static List> getItemBonuses(ItemStack stack) { - if (!stack.hasTag()) return ImmutableList.of(); + CustomData customData = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY); + if (!customData.contains(SKILL_BONUSES_TAG)) return ImmutableList.of(); List> list = new ArrayList<>(); - CompoundTag stackTag = stack.getOrCreateTag(); - CompoundTag bonusesTag = stackTag.getCompound("SkillBonuses"); + CompoundTag bonusesTag = customData.copyTag().getCompound(SKILL_BONUSES_TAG); for (int i = 0; true; i++) { if (!bonusesTag.contains("" + i)) { return list; @@ -107,14 +112,11 @@ public static void setItemBonuses(ItemStack stack, List> bonuses) { bonusesTag.put("" + i, bonusTag); i++; } - stack.getOrCreateTag().put("SkillBonuses", bonusesTag); + CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put(SKILL_BONUSES_TAG, bonusesTag)); } public static void removeItemBonuses(ItemStack stack) { - if (!stack.hasTag()) { - return; - } - stack.getOrCreateTag().remove("SkillBonuses"); + CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.remove(SKILL_BONUSES_TAG)); } private static CompoundTag serializeBonus(ItemBonus> bonus) { @@ -127,7 +129,7 @@ private static CompoundTag serializeBonus(ItemBonus> bonu private static ItemBonus deserializeBonus(CompoundTag tag) { if (!tag.contains("type")) return null; - ResourceLocation id = new ResourceLocation(tag.getString("type")); + ResourceLocation id = ResourceLocation.parse(tag.getString("type")); ItemBonus.Serializer serializer = PSTRegistries.ITEM_BONUSES.get().getValue(id); if (serializer == null) return null; try { diff --git a/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusListItemBonus.java b/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusListItemBonus.java index 684b370ea..63a9982e1 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusListItemBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/item/ItemBonusListItemBonus.java @@ -3,6 +3,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import daripher.skilltree.SkillTreeMod; import daripher.skilltree.init.PSTItemBonuses; import daripher.skilltree.init.PSTRegistries; import daripher.skilltree.network.NetworkHelper; @@ -105,7 +106,7 @@ public ItemBonus deserialize(JsonObject json) throws JsonParseException { for (int i = 0; i < innerBonusesJson.size(); i++) { JsonObject innerBonusTag = innerBonusesJson.get(i).getAsJsonObject(); String serializerIdString = innerBonusTag.get("type").getAsString(); - ResourceLocation serializerId = new ResourceLocation(serializerIdString); + ResourceLocation serializerId = ResourceLocation.parse(serializerIdString); ItemBonus.Serializer serializer = PSTRegistries.ITEM_BONUSES.get().getValue(serializerId); Objects.requireNonNull(serializer, "Unknown item bonus: " + serializerId); ItemBonus innerBonus = serializer.deserialize(innerBonusTag); @@ -140,7 +141,7 @@ public ItemBonus deserialize(CompoundTag tag) { for (Tag value : innerBonusesTag) { CompoundTag innerBonusTag = (CompoundTag) value; String type = innerBonusTag.getString("type"); - ResourceLocation serializerId = new ResourceLocation(type); + ResourceLocation serializerId = ResourceLocation.parse(type); ItemBonus.Serializer serializer = PSTRegistries.ITEM_BONUSES.get().getValue(serializerId); Objects.requireNonNull(serializer, "Unknown item bonus: " + serializerId); innerBonuses.add(serializer.deserialize(innerBonusTag)); @@ -192,11 +193,14 @@ public void serialize(FriendlyByteBuf buf, ItemBonus bonus) { @Override public ItemBonus createDefaultInstance() { AttributeModifier defaultModifier = - new AttributeModifier("Default Modifier", 1, AttributeModifier.Operation.ADDITION); + new AttributeModifier( + ResourceLocation.fromNamespaceAndPath(SkillTreeMod.MOD_ID, "default_item_bonus"), + 1, + AttributeModifier.Operation.ADD_VALUE); ItemBonus bonus1 = - new SkillBonusItemBonus(new AttributeBonus(Attributes.ARMOR, defaultModifier)); + new SkillBonusItemBonus(new AttributeBonus(Attributes.ARMOR.value(), defaultModifier)); ItemBonus bonus2 = - new SkillBonusItemBonus(new AttributeBonus(Attributes.ARMOR_TOUGHNESS, defaultModifier)); + new SkillBonusItemBonus(new AttributeBonus(Attributes.ARMOR_TOUGHNESS.value(), defaultModifier)); return new ItemBonusListItemBonus(List.of(bonus1, bonus2)); } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/item/SkillBonusItemBonus.java b/src/main/java/daripher/skilltree/skill/bonus/item/SkillBonusItemBonus.java index b160fd778..5009c5afc 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/item/SkillBonusItemBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/item/SkillBonusItemBonus.java @@ -93,7 +93,7 @@ public void serialize(JsonObject json, ItemBonus bonus) { public ItemBonus deserialize(CompoundTag tag) { CompoundTag skillBonusTag = tag.getCompound("skill_bonus"); String type = skillBonusTag.getString("type"); - ResourceLocation serializerId = new ResourceLocation(type); + ResourceLocation serializerId = ResourceLocation.parse(type); SkillBonus.Serializer serializer = PSTRegistries.SKILL_BONUSES.get().getValue(serializerId); Objects.requireNonNull(serializer, "Unknown skill bonus: " + serializerId); SkillBonus skillBonus = serializer.deserialize(skillBonusTag); @@ -131,7 +131,7 @@ public void serialize(FriendlyByteBuf buf, ItemBonus bonus) { @Override public ItemBonus createDefaultInstance() { - return new SkillBonusItemBonus(new DamageBonus(0.1f, AttributeModifier.Operation.MULTIPLY_BASE)); + return new SkillBonusItemBonus(new DamageBonus(0.1f, AttributeModifier.Operation.ADD_MULTIPLIED_BASE)); } } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/multiplier/FloatFunctionMultiplier.java b/src/main/java/daripher/skilltree/skill/bonus/multiplier/FloatFunctionMultiplier.java index 199e65688..e8e8c1220 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/multiplier/FloatFunctionMultiplier.java +++ b/src/main/java/daripher/skilltree/skill/bonus/multiplier/FloatFunctionMultiplier.java @@ -163,7 +163,7 @@ public void serialize(FriendlyByteBuf buf, LivingMultiplier multiplier) { @Override public LivingMultiplier createDefaultInstance() { - return new FloatFunctionMultiplier(new AttributeValueFunction(Attributes.MAX_HEALTH), 5f); + return new FloatFunctionMultiplier(new AttributeValueFunction(Attributes.MAX_HEALTH.value()), 5f); } } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/AllAttributesBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/AllAttributesBonus.java index cf5379fd7..33d61e450 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/AllAttributesBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/AllAttributesBonus.java @@ -1,6 +1,7 @@ package daripher.skilltree.skill.bonus.player; import com.google.gson.*; +import daripher.skilltree.SkillTreeMod; import daripher.skilltree.client.tooltip.TooltipHelper; import daripher.skilltree.client.widget.editor.SkillTreeEditor; import daripher.skilltree.data.serializers.SerializationHelper; @@ -19,9 +20,12 @@ import java.util.function.Consumer; import javax.annotation.Nonnull; import net.minecraft.ChatFormatting; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.ai.attributes.Attribute; @@ -29,12 +33,11 @@ import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.registries.ForgeRegistries; +import daripher.skilltree.util.ForgeRegistries; public final class AllAttributesBonus implements SkillBonus, TickingSkillBonus { - private static final Set AFFECTED_ATTRIBUTES = new HashSet<>(); + private static final Set> AFFECTED_ATTRIBUTES = new HashSet<>(); private AttributeModifier modifier; private @Nonnull LivingMultiplier playerMultiplier = NoneLivingMultiplier.INSTANCE; private @Nonnull LivingEntityPredicate playerCondition = NoneLivingEntityPredicate.INSTANCE; @@ -52,7 +55,7 @@ public void onSkillLearned(ServerPlayer player, boolean firstTime) { getAffectedAttributes().stream() .map(player::getAttribute) .filter(Objects::nonNull) - .filter(a -> !a.hasModifier(modifier)) + .filter(a -> !a.hasModifier(modifier.id())) .forEach(a -> applyAttributeModifier(a, modifier, player)); } @@ -61,8 +64,8 @@ public void onSkillRemoved(ServerPlayer player) { getAffectedAttributes().stream() .map(player::getAttribute) .filter(Objects::nonNull) - .filter(a -> !a.hasModifier(modifier)) - .forEach(a -> a.removeModifier(modifier.getId())); + .filter(a -> !a.hasModifier(modifier.id())) + .forEach(a -> a.removeModifier(modifier.id())); } @Override @@ -91,18 +94,18 @@ private void applyDynamicAttributeBonus(ServerPlayer player) { .filter(Objects::nonNull) .forEach( playerAttribute -> { - AttributeModifier oldModifier = playerAttribute.getModifier(modifier.getId()); - double value = modifier.getAmount(); + AttributeModifier oldModifier = playerAttribute.getModifier(modifier.id()); + double value = modifier.amount(); value *= playerMultiplier.getValue(player); if (oldModifier != null) { - if (oldModifier.getAmount() == value) return; - playerAttribute.removeModifier(modifier.getId()); + if (oldModifier.amount() == value) return; + playerAttribute.removeModifier(modifier.id()); } AttributeModifier dynamicModifier = new AttributeModifier( - modifier.getId(), "Dynamic", value, modifier.getOperation()); + modifier.id(), value, modifier.operation()); applyAttributeModifier(playerAttribute, dynamicModifier, player); - if (playerAttribute.getAttribute() == Attributes.MAX_HEALTH) { + if (playerAttribute.getAttribute().is(Attributes.MAX_HEALTH)) { player.setHealth(player.getHealth()); } }); @@ -126,10 +129,10 @@ public SkillBonus.Serializer getSerializer() { public AllAttributesBonus copy() { AttributeModifier modifier = new AttributeModifier( - UUID.randomUUID(), - this.modifier.getName(), - this.modifier.getAmount(), - this.modifier.getOperation()); + ResourceLocation.fromNamespaceAndPath( + SkillTreeMod.MOD_ID, "all_attributes_bonus/" + UUID.randomUUID()), + this.modifier.amount(), + this.modifier.operation()); AllAttributesBonus bonus = new AllAttributesBonus(modifier); bonus.playerMultiplier = this.playerMultiplier; bonus.playerCondition = this.playerCondition; @@ -140,10 +143,9 @@ public AllAttributesBonus copy() { public AllAttributesBonus multiply(double multiplier) { modifier = new AttributeModifier( - modifier.getId(), - modifier.getName(), - modifier.getAmount() * multiplier, - modifier.getOperation()); + modifier.id(), + modifier.amount() * multiplier, + modifier.operation()); return this; } @@ -152,7 +154,7 @@ public boolean canMerge(SkillBonus other) { if (!(other instanceof AllAttributesBonus otherBonus)) return false; if (!Objects.equals(otherBonus.playerMultiplier, this.playerMultiplier)) return false; if (!Objects.equals(otherBonus.playerCondition, this.playerCondition)) return false; - return otherBonus.modifier.getOperation() == this.modifier.getOperation(); + return otherBonus.modifier.operation() == this.modifier.operation(); } @Override @@ -162,10 +164,9 @@ public SkillBonus merge(SkillBonus other) { } AttributeModifier mergedModifier = new AttributeModifier( - this.modifier.getId(), - "Merged", - this.modifier.getAmount() + otherBonus.modifier.getAmount(), - this.modifier.getOperation()); + this.modifier.id(), + this.modifier.amount() + otherBonus.modifier.amount(), + this.modifier.operation()); AllAttributesBonus mergedBonus = new AllAttributesBonus(mergedModifier); mergedBonus.playerMultiplier = this.playerMultiplier; mergedBonus.playerCondition = this.playerCondition; @@ -176,7 +177,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { MutableComponent tooltip = TooltipHelper.getSkillBonusTooltip( - getDescriptionId(), modifier.getAmount(), modifier.getOperation()); + getDescriptionId(), modifier.amount(), modifier.operation()); tooltip = playerMultiplier.getTooltip(tooltip, Target.PLAYER); tooltip = playerCondition.getTooltip(tooltip, Target.PLAYER); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); @@ -184,7 +185,7 @@ public MutableComponent getTooltip() { @Override public boolean isPositive() { - return modifier.getAmount() > 0; + return modifier.amount() > 0; } @Override @@ -194,10 +195,10 @@ public void addEditorWidgets( editor.addLabel(0, 0, "Operation", ChatFormatting.GOLD); editor.increaseHeight(19); editor - .addNumericTextField(110, 0, 50, 14, modifier.getAmount()) + .addNumericTextField(110, 0, 50, 14, modifier.amount()) .setNumericResponder(value -> selectAmount(consumer, value)); editor - .addOperationSelection(0, 0, 80, modifier.getOperation()) + .addOperationSelection(0, 0, 80, modifier.operation()) .setResponder(operation -> selectOperation(consumer, operation)); editor.increaseHeight(29); editor.addLabel(0, 0, "Player Condition", ChatFormatting.GOLD); @@ -264,13 +265,13 @@ private void addPlayerConditionWidgets( public void setAmount(double amount) { this.modifier = new AttributeModifier( - modifier.getId(), modifier.getName(), amount, modifier.getOperation()); + modifier.id(), amount, modifier.operation()); } public void setOperation(AttributeModifier.Operation operation) { this.modifier = new AttributeModifier( - modifier.getId(), modifier.getName(), modifier.getAmount(), operation); + modifier.id(), modifier.amount(), operation); } public SkillBonus setCondition(LivingEntityPredicate condition) { @@ -284,10 +285,11 @@ public SkillBonus setMultiplier(LivingMultiplier multiplier) { } @SuppressWarnings("deprecation") - private static Set getAffectedAttributes() { + private static Set> getAffectedAttributes() { if (AFFECTED_ATTRIBUTES.isEmpty()) { ForgeRegistries.ATTRIBUTES.getValues().stream() - .filter(ForgeHooks.getAttributesView().get(EntityType.PLAYER)::hasAttribute) + .map(BuiltInRegistries.ATTRIBUTE::wrapAsHolder) + .filter(Player.createAttributes().build()::hasAttribute) .forEach(AFFECTED_ATTRIBUTES::add); } return AFFECTED_ATTRIBUTES; @@ -364,7 +366,10 @@ public void serialize(FriendlyByteBuf buf, SkillBonus bonus) { public SkillBonus createDefaultInstance() { return new AllAttributesBonus( new AttributeModifier( - UUID.randomUUID(), "Skill", 0.05, AttributeModifier.Operation.MULTIPLY_BASE)); + ResourceLocation.fromNamespaceAndPath( + SkillTreeMod.MOD_ID, "all_attributes_bonus/" + UUID.randomUUID()), + 0.05, + AttributeModifier.Operation.ADD_MULTIPLIED_BASE)); } } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/ArrowRetrievalBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/ArrowRetrievalBonus.java index fcbb526a8..084a78db8 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/ArrowRetrievalBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/ArrowRetrievalBonus.java @@ -52,7 +52,7 @@ public SkillBonus merge(SkillBonus other) { @Override public MutableComponent getTooltip() { return TooltipHelper.getSkillBonusTooltip( - getDescriptionId(), chance, AttributeModifier.Operation.MULTIPLY_BASE) + getDescriptionId(), chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE) .withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/AttributeBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/AttributeBonus.java index f28e2fb62..b1ca1741c 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/AttributeBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/AttributeBonus.java @@ -19,10 +19,13 @@ import java.util.function.Consumer; import javax.annotation.Nonnull; import net.minecraft.ChatFormatting; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeInstance; @@ -47,28 +50,28 @@ public void onSkillLearned(ServerPlayer player, boolean firstTime) { || playerMultiplier != NoneLivingMultiplier.INSTANCE) { return; } - AttributeInstance instance = player.getAttribute(attribute); + AttributeInstance instance = player.getAttribute(getAttributeHolder()); if (instance == null) { SkillTreeMod.LOGGER.error( "Attempting to add attribute modifier to attribute {}, which is not present for player", attribute); return; } - if (!instance.hasModifier(modifier)) { + if (!instance.hasModifier(modifier.id())) { applyAttributeModifier(instance, modifier, player); } } @Override public void onSkillRemoved(ServerPlayer player) { - AttributeInstance instance = player.getAttribute(attribute); + AttributeInstance instance = player.getAttribute(getAttributeHolder()); if (instance == null) { SkillTreeMod.LOGGER.error( "Attempting to remove attribute modifier from attribute {}, which is not present for player", attribute); return; } - instance.removeModifier(modifier.getId()); + instance.removeModifier(modifier.id()); } @Override @@ -96,27 +99,27 @@ public boolean isDynamic() { } private void applyDynamicAttributeBonus(ServerPlayer player) { - AttributeInstance instance = player.getAttribute(attribute); + AttributeInstance instance = player.getAttribute(getAttributeHolder()); if (instance == null) return; - AttributeModifier oldModifier = instance.getModifier(modifier.getId()); - double value = modifier.getAmount(); + AttributeModifier oldModifier = instance.getModifier(modifier.id()); + double value = modifier.amount(); value *= playerMultiplier.getValue(player); if (oldModifier != null) { - if (oldModifier.getAmount() == value) return; + if (oldModifier.amount() == value) return; } AttributeModifier dynamicModifier = - new AttributeModifier(modifier.getId(), "DynamicBonus", value, modifier.getOperation()); + new AttributeModifier(modifier.id(), value, modifier.operation()); applyAttributeModifier(instance, dynamicModifier, player); } private void applyAttributeModifier( AttributeInstance instance, AttributeModifier modifier, Player player) { float healthPercentage = player.getHealth() / player.getMaxHealth(); - if (instance.getModifier(modifier.getId()) != null) { - instance.removeModifier(modifier.getId()); + if (instance.getModifier(modifier.id()) != null) { + instance.removeModifier(modifier.id()); } instance.addTransientModifier(modifier); - if (attribute == Attributes.MAX_HEALTH) { + if (attribute == Attributes.MAX_HEALTH.value()) { player.setHealth(player.getMaxHealth() * healthPercentage); } } @@ -130,10 +133,10 @@ public SkillBonus.Serializer getSerializer() { public AttributeBonus copy() { AttributeModifier modifier = new AttributeModifier( - UUID.randomUUID(), - this.modifier.getName(), - this.modifier.getAmount(), - this.modifier.getOperation()); + ResourceLocation.fromNamespaceAndPath( + SkillTreeMod.MOD_ID, "attribute_bonus/" + UUID.randomUUID()), + this.modifier.amount(), + this.modifier.operation()); AttributeBonus bonus = new AttributeBonus(attribute, modifier); bonus.playerMultiplier = this.playerMultiplier; bonus.playerCondition = this.playerCondition; @@ -144,10 +147,9 @@ public AttributeBonus copy() { public AttributeBonus multiply(double multiplier) { modifier = new AttributeModifier( - modifier.getId(), - modifier.getName(), - modifier.getAmount() * multiplier, - modifier.getOperation()); + modifier.id(), + modifier.amount() * multiplier, + modifier.operation()); return this; } @@ -157,7 +159,7 @@ public boolean canMerge(SkillBonus other) { if (otherBonus.attribute != this.attribute) return false; if (!Objects.equals(otherBonus.playerMultiplier, this.playerMultiplier)) return false; if (!Objects.equals(otherBonus.playerCondition, this.playerCondition)) return false; - return otherBonus.modifier.getOperation() == this.modifier.getOperation(); + return otherBonus.modifier.operation() == this.modifier.operation(); } @Override @@ -167,10 +169,9 @@ public SkillBonus merge(SkillBonus other) { } AttributeModifier mergedModifier = new AttributeModifier( - this.modifier.getId(), - "Merged", - this.modifier.getAmount() + otherBonus.modifier.getAmount(), - this.modifier.getOperation()); + this.modifier.id(), + this.modifier.amount() + otherBonus.modifier.amount(), + this.modifier.operation()); AttributeBonus mergedBonus = new AttributeBonus(this.attribute, mergedModifier); mergedBonus.playerMultiplier = this.playerMultiplier; mergedBonus.playerCondition = this.playerCondition; @@ -179,7 +180,7 @@ public SkillBonus merge(SkillBonus other) { @Override public MutableComponent getTooltip() { - float visibleAmount = (float) modifier.getAmount(); + float visibleAmount = (float) modifier.amount(); String descriptionId = attribute.getDescriptionId(); MutableComponent tooltip; if (isPercentageRegeneration()) { @@ -191,7 +192,7 @@ public MutableComponent getTooltip() { if (isKnockbackResistanceAddition()) { visibleAmount *= 10; } - AttributeModifier.Operation operation = modifier.getOperation(); + AttributeModifier.Operation operation = modifier.operation(); tooltip = TooltipHelper.getSkillBonusTooltip(descriptionId, visibleAmount, operation); tooltip = playerMultiplier.getTooltip(tooltip, Target.PLAYER); } @@ -200,16 +201,16 @@ public MutableComponent getTooltip() { } private boolean isKnockbackResistanceAddition() { - return modifier.getOperation() == AttributeModifier.Operation.ADDITION - && attribute.equals(Attributes.KNOCKBACK_RESISTANCE); + return modifier.operation() == AttributeModifier.Operation.ADD_VALUE + && attribute.equals(Attributes.KNOCKBACK_RESISTANCE.value()); } private boolean isPercentageRegeneration() { - return modifier.getOperation() == AttributeModifier.Operation.ADDITION + return modifier.operation() == AttributeModifier.Operation.ADD_VALUE && playerMultiplier instanceof FloatFunctionMultiplier floatFunctionMultiplier && floatFunctionMultiplier.getFloatFunction() instanceof AttributeValueFunction attributeValueFunction - && attributeValueFunction.getAttribute() == Attributes.MAX_HEALTH + && attributeValueFunction.getAttribute() == Attributes.MAX_HEALTH.value() && floatFunctionMultiplier.getDivisor() == 1; } @@ -221,7 +222,7 @@ public void gatherInfo(Consumer consumer) { @Override public boolean isPositive() { - return modifier.getAmount() > 0; + return modifier.amount() > 0; } @Override @@ -237,10 +238,10 @@ public void addEditorWidgets( editor.addLabel(0, 0, "Operation", ChatFormatting.GOLD); editor.increaseHeight(19); editor - .addNumericTextField(110, 0, 50, 14, modifier.getAmount()) + .addNumericTextField(110, 0, 50, 14, modifier.amount()) .setNumericResponder(value -> selectAmount(consumer, value)); editor - .addOperationSelection(0, 0, 80, modifier.getOperation()) + .addOperationSelection(0, 0, 80, modifier.operation()) .setResponder(operation -> selectOperation(consumer, operation)); editor.increaseHeight(29); editor.addLabel(0, 0, "Player Condition", ChatFormatting.GOLD); @@ -313,6 +314,10 @@ public Attribute getAttribute() { return attribute; } + public Holder getAttributeHolder() { + return BuiltInRegistries.ATTRIBUTE.wrapAsHolder(attribute); + } + public AttributeModifier getModifier() { return modifier; } @@ -324,13 +329,13 @@ public void setAttribute(Attribute attribute) { public void setAmount(double amount) { this.modifier = new AttributeModifier( - modifier.getId(), modifier.getName(), amount, modifier.getOperation()); + modifier.id(), amount, modifier.operation()); } public void setOperation(AttributeModifier.Operation operation) { this.modifier = new AttributeModifier( - modifier.getId(), modifier.getName(), modifier.getAmount(), operation); + modifier.id(), modifier.amount(), operation); } public SkillBonus setCondition(LivingEntityPredicate condition) { @@ -419,9 +424,12 @@ public void serialize(FriendlyByteBuf buf, SkillBonus bonus) { @Override public SkillBonus createDefaultInstance() { return new AttributeBonus( - Attributes.ARMOR, + Attributes.ARMOR.value(), new AttributeModifier( - UUID.randomUUID(), "Skill", 1, AttributeModifier.Operation.ADDITION)); + ResourceLocation.fromNamespaceAndPath( + SkillTreeMod.MOD_ID, "attribute_bonus/" + UUID.randomUUID()), + 1, + AttributeModifier.Operation.ADD_VALUE)); } } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/BlockBreakSpeedBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/BlockBreakSpeedBonus.java index 79aaff179..cb22d286a 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/BlockBreakSpeedBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/BlockBreakSpeedBonus.java @@ -74,7 +74,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { MutableComponent bonusTooltip = TooltipHelper.getSkillBonusTooltip( - getDescriptionId(), multiplier, AttributeModifier.Operation.MULTIPLY_BASE); + getDescriptionId(), multiplier, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); bonusTooltip = playerCondition.getTooltip(bonusTooltip, Target.PLAYER); bonusTooltip = playerMultiplier.getTooltip(bonusTooltip, Target.PLAYER); return bonusTooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/CritChanceBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/CritChanceBonus.java index cbc1dec7a..9142c6ea0 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/CritChanceBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/CritChanceBonus.java @@ -95,7 +95,7 @@ public SkillBonus merge(SkillBonus other) { @Override public MutableComponent getTooltip() { - AttributeModifier.Operation operation = AttributeModifier.Operation.MULTIPLY_BASE; + AttributeModifier.Operation operation = AttributeModifier.Operation.ADD_MULTIPLIED_BASE; MutableComponent tooltip; if (damageCondition == NoneDamageCondition.INSTANCE) { tooltip = TooltipHelper.getSkillBonusTooltip(getDescriptionId(), chance, operation); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/CritDamageBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/CritDamageBonus.java index 921a6e0f3..39ddc2e68 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/CritDamageBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/CritDamageBonus.java @@ -93,7 +93,7 @@ public SkillBonus merge(SkillBonus other) { @Override public MutableComponent getTooltip() { - AttributeModifier.Operation operation = AttributeModifier.Operation.MULTIPLY_BASE; + AttributeModifier.Operation operation = AttributeModifier.Operation.ADD_MULTIPLIED_BASE; MutableComponent tooltip; if (damageCondition == NoneDamageCondition.INSTANCE) { tooltip = TooltipHelper.getSkillBonusTooltip(getDescriptionId(), amount, operation); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/DamageAvoidanceBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/DamageAvoidanceBonus.java index cfe7c0fcd..377620ce4 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/DamageAvoidanceBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/DamageAvoidanceBonus.java @@ -109,7 +109,7 @@ public MutableComponent getTooltip() { Component.translatable(getDescriptionId(), damageCondition.getTooltip()); tooltip = TooltipHelper.getSkillBonusTooltip( - tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); tooltip = playerMultiplier.getTooltip(tooltip, Target.PLAYER); tooltip = attackerMultiplier.getTooltip(tooltip, Target.ENEMY); tooltip = playerCondition.getTooltip(tooltip, Target.PLAYER); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/DamageBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/DamageBonus.java index a63c9a047..3a5350a4d 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/DamageBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/DamageBonus.java @@ -356,7 +356,7 @@ public CompoundTag serialize(SkillBonus bonus) { @Override public DamageBonus deserialize(FriendlyByteBuf buf) { float amount = buf.readFloat(); - AttributeModifier.Operation operation = AttributeModifier.Operation.fromValue(buf.readInt()); + AttributeModifier.Operation operation = AttributeModifier.Operation.BY_ID.apply(buf.readInt()); DamageBonus bonus = new DamageBonus(amount, operation); bonus.playerMultiplier = NetworkHelper.readLivingMultiplier(buf); bonus.targetMultiplier = NetworkHelper.readLivingMultiplier(buf); @@ -372,7 +372,7 @@ public void serialize(FriendlyByteBuf buf, SkillBonus bonus) { throw new IllegalArgumentException(); } buf.writeFloat(aBonus.amount); - buf.writeInt(aBonus.operation.toValue()); + buf.writeInt(aBonus.operation.id()); NetworkHelper.writeLivingMultiplier(buf, aBonus.playerMultiplier); NetworkHelper.writeLivingMultiplier(buf, aBonus.targetMultiplier); NetworkHelper.writeLivingCondition(buf, aBonus.playerCondition); @@ -382,7 +382,7 @@ public void serialize(FriendlyByteBuf buf, SkillBonus bonus) { @Override public SkillBonus createDefaultInstance() { - return new DamageBonus(0.1f, AttributeModifier.Operation.MULTIPLY_BASE) + return new DamageBonus(0.1f, AttributeModifier.Operation.ADD_MULTIPLIED_BASE) .setDamageCondition(new MeleeDamageCondition()); } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/DamageTakenBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/DamageTakenBonus.java index eda3b63de..b48361dcb 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/DamageTakenBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/DamageTakenBonus.java @@ -360,7 +360,7 @@ public CompoundTag serialize(SkillBonus bonus) { @Override public DamageTakenBonus deserialize(FriendlyByteBuf buf) { float amount = buf.readFloat(); - AttributeModifier.Operation operation = AttributeModifier.Operation.fromValue(buf.readInt()); + AttributeModifier.Operation operation = AttributeModifier.Operation.BY_ID.apply(buf.readInt()); DamageTakenBonus bonus = new DamageTakenBonus(amount, operation); bonus.playerMultiplier = NetworkHelper.readLivingMultiplier(buf); bonus.attackerMultiplier = NetworkHelper.readLivingMultiplier(buf); @@ -376,7 +376,7 @@ public void serialize(FriendlyByteBuf buf, SkillBonus bonus) { throw new IllegalArgumentException(); } buf.writeFloat(aBonus.amount); - buf.writeInt(aBonus.operation.toValue()); + buf.writeInt(aBonus.operation.id()); NetworkHelper.writeLivingMultiplier(buf, aBonus.playerMultiplier); NetworkHelper.writeLivingMultiplier(buf, aBonus.attackerMultiplier); NetworkHelper.writeLivingCondition(buf, aBonus.playerCondition); @@ -386,7 +386,7 @@ public void serialize(FriendlyByteBuf buf, SkillBonus bonus) { @Override public SkillBonus createDefaultInstance() { - return new DamageTakenBonus(0.1f, AttributeModifier.Operation.MULTIPLY_BASE) + return new DamageTakenBonus(0.1f, AttributeModifier.Operation.ADD_MULTIPLIED_BASE) .setDamageCondition(new MeleeDamageCondition()); } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/EffectDurationBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/EffectDurationBonus.java index ac976b00f..0ed5c94d3 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/EffectDurationBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/EffectDurationBonus.java @@ -102,7 +102,7 @@ public MutableComponent getTooltip() { Component effectTypeDescription = Component.translatable(effectType.getDescriptionId() + ".plural"); String key = getDescriptionId() + "." + target.getName(); MutableComponent tooltip = Component.translatable(key, effectTypeDescription); - tooltip = TooltipHelper.getSkillBonusTooltip(tooltip, duration, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip = TooltipHelper.getSkillBonusTooltip(tooltip, duration, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); tooltip = playerMultiplier.getTooltip(tooltip, target); tooltip = playerCondition.getTooltip(tooltip, target); tooltip = enemyMultiplier.getTooltip(tooltip, target); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/FreeEnchantmentBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/FreeEnchantmentBonus.java index b776b8db2..282de4e7e 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/FreeEnchantmentBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/FreeEnchantmentBonus.java @@ -90,7 +90,7 @@ public MutableComponent getTooltip() { tooltip = Component.translatable(getDescriptionId() + ".chance", itemStackPredicate.getTooltip()); tooltip = TooltipHelper.getSkillBonusTooltip( - tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } else { tooltip = Component.translatable(getDescriptionId(), itemStackPredicate.getTooltip("plural")); } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/GainExperienceBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/GainExperienceBonus.java index 20d510bab..609441cdd 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/GainExperienceBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/GainExperienceBonus.java @@ -94,7 +94,7 @@ public MutableComponent getTooltip() { if (chance < 1) { tooltip = TooltipHelper.getSkillBonusTooltip( - tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } tooltip = eventListener.getTooltip(tooltip); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/GainedExperienceBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/GainedExperienceBonus.java index a9f36ddde..f3cdf0257 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/GainedExperienceBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/GainedExperienceBonus.java @@ -71,7 +71,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { Component sourceDescription = Component.translatable(experienceSource.getDescriptionId()); MutableComponent tooltip = Component.translatable(getDescriptionId(), sourceDescription); - tooltip = TooltipHelper.getSkillBonusTooltip(tooltip, multiplier, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip = TooltipHelper.getSkillBonusTooltip(tooltip, multiplier, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); tooltip = playerMultiplier.getTooltip(tooltip, Target.PLAYER); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/GrantItemBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/GrantItemBonus.java index 1a635a8ef..cd456cadf 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/GrantItemBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/GrantItemBonus.java @@ -20,7 +20,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import net.minecraftforge.registries.ForgeRegistries; +import daripher.skilltree.util.ForgeRegistries; import java.util.List; import java.util.Map; @@ -153,7 +153,7 @@ public void setAmount(int amount) { public static class Serializer implements SkillBonus.Serializer { @Override public GrantItemBonus deserialize(JsonObject json) throws JsonParseException { - ResourceLocation itemId = new ResourceLocation(json.get("item_id") + ResourceLocation itemId = ResourceLocation.parse(json.get("item_id") .getAsString()); int amount = SerializationHelper.getElement(json, "amount") .getAsInt(); @@ -171,7 +171,7 @@ public void serialize(JsonObject json, SkillBonus bonus) { @Override public GrantItemBonus deserialize(CompoundTag tag) { - ResourceLocation itemId = new ResourceLocation(tag.getString("item_id")); + ResourceLocation itemId = ResourceLocation.parse(tag.getString("item_id")); int amount = tag.getInt("amount"); return new GrantItemBonus(itemId, amount); } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/HealingBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/HealingBonus.java index fda388c34..cb32c355d 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/HealingBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/HealingBonus.java @@ -111,7 +111,7 @@ public MutableComponent getTooltip() { if (chance < 1) { tooltip = TooltipHelper.getSkillBonusTooltip( - tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } tooltip = eventListener.getTooltip(tooltip); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/HealthReservationBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/HealthReservationBonus.java index 325bab324..c4a62df94 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/HealthReservationBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/HealthReservationBonus.java @@ -77,7 +77,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { MutableComponent tooltip = TooltipHelper.getSkillBonusTooltip( - getDescriptionId(), amount, AttributeModifier.Operation.MULTIPLY_BASE); + getDescriptionId(), amount, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); tooltip = playerMultiplier.getTooltip(tooltip, Target.PLAYER); tooltip = playerCondition.getTooltip(tooltip, Target.PLAYER); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/IncomingHealingBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/IncomingHealingBonus.java index c7d2ccb79..9e70614cf 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/IncomingHealingBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/IncomingHealingBonus.java @@ -78,7 +78,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { MutableComponent tooltip = TooltipHelper.getSkillBonusTooltip( - getDescriptionId(), multiplier, AttributeModifier.Operation.MULTIPLY_BASE); + getDescriptionId(), multiplier, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); tooltip = playerMultiplier.getTooltip(tooltip, Target.PLAYER); tooltip = playerCondition.getTooltip(tooltip, Target.PLAYER); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/InflictDamageBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/InflictDamageBonus.java index 3e768632e..27c4d9a0c 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/InflictDamageBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/InflictDamageBonus.java @@ -103,7 +103,7 @@ public MutableComponent getTooltip() { } MutableComponent tooltip = Component.translatable(key, damageDescription, damageTypeDescription); if (chance < 1) { - tooltip = TooltipHelper.getSkillBonusTooltip(tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip = TooltipHelper.getSkillBonusTooltip(tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } tooltip = eventListener.getTooltip(tooltip); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/InflictEffectBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/InflictEffectBonus.java index 2e9f16841..b16b8a5a6 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/InflictEffectBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/InflictEffectBonus.java @@ -16,6 +16,8 @@ import daripher.skilltree.skill.bonus.event.TickingEventListener; import net.minecraft.ChatFormatting; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; @@ -56,7 +58,7 @@ public void applyEffect(LivingEntity target) { return; } MobEffectInstance effectInstanceCopy = new MobEffectInstance(effectInstance); - MobEffect effect = effectInstance.getEffect(); + Holder effect = effectInstance.getEffect(); if (maxStacks > 1) { effectInstanceCopy = getStackedEffectInstance(target, effect, effectInstanceCopy); } @@ -64,7 +66,7 @@ public void applyEffect(LivingEntity target) { } private MobEffectInstance getStackedEffectInstance( - LivingEntity target, MobEffect effect, MobEffectInstance effectInstanceCopy) { + LivingEntity target, Holder effect, MobEffectInstance effectInstanceCopy) { MobEffectInstance activeEffectInstance = target.getEffect(effect); if (activeEffectInstance == null) { return effectInstanceCopy; @@ -149,7 +151,7 @@ public MutableComponent getTooltip() { if (chance < 1) { tooltip = TooltipHelper.getSkillBonusTooltip( - tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } tooltip = eventListener.getTooltip(tooltip); if (maxStacks > 1) { @@ -178,7 +180,7 @@ public void gatherInfo(Consumer consumer) { public boolean isPositive() { return chance > 0 ^ eventListener.getTarget() == Target.PLAYER - ^ effectInstance.getEffect().getCategory() != MobEffectCategory.HARMFUL; + ^ effectInstance.getEffect().value().getCategory() != MobEffectCategory.HARMFUL; } @Override @@ -193,7 +195,7 @@ public void addEditorWidgets( editor.addLabel(150, 0, "Chance", ChatFormatting.GOLD); editor.increaseHeight(19); editor - .addSelectionMenu(0, 0, 145, effectInstance.getEffect()) + .addSelectionMenu(0, 0, 145, effectInstance.getEffect().value()) .setResponder(effect -> selectEffect(consumer, effect)); editor .addNumericTextField(150, 0, 50, 14, chance) @@ -281,7 +283,9 @@ public void setChance(float chance) { public void setEffectInstance(MobEffect effectInstance) { this.effectInstance = new MobEffectInstance( - effectInstance, this.effectInstance.getDuration(), this.effectInstance.getAmplifier()); + BuiltInRegistries.MOB_EFFECT.wrapAsHolder(effectInstance), + this.effectInstance.getDuration(), + this.effectInstance.getAmplifier()); } public void setDuration(int duration) { diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/InflictIgniteBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/InflictIgniteBonus.java index 556acaa03..2aaf4ec82 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/InflictIgniteBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/InflictIgniteBonus.java @@ -39,7 +39,7 @@ public InflictIgniteBonus(float chance, int duration) { @Override public void applyEffect(LivingEntity target) { if (target.getRandom().nextFloat() < chance) { - target.setSecondsOnFire(duration); + target.igniteForSeconds(duration); } } @@ -76,7 +76,7 @@ public SkillBonus> merge(SkillBonus ot @Override public MutableComponent getTooltip() { - String durationDescription = StringUtil.formatTickDuration(duration * 20); + String durationDescription = StringUtil.formatTickDuration(duration * 20, 20f); String targetDescription = eventListener.getTarget().name().toLowerCase(); String bonusDescription = getDescriptionId() + "." + targetDescription; if (chance < 1) { @@ -86,7 +86,7 @@ public MutableComponent getTooltip() { if (chance < 1) { tooltip = TooltipHelper.getSkillBonusTooltip( - tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } tooltip = eventListener.getTooltip(tooltip); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/ItemDurabilityLossAvoidanceBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/ItemDurabilityLossAvoidanceBonus.java index a33b69e50..09d489ec3 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/ItemDurabilityLossAvoidanceBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/ItemDurabilityLossAvoidanceBonus.java @@ -92,7 +92,7 @@ public MutableComponent getTooltip() { tooltip = Component.translatable(getDescriptionId() + ".chance", itemStackPredicate.getTooltip()); tooltip = TooltipHelper.getSkillBonusTooltip( - tooltip, chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } else { tooltip = Component.translatable(getDescriptionId(), itemStackPredicate.getTooltip()); } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/JumpHeightBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/JumpHeightBonus.java index d40f0968c..ee34862b2 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/JumpHeightBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/JumpHeightBonus.java @@ -71,7 +71,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { MutableComponent tooltip = TooltipHelper.getSkillBonusTooltip( - getDescriptionId(), multiplier, AttributeModifier.Operation.MULTIPLY_BASE); + getDescriptionId(), multiplier, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); tooltip = playerCondition.getTooltip(tooltip, Target.PLAYER); return tooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/LootDuplicationBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/LootDuplicationBonus.java index 7c8d9ffde..794ca0ecb 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/LootDuplicationBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/LootDuplicationBonus.java @@ -17,7 +17,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemAttributeModifiers; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParam; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; @@ -79,13 +79,13 @@ else if (multiplier == 2) { multiplierDescription = Component.translatable(descriptionId + ".triple"); } else { - String formattedMultiplier = ItemStack.ATTRIBUTE_MODIFIER_FORMAT.format(multiplier * 100); + String formattedMultiplier = ItemAttributeModifiers.ATTRIBUTE_MODIFIER_FORMAT.format(multiplier * 100); multiplierDescription = Component.translatable(descriptionId + ".multiplier", formattedMultiplier); } MutableComponent bonusDescription; if (chance < 1) { bonusDescription = Component.translatable(descriptionId, multiplierDescription, lootDescription); - bonusDescription = TooltipHelper.getSkillBonusTooltip(bonusDescription, chance, AttributeModifier.Operation.MULTIPLY_BASE); + bonusDescription = TooltipHelper.getSkillBonusTooltip(bonusDescription, chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } else { bonusDescription = Component.translatable(descriptionId + ".guaranteed", multiplierDescription, lootDescription); @@ -196,7 +196,7 @@ public boolean canAffect(LootContext lootContext) { public LootContextParam getPlayerLootContextParam() { return switch (this) { - case MOBS, FISHING -> LootContextParams.KILLER_ENTITY; + case MOBS, FISHING -> LootContextParams.ATTACKING_ENTITY; case GEMS, CHESTS, ORE, ARCHAEOLOGY -> LootContextParams.THIS_ENTITY; }; } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileDuplicationBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileDuplicationBonus.java index d07d788e0..b88d919f9 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileDuplicationBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileDuplicationBonus.java @@ -82,7 +82,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { MutableComponent tooltip; if (chance < 1f || chance % 1 != 0) { - tooltip = TooltipHelper.getSkillBonusTooltip(getDescriptionId() + ".chance", chance, AttributeModifier.Operation.MULTIPLY_BASE); + tooltip = TooltipHelper.getSkillBonusTooltip(getDescriptionId() + ".chance", chance, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); } else if (chance == 1f) { tooltip = Component.translatable(getDescriptionId()); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileSpeedBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileSpeedBonus.java index 520179148..2e2fc5a35 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileSpeedBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/ProjectileSpeedBonus.java @@ -76,7 +76,7 @@ public SkillBonus merge(SkillBonus other) { public MutableComponent getTooltip() { MutableComponent bonusTooltip = TooltipHelper.getSkillBonusTooltip( - getDescriptionId(), multiplier, AttributeModifier.Operation.MULTIPLY_BASE); + getDescriptionId(), multiplier, AttributeModifier.Operation.ADD_MULTIPLIED_BASE); bonusTooltip = playerCondition.getTooltip(bonusTooltip, Target.PLAYER); bonusTooltip = playerMultiplier.getTooltip(bonusTooltip, Target.PLAYER); return bonusTooltip.withStyle(TooltipHelper.getSkillBonusStyle(isPositive())); diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/RecipeUnlockBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/RecipeUnlockBonus.java index dcd770613..b088146c1 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/RecipeUnlockBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/RecipeUnlockBonus.java @@ -20,7 +20,7 @@ import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeManager; public class RecipeUnlockBonus implements SkillBonus { @@ -79,8 +79,8 @@ public void addEditorWidgets( Objects.requireNonNull(clientLevel); RecipeManager recipesManager = clientLevel.getRecipeManager(); List artisanRecipes = - recipesManager.getAllRecipesFor(PSTRecipeTypes.WORKBENCH).stream() - .map(Recipe::getId) + recipesManager.getAllRecipesFor(PSTRecipeTypes.WORKBENCH.get()).stream() + .map(RecipeHolder::id) .toList(); editor .addSelectionMenu(0, 0, 200, artisanRecipes) @@ -121,7 +121,7 @@ public int hashCode() { public static class Serializer implements SkillBonus.Serializer { @Override public RecipeUnlockBonus deserialize(JsonObject json) throws JsonParseException { - ResourceLocation recipeId = new ResourceLocation(json.get("recipe_id").getAsString()); + ResourceLocation recipeId = ResourceLocation.parse(json.get("recipe_id").getAsString()); return new RecipeUnlockBonus(recipeId); } @@ -135,7 +135,7 @@ public void serialize(JsonObject json, SkillBonus bonus) { @Override public RecipeUnlockBonus deserialize(CompoundTag tag) { - ResourceLocation recipeId = new ResourceLocation(tag.getString("recipe_id")); + ResourceLocation recipeId = ResourceLocation.parse(tag.getString("recipe_id")); return new RecipeUnlockBonus(recipeId); } @@ -151,7 +151,7 @@ public CompoundTag serialize(SkillBonus bonus) { @Override public RecipeUnlockBonus deserialize(FriendlyByteBuf buf) { - ResourceLocation recipeId = new ResourceLocation(buf.readUtf()); + ResourceLocation recipeId = ResourceLocation.parse(buf.readUtf()); return new RecipeUnlockBonus(recipeId); } @@ -165,7 +165,7 @@ public void serialize(FriendlyByteBuf buf, SkillBonus bonus) { @Override public SkillBonus createDefaultInstance() { - return new RecipeUnlockBonus(new ResourceLocation("unknown_recipe")); + return new RecipeUnlockBonus(ResourceLocation.parse("unknown_recipe")); } } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/player/RepairEfficiencyBonus.java b/src/main/java/daripher/skilltree/skill/bonus/player/RepairEfficiencyBonus.java index e56e371a3..b1a067816 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/player/RepairEfficiencyBonus.java +++ b/src/main/java/daripher/skilltree/skill/bonus/player/RepairEfficiencyBonus.java @@ -60,7 +60,7 @@ public SkillBonus merge(SkillBonus other) { @Override public MutableComponent getTooltip() { Component itemDescription = itemStackPredicate.getTooltip("plural.type"); - AttributeModifier.Operation operation = AttributeModifier.Operation.MULTIPLY_BASE; + AttributeModifier.Operation operation = AttributeModifier.Operation.ADD_MULTIPLIED_BASE; Component bonusDescription = Component.translatable(getDescriptionId() + ".bonus"); bonusDescription = TooltipHelper.getSkillBonusTooltip(bonusDescription, multiplier, operation) diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/ArmorEnchantmentCondition.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/ArmorEnchantmentCondition.java index 574dea48d..c0579b556 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/ArmorEnchantmentCondition.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/ArmorEnchantmentCondition.java @@ -6,7 +6,7 @@ import java.util.Objects; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.item.enchantment.EnchantmentCategory; +import daripher.skilltree.enchantment.EnchantmentCategory; public class ArmorEnchantmentCondition implements EnchantmentCondition { @Override diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/EnchantmentCondition.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/EnchantmentCondition.java index dd743f941..181e1066a 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/EnchantmentCondition.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/EnchantmentCondition.java @@ -3,7 +3,7 @@ import daripher.skilltree.init.PSTRegistries; import java.util.Objects; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.enchantment.EnchantmentCategory; +import daripher.skilltree.enchantment.EnchantmentCategory; public interface EnchantmentCondition { boolean met(EnchantmentCategory category); diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/NoneEnchantmentCondition.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/NoneEnchantmentCondition.java index 6b82d84f1..aa5eeedcd 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/NoneEnchantmentCondition.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/NoneEnchantmentCondition.java @@ -5,7 +5,7 @@ import daripher.skilltree.init.PSTEnchantmentConditions; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.item.enchantment.EnchantmentCategory; +import daripher.skilltree.enchantment.EnchantmentCategory; public enum NoneEnchantmentCondition implements EnchantmentCondition { INSTANCE; diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/WeaponEnchantmentCondition.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/WeaponEnchantmentCondition.java index aa5b95abe..f1472537b 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/WeaponEnchantmentCondition.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/enchantment/WeaponEnchantmentCondition.java @@ -6,7 +6,7 @@ import java.util.Objects; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.item.enchantment.EnchantmentCategory; +import daripher.skilltree.enchantment.EnchantmentCategory; public class WeaponEnchantmentCondition implements EnchantmentCondition { @Override diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EnchantedStackPredicate.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EnchantedStackPredicate.java index 22fe8d17a..1ab74fbde 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EnchantedStackPredicate.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EnchantedStackPredicate.java @@ -25,7 +25,7 @@ public EnchantedStackPredicate(ItemStackPredicate itemStackPredicate) { @Override public boolean test(ItemStack stack) { - return !EnchantmentHelper.getEnchantments(stack).isEmpty() && itemStackPredicate.test(stack); + return !stack.getEnchantments().isEmpty() && itemStackPredicate.test(stack); } @Override diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EquipmentPredicate.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EquipmentPredicate.java index e47b769de..3ffec5bfb 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EquipmentPredicate.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/EquipmentPredicate.java @@ -16,8 +16,8 @@ import net.minecraft.tags.ItemTags; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.item.*; -import net.minecraftforge.common.Tags; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.Tags; +import daripher.skilltree.util.ForgeRegistries; public class EquipmentPredicate implements ItemStackPredicate { public Type type; @@ -66,13 +66,13 @@ public static boolean isMeleeWeapon(ItemStack stack) { public static boolean isLeggings(ItemStack stack) { return stack.getItem() instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.LEGS - || stack.is(Tags.Items.ARMORS_LEGGINGS); + || stack.is(ItemTags.LEG_ARMOR); } public static boolean isTrident(ItemStack stack) { ResourceLocation id = ForgeRegistries.ITEMS.getKey(stack.getItem()); if (Objects.requireNonNull(id).toString().equals("tetra:modular_single")) return true; - return stack.getItem() instanceof TridentItem || stack.is(Tags.Items.TOOLS_TRIDENTS); + return stack.getItem() instanceof TridentItem || stack.is(Tags.Items.TOOLS_SPEAR); } public static boolean isPickaxe(ItemStack stack) { @@ -82,7 +82,7 @@ public static boolean isPickaxe(ItemStack stack) { public static boolean isCrossbow(ItemStack stack) { ResourceLocation id = ForgeRegistries.ITEMS.getKey(stack.getItem()); if (Objects.requireNonNull(id).toString().equals("tetra:modular_crossbow")) return true; - return stack.getItem() instanceof CrossbowItem || stack.is(Tags.Items.TOOLS_CROSSBOWS); + return stack.getItem() instanceof CrossbowItem || stack.is(Tags.Items.TOOLS_CROSSBOW); } public static boolean isWeapon(ItemStack stack) { @@ -96,7 +96,7 @@ public static boolean isPotion(ItemStack stack) { public static boolean isChestplate(ItemStack stack) { return stack.getItem() instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.CHEST - || stack.is(Tags.Items.ARMORS_CHESTPLATES); + || stack.is(ItemTags.CHEST_ARMOR); } public static boolean isShovel(ItemStack stack) { @@ -106,13 +106,13 @@ public static boolean isShovel(ItemStack stack) { public static boolean isShield(ItemStack stack) { ResourceLocation id = ForgeRegistries.ITEMS.getKey(stack.getItem()); if (Objects.requireNonNull(id).toString().equals("tetra:modular_shield")) return true; - return stack.getItem() instanceof ShieldItem || stack.is(Tags.Items.TOOLS_SHIELDS); + return stack.getItem() instanceof ShieldItem || stack.is(Tags.Items.TOOLS_SHIELD); } public static boolean isHelmet(ItemStack stack) { return stack.getItem() instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.HEAD - || stack.is(Tags.Items.ARMORS_HELMETS); + || stack.is(ItemTags.HEAD_ARMOR); } public static boolean isSword(ItemStack stack) { @@ -132,13 +132,13 @@ public static boolean isHoe(ItemStack stack) { public static boolean isBow(ItemStack stack) { ResourceLocation id = ForgeRegistries.ITEMS.getKey(stack.getItem()); if (Objects.requireNonNull(id).toString().equals("tetra:modular_bow")) return true; - return stack.getItem() instanceof BowItem || stack.is(Tags.Items.TOOLS_BOWS); + return stack.getItem() instanceof BowItem || stack.is(Tags.Items.TOOLS_BOW); } public static boolean isBoots(ItemStack stack) { return stack.getItem() instanceof ArmorItem armor && armor.getEquipmentSlot() == EquipmentSlot.FEET - || stack.is(Tags.Items.ARMORS_BOOTS); + || stack.is(ItemTags.FOOT_ARMOR); } public static boolean isAxe(ItemStack stack) { diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemIdPredicate.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemIdPredicate.java index 7a1d6716e..cc030a22b 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemIdPredicate.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemIdPredicate.java @@ -13,7 +13,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.registries.ForgeRegistries; +import daripher.skilltree.util.ForgeRegistries; public final class ItemIdPredicate implements ItemStackPredicate { private ResourceLocation id; @@ -66,13 +66,13 @@ public void addEditorWidgets(SkillTreeEditor editor, Consumer consumer, String text) { - setId(new ResourceLocation(text)); + setId(ResourceLocation.parse(text)); consumer.accept(this); } private static boolean isItemId(String text) { - if (!ResourceLocation.isValidResourceLocation(text)) return false; - return ForgeRegistries.ITEMS.containsKey(new ResourceLocation(text)); + if (ResourceLocation.tryParse(text) == null) return false; + return ForgeRegistries.ITEMS.containsKey(ResourceLocation.parse(text)); } public void setId(ResourceLocation id) { @@ -82,7 +82,7 @@ public void setId(ResourceLocation id) { public static class Serializer implements ItemStackPredicate.Serializer { @Override public ItemStackPredicate deserialize(JsonObject json) throws JsonParseException { - ResourceLocation id = new ResourceLocation(json.get("id").getAsString()); + ResourceLocation id = ResourceLocation.parse(json.get("id").getAsString()); return new ItemIdPredicate(id); } @@ -98,7 +98,7 @@ public void serialize(JsonObject json, ItemStackPredicate condition) { public ItemStackPredicate deserialize(CompoundTag tag) { Tag idTag = tag.get("id"); Objects.requireNonNull(idTag); - ResourceLocation id = new ResourceLocation(idTag.getAsString()); + ResourceLocation id = ResourceLocation.parse(idTag.getAsString()); return new ItemIdPredicate(id); } @@ -114,7 +114,7 @@ public CompoundTag serialize(ItemStackPredicate condition) { @Override public ItemStackPredicate deserialize(FriendlyByteBuf buf) { - return new ItemIdPredicate(new ResourceLocation(buf.readUtf())); + return new ItemIdPredicate(ResourceLocation.parse(buf.readUtf())); } @Override @@ -127,7 +127,7 @@ public void serialize(FriendlyByteBuf buf, ItemStackPredicate condition) { @Override public ItemStackPredicate createDefaultInstance() { - return new ItemIdPredicate(new ResourceLocation("minecraft:shield")); + return new ItemIdPredicate(ResourceLocation.parse("minecraft:shield")); } } } diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemTagPredicate.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemTagPredicate.java index 62717a5e0..d37c472e0 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemTagPredicate.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/ItemTagPredicate.java @@ -12,7 +12,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.ItemTags; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; public class ItemTagPredicate implements ItemStackPredicate { private ResourceLocation tagId; @@ -55,13 +55,13 @@ public void addEditorWidgets(SkillTreeEditor editor, Consumer ResourceLocation.tryParse(text) != null) .setResponder(text -> selectTagId(consumer, text)); editor.increaseHeight(19); } private void selectTagId(Consumer consumer, String text) { - setTagId(new ResourceLocation(text)); + setTagId(ResourceLocation.parse(text)); consumer.accept(this); } @@ -72,7 +72,7 @@ public void setTagId(ResourceLocation tagId) { public static class Serializer implements ItemStackPredicate.Serializer { @Override public ItemStackPredicate deserialize(JsonObject json) throws JsonParseException { - ResourceLocation tagId = new ResourceLocation(json.get("tag_id").getAsString()); + ResourceLocation tagId = ResourceLocation.parse(json.get("tag_id").getAsString()); return new ItemTagPredicate(tagId); } @@ -86,7 +86,7 @@ public void serialize(JsonObject json, ItemStackPredicate condition) { @Override public ItemStackPredicate deserialize(CompoundTag tag) { - ResourceLocation tagId = new ResourceLocation(tag.getString("tag_id")); + ResourceLocation tagId = ResourceLocation.parse(tag.getString("tag_id")); return new ItemTagPredicate(tagId); } @@ -102,7 +102,7 @@ public CompoundTag serialize(ItemStackPredicate condition) { @Override public ItemStackPredicate deserialize(FriendlyByteBuf buf) { - ResourceLocation tagId = new ResourceLocation(buf.readUtf()); + ResourceLocation tagId = ResourceLocation.parse(buf.readUtf()); return new ItemTagPredicate(tagId); } diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/PotionStackPredicate.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/PotionStackPredicate.java index 957a3ef23..f4f1eb6cb 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/item/PotionStackPredicate.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/item/PotionStackPredicate.java @@ -8,7 +8,9 @@ import daripher.skilltree.network.NetworkHelper; import java.util.Objects; import java.util.function.Consumer; +import java.util.stream.StreamSupport; import net.minecraft.ChatFormatting; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; @@ -16,7 +18,7 @@ import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.PotionItem; -import net.minecraft.world.item.alchemy.PotionUtils; +import net.minecraft.world.item.alchemy.PotionContents; public final class PotionStackPredicate implements ItemStackPredicate { private Type type; @@ -37,9 +39,11 @@ public boolean test(ItemStack stack) { } private boolean hasEffects(ItemStack stack, MobEffectCategory category) { - return PotionUtils.getAllEffects(stack.getOrCreateTag()).stream() + PotionContents contents = + stack.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY); + return StreamSupport.stream(contents.getAllEffects().spliterator(), false) .map(MobEffectInstance::getEffect) - .anyMatch(effect -> effect.getCategory() == category); + .anyMatch(effect -> effect.value().getCategory() == category); } @Override diff --git a/src/main/java/daripher/skilltree/skill/bonus/predicate/living/HasEffectEntityPredicate.java b/src/main/java/daripher/skilltree/skill/bonus/predicate/living/HasEffectEntityPredicate.java index 10bfecfba..c41fb5899 100644 --- a/src/main/java/daripher/skilltree/skill/bonus/predicate/living/HasEffectEntityPredicate.java +++ b/src/main/java/daripher/skilltree/skill/bonus/predicate/living/HasEffectEntityPredicate.java @@ -11,6 +11,8 @@ import daripher.skilltree.skill.bonus.SkillBonus; import net.minecraft.ChatFormatting; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; @@ -37,8 +39,9 @@ public HasEffectEntityPredicate(@Nonnull MobEffect effect, int amplifier) { @Override public boolean test(LivingEntity living) { - if (amplifier == 0) return living.hasEffect(this.effect); - MobEffectInstance effect = living.getEffect(this.effect); + Holder effectHolder = getEffectHolder(); + if (amplifier == 0) return living.hasEffect(effectHolder); + MobEffectInstance effect = living.getEffect(effectHolder); return effect != null && effect.getAmplifier() >= this.amplifier; } @@ -108,6 +111,10 @@ public void setAmplifier(int amplifier) { this.amplifier = amplifier; } + private Holder getEffectHolder() { + return BuiltInRegistries.MOB_EFFECT.wrapAsHolder(effect); + } + public static class Serializer implements LivingEntityPredicate.Serializer { @Override public LivingEntityPredicate deserialize(JsonObject json) throws JsonParseException { @@ -163,7 +170,7 @@ public void serialize(FriendlyByteBuf buf, LivingEntityPredicate condition) { @Override public LivingEntityPredicate createDefaultInstance() { - return new HasEffectEntityPredicate(MobEffects.POISON); + return new HasEffectEntityPredicate(MobEffects.POISON.value()); } } } diff --git a/src/main/java/daripher/skilltree/skill/requirement/AdvancementRequirement.java b/src/main/java/daripher/skilltree/skill/requirement/AdvancementRequirement.java index c2182c294..5c46d42b8 100644 --- a/src/main/java/daripher/skilltree/skill/requirement/AdvancementRequirement.java +++ b/src/main/java/daripher/skilltree/skill/requirement/AdvancementRequirement.java @@ -9,7 +9,7 @@ import java.util.Objects; import java.util.function.Consumer; import net.minecraft.ChatFormatting; -import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.AdvancementProgress; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientAdvancements; @@ -39,7 +39,7 @@ public boolean test(Player player) { LocalPlayer localPlayer = (LocalPlayer) player; ClientAdvancements advancements = localPlayer.connection.getAdvancements(); ClientAdvancementsAccessor advancementsAccessor = (ClientAdvancementsAccessor) advancements; - Advancement advancement = advancements.getAdvancements().get(advancementId); + AdvancementHolder advancement = advancements.get(advancementId); AdvancementProgress progress = advancementsAccessor.getProgress().get(advancement); if (progress == null) { return false; @@ -53,7 +53,7 @@ public boolean test(Player player) { } ServerAdvancementManager advancementManager = server.getAdvancements(); PlayerAdvancements advancements = serverPlayer.getAdvancements(); - Advancement advancement = advancementManager.getAdvancement(advancementId); + AdvancementHolder advancement = advancementManager.get(advancementId); if (advancement == null) { return false; } @@ -78,8 +78,8 @@ public void addEditorWidgets(SkillTreeEditor editor, Consumer advancementIds = - advancements.getAdvancements().getAllAdvancements().stream() - .map(Advancement::getId) + advancements.getTree().nodes().stream() + .map(node -> node.holder().id()) .toList(); editor .addSelectionMenu(0, 0, 200, advancementIds) @@ -128,7 +128,7 @@ public SkillRequirement.Serializer getSerializer() { public static class Serializer implements SkillRequirement.Serializer { @Override public SkillRequirement deserialize(JsonObject json) throws JsonParseException { - ResourceLocation id = new ResourceLocation(json.get("advancement").getAsString()); + ResourceLocation id = ResourceLocation.parse(json.get("advancement").getAsString()); return new AdvancementRequirement(id); } @@ -141,7 +141,7 @@ public void serialize(JsonObject json, SkillRequirement requirement) { @Override public SkillRequirement deserialize(CompoundTag tag) { - ResourceLocation id = new ResourceLocation(tag.getString("advancement")); + ResourceLocation id = ResourceLocation.parse(tag.getString("advancement")); return new AdvancementRequirement(id); } @@ -156,7 +156,7 @@ public CompoundTag serialize(SkillRequirement requirement) { @Override public SkillRequirement deserialize(FriendlyByteBuf buf) { - ResourceLocation id = new ResourceLocation(buf.readUtf()); + ResourceLocation id = ResourceLocation.parse(buf.readUtf()); return new AdvancementRequirement(id); } @@ -170,7 +170,7 @@ public void serialize(FriendlyByteBuf buf, SkillRequirement requirement) { @Override public SkillRequirement createDefaultInstance() { return new AdvancementRequirement( - new ResourceLocation("minecraft:adventure/hero_of_the_village")); + ResourceLocation.parse("minecraft:adventure/hero_of_the_village")); } } } diff --git a/src/main/java/daripher/skilltree/skill/requirement/LearnedSkillRequirement.java b/src/main/java/daripher/skilltree/skill/requirement/LearnedSkillRequirement.java index e2557f84b..86784a0c0 100644 --- a/src/main/java/daripher/skilltree/skill/requirement/LearnedSkillRequirement.java +++ b/src/main/java/daripher/skilltree/skill/requirement/LearnedSkillRequirement.java @@ -95,7 +95,7 @@ public SkillRequirement.Serializer getSerializer() { public static class Serializer implements SkillRequirement.Serializer { @Override public SkillRequirement deserialize(JsonObject json) throws JsonParseException { - ResourceLocation id = new ResourceLocation(json.get("skill_id").getAsString()); + ResourceLocation id = ResourceLocation.parse(json.get("skill_id").getAsString()); return new LearnedSkillRequirement(id); } @@ -108,7 +108,7 @@ public void serialize(JsonObject json, SkillRequirement requirement) { @Override public SkillRequirement deserialize(CompoundTag tag) { - ResourceLocation id = new ResourceLocation(tag.getString("skill_id")); + ResourceLocation id = ResourceLocation.parse(tag.getString("skill_id")); return new LearnedSkillRequirement(id); } @@ -123,7 +123,7 @@ public CompoundTag serialize(SkillRequirement requirement) { @Override public SkillRequirement deserialize(FriendlyByteBuf buf) { - ResourceLocation id = new ResourceLocation(buf.readUtf()); + ResourceLocation id = ResourceLocation.parse(buf.readUtf()); return new LearnedSkillRequirement(id); } @@ -136,7 +136,7 @@ public void serialize(FriendlyByteBuf buf, SkillRequirement requirement) { @Override public SkillRequirement createDefaultInstance() { - return new LearnedSkillRequirement(new ResourceLocation("skilltree:hunter_1")); + return new LearnedSkillRequirement(ResourceLocation.parse("skilltree:hunter_1")); } } } diff --git a/src/main/java/daripher/skilltree/skill/requirement/StatRequirement.java b/src/main/java/daripher/skilltree/skill/requirement/StatRequirement.java index 4dc569d1e..3cfbc2d27 100644 --- a/src/main/java/daripher/skilltree/skill/requirement/StatRequirement.java +++ b/src/main/java/daripher/skilltree/skill/requirement/StatRequirement.java @@ -23,9 +23,9 @@ import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import daripher.skilltree.util.ForgeRegistries; public final class StatRequirement implements SkillRequirement { private ResourceLocation statTypeId; @@ -69,7 +69,7 @@ public MutableComponent getTooltip() { return Component.literal("Unknown entity: " + statId).withStyle(ChatFormatting.RED); } Component entityName = entityType.getDescription(); - return Component.translatable(statType.getTranslationKey(), minValue, entityName); + return Component.literal(statType.getDisplayName().getString() + " " + entityName.getString() + ": " + minValue); } if (statType == Stats.ENTITY_KILLED_BY) { EntityType entityType = ForgeRegistries.ENTITY_TYPES.getValue(statId); @@ -77,7 +77,7 @@ public MutableComponent getTooltip() { return Component.literal("Unknown entity: " + statId).withStyle(ChatFormatting.RED); } Component entityName = entityType.getDescription(); - return Component.translatable(statType.getTranslationKey(), entityName, minValue); + return Component.literal(statType.getDisplayName().getString() + " " + entityName.getString() + ": " + minValue); } else { Item item = ForgeRegistries.ITEMS.getValue(statId); if (item == null) { @@ -216,8 +216,8 @@ public SkillRequirement.Serializer getSerializer() { public static class Serializer implements SkillRequirement.Serializer { @Override public SkillRequirement deserialize(JsonObject json) throws JsonParseException { - ResourceLocation statTypeId = new ResourceLocation(json.get("statTypeId").getAsString()); - ResourceLocation statId = new ResourceLocation(json.get("statId").getAsString()); + ResourceLocation statTypeId = ResourceLocation.parse(json.get("statTypeId").getAsString()); + ResourceLocation statId = ResourceLocation.parse(json.get("statId").getAsString()); int minValue = json.get("minValue").getAsInt(); return new StatRequirement(statTypeId, statId, minValue); } @@ -233,8 +233,8 @@ public void serialize(JsonObject json, SkillRequirement requirement) { @Override public SkillRequirement deserialize(CompoundTag tag) { - ResourceLocation statTypeId = new ResourceLocation(tag.getString("statTypeId")); - ResourceLocation statId = new ResourceLocation(tag.getString("statId")); + ResourceLocation statTypeId = ResourceLocation.parse(tag.getString("statTypeId")); + ResourceLocation statId = ResourceLocation.parse(tag.getString("statId")); int minValue = tag.getInt("minValue"); return new StatRequirement(statTypeId, statId, minValue); } @@ -252,8 +252,8 @@ public CompoundTag serialize(SkillRequirement requirement) { @Override public SkillRequirement deserialize(FriendlyByteBuf buf) { - ResourceLocation statTypeId = new ResourceLocation(buf.readUtf()); - ResourceLocation statId = new ResourceLocation(buf.readUtf()); + ResourceLocation statTypeId = ResourceLocation.parse(buf.readUtf()); + ResourceLocation statId = ResourceLocation.parse(buf.readUtf()); int minValue = buf.readInt(); return new StatRequirement(statTypeId, statId, minValue); } diff --git a/src/main/java/daripher/skilltree/util/ForgeRegistries.java b/src/main/java/daripher/skilltree/util/ForgeRegistries.java new file mode 100644 index 000000000..8741d1f1f --- /dev/null +++ b/src/main/java/daripher/skilltree/util/ForgeRegistries.java @@ -0,0 +1,315 @@ +package daripher.skilltree.util; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; +import net.neoforged.neoforge.registries.callback.RegistryCallback; +import net.neoforged.neoforge.registries.datamaps.DataMapType; +import net.neoforged.neoforge.registries.IRegistryExtension; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.HolderOwner; +import net.minecraft.core.HolderSet; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistrationInfo; +import net.minecraft.core.registries.BuiltInRegistries; +import com.mojang.serialization.Lifecycle; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.stats.StatType; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.Attribute; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.alchemy.Potion; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.block.Block; + +public final class ForgeRegistries { + public static final ForgeRegistry ITEMS = new ForgeRegistry<>(BuiltInRegistries.ITEM); + public static final ForgeRegistry BLOCKS = new ForgeRegistry<>(BuiltInRegistries.BLOCK); + public static final ForgeRegistry MOB_EFFECTS = + new ForgeRegistry<>(BuiltInRegistries.MOB_EFFECT); + public static final ForgeRegistry POTIONS = new ForgeRegistry<>(BuiltInRegistries.POTION); + public static final ForgeRegistry> MENU_TYPES = + new ForgeRegistry<>(BuiltInRegistries.MENU); + public static final ForgeRegistry> RECIPE_SERIALIZERS = + new ForgeRegistry<>(BuiltInRegistries.RECIPE_SERIALIZER); + public static final ForgeRegistry> RECIPE_TYPES = + new ForgeRegistry<>(BuiltInRegistries.RECIPE_TYPE); + public static final ForgeRegistry ATTRIBUTES = + new ForgeRegistry<>(BuiltInRegistries.ATTRIBUTE); + public static final ForgeRegistry> ENTITY_TYPES = + new ForgeRegistry<>(BuiltInRegistries.ENTITY_TYPE); + public static final ForgeRegistry> STAT_TYPES = + new ForgeRegistry<>(BuiltInRegistries.STAT_TYPE); + + private ForgeRegistries() {} + + public static final class ForgeRegistry implements Registry { + private final Registry registry; + + public ForgeRegistry(Registry registry) { + this.registry = registry; + } + + public T getValue(ResourceLocation id) { + return registry.get(id); + } + + public Collection getValues() { + return registry.stream().toList(); + } + + public Set, T>> getEntries() { + return registry.entrySet(); + } + + public Set getKeys() { + return registry.keySet(); + } + + public T register(String id, T value) { + return Registry.register(registry, id, value); + } + + public T register(ResourceLocation id, T value) { + return Registry.register(registry, id, value); + } + + @Override + public ResourceKey> key() { + return registry.key(); + } + + private IRegistryExtension extension() { + return registry; + } + + @Override + public ResourceLocation getKey(T value) { + return registry.getKey(value); + } + + @Override + public Optional> getResourceKey(T value) { + return registry.getResourceKey(value); + } + + @Override + public int getId(T value) { + return registry.getId(value); + } + + @Override + public T byId(int id) { + return registry.byId(id); + } + + @Override + public int size() { + return registry.size(); + } + + @Override + public Iterator iterator() { + return registry.iterator(); + } + + @Override + public T get(ResourceKey key) { + return registry.get(key); + } + + @Override + public T get(ResourceLocation id) { + return registry.get(id); + } + + @Override + public Optional registrationInfo(ResourceKey key) { + return registry.registrationInfo(key); + } + + @Override + public Lifecycle registryLifecycle() { + return registry.registryLifecycle(); + } + + @Override + public Optional> getAny() { + return registry.getAny(); + } + + @Override + public Set keySet() { + return registry.keySet(); + } + + @Override + public Set, T>> entrySet() { + return registry.entrySet(); + } + + @Override + public Set> registryKeySet() { + return registry.registryKeySet(); + } + + @Override + public Optional> getRandom(net.minecraft.util.RandomSource random) { + return registry.getRandom(random); + } + + @Override + public boolean containsKey(ResourceLocation id) { + return registry.containsKey(id); + } + + @Override + public boolean containsKey(ResourceKey key) { + return registry.containsKey(key); + } + + @Override + public Registry freeze() { + return registry.freeze(); + } + + @Override + public Holder.Reference createIntrusiveHolder(T value) { + return registry.createIntrusiveHolder(value); + } + + @Override + public Optional> getHolder(int id) { + return registry.getHolder(id); + } + + @Override + public Optional> getHolder(ResourceLocation id) { + return registry.getHolder(id); + } + + @Override + public Optional> getHolder(ResourceKey key) { + return registry.getHolder(key); + } + + @Override + public Holder wrapAsHolder(T value) { + return registry.wrapAsHolder(value); + } + + @Override + public Stream> holders() { + return registry.holders(); + } + + @Override + public Optional> getTag(net.minecraft.tags.TagKey tag) { + return registry.getTag(tag); + } + + @Override + public HolderSet.Named getOrCreateTag(net.minecraft.tags.TagKey tag) { + return registry.getOrCreateTag(tag); + } + + @Override + public Stream, HolderSet.Named>> + getTags() { + return registry.getTags(); + } + + @Override + public Stream> getTagNames() { + return registry.getTagNames(); + } + + @Override + public void resetTags() { + registry.resetTags(); + } + + @Override + public void bindTags(Map, java.util.List>> tags) { + registry.bindTags(tags); + } + + @Override + public HolderOwner holderOwner() { + return registry.holderOwner(); + } + + @Override + public HolderLookup.RegistryLookup asLookup() { + return registry.asLookup(); + } + + @Override + public HolderLookup.RegistryLookup asTagAddingLookup() { + return registry.asTagAddingLookup(); + } + + @Override + public boolean doesSync() { + return extension().doesSync(); + } + + @Override + public int getMaxId() { + return extension().getMaxId(); + } + + @Override + public void addCallback(RegistryCallback callback) { + extension().addCallback(callback); + } + + @Override + public void addAlias(ResourceLocation from, ResourceLocation to) { + extension().addAlias(from, to); + } + + @Override + public ResourceLocation resolve(ResourceLocation id) { + return extension().resolve(id); + } + + @Override + public ResourceKey resolve(ResourceKey key) { + return extension().resolve(key); + } + + @Override + public int getId(ResourceKey key) { + return extension().getId(key); + } + + @Override + public int getId(ResourceLocation id) { + return extension().getId(id); + } + + @Override + public boolean containsValue(T value) { + return extension().containsValue(value); + } + + @Override + public A getData(DataMapType type, ResourceKey key) { + return extension().getData(type, key); + } + + @Override + public Map, A> getDataMap(DataMapType type) { + return extension().getDataMap(type); + } + } +} diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml deleted file mode 100644 index e2aade41a..000000000 --- a/src/main/resources/META-INF/mods.toml +++ /dev/null @@ -1,38 +0,0 @@ -modLoader="javafml" -loaderVersion="${loader_version_range}" -license="${mod_license}" - -[[mods]] - modId="${mod_id}" - version="${mod_version}" - displayName="${mod_name}" - authors="${mod_authors}" - description='''${mod_description}''' - -[[dependencies.${mod_id}]] - modId="forge" - mandatory=true - versionRange="${forge_version_range}" - ordering="NONE" - side="BOTH" - -[[dependencies.${mod_id}]] - modId="minecraft" - mandatory=true - versionRange="${minecraft_version_range}" - ordering="NONE" - side="BOTH" - -[[dependencies.${mod_id}]] - modId="attributefix" - mandatory=true - versionRange="[21.0.1,)" - ordering="NONE" - side="BOTH" - -[[dependencies.${mod_id}]] - modId="curios" - mandatory=false - versionRange="[5.3.1+1.20.1,)" - ordering="AFTER" - side="BOTH" \ No newline at end of file diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 000000000..b246b4081 --- /dev/null +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,41 @@ +modLoader="javafml" +loaderVersion="${loader_version_range}" +license="${mod_license}" + +[[mods]] +modId="${mod_id}" +version="${mod_version}" +displayName="${mod_name}" +authors="${mod_authors}" +description='''${mod_description}''' + +[[mixins]] +config="${mod_id}.mixins.json" + +[[dependencies.${mod_id}]] +modId="neoforge" +mandatory=true +versionRange="[${neo_version},)" +ordering="NONE" +side="BOTH" + +[[dependencies.${mod_id}]] +modId="minecraft" +mandatory=true +versionRange="${minecraft_version_range}" +ordering="NONE" +side="BOTH" + +[[dependencies.${mod_id}]] +modId="attributefix" +mandatory=true +versionRange="[21.1.1,)" +ordering="NONE" +side="BOTH" + +[[dependencies.${mod_id}]] +modId="curios" +mandatory=false +versionRange="[9.4.2+1.21.1,)" +ordering="AFTER" +side="BOTH" diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta index eca79ae4a..b90fdd4df 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -3,6 +3,6 @@ "description": { "text": "${mod_id} resources" }, - "pack_format": 15 + "pack_format": 34 } -} \ No newline at end of file +} diff --git a/src/main/resources/skilltree.mixins.json b/src/main/resources/skilltree.mixins.json index 6b09254ec..e19df4ce6 100644 --- a/src/main/resources/skilltree.mixins.json +++ b/src/main/resources/skilltree.mixins.json @@ -1,7 +1,7 @@ { "required": true, "minVersion": "0.8", - "compatibilityLevel": "JAVA_17", + "compatibilityLevel": "JAVA_21", "package": "daripher.skilltree.mixin", "mixins": [ "minecraft/PlayerMixin", @@ -15,10 +15,11 @@ ], "client": [ "EditBoxAccessor", - "ClientAdvancementsAccessor" + "ClientAdvancementsAccessor", + "minecraft/ClientPacketListenerMixin" ], "injectors": { "defaultRequire": 1 }, "refmap": "skilltree.refmap.json" -} \ No newline at end of file +}