diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5ed4f50..6b0acc7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,22 +1,38 @@ name: Build -on: [push] +on: [ push, workflow_dispatch ] jobs: build: + strategy: + matrix: + java: [ 21 ] + os: [ ubuntu-latest ] + runs-on: ${{ matrix.os }} - runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 - container: - image: openjdk:17-jdk - options: --user root + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 - steps: - - uses: actions/checkout@v2.2.0 - - run: | - chmod +x ./gradlew - ./gradlew build - - uses: actions/upload-artifact@v2 - with: - name: build-artifacts - path: build/libs/ \ No newline at end of file + - name: Setup JDK ${{ matrix.java }} + uses: actions/setup-java@v3 + with: + distribution: zulu + java-version: ${{ matrix.java }} + + - name: Make Gradle wrapper executable + run: chmod +x ./gradlew + + - name: Build + run: ./gradlew build --stacktrace --parallel + + - name: Capture build artifacts + uses: actions/upload-artifact@v3 + with: + name: Artifacts + path: build/libs/ \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 10a7ebb..cc14200 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,24 +1,39 @@ name: Release -on: [workflow_dispatch] +on: [ workflow_dispatch ] jobs: release: + strategy: + matrix: + java: [ 21 ] + os: [ ubuntu-latest ] - runs-on: ubuntu-latest - - container: - image: openjdk:17-jdk - options: --user root + runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v2.2.0 - - run: | - chmod +x ./gradlew - ./gradlew build publish github curseforge modrinth --stacktrace - env: - CURSEFORGE_API_KEY: ${{ secrets.CURSEFORGE_API_KEY }} - GITHUB_TOKEN: ${{ secrets.GH_API_KEY }} - MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} - MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} - MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} \ No newline at end of file + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup JDK ${{ matrix.java }} + uses: actions/setup-java@v3 + with: + distribution: zulu + java-version: ${{ matrix.java }} + + - name: Make Gradle wrapper executable + run: chmod +x ./gradlew + + - name: Build + run: ./gradlew build publish github curseforge modrinth --stacktrace + env: + CURSEFORGE_API_KEY: ${{ secrets.CURSEFORGE_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GH_API_KEY }} + MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} + MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 41e16fa..fe8a9cc 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -211,5 +211,12 @@ publishing { } + } +} + +idea { + module { + isDownloadSources = true + isDownloadJavadoc = true } } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index d3140d1..19deaea 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,7 +2,7 @@ org.gradle.jvmargs=-Xmx4G # Gradle Plugins -loom_version=1.1-SNAPSHOT +loom_version=1.7-SNAPSHOT grgit_version=5.0.0 cursegradle_version=1.4.0 modrinth_version=2.7.3 @@ -13,16 +13,16 @@ mod_version=2.3+1.20 maven_group=io.github.lucaargolo # Fabric Properties -minecraft_version=1.20.1 -yarn_mappings=1.20.1+build.10 -loader_version=0.14.22 +minecraft_version=1.21 +yarn_mappings=1.21+build.9 +loader_version=0.15.11 #Fabric api -fabric_version=0.86.1+1.20.1 +fabric_version=0.100.7+1.21 #Libraries -modmenu_version=7.2.1 -rei_version=12.0.645 +modmenu_version=11.0.1 +rei_version=16.0.729 #Publishing curseforge_id=413523 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e750102..0d18421 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/java/io/github/lucaargolo/seasons/FabricSeasons.java b/src/main/java/io/github/lucaargolo/seasons/FabricSeasons.java index 54de714..b449a37 100644 --- a/src/main/java/io/github/lucaargolo/seasons/FabricSeasons.java +++ b/src/main/java/io/github/lucaargolo/seasons/FabricSeasons.java @@ -5,8 +5,15 @@ import com.google.gson.JsonParser; import io.github.lucaargolo.seasons.commands.SeasonCommand; import io.github.lucaargolo.seasons.mixed.BiomeMixed; +import io.github.lucaargolo.seasons.payload.ConfigSyncPacket; +import io.github.lucaargolo.seasons.payload.UpdateCropsPaycket; import io.github.lucaargolo.seasons.resources.CropConfigs; -import io.github.lucaargolo.seasons.utils.*; +import io.github.lucaargolo.seasons.utils.GreenhouseCache; +import io.github.lucaargolo.seasons.utils.ModConfig; +import io.github.lucaargolo.seasons.utils.PlacedMeltablesState; +import io.github.lucaargolo.seasons.utils.ReplacedMeltablesState; +import io.github.lucaargolo.seasons.utils.Season; +import io.github.lucaargolo.seasons.utils.SeasonalFertilizable; import it.unimi.dsi.fastutil.longs.LongArraySet; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -14,7 +21,7 @@ import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; -import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; +import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.loader.api.FabricLoader; @@ -23,7 +30,6 @@ import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; -import net.minecraft.network.PacketByteBuf; import net.minecraft.registry.Registries; import net.minecraft.registry.RegistryKey; import net.minecraft.registry.RegistryKeys; @@ -62,62 +68,53 @@ public class FabricSeasons implements ModInitializer { public static HashMap SEEDS_MAP = new HashMap<>(); - public static Identifier ASK_FOR_CONFIG = new ModIdentifier("ask_for_config"); - public static Identifier ANSWER_CONFIG = new ModIdentifier("anwer_config"); - - public static Identifier UPDATE_CROPS = new ModIdentifier("update_crops"); - - @Override public void onInitialize() { - Path configPath = FabricLoader.getInstance().getConfigDir(); File configFile = new File(configPath + File.separator + "seasons.json"); - - LOGGER.info("["+MOD_NAME+"] Trying to read config file..."); + + LOGGER.info("[" + MOD_NAME + "] Trying to read config file..."); try { if (configFile.createNewFile()) { - LOGGER.info("["+MOD_NAME+"] No config file found, creating a new one..."); + LOGGER.info("[" + MOD_NAME + "] No config file found, creating a new one..."); String json = GSON.toJson(JsonParser.parseString(GSON.toJson(new ModConfig()))); try (PrintWriter out = new PrintWriter(configFile)) { out.println(json); } CONFIG = new ModConfig(); - LOGGER.info("["+MOD_NAME+"] Successfully created default config file."); + LOGGER.info("[" + MOD_NAME + "] Successfully created default config file."); } else { - LOGGER.info("["+MOD_NAME+"] A config file was found, loading it.."); + LOGGER.info("[" + MOD_NAME + "] A config file was found, loading it.."); CONFIG = GSON.fromJson(new String(Files.readAllBytes(configFile.toPath())), ModConfig.class); - if(CONFIG == null) { - throw new NullPointerException("["+MOD_NAME+"] The config file was empty."); - }else{ - LOGGER.info("["+MOD_NAME+"] Successfully loaded config file."); + if (CONFIG == null) { + throw new NullPointerException("[" + MOD_NAME + "] The config file was empty."); + } else { + LOGGER.info("[" + MOD_NAME + "] Successfully loaded config file."); } } - }catch (Exception exception) { - LOGGER.error("["+MOD_NAME+"] There was an error creating/loading the config file!", exception); + } catch (Exception exception) { + LOGGER.error("[" + MOD_NAME + "] There was an error creating/loading the config file!", exception); CONFIG = new ModConfig(); - LOGGER.warn("["+MOD_NAME+"] Defaulting to original config."); + LOGGER.warn("[" + MOD_NAME + "] Defaulting to original config."); } - + CommandRegistrationCallback.EVENT.register((dispatcher, dedicated, ignored) -> SeasonCommand.register(dispatcher)); - + ServerLifecycleEvents.SERVER_STARTED.register(server -> { SEEDS_MAP.clear(); Registries.ITEM.forEach(item -> { - if(item instanceof BlockItem) { + if (item instanceof BlockItem) { Block block = ((BlockItem) item).getBlock(); - if(block instanceof SeasonalFertilizable) { + if (block instanceof SeasonalFertilizable) { FabricSeasons.SEEDS_MAP.put(item, ((BlockItem) item).getBlock()); } } }); }); - + + PayloadTypeRegistry.playS2C().register(UpdateCropsPaycket.ID, UpdateCropsPaycket.CODEC); ServerLifecycleEvents.SYNC_DATA_PACK_CONTENTS.register((player, joined) -> { - PacketByteBuf buf = PacketByteBufs.create(); - CropConfigs.getDefaultCropConfig().toBuf(buf); - CropConfigs.toBuf(buf); - ServerPlayNetworking.send(player, UPDATE_CROPS, buf); + ServerPlayNetworking.send(player, UpdateCropsPaycket.fromConfig(CropConfigs.getDefaultCropConfig(), CropConfigs.getCropConfigMap())); }); ServerTickEvents.END_SERVER_TICK.register(server -> { @@ -125,15 +122,20 @@ public void onInitialize() { temporaryMeltableCache.clear(); }); - ServerPlayNetworking.registerGlobalReceiver(ASK_FOR_CONFIG, (server, player, handler, buf, responseSender) -> { + PayloadTypeRegistry.playS2C().register(ConfigSyncPacket.ID, ConfigSyncPacket.CODEC); + PayloadTypeRegistry.playC2S().register(ConfigSyncPacket.ID, ConfigSyncPacket.CODEC); + + ServerPlayNetworking.registerGlobalReceiver(ConfigSyncPacket.ID, (payload, context) -> { String configJson = GSON.toJson(JsonParser.parseString(GSON.toJson(CONFIG))); - PacketByteBuf configBuf = PacketByteBufs.create(); - configBuf.writeString(configJson); - ServerPlayNetworking.send(player, ANSWER_CONFIG, configBuf); + ServerPlayNetworking.send(context.player(), new ConfigSyncPacket(configJson)); }); ResourceManagerHelper.get(ResourceType.SERVER_DATA).registerReloadListener(new CropConfigs()); } + + public static Identifier identifier(String path) { + return Identifier.of(MOD_ID, path); + } public static void setMeltable(BlockPos blockPos) { temporaryMeltableCache.add(blockPos.asLong()); @@ -144,11 +146,11 @@ public static boolean isMeltable(BlockPos blockPos) { } public static PlacedMeltablesState getPlacedMeltablesState(ServerWorld world) { - return world.getPersistentStateManager().getOrCreate(PlacedMeltablesState::createFromNbt, PlacedMeltablesState::new, "seasons_placed_meltables"); + return world.getPersistentStateManager().getOrCreate(PlacedMeltablesState.getPersistentStateType(), "seasons_placed_meltables"); } public static ReplacedMeltablesState getReplacedMeltablesState(ServerWorld world) { - return world.getPersistentStateManager().getOrCreate(ReplacedMeltablesState::createFromNbt, ReplacedMeltablesState::new, "seasons_replaced_meltables"); + return world.getPersistentStateManager().getOrCreate(ReplacedMeltablesState.getPersistentStateType(), "seasons_replaced_meltables"); } public static long getTimeToNextSeason(World world) { @@ -337,8 +339,8 @@ else if (m == 12 && d > 20) return season; } - private static final TagKey IGNORED_CATEGORIES_TAG = TagKey.of(RegistryKeys.BIOME, new Identifier(FabricSeasons.MOD_ID, "ignored")); - private static final TagKey JUNGLE_LIKE_TAG = TagKey.of(RegistryKeys.BIOME, new Identifier(FabricSeasons.MOD_ID, "jungle_like")); + private static final TagKey IGNORED_CATEGORIES_TAG = TagKey.of(RegistryKeys.BIOME, FabricSeasons.identifier("ignored")); + private static final TagKey JUNGLE_LIKE_TAG = TagKey.of(RegistryKeys.BIOME, FabricSeasons.identifier("jungle_like")); public static void injectBiomeTemperature(RegistryEntry entry, World world) { if(entry.isIn(IGNORED_CATEGORIES_TAG)) diff --git a/src/main/java/io/github/lucaargolo/seasons/FabricSeasonsClient.java b/src/main/java/io/github/lucaargolo/seasons/FabricSeasonsClient.java index 50225a1..36911f4 100644 --- a/src/main/java/io/github/lucaargolo/seasons/FabricSeasonsClient.java +++ b/src/main/java/io/github/lucaargolo/seasons/FabricSeasonsClient.java @@ -1,17 +1,22 @@ package io.github.lucaargolo.seasons; import io.github.lucaargolo.seasons.commands.SeasonDebugCommand; +import io.github.lucaargolo.seasons.payload.ConfigSyncPacket; +import io.github.lucaargolo.seasons.payload.UpdateCropsPaycket; import io.github.lucaargolo.seasons.resources.CropConfigs; import io.github.lucaargolo.seasons.resources.FoliageSeasonColors; import io.github.lucaargolo.seasons.resources.GrassSeasonColors; -import io.github.lucaargolo.seasons.utils.*; +import io.github.lucaargolo.seasons.utils.CompatWarnState; +import io.github.lucaargolo.seasons.utils.CropConfig; +import io.github.lucaargolo.seasons.utils.ModConfig; +import io.github.lucaargolo.seasons.utils.Season; +import io.github.lucaargolo.seasons.utils.SeasonalFertilizable; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; -import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.fabric.api.resource.ResourcePackActivationType; import net.fabricmc.loader.api.FabricLoader; @@ -29,7 +34,9 @@ import java.util.HashMap; import java.util.Map; -import static io.github.lucaargolo.seasons.FabricSeasons.*; +import static io.github.lucaargolo.seasons.FabricSeasons.CONFIG; +import static io.github.lucaargolo.seasons.FabricSeasons.MOD_ID; +import static io.github.lucaargolo.seasons.FabricSeasons.MOD_NAME; public class FabricSeasonsClient implements ClientModInitializer { @@ -44,72 +51,70 @@ public void onInitializeClient() { clientConfig = FabricSeasons.CONFIG; ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(new GrassSeasonColors()); ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(new FoliageSeasonColors()); - + ClientLifecycleEvents.CLIENT_STARTED.register(client -> { FabricSeasons.SEEDS_MAP.clear(); Registries.ITEM.forEach(item -> { - if(item instanceof BlockItem) { + if (item instanceof BlockItem) { Block block = ((BlockItem) item).getBlock(); - if(block instanceof SeasonalFertilizable) { + if (block instanceof SeasonalFertilizable) { FabricSeasons.SEEDS_MAP.put(item, ((BlockItem) item).getBlock()); } } }); }); - + ClientTickEvents.END_WORLD_TICK.register((clientWorld) -> { - if(FabricSeasons.getCurrentSeason(clientWorld) != lastRenderedSeasonMap.get(clientWorld.getRegistryKey())) { + if (FabricSeasons.getCurrentSeason(clientWorld) != lastRenderedSeasonMap.get(clientWorld.getRegistryKey())) { lastRenderedSeasonMap.put(clientWorld.getRegistryKey(), FabricSeasons.getCurrentSeason(clientWorld)); MinecraftClient.getInstance().worldRenderer.reload(); } }); - - ClientPlayNetworking.registerGlobalReceiver(FabricSeasons.ANSWER_CONFIG, (client, handler, buf, responseSender) -> { - String configJson = buf.readString(); - client.execute(() -> { + + ClientPlayNetworking.registerGlobalReceiver(ConfigSyncPacket.ID, (payload, handler) -> { + String configJson = payload.config(); + handler.client().execute(() -> { FabricSeasons.CONFIG = FabricSeasons.GSON.fromJson(configJson, ModConfig.class); isServerConfig = true; - FabricSeasons.LOGGER.info("["+MOD_NAME+"] Received dedicated server config."); + FabricSeasons.LOGGER.info("[" + MOD_NAME + "] Received dedicated server config."); }); - }); - - ClientPlayNetworking.registerGlobalReceiver(FabricSeasons.UPDATE_CROPS, (client, handler, buf, responseSender) -> { - CropConfig receivedConfig = CropConfig.fromBuf(buf); - HashMap receivedMap = CropConfigs.fromBuf(buf); - client.execute(() -> { + + ClientPlayNetworking.registerGlobalReceiver(UpdateCropsPaycket.ID, (payload, context) -> { + CropConfig receivedConfig = payload.cropConfig(); + HashMap receivedMap = payload.cropConfigMap(); + + context.client().execute(() -> { CropConfigs.receiveConfig(receivedConfig, receivedMap); - FabricSeasons.LOGGER.info("["+MOD_NAME+"] Received dedicated server crops."); + FabricSeasons.LOGGER.info("[" + MOD_NAME + "] Received dedicated server crops."); }); - }); - - + ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> { - if(CONFIG.shouldNotifyCompat()) { + if (CONFIG.shouldNotifyCompat()) { CompatWarnState.join(client); } - if(!client.isIntegratedServerRunning()) { - FabricSeasons.LOGGER.info("["+MOD_NAME+"] Joined dedicated server, asking for config."); - ClientPlayNetworking.send(ASK_FOR_CONFIG, PacketByteBufs.empty()); + if (!client.isIntegratedServerRunning()) { + FabricSeasons.LOGGER.info("[" + MOD_NAME + "] Joined dedicated server, asking for config."); + ClientPlayNetworking.send(new ConfigSyncPacket("request")); } }); - + ClientPlayConnectionEvents.DISCONNECT.register(((handler, client) -> { CropConfigs.clear(); - if(isServerConfig && clientConfig != null) { - FabricSeasons.LOGGER.info("["+MOD_NAME+"] Left dedicated server, restoring config."); + if (isServerConfig && clientConfig != null) { + FabricSeasons.LOGGER.info("[" + MOD_NAME + "] Left dedicated server, restoring config."); FabricSeasons.CONFIG = clientConfig; isServerConfig = false; } })); - - if(FabricLoader.getInstance().isDevelopmentEnvironment() || CONFIG.isDebugCommandEnabled()) { + + if (FabricLoader.getInstance().isDevelopmentEnvironment() || CONFIG.isDebugCommandEnabled()) { ClientCommandRegistrationCallback.EVENT.register((SeasonDebugCommand::register)); } - + FabricLoader.getInstance().getModContainer(MOD_ID).ifPresent((container) -> { - ResourceManagerHelper.registerBuiltinResourcePack(new ModIdentifier("seasonal_lush_caves"), container, Text.literal("Seasonal Lush Caves"), ResourcePackActivationType.DEFAULT_ENABLED); + ResourceManagerHelper.registerBuiltinResourcePack(FabricSeasons.identifier("seasonal_lush_caves"), container, Text.literal("Seasonal Lush Caves"), ResourcePackActivationType.DEFAULT_ENABLED); }); } } diff --git a/src/main/java/io/github/lucaargolo/seasons/commands/SeasonDebugCommand.java b/src/main/java/io/github/lucaargolo/seasons/commands/SeasonDebugCommand.java index cf1b3ba..f7843a8 100644 --- a/src/main/java/io/github/lucaargolo/seasons/commands/SeasonDebugCommand.java +++ b/src/main/java/io/github/lucaargolo/seasons/commands/SeasonDebugCommand.java @@ -77,20 +77,20 @@ public static void register(CommandDispatcher dispatc if(optional.isPresent()) { MinecraftClient client = MinecraftClient.getInstance(); Identifier blockId = optional.get().getValue(); - Optional optional2 = client.getResourceManager().getResource(new Identifier(blockId.getNamespace(), "blockstates/"+blockId.getPath()+".json")); + Optional optional2 = client.getResourceManager().getResource(Identifier.of(blockId.getNamespace(), "blockstates/"+blockId.getPath()+".json")); if(optional2.isPresent()) { Resource blockState = optional2.get(); try { HashSet models = collectModels(new HashSet<>(), JsonParser.parseReader(new InputStreamReader(blockState.getInputStream(), StandardCharsets.UTF_8))); models.forEach((model) -> { - Identifier modelId = new Identifier(model.getNamespace(), "models/"+model.getPath()+".json"); + Identifier modelId = Identifier.of(model.getNamespace(), "models/"+model.getPath()+".json"); Optional optional3 = client.getResourceManager().getResource(modelId); if(optional3.isPresent()) { Resource blockModel = optional3.get(); try { HashMap textures = collectTextures(new HashMap<>(), client.getResourceManager(), JsonParser.parseReader(new InputStreamReader(blockModel.getInputStream(), StandardCharsets.UTF_8))); textures.forEach((name, id) -> { - Optional optional4 = client.getResourceManager().getResource(new Identifier(id.getNamespace(), "textures/"+id.getPath()+".png")); + Optional optional4 = client.getResourceManager().getResource(Identifier.of(id.getNamespace(), "textures/"+id.getPath()+".png")); if(optional4.isPresent()) { Resource texture = optional4.get(); try { @@ -122,14 +122,14 @@ public static void register(CommandDispatcher dispatc if(optional.isPresent()) { MinecraftClient client = MinecraftClient.getInstance(); Identifier itemId = optional.get().getValue(); - Identifier modelId = new Identifier(itemId.getNamespace(), "models/item/"+itemId.getPath()+".json"); + Identifier modelId = Identifier.of(itemId.getNamespace(), "models/item/"+itemId.getPath()+".json"); Optional optional2 = client.getResourceManager().getResource(modelId); if(optional2.isPresent()) { Resource itemModel = optional2.get(); try { HashMap textures = collectTextures(new HashMap<>(), client.getResourceManager(), JsonParser.parseReader(new InputStreamReader(itemModel.getInputStream(), StandardCharsets.UTF_8))); textures.forEach((name, id) -> { - Optional optional4 = client.getResourceManager().getResource(new Identifier(id.getNamespace(), "textures/"+id.getPath()+".png")); + Optional optional4 = client.getResourceManager().getResource(Identifier.of(id.getNamespace(), "textures/"+id.getPath()+".png")); if(optional4.isPresent()) { Resource texture = optional4.get(); try { @@ -152,9 +152,9 @@ public static void register(CommandDispatcher dispatc ClientPlayerEntity player = context.getSource().getPlayer(); List> entries = new ArrayList<>(); player.getWorld().getRegistryManager().get(RegistryKeys.BIOME).getIndexedEntries().forEach(entries::add); - entries.sort(Comparator.comparing(entry -> entry.getKey().orElse(RegistryKey.of(RegistryKeys.BIOME, new Identifier("missingno"))).getValue().toString())); + entries.sort(Comparator.comparing(entry -> entry.getKey().orElse(RegistryKey.of(RegistryKeys.BIOME, Identifier.of("missingno"))).getValue().toString())); AtomicReference str = new AtomicReference<>("\n"); - entries.forEach((entry) -> str.updateAndGet(s -> s + entry.getKey().orElse(RegistryKey.of(RegistryKeys.BIOME, new Identifier("missingno"))).getValue().toString() + "\n")); + entries.forEach((entry) -> str.updateAndGet(s -> s + entry.getKey().orElse(RegistryKey.of(RegistryKeys.BIOME, Identifier.of("missingno"))).getValue().toString() + "\n")); System.out.println(str.get()); return 1; })) @@ -223,35 +223,39 @@ public static void register(CommandDispatcher dispatc private static HashMap collectTextures(HashMap map, ResourceManager manager, JsonElement element) throws IOException { JsonObject model = element.getAsJsonObject(); - if(model.has("parent")) { - Identifier parent = new Identifier(model.get("parent").getAsString()); - Optional optional = manager.getResource(new Identifier(parent.getNamespace(), "models/"+parent.getPath()+".json")); - if(optional.isPresent()) { + + if (model.has("parent")) { + Identifier parent = Identifier.of(model.get("parent").getAsString()); + Optional optional = manager.getResource(Identifier.of(parent.getNamespace(), "models/" + parent.getPath() + ".json")); + if (optional.isPresent()) { Resource parentModel = optional.get(); collectTextures(map, manager, JsonParser.parseReader(new InputStreamReader(parentModel.getInputStream(), StandardCharsets.UTF_8))); } } - if(model.has("textures")) { + + if (model.has("textures")) { JsonObject textures = model.getAsJsonObject("textures"); textures.entrySet().forEach((entry) -> { - if(Identifier.isValid(entry.getValue().getAsString())) { - map.put(entry.getKey(), new Identifier(entry.getValue().getAsString())); + final Identifier identifier = Identifier.tryParse(entry.getValue().getAsString()); + if (identifier != null) { + map.put(entry.getKey(), identifier); } }); } + return map; } private static HashSet collectModels(HashSet set, JsonElement element) { - if(element.isJsonObject()) { + if (element.isJsonObject()) { element.getAsJsonObject().entrySet().forEach((entry) -> { - if(Objects.equals(entry.getKey(), "model") && entry.getValue().isJsonPrimitive() && entry.getValue().getAsJsonPrimitive().isString()) { - set.add(new Identifier(entry.getValue().getAsString())); - }else{ + if (Objects.equals(entry.getKey(), "model") && entry.getValue().isJsonPrimitive() && entry.getValue().getAsJsonPrimitive().isString()) { + set.add(Identifier.of(entry.getValue().getAsString())); + } else { collectModels(set, entry.getValue()); } }); - }else if(element.isJsonArray()) { + } else if (element.isJsonArray()) { element.getAsJsonArray().forEach((innerElement) -> { collectModels(set, innerElement); }); @@ -281,7 +285,7 @@ private static void createTextureIndex(Identifier id, HashMap info) { info.setReturnValue(GrassSeasonColors.getColor(FabricSeasons.getCurrentSeason(), 0.5D, 1.0D)); } - - @Inject(method = "method_1695", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/color/world/FoliageColors;getSpruceColor()I"), cancellable = true) + + @Inject(method = "method_1695", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/biome/FoliageColors;getSpruceColor()I"), cancellable = true) private static void injectSpruceColor(BlockState state, @Nullable BlockRenderView world, @Nullable BlockPos pos, int tintIndex, CallbackInfoReturnable info) { info.setReturnValue(FoliageSeasonColors.getSpruceColor(FabricSeasons.getCurrentSeason())); } - - @Inject(method = "method_1687", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/color/world/FoliageColors;getBirchColor()I"), cancellable = true) + + @Inject(method = "method_1687", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/biome/FoliageColors;getBirchColor()I"), cancellable = true) private static void injectBirchColor(BlockState state, @Nullable BlockRenderView world, @Nullable BlockPos pos, int tintIndex, CallbackInfoReturnable info) { info.setReturnValue(FoliageSeasonColors.getBirchColor(FabricSeasons.getCurrentSeason())); } - - @Inject(method = "method_1692", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/color/world/FoliageColors;getDefaultColor()I"), cancellable = true) + + @Inject(method = "method_1692", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/biome/FoliageColors;getDefaultColor()I"), cancellable = true) private static void injectFoliageColor(BlockState state, @Nullable BlockRenderView world, @Nullable BlockPos pos, int tintIndex, CallbackInfoReturnable info) { info.setReturnValue(FoliageSeasonColors.getDefaultColor(FabricSeasons.getCurrentSeason())); } - } diff --git a/src/main/java/io/github/lucaargolo/seasons/mixin/ItemMixin.java b/src/main/java/io/github/lucaargolo/seasons/mixin/ItemMixin.java index a70982d..8cdecd4 100644 --- a/src/main/java/io/github/lucaargolo/seasons/mixin/ItemMixin.java +++ b/src/main/java/io/github/lucaargolo/seasons/mixin/ItemMixin.java @@ -5,18 +5,16 @@ import io.github.lucaargolo.seasons.utils.Season; import net.minecraft.block.Block; import net.minecraft.client.MinecraftClient; -import net.minecraft.client.item.TooltipContext; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.item.tooltip.TooltipType; import net.minecraft.registry.Registries; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.Identifier; -import net.minecraft.world.World; -import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -29,7 +27,7 @@ public class ItemMixin { @Inject(at = @At("HEAD"), method = "appendTooltip") - public void appendTooltipInject(ItemStack stack, @Nullable World world, List tooltip, TooltipContext context, CallbackInfo ci) { + public void appendTooltipInject(ItemStack stack, Item.TooltipContext context, List tooltip, TooltipType type, CallbackInfo ci) { if(FabricSeasons.CONFIG.isSeasonMessingCrops()) { Season season = FabricSeasons.getCurrentSeason(); Item item = stack.getItem(); diff --git a/src/main/java/io/github/lucaargolo/seasons/mixin/JsonUnbakedModelMixin.java b/src/main/java/io/github/lucaargolo/seasons/mixin/JsonUnbakedModelMixin.java index 8052c38..1f0be57 100644 --- a/src/main/java/io/github/lucaargolo/seasons/mixin/JsonUnbakedModelMixin.java +++ b/src/main/java/io/github/lucaargolo/seasons/mixin/JsonUnbakedModelMixin.java @@ -33,7 +33,7 @@ public abstract class JsonUnbakedModelMixin implements JsonUnbakedModelMixed { @Shadow protected Map> textureMap; - @Shadow public abstract BakedModel bake(Baker baker, JsonUnbakedModel parent, Function textureGetter, ModelBakeSettings settings, Identifier id, boolean hasDepth); + @Shadow public abstract BakedModel bake(Baker baker, JsonUnbakedModel parent, Function textureGetter, ModelBakeSettings settings, boolean hasDepth); private Map>> seasonalTextureMap; private Map> originalTextureMap; @@ -53,8 +53,8 @@ public void setSeasonalTextureMap(Map textureGetter, ModelBakeSettings settings, Identifier id, boolean hasDepth, CallbackInfoReturnable cir) { + @Inject(at = @At("RETURN"), method = "bake(Lnet/minecraft/client/render/model/Baker;Lnet/minecraft/client/render/model/json/JsonUnbakedModel;Ljava/util/function/Function;Lnet/minecraft/client/render/model/ModelBakeSettings;Z)Lnet/minecraft/client/render/model/BakedModel;") + public void collectSeasonalModels(Baker baker, JsonUnbakedModel parent, Function textureGetter, ModelBakeSettings settings, boolean hasDepth, CallbackInfoReturnable cir) { BakedModel originalModel = cir.getReturnValue(); if(seasonalTextureMap != null && this.textureMap == this.originalTextureMap) { seasonalTextureMap.forEach((season, textureMap) -> { @@ -62,7 +62,7 @@ public void collectSeasonalModels(Baker baker, JsonUnbakedModel parent, Function if(!FabricSeasonsClient.originalToSeasonModelMap.containsKey(originalModel)) { FabricSeasonsClient.originalToSeasonModelMap.put(originalModel, Maps.newHashMap()); } - FabricSeasonsClient.originalToSeasonModelMap.get(originalModel).put(season, bake(baker, parent, textureGetter, settings, id, hasDepth)); + FabricSeasonsClient.originalToSeasonModelMap.get(originalModel).put(season, bake(baker, parent, textureGetter, settings, hasDepth)); }); this.textureMap = originalTextureMap; } diff --git a/src/main/java/io/github/lucaargolo/seasons/mixin/ModelLoaderMixin.java b/src/main/java/io/github/lucaargolo/seasons/mixin/ModelLoaderMixin.java index 0299ebe..488cfa9 100644 --- a/src/main/java/io/github/lucaargolo/seasons/mixin/ModelLoaderMixin.java +++ b/src/main/java/io/github/lucaargolo/seasons/mixin/ModelLoaderMixin.java @@ -36,7 +36,7 @@ public class ModelLoaderMixin { @Inject(at = @At("RETURN"), method = "loadModelFromJson", locals = LocalCapture.CAPTURE_FAILSOFT) public void injectSeasonalModels(Identifier id, CallbackInfoReturnable cir) { MinecraftClient client = MinecraftClient.getInstance(); - Optional optional = client.getResourceManager().getResource(new Identifier(id.getNamespace(), "seasons/models/" + id.getPath() + ".json")); + Optional optional = client.getResourceManager().getResource(Identifier.of(id.getNamespace(), "seasons/models/" + id.getPath() + ".json")); if(optional.isPresent()) { Resource resource = optional.get(); try { diff --git a/src/main/java/io/github/lucaargolo/seasons/mixin/ServerWorldMixin.java b/src/main/java/io/github/lucaargolo/seasons/mixin/ServerWorldMixin.java index d3b21e9..86a8c3c 100644 --- a/src/main/java/io/github/lucaargolo/seasons/mixin/ServerWorldMixin.java +++ b/src/main/java/io/github/lucaargolo/seasons/mixin/ServerWorldMixin.java @@ -8,13 +8,11 @@ import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; import net.minecraft.util.profiler.Profiler; import net.minecraft.world.MutableWorldProperties; import net.minecraft.world.StructureWorldAccess; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; -import net.minecraft.world.chunk.WorldChunk; import net.minecraft.world.dimension.DimensionType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -32,23 +30,23 @@ protected ServerWorldMixin(MutableWorldProperties properties, RegistryKey super(properties, registryRef, registryManager, dimensionEntry, profiler, isClient, debugWorld, biomeAccess, maxChainedNeighborUpdates); } - @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Z", ordinal = 0), method = "tickChunk", locals = LocalCapture.CAPTURE_FAILSOFT) - public void setMeltableIce(WorldChunk chunk, int randomTickSpeed, CallbackInfo ci, ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, BlockPos blockPos2, Biome biome) { + @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Z", ordinal = 0), method = "tickIceAndSnow(Lnet/minecraft/util/math/BlockPos;)V", locals = LocalCapture.CAPTURE_FAILSOFT) + public void setMeltableIce(BlockPos pos, CallbackInfo ci, BlockPos blockPos, BlockPos blockPos2, Biome biome) { FabricSeasons.setMeltable(blockPos2); } - @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Z", ordinal = 1), method = "tickChunk", locals = LocalCapture.CAPTURE_FAILSOFT) - public void setMeltableLayeredSnow(WorldChunk chunk, int randomTickSpeed, CallbackInfo ci, ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, BlockPos blockPos2, Biome biome) { + @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Z", ordinal = 1), method = "tickIceAndSnow(Lnet/minecraft/util/math/BlockPos;)V", locals = LocalCapture.CAPTURE_FAILSOFT) + public void setMeltableLayeredSnow(BlockPos pos, CallbackInfo ci, BlockPos blockPos, BlockPos blockPos2, Biome biome, int i, BlockState blockState, int j, BlockState blockState2) { FabricSeasons.setMeltable(blockPos); } - @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Z", ordinal = 2), method = "tickChunk", locals = LocalCapture.CAPTURE_FAILSOFT) - public void setMeltableSnow(WorldChunk chunk, int randomTickSpeed, CallbackInfo ci, ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, BlockPos blockPos2, Biome biome) { + @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Z", ordinal = 2), method = "tickIceAndSnow(Lnet/minecraft/util/math/BlockPos;)V", locals = LocalCapture.CAPTURE_FAILSOFT) + public void setMeltableSnow(BlockPos pos, CallbackInfo ci, BlockPos blockPos, BlockPos blockPos2, Biome biome) { FabricSeasons.setMeltable(blockPos); } - @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;precipitationTick(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/biome/Biome$Precipitation;)V"), method = "tickChunk", locals = LocalCapture.CAPTURE_FAILSOFT) - public void setReplacedMeltable(WorldChunk chunk, int randomTickSpeed, CallbackInfo ci, ChunkPos chunkPos, boolean bl, int i, int j, Profiler profiler, BlockPos blockPos, BlockPos blockPos2, Biome biome, int k, Biome.Precipitation precipitation, BlockState blockState3) { + @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;precipitationTick(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/biome/Biome$Precipitation;)V"), method = "tickIceAndSnow(Lnet/minecraft/util/math/BlockPos;)V", locals = LocalCapture.CAPTURE_FAILSOFT) + public void setReplacedMeltable(BlockPos pos, CallbackInfo ci, BlockPos blockPos, BlockPos blockPos2, Biome biome, int i, Biome.Precipitation precipitation, BlockState blockState3) { Meltable.replaceBlockOnSnow((ServerWorld) (Object) this, blockPos, biome); } diff --git a/src/main/java/io/github/lucaargolo/seasons/payload/ConfigSyncPacket.java b/src/main/java/io/github/lucaargolo/seasons/payload/ConfigSyncPacket.java new file mode 100644 index 0000000..934d58e --- /dev/null +++ b/src/main/java/io/github/lucaargolo/seasons/payload/ConfigSyncPacket.java @@ -0,0 +1,20 @@ +package io.github.lucaargolo.seasons.payload; + +import io.github.lucaargolo.seasons.FabricSeasons; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.network.packet.CustomPayload; + +public record ConfigSyncPacket(String config) implements CustomPayload { + public static final CustomPayload.Id ID = new CustomPayload.Id<>(FabricSeasons.identifier("config_sync")); + public static final PacketCodec CODEC = PacketCodec.tuple( + PacketCodecs.STRING, ConfigSyncPacket::config, + ConfigSyncPacket::new + ); + + @Override + public Id getId() { + return ID; + } +} diff --git a/src/main/java/io/github/lucaargolo/seasons/payload/UpdateCropsPaycket.java b/src/main/java/io/github/lucaargolo/seasons/payload/UpdateCropsPaycket.java new file mode 100644 index 0000000..cc1c828 --- /dev/null +++ b/src/main/java/io/github/lucaargolo/seasons/payload/UpdateCropsPaycket.java @@ -0,0 +1,30 @@ +package io.github.lucaargolo.seasons.payload; + +import io.github.lucaargolo.seasons.FabricSeasons; +import io.github.lucaargolo.seasons.utils.CropConfig; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; +import net.minecraft.network.packet.CustomPayload; +import net.minecraft.util.Identifier; + +import java.util.HashMap; + +public record UpdateCropsPaycket(CropConfig cropConfig, HashMap cropConfigMap) implements CustomPayload { + public static final CustomPayload.Id ID = new CustomPayload.Id<>(FabricSeasons.identifier("update_crops")); + + public static final PacketCodec CODEC = PacketCodec.tuple( + CropConfig.PACKET_CODEC, UpdateCropsPaycket::cropConfig, + PacketCodecs.map(HashMap::new, Identifier.PACKET_CODEC, CropConfig.PACKET_CODEC), UpdateCropsPaycket::cropConfigMap, + UpdateCropsPaycket::new + ); + + public static UpdateCropsPaycket fromConfig(CropConfig config, HashMap configMap) { + return new UpdateCropsPaycket(config, configMap); + } + + @Override + public CustomPayload.Id getId() { + return ID; + } +} diff --git a/src/main/java/io/github/lucaargolo/seasons/resources/CropConfigs.java b/src/main/java/io/github/lucaargolo/seasons/resources/CropConfigs.java index bfa99e0..4ba6c98 100644 --- a/src/main/java/io/github/lucaargolo/seasons/resources/CropConfigs.java +++ b/src/main/java/io/github/lucaargolo/seasons/resources/CropConfigs.java @@ -1,12 +1,14 @@ package io.github.lucaargolo.seasons.resources; +import com.google.gson.JsonElement; import com.google.gson.JsonParser; +import com.mojang.serialization.JsonOps; import io.github.lucaargolo.seasons.FabricSeasons; import io.github.lucaargolo.seasons.utils.CropConfig; -import io.github.lucaargolo.seasons.utils.ModIdentifier; import io.github.lucaargolo.seasons.utils.Season; import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; import net.minecraft.resource.Resource; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; @@ -41,49 +43,57 @@ public static CropConfig getDefaultCropConfig() { return defaultCropConfig; } - public static void toBuf(PacketByteBuf buf) { + public static void toBuf(RegistryByteBuf buf) { buf.writeInt(cropConfigMap.size()); cropConfigMap.forEach((id, config) -> { buf.writeIdentifier(id); config.toBuf(buf); }); } - - public static HashMap fromBuf(PacketByteBuf buf) { + + public static HashMap fromBuf(RegistryByteBuf buf) { HashMap cropConfigMap = new HashMap<>(); int size = buf.readInt(); - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { cropConfigMap.put(buf.readIdentifier(), CropConfig.fromBuf(buf)); } return cropConfigMap; } - + + public static HashMap getCropConfigMap() { + return cropConfigMap; + } + @Override public Identifier getFabricId() { - return new ModIdentifier("crop_configs"); + return FabricSeasons.identifier("crop_configs"); } @Override public void reload(ResourceManager manager) { - try{ - Resource resource = manager.getResource(new ModIdentifier("hardcoded/crop/default.json")).orElseThrow(); - defaultCropConfig = new CropConfig(JsonParser.parseReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))); - }catch (Exception e) { - FabricSeasons.LOGGER.error("["+MOD_NAME+"] Failed to load hardcoded grass colors", e); + try { + Resource resource = manager.getResource(FabricSeasons.identifier("hardcoded/crop/default.json")).orElseThrow(); + JsonElement input = JsonParser.parseReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)); + defaultCropConfig = CropConfig.CODEC.parse(JsonOps.INSTANCE, input.getAsJsonObject()).getOrThrow(); + } catch (Exception e) { + FabricSeasons.LOGGER.error("[" + MOD_NAME + "] Failed to load hardcoded grass colors", e); } + cropConfigMap.clear(); manager.findResources("seasons/crop", id -> id.getPath().endsWith(".json")).forEach((id, resource) -> { String[] split = id.getPath().split("/"); - Identifier cropIdentifier = new Identifier(id.getNamespace(), split[split.length-1].replace(".json", "")); + Identifier cropIdentifier = Identifier.of(id.getNamespace(), split[split.length - 1].replace(".json", "")); try { - CropConfig config = new CropConfig(JsonParser.parseReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))); + JsonElement input = JsonParser.parseReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)); + CropConfig config = CropConfig.CODEC.parse(JsonOps.INSTANCE, input.getAsJsonObject()).getOrThrow(); cropConfigMap.put(cropIdentifier, config); - }catch(Exception e) { - FabricSeasons.LOGGER.error("["+MOD_NAME+"] Failed to load crop config for: "+cropIdentifier, e); + } catch (Exception e) { + FabricSeasons.LOGGER.error("[" + MOD_NAME + "] Failed to load crop config for: " + cropIdentifier, e); } }); - if(!cropConfigMap.isEmpty()) { - FabricSeasons.LOGGER.info("["+MOD_NAME+"] Successfully loaded "+cropConfigMap.size()+" custom crop configs."); + + if (!cropConfigMap.isEmpty()) { + FabricSeasons.LOGGER.info("[" + MOD_NAME + "] Successfully loaded {} custom crop configs.", cropConfigMap.size()); } } } diff --git a/src/main/java/io/github/lucaargolo/seasons/resources/FoliageSeasonColors.java b/src/main/java/io/github/lucaargolo/seasons/resources/FoliageSeasonColors.java index a51abf6..6bb7c1e 100644 --- a/src/main/java/io/github/lucaargolo/seasons/resources/FoliageSeasonColors.java +++ b/src/main/java/io/github/lucaargolo/seasons/resources/FoliageSeasonColors.java @@ -2,7 +2,6 @@ import com.google.gson.JsonParser; import io.github.lucaargolo.seasons.FabricSeasons; -import io.github.lucaargolo.seasons.utils.ModIdentifier; import io.github.lucaargolo.seasons.utils.Season; import io.github.lucaargolo.seasons.utils.SeasonColor; import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; @@ -22,10 +21,10 @@ public class FoliageSeasonColors implements SimpleSynchronousResourceReloadListener { - private static final Identifier SPRING_FOLIAGE_COLORMAP = new ModIdentifier("textures/colormap/spring_foliage.png"); - private static final Identifier SUMMER_FOLIAGE_COLORMAP = new ModIdentifier("textures/colormap/summer_foliage.png"); - private static final Identifier FALL_FOLIAGE_COLORMAP = new ModIdentifier("textures/colormap/fall_foliage.png"); - private static final Identifier WINTER_FOLIAGE_COLORMAP = new ModIdentifier("textures/colormap/winter_foliage.png"); + private static final Identifier SPRING_FOLIAGE_COLORMAP = FabricSeasons.identifier("textures/colormap/spring_foliage.png"); + private static final Identifier SUMMER_FOLIAGE_COLORMAP = FabricSeasons.identifier("textures/colormap/summer_foliage.png"); + private static final Identifier FALL_FOLIAGE_COLORMAP = FabricSeasons.identifier("textures/colormap/fall_foliage.png"); + private static final Identifier WINTER_FOLIAGE_COLORMAP = FabricSeasons.identifier("textures/colormap/winter_foliage.png"); private static int[] springColorMap = new int[65536]; private static int[] summerColorMap = new int[65536]; @@ -75,18 +74,18 @@ public static int getDefaultColor(Season season) { @Override public Identifier getFabricId() { - return new ModIdentifier("foliage_season_colors"); + return FabricSeasons.identifier("foliage_season_colors"); } @SuppressWarnings("deprecation") @Override public void reload(ResourceManager manager) { try{ - Resource spruceFoliage = manager.getResource(new ModIdentifier("hardcoded/foliage/spruce.json")).orElseThrow(); + Resource spruceFoliage = manager.getResource(FabricSeasons.identifier("hardcoded/foliage/spruce.json")).orElseThrow(); minecraftSpruceFoliage = new SeasonColor(JsonParser.parseReader(new InputStreamReader(spruceFoliage.getInputStream(), StandardCharsets.UTF_8))); - Resource birchFoliage = manager.getResource(new ModIdentifier("hardcoded/foliage/birch.json")).orElseThrow(); + Resource birchFoliage = manager.getResource(FabricSeasons.identifier("hardcoded/foliage/birch.json")).orElseThrow(); minecraftBirchFoliage = new SeasonColor(JsonParser.parseReader(new InputStreamReader(birchFoliage.getInputStream(), StandardCharsets.UTF_8))); - Resource defaultFoliage = manager.getResource(new ModIdentifier("hardcoded/foliage/default.json")).orElseThrow(); + Resource defaultFoliage = manager.getResource(FabricSeasons.identifier("hardcoded/foliage/default.json")).orElseThrow(); minecraftDefaultFoliage = new SeasonColor(JsonParser.parseReader(new InputStreamReader(defaultFoliage.getInputStream(), StandardCharsets.UTF_8))); }catch (Exception e) { FabricSeasons.LOGGER.error("["+MOD_NAME+"] Failed to load hardcoded foliage colors", e); @@ -94,7 +93,7 @@ public void reload(ResourceManager manager) { foliageColorMap.clear(); manager.findResources("seasons/foliage", id -> id.getPath().endsWith(".json")).forEach((id, resource) -> { String[] split = id.getPath().split("/"); - Identifier biomeIdentifier = new Identifier(id.getNamespace(), split[split.length-1].replace(".json", "")); + Identifier biomeIdentifier = Identifier.of(id.getNamespace(), split[split.length-1].replace(".json", "")); try { SeasonColor colors = new SeasonColor(JsonParser.parseReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))); foliageColorMap.put(biomeIdentifier, colors); diff --git a/src/main/java/io/github/lucaargolo/seasons/resources/GrassSeasonColors.java b/src/main/java/io/github/lucaargolo/seasons/resources/GrassSeasonColors.java index 49a7fc7..20747e1 100644 --- a/src/main/java/io/github/lucaargolo/seasons/resources/GrassSeasonColors.java +++ b/src/main/java/io/github/lucaargolo/seasons/resources/GrassSeasonColors.java @@ -2,7 +2,6 @@ import com.google.gson.JsonParser; import io.github.lucaargolo.seasons.FabricSeasons; -import io.github.lucaargolo.seasons.utils.ModIdentifier; import io.github.lucaargolo.seasons.utils.Season; import io.github.lucaargolo.seasons.utils.SeasonColor; import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; @@ -22,10 +21,10 @@ public class GrassSeasonColors implements SimpleSynchronousResourceReloadListener { - private static final Identifier SPRING_GRASS_COLORMAP = new ModIdentifier("textures/colormap/spring_grass.png"); - private static final Identifier SUMMER_GRASS_COLORMAP = new ModIdentifier("textures/colormap/summer_grass.png"); - private static final Identifier FALL_GRASS_COLORMAP = new ModIdentifier("textures/colormap/fall_grass.png"); - private static final Identifier WINTER_GRASS_COLORMAP = new ModIdentifier("textures/colormap/winter_grass.png"); + private static final Identifier SPRING_GRASS_COLORMAP = FabricSeasons.identifier("textures/colormap/spring_grass.png"); + private static final Identifier SUMMER_GRASS_COLORMAP = FabricSeasons.identifier("textures/colormap/summer_grass.png"); + private static final Identifier FALL_GRASS_COLORMAP = FabricSeasons.identifier("textures/colormap/fall_grass.png"); + private static final Identifier WINTER_GRASS_COLORMAP = FabricSeasons.identifier("textures/colormap/winter_grass.png"); private static int[] springColorMap = new int[65536]; private static int[] summerColorMap = new int[65536]; @@ -70,16 +69,16 @@ public static int getSwampColor2(Season season) { @Override public Identifier getFabricId() { - return new ModIdentifier("grass_season_colors"); + return FabricSeasons.identifier("grass_season_colors"); } @SuppressWarnings("deprecation") @Override public void reload(ResourceManager manager) { try{ - Resource swampGrass1 = manager.getResource(new ModIdentifier("hardcoded/grass/swamp1.json")).orElseThrow(); + Resource swampGrass1 = manager.getResource(FabricSeasons.identifier("hardcoded/grass/swamp1.json")).orElseThrow(); minecraftSwampGrass1 = new SeasonColor(JsonParser.parseReader(new InputStreamReader(swampGrass1.getInputStream(), StandardCharsets.UTF_8))); - Resource swampGrass2 = manager.getResource(new ModIdentifier("hardcoded/grass/swamp2.json")).orElseThrow(); + Resource swampGrass2 = manager.getResource(FabricSeasons.identifier("hardcoded/grass/swamp2.json")).orElseThrow(); minecraftSwampGrass2 = new SeasonColor(JsonParser.parseReader(new InputStreamReader(swampGrass2.getInputStream(), StandardCharsets.UTF_8))); }catch (Exception e) { FabricSeasons.LOGGER.error("["+MOD_NAME+"] Failed to load hardcoded grass colors", e); @@ -87,7 +86,7 @@ public void reload(ResourceManager manager) { grassColorMap.clear(); manager.findResources("seasons/grass", id -> id.getPath().endsWith(".json")).forEach((id, resource) -> { String[] split = id.getPath().split("/"); - Identifier biomeIdentifier = new Identifier(id.getNamespace(), split[split.length-1].replace(".json", "")); + Identifier biomeIdentifier = Identifier.of(id.getNamespace(), split[split.length-1].replace(".json", "")); try { SeasonColor colors = new SeasonColor(JsonParser.parseReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))); grassColorMap.put(biomeIdentifier, colors); diff --git a/src/main/java/io/github/lucaargolo/seasons/utils/CompatWarnState.java b/src/main/java/io/github/lucaargolo/seasons/utils/CompatWarnState.java index 88319fd..4d093f2 100644 --- a/src/main/java/io/github/lucaargolo/seasons/utils/CompatWarnState.java +++ b/src/main/java/io/github/lucaargolo/seasons/utils/CompatWarnState.java @@ -85,7 +85,7 @@ private void saveState() { try { Boolean ignored = compatWarnFile.getParentFile().mkdirs(); Boolean ignored2 = compatWarnFile.createNewFile(); - NbtIo.writeCompressed(nbt, compatWarnFile); + NbtIo.writeCompressed(nbt, compatWarnFile.toPath()); } catch (IOException e) { FabricSeasons.LOGGER.error("["+MOD_NAME+"] Failed to save season compat warn state.", e); } @@ -96,7 +96,7 @@ public static CompatWarnState loadState(MinecraftClient client) { HashSet alreadyWarned = new HashSet<>(); NbtCompound nbt; try { - nbt = NbtIo.readCompressed(compatWarnFile); + nbt = NbtIo.readCompressed(compatWarnFile.toPath(), NbtSizeTracker.of(0x6400000L)); } catch (Exception e) { nbt = new NbtCompound(); } diff --git a/src/main/java/io/github/lucaargolo/seasons/utils/CropConfig.java b/src/main/java/io/github/lucaargolo/seasons/utils/CropConfig.java index 0834534..7eb83a3 100644 --- a/src/main/java/io/github/lucaargolo/seasons/utils/CropConfig.java +++ b/src/main/java/io/github/lucaargolo/seasons/utils/CropConfig.java @@ -1,9 +1,23 @@ package io.github.lucaargolo.seasons.utils; import com.google.gson.JsonElement; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.RegistryByteBuf; +import net.minecraft.network.codec.PacketCodec; +import net.minecraft.network.codec.PacketCodecs; public class CropConfig { + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.FLOAT.fieldOf("spring").forGetter(CropConfig::springModifier), + Codec.FLOAT.fieldOf("summer").forGetter(CropConfig::summerModifier), + Codec.FLOAT.fieldOf("fall").forGetter(CropConfig::fallModifier), + Codec.FLOAT.fieldOf("winter").forGetter(CropConfig::winterModifier) + ).apply(instance, CropConfig::new)); + public static final PacketCodec PACKET_CODEC = PacketCodec.of(CropConfig::toBuf, CropConfig::fromBuf); + private final float springModifier; private final float summerModifier; private final float fallModifier; @@ -36,15 +50,30 @@ public float getModifier(Season season) { }; } - public void toBuf(PacketByteBuf buf) { + public void toBuf(ByteBuf buf) { buf.writeFloat(springModifier); buf.writeFloat(summerModifier); buf.writeFloat(fallModifier); buf.writeFloat(winterModifier); } - public static CropConfig fromBuf(PacketByteBuf buf) { + public static CropConfig fromBuf(ByteBuf buf) { return new CropConfig(buf.readFloat(), buf.readFloat(), buf.readFloat(), buf.readFloat()); } - + + public float springModifier() { + return springModifier; + } + + public float summerModifier() { + return summerModifier; + } + + public float fallModifier() { + return fallModifier; + } + + public float winterModifier() { + return winterModifier; + } } \ No newline at end of file diff --git a/src/main/java/io/github/lucaargolo/seasons/utils/Meltable.java b/src/main/java/io/github/lucaargolo/seasons/utils/Meltable.java index 3365258..dcbb23f 100644 --- a/src/main/java/io/github/lucaargolo/seasons/utils/Meltable.java +++ b/src/main/java/io/github/lucaargolo/seasons/utils/Meltable.java @@ -15,7 +15,7 @@ public interface Meltable { - TagKey REPLACEABLE_BY_SNOW = TagKey.of(RegistryKeys.BLOCK, new ModIdentifier("replaceable_by_snow")); + TagKey REPLACEABLE_BY_SNOW = TagKey.of(RegistryKeys.BLOCK, FabricSeasons.identifier("replaceable_by_snow")); default void onMeltableReplaced(ServerWorld world, BlockPos pos) { FabricSeasons.getPlacedMeltablesState(world).setManuallyPlaced(pos, false); diff --git a/src/main/java/io/github/lucaargolo/seasons/utils/ModIdentifier.java b/src/main/java/io/github/lucaargolo/seasons/utils/ModIdentifier.java deleted file mode 100644 index dd60d99..0000000 --- a/src/main/java/io/github/lucaargolo/seasons/utils/ModIdentifier.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.github.lucaargolo.seasons.utils; - -import io.github.lucaargolo.seasons.FabricSeasons; -import net.minecraft.util.Identifier; - -public class ModIdentifier extends Identifier { - - public ModIdentifier(String path) { - super(FabricSeasons.MOD_ID, path); - } - -} diff --git a/src/main/java/io/github/lucaargolo/seasons/utils/PlacedMeltablesState.java b/src/main/java/io/github/lucaargolo/seasons/utils/PlacedMeltablesState.java index 183c6b4..64ea552 100644 --- a/src/main/java/io/github/lucaargolo/seasons/utils/PlacedMeltablesState.java +++ b/src/main/java/io/github/lucaargolo/seasons/utils/PlacedMeltablesState.java @@ -3,10 +3,13 @@ import io.github.lucaargolo.seasons.FabricSeasons; import it.unimi.dsi.fastutil.longs.Long2ObjectArrayMap; import it.unimi.dsi.fastutil.longs.LongArraySet; +import net.minecraft.datafixer.DataFixTypes; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtLongArray; +import net.minecraft.registry.RegistryWrapper; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; +import net.minecraft.world.ForcedChunkState; import net.minecraft.world.PersistentState; import static io.github.lucaargolo.seasons.FabricSeasons.MOD_NAME; @@ -42,7 +45,7 @@ public void setManuallyPlaced(BlockPos blockPos, Boolean manuallyPlaced) { } @Override - public NbtCompound writeNbt(NbtCompound nbt) { + public NbtCompound writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { chunkToPlaced.long2ObjectEntrySet().fastForEach(entry -> { if(!entry.getValue().isEmpty()) { nbt.put(entry.getLongKey() + "", new NbtLongArray(entry.getValue())); @@ -50,7 +53,8 @@ public NbtCompound writeNbt(NbtCompound nbt) { }); return nbt; } - public static PlacedMeltablesState createFromNbt(NbtCompound nbt) { + + public static PlacedMeltablesState createFromNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { PlacedMeltablesState state = new PlacedMeltablesState(); nbt.getKeys().forEach(key -> { try { @@ -63,4 +67,8 @@ public static PlacedMeltablesState createFromNbt(NbtCompound nbt) { }); return state; } + + public static PersistentState.Type getPersistentStateType() { + return new PersistentState.Type<>(PlacedMeltablesState::new, PlacedMeltablesState::createFromNbt, null); + } } diff --git a/src/main/java/io/github/lucaargolo/seasons/utils/ReplacedMeltablesState.java b/src/main/java/io/github/lucaargolo/seasons/utils/ReplacedMeltablesState.java index 827d23c..fe4d878 100644 --- a/src/main/java/io/github/lucaargolo/seasons/utils/ReplacedMeltablesState.java +++ b/src/main/java/io/github/lucaargolo/seasons/utils/ReplacedMeltablesState.java @@ -5,6 +5,7 @@ import net.minecraft.block.BlockState; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtOps; +import net.minecraft.registry.RegistryWrapper; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.PersistentState; @@ -46,12 +47,12 @@ public void setReplaced(BlockPos blockPos, BlockState replacedState) { } @Override - public NbtCompound writeNbt(NbtCompound nbt) { + public NbtCompound writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { chunkToReplaced.long2ObjectEntrySet().fastForEach(entry -> { if(!entry.getValue().isEmpty()) { NbtCompound innerNbt = new NbtCompound(); entry.getValue().long2ObjectEntrySet().fastForEach(innerEntry -> { - BlockState.CODEC.encode(innerEntry.getValue(), NbtOps.INSTANCE, NbtOps.INSTANCE.empty()).get().ifLeft((element) -> { + BlockState.CODEC.encode(innerEntry.getValue(), NbtOps.INSTANCE, NbtOps.INSTANCE.empty()).ifSuccess((element) -> { innerNbt.put(innerEntry.getLongKey() + "", element); }); }); @@ -60,7 +61,8 @@ public NbtCompound writeNbt(NbtCompound nbt) { }); return nbt; } - public static ReplacedMeltablesState createFromNbt(NbtCompound nbt) { + + public static ReplacedMeltablesState createFromNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) { ReplacedMeltablesState state = new ReplacedMeltablesState(); nbt.getKeys().forEach(key -> { try { @@ -69,7 +71,7 @@ public static ReplacedMeltablesState createFromNbt(NbtCompound nbt) { NbtCompound innerNbt = nbt.getCompound(key); innerNbt.getKeys().forEach(innerKey -> { long innerLongKey = Long.parseLong(innerKey); - BlockState.CODEC.decode(NbtOps.INSTANCE, innerNbt.get(innerKey)).get().ifLeft((pair) -> { + BlockState.CODEC.decode(NbtOps.INSTANCE, innerNbt.get(innerKey)).ifSuccess((pair) -> { BlockState replacedState = pair.getFirst(); posToReplaced.put(innerLongKey, replacedState); }); @@ -81,4 +83,8 @@ public static ReplacedMeltablesState createFromNbt(NbtCompound nbt) { }); return state; } + + public static PersistentState.Type getPersistentStateType() { + return new PersistentState.Type<>(ReplacedMeltablesState::new, ReplacedMeltablesState::createFromNbt, null); + } } diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 1fa6451..f8488d6 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -33,7 +33,7 @@ "depends": { "fabricloader": ">=0.14.8", "fabric": ">=0.83.0", - "minecraft": "1.20.x" + "minecraft": ">=1.21" }, "custom": { "modmenu": { diff --git a/src/main/resources/seasons.accesswidener b/src/main/resources/seasons.accesswidener index 8603013..83bfece 100644 --- a/src/main/resources/seasons.accesswidener +++ b/src/main/resources/seasons.accesswidener @@ -10,4 +10,5 @@ mutable field net/minecraft/world/biome/Biome$Weather temperature F accessible field net/minecraft/client/option/KeyBinding boundKey Lnet/minecraft/client/util/InputUtil$Key; accessible method net/minecraft/world/biome/Biome getTemperature (Lnet/minecraft/util/math/BlockPos;)F accessible method net/minecraft/client/render/model/json/JsonUnbakedModel$Deserializer resolveReference (Lnet/minecraft/util/Identifier;Ljava/lang/String;)Lcom/mojang/datafixers/util/Either; -mutable field net/minecraft/client/render/model/json/JsonUnbakedModel textureMap Ljava/util/Map; \ No newline at end of file +mutable field net/minecraft/client/render/model/json/JsonUnbakedModel textureMap Ljava/util/Map; +accessible method net/minecraft/block/AbstractBlock randomTick (Lnet/minecraft/block/BlockState;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/random/Random;)V \ No newline at end of file