From f53823b616d14321578c9b6b10fef119fec34472 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 18:27:16 +0200 Subject: [PATCH 01/22] Share pottery profiles and backport painted vessels to Forge 1.12.2 and 1.20.1 Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/DisplayCheck.java | 100 ++++++++++ .../1.20.1/potterycheck/DisplayCheck.java | 107 +++++++++++ .github/forge-display-check/check.init.gradle | 18 ++ .github/workflows/ci.yml | 50 ++++- README.md | 15 +- .../src/main/groovy/multiloader-common.gradle | 3 + core/build.gradle | 11 ++ .../primalpottery/pottery/BakedVessels.java | 49 +++++ .../primalpottery/pottery/FacePaint.java | 42 +++-- .../primalpottery/pottery/PaintedVessel.java | 133 ++++++++++++++ .../primalpottery/pottery/Pottery.java | 126 ++++++------- .../primalpottery/pottery/PotteryCodec.java | 57 ++++++ .../primalpottery/pottery/PotteryDisc.java | 38 ++++ .../primalpottery/pottery/PotteryProfile.java | 41 ++++- .../primalpottery/pottery/PotteryType.java | 50 +++++ .../pottery/VesselQuadPacker.java | 51 ++++++ forge/build.gradle | 33 ++++ .../primalpottery/forge/ForgePotteryTags.java | 33 ++++ .../primalpottery/forge/PaintedPotBlock.java | 41 +++++ .../primalpottery/forge/PaintedPotEntity.java | 60 ++++++ .../forge/PrimalPotteryForge.java | 31 ++++ .../forge/client/PotteryModel.java | 73 ++++++++ .../forge/client/PotteryQuads.java | 19 ++ forge/src/main/resources/META-INF/mods.toml | 14 ++ .../primalpottery/blockstates/pottery.json | 1 + .../assets/primalpottery/lang/en_us.json | 1 + .../primalpottery/models/block/pottery.json | 8 + .../models/block/pottery_inks.json | 1 + .../primalpottery/models/item/pottery.json | 1 + .../textures/block/pottery_inks.png | Bin 0 -> 396 bytes forge/src/main/resources/pack.mcmeta | 1 + legacy/forge-1.12.2/build.gradle | 48 +++++ .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 54413 bytes .../gradle/wrapper/gradle-wrapper.properties | 5 + legacy/forge-1.12.2/gradlew | 172 ++++++++++++++++++ legacy/forge-1.12.2/gradlew.bat | 84 +++++++++ legacy/forge-1.12.2/settings.gradle | 3 + .../legacy/ForgePotteryTags.java | 33 ++++ .../primalpottery/legacy/PaintedPotBlock.java | 78 ++++++++ .../legacy/PaintedPotEntity.java | 54 ++++++ .../legacy/PrimalPotteryForge.java | 30 +++ .../legacy/client/PotteryModel.java | 84 +++++++++ .../legacy/client/PotteryQuads.java | 20 ++ .../primalpottery/blockstates/pottery.json | 1 + .../assets/primalpottery/lang/en_us.lang | 1 + .../src/main/resources/mcmod.info | 1 + .../src/main/resources/pack.mcmeta | 1 + neoforge/build.gradle | 1 + settings.gradle.kts | 1 + .../block/PaintingTableEntity.java | 3 +- .../block/PotteryBlockEntity.java | 5 +- .../block/PotteryWheelBlockEntity.java | 13 +- .../primalpottery/client/ItemIconStamp.java | 3 +- .../primalpottery/client/PaintAtlas.java | 3 +- .../primalpottery/client/PaintingScreen.java | 5 +- .../primalpottery/client/PlatePaint.java | 3 +- .../primalpottery/client/PotteryPaint.java | 3 +- .../primalpottery/client/TemplateScreen.java | 2 +- .../primalpottery/item/PotteryItem.java | 9 +- .../primalpottery/item/RawPotteryItem.java | 9 +- .../primalpottery/item/TemplateItem.java | 7 +- .../primalpottery/menu/PaintingMenu.java | 3 +- .../primalpottery/pottery/PaintColors.java | 19 ++ .../primalpottery/pottery/PotteryDisc.java | 7 - .../primalpottery/pottery/PotteryTags.java | 30 +++ .../primalpottery/pottery/PotteryType.java | 57 ------ .../primalpottery/client/MeshTest.java | 5 +- .../primalpottery/pottery/PotteryTest.java | 40 ++-- stonecutter.gradle.kts | 5 +- 69 files changed, 1850 insertions(+), 206 deletions(-) create mode 100644 .github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java create mode 100644 .github/forge-display-check/check.init.gradle create mode 100644 core/build.gradle create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java rename {src => core/src}/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java (70%) create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java rename {src => core/src}/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java (82%) create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryCodec.java create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java rename {src => core/src}/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryProfile.java (86%) create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java create mode 100644 forge/build.gradle create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgePotteryTags.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java create mode 100644 forge/src/main/resources/META-INF/mods.toml create mode 100644 forge/src/main/resources/assets/primalpottery/blockstates/pottery.json create mode 100644 forge/src/main/resources/assets/primalpottery/lang/en_us.json create mode 100644 forge/src/main/resources/assets/primalpottery/models/block/pottery.json create mode 100644 forge/src/main/resources/assets/primalpottery/models/block/pottery_inks.json create mode 100644 forge/src/main/resources/assets/primalpottery/models/item/pottery.json create mode 100644 forge/src/main/resources/assets/primalpottery/textures/block/pottery_inks.png create mode 100644 forge/src/main/resources/pack.mcmeta create mode 100644 legacy/forge-1.12.2/build.gradle create mode 100644 legacy/forge-1.12.2/gradle/wrapper/gradle-wrapper.jar create mode 100644 legacy/forge-1.12.2/gradle/wrapper/gradle-wrapper.properties create mode 100755 legacy/forge-1.12.2/gradlew create mode 100644 legacy/forge-1.12.2/gradlew.bat create mode 100644 legacy/forge-1.12.2/settings.gradle create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgePotteryTags.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery.json create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang create mode 100644 legacy/forge-1.12.2/src/main/resources/mcmod.info create mode 100644 legacy/forge-1.12.2/src/main/resources/pack.mcmeta create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintColors.java delete mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTags.java delete mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java new file mode 100644 index 0000000..8f07c83 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -0,0 +1,100 @@ +package potterycheck; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Locale; +import net.minecraft.client.Minecraft; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.legacy.ForgePotteryTags; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ScreenShotHelper; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.GameType; +import net.minecraft.world.WorldServer; +import net.minecraft.world.WorldSettings; +import net.minecraft.world.WorldType; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) +// Runs only in the disposable hosted world, under Xvfb with Mesa software rendering. +public final class DisplayCheck { + private static boolean opening; + private static boolean placed; + private static int ticks; + private static long firstFrame; + private static long previousFrame; + private static final ArrayList frames = new ArrayList<>(); + private static final String WORLD = "painted-pot-display"; + + @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END) return; + Minecraft mc = Minecraft.getMinecraft(); + if (!opening && mc.currentScreen instanceof GuiMainMenu) { + opening = true; + mc.gameSettings.limitFramerate = 30; + mc.gameSettings.pauseOnLostFocus = false; + mc.launchIntegratedServer(WORLD, WORLD, new WorldSettings(42, GameType.CREATIVE, false, false, WorldType.FLAT)); + return; + } + if (mc.player == null || mc.world == null || ++ticks < 40) return; + if (!placed) { + placed = true; + mc.gameSettings.hideGUI = true; + mc.getIntegratedServer().addScheduledTask(() -> { + WorldServer level = mc.getIntegratedServer().getWorld(0); + install(level); + mc.getIntegratedServer().getPlayerList().getPlayers().get(0).connection.setPlayerLocation(.5, 85, -18.5, 0, 5); + }); + } + } + + private static void install(WorldServer level) { + BlockPos platform = new BlockPos(0, 84, -19); + level.setBlockState(platform, Blocks.STONE.getDefaultState()); + StringBuilder pixels = new StringBuilder(256); + for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) pixels.append((x + y) % 2 == 0 ? 'A' : 'O'); + Pottery model = Pottery.jug().withPaint(FacePaint.read(pixels.toString())); + ItemStack stack = new ItemStack(PrimalPotteryForge.POT); + stack.setTagInfo("pottery", ForgePotteryTags.save(model)); + for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { + BlockPos pos = new BlockPos(x, y, 0); + level.setBlockState(pos, PrimalPotteryForge.POT.getDefaultState()); + PrimalPotteryForge.POT.onBlockPlacedBy(level, pos, level.getBlockState(pos), null, stack); + } + } + + @SubscribeEvent public static void frame(TickEvent.RenderTickEvent event) throws Exception { + if (!placed || event.phase != TickEvent.Phase.END) return; + Minecraft mc = Minecraft.getMinecraft(); + if (mc.player == null || mc.currentScreen != null || mc.player.posZ > -18) return; + long now = System.nanoTime(); + if (firstFrame == 0) { + for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { + if (!(mc.world.getTileEntity(new BlockPos(x,y,0)) instanceof PaintedPotEntity)) return; + } + firstFrame = previousFrame = now; + return; + } + if (now - firstFrame > 5_000_000_000L) frames.add(now - previousFrame); + previousFrame = now; + if (now - firstFrame < 17_000_000_000L) return; + placed = false; + Collections.sort(frames); + String report = String.format(Locale.ROOT, "200 checkerboard pots, %d frames, p50 %.2f ms, p95 %.2f ms (30 FPS cap)", + frames.size(), frames.get(frames.size() / 2) / 1e6, frames.get(frames.size() * 95 / 100) / 1e6); + ScreenShotHelper.saveScreenshot(new File("."), "pots.png", mc.displayWidth, mc.displayHeight, mc.getFramebuffer()); + Files.write(Paths.get("display-check.txt"), Collections.singletonList(report)); + mc.shutdown(); + } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java new file mode 100644 index 0000000..92219fb --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -0,0 +1,107 @@ +package potterycheck; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Locale; +import net.minecraft.client.Minecraft; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.forge.ForgePotteryTags; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.minecraft.client.Screenshot; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.Difficulty; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.level.levelgen.presets.WorldPresets; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.registries.ForgeRegistries; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) +// Runs only in the disposable hosted world, under Xvfb with Mesa software rendering. +public final class DisplayCheck { + private static boolean opening; + private static boolean placed; + private static int ticks; + private static long firstFrame; + private static long previousFrame; + private static final ArrayList frames = new ArrayList<>(); + private static final String WORLD = "painted-pot-display"; + + @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END) return; + Minecraft mc = Minecraft.getInstance(); + if (!opening && mc.screen instanceof TitleScreen && mc.getOverlay() == null) { + opening = true; + mc.options.framerateLimit().set(30); + mc.options.pauseOnLostFocus = false; + LevelSettings settings = new LevelSettings(WORLD, GameType.CREATIVE, false, Difficulty.PEACEFUL, + true, new GameRules(), WorldDataConfiguration.DEFAULT); + mc.createWorldOpenFlows().createFreshLevel(WORLD, settings, new WorldOptions(42L, false, false), + access -> access.registryOrThrow(Registries.WORLD_PRESET).getOrThrow(WorldPresets.FLAT).createWorldDimensions()); + return; + } + if (mc.player == null || mc.level == null || ++ticks < 40) return; + if (!placed) { + placed = true; + mc.options.hideGui = true; + var server = mc.getSingleplayerServer(); + server.execute(() -> { + install(server.overworld()); + server.getPlayerList().getPlayers().get(0).connection.teleport(.5, 85, -18.5, 0, 5); + }); + } + } + + private static void install(ServerLevel level) { + BlockPos platform = new BlockPos(0, 84, -19); + level.setBlockAndUpdate(platform, Blocks.STONE.defaultBlockState()); + StringBuilder pixels = new StringBuilder(256); + for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) pixels.append((x + y) % 2 == 0 ? 'A' : 'O'); + Pottery model = Pottery.jug().withPaint(FacePaint.read(pixels.toString())); + var block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation("primalpottery", "pottery")); + ItemStack stack = new ItemStack(block); + stack.addTagElement("pottery", ForgePotteryTags.save(model)); + for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { + BlockPos pos = new BlockPos(x, y, 0); + level.setBlockAndUpdate(pos, block.defaultBlockState()); + block.setPlacedBy(level, pos, block.defaultBlockState(), null, stack); + } + } + + @SubscribeEvent public static void frame(TickEvent.RenderTickEvent event) throws Exception { + if (!placed || event.phase != TickEvent.Phase.END) return; + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.screen != null || mc.player.getZ() > -18) return; + long now = System.nanoTime(); + if (firstFrame == 0) { + for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { + if (!(mc.level.getBlockEntity(new BlockPos(x,y,0)) instanceof PaintedPotEntity)) return; + } + firstFrame = previousFrame = now; + return; + } + if (now - firstFrame > 5_000_000_000L) frames.add(now - previousFrame); + previousFrame = now; + if (now - firstFrame < 17_000_000_000L) return; + placed = false; + Collections.sort(frames); + String report = String.format(Locale.ROOT, "200 checkerboard pots, %d frames, p50 %.2f ms, p95 %.2f ms (30 FPS cap)", + frames.size(), frames.get(frames.size() / 2) / 1e6, frames.get(frames.size() * 95 / 100) / 1e6); + try (var image = Screenshot.takeScreenshot(mc.getMainRenderTarget())) { image.writeToFile(new File("pots.png")); } + Files.write(Paths.get("display-check.txt"), Collections.singletonList(report)); + mc.stop(); + } +} diff --git a/.github/forge-display-check/check.init.gradle b/.github/forge-display-check/check.init.gradle new file mode 100644 index 0000000..6fdad3c --- /dev/null +++ b/.github/forge-display-check/check.init.gradle @@ -0,0 +1,18 @@ +// Only used by the hosted display check. The production jars are built in a separate Gradle invocation. +gradle.beforeProject { p -> + if (p.path == ':forge') p.afterEvaluate { + p.sourceSets.main.java.srcDir(p.rootProject.file('.github/forge-display-check/1.20.1')) + p.legacyForge.runs.client { + gameDirectory = p.rootProject.file('build/display-check') + programArguments.addAll '--width', '854', '--height', '480' + } + } + if (p == p.rootProject && p.name == 'primalpottery-forge-1.12.2') p.afterEvaluate { + p.sourceSets.main.java.srcDir(p.file('../../.github/forge-display-check/1.12.2')) + p.minecraft.runs.client { + workingDirectory p.file('../../build/display-check') + args '--width','854','--height','480' + mods { primalpottery { source p.sourceSets.main } } + } + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 269d38b..dedf349 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,10 +103,58 @@ jobs: name: jars-1.21.1 path: neoforge/versions/1.21.1/build/libs/primalpottery-neoforge-1.21.1-*.jar + forge-painted-pot: + name: Forge painted pot ${{ matrix.minecraft }} + runs-on: ubuntu-latest + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: + - minecraft: '1.12.2' + java: '8' + directory: legacy/forge-1.12.2 + build: ./gradlew build + client: ./gradlew -I ../../.github/forge-display-check/check.init.gradle runClient + - minecraft: '1.20.1' + java: '21' + directory: . + build: ./gradlew :forge:build + client: ./gradlew -I .github/forge-display-check/check.init.gradle :forge:runClient + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: ${{ matrix.java }} + - uses: gradle/actions/setup-gradle@v6 + - name: Build production jar + working-directory: ${{ matrix.directory }} + run: ${{ matrix.build }} + - name: Render 200 painted pots on the hosted software renderer + working-directory: ${{ matrix.directory }} + env: + LIBGL_ALWAYS_SOFTWARE: '1' + ALSOFT_DRIVERS: 'null' + run: | + mkdir -p "$GITHUB_WORKSPACE/build/display-check" + printf 'onboardAccessibility:false\nmaxFps:30\npauseOnLostFocus:false\nrenderDistance:5\n' > "$GITHUB_WORKSPACE/build/display-check/options.txt" + timeout 20m xvfb-run -a ${{ matrix.client }} + cat "$GITHUB_WORKSPACE/build/display-check/display-check.txt" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: forge-display-${{ matrix.minecraft }} + path: | + build/display-check/**/*.png + build/display-check/display-check.txt + build/display-check/logs/latest.log + build/display-check/crash-reports/ + all-versions: name: all-versions if: always() - needs: [mc-26-3, mc-1-20-6, mc-1-21-1, release-scripts] + needs: [mc-26-3, mc-1-20-6, mc-1-21-1, forge-painted-pot, release-scripts] runs-on: ubuntu-latest steps: - name: Every check passed diff --git a/README.md b/README.md index d203f1e..815b0b5 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,17 @@ Shape clay on a wheel. -The `main` branch is a Java mod built with Stonecutter. NeoForge covers 1.20.6, 1.21.1, and 26.3. Fabric covers 26.3. Shared sources are written for 26.3. The Forge 1.12 mod remains on the `1.12` branch. +NeoForge covers 1.20.6, 1.21.1, and 26.3. Fabric covers 26.3. Stonecutter keeps their Minecraft integration in `src/`, written for 26.3. The Java 8 library in `core/` owns the pottery profile, classification, dimensions and paint. -`./gradlew collectJars` writes the loader jars to `build/libs//`. +`./gradlew collectJars` collects the Stonecutter loader jars in `build/libs//`. + +## Forge painted-pot preview + +The Forge previews for 1.12.2 and 1.20.1 support one fired vessel per block. Use `/give @p primalpottery:pottery` for a flower-painted jug. Place it, reload the world and harvest it in survival to recover the profile and paint. Both versions use the same disc list and 16 × 16 face pattern. The template editor, wheel and firing recipes are later milestones. + +| Target | Build | Output | +|---|---|---| +| Forge 1.20.1 · Java 17 game | From the root, run `./gradlew :forge:build` with the modern Gradle JDK. | `forge/build/libs/` | +| Forge 1.12.2 · Java 8 game | From `legacy/forge-1.12.2/`, set `JAVA_HOME` to a JDK 8 and run `./gradlew build`. | `legacy/forge-1.12.2/build/libs/` | + +Use `gradlew.bat` on Windows. The Forge directories each contain their own block, saved-data and baked-model adapters. Both compile against the same checkout of `core/` and include it in their production jar. diff --git a/build-logic/src/main/groovy/multiloader-common.gradle b/build-logic/src/main/groovy/multiloader-common.gradle index ef54462..1c57dc4 100644 --- a/build-logic/src/main/groovy/multiloader-common.gradle +++ b/build-logic/src/main/groovy/multiloader-common.gradle @@ -4,6 +4,7 @@ plugins { } // Version projects sit at : for the common code and :: for fabric and neoforge. +evaluationDependsOn(':core') def loaderName = project.parent == rootProject ? 'common' : project.parent.name // The common project for this Minecraft version, e.g. :26.3 for :fabric:26.3. def commonProject = loaderName == 'common' ? project : rootProject.project(":${project.name}") @@ -15,6 +16,7 @@ repositories { } dependencies { + implementation project(':core') // Null annotations: newer Minecraft ships JSpecify, 1.21.1 doesn't. compileOnly 'org.jspecify:jspecify:1.0.0' } @@ -75,6 +77,7 @@ tasks.withType(Jar).configureEach { } jar { + from(project(':core').sourceSets.main.output) manifest { attributes([ diff --git a/core/build.gradle b/core/build.gradle new file mode 100644 index 0000000..4e06a2c --- /dev/null +++ b/core/build.gradle @@ -0,0 +1,11 @@ +plugins { + id 'java-library' +} + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} +if (JavaVersion.current().isJava9Compatible()) { + tasks.withType(JavaCompile).configureEach { options.release = 8 } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java new file mode 100644 index 0000000..f876e38 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java @@ -0,0 +1,49 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** One cache per atlas bake. Chunk builders and the inventory can share an immutable list of native faces. */ +public abstract class BakedVessels { + private static final int MAX_QUADS = 32768; + private final Map> models = new LinkedHashMap<>(16, .75F, true); + private int quads; + + private static final class Key { + final List discs; + final FacePaint paint; + Key(Pottery pot) { discs = pot.discs(); paint = pot.paint(); } + @Override public int hashCode() { return discs.hashCode() * 31 + paint.hashCode(); } + @Override public boolean equals(Object obj) { + if (!(obj instanceof Key)) return false; + Key other = (Key) obj; + return discs.equals(other.discs) && paint.equals(other.paint); + } + } + + public synchronized List model(Pottery pot) { + Key key = new Key(pot); + List cached = models.get(key); + if (cached != null) return cached; + List faces = new ArrayList<>(); + new PaintedVessel(pot, (a, b, c, d, ink) -> faces.add(bake(a, b, c, d, ink))); + List model = Collections.unmodifiableList(faces); + if (model.size() > MAX_QUADS) return model; + Iterator> oldest = models.values().iterator(); + int weight = Math.max(1, model.size()); + while (quads + weight > MAX_QUADS && oldest.hasNext()) { + quads -= Math.max(1, oldest.next().size()); + oldest.remove(); + } + quads += weight; + models.put(key, model); + return model; + } + + protected abstract Q bake(PaintedVessel.Vertex a, PaintedVessel.Vertex b, PaintedVessel.Vertex c, + PaintedVessel.Vertex d, int pigment); +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java similarity index 70% rename from src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java rename to core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java index aca9cc0..6d2ecf3 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java @@ -1,17 +1,41 @@ package net.modcrafters.minecraft.primalpottery.pottery; -import net.minecraft.world.item.DyeColor; +import java.util.Arrays; /** One upright 16 by 16 face, stored once and repeated around the vessel. */ -public record FacePaint(String pixels) { +public final class FacePaint { + private final String pixels; + + public FacePaint(String pixels) { + this.pixels = pixels; + } + + public String pixels() { return pixels; } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof FacePaint)) return false; + FacePaint other = (FacePaint) obj; + return pixels.equals(other.pixels); + } + + @Override + public int hashCode() { return pixels.hashCode(); } + public static final int SIDE = 16; public static final int CELLS = SIDE * SIDE; public static final int COLORS = 16; public static final int ERASE = -1; - public static final FacePaint EMPTY = new FacePaint(".".repeat(CELLS)); + public static final FacePaint EMPTY = new FacePaint(blankPixels()); private static final String FLOWER_INKS = "ipygtsl"; private static final int[] FLOWER_RGB = {0xFFF1CA, 0xEAC89A, 0xF4C04D, 0xCA8338, 0x467D68, 0x62927A, 0x83A979}; + private static String blankPixels() { + char[] pixels = new char[CELLS]; + Arrays.fill(pixels, '.'); + return new String(pixels); + } + public static FacePaint read(String pixels) { if ("flower".equals(pixels)) return readLegacyFlower(); if (pixels.length() != CELLS || !pixels.chars().allMatch(c -> c == '.' || c >= 'A' && c < 'A' + COLORS + FLOWER_RGB.length)) { @@ -44,15 +68,5 @@ public FacePaint with(int cell, int color) { return new FacePaint(next.toString()); } - public static int rgb(int color) { - if (color >= COLORS) { - return FLOWER_RGB[color - COLORS]; - } - //? if >=1.21 { - return DyeColor.byId(color).getTextureDiffuseColor() & 0xFFFFFF; - //?} else { - /*float[] rgb = DyeColor.byId(color).getTextureDiffuseColors(); - return Math.round(rgb[0] * 255) << 16 | Math.round(rgb[1] * 255) << 8 | Math.round(rgb[2] * 255); - *///?} - } + public static int flowerRgb(int color) { return FLOWER_RGB[color - COLORS]; } } diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java new file mode 100644 index 0000000..655e693 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java @@ -0,0 +1,133 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.List; + +/** Bakes a stationary vessel into ordinary chunk faces. Coordinates are in local block units. */ +public final class PaintedVessel { + public static final Pottery SAMPLE = Pottery.jug().withPaint(FacePaint.read("flower")); + public static final int CLAY = -1; + private static final int SIDES = 8; + private static final double UNITS = 32; + private static final double[] X = new double[SIDES + 1]; + private static final double[] Z = new double[SIDES + 1]; + static { + for (int side = 0; side <= SIDES; side++) { + double angle = (side % SIDES + 0.5) * Math.PI / 4; + X[side] = Math.cos(angle) / UNITS; + Z[side] = Math.sin(angle) / UNITS; + } + } + + public interface Faces { + void quad(Vertex a, Vertex b, Vertex c, Vertex d, int pigment); + } + + public static final class Vertex { + public final float x, y, z, u, v; + + Vertex(double x, double y, double z, double u, double v) { + this.x = (float) x; + this.y = (float) y; + this.z = (float) z; + this.u = (float) u; + this.v = (float) v; + } + } + + private final Pottery pot; + private final Faces faces; + private final double paintTop; + private final double paintSpan; + private final int[] nextPaintRow = new int[FacePaint.SIDE]; + + public PaintedVessel(Pottery pot, Faces faces) { + this.pot = pot; + this.faces = faces; + List outside = PotteryProfile.profile(pot.discs(), false); + double middle = pot.height() * 0.48; + paintSpan = Math.min(2 * Math.sin(Math.PI / 8) * PotteryProfile.sample(outside, middle), pot.height() * 0.84); + paintTop = middle + paintSpan / 2; + String pixels = pot.paint().pixels(); + for (int row = FacePaint.SIDE - 1; row >= 0; row--) { + int next = row + 1; + nextPaintRow[row] = next < FacePaint.SIDE && pixels.regionMatches(row * 16, pixels, next * 16, 16) + ? nextPaintRow[next] : next; + } + surface(outside, true); + surface(PotteryProfile.profile(pot.discs(), true), false); + PotteryDisc lip = pot.discs().get(0); + PotteryDisc foot = pot.discs().get(pot.discs().size() - 1); + ring(pot.height(), lip.radius(), lip.innerRadius(), true); + ring(0, foot.radius(), foot.innerRadius(), false); + } + + private void surface(List outline, boolean outside) { + for (int i = 1; i < outline.size(); i++) { + PotteryProfile.Station low = outline.get(i - 1); + PotteryProfile.Station high = outline.get(i); + if (low.y() == high.y()) { + ring(low.y(), Math.max(low.radius(), high.radius()), Math.min(low.radius(), high.radius()), + outside == (low.radius() > high.radius())); + continue; + } + if (low.radius() == 0 && high.radius() == 0) continue; + for (int side = 0; side < SIDES; side++) { + Vertex a = vertex(side, low.radius(), low.y(), 0, 16); + Vertex b = vertex(side + 1, low.radius(), low.y(), 16, 16); + Vertex c = vertex(side + 1, high.radius(), high.y(), 16, 0); + Vertex d = vertex(side, high.radius(), high.y(), 0, 0); + if (outside) { + faces.quad(b, a, d, c, CLAY); + if (!FacePaint.EMPTY.equals(pot.paint())) paint(low, high, side); + } else { + faces.quad(a, b, c, d, CLAY); + } + } + } + } + + private void ring(double y, double outer, double inner, boolean up) { + if (outer <= inner) return; + for (int side = 0; side < SIDES; side++) { + Vertex a = vertex(side, outer, y, 0, 16); + Vertex b = vertex(side + 1, outer, y, 16, 16); + Vertex c = vertex(side + 1, inner, y, 16, 0); + Vertex d = vertex(side, inner, y, 0, 0); + if (up) faces.quad(d, c, b, a, CLAY); + else faces.quad(a, b, c, d, CLAY); + } + } + + private Vertex vertex(int side, double radius, double y, double u, double v) { + return new Vertex(0.5 + X[side] * radius, y / UNITS, 0.5 + Z[side] * radius, u, v); + } + + private Vertex paintVertex(int side, double radius, double y, int column) { + double t = column / 16.0; + double x = X[side + 1] + (X[side] - X[side + 1]) * t; + double z = Z[side + 1] + (Z[side] - Z[side + 1]) * t; + return new Vertex(0.5 + x * radius * 1.003, y / UNITS, 0.5 + z * radius * 1.003, 8, 8); + } + + private void paint(PotteryProfile.Station low, PotteryProfile.Station high, int side) { + if (paintSpan <= 0 || high.y() <= paintTop - paintSpan || low.y() >= paintTop) return; + double slope = (high.radius() - low.radius()) / (high.y() - low.y()); + for (int row = 0; row < FacePaint.SIDE;) { + int end = nextPaintRow[row]; + double top = Math.min(high.y(), paintTop - row * paintSpan / 16); + double bottom = Math.max(low.y(), paintTop - end * paintSpan / 16); + int offset = row * 16; + row = end; + if (top <= bottom) continue; + double r0 = low.radius() + (bottom - low.y()) * slope; + double r1 = low.radius() + (top - low.y()) * slope; + for (int x = 0; x < FacePaint.SIDE;) { + int start = x++; + int ink = pot.paint().color(offset + start); + while (x < 16 && pot.paint().color(offset + x) == ink) x++; + if (ink != FacePaint.ERASE) faces.quad(paintVertex(side, r0, bottom, start), + paintVertex(side, r0, bottom, x), paintVertex(side, r1, top, x), paintVertex(side, r1, top, start), ink); + } + } + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java similarity index 82% rename from src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java rename to core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java index b64d75f..9f1823c 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/Pottery.java @@ -2,9 +2,9 @@ import java.util.ArrayList; import java.util.List; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import org.jspecify.annotations.Nullable; +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.Collectors; public final class Pottery { public static final int TEMPLATE_WALL = 2; @@ -29,7 +29,7 @@ int capacity(double hollow) { if (hollow >= largestHollow - 8 * Math.ulp(largestHollow)) { return this.maxVolume; } - return (int) Math.clamp(Math.round(this.maxVolume * hollow / largestHollow), 1, this.maxVolume - 1); + return (int) Math.max(1, Math.min(Math.round(this.maxVolume * hollow / largestHollow), this.maxVolume - 1)); } public int radius() { @@ -62,7 +62,7 @@ public Pottery(Size size, List discs, FacePaint paint) { public Pottery(Size size, List discs, FacePaint paint, boolean allowPlatter) { this.size = size; - this.discs = List.copyOf(discs); + this.discs = Collections.unmodifiableList(new ArrayList<>(discs)); this.paint = paint; this.height = this.discs.stream().mapToDouble(PotteryDisc::height).sum(); this.widestRadius = this.discs.stream().mapToDouble(PotteryDisc::radius).max().orElse(0); @@ -151,7 +151,7 @@ private boolean hasPlateShape() { for (PotteryDisc disc : discs) { if (disc.radius() - disc.innerRadius() < 0.5) return false; } - return discs.getLast().innerRadius() == 0; + return discs.get(discs.size() - 1).innerRadius() == 0; } /** Edge slots identify plates in saves from before the minimum radius. */ @@ -159,7 +159,7 @@ public Pottery fitSavedPlate() { if (size != Size.SMALL || !hasPlateShape() || widestRadius() >= MIN_PLATE_RADIUS) return this; double width = widestRadius(); return new Pottery(size, discs.stream().map(d -> new PotteryDisc(d.height(), - d.radius() / width * MIN_PLATE_RADIUS, d.innerRadius() / width * MIN_PLATE_RADIUS)).toList(), paint); + d.radius() / width * MIN_PLATE_RADIUS, d.innerRadius() / width * MIN_PLATE_RADIUS)).collect(Collectors.toList()), paint); } public int paintColumns() { @@ -218,11 +218,38 @@ public static double cavityArea(double innerRadius) { * Where a lid is drawn. {@code top} is the pot's top, {@code layer} is the top disc's height, * and {@code radius} is the fitted plate radius. The lid is not stored on the profile. */ - public record Cover(double top, double layer, double radius) { + public static final class Cover { + private final double top; + private final double layer; + private final double radius; + + public Cover(double top, double layer, double radius) { + this.top = top; + this.layer = layer; + this.radius = radius; + } + + public double top() { return top; } + + public double layer() { return layer; } + + public double radius() { return radius; } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Cover)) return false; + Cover other = (Cover) obj; + return Double.compare(top, other.top) == 0 + && Double.compare(layer, other.layer) == 0 + && Double.compare(radius, other.radius) == 0; + } + + @Override + public int hashCode() { return java.util.Objects.hash(top, layer, radius); } } /** The rim a lid can cover, or null when the profile has no open mouth. */ - public @Nullable Cover cover() { + public Cover cover() { if (isPlate()) return null; int rim = this.rimIndex(); if (rim < 0) { @@ -240,7 +267,7 @@ public record Cover(double top, double layer, double radius) { /** * The lid plate: one pixel thick, and fitted to the rim. Null when {@link #cover()} is null. */ - public @Nullable PotteryDisc lidDisc() { + public PotteryDisc lidDisc() { Cover cover = this.cover(); if (cover == null) { return null; @@ -281,55 +308,6 @@ private static PotteryType vesselType(double openingRadius, double maxRadius) { return PotteryType.JAR; } - public CompoundTag save() { - CompoundTag tag = new CompoundTag(); - ListTag list = new ListTag(); - for (PotteryDisc disc : this.discs) { - CompoundTag discTag = new CompoundTag(); - discTag.putDouble("height", disc.height()); - discTag.putDouble("radius", disc.radius()); - discTag.putDouble("inner", disc.innerRadius()); - list.add(discTag); - } - tag.put("discs", list); - if (!FacePaint.EMPTY.equals(this.paint)) { - tag.putString("paint", this.paint.pixels()); - } - if (this.size == Size.LARGE) { - tag.putBoolean("large", true); - if (isPlatter()) tag.putBoolean("platter", true); - } - return tag; - } - - public static Pottery load(CompoundTag tag) { - Pottery loaded = readProfile(tag); - return loaded == null ? display() : loaded; - } - - public static @Nullable Pottery readProfile(CompoundTag tag) { - Size size = Nbt.getBoolean(tag, "large") ? Size.LARGE : Size.SMALL; - List discs = new ArrayList<>(); - ListTag list = Nbt.list(tag, "discs"); - if (list.size() > MAX_DISCS) { - return null; - } - for (int index = 0; index < list.size(); index++) { - CompoundTag discTag = Nbt.compoundAt(list, index); - double radius = Nbt.getDouble(discTag, "radius"); - double inner = Nbt.getDouble(discTag, "inner"); - // Older editors allowed the inner brush to cross the outer edge, producing a zero-width wall. - if (inner > radius && inner <= size.radius()) { - inner = radius; - } - discs.add(new PotteryDisc(Nbt.getDouble(discTag, "height"), radius, inner)); - } - String paint = Nbt.getString(tag, "paint"); - // Wide, shallow large vessels made before platters retain their capacity and fitted lid. - return validProfile(size, discs) ? new Pottery(size, discs, FacePaint.read(paint), - Nbt.getBoolean(tag, "platter")) : null; - } - /** The pot a wheel forms: the installed template, or the plain vase when none is installed. */ public static Pottery formed(Pottery template) { return template == null ? wheelShape() : template; @@ -340,7 +318,7 @@ public static Pottery formed(Pottery template) { * Progress at least 1 returns {@code target}. Below 0 is 0. * The result keeps the target's disc count and heights. */ - public static Pottery shaped(@Nullable Pottery start, Pottery target, double progress) { + public static Pottery shaped(Pottery start, Pottery target, double progress) { if (progress >= 1) { return target; } @@ -376,7 +354,7 @@ public double height() { /** Resample the silhouette into editable unit rings, keeping the lip and foot at the ends. */ public Pottery withHeight(int height) { - int rows = Math.clamp(height, 1, this.size.units); + int rows = Math.max(1, Math.min(height, this.size.units)); double originalHeight = this.height(); List rings = new ArrayList<>(rows); for (int i = 0; i < rows; i++) { @@ -411,7 +389,7 @@ private static PotteryDisc sample(Pottery start, double point, double total) { * Discs run from the lip down to the foot. */ public static Pottery jug() { - return new Pottery(List.of( + return new Pottery(Arrays.asList( new PotteryDisc(1.0, 3.4, 2.2), new PotteryDisc(1.5, 2.6, 1.6), new PotteryDisc(2.0, 4.2, 3.0), @@ -429,6 +407,28 @@ public static Pottery display() { return jug(); } - public record Info(PotteryType type, int volume) { + public static final class Info { + private final PotteryType type; + private final int volume; + + public Info(PotteryType type, int volume) { + this.type = type; + this.volume = volume; + } + + public PotteryType type() { return type; } + + public int volume() { return volume; } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Info)) return false; + Info other = (Info) obj; + return type == other.type + && volume == other.volume; + } + + @Override + public int hashCode() { return java.util.Objects.hash(type, volume); } } } diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryCodec.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryCodec.java new file mode 100644 index 0000000..2314daa --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryCodec.java @@ -0,0 +1,57 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.ArrayList; +import java.util.List; + +/** The pottery payload inside an item or block entity. Each game supplies its native tag operations. */ +public abstract class PotteryCodec { + protected abstract T compound(); + protected abstract L list(); + protected abstract L discs(T tag); + protected abstract int size(L list); + protected abstract T at(L list, int index); + protected abstract void append(L list, T tag); + protected abstract void writeDiscs(T tag, L discs); + protected abstract void number(T tag, String key, double value); + protected abstract double number(T tag, String key); + protected abstract void flag(T tag, String key); + protected abstract boolean flagged(T tag, String key); + protected abstract void text(T tag, String key, String value); + protected abstract String text(T tag, String key); + + public final T encode(Pottery pot) { + T tag = compound(); + L rings = list(); + for (PotteryDisc ring : pot.discs()) { + T disc = compound(); + number(disc, "height", ring.height()); + number(disc, "radius", ring.radius()); + number(disc, "inner", ring.innerRadius()); + append(rings, disc); + } + writeDiscs(tag, rings); + if (!FacePaint.EMPTY.equals(pot.paint())) text(tag, "paint", pot.paint().pixels()); + if (pot.size() == Pottery.Size.LARGE) flag(tag, "large"); + if (pot.isPlatter()) flag(tag, "platter"); + return tag; + } + + /** Returns null for a malformed or absent profile so each caller can choose its fallback. */ + public final Pottery decode(T tag) { + Pottery.Size size = flagged(tag, "large") ? Pottery.Size.LARGE : Pottery.Size.SMALL; + L rings = discs(tag); + int count = size(rings); + if (count > Pottery.MAX_DISCS) return null; + List result = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + T disc = at(rings, i); + double radius = number(disc, "radius"); + double inner = number(disc, "inner"); + // Early editors could save a zero-width wall with crossed brushes. + if (inner > radius && inner <= size.radius()) inner = radius; + result.add(new PotteryDisc(number(disc, "height"), radius, inner)); + } + if (!Pottery.validProfile(size, result)) return null; + return new Pottery(size, result, FacePaint.read(text(tag, "paint")), flagged(tag, "platter")); + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java new file mode 100644 index 0000000..cb8d52f --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java @@ -0,0 +1,38 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +public final class PotteryDisc { + private final double height; + private final double radius; + private final double innerRadius; + + public PotteryDisc(double height, double radius, double innerRadius) { + this.height = height; + this.radius = radius; + this.innerRadius = innerRadius; + } + + public PotteryDisc(double height, double radius) { + this(height, radius, 0); + } + + public double height() { return height; } + + public double radius() { return radius; } + + public double innerRadius() { return innerRadius; } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof PotteryDisc)) return false; + PotteryDisc other = (PotteryDisc) obj; + return Double.compare(height, other.height) == 0 + && Double.compare(radius, other.radius) == 0 + && Double.compare(innerRadius, other.innerRadius) == 0; + } + + @Override + public int hashCode() { + int hash = 31 * Double.hashCode(height) + Double.hashCode(radius); + return 31 * hash + Double.hashCode(innerRadius); + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryProfile.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryProfile.java similarity index 86% rename from src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryProfile.java rename to core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryProfile.java index 837344b..a788d75 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryProfile.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryProfile.java @@ -20,7 +20,29 @@ public static double clampedInner(PotteryDisc disc) { private static final double SLOPE_REACH = Pottery.PIXEL * 2; private static final int SLOPE_STEPS = 4; - public record Station(double y, double radius) { + public static final class Station { + private final double y; + private final double radius; + + public Station(double y, double radius) { + this.y = y; + this.radius = radius; + } + + public double y() { return y; } + + public double radius() { return radius; } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Station)) return false; + Station other = (Station) obj; + return Double.compare(y, other.y) == 0 + && Double.compare(radius, other.radius) == 0; + } + + @Override + public int hashCode() { return java.util.Objects.hash(y, radius); } } private static final class Slope { @@ -52,8 +74,7 @@ public static boolean slopes(PotteryDisc below, PotteryDisc above, boolean inner } public static List profile(List discs, boolean inner) { - List rising = discs.reversed(); - int count = rising.size(); + int count = discs.size(); List stations = new ArrayList<>(); if (count == 0) { return stations; @@ -62,17 +83,17 @@ public static List profile(List discs, boolean inner) { double[] radius = new double[count]; double y = 0; for (int index = 0; index < count; index++) { - y += Math.max(0, rising.get(index).height()); + y += Math.max(0, discs.get(count - 1 - index).height()); y1[index] = y; - radius[index] = inner ? clampedInner(rising.get(index)) : clayRadius(rising.get(index)); + radius[index] = inner ? clampedInner(discs.get(count - 1 - index)) : clayRadius(discs.get(count - 1 - index)); } double top = y; List slopes = new ArrayList<>(); double sectionBase = 0; int firstSlope = 0; for (int index = 0; index < count - 1; index++) { - PotteryDisc belowDisc = rising.get(index); - PotteryDisc aboveDisc = rising.get(index + 1); + PotteryDisc belowDisc = discs.get(count - 1 - index); + PotteryDisc aboveDisc = discs.get(count - 2 - index); // A floor or a gap ends the continuous shell. Easing cannot cross that face. if ((clampedInner(belowDisc) > 0) != (clampedInner(aboveDisc) > 0) || clayRadius(belowDisc) == 0 || clayRadius(aboveDisc) == 0) { @@ -89,8 +110,8 @@ public static List profile(List discs, boolean inner) { continue; } double joint = y1[index]; - double below = Math.max(Math.max(0, rising.get(index).height()) / 2.0, SLOPE_REACH); - double above = Math.max(Math.max(0, rising.get(index + 1).height()) / 2.0, SLOPE_REACH); + double below = Math.max(Math.max(0, discs.get(count - 1 - index).height()) / 2.0, SLOPE_REACH); + double above = Math.max(Math.max(0, discs.get(count - 2 - index).height()) / 2.0, SLOPE_REACH); slopes.add(new Slope(index, joint, radius[index], radius[index + 1], Math.max(sectionBase, joint - below), joint + above)); } for (int index = 0; index < slopes.size() - 1; index++) { @@ -210,6 +231,6 @@ public static double fillHeight(List wall, double remaining) { } remaining -= segment; } - return wall.getLast().y; + return wall.get(wall.size() - 1).y; } } diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java new file mode 100644 index 0000000..92a1956 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java @@ -0,0 +1,50 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.Locale; + +public enum PotteryType { + LUMP("Just a lump of clay"), + LUMP_NO_BOTTOM("A pipe?"), + LUMP_THIN("Too thin!"), + PLATE("A plate!"), + PLATTER("A serving platter!"), + POT("A bowl!"), + JAR("Pottery"), + JUG("A jug!"); + + private final String label; + + PotteryType(String label) { + this.label = label; + } + + public String label() { + return this.label; + } + + public boolean isVessel() { + return this == POT || this == JAR || this == JUG; + } + + public String tooltipKey() { + PotteryType type = isServingDish() || this.isVessel() ? this : LUMP; + return "pottery.primalpottery.type." + type.name().toLowerCase(Locale.ROOT); + } + + public boolean isServingDish() { + return this == PLATE || this == PLATTER; + } + + /** Wide mouth is a bowl, narrow mouth is a jug, and every other shape is pottery. */ + public String shapeKey() { + String shape; + switch (this) { + case PLATE: shape = "plate"; break; + case PLATTER: shape = "platter"; break; + case JUG: shape = "jug"; break; + case POT: shape = "bowl"; break; + default: shape = "pottery"; break; + } + return "pottery.primalpottery.shape." + shape; + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java new file mode 100644 index 0000000..dcb5bb4 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java @@ -0,0 +1,51 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.Vertex; + +/** Packs cached block-model vertices. Each Forge adapter supplies its atlas UVs, native stride and quad factory. */ +public abstract class VesselQuadPacker extends BakedVessels { + private final S clay; + private final S inks; + private final int stride; + + protected VesselQuadPacker(S clay, S inks, int stride) { + this.clay = clay; + this.inks = inks; + this.stride = stride; + } + + protected abstract float u(S sprite, float pixels); + protected abstract float v(S sprite, float pixels); + protected abstract Q quad(int[] data, S sprite, float nx, float ny, float nz); + + @Override protected final Q bake(Vertex a, Vertex b, Vertex c, Vertex d, int pigment) { + // Diagonals also give floor triangles a normal when their two centre vertices coincide. + float ax = c.x - a.x, ay = c.y - a.y, az = c.z - a.z; + float bx = d.x - b.x, by = d.y - b.y, bz = d.z - b.z; + float nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx; + float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); + int normal = length == 0 ? 0 : pack(nx / length) | pack(ny / length) << 8 | pack(nz / length) << 16; + S sprite = pigment == PaintedVessel.CLAY ? clay : inks; + int[] data = new int[stride * 4]; + write(data, 0, a, sprite, normal, pigment); + write(data, stride, b, sprite, normal, pigment); + write(data, stride * 2, c, sprite, normal, pigment); + write(data, stride * 3, d, sprite, normal, pigment); + return quad(data, sprite, nx, ny, nz); + } + + private void write(int[] data, int index, Vertex point, S sprite, int normal, int pigment) { + // Each ink occupies one cell in the 8-column, 4-row palette. Sample its centre at every vertex. + float x = pigment < 0 ? point.u : (pigment % 8 + .5F) * 2; + float y = pigment < 0 ? point.v : (pigment / 8 + .5F) * 4; + data[index] = Float.floatToRawIntBits(point.x); + data[index + 1] = Float.floatToRawIntBits(point.y); + data[index + 2] = Float.floatToRawIntBits(point.z); + data[index + 3] = 0xffffffff; + data[index + 4] = Float.floatToRawIntBits(u(sprite, x)); + data[index + 5] = Float.floatToRawIntBits(v(sprite, y)); + data[index + stride - 1] = normal; + } + + private static int pack(float value) { return Math.round(value * 127) & 255; } +} diff --git a/forge/build.gradle b/forge/build.gradle new file mode 100644 index 0000000..9562b27 --- /dev/null +++ b/forge/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'java' + id 'net.neoforged.moddev.legacyforge' +} + +evaluationDependsOn(':core') +java.toolchain.languageVersion = JavaLanguageVersion.of(17) +base.archivesName = 'primalpottery-forge-1.20.1' +dependencies { + implementation project(':core') +} +jar { + manifest.attributes('Implementation-Version': project.version) + from(project(':core').sourceSets.main.output) + from(rootProject.file('LICENSE')) +} +processResources { + from(rootProject.file('src/main/resources')) { include 'assets/primalpottery/textures/block/fired_clay.png' } +} + +legacyForge { + version = '1.20.1-47.1.3' + mods { + primalpottery { + sourceSet sourceSets.main + sourceSet project(':core').sourceSets.main + } + } + runs { + client { client() } + server { server() } + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgePotteryTags.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgePotteryTags.java new file mode 100644 index 0000000..2c7ca7b --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgePotteryTags.java @@ -0,0 +1,33 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryCodec; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; + +public final class ForgePotteryTags extends PotteryCodec { + private static final ForgePotteryTags CODEC = new ForgePotteryTags(); + + public static CompoundTag save(Pottery pot) { return CODEC.encode(pot); } + public static Pottery readProfile(CompoundTag tag) { return CODEC.decode(tag); } + + public static Pottery load(CompoundTag tag) { + Pottery profile = readProfile(tag); + return profile == null ? PaintedVessel.SAMPLE : profile; + } + + protected CompoundTag compound() { return new CompoundTag(); } + protected ListTag list() { return new ListTag(); } + protected ListTag discs(CompoundTag tag) { return tag.getList("discs", 10); } + protected int size(ListTag list) { return list.size(); } + protected CompoundTag at(ListTag list, int i) { return list.getCompound(i); } + protected void append(ListTag list, CompoundTag disc) { list.add(disc); } + protected void writeDiscs(CompoundTag tag, ListTag discs) { tag.put("discs", discs); } + protected void number(CompoundTag tag, String key, double value) { tag.putDouble(key, value); } + protected double number(CompoundTag tag, String key) { return tag.getDouble(key); } + protected void flag(CompoundTag tag, String key) { tag.putBoolean(key, true); } + protected boolean flagged(CompoundTag tag, String key) { return tag.getBoolean(key); } + protected void text(CompoundTag tag, String key, String value) { tag.putString(key, value); } + protected String text(CompoundTag tag, String key) { return tag.getString(key); } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java new file mode 100644 index 0000000..244f77f --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java @@ -0,0 +1,41 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseEntityBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.RenderShape; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.storage.loot.LootParams; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.VoxelShape; + +public final class PaintedPotBlock extends BaseEntityBlock { + private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 8, 12); + PaintedPotBlock() { super(Properties.of().strength(0.5F).noOcclusion()); } + + @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new PaintedPotEntity(pos, state); } + @Override public RenderShape getRenderShape(BlockState state) { return RenderShape.MODEL; } + @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { return SHAPE; } + + @Override public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) { + if (!level.isClientSide && level.getBlockEntity(pos) instanceof PaintedPotEntity pot) pot.install(stack); + } + + @Override public List getDrops(BlockState state, LootParams.Builder loot) { + return loot.getOptionalParameter(LootContextParams.BLOCK_ENTITY) instanceof PaintedPotEntity pot + ? List.of(pot.pickup()) : List.of(new ItemStack(this)); + } + + @Override public ItemStack getCloneItemStack(BlockState state, HitResult hit, BlockGetter level, BlockPos pos, Player player) { + return level.getBlockEntity(pos) instanceof PaintedPotEntity pot ? pot.pickup() : new ItemStack(this); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java new file mode 100644 index 0000000..2d097e8 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java @@ -0,0 +1,60 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.client.model.data.ModelData; +import net.minecraftforge.client.model.data.ModelProperty; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PaintedPotEntity extends BlockEntity { + public static final ModelProperty PROFILE = new ModelProperty<>(); + private Pottery pot = PaintedVessel.SAMPLE; + + PaintedPotEntity(BlockPos pos, BlockState state) { + super(PrimalPotteryForge.ENTITY.get(), pos, state); + } + + public static Pottery fromStack(ItemStack stack) { + CompoundTag tag = stack.getTagElement("pottery"); + return tag == null ? PaintedVessel.SAMPLE : ForgePotteryTags.load(tag); + } + + void install(ItemStack stack) { + pot = fromStack(stack); + setChanged(); + level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 3); + } + + ItemStack pickup() { + ItemStack result = new ItemStack(PrimalPotteryForge.ITEM.get()); + result.addTagElement("pottery", ForgePotteryTags.save(pot)); + return result; + } + + @Override public ModelData getModelData() { return ModelData.builder().with(PROFILE, pot).build(); } + + @Override protected void saveAdditional(CompoundTag tag) { + super.saveAdditional(tag); + tag.put("pottery", ForgePotteryTags.save(pot)); + } + + @Override public void load(CompoundTag tag) { + super.load(tag); + pot = ForgePotteryTags.load(tag.getCompound("pottery")); + if (level != null && level.isClientSide) { + requestModelDataUpdate(); + level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 8); + } + } + + @Override public CompoundTag getUpdateTag() { return saveWithoutMetadata(); } + + @Override public ClientboundBlockEntityDataPacket getUpdatePacket() { + return ClientboundBlockEntityDataPacket.create(this); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java new file mode 100644 index 0000000..d435761 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java @@ -0,0 +1,31 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.registries.DeferredRegister; +import net.minecraftforge.registries.ForgeRegistries; +import net.minecraftforge.registries.RegistryObject; + +@Mod("primalpottery") +public final class PrimalPotteryForge { + private static final String MOD_ID = "primalpottery"; + private static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID); + private static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID); + private static final DeferredRegister> ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MOD_ID); + + static final RegistryObject POT = BLOCKS.register("pottery", PaintedPotBlock::new); + static final RegistryObject ITEM = ITEMS.register("pottery", () -> new BlockItem(POT.get(), new Item.Properties().stacksTo(1))); + static final RegistryObject> ENTITY = ENTITIES.register("pottery", + () -> BlockEntityType.Builder.of(PaintedPotEntity::new, POT.get()).build(null)); + + public PrimalPotteryForge() { + IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); + BLOCKS.register(bus); + ITEMS.register(bus); + ENTITIES.register(bus); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java new file mode 100644 index 0000000..dfe123a --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java @@ -0,0 +1,73 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import com.mojang.blaze3d.vertex.PoseStack; +import java.util.List; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.ModelEvent; +import net.minecraftforge.client.model.BakedModelWrapper; +import net.minecraftforge.client.model.data.ModelData; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +@Mod.EventBusSubscriber(modid = "primalpottery", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) +public final class PotteryModel extends BakedModelWrapper { + private static final ResourceLocation INKS = new ResourceLocation("primalpottery", "block/pottery_inks"); + private final PotteryQuads bakery; + private final List item; + private final ItemOverrides overrides = new ItemOverrides() { + @Override public BakedModel resolve(BakedModel model, ItemStack stack, ClientLevel world, LivingEntity entity, int seed) { + return new PotteryModel(originalModel, bakery, bakery.model(PaintedPotEntity.fromStack(stack))); + } + }; + + private PotteryModel(BakedModel base, PotteryQuads bakery, List item) { + super(base); + this.bakery = bakery; + this.item = item; + } + + @SubscribeEvent public static void register(ModelEvent.RegisterAdditional event) { event.register(INKS); } + + @SubscribeEvent public static void bake(ModelEvent.ModifyBakingResult event) { + var inks = event.getModels().get(INKS).getParticleIcon(); + event.getModels().replaceAll((key, base) -> { + if (!key.getNamespace().equals("primalpottery") || !key.getPath().equals("pottery")) return base; + var bakery = new PotteryQuads(base.getParticleIcon(), inks); + return new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE)); + }); + } + + @Override public ItemOverrides getOverrides() { return overrides; } + + @Override public List getQuads(BlockState state, Direction side, RandomSource random) { + return side == null ? item : List.of(); + } + + @Override public List getQuads(BlockState state, Direction side, RandomSource random, ModelData data, RenderType type) { + if (side != null) return List.of(); + Pottery profile = data.get(PaintedPotEntity.PROFILE); + return profile == null ? item : bakery.model(profile); + } + + @Override public List getRenderPasses(ItemStack stack, boolean fabulous) { return List.of(this); } + + @Override public BakedModel applyTransform(ItemDisplayContext context, PoseStack pose, boolean leftHand) { + getTransforms().getTransform(context).apply(leftHand, pose); + return this; + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java new file mode 100644 index 0000000..fd951a4 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java @@ -0,0 +1,19 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; +import net.modcrafters.minecraft.primalpottery.pottery.VesselQuadPacker; + +final class PotteryQuads extends VesselQuadPacker { + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks) { + super(clay, inks, 8); + } + + @Override protected float u(TextureAtlasSprite sprite, float pixels) { return sprite.getU(pixels); } + @Override protected float v(TextureAtlasSprite sprite, float pixels) { return sprite.getV(pixels); } + + @Override protected BakedQuad quad(int[] vertices, TextureAtlasSprite sprite, float nx, float ny, float nz) { + return new BakedQuad(vertices, -1, Direction.getNearest(nx, ny, nz), sprite, true); + } +} diff --git a/forge/src/main/resources/META-INF/mods.toml b/forge/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..6ec0832 --- /dev/null +++ b/forge/src/main/resources/META-INF/mods.toml @@ -0,0 +1,14 @@ +modLoader="javafml" +loaderVersion="[47,)" +license="MIT" +[[mods]] +modId="primalpottery" +version="${file.jarVersion}" +displayName="Primal Pottery" +description="Shape clay on a wheel. Forge preview with placeable painted pottery." +[[dependencies.primalpottery]] +modId="minecraft" +mandatory=true +versionRange="[1.20.1,1.20.2)" +ordering="NONE" +side="BOTH" diff --git a/forge/src/main/resources/assets/primalpottery/blockstates/pottery.json b/forge/src/main/resources/assets/primalpottery/blockstates/pottery.json new file mode 100644 index 0000000..17f87c3 --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/blockstates/pottery.json @@ -0,0 +1 @@ +{"variants":{"":{"model":"primalpottery:block/pottery"}}} diff --git a/forge/src/main/resources/assets/primalpottery/lang/en_us.json b/forge/src/main/resources/assets/primalpottery/lang/en_us.json new file mode 100644 index 0000000..bd44227 --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/lang/en_us.json @@ -0,0 +1 @@ +{"block.primalpottery.pottery":"Painted Pottery"} diff --git a/forge/src/main/resources/assets/primalpottery/models/block/pottery.json b/forge/src/main/resources/assets/primalpottery/models/block/pottery.json new file mode 100644 index 0000000..e1d3924 --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/models/block/pottery.json @@ -0,0 +1,8 @@ +{ + "parent": "block/block", + "textures": {"particle": "primalpottery:block/fired_clay"}, + "display": { + "gui": {"rotation": [30, 45, 0], "translation": [0, 4, 0], "scale": [1.75, 1.75, 1.75]}, + "ground": {"translation": [0, 4, 0], "scale": [1, 1, 1]} + } +} diff --git a/forge/src/main/resources/assets/primalpottery/models/block/pottery_inks.json b/forge/src/main/resources/assets/primalpottery/models/block/pottery_inks.json new file mode 100644 index 0000000..dcb6b1a --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/models/block/pottery_inks.json @@ -0,0 +1 @@ +{"textures":{"particle":"primalpottery:block/pottery_inks"}} diff --git a/forge/src/main/resources/assets/primalpottery/models/item/pottery.json b/forge/src/main/resources/assets/primalpottery/models/item/pottery.json new file mode 100644 index 0000000..cdc7cd8 --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/models/item/pottery.json @@ -0,0 +1 @@ +{"parent":"primalpottery:block/pottery"} diff --git a/forge/src/main/resources/assets/primalpottery/textures/block/pottery_inks.png b/forge/src/main/resources/assets/primalpottery/textures/block/pottery_inks.png new file mode 100644 index 0000000000000000000000000000000000000000..77485fcf1c19912a103119f643bdb16cce7d8c0e GIT binary patch literal 396 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1SEZ8zRh7^U<~$jaSW-r_4cBnmlGqy@rUJH z+uOHTm|1vU5i^ZcILqrB>!>MkPbE*c@daZMS4>os*Q9_k+a{re0pa5D`#Whz5g*T{L|0AxLYAtTYI}(4`>;wph1cuZS(aP$4aDZv+7;u z$DdogdUx5Ezro7C{%#SCou+<~R0DzP9b_5W-)dETw(b1)_m$iFReoQteop>!__V^V qs@Lw~ndF$r%P>jB6BWI@U(T|CPsU^Y%YxM)BRyUHT-G@yGywptrDu!) literal 0 HcmV?d00001 diff --git a/forge/src/main/resources/pack.mcmeta b/forge/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..1001729 --- /dev/null +++ b/forge/src/main/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"pack_format":15,"description":"Primal Pottery"}} diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle new file mode 100644 index 0000000..f696589 --- /dev/null +++ b/legacy/forge-1.12.2/build.gradle @@ -0,0 +1,48 @@ +buildscript { + repositories { + maven { url = 'https://maven.minecraftforge.net/' } + mavenCentral() + } + dependencies { classpath 'net.minecraftforge.gradle:ForgeGradle:3.0.197' } +} +apply plugin: 'net.minecraftforge.gradle' +apply plugin: 'java' + +def modProperties = new Properties() +file('../../gradle.properties').withInputStream { modProperties.load(it) } +version = modProperties.version +sourceCompatibility = targetCompatibility = '1.8' +project(':core').buildDir = file('build/core') +evaluationDependsOn(':core') + +minecraft { + mappings channel: 'snapshot', version: '20171003-1.12' + runs { + client { workingDirectory project.file('run/client') } + server { workingDirectory project.file('run/server') } + } +} +dependencies { + minecraft 'net.minecraftforge:forge:1.12.2-14.23.5.2864' + implementation project(':core') +} +// MCP's merged development jar contains an extra Side.BUKKIT value which stock FML cannot initialize. +// Use Forge's corrected pair of side markers only on the userdev launch classpath (ForgeGradle #748). +configurations { devSideMarkers } +dependencies { devSideMarkers 'net.minecraftforge:mergetool:0.2.3.3:forge@jar' } +tasks.withType(JavaExec).matching { it.name in ['runClient', 'runServer'] }.configureEach { + doFirst { classpath = configurations.devSideMarkers + classpath } +} +jar { + from(project(':core').sourceSets.main.output) + from('../../LICENSE') + finalizedBy 'reobfJar' +} +processResources { + inputs.property 'version', version + filesMatching('mcmod.info') { expand(version: project.version) } + from('../../src/main/resources') { include 'assets/primalpottery/textures/block/fired_clay.png' } + from('../../forge/src/main/resources') { + include 'assets/primalpottery/models/**', 'assets/primalpottery/textures/block/pottery_inks.png' + } +} diff --git a/legacy/forge-1.12.2/gradle/wrapper/gradle-wrapper.jar b/legacy/forge-1.12.2/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..0d4a9516871afd710a9d84d89e31ba77745607bd GIT binary patch literal 54413 zcmafaV|Zr4wq`oEZQHiZj%|LijZQlLf{tz5M#r{o+fI6V=G-$g=gzrzeyqLskF}nv zRZs0&c;EUi2L_G~0s;*U0szbL-0C3_3~ zRZ#mYf6f1oqJoH`jHHCB8l!^by~4z}yc`4LEP@;Z?bO6{g9`Hk+s@(L1jC5Tq{1Yf z4E;CQvrx0-gF+peRxFC*gF=&$zNYjO?K|gN=WqXMz`tYs@0o%B{dRD+{C_6(f9t^g zhmNJQv6-#;f2)f2uc{u-#*U8W&i{|ewYN^n_1~cv|1J!}zc&$eaBy{T{cEpa46s*q zHFkD2cV;xTHFj}{*3kBt*FgS4A5SI|$F%$gB@It9FlC}D3y`sbZG{2P6gGwC$U`6O zb_cId9AhQl#A<&=x>-xDD%=Ppt$;y71@Lwsl{x943#T@8*?cbR<~d`@@}4V${+r$jICUIOzgZJy_9I zu*eA(F)$~J07zX%tmQN}1^wj+RM|9bbwhQA=xrPE*{vB_P!pPYT5{Or^m*;Qz#@Bl zRywCG_RDyM6bf~=xn}FtiFAw|rrUxa1+z^H`j6e|GwKDuq}P)z&@J>MEhsVBvnF|O zOEm)dADU1wi8~mX(j_8`DwMT_OUAnjbWYer;P*^Uku_qMu3}qJU zTAkza-K9aj&wcsGuhQ>RQoD?gz~L8RwCHOZDzhBD$az*$TQ3!uygnx_rsXG`#_x5t zn*lb(%JI3%G^MpYp-Y(KI4@_!&kBRa3q z|Fzn&3R%ZsoMNEn4pN3-BSw2S_{IB8RzRv(eQ1X zyBQZHJ<(~PfUZ~EoI!Aj`9k<+Cy z2DtI<+9sXQu!6&-Sk4SW3oz}?Q~mFvy(urUy<)x!KQ>#7yIPC)(ORhKl7k)4eSy~} z7#H3KG<|lt68$tk^`=yjev%^usOfpQ#+Tqyx|b#dVA(>fPlGuS@9ydo z!Cs#hse9nUETfGX-7lg;F>9)+ml@M8OO^q|W~NiysX2N|2dH>qj%NM`=*d3GvES_# zyLEHw&1Fx<-dYxCQbk_wk^CI?W44%Q9!!9aJKZW-bGVhK?N;q`+Cgc*WqyXcxZ%U5QXKu!Xn)u_dxeQ z;uw9Vysk!3OFzUmVoe)qt3ifPin0h25TU zrG*03L~0|aaBg7^YPEW^Yq3>mSNQgk-o^CEH?wXZ^QiPiuH}jGk;75PUMNquJjm$3 zLcXN*uDRf$Jukqg3;046b;3s8zkxa_6yAlG{+7{81O3w96i_A$KcJhD&+oz1<>?lun#C3+X0q zO4JxN{qZ!e#FCl@e_3G?0I^$CX6e$cy7$BL#4<`AA)Lw+k`^15pmb-447~5lkSMZ` z>Ce|adKhb-F%yy!vx>yQbXFgHyl(an=x^zi(!-~|k;G1=E(e@JgqbAF{;nv`3i)oi zDeT*Q+Mp{+NkURoabYb9@#Bi5FMQnBFEU?H{~9c;g3K%m{+^hNe}(MdpPb?j9`?2l z#%AO!|2QxGq7-2Jn2|%atvGb(+?j&lmP509i5y87`9*BSY++<%%DXb)kaqG0(4Eft zj|2!Od~2TfVTi^0dazAIeVe&b#{J4DjN6;4W;M{yWj7#+oLhJyqeRaO;>?%mX>Ec{Mp~;`bo}p;`)@5dA8fNQ38FyMf;wUPOdZS{U*8SN6xa z-kq3>*Zos!2`FMA7qjhw-`^3ci%c91Lh`;h{qX1r;x1}eW2hYaE*3lTk4GwenoxQ1kHt1Lw!*N8Z%DdZSGg5~Bw}+L!1#d$u+S=Bzo7gi zqGsBV29i)Jw(vix>De)H&PC; z-t2OX_ak#~eSJ?Xq=q9A#0oaP*dO7*MqV;dJv|aUG00UX=cIhdaet|YEIhv6AUuyM zH1h7fK9-AV)k8sr#POIhl+?Z^r?wI^GE)ZI=H!WR<|UI(3_YUaD#TYV$Fxd015^mT zpy&#-IK>ahfBlJm-J(n(A%cKV;)8&Y{P!E|AHPtRHk=XqvYUX?+9po4B$0-6t74UUef${01V{QLEE8gzw* z5nFnvJ|T4dlRiW9;Ed_yB{R@)fC=zo4hCtD?TPW*WJmMXYxN_&@YQYg zBQ$XRHa&EE;YJrS{bn7q?}Y&DH*h;){5MmE(9A6aSU|W?{3Ox%5fHLFScv7O-txuRbPG1KQtI`Oay=IcEG=+hPhlnYC;`wSHeo|XGio0aTS6&W($E$ z?N&?TK*l8;Y^-xPl-WVZwrfdiQv10KdsAb9u-*1co*0-Z(h#H)k{Vc5CT!708cs%sExvPC+7-^UY~jTfFq=cj z!Dmy<+NtKp&}}$}rD{l?%MwHdpE(cPCd;-QFPk1`E5EVNY2i6E`;^aBlx4}h*l42z zpY#2cYzC1l6EDrOY*ccb%kP;k8LHE3tP>l3iK?XZ%FI<3666yPw1rM%>eCgnv^JS_ zK7c~;g7yXt9fz@(49}Dj7VO%+P!eEm& z;z8UXs%NsQ%@2S5nve)@;yT^61BpVlc}=+i6{ZZ9r7<({yUYqe==9*Z+HguP3`sA& z{`inI4G)eLieUQ*pH9M@)u7yVnWTQva;|xq&-B<>MoP(|xP(HqeCk1&h>DHNLT>Zi zQ$uH%s6GoPAi0~)sC;`;ngsk+StYL9NFzhFEoT&Hzfma1f|tEnL0 zMWdX4(@Y*?*tM2@H<#^_l}BC&;PYJl%~E#veQ61{wG6!~nyop<^e)scV5#VkGjYc2 z$u)AW-NmMm%T7WschOnQ!Hbbw&?`oMZrJ&%dVlN3VNra1d0TKfbOz{dHfrCmJ2Jj= zS#Gr}JQcVD?S9X!u|oQ7LZ+qcq{$40 ziG5=X^+WqeqxU00YuftU7o;db=K+Tq!y^daCZgQ)O=M} zK>j*<3oxs=Rcr&W2h%w?0Cn3);~vqG>JO_tTOzuom^g&^vzlEjkx>Sv!@NNX%_C!v zaMpB>%yVb}&ND9b*O>?HxQ$5-%@xMGe4XKjWh7X>CYoRI2^JIwi&3Q5UM)?G^k8;8 zmY$u;(KjZx>vb3fe2zgD7V;T2_|1KZQW$Yq%y5Ioxmna9#xktcgVitv7Sb3SlLd6D zfmBM9Vs4rt1s0M}c_&%iP5O{Dnyp|g1(cLYz^qLqTfN6`+o}59Zlu%~oR3Q3?{Bnr zkx+wTpeag^G12fb_%SghFcl|p2~<)Av?Agumf@v7y-)ecVs`US=q~=QG%(_RTsqQi z%B&JdbOBOmoywgDW|DKR5>l$1^FPhxsBrja<&}*pfvE|5dQ7j-wV|ur%QUCRCzBR3q*X`05O3U@?#$<>@e+Zh&Z&`KfuM!0XL& zI$gc@ZpM4o>d&5)mg7+-Mmp98K^b*28(|Ew8kW}XEV7k^vnX-$onm9OtaO@NU9a|as7iA%5Wrw9*%UtJYacltplA5}gx^YQM` zVkn`TIw~avq)mIQO0F0xg)w$c)=8~6Jl|gdqnO6<5XD)&e7z7ypd3HOIR+ss0ikSVrWar?548HFQ*+hC)NPCq*;cG#B$7 z!n?{e9`&Nh-y}v=nK&PR>PFdut*q&i81Id`Z<0vXUPEbbJ|<~_D!)DJMqSF~ly$tN zygoa)um~xdYT<7%%m!K8+V(&%83{758b0}`b&=`))Tuv_)OL6pf=XOdFk&Mfx9y{! z6nL>V?t=#eFfM$GgGT8DgbGRCF@0ZcWaNs_#yl+6&sK~(JFwJmN-aHX{#Xkpmg;!} zgNyYYrtZdLzW1tN#QZAh!z5>h|At3m+ryJ-DFl%V>w?cmVTxt^DsCi1ZwPaCe*D{) z?#AZV6Debz{*D#C2>44Czy^yT3y92AYDcIXtZrK{L-XacVl$4i=X2|K=Fy5vAzhk{ zu3qG=qSb_YYh^HirWf~n!_Hn;TwV8FU9H8+=BO)XVFV`nt)b>5yACVr!b98QlLOBDY=^KS<*m9@_h3;64VhBQzb_QI)gbM zSDto2i*iFrvxSmAIrePB3i`Ib>LdM8wXq8(R{-)P6DjUi{2;?}9S7l7bND4w%L2!; zUh~sJ(?Yp}o!q6)2CwG*mgUUWlZ;xJZo`U`tiqa)H4j>QVC_dE7ha0)nP5mWGB268 zn~MVG<#fP#R%F=Ic@(&Va4dMk$ysM$^Avr1&hS!p=-7F>UMzd(M^N9Ijb|364}qcj zcIIh7suk$fQE3?Z^W4XKIPh~|+3(@{8*dSo&+Kr(J4^VtC{z*_{2}ld<`+mDE2)S| zQ}G#Q0@ffZCw!%ZGc@kNoMIdQ?1db%N1O0{IPPesUHI;(h8I}ETudk5ESK#boZgln z(0kvE`&6z1xH!s&={%wQe;{^&5e@N0s7IqR?L*x%iXM_czI5R1aU?!bA7)#c4UN2u zc_LZU+@elD5iZ=4*X&8%7~mA;SA$SJ-8q^tL6y)d150iM)!-ry@TI<=cnS#$kJAS# zq%eK**T*Wi2OlJ#w+d_}4=VN^A%1O+{?`BK00wkm)g8;u?vM;RR+F1G?}({ENT3i= zQsjJkp-dmJ&3-jMNo)wrz0!g*1z!V7D(StmL(A}gr^H-CZ~G9u?*Uhcx|x7rb`v^X z9~QGx;wdF4VcxCmEBp$F#sms@MR?CF67)rlpMxvwhEZLgp2?wQq|ci#rLtrYRV~iR zN?UrkDDTu114&d~Utjcyh#tXE_1x%!dY?G>qb81pWWH)Ku@Kxbnq0=zL#x@sCB(gs zm}COI(!{6-XO5li0>1n}Wz?w7AT-Sp+=NQ1aV@fM$`PGZjs*L+H^EW&s!XafStI!S zzgdntht=*p#R*o8-ZiSb5zf6z?TZr$^BtmIfGAGK;cdg=EyEG)fc*E<*T=#a?l=R5 zv#J;6C(umoSfc)W*EODW4z6czg3tXIm?x8{+8i^b;$|w~k)KLhJQnNW7kWXcR^sol z1GYOp?)a+}9Dg*nJ4fy*_riThdkbHO37^csfZRGN;CvQOtRacu6uoh^gg%_oEZKDd z?X_k67s$`|Q&huidfEonytrq!wOg07H&z@`&BU6D114p!rtT2|iukF}>k?71-3Hk< zs6yvmsMRO%KBQ44X4_FEYW~$yx@Y9tKrQ|rC1%W$6w}-9!2%4Zk%NycTzCB=nb)r6*92_Dg+c0;a%l1 zsJ$X)iyYR2iSh|%pIzYV1OUWER&np{w1+RXb~ zMUMRymjAw*{M)UtbT)T!kq5ZAn%n=gq3ssk3mYViE^$paZ;c^7{vXDJ`)q<}QKd2?{r9`X3mpZ{AW^UaRe2^wWxIZ$tuyKzp#!X-hXkHwfD zj@2tA--vFi3o_6B?|I%uwD~emwn0a z+?2Lc1xs(`H{Xu>IHXpz=@-84uw%dNV;{|c&ub|nFz(=W-t4|MME(dE4tZQi?0CE|4_?O_dyZj1)r zBcqB8I^Lt*#)ABdw#yq{OtNgf240Jvjm8^zdSf40 z;H)cp*rj>WhGSy|RC5A@mwnmQ`y4{O*SJ&S@UFbvLWyPdh)QnM=(+m3p;0&$^ysbZ zJt!ZkNQ%3hOY*sF2_~-*`aP|3Jq7_<18PX*MEUH*)t{eIx%#ibC|d&^L5FwoBN}Oe z?!)9RS@Zz%X1mqpHgym75{_BM4g)k1!L{$r4(2kL<#Oh$Ei7koqoccI3(MN1+6cDJ zp=xQhmilz1?+ZjkX%kfn4{_6K_D{wb~rdbkh!!k!Z@cE z^&jz55*QtsuNSlGPrU=R?}{*_8?4L7(+?>?(^3Ss)f!ou&{6<9QgH>#2$?-HfmDPN z6oIJ$lRbDZb)h-fFEm^1-v?Slb8udG{7GhbaGD_JJ8a9f{6{TqQN;m@$&)t81k77A z?{{)61za|e2GEq2)-OqcEjP`fhIlUs_Es-dfgX-3{S08g`w=wGj2{?`k^GD8d$}6Z zBT0T1lNw~fuwjO5BurKM593NGYGWAK%UCYiq{$p^GoYz^Uq0$YQ$j5CBXyog8(p_E znTC+$D`*^PFNc3Ih3b!2Lu|OOH6@46D)bbvaZHy%-9=$cz}V^|VPBpmPB6Ivzlu&c zPq6s7(2c4=1M;xlr}bkSmo9P`DAF>?Y*K%VPsY`cVZ{mN&0I=jagJ?GA!I;R)i&@{ z0Gl^%TLf_N`)`WKs?zlWolWvEM_?{vVyo(!taG$`FH2bqB`(o50pA=W34kl-qI62lt z1~4LG_j%sR2tBFteI{&mOTRVU7AH>>-4ZCD_p6;-J<=qrod`YFBwJz(Siu(`S}&}1 z6&OVJS@(O!=HKr-Xyzuhi;swJYK*ums~y1ePdX#~*04=b9)UqHHg;*XJOxnS6XK#j zG|O$>^2eW2ZVczP8#$C`EpcWwPFX4^}$omn{;P(fL z>J~%-r5}*D3$Kii z34r@JmMW2XEa~UV{bYP=F;Y5=9miJ+Jw6tjkR+cUD5+5TuKI`mSnEaYE2=usXNBs9 zac}V13%|q&Yg6**?H9D620qj62dM+&&1&a{NjF}JqmIP1I1RGppZ|oIfR}l1>itC% zl>ed${{_}8^}m2^br*AIX$L!Vc?Sm@H^=|LnpJg`a7EC+B;)j#9#tx-o0_e4!F5-4 zF4gA;#>*qrpow9W%tBzQ89U6hZ9g=-$gQpCh6Nv_I0X7t=th2ajJ8dBbh{i)Ok4{I z`Gacpl?N$LjC$tp&}7Sm(?A;;Nb0>rAWPN~@3sZ~0_j5bR+dz;Qs|R|k%LdreS3Nn zp*36^t#&ASm=jT)PIjNqaSe4mTjAzlAFr*@nQ~F+Xdh$VjHWZMKaI+s#FF#zjx)BJ zufxkW_JQcPcHa9PviuAu$lhwPR{R{7CzMUi49=MaOA%ElpK;A)6Sgsl7lw)D$8FwE zi(O6g;m*86kcJQ{KIT-Rv&cbv_SY4 zpm1|lSL*o_1LGOlBK0KuU2?vWcEcQ6f4;&K=&?|f`~X+s8H)se?|~2HcJo{M?Ity) zE9U!EKGz2^NgB6Ud;?GcV*1xC^1RYIp&0fr;DrqWLi_Kts()-#&3|wz{wFQsKfnnsC||T?oIgUp z{O(?Df7&vW!i#_~*@naguLLjDAz+)~*_xV2iz2?(N|0y8DMneikrT*dG`mu6vdK`% z=&nX5{F-V!Reau}+w_V3)4?}h@A@O)6GCY7eXC{p-5~p8x{cH=hNR;Sb{*XloSZ_%0ZKYG=w<|!vy?spR4!6mF!sXMUB5S9o_lh^g0!=2m55hGR; z-&*BZ*&;YSo474=SAM!WzrvjmNtq17L`kxbrZ8RN419e=5CiQ-bP1j-C#@@-&5*(8 zRQdU~+e(teUf}I3tu%PB1@Tr{r=?@0KOi3+Dy8}+y#bvgeY(FdN!!`Kb>-nM;7u=6 z;0yBwOJ6OdWn0gnuM{0`*fd=C(f8ASnH5aNYJjpbY1apTAY$-%)uDi$%2)lpH=#)=HH z<9JaYwPKil@QbfGOWvJ?cN6RPBr`f+jBC|-dO|W@x_Vv~)bmY(U(!cs6cnhe0z31O z>yTtL4@KJ*ac85u9|=LFST22~!lb>n7IeHs)_(P_gU}|8G>{D_fJX)8BJ;Se? z67QTTlTzZykb^4!{xF!=C}VeFd@n!9E)JAK4|vWVwWop5vSWcD<;2!88v-lS&ve7C zuYRH^85#hGKX(Mrk};f$j_V&`Nb}MZy1mmfz(e`nnI4Vpq(R}26pZx?fq%^|(n~>* z5a5OFtFJJfrZmgjyHbj1`9||Yp?~`p2?4NCwu_!!*4w8K`&G7U_|np&g7oY*-i;sI zu)~kYH;FddS{7Ri#Z5)U&X3h1$Mj{{yk1Q6bh4!7!)r&rqO6K~{afz@bis?*a56i& zxi#(Ss6tkU5hDQJ0{4sKfM*ah0f$>WvuRL zunQ-eOqa3&(rv4kiQ(N4`FO6w+nko_HggKFWx@5aYr}<~8wuEbD(Icvyl~9QL^MBt zSvD)*C#{2}!Z55k1ukV$kcJLtW2d~%z$t0qMe(%2qG`iF9K_Gsae7OO%Tf8E>ooch ztAw01`WVv6?*14e1w%Wovtj7jz_)4bGAqqo zvTD|B4)Ls8x7-yr6%tYp)A7|A)x{WcI&|&DTQR&2ir(KGR7~_RhNOft)wS<+vQ*|sf;d>s zEfl&B^*ZJp$|N`w**cXOza8(ARhJT{O3np#OlfxP9Nnle4Sto)Fv{w6ifKIN^f1qO*m8+MOgA1^Du!=(@MAh8)@wU8t=Ymh!iuT_lzfm za~xEazL-0xwy9$48!+?^lBwMV{!Gx)N>}CDi?Jwax^YX@_bxl*+4itP;DrTswv~n{ zZ0P>@EB({J9ZJ(^|ptn4ks^Z2UI&87d~J_^z0&vD2yb%*H^AE!w= zm&FiH*c%vvm{v&i3S>_hacFH${|(2+q!`X~zn4$aJDAry>=n|{C7le(0a)nyV{kAD zlud4-6X>1@-XZd`3SKKHm*XNn_zCyKHmf*`C_O509$iy$Wj`Sm3y?nWLCDy>MUx1x zl-sz7^{m(&NUk*%_0(G^>wLDnXW90FzNi$Tu6* z<+{ePBD`%IByu977rI^x;gO5M)Tfa-l*A2mU-#IL2?+NXK-?np<&2rlF;5kaGGrx2 zy8Xrz`kHtTVlSSlC=nlV4_oCsbwyVHG4@Adb6RWzd|Otr!LU=% zEjM5sZ#Ib4#jF(l!)8Na%$5VK#tzS>=05GpV?&o* z3goH1co0YR=)98rPJ~PuHvkA59KUi#i(Mq_$rApn1o&n1mUuZfFLjx@3;h`0^|S##QiTP8rD`r8P+#D@gvDJh>amMIl065I)PxT6Hg(lJ?X7*|XF2Le zv36p8dWHCo)f#C&(|@i1RAag->5ch8TY!LJ3(+KBmLxyMA%8*X%_ARR*!$AL66nF= z=D}uH)D)dKGZ5AG)8N-;Il*-QJ&d8u30&$_Q0n1B58S0ykyDAyGa+BZ>FkiOHm1*& zNOVH;#>Hg5p?3f(7#q*dL74;$4!t?a#6cfy#}9H3IFGiCmevir5@zXQj6~)@zYrWZ zRl*e66rjwksx-)Flr|Kzd#Bg>We+a&E{h7bKSae9P~ z(g|zuXmZ zD?R*MlmoZ##+0c|cJ(O{*h(JtRdA#lChYhfsx25(Z`@AK?Q-S8_PQqk z>|Z@Ki1=wL1_c6giS%E4YVYD|Y-{^ZzFwB*yN8-4#+TxeQ`jhks7|SBu7X|g=!_XL z`mY=0^chZfXm%2DYHJ4z#soO7=NONxn^K3WX={dV>$CTWSZe@<81-8DVtJEw#Uhd3 zxZx+($6%4a&y_rD8a&E`4$pD6-_zZJ%LEE*1|!9uOm!kYXW< zOBXZAowsX-&$5C`xgWkC43GcnY)UQt2Qkib4!!8Mh-Q!_M%5{EC=Gim@_;0+lP%O^ zG~Q$QmatQk{Mu&l{q~#kOD;T-{b1P5u7)o-QPPnqi?7~5?7%IIFKdj{;3~Hu#iS|j z)Zoo2wjf%+rRj?vzWz(6JU`=7H}WxLF*|?WE)ci7aK?SCmd}pMW<{#1Z!_7BmVP{w zSrG>?t}yNyCR%ZFP?;}e8_ zRy67~&u11TN4UlopWGj6IokS{vB!v!n~TJYD6k?~XQkpiPMUGLG2j;lh>Eb5bLTkX zx>CZlXdoJsiPx=E48a4Fkla>8dZYB%^;Xkd(BZK$z3J&@({A`aspC6$qnK`BWL;*O z-nRF{XRS`3Y&b+}G&|pE1K-Ll_NpT!%4@7~l=-TtYRW0JJ!s2C-_UsRBQ=v@VQ+4> z*6jF0;R@5XLHO^&PFyaMDvyo?-lAD(@H61l-No#t@at@Le9xOgTFqkc%07KL^&iss z!S2Ghm)u#26D(e1Q7E;L`rxOy-N{kJ zTgfw}az9=9Su?NEMMtpRlYwDxUAUr8F+P=+9pkX4%iA4&&D<|=B|~s*-U+q6cq`y* zIE+;2rD7&D5X;VAv=5rC5&nP$E9Z3HKTqIFCEV%V;b)Y|dY?8ySn|FD?s3IO>VZ&&f)idp_7AGnwVd1Z znBUOBA}~wogNpEWTt^1Rm-(YLftB=SU|#o&pT7vTr`bQo;=ZqJHIj2MP{JuXQPV7% z0k$5Ha6##aGly<}u>d&d{Hkpu?ZQeL_*M%A8IaXq2SQl35yW9zs4^CZheVgHF`%r= zs(Z|N!gU5gj-B^5{*sF>;~fauKVTq-Ml2>t>E0xl9wywD&nVYZfs1F9Lq}(clpNLz z4O(gm_i}!k`wUoKr|H#j#@XOXQ<#eDGJ=eRJjhOUtiKOG;hym-1Hu)1JYj+Kl*To<8( za1Kf4_Y@Cy>eoC59HZ4o&xY@!G(2p^=wTCV>?rQE`Upo^pbhWdM$WP4HFdDy$HiZ~ zRUJFWTII{J$GLVWR?miDjowFk<1#foE3}C2AKTNFku+BhLUuT>?PATB?WVLzEYyu+ zM*x((pGdotzLJ{}R=OD*jUexKi`mb1MaN0Hr(Wk8-Uj0zA;^1w2rmxLI$qq68D>^$ zj@)~T1l@K|~@YJ6+@1vlWl zHg5g%F{@fW5K!u>4LX8W;ua(t6YCCO_oNu}IIvI6>Fo@MilYuwUR?9p)rKNzDmTAN zzN2d>=Za&?Z!rJFV*;mJ&-sBV80%<-HN1;ciLb*Jk^p?u<~T25%7jjFnorfr={+wm zzl5Q6O>tsN8q*?>uSU6#xG}FpAVEQ_++@}G$?;S7owlK~@trhc#C)TeIYj^N(R&a} zypm~c=fIs;M!YQrL}5{xl=tUU-Tfc0ZfhQuA-u5(*w5RXg!2kChQRd$Fa8xQ0CQIU zC`cZ*!!|O!*y1k1J^m8IIi|Sl3R}gm@CC&;4840^9_bb9%&IZTRk#=^H0w%`5pMDCUef5 zYt-KpWp2ijh+FM`!zZ35>+7eLN;s3*P!bp%-oSx34fdTZ14Tsf2v7ZrP+mitUx$rS zW(sOi^CFxe$g3$x45snQwPV5wpf}>5OB?}&Gh<~i(mU&ss#7;utaLZ!|KaTHniGO9 zVC9OTzuMKz)afey_{93x5S*Hfp$+r*W>O^$2ng|ik!<`U1pkxm3*)PH*d#>7md1y} zs7u^a8zW8bvl92iN;*hfOc-=P7{lJeJ|3=NfX{(XRXr;*W3j845SKG&%N zuBqCtDWj*>KooINK1 zFPCsCWr!-8G}G)X*QM~34R*k zmRmDGF*QE?jCeNfc?k{w<}@29e}W|qKJ1K|AX!htt2|B`nL=HkC4?1bEaHtGBg}V( zl(A`6z*tck_F$4;kz-TNF%7?=20iqQo&ohf@S{_!TTXnVh}FaW2jxAh(DI0f*SDG- z7tqf5X@p#l?7pUNI(BGi>n_phw=lDm>2OgHx-{`T>KP2YH9Gm5ma zb{>7>`tZ>0d5K$j|s2!{^sFWQo3+xDb~#=9-jp(1ydI3_&RXGB~rxWSMgDCGQG)oNoc#>)td zqE|X->35U?_M6{^lB4l(HSN|`TC2U*-`1jSQeiXPtvVXdN-?i1?d#;pw%RfQuKJ|e zjg75M+Q4F0p@8I3ECpBhGs^kK;^0;7O@MV=sX^EJLVJf>L;GmO z3}EbTcoom7QbI(N8ad!z(!6$!MzKaajSRb0c+ZDQ($kFT&&?GvXmu7+V3^_(VJx1z zP-1kW_AB&_A;cxm*g`$ z#Pl@Cg{siF0ST2-w)zJkzi@X)5i@)Z;7M5ewX+xcY36IaE0#flASPY2WmF8St0am{ zV|P|j9wqcMi%r-TaU>(l*=HxnrN?&qAyzimA@wtf;#^%{$G7i4nXu=Pp2#r@O~wi)zB>@25A*|axl zEclXBlXx1LP3x0yrSx@s-kVW4qlF+idF+{M7RG54CgA&soDU-3SfHW@-6_ z+*;{n_SixmGCeZjHmEE!IF}!#aswth_{zm5Qhj0z-@I}pR?cu=P)HJUBClC;U+9;$#@xia30o$% zDw%BgOl>%vRenxL#|M$s^9X}diJ9q7wI1-0n2#6>@q}rK@ng(4M68(t52H_Jc{f&M9NPxRr->vj-88hoI?pvpn}llcv_r0`;uN>wuE{ z&TOx_i4==o;)>V4vCqG)A!mW>dI^Ql8BmhOy$6^>OaUAnI3>mN!Zr#qo4A>BegYj` zNG_)2Nvy2Cqxs1SF9A5HHhL7sai#Umw%K@+riaF+q)7&MUJvA&;$`(w)+B@c6!kX@ zzuY;LGu6|Q2eu^06PzSLspV2v4E?IPf`?Su_g8CX!75l)PCvyWKi4YRoRThB!-BhG zubQ#<7oCvj@z`^y&mPhSlbMf0<;0D z?5&!I?nV-jh-j1g~&R(YL@c=KB_gNup$8abPzXZN`N|WLqxlN)ZJ+#k4UWq#WqvVD z^|j+8f5uxTJtgcUscKTqKcr?5g-Ih3nmbvWvvEk})u-O}h$=-p4WE^qq7Z|rLas0$ zh0j&lhm@Rk(6ZF0_6^>Rd?Ni-#u1y`;$9tS;~!ph8T7fLlYE{P=XtWfV0Ql z#z{_;A%p|8+LhbZT0D_1!b}}MBx9`R9uM|+*`4l3^O(>Mk%@ha>VDY=nZMMb2TnJ= zGlQ+#+pmE98zuFxwAQcVkH1M887y;Bz&EJ7chIQQe!pgWX>(2ruI(emhz@_6t@k8Z zqFEyJFX2PO`$gJ6p$=ku{7!vR#u+$qo|1r;orjtp9FP^o2`2_vV;W&OT)acRXLN^m zY8a;geAxg!nbVu|uS8>@Gvf@JoL&GP`2v4s$Y^5vE32&l;2)`S%e#AnFI-YY7_>d#IKJI!oL6e z_7W3e=-0iz{bmuB*HP+D{Nb;rn+RyimTFqNV9Bzpa0?l`pWmR0yQOu&9c0S*1EPr1 zdoHMYlr>BycjTm%WeVuFd|QF8I{NPT&`fm=dITj&3(M^q ze2J{_2zB;wDME%}SzVWSW6)>1QtiX)Iiy^p2eT}Ii$E9w$5m)kv(3wSCNWq=#DaKZ zs%P`#^b7F-J0DgQ1?~2M`5ClYtYN{AlU|v4pEg4z03=g6nqH`JjQuM{k`!6jaIL_F zC;sn?1x?~uMo_DFg#ypNeie{3udcm~M&bYJ1LI zE%y}P9oCX3I1Y9yhF(y9Ix_=8L(p)EYr&|XZWCOb$7f2qX|A4aJ9bl7pt40Xr zXUT#NMBB8I@xoIGSHAZkYdCj>eEd#>a;W-?v4k%CwBaR5N>e3IFLRbDQTH#m_H+4b zk2UHVymC`%IqwtHUmpS1!1p-uQB`CW1Y!+VD!N4TT}D8(V0IOL|&R&)Rwj@n8g@=`h&z9YTPDT+R9agnwPuM!JW~=_ya~% zIJ*>$Fl;y7_`B7G4*P!kcy=MnNmR`(WS5_sRsvHF42NJ;EaDram5HwQ4Aw*qbYn0j;#)bh1lyKLg#dYjN*BMlh+fxmCL~?zB;HBWho;20WA==ci0mAqMfyG>1!HW zO7rOga-I9bvut1Ke_1eFo9tbzsoPTXDW1Si4}w3fq^Z|5LGf&egnw%DV=b11$F=P~ z(aV+j8S}m=CkI*8=RcrT>GmuYifP%hCoKY22Z4 zmu}o08h3YhcXx-v-QC??8mDn<+}+*X{+gZH-I;G^|7=1fBveS?J$27H&wV5^V^P$! z84?{UeYSmZ3M!@>UFoIN?GJT@IroYr;X@H~ax*CQ>b5|Xi9FXt5j`AwUPBq`0sWEJ z3O|k+g^JKMl}L(wfCqyMdRj9yS8ncE7nI14Tv#&(?}Q7oZpti{Q{Hw&5rN-&i|=fWH`XTQSu~1jx(hqm$Ibv zRzFW9$xf@oZAxL~wpj<0ZJ3rdPAE=0B>G+495QJ7D>=A&v^zXC9)2$$EnxQJ<^WlV zYKCHb1ZzzB!mBEW2WE|QG@&k?VXarY?umPPQ|kziS4{EqlIxqYHP!HN!ncw6BKQzKjqk!M&IiOJ9M^wc~ZQ1xoaI z;4je%ern~?qi&J?eD!vTl__*kd*nFF0n6mGEwI7%dI9rzCe~8vU1=nE&n4d&8}pdL zaz`QAY?6K@{s2x%Sx%#(y+t6qLw==>2(gb>AksEebXv=@ht>NBpqw=mkJR(c?l7vo z&cV)hxNoYPGqUh9KAKT)kc(NqekzE6(wjjotP(ac?`DJF=Sb7^Xet-A3PRl%n&zKk zruT9cS~vV1{%p>OVm1-miuKr<@rotj*5gd$?K`oteNibI&K?D63RoBjw)SommJ5<4 zus$!C8aCP{JHiFn2>XpX&l&jI7E7DcTjzuLYvON2{rz<)#$HNu(;ie-5$G<%eLKnTK7QXfn(UR(n+vX%aeS6!q6kv z!3nzY76-pdJp339zsl_%EI|;ic_m56({wdc(0C5LvLULW=&tWc5PW-4;&n+hm1m`f zzQV0T>OPSTjw=Ox&UF^y< zarsYKY8}YZF+~k70=olu$b$zdLaozBE|QE@H{_R21QlD5BilYBTOyv$D5DQZ8b1r- zIpSKX!SbA0Pb5#cT)L5!KpxX+x+8DRy&`o-nj+nmgV6-Gm%Fe91R1ca3`nt*hRS|^ z<&we;TJcUuPDqkM7k0S~cR%t7a`YP#80{BI$e=E!pY}am)2v3-Iqk2qvuAa1YM>xj#bh+H2V z{b#St2<;Gg>$orQ)c2a4AwD5iPcgZ7o_}7xhO86(JSJ(q(EWKTJDl|iBjGEMbX8|P z4PQHi+n(wZ_5QrX0?X_J)e_yGcTM#E#R^u_n8pK@l5416`c9S=q-e!%0RjoPyTliO zkp{OC@Ep^#Ig-n!C)K0Cy%8~**Vci8F1U(viN{==KU0nAg2(+K+GD_Gu#Bx!{tmUm zCwTrT(tCr6X8j43_n96H9%>>?4akSGMvgd+krS4wRexwZ1JxrJy!Uhz#yt$-=aq?A z@?*)bRZxjG9OF~7d$J0cwE_^CLceRK=LvjfH-~{S><^D;6B2&p-02?cl?|$@>`Qt$ zP*iaOxg<+(rbk>34VQDQpNQ|a9*)wScu!}<{oXC87hRPqyrNWpo?#=;1%^D2n2+C* zKKQH;?rWn-@%Y9g%NHG&lHwK9pBfV1a`!TqeU_Fv8s6_(@=RHua7`VYO|!W&WL*x= zIWE9eQaPq3zMaXuf)D0$V`RIZ74f)0P73xpeyk4)-?8j;|K%pD$eq4j2%tL=;&+E91O(2p91K|85b)GQcbRe&u6Ilu@SnE={^{Ix1Eqgv8D z4=w65+&36|;5WhBm$!n*!)ACCwT9Sip#1_z&g~E1kB=AlEhO0lu`Ls@6gw*a)lzc# zKx!fFP%eSBBs)U>xIcQKF(r_$SWD3TD@^^2Ylm=kC*tR+I@X>&SoPZdJ2fT!ysjH% z-U%|SznY8Fhsq7Vau%{Ad^Pvbf3IqVk{M2oD+w>MWimJA@VSZC$QooAO3 zC=DplXdkyl>mSp^$zk7&2+eoGQ6VVh_^E#Z3>tX7Dmi<2aqlM&YBmK&U}m>a%8)LQ z8v+c}a0QtXmyd%Kc2QNGf8TK?_EK4wtRUQ*VDnf5jHa?VvH2K(FDZOjAqYufW8oIZ z31|o~MR~T;ZS!Lz%8M0*iVARJ>_G2BXEF8(}6Dmn_rFV~5NI`lJjp`Mi~g7~P%H zO`S&-)Fngo3VXDMo7ImlaZxY^s!>2|csKca6!|m7)l^M0SQT1_L~K29%x4KV8*xiu zwP=GlyIE9YPSTC0BV`6|#)30=hJ~^aYeq7d6TNfoYUkk-^k0!(3qp(7Mo-$|48d8Z2d zrsfsRM)y$5)0G`fNq!V?qQ+nh0xwFbcp{nhW%vZ?h);=LxvM(pWd9FG$Bg1;@Bv)mKDW>AP{ol zD(R~mLzdDrBv$OSi{E%OD`Ano=F^vwc)rNb*Bg3-o)bbAgYE=M7Gj2OHY{8#pM${_^ zwkU|tnTKawxUF7vqM9UfcQ`V49zg78V%W)$#5ssR}Rj7E&p(4_ib^?9luZPJ%iJTvW&-U$nFYky>KJwHpEHHx zVEC;!ETdkCnO|${Vj#CY>LLut_+c|(hpWk8HRgMGRY%E--%oKh@{KnbQ~0GZd}{b@ z`J2qHBcqqjfHk^q=uQL!>6HSSF3LXL*cCd%opM|k#=xTShX~qcxpHTW*BI!c3`)hQq{@!7^mdUaG7sFsFYnl1%blslM;?B8Q zuifKqUAmR=>33g~#>EMNfdye#rz@IHgpM$~Z7c5@bO@S>MyFE3_F}HVNLnG0TjtXU zJeRWH^j5w_qXb$IGs+E>daTa}XPtrUnnpTRO9NEx4g6uaFEfHP9gW;xZnJi{oqAH~ z5dHS(ch3^hbvkv@u3QPLuWa}ImaElDrmIc%5HN<^bwej}3+?g) z-ai7D&6Iq_P(}k`i^4l?hRLbCb>X9iq2UYMl=`9U9Rf=3Y!gnJbr?eJqy>Zpp)m>Ae zcQ4Qfs&AaE?UDTODcEj#$_n4KeERZHx-I+E5I~E#L_T3WI3cj$5EYR75H7hy%80a8Ej?Y6hv+fR6wHN%_0$-xL!eI}fdjOK7(GdFD%`f%-qY@-i@fTAS&ETI99jUVg8 zslPSl#d4zbOcrgvopvB2c2A6r^pEr&Sa5I5%@1~BpGq`Wo|x=&)WnnQjE+)$^U-wW zr2Kv?XJby(8fcn z8JgPn)2_#-OhZ+;72R6PspMfCVvtLxFHeb7d}fo(GRjm_+R(*?9QRBr+yPF(iPO~ zA4Tp1<0}#fa{v0CU6jz}q9;!3Pew>ikG1qh$5WPRTQZ~ExQH}b1hDuzRS1}65uydS z~Te*3@?o8fih=mZ`iI!hL5iv3?VUBLQv0X zLtu58MIE7Jbm?)NFUZuMN2_~eh_Sqq*56yIo!+d_zr@^c@UwR&*j!fati$W<=rGGN zD$X`$lI%8Qe+KzBU*y3O+;f-Csr4$?3_l+uJ=K@dxOfZ?3APc5_x2R=a^kLFoxt*_ z4)nvvP+(zwlT5WYi!4l7+HKqzmXKYyM9kL5wX$dTSFSN&)*-&8Q{Q$K-})rWMin8S zy*5G*tRYNqk7&+v;@+>~EIQgf_SB;VxRTQFcm5VtqtKZ)x=?-f+%OY(VLrXb^6*aP zP&0Nu@~l2L!aF8i2!N~fJiHyxRl?I1QNjB)`uP_DuaU?2W;{?0#RGKTr2qH5QqdhK zP__ojm4WV^PUgmrV)`~f>(769t3|13DrzdDeXxqN6XA|_GK*;zHU()a(20>X{y-x| z2P6Ahq;o=)Nge`l+!+xEwY`7Q(8V=93A9C+WS^W%p&yR)eiSX+lp)?*7&WSYSh4i> zJa6i5T9o;Cd5z%%?FhB?J{l+t_)c&_f86gZMU{HpOA=-KoU5lIL#*&CZ_66O5$3?# ztgjGLo`Y7bj&eYnK#5x1trB_6tpu4$EomotZLb*9l6P(JmqG`{z$?lNKgq?GAVhkA zvw!oFhLyX=$K=jTAMwDQ)E-8ZW5$X%P2$YB5aq!VAnhwGv$VR&;Ix#fu%xlG{|j_K zbEYL&bx%*YpXcaGZj<{Y{k@rsrFKh7(|saspt?OxQ~oj_6En(&!rTZPa7fLCEU~mA zB7tbVs=-;cnzv*#INgF_9f3OZhp8c5yk!Dy1+`uA7@eJfvd~g34~wKI1PW%h(y&nA zRwMni12AHEw36)C4Tr-pt6s82EJa^8N#bjy??F*rg4fS@?6^MbiY3;7x=gd~G|Hi& zwmG+pAn!aV>>nNfP7-Zn8BLbJm&7}&ZX+$|z5*5{{F}BRSxN=JKZTa#{ut$v0Z0Fs za@UjXo#3!wACv+p9k*^9^n+(0(YKIUFo`@ib@bjz?Mh8*+V$`c%`Q>mrc5bs4aEf4 zh0qtL1qNE|xQ9JrM}qE>X>Y@dQ?%` zBx(*|1FMzVY&~|dE^}gHJ37O9bjnk$d8vKipgcf+As(kt2cbxAR3^4d0?`}}hYO*O z{+L&>G>AYaauAxE8=#F&u#1YGv%`d*v+EyDcU2TnqvRE33l1r}p#Vmcl%n>NrYOqV z2Car_^^NsZ&K=a~bj%SZlfxzHAxX$>=Q|Zi;E0oyfhgGgqe1Sd5-E$8KV9=`!3jWZCb2crb;rvQ##iw}xm7Da za!H${ls5Ihwxkh^D)M<4Yy3bp<-0a+&KfV@CVd9X6Q?v)$R3*rfT@jsedSEhoV(vqv?R1E8oWV;_{l_+_6= zLjV^-bZU$D_ocfSpRxDGk*J>n4G6s-e>D8JK6-gA>aM^Hv8@)txvKMi7Pi#DS5Y?r zK0%+L;QJdrIPXS2 ztjWAxkSwt2xG$L)Zb7F??cjs!KCTF+D{mZ5e0^8bdu_NLgFHTnO*wx!_8#}NO^mu{FaYeCXGjnUgt_+B-Ru!2_Ue-0UPg2Y)K3phLmR<4 zqUCWYX!KDU!jYF6c?k;;vF@Qh^q(PWwp1ez#I+0>d7V(u_h|L+kX+MN1f5WqMLn!L z!c(pozt7tRQi&duH8n=t-|d)c^;%K~6Kpyz(o53IQ_J+aCapAif$Ek#i0F9U>i+94 zFb=OH5(fk-o`L(o|DyQ(hlozl*2cu#)Y(D*zgNMi1Z!DTex#w#)x(8A-T=S+eByJW z%-k&|XhdZOWjJ&(FTrZNWRm^pHEot_MRQ_?>tKQ&MB~g(&D_e>-)u|`Ot(4j=UT6? zQ&YMi2UnCKlBpwltP!}8a2NJ`LlfL=k8SQf69U)~=G;bq9<2GU&Q#cHwL|o4?ah1` z;fG)%t0wMC;DR?^!jCoKib_iiIjsxCSxRUgJDCE%0P;4JZhJCy)vR1%zRl>K?V6#) z2lDi*W3q9rA zo;yvMujs+)a&00~W<-MNj=dJ@4%tccwT<@+c$#CPR%#aE#Dra+-5eSDl^E>is2v^~ z8lgRwkpeU$|1LW4yFwA{PQ^A{5JY!N5PCZ=hog~|FyPPK0-i;fCl4a%1 z?&@&E-)b4cK)wjXGq|?Kqv0s7y~xqvSj-NpOImt{Riam*Z!wz-coZIMuQU>M%6ben z>P@#o^W;fizVd#?`eeEPs#Gz^ySqJn+~`Pq%-Ee6*X+E>!PJGU#rs6qu0z5{+?`-N zxf1#+JNk7e6AoJTdQwxs&GMTq?Djch_8^xL^A;9XggtGL>!@0|BRuIdE&j$tzvt7I zr@I@0<0io%lpF697s1|qNS|BsA>!>-9DVlgGgw2;;k;=7)3+&t!);W3ulPgR>#JiV zUerO;WxuJqr$ghj-veVGfKF?O7si#mzX@GVt+F&atsB@NmBoV4dK|!owGP005$7LN7AqCG(S+={YA- zn#I{UoP_$~Epc=j78{(!2NLN)3qSm-1&{F&1z4Dz&7Mj_+SdlR^Q5{J=r822d4A@?Rj~xATaWewHUOus{*C|KoH`G zHB8SUT06GpSt)}cFJ18!$Kp@r+V3tE_L^^J%9$&fcyd_AHB)WBghwqBEWW!oh@StV zDrC?ttu4#?Aun!PhC4_KF1s2#kvIh~zds!y9#PIrnk9BWkJpq}{Hlqi+xPOR&A1oP zB0~1tV$Zt1pQuHpJw1TAOS=3$Jl&n{n!a+&SgYVe%igUtvE>eHqKY0`e5lwAf}2x( zP>9Wz+9uirp7<7kK0m2&Y*mzArUx%$CkV661=AIAS=V=|xY{;$B7cS5q0)=oq0uXU z_roo90&gHSfM6@6kmB_FJZ)3y_tt0}7#PA&pWo@_qzdIMRa-;U*Dy>Oo#S_n61Fn! z%mrH%tRmvQvg%UqN_2(C#LSxgQ>m}FKLGG=uqJQuSkk=S@c~QLi4N+>lr}QcOuP&% zQCP^cRk&rk-@lpa0^Lcvdu`F*qE)-0$TnxJlwZf|dP~s8cjhL%>^+L~{umxl5Xr6@ z^7zVKiN1Xg;-h+kr4Yt2BzjZs-Mo54`pDbLc}fWq{34=6>U9@sBP~iWZE`+FhtU|x zTV}ajn*Hc}Y?3agQ+bV@oIRm=qAu%|zE;hBw7kCcDx{pm!_qCxfPX3sh5^B$k_2d` z6#rAeUZC;e-LuMZ-f?gHeZogOa*mE>ffs+waQ+fQl4YKoAyZii_!O0;h55EMzD{;) z8lSJvv((#UqgJ?SCQFqJ-UU?2(0V{;7zT3TW`u6GH6h4m3}SuAAj_K(raGBu>|S&Q zZGL?r9@caTbmRm7p=&Tv?Y1)60*9At38w)$(1c?4cpFY2RLyw9c<{OwQE{b@WI}FQ zTT<2HOF4222d%k70yL~x_d#6SNz`*%@4++8gYQ8?yq0T@w~bF@aOHL2)T4xj`AVps9k z?m;<2ClJh$B6~fOYTWIV*T9y1BpB1*C?dgE{%lVtIjw>4MK{wP6OKTb znbPWrkZjYCbr`GGa%Xo0h;iFPNJBI3fK5`wtJV?wq_G<_PZ<`eiKtvN$IKfyju*^t zXc}HNg>^PPZ16m6bfTpmaW5=qoSsj>3)HS}teRa~qj+Y}mGRE?cH!qMDBJ8 zJB!&-=MG8Tb;V4cZjI_#{>ca0VhG_P=j0kcXVX5)^Sdpk+LKNv#yhpwC$k@v^Am&! z_cz2^4Cc{_BC!K#zN!KEkPzviUFPJ^N_L-kHG6}(X#$>Q=9?!{$A(=B3)P?PkxG9gs#l! zo6TOHo$F|IvjTC3MW%XrDoc7;m-6wb9mL(^2(>PQXY53hE?%4FW$rTHtN`!VgH72U zRY)#?Y*pMA<)x3B-&fgWQ(TQ6S6nUeSY{9)XOo_k=j$<*mA=f+ghSALYwBw~!Egn!jtjubOh?6Cb-Zi3IYn*fYl()^3u zRiX0I{5QaNPJ9w{yh4(o#$geO7b5lSh<5ZaRg9_=aFdZjxjXv(_SCv^v-{ZKQFtAA}kw=GPC7l81GY zeP@0Da{aR#{6`lbI0ON0y#K=t|L*}MG_HSl$e{U;v=BSs{SU3(e*qa(l%rD;(zM^3 zrRgN3M#Sf(Cr9>v{FtB`8JBK?_zO+~{H_0$lLA!l{YOs9KQd4Zt<3*Ns7dVbT{1Ut z?N9{XkN(96?r(4BH~3qeiJ_CAt+h1}O_4IUF$S(5EyTyo=`{^16P z=VhDY!NxkDukQz>T`0*H=(D3G7Np*2P`s(6M*(*ZJa;?@JYj&_z`d5bap=KK37p3I zr5#`%aC)7fUo#;*X5k7g&gQjxlC9CF{0dz*m2&+mf$Sc1LnyXn9lpZ!!Bl!@hnsE5px};b-b-`qne0Kh;hziNC zXV|zH%+PE!2@-IrIq!HM2+ld;VyNUZiDc@Tjt|-1&kq}>muY;TA3#Oy zWdYGP3NOZWSWtx6?S6ES@>)_Yz%%nLG3P>Z7`SrhkZ?shTfrHkYI;2zAn8h65wV3r z^{4izW-c9!MTge3eN=~r5aTnz6*6l#sD68kJ7Nv2wMbL~Ojj0H;M`mAvk*`Q!`KI? z7nCYBqbu$@MSNd+O&_oWdX()8Eh|Z&v&dJPg*o-sOBb2hriny)< zd(o&&kZM^NDtV=hufp8L zCkKu7)k`+czHaAU567$?GPRGdkb4$37zlIuS&<&1pgArURzoWCbyTEl9OiXZBn4p<$48-Gekh7>e)v*?{9xBt z=|Rx!@Y3N@ffW5*5!bio$jhJ7&{!B&SkAaN`w+&3x|D^o@s{ZAuqNss8K;211tUWIi1B!%-ViYX+Ys6w)Q z^o1{V=hK#+tt&aC(g+^bt-J9zNRdv>ZYm9KV^L0y-yoY7QVZJ_ivBS02I|mGD2;9c zR%+KD&jdXjPiUv#t1VmFOM&=OUE2`SNm4jm&a<;ZH`cYqBZoAglCyixC?+I+}*ScG#;?SEAFob{v0ZKw{`zw*tX}<2k zoH(fNh!>b5w8SWSV}rQ*E24cO=_eQHWy8J!5;Y>Bh|p;|nWH|nK9+ol$k`A*u*Y^Uz^%|h4Owu}Cb$zhIxlVJ8XJ0xtrErT zcK;34CB;ohd|^NfmVIF=XlmB5raI}nXjFz;ObQ4Mpl_`$dUe7sj!P3_WIC~I`_Xy@ z>P5*QE{RSPpuV=3z4p3}dh>Dp0=We@fdaF{sJ|+_E*#jyaTrj-6Y!GfD@#y@DUa;& zu4Iqw5(5AamgF!2SI&WT$rvChhIB$RFFF|W6A>(L9XT{0%DM{L`knIQPC$4F`8FWb zGlem_>>JK-Fib;g*xd<-9^&_ue95grYH>5OvTiM;#uT^LVmNXM-n8chJBD2KeDV7t zbnv3CaiyN>w(HfGv86K5MEM{?f#BTR7**smpNZ}ftm+gafRSt=6fN$(&?#6m3hF!>e$X)hFyCF++Qvx(<~q3esTI zH#8Sv!WIl2<&~=B)#sz1x2=+KTHj=0v&}iAi8eD=M->H|a@Qm|CSSzH#eVIR3_Tvu zG8S**NFbz%*X?DbDuP(oNv2;Lo@#_y4k$W+r^#TtJ8NyL&&Rk;@Q}~24`BB)bgwcp z=a^r(K_NEukZ*|*7c2JKrm&h&NP)9<($f)eTN}3|Rt`$5uB0|!$Xr4Vn#i;muSljn zxG?zbRD(M6+8MzGhbOn%C`M#OcRK!&ZHihwl{F+OAnR>cyg~No44>vliu$8^T!>>*vYQJCJg=EF^lJ*3M^=nGCw`Yg@hCmP(Gq^=eCEE1!t-2>%Al{w@*c% zUK{maww*>K$tu;~I@ERb9*uU@LsIJ|&@qcb!&b zsWIvDo4#9Qbvc#IS%sV1_4>^`newSxEcE08c9?rHY2%TRJfK2}-I=Fq-C)jc`gzV( zCn?^noD(9pAf2MP$>ur0;da`>Hr>o>N@8M;X@&mkf;%2A*2CmQBXirsJLY zlX21ma}mKH_LgYUM-->;tt;6F?E5=fUWDwQhp*drQ%hH0<5t2m)rFP%=6aPIC0j$R znGI0hcV~}vk?^&G`v~YCKc7#DrdMM3TcPBmxx#XUC_JVEt@k=%3-+7<3*fTcQ>f~?TdLjv96nb66xj=wVQfpuCD(?kzs~dUV<}P+Fpd)BOTO^<*E#H zeE80(b~h<*Qgez(iFFOkl!G!6#9NZAnsxghe$L=Twi^(Q&48 zD0ohTj)kGLD){xu%pm|}f#ZaFPYpHtg!HB30>F1c=cP)RqzK2co`01O5qwAP zUJm0jS0#mci>|Nu4#MF@u-%-4t>oUTnn_#3K09Hrwnw13HO@9L;wFJ*Z@=gCgpA@p zMswqk;)PTXWuMC-^MQxyNu8_G-i3W9!MLd2>;cM+;Hf&w| zLv{p*hArp9+h2wsMqT5WVqkkc0>1uokMox{AgAvDG^YJebD-czexMB!lJKWllLoBI zetW2;;FKI1xNtA(ZWys!_un~+834+6y|uV&Lo%dKwhcoDzRADYM*peh{o`-tHvwWIBIXW`PKwS3|M>CW37Z2dr!uJWNFS5UwY4;I zNIy1^sr+@8Fob%DHRNa&G{lm?KWU7sV2x9(Ft5?QKsLXi!v6@n&Iyaz5&U*|hCz+d z9vu60IG<v6+^ZmBs_aN!}p|{f(ikVl&LcB+UY;PPz* zj84Tm>g5~-X=GF_4JrVmtEtm=3mMEL1#z+pc~t^Iify^ft~cE=R0TymXu*iQL+XLX zdSK$~5pglr3f@Lrcp`>==b5Z6r7c=p=@A5nXNacsPfr(5m;~ks@*Wu7A z%WyY$Pt*RAKHz_7cghHuQqdU>hq$vD?plol_1EU(Fkgyo&Q2&2e?FT3;H%!|bhU~D z>VX4-6}JLQz8g3%Bq}n^NhfJur~v5H0dbB^$~+7lY{f3ES}E?|JnoLsAG%l^%eu_PM zEl0W(sbMRB3rFeYG&tR~(i2J0)RjngE`N_Jvxx!UAA1mc7J>9)`c=`}4bVbm8&{A` z3sMPU-!r-8de=P(C@7-{GgB<5I%)x{WfzJwEvG#hn3ict8@mexdoTz*(XX!C&~}L* z^%3eYQ8{Smsmq(GIM4d5ilDUk{t@2@*-aevxhy7yk(wH?8yFz%gOAXRbCYzm)=AsM z?~+vo2;{-jkA%Pqwq&co;|m{=y}y2lN$QPK>G_+jP`&?U&Ubq~T`BzAj1TlC`%8+$ zzdwNf<3suPnbh&`AI7RAYuQ<#!sD|A=ky2?hca{uHsB|0VqShI1G3lG5g}9~WSvy4 zX3p~Us^f5AfXlBZ0hA;mR6aj~Q8yb^QDaS*LFQwg!!<|W!%WX9Yu}HThc7>oC9##H zEW`}UQ%JQ38UdsxEUBrA@=6R-v1P6IoIw8$8fw6F{OSC7`cOr*u?p_0*Jvj|S)1cd z-9T);F8F-Y_*+h-Yt9cQQq{E|y^b@r&6=Cd9j0EZL}Pj*RdyxgJentY49AyC@PM<< zl&*aq_ubX%*pqUkQ^Zsi@DqhIeR&Ad)slJ2g zmeo&+(g!tg$z1ao1a#Qq1J022mH4}y?AvWboI4H028;trScqDQrB36t!gs|uZS9}KG0}DD$ zf2xF}M*@VJSzEJ5>ucf+L_AtN-Ht=34g&C?oPP>W^bwoigIncKUyf61!ce!2zpcNT zj&;rPGI~q2!Sy>Q7_lRX*DoIs-1Cei=Cd=+Xv4=%bn#Yqo@C=V`|QwlF0Y- zONtrwpHQ##4}VCL-1ol(e<~KU9-ja^kryz!g!})y-2S5z2^gE$Isj8l{%tF=Rzy`r z^RcP7vu`jHgHLKUE957n3j+BeE(bf;f)Zw($XaU6rZ26Upl#Yv28=8Y`hew{MbH>* z-sGI6dnb5D&dUCUBS`NLAIBP!Vi!2+~=AU+)^X^IpOEAn#+ab=`7c z%7B|mZ>wU+L;^&abXKan&N)O;=XI#dTV|9OMYxYqLbtT#GY8PP$45Rm2~of+J>>HIKIVn(uQf-rp09_MwOVIp@6!8bKV(C#(KxcW z;Pesq(wSafCc>iJNV8sg&`!g&G55<06{_1pIoL`2<7hPvAzR1+>H6Rx0Ra%4j7H-<-fnivydlm{TBr06;J-Bq8GdE^Amo)ptV>kS!Kyp*`wUx=K@{3cGZnz53`+C zLco1jxLkLNgbEdU)pRKB#Pq(#(Jt>)Yh8M?j^w&RPUueC)X(6`@@2R~PV@G(8xPwO z^B8^+`qZnQr$8AJ7<06J**+T8xIs)XCV6E_3W+al18!ycMqCfV>=rW0KBRjC* zuJkvrv;t&xBpl?OB3+Li(vQsS(-TPZ)Pw2>s8(3eF3=n*i0uqv@RM^T#Ql7(Em{(~%f2Fw|Reg@eSCey~P zBQlW)_DioA*yxxDcER@_=C1MC{UswPMLr5BQ~T6AcRyt0W44ffJG#T~Fk}wU^aYoF zYTayu-s?)<`2H(w+1(6X&I4?m3&8sok^jpXBB<|ZENso#?v@R1^DdVvKoD?}3%@{}}_E7;wt9USgrfR3(wabPRhJ{#1es81yP!o4)n~CGsh2_Yj2F^z|t zk((i&%nDLA%4KFdG96pQR26W>R2^?C1X4+a*hIzL$L=n4M7r$NOTQEo+k|2~SUI{XL{ynLSCPe%gWMMPFLO{&VN2pom zBUCQ(30qj=YtD_6H0-ZrJ46~YY*A;?tmaGvHvS^H&FXUG4)%-a1K~ly6LYaIn+4lG zt=wuGLw!%h=Pyz?TP=?6O-K-sT4W%_|Nl~;k~YA^_`gqfe{Xw=PWn#9f1mNz)sFuL zJbrevo(DPgpirvGMb6ByuEPd=Rgn}fYXqeUKyM+!n(cKeo|IY%p!#va6`D8?A*{u3 zEeWw0*oylJ1X!L#OCKktX2|>-z3#>`9xr~azOH+2dXHRwdfnpri9|xmK^Q~AuY!Fg z`9Xx?hxkJge~)NVkPQ(VaW(Ce2pXEtgY*cL8i4E)mM(iz_vdm|f@%cSb*Lw{WbShh41VGuplex9E^VvW}irx|;_{VK=N_WF39^ zH4<*peWzgc)0UQi4fBk2{FEzldDh5+KlRd!$_*@eYRMMRb1gU~9lSO_>Vh-~q|NTD zL}X*~hgMj$*Gp5AEs~>Bbjjq7G>}>ki1VxA>@kIhLe+(EQS0mjNEP&eXs5)I;7m1a zmK0Ly*!d~Dk4uxRIO%iZ!1-ztZxOG#W!Q_$M7_DKND0OwI+uC;PQCbQ#k#Y=^zQve zTZVepdX>5{JSJb;DX3%3g42Wz2D@%rhIhLBaFmx#ZV8mhya}jo1u{t^tzoiQy=jJp zjY2b7D2f$ZzJx)8fknqdD6fd5-iF8e(V}(@xe)N=fvS%{X$BRvW!N3TS8jn=P%;5j zShSbzsLs3uqycFi3=iSvqH~}bQn1WQGOL4?trj(kl?+q2R23I42!ipQ&`I*&?G#i9 zWvNh8xoGKDt>%@i0+}j?Ykw&_2C4!aYEW0^7)h2Hi7$;qgF3;Go?bs=v)kHmvd|`R z%(n94LdfxxZ)zh$ET8dH1F&J#O5&IcPH3=8o;%>OIT6w$P1Yz4S!}kJHNhMQ1(prc zM-jSA-7Iq=PiqxKSWb+YbLB-)lSkD6=!`4VL~`ExISOh2ud=TI&SKfR4J08Bad&rj zcXxMpcNgOB?w$~L7l^wPcXxw$0=$oV?)`I44)}b#ChS`_lBQhvb6ks?HDr3tFgkg&td19?b8=!sETXtp=&+3T$cCwZe z0nAET-7561gsbBws$TVjP7QxY(NuBYXVn9~9%vyN-B#&tJhWgtL1B<%BTS*-2$xB` zO)cMDHoWsm%JACZF--Pa7oP;f!n%p`*trlpvZ!HKoB={l+-(8O;;eYv2A=ra z3U7rSMCkP_6wAy`l|Se(&5|AefXvV1E#XA(LT!% zjj4|~xlZ-kPLNeQLFyXb%$K}YEfCBvHA-Znw#dZSI6V%3YD{Wj2@utT5Hieyofp6Qi+lz!u)htnI1GWzvQsA)baEuw9|+&(E@p8M+#&fsX@Kf`_YQ>VM+40YLv`3-(!Z7HKYg@+l00WGr779i-%t`kid%e zDtbh8UfBVT3|=8FrNian@aR3*DTUy&u&05x%(Lm3yNoBZXMHWS7OjdqHp>cD>g!wK z#~R{1`%v$IP;rBoP0B0P><;dxN9Xr+fp*s_EK3{EZ94{AV0#Mtv?;$1YaAdEiq5)g zYME;XN9cZs$;*2p63Q9^x&>PaA1p^5m7|W?hrXp2^m;B@xg0bD?J;wIbm6O~Nq^^K z2AYQs@7k)L#tgUkTOUHsh&*6b*EjYmwngU}qesKYPWxU-z_D> zDWr|K)XLf_3#k_9Rd;(@=P^S^?Wqlwert#9(A$*Y$s-Hy)BA0U0+Y58zs~h=YtDKxY0~BO^0&9{?6Nny;3=l59(6ec9j(79M?P1cE zex!T%$Ta-KhjFZLHjmPl_D=NhJULC}i$}9Qt?nm6K6-i8&X_P+i(c*LI3mtl3 z*B+F+7pnAZ5}UU_eImDj(et;Khf-z^4uHwrA7dwAm-e4 zwP1$Ov3NP5ts+e(SvM)u!3aZMuFQq@KE-W;K6 zag=H~vzsua&4Sb$4ja>&cSJ)jjVebuj+?ivYqrwp3!5>ul`B*4hJGrF;!`FaE+wKo z#};5)euvxC1zX0-G;AV@R(ZMl=q_~u8mQ5OYl;@BAkt)~#PynFX#c1K zUQ1^_N8g+IZwUl*n0Bb-vvliVtM=zuMGU-4a8|_8f|2GEd(2zSV?aSHUN9X^GDA8M zgTZW06m*iAy@7l>F3!7+_Y3mj^vjBsAux3$%U#d$BT^fTf-7{Y z_W0l=7$ro5IDt7jp;^cWh^Zl3Ga1qFNrprdu#g=n9=KH!CjLF#ucU5gy6*uASO~|b z7gcqm90K@rqe({P>;ww_q%4}@bq`ST8!0{V08YXY)5&V!>Td)?j7#K}HVaN4FU4DZ z%|7OppQq-h`HJ;rw-BAfH* z1H$ufM~W{%+b@9NK?RAp-$(P0N=b<(;wFbBN0{u5vc+>aoZ|3&^a866X@el7E8!E7 z=9V(Ma**m_{DKZit2k;ZOINI~E$|wO99by=HO{GNc1t?nl8soP@gxk8)WfxhIoxTP zoO`RA0VCaq)&iRDN9yh_@|zqF+f07Esbhe!e-j$^PS57%mq2p=+C%0KiwV#t^%_hH zoO?{^_yk5x~S)haR6akK6d|#2TN& zfWcN zc7QAWl)E9`!KlY>7^DNw$=yYmmRto>w0L(~fe?|n6k2TBsyG@sI)goigj=mn)E)I* z4_AGyEL7?(_+2z=1N@D}9$7FYdTu;%MFGP_mEJXc2OuXEcY1-$fpt8m_r2B|<~Xfs zX@3RQi`E-1}^9N{$(|YS@#{ZWuCxo)91{k>ESD54g_LYhm~vlOK_CAJHeYFfuIVB^%cqCfvpy#sU8Do8u}# z>>%PLKOZ^+$H54o@brtL-hHorSKcsjk_ZibBKBgyHt~L z=T6?e0oLX|h!Z3lbkPMO27MM?xn|uZAJwvmX?Yvp#lE3sQFY)xqet>`S2Y@1t)Z*& z;*I3;Ha8DFhk=YBt~{zp=%%*fEC}_8?9=(-k7HfFeN^GrhNw4e?vx*#oMztnO*&zY zmRT9dGI@O)t^=Wj&Og1R3b%(m*kb&yc;i`^-tqY9(0t!eyOkH<$@~1lXmm!SJllE_ zr~{a&w|8*LI>Z^h!m%YLgKv06Js7j7RaoX}ZJGYirR<#4Mghd{#;38j3|V+&=ZUq#1$ zgZb-7kV)WJUko?{R`hpSrC;w2{qa`(Z4gM5*ZL`|#8szO=PV^vpSI-^K_*OQji^J2 zZ_1142N}zG$1E0fI%uqHOhV+7%Tp{9$bAR=kRRs4{0a`r%o%$;vu!_Xgv;go)3!B#;hC5qD-bcUrKR&Sc%Zb1Y($r78T z=eG`X#IpBzmXm(o6NVmZdCQf6wzqawqI63v@e%3TKuF!cQ#NQbZ^?6K-3`_b=?ztW zA>^?F#dvVH=H-r3;;5%6hTN_KVZ=ps4^YtRk>P1i>uLZ)Ii2G7V5vy;OJ0}0!g>j^ z&TY&E2!|BDIf1}U(+4G5L~X6sQ_e7In0qJmWYpn!5j|2V{1zhjZt9cdKm!we6|Pp$ z07E+C8=tOwF<<}11VgVMzV8tCg+cD_z?u+$sBjwPXl^(Ge7y8-=c=fgNg@FxI1i5Y-HYQMEH z_($je;nw`Otdhd1G{Vn*w*u@j8&T=xnL;X?H6;{=WaFY+NJfB2(xN`G)LW?4u39;x z6?eSh3Wc@LR&yA2tJj;0{+h6rxF zKyHo}N}@004HA(adG~0solJ(7>?LoXKoH0~bm+xItnZ;3)VJt!?ue|~2C=ylHbPP7 zv2{DH()FXXS_ho-sbto)gk|2V#;BThoE}b1EkNYGT8U#0ItdHG>vOZx8JYN*5jUh5Fdr9#12^ zsEyffqFEQD(u&76zA^9Jklbiz#S|o1EET$ujLJAVDYF znX&4%;vPm-rT<8fDutDIPC@L=zskw49`G%}q#l$1G3atT(w70lgCyfYkg7-=+r7$%E`G?1NjiH)MvnKMWo-ivPSQHbk&_l5tedNp|3NbU^wk0SSXF9ohtM zUqXiOg*8ERKx{wO%BimK)=g^?w=pxB1Vu_x<9jKOcU7N;(!o3~UxyO+*ZCw|jy2}V*Z22~KhmvxoTszc+#EMWXTM6QF*ks% zW47#2B~?wS)6>_ciKe1Fu!@Tc6oN7e+6nriSU;qT7}f@DJiDF@P2jXUv|o|Wh1QPf zLG31d>@CpThA+Ex#y)ny8wkC4x-ELYCXGm1rFI=1C4`I5qboYgDf322B_Nk@#eMZ% znluCKW2GZ{r9HR@VY`>sNgy~s+D_GkqFyz6jgXKD)U|*eKBkJRRIz{gm3tUd*yXmR z(O4&#ZA*us6!^O*TzpKAZ#}B5@}?f=vdnqnRmG}xyt=)2o%<9jj>-4wLP1X-bI{(n zD9#|rN#J;G%LJ&$+Gl2eTRPx6BQC6Uc~YK?nMmktvy^E8#Y*6ZJVZ>Y(cgsVnd!tV z!%twMNznd)?}YCWyy1-#P|2Fu%~}hcTGoy>_uawRTVl=(xo5!%F#A38L109wyh@wm zdy+S8E_&$Gjm=7va-b7@Hv=*sNo0{i8B7=n4ex-mfg`$!n#)v@xxyQCr3m&O1Jxg! z+FXX^jtlw=utuQ+>Yj$`9!E<5-c!|FX(~q`mvt6i*K!L(MHaqZBTtuSA9V~V9Q$G? zC8wAV|#XY=;TQD#H;;dcHVb9I7Vu2nI0hHo)!_{qIa@|2}9d ztpC*Q{4Py~2;~6URN^4FBCBip`QDf|O_Y%iZyA0R`^MQf$ce0JuaV(_=YA`knEMXw zP6TbjYSGXi#B4eX=QiWqb3bEw-N*a;Yg?dsVPpeYFS*&AsqtW1j2D$h$*ZOdEb$8n0 zGET4Igs^cMTXWG{2#A7w_usx=KMmNfi4oAk8!MA8Y=Rh9^*r>jEV(-{I0=rc);`Y) zm+6KHz-;MIy|@2todN&F+Yv1e&b&ZvycbTHpDoZ>FIiUn+M-=%A2C(I*^Yx@VKf(Z zxJOny&WoWcyKodkeN^5))aV|-UBFw{?AGo?;NNFFcKzk+6|gYfA#FR=y@?;3IoQ zUMI=7lwo9gV9fRvYi}Nd)&gQw7(K3=a0#p27u6Q)7JlP#A)piUUF8B3Li&38Xk$@| z9OR+tU~qgd3T3322E))eV)hAAHYIj$TmhH#R+C-&E-}5Qd{3B}gD{MXnsrS;{Erv1 z6IyQ=S2qD>Weqqj#Pd65rDSdK54%boN+a?=CkR|agnIP6;INm0A*4gF;G4PlA^3%b zN{H%#wYu|!3fl*UL1~f+Iu|;cqDax?DBkZWSUQodSDL4Es@u6zA>sIm>^Aq-&X#X8 zI=#-ucD|iAodfOIY4AaBL$cFO@s(xJ#&_@ZbtU+jjSAW^g;_w`FK%aH_hAY=!MTjI zwh_OEJ_25zTQv$#9&u0A11x_cGd92E74AbOrD`~f6Ir9ENNQAV2_J2Ig~mHWhaO5a zc>fYG$zke^S+fBupw+klDkiljJAha z6DnTemhkf>hv`8J*W_#wBj-2w(cVtXbkWWtE(3j@!A-IfF?`r$MhVknTs3D1N`rYN zKth9jZtX#>v#%U@^DVN!;ni#n1)U&H_uB{6pcq7$TqXJX!Q0P7U*JUZyclb~)l*DS zOLpoQfW_3;a0S$#V0SOwVeeqE$Hd^L`$;l_~2giLYd?7!gUYIpOs!jqSL~pI)4`YuB_692~A z^T#YYQ_W3Rakk}$SL&{`H8mc{>j+3eKprw6BK`$vSSIn;s31M~YlJLApJ)+Gi1{^- zw96WnT9M0Vr_D=e=a}${raR{(35Q!g+8`}vOFj1e&Or(_wp2U2aVQP0_jP57 z2(R4E(E$n!xl<}Zx38wO;27wuQ`P#_j!}L2 z2qr;As4D4n2X$-Jd_-!fsbu_D(64i;c4cJnP576x_>Q4WNushFwkBV!kVd(AYFXe{ zaqO5`Qfr!#ETmE(B;u_&FITotv~W}QYFCI!&ENKIb1p4fg*Yv1)EDMb==EjHHWM#{ zGMpqb2-LXdHB@D~pE3|+B392Gh4q)y9jBd$a^&cJM60VEUnLtHQD5i-X6PVF>9m_k zDvG3P(?CzdaIrC8s4cu~N9MEb!Tt(g*GK~gIp1Gyeaw3b7#YPx_1T6i zRi#pAMr~PJKe9P~I+ARa$a!K~)t(4LaVbjva1yd;b1Yz2$7MMc`aLmMl(a^DgN(u? zq2o9&Gif@Tq~Yq+qDfx^F*nCnpuPv%hRFc$I!p74*quLt^M}D_rwl10uMTr!)(*=7 zSC5ea@#;l(h87k4T4x)(o^#l76P-GYJA(pOa&F9YT=fS<*O{4agzba^dIrh0hjls<~APlIz9{ zgRY{OMv2s|`;VCoYVj?InYoq^QWuA&*VDyOn@pPvK8l~g#1~~MGVVvtLDt}>id_Z` zn(ihfL?Y}Y4YX335m*Xx(y+bbukchHrM zycIGp#1*K3$!(tgTsMD2VyUSg^yvCwB8*V~sACE(yq2!MS6f+gsxv^GR|Q7R_euYx z&X+@@H?_oQddGxJYS&ZG-9O(X+l{wcw;W7srpYjZZvanY(>Q1utSiyuuonkjh5J0q zGz6`&meSuxixIPt{UoHVupUbFKIA+3V5(?ijn}(C(v>=v?L*lJF8|yRjl-m#^|krg zLVbFV6+VkoEGNz6he;EkP!Z6|a@n8?yCzX9>FEzLnp21JpU0x!Qee}lwVKA})LZJq zlI|C??|;gZ8#fC3`gzDU%7R87KZyd)H__0c^T^$zo@TBKTP*i{)Gp3E0TZ}s3mKSY zix@atp^j#QnSc5K&LsU38#{lUdwj%xF zcx&l^?95uq9on1m*0gp$ruu||5MQo)XaN>|ngV5Jb#^wWH^5AdYcn_1>H~XtNwJd3 zd9&?orMSSuj=lhO?6)Ay7;gdU#E}pTBa5wFu`nejq##Xd71BHzH2XqLA5 zeLEo;9$}~u0pEu@(?hXB_l;{jQ=7m?~mwj-ME~Tw-OHPrR7K2Xq9eCNwQO$hR z3_A?=`FJctNXA#yQEorVoh{RWxJbdQga zU%K##XEPgy?E|K(=o#IPgnbk7E&5%J=VHube|2%!Qp}@LznjE%VQhJ?L(XJOmFVY~ zo-az+^5!Ck7Lo<7b~XC6JFk>17*_dY;=z!<0eSdFD2L?CSp_XB+?;N+(5;@=_Ss3& zXse>@sA7hpq;IAeIp3hTe9^$DVYf&?)={zc9*hZAV)|UgKoD!1w{UVo8D)Htwi8*P z%#NAn+8sd@b{h=O)dy9EGKbpyDtl@NBZw0}+Wd=@65JyQ2QgU}q2ii;ot1OsAj zUI&+Pz+NvuRv#8ugesT<<@l4L$zso0AQMh{we$tkeG*mpLmOTiy8|dNYhsqhp+q*yfZA`Z)UC*(oxTNPfOFk3RXkbzAEPofVUy zZ3A%mO?WyTRh@WdXz+zD!ogo}gbUMV!YtTNhr zrt@3PcP%5F;_SQ>Ui`Gq-lUe&taU4*h2)6RDh@8G1$o!){k~3)DT87%tQeHYdO?B` zAmoJvG6wWS?=0(Cj?Aqj59`p(SIEvYyPGJ^reI z`Hr?3#U2zI7k0=UmqMD35l`>3xMcWlDv$oo6;b`dZq3d!~)W z=4Qk)lE8&>#HV>?kRLOHZYz83{u7?^KoXmM^pazj8`7OwQ=5I!==; zA!uN`Q#n=Drmzg}@^nG!mJp9ml3ukWk96^6*us*;&>s+7hWfLXtl?a}(|-#=P12>A zon1}yqh^?9!;on?tRd6Fk0knQSLl4vBGb87A_kJNDGyrnpmn48lz_%P{* z_G*3D#IR<2SS54L5^h*%=)4D9NPpji7DZ5&lHD|99W86QN_(|aJ<5C~PX%YB`Qt_W z>jF_Os@kI6R!ub4n-!orS(G6~mKL7()1g=Lf~{D!LR7#wRHfLxTjYr{*c{neyhz#U zbm@WBKozE+kTd+h-mgF+ELWqTKin57P;0b){ zii5=(B%S(N!Z=rAFGnM6iePtvpxB_Q9-oq_xH!URn2_d-H~i;lro8r{-g!k-Ydb6_w5K@FOV?zPF_hi z%rlxBv$lQi%bjsu^7KT~@u#*c$2-;AkuP)hVEN?W5MO8C9snj*EC&|M!aK6o12q3+ z8e?+dH17E!A$tRlbJW~GtMDkMPT=m1g-v67q{sznnWOI$`g(8E!Pf!#KpO?FETxLK z2b^8^@mE#AR1z(DT~R3!nnvq}LG2zDGoE1URR=A2SA z%lN$#V@#E&ip_KZL}Q6mvm(dsS?oHoRf8TWL~1)4^5<3JvvVbEsQqSa3(lF*_mA$g zv`LWarC79G)zR0J+#=6kB`SgjQZ2460W zN%lZt%M@=EN>Wz4I;eH>C0VnDyFe)DBS_2{h6=0ZJ*w%s)QFxLq+%L%e~UQ0mM9ud zm&|r){_<*Om%vlT(K9>dE(3AHjSYro5Y1I?ZjMqWyHzuCE0nyCn`6eq%MEt(aY=M2rIzHeMds)4^Aub^iTIT|%*izG4YH;sT`D9MR(eND-SB+e66LZT z2VX)RJsn${O{D48aUBl|(>ocol$1@glsxisc#GE*=DXHXA?|hJT#{;X{i$XibrA}X zFHJa+ssa2$F_UC(o2k2Z0vwx%Wb(<6_bdDO#=a$0gK2NoscCr;vyx?#cF)JjM%;a| z$^GIlIzvz%Hx3WVU481}_e4~aWcyC|j&BZ@uWW1`bH1y9EWXOxd~f-VE5DpueNofN zv7vZeV<*!A^|36hUE;`#x%MHhL(~?eZ5fhA9Ql3KHTWoAeO-^7&|2)$IcD1r5X#-u zN~N0$6pHPhop@t1_d`dO3#TC0>y5jm>8;$F5_A2& zt#=^IDfYv?JjPPTPNx2TL-Lrl82VClQSLWW_$3=XPbH}xM34)cyW5@lnxy=&h%eRq zv29&h^fMoxjsDnmua(>~OnX{Cq!7vM0M4Mr@_18|YuSKPBKUTV$s^So zc}JlAW&bVz|JY#Eyup6Ny{|P_s0Pq;5*tinH+>5Xa--{ z2;?2PBs((S4{g=G`S?B3Ien`o#5DmUVwzpGuABthYG~OKIY`2ms;33SN9u^I8i_H5`BQ%yOfW+N3r|ufHS_;U;TWT5z;b14n1gX%Pn`uuO z6#>Vl)L0*8yl|#mICWQUtgzeFp9$puHl~m&O+vj3Ox#SxQUa?fY*uK?A;00RiFg(G zK?g=7b5~U4QIK`C*um%=Sw=OJ1eeaV@WZ%hh-3<=lR#(Xesk%?)l4p(EpTwPvN99V@TT)!A8SeFTV+frN=r|5l?K#odjijx2nFgc3kI zC$hVs1S-!z9>xn9MZcRk0YXdYlf~8*LfH$IHKD59H&gLz%6 z#mAYSRJufbRi~LRadwM*G!O2>&U<^d`@<)otXZJJxT@G}4kTx0zPDVhVXwiU)$}5Y z`0iV`8EEh&GlUk&VY9m0Mqr*U&|^Bc?FB`<%{x-o0ATntwIA%(YDcxWs$C)%a%d_@ z?fx!Co+@3p7ha$|pWYD}p6#(PG%_h8K7sQjT_P~|3ZEH0DRxa3~bP&&lPMj3C~!H2QD zq>(f^RUFSqf6K3BMBFy$jiuoSE+DhEq$xLDb7{57 z0B|1pSjYJ5F@cHG%qDZ{ogL$P!BK&sR%zD`gbK#9gRZX17EtAJxN% zys^gb2=X9=7HP}N(iRqt(tot2yyeE%s;L}AcMh;~-W~s_eAe!gIUYdQz5j~T)0trh z>#1U$uOyyl%!Pi(gD&)uHe9Q^27_kHyFCC}n^-KL(=OxHqUfex1YS__RJh0m-S>eM zqAk`aSev*z1lI&-?CycgDm=bdQCp}RqS0_d-4Mf&>u2KyGFxKe8JM1N{GNWw0n$FL z1UDp(h0(1I2Jh9I`?IS}h4R~n zRwRz>8?$fFMB2{UPe^$Ifl;Oc>}@Q9`|8DCeR{?LUQLPfaMsxs8ps=D_aAXORZH~< zdcIOca-F;+D3~M+)Vi4h)I4O3<)$65yI)goQ_vk#fb;Uim>UI4Dv9#2b1;N_Wg>-F zNwKeMKY+su#~NL0uE%_$mw1%ddX2Qs2P!ncM+>wnz}OCQX1!q~oS?OqYU;&ESAAwP z452QWL0&u^mraF#=j_ZeBWhm&F|d!QjwRl^7=Bl7@(43=BkN=3{BRv#QHIk>Umc_w zvP>q|q{lJ=zs|W9%a@8%W>C@MYN1D5{(=Af31+pR#kB`cd0-YlQQTg}+ zL|_h=F9JQ|Gux5c0ehaffHNYLf8VwF+qnM6IjBEI_eceee;o;FY@#~FFVsZjBSp!j z8V*Bgmn{RK!!zqGc;jy)z@Zjo>5{%m1?K}fLEL$l6Dl4f=ye0wNI#)2L=^K(&18Gb zJoj8@WBB;P^T#V)I0`aDSy?$rJU{+-5472NyFp>;Vw43j@3Z=;D2eSfyw5*0Q+&ML zsV&&*3c3$pa`qcaGbEB0*CA~Wp3%PkF?B87FV&rWNb|@GU$LB;l|;YutU*k za1hjUL_BX%G^s;BuzRi4Hl?eqC2z&ZrKh1tZDwnufG$g$LX(j!h%F5(n8D@in3lnX z(*8+3ZT6TVYRcSpM1eMeCps=Fz8q%gyM&B=a7(Vf`4k3dN$IM+`BO^_7HZq4BR|7w z+5kOJ;9_$X%-~arA@qmXSzD|+NMh--%5-9u6t(M=f%&z$<_V#Y_lzn{E$MZZG)+A> zu2E`_Y(MBJ2l*AqvCUmU;yBT}#oQ{V=((mC-QGJwsCOH*a;{1JRTKv7DBNG+M!XL7(^jbv&Qy-o9HNFrmN)-`D3WFtXs>1vBOJpI(=x; zKhJlFdfMf^G#oU(w1+ucMKYPZaDp>$kt=wiYsBCjUY-uz<4JziB>6fXDSLH*2Y z&Px5y`#3!fF=c4>fCMdg-tX582pemU@ZxyFbznL8-=TTo1Sybg9>7h*J^9^~XxXJO z`k9v~=4amxl<;FCV9h2k%?^-ZUzQy^#{JleyH23o1S{r<+t#z6jKS<9rbAM96^1iY zi6{IjauB)UwBhC-_L(MzGCxhhv`?ryc zja_Uwi7$8l!}*vjJppGyp#Wz=*?;jC*xQ&J894rql5A$2giJRtV&DWQh#(+Vs3-5_ z69_tj(>8%z1VtVp>a74r5}j2rG%&;uaTQ|fr&r%ew-HO}76i8`&ki%#)~}q4Y|d$_ zfNp9uc#$#OEca>>MaY6rF`dB|5#S)bghf>>TmmE&S~IFw;PF0UztO6+R-0!TSC?QP z{b(RA_;q3QAPW^XN?qQqu{h<}Vfiv}Rr!lA$C79^1=U>+ng9Dh>v{`?AOZt>CrQ=o zI}=mSnR))8fJpO->rcX?H);oqSQUZ?sR!fH2SoFdcPm5*2y<_u;4h;BqcF*XbwWSv zcJN%!g|L(22Xp!^1?c;T&qm%rpkP&2EQC3JF+SENm$+@7#e!UKD1uQ{TDw43?!b!3 zUooS_rt=xJfa&h?c^hfV>YwQXre3qosz_^c#)FO~d!<)2o}Oxz5HWtr<)1Yw012v4 zhv0w(RfJspDnA^-6Jmr;GkWt%{mAYOm6yPb&Vl&rv@D^K&;#?=X{kaK5FhScNJ_3> z#5u(Saisq2(~pVlrfG#@kLM#Ot~5rZZc%B&h1=gen?R+#t^1bYKf zVvtefX=D$*)39e^2@!~A_}9c${Gf0?1;dk=!Itp#s%0>Io%k`9(bDeI-udd&E6Zfu zcaiv(h`DM3W3Mfda)fYwhB=8RAPkotVt5-z21Ij~Ot9A^SK-1u*zFVK&mF?q1;|wy zrF+XWs^5Q-%Z6I62gTwrRe#F>riVM#fv_TihxSJ6to1X7NVszgivoTa!fPfBBYj94 zuc2m zL_k-<1FoORng1aL{Zx(P7JmUiH zlmTHdzkn75=mS{V=o$V;gzhEaunoJzJ3uq>0_w~77eID^U*w+v0po_N8=sS-DL~!V z%-~rL<0V7PCEWPCpNgpfsein`Fr)+8=N}mUn2x=K`z%efnhSs#23&N1fjdO`M>s%z zP3(;v93%lLq>ZfqBi#QI-aCXAP8-may8x5s`G)KA;{HSYe2szWINWf^b*fc{jl0KecD zRTle?)%_YzJJcVb>;VJ>P?3Lu2S)vCJZlF>Jxj~~X2U5-NNNy(H?8%XD~yFUxNKs&hwWx^)iF@ zGmEv<|7Q7hGrY_+`iz+d_=^9c(_c}UCzq2#%A0|5WjzCXjZUOxOX zU&-^smw$iwKPe;r`&{rP{L35^&+wk6f2-Sn;D2Ww@sjAJj{Gwbp4H!o{#5_}qALFq z{-q%LGklZvKf%A4D!+t%sRRBDi(>mvuz&V4yu^GdD*KFy?fg%ef5ZU%w=d&M`POGt zNSEJ0{qJI~FRTAjlJc1-+x>Tm{%D?m3sk-&cq#w)OpxI98wCF#2KbWcrAXK_(}M4B zF#VQf*h|irx=+uXZUMi+`A;fPFR5M%Wjs^Wh5rWCKgedhWO^w|@XS;b^&3oom;>K0 zB??|ry^IBarYem6Z7RU`#rDs-ZZAn*hSollv?csD$sh0QpTtI9vb>Dpd}e7*`fZj! zM|8d{~YM@vfW-r0z8vJ z<^6B6Ur(}L?ms_c9@hO0^Iy&J_uc51^?d33e#Y!-``?)VG)BGjCq5$&0G8A*r!2qk zUHscGc;VxE=1KqbH=dW%&Ogl({>L!>((m$2W8M9KQ@a1=h51jN|KoG{v(x0K&*iy% e1c3cF4~(n?C}6GmGu)3JNC)6=LGAhZ*Z%`+-T+_# literal 0 HcmV?d00001 diff --git a/legacy/forge-1.12.2/gradle/wrapper/gradle-wrapper.properties b/legacy/forge-1.12.2/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5028f28 --- /dev/null +++ b/legacy/forge-1.12.2/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/legacy/forge-1.12.2/gradlew b/legacy/forge-1.12.2/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/legacy/forge-1.12.2/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/legacy/forge-1.12.2/gradlew.bat b/legacy/forge-1.12.2/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/legacy/forge-1.12.2/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/legacy/forge-1.12.2/settings.gradle b/legacy/forge-1.12.2/settings.gradle new file mode 100644 index 0000000..266e174 --- /dev/null +++ b/legacy/forge-1.12.2/settings.gradle @@ -0,0 +1,3 @@ +rootProject.name = 'primalpottery-forge-1.12.2' +include 'core' +project(':core').projectDir = file('../../core') diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgePotteryTags.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgePotteryTags.java new file mode 100644 index 0000000..d789cb7 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgePotteryTags.java @@ -0,0 +1,33 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryCodec; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; + +public final class ForgePotteryTags extends PotteryCodec { + private static final ForgePotteryTags CODEC = new ForgePotteryTags(); + + public static NBTTagCompound save(Pottery pot) { return CODEC.encode(pot); } + public static Pottery readProfile(NBTTagCompound tag) { return CODEC.decode(tag); } + + public static Pottery load(NBTTagCompound tag) { + Pottery profile = readProfile(tag); + return profile == null ? PaintedVessel.SAMPLE : profile; + } + + protected NBTTagCompound compound() { return new NBTTagCompound(); } + protected NBTTagList list() { return new NBTTagList(); } + protected NBTTagList discs(NBTTagCompound tag) { return tag.getTagList("discs", 10); } + protected int size(NBTTagList list) { return list.tagCount(); } + protected NBTTagCompound at(NBTTagList list, int i) { return list.getCompoundTagAt(i); } + protected void append(NBTTagList list, NBTTagCompound disc) { list.appendTag(disc); } + protected void writeDiscs(NBTTagCompound tag, NBTTagList discs) { tag.setTag("discs", discs); } + protected void number(NBTTagCompound tag, String key, double value) { tag.setDouble(key, value); } + protected double number(NBTTagCompound tag, String key) { return tag.getDouble(key); } + protected void flag(NBTTagCompound tag, String key) { tag.setBoolean(key, true); } + protected boolean flagged(NBTTagCompound tag, String key) { return tag.getBoolean(key); } + protected void text(NBTTagCompound tag, String key, String value) { tag.setString(key, value); } + protected String text(NBTTagCompound tag, String key) { return tag.getString(key); } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java new file mode 100644 index 0000000..246078c --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java @@ -0,0 +1,78 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.block.Block; +import net.minecraft.block.ITileEntityProvider; +import net.minecraft.block.material.Material; +import net.minecraft.block.properties.IProperty; +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.world.ChunkCache; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.common.property.ExtendedBlockState; +import net.minecraftforge.common.property.IExtendedBlockState; +import net.minecraftforge.common.property.IUnlistedProperty; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PaintedPotBlock extends Block implements ITileEntityProvider { + public static final IUnlistedProperty PROFILE = new IUnlistedProperty() { + public String getName() { return "profile"; } + public Class getType() { return Pottery.class; } + public boolean isValid(Pottery pot) { return pot != null; } + public String valueToString(Pottery pot) { return pot.cacheKey(); } + }; + private static final AxisAlignedBB BOUNDS = new AxisAlignedBB(.25, 0, .25, .75, .5, .75); + + PaintedPotBlock() { + super(Material.CLAY); + setHardness(0.5F); + setUnlocalizedName("primalpottery.pottery"); + } + + @Override protected BlockStateContainer createBlockState() { + return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{PROFILE}); + } + @Override public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { + TileEntity tile = world instanceof ChunkCache + ? ((ChunkCache) world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos); + return tile instanceof PaintedPotEntity ? ((IExtendedBlockState)state).withProperty(PROFILE, ((PaintedPotEntity)tile).profile()) : state; + } + @Override public TileEntity createNewTileEntity(World world, int metadata) { return new PaintedPotEntity(); } + @Override public boolean isOpaqueCube(IBlockState state) { return false; } + @Override public boolean isFullCube(IBlockState state) { return false; } + @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { return BOUNDS; } + + @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { + TileEntity tile = world.getTileEntity(pos); + if (!world.isRemote && tile instanceof PaintedPotEntity) ((PaintedPotEntity)tile).install(stack); + } + + @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult hit, World world, BlockPos pos, EntityPlayer player) { + TileEntity tile = world.getTileEntity(pos); + return tile instanceof PaintedPotEntity ? ((PaintedPotEntity)tile).pickup() : new ItemStack(this); + } + + @Override public void getDrops(NonNullList drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { + TileEntity tile = world.getTileEntity(pos); + drops.add(tile instanceof PaintedPotEntity ? ((PaintedPotEntity)tile).pickup() : new ItemStack(this)); + } + + // Forge requests player drops after removedByPlayer. Keep the profile alive until harvest completes. + @Override public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) { + return willHarvest || super.removedByPlayer(state, world, pos, player, false); + } + + @Override public void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity tile, ItemStack tool) { + super.harvestBlock(world, player, pos, state, tile, tool); + world.setBlockToAir(pos); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java new file mode 100644 index 0000000..9c4038f --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java @@ -0,0 +1,54 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.play.server.SPacketUpdateTileEntity; +import net.minecraft.tileentity.TileEntity; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PaintedPotEntity extends TileEntity { + private Pottery pot = PaintedVessel.SAMPLE; + + public Pottery profile() { return pot; } + + public static Pottery fromStack(ItemStack stack) { + NBTTagCompound tag = stack.getSubCompound("pottery"); + return tag == null ? PaintedVessel.SAMPLE : ForgePotteryTags.load(tag); + } + + void install(ItemStack stack) { + pot = fromStack(stack); + markDirty(); + IBlockState state = world.getBlockState(pos); + world.notifyBlockUpdate(pos, state, state, 3); + } + + ItemStack pickup() { + ItemStack result = new ItemStack(PrimalPotteryForge.POT); + result.setTagInfo("pottery", ForgePotteryTags.save(pot)); + return result; + } + + @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setTag("pottery", ForgePotteryTags.save(pot)); + return tag; + } + + @Override public void readFromNBT(NBTTagCompound tag) { + super.readFromNBT(tag); + pot = ForgePotteryTags.load(tag.getCompoundTag("pottery")); + } + + @Override public NBTTagCompound getUpdateTag() { return writeToNBT(new NBTTagCompound()); } + + @Override public SPacketUpdateTileEntity getUpdatePacket() { return new SPacketUpdateTileEntity(pos, 0, getUpdateTag()); } + + @Override public void onDataPacket(NetworkManager network, SPacketUpdateTileEntity packet) { + readFromNBT(packet.getNbtCompound()); + world.markBlockRangeForRenderUpdate(pos, pos); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java new file mode 100644 index 0000000..bf5dd09 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java @@ -0,0 +1,30 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.event.RegistryEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.registry.GameRegistry; + +@Mod(modid = "primalpottery", name = "Primal Pottery", useMetadata = true, acceptedMinecraftVersions = "[1.12.2]") +@Mod.EventBusSubscriber(modid = "primalpottery") +public final class PrimalPotteryForge { + public static final ResourceLocation ID = new ResourceLocation("primalpottery", "pottery"); + public static final PaintedPotBlock POT = new PaintedPotBlock(); + + @Mod.EventHandler public void setup(FMLPreInitializationEvent event) { + GameRegistry.registerTileEntity(PaintedPotEntity.class, ID); + } + + @SubscribeEvent public static void registerBlocks(RegistryEvent.Register event) { + event.getRegistry().register(POT.setRegistryName(ID)); + } + + @SubscribeEvent public static void registerItems(RegistryEvent.Register event) { + event.getRegistry().register(new ItemBlock(POT).setRegistryName(ID).setMaxStackSize(1)); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java new file mode 100644 index 0000000..314b63a --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java @@ -0,0 +1,84 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import java.util.Collections; +import java.util.List; +import javax.vecmath.Matrix4f; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.client.renderer.block.model.ItemOverrideList; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import net.minecraftforge.client.event.ModelBakeEvent; +import net.minecraftforge.client.event.ModelRegistryEvent; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.client.model.BakedModelWrapper; +import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.common.property.IExtendedBlockState; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotBlock; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import org.apache.commons.lang3.tuple.Pair; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) +public final class PotteryModel extends BakedModelWrapper { + private static final ResourceLocation INKS = new ResourceLocation("primalpottery", "block/pottery_inks"); + private final PotteryQuads bakery; + private final List item; + private final ItemOverrideList overrides = new ItemOverrideList(Collections.emptyList()) { + @Override public IBakedModel handleItemState(IBakedModel model, ItemStack stack, World world, EntityLivingBase entity) { + return new PotteryModel(originalModel, bakery, bakery.model(PaintedPotEntity.fromStack(stack))); + } + }; + + private PotteryModel(IBakedModel base, PotteryQuads bakery, List item) { + super(base); + this.bakery = bakery; + this.item = item; + } + + @SubscribeEvent public static void register(ModelRegistryEvent event) { + ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(PrimalPotteryForge.POT), 0, + new ModelResourceLocation(PrimalPotteryForge.ID, "inventory")); + } + + @SubscribeEvent public static void stitch(TextureStitchEvent.Pre event) { event.getMap().registerSprite(INKS); } + + @SubscribeEvent public static void bake(ModelBakeEvent event) { + TextureAtlasSprite inks = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(INKS.toString()); + for (String variant : new String[]{"normal", "inventory"}) { + ModelResourceLocation key = new ModelResourceLocation(PrimalPotteryForge.ID, variant); + IBakedModel base = event.getModelRegistry().getObject(key); + PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks); + event.getModelRegistry().putObject(key, new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE))); + } + } + + @Override public ItemOverrideList getOverrides() { return overrides; } + + @Override public Pair handlePerspective(ItemCameraTransforms.TransformType type) { + return Pair.of(this, originalModel.handlePerspective(type).getRight()); + } + + @Override public List getQuads(IBlockState state, EnumFacing side, long seed) { + if (side != null) return Collections.emptyList(); + if (state instanceof IExtendedBlockState) { + Pottery profile = ((IExtendedBlockState) state).getValue(PaintedPotBlock.PROFILE); + if (profile != null) return bakery.model(profile); + } + return item; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java new file mode 100644 index 0000000..c8b370b --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java @@ -0,0 +1,20 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.util.EnumFacing; +import net.modcrafters.minecraft.primalpottery.pottery.VesselQuadPacker; + +final class PotteryQuads extends VesselQuadPacker { + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks) { + super(clay, inks, DefaultVertexFormats.ITEM.getIntegerSize()); + } + + @Override protected float u(TextureAtlasSprite sprite, float pixels) { return sprite.getInterpolatedU(pixels); } + @Override protected float v(TextureAtlasSprite sprite, float pixels) { return sprite.getInterpolatedV(pixels); } + + @Override protected BakedQuad quad(int[] vertices, TextureAtlasSprite sprite, float nx, float ny, float nz) { + return new BakedQuad(vertices, -1, EnumFacing.getFacingFromVector(nx, ny, nz), sprite, true, DefaultVertexFormats.ITEM); + } +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery.json new file mode 100644 index 0000000..14b98df --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery.json @@ -0,0 +1 @@ +{"variants":{"normal":{"model":"primalpottery:pottery"}}} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang new file mode 100644 index 0000000..60ed62a --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang @@ -0,0 +1 @@ +tile.primalpottery.pottery.name=Painted Pottery diff --git a/legacy/forge-1.12.2/src/main/resources/mcmod.info b/legacy/forge-1.12.2/src/main/resources/mcmod.info new file mode 100644 index 0000000..ec20409 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/mcmod.info @@ -0,0 +1 @@ +[{"modid":"primalpottery","name":"Primal Pottery","version":"${version}","mcversion":"1.12.2","description":"Placeable painted pottery.","authorList":["modcrafters"]}] diff --git a/legacy/forge-1.12.2/src/main/resources/pack.mcmeta b/legacy/forge-1.12.2/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..360fea4 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"pack_format":3,"description":"Primal Pottery"}} diff --git a/neoforge/build.gradle b/neoforge/build.gradle index a6b4427..a395239 100644 --- a/neoforge/build.gradle +++ b/neoforge/build.gradle @@ -113,6 +113,7 @@ neoForge { mods { "${mod_id}" { sourceSet sourceSets.main + sourceSet project(':core').sourceSets.main } } } diff --git a/settings.gradle.kts b/settings.gradle.kts index b7d14f4..1c6c68d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -37,3 +37,4 @@ stonecutter { // This should match the folder name of the project, or else IDEA may complain (see https://youtrack.jetbrains.com/issue/IDEA-317606) rootProject.name = "primal-pottery" includeBuild("build-logic") +include("core", "forge") diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PaintingTableEntity.java b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PaintingTableEntity.java index 2630296..c7dd485 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PaintingTableEntity.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PaintingTableEntity.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.block; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; @@ -83,7 +84,7 @@ void stamp(ServerPlayer player, FacePaint pattern) { System.arraycopy(remaining, 0, tanks, 0, tanks.length); setChanged(); PotteryItem.editOne(player, net.minecraft.world.InteractionHand.MAIN_HAND, painted -> - CustomData.update(DataComponents.CUSTOM_DATA, painted, tag -> tag.put("pottery", pot.withPaint(pattern).save()))); + CustomData.update(DataComponents.CUSTOM_DATA, painted, tag -> tag.put("pottery", PotteryTags.save(pot.withPaint(pattern))))); inventory.setChanged(); player.sendSystemMessage(Component.translatable("message.primalpottery.paint.stamped", icon.getHoverName()), true); } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java index a8f4f14..e2d90b4 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryBlockEntity.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.block; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import java.util.Arrays; import java.util.List; import net.minecraft.core.BlockPos; @@ -496,7 +497,7 @@ private CompoundTag saveSlots() { Pottery slot = this.slots[index]; CompoundTag entry = new CompoundTag(); if (slot != null) { - entry.put("pottery", slot.save()); + entry.put("pottery", PotteryTags.save(slot)); this.contents[index].write(entry); if (this.planters[index] != null) { this.planters[index].save(entry); @@ -532,7 +533,7 @@ private void loadSlots(CompoundTag tag) { } CompoundTag pottery = Nbt.compound(entry, "pottery"); if (!pottery.isEmpty()) { - this.slots[index] = Pottery.load(pottery); + this.slots[index] = PotteryTags.load(pottery); if (this.slots[index] == null) continue; if (index >= CORNERS) this.slots[index] = this.slots[index].fitSavedPlate(); this.contents[index] = VesselContents.read(entry).limitedTo(this.slots[index]); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryWheelBlockEntity.java b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryWheelBlockEntity.java index 2c3dee2..302137c 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryWheelBlockEntity.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/block/PotteryWheelBlockEntity.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.block; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; @@ -294,10 +295,10 @@ private CompoundTag saveWheel() { tag.putFloat("progress", this.clayProgress); this.saveTemplate(tag); if (this.target != null) { - tag.put("target", this.target.save()); + tag.put("target", PotteryTags.save(this.target)); } if (this.start != null) { - tag.put("start", this.start.save()); + tag.put("start", PotteryTags.save(this.start)); } return tag; } @@ -310,9 +311,9 @@ private void loadWheel(CompoundTag tag) { this.clayProgress = Nbt.getFloat(tag, "progress"); this.loadTemplate(tag); CompoundTag target = Nbt.compound(tag, "target"); - this.target = this.hasClay ? (target.isEmpty() ? Pottery.formed(this.template()) : Pottery.load(target)) : null; + this.target = this.hasClay ? (target.isEmpty() ? Pottery.formed(this.template()) : PotteryTags.load(target)) : null; CompoundTag start = Nbt.compound(tag, "start"); - this.start = start.isEmpty() ? null : Pottery.load(start); + this.start = start.isEmpty() ? null : PotteryTags.load(start); } private void saveTemplate(CompoundTag tag) { @@ -323,7 +324,7 @@ private void saveTemplate(CompoundTag tag) { tag.putBoolean("large_template", this.installed.is(ModItems.LARGE_BLUEPRINT)); Pottery saved = TemplateItem.read(this.installed); if (saved != null) { - tag.put("template", saved.save()); + tag.put("template", PotteryTags.save(saved)); } } @@ -335,7 +336,7 @@ private void loadTemplate(CompoundTag tag) { } ItemStack stack = new ItemStack(Nbt.getBoolean(tag, "large_template") ? ModItems.LARGE_BLUEPRINT : ModItems.BLUEPRINT); if (!saved.isEmpty()) { - TemplateItem.write(stack, Pottery.load(saved)); + TemplateItem.write(stack, PotteryTags.load(saved)); } this.installed = stack; } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/ItemIconStamp.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/ItemIconStamp.java index 7d79f4a..1c36f8e 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/ItemIconStamp.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/ItemIconStamp.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.client; +import net.modcrafters.minecraft.primalpottery.pottery.PaintColors; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; @@ -158,7 +159,7 @@ static String quantize(int[] pixels) { visible = true; int closest = 0, bestDistance = Integer.MAX_VALUE; for (int dye = 0; dye < FacePaint.COLORS; dye++) { - int rgb = FacePaint.rgb(dye); + int rgb = PaintColors.rgb(dye); int r = (argb >>> 16 & 255) - (rgb >>> 16 & 255); int g = (argb >>> 8 & 255) - (rgb >>> 8 & 255); int b = (argb & 255) - (rgb & 255); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java index ea6cc68..d3576f9 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.client; +import net.modcrafters.minecraft.primalpottery.pottery.PaintColors; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; @@ -103,7 +104,7 @@ static Tile acquire(FacePaint paint) { for (int v = -1; v <= FacePaint.SIDE; v++) { for (int u = -1; u <= FacePaint.SIDE; u++) { int ink = paint.color(Math.clamp(v, 0, FacePaint.SIDE-1) * FacePaint.SIDE + Math.clamp(u, 0, FacePaint.SIDE-1)); - int argb = ink < 0 ? 0 : 0xFF000000 | FacePaint.rgb(ink); + int argb = ink < 0 ? 0 : 0xFF000000 | PaintColors.rgb(ink); //? if >=26.1 { pixels.setPixel(x+u, y+v, argb); //?} else diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintingScreen.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintingScreen.java index db8c005..25181ac 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintingScreen.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintingScreen.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.client; +import net.modcrafters.minecraft.primalpottery.pottery.PaintColors; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.components.Button; @@ -158,7 +159,7 @@ private void panel(GuiGraphicsExtractor graphics) { for (int column = 0; column < columns; column++) { int color = pattern.color(paintCell(column, row)); int px = gridLeft + column*PIXEL, py = gridTop + row*PIXEL; - graphics.fill(px, py, px+PIXEL-1, py+PIXEL-1, color < 0 ? clay : 0xFF000000 | FacePaint.rgb(color)); + graphics.fill(px, py, px+PIXEL-1, py+PIXEL-1, color < 0 ? clay : 0xFF000000 | PaintColors.rgb(color)); } } if (columns < FacePaint.SIDE) { @@ -176,7 +177,7 @@ private void panel(GuiGraphicsExtractor graphics) { for (int color = 0; color < FacePaint.COLORS; color++) { int px = x+TANK_X+STRIDE*color, py = y+TANK_Y; graphics.fill(px, py, px+SWATCH_SIZE, py+SWATCH_SIZE, selected == color ? 0xFFFFFFFF : 0xFF695E56); - graphics.fill(px+1, py+1, px+SWATCH_SIZE-1, py+SWATCH_SIZE-1, 0xFF000000 | FacePaint.rgb(color)); + graphics.fill(px+1, py+1, px+SWATCH_SIZE-1, py+SWATCH_SIZE-1, 0xFF000000 | PaintColors.rgb(color)); int gaugeY = py+SWATCH_SIZE+1; graphics.fill(px, gaugeY, px+SWATCH_SIZE, gaugeY+2, 0xFF40352D); int fill = Math.ceilDiv(menu.volume(color)*SWATCH_SIZE, 100); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java index acc03fe..03040ef 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.client; +import net.modcrafters.minecraft.primalpottery.pottery.PaintColors; import java.util.ArrayList; import java.util.List; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; @@ -75,7 +76,7 @@ private static Mesh.Quad strip(double x, double base, double z, Station a, Stati float nz = (float)(-rise*Math.sin(mid)/normalLength); Mesh.Quad q = new Mesh.Quad(nx, ny, nz, Mesh.Texture.PIGMENT); q.cornerNormals = new float[12]; - if (!atlas) q.pigment = FacePaint.rgb(ink); + if (!atlas) q.pigment = PaintColors.rgb(ink); for (int v = 0; v < 4; v++) { double u = v < 2 ? from : to; double t = (u-start)/(end-start); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java index b44a886..2ce8ef8 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.client; +import net.modcrafters.minecraft.primalpottery.pottery.PaintColors; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; @@ -80,7 +81,7 @@ private static void paintRows(Mesh mesh, Mesh.Quad face, FacePaint pattern) { continue; } Mesh.Quad strip = new Mesh.Quad(face.nx, face.ny, face.nz, Mesh.Texture.PIGMENT); - strip.pigment = FacePaint.rgb(color); + strip.pigment = PaintColors.rgb(color); strip.cornerNormals = new float[12]; for (int v = 0; v < 4; v++) { float u = (v == 0 || v == 3 ? start : x) / 16F; diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/TemplateScreen.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/TemplateScreen.java index 447e606..377642e 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/TemplateScreen.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/TemplateScreen.java @@ -323,7 +323,7 @@ private void paint(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { String hint = this.turning || this.overPreview(mouseX, mouseY) ? "turn_hint" : (insideTool ? "hollow_hint" : "shape_hint"); graphics.text(this.font, label(hint), this.left + 9, this.top + 167, 0xFF403C37, false); PotteryType type = this.info.type(); - Component kind = type.isServingDish() || type.isVessel() ? type.shapeName() : Component.literal(type.label()); + Component kind = type.isServingDish() || type.isVessel() ? Component.translatable(type.shapeKey()) : Component.literal(type.label()); graphics.text(this.font, kind, this.left + 28, this.top + 181, 0xFF403C37, false); if (!type.isServingDish()) { Component capacity = Component.translatable("gui.primalpottery.template.volume", this.info.volume()); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java index 5d47da3..8f40852 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.item; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import java.util.Map; import java.util.function.Consumer; import net.minecraft.core.BlockPos; @@ -103,7 +104,7 @@ public static Component dyedName(Component name, @Nullable String dye) { @Override public Component getName(ItemStack stack) { - return dyedName(read(stack).classify().type().shapeName(), dye(stack)); + return dyedName(Component.translatable(read(stack).classify().type().shapeKey()), dye(stack)); } public static ItemStack stack(Pottery pottery) { @@ -125,7 +126,7 @@ public static ItemStack stack(Pottery pottery, VesselContents contents, boolean public static ItemStack stack(Pottery pottery, VesselContents contents, boolean lid, @Nullable String dye, @Nullable Planter planter) { ItemStack stack = new ItemStack(ModItems.POTTERY); CompoundTag tag = new CompoundTag(); - tag.put("pottery", pottery.save()); + tag.put("pottery", PotteryTags.save(pottery)); contents = contents.limitedTo(pottery); contents.write(tag); if (planter != null) { @@ -171,7 +172,7 @@ public void inventoryTick(ItemStack stack, Level level, Entity owner, int slot, if (data == null || !data.contains("fluid") && !data.contains("soil")) { Pottery profile = read(stack); if (data == null || !data.contains("pottery")) { - CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", profile.save())); + CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", PotteryTags.save(profile))); } stack.set(DataComponents.MAX_STACK_SIZE, profile.size().emptyStackLimit); } @@ -263,7 +264,7 @@ public static Pottery read(ItemStack stack) { if (pottery.isEmpty()) { return Pottery.display(); } - return Pottery.load(pottery); + return PotteryTags.load(pottery); } public static VesselContents contents(ItemStack stack) { diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java index e9384c8..b49d8dc 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.item; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import java.util.List; import java.util.function.Consumer; import net.minecraft.ChatFormatting; @@ -35,7 +36,7 @@ public static ItemStack stack(Pottery pottery) { public static ItemStack stack(Pottery pottery, @Nullable String dye) { ItemStack stack = new ItemStack(ModItems.RAW_POTTERY); CompoundTag tag = new CompoundTag(); - tag.put("pottery", pottery.save()); + tag.put("pottery", PotteryTags.save(pottery)); if (dye != null && !dye.isEmpty()) { tag.putString("dye", dye); } @@ -63,7 +64,7 @@ public void inventoryTick(ItemStack stack, Level level, Entity owner, int slot, /** * The profile a wheel may reshape. Null when the stack is dyed, or the pottery compound is missing or invalid. - * {@link Pottery#load} would substitute the display vase for a bad tag, so that stack must not be accepted. + * {@link PotteryTags#load} would substitute the display vase for a bad tag, so that stack must not be accepted. */ public static @Nullable Pottery wheelProfile(ItemStack stack) { if (!stack.is(ModItems.RAW_POTTERY) || PotteryItem.dye(stack) != null) { @@ -77,13 +78,13 @@ public void inventoryTick(ItemStack stack, Level level, Entity owner, int slot, if (pottery.isEmpty()) { return null; } - return Pottery.readProfile(pottery); + return PotteryTags.readProfile(pottery); } @Override public Component getName(ItemStack stack) { return PotteryItem.dyedName( - Component.translatable("item.primalpottery.raw_shape", PotteryItem.read(stack).classify().type().shapeName()), + Component.translatable("item.primalpottery.raw_shape", Component.translatable(PotteryItem.read(stack).classify().type().shapeKey())), PotteryItem.dye(stack) ); } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java index 97affec..7c33184 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.item; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; @@ -62,7 +63,7 @@ public static Pottery fresh(Pottery.Size size) { } public static void write(ItemStack stack, Pottery pottery) { - CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", pottery.save())); + CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", PotteryTags.save(pottery))); } public static Pottery read(ItemStack stack) { @@ -74,7 +75,7 @@ public static Pottery read(ItemStack stack) { if (pottery.isEmpty()) { return null; } - return Pottery.load(pottery); + return PotteryTags.load(pottery); } /** The saved profile, or the editor's starting shape. */ @@ -99,7 +100,7 @@ public void appendHoverText(ItemStack stack, TooltipContext context, List tooltip) { if (ModItems.isBlueprint(stack)) { Pottery.Info info = profile(stack).classify(); - tooltip.accept(Component.translatable("tooltip.primalpottery.type", info.type().tooltipName())); + tooltip.accept(Component.translatable("tooltip.primalpottery.type", Component.translatable(info.type().tooltipKey()))); tooltip.accept(Component.translatable(size(stack) == Pottery.Size.LARGE ? "tooltip.primalpottery.wheel_clay_block" : "tooltip.primalpottery.wheel_clay_ball")); if (info.volume() > 0) { diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/menu/PaintingMenu.java b/src/main/java/net/modcrafters/minecraft/primalpottery/menu/PaintingMenu.java index 19b223e..72f6915 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/menu/PaintingMenu.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/menu/PaintingMenu.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.menu; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import net.minecraft.core.component.DataComponents; import net.minecraft.world.SimpleContainer; import net.minecraft.world.entity.player.Inventory; @@ -186,7 +187,7 @@ private static int inkFor(int color) { private void writeCell(ItemStack stack, Pottery before, int cell, int color) { Pottery painted = before.withPaint(before.paint().with(cell, color)); - CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", painted.save())); + CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", PotteryTags.save(painted))); work.setChanged(); undoInk.set(history.isEmpty() ? 0 : inkFor(history.getLast().previous()) + 2); broadcastChanges(); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintColors.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintColors.java new file mode 100644 index 0000000..1befb71 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintColors.java @@ -0,0 +1,19 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import net.minecraft.world.item.DyeColor; + +public final class PaintColors { + private PaintColors() {} + + public static int rgb(int color) { + if (color >= FacePaint.COLORS) { + return FacePaint.flowerRgb(color); + } + //? if >=1.21 { + return DyeColor.byId(color).getTextureDiffuseColor() & 0xFFFFFF; + //?} else { + /*float[] rgb = DyeColor.byId(color).getTextureDiffuseColors(); + return Math.round(rgb[0] * 255) << 16 | Math.round(rgb[1] * 255) << 8 | Math.round(rgb[2] * 255); + *///?} + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java deleted file mode 100644 index 9a708dc..0000000 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryDisc.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.modcrafters.minecraft.primalpottery.pottery; - -public record PotteryDisc(double height, double radius, double innerRadius) { - public PotteryDisc(double height, double radius) { - this(height, radius, 0); - } -} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTags.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTags.java new file mode 100644 index 0000000..72fb73a --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTags.java @@ -0,0 +1,30 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; + +public final class PotteryTags extends PotteryCodec { + private static final PotteryTags CODEC = new PotteryTags(); + + public static CompoundTag save(Pottery pot) { return CODEC.encode(pot); } + public static Pottery readProfile(CompoundTag tag) { return CODEC.decode(tag); } + + public static Pottery load(CompoundTag tag) { + Pottery profile = readProfile(tag); + return profile == null ? Pottery.display() : profile; + } + + protected CompoundTag compound() { return new CompoundTag(); } + protected ListTag list() { return new ListTag(); } + protected ListTag discs(CompoundTag tag) { return Nbt.list(tag, "discs"); } + protected int size(ListTag list) { return list.size(); } + protected CompoundTag at(ListTag list, int i) { return Nbt.compoundAt(list, i); } + protected void append(ListTag list, CompoundTag disc) { list.add(disc); } + protected void writeDiscs(CompoundTag tag, ListTag discs) { tag.put("discs", discs); } + protected void number(CompoundTag tag, String key, double value) { tag.putDouble(key, value); } + protected double number(CompoundTag tag, String key) { return Nbt.getDouble(tag, key); } + protected void flag(CompoundTag tag, String key) { tag.putBoolean(key, true); } + protected boolean flagged(CompoundTag tag, String key) { return Nbt.getBoolean(tag, key); } + protected void text(CompoundTag tag, String key, String value) { tag.putString(key, value); } + protected String text(CompoundTag tag, String key) { return Nbt.getString(tag, key); } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java b/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java deleted file mode 100644 index a88f42b..0000000 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryType.java +++ /dev/null @@ -1,57 +0,0 @@ -package net.modcrafters.minecraft.primalpottery.pottery; - -import java.util.Locale; -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.Component; - -public enum PotteryType { - LUMP("Just a lump of clay", ChatFormatting.DARK_RED), - LUMP_NO_BOTTOM("A pipe?", ChatFormatting.DARK_RED), - LUMP_THIN("Too thin!", ChatFormatting.DARK_RED), - PLATE("A plate!", ChatFormatting.DARK_AQUA), - PLATTER("A serving platter!", ChatFormatting.DARK_AQUA), - POT("A bowl!", ChatFormatting.DARK_AQUA), - JAR("Pottery", ChatFormatting.DARK_AQUA), - JUG("A jug!", ChatFormatting.DARK_AQUA); - - private final String label; - private final ChatFormatting color; - - PotteryType(String label, ChatFormatting color) { - this.label = label; - this.color = color; - } - - public String label() { - return this.label; - } - - public ChatFormatting color() { - return this.color; - } - - public boolean isVessel() { - return this == POT || this == JAR || this == JUG; - } - - public Component tooltipName() { - PotteryType type = isServingDish() || this.isVessel() ? this : LUMP; - return Component.translatable("pottery.primalpottery.type." + type.name().toLowerCase(Locale.ROOT)); - } - - public boolean isServingDish() { - return this == PLATE || this == PLATTER; - } - - /** Wide mouth is a bowl, narrow mouth is a jug, and every other shape is pottery. */ - public Component shapeName() { - String shape = switch (this) { - case PLATE -> "plate"; - case PLATTER -> "platter"; - case JUG -> "jug"; - case POT -> "bowl"; - default -> "pottery"; - }; - return Component.translatable("pottery.primalpottery.shape." + shape); - } -} diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java index 2a9f4a7..84280a6 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java @@ -1,5 +1,6 @@ package net.modcrafters.minecraft.primalpottery.client; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; @@ -33,7 +34,7 @@ void stampSamplesTheSpriteFrameAndTintInPaintingTableOrder() { int[] pixels = new int[256]; var sheet = new java.awt.image.BufferedImage(32, 64, java.awt.image.BufferedImage.TYPE_INT_ARGB); sheet.setRGB(31, 33, -1); - int tint = 0xff000000 | net.modcrafters.minecraft.primalpottery.pottery.FacePaint.rgb(11); + int tint = 0xff000000 | net.modcrafters.minecraft.primalpottery.pottery.PaintColors.rgb(11); ItemIconStamp.sampleFrame(pixels, sheet::getRGB, 0, 32, 32, 32, tint); assertEquals(".".repeat(15) + "L" + ".".repeat(240), ItemIconStamp.quantize(pixels)); assertEquals(tint, ItemIconStamp.composite(tint, 0, -1)); @@ -74,7 +75,7 @@ void platterMarksStayOnTheLipAtTheSixServingBoundariesAndSampleOnlyClay() { void firedMeshCacheReusesEqualProfilesAndKeepsFinishesAndPositionsSeparate() { Pottery jug = Pottery.jug(); Mesh plain = Mesh.firedVessel(0, 0, 0, jug); - assertSame(plain, Mesh.firedVessel(0, 0, 0, Pottery.load(jug.save()))); + assertSame(plain, Mesh.firedVessel(0, 0, 0, PotteryTags.load(PotteryTags.save(jug)))); assertNotSame(plain, Mesh.firedVessel(8, 0, 0, jug)); var custom = new Pottery(jug.size(), jug.discs(), jug.paint().with(48, 3)); assertSame(plain, Mesh.placedVessel(0, 0, custom, 1)); diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java index 991dd61..a28b19a 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java @@ -44,17 +44,17 @@ class PotteryTest { @Test void legacyFlowerLoadsAsEditablePixelsAndSavesInTheCustomFormat() { - var saved = Pottery.jug().save(); + var saved = PotteryTags.save(Pottery.jug()); assertFalse(saved.contains("paint")); saved.putString("paint", "flower"); - var pot = Pottery.load(saved); + var pot = PotteryTags.load(saved); var pixels = pot.paint(); int petal = FacePaint.SIDE + 7; - assertEquals(0xFFF1CA, FacePaint.rgb(pixels.color(petal))); - assertEquals(pixels.pixels(), Nbt.getString(pot.save(), "paint")); + assertEquals(0xFFF1CA, PaintColors.rgb(pixels.color(petal))); + assertEquals(pixels.pixels(), Nbt.getString(PotteryTags.save(pot), "paint")); var edited = pot.withPaint(pixels.with(petal, FacePaint.ERASE)); assertEquals(pixels.color(petal + 1), edited.paint().color(petal + 1)); - assertEquals(FacePaint.ERASE, Pottery.load(edited.save()).paint().color(petal)); + assertEquals(FacePaint.ERASE, PotteryTags.load(PotteryTags.save(edited)).paint().color(petal)); } private static final Map DYE_COLORS = Map.ofEntries( @@ -233,13 +233,13 @@ void largeWideShallowProfilesArePlattersAndPreviouslySavedVesselsKeepTheirHollow Pottery platter = new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(5, 12.8, 10), new PotteryDisc(1, 10))); assertEquals(new Pottery.Info(PotteryType.PLATTER, 0), platter.classify()); assertNull(platter.lidDisc()); - CompoundTag tag = platter.save(); - assertTrue(Pottery.load(tag).isPlatter()); + CompoundTag tag = PotteryTags.save(platter); + assertTrue(PotteryTags.load(tag).isPlatter()); tag.remove("platter"); - Pottery legacy = Pottery.load(tag); + Pottery legacy = PotteryTags.load(tag); assertTrue(legacy.classify().volume() > 0); assertTrue(legacy.cover() != null); - assertFalse(Pottery.load(legacy.withPaint(FacePaint.EMPTY.with(0, 3)).save()).isPlatter()); + assertFalse(PotteryTags.load(PotteryTags.save(legacy.withPaint(FacePaint.EMPTY.with(0, 3)))).isPlatter()); assertFalse(new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(6, 12.79))).isPlatter()); assertFalse(new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(7, 16))).isPlatter()); } @@ -315,9 +315,9 @@ void shapedIsTheOnlyLerp() { @Test void itemNameUsesJugBowlOrPottery() { - assertEquals(Component.translatable("pottery.primalpottery.shape.bowl"), vessel(5).classify().type().shapeName()); - assertEquals(Component.translatable("pottery.primalpottery.shape.pottery"), vessel(4).classify().type().shapeName()); - assertEquals(Component.translatable("pottery.primalpottery.shape.jug"), vessel(2.7).classify().type().shapeName()); + assertEquals(Component.translatable("pottery.primalpottery.shape.bowl"), Component.translatable(vessel(5).classify().type().shapeKey())); + assertEquals(Component.translatable("pottery.primalpottery.shape.pottery"), Component.translatable(vessel(4).classify().type().shapeKey())); + assertEquals(Component.translatable("pottery.primalpottery.shape.jug"), Component.translatable(vessel(2.7).classify().type().shapeKey())); assertEquals( Component.translatable("item.primalpottery.raw_shape", Component.translatable("pottery.primalpottery.shape.jug")), RawPotteryItem.stack(vessel(2.7)).getHoverName() @@ -366,7 +366,7 @@ void dyeRoundTripsAndClayTextureUsesTerracotta() { assertEquals(1, new ItemStack(ModItems.RAW_POTTERY).getMaxStackSize()); CompoundTag tag = PotteryItem.customData(raw); assertEquals("blue", Nbt.getString(tag, "dye")); - assertEquals(profile.discs(), Pottery.load(Nbt.compound(tag, "pottery")).discs()); + assertEquals(profile.discs(), PotteryTags.load(Nbt.compound(tag, "pottery")).discs()); assertFalse(tag.contains("fluid")); assertFalse(tag.contains("lid")); assertEquals(0x2F4BFF, raw.getItem().getName(raw).getStyle().getColor().getValue()); @@ -383,10 +383,10 @@ void dyeRoundTripsAndClayTextureUsesTerracotta() { ItemStack missing = new ItemStack(ModItems.RAW_POTTERY); assertNull(RawPotteryItem.wheelProfile(missing)); CompoundTag broken = new CompoundTag(); - broken.put("pottery", new Pottery(List.of(new PotteryDisc(0, 2))).save()); + broken.put("pottery", PotteryTags.save(new Pottery(List.of(new PotteryDisc(0, 2))))); missing.set(net.minecraft.core.component.DataComponents.CUSTOM_DATA, net.minecraft.world.item.component.CustomData.of(broken)); assertNull(RawPotteryItem.wheelProfile(missing)); - assertEquals(Pottery.display().discs(), Pottery.load(Nbt.compound(broken, "pottery")).discs()); + assertEquals(Pottery.display().discs(), PotteryTags.load(Nbt.compound(broken, "pottery")).discs()); ItemStack fired = PotteryItem.stack(profile, VesselContents.EMPTY, false, "blue"); ItemStack undyed = PotteryItem.stack(profile); @@ -497,7 +497,7 @@ void resizeKeepsTheFootAndLipAndRoundTripsAtTheChosenHeight() { assertEquals(5, shortPot.discs().getFirst().radius()); assertEquals(4, shortPot.discs().getLast().radius()); assertEquals(0, shortPot.discs().getLast().innerRadius()); - assertEquals(shortPot.discs(), Pottery.load(shortPot.save()).discs()); + assertEquals(shortPot.discs(), PotteryTags.load(PotteryTags.save(shortPot)).discs()); assertEquals(size.units, shape.withHeight(99).height()); assertEquals(1, shape.withHeight(0).height()); } @@ -575,7 +575,7 @@ void templatesKeepTheirSizeThroughFormingAndFiring() { assertFalse(Pottery.validProfile(Pottery.Size.SMALL, TemplateItem.fresh(Pottery.Size.LARGE).discs())); assertFalse(Pottery.validProfile(Pottery.Size.LARGE, List.of(new PotteryDisc(33, 16)))); assertFalse(Pottery.validProfile(Pottery.Size.LARGE, List.of(new PotteryDisc(32, 16.1)))); - assertEquals(Pottery.Size.SMALL, Pottery.load(Pottery.jug().save()).size()); + assertEquals(Pottery.Size.SMALL, PotteryTags.load(PotteryTags.save(Pottery.jug())).size()); } @Test @@ -585,13 +585,13 @@ void profilesRejectInvalidDimensionsAndKeepOlderZeroWidthWalls() { new PotteryDisc(1, 2, Double.NaN), new PotteryDisc(1, 2, -1))) { Pottery bad = new Pottery(List.of(invalid)); assertFalse(Pottery.validProfile(bad.discs())); - assertEquals(Pottery.display().discs(), Pottery.load(bad.save()).discs()); + assertEquals(Pottery.display().discs(), PotteryTags.load(PotteryTags.save(bad)).discs()); } assertFalse(Pottery.validProfile(List.of(new PotteryDisc(8, 2), new PotteryDisc(8.01, 2)))); assertFalse(Pottery.validProfile(java.util.Collections.nCopies(65, new PotteryDisc(0.1, 2)))); Pottery crossed = new Pottery(List.of(new PotteryDisc(1, 2, 3), new PotteryDisc(1, 2))); assertFalse(Pottery.validProfile(crossed.discs())); - assertEquals(List.of(new PotteryDisc(1, 2, 2), new PotteryDisc(1, 2)), Pottery.load(crossed.save()).discs()); + assertEquals(List.of(new PotteryDisc(1, 2, 2), new PotteryDisc(1, 2)), PotteryTags.load(PotteryTags.save(crossed)).discs()); } @Test @@ -601,7 +601,7 @@ void nbtRoundTripKeepsTheShape() { new PotteryDisc(2, 4, 2), new PotteryDisc(1, 4, 0) )); - Pottery loaded = Pottery.load(pottery.save()); + Pottery loaded = PotteryTags.load(PotteryTags.save(pottery)); assertEquals(PotteryType.JUG, loaded.classify().type()); assertEquals(3, loaded.discs().size()); assertEquals(4, loaded.discs().getFirst().radius(), 0.0001); diff --git a/stonecutter.gradle.kts b/stonecutter.gradle.kts index aea991e..613609c 100644 --- a/stonecutter.gradle.kts +++ b/stonecutter.gradle.kts @@ -4,6 +4,7 @@ plugins { id("net.fabricmc.fabric-loom") version "1.18.1" apply false // see https://projects.neoforged.net/neoforged/moddevgradle for new versions id("net.neoforged.moddev") version "2.0.147" apply false + id("net.neoforged.moddev.legacyforge") version "2.0.147" apply false } stonecutter active "26.3" @@ -61,8 +62,8 @@ subprojects { // The active version's merge writes this branch's shared sources. Other versions read those folders // while generating, so they have to wait for that write. Their own merge is not a dependency: running // it would copy the inactive version back over the shared sources. - if (parent != null) { - val activeNode = parent!!.project("26.3") + val activeNode = parent?.findProject("26.3") + if (activeNode != null && name.first().isDigit()) { if (path != activeNode.path) { val activeMerge = activeNode.tasks.named("stonecutterMerge") val activeTestMerge = activeNode.tasks.named("stonecutterMergeTest") From 50b676df5dca6b639ee09c169344dcb6cf3e8351 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 18:30:48 +0200 Subject: [PATCH 02/22] Test the shared painted mesh and expose the preview jars in CI Co-authored-by: Face of Cat --- .github/workflows/ci.yml | 10 +++++- core/build.gradle | 2 ++ .../pottery/PaintedVesselTest.java | 35 +++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dedf349..c31c8ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,6 +3,7 @@ name: CI # Every pull request must build and pass on every Minecraft version before it can merge. # `all-versions` requires every version job and the release-script checks, so it is the one check for a ruleset on main to require. on: + workflow_dispatch: pull_request: push: branches: [main] @@ -119,7 +120,7 @@ jobs: - minecraft: '1.20.1' java: '21' directory: . - build: ./gradlew :forge:build + build: ./gradlew :core:test :forge:build client: ./gradlew -I .github/forge-display-check/check.init.gradle :forge:runClient steps: - uses: actions/checkout@v7 @@ -131,6 +132,13 @@ jobs: - name: Build production jar working-directory: ${{ matrix.directory }} run: ${{ matrix.build }} + - uses: actions/upload-artifact@v7 + with: + name: jar-forge-${{ matrix.minecraft }} + path: | + forge/build/libs/primalpottery-forge-${{ matrix.minecraft }}-*.jar + legacy/forge-1.12.2/build/libs/primalpottery-forge-${{ matrix.minecraft }}-*.jar + if-no-files-found: error - name: Render 200 painted pots on the hosted software renderer working-directory: ${{ matrix.directory }} env: diff --git a/core/build.gradle b/core/build.gradle index 4e06a2c..621ab3d 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -6,6 +6,8 @@ java { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } +repositories { mavenCentral() } +dependencies { testImplementation 'junit:junit:4.13.2' } if (JavaVersion.current().isJava9Compatible()) { tasks.withType(JavaCompile).configureEach { options.release = 8 } } diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java new file mode 100644 index 0000000..f7f03b3 --- /dev/null +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java @@ -0,0 +1,35 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PaintedVesselTest { + private static final class FaceCounter extends BakedVessels { + int builds; + @Override protected Integer bake(PaintedVessel.Vertex a, PaintedVessel.Vertex b, + PaintedVessel.Vertex c, PaintedVessel.Vertex d, int pigment) { + builds++; + return pigment; + } + } + + @Test public void independentlyLoadedEqualProfilesShareABakeButDifferentPaintDoesNot() { + FaceCounter counter = new FaceCounter(); + List plain = counter.model(Pottery.jug()); + int built = counter.builds; + assertSame(plain, counter.model(Pottery.jug())); + assertEquals(built, counter.builds); + assertTrue(plain.stream().allMatch(ink -> ink == PaintedVessel.CLAY)); + assertTrue(counter.model(PaintedVessel.SAMPLE).stream().anyMatch(ink -> ink >= 0)); + } + + @Test public void contiguousRowsBecomeOneBandOnEachOfEightFlatFaces() { + char[] pixels = FacePaint.EMPTY.pixels().toCharArray(); + Arrays.fill(pixels, 5 * 16, 11 * 16, 'C'); + Pottery cylinder = new Pottery(Arrays.asList(new PotteryDisc(12, 4, 3), new PotteryDisc(1, 4))); + List quads = new FaceCounter().model(cylinder.withPaint(FacePaint.read(new String(pixels)))); + assertEquals(8, quads.stream().filter(ink -> ink == 2).count()); + } +} From 5a2aed83007bd16592bb3848a1955ef4e9adda6d Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 18:36:10 +0200 Subject: [PATCH 03/22] Give the hosted LWJGL 2 client a virtual monitor mode Co-authored-by: Face of Cat --- .github/forge-display-check/xorg.conf | 24 ++++++++++++++++++++++++ .github/workflows/ci.yml | 17 +++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 .github/forge-display-check/xorg.conf diff --git a/.github/forge-display-check/xorg.conf b/.github/forge-display-check/xorg.conf new file mode 100644 index 0000000..f73ab31 --- /dev/null +++ b/.github/forge-display-check/xorg.conf @@ -0,0 +1,24 @@ +# LWJGL 2 reads monitor modes through xrandr. Give its hosted display a named mode and refresh rate. +Section "Device" + Identifier "Headless" + Driver "dummy" + VideoRam 16384 +EndSection + +Section "Monitor" + Identifier "Virtual monitor" + HorizSync 30-80 + VertRefresh 50-75 + Modeline "1280x720" 74.50 1280 1344 1472 1664 720 723 728 748 -hsync +vsync +EndSection + +Section "Screen" + Identifier "Screen" + Device "Headless" + Monitor "Virtual monitor" + DefaultDepth 24 + SubSection "Display" + Depth 24 + Modes "1280x720" + EndSubSection +EndSection diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c31c8ec..9767bf7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -121,7 +121,7 @@ jobs: java: '21' directory: . build: ./gradlew :core:test :forge:build - client: ./gradlew -I .github/forge-display-check/check.init.gradle :forge:runClient + client: xvfb-run -a ./gradlew -I .github/forge-display-check/check.init.gradle :forge:runClient steps: - uses: actions/checkout@v7 - uses: actions/setup-java@v6 @@ -139,6 +139,19 @@ jobs: forge/build/libs/primalpottery-forge-${{ matrix.minecraft }}-*.jar legacy/forge-1.12.2/build/libs/primalpottery-forge-${{ matrix.minecraft }}-*.jar if-no-files-found: error + - name: Start a virtual monitor for LWJGL 2 + if: matrix.minecraft == '1.12.2' + run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends xserver-xorg-core xserver-xorg-video-dummy x11-xserver-utils + sudo Xorg :95 -config "$GITHUB_WORKSPACE/.github/forge-display-check/xorg.conf" -nolisten tcp -noreset -logfile "$RUNNER_TEMP/Xorg.log" >"$RUNNER_TEMP/xorg-console.log" 2>&1 & + export DISPLAY=:95 + for attempt in {1..20}; do + if xrandr --query; then echo "DISPLAY=$DISPLAY" >> "$GITHUB_ENV"; exit 0; fi + sleep 1 + done + cat "$RUNNER_TEMP/Xorg.log" + exit 1 - name: Render 200 painted pots on the hosted software renderer working-directory: ${{ matrix.directory }} env: @@ -147,7 +160,7 @@ jobs: run: | mkdir -p "$GITHUB_WORKSPACE/build/display-check" printf 'onboardAccessibility:false\nmaxFps:30\npauseOnLostFocus:false\nrenderDistance:5\n' > "$GITHUB_WORKSPACE/build/display-check/options.txt" - timeout 20m xvfb-run -a ${{ matrix.client }} + timeout 20m ${{ matrix.client }} cat "$GITHUB_WORKSPACE/build/display-check/display-check.txt" - uses: actions/upload-artifact@v7 if: always() From 971984f6a3c298a633e824b2d1bf7eaa831bbbe6 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 18:42:31 +0200 Subject: [PATCH 04/22] Load legacy dev resources and verify the held and placed reference pot Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/DisplayCheck.java | 44 ++++++++++++++++--- .../1.20.1/potterycheck/DisplayCheck.java | 39 +++++++++++++--- legacy/forge-1.12.2/build.gradle | 13 +++++- 3 files changed, 84 insertions(+), 12 deletions(-) diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java index 8f07c83..4baf98f 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -27,13 +27,14 @@ import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; @Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) -// Runs only in the disposable hosted world, under Xvfb with Mesa software rendering. +// Runs only in the disposable hosted world, with Mesa software rendering. public final class DisplayCheck { private static boolean opening; private static boolean placed; private static int ticks; private static long firstFrame; private static long previousFrame; + private static long referenceStarted; private static final ArrayList frames = new ArrayList<>(); private static final String WORLD = "painted-pot-display"; @@ -41,6 +42,12 @@ public final class DisplayCheck { if (event.phase != TickEvent.Phase.END) return; Minecraft mc = Minecraft.getMinecraft(); if (!opening && mc.currentScreen instanceof GuiMainMenu) { + for (String texture : new String[]{"block/fired_clay", "block/pottery_inks"}) { + String id = "primalpottery:" + texture; + if (!id.equals(mc.getTextureMapBlocks().getAtlasSprite(id).getIconName())) { + throw new AssertionError("Missing pottery texture " + id); + } + } opening = true; mc.gameSettings.limitFramerate = 30; mc.gameSettings.pauseOnLostFocus = false; @@ -77,7 +84,15 @@ private static void install(WorldServer level) { @SubscribeEvent public static void frame(TickEvent.RenderTickEvent event) throws Exception { if (!placed || event.phase != TickEvent.Phase.END) return; Minecraft mc = Minecraft.getMinecraft(); - if (mc.player == null || mc.currentScreen != null || mc.player.posZ > -18) return; + if (mc.player == null || mc.currentScreen != null) return; + if (referenceStarted != 0) { + if (mc.player.posX > 39 && System.nanoTime() - referenceStarted > 4_000_000_000L) { + screenshot(mc, "reference.png"); + mc.shutdown(); + } + return; + } + if (mc.player.posZ > -18) return; long now = System.nanoTime(); if (firstFrame == 0) { for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { @@ -89,12 +104,31 @@ private static void install(WorldServer level) { if (now - firstFrame > 5_000_000_000L) frames.add(now - previousFrame); previousFrame = now; if (now - firstFrame < 17_000_000_000L) return; - placed = false; Collections.sort(frames); String report = String.format(Locale.ROOT, "200 checkerboard pots, %d frames, p50 %.2f ms, p95 %.2f ms (30 FPS cap)", frames.size(), frames.get(frames.size() / 2) / 1e6, frames.get(frames.size() * 95 / 100) / 1e6); - ScreenShotHelper.saveScreenshot(new File("."), "pots.png", mc.displayWidth, mc.displayHeight, mc.getFramebuffer()); + screenshot(mc, "pots.png"); Files.write(Paths.get("display-check.txt"), Collections.singletonList(report)); - mc.shutdown(); + referenceStarted = now; + showReference(mc); + } + + private static void showReference(Minecraft mc) { + mc.gameSettings.hideGUI = false; + net.minecraft.server.MinecraftServer server = mc.getIntegratedServer(); + server.addScheduledTask(() -> { + WorldServer level = server.getWorld(0); + level.setBlockState(new BlockPos(40, 79, -2), Blocks.STONE.getDefaultState()); + level.setBlockState(new BlockPos(40, 80, 0), Blocks.STONE.getDefaultState()); + level.setBlockState(new BlockPos(40, 81, 0), PrimalPotteryForge.POT.getDefaultState()); + net.minecraft.entity.player.EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); + player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(PrimalPotteryForge.POT)); + player.inventoryContainer.detectAndSendChanges(); + player.connection.setPlayerLocation(40.5, 80, -1.5, 0, 15); + }); + } + + private static void screenshot(Minecraft mc, String name) throws Exception { + ScreenShotHelper.saveScreenshot(new File("."), name, mc.displayWidth, mc.displayHeight, mc.getFramebuffer()); } } diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index 92219fb..b42aae0 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -30,13 +30,14 @@ import net.minecraftforge.registries.ForgeRegistries; @Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) -// Runs only in the disposable hosted world, under Xvfb with Mesa software rendering. +// Runs only in the disposable hosted world, with Mesa software rendering. public final class DisplayCheck { private static boolean opening; private static boolean placed; private static int ticks; private static long firstFrame; private static long previousFrame; + private static long referenceStarted; private static final ArrayList frames = new ArrayList<>(); private static final String WORLD = "painted-pot-display"; @@ -84,7 +85,15 @@ private static void install(ServerLevel level) { @SubscribeEvent public static void frame(TickEvent.RenderTickEvent event) throws Exception { if (!placed || event.phase != TickEvent.Phase.END) return; Minecraft mc = Minecraft.getInstance(); - if (mc.player == null || mc.screen != null || mc.player.getZ() > -18) return; + if (mc.player == null || mc.screen != null) return; + if (referenceStarted != 0) { + if (mc.player.getX() > 39 && System.nanoTime() - referenceStarted > 4_000_000_000L) { + screenshot(mc, "reference.png"); + mc.stop(); + } + return; + } + if (mc.player.getZ() > -18) return; long now = System.nanoTime(); if (firstFrame == 0) { for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { @@ -96,12 +105,32 @@ private static void install(ServerLevel level) { if (now - firstFrame > 5_000_000_000L) frames.add(now - previousFrame); previousFrame = now; if (now - firstFrame < 17_000_000_000L) return; - placed = false; Collections.sort(frames); String report = String.format(Locale.ROOT, "200 checkerboard pots, %d frames, p50 %.2f ms, p95 %.2f ms (30 FPS cap)", frames.size(), frames.get(frames.size() / 2) / 1e6, frames.get(frames.size() * 95 / 100) / 1e6); - try (var image = Screenshot.takeScreenshot(mc.getMainRenderTarget())) { image.writeToFile(new File("pots.png")); } + screenshot(mc, "pots.png"); Files.write(Paths.get("display-check.txt"), Collections.singletonList(report)); - mc.stop(); + referenceStarted = now; + showReference(mc); + } + + private static void showReference(Minecraft mc) { + mc.options.hideGui = false; + var server = mc.getSingleplayerServer(); + server.execute(() -> { + ServerLevel level = server.overworld(); + var block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation("primalpottery", "pottery")); + level.setBlockAndUpdate(new BlockPos(40, 79, -2), Blocks.STONE.defaultBlockState()); + level.setBlockAndUpdate(new BlockPos(40, 80, 0), Blocks.STONE.defaultBlockState()); + level.setBlockAndUpdate(new BlockPos(40, 81, 0), block.defaultBlockState()); + var player = server.getPlayerList().getPlayers().get(0); + player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, new ItemStack(block)); + player.inventoryMenu.broadcastChanges(); + player.connection.teleport(40.5, 80, -1.5, 0, 15); + }); + } + + private static void screenshot(Minecraft mc, String name) throws Exception { + try (var image = Screenshot.takeScreenshot(mc.getMainRenderTarget())) { image.writeToFile(new File(name)); } } } diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle index f696589..4418c3e 100644 --- a/legacy/forge-1.12.2/build.gradle +++ b/legacy/forge-1.12.2/build.gradle @@ -15,11 +15,20 @@ sourceCompatibility = targetCompatibility = '1.8' project(':core').buildDir = file('build/core') evaluationDependsOn(':core') +// FML 1.12 opens the directory containing @Mod as its resource pack in development. +sourceSets.main.output.resourcesDir = compileJava.destinationDir + minecraft { mappings channel: 'snapshot', version: '20171003-1.12' runs { - client { workingDirectory project.file('run/client') } - server { workingDirectory project.file('run/server') } + client { + workingDirectory project.file('run/client') + forceExit false + } + server { + workingDirectory project.file('run/server') + forceExit false + } } } dependencies { From 2b822892d83c072066dc413748047da0a1019625 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 18:47:18 +0200 Subject: [PATCH 05/22] Position the painted vessel visibly in first person Co-authored-by: Face of Cat --- .../resources/assets/primalpottery/models/block/pottery.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/forge/src/main/resources/assets/primalpottery/models/block/pottery.json b/forge/src/main/resources/assets/primalpottery/models/block/pottery.json index e1d3924..acb02a0 100644 --- a/forge/src/main/resources/assets/primalpottery/models/block/pottery.json +++ b/forge/src/main/resources/assets/primalpottery/models/block/pottery.json @@ -2,6 +2,8 @@ "parent": "block/block", "textures": {"particle": "primalpottery:block/fired_clay"}, "display": { + "firstperson_righthand": {"rotation": [0, 45, 0], "translation": [-2, 8, 0], "scale": [0.85, 0.85, 0.85]}, + "firstperson_lefthand": {"rotation": [0, 225, 0], "translation": [-2, 8, 0], "scale": [0.85, 0.85, 0.85]}, "gui": {"rotation": [30, 45, 0], "translation": [0, 4, 0], "scale": [1.75, 1.75, 1.75]}, "ground": {"translation": [0, 4, 0], "scale": [1, 1, 1]} } From 0860db125848c4a4c192c4870847dfc196fb7a27 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 19:07:01 +0200 Subject: [PATCH 06/22] Draw Forge 1.20.1 pottery paint from reusable atlas tiles and profile terrain GPU time Co-authored-by: Face of Cat --- .../1.20.1/potterycheck/DisplayCheck.java | 76 ++++++++++++-- .../1.20.1/potterycheck/TerrainTiming.java | 64 ++++++++++++ .../primalpottery/pottery/BakedVessels.java | 4 +- .../primalpottery/pottery/PaintedVessel.java | 56 ++++++++-- .../pottery/VesselQuadPacker.java | 4 + .../pottery/PaintedVesselTest.java | 17 +++ .../forge/client/PaintSheet.java | 98 ++++++++++++++++++ .../forge/client/PotteryModel.java | 14 ++- .../forge/client/PotteryQuads.java | 17 ++- .../models/block/paint_sheet.json | 1 + .../primalpottery/models/block/pottery.json | 1 + .../textures/block/paint_sheet.png | Bin 0 -> 334 bytes .../textures/block/paint_sheet.png.mcmeta | 1 + legacy/forge-1.12.2/build.gradle | 3 +- 14 files changed, 333 insertions(+), 23 deletions(-) create mode 100644 .github/forge-display-check/1.20.1/potterycheck/TerrainTiming.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java create mode 100644 forge/src/main/resources/assets/primalpottery/models/block/paint_sheet.json create mode 100644 forge/src/main/resources/assets/primalpottery/textures/block/paint_sheet.png create mode 100644 forge/src/main/resources/assets/primalpottery/textures/block/paint_sheet.png.mcmeta diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index b42aae0..6000767 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -5,7 +5,12 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.util.RandomSource; +import net.minecraftforge.client.model.data.ModelData; import net.minecraft.client.Minecraft; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; @@ -32,12 +37,14 @@ @Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) // Runs only in the disposable hosted world, with Mesa software rendering. public final class DisplayCheck { + private static final Pottery CHECKER = checkerboardJug(); private static boolean opening; private static boolean placed; private static int ticks; private static long firstFrame; private static long previousFrame; private static long referenceStarted; + private static CompletableFuture reload; private static final ArrayList frames = new ArrayList<>(); private static final String WORLD = "painted-pot-display"; @@ -66,15 +73,18 @@ public final class DisplayCheck { } } + private static Pottery checkerboardJug() { + StringBuilder pixels = new StringBuilder(256); + for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) pixels.append((x + y) % 2 == 0 ? 'A' : 'O'); + return Pottery.jug().withPaint(FacePaint.read(pixels.toString())); + } + private static void install(ServerLevel level) { BlockPos platform = new BlockPos(0, 84, -19); level.setBlockAndUpdate(platform, Blocks.STONE.defaultBlockState()); - StringBuilder pixels = new StringBuilder(256); - for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) pixels.append((x + y) % 2 == 0 ? 'A' : 'O'); - Pottery model = Pottery.jug().withPaint(FacePaint.read(pixels.toString())); var block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation("primalpottery", "pottery")); ItemStack stack = new ItemStack(block); - stack.addTagElement("pottery", ForgePotteryTags.save(model)); + stack.addTagElement("pottery", ForgePotteryTags.save(CHECKER)); for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { BlockPos pos = new BlockPos(x, y, 0); level.setBlockAndUpdate(pos, block.defaultBlockState()); @@ -86,8 +96,11 @@ private static void install(ServerLevel level) { if (!placed || event.phase != TickEvent.Phase.END) return; Minecraft mc = Minecraft.getInstance(); if (mc.player == null || mc.screen != null) return; - if (referenceStarted != 0) { - if (mc.player.getX() > 39 && System.nanoTime() - referenceStarted > 4_000_000_000L) { + if (reload != null) { + if (!reload.isDone() || mc.getOverlay() != null || mc.player.getX() < 39) return; + reload.join(); + if (referenceStarted == 0) referenceStarted = System.nanoTime(); + if (System.nanoTime() - referenceStarted > 4_000_000_000L) { screenshot(mc, "reference.png"); mc.stop(); } @@ -97,21 +110,58 @@ private static void install(ServerLevel level) { long now = System.nanoTime(); if (firstFrame == 0) { for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { - if (!(mc.level.getBlockEntity(new BlockPos(x,y,0)) instanceof PaintedPotEntity)) return; + if (!(mc.level.getBlockEntity(new BlockPos(x, y, 0)) instanceof PaintedPotEntity entity)) return; + Pottery pot = entity.getModelData().get(PaintedPotEntity.PROFILE); + if (pot == null || !pot.paint().equals(CHECKER.paint())) return; } firstFrame = previousFrame = now; return; } - if (now - firstFrame > 5_000_000_000L) frames.add(now - previousFrame); + if (now - firstFrame > 5_000_000_000L) { + TerrainTiming.measuring = true; + frames.add(now - previousFrame); + } previousFrame = now; if (now - firstFrame < 17_000_000_000L) return; Collections.sort(frames); String report = String.format(Locale.ROOT, "200 checkerboard pots, %d frames, p50 %.2f ms, p95 %.2f ms (30 FPS cap)", frames.size(), frames.get(frames.size() / 2) / 1e6, frames.get(frames.size() * 95 / 100) / 1e6); screenshot(mc, "pots.png"); - Files.write(Paths.get("display-check.txt"), Collections.singletonList(report)); - referenceStarted = now; + Files.write(Paths.get("display-check.txt"), List.of(report, TerrainTiming.report(), geometryReport(mc))); + verifyFullSheet(mc); showReference(mc); + reload = mc.reloadResourcePacks(); + } + + private static String geometryReport(Minecraft mc) { + var quads = modelQuads(mc, CHECKER); + long overlays = quads.stream().filter(DisplayCheck::usesPaintSheet).count(); + if (overlays == 0) throw new AssertionError("Checkerboard used fallback geometry"); + return quads.size() * 200 + " terrain quads for 200 pots (" + overlays + " paint quads per pot)"; + } + + private static void verifyFullSheet(Minecraft mc) { + // Fill a sheet with distinct one-pixel designs. A full sheet must keep already-visible pots valid. + List last = List.of(); + for (int cell = 0; cell < FacePaint.CELLS; cell++) { + last = modelQuads(mc, CHECKER.withPaint(FacePaint.EMPTY.with(cell, 1))); + } + if (last.stream().anyMatch(DisplayCheck::usesPaintSheet) + || last.stream().noneMatch(q -> q.getSprite().contents().name().getPath().equals("block/pottery_inks")) + || modelQuads(mc, CHECKER).stream().noneMatch(DisplayCheck::usesPaintSheet)) { + throw new AssertionError("Paint sheet overflow lost a design"); + } + } + + private static boolean usesPaintSheet(BakedQuad quad) { + return quad.getSprite().contents().name().getPath().equals("block/paint_sheet"); + } + + private static List modelQuads(Minecraft mc, Pottery pot) { + var state = mc.level.getBlockState(new BlockPos(0, 85, 0)); + var model = mc.getBlockRenderer().getBlockModel(state); + var data = ModelData.builder().with(PaintedPotEntity.PROFILE, pot).build(); + return model.getQuads(state, null, RandomSource.create(0), data, null); } private static void showReference(Minecraft mc) { @@ -123,6 +173,12 @@ private static void showReference(Minecraft mc) { level.setBlockAndUpdate(new BlockPos(40, 79, -2), Blocks.STONE.defaultBlockState()); level.setBlockAndUpdate(new BlockPos(40, 80, 0), Blocks.STONE.defaultBlockState()); level.setBlockAndUpdate(new BlockPos(40, 81, 0), block.defaultBlockState()); + BlockPos neighbor = new BlockPos(39, 81, 0); + level.setBlockAndUpdate(neighbor.below(), Blocks.STONE.defaultBlockState()); + level.setBlockAndUpdate(neighbor, block.defaultBlockState()); + ItemStack checker = new ItemStack(block); + checker.addTagElement("pottery", ForgePotteryTags.save(CHECKER)); + block.setPlacedBy(level, neighbor, block.defaultBlockState(), null, checker); var player = server.getPlayerList().getPlayers().get(0); player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, new ItemStack(block)); player.inventoryMenu.broadcastChanges(); diff --git a/.github/forge-display-check/1.20.1/potterycheck/TerrainTiming.java b/.github/forge-display-check/1.20.1/potterycheck/TerrainTiming.java new file mode 100644 index 0000000..719e57a --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/TerrainTiming.java @@ -0,0 +1,64 @@ +package potterycheck; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Locale; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.RenderLevelStageEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL33; + +/** Asynchronous GPU timestamps bracket opaque terrain, including both cutout layers. */ +@Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) +public final class TerrainTiming { + private record Sample(int begin, int end) {} + private static final ArrayDeque pending = new ArrayDeque<>(); + private static final ArrayList gpuMs = new ArrayList<>(); + private static final ArrayList cpuMs = new ArrayList<>(); + private static long cpuStart; + private static int begin; + static boolean measuring; + + @SubscribeEvent public static void stage(RenderLevelStageEvent event) { + if (!measuring) return; + if (event.getStage() == RenderLevelStageEvent.Stage.AFTER_SKY) { + collect(); + begin = GL15.glGenQueries(); + GL33.glQueryCounter(begin, GL33.GL_TIMESTAMP); + cpuStart = System.nanoTime(); + } + if (event.getStage() == RenderLevelStageEvent.Stage.AFTER_CUTOUT_BLOCKS && begin != 0) { + int end = GL15.glGenQueries(); + GL33.glQueryCounter(end, GL33.GL_TIMESTAMP); + pending.addLast(new Sample(begin, end)); + cpuMs.add((System.nanoTime() - cpuStart) / 1e6); + begin = 0; + } + } + + private static void collect() { + while (!pending.isEmpty() && GL15.glGetQueryObjecti(pending.peek().end(), GL15.GL_QUERY_RESULT_AVAILABLE) != 0) { + Sample sample = pending.remove(); + long elapsed = GL33.glGetQueryObjecti64(sample.end(), GL15.GL_QUERY_RESULT) + - GL33.glGetQueryObjecti64(sample.begin(), GL15.GL_QUERY_RESULT); + gpuMs.add(elapsed / 1e6); + GL15.glDeleteQueries(sample.begin()); + GL15.glDeleteQueries(sample.end()); + } + } + + static String report() { + measuring = false; + collect(); + if (gpuMs.isEmpty()) throw new IllegalStateException("No terrain GPU timings collected"); + Collections.sort(gpuMs); + Collections.sort(cpuMs); + return String.format(Locale.ROOT, "%s; terrain GPU p50 %.3f ms, p95 %.3f ms (%d samples); terrain CPU submit p50 %.3f ms", + GL11.glGetString(GL11.GL_RENDERER), gpuMs.get(gpuMs.size() / 2), gpuMs.get(gpuMs.size() * 95 / 100), + gpuMs.size(), cpuMs.get(cpuMs.size() / 2)); + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java index f876e38..cf28fa7 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java @@ -30,7 +30,7 @@ public synchronized List model(Pottery pot) { List cached = models.get(key); if (cached != null) return cached; List faces = new ArrayList<>(); - new PaintedVessel(pot, (a, b, c, d, ink) -> faces.add(bake(a, b, c, d, ink))); + new PaintedVessel(pot, (a, b, c, d, ink) -> faces.add(bake(a, b, c, d, ink)), paintTile(pot.paint())); List model = Collections.unmodifiableList(faces); if (model.size() > MAX_QUADS) return model; Iterator> oldest = models.values().iterator(); @@ -44,6 +44,8 @@ public synchronized List model(Pottery pot) { return model; } + protected PaintedVessel.PaintTile paintTile(FacePaint paint) { return null; } + protected abstract Q bake(PaintedVessel.Vertex a, PaintedVessel.Vertex b, PaintedVessel.Vertex c, PaintedVessel.Vertex d, int pigment); } diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java index 655e693..075194a 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java @@ -6,6 +6,7 @@ public final class PaintedVessel { public static final Pottery SAMPLE = Pottery.jug().withPaint(FacePaint.read("flower")); public static final int CLAY = -1; + static final int PAINT_TEXTURE = -2; private static final int SIDES = 8; private static final double UNITS = 32; private static final double[] X = new double[SIDES + 1]; @@ -34,6 +35,18 @@ public static final class Vertex { } } + /** Bounds within a stitched paint sheet, in Minecraft's 0..16 sprite coordinates. */ + public static final class PaintTile { + private final double u, v, size; + + public PaintTile(double u, double v, double size) { + this.u = u; + this.v = v; + this.size = size; + } + } + + private final PaintTile tile; private final Pottery pot; private final Faces faces; private final double paintTop; @@ -41,18 +54,18 @@ public static final class Vertex { private final int[] nextPaintRow = new int[FacePaint.SIDE]; public PaintedVessel(Pottery pot, Faces faces) { + this(pot, faces, null); + } + + public PaintedVessel(Pottery pot, Faces faces, PaintTile tile) { + this.tile = tile; this.pot = pot; this.faces = faces; List outside = PotteryProfile.profile(pot.discs(), false); double middle = pot.height() * 0.48; paintSpan = Math.min(2 * Math.sin(Math.PI / 8) * PotteryProfile.sample(outside, middle), pot.height() * 0.84); paintTop = middle + paintSpan / 2; - String pixels = pot.paint().pixels(); - for (int row = FacePaint.SIDE - 1; row >= 0; row--) { - int next = row + 1; - nextPaintRow[row] = next < FacePaint.SIDE && pixels.regionMatches(row * 16, pixels, next * 16, 16) - ? nextPaintRow[next] : next; - } + if (tile == null) findMatchingRows(pot.paint().pixels()); surface(outside, true); surface(PotteryProfile.profile(pot.discs(), true), false); PotteryDisc lip = pot.discs().get(0); @@ -61,6 +74,14 @@ public PaintedVessel(Pottery pot, Faces faces) { ring(0, foot.radius(), foot.innerRadius(), false); } + private void findMatchingRows(String pixels) { + for (int row = FacePaint.SIDE - 1; row >= 0; row--) { + int next = row + 1; + nextPaintRow[row] = next < FacePaint.SIDE && pixels.regionMatches(row * 16, pixels, next * 16, 16) + ? nextPaintRow[next] : next; + } + } + private void surface(List outline, boolean outside) { for (int i = 1; i < outline.size(); i++) { PotteryProfile.Station low = outline.get(i - 1); @@ -103,15 +124,34 @@ private Vertex vertex(int side, double radius, double y, double u, double v) { } private Vertex paintVertex(int side, double radius, double y, int column) { - double t = column / 16.0; + return paintVertex(side, radius, y, column, 8, 8); + } + + private Vertex tileVertex(int side, double radius, double y, int column) { + double u = tile.u + tile.size * column / FacePaint.SIDE; + double v = tile.v + tile.size * (paintTop - y) / paintSpan; + return paintVertex(side, radius, y, column, u, v); + } + + private Vertex paintVertex(int side, double radius, double y, int column, double u, double v) { + double t = column / (double) FacePaint.SIDE; double x = X[side + 1] + (X[side] - X[side + 1]) * t; double z = Z[side + 1] + (Z[side] - Z[side + 1]) * t; - return new Vertex(0.5 + x * radius * 1.003, y / UNITS, 0.5 + z * radius * 1.003, 8, 8); + return new Vertex(0.5 + x * radius * 1.003, y / UNITS, 0.5 + z * radius * 1.003, u, v); } private void paint(PotteryProfile.Station low, PotteryProfile.Station high, int side) { if (paintSpan <= 0 || high.y() <= paintTop - paintSpan || low.y() >= paintTop) return; double slope = (high.radius() - low.radius()) / (high.y() - low.y()); + if (tile != null) { + double top = Math.min(high.y(), paintTop); + double bottom = Math.max(low.y(), paintTop - paintSpan); + double r0 = low.radius() + (bottom - low.y()) * slope; + double r1 = low.radius() + (top - low.y()) * slope; + faces.quad(tileVertex(side, r0, bottom, 0), tileVertex(side, r0, bottom, 16), + tileVertex(side, r1, top, 16), tileVertex(side, r1, top, 0), PAINT_TEXTURE); + return; + } for (int row = 0; row < FacePaint.SIDE;) { int end = nextPaintRow[row]; double top = Math.min(high.y(), paintTop - row * paintSpan / 16); diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java index dcb5bb4..2f2acf8 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java @@ -14,6 +14,9 @@ protected VesselQuadPacker(S clay, S inks, int stride) { this.stride = stride; } + /** Used by adapters that provide texture tiles for whole paint designs. */ + protected S paintSheet() { return inks; } + protected abstract float u(S sprite, float pixels); protected abstract float v(S sprite, float pixels); protected abstract Q quad(int[] data, S sprite, float nx, float ny, float nz); @@ -26,6 +29,7 @@ protected VesselQuadPacker(S clay, S inks, int stride) { float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); int normal = length == 0 ? 0 : pack(nx / length) | pack(ny / length) << 8 | pack(nz / length) << 16; S sprite = pigment == PaintedVessel.CLAY ? clay : inks; + if (pigment == PaintedVessel.PAINT_TEXTURE) sprite = paintSheet(); int[] data = new int[stride * 4]; write(data, 0, a, sprite, normal, pigment); write(data, stride, b, sprite, normal, pigment); diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java index f7f03b3..583c4c1 100644 --- a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java @@ -32,4 +32,21 @@ private static final class FaceCounter extends BakedVessels { List quads = new FaceCounter().model(cylinder.withPaint(FacePaint.read(new String(pixels)))); assertEquals(8, quads.stream().filter(ink -> ink == 2).count()); } + + @Test public void texturedPaintUsesOneQuadPerSideOnAStraightWallAndKeepsTheDesignUpright() { + Pottery cylinder = new Pottery(Arrays.asList(new PotteryDisc(12, 4, 3), new PotteryDisc(1, 4))); + int[] painted = {0}; + PaintedVessel.Faces inspect = (a, b, c, d, ink) -> { + if (ink == PaintedVessel.CLAY) return; + assertEquals(PaintedVessel.PAINT_TEXTURE, ink); + assertEquals(2, a.u, 0.0001); + assertEquals(3, b.u, 0.0001); + assertEquals(6, a.v, 0.0001); + assertEquals(5, d.v, 0.0001); + assertTrue(a.y < d.y); + painted[0]++; + }; + new PaintedVessel(cylinder.withPaint(PaintedVessel.SAMPLE.paint()), inspect, new PaintedVessel.PaintTile(2, 5, 1)); + assertEquals(8, painted[0]); + } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java new file mode 100644 index 0000000..48db500 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java @@ -0,0 +1,98 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import com.mojang.blaze3d.platform.NativeImage; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.Map; +import net.minecraft.client.renderer.texture.MipmapGenerator; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection; +import net.minecraft.client.resources.metadata.animation.FrameSize; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.Resource; +import net.minecraftforge.client.textures.ForgeTextureMetadata; +import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; + +/** Stable tiles in the ordinary block atlas. Compiled chunks can keep their UVs until the next resource reload. */ +final class PaintSheet extends TextureAtlasSprite { + private static final int SIDE = FacePaint.SIDE; + private static final int SHEET_SIZE = 256; + private static final int COLUMNS = SHEET_SIZE / SIDE; + private final Map tiles = new HashMap<>(); + private final ArrayDeque pending = new ArrayDeque<>(); + private final int mipLevels; + + private record Upload(FacePaint paint, int x, int y, TextureAtlasSprite palette) {} + + private PaintSheet(ResourceLocation atlas, SpriteContents contents, int width, int height, int x, int y, int mipLevels) { + super(atlas, contents, width, height, x, y); + this.mipLevels = mipLevels; + } + + /** Chunk workers reserve tiles. Once full, new designs use the existing palette geometry. */ + synchronized PaintTile reserve(FacePaint paint, TextureAtlasSprite palette) { + if (FacePaint.EMPTY.equals(paint)) return null; + PaintTile cached = tiles.get(paint); + if (cached != null) return cached; + if (tiles.size() == COLUMNS * COLUMNS || contents().width() != SHEET_SIZE || contents().height() != SHEET_SIZE + || (SIDE >> mipLevels) == 0) return null; + int x = tiles.size() % COLUMNS; + int y = tiles.size() / COLUMNS; + double span = 16.0 / COLUMNS; + PaintTile tile = new PaintTile(x * span, y * span, span); + tiles.put(paint, tile); + pending.add(new Upload(paint, x * SIDE, y * SIDE, palette)); + return tile; + } + + private synchronized Upload nextUpload() { return pending.poll(); } + + @Override public Ticker createTicker() { + // Minecraft binds the correct atlas before ticking its sprites and replaces the ticker on reload. + return new Ticker() { + @Override public void tickAndUpload() { + for (Upload next = nextUpload(); next != null; next = nextUpload()) upload(next); + } + + @Override public void close() {} + }; + } + + private void upload(Upload slot) { + NativeImage pixels = new NativeImage(SIDE, SIDE, true); + NativeImage[] levels = {pixels}; + try { + TextureAtlasSprite palette = slot.palette(); + for (int i = 0; i < FacePaint.CELLS; i++) { + int ink = slot.paint().color(i); + if (ink == FacePaint.ERASE) continue; + int x = (2 * (ink % 8) + 1) * palette.contents().width() / 16; + int y = (2 * (ink / 8) + 1) * palette.contents().height() / 8; + pixels.setPixelRGBA(i % SIDE, i / SIDE, palette.getPixelRGBA(0, x, y)); + } + levels = MipmapGenerator.generateMipLevels(levels, mipLevels); + for (int i = 0; i < levels.length; i++) { + NativeImage level = levels[i]; + level.upload(i, (getX() + slot.x()) >> i, (getY() + slot.y()) >> i, + 0, 0, level.getWidth(), level.getHeight(), mipLevels > 0, false); + } + } finally { + for (NativeImage level : levels) level.close(); + } + } + + static final class Loader implements ITextureAtlasSpriteLoader { + @Override public SpriteContents loadContents(ResourceLocation name, Resource resource, FrameSize size, NativeImage image, + AnimationMetadataSection animation, ForgeTextureMetadata metadata) { + return new SpriteContents(name, size, image, animation, metadata); + } + + @Override public TextureAtlasSprite makeSprite(ResourceLocation atlas, SpriteContents contents, int width, int height, + int x, int y, int mipLevels) { + return new PaintSheet(atlas, contents, width, height, x, y, mipLevels); + } + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java index dfe123a..b9edbd7 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelEvent; +import net.minecraftforge.client.event.RegisterTextureAtlasSpriteLoadersEvent; import net.minecraftforge.client.model.BakedModelWrapper; import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.eventbus.api.SubscribeEvent; @@ -27,6 +28,7 @@ @Mod.EventBusSubscriber(modid = "primalpottery", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public final class PotteryModel extends BakedModelWrapper { private static final ResourceLocation INKS = new ResourceLocation("primalpottery", "block/pottery_inks"); + private static final ResourceLocation PAINT_SHEET = new ResourceLocation("primalpottery", "block/paint_sheet"); private final PotteryQuads bakery; private final List item; private final ItemOverrides overrides = new ItemOverrides() { @@ -41,13 +43,21 @@ private PotteryModel(BakedModel base, PotteryQuads bakery, List item) this.item = item; } - @SubscribeEvent public static void register(ModelEvent.RegisterAdditional event) { event.register(INKS); } + @SubscribeEvent public static void register(ModelEvent.RegisterAdditional event) { + event.register(INKS); + event.register(PAINT_SHEET); + } + + @SubscribeEvent public static void registerPaintSheet(RegisterTextureAtlasSpriteLoadersEvent event) { + event.register("paint_sheet", new PaintSheet.Loader()); + } @SubscribeEvent public static void bake(ModelEvent.ModifyBakingResult event) { var inks = event.getModels().get(INKS).getParticleIcon(); + var sheet = event.getModels().get(PAINT_SHEET).getParticleIcon(); event.getModels().replaceAll((key, base) -> { if (!key.getNamespace().equals("primalpottery") || !key.getPath().equals("pottery")) return base; - var bakery = new PotteryQuads(base.getParticleIcon(), inks); + var bakery = new PotteryQuads(base.getParticleIcon(), inks, sheet); return new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE)); }); } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java index fd951a4..c726616 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java @@ -3,13 +3,28 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; import net.modcrafters.minecraft.primalpottery.pottery.VesselQuadPacker; final class PotteryQuads extends VesselQuadPacker { - PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks) { + private final PaintSheet sheet; + private final TextureAtlasSprite palette; + + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite sheet) { super(clay, inks, 8); + // A resource pack can animate the ink palette. Its original sprite keeps that animation live. + boolean staticPalette = inks.contents().getUniqueFrames().limit(2).count() == 1; + this.sheet = staticPalette && sheet instanceof PaintSheet custom ? custom : null; + this.palette = inks; + } + + @Override protected PaintTile paintTile(FacePaint paint) { + return sheet == null ? null : sheet.reserve(paint, palette); } + @Override protected TextureAtlasSprite paintSheet() { return sheet; } + @Override protected float u(TextureAtlasSprite sprite, float pixels) { return sprite.getU(pixels); } @Override protected float v(TextureAtlasSprite sprite, float pixels) { return sprite.getV(pixels); } diff --git a/forge/src/main/resources/assets/primalpottery/models/block/paint_sheet.json b/forge/src/main/resources/assets/primalpottery/models/block/paint_sheet.json new file mode 100644 index 0000000..90c9149 --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/models/block/paint_sheet.json @@ -0,0 +1 @@ +{"textures":{"particle":"primalpottery:block/paint_sheet"}} diff --git a/forge/src/main/resources/assets/primalpottery/models/block/pottery.json b/forge/src/main/resources/assets/primalpottery/models/block/pottery.json index acb02a0..cc9338c 100644 --- a/forge/src/main/resources/assets/primalpottery/models/block/pottery.json +++ b/forge/src/main/resources/assets/primalpottery/models/block/pottery.json @@ -1,4 +1,5 @@ { + "render_type": "minecraft:cutout_mipped", "parent": "block/block", "textures": {"particle": "primalpottery:block/fired_clay"}, "display": { diff --git a/forge/src/main/resources/assets/primalpottery/textures/block/paint_sheet.png b/forge/src/main/resources/assets/primalpottery/textures/block/paint_sheet.png new file mode 100644 index 0000000000000000000000000000000000000000..69bfa68234dfdd05aa5dd27fc878caa2a4727afa GIT binary patch literal 334 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K5893O0R7}x|G$2RR)5S5Q;?~=Ph9J2^3%>fl g&E{ADWR74^!OUpGz<5K`nFSOGp00i_>zopr07nTD%>V!Z literal 0 HcmV?d00001 diff --git a/forge/src/main/resources/assets/primalpottery/textures/block/paint_sheet.png.mcmeta b/forge/src/main/resources/assets/primalpottery/textures/block/paint_sheet.png.mcmeta new file mode 100644 index 0000000..6029d7a --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/textures/block/paint_sheet.png.mcmeta @@ -0,0 +1 @@ +{"forge":{"loader":"primalpottery:paint_sheet"}} diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle index 4418c3e..f393eed 100644 --- a/legacy/forge-1.12.2/build.gradle +++ b/legacy/forge-1.12.2/build.gradle @@ -52,6 +52,7 @@ processResources { filesMatching('mcmod.info') { expand(version: project.version) } from('../../src/main/resources') { include 'assets/primalpottery/textures/block/fired_clay.png' } from('../../forge/src/main/resources') { - include 'assets/primalpottery/models/**', 'assets/primalpottery/textures/block/pottery_inks.png' + include 'assets/primalpottery/models/block/pottery.json', 'assets/primalpottery/models/item/pottery.json', + 'assets/primalpottery/textures/block/pottery_inks.png' } } From deefed623b8b8d192693663235c4dab855cee167 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 19:22:14 +0200 Subject: [PATCH 07/22] Share paint tiles across both Forge targets and skip clay hidden by opaque paint Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/DisplayCheck.java | 64 ++++++++++++++----- .../1.20.1/potterycheck/DisplayCheck.java | 21 +++--- .github/forge-display-check/check.init.gradle | 6 +- .../common/potterycheck/FrameReport.java | 24 +++++++ .../primalpottery/pottery/FacePaint.java | 1 + .../pottery/PaintSheetTiles.java | 61 ++++++++++++++++++ .../primalpottery/pottery/PaintedVessel.java | 28 ++++---- .../pottery/PaintSheetTilesTest.java | 43 +++++++++++++ .../pottery/PaintedVesselTest.java | 2 +- .../forge/client/PaintSheet.java | 46 +++---------- .../forge/client/PotteryQuads.java | 10 +-- legacy/forge-1.12.2/build.gradle | 2 +- .../primalpottery/legacy/PaintedPotBlock.java | 2 + .../legacy/client/PaintSheet.java | 31 +++++++++ .../legacy/client/PotteryModel.java | 9 ++- .../legacy/client/PotteryQuads.java | 18 +++++- 16 files changed, 286 insertions(+), 82 deletions(-) create mode 100644 .github/forge-display-check/common/potterycheck/FrameReport.java create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTiles.java create mode 100644 core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTilesTest.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintSheet.java diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java index 4baf98f..bb0cefe 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -3,9 +3,11 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Locale; +import java.util.Arrays; +import java.util.List; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.tileentity.TileEntity; import net.minecraft.client.Minecraft; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; @@ -27,15 +29,16 @@ import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; @Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) -// Runs only in the disposable hosted world, with Mesa software rendering. +// Runs only in the disposable display-check world. public final class DisplayCheck { + private static final Pottery CHECKER = checkerboardJug(); private static boolean opening; private static boolean placed; private static int ticks; private static long firstFrame; private static long previousFrame; private static long referenceStarted; - private static final ArrayList frames = new ArrayList<>(); + private static final FrameReport frames = new FrameReport(); private static final String WORLD = "painted-pot-display"; @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { @@ -66,14 +69,17 @@ public final class DisplayCheck { } } + private static Pottery checkerboardJug() { + StringBuilder pixels = new StringBuilder(256); + for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) pixels.append((x + y) % 2 == 0 ? 'A' : 'O'); + return Pottery.jug().withPaint(FacePaint.read(pixels.toString())); + } + private static void install(WorldServer level) { BlockPos platform = new BlockPos(0, 84, -19); level.setBlockState(platform, Blocks.STONE.getDefaultState()); - StringBuilder pixels = new StringBuilder(256); - for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) pixels.append((x + y) % 2 == 0 ? 'A' : 'O'); - Pottery model = Pottery.jug().withPaint(FacePaint.read(pixels.toString())); ItemStack stack = new ItemStack(PrimalPotteryForge.POT); - stack.setTagInfo("pottery", ForgePotteryTags.save(model)); + stack.setTagInfo("pottery", ForgePotteryTags.save(CHECKER)); for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { BlockPos pos = new BlockPos(x, y, 0); level.setBlockState(pos, PrimalPotteryForge.POT.getDefaultState()); @@ -96,23 +102,43 @@ private static void install(WorldServer level) { long now = System.nanoTime(); if (firstFrame == 0) { for (int x = -10; x < 10; x++) for (int y = 80; y < 90; y++) { - if (!(mc.world.getTileEntity(new BlockPos(x,y,0)) instanceof PaintedPotEntity)) return; + TileEntity entity = mc.world.getTileEntity(new BlockPos(x, y, 0)); + if (!(entity instanceof PaintedPotEntity) || !((PaintedPotEntity) entity).profile().paint().equals(CHECKER.paint())) return; + } + if (FrameReport.UNCAPPED) { + mc.gameSettings.enableVsync = false; + org.lwjgl.opengl.Display.setVSyncEnabled(false); + mc.gameSettings.limitFramerate = (int) net.minecraft.client.settings.GameSettings.Options.FRAMERATE_LIMIT.getValueMax(); } firstFrame = previousFrame = now; return; } - if (now - firstFrame > 5_000_000_000L) frames.add(now - previousFrame); + if (now - firstFrame > 5_000_000_000L) frames.sample(now - previousFrame); previousFrame = now; if (now - firstFrame < 17_000_000_000L) return; - Collections.sort(frames); - String report = String.format(Locale.ROOT, "200 checkerboard pots, %d frames, p50 %.2f ms, p95 %.2f ms (30 FPS cap)", - frames.size(), frames.get(frames.size() / 2) / 1e6, frames.get(frames.size() * 95 / 100) / 1e6); + if (FrameReport.UNCAPPED) { + mc.gameSettings.limitFramerate = 30; + mc.gameSettings.enableVsync = true; + org.lwjgl.opengl.Display.setVSyncEnabled(true); + } + String report = frames.summary(org.lwjgl.opengl.GL11.glGetString(org.lwjgl.opengl.GL11.GL_RENDERER)); screenshot(mc, "pots.png"); - Files.write(Paths.get("display-check.txt"), Collections.singletonList(report)); - referenceStarted = now; + Files.write(Paths.get("display-check.txt"), Arrays.asList(report, geometryReport(mc))); + mc.refreshResources(); + referenceStarted = System.nanoTime(); showReference(mc); } + private static String geometryReport(Minecraft mc) { + BlockPos pos = new BlockPos(0, 85, 0); + IBlockState state = mc.world.getBlockState(pos); + IBlockState extended = state.getBlock().getExtendedState(state, mc.world, pos); + List quads = mc.getBlockRendererDispatcher().getModelForState(state).getQuads(extended, null, 0); + long overlays = quads.stream().filter(q -> q.getSprite().getIconName().equals("primalpottery:block/paint_sheet")).count(); + if (overlays == 0) throw new AssertionError("Checkerboard used fallback geometry"); + return quads.size() * 200 + " terrain quads for 200 pots (" + overlays + " paint quads per pot)"; + } + private static void showReference(Minecraft mc) { mc.gameSettings.hideGUI = false; net.minecraft.server.MinecraftServer server = mc.getIntegratedServer(); @@ -121,6 +147,12 @@ private static void showReference(Minecraft mc) { level.setBlockState(new BlockPos(40, 79, -2), Blocks.STONE.getDefaultState()); level.setBlockState(new BlockPos(40, 80, 0), Blocks.STONE.getDefaultState()); level.setBlockState(new BlockPos(40, 81, 0), PrimalPotteryForge.POT.getDefaultState()); + BlockPos neighbor = new BlockPos(39, 81, 0); + level.setBlockState(neighbor.down(), Blocks.STONE.getDefaultState()); + level.setBlockState(neighbor, PrimalPotteryForge.POT.getDefaultState()); + ItemStack checker = new ItemStack(PrimalPotteryForge.POT); + checker.setTagInfo("pottery", ForgePotteryTags.save(CHECKER)); + PrimalPotteryForge.POT.onBlockPlacedBy(level, neighbor, level.getBlockState(neighbor), null, checker); net.minecraft.entity.player.EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(PrimalPotteryForge.POT)); player.inventoryContainer.detectAndSendChanges(); diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index 6000767..1f3c73f 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -3,10 +3,7 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import java.util.Locale; import java.util.concurrent.CompletableFuture; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.util.RandomSource; @@ -35,7 +32,7 @@ import net.minecraftforge.registries.ForgeRegistries; @Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) -// Runs only in the disposable hosted world, with Mesa software rendering. +// Runs only in the disposable display-check world. public final class DisplayCheck { private static final Pottery CHECKER = checkerboardJug(); private static boolean opening; @@ -45,7 +42,7 @@ public final class DisplayCheck { private static long previousFrame; private static long referenceStarted; private static CompletableFuture reload; - private static final ArrayList frames = new ArrayList<>(); + private static final FrameReport frames = new FrameReport(); private static final String WORLD = "painted-pot-display"; @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { @@ -114,18 +111,24 @@ private static void install(ServerLevel level) { Pottery pot = entity.getModelData().get(PaintedPotEntity.PROFILE); if (pot == null || !pot.paint().equals(CHECKER.paint())) return; } + if (FrameReport.UNCAPPED) { + mc.options.enableVsync().set(false); + mc.options.framerateLimit().set(260); + } firstFrame = previousFrame = now; return; } if (now - firstFrame > 5_000_000_000L) { TerrainTiming.measuring = true; - frames.add(now - previousFrame); + frames.sample(now - previousFrame); } previousFrame = now; if (now - firstFrame < 17_000_000_000L) return; - Collections.sort(frames); - String report = String.format(Locale.ROOT, "200 checkerboard pots, %d frames, p50 %.2f ms, p95 %.2f ms (30 FPS cap)", - frames.size(), frames.get(frames.size() / 2) / 1e6, frames.get(frames.size() * 95 / 100) / 1e6); + if (FrameReport.UNCAPPED) { + mc.options.framerateLimit().set(30); + mc.options.enableVsync().set(true); + } + String report = frames.summary(org.lwjgl.opengl.GL11.glGetString(org.lwjgl.opengl.GL11.GL_RENDERER)); screenshot(mc, "pots.png"); Files.write(Paths.get("display-check.txt"), List.of(report, TerrainTiming.report(), geometryReport(mc))); verifyFullSheet(mc); diff --git a/.github/forge-display-check/check.init.gradle b/.github/forge-display-check/check.init.gradle index 6fdad3c..c9c1823 100644 --- a/.github/forge-display-check/check.init.gradle +++ b/.github/forge-display-check/check.init.gradle @@ -1,15 +1,19 @@ -// Only used by the hosted display check. The production jars are built in a separate Gradle invocation. +// Display-check sources are injected only for test runs. Pass -Puncapped to time hardware beyond the CI frame limit. gradle.beforeProject { p -> if (p.path == ':forge') p.afterEvaluate { p.sourceSets.main.java.srcDir(p.rootProject.file('.github/forge-display-check/1.20.1')) + p.sourceSets.main.java.srcDir(p.rootProject.file('.github/forge-display-check/common')) p.legacyForge.runs.client { + systemProperty 'potterycheck.uncapped', p.hasProperty('uncapped').toString() gameDirectory = p.rootProject.file('build/display-check') programArguments.addAll '--width', '854', '--height', '480' } } if (p == p.rootProject && p.name == 'primalpottery-forge-1.12.2') p.afterEvaluate { p.sourceSets.main.java.srcDir(p.file('../../.github/forge-display-check/1.12.2')) + p.sourceSets.main.java.srcDir(p.file('../../.github/forge-display-check/common')) p.minecraft.runs.client { + property 'potterycheck.uncapped', p.hasProperty('uncapped').toString() workingDirectory p.file('../../build/display-check') args '--width','854','--height','480' mods { primalpottery { source p.sourceSets.main } } diff --git a/.github/forge-display-check/common/potterycheck/FrameReport.java b/.github/forge-display-check/common/potterycheck/FrameReport.java new file mode 100644 index 0000000..845ea4e --- /dev/null +++ b/.github/forge-display-check/common/potterycheck/FrameReport.java @@ -0,0 +1,24 @@ +package potterycheck; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +final class FrameReport { + static final boolean UNCAPPED = Boolean.getBoolean("potterycheck.uncapped"); + private final List frames = new ArrayList<>(); + private long elapsed; + + void sample(long nanos) { + frames.add(nanos); + elapsed += nanos; + } + + String summary(String renderer) { + Collections.sort(frames); + return String.format(Locale.ROOT, "%s; 200 checkerboard pots, %d frames, %.1f average FPS, p50 %.3f ms, p95 %.3f ms (%s)", + renderer, frames.size(), frames.size() * 1e9 / elapsed, frames.get(frames.size() / 2) / 1e6, + frames.get(frames.size() * 95 / 100) / 1e6, UNCAPPED ? "unlimited, VSync off" : "30 FPS cap"); + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java index 6d2ecf3..a80a6db 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/FacePaint.java @@ -29,6 +29,7 @@ public boolean equals(Object obj) { public static final FacePaint EMPTY = new FacePaint(blankPixels()); private static final String FLOWER_INKS = "ipygtsl"; private static final int[] FLOWER_RGB = {0xFFF1CA, 0xEAC89A, 0xF4C04D, 0xCA8338, 0x467D68, 0x62927A, 0x83A979}; + public static final int INK_COUNT = COLORS + FLOWER_RGB.length; private static String blankPixels() { char[] pixels = new char[CELLS]; diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTiles.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTiles.java new file mode 100644 index 0000000..125f907 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTiles.java @@ -0,0 +1,61 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.Map; +import java.util.function.IntBinaryOperator; + +/** One allocation table per stitched sprite. A chunk's UVs remain valid until the next atlas reload. */ +public final class PaintSheetTiles { + public static final int SIZE = 256; + private static final int SIDE = FacePaint.SIDE; + private static final int COLUMNS = SIZE / SIDE; + private final Map tiles = new HashMap<>(); + private final ArrayDeque pending = new ArrayDeque<>(); + + /** Sample the active resource pack once. Both native pixel formats keep alpha in the high byte. */ + public static int[] palette(int width, int height, IntBinaryOperator pixel) { + int[] colors = new int[FacePaint.INK_COUNT]; + for (int ink = 0; ink < colors.length; ink++) { + int x = (2 * (ink % 8) + 1) * width / 16; + int y = (2 * (ink / 8) + 1) * height / 8; + colors[ink] = pixel.applyAsInt(x, y); + } + return colors; + } + + /** Chunk workers reserve tiles. The native texture ticker consumes each upload once. */ + public synchronized PaintedVessel.PaintTile reserve(FacePaint paint, int[] colors) { + if (FacePaint.EMPTY.equals(paint)) return null; + PaintedVessel.PaintTile cached = tiles.get(paint); + if (cached != null) return cached; + if (tiles.size() == COLUMNS * COLUMNS) return null; + int x = tiles.size() % COLUMNS; + int y = tiles.size() / COLUMNS; + int[] pixels = new int[FacePaint.CELLS]; + boolean opaque = true; + for (int i = 0; i < pixels.length; i++) { + int ink = paint.color(i); + pixels[i] = ink == FacePaint.ERASE ? 0 : colors[ink]; + opaque &= pixels[i] >>> 24 == 255; + } + double span = 16.0 / COLUMNS; + PaintedVessel.PaintTile tile = new PaintedVessel.PaintTile(x * span, y * span, span, opaque); + tiles.put(paint, tile); + pending.add(new Upload(x * SIDE, y * SIDE, pixels)); + return tile; + } + + public synchronized Upload poll() { return pending.poll(); } + + public static final class Upload { + public final int x, y; + public final int[] pixels; + + private Upload(int x, int y, int[] pixels) { + this.x = x; + this.y = y; + this.pixels = pixels; + } + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java index 075194a..0255bfe 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java @@ -39,7 +39,10 @@ public static final class Vertex { public static final class PaintTile { private final double u, v, size; - public PaintTile(double u, double v, double size) { + private final boolean opaque; + + public PaintTile(double u, double v, double size, boolean opaque) { + this.opaque = opaque; this.u = u; this.v = v; this.size = size; @@ -92,21 +95,24 @@ private void surface(List outline, boolean outside) { continue; } if (low.radius() == 0 && high.radius() == 0) continue; + boolean covered = outside && tile != null && tile.opaque && paintSpan > 0 + && low.y() >= paintTop - paintSpan && high.y() <= paintTop; for (int side = 0; side < SIDES; side++) { - Vertex a = vertex(side, low.radius(), low.y(), 0, 16); - Vertex b = vertex(side + 1, low.radius(), low.y(), 16, 16); - Vertex c = vertex(side + 1, high.radius(), high.y(), 16, 0); - Vertex d = vertex(side, high.radius(), high.y(), 0, 0); - if (outside) { - faces.quad(b, a, d, c, CLAY); - if (!FacePaint.EMPTY.equals(pot.paint())) paint(low, high, side); - } else { - faces.quad(a, b, c, d, CLAY); - } + if (!covered) clayWall(low, high, side, outside); + if (outside && !FacePaint.EMPTY.equals(pot.paint())) paint(low, high, side); } } } + private void clayWall(PotteryProfile.Station low, PotteryProfile.Station high, int side, boolean outside) { + Vertex a = vertex(side, low.radius(), low.y(), 0, 16); + Vertex b = vertex(side + 1, low.radius(), low.y(), 16, 16); + Vertex c = vertex(side + 1, high.radius(), high.y(), 16, 0); + Vertex d = vertex(side, high.radius(), high.y(), 0, 0); + if (outside) faces.quad(b, a, d, c, CLAY); + else faces.quad(a, b, c, d, CLAY); + } + private void ring(double y, double outer, double inner, boolean up) { if (outer <= inner) return; for (int side = 0; side < SIDES; side++) { diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTilesTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTilesTest.java new file mode 100644 index 0000000..5770bfb --- /dev/null +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintSheetTilesTest.java @@ -0,0 +1,43 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.Arrays; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PaintSheetTilesTest { + @Test public void tileKeepsItsPixelsAndCoordinatesWhenTheSheetFills() { + PaintSheetTiles sheet = new PaintSheetTiles(); + int[] palette = PaintSheetTiles.palette(128, 128, (x, y) -> 0xff000000 | x << 8 | y); + FacePaint first = FacePaint.EMPTY.with(0, 0); + PaintedVessel.PaintTile original = sheet.reserve(first, palette); + PaintSheetTiles.Upload upload = sheet.poll(); + assertEquals(0, upload.x); + assertEquals(0, upload.y); + assertEquals(0xff000810, upload.pixels[0]); + assertEquals(0, upload.pixels[1]); + for (int i = 1; i < FacePaint.CELLS; i++) { + assertNotNull(sheet.reserve(FacePaint.EMPTY.with(i, 0), palette)); + } + assertNull(sheet.reserve(FacePaint.EMPTY.with(0, 1), palette)); + assertSame(original, sheet.reserve(first, palette)); + } + + @Test public void eraseAndTranslucentPaletteEntriesKeepTheUnderlyingClay() { + char[] pixels = new char[FacePaint.CELLS]; + Arrays.fill(pixels, 'A'); + FacePaint opaque = FacePaint.read(new String(pixels)); + int unpainted = clayFaces(FacePaint.EMPTY, 0xffffffff); + assertTrue(clayFaces(opaque, 0xffffffff) < unpainted); + assertEquals(unpainted, clayFaces(opaque.with(0, FacePaint.ERASE), 0xffffffff)); + assertEquals(unpainted, clayFaces(opaque, 0x7fffffff)); + } + + private static int clayFaces(FacePaint paint, int color) { + PaintedVessel.PaintTile tile = new PaintSheetTiles().reserve(paint, new int[]{color}); + int[] count = {0}; + new PaintedVessel(Pottery.jug().withPaint(paint), (a, b, c, d, ink) -> { + if (ink == PaintedVessel.CLAY) count[0]++; + }, tile); + return count[0]; + } +} diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java index 583c4c1..8ba3240 100644 --- a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java @@ -46,7 +46,7 @@ private static final class FaceCounter extends BakedVessels { assertTrue(a.y < d.y); painted[0]++; }; - new PaintedVessel(cylinder.withPaint(PaintedVessel.SAMPLE.paint()), inspect, new PaintedVessel.PaintTile(2, 5, 1)); + new PaintedVessel(cylinder.withPaint(PaintedVessel.SAMPLE.paint()), inspect, new PaintedVessel.PaintTile(2, 5, 1, false)); assertEquals(8, painted[0]); } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java index 48db500..8aff19c 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintSheet.java @@ -1,9 +1,6 @@ package net.modcrafters.minecraft.primalpottery.forge.client; import com.mojang.blaze3d.platform.NativeImage; -import java.util.ArrayDeque; -import java.util.HashMap; -import java.util.Map; import net.minecraft.client.renderer.texture.MipmapGenerator; import net.minecraft.client.renderer.texture.SpriteContents; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -14,69 +11,46 @@ import net.minecraftforge.client.textures.ForgeTextureMetadata; import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; -import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; +import net.modcrafters.minecraft.primalpottery.pottery.PaintSheetTiles; /** Stable tiles in the ordinary block atlas. Compiled chunks can keep their UVs until the next resource reload. */ final class PaintSheet extends TextureAtlasSprite { private static final int SIDE = FacePaint.SIDE; - private static final int SHEET_SIZE = 256; - private static final int COLUMNS = SHEET_SIZE / SIDE; - private final Map tiles = new HashMap<>(); - private final ArrayDeque pending = new ArrayDeque<>(); + final PaintSheetTiles tiles = new PaintSheetTiles(); private final int mipLevels; - private record Upload(FacePaint paint, int x, int y, TextureAtlasSprite palette) {} - private PaintSheet(ResourceLocation atlas, SpriteContents contents, int width, int height, int x, int y, int mipLevels) { super(atlas, contents, width, height, x, y); this.mipLevels = mipLevels; } - /** Chunk workers reserve tiles. Once full, new designs use the existing palette geometry. */ - synchronized PaintTile reserve(FacePaint paint, TextureAtlasSprite palette) { - if (FacePaint.EMPTY.equals(paint)) return null; - PaintTile cached = tiles.get(paint); - if (cached != null) return cached; - if (tiles.size() == COLUMNS * COLUMNS || contents().width() != SHEET_SIZE || contents().height() != SHEET_SIZE - || (SIDE >> mipLevels) == 0) return null; - int x = tiles.size() % COLUMNS; - int y = tiles.size() / COLUMNS; - double span = 16.0 / COLUMNS; - PaintTile tile = new PaintTile(x * span, y * span, span); - tiles.put(paint, tile); - pending.add(new Upload(paint, x * SIDE, y * SIDE, palette)); - return tile; + boolean supportsTiles() { + return contents().width() == PaintSheetTiles.SIZE && contents().height() == PaintSheetTiles.SIZE + && (SIDE >> mipLevels) > 0; } - private synchronized Upload nextUpload() { return pending.poll(); } - @Override public Ticker createTicker() { // Minecraft binds the correct atlas before ticking its sprites and replaces the ticker on reload. return new Ticker() { @Override public void tickAndUpload() { - for (Upload next = nextUpload(); next != null; next = nextUpload()) upload(next); + for (PaintSheetTiles.Upload next = tiles.poll(); next != null; next = tiles.poll()) upload(next); } @Override public void close() {} }; } - private void upload(Upload slot) { + private void upload(PaintSheetTiles.Upload slot) { NativeImage pixels = new NativeImage(SIDE, SIDE, true); NativeImage[] levels = {pixels}; try { - TextureAtlasSprite palette = slot.palette(); - for (int i = 0; i < FacePaint.CELLS; i++) { - int ink = slot.paint().color(i); - if (ink == FacePaint.ERASE) continue; - int x = (2 * (ink % 8) + 1) * palette.contents().width() / 16; - int y = (2 * (ink / 8) + 1) * palette.contents().height() / 8; - pixels.setPixelRGBA(i % SIDE, i / SIDE, palette.getPixelRGBA(0, x, y)); + for (int i = 0; i < slot.pixels.length; i++) { + pixels.setPixelRGBA(i % SIDE, i / SIDE, slot.pixels[i]); } levels = MipmapGenerator.generateMipLevels(levels, mipLevels); for (int i = 0; i < levels.length; i++) { NativeImage level = levels[i]; - level.upload(i, (getX() + slot.x()) >> i, (getY() + slot.y()) >> i, + level.upload(i, (getX() + slot.x) >> i, (getY() + slot.y) >> i, 0, 0, level.getWidth(), level.getHeight(), mipLevels > 0, false); } } finally { diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java index c726616..3a84a82 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java @@ -4,23 +4,25 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.PaintSheetTiles; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; import net.modcrafters.minecraft.primalpottery.pottery.VesselQuadPacker; final class PotteryQuads extends VesselQuadPacker { private final PaintSheet sheet; - private final TextureAtlasSprite palette; + private final int[] palette; PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite sheet) { super(clay, inks, 8); // A resource pack can animate the ink palette. Its original sprite keeps that animation live. boolean staticPalette = inks.contents().getUniqueFrames().limit(2).count() == 1; - this.sheet = staticPalette && sheet instanceof PaintSheet custom ? custom : null; - this.palette = inks; + this.sheet = staticPalette && sheet instanceof PaintSheet custom && custom.supportsTiles() ? custom : null; + this.palette = PaintSheetTiles.palette(inks.contents().width(), inks.contents().height(), + (x, y) -> inks.getPixelRGBA(0, x, y)); } @Override protected PaintTile paintTile(FacePaint paint) { - return sheet == null ? null : sheet.reserve(paint, palette); + return sheet == null ? null : sheet.tiles.reserve(paint, palette); } @Override protected TextureAtlasSprite paintSheet() { return sheet; } diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle index f393eed..995ccf3 100644 --- a/legacy/forge-1.12.2/build.gradle +++ b/legacy/forge-1.12.2/build.gradle @@ -53,6 +53,6 @@ processResources { from('../../src/main/resources') { include 'assets/primalpottery/textures/block/fired_clay.png' } from('../../forge/src/main/resources') { include 'assets/primalpottery/models/block/pottery.json', 'assets/primalpottery/models/item/pottery.json', - 'assets/primalpottery/textures/block/pottery_inks.png' + 'assets/primalpottery/textures/block/pottery_inks.png', 'assets/primalpottery/textures/block/paint_sheet.png' } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java index 246078c..4307999 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java @@ -10,6 +10,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; @@ -47,6 +48,7 @@ public final class PaintedPotBlock extends Block implements ITileEntityProvider return tile instanceof PaintedPotEntity ? ((IExtendedBlockState)state).withProperty(PROFILE, ((PaintedPotEntity)tile).profile()) : state; } @Override public TileEntity createNewTileEntity(World world, int metadata) { return new PaintedPotEntity(); } + @Override public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT_MIPPED; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { return BOUNDS; } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintSheet.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintSheet.java new file mode 100644 index 0000000..a6c5408 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintSheet.java @@ -0,0 +1,31 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.texture.TextureUtil; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.PaintSheetTiles; + +/** Forge 1.12 ticks animated sprites with the block atlas bound. Each reserved tile uploads once. */ +final class PaintSheet extends TextureAtlasSprite { + final PaintSheetTiles tiles = new PaintSheetTiles(); + + PaintSheet(String name) { super(name); } + + boolean supportsTiles() { + return getIconWidth() == PaintSheetTiles.SIZE && getIconHeight() == PaintSheetTiles.SIZE + && getFrameCount() == 1 && getFrameTextureData(0).length <= 5; + } + + @Override public boolean hasAnimationMetadata() { return true; } + + @Override public void updateAnimation() { + for (PaintSheetTiles.Upload next = tiles.poll(); next != null; next = tiles.poll()) { + int side = FacePaint.SIDE; + int levels = getFrameTextureData(0).length; + int[][] data = new int[levels][]; + data[0] = next.pixels; + int[][] mips = TextureUtil.generateMipmapData(levels - 1, side, data); + TextureUtil.uploadTextureMipmap(mips, side, side, getOriginX() + next.x, getOriginY() + next.y, false, false); + } + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java index 314b63a..7bcf3a0 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java @@ -36,6 +36,7 @@ @Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) public final class PotteryModel extends BakedModelWrapper { private static final ResourceLocation INKS = new ResourceLocation("primalpottery", "block/pottery_inks"); + private static final ResourceLocation PAINT_SHEET = new ResourceLocation("primalpottery", "block/paint_sheet"); private final PotteryQuads bakery; private final List item; private final ItemOverrideList overrides = new ItemOverrideList(Collections.emptyList()) { @@ -55,14 +56,18 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item new ModelResourceLocation(PrimalPotteryForge.ID, "inventory")); } - @SubscribeEvent public static void stitch(TextureStitchEvent.Pre event) { event.getMap().registerSprite(INKS); } + @SubscribeEvent public static void stitch(TextureStitchEvent.Pre event) { + event.getMap().registerSprite(INKS); + event.getMap().setTextureEntry(new PaintSheet(PAINT_SHEET.toString())); + } @SubscribeEvent public static void bake(ModelBakeEvent event) { TextureAtlasSprite inks = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(INKS.toString()); + TextureAtlasSprite sheet = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(PAINT_SHEET.toString()); for (String variant : new String[]{"normal", "inventory"}) { ModelResourceLocation key = new ModelResourceLocation(PrimalPotteryForge.ID, variant); IBakedModel base = event.getModelRegistry().getObject(key); - PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks); + PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks, sheet); event.getModelRegistry().putObject(key, new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE))); } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java index c8b370b..443d452 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java @@ -4,13 +4,29 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.EnumFacing; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.PaintSheetTiles; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; import net.modcrafters.minecraft.primalpottery.pottery.VesselQuadPacker; final class PotteryQuads extends VesselQuadPacker { - PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks) { + private final PaintSheet sheet; + private final int[] palette; + + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite atlasSprite) { super(clay, inks, DefaultVertexFormats.ITEM.getIntegerSize()); + PaintSheet candidate = atlasSprite instanceof PaintSheet ? (PaintSheet) atlasSprite : null; + sheet = candidate != null && candidate.supportsTiles() && !inks.hasAnimationMetadata() ? candidate : null; + palette = sheet == null ? null : PaintSheetTiles.palette(inks.getIconWidth(), inks.getIconHeight(), + (x, y) -> inks.getFrameTextureData(0)[0][y * inks.getIconWidth() + x]); + } + + @Override protected PaintTile paintTile(FacePaint paint) { + return sheet == null ? null : sheet.tiles.reserve(paint, palette); } + @Override protected TextureAtlasSprite paintSheet() { return sheet; } + @Override protected float u(TextureAtlasSprite sprite, float pixels) { return sprite.getInterpolatedU(pixels); } @Override protected float v(TextureAtlasSprite sprite, float pixels) { return sprite.getInterpolatedV(pixels); } From 2667ef4d55b212ca14885a7cc8b4ed66e05e1fa2 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 20:04:10 +0200 Subject: [PATCH 08/22] Render item and preview paint from shared atlas tiles across modern targets Co-authored-by: Face of Cat --- .../minecraft/primalpottery/client/Mesh.java | 28 ++++++---- .../primalpottery/client/PaintAtlas.java | 11 ++++ .../primalpottery/client/PaintLayer.java | 36 +++++++++++++ .../primalpottery/client/PlatePaint.java | 30 +++-------- .../primalpottery/client/PotteryItemMesh.java | 11 +--- .../client/PotteryItemRenderer.java | 6 ++- .../primalpottery/client/PotteryPaint.java | 52 +------------------ .../primalpottery/client/PotteryPreview.java | 45 +++++++++++----- .../primalpottery/client/PotteryRenderer.java | 4 +- .../client/PotterySpecialRenderer.java | 1 + .../primalpottery/client/Sprites.java | 15 ++++-- .../primalpottery/client/MeshTest.java | 22 +++++--- 12 files changed, 139 insertions(+), 122 deletions(-) create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintLayer.java diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java index a587607..509afeb 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java @@ -6,7 +6,6 @@ import net.minecraft.core.Direction; import net.minecraft.world.phys.Vec3; import net.modcrafters.minecraft.primalpottery.pottery.PlatterSegments; -import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; @@ -57,29 +56,26 @@ public List quads() { return this.quads; } - private record FiredKey(boolean plate, double x, double y, double z, double width, List discs, FacePaint paint) {} + private record FiredKey(boolean plate, boolean platter, double x, double y, double z, double width, List discs) {} private static final LinkedHashMap firedMeshes = new LinkedHashMap<>(16, 0.75F, true); private static int cachedQuads; static Mesh firedVessel(double x, double y, double z, Pottery pottery) { - return firedVessel(x, y, z, pottery, pottery.paint(), 1); + return firedVessel(x, y, z, pottery, 1); } static Mesh placedVessel(double x, double z, Pottery pottery, double width) { - return firedVessel(x, 0, z, pottery, FacePaint.EMPTY, width); + return firedVessel(x, 0, z, pottery, width); } - /** Shared read-only geometry. Placed custom designs draw their paint atlas separately. */ - private static synchronized Mesh firedVessel(double x, double y, double z, Pottery pottery, FacePaint bakedPaint, double width) { - FiredKey key = new FiredKey(pottery.isPlate(), x, y, z, width, pottery.discs(), bakedPaint); + /** Shared read-only clay geometry, independent of the painted design. */ + private static synchronized Mesh firedVessel(double x, double y, double z, Pottery pottery, double width) { + FiredKey key = new FiredKey(pottery.isPlate(), pottery.isPlatter(), x, y, z, width, pottery.discs()); Mesh mesh = firedMeshes.get(key); if (mesh == null) { mesh = new Mesh(); mesh.vessel(x, y, z, pottery, Texture.FIRED_CLAY); mesh.fitSprite(); - if (!FacePaint.EMPTY.equals(bakedPaint)) { - PotteryPaint.apply(mesh, x, y, z, pottery); - } if (width != 1) mesh.scaleWidth(x, z, width); firedMeshes.put(key, mesh); cachedQuads += mesh.quads().size(); @@ -90,6 +86,18 @@ private static synchronized Mesh firedVessel(double x, double y, double z, Potte return mesh; } + private Mesh paintSurface; + + /** Called on a cached fired vessel with its original placement and width. */ + synchronized Mesh paintSurface(double x, double y, double z, Pottery pottery, double width) { + if (paintSurface == null) { + paintSurface = PotteryPaint.overlay(this, x, y, z, pottery); + // Plate mapping uses the profile. Wall mapping already follows the scaled mesh. + if (pottery.isPlate() && width != 1) paintSurface.scaleWidth(x, z, width); + } + return paintSurface; + } + void vessel(double x, double base, double z, Pottery pottery, Texture texture) { vessel(x, base, z, pottery.discs(), texture); if (!pottery.isPlatter()) return; diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java index d3576f9..6f17382 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java @@ -4,6 +4,7 @@ import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.WeakHashMap; import net.minecraft.client.Minecraft; @@ -21,6 +22,15 @@ public final class PaintAtlas { private static final WeakHashMap patterns = new WeakHashMap<>(); private static ReferenceQueue unused = new ReferenceQueue<>(); + // Items and editor previews are transient. Keep recent designs warm between frames. + private static final LinkedHashMap displayed = new LinkedHashMap<>(64, 0.75F, true); + + static Tile forDisplay(FacePaint pattern) { + Tile tile = displayed.computeIfAbsent(pattern, PaintAtlas::acquire); + if (displayed.size() > 128) displayed.pollFirstEntry(); + return tile; + } + record Tile(FacePaint pattern, Page page, int x, int y) {} private static final class TileRef extends WeakReference { @@ -68,6 +78,7 @@ public static void clear() { } pages.clear(); patterns.clear(); + displayed.clear(); unused = new ReferenceQueue<>(); } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintLayer.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintLayer.java new file mode 100644 index 0000000..a374b02 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintLayer.java @@ -0,0 +1,36 @@ +package net.modcrafters.minecraft.primalpottery.client; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import org.jspecify.annotations.Nullable; +//? if >=26.1 { +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.rendertype.RenderTypes; +//?} else { +/*import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +*///?} + +/** A pottery design and the surface it wraps. Queued draws retain their atlas tile until rendered. */ +record PaintLayer(Mesh surface, FacePaint pattern) { + static @Nullable PaintLayer of(Mesh vessel, Pottery pottery, double width) { + return FacePaint.EMPTY.equals(pottery.paint()) ? null + : new PaintLayer(vessel.paintSurface(0, 0, 0, pottery, width), pottery.paint()); + } + + //? if >=26.1 { + void submit(PoseStack pose, SubmitNodeCollector collector, int light) { + var tile = PaintAtlas.forDisplay(pattern); + collector.submitCustomGeometry(pose, RenderTypes.entityCutoutCull(tile.page().texture), + (entry, buffer) -> Sprites.drawPaint(surface, tile, buffer, entry, light)); + } + //?} else { + /*RenderType draw(PoseStack pose, MultiBufferSource buffers, int light, boolean shade) { + var tile = PaintAtlas.forDisplay(pattern); + var type = RenderType.entityCutout(tile.page().texture); + Sprites.drawPaint(surface, tile, buffers.getBuffer(type), pose.last(), light, shade); + return type; + } + *///?} +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java index 03040ef..4aeb1ee 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlatePaint.java @@ -1,6 +1,5 @@ package net.modcrafters.minecraft.primalpottery.client; -import net.modcrafters.minecraft.primalpottery.pottery.PaintColors; import java.util.ArrayList; import java.util.List; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; @@ -26,7 +25,7 @@ private static List surface(Pottery plate) { return path; } - static void build(Mesh mesh, double x, double base, double z, Pottery plate, boolean atlas) { + static void build(Mesh mesh, double x, double base, double z, Pottery plate) { List path = surface(plate); double[] distance = new double[path.size()]; for (int i = 1; i < path.size(); i++) { @@ -45,21 +44,7 @@ static void build(Mesh mesh, double x, double base, double z, Pottery plate, boo if (distance[i] <= distance[i-1]) continue; Station a = path.get(i-1), b = path.get(i); double start = distance[i-1]*FacePaint.SIDE/length, end = distance[i]*FacePaint.SIDE/length; - for (double from = start; from < end;) { - int row = Math.min((int)from, FacePaint.SIDE-1); - int ink = plate.paint().color(column*FacePaint.SIDE + row); - double to = end; - if (!atlas) { - int stop = row+1; - while (stop < end && plate.paint().color(column*FacePaint.SIDE + stop) == ink) stop++; - to = Math.min(end, stop); - } - if (atlas || ink != FacePaint.ERASE) { - mesh.quads().add(strip(x, base, z, a, b, x0, z0, x1, z1, angle, left, right, - start, end, from, to, column, ink, atlas)); - } - from = to; - } + mesh.quads().add(strip(x, base, z, a, b, x0, z0, x1, z1, angle, left, right, start, end, column)); } } } @@ -67,7 +52,7 @@ static void build(Mesh mesh, double x, double base, double z, Pottery plate, boo private static Mesh.Quad strip(double x, double base, double z, Station a, Station b, double x0, double z0, double x1, double z1, double angle, double left, double right, - double start, double end, double from, double to, int column, int ink, boolean atlas) { + double start, double end, int column) { double rise = b.y()-a.y(), run = (b.radius()-a.radius())*Math.cos(Math.PI/8); double normalLength = Math.hypot(rise, run); double mid = angle + Math.PI/8; @@ -76,18 +61,17 @@ private static Mesh.Quad strip(double x, double base, double z, Station a, Stati float nz = (float)(-rise*Math.sin(mid)/normalLength); Mesh.Quad q = new Mesh.Quad(nx, ny, nz, Mesh.Texture.PIGMENT); q.cornerNormals = new float[12]; - if (!atlas) q.pigment = PaintColors.rgb(ink); for (int v = 0; v < 4; v++) { - double u = v < 2 ? from : to; - double t = (u-start)/(end-start); + double u = v < 2 ? start : end; + double t = v < 2 ? 0 : 1; double across = v == 0 || v == 3 ? left : right; // The slight inward/upward inset clears the clay, including vertical inner walls. double radius = Math.max(0, a.radius() + t*(b.radius()-a.radius()) - 0.008); q.x[v] = (float)(x + radius*(x0 + across*(x1-x0))); q.z[v] = (float)(z + radius*(z0 + across*(z1-z0))); q.y[v] = (float)(base + a.y() + t*rise + 0.012); - q.u[v] = atlas ? (float)u : 8; - q.v[v] = atlas ? column + 0.5F : 8; + q.u[v] = (float)u; + q.v[v] = column + 0.5F; q.cornerNormals[v*3] = q.nx; q.cornerNormals[v*3+1] = q.ny; q.cornerNormals[v*3+2] = q.nz; diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemMesh.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemMesh.java index e50afea..4c6167c 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemMesh.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemMesh.java @@ -61,7 +61,7 @@ public static Prepared prepare(Pottery pottery, boolean closed, boolean raw, @Nu lid.fitSprite(); } Identifier texture = raw && PotteryItem.dyeColor(dye) == null ? Sprites.rawTexture() : Sprites.clayTexture(dye); - return new Prepared(vessel, lid, scale(radius, height), texture, Sprites.dyeTint(dye)); + return new Prepared(vessel, lid, raw ? null : PaintLayer.of(vessel, pottery, 1), scale(radius, height), texture, Sprites.dyeTint(dye)); } /** Mesh units to block units, keeping the profile inside a 10 by 12.5 pixel icon. */ @@ -91,12 +91,5 @@ public void draw(PoseStack.Pose pose, VertexConsumer buffer, int light) { } } - public record Prepared(@Nullable Mesh vessel, @Nullable Mesh lid, float scale, Identifier texture, int color) { - public void draw(PoseStack pose, VertexConsumer buffer, int light, boolean shade) { - pose.pushPose(); - pose.scale(this.scale, this.scale, this.scale); - Sprites.draw(this.vessel, this.lid, buffer, pose.last(), light, this.texture, this.color, shade); - pose.popPose(); - } - } + public record Prepared(Mesh vessel, @Nullable Mesh lid, @Nullable PaintLayer paint, float scale, Identifier texture, int color) {} } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemRenderer.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemRenderer.java index faff615..127b016 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemRenderer.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryItemRenderer.java @@ -46,11 +46,13 @@ public void renderByItem( pose.translate(0.0F, -0.5F, 0.0F); var buffer = buffers.getBuffer(RenderType.entityCutout(Sprites.blocks())); PotteryItemMesh.Prepared prepared = PotteryItemMesh.prepare(stack); - prepared.draw(pose, buffer, light, context == ItemDisplayContext.GUI); + pose.scale(prepared.scale(), prepared.scale(), prepared.scale()); + boolean shade = context == ItemDisplayContext.GUI; + Sprites.draw(prepared.vessel(), prepared.lid(), buffer, pose.last(), light, prepared.texture(), prepared.color(), shade); + if (prepared.paint() != null) prepared.paint().draw(pose, buffers, light, shade); if (stack.is(net.modcrafters.minecraft.primalpottery.item.ModItems.POTTERY)) { var fluid = PotteryItemMesh.fluid(PotteryItem.read(stack), PotteryItem.contents(stack), PotteryItem.lid(stack)); if (fluid != null) { - pose.scale(prepared.scale(), prepared.scale(), prepared.scale()); fluid.draw(pose.last(), buffers.getBuffer(fluid.solid() ? RenderType.entitySolid(Sprites.blocks()) : RenderType.entityTranslucent(Sprites.blocks())), light); } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java index 2ce8ef8..437e88f 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPaint.java @@ -1,30 +1,17 @@ package net.modcrafters.minecraft.primalpottery.client; -import net.modcrafters.minecraft.primalpottery.pottery.PaintColors; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; -import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; /** Maps one square of slip decoration across the throwing rings of each exterior face. */ final class PotteryPaint { private PotteryPaint() { } - static void apply(Mesh vessel, double x, double base, double z, Pottery pottery) { - if (pottery.isPlate()) { - PlatePaint.build(vessel, x, base, z, pottery, false); - return; - } - Mesh overlay = overlay(vessel, x, base, z, pottery); - for (Mesh.Quad face : overlay.quads()) { - paintRows(vessel, face, pottery.paint()); - } - } - static Mesh overlay(Mesh vessel, double x, double base, double z, Pottery pottery) { Mesh overlay = new Mesh(); if (pottery.isPlate()) { - PlatePaint.build(overlay, x, base, z, pottery, true); + PlatePaint.build(overlay, x, base, z, pottery); return overlay; } var wall = PotteryProfile.profile(pottery.discs(), false); @@ -67,43 +54,6 @@ static Mesh overlay(Mesh vessel, double x, double base, double z, Pottery potter return overlay; } - private static void paintRows(Mesh mesh, Mesh.Quad face, FacePaint pattern) { - for (int row = Math.max(0, (int) Math.floor(face.v[3])); row < Math.min(16, Math.ceil(face.v[0])); row++) { - double top = Math.max(row, face.v[3]); - double bottom = Math.min(row + 1, face.v[0]); - for (int x = 0; x < FacePaint.SIDE;) { - int start = x++; - int color = pattern.color(row * FacePaint.SIDE + start); - while (x < FacePaint.SIDE && pattern.color(row * FacePaint.SIDE + x) == color) { - x++; - } - if (color == FacePaint.ERASE) { - continue; - } - Mesh.Quad strip = new Mesh.Quad(face.nx, face.ny, face.nz, Mesh.Texture.PIGMENT); - strip.pigment = PaintColors.rgb(color); - strip.cornerNormals = new float[12]; - for (int v = 0; v < 4; v++) { - float u = (v == 0 || v == 3 ? start : x) / 16F; - float t = (float) ((face.v[0] - (v < 2 ? bottom : top)) / (face.v[0] - face.v[3])); - strip.x[v] = sample(face.x, u, t); - strip.y[v] = sample(face.y, u, t); - strip.z[v] = sample(face.z, u, t); - for (int a = 0; a < 3; a++) { - float[] n = face.cornerNormals; - strip.cornerNormals[3 * v + a] = lerp(lerp(n[a], n[a+3], u), lerp(n[a+9], n[a+6], u), t); - } - strip.u[v] = strip.v[v] = 8; - } - mesh.quads().add(strip); - } - } - } - - private static float sample(float[] values, float u, float t) { - return lerp(lerp(values[0], values[1], u), lerp(values[3], values[2], u), t); - } - private static float lerp(float a, float b, float t) { return a + (b - a) * t; } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java index a2f7b62..a13af50 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryPreview.java @@ -42,7 +42,7 @@ private static Mesh displayBlock() { return block; } - record Placement(Mesh pot, List centers, double height, double reach) { + record Placement(Mesh pot, @Nullable PaintLayer paint, List centers, double height, double reach) { Model frame(int width, int height, float tilt) { // Reserve the full sweep once. Neither the support's pivot nor the zoom moves during a drag. double corner = Math.hypot(16, 16); @@ -51,25 +51,25 @@ Model frame(int width, int height, float tilt) { float pivot = (float) Math.min(height - 2, height * above / (above + below) + 3); float scale = (float) Math.min((width - 2) / (2 * corner), Math.min((pivot - 1) / above, (height - pivot - 1) / below)); - return new Model(this.pot, 0, 0, scale, pivot - height / 2F, DISPLAY_BLOCK, tilt, this.centers); + return new Model(this.pot, this.paint, 0, 0, scale, pivot - height / 2F, DISPLAY_BLOCK, tilt, this.centers); } } static Placement placement(Pottery pottery) { - Mesh pot = new Mesh(); - pot.vessel(0, 0, 0, pottery, Mesh.Texture.FIRED_CLAY); - pot.fitSprite(); - if (pottery.isPlate() && pottery.size() == Pottery.Size.SMALL) { + boolean smallPlate = pottery.isPlate() && pottery.size() == Pottery.Size.SMALL; + double width = smallPlate ? net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity.PLATE_SCALE : 1; + Mesh pot = Mesh.placedVessel(0, 0, pottery, width); + PaintLayer paint = PaintLayer.of(pot, pottery, width); + if (smallPlate) { double offset = 32.0 / 3; - pot.scaleWidth(0, 0, net.modcrafters.minecraft.primalpottery.block.PotteryBlockEntity.PLATE_SCALE); - return new Placement(pot, List.of(new Vec3(0, 0, -offset), new Vec3(offset, 0, 0), + return new Placement(pot, paint, List.of(new Vec3(0, 0, -offset), new Vec3(offset, 0, 0), new Vec3(0, 0, offset), new Vec3(-offset, 0, 0)), pottery.height(), 16); } boolean small = pottery.size() == Pottery.Size.SMALL; double radius = pottery.discs().stream().mapToDouble(PotteryDisc::radius).max().orElse(0); double offset = small ? Math.hypot(8, 8) : 0; double height = pottery.discs().stream().mapToDouble(PotteryDisc::height).sum(); - return new Placement(pot, small ? QUARTERS : CENTER, height, offset + radius); + return new Placement(pot, paint, small ? QUARTERS : CENTER, height, offset + radius); } static void drawModel(GuiGraphicsExtractor graphics, Model model, String dye, float spin, int x0, int y0, int x1, int y1) { @@ -93,6 +93,14 @@ static void drawModel(GuiGraphicsExtractor graphics, Model model, PotteryItemMes RenderType type = RenderType.entityCutout(Sprites.blocks()); drawMeshes(model, dye, buffers.getBuffer(type), pose.last()); buffers.endBatch(type); + if (model.paint() != null) { + for (Vec3 center : model.centers()) { + pose.pushPose(); + pose.translate(center.x, 0, center.z); + buffers.endBatch(model.paint().draw(pose, buffers, 0xF000F0, false)); + pose.popPose(); + } + } if (fluid != null) { RenderType fluidType = fluid.solid() ? type : RenderType.entityTranslucent(Sprites.blocks()); fluid.draw(pose.last(), buffers.getBuffer(fluidType), 0xF000F0); @@ -112,12 +120,14 @@ static Model rotatablePot(Pottery pottery, int width, int height, float tilt) { // Fit the full rotation once so a wide bowl or tall vase stays in frame at any tilt. double fit = Math.min((width-4) / Math.max(1, diameter), (height-4) / Math.max(1, Math.hypot(diameter, vesselHeight))); - return new Model(Mesh.firedVessel(0, 0, 0, pottery), 0, (float) (vesselHeight / 2), + Mesh mesh = Mesh.firedVessel(0, 0, 0, pottery); + return new Model(mesh, PaintLayer.of(mesh, pottery, 1), 0, (float) (vesselHeight / 2), (float) fit, 0, null, tilt, CENTER); } static Model model(Pottery pottery, int width, int height, Pottery.@Nullable Cover cover, boolean closed) { Mesh mesh = Mesh.firedVessel(0, 0, 0, pottery); + PaintLayer paint = PaintLayer.of(mesh, pottery, 1); double vesselHeight = 0; double radius = 0; for (PotteryDisc disc : pottery.discs()) { @@ -144,7 +154,7 @@ static Model model(Pottery pottery, int width, int height, Pottery.@Nullable Cov double tilt = Math.toRadians(TILT); double projectedHeight = vesselHeight * Math.cos(tilt) + 2 * radius * Math.sin(tilt); double fit = Math.min((width - 4) / Math.max(1, sceneWidth), (height - 4) / Math.max(1, projectedHeight)); - return new Model(mesh, (float) centerX, (float) (vesselHeight / 2), (float) fit, 0, null, TILT, CENTER); + return new Model(mesh, paint, (float) centerX, (float) (vesselHeight / 2), (float) fit, 0, null, TILT, CENTER); } static void orient(PoseStack pose, Model model, float spin) { @@ -175,9 +185,9 @@ private static void drawMeshes(Model model, String dye, com.mojang.blaze3d.verte } } - record Model(Mesh mesh, float centerX, float centerY, float scale, float offsetY, @Nullable Mesh ground, float tilt, List centers) { + record Model(Mesh mesh, @Nullable PaintLayer paint, float centerX, float centerY, float scale, float offsetY, @Nullable Mesh ground, float tilt, List centers) { Model withTilt(float angle) { - return new Model(mesh, centerX, centerY, scale, offsetY, ground, angle, centers); + return new Model(mesh, paint, centerX, centerY, scale, offsetY, ground, angle, centers); } } @@ -235,6 +245,15 @@ protected void renderToTexture(State state, PoseStack pose, SubmitNodeCollector RenderTypes.entityCutoutCull(Sprites.blocks()), (entry, buffer) -> drawMeshes(state.model(), state.dye(), buffer, entry) ); + Model model = state.model(); + if (model.paint() != null) { + for (Vec3 center : model.centers()) { + pose.pushPose(); + pose.translate(center.x, 0, center.z); + model.paint().submit(pose, collector, 0xF000F0); + pose.popPose(); + } + } var fluid = state.fluid(); if (fluid != null) { collector.submitCustomGeometry(pose, fluid.solid() ? RenderTypes.entitySolid(Sprites.blocks()) diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java index 6eb1e4f..2492173 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java @@ -450,9 +450,7 @@ Mesh fluidMesh(int slot, Pottery pottery, int amount) { PlacedPot(Pottery pottery, double x, double z, double width) { vessel = Mesh.placedVessel(x, z, pottery, width); if (!FacePaint.EMPTY.equals(pottery.paint())) { - paint = PotteryPaint.overlay(vessel, x, 0, z, pottery); - // Plate paint is generated from the unscaled profile, vessel paint from the mesh. - if (pottery.isPlate() && width != 1) paint.scaleWidth(x, z, width); + paint = vessel.paintSurface(x, 0, z, pottery, width); tile = PaintAtlas.acquire(pottery.paint()); } } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotterySpecialRenderer.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotterySpecialRenderer.java index 0182f5d..35ecda9 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotterySpecialRenderer.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotterySpecialRenderer.java @@ -57,6 +57,7 @@ public void submit( RenderTypes.entityCutoutCull(Sprites.blocks()), (pose, buffer) -> Sprites.draw(prepared.vessel(), prepared.lid(), buffer, pose, light, prepared.texture(), prepared.color()) ); + if (prepared.paint() != null) prepared.paint().submit(poseStack, collector, light); drawFluid(drawn, poseStack, collector, light); poseStack.popPose(); } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java index aa001a0..1224015 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java @@ -199,7 +199,7 @@ private static void write(Mesh mesh, @Nullable TextureAtlasSprite forced, Vertex float nz = normals == null ? quad.nz : normals[i + 2]; // Blend the vanilla axis brightnesses for flat-lit inventory icons. float brightness = shade && normals != null - ? nx * nx * 0.6F + nz * nz * 0.8F + ny * ny * (ny > 0 ? 1.0F : 0.5F) + ? curvedShade(nx, ny, nz) : flatShade; put(buffer, pose, transformed, quad.x[vertex], quad.y[vertex], quad.z[vertex], sampleU(sprite, quad.u[vertex]), sampleV(sprite, quad.v[vertex]), light, @@ -208,6 +208,10 @@ private static void write(Mesh mesh, @Nullable TextureAtlasSprite forced, Vertex } } + private static float curvedShade(float nx, float ny, float nz) { + return nx * nx * 0.6F + nz * nz * 0.8F + ny * ny * (ny > 0 ? 1.0F : 0.5F); + } + /** Block-item brightness for the nearest axis. Up is full, down is half, north and south are 0.8, east and west are 0.6. */ private static float faceShade(float nx, float ny, float nz) { float ax = Math.abs(nx); @@ -243,14 +247,19 @@ private static float sampleU(TextureAtlasSprite sprite, float unit) { } static void drawPaint(Mesh overlay, PaintAtlas.Tile tile, VertexConsumer buffer, PoseStack.Pose pose, int light) { + drawPaint(overlay, tile, buffer, pose, light, false); + } + + static void drawPaint(Mesh overlay, PaintAtlas.Tile tile, VertexConsumer buffer, PoseStack.Pose pose, int light, boolean shade) { tile.page().upload(); Vector3f transformed = new Vector3f(); for (Mesh.Quad quad : overlay.quads()) { for (int v = 0; v < 4; v++) { float u = (tile.x() + quad.u[v]) / PaintAtlas.SIZE; float t = (tile.y() + quad.v[v]) / PaintAtlas.SIZE; - put(buffer, pose, transformed, quad.x[v], quad.y[v], quad.z[v], u, t, light, 255, 255, 255, 255, - quad.cornerNormals[3*v], quad.cornerNormals[3*v+1], quad.cornerNormals[3*v+2]); + float nx = quad.cornerNormals[3*v], ny = quad.cornerNormals[3*v+1], nz = quad.cornerNormals[3*v+2]; + int white = shade ? (int) (255 * curvedShade(nx, ny, nz)) : 255; + put(buffer, pose, transformed, quad.x[v], quad.y[v], quad.z[v], u, t, light, white, white, white, 255, nx, ny, nz); } } } diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java index 84280a6..b34e427 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java @@ -4,6 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -72,14 +74,14 @@ void platterMarksStayOnTheLipAtTheSixServingBoundariesAndSampleOnlyClay() { } @Test - void firedMeshCacheReusesEqualProfilesAndKeepsFinishesAndPositionsSeparate() { + void firedMeshesShareGeometryAcrossDesignsAndKeepPositionsSeparate() { Pottery jug = Pottery.jug(); Mesh plain = Mesh.firedVessel(0, 0, 0, jug); assertSame(plain, Mesh.firedVessel(0, 0, 0, PotteryTags.load(PotteryTags.save(jug)))); assertNotSame(plain, Mesh.firedVessel(8, 0, 0, jug)); var custom = new Pottery(jug.size(), jug.discs(), jug.paint().with(48, 3)); assertSame(plain, Mesh.placedVessel(0, 0, custom, 1)); - assertNotSame(plain, Mesh.firedVessel(0, 0, 0, custom)); + assertSame(plain, Mesh.firedVessel(0, 0, 0, custom)); var plate = new Pottery(List.of(new PotteryDisc(2, 8, 6), new PotteryDisc(1, 7, 0))); var full = Mesh.placedVessel(0, 0, plate, 1); float fullX = full.quads().getFirst().x[0]; @@ -105,10 +107,15 @@ void platePaintSpansFloorInnerWallAndRimOnAllEightSectors() { } var ink = plate.paint().with(0, 4).with(63, 9); var painted = new Pottery(plate.size(), plate.discs(), ink); - var pixels = new Mesh(); - PotteryPaint.apply(pixels, 0, 0, 0, painted); - assertEquals(8, pixels.quads().stream().filter(q -> q.x[0] == 0 && q.z[0] == 0).count()); - assertEquals(16, pixels.quads().size()); + var vessel = Mesh.firedVessel(0, 0, 0, painted); + var first = PaintLayer.of(vessel, painted, 1); + var edited = painted.withPaint(ink.with(2, 1)); + var preview = PotteryPreview.rotatablePot(edited, 124, 98, 30); + assertSame(vessel, preview.mesh()); + assertSame(first.surface(), preview.paint().surface()); + assertEquals(edited.paint(), preview.withTilt(45).paint().pattern()); + assertNotEquals(first.pattern(), preview.paint().pattern()); + assertNull(PaintLayer.of(vessel, plate, 1)); } @Test @@ -117,8 +124,7 @@ void customPaintWrapsEachExteriorFaceOnceAcrossTheMiddleOfTheVessel() { var painted = plain.withPaint(plain.paint().with(120, 3)); var mesh = Mesh.placedVessel(8, 24, painted, 1); assertTrue(mesh.quads().stream().noneMatch(quad -> quad.texture == Mesh.Texture.PIGMENT)); - assertTrue(Mesh.firedVessel(8, 0, 24, painted).quads().stream() - .anyMatch(quad -> quad.texture == Mesh.Texture.PIGMENT)); + assertSame(mesh, Mesh.firedVessel(8, 0, 24, painted)); int faces = 0; double middle = painted.height() * 0.48; for (var quad : PotteryPaint.overlay(mesh, 8, 0, 24, painted).quads()) { From 84212b032b18ac0c205a527e20f6875e3995d7ba Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 20:29:49 +0200 Subject: [PATCH 09/22] Keep benchmark reports and documentation in the design repository Co-authored-by: Face of Cat --- .github/workflows/ci.yml | 10 ---------- README.md | 15 ++------------- 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9767bf7..a62d8bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -161,16 +161,6 @@ jobs: mkdir -p "$GITHUB_WORKSPACE/build/display-check" printf 'onboardAccessibility:false\nmaxFps:30\npauseOnLostFocus:false\nrenderDistance:5\n' > "$GITHUB_WORKSPACE/build/display-check/options.txt" timeout 20m ${{ matrix.client }} - cat "$GITHUB_WORKSPACE/build/display-check/display-check.txt" - - uses: actions/upload-artifact@v7 - if: always() - with: - name: forge-display-${{ matrix.minecraft }} - path: | - build/display-check/**/*.png - build/display-check/display-check.txt - build/display-check/logs/latest.log - build/display-check/crash-reports/ all-versions: name: all-versions diff --git a/README.md b/README.md index 815b0b5..d203f1e 100644 --- a/README.md +++ b/README.md @@ -2,17 +2,6 @@ Shape clay on a wheel. -NeoForge covers 1.20.6, 1.21.1, and 26.3. Fabric covers 26.3. Stonecutter keeps their Minecraft integration in `src/`, written for 26.3. The Java 8 library in `core/` owns the pottery profile, classification, dimensions and paint. +The `main` branch is a Java mod built with Stonecutter. NeoForge covers 1.20.6, 1.21.1, and 26.3. Fabric covers 26.3. Shared sources are written for 26.3. The Forge 1.12 mod remains on the `1.12` branch. -`./gradlew collectJars` collects the Stonecutter loader jars in `build/libs//`. - -## Forge painted-pot preview - -The Forge previews for 1.12.2 and 1.20.1 support one fired vessel per block. Use `/give @p primalpottery:pottery` for a flower-painted jug. Place it, reload the world and harvest it in survival to recover the profile and paint. Both versions use the same disc list and 16 × 16 face pattern. The template editor, wheel and firing recipes are later milestones. - -| Target | Build | Output | -|---|---|---| -| Forge 1.20.1 · Java 17 game | From the root, run `./gradlew :forge:build` with the modern Gradle JDK. | `forge/build/libs/` | -| Forge 1.12.2 · Java 8 game | From `legacy/forge-1.12.2/`, set `JAVA_HOME` to a JDK 8 and run `./gradlew build`. | `legacy/forge-1.12.2/build/libs/` | - -Use `gradlew.bat` on Windows. The Forge directories each contain their own block, saved-data and baked-model adapters. Both compile against the same checkout of `core/` and include it in their production jar. +`./gradlew collectJars` writes the loader jars to `build/libs//`. From 3dca3a527250a7eb21dbaace93c5e3bbe2777e3a Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 21:22:55 +0200 Subject: [PATCH 10/22] Cull back-facing pottery geometry and batch atlas draws Co-authored-by: Face of Cat --- .../client/PrimalPotteryNeoForgeClient.java | 5 +- .../minecraft/primalpottery/client/Mesh.java | 7 ++ .../primalpottery/client/PaintAtlas.java | 6 +- .../primalpottery/client/PlacedFaces.java | 68 +++++++++++++++++++ .../primalpottery/client/PotteryRenderer.java | 35 ++++++---- .../primalpottery/client/Sprites.java | 22 ++++-- .../primalpottery/client/MeshTest.java | 27 ++++++++ 7 files changed, 149 insertions(+), 21 deletions(-) create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java diff --git a/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java b/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java index 7b85a22..8b5e036 100644 --- a/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java +++ b/neoforge/src/main/java/net/modcrafters/minecraft/primalpottery/neoforge/client/PrimalPotteryNeoForgeClient.java @@ -79,7 +79,10 @@ public static void register(IEventBus modBus) { }; modBus.addListener(PrimalPotteryNeoForgeClient::renderers); //? if <26.1 { - /*modBus.addListener(PrimalPotteryNeoForgeClient::colors); + /*// Keep the first paint page batched across block entities. Overflow pages use the regular buffer. + modBus.addListener((net.neoforged.neoforge.client.event.RegisterRenderBuffersEvent event) -> + event.registerRenderBuffer(RenderType.entityCutout(net.modcrafters.minecraft.primalpottery.client.PaintAtlas.pageTexture(0)))); + modBus.addListener(PrimalPotteryNeoForgeClient::colors); *///?} //? if >=26.1 { modBus.addListener(PrimalPotteryNeoForgeClient::pictures); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java index 509afeb..ae1ac80 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Mesh.java @@ -87,6 +87,13 @@ private static synchronized Mesh firedVessel(double x, double y, double z, Potte } private Mesh paintSurface; + private PlacedFaces placedFaces; + + /** Only requested after shaping and scaling are complete. */ + synchronized PlacedFaces placedFaces() { + if (placedFaces == null) placedFaces = new PlacedFaces(quads); + return placedFaces; + } /** Called on a cached fired vessel with its original placement and width. */ synchronized Mesh paintSurface(double x, double y, double z, Pottery pottery, double width) { diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java index 6f17382..85b4e25 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PaintAtlas.java @@ -54,7 +54,7 @@ static final class Page { Page(int index) { this.index = index; - texture = Ids.of("dynamic/pottery_paint_" + index); + texture = pageTexture(index); //? if >=26.1 { image = new DynamicTexture(texture::toString, SIZE, SIZE, true); //?} else @@ -72,6 +72,10 @@ void upload() { private PaintAtlas() {} + public static Identifier pageTexture(int index) { + return Ids.of("dynamic/pottery_paint_" + index); + } + public static void clear() { for (Page page : pages) { if (page != null) Minecraft.getInstance().getTextureManager().release(page.texture); diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java new file mode 100644 index 0000000..a0b98b4 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java @@ -0,0 +1,68 @@ +package net.modcrafters.minecraft.primalpottery.client; + +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import net.minecraft.world.phys.Vec3; + +/** Face planes for the back-face-culled render pass of a finished, placed pot. */ +final class PlacedFaces { + private final Face[] faces; + + PlacedFaces(List quads) { + faces = new Face[quads.size()]; + for (int i = 0; i < faces.length; i++) { + Mesh.Quad q = quads.get(i); + faces[i] = new Face(q, Plane.triangle(q, 1, 2), Plane.triangle(q, 2, 3)); + } + } + + Iterable visibleFrom(Vec3 eye) { + return () -> new Iterator<>() { + int index = findNext(0); + + private int findNext(int start) { + while (start < faces.length && !faces[start].visibleFrom(eye)) start++; + return start; + } + + @Override + public boolean hasNext() { + return index < faces.length; + } + + @Override + public Mesh.Quad next() { + if (!hasNext()) throw new NoSuchElementException(); + Mesh.Quad quad = faces[index].quad; + index = findNext(index + 1); + return quad; + } + }; + } + + private record Face(Mesh.Quad quad, Plane first, Plane second) { + boolean visibleFrom(Vec3 eye) { + return first.visibleFrom(eye) || second.visibleFrom(eye); + } + } + + // Follow the index buffer's winding. Curved lighting normals do not describe the face plane. + private record Plane(double nx, double ny, double nz, double offset) { + static Plane triangle(Mesh.Quad q, int b, int c) { + Vec3 origin = corner(q, 0); + Vec3 normal = corner(q, b).subtract(origin).cross(corner(q, c).subtract(origin)); + // Keep grazing faces. A zero-area triangle has no fragments from either side. + double offset = -normal.dot(origin) + 1e-4 * normal.length(); + return new Plane(normal.x, normal.y, normal.z, offset); + } + + private static Vec3 corner(Mesh.Quad q, int i) { + return new Vec3(q.x[i], q.y[i], q.z[i]); + } + + boolean visibleFrom(Vec3 eye) { + return nx * eye.x + ny * eye.y + nz * eye.z + offset > 0; + } + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java index 2492173..3eb15f2 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PotteryRenderer.java @@ -11,6 +11,7 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.BiomeColors; import net.minecraft.core.Direction; +import net.minecraft.world.phys.Vec3; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.DoubleBlockHalf; @@ -109,6 +110,7 @@ public void submit( net.minecraft.client.renderer.SubmitNodeCollector collector, net.minecraft.client.renderer.state.level.CameraRenderState camera ) { + Vec3 eye = localEye(camera.pos, state.blockPos); PlacedPot[] bodies = bodies(state.slots, state.lids); List draws = fluids(bodies, state.slots, state.contents); boolean solidFluid = has(draws, true); @@ -123,7 +125,7 @@ public void submit( poseStack, net.minecraft.client.renderer.rendertype.RenderTypes.entityCutoutCull(Sprites.blocks()), (pose, buffer) -> { - drawClay(bodies, state.lids, state.dyes, buffer, pose, state.lightCoords); + drawClay(eye, bodies, state.lids, state.dyes, buffer, pose, state.lightCoords); drawSoil(state.plantings, buffer, pose, state.lightCoords); drawFluids(draws, buffer, pose, state.lightCoords, true); } @@ -133,7 +135,7 @@ public void submit( if (body != null && body.tile != null) { collector.submitCustomGeometry(poseStack, net.minecraft.client.renderer.rendertype.RenderTypes.entityCutoutCull(body.tile.page().texture), - (pose, buffer) -> Sprites.drawPaint(body.paint, body.tile, buffer, pose, state.lightCoords)); + (pose, buffer) -> Sprites.drawPaint(body.paint.visibleFrom(eye), body.tile, buffer, pose, state.lightCoords, false)); } } if (translucent) { @@ -196,6 +198,7 @@ public void render( int light, int overlay ) { + Vec3 eye = localEye(net.minecraft.client.Minecraft.getInstance().gameRenderer.getMainCamera().getPosition(), blockEntity.getBlockPos()); var slots = blockEntity.slots(); var lids = blockEntity.lids(); PlacedPot[] bodies = bodies(slots, lids); @@ -210,14 +213,14 @@ public void render( poseStack.scale(1 / 32.0F, 1 / 32.0F, 1 / 32.0F); if (occupied(slots) || solidFluid) { var buffer = buffers.getBuffer(net.minecraft.client.renderer.RenderType.entityCutout(Sprites.blocks())); - drawClay(bodies, lids, blockEntity.dyes(), buffer, poseStack.last(), light); + drawClay(eye, bodies, lids, blockEntity.dyes(), buffer, poseStack.last(), light); drawSoil(plantings, buffer, poseStack.last(), light); drawFluids(draws, buffer, poseStack.last(), light, true); } for (PlacedPot body : bodies) { if (body != null && body.tile != null) { var type = net.minecraft.client.renderer.RenderType.entityCutout(body.tile.page().texture); - Sprites.drawPaint(body.paint, body.tile, buffers.getBuffer(type), poseStack.last(), light); + Sprites.drawPaint(body.paint.visibleFrom(eye), body.tile, buffers.getBuffer(type), poseStack.last(), light, false); } } if (translucent) { @@ -424,9 +427,9 @@ private static boolean occupied(Pottery[] slots) { private final Map placed = new WeakHashMap<>(); private static final class PlacedPot { - final Mesh vessel; - Mesh lid; - Mesh paint; + final PlacedFaces vessel; + PlacedFaces lid; + PlacedFaces paint; PaintAtlas.Tile tile; private Mesh fluid; @@ -448,9 +451,10 @@ Mesh fluidMesh(int slot, Pottery pottery, int amount) { } PlacedPot(Pottery pottery, double x, double z, double width) { - vessel = Mesh.placedVessel(x, z, pottery, width); + Mesh clay = Mesh.placedVessel(x, z, pottery, width); + vessel = clay.placedFaces(); if (!FacePaint.EMPTY.equals(pottery.paint())) { - paint = vessel.paintSurface(x, 0, z, pottery, width); + paint = clay.paintSurface(x, 0, z, pottery, width).placedFaces(); tile = PaintAtlas.acquire(pottery.paint()); } } @@ -477,7 +481,7 @@ private PlacedPot[] bodies(Pottery[] slots, boolean[] lids) { lid.fitSprite(); if (i >= PotteryBlockEntity.CORNERS) lid.scaleWidth(x, z, PotteryBlockEntity.PLATE_SCALE); } - positions[i].lid = lid; + positions[i].lid = lid.placedFaces(); } } result[i] = positions[i]; @@ -485,13 +489,20 @@ private PlacedPot[] bodies(Pottery[] slots, boolean[] lids) { return result; } + private static Vec3 localEye(Vec3 camera, BlockPos block) { + return camera.subtract(block.getX(), block.getY(), block.getZ()).scale(32); + } + private static void drawClay( - PlacedPot[] bodies, boolean[] lids, String[] dyes, com.mojang.blaze3d.vertex.VertexConsumer buffer, PoseStack.Pose pose, int light + Vec3 eye, PlacedPot[] bodies, boolean[] lids, String[] dyes, com.mojang.blaze3d.vertex.VertexConsumer buffer, PoseStack.Pose pose, int light ) { for (int i = 0; i < bodies.length; i++) { PlacedPot body = bodies[i]; if (body != null) { - Sprites.draw(body.vessel, lids[i] ? body.lid : null, buffer, pose, light, Sprites.clayTexture(dyes[i]), Sprites.dyeTint(dyes[i])); + var sprite = Sprites.sprite(Sprites.clayTexture(dyes[i])); + int tint = Sprites.dyeTint(dyes[i]); + Sprites.drawPlacedClay(body.vessel.visibleFrom(eye), buffer, pose, light, sprite, tint); + if (lids[i]) Sprites.drawPlacedClay(body.lid.visibleFrom(eye), buffer, pose, light, sprite, tint); } } } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java index 1224015..75407f3 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/Sprites.java @@ -162,22 +162,22 @@ public static void draw(@Nullable Mesh first, @Nullable Mesh second, VertexConsu int green = (color >> 8) & 255; int blue = color & 255; if (first != null) { - write(first, sprite, buffer, pose, light, red, green, blue, 255, shade); + write(first.quads(), sprite, buffer, pose, light, red, green, blue, 255, shade); } if (second != null) { - write(second, sprite, buffer, pose, light, red, green, blue, 255, shade); + write(second.quads(), sprite, buffer, pose, light, red, green, blue, 255, shade); } } private static void write(Mesh mesh, @Nullable TextureAtlasSprite forced, VertexConsumer buffer, PoseStack.Pose pose, int light, int alpha) { - write(mesh, forced, buffer, pose, light, 255, 255, 255, alpha, false); + write(mesh.quads(), forced, buffer, pose, light, 255, 255, 255, alpha, false); } - private static void write(Mesh mesh, @Nullable TextureAtlasSprite forced, VertexConsumer buffer, PoseStack.Pose pose, int light, int red, int green, int blue, int alpha, boolean shade) { + private static void write(Iterable faces, @Nullable TextureAtlasSprite forced, VertexConsumer buffer, PoseStack.Pose pose, int light, int red, int green, int blue, int alpha, boolean shade) { Vector3f transformed = new Vector3f(); Mesh.Texture lastTexture = null; TextureAtlasSprite lastSprite = null; - for (Mesh.Quad quad : mesh.quads()) { + for (Mesh.Quad quad : faces) { boolean paint = quad.texture == Mesh.Texture.PIGMENT; TextureAtlasSprite sprite = forced; if (sprite == null || paint) { @@ -208,6 +208,10 @@ private static void write(Mesh mesh, @Nullable TextureAtlasSprite forced, Vertex } } + static void drawPlacedClay(Iterable faces, VertexConsumer buffer, PoseStack.Pose pose, int light, TextureAtlasSprite sprite, int color) { + write(faces, sprite, buffer, pose, light, color >> 16 & 255, color >> 8 & 255, color & 255, 255, false); + } + private static float curvedShade(float nx, float ny, float nz) { return nx * nx * 0.6F + nz * nz * 0.8F + ny * ny * (ny > 0 ? 1.0F : 0.5F); } @@ -227,7 +231,7 @@ private static float faceShade(float nx, float ny, float nz) { } public static void drawTinted(Mesh mesh, VertexConsumer buffer, PoseStack.Pose pose, int light, int color) { - write(mesh, null, buffer, pose, light, (color >> 16) & 255, (color >> 8) & 255, color & 255, 255, false); + write(mesh.quads(), null, buffer, pose, light, (color >> 16) & 255, (color >> 8) & 255, color & 255, 255, false); } public static void drawFluid(Mesh mesh, VertexConsumer buffer, PoseStack.Pose pose, int light, TextureAtlasSprite sprite, int color) { @@ -251,9 +255,13 @@ static void drawPaint(Mesh overlay, PaintAtlas.Tile tile, VertexConsumer buffer, } static void drawPaint(Mesh overlay, PaintAtlas.Tile tile, VertexConsumer buffer, PoseStack.Pose pose, int light, boolean shade) { + drawPaint(overlay.quads(), tile, buffer, pose, light, shade); + } + + static void drawPaint(Iterable faces, PaintAtlas.Tile tile, VertexConsumer buffer, PoseStack.Pose pose, int light, boolean shade) { tile.page().upload(); Vector3f transformed = new Vector3f(); - for (Mesh.Quad quad : overlay.quads()) { + for (Mesh.Quad quad : faces) { for (int v = 0; v < 4; v++) { float u = (tile.x() + quad.u[v]) / PaintAtlas.SIZE; float t = (tile.y() + quad.v[v]) / PaintAtlas.SIZE; diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java index b34e427..ea07180 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java @@ -10,6 +10,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.core.Direction; +import net.minecraft.world.phys.Vec3; import java.util.ArrayList; import java.util.List; import net.modcrafters.minecraft.primalpottery.pottery.PlatterSegments; @@ -73,6 +75,31 @@ void platterMarksStayOnTheLipAtTheSixServingBoundariesAndSampleOnlyClay() { } } + @Test + void placedFacesUseTheWindingOfBothTriangles() { + var mesh = new Mesh(); + mesh.boxFace(0, 0, 0, 2, 2, 0, Direction.SOUTH, Mesh.Texture.FIRED_CLAY); + var quad = mesh.quads().getFirst(); + quad.z[3] = 2; // The second triangle now faces sideways as well as forward. + var faces = mesh.placedFaces(); + assertSame(quad, faces.visibleFrom(new Vec3(1, 1, 4)).iterator().next()); + assertTrue(faces.visibleFrom(new Vec3(8, 1, -1)).iterator().hasNext()); + assertFalse(faces.visibleFrom(new Vec3(1, 1, -4)).iterator().hasNext()); + } + + @Test + void repeatedCornerOnARimFacetDoesNotHideItsVisibleTriangle() { + var mesh = new Mesh(); + mesh.boxFace(0, 0, 0, 2, 2, 0, Direction.SOUTH, Mesh.Texture.FIRED_CLAY); + var quad = mesh.quads().getFirst(); + quad.x[3] = quad.x[2]; + var faces = mesh.placedFaces(); + for (double z : new double[]{0, 1}) { + assertSame(quad, faces.visibleFrom(new Vec3(1, 1, z)).iterator().next()); + } + assertFalse(faces.visibleFrom(new Vec3(1, 1, -1)).iterator().hasNext()); + } + @Test void firedMeshesShareGeometryAcrossDesignsAndKeepPositionsSeparate() { Pottery jug = Pottery.jug(); From 67a35ece69c99c103b74dcb9e81770d4a52766f9 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Wed, 2 Dec 2026 21:27:05 +0200 Subject: [PATCH 11/22] Keep grazing pottery faces visible during camera bobbing Co-authored-by: Face of Cat --- .../minecraft/primalpottery/client/PlacedFaces.java | 4 +++- .../minecraft/primalpottery/client/MeshTest.java | 8 ++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java index a0b98b4..d97d1fc 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/client/PlacedFaces.java @@ -7,6 +7,8 @@ /** Face planes for the back-face-culled render pass of a finished, placed pot. */ final class PlacedFaces { + // Camera bobbing shifts the projected eye by up to 0.1 blocks after the camera position is read. + private static final double EYE_MARGIN = 4.0; // 1/8 block in the mesh's 32 units per block. private final Face[] faces; PlacedFaces(List quads) { @@ -53,7 +55,7 @@ static Plane triangle(Mesh.Quad q, int b, int c) { Vec3 origin = corner(q, 0); Vec3 normal = corner(q, b).subtract(origin).cross(corner(q, c).subtract(origin)); // Keep grazing faces. A zero-area triangle has no fragments from either side. - double offset = -normal.dot(origin) + 1e-4 * normal.length(); + double offset = -normal.dot(origin) + EYE_MARGIN * normal.length(); return new Plane(normal.x, normal.y, normal.z, offset); } diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java index ea07180..5bf0911 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/client/MeshTest.java @@ -83,8 +83,8 @@ void placedFacesUseTheWindingOfBothTriangles() { quad.z[3] = 2; // The second triangle now faces sideways as well as forward. var faces = mesh.placedFaces(); assertSame(quad, faces.visibleFrom(new Vec3(1, 1, 4)).iterator().next()); - assertTrue(faces.visibleFrom(new Vec3(8, 1, -1)).iterator().hasNext()); - assertFalse(faces.visibleFrom(new Vec3(1, 1, -4)).iterator().hasNext()); + assertTrue(faces.visibleFrom(new Vec3(20, 1, -9)).iterator().hasNext()); + assertFalse(faces.visibleFrom(new Vec3(1, 1, -12)).iterator().hasNext()); } @Test @@ -94,10 +94,10 @@ void repeatedCornerOnARimFacetDoesNotHideItsVisibleTriangle() { var quad = mesh.quads().getFirst(); quad.x[3] = quad.x[2]; var faces = mesh.placedFaces(); - for (double z : new double[]{0, 1}) { + for (double z : new double[]{-3.2, 0, 1}) { assertSame(quad, faces.visibleFrom(new Vec3(1, 1, z)).iterator().next()); } - assertFalse(faces.visibleFrom(new Vec3(1, 1, -1)).iterator().hasNext()); + assertFalse(faces.visibleFrom(new Vec3(1, 1, -5)).iterator().hasNext()); } @Test From 0f8fc7bd0f8c6c8e5e2c4788f97770567cf72ee9 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 03:30:02 +0200 Subject: [PATCH 12/22] Verify saved pottery profiles across Forge tags and item components Co-authored-by: Face of Cat --- build.gradle | 2 + .../pottery/PotteryStackProfiles.java | 10 + .../pottery/PotteryModelTest.java | 193 ++++++++++++++++++ .../pottery/StackProfileContract.java | 70 +++++++ .../resources/profiles/large-jar.snbt | 1 + .../resources/profiles/painted-jug.snbt | 1 + .../resources/profiles/platter.snbt | 1 + forge/build.gradle | 13 ++ .../forge/ForgeStackProfiles.java | 21 ++ .../primalpottery/forge/PaintedPotEntity.java | 6 +- .../forge/ForgeStackProfileTest.java | 40 ++++ legacy/forge-1.12.2/build.gradle | 12 ++ .../legacy/ForgeStackProfiles.java | 21 ++ .../legacy/PaintedPotEntity.java | 6 +- .../legacy/ForgeStackProfileTest.java | 38 ++++ .../item/ComponentPotteryProfiles.java | 33 +++ .../primalpottery/item/PotteryItem.java | 23 +-- .../primalpottery/item/RawPotteryItem.java | 11 +- .../primalpottery/item/TemplateItem.java | 16 +- .../item/ComponentStackProfileTest.java | 58 ++++++ .../primalpottery/pottery/PotteryTest.java | 176 ---------------- 21 files changed, 529 insertions(+), 223 deletions(-) create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryStackProfiles.java create mode 100644 core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryModelTest.java create mode 100644 core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java create mode 100644 core/src/testFixtures/resources/profiles/large-jar.snbt create mode 100644 core/src/testFixtures/resources/profiles/painted-jug.snbt create mode 100644 core/src/testFixtures/resources/profiles/platter.snbt create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfiles.java create mode 100644 forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfiles.java create mode 100644 legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java create mode 100644 src/main/java/net/modcrafters/minecraft/primalpottery/item/ComponentPotteryProfiles.java create mode 100644 src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java diff --git a/build.gradle b/build.gradle index 0798b64..9777398 100644 --- a/build.gradle +++ b/build.gradle @@ -44,6 +44,8 @@ tasks.named('test', Test) { // Geometry tests exercise the real PoseStack and arm transforms without launching a client. sourceSets.test { + java.srcDir rootProject.file('core/src/testFixtures/java') + resources.srcDir rootProject.file('core/src/testFixtures/resources') compileClasspath += sourceSets.main.compileClasspath runtimeClasspath += sourceSets.main.compileClasspath } diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryStackProfiles.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryStackProfiles.java new file mode 100644 index 0000000..029eb99 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryStackProfiles.java @@ -0,0 +1,10 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +/** Access to the vessel profile stored on a native item stack. */ +public interface PotteryStackProfiles { + /** Returns null when the stack has no valid saved profile. */ + Pottery read(S stack); + + /** Replaces the profile and preserves the other data on the stack. */ + void write(S stack, Pottery profile); +} diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryModelTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryModelTest.java new file mode 100644 index 0000000..902dfb1 --- /dev/null +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryModelTest.java @@ -0,0 +1,193 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PotteryModelTest { + @Test + public void editingANarrowShoulderLimitsTheHollowOnBothSides() { + List rings = new ArrayList<>(); + for (int i = 0; i < 9; i++) { + rings.add(new PotteryDisc(1, i == 4 ? 2 : 7, 7)); + } + Pottery.sealTemplate(rings); + assertEquals(Arrays.asList(5D, 5D, 1D, 1D, 0D, 1D, 1D, 5D, 0D), + rings.stream().map(PotteryDisc::innerRadius).collect(Collectors.toList())); + List sealed = new ArrayList<>(rings); + Pottery.sealTemplate(rings); + assertEquals(sealed, rings); + } + + @Test + public void classificationUsesTheOpeningAndWidestOutsideDiameter() { + assertEquals(PotteryType.POT, vessel(5).classify().type()); + assertEquals(PotteryType.JAR, vessel(4.95).classify().type()); + assertEquals(PotteryType.JAR, vessel(2.75).classify().type()); + assertEquals(PotteryType.JUG, vessel(2.7).classify().type()); + } + + @Test + public void capacityUsesSliceAreaAndHeightUntilTheFirstSolidFloor() { + Pottery pottery = new Pottery(Arrays.asList( + new PotteryDisc(1, 4, 3), + new PotteryDisc(2, 4, 2), + new PotteryDisc(1, 4, 0), + new PotteryDisc(4, 4, 2), + new PotteryDisc(1, 4, 0) + )); + assertEquals(PotteryType.JAR, pottery.classify().type()); + assertEquals(35, pottery.classify().volume()); + } + + @Test + public void changingTheHollowStillMattersNearMaximumCapacity() { + for (Pottery.Size size : Pottery.Size.values()) { + double radius = size.radius(); + double inner = radius - Pottery.TEMPLATE_WALL; + int openHeight = size.units - 1; + PotteryDisc floor = new PotteryDisc(1, radius); + Pottery full = new Pottery(size, Arrays.asList(new PotteryDisc(openHeight, radius, inner), floor)); + Pottery shorter = new Pottery(size, Arrays.asList(new PotteryDisc(openHeight - 1, radius, inner), floor)); + Pottery narrower = new Pottery(size, Arrays.asList(new PotteryDisc(openHeight, radius, inner - 1), floor)); + Pottery nearlyFull = new Pottery(size, Arrays.asList(new PotteryDisc(openHeight, radius, inner - 0.00001), floor)); + assertEquals(size.maxVolume, full.classify().volume()); + assertEquals(Math.round(size.maxVolume * (openHeight - 1.0) / openHeight), shorter.classify().volume()); + assertEquals(Math.round(size.maxVolume * Math.pow((inner - 1) / inner, 2)), narrower.classify().volume()); + assertEquals(size.maxVolume - 1, nearlyFull.classify().volume()); + } + } + + @Test + public void platesNeedEightyPercentOfTheSmallRadiusAndHaveNoCapacityOrLid() { + Pottery plate = new Pottery(Arrays.asList(new PotteryDisc(2, 6.4, 4), new PotteryDisc(1, 4))); + assertEquals(new Pottery.Info(PotteryType.PLATE, 0), plate.classify()); + assertNull(plate.cover()); + Pottery narrow = new Pottery(Arrays.asList(new PotteryDisc(2, 6.39, 4), new PotteryDisc(1, 4))); + assertFalse(narrow.isPlate()); + assertTrue(narrow.classify().volume() > 0); + assertTrue(narrow.fitSavedPlate().isPlate()); + } + + @Test + public void thinWallIsALump() { + Pottery pottery = new Pottery(Arrays.asList(new PotteryDisc(2, 0.4, 0))); + assertEquals(PotteryType.LUMP_THIN, pottery.classify().type()); + } + + @Test + public void missingBottomIsAPipe() { + Pottery pottery = new Pottery(Arrays.asList( + new PotteryDisc(2, 4, 2), new PotteryDisc(1, 0), new PotteryDisc(1, 4) + )); + assertEquals(PotteryType.LUMP_NO_BOTTOM, pottery.classify().type()); + } + + @Test + public void solidClayIsALump() { + Pottery pottery = new Pottery(Arrays.asList(new PotteryDisc(2, 4, 0), new PotteryDisc(2, 4, 0))); + assertEquals(PotteryType.LUMP, pottery.classify().type()); + } + + @Test + public void wheelWithoutATemplateThrowsAJug() { + Pottery jug = Pottery.formed(null); + assertEquals(PotteryType.JUG, jug.classify().type()); + assertEquals(jug.discs(), Pottery.display().discs()); + assertTrue(jug.discs().get(0).innerRadius() > 1); + assertTrue(jug.discs().stream().mapToDouble(PotteryDisc::radius).max().orElse(0) > 5); + } + + @Test + public void shapedIsTheOnlyLerp() { + assertEquals(4, Pottery.BLANK_RADIUS, 0); + Pottery target = new Pottery(Arrays.asList(new PotteryDisc(1, 3, 1))); + Pottery blank = Pottery.shaped(null, target, 0); + assertEquals(1, blank.discs().get(0).height(), 0.0001); + assertEquals(4, blank.discs().get(0).radius(), 0.0001); + assertEquals(0, blank.discs().get(0).innerRadius(), 0.0001); + Pottery half = Pottery.shaped(null, target, 0.5); + assertEquals(3.5, half.discs().get(0).radius(), 0.0001); + assertEquals(0.5, half.discs().get(0).innerRadius(), 0.0001); + assertSame(target, Pottery.shaped(null, target, 1)); + assertSame(target, Pottery.shaped(null, target, 2)); + assertEquals(blank.discs(), Pottery.shaped(null, target, -0.2).discs()); + + Pottery start = new Pottery(Arrays.asList(new PotteryDisc(1, 2, 0))); + Pottery wider = new Pottery(Arrays.asList(new PotteryDisc(1, 4, 2))); + assertEquals(start.discs(), Pottery.shaped(start, wider, 0).discs()); + Pottery mid = Pottery.shaped(start, wider, 0.5); + assertEquals(3, mid.discs().get(0).radius(), 0.0001); + assertEquals(1, mid.discs().get(0).innerRadius(), 0.0001); + + Pottery stacked = new Pottery(Arrays.asList(new PotteryDisc(2, 1, 0), new PotteryDisc(2, 5, 0))); + Pottery pair = new Pottery(Arrays.asList(new PotteryDisc(2, 4, 2), new PotteryDisc(2, 4, 2))); + Pottery held = Pottery.shaped(stacked, pair, 0); + assertEquals(1, held.discs().get(0).radius(), 0.0001); + assertEquals(5, held.discs().get(1).radius(), 0.0001); + + Pottery edge = new Pottery(Arrays.asList(new PotteryDisc(1, 1), new PotteryDisc(1, 5))); + Pottery tall = new Pottery(Arrays.asList(new PotteryDisc(2, 4))); + assertEquals(5, Pottery.shaped(edge, tall, 0).discs().get(0).radius(), 0.0001); + + Pottery vase = Pottery.shaped(null, Pottery.formed(null), 0.5); + assertEquals(3.7, vase.discs().get(0).radius(), 0.0001); + assertEquals(Pottery.formed(null).discs().size(), vase.discs().size()); + assertTrue(Pottery.validProfile(vase.discs())); + assertTrue(Pottery.validProfile(Pottery.shaped(stacked, pair, 0.5).discs())); + assertEquals(Pottery.formed(null).discs(), Pottery.shaped(null, Pottery.formed(null), 1).discs()); + } + + @Test + public void wheelFormsTheInstalledTemplate() { + Pottery template = new Pottery(Arrays.asList(new PotteryDisc(1, 3, 1))); + assertEquals(template, Pottery.formed(template)); + assertEquals(3, Pottery.formed(template).discs().get(0).radius(), 0.0001); + assertEquals(1, Pottery.formed(template).discs().get(0).innerRadius(), 0.0001); + } + + @Test + public void largeLidSpansEvenAThickRim() { + Pottery broad = new Pottery(Pottery.Size.LARGE, Arrays.asList(new PotteryDisc(8, 15, 5), new PotteryDisc(1, 12))); + assertEquals(15, broad.cover().radius(), 0.0001); + assertEquals(broad.cover().radius(), broad.lidDisc().radius(), 0.0001); + } + + @Test + public void lidCopiesTheRimAndLeavesTheProfile() { + Pottery pottery = new Pottery(Arrays.asList( + new PotteryDisc(1, 0, 0), + new PotteryDisc(2, 4, 2), + new PotteryDisc(3, 5, 3), + new PotteryDisc(1, 5, 0) + )); + int volume = pottery.classify().volume(); + PotteryDisc lid = pottery.lidDisc(); + assertEquals(Pottery.PIXEL, lid.height(), 0.0001); + assertEquals(2 + Pottery.PIXEL / 2.0, lid.radius(), 0.0001); + assertEquals(0, lid.innerRadius(), 0.0001); + assertEquals(pottery.discs(), pottery.drawDiscs(true)); + assertEquals(pottery.discs(), pottery.drawDiscs(false)); + assertEquals(volume, pottery.classify().volume()); + Pottery.Cover cover = pottery.cover(); + assertEquals(1 + 2 + 3 + 1, cover.top(), 0.0001); + assertEquals(2, cover.layer(), 0.0001); + assertEquals(3, cover.radius(), 0.0001); + + Pottery lump = new Pottery(Arrays.asList(new PotteryDisc(2, 4, 0), new PotteryDisc(2, 4, 0))); + assertNull(lump.lidDisc()); + assertEquals(lump.discs(), lump.drawDiscs(true)); + assertNull(new Pottery(Arrays.asList(new PotteryDisc(2, 0.4, 0))).lidDisc()); + } + + private static Pottery vessel(double opening) { + return new Pottery(Arrays.asList( + new PotteryDisc(1, opening + 0.5, opening), + new PotteryDisc(2, 5.5, 3), + new PotteryDisc(1, 5) + )); + } +} diff --git a/core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java b/core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java new file mode 100644 index 0000000..1396cc7 --- /dev/null +++ b/core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java @@ -0,0 +1,70 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.Objects; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +/** The same native-stack checks run against both Forge tag formats and the component-backed format. */ +public abstract class StackProfileContract { + protected abstract PotteryStackProfiles profiles(); + protected abstract T parse(String snbt) throws Exception; + protected abstract S stackWith(T data); + protected abstract T data(S stack); + + // These are literal outputs of Pottery.save() at 286afa4 (before platters) and be42faa. + private String fixture(String name) throws Exception { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull( + getClass().getResourceAsStream("/profiles/" + name + ".snbt")), StandardCharsets.UTF_8))) { + return reader.readLine(); + } + } + + private Pottery checkSaved(String name, Pottery.Size size, PotteryType type, int volume) throws Exception { + String metadata = "dye:blue,lid:1b,other:{label:Kiln,values:[1,3,5]}"; + T original = parse("{" + metadata + ",pottery:" + fixture(name) + "}"); + S stack = stackWith(original); + Pottery profile = profiles().read(stack); + assertNotNull(profile, name); + assertEquals(size, profile.size()); + assertEquals(type, profile.classify().type()); + assertEquals(volume, profile.classify().volume()); + + // Write into an existing stack with a different profile and compare its entire native payload. + S target = stackWith(parse("{" + metadata + ",pottery:{obsolete:1b}}")); + profiles().write(target, profile); + assertEquals(original, data(target), name); + return profile; + } + + @Test + public void asymmetricPaintAndOrderedRingsSurvive() throws Exception { + Pottery jug = checkSaved("painted-jug", Pottery.Size.SMALL, PotteryType.JUG, 22); + assertEquals(Arrays.asList(new PotteryDisc(3, 4, 2), new PotteryDisc(2, 5)), jug.discs()); + assertEquals(FacePaint.EMPTY.with(3, 7).with(241, 2), jug.paint()); + } + + @Test + public void sameShapeDistinguishesAnOldJarFromAPlatter() throws Exception { + Pottery jar = checkSaved("large-jar", Pottery.Size.LARGE, PotteryType.JAR, 329); + Pottery platter = checkSaved("platter", Pottery.Size.LARGE, PotteryType.PLATTER, 0); + assertEquals(jar.discs(), platter.discs()); + assertNotNull(jar.cover()); + assertNull(platter.cover()); + } + + @Test + public void strictReadsRejectMissingMalformedAndOversizedProfilesWithoutEditingThem() throws Exception { + String many = String.join(",", Collections.nCopies(65, "{height:0.1d,radius:2d}")); + for (String source : Arrays.asList("{}", "{pottery:42}", "{pottery:{}}", + "{pottery:{discs:[{height:0d,radius:4d}]}}", "{pottery:{discs:[" + many + "]}}")) { + S stack = stackWith(parse(source)); + assertNull(profiles().read(stack), source); + assertEquals(parse(source), data(stack)); + } + } +} diff --git a/core/src/testFixtures/resources/profiles/large-jar.snbt b/core/src/testFixtures/resources/profiles/large-jar.snbt new file mode 100644 index 0000000..8b0530d --- /dev/null +++ b/core/src/testFixtures/resources/profiles/large-jar.snbt @@ -0,0 +1 @@ +{discs:[{height:5.0d,inner:10.0d,radius:12.8d},{height:1.0d,inner:0.0d,radius:10.0d}],large:1b} diff --git a/core/src/testFixtures/resources/profiles/painted-jug.snbt b/core/src/testFixtures/resources/profiles/painted-jug.snbt new file mode 100644 index 0000000..155a813 --- /dev/null +++ b/core/src/testFixtures/resources/profiles/painted-jug.snbt @@ -0,0 +1 @@ +{discs:[{height:3.0d,inner:2.0d,radius:4.0d},{height:2.0d,inner:0.0d,radius:5.0d}],paint:"...H.............................................................................................................................................................................................................................................C.............."} diff --git a/core/src/testFixtures/resources/profiles/platter.snbt b/core/src/testFixtures/resources/profiles/platter.snbt new file mode 100644 index 0000000..8d47197 --- /dev/null +++ b/core/src/testFixtures/resources/profiles/platter.snbt @@ -0,0 +1 @@ +{discs:[{height:5.0d,inner:10.0d,radius:12.8d},{height:1.0d,inner:0.0d,radius:10.0d}],large:1b,platter:1b} diff --git a/forge/build.gradle b/forge/build.gradle index 9562b27..1f45ef4 100644 --- a/forge/build.gradle +++ b/forge/build.gradle @@ -3,11 +3,14 @@ plugins { id 'net.neoforged.moddev.legacyforge' } +repositories { mavenCentral() } evaluationDependsOn(':core') java.toolchain.languageVersion = JavaLanguageVersion.of(17) base.archivesName = 'primalpottery-forge-1.20.1' dependencies { implementation project(':core') + testImplementation 'org.junit.jupiter:junit-jupiter:5.12.2' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } jar { manifest.attributes('Implementation-Version': project.version) @@ -20,6 +23,7 @@ processResources { legacyForge { version = '1.20.1-47.1.3' + addModdingDependenciesTo sourceSets.test mods { primalpottery { sourceSet sourceSets.main @@ -31,3 +35,12 @@ legacyForge { server { server() } } } + +sourceSets.test { + java.srcDir rootProject.file('core/src/testFixtures/java') + resources.srcDir rootProject.file('core/src/testFixtures/resources') +} +test { + useJUnitPlatform() + workingDir layout.buildDirectory.get().asFile +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfiles.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfiles.java new file mode 100644 index 0000000..0a179b4 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfiles.java @@ -0,0 +1,21 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryStackProfiles; + +public enum ForgeStackProfiles implements PotteryStackProfiles { + INSTANCE; + + @Override + public Pottery read(ItemStack stack) { + CompoundTag tag = stack.getTagElement("pottery"); + return tag == null ? null : ForgePotteryTags.readProfile(tag); + } + + @Override + public void write(ItemStack stack, Pottery profile) { + stack.addTagElement("pottery", ForgePotteryTags.save(profile)); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java index 2d097e8..76a6c9b 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java @@ -20,8 +20,8 @@ public final class PaintedPotEntity extends BlockEntity { } public static Pottery fromStack(ItemStack stack) { - CompoundTag tag = stack.getTagElement("pottery"); - return tag == null ? PaintedVessel.SAMPLE : ForgePotteryTags.load(tag); + Pottery profile = ForgeStackProfiles.INSTANCE.read(stack); + return profile == null ? PaintedVessel.SAMPLE : profile; } void install(ItemStack stack) { @@ -32,7 +32,7 @@ void install(ItemStack stack) { ItemStack pickup() { ItemStack result = new ItemStack(PrimalPotteryForge.ITEM.get()); - result.addTagElement("pottery", ForgePotteryTags.save(pot)); + ForgeStackProfiles.INSTANCE.write(result, pot); return result; } diff --git a/forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java b/forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java new file mode 100644 index 0000000..761fe5a --- /dev/null +++ b/forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java @@ -0,0 +1,40 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.SharedConstants; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.TagParser; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.modcrafters.minecraft.primalpottery.pottery.StackProfileContract; +import org.junit.jupiter.api.BeforeAll; + +class ForgeStackProfileTest extends StackProfileContract { + @BeforeAll + static void bootstrap() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Override + protected ForgeStackProfiles profiles() { + return ForgeStackProfiles.INSTANCE; + } + + @Override + protected CompoundTag parse(String snbt) throws Exception { + return TagParser.parseTag(snbt); + } + + @Override + protected ItemStack stackWith(CompoundTag data) { + ItemStack stack = new ItemStack(Items.CLAY_BALL); + stack.setTag(data); + return stack; + } + + @Override + protected CompoundTag data(ItemStack stack) { + return stack.getTag(); + } +} diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle index 995ccf3..d4bb652 100644 --- a/legacy/forge-1.12.2/build.gradle +++ b/legacy/forge-1.12.2/build.gradle @@ -31,9 +31,12 @@ minecraft { } } } +repositories { mavenCentral() } dependencies { minecraft 'net.minecraftforge:forge:1.12.2-14.23.5.2864' implementation project(':core') + testImplementation 'org.junit.jupiter:junit-jupiter:5.12.2' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.12.2' } // MCP's merged development jar contains an extra Side.BUKKIT value which stock FML cannot initialize. // Use Forge's corrected pair of side markers only on the userdev launch classpath (ForgeGradle #748). @@ -56,3 +59,12 @@ processResources { 'assets/primalpottery/textures/block/pottery_inks.png', 'assets/primalpottery/textures/block/paint_sheet.png' } } + +sourceSets.test { + java.srcDir file('../../core/src/testFixtures/java') + resources.srcDir file('../../core/src/testFixtures/resources') +} +test { + useJUnitPlatform() + workingDir layout.buildDirectory.get().asFile +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfiles.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfiles.java new file mode 100644 index 0000000..bda9cd2 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfiles.java @@ -0,0 +1,21 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryStackProfiles; + +public enum ForgeStackProfiles implements PotteryStackProfiles { + INSTANCE; + + @Override + public Pottery read(ItemStack stack) { + NBTTagCompound tag = stack.getSubCompound("pottery"); + return tag == null ? null : ForgePotteryTags.readProfile(tag); + } + + @Override + public void write(ItemStack stack, Pottery profile) { + stack.setTagInfo("pottery", ForgePotteryTags.save(profile)); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java index 9c4038f..a079977 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java @@ -15,8 +15,8 @@ public final class PaintedPotEntity extends TileEntity { public Pottery profile() { return pot; } public static Pottery fromStack(ItemStack stack) { - NBTTagCompound tag = stack.getSubCompound("pottery"); - return tag == null ? PaintedVessel.SAMPLE : ForgePotteryTags.load(tag); + Pottery profile = ForgeStackProfiles.INSTANCE.read(stack); + return profile == null ? PaintedVessel.SAMPLE : profile; } void install(ItemStack stack) { @@ -28,7 +28,7 @@ void install(ItemStack stack) { ItemStack pickup() { ItemStack result = new ItemStack(PrimalPotteryForge.POT); - result.setTagInfo("pottery", ForgePotteryTags.save(pot)); + ForgeStackProfiles.INSTANCE.write(result, pot); return result; } diff --git a/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java new file mode 100644 index 0000000..3468f35 --- /dev/null +++ b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java @@ -0,0 +1,38 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.init.Bootstrap; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.JsonToNBT; +import net.minecraft.nbt.NBTTagCompound; +import net.modcrafters.minecraft.primalpottery.pottery.StackProfileContract; +import org.junit.jupiter.api.BeforeAll; + +class ForgeStackProfileTest extends StackProfileContract { + @BeforeAll + static void bootstrap() { + Bootstrap.register(); + } + + @Override + protected ForgeStackProfiles profiles() { + return ForgeStackProfiles.INSTANCE; + } + + @Override + protected NBTTagCompound parse(String snbt) throws Exception { + return JsonToNBT.getTagFromJson(snbt); + } + + @Override + protected ItemStack stackWith(NBTTagCompound data) { + ItemStack stack = new ItemStack(Items.CLAY_BALL); + stack.setTagCompound(data); + return stack; + } + + @Override + protected NBTTagCompound data(ItemStack stack) { + return stack.getTagCompound(); + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/ComponentPotteryProfiles.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/ComponentPotteryProfiles.java new file mode 100644 index 0000000..12c0c80 --- /dev/null +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/ComponentPotteryProfiles.java @@ -0,0 +1,33 @@ +package net.modcrafters.minecraft.primalpottery.item; + +import net.minecraft.core.component.DataComponents; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; +import net.modcrafters.minecraft.primalpottery.pottery.Nbt; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryStackProfiles; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; +import org.jspecify.annotations.Nullable; + +public enum ComponentPotteryProfiles implements PotteryStackProfiles { + INSTANCE; + + static @Nullable CompoundTag profileTag(ItemStack stack) { + CustomData data = stack.get(DataComponents.CUSTOM_DATA); + if (data == null) return null; + CompoundTag tag = Nbt.compound(data.copyTag(), "pottery"); + return tag.isEmpty() ? null : tag; + } + + @Override + public @Nullable Pottery read(ItemStack stack) { + CompoundTag tag = profileTag(stack); + return tag == null ? null : PotteryTags.readProfile(tag); + } + + @Override + public void write(ItemStack stack, Pottery profile) { + CustomData.update(DataComponents.CUSTOM_DATA, stack, data -> data.put("pottery", PotteryTags.save(profile))); + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java index 8f40852..87e571f 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/PotteryItem.java @@ -172,7 +172,7 @@ public void inventoryTick(ItemStack stack, Level level, Entity owner, int slot, if (data == null || !data.contains("fluid") && !data.contains("soil")) { Pottery profile = read(stack); if (data == null || !data.contains("pottery")) { - CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", PotteryTags.save(profile))); + ComponentPotteryProfiles.INSTANCE.write(stack, profile); } stack.set(DataComponents.MAX_STACK_SIZE, profile.size().emptyStackLimit); } @@ -227,14 +227,8 @@ public int getBarColor(ItemStack stack) { /** Copies the pottery compound onto {@code into} when the stack has one. */ public static void copyPottery(ItemStack stack, CompoundTag into) { - CompoundTag data = customData(stack); - if (data == null) { - return; - } - CompoundTag pottery = Nbt.compound(data, "pottery"); - if (!pottery.isEmpty()) { - into.put("pottery", pottery.copy()); - } + CompoundTag pottery = ComponentPotteryProfiles.profileTag(stack); + if (pottery != null) into.put("pottery", pottery); } public static @Nullable CompoundTag customData(ItemStack stack) { @@ -256,15 +250,8 @@ public static Component fluidName(Fluid fluid) { } public static Pottery read(ItemStack stack) { - CompoundTag tag = tag(stack); - if (tag == null) { - return Pottery.display(); - } - CompoundTag pottery = Nbt.compound(tag, "pottery"); - if (pottery.isEmpty()) { - return Pottery.display(); - } - return PotteryTags.load(pottery); + Pottery profile = ComponentPotteryProfiles.INSTANCE.read(stack); + return profile == null ? Pottery.display() : profile; } public static VesselContents contents(ItemStack stack) { diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java index b49d8dc..a0b9a1d 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/RawPotteryItem.java @@ -19,7 +19,6 @@ import net.minecraft.world.item.component.CustomData; //? if >=26.1 import net.minecraft.world.item.component.TooltipDisplay; -import net.modcrafters.minecraft.primalpottery.pottery.Nbt; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import org.jspecify.annotations.Nullable; @@ -70,15 +69,7 @@ public void inventoryTick(ItemStack stack, Level level, Entity owner, int slot, if (!stack.is(ModItems.RAW_POTTERY) || PotteryItem.dye(stack) != null) { return null; } - CompoundTag data = PotteryItem.customData(stack); - if (data == null) { - return null; - } - CompoundTag pottery = Nbt.compound(data, "pottery"); - if (pottery.isEmpty()) { - return null; - } - return PotteryTags.readProfile(pottery); + return ComponentPotteryProfiles.INSTANCE.read(stack); } @Override diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java index 7c33184..51e207f 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; -import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; @@ -13,11 +12,9 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.modcrafters.minecraft.primalpottery.client.TemplateScreen; -import net.modcrafters.minecraft.primalpottery.pottery.Nbt; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; //? if >=26.1 @@ -63,19 +60,12 @@ public static Pottery fresh(Pottery.Size size) { } public static void write(ItemStack stack, Pottery pottery) { - CustomData.update(DataComponents.CUSTOM_DATA, stack, tag -> tag.put("pottery", PotteryTags.save(pottery))); + ComponentPotteryProfiles.INSTANCE.write(stack, pottery); } public static Pottery read(ItemStack stack) { - CustomData data = stack.get(DataComponents.CUSTOM_DATA); - if (data == null) { - return null; - } - CompoundTag pottery = Nbt.compound(data.copyTag(), "pottery"); - if (pottery.isEmpty()) { - return null; - } - return PotteryTags.load(pottery); + CompoundTag tag = ComponentPotteryProfiles.profileTag(stack); + return tag == null ? null : PotteryTags.load(tag); } /** The saved profile, or the editor's starting shape. */ diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java new file mode 100644 index 0000000..5f27ff2 --- /dev/null +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java @@ -0,0 +1,58 @@ +package net.modcrafters.minecraft.primalpottery.item; + +import net.minecraft.SharedConstants; +import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponents; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.TagParser; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.CustomData; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.StackProfileContract; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ComponentStackProfileTest extends StackProfileContract { + @BeforeAll + static void bootstrap() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + void templateDistinguishesAnAbsentProfileFromADamagedSavedOne() throws Exception { + assertNull(TemplateItem.read(stackWith(parse("{}")))); + ItemStack broken = stackWith(parse("{pottery:{discs:[]}}")); + assertEquals(Pottery.display().discs(), TemplateItem.read(broken).discs()); + } + + @Override + protected ComponentPotteryProfiles profiles() { + return ComponentPotteryProfiles.INSTANCE; + } + + @Override + protected CompoundTag parse(String snbt) throws Exception { + //? if >=26.1 { + return TagParser.parseCompoundFully(snbt); + //?} else + //return TagParser.parseTag(snbt); + } + + @Override + protected ItemStack stackWith(CompoundTag data) { + ItemStack stack = new ItemStack(Holder.direct(Items.CLAY_BALL), 1); + stack.set(DataComponents.CUSTOM_DATA, CustomData.of(data)); + return stack; + } + + @Override + protected CompoundTag data(ItemStack stack) { + return stack.get(DataComponents.CUSTOM_DATA).copyTag(); + } +} diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java index a28b19a..8c79494 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTest.java @@ -3,7 +3,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; @@ -164,70 +163,6 @@ private static void openIntrusiveHolders() { } } - @Test - void editingANarrowShoulderLimitsTheHollowOnBothSides() { - List rings = new java.util.ArrayList<>(); - for (int i = 0; i < 9; i++) { - rings.add(new PotteryDisc(1, i == 4 ? 2 : 7, 7)); - } - Pottery.sealTemplate(rings); - assertEquals(List.of(5D, 5D, 1D, 1D, 0D, 1D, 1D, 5D, 0D), - rings.stream().map(PotteryDisc::innerRadius).toList()); - List sealed = List.copyOf(rings); - Pottery.sealTemplate(rings); - assertEquals(sealed, rings); - } - - @Test - void classificationUsesTheOpeningAndWidestOutsideDiameter() { - assertEquals(PotteryType.POT, vessel(5).classify().type()); - assertEquals(PotteryType.JAR, vessel(4.95).classify().type()); - assertEquals(PotteryType.JAR, vessel(2.75).classify().type()); - assertEquals(PotteryType.JUG, vessel(2.7).classify().type()); - } - - @Test - void capacityUsesSliceAreaAndHeightUntilTheFirstSolidFloor() { - Pottery pottery = new Pottery(List.of( - new PotteryDisc(1, 4, 3), - new PotteryDisc(2, 4, 2), - new PotteryDisc(1, 4, 0), - new PotteryDisc(4, 4, 2), - new PotteryDisc(1, 4, 0) - )); - assertEquals(PotteryType.JAR, pottery.classify().type()); - assertEquals(35, pottery.classify().volume()); - } - - @Test - void changingTheHollowStillMattersNearMaximumCapacity() { - for (Pottery.Size size : Pottery.Size.values()) { - double radius = size.radius(); - double inner = radius - Pottery.TEMPLATE_WALL; - int openHeight = size.units - 1; - PotteryDisc floor = new PotteryDisc(1, radius); - Pottery full = new Pottery(size, List.of(new PotteryDisc(openHeight, radius, inner), floor)); - Pottery shorter = new Pottery(size, List.of(new PotteryDisc(openHeight - 1, radius, inner), floor)); - Pottery narrower = new Pottery(size, List.of(new PotteryDisc(openHeight, radius, inner - 1), floor)); - Pottery nearlyFull = new Pottery(size, List.of(new PotteryDisc(openHeight, radius, inner - 0.00001), floor)); - assertEquals(size.maxVolume, full.classify().volume()); - assertEquals(Math.round(size.maxVolume * (openHeight - 1.0) / openHeight), shorter.classify().volume()); - assertEquals(Math.round(size.maxVolume * Math.pow((inner - 1) / inner, 2)), narrower.classify().volume()); - assertEquals(size.maxVolume - 1, nearlyFull.classify().volume()); - } - } - - @Test - void platesNeedEightyPercentOfTheSmallRadiusAndHaveNoCapacityOrLid() { - Pottery plate = new Pottery(List.of(new PotteryDisc(2, 6.4, 4), new PotteryDisc(1, 4))); - assertEquals(new Pottery.Info(PotteryType.PLATE, 0), plate.classify()); - assertNull(plate.cover()); - Pottery narrow = new Pottery(List.of(new PotteryDisc(2, 6.39, 4), new PotteryDisc(1, 4))); - assertFalse(narrow.isPlate()); - assertTrue(narrow.classify().volume() > 0); - assertTrue(narrow.fitSavedPlate().isPlate()); - } - @Test void largeWideShallowProfilesArePlattersAndPreviouslySavedVesselsKeepTheirHollow() { Pottery platter = new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(5, 12.8, 10), new PotteryDisc(1, 10))); @@ -244,75 +179,6 @@ void largeWideShallowProfilesArePlattersAndPreviouslySavedVesselsKeepTheirHollow assertFalse(new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(7, 16))).isPlatter()); } - @Test - void thinWallIsALump() { - Pottery pottery = new Pottery(List.of(new PotteryDisc(2, 0.4, 0))); - assertEquals(PotteryType.LUMP_THIN, pottery.classify().type()); - } - - @Test - void missingBottomIsAPipe() { - Pottery pottery = new Pottery(List.of( - new PotteryDisc(2, 4, 2), new PotteryDisc(1, 0), new PotteryDisc(1, 4) - )); - assertEquals(PotteryType.LUMP_NO_BOTTOM, pottery.classify().type()); - } - - @Test - void solidClayIsALump() { - Pottery pottery = new Pottery(List.of(new PotteryDisc(2, 4, 0), new PotteryDisc(2, 4, 0))); - assertEquals(PotteryType.LUMP, pottery.classify().type()); - } - - @Test - void wheelWithoutATemplateThrowsAJug() { - Pottery jug = Pottery.formed(null); - assertEquals(PotteryType.JUG, jug.classify().type()); - assertEquals(jug.discs(), Pottery.display().discs()); - assertTrue(jug.discs().getFirst().innerRadius() > 1); - assertTrue(jug.discs().stream().mapToDouble(PotteryDisc::radius).max().orElse(0) > 5); - } - - @Test - void shapedIsTheOnlyLerp() { - assertEquals(4, Pottery.BLANK_RADIUS, 0); - Pottery target = new Pottery(List.of(new PotteryDisc(1, 3, 1))); - Pottery blank = Pottery.shaped(null, target, 0); - assertEquals(1, blank.discs().getFirst().height(), 0.0001); - assertEquals(4, blank.discs().getFirst().radius(), 0.0001); - assertEquals(0, blank.discs().getFirst().innerRadius(), 0.0001); - Pottery half = Pottery.shaped(null, target, 0.5); - assertEquals(3.5, half.discs().getFirst().radius(), 0.0001); - assertEquals(0.5, half.discs().getFirst().innerRadius(), 0.0001); - assertSame(target, Pottery.shaped(null, target, 1)); - assertSame(target, Pottery.shaped(null, target, 2)); - assertEquals(blank.discs(), Pottery.shaped(null, target, -0.2).discs()); - - Pottery start = new Pottery(List.of(new PotteryDisc(1, 2, 0))); - Pottery wider = new Pottery(List.of(new PotteryDisc(1, 4, 2))); - assertEquals(start.discs(), Pottery.shaped(start, wider, 0).discs()); - Pottery mid = Pottery.shaped(start, wider, 0.5); - assertEquals(3, mid.discs().getFirst().radius(), 0.0001); - assertEquals(1, mid.discs().getFirst().innerRadius(), 0.0001); - - Pottery stacked = new Pottery(List.of(new PotteryDisc(2, 1, 0), new PotteryDisc(2, 5, 0))); - Pottery pair = new Pottery(List.of(new PotteryDisc(2, 4, 2), new PotteryDisc(2, 4, 2))); - Pottery held = Pottery.shaped(stacked, pair, 0); - assertEquals(1, held.discs().get(0).radius(), 0.0001); - assertEquals(5, held.discs().get(1).radius(), 0.0001); - - Pottery edge = new Pottery(List.of(new PotteryDisc(1, 1), new PotteryDisc(1, 5))); - Pottery tall = new Pottery(List.of(new PotteryDisc(2, 4))); - assertEquals(5, Pottery.shaped(edge, tall, 0).discs().getFirst().radius(), 0.0001); - - Pottery vase = Pottery.shaped(null, Pottery.formed(null), 0.5); - assertEquals(3.7, vase.discs().getFirst().radius(), 0.0001); - assertEquals(Pottery.formed(null).discs().size(), vase.discs().size()); - assertTrue(Pottery.validProfile(vase.discs())); - assertTrue(Pottery.validProfile(Pottery.shaped(stacked, pair, 0.5).discs())); - assertEquals(Pottery.formed(null).discs(), Pottery.shaped(null, Pottery.formed(null), 1).discs()); - } - @Test void itemNameUsesJugBowlOrPottery() { assertEquals(Component.translatable("pottery.primalpottery.shape.bowl"), Component.translatable(vessel(5).classify().type().shapeKey())); @@ -479,14 +345,6 @@ void paintAndFireKeepTheProfile() { *///?} } - @Test - void wheelFormsTheInstalledTemplate() { - Pottery template = new Pottery(List.of(new PotteryDisc(1, 3, 1))); - assertEquals(template, Pottery.formed(template)); - assertEquals(3, Pottery.formed(template).discs().getFirst().radius(), 0.0001); - assertEquals(1, Pottery.formed(template).discs().getFirst().innerRadius(), 0.0001); - } - @Test void resizeKeepsTheFootAndLipAndRoundTripsAtTheChosenHeight() { for (Pottery.Size size : Pottery.Size.values()) { @@ -503,40 +361,6 @@ void resizeKeepsTheFootAndLipAndRoundTripsAtTheChosenHeight() { } } - @Test - void largeLidSpansEvenAThickRim() { - Pottery broad = new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(8, 15, 5), new PotteryDisc(1, 12))); - assertEquals(15, broad.cover().radius()); - assertEquals(broad.cover().radius(), broad.lidDisc().radius()); - } - - @Test - void lidCopiesTheRimAndLeavesTheProfile() { - Pottery pottery = new Pottery(List.of( - new PotteryDisc(1, 0, 0), - new PotteryDisc(2, 4, 2), - new PotteryDisc(3, 5, 3), - new PotteryDisc(1, 5, 0) - )); - int volume = pottery.classify().volume(); - PotteryDisc lid = pottery.lidDisc(); - assertEquals(Pottery.PIXEL, lid.height(), 0.0001); - assertEquals(2 + Pottery.PIXEL / 2.0, lid.radius(), 0.0001); - assertEquals(0, lid.innerRadius(), 0.0001); - assertEquals(pottery.discs(), pottery.drawDiscs(true)); - assertEquals(pottery.discs(), pottery.drawDiscs(false)); - assertEquals(volume, pottery.classify().volume()); - Pottery.Cover cover = pottery.cover(); - assertEquals(1 + 2 + 3 + 1, cover.top(), 0.0001); - assertEquals(2, cover.layer(), 0.0001); - assertEquals(3, cover.radius(), 0.0001); - - Pottery lump = new Pottery(List.of(new PotteryDisc(2, 4, 0), new PotteryDisc(2, 4, 0))); - assertNull(lump.lidDisc()); - assertEquals(lump.discs(), lump.drawDiscs(true)); - assertNull(new Pottery(List.of(new PotteryDisc(2, 0.4, 0))).lidDisc()); - } - @Test void lidKeyIsOmittedWhenOpen() { CompoundTag tag = new CompoundTag(); From 9ce5a1d029a295ef46d8c6dbc6bb83aadafe1bd1 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 03:35:25 +0200 Subject: [PATCH 13/22] Exercise Forge 1.20.1 stack compatibility inside the game runtime Co-authored-by: Face of Cat --- .../1.20.1/potterycheck/DisplayCheck.java | 3 +- .../potterycheck/ForgeStackProfileCheck.java | 19 +++----- .github/forge-display-check/check.init.gradle | 2 + .../pottery/StackProfileContract.java | 47 +++++++++++-------- forge/build.gradle | 13 ----- .../legacy/ForgeStackProfileTest.java | 6 +++ .../item/ComponentStackProfileTest.java | 5 ++ 7 files changed, 48 insertions(+), 47 deletions(-) rename forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java => .github/forge-display-check/1.20.1/potterycheck/ForgeStackProfileCheck.java (57%) diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index 1f3c73f..18dec4b 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -45,10 +45,11 @@ public final class DisplayCheck { private static final FrameReport frames = new FrameReport(); private static final String WORLD = "painted-pot-display"; - @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { + @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) throws Exception { if (event.phase != TickEvent.Phase.END) return; Minecraft mc = Minecraft.getInstance(); if (!opening && mc.screen instanceof TitleScreen && mc.getOverlay() == null) { + new ForgeStackProfileCheck().verifySavedProfiles(); opening = true; mc.options.framerateLimit().set(30); mc.options.pauseOnLostFocus = false; diff --git a/forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java b/.github/forge-display-check/1.20.1/potterycheck/ForgeStackProfileCheck.java similarity index 57% rename from forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java rename to .github/forge-display-check/1.20.1/potterycheck/ForgeStackProfileCheck.java index 761fe5a..f5ccaba 100644 --- a/forge/src/test/java/net/modcrafters/minecraft/primalpottery/forge/ForgeStackProfileTest.java +++ b/.github/forge-display-check/1.20.1/potterycheck/ForgeStackProfileCheck.java @@ -1,21 +1,14 @@ -package net.modcrafters.minecraft.primalpottery.forge; +package potterycheck; -import net.minecraft.SharedConstants; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.TagParser; -import net.minecraft.server.Bootstrap; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; +import net.minecraftforge.registries.ForgeRegistries; +import net.modcrafters.minecraft.primalpottery.forge.ForgeStackProfiles; import net.modcrafters.minecraft.primalpottery.pottery.StackProfileContract; -import org.junit.jupiter.api.BeforeAll; - -class ForgeStackProfileTest extends StackProfileContract { - @BeforeAll - static void bootstrap() { - SharedConstants.tryDetectVersion(); - Bootstrap.bootStrap(); - } +final class ForgeStackProfileCheck extends StackProfileContract { @Override protected ForgeStackProfiles profiles() { return ForgeStackProfiles.INSTANCE; @@ -28,7 +21,7 @@ protected CompoundTag parse(String snbt) throws Exception { @Override protected ItemStack stackWith(CompoundTag data) { - ItemStack stack = new ItemStack(Items.CLAY_BALL); + ItemStack stack = new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation("primalpottery", "pottery"))); stack.setTag(data); return stack; } diff --git a/.github/forge-display-check/check.init.gradle b/.github/forge-display-check/check.init.gradle index c9c1823..45138e0 100644 --- a/.github/forge-display-check/check.init.gradle +++ b/.github/forge-display-check/check.init.gradle @@ -1,6 +1,8 @@ // Display-check sources are injected only for test runs. Pass -Puncapped to time hardware beyond the CI frame limit. gradle.beforeProject { p -> if (p.path == ':forge') p.afterEvaluate { + p.sourceSets.main.java.srcDir(p.rootProject.file('core/src/testFixtures/java')) + p.sourceSets.main.resources.srcDir(p.rootProject.file('core/src/testFixtures/resources')) p.sourceSets.main.java.srcDir(p.rootProject.file('.github/forge-display-check/1.20.1')) p.sourceSets.main.java.srcDir(p.rootProject.file('.github/forge-display-check/common')) p.legacyForge.runs.client { diff --git a/core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java b/core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java index 1396cc7..6725374 100644 --- a/core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java +++ b/core/src/testFixtures/java/net/modcrafters/minecraft/primalpottery/pottery/StackProfileContract.java @@ -6,8 +6,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.Objects; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; /** The same native-stack checks run against both Forge tag formats and the component-backed format. */ public abstract class StackProfileContract { @@ -16,6 +14,18 @@ public abstract class StackProfileContract { protected abstract S stackWith(T data); protected abstract T data(S stack); + public final void verifySavedProfiles() throws Exception { + asymmetricPaintAndOrderedRingsSurvive(); + sameShapeDistinguishesAnOldJarFromAPlatter(); + strictReadsRejectMissingMalformedAndOversizedProfilesWithoutEditingThem(); + } + + private static void expect(Object expected, Object actual, String field) { + if (!Objects.equals(expected, actual)) { + throw new AssertionError(field + ": expected " + expected + ", got " + actual); + } + } + // These are literal outputs of Pottery.save() at 286afa4 (before platters) and be42faa. private String fixture(String name) throws Exception { try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull( @@ -29,42 +39,39 @@ private Pottery checkSaved(String name, Pottery.Size size, PotteryType type, int T original = parse("{" + metadata + ",pottery:" + fixture(name) + "}"); S stack = stackWith(original); Pottery profile = profiles().read(stack); - assertNotNull(profile, name); - assertEquals(size, profile.size()); - assertEquals(type, profile.classify().type()); - assertEquals(volume, profile.classify().volume()); + Objects.requireNonNull(profile, name); + expect(size, profile.size(), name + " size"); + expect(type, profile.classify().type(), name + " type"); + expect(volume, profile.classify().volume(), name + " capacity"); // Write into an existing stack with a different profile and compare its entire native payload. S target = stackWith(parse("{" + metadata + ",pottery:{obsolete:1b}}")); profiles().write(target, profile); - assertEquals(original, data(target), name); + expect(original, data(target), name + " stack data"); return profile; } - @Test - public void asymmetricPaintAndOrderedRingsSurvive() throws Exception { + private void asymmetricPaintAndOrderedRingsSurvive() throws Exception { Pottery jug = checkSaved("painted-jug", Pottery.Size.SMALL, PotteryType.JUG, 22); - assertEquals(Arrays.asList(new PotteryDisc(3, 4, 2), new PotteryDisc(2, 5)), jug.discs()); - assertEquals(FacePaint.EMPTY.with(3, 7).with(241, 2), jug.paint()); + expect(Arrays.asList(new PotteryDisc(3, 4, 2), new PotteryDisc(2, 5)), jug.discs(), "ring order"); + expect(FacePaint.EMPTY.with(3, 7).with(241, 2), jug.paint(), "paint orientation"); } - @Test - public void sameShapeDistinguishesAnOldJarFromAPlatter() throws Exception { + private void sameShapeDistinguishesAnOldJarFromAPlatter() throws Exception { Pottery jar = checkSaved("large-jar", Pottery.Size.LARGE, PotteryType.JAR, 329); Pottery platter = checkSaved("platter", Pottery.Size.LARGE, PotteryType.PLATTER, 0); - assertEquals(jar.discs(), platter.discs()); - assertNotNull(jar.cover()); - assertNull(platter.cover()); + expect(jar.discs(), platter.discs(), "large profile geometry"); + Objects.requireNonNull(jar.cover(), "legacy jar cover"); + expect(null, platter.cover(), "platter cover"); } - @Test - public void strictReadsRejectMissingMalformedAndOversizedProfilesWithoutEditingThem() throws Exception { + private void strictReadsRejectMissingMalformedAndOversizedProfilesWithoutEditingThem() throws Exception { String many = String.join(",", Collections.nCopies(65, "{height:0.1d,radius:2d}")); for (String source : Arrays.asList("{}", "{pottery:42}", "{pottery:{}}", "{pottery:{discs:[{height:0d,radius:4d}]}}", "{pottery:{discs:[" + many + "]}}")) { S stack = stackWith(parse(source)); - assertNull(profiles().read(stack), source); - assertEquals(parse(source), data(stack)); + expect(null, profiles().read(stack), source); + expect(parse(source), data(stack), "unchanged " + source); } } } diff --git a/forge/build.gradle b/forge/build.gradle index 1f45ef4..9562b27 100644 --- a/forge/build.gradle +++ b/forge/build.gradle @@ -3,14 +3,11 @@ plugins { id 'net.neoforged.moddev.legacyforge' } -repositories { mavenCentral() } evaluationDependsOn(':core') java.toolchain.languageVersion = JavaLanguageVersion.of(17) base.archivesName = 'primalpottery-forge-1.20.1' dependencies { implementation project(':core') - testImplementation 'org.junit.jupiter:junit-jupiter:5.12.2' - testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } jar { manifest.attributes('Implementation-Version': project.version) @@ -23,7 +20,6 @@ processResources { legacyForge { version = '1.20.1-47.1.3' - addModdingDependenciesTo sourceSets.test mods { primalpottery { sourceSet sourceSets.main @@ -35,12 +31,3 @@ legacyForge { server { server() } } } - -sourceSets.test { - java.srcDir rootProject.file('core/src/testFixtures/java') - resources.srcDir rootProject.file('core/src/testFixtures/resources') -} -test { - useJUnitPlatform() - workingDir layout.buildDirectory.get().asFile -} diff --git a/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java index 3468f35..2f4ca9d 100644 --- a/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java +++ b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeStackProfileTest.java @@ -7,8 +7,14 @@ import net.minecraft.nbt.NBTTagCompound; import net.modcrafters.minecraft.primalpottery.pottery.StackProfileContract; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; class ForgeStackProfileTest extends StackProfileContract { + @Test + void savedStackCompatibility() throws Exception { + verifySavedProfiles(); + } + @BeforeAll static void bootstrap() { Bootstrap.register(); diff --git a/src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java b/src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java index 5f27ff2..cc6a58c 100644 --- a/src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java +++ b/src/test/java/net/modcrafters/minecraft/primalpottery/item/ComponentStackProfileTest.java @@ -18,6 +18,11 @@ import static org.junit.jupiter.api.Assertions.assertNull; class ComponentStackProfileTest extends StackProfileContract { + @Test + void savedStackCompatibility() throws Exception { + verifySavedProfiles(); + } + @BeforeAll static void bootstrap() { SharedConstants.tryDetectVersion(); From 217d61c6b1723b5538392a08637e94b1ef558a6f Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 04:13:51 +0200 Subject: [PATCH 14/22] Edit and stamp pottery blueprints on both Forge targets Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/DisplayCheck.java | 6 +- .../potterycheck/ForgeTemplateCheck.java | 76 +++++++++ .../1.20.1/potterycheck/DisplayCheck.java | 4 +- .../potterycheck/ForgeTemplateCheck.java | 79 +++++++++ .../potterycheck/TemplateEditorCheck.java | 85 ++++++++++ .../pottery/PotteryTemplates.java | 38 +++++ forge/build.gradle | 7 +- .../primalpottery/template/TemplateEdits.java | 59 +++++++ .../primalpottery/template/TemplateKind.java | 22 +++ .../primalpottery/template/TemplatePanel.java | 160 ++++++++++++++++++ .../template/TemplatePreview.java | 74 ++++++++ .../primalpottery/template/TemplateWire.java | 55 ++++++ .../forge/ForgeTemplateItem.java | 25 +++ .../forge/PrimalPotteryForge.java | 18 ++ .../primalpottery/forge/TemplateChannel.java | 80 +++++++++ .../forge/client/ForgeTemplateScreen.java | 128 ++++++++++++++ .../assets/primalpottery/lang/en_us.json | 28 ++- .../clear_large_pottery_blueprint.json | 11 ++ .../recipes/clear_pottery_blueprint.json | 11 ++ .../recipes/large_raw_pottery_template.json | 14 ++ .../recipes/raw_pottery_template.json | 14 ++ legacy/forge-1.12.2/build.gradle | 11 +- .../legacy/ForgeTemplateItem.java | 30 ++++ .../legacy/PrimalPotteryForge.java | 14 ++ .../primalpottery/legacy/TemplateChannel.java | 76 +++++++++ .../legacy/client/ForgeTemplateScreen.java | 132 +++++++++++++++ .../legacy/client/PotteryModel.java | 5 + .../assets/primalpottery/lang/en_us.lang | 24 +++ .../template/TemplateEditsTest.java | 57 +++++++ .../primalpottery/item/TemplateItem.java | 22 +-- .../primalpottery/network/TemplateSync.java | 10 +- 31 files changed, 1342 insertions(+), 33 deletions(-) create mode 100644 .github/forge-display-check/1.12.2/potterycheck/ForgeTemplateCheck.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/ForgeTemplateCheck.java create mode 100644 .github/forge-display-check/common/potterycheck/TemplateEditorCheck.java create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTemplates.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateEdits.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateKind.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePanel.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePreview.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateWire.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TemplateChannel.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/ForgeTemplateScreen.java create mode 100644 forge/src/main/resources/data/primalpottery/recipes/clear_large_pottery_blueprint.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/clear_pottery_blueprint.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/large_raw_pottery_template.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/raw_pottery_template.json create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TemplateChannel.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/ForgeTemplateScreen.java create mode 100644 legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/template/TemplateEditsTest.java diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java index bb0cefe..5efcb83 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -32,6 +32,7 @@ // Runs only in the disposable display-check world. public final class DisplayCheck { private static final Pottery CHECKER = checkerboardJug(); + private static final ForgeTemplateCheck templates = new ForgeTemplateCheck(); private static boolean opening; private static boolean placed; private static int ticks; @@ -41,7 +42,7 @@ public final class DisplayCheck { private static final FrameReport frames = new FrameReport(); private static final String WORLD = "painted-pot-display"; - @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { + @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) throws Exception { if (event.phase != TickEvent.Phase.END) return; Minecraft mc = Minecraft.getMinecraft(); if (!opening && mc.currentScreen instanceof GuiMainMenu) { @@ -58,6 +59,7 @@ public final class DisplayCheck { return; } if (mc.player == null || mc.world == null || ++ticks < 40) return; + if (!templates.tick()) return; if (!placed) { placed = true; mc.gameSettings.hideGUI = true; @@ -160,7 +162,7 @@ private static void showReference(Minecraft mc) { }); } - private static void screenshot(Minecraft mc, String name) throws Exception { + static void screenshot(Minecraft mc, String name) throws Exception { ScreenShotHelper.saveScreenshot(new File("."), name, mc.displayWidth, mc.displayHeight, mc.getFramebuffer()); } } diff --git a/.github/forge-display-check/1.12.2/potterycheck/ForgeTemplateCheck.java b/.github/forge-display-check/1.12.2/potterycheck/ForgeTemplateCheck.java new file mode 100644 index 0000000..b425abd --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/ForgeTemplateCheck.java @@ -0,0 +1,76 @@ +package potterycheck; + +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumHand; +import net.modcrafters.minecraft.primalpottery.legacy.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.legacy.client.ForgeTemplateScreen; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.template.TemplatePanel; + +final class ForgeTemplateCheck extends TemplateEditorCheck { + private Minecraft client() { return Minecraft.getMinecraft(); } + private ForgeTemplateScreen screen() { return (ForgeTemplateScreen) client().currentScreen; } + private EnumHand hand(boolean offhand) { + return offhand ? EnumHand.OFF_HAND : EnumHand.MAIN_HAND; + } + private Item item(TemplateKind kind) { + return Item.getByNameOrId("primalpottery:" + kind.id); + } + @Override void give(TemplateKind kind, int count, boolean offhand) { + net.minecraft.server.MinecraftServer server = client().getIntegratedServer(); + server.addScheduledTask(() -> { + EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); + ItemStack clay = kind == TemplateKind.SMALL_RAW ? new ItemStack(Items.CLAY_BALL) : new ItemStack(Blocks.CLAY); + ItemStack blank = craft(player, clay, new ItemStack(Items.STICK)); + ItemStack reclaimed = craft(player, new ItemStack(item(kind.blueprint())), ItemStack.EMPTY); + if (blank.getItem() != item(kind) || reclaimed.getItem() != item(kind) || reclaimed.hasTagCompound()) { + throw new AssertionError("Raw and reclaim recipes for " + kind); + } + blank.setCount(count); + player.setHeldItem(hand(offhand), blank); + player.inventoryContainer.detectAndSendChanges(); + }); + } + private ItemStack craft(EntityPlayerMP player, ItemStack first, ItemStack second) { + InventoryCrafting grid = new InventoryCrafting(player.inventoryContainer, 2, 2); + grid.setInventorySlotContents(0, first); + grid.setInventorySlotContents(1, second); + return CraftingManager.findMatchingResult(grid, player.world); + } + @Override int count(TemplateKind kind, boolean offhand) { + ItemStack held = client().player.getHeldItem(hand(offhand)); + return held.getItem() == item(kind) ? held.getCount() : 0; + } + @Override Pottery blueprint(TemplateKind kind, boolean offhand) { + if (offhand && count(kind, true) == 1) return ForgeStackProfiles.INSTANCE.read(client().player.getHeldItemOffhand()); + if (!offhand) for (ItemStack stack : client().player.inventory.mainInventory) { + if (stack.getItem() == item(kind)) return ForgeStackProfiles.INSTANCE.read(stack); + } + return null; + } + @Override void use(boolean offhand) { + client().playerController.processRightClick(client().player, client().world, hand(offhand)); + } + @Override boolean editorOpen() { return client().currentScreen instanceof ForgeTemplateScreen; } + @Override void stroke(int x, int y, int endX, int endY, int button) throws Exception { + ForgeTemplateScreen screen = screen(); + int left = (screen.width - TemplatePanel.WIDTH) / 2; + int top = (screen.height - TemplatePanel.HEIGHT) / 2; + screen.mouseClicked(left + x, top + y, button); + screen.mouseClickMove(left + endX, top + endY, button, 20L); + screen.mouseReleased(left + endX, top + endY, button); + } + @Override void stamp() throws Exception { + ForgeTemplateScreen screen = screen(); + screen.mouseClicked((screen.width - TemplatePanel.WIDTH) / 2 + 185, (screen.height - TemplatePanel.HEIGHT) / 2 + 190, 0); + } + @Override void screenshot() throws Exception { DisplayCheck.screenshot(client(), "template.png"); } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index 18dec4b..7a224e2 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -35,6 +35,7 @@ // Runs only in the disposable display-check world. public final class DisplayCheck { private static final Pottery CHECKER = checkerboardJug(); + private static final ForgeTemplateCheck templates = new ForgeTemplateCheck(); private static boolean opening; private static boolean placed; private static int ticks; @@ -60,6 +61,7 @@ public final class DisplayCheck { return; } if (mc.player == null || mc.level == null || ++ticks < 40) return; + if (!templates.tick()) return; if (!placed) { placed = true; mc.options.hideGui = true; @@ -190,7 +192,7 @@ private static void showReference(Minecraft mc) { }); } - private static void screenshot(Minecraft mc, String name) throws Exception { + static void screenshot(Minecraft mc, String name) throws Exception { try (var image = Screenshot.takeScreenshot(mc.getMainRenderTarget())) { image.writeToFile(new File(name)); } } } diff --git a/.github/forge-display-check/1.20.1/potterycheck/ForgeTemplateCheck.java b/.github/forge-display-check/1.20.1/potterycheck/ForgeTemplateCheck.java new file mode 100644 index 0000000..9443036 --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/ForgeTemplateCheck.java @@ -0,0 +1,79 @@ +package potterycheck; + +import net.minecraft.client.Minecraft; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.inventory.TransientCraftingContainer; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.registries.ForgeRegistries; +import net.modcrafters.minecraft.primalpottery.forge.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.forge.client.ForgeTemplateScreen; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.template.TemplatePanel; + +final class ForgeTemplateCheck extends TemplateEditorCheck { + private Minecraft client() { return Minecraft.getInstance(); } + private ForgeTemplateScreen screen() { return (ForgeTemplateScreen) client().screen; } + private InteractionHand hand(boolean offhand) { + return offhand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND; + } + private Item item(TemplateKind kind) { + return ForgeRegistries.ITEMS.getValue(new ResourceLocation("primalpottery", kind.id)); + } + @Override void give(TemplateKind kind, int count, boolean offhand) { + var server = client().getSingleplayerServer(); + server.execute(() -> { + var player = server.getPlayerList().getPlayers().get(0); + ItemStack clay = kind == TemplateKind.SMALL_RAW ? new ItemStack(Items.CLAY_BALL) : new ItemStack(Items.CLAY); + ItemStack blank = craft(player, clay, new ItemStack(Items.STICK)); + ItemStack reclaimed = craft(player, new ItemStack(item(kind.blueprint())), ItemStack.EMPTY); + if (blank.getItem() != item(kind) || reclaimed.getItem() != item(kind) || reclaimed.hasTag()) { + throw new AssertionError("Raw and reclaim recipes for " + kind); + } + blank.setCount(count); + player.setItemInHand(hand(offhand), blank); + player.inventoryMenu.broadcastChanges(); + }); + } + private ItemStack craft(ServerPlayer player, ItemStack first, ItemStack second) { + var grid = new TransientCraftingContainer(player.inventoryMenu, 2, 2); + grid.setItem(0, first); + grid.setItem(1, second); + var level = player.serverLevel(); + return level.getRecipeManager().getRecipeFor(RecipeType.CRAFTING, grid, level) + .orElseThrow().assemble(grid, level.registryAccess()); + } + @Override int count(TemplateKind kind, boolean offhand) { + ItemStack held = client().player.getItemInHand(hand(offhand)); + return held.getItem() == item(kind) ? held.getCount() : 0; + } + @Override Pottery blueprint(TemplateKind kind, boolean offhand) { + if (offhand && count(kind, true) == 1) return ForgeStackProfiles.INSTANCE.read(client().player.getOffhandItem()); + if (!offhand) for (ItemStack stack : client().player.getInventory().items) { + if (stack.getItem() == item(kind)) return ForgeStackProfiles.INSTANCE.read(stack); + } + return null; + } + @Override void use(boolean offhand) { + client().gameMode.useItem(client().player, hand(offhand)); + } + @Override boolean editorOpen() { return client().screen instanceof ForgeTemplateScreen; } + @Override void stroke(int x, int y, int endX, int endY, int button) throws Exception { + ForgeTemplateScreen screen = screen(); + int left = (screen.width - TemplatePanel.WIDTH) / 2; + int top = (screen.height - TemplatePanel.HEIGHT) / 2; + screen.mouseClicked(left + x, top + y, button); + screen.mouseDragged(left + endX, top + endY, button, endX - x, endY - y); + screen.mouseReleased(left + endX, top + endY, button); + } + @Override void stamp() throws Exception { + ForgeTemplateScreen screen = screen(); + screen.mouseClicked((screen.width - TemplatePanel.WIDTH) / 2 + 185, (screen.height - TemplatePanel.HEIGHT) / 2 + 190, 0); + } + @Override void screenshot() throws Exception { DisplayCheck.screenshot(client(), "template.png"); } +} diff --git a/.github/forge-display-check/common/potterycheck/TemplateEditorCheck.java b/.github/forge-display-check/common/potterycheck/TemplateEditorCheck.java new file mode 100644 index 0000000..c17e598 --- /dev/null +++ b/.github/forge-display-check/common/potterycheck/TemplateEditorCheck.java @@ -0,0 +1,85 @@ +package potterycheck; + +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; + +/** Drives native item use and screen input, then reads the inventory synchronized by the server. */ +abstract class TemplateEditorCheck { + private enum Step { GIVE_SMALL, USE_SMALL, EDIT_SMALL, STAMP_SMALL, REOPEN, EDIT_BLUEPRINT, + VERIFY_SECOND_EDIT, USE_LARGE, EDIT_LARGE, VERIFY_STACK, DONE } + private Step step = Step.GIVE_SMALL; + private int waiting; + private Pottery first; + + abstract void give(TemplateKind kind, int count, boolean offhand); + abstract int count(TemplateKind kind, boolean offhand); + abstract Pottery blueprint(TemplateKind kind, boolean offhand); + abstract void use(boolean offhand); + abstract boolean editorOpen(); + abstract void stroke(int x, int y, int endX, int endY, int button) throws Exception; + abstract void stamp() throws Exception; + abstract void screenshot() throws Exception; + + boolean tick() throws Exception { + if (step == Step.DONE) return true; + if (++waiting > 600) throw new AssertionError("Template editor timed out at " + step); + switch (step) { + case GIVE_SMALL: + give(TemplateKind.SMALL_RAW, 1, true); + break; + case USE_SMALL: + if (count(TemplateKind.SMALL_RAW, true) != 1) return false; + use(true); + break; + case EDIT_SMALL: + if (!editorOpen()) return false; + stroke(75, 43, 82, 52, 0); + break; + case STAMP_SMALL: + if (waiting < 5) return false; + screenshot(); + stamp(); + break; + case REOPEN: + first = blueprint(TemplateKind.SMALL_BLUEPRINT, true); + if (first == null) return false; + if (first.discs().equals(PotteryTemplates.fresh(Pottery.Size.SMALL).discs())) + throw new AssertionError("The first stroke was lost"); + use(true); + break; + case EDIT_BLUEPRINT: + if (!editorOpen()) return false; + stroke(69, 84, 70, 96, 1); + stamp(); + break; + case VERIFY_SECOND_EDIT: + Pottery revised = blueprint(TemplateKind.SMALL_BLUEPRINT, true); + if (revised == null || first.discs().equals(revised.discs())) return false; + if (!revised.discs().subList(0, 3).equals(first.discs().subList(0, 3))) + throw new AssertionError("Reopening lost the first stroke"); + give(TemplateKind.LARGE_RAW, 2, false); + break; + case USE_LARGE: + if (count(TemplateKind.LARGE_RAW, false) != 2) return false; + use(false); + break; + case EDIT_LARGE: + if (!editorOpen()) return false; + stroke(76, 48, 83, 58, 0); + stamp(); + break; + case VERIFY_STACK: + Pottery large = blueprint(TemplateKind.LARGE_BLUEPRINT, false); + if (large == null || count(TemplateKind.LARGE_RAW, false) != 1) return false; + if (large.size() != Pottery.Size.LARGE || large.discs().equals(PotteryTemplates.fresh(Pottery.Size.LARGE).discs())) + throw new AssertionError("Stacked large template produced the wrong drawing"); + System.out.println("POTTERY VERIFIED template: offhand edit, stamp, reopen, second stroke and stacked large blank"); + break; + default: throw new AssertionError(step); + } + step = Step.values()[step.ordinal() + 1]; + waiting = 0; + return false; + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTemplates.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTemplates.java new file mode 100644 index 0000000..1feba9d --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryTemplates.java @@ -0,0 +1,38 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.ArrayList; +import java.util.List; + +/** Starting clay and server-side shape validation for reusable blueprints. */ +public final class PotteryTemplates { + private PotteryTemplates() {} + + public static Pottery fresh(Pottery.Size size) { + // Sample the starter jug into one editable ring per unit of clay. + List jug = Pottery.jug().discs(); + double height = jug.stream().mapToDouble(PotteryDisc::height).sum(); + double widest = jug.stream().mapToDouble(PotteryDisc::radius).max().getAsDouble(); + double scale = size.radius() / widest; + List rings = new ArrayList<>(size.units); + int index = 0; + double end = jug.get(0).height(); + for (int row = 0; row < size.units; row++) { + double y = (row + 0.5) * height / size.units; + while (y >= end && index + 1 < jug.size()) { + end += jug.get(++index).height(); + } + PotteryDisc disc = jug.get(index); + rings.add(new PotteryDisc(1, disc.radius() * scale, disc.innerRadius() * scale)); + } + Pottery.sealTemplate(rings); + return new Pottery(size, rings); + } + + /** Returns null for a drawing that cannot fit the held template. */ + public static Pottery stamp(Pottery.Size size, List discs) { + if (!Pottery.validProfile(size, discs)) return null; + List rings = new ArrayList<>(discs); + Pottery.sealTemplate(rings); + return new Pottery(size, rings); + } +} diff --git a/forge/build.gradle b/forge/build.gradle index 9562b27..af6fc47 100644 --- a/forge/build.gradle +++ b/forge/build.gradle @@ -14,8 +14,13 @@ jar { from(project(':core').sourceSets.main.output) from(rootProject.file('LICENSE')) } +sourceSets.main.java.srcDir 'shared/src/main/java' + processResources { - from(rootProject.file('src/main/resources')) { include 'assets/primalpottery/textures/block/fired_clay.png' } + from(rootProject.file('src/main/resources')) { include 'assets/primalpottery/textures/block/fired_clay.png', + 'assets/primalpottery/textures/item/*pottery_template.png', + 'assets/primalpottery/textures/gui/template_editor.png', + 'assets/primalpottery/models/item/*pottery_template.json' } } legacyForge { diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateEdits.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateEdits.java new file mode 100644 index 0000000..bf92313 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateEdits.java @@ -0,0 +1,59 @@ +package net.modcrafters.minecraft.primalpottery.template; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.WeakHashMap; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryStackProfiles; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; + +/** One server-thread edit per player, bound to the exact stack used to open the editor. */ +public abstract class TemplateEdits { + private final Map> sessions = new WeakHashMap<>(); + private final PotteryStackProfiles profiles; + + protected TemplateEdits(PotteryStackProfiles profiles) { + this.profiles = profiles; + } + + protected abstract S held(P player, H hand); + protected abstract void show(P player, UUID token, Pottery shape); + protected abstract void giveBlueprint(P player, H hand, S raw, TemplateKind kind, Pottery shape); + + public final void open(P player, H hand, TemplateKind kind) { + S stack = held(player, hand); + Session session = new Session<>(hand, stack, kind); + sessions.put(player, session); + Pottery shape = profiles.read(stack); + show(player, session.token, shape != null && shape.size() == kind.size ? shape : PotteryTemplates.fresh(kind.size)); + } + + public final void finish(P player, UUID token, List rings) { + Session session = sessions.get(player); + if (session == null || !session.token.equals(token)) return; + sessions.remove(player); + if (held(player, session.hand) != session.stack) return; + Pottery shape = PotteryTemplates.stamp(session.kind.size, rings); + if (shape == null) return; + if (session.kind == session.kind.blueprint()) { + profiles.write(session.stack, shape); + } else { + giveBlueprint(player, session.hand, session.stack, session.kind.blueprint(), shape); + } + } + + private static final class Session { + final UUID token = UUID.randomUUID(); + final H hand; + final S stack; + final TemplateKind kind; + + Session(H hand, S stack, TemplateKind kind) { + this.hand = hand; + this.stack = stack; + this.kind = kind; + } + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateKind.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateKind.java new file mode 100644 index 0000000..b7409fb --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateKind.java @@ -0,0 +1,22 @@ +package net.modcrafters.minecraft.primalpottery.template; + +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public enum TemplateKind { + SMALL_RAW("raw_pottery_template", Pottery.Size.SMALL), + SMALL_BLUEPRINT("pottery_template", Pottery.Size.SMALL), + LARGE_RAW("large_raw_pottery_template", Pottery.Size.LARGE), + LARGE_BLUEPRINT("large_pottery_template", Pottery.Size.LARGE); + + public final String id; + public final Pottery.Size size; + + TemplateKind(String id, Pottery.Size size) { + this.id = id; + this.size = size; + } + + public TemplateKind blueprint() { + return size == Pottery.Size.SMALL ? SMALL_BLUEPRINT : LARGE_BLUEPRINT; + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePanel.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePanel.java new file mode 100644 index 0000000..cd4ccc1 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePanel.java @@ -0,0 +1,160 @@ +package net.modcrafters.minecraft.primalpottery.template; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; + +/** State and coordinates of the template editor, in pixels relative to the background artwork. */ +public final class TemplatePanel { + public interface Canvas extends TemplatePreview.Canvas { + void fill(int left, int top, int right, int bottom, int color); + } + + public static final int WIDTH = 248, HEIGHT = 206; + private static final int CENTER = 67, BASE = 122, CLAY_HEIGHT = 84; + private final Deque undo = new ArrayDeque<>(); + private Pottery shape; + private Pottery.Info info; + private String heightLabel; + private List outside, cavity; + private TemplatePreview preview; + private Pottery heightSource; + private boolean hollow, turning; + private int dragButton = -1, lastRow; + private double lastX, lastY, yaw = 25, tilt = 35; + private int[] edges; + + public TemplatePanel(Pottery initial) { update(initial); } + + public Pottery shape() { return shape; } + public Pottery.Info info() { return info; } + public String heightLabel() { return heightLabel; } + public boolean hollow() { return hollow; } + public void hollow(boolean value) { hollow = value; } + public boolean canUndo() { return !undo.isEmpty(); } + public boolean canResize(int step) { return step < 0 ? shape.height() > 1 : shape.height() < shape.size().units; } + + private void update(Pottery pottery) { + shape = pottery; + info = pottery.classify(); + heightLabel = java.text.NumberFormat.getNumberInstance().format(pottery.height()); + outside = PotteryProfile.profile(shape.discs(), false); + cavity = PotteryProfile.profile(shape.discs(), true); + preview = new TemplatePreview(pottery); + edges = new int[shape.discs().size() + 1]; + edges[edges.length - 1] = BASE; + double height = 0; + for (int i = edges.length - 2; i >= 0; i--) { + height += shape.discs().get(i).height(); + edges[i] = BASE - (int) Math.round(height * scale()); + } + } + + private double scale() { return (double) CLAY_HEIGHT / shape.size().units; } + + private void remember() { + if (undo.size() == 32) undo.removeLast(); + undo.push(shape); + } + + public void undo() { + if (canUndo()) { + heightSource = null; + update(undo.pop()); + } + } + + public void resize(int step) { + if (!canResize(step)) return; + remember(); + if (heightSource == null) heightSource = shape; + int target = step < 0 ? (int) Math.ceil(shape.height()) - 1 : (int) Math.floor(shape.height()) + 1; + update(target == heightSource.height() ? heightSource : heightSource.withHeight(target)); + } + + public boolean begin(double x, double y, int button) { + if (dragButton != -1 || (button != 0 && button != 1)) return false; + turning = button == 0 && x >= 135 && x < 239 && y >= 22 && y < 134; + if (!turning) { + lastRow = rowAt(y); + if (lastRow < 0 || Math.abs(x - CENTER) > CLAY_HEIGHT / 2 + 1) return false; + remember(); + } + dragButton = button; + lastX = x; + lastY = y; + return drag(x, y, button); + } + + public boolean drag(double x, double y, int button) { + if (button != dragButton || button < 0) return false; + if (turning) { + yaw += (x - lastX) * 2; + tilt = Math.max(10, Math.min(75, tilt + y - lastY)); + } else { + int row = rowAt(y); + if (row < 0) return true; + sculpt(row, x, y); + lastRow = row; + } + lastX = x; + lastY = y; + return true; + } + + public void release() { + dragButton = -1; + turning = false; + } + + private int rowAt(double y) { + for (int i = 0; i < edges.length - 1; i++) if (y >= edges[i] && y < edges[i + 1]) return i; + return -1; + } + + private void sculpt(int row, double x, double y) { + List rings = new ArrayList<>(shape.discs()); + int step = row >= lastRow ? 1 : -1; + int first = row == lastRow ? row : lastRow + step; + boolean inside = hollow || dragButton == 1; + for (int i = first; i != row + step; i += step) { + double midY = (edges[i] + edges[i + 1]) * 0.5; + double strokeX = i == row ? x : lastX + (x - lastX) * (midY - lastY) / (y - lastY); + double radius = Math.min(shape.size().radius(), Math.abs(strokeX - CENTER) / scale()); + PotteryDisc old = rings.get(i); + double outer = inside ? old.radius() : Math.max(1, radius); + rings.set(i, new PotteryDisc(old.height(), outer, Math.min(outer, inside ? radius : old.innerRadius()))); + } + Pottery edited = PotteryTemplates.stamp(shape.size(), rings); + if (edited != null && !edited.discs().equals(shape.discs())) { + heightSource = null; + update(edited); + } + } + + public void draw(Canvas canvas, int left, int top) { + for (int py = edges[0]; py < BASE; py++) { + double h = (BASE - py - 0.5) / scale(); + int r = (int) Math.round(PotteryProfile.sample(outside, h) * scale()); + int cx = left + CENTER, y = top + py; + canvas.fill(cx - r, y, cx + r, y + 1, 0xff955d49); + canvas.fill(cx - r * 3 / 4, y, cx + r / 2, y + 1, 0xffc48564); + canvas.fill(cx - r / 3, y, cx + r / 5, y + 1, 0xffd79773); + if ((hollow || dragButton == 1 || py == edges[0]) && !cavity.isEmpty()) { + int hole = (int) Math.round(PotteryProfile.sample(cavity, h) * scale()); + canvas.fill(cx - hole, y, cx + hole, y + 1, 0xff684537); + } + } + preview.draw(canvas, left + 187, top + 78, yaw, tilt); + } + + public String hint(double x, double y) { + if (turning || x >= 135 && x < 239 && y >= 22 && y < 134) return "turn_hint"; + return hollow || dragButton == 1 ? "hollow_hint" : "shape_hint"; + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePreview.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePreview.java new file mode 100644 index 0000000..d2be139 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplatePreview.java @@ -0,0 +1,74 @@ +package net.modcrafters.minecraft.primalpottery.template; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Orthographic view of the same vessel mesh the Forge item renders, with the rim and cavity visible. */ +final class TemplatePreview { + interface Canvas { + void beginQuads(); + void vertex(float x, float y, int color); + void endQuads(); + } + + private final List faces = new ArrayList<>(); + private final double centerY; + private final double scale; + private double lastYaw = Double.NaN, lastTilt; + + TemplatePreview(Pottery shape) { + centerY = shape.height() / 64; + scale = 91 * 32 / Math.max(1, Math.hypot(shape.height(), shape.widestRadius() * 2)); + new PaintedVessel(shape, (a, b, c, d, ink) -> faces.add(new Face(a, b, c, d))); + } + + void draw(Canvas canvas, int cx, int cy, double yaw, double tilt) { + if (yaw != lastYaw || tilt != lastTilt) { + project(yaw, tilt); + lastYaw = yaw; + lastTilt = tilt; + } + canvas.beginQuads(); + for (Face face : faces) { + for (int i = 0; i < 4; i++) canvas.vertex(cx + face.x[i], cy + face.y[i], face.color); + } + canvas.endQuads(); + } + + private void project(double yaw, double tilt) { + double sy = Math.sin(Math.toRadians(yaw)), dy = Math.cos(Math.toRadians(yaw)); + double st = Math.sin(Math.toRadians(tilt)), dt = Math.cos(Math.toRadians(tilt)); + for (Face face : faces) { + face.depth = 0; + for (int i = 0; i < 4; i++) { + PaintedVessel.Vertex v = face.vertices[i]; + double x = v.x - 0.5, y = v.y - centerY, z = v.z - 0.5; + double forward = z * dy - x * sy; + face.x[i] = (float) (scale * (x * dy + z * sy)); + face.y[i] = (float) (-scale * (y * dt - forward * st)); + face.depth += y * st + forward * dt; + } + } + faces.sort(Comparator.comparingDouble(face -> face.depth)); + } + + private static final class Face { + final PaintedVessel.Vertex[] vertices; + final float[] x = new float[4], y = new float[4]; + final int color; + double depth; + + Face(PaintedVessel.Vertex a, PaintedVessel.Vertex b, PaintedVessel.Vertex c, PaintedVessel.Vertex d) { + vertices = new PaintedVessel.Vertex[]{a, b, c, d}; + double ux = b.x - a.x, uy = b.y - a.y, uz = b.z - a.z; + double vx = d.x - a.x, vy = d.y - a.y, vz = d.z - a.z; + double nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx; + double length = Math.sqrt(nx * nx + ny * ny + nz * nz); + double shade = 0.68 + (length == 0 ? 0 : 0.32 * (-0.4 * nx + 0.8 * ny + 0.44 * nz) / length); + color = 0xff000000 | (int)(212 * shade) << 16 | (int)(149 * shade) << 8 | (int)(104 * shade); + } + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateWire.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateWire.java new file mode 100644 index 0000000..2284ea5 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/template/TemplateWire.java @@ -0,0 +1,55 @@ +package net.modcrafters.minecraft.primalpottery.template; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.DecoderException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; + +/** Both Forge transports use a UUID followed by a bounded sequence of rim-to-foot rings. */ +public final class TemplateWire { + private TemplateWire() {} + + public static UUID readToken(ByteBuf buffer) { + return new UUID(buffer.readLong(), buffer.readLong()); + } + + public static void writeToken(ByteBuf buffer, UUID token) { + buffer.writeLong(token.getMostSignificantBits()); + buffer.writeLong(token.getLeastSignificantBits()); + } + + public static List readRings(ByteBuf buffer) { + int count = buffer.readUnsignedByte(); + if (count > Pottery.MAX_DISCS || buffer.readableBytes() < count * 24) + throw new DecoderException("Invalid template ring count: " + count); + List rings = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + rings.add(new PotteryDisc(buffer.readDouble(), buffer.readDouble(), buffer.readDouble())); + } + return rings; + } + + public static void writeRings(ByteBuf buffer, List rings) { + buffer.writeByte(rings.size()); + for (PotteryDisc ring : rings) { + buffer.writeDouble(ring.height()); + buffer.writeDouble(ring.radius()); + buffer.writeDouble(ring.innerRadius()); + } + } + + public static Pottery readShape(ByteBuf buffer) { + Pottery.Size size = buffer.readBoolean() ? Pottery.Size.LARGE : Pottery.Size.SMALL; + List rings = readRings(buffer); + if (!Pottery.validProfile(size, rings)) throw new DecoderException("Invalid template shape"); + return new Pottery(size, rings); + } + + public static void writeShape(ByteBuf buffer, Pottery shape) { + buffer.writeBoolean(shape.size() == Pottery.Size.LARGE); + writeRings(buffer, shape.discs()); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java new file mode 100644 index 0000000..92123f7 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java @@ -0,0 +1,25 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; + +final class ForgeTemplateItem extends Item { + private final TemplateKind kind; + + ForgeTemplateItem(TemplateKind kind) { + super(new Properties().stacksTo(kind == kind.blueprint() ? 1 : 64)); + this.kind = kind; + } + + @Override + public InteractionResultHolder use(Level level, Player player, InteractionHand hand) { + if (player instanceof ServerPlayer server) TemplateChannel.EDITS.open(server, hand, kind); + return InteractionResultHolder.sidedSuccess(player.getItemInHand(hand), level.isClientSide); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java index d435761..d4ca40b 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java @@ -1,5 +1,7 @@ package net.modcrafters.minecraft.primalpottery.forge; +import java.util.EnumMap; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -22,8 +24,24 @@ public final class PrimalPotteryForge { static final RegistryObject> ENTITY = ENTITIES.register("pottery", () -> BlockEntityType.Builder.of(PaintedPotEntity::new, POT.get()).build(null)); + private static final EnumMap> TEMPLATES = new EnumMap<>(TemplateKind.class); + + public static Item template(TemplateKind kind) { + return TEMPLATES.get(kind).get(); + } + public PrimalPotteryForge() { + for (TemplateKind kind : TemplateKind.values()) { + TEMPLATES.put(kind, ITEMS.register(kind.id, () -> new ForgeTemplateItem(kind))); + } + TemplateChannel.register(); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); + bus.addListener((net.minecraftforge.event.BuildCreativeModeTabContentsEvent event) -> { + if (event.getTabKey() == net.minecraft.world.item.CreativeModeTabs.INGREDIENTS) { + event.accept(TEMPLATES.get(TemplateKind.SMALL_RAW).get()); + event.accept(TEMPLATES.get(TemplateKind.LARGE_RAW).get()); + } + }); BLOCKS.register(bus); ITEMS.register(bus); ENTITIES.register(bus); diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TemplateChannel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TemplateChannel.java new file mode 100644 index 0000000..cfeb0a5 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TemplateChannel.java @@ -0,0 +1,80 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.network.NetworkDirection; +import net.minecraftforge.network.NetworkEvent; +import net.minecraftforge.network.NetworkRegistry; +import net.minecraftforge.network.PacketDistributor; +import net.minecraftforge.network.simple.SimpleChannel; +import net.modcrafters.minecraft.primalpottery.forge.client.ForgeTemplateScreen; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.template.TemplateEdits; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.template.TemplateWire; + +public final class TemplateChannel { + private static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( + new ResourceLocation("primalpottery", "templates"), () -> "1", "1"::equals, "1"::equals); + + static final TemplateEdits EDITS = new TemplateEdits<>(ForgeStackProfiles.INSTANCE) { + protected ItemStack held(ServerPlayer player, InteractionHand hand) { return player.getItemInHand(hand); } + + protected void show(ServerPlayer player, UUID token, Pottery shape) { + CHANNEL.send(PacketDistributor.PLAYER.with(() -> player), new Open(token, shape)); + } + + protected void giveBlueprint(ServerPlayer player, InteractionHand hand, ItemStack raw, TemplateKind kind, Pottery shape) { + ItemStack blueprint = new ItemStack(PrimalPotteryForge.template(kind)); + if (raw.hasTag()) blueprint.setTag(raw.getTag().copy()); + ForgeStackProfiles.INSTANCE.write(blueprint, shape); + raw.shrink(1); + if (raw.isEmpty()) player.setItemInHand(hand, blueprint); + else if (!player.getInventory().add(blueprint)) player.drop(blueprint, false); + } + }; + + static void register() { + CHANNEL.registerMessage(0, Open.class, Open::write, Open::read, Open::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT)); + CHANNEL.registerMessage(1, Stamp.class, Stamp::write, Stamp::read, Stamp::handle, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + } + + public static void finish(UUID token, List rings) { + CHANNEL.sendToServer(new Stamp(token, rings)); + } + + private record Open(UUID token, Pottery shape) { + void write(FriendlyByteBuf buf) { + TemplateWire.writeToken(buf, token); + TemplateWire.writeShape(buf, shape); + } + static Open read(FriendlyByteBuf buf) { return new Open(TemplateWire.readToken(buf), TemplateWire.readShape(buf)); } + void handle(Supplier context) { + context.get().enqueueWork(() -> ForgeTemplateScreen.open(token, shape)); + context.get().setPacketHandled(true); + } + } + + private record Stamp(UUID token, List rings) { + void write(FriendlyByteBuf buf) { + TemplateWire.writeToken(buf, token); + TemplateWire.writeRings(buf, rings); + } + static Stamp read(FriendlyByteBuf buf) { return new Stamp(TemplateWire.readToken(buf), TemplateWire.readRings(buf)); } + void handle(Supplier context) { + ServerPlayer player = context.get().getSender(); + context.get().enqueueWork(() -> EDITS.finish(player, token, rings)); + context.get().setPacketHandled(true); + } + } + + private TemplateChannel() {} +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/ForgeTemplateScreen.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/ForgeTemplateScreen.java new file mode 100644 index 0000000..e781706 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/ForgeTemplateScreen.java @@ -0,0 +1,128 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.BufferUploader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; +import java.util.UUID; +import net.minecraft.world.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.forge.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryType; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.modcrafters.minecraft.primalpottery.forge.TemplateChannel; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.template.TemplatePanel; + +public final class ForgeTemplateScreen extends Screen implements TemplatePanel.Canvas { + private static final ResourceLocation BACKGROUND = new ResourceLocation("primalpottery", "textures/gui/template_editor.png"); + private final UUID token; + private final TemplatePanel panel; + private final ItemStack blankIcon, blueprintIcon; + private int left, top; + private Button shape, hollow, shorter, taller, undo; + private boolean sent; + private GuiGraphics graphics; + private BufferBuilder buffer; + + private ForgeTemplateScreen(UUID token, Pottery initial) { + super(label(initial.size() == Pottery.Size.LARGE ? "large" : "small")); + this.token = token; + this.panel = new TemplatePanel(initial); + TemplateKind blank = initial.size() == Pottery.Size.LARGE ? TemplateKind.LARGE_RAW : TemplateKind.SMALL_RAW; + blankIcon = new ItemStack(PrimalPotteryForge.template(blank)); + blueprintIcon = new ItemStack(PrimalPotteryForge.template(blank.blueprint())); + } + + public static void open(UUID token, Pottery initial) { + Minecraft.getInstance().setScreen(new ForgeTemplateScreen(token, initial)); + } + + private static Component label(String key, Object... args) { + return Component.translatable("gui.primalpottery.template." + key, args); + } + + @Override protected void init() { + left = (width - TemplatePanel.WIDTH) / 2; + top = (height - TemplatePanel.HEIGHT) / 2; + shape = button("shape", 9, 146, 45, () -> panel.hollow(false)); + hollow = button("hollow", 55, 146, 48, () -> panel.hollow(true)); + shorter = button("shorter", 106, 146, 16, () -> panel.resize(-1)); + taller = button("taller", 177, 146, 16, () -> panel.resize(1)); + undo = button("undo", 196, 146, 43, panel::undo); + button("stamp", 146, 181, 93, () -> { + sent = true; + TemplateChannel.finish(token, panel.shape().discs()); + minecraft.setScreen(null); + }); + } + + private Button button(String key, int x, int y, int w, Runnable press) { + return addRenderableWidget(Button.builder(label(key), b -> press.run()).bounds(left + x, top + y, w, 18).build()); + } + + @Override public boolean isPauseScreen() { return false; } + @Override public void removed() { + if (!sent && minecraft.getConnection() != null) TemplateChannel.finish(token, java.util.List.of()); + super.removed(); + } + + @Override public boolean mouseClicked(double x, double y, int button) { + return panel.begin(x - left, y - top, button) || super.mouseClicked(x, y, button); + } + @Override public boolean mouseDragged(double x, double y, int button, double dx, double dy) { + return panel.drag(x - left, y - top, button) || super.mouseDragged(x, y, button, dx, dy); + } + @Override public boolean mouseReleased(double x, double y, int button) { + panel.release(); + return super.mouseReleased(x, y, button); + } + + @Override public void render(GuiGraphics gui, int mx, int my, float partialTick) { + renderBackground(gui); + gui.blit(BACKGROUND, left, top, 0, 0, TemplatePanel.WIDTH, TemplatePanel.HEIGHT, 256, 256); + graphics = gui; + panel.draw(this, left, top); + graphics = null; + gui.renderItem(blankIcon, left + 8, top + 3); + gui.renderItem(blueprintIcon, left + 8, top + 182); + PotteryType type = panel.info().type(); + gui.drawString(font, title, left + 28, top + 8, 0xff403c37, false); + Component h = label("height", panel.heightLabel()); + gui.drawString(font, h, left + 150 - font.width(h) / 2, top + 151, 0xff403c37, false); + gui.drawString(font, label(panel.hint(mx - left, my - top)), left + 9, top + 167, 0xff403c37, false); + Component kind = type.isVessel() || type.isServingDish() + ? Component.translatable(type.shapeKey()) : Component.literal(type.label()); + gui.drawString(font, kind, left + 28, top + 181, 0xff403c37, false); + if (!type.isServingDish()) { + gui.drawString(font, label("volume", panel.info().volume()), left + 28, top + 192, 0xff51473d, false); + } + shape.active = panel.hollow(); + hollow.active = !panel.hollow(); + shorter.active = panel.canResize(-1); + taller.active = panel.canResize(1); + undo.active = panel.canUndo(); + super.render(gui, mx, my, partialTick); + } + + public void fill(int x, int y, int right, int bottom, int color) { graphics.fill(x, y, right, bottom, color); } + + public void beginQuads() { + graphics.flush(); + RenderSystem.setShader(GameRenderer::getPositionColorShader); + buffer = Tesselator.getInstance().getBuilder(); + buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + } + public void vertex(float x, float y, int color) { + buffer.vertex(graphics.pose().last().pose(), x, y, 0).color(color).endVertex(); + } + public void endQuads() { BufferUploader.drawWithShader(buffer.end()); } +} diff --git a/forge/src/main/resources/assets/primalpottery/lang/en_us.json b/forge/src/main/resources/assets/primalpottery/lang/en_us.json index bd44227..f9f3065 100644 --- a/forge/src/main/resources/assets/primalpottery/lang/en_us.json +++ b/forge/src/main/resources/assets/primalpottery/lang/en_us.json @@ -1 +1,27 @@ -{"block.primalpottery.pottery":"Painted Pottery"} +{ + "block.primalpottery.pottery": "Painted Pottery", + "item.primalpottery.pottery_template": "Pottery Blueprint", + "item.primalpottery.raw_pottery_template": "Raw Pottery Template", + "item.primalpottery.large_pottery_template": "Large Pottery Blueprint", + "item.primalpottery.large_raw_pottery_template": "Large Raw Pottery Template", + "gui.primalpottery.template.small": "Pottery Template", + "gui.primalpottery.template.large": "Large Pottery Template", + "gui.primalpottery.template.volume": "%s mL", + "gui.primalpottery.template.height": "Height %s", + "gui.primalpottery.template.shorter": "-", + "gui.primalpottery.template.taller": "+", + "gui.primalpottery.template.shape": "Shape", + "gui.primalpottery.template.hollow": "Hollow", + "gui.primalpottery.template.undo": "Undo", + "gui.primalpottery.template.stamp": "Stamp template", + "gui.primalpottery.template.shape_hint": "Drag the side of the clay to shape it.", + "gui.primalpottery.template.hollow_hint": "Drag inside the pot to hollow it out.", + "gui.primalpottery.template.turn_hint": "Drag to turn the display block.", + "pottery.primalpottery.shape.plate": "Plate", + "pottery.primalpottery.shape.platter": "Serving Platter", + "gui.primalpottery.template.small_place": "Four per block", + "gui.primalpottery.template.large_place": "One per block", + "pottery.primalpottery.shape.jug": "Jug", + "pottery.primalpottery.shape.bowl": "Bowl", + "pottery.primalpottery.shape.pottery": "Pottery" +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/clear_large_pottery_blueprint.json b/forge/src/main/resources/data/primalpottery/recipes/clear_large_pottery_blueprint.json new file mode 100644 index 0000000..e9fbfb4 --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/clear_large_pottery_blueprint.json @@ -0,0 +1,11 @@ +{ + "type": "minecraft:crafting_shapeless", + "ingredients": [ + { + "item": "primalpottery:large_pottery_template" + } + ], + "result": { + "item": "primalpottery:large_raw_pottery_template" + } +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/clear_pottery_blueprint.json b/forge/src/main/resources/data/primalpottery/recipes/clear_pottery_blueprint.json new file mode 100644 index 0000000..04eee31 --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/clear_pottery_blueprint.json @@ -0,0 +1,11 @@ +{ + "type": "minecraft:crafting_shapeless", + "ingredients": [ + { + "item": "primalpottery:pottery_template" + } + ], + "result": { + "item": "primalpottery:raw_pottery_template" + } +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/large_raw_pottery_template.json b/forge/src/main/resources/data/primalpottery/recipes/large_raw_pottery_template.json new file mode 100644 index 0000000..e0f2977 --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/large_raw_pottery_template.json @@ -0,0 +1,14 @@ +{ + "type": "minecraft:crafting_shapeless", + "ingredients": [ + { + "item": "minecraft:clay" + }, + { + "item": "minecraft:stick" + } + ], + "result": { + "item": "primalpottery:large_raw_pottery_template" + } +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/raw_pottery_template.json b/forge/src/main/resources/data/primalpottery/recipes/raw_pottery_template.json new file mode 100644 index 0000000..c64e398 --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/raw_pottery_template.json @@ -0,0 +1,14 @@ +{ + "type": "minecraft:crafting_shapeless", + "ingredients": [ + { + "item": "minecraft:clay_ball" + }, + { + "item": "minecraft:stick" + } + ], + "result": { + "item": "primalpottery:raw_pottery_template" + } +} diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle index d4bb652..380d6f0 100644 --- a/legacy/forge-1.12.2/build.gradle +++ b/legacy/forge-1.12.2/build.gradle @@ -50,10 +50,19 @@ jar { from('../../LICENSE') finalizedBy 'reobfJar' } +sourceSets.main.java.srcDir '../../forge/shared/src/main/java' + processResources { inputs.property 'version', version filesMatching('mcmod.info') { expand(version: project.version) } - from('../../src/main/resources') { include 'assets/primalpottery/textures/block/fired_clay.png' } + from('../../src/main/resources') { include 'assets/primalpottery/textures/block/fired_clay.png', + 'assets/primalpottery/textures/item/*pottery_template.png', + 'assets/primalpottery/textures/gui/template_editor.png', + 'assets/primalpottery/models/item/*pottery_template.json' } + from('../../forge/src/main/resources/data/primalpottery/recipes') { + include '*pottery_template.json', 'clear*pottery_blueprint.json' + into 'assets/primalpottery/recipes' + } from('../../forge/src/main/resources') { include 'assets/primalpottery/models/block/pottery.json', 'assets/primalpottery/models/item/pottery.json', 'assets/primalpottery/textures/block/pottery_inks.png', 'assets/primalpottery/textures/block/paint_sheet.png' diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java new file mode 100644 index 0000000..5c6bb46 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java @@ -0,0 +1,30 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.world.World; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; + +final class ForgeTemplateItem extends Item { + private final TemplateKind kind; + + ForgeTemplateItem(TemplateKind kind) { + this.kind = kind; + setRegistryName("primalpottery", kind.id); + setUnlocalizedName("primalpottery." + kind.id); + setMaxStackSize(kind == kind.blueprint() ? 1 : 64); + setCreativeTab(CreativeTabs.MISC); + } + + @Override + public ActionResult onItemRightClick(World world, EntityPlayer player, EnumHand hand) { + if (player instanceof EntityPlayerMP) TemplateChannel.EDITS.open((EntityPlayerMP) player, hand, kind); + return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java index bf5dd09..206e604 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java @@ -1,5 +1,7 @@ package net.modcrafters.minecraft.primalpottery.legacy; +import java.util.EnumMap; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; @@ -16,7 +18,14 @@ public final class PrimalPotteryForge { public static final ResourceLocation ID = new ResourceLocation("primalpottery", "pottery"); public static final PaintedPotBlock POT = new PaintedPotBlock(); + private static final EnumMap TEMPLATES = new EnumMap<>(TemplateKind.class); + + public static Item template(TemplateKind kind) { + return TEMPLATES.get(kind); + } + @Mod.EventHandler public void setup(FMLPreInitializationEvent event) { + TemplateChannel.register(); GameRegistry.registerTileEntity(PaintedPotEntity.class, ID); } @@ -25,6 +34,11 @@ public final class PrimalPotteryForge { } @SubscribeEvent public static void registerItems(RegistryEvent.Register event) { + for (TemplateKind kind : TemplateKind.values()) { + Item template = new ForgeTemplateItem(kind); + TEMPLATES.put(kind, template); + event.getRegistry().register(template); + } event.getRegistry().register(new ItemBlock(POT).setRegistryName(ID).setMaxStackSize(1)); } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TemplateChannel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TemplateChannel.java new file mode 100644 index 0000000..f35d17e --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TemplateChannel.java @@ -0,0 +1,76 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import io.netty.buffer.ByteBuf; +import java.util.List; +import java.util.UUID; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumHand; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.network.simpleimpl.IMessage; +import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; +import net.minecraftforge.fml.relauncher.Side; +import net.modcrafters.minecraft.primalpottery.legacy.client.ForgeTemplateScreen; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.template.TemplateEdits; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.template.TemplateWire; + +public final class TemplateChannel { + private static final SimpleNetworkWrapper CHANNEL = NetworkRegistry.INSTANCE.newSimpleChannel("pottery_templates"); + + static final TemplateEdits EDITS = + new TemplateEdits(ForgeStackProfiles.INSTANCE) { + protected ItemStack held(EntityPlayerMP player, EnumHand hand) { return player.getHeldItem(hand); } + + protected void show(EntityPlayerMP player, UUID token, Pottery shape) { + CHANNEL.sendTo(new Open(token, shape), player); + } + + protected void giveBlueprint(EntityPlayerMP player, EnumHand hand, ItemStack raw, TemplateKind kind, Pottery shape) { + ItemStack blueprint = new ItemStack(PrimalPotteryForge.template(kind)); + if (raw.hasTagCompound()) blueprint.setTagCompound(raw.getTagCompound().copy()); + ForgeStackProfiles.INSTANCE.write(blueprint, shape); + raw.shrink(1); + if (raw.isEmpty()) player.setHeldItem(hand, blueprint); + else if (!player.inventory.addItemStackToInventory(blueprint)) player.dropItem(blueprint, false); + } + }; + + static void register() { + CHANNEL.registerMessage((Open message, net.minecraftforge.fml.common.network.simpleimpl.MessageContext ctx) -> { + ForgeTemplateScreen.openOnClientThread(message.token, message.shape); + return null; + }, Open.class, 0, Side.CLIENT); + CHANNEL.registerMessage((Stamp message, net.minecraftforge.fml.common.network.simpleimpl.MessageContext ctx) -> { + EntityPlayerMP player = ctx.getServerHandler().player; + player.getServerWorld().addScheduledTask(() -> EDITS.finish(player, message.token, message.rings)); + return null; + }, Stamp.class, 1, Side.SERVER); + } + + public static void finish(UUID token, List rings) { + CHANNEL.sendToServer(new Stamp(token, rings)); + } + + public static final class Open implements IMessage { + private UUID token; + private Pottery shape; + public Open() {} + Open(UUID token, Pottery shape) { this.token = token; this.shape = shape; } + public void toBytes(ByteBuf buf) { TemplateWire.writeToken(buf, token); TemplateWire.writeShape(buf, shape); } + public void fromBytes(ByteBuf buf) { token = TemplateWire.readToken(buf); shape = TemplateWire.readShape(buf); } + } + + public static final class Stamp implements IMessage { + private UUID token; + private List rings; + public Stamp() {} + Stamp(UUID token, List rings) { this.token = token; this.rings = rings; } + public void toBytes(ByteBuf buf) { TemplateWire.writeToken(buf, token); TemplateWire.writeRings(buf, rings); } + public void fromBytes(ByteBuf buf) { token = TemplateWire.readToken(buf); rings = TemplateWire.readRings(buf); } + } + + private TemplateChannel() {} +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/ForgeTemplateScreen.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/ForgeTemplateScreen.java new file mode 100644 index 0000000..b37f4e8 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/ForgeTemplateScreen.java @@ -0,0 +1,132 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import java.io.IOException; +import java.util.Collections; +import java.util.UUID; +import net.minecraft.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryType; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.BufferBuilder; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.client.resources.I18n; +import net.minecraft.util.ResourceLocation; +import net.modcrafters.minecraft.primalpottery.legacy.TemplateChannel; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.template.TemplatePanel; +import org.lwjgl.opengl.GL11; + +public final class ForgeTemplateScreen extends GuiScreen implements TemplatePanel.Canvas { + private static final ResourceLocation BACKGROUND = new ResourceLocation("primalpottery", "textures/gui/template_editor.png"); + private final UUID token; + private final TemplatePanel panel; + private final ItemStack blankIcon, blueprintIcon; + private int left, top; + private GuiButton shape, hollow, shorter, taller, undo, stamp; + private BufferBuilder buffer; + private boolean sent; + + private ForgeTemplateScreen(UUID token, Pottery initial) { + this.token = token; + this.panel = new TemplatePanel(initial); + TemplateKind blank = initial.size() == Pottery.Size.LARGE ? TemplateKind.LARGE_RAW : TemplateKind.SMALL_RAW; + blankIcon = new ItemStack(PrimalPotteryForge.template(blank)); + blueprintIcon = new ItemStack(PrimalPotteryForge.template(blank.blueprint())); + } + + public static void openOnClientThread(UUID token, Pottery initial) { + Minecraft mc = Minecraft.getMinecraft(); + mc.addScheduledTask(() -> mc.displayGuiScreen(new ForgeTemplateScreen(token, initial))); + } + + private static String label(String key, Object... args) { return I18n.format("gui.primalpottery.template." + key, args); } + + @Override public void initGui() { + left = (width - TemplatePanel.WIDTH) / 2; + top = (height - TemplatePanel.HEIGHT) / 2; + shape = button("shape", 9, 146, 45); + hollow = button("hollow", 55, 146, 48); + shorter = button("shorter", 106, 146, 16); + taller = button("taller", 177, 146, 16); + undo = button("undo", 196, 146, 43); + stamp = button("stamp", 146, 181, 93); + } + private GuiButton button(String key, int x, int y, int w) { + return addButton(new GuiButton(buttonList.size(), left + x, top + y, w, 18, label(key))); + } + + @Override protected void actionPerformed(GuiButton button) { + if (button == shape || button == hollow) panel.hollow(button == hollow); + else if (button == shorter || button == taller) panel.resize(button == taller ? 1 : -1); + else if (button == undo) panel.undo(); + else if (button == stamp) { + sent = true; + TemplateChannel.finish(token, panel.shape().discs()); + mc.displayGuiScreen(null); + } + } + + @Override public boolean doesGuiPauseGame() { return false; } + @Override public void onGuiClosed() { + if (!sent && mc.getConnection() != null) TemplateChannel.finish(token, Collections.emptyList()); + } + + @Override public void mouseClicked(int x, int y, int button) throws IOException { + if (!panel.begin(x - left, y - top, button)) super.mouseClicked(x, y, button); + } + @Override public void mouseClickMove(int x, int y, int button, long time) { + if (!panel.drag(x - left, y - top, button)) super.mouseClickMove(x, y, button, time); + } + @Override public void mouseReleased(int x, int y, int button) { + panel.release(); + super.mouseReleased(x, y, button); + } + + @Override public void drawScreen(int mx, int my, float partialTick) { + drawDefaultBackground(); + GlStateManager.color(1, 1, 1, 1); + mc.getTextureManager().bindTexture(BACKGROUND); + drawModalRectWithCustomSizedTexture(left, top, 0, 0, TemplatePanel.WIDTH, TemplatePanel.HEIGHT, 256, 256); + panel.draw(this, left, top); + itemRender.renderItemAndEffectIntoGUI(blankIcon, left + 8, top + 3); + itemRender.renderItemAndEffectIntoGUI(blueprintIcon, left + 8, top + 182); + PotteryType type = panel.info().type(); + Pottery pot = panel.shape(); + fontRenderer.drawString(label(pot.size() == Pottery.Size.LARGE ? "large" : "small"), left + 28, top + 8, 0xff403c37); + String h = label("height", panel.heightLabel()); + fontRenderer.drawString(h, left + 150 - fontRenderer.getStringWidth(h) / 2, top + 151, 0xff403c37); + fontRenderer.drawString(label(panel.hint(mx - left, my - top)), left + 9, top + 167, 0xff403c37); + String kind = type.isVessel() || type.isServingDish() + ? I18n.format(type.shapeKey()) : type.label(); + fontRenderer.drawString(kind, left + 28, top + 181, 0xff403c37); + if (!type.isServingDish()) { + fontRenderer.drawString(label("volume", panel.info().volume()), left + 28, top + 192, 0xff51473d); + } + shape.enabled = panel.hollow(); + hollow.enabled = !panel.hollow(); + shorter.enabled = panel.canResize(-1); + taller.enabled = panel.canResize(1); + undo.enabled = panel.canUndo(); + super.drawScreen(mx, my, partialTick); + } + + public void fill(int x, int y, int right, int bottom, int color) { drawRect(x, y, right, bottom, color); } + public void beginQuads() { + GlStateManager.disableTexture2D(); + buffer = Tessellator.getInstance().getBuffer(); + buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); + } + public void vertex(float x, float y, int color) { + buffer.pos(x, y, 0).color(color >> 16 & 255, color >> 8 & 255, color & 255, 255).endVertex(); + } + public void endQuads() { + Tessellator.getInstance().draw(); + GlStateManager.enableTexture2D(); + GlStateManager.color(1, 1, 1, 1); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java index 7bcf3a0..973ab8c 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java @@ -29,6 +29,7 @@ import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotBlock; import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import org.apache.commons.lang3.tuple.Pair; @@ -52,6 +53,10 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item } @SubscribeEvent public static void register(ModelRegistryEvent event) { + for (TemplateKind kind : TemplateKind.values()) { + ModelLoader.setCustomModelResourceLocation(PrimalPotteryForge.template(kind), 0, + new ModelResourceLocation(new ResourceLocation("primalpottery", kind.id), "inventory")); + } ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(PrimalPotteryForge.POT), 0, new ModelResourceLocation(PrimalPotteryForge.ID, "inventory")); } diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang index 60ed62a..740f8db 100644 --- a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang @@ -1 +1,25 @@ tile.primalpottery.pottery.name=Painted Pottery +item.primalpottery.pottery_template.name=Pottery Blueprint +item.primalpottery.raw_pottery_template.name=Raw Pottery Template +item.primalpottery.large_pottery_template.name=Large Pottery Blueprint +item.primalpottery.large_raw_pottery_template.name=Large Raw Pottery Template +gui.primalpottery.template.small=Pottery Template +gui.primalpottery.template.large=Large Pottery Template +gui.primalpottery.template.volume=%s mL +gui.primalpottery.template.height=Height %s +gui.primalpottery.template.shorter=- +gui.primalpottery.template.taller=+ +gui.primalpottery.template.shape=Shape +gui.primalpottery.template.hollow=Hollow +gui.primalpottery.template.undo=Undo +gui.primalpottery.template.stamp=Stamp template +gui.primalpottery.template.shape_hint=Drag the side of the clay to shape it. +gui.primalpottery.template.hollow_hint=Drag inside the pot to hollow it out. +gui.primalpottery.template.turn_hint=Drag to turn the display block. +pottery.primalpottery.shape.plate=Plate +pottery.primalpottery.shape.platter=Serving Platter +gui.primalpottery.template.small_place=Four per block +gui.primalpottery.template.large_place=One per block +pottery.primalpottery.shape.jug=Jug +pottery.primalpottery.shape.bowl=Bowl +pottery.primalpottery.shape.pottery=Pottery diff --git a/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/template/TemplateEditsTest.java b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/template/TemplateEditsTest.java new file mode 100644 index 0000000..eada9fd --- /dev/null +++ b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/template/TemplateEditsTest.java @@ -0,0 +1,57 @@ +package net.modcrafters.minecraft.primalpottery.template; + +import java.util.Collections; +import java.util.UUID; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryStackProfiles; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class TemplateEditsTest { + private static class Stack { Pottery saved; } + private static final PotteryStackProfiles PROFILES = new PotteryStackProfiles() { + public Pottery read(Stack stack) { return stack.saved; } + public void write(Stack stack, Pottery shape) { stack.saved = shape; } + }; + private final Object player = new Object(); + private Stack held = new Stack(); + private UUID token; + private Pottery drawing; + private int stamped; + private final TemplateEdits edits = new TemplateEdits(PROFILES) { + protected Stack held(Object player, String hand) { return held; } + protected void show(Object player, UUID id, Pottery shape) { token = id; drawing = shape; } + protected void giveBlueprint(Object player, String hand, Stack raw, TemplateKind kind, Pottery shape) { stamped++; } + }; + + @Test void cancellingOrChangingStacksDiscardsTheEdit() { + edits.open(player, "main", TemplateKind.SMALL_RAW); + edits.finish(player, token, Collections.emptyList()); + edits.finish(player, token, drawing.discs()); + edits.open(player, "main", TemplateKind.SMALL_RAW); + held = new Stack(); + edits.finish(player, token, drawing.discs()); + assertEquals(0, stamped); + } + + @Test void onlyTheCurrentSessionCanStampOnce() { + edits.open(player, "main", TemplateKind.SMALL_RAW); + UUID previous = token; + edits.open(player, "main", TemplateKind.SMALL_RAW); + edits.finish(player, previous, drawing.discs()); + edits.finish(new Object(), token, drawing.discs()); + assertEquals(0, stamped); + edits.finish(player, token, drawing.discs()); + edits.finish(player, token, drawing.discs()); + assertEquals(1, stamped); + } + + @Test void invalidDimensionsLeaveTheOriginalBlueprintIntact() { + held.saved = Pottery.jug(); + Pottery original = held.saved; + edits.open(player, "off", TemplateKind.SMALL_BLUEPRINT); + edits.finish(player, token, Collections.singletonList(new PotteryDisc(1, Double.NaN))); + assertSame(original, held.saved); + } +} diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java b/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java index 51e207f..1107580 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/item/TemplateItem.java @@ -1,7 +1,6 @@ package net.modcrafters.minecraft.primalpottery.item; import net.modcrafters.minecraft.primalpottery.pottery.PotteryTags; -import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import net.minecraft.nbt.CompoundTag; @@ -16,7 +15,7 @@ import net.minecraft.world.level.Level; import net.modcrafters.minecraft.primalpottery.client.TemplateScreen; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; -import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; //? if >=26.1 import net.minecraft.world.item.component.TooltipDisplay; //? if <26.1 @@ -39,24 +38,7 @@ public static Pottery.Size size(ItemStack stack) { } public static Pottery fresh(Pottery.Size size) { - // Sample the starter jug into one editable ring per unit of clay. - List jug = Pottery.jug().discs(); - double height = jug.stream().mapToDouble(PotteryDisc::height).sum(); - double widest = jug.stream().mapToDouble(PotteryDisc::radius).max().orElseThrow(); - double scale = size.radius() / widest; - List rings = new ArrayList<>(size.units); - int index = 0; - double end = jug.getFirst().height(); - for (int row = 0; row < size.units; row++) { - double y = (row + 0.5) * height / size.units; - while (y >= end && index + 1 < jug.size()) { - end += jug.get(++index).height(); - } - PotteryDisc disc = jug.get(index); - rings.add(new PotteryDisc(1, disc.radius() * scale, disc.innerRadius() * scale)); - } - Pottery.sealTemplate(rings); - return new Pottery(size, rings); + return PotteryTemplates.fresh(size); } public static void write(ItemStack stack, Pottery pottery) { diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/network/TemplateSync.java b/src/main/java/net/modcrafters/minecraft/primalpottery/network/TemplateSync.java index c7474ef..0175731 100644 --- a/src/main/java/net/modcrafters/minecraft/primalpottery/network/TemplateSync.java +++ b/src/main/java/net/modcrafters/minecraft/primalpottery/network/TemplateSync.java @@ -1,6 +1,5 @@ package net.modcrafters.minecraft.primalpottery.network; -import java.util.ArrayList; import java.util.List; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; @@ -9,6 +8,7 @@ import net.modcrafters.minecraft.primalpottery.item.TemplateItem; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; /** The server saves the profile and turns a raw template into a blueprint. */ public final class TemplateSync { @@ -30,12 +30,8 @@ public static void apply(Player player, boolean mainHand, List disc InteractionHand hand = mainHand ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; ItemStack stack = player.getItemInHand(hand); Pottery.Size size = TemplateItem.size(stack); - if (!Pottery.validProfile(size, discs)) { - return; - } - List rings = new ArrayList<>(discs); - Pottery.sealTemplate(rings); - Pottery template = new Pottery(size, rings); + Pottery template = PotteryTemplates.stamp(size, discs); + if (template == null) return; if (stack.is(ModItems.RAW_TEMPLATE) || stack.is(ModItems.LARGE_RAW_TEMPLATE)) { ItemStack blueprint = new ItemStack(size == Pottery.Size.LARGE ? ModItems.LARGE_BLUEPRINT : ModItems.BLUEPRINT); TemplateItem.write(blueprint, template); From 08b6ac046a7dc403556aa8a82867f857ec47abfb Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 04:31:41 +0200 Subject: [PATCH 15/22] Shape and fire pottery on both Forge wheels Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/DisplayCheck.java | 3 +- .../1.12.2/potterycheck/WheelClientCheck.java | 55 ++++++++ .../1.12.2/potterycheck/WheelGameplay.java | 96 +++++++++++++ .../1.20.1/potterycheck/DisplayCheck.java | 3 +- .../1.20.1/potterycheck/WheelClientCheck.java | 55 ++++++++ .../1.20.1/potterycheck/WheelGameplay.java | 98 +++++++++++++ .../primalpottery/pottery/WheelClay.java | 65 +++++++++ forge/build.gradle | 3 + .../primalpottery/wheel/WheelInteraction.java | 44 ++++++ forge/shared/wheel-models.gradle | 27 ++++ .../forge/FirePotteryRecipe.java | 31 +++++ .../forge/PrimalPotteryForge.java | 12 ++ .../primalpottery/forge/WheelBlock.java | 79 +++++++++++ .../primalpottery/forge/WheelEntity.java | 127 +++++++++++++++++ .../forge/client/PotteryModel.java | 3 +- .../forge/client/WheelRenderer.java | 46 ++++++ .../blockstates/pottery_wheel.json | 10 ++ .../assets/primalpottery/lang/en_us.json | 4 +- .../models/block/wheel_empty.json | 6 + .../models/item/raw_pottery.json | 6 + .../loot_tables/blocks/pottery_wheel.json | 26 ++++ .../primalpottery/recipes/fire_pottery.json | 3 + .../primalpottery/recipes/pottery_wheel.json | 22 +++ legacy/forge-1.12.2/build.gradle | 5 + .../legacy/FirePotteryRecipe.java | 16 +++ .../legacy/PrimalPotteryForge.java | 11 ++ .../primalpottery/legacy/RawPotteryItem.java | 6 + .../primalpottery/legacy/WheelBlock.java | 90 ++++++++++++ .../primalpottery/legacy/WheelEntity.java | 131 ++++++++++++++++++ .../legacy/client/PotteryModel.java | 13 +- .../legacy/client/WheelRenderer.java | 36 +++++ .../legacy/loading/FurnacePlugin.java | 16 +++ .../loading/FurnaceResultTransformer.java | 35 +++++ .../blockstates/pottery_wheel.json | 10 ++ .../assets/primalpottery/lang/en_us.lang | 2 + .../models/block/wheel_empty.json | 6 + .../models/item/raw_pottery.json | 6 + .../models/item/wheel_rotor.json | 3 + .../primalpottery/recipes/pottery_wheel.json | 24 ++++ 39 files changed, 1228 insertions(+), 6 deletions(-) create mode 100644 .github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java create mode 100644 .github/forge-display-check/1.12.2/potterycheck/WheelGameplay.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/WheelGameplay.java create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/WheelClay.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java create mode 100644 forge/shared/wheel-models.gradle create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelBlock.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java create mode 100644 forge/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json create mode 100644 forge/src/main/resources/assets/primalpottery/models/block/wheel_empty.json create mode 100644 forge/src/main/resources/assets/primalpottery/models/item/raw_pottery.json create mode 100644 forge/src/main/resources/data/primalpottery/loot_tables/blocks/pottery_wheel.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/fire_pottery.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/pottery_wheel.json create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelBlock.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnacePlugin.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/block/wheel_empty.json create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/raw_pottery.json create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/wheel_rotor.json create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/pottery_wheel.json diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java index 5efcb83..3a0f7ba 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -33,6 +33,7 @@ public final class DisplayCheck { private static final Pottery CHECKER = checkerboardJug(); private static final ForgeTemplateCheck templates = new ForgeTemplateCheck(); + private static final WheelClientCheck wheel = new WheelClientCheck(); private static boolean opening; private static boolean placed; private static int ticks; @@ -59,7 +60,7 @@ public final class DisplayCheck { return; } if (mc.player == null || mc.world == null || ++ticks < 40) return; - if (!templates.tick()) return; + if (!templates.tick() || !wheel.tick(mc)) return; if (!placed) { placed = true; mc.gameSettings.hideGUI = true; diff --git a/.github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java new file mode 100644 index 0000000..b43b0f8 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java @@ -0,0 +1,55 @@ +package potterycheck; + +import java.util.concurrent.Future; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.client.Minecraft; +import net.modcrafters.minecraft.primalpottery.legacy.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.legacy.WheelEntity; + +final class WheelClientCheck { + private enum Phase { START, SHAPE, CAPTURE, FIRE, DONE } + private volatile Phase phase = Phase.START; + private Future pending; + private WheelGameplay gameplay; + private int ticks; + + boolean tick(Minecraft client) throws Exception { + if (pending != null) { + if (!pending.isDone()) return false; + pending.get(); + } + if (phase == Phase.DONE) return true; + if (++ticks > 1200) throw new AssertionError("Wheel timed out at " + phase); + net.minecraft.server.MinecraftServer server = client.getIntegratedServer(); + if (phase == Phase.CAPTURE) { + net.minecraft.tileentity.TileEntity tile = client.world.getTileEntity(WheelGameplay.BASE); + if (!(tile instanceof WheelEntity) || ((WheelEntity) tile).clay.worked() != 100) return false; + DisplayCheck.screenshot(client, "wheel.png"); + phase = Phase.FIRE; + pending = server.addScheduledTask(() -> gameplay.fire()); + } else { + pending = server.addScheduledTask(() -> { + switch (phase) { + case START: + EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); + gameplay = new WheelGameplay(server.getWorld(0), player, + ForgeStackProfiles.INSTANCE.read(player.getHeldItemOffhand())); + gameplay.start(); + phase = Phase.SHAPE; + break; + case SHAPE: + if (gameplay.finished()) phase = Phase.CAPTURE; + break; + case FIRE: + if (gameplay.fired()) { + gameplay.verify(); + phase = Phase.DONE; + } + break; + default: throw new AssertionError(phase); + } + }); + } + return false; + } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/WheelGameplay.java b/.github/forge-display-check/1.12.2/potterycheck/WheelGameplay.java new file mode 100644 index 0000000..474488e --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/WheelGameplay.java @@ -0,0 +1,96 @@ +package potterycheck; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntityFurnace; +import net.minecraft.util.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.WorldServer; +import net.modcrafters.minecraft.primalpottery.legacy.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.legacy.WheelEntity; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Exercises the wheel item, block use, inventory and real furnace tick path in the disposable world. */ +public final class WheelGameplay { + public static final BlockPos BASE = new BlockPos(44, 80, 4); + private final WorldServer level; + private final EntityPlayerMP player; + private final Pottery expected; + + public WheelGameplay(WorldServer level, EntityPlayerMP player, Pottery expected) { + this.level = level; + this.player = player; + this.expected = expected; + } + public void start() { + for (int x = -2; x <= 2; x++) for (int z = -4; z <= 2; z++) { + level.setBlockState(BASE.add(x, -1, z), Blocks.STONE.getDefaultState()); + } + player.connection.setPlayerLocation(44.5, 80, 1.5, 0, 12); + player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(PrimalPotteryForge.WHEEL)); + place(BASE); + use(EnumHand.OFF_HAND, .08, .96, .12); + check(player.getHeldItem(EnumHand.OFF_HAND).isEmpty(), "Blueprint did not move onto table"); + player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(Items.CLAY_BALL)); + use(EnumHand.MAIN_HAND, .5, 1, .5); + for (int kick = 0; kick < 5; kick++) use(EnumHand.MAIN_HAND, .5, .25, .1); + check(wheel().clay.target() != null && wheel().clay.momentum() == 120, "Clay or kicks missing"); + player.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); + } + public boolean finished() { return wheel().clay.worked() == 100; } + public void fire() { + use(EnumHand.MAIN_HAND, .5, 1, .5); + ItemStack raw = player.getHeldItem(EnumHand.MAIN_HAND); + same(ForgeStackProfiles.INSTANCE.read(raw)); + check(raw.getItem() == PrimalPotteryForge.RAW, "Did not take unfired clay"); + BlockPos oven = BASE.east(2); + level.setBlockState(oven, Blocks.FURNACE.getDefaultState()); + TileEntityFurnace furnace = (TileEntityFurnace) level.getTileEntity(oven); + furnace.setInventorySlotContents(0, raw); + player.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); + furnace.setInventorySlotContents(1, new ItemStack(Items.COAL)); + } + public boolean fired() { + TileEntityFurnace furnace = (TileEntityFurnace) level.getTileEntity(BASE.east(2)); + return !furnace.getStackInSlot(2).isEmpty(); + } + public void verify() { + TileEntityFurnace furnace = (TileEntityFurnace) level.getTileEntity(BASE.east(2)); + ItemStack fired = furnace.removeStackFromSlot(2); + same(ForgeStackProfiles.INSTANCE.read(fired)); + player.setHeldItem(EnumHand.MAIN_HAND, fired); + BlockPos potPos = BASE.west(); + place(potPos); + PaintedPotEntity pot = (PaintedPotEntity) level.getTileEntity(potPos); + same(ForgeStackProfiles.INSTANCE.read(level.getBlockState(potPos).getBlock().getPickBlock(level.getBlockState(potPos), + new net.minecraft.util.math.RayTraceResult(player.getPositionVector(), EnumFacing.UP, potPos), level, potPos, player))); + check(pot != null, "Missing fired vessel"); + player.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); + use(EnumHand.MAIN_HAND, .08, .96, .12); + same(ForgeStackProfiles.INSTANCE.read(player.getHeldItem(EnumHand.MAIN_HAND))); + check(wheel().blueprintStack().isEmpty(), "Blueprint stayed on the wheel"); + level.destroyBlock(BASE.up(), true); + check(level.isAirBlock(BASE), "Breaking the head left a second wheel"); + System.out.println("POTTERY VERIFIED wheel: install, spin, take, furnace, place, pick and retrieve blueprint"); + } + + private WheelEntity wheel() { return (WheelEntity) level.getTileEntity(BASE); } + + private void place(BlockPos pos) { + player.getHeldItemMainhand().onItemUse(player, level, pos.down(), EnumHand.MAIN_HAND, EnumFacing.UP, .5F, 1, .5F); + } + private void use(EnumHand hand, double x, double y, double z) { + IBlockState state = level.getBlockState(BASE); + check(state.getBlock().onBlockActivated(level, BASE, state, player, hand, EnumFacing.UP, (float) x, (float) y, (float) z), "Wheel use"); + } + private void same(Pottery shape) { + check(shape != null && shape.size() == expected.size() && shape.discs().equals(expected.discs()) + && shape.paint().equals(expected.paint()), "Wheel or furnace lost the profile"); + } + private static void check(boolean ok, String message) { if (!ok) throw new AssertionError(message); } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index 7a224e2..f0ade77 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -36,6 +36,7 @@ public final class DisplayCheck { private static final Pottery CHECKER = checkerboardJug(); private static final ForgeTemplateCheck templates = new ForgeTemplateCheck(); + private static final WheelClientCheck wheel = new WheelClientCheck(); private static boolean opening; private static boolean placed; private static int ticks; @@ -61,7 +62,7 @@ public final class DisplayCheck { return; } if (mc.player == null || mc.level == null || ++ticks < 40) return; - if (!templates.tick()) return; + if (!templates.tick() || !wheel.tick(mc)) return; if (!placed) { placed = true; mc.options.hideGui = true; diff --git a/.github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java b/.github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java new file mode 100644 index 0000000..8c46675 --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java @@ -0,0 +1,55 @@ +package potterycheck; + +import java.util.concurrent.Future; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.client.Minecraft; +import net.modcrafters.minecraft.primalpottery.forge.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.forge.WheelEntity; + +final class WheelClientCheck { + private enum Phase { START, SHAPE, CAPTURE, FIRE, DONE } + private volatile Phase phase = Phase.START; + private Future pending; + private WheelGameplay gameplay; + private int ticks; + + boolean tick(Minecraft client) throws Exception { + if (pending != null) { + if (!pending.isDone()) return false; + pending.get(); + } + if (phase == Phase.DONE) return true; + if (++ticks > 1200) throw new AssertionError("Wheel timed out at " + phase); + var server = client.getSingleplayerServer(); + if (phase == Phase.CAPTURE) { + var tile = client.level.getBlockEntity(WheelGameplay.BASE); + if (!(tile instanceof WheelEntity) || ((WheelEntity) tile).clay.worked() != 100) return false; + DisplayCheck.screenshot(client, "wheel.png"); + phase = Phase.FIRE; + pending = server.submit(() -> gameplay.fire()); + } else { + pending = server.submit(() -> { + switch (phase) { + case START: + ServerPlayer player = server.getPlayerList().getPlayers().get(0); + gameplay = new WheelGameplay(server.overworld(), player, + ForgeStackProfiles.INSTANCE.read(player.getOffhandItem())); + gameplay.start(); + phase = Phase.SHAPE; + break; + case SHAPE: + if (gameplay.finished()) phase = Phase.CAPTURE; + break; + case FIRE: + if (gameplay.fired()) { + gameplay.verify(); + phase = Phase.DONE; + } + break; + default: throw new AssertionError(phase); + } + }); + } + return false; + } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/WheelGameplay.java b/.github/forge-display-check/1.20.1/potterycheck/WheelGameplay.java new file mode 100644 index 0000000..2a3d93c --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/WheelGameplay.java @@ -0,0 +1,98 @@ +package potterycheck; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.*; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.FurnaceBlockEntity; +import net.minecraft.world.phys.*; +import net.modcrafters.minecraft.primalpottery.forge.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.forge.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.forge.WheelEntity; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Exercises the wheel item, block use, inventory and real furnace tick path in the disposable world. */ +public final class WheelGameplay { + public static final BlockPos BASE = new BlockPos(44, 80, 4); + private final ServerLevel level; + private final ServerPlayer player; + private final Pottery expected; + + public WheelGameplay(ServerLevel level, ServerPlayer player, Pottery expected) { + this.level = level; + this.player = player; + this.expected = expected; + } + public void start() { + for (int x = -2; x <= 2; x++) for (int z = -4; z <= 2; z++) { + level.setBlockAndUpdate(BASE.offset(x, -1, z), Blocks.STONE.defaultBlockState()); + } + player.connection.teleport(44.5, 80, 1.5, 0, 12); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(PrimalPotteryForge.WHEEL.get())); + place(BASE); + use(InteractionHand.OFF_HAND, .08, .96, .12); + check(player.getItemInHand(InteractionHand.OFF_HAND).isEmpty(), "Blueprint did not move onto table"); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.CLAY_BALL)); + use(InteractionHand.MAIN_HAND, .5, 1, .5); + for (int kick = 0; kick < 5; kick++) use(InteractionHand.MAIN_HAND, .5, .25, .1); + check(wheel().clay.target() != null && wheel().clay.momentum() == 120, "Clay or kicks missing"); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + } + public boolean finished() { return wheel().clay.worked() == 100; } + public void fire() { + use(InteractionHand.MAIN_HAND, .5, 1, .5); + ItemStack raw = player.getItemInHand(InteractionHand.MAIN_HAND); + same(ForgeStackProfiles.INSTANCE.read(raw)); + check(raw.getItem() == PrimalPotteryForge.RAW.get(), "Did not take unfired clay"); + BlockPos oven = BASE.east(2); + level.setBlockAndUpdate(oven, Blocks.FURNACE.defaultBlockState()); + FurnaceBlockEntity furnace = (FurnaceBlockEntity) level.getBlockEntity(oven); + furnace.setItem(0, raw); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + furnace.setItem(1, new ItemStack(Items.COAL)); + } + public boolean fired() { + FurnaceBlockEntity furnace = (FurnaceBlockEntity) level.getBlockEntity(BASE.east(2)); + return !furnace.getItem(2).isEmpty(); + } + public void verify() { + FurnaceBlockEntity furnace = (FurnaceBlockEntity) level.getBlockEntity(BASE.east(2)); + ItemStack fired = furnace.removeItemNoUpdate(2); + same(ForgeStackProfiles.INSTANCE.read(fired)); + player.setItemInHand(InteractionHand.MAIN_HAND, fired); + BlockPos potPos = BASE.west(); + place(potPos); + PaintedPotEntity pot = (PaintedPotEntity) level.getBlockEntity(potPos); + same(ForgeStackProfiles.INSTANCE.read(level.getBlockState(potPos).getCloneItemStack(new BlockHitResult(Vec3.atCenterOf(potPos), Direction.UP, potPos, false), + level, potPos, player))); + check(pot != null, "Missing fired vessel"); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + use(InteractionHand.MAIN_HAND, .08, .96, .12); + same(ForgeStackProfiles.INSTANCE.read(player.getItemInHand(InteractionHand.MAIN_HAND))); + check(wheel().blueprintStack().isEmpty(), "Blueprint stayed on the wheel"); + level.destroyBlock(BASE.above(), true); + check(level.isEmptyBlock(BASE), "Breaking the head left a second wheel"); + System.out.println("POTTERY VERIFIED wheel: install, spin, take, furnace, place, pick and retrieve blueprint"); + } + + private WheelEntity wheel() { return (WheelEntity) level.getBlockEntity(BASE); } + + private void place(BlockPos pos) { + var hit = new BlockHitResult(Vec3.atBottomCenterOf(pos), Direction.UP, pos.below(), false); + player.getMainHandItem().useOn(new UseOnContext(player, InteractionHand.MAIN_HAND, hit)); + } + private void use(InteractionHand hand, double x, double y, double z) { + var hit = new BlockHitResult(Vec3.atLowerCornerOf(BASE).add(x, y, z), Direction.UP, BASE, false); + check(level.getBlockState(BASE).use(level, player, hand, hit).consumesAction(), "Wheel use"); + } + private void same(Pottery shape) { + check(shape != null && shape.size() == expected.size() && shape.discs().equals(expected.discs()) + && shape.paint().equals(expected.paint()), "Wheel or furnace lost the profile"); + } + private static void check(boolean ok, String message) { if (!ok) throw new AssertionError(message); } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/WheelClay.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/WheelClay.java new file mode 100644 index 0000000..9f96f89 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/WheelClay.java @@ -0,0 +1,65 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +/** Formation on a kick wheel. A kick supplies 24 ticks and a finished vessel takes 100. */ +public final class WheelClay { + private Pottery start, target; + private int worked, momentum, angle; + private Pottery cached; + + public void start(Pottery startingShape, Pottery blueprint) { + start = startingShape; + target = Pottery.formed(blueprint); + worked = 0; + cached = null; + } + + public void retarget(Pottery blueprint) { + Pottery next = Pottery.formed(blueprint); + if (target != null && target.size() == next.size()) { + target = next; + cached = null; + } + } + + public void kick() { + if (worked < 100) momentum = Math.min(momentum, Integer.MAX_VALUE - 24) + 24; + } + + public boolean tick() { + if (momentum == 0) return false; + momentum--; + angle = (angle + 30) % 360; + if (target != null) { + cached = null; + if (++worked == 100) momentum = 0; + } + return true; + } + + public Pottery shape() { + if (target != null && cached == null) cached = Pottery.shaped(start, target, worked / 100.0); + return cached; + } + + public Pottery take() { + Pottery current = shape(); + start = target = cached = null; + worked = 0; + return current; + } + + public void restore(Pottery start, Pottery target, int worked, int momentum, int angle) { + this.start = start != null && target != null && start.size() == target.size() ? start : null; + this.target = target; + this.worked = target == null ? 0 : Math.max(0, Math.min(100, worked)); + this.momentum = this.worked == 100 ? 0 : Math.max(0, momentum); + this.angle = Math.floorMod(angle, 360); + cached = null; + } + + public Pottery start() { return start; } + public Pottery target() { return target; } + public int worked() { return worked; } + public int momentum() { return momentum; } + public int angle() { return angle; } +} diff --git a/forge/build.gradle b/forge/build.gradle index af6fc47..69b7fbc 100644 --- a/forge/build.gradle +++ b/forge/build.gradle @@ -36,3 +36,6 @@ legacyForge { server { server() } } } + +ext.potteryAssets = file('../src/main/resources/assets/primalpottery') +apply from: 'shared/wheel-models.gradle' diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java new file mode 100644 index 0000000..3584a0d --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java @@ -0,0 +1,44 @@ +package net.modcrafters.minecraft.primalpottery.wheel; + +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.WheelClay; + +/** Native adapters move stacks. This class decides which part the player used and what it accepts. */ +public abstract class WheelInteraction { + public abstract boolean holdingBlueprint(); + public abstract boolean emptyHand(); + public abstract Pottery blueprint(); + public abstract boolean hasBlueprint(); + public abstract Pottery rawShape(); + public abstract boolean holdsClay(Pottery.Size size); + public abstract void exchangeBlueprint(); + public abstract void consumeClay(); + public abstract void giveRaw(Pottery pottery); + + public boolean use(WheelClay clay, double x, double y, double z, boolean server) { + if (y < 0.75) { + if (server) clay.kick(); + return true; + } + if (y < 31.0 / 32 || Math.max(Math.abs(x - .5), Math.abs(z - .5)) > 10.0 / 32) { + if (!holdingBlueprint() && !(emptyHand() && hasBlueprint())) return false; + if (server) { + exchangeBlueprint(); + clay.retarget(blueprint()); + } + return true; + } + if (clay.target() != null) { + if (server) giveRaw(clay.take()); + return true; + } + Pottery.Size size = Pottery.formed(blueprint()).size(); + Pottery raw = rawShape(); + if (raw == null ? !holdsClay(size) : raw.size() != size) return false; + if (server) { + clay.start(raw, blueprint()); + consumeClay(); + } + return true; + } +} diff --git a/forge/shared/wheel-models.gradle b/forge/shared/wheel-models.gradle new file mode 100644 index 0000000..02d44b5 --- /dev/null +++ b/forge/shared/wheel-models.gradle @@ -0,0 +1,27 @@ +// The item shows the entire wheel. In the world, the frame is static and the shaft turns. +def wheelModel = new File(project.ext.potteryAssets, 'models/block/pottery_wheel.json') +def output = file("$buildDir/generated/wheel-models") +def generateModels = tasks.register('generateWheelModels') { + inputs.file(wheelModel) + outputs.dir(output) + doLast { + def model = new groovy.json.JsonSlurper().parse(wheelModel) + model.textures.particle = model.textures.wheel + def rotating = ['Kickwheel', 'Spindle', 'Throwing head'] + def parts = model.elements.groupBy { rotating.contains(it.name) } + def models = ['pottery_wheel': model.elements, 'wheel_frame': parts[false], 'wheel_rotor': parts[true]] + def folder = new File(output, 'assets/primalpottery/models/block') + folder.mkdirs() + models.each { name, elements -> + new File(folder, name + '.json').text = groovy.json.JsonOutput.toJson(model + [elements: elements]) + } + } +} +processResources { + dependsOn generateModels + from(output) + from(project.ext.potteryAssets) { + include 'models/item/pottery_wheel.json', 'textures/block/pottery_wheel.png' + into 'assets/primalpottery' + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java new file mode 100644 index 0000000..6788703 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java @@ -0,0 +1,31 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import com.google.gson.JsonObject; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.Container; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.*; + +public final class FirePotteryRecipe extends SmeltingRecipe { + private FirePotteryRecipe(ResourceLocation id) { + super(id, "", CookingBookCategory.MISC, Ingredient.of(PrimalPotteryForge.RAW.get()), + new ItemStack(PrimalPotteryForge.ITEM.get()), 0.1F, 200); + } + + @Override public ItemStack assemble(Container furnace, RegistryAccess registries) { + ItemStack fired = new ItemStack(PrimalPotteryForge.ITEM.get()); + ItemStack raw = furnace.getItem(0); + if (raw.hasTag()) fired.setTag(raw.getTag().copy()); + return fired; + } + + @Override public RecipeSerializer getSerializer() { return PrimalPotteryForge.FIRING.get(); } + + public static final class Serializer implements RecipeSerializer { + public FirePotteryRecipe fromJson(ResourceLocation id, JsonObject json) { return new FirePotteryRecipe(id); } + public FirePotteryRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buffer) { return new FirePotteryRecipe(id); } + public void toNetwork(FriendlyByteBuf buffer, FirePotteryRecipe recipe) {} + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java index d4ca40b..d5bf10c 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java @@ -24,6 +24,16 @@ public final class PrimalPotteryForge { static final RegistryObject> ENTITY = ENTITIES.register("pottery", () -> BlockEntityType.Builder.of(PaintedPotEntity::new, POT.get()).build(null)); + public static final RegistryObject WHEEL = BLOCKS.register("pottery_wheel", WheelBlock::new); + public static final RegistryObject RAW = ITEMS.register("raw_pottery", () -> new Item(new Item.Properties().stacksTo(1))); + private static final RegistryObject WHEEL_ITEM = ITEMS.register("pottery_wheel", + () -> new BlockItem(WHEEL.get(), new Item.Properties())); + public static final RegistryObject> WHEEL_ENTITY = ENTITIES.register("pottery_wheel", + () -> BlockEntityType.Builder.of(WheelEntity::new, WHEEL.get()).build(null)); + private static final DeferredRegister> RECIPES = + DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, MOD_ID); + static final RegistryObject FIRING = RECIPES.register("fire_pottery", FirePotteryRecipe.Serializer::new); + private static final EnumMap> TEMPLATES = new EnumMap<>(TemplateKind.class); public static Item template(TemplateKind kind) { @@ -38,10 +48,12 @@ public PrimalPotteryForge() { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); bus.addListener((net.minecraftforge.event.BuildCreativeModeTabContentsEvent event) -> { if (event.getTabKey() == net.minecraft.world.item.CreativeModeTabs.INGREDIENTS) { + event.accept(WHEEL_ITEM.get()); event.accept(TEMPLATES.get(TemplateKind.SMALL_RAW).get()); event.accept(TEMPLATES.get(TemplateKind.LARGE_RAW).get()); } }); + RECIPES.register(bus); BLOCKS.register(bus); ITEMS.register(bus); ENTITIES.register(bus); diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelBlock.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelBlock.java new file mode 100644 index 0000000..07762f5 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelBlock.java @@ -0,0 +1,79 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseEntityBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.RenderShape; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BooleanProperty; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.*; + +public final class WheelBlock extends BaseEntityBlock { + static final BooleanProperty UPPER = BooleanProperty.create("upper"); + private static final VoxelShape TOP = box(3, 0, 3, 13, 8, 13); + private static final VoxelShape PARTS = Shapes.or(box(0, 13.5, 0, 16, 15.5, 16), + box(3, 15.5, 3, 13, 16, 13), box(1.5, 3, 1.5, 14.5, 5, 14.5)); + + WheelBlock() { + super(Properties.of().strength(2).noOcclusion()); + registerDefaultState(stateDefinition.any().setValue(UPPER, false)); + } + @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { builder.add(UPPER); } + @Override public BlockState getStateForPlacement(BlockPlaceContext context) { + BlockPos above = context.getClickedPos().above(); + return !context.getLevel().isOutsideBuildHeight(above) && context.getLevel().getBlockState(above).canBeReplaced(context) + ? defaultBlockState() : null; + } + @Override public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) { + level.setBlock(pos.above(), state.setValue(UPPER, true), 3); + } + @Override public RenderShape getRenderShape(BlockState state) { return state.getValue(UPPER) ? RenderShape.INVISIBLE : RenderShape.MODEL; } + @Override public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext ctx) { + return state.getValue(UPPER) ? TOP : PARTS; + } + @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return state.getValue(UPPER) ? null : new WheelEntity(pos, state); } + @Override public BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { + return createTickerHelper(type, PrimalPotteryForge.WHEEL_ENTITY.get(), (world, pos, block, wheel) -> wheel.tick()); + } + @Override public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + BlockPos base = state.getValue(UPPER) ? pos.below() : pos; + Vec3 at = hit.getLocation().subtract(base.getX(), base.getY(), base.getZ()); + if (level.getBlockEntity(base) instanceof WheelEntity wheel && wheel.use(player, hand, at.x, at.y, at.z)) { + return InteractionResult.sidedSuccess(level.isClientSide); + } + return InteractionResult.PASS; + } + @Override public void playerWillDestroy(Level level, BlockPos pos, BlockState state, Player player) { + if (!level.isClientSide && player.isCreative() && state.getValue(UPPER) && level.getBlockState(pos.below()).is(this)) { + level.destroyBlock(pos.below(), false); + } + super.playerWillDestroy(level, pos, state, player); + } + @Override public void onRemove(BlockState state, Level level, BlockPos pos, BlockState next, boolean moving) { + if (!state.is(next.getBlock()) && !level.isClientSide) { + if (level.getBlockEntity(pos) instanceof WheelEntity wheel) { + popResource(level, pos, wheel.takeClay()); + popResource(level, pos, wheel.takeBlueprint()); + } + boolean upper = state.getValue(UPPER); + BlockPos other = upper ? pos.below() : pos.above(); + BlockState partner = level.getBlockState(other); + if (partner.is(this) && partner.getValue(UPPER) != upper) level.destroyBlock(other, upper); + } + super.onRemove(state, level, pos, next, moving); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java new file mode 100644 index 0000000..f4f3679 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java @@ -0,0 +1,127 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; +import net.modcrafters.minecraft.primalpottery.pottery.WheelClay; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.wheel.WheelInteraction; + +public final class WheelEntity extends BlockEntity { + public final WheelClay clay = new WheelClay(); + private ItemStack installed = ItemStack.EMPTY; + private ItemStack visual = ItemStack.EMPTY; + private Pottery visualProfile; + + WheelEntity(BlockPos pos, BlockState state) { + super(PrimalPotteryForge.WHEEL_ENTITY.get(), pos, state); + } + + public ItemStack blueprintStack() { return installed; } + + public ItemStack visibleClay() { + Pottery shape = clay.shape(); + if (shape != visualProfile) { + visual = raw(shape); + visualProfile = shape; + } + return visual; + } + + private static ItemStack raw(Pottery shape) { + if (shape == null) return ItemStack.EMPTY; + ItemStack result = new ItemStack(PrimalPotteryForge.RAW.get()); + ForgeStackProfiles.INSTANCE.write(result, shape); + return result; + } + + ItemStack takeClay() { return raw(clay.take()); } + ItemStack takeBlueprint() { + ItemStack previous = installed; + installed = ItemStack.EMPTY; + return previous; + } + + public void tick() { + if (!clay.tick() || level.isClientSide) return; + if (clay.momentum() == 0) synchronize(); + else setChanged(); + } + + boolean use(Player player, InteractionHand hand, double x, double y, double z) { + ItemStack held = player.getItemInHand(hand); + boolean server = !level.isClientSide; + WheelInteraction interaction = new WheelInteraction() { + public boolean holdingBlueprint() { + return held.getItem() == PrimalPotteryForge.template(TemplateKind.SMALL_BLUEPRINT) + || held.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT); + } + public boolean emptyHand() { return held.isEmpty(); } + public boolean hasBlueprint() { return !installed.isEmpty(); } + public Pottery blueprint() { + if (installed.isEmpty()) return null; + Pottery saved = ForgeStackProfiles.INSTANCE.read(installed); + Pottery.Size size = installed.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT) + ? Pottery.Size.LARGE : Pottery.Size.SMALL; + return saved != null && saved.size() == size ? saved : PotteryTemplates.fresh(size); + } + public Pottery rawShape() { + return held.getItem() == PrimalPotteryForge.RAW.get() ? ForgeStackProfiles.INSTANCE.read(held) : null; + } + public boolean holdsClay(Pottery.Size size) { + return held.getItem() == (size == Pottery.Size.LARGE ? Items.CLAY : Items.CLAY_BALL); + } + public void consumeClay() { if (!player.getAbilities().instabuild) held.shrink(1); } + public void exchangeBlueprint() { + ItemStack previous = installed; + installed = held.isEmpty() ? ItemStack.EMPTY : held.split(1); + give(previous); + } + public void giveRaw(Pottery shape) { give(raw(shape)); } + private void give(ItemStack stack) { + if (stack.isEmpty()) return; + if (held.isEmpty()) player.setItemInHand(hand, stack); + else if (!player.getInventory().add(stack)) player.drop(stack, false); + } + }; + boolean used = interaction.use(clay, x, y, z, server); + if (used && server) synchronize(); + return used; + } + + private void synchronize() { + setChanged(); + level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 2); + } + + @Override protected void saveAdditional(CompoundTag tag) { + super.saveAdditional(tag); + if (!installed.isEmpty()) tag.put("blueprint", installed.save(new CompoundTag())); + if (clay.target() != null) tag.put("target", ForgePotteryTags.save(clay.target())); + if (clay.start() != null) tag.put("start", ForgePotteryTags.save(clay.start())); + tag.putInt("worked", clay.worked()); + tag.putInt("momentum", clay.momentum()); + tag.putInt("angle", clay.angle()); + } + + @Override public void load(CompoundTag tag) { + super.load(tag); + installed = ItemStack.of(tag.getCompound("blueprint")); + clay.restore(ForgePotteryTags.readProfile(tag.getCompound("start")), + ForgePotteryTags.readProfile(tag.getCompound("target")), + tag.getInt("worked"), tag.getInt("momentum"), tag.getInt("angle")); + } + + @Override public CompoundTag getUpdateTag() { return saveWithoutMetadata(); } + @Override public ClientboundBlockEntityDataPacket getUpdatePacket() { + return ClientboundBlockEntityDataPacket.create(this); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java index b9edbd7..e707d8a 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java @@ -44,6 +44,7 @@ private PotteryModel(BakedModel base, PotteryQuads bakery, List item) } @SubscribeEvent public static void register(ModelEvent.RegisterAdditional event) { + event.register(WheelRenderer.ROTOR); event.register(INKS); event.register(PAINT_SHEET); } @@ -56,7 +57,7 @@ private PotteryModel(BakedModel base, PotteryQuads bakery, List item) var inks = event.getModels().get(INKS).getParticleIcon(); var sheet = event.getModels().get(PAINT_SHEET).getParticleIcon(); event.getModels().replaceAll((key, base) -> { - if (!key.getNamespace().equals("primalpottery") || !key.getPath().equals("pottery")) return base; + if (!key.getNamespace().equals("primalpottery") || !(key.getPath().equals("pottery") || key.getPath().equals("raw_pottery"))) return base; var bakery = new PotteryQuads(base.getParticleIcon(), inks, sheet); return new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE)); }); diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java new file mode 100644 index 0000000..445937c --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java @@ -0,0 +1,46 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.EntityRenderersEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.modcrafters.minecraft.primalpottery.forge.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.forge.WheelEntity; + +@Mod.EventBusSubscriber(modid = "primalpottery", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) +public final class WheelRenderer implements BlockEntityRenderer { + static final ResourceLocation ROTOR = new ResourceLocation("primalpottery", "block/wheel_rotor"); + @SubscribeEvent public static void register(EntityRenderersEvent.RegisterRenderers event) { + event.registerBlockEntityRenderer(PrimalPotteryForge.WHEEL_ENTITY.get(), context -> new WheelRenderer()); + } + + @Override public void render(WheelEntity wheel, float partial, PoseStack pose, MultiBufferSource buffers, int light, int overlay) { + Minecraft client = Minecraft.getInstance(); + pose.pushPose(); + pose.translate(.5, 0, .5); + pose.mulPose(Axis.YP.rotationDegrees(wheel.clay.angle() + (wheel.clay.momentum() > 0 ? partial * 30 : 0))); + pose.translate(-.5, 0, -.5); + var rotor = client.getModelManager().getModel(ROTOR); + client.getBlockRenderer().getModelRenderer().renderModel(pose.last(), buffers.getBuffer(RenderType.solid()), + wheel.getBlockState(), rotor, 1, 1, 1, light, overlay); + pose.translate(.5, 1.5, .5); + client.getItemRenderer().renderStatic(wheel.visibleClay(), ItemDisplayContext.NONE, light, overlay, + pose, buffers, wheel.getLevel(), 0); + pose.popPose(); + pose.pushPose(); + pose.translate(.14, .98, .14); + pose.mulPose(Axis.XP.rotationDegrees(90)); + pose.scale(.23F, .23F, .23F); + client.getItemRenderer().renderStatic(wheel.blueprintStack(), ItemDisplayContext.NONE, light, overlay, + pose, buffers, wheel.getLevel(), 0); + pose.popPose(); + } +} diff --git a/forge/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json b/forge/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json new file mode 100644 index 0000000..f664e3b --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json @@ -0,0 +1,10 @@ +{ + "variants": { + "upper=false": { + "model": "primalpottery:block/wheel_frame" + }, + "upper=true": { + "model": "primalpottery:block/wheel_empty" + } + } +} diff --git a/forge/src/main/resources/assets/primalpottery/lang/en_us.json b/forge/src/main/resources/assets/primalpottery/lang/en_us.json index f9f3065..984b10a 100644 --- a/forge/src/main/resources/assets/primalpottery/lang/en_us.json +++ b/forge/src/main/resources/assets/primalpottery/lang/en_us.json @@ -23,5 +23,7 @@ "gui.primalpottery.template.large_place": "One per block", "pottery.primalpottery.shape.jug": "Jug", "pottery.primalpottery.shape.bowl": "Bowl", - "pottery.primalpottery.shape.pottery": "Pottery" + "pottery.primalpottery.shape.pottery": "Pottery", + "block.primalpottery.pottery_wheel": "Pottery Wheel", + "item.primalpottery.raw_pottery": "Unfired Pottery" } diff --git a/forge/src/main/resources/assets/primalpottery/models/block/wheel_empty.json b/forge/src/main/resources/assets/primalpottery/models/block/wheel_empty.json new file mode 100644 index 0000000..01dca87 --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/models/block/wheel_empty.json @@ -0,0 +1,6 @@ +{ + "textures": { + "particle": "primalpottery:block/pottery_wheel" + }, + "elements": [] +} diff --git a/forge/src/main/resources/assets/primalpottery/models/item/raw_pottery.json b/forge/src/main/resources/assets/primalpottery/models/item/raw_pottery.json new file mode 100644 index 0000000..6b6deeb --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/models/item/raw_pottery.json @@ -0,0 +1,6 @@ +{ + "parent": "primalpottery:block/pottery", + "textures": { + "particle": "minecraft:block/clay" + } +} diff --git a/forge/src/main/resources/data/primalpottery/loot_tables/blocks/pottery_wheel.json b/forge/src/main/resources/data/primalpottery/loot_tables/blocks/pottery_wheel.json new file mode 100644 index 0000000..721cf54 --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/loot_tables/blocks/pottery_wheel.json @@ -0,0 +1,26 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "primalpottery:pottery_wheel" + } + ], + "conditions": [ + { + "condition": "minecraft:block_state_property", + "block": "primalpottery:pottery_wheel", + "properties": { + "upper": "false" + } + }, + { + "condition": "minecraft:survives_explosion" + } + ] + } + ] +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/fire_pottery.json b/forge/src/main/resources/data/primalpottery/recipes/fire_pottery.json new file mode 100644 index 0000000..80f1daa --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/fire_pottery.json @@ -0,0 +1,3 @@ +{ + "type": "primalpottery:fire_pottery" +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/pottery_wheel.json b/forge/src/main/resources/data/primalpottery/recipes/pottery_wheel.json new file mode 100644 index 0000000..0f9e6aa --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/pottery_wheel.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " S ", + "PPP", + "TST" + ], + "key": { + "S": { + "item": "minecraft:stone_slab" + }, + "P": { + "tag": "minecraft:planks" + }, + "T": { + "item": "minecraft:stick" + } + }, + "result": { + "item": "primalpottery:pottery_wheel" + } +} diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle index 380d6f0..2cc4bd5 100644 --- a/legacy/forge-1.12.2/build.gradle +++ b/legacy/forge-1.12.2/build.gradle @@ -43,9 +43,11 @@ dependencies { configurations { devSideMarkers } dependencies { devSideMarkers 'net.minecraftforge:mergetool:0.2.3.3:forge@jar' } tasks.withType(JavaExec).matching { it.name in ['runClient', 'runServer'] }.configureEach { + systemProperty 'fml.coreMods.load', 'net.modcrafters.minecraft.primalpottery.legacy.loading.FurnacePlugin' doFirst { classpath = configurations.devSideMarkers + classpath } } jar { + manifest.attributes FMLCorePlugin: 'net.modcrafters.minecraft.primalpottery.legacy.loading.FurnacePlugin', FMLCorePluginContainsFMLMod: 'true' from(project(':core').sourceSets.main.output) from('../../LICENSE') finalizedBy 'reobfJar' @@ -77,3 +79,6 @@ test { useJUnitPlatform() workingDir layout.buildDirectory.get().asFile } + +ext.potteryAssets = file('../../src/main/resources/assets/primalpottery') +apply from: '../../forge/shared/wheel-models.gradle' diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java new file mode 100644 index 0000000..bf86e97 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java @@ -0,0 +1,16 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.item.ItemStack; + +/** Called after vanilla's smelting lookup. Only the raw-pottery recipe has an input-dependent result. */ +public final class FirePotteryRecipe { + private FirePotteryRecipe() {} + + public static ItemStack preserveProfile(ItemStack result, ItemStack input) { + if (input.isEmpty() || !(input.getItem() instanceof RawPotteryItem) || result.isEmpty() + || result.getItem() != net.minecraft.item.Item.getItemFromBlock(PrimalPotteryForge.POT)) return result; + ItemStack fired = result.copy(); + if (input.hasTagCompound()) fired.setTagCompound(input.getTagCompound().copy()); + return fired; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java index 206e604..796750a 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java @@ -18,6 +18,9 @@ public final class PrimalPotteryForge { public static final ResourceLocation ID = new ResourceLocation("primalpottery", "pottery"); public static final PaintedPotBlock POT = new PaintedPotBlock(); + public static final WheelBlock WHEEL = new WheelBlock(); + public static final Item RAW = new RawPotteryItem().setMaxStackSize(1).setUnlocalizedName("primalpottery.raw_pottery"); + private static final EnumMap TEMPLATES = new EnumMap<>(TemplateKind.class); public static Item template(TemplateKind kind) { @@ -25,15 +28,23 @@ public static Item template(TemplateKind kind) { } @Mod.EventHandler public void setup(FMLPreInitializationEvent event) { + GameRegistry.registerTileEntity(WheelEntity.class, new ResourceLocation("primalpottery", "pottery_wheel")); TemplateChannel.register(); GameRegistry.registerTileEntity(PaintedPotEntity.class, ID); } + @Mod.EventHandler public void recipes(net.minecraftforge.fml.common.event.FMLInitializationEvent event) { + GameRegistry.addSmelting(RAW, new net.minecraft.item.ItemStack(POT), 0.1F); + } + @SubscribeEvent public static void registerBlocks(RegistryEvent.Register event) { + event.getRegistry().register(WHEEL.setRegistryName("primalpottery", "pottery_wheel")); event.getRegistry().register(POT.setRegistryName(ID)); } @SubscribeEvent public static void registerItems(RegistryEvent.Register event) { + event.getRegistry().register(new ItemBlock(WHEEL).setRegistryName(WHEEL.getRegistryName())); + event.getRegistry().register(RAW.setRegistryName("primalpottery", "raw_pottery")); for (TemplateKind kind : TemplateKind.values()) { Item template = new ForgeTemplateItem(kind); TEMPLATES.put(kind, template); diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java new file mode 100644 index 0000000..62cb633 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java @@ -0,0 +1,6 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.item.Item; + +/** Marker used by the legacy furnace before the mod registry is available during vanilla bootstrap. */ +final class RawPotteryItem extends Item {} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelBlock.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelBlock.java new file mode 100644 index 0000000..44229af --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelBlock.java @@ -0,0 +1,90 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.block.properties.PropertyBool; +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.*; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +public final class WheelBlock extends Block { + static final PropertyBool UPPER = PropertyBool.create("upper"); + private static final AxisAlignedBB TOP = new AxisAlignedBB(.1875, 0, .1875, .8125, .5, .8125); + private static final AxisAlignedBB[] PARTS = { + new AxisAlignedBB(0, 13.5/16, 0, 1, 15.5/16, 1), + new AxisAlignedBB(3./16, 15.5/16, 3./16, 13./16, 1, 13./16), + new AxisAlignedBB(1.5/16, 3./16, 1.5/16, 14.5/16, 5./16, 14.5/16) + }; + + WheelBlock() { + super(Material.WOOD); + setHardness(2); + setCreativeTab(CreativeTabs.DECORATIONS); + setUnlocalizedName("primalpottery.pottery_wheel"); + setDefaultState(blockState.getBaseState().withProperty(UPPER, false)); + } + @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, UPPER); } + @Override public int getMetaFromState(IBlockState state) { return state.getValue(UPPER) ? 1 : 0; } + @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(UPPER, (meta & 1) != 0); } + @Override public boolean canPlaceBlockAt(World world, BlockPos pos) { + return super.canPlaceBlockAt(world, pos) && pos.getY() + 1 < world.getHeight() + && world.getBlockState(pos.up()).getBlock().isReplaceable(world, pos.up()); + } + @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { + world.setBlockState(pos.up(), state.withProperty(UPPER, true), 3); + } + @Override public boolean hasTileEntity(IBlockState state) { return !state.getValue(UPPER); } + @Override public TileEntity createTileEntity(World world, IBlockState state) { return new WheelEntity(); } + @Override public boolean isFullCube(IBlockState state) { return false; } + @Override public boolean isOpaqueCube(IBlockState state) { return false; } + @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { + return state.getValue(UPPER) ? TOP : FULL_BLOCK_AABB; + } + @Override public RayTraceResult collisionRayTrace(IBlockState state, World world, BlockPos pos, Vec3d from, Vec3d to) { + if (state.getValue(UPPER)) return rayTrace(pos, from, to, TOP); + RayTraceResult closest = null; + for (AxisAlignedBB part : PARTS) { + RayTraceResult hit = rayTrace(pos, from, to, part); + if (hit != null && (closest == null || from.squareDistanceTo(hit.hitVec) < from.squareDistanceTo(closest.hitVec))) closest = hit; + } + return closest; + } + @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, + EnumHand hand, EnumFacing side, float x, float y, float z) { + boolean upper = state.getValue(UPPER); + TileEntity tile = world.getTileEntity(upper ? pos.down() : pos); + return tile instanceof WheelEntity && ((WheelEntity) tile).use(player, hand, x, upper ? y + 1 : y, z); + } + @Override public int quantityDropped(IBlockState state, int fortune, Random random) { return state.getValue(UPPER) ? 0 : 1; } + @Override public void onBlockHarvested(World world, BlockPos pos, IBlockState state, EntityPlayer player) { + if (!world.isRemote && player.capabilities.isCreativeMode && state.getValue(UPPER) && world.getBlockState(pos.down()).getBlock() == this) { + world.setBlockToAir(pos.down()); + } + super.onBlockHarvested(world, pos, state, player); + } + @Override public void breakBlock(World world, BlockPos pos, IBlockState state) { + if (!world.isRemote) { + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof WheelEntity) { + WheelEntity wheel = (WheelEntity) tile; + spawnAsEntity(world, pos, wheel.takeClay()); + spawnAsEntity(world, pos, wheel.takeBlueprint()); + } + boolean upper = state.getValue(UPPER); + BlockPos other = upper ? pos.down() : pos.up(); + IBlockState partner = world.getBlockState(other); + if (partner.getBlock() == this && partner.getValue(UPPER) != upper) world.destroyBlock(other, upper); + } + super.breakBlock(world, pos, state); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java new file mode 100644 index 0000000..e48ff3c --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java @@ -0,0 +1,131 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.play.server.SPacketUpdateTileEntity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ITickable; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; +import net.modcrafters.minecraft.primalpottery.pottery.WheelClay; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; +import net.modcrafters.minecraft.primalpottery.wheel.WheelInteraction; + +public final class WheelEntity extends TileEntity implements ITickable { + public final WheelClay clay = new WheelClay(); + private ItemStack installed = ItemStack.EMPTY; + private ItemStack visual = ItemStack.EMPTY; + private Pottery visualProfile; + + public ItemStack blueprintStack() { return installed; } + + public ItemStack visibleClay() { + Pottery shape = clay.shape(); + if (shape != visualProfile) { + visual = raw(shape); + visualProfile = shape; + } + return visual; + } + + private static ItemStack raw(Pottery shape) { + if (shape == null) return ItemStack.EMPTY; + ItemStack result = new ItemStack(PrimalPotteryForge.RAW); + ForgeStackProfiles.INSTANCE.write(result, shape); + return result; + } + + ItemStack takeClay() { return raw(clay.take()); } + ItemStack takeBlueprint() { + ItemStack previous = installed; + installed = ItemStack.EMPTY; + return previous; + } + + public void update() { + if (!clay.tick() || world.isRemote) return; + if (clay.momentum() == 0) synchronize(); + else markDirty(); + } + + boolean use(EntityPlayer player, EnumHand hand, double x, double y, double z) { + ItemStack held = player.getHeldItem(hand); + boolean server = !world.isRemote; + WheelInteraction interaction = new WheelInteraction() { + public boolean holdingBlueprint() { + return held.getItem() == PrimalPotteryForge.template(TemplateKind.SMALL_BLUEPRINT) + || held.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT); + } + public boolean emptyHand() { return held.isEmpty(); } + public boolean hasBlueprint() { return !installed.isEmpty(); } + public Pottery blueprint() { + if (installed.isEmpty()) return null; + Pottery saved = ForgeStackProfiles.INSTANCE.read(installed); + Pottery.Size size = installed.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT) + ? Pottery.Size.LARGE : Pottery.Size.SMALL; + return saved != null && saved.size() == size ? saved : PotteryTemplates.fresh(size); + } + public Pottery rawShape() { + return held.getItem() == PrimalPotteryForge.RAW ? ForgeStackProfiles.INSTANCE.read(held) : null; + } + public boolean holdsClay(Pottery.Size size) { + return held.getItem() == (size == Pottery.Size.LARGE ? Item.getItemFromBlock(Blocks.CLAY) : Items.CLAY_BALL); + } + public void consumeClay() { if (!player.capabilities.isCreativeMode) held.shrink(1); } + public void exchangeBlueprint() { + ItemStack previous = installed; + installed = held.isEmpty() ? ItemStack.EMPTY : held.splitStack(1); + give(previous); + } + public void giveRaw(Pottery shape) { give(raw(shape)); } + private void give(ItemStack stack) { + if (stack.isEmpty()) return; + if (held.isEmpty()) player.setHeldItem(hand, stack); + else if (!player.inventory.addItemStackToInventory(stack)) player.dropItem(stack, false); + } + }; + boolean used = interaction.use(clay, x, y, z, server); + if (used && server) synchronize(); + return used; + } + + private void synchronize() { + markDirty(); + IBlockState state = world.getBlockState(pos); + world.notifyBlockUpdate(pos, state, state, 2); + } + + @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { + super.writeToNBT(tag); + if (!installed.isEmpty()) tag.setTag("blueprint", installed.writeToNBT(new NBTTagCompound())); + if (clay.target() != null) tag.setTag("target", ForgePotteryTags.save(clay.target())); + if (clay.start() != null) tag.setTag("start", ForgePotteryTags.save(clay.start())); + tag.setInteger("worked", clay.worked()); + tag.setInteger("momentum", clay.momentum()); + tag.setInteger("angle", clay.angle()); + return tag; + } + + @Override public void readFromNBT(NBTTagCompound tag) { + super.readFromNBT(tag); + installed = new ItemStack(tag.getCompoundTag("blueprint")); + clay.restore(ForgePotteryTags.readProfile(tag.getCompoundTag("start")), + ForgePotteryTags.readProfile(tag.getCompoundTag("target")), + tag.getInteger("worked"), tag.getInteger("momentum"), tag.getInteger("angle")); + } + + @Override public NBTTagCompound getUpdateTag() { return writeToNBT(new NBTTagCompound()); } + @Override public SPacketUpdateTileEntity getUpdatePacket() { + return new SPacketUpdateTileEntity(pos, 0, getUpdateTag()); + } + @Override public void onDataPacket(NetworkManager network, SPacketUpdateTileEntity packet) { + readFromNBT(packet.getNbtCompound()); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java index 973ab8c..07b32fb 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java @@ -53,6 +53,13 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item } @SubscribeEvent public static void register(ModelRegistryEvent event) { + Item wheel = Item.getItemFromBlock(PrimalPotteryForge.WHEEL); + ModelLoader.setCustomModelResourceLocation(wheel, 0, new ModelResourceLocation(wheel.getRegistryName(), "inventory")); + net.minecraft.client.renderer.block.model.ModelBakery.registerItemVariants(wheel, new ResourceLocation("primalpottery", "wheel_rotor")); + ModelLoader.setCustomModelResourceLocation(PrimalPotteryForge.RAW, 0, + new ModelResourceLocation(PrimalPotteryForge.RAW.getRegistryName(), "inventory")); + net.minecraftforge.fml.client.registry.ClientRegistry.bindTileEntitySpecialRenderer( + net.modcrafters.minecraft.primalpottery.legacy.WheelEntity.class, new WheelRenderer()); for (TemplateKind kind : TemplateKind.values()) { ModelLoader.setCustomModelResourceLocation(PrimalPotteryForge.template(kind), 0, new ModelResourceLocation(new ResourceLocation("primalpottery", kind.id), "inventory")); @@ -69,8 +76,10 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item @SubscribeEvent public static void bake(ModelBakeEvent event) { TextureAtlasSprite inks = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(INKS.toString()); TextureAtlasSprite sheet = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(PAINT_SHEET.toString()); - for (String variant : new String[]{"normal", "inventory"}) { - ModelResourceLocation key = new ModelResourceLocation(PrimalPotteryForge.ID, variant); + for (ModelResourceLocation key : new ModelResourceLocation[]{ + new ModelResourceLocation(PrimalPotteryForge.ID, "normal"), + new ModelResourceLocation(PrimalPotteryForge.ID, "inventory"), + new ModelResourceLocation(PrimalPotteryForge.RAW.getRegistryName(), "inventory")}) { IBakedModel base = event.getModelRegistry().getObject(key); PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks, sheet); event.getModelRegistry().putObject(key, new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE))); diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java new file mode 100644 index 0000000..273646d --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java @@ -0,0 +1,36 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderItem; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.legacy.WheelEntity; + +public final class WheelRenderer extends TileEntitySpecialRenderer { + private static final ModelResourceLocation ROTOR = new ModelResourceLocation("primalpottery:wheel_rotor", "inventory"); + private final ItemStack wheelItem = new ItemStack(PrimalPotteryForge.WHEEL); + + @Override public void render(WheelEntity wheel, double x, double y, double z, float partial, int destroy, float alpha) { + Minecraft client = Minecraft.getMinecraft(); + RenderItem items = client.getRenderItem(); + bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + GlStateManager.pushMatrix(); + GlStateManager.translate(x + .5, y + .5, z + .5); + GlStateManager.rotate(wheel.clay.angle() + (wheel.clay.momentum() > 0 ? partial * 30 : 0), 0, 1, 0); + items.renderItem(wheelItem, client.getBlockRendererDispatcher().getBlockModelShapes().getModelManager().getModel(ROTOR)); + GlStateManager.translate(0, 1, 0); + items.renderItem(wheel.visibleClay(), ItemCameraTransforms.TransformType.NONE); + GlStateManager.popMatrix(); + GlStateManager.pushMatrix(); + GlStateManager.translate(x + .14, y + .98, z + .14); + GlStateManager.rotate(90, 1, 0, 0); + GlStateManager.scale(.23, .23, .23); + items.renderItem(wheel.blueprintStack(), ItemCameraTransforms.TransformType.NONE); + GlStateManager.popMatrix(); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnacePlugin.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnacePlugin.java new file mode 100644 index 0000000..eb7113f --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnacePlugin.java @@ -0,0 +1,16 @@ +package net.modcrafters.minecraft.primalpottery.legacy.loading; + +import java.util.Map; +import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; + +@IFMLLoadingPlugin.Name("Primal Pottery furnace recipes") +@IFMLLoadingPlugin.MCVersion("1.12.2") +@IFMLLoadingPlugin.SortingIndex(1001) +@IFMLLoadingPlugin.TransformerExclusions("net.modcrafters.minecraft.primalpottery.legacy.loading") +public final class FurnacePlugin implements IFMLLoadingPlugin { + public String[] getASMTransformerClass() { return new String[]{FurnaceResultTransformer.class.getName()}; } + public String getModContainerClass() { return null; } + public String getSetupClass() { return null; } + public void injectData(Map data) {} + public String getAccessTransformerClass() { return null; } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java new file mode 100644 index 0000000..1731e3c --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java @@ -0,0 +1,35 @@ +package net.modcrafters.minecraft.primalpottery.legacy.loading; + +import net.minecraft.launchwrapper.IClassTransformer; +import org.objectweb.asm.*; +import org.objectweb.asm.tree.*; + +/** Forge 1.12 supplies only a constant output stack for a smelting recipe, including for hoppers. + * Pass the input to the pottery recipe at the normal return sites of FurnaceRecipes#getSmeltingResult. */ +public final class FurnaceResultTransformer implements IClassTransformer { + private static final String STACK = "Lnet/minecraft/item/ItemStack;"; + private static final String HOOK = "net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe"; + + public byte[] transform(String name, String mappedName, byte[] bytes) { + if (!"net.minecraft.item.crafting.FurnaceRecipes".equals(mappedName)) return bytes; + ClassNode recipes = new ClassNode(); + new ClassReader(bytes).accept(recipes, 0); + for (MethodNode method : recipes.methods) { + if (!(method.name.equals("getSmeltingResult") || method.name.equals("func_151395_a")) + || !method.desc.equals("(" + STACK + ")" + STACK)) continue; + for (AbstractInsnNode instruction : method.instructions.toArray()) { + if (instruction.getOpcode() != Opcodes.ARETURN) continue; + InsnList passInput = new InsnList(); + passInput.add(new VarInsnNode(Opcodes.ALOAD, 1)); + passInput.add(new MethodInsnNode(Opcodes.INVOKESTATIC, HOOK, "preserveProfile", + "(" + STACK + STACK + ")" + STACK, false)); + method.instructions.insertBefore(instruction, passInput); + } + method.maxStack++; + ClassWriter writer = new ClassWriter(0); + recipes.accept(writer); + return writer.toByteArray(); + } + throw new IllegalStateException("Missing Forge 1.12.2 furnace recipe lookup"); + } +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json new file mode 100644 index 0000000..c279ad5 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/pottery_wheel.json @@ -0,0 +1,10 @@ +{ + "variants": { + "upper=false": { + "model": "primalpottery:wheel_frame" + }, + "upper=true": { + "model": "primalpottery:wheel_empty" + } + } +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang index 740f8db..f28a5e8 100644 --- a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang @@ -23,3 +23,5 @@ gui.primalpottery.template.large_place=One per block pottery.primalpottery.shape.jug=Jug pottery.primalpottery.shape.bowl=Bowl pottery.primalpottery.shape.pottery=Pottery +tile.primalpottery.pottery_wheel.name=Pottery Wheel +item.primalpottery.raw_pottery.name=Unfired Pottery diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/block/wheel_empty.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/block/wheel_empty.json new file mode 100644 index 0000000..01dca87 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/block/wheel_empty.json @@ -0,0 +1,6 @@ +{ + "textures": { + "particle": "primalpottery:block/pottery_wheel" + }, + "elements": [] +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/raw_pottery.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/raw_pottery.json new file mode 100644 index 0000000..2949fa3 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/raw_pottery.json @@ -0,0 +1,6 @@ +{ + "parent": "primalpottery:block/pottery", + "textures": { + "particle": "minecraft:blocks/clay" + } +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/wheel_rotor.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/wheel_rotor.json new file mode 100644 index 0000000..6b7a20a --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/models/item/wheel_rotor.json @@ -0,0 +1,3 @@ +{ + "parent": "primalpottery:block/wheel_rotor" +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/pottery_wheel.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/pottery_wheel.json new file mode 100644 index 0000000..8cadda4 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/pottery_wheel.json @@ -0,0 +1,24 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " S ", + "PPP", + "TST" + ], + "key": { + "S": { + "item": "minecraft:stone_slab", + "data": 0 + }, + "P": { + "type": "forge:ore_dict", + "ore": "plankWood" + }, + "T": { + "item": "minecraft:stick" + } + }, + "result": { + "item": "primalpottery:pottery_wheel" + } +} From 1797e3fb8a8bac5042fbbaeee8935bffd2f55667 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 05:02:32 +0200 Subject: [PATCH 16/22] Backport painting, vessel contents, planters and dining to both Forge targets Co-authored-by: Face of Cat --- .../potterycheck/DiningClientCheck.java | 196 +++++++++++++ .../1.12.2/potterycheck/DisplayCheck.java | 3 +- .../potterycheck/PaintingClientCheck.java | 155 ++++++++++ .../potterycheck/PlacementGameplay.java | 67 +++++ .../potterycheck/VesselClientCheck.java | 76 +++++ .../1.12.2/potterycheck/VesselGameplay.java | 117 ++++++++ .../1.12.2/potterycheck/WheelClientCheck.java | 2 + .../potterycheck/DiningClientCheck.java | 199 +++++++++++++ .../1.20.1/potterycheck/DisplayCheck.java | 3 +- .../potterycheck/PaintingClientCheck.java | 155 ++++++++++ .../potterycheck/PlacementGameplay.java | 68 +++++ .../potterycheck/VesselClientCheck.java | 76 +++++ .../1.20.1/potterycheck/VesselGameplay.java | 117 ++++++++ .../1.20.1/potterycheck/WheelClientCheck.java | 2 + .github/scripts/release-publish.sh | 86 +++--- .github/scripts/test_curseforge_versions.py | 30 +- .github/workflows/release.yml | 37 ++- .../primalpottery/pottery/BakedVessels.java | 43 ++- .../primalpottery/pottery/PaintedPlate.java | 106 +++++++ .../primalpottery/pottery/PaintedVessel.java | 14 +- .../pottery/PlatterSegments.java | 0 .../primalpottery/pottery/PotteryLayout.java | 95 ++++++ .../pottery/VesselQuadPacker.java | 29 +- .../pottery/PaintedVesselTest.java | 14 + .../pottery/PotteryLayoutTest.java | 34 +++ forge/build.gradle | 4 + forge/shared/dining.gradle | 7 + forge/shared/painting.gradle | 11 + .../primalpottery/dining/CutleryModels.java | 121 ++++++++ .../minecraft/primalpottery/dining/Diner.java | 34 +++ .../primalpottery/dining/DiningMesh.java | 30 ++ .../primalpottery/dining/DiningScene.java | 106 +++++++ .../primalpottery/dining/DiningUse.java | 112 +++++++ .../minecraft/primalpottery/dining/Point.java | 18 ++ .../dining/ServingInventory.java | 80 +++++ .../primalpottery/dining/ServingPieces.java | 75 +++++ .../primalpottery/dining/TableSetting.java | 54 ++++ .../primalpottery/painting/IconPixels.java | 59 ++++ .../primalpottery/painting/PaintBrush.java | 43 +++ .../primalpottery/painting/PaintPanel.java | 92 ++++++ .../primalpottery/painting/PigmentTanks.java | 54 ++++ .../primalpottery/painting/Pigments.java | 19 ++ .../primalpottery/vessel/VesselMesh.java | 112 +++++++ .../vessel/VesselPreviewFrame.java | 32 ++ .../primalpottery/vessel/VesselRules.java | 38 +++ .../primalpottery/wheel/WheelGuides.java | 78 +++++ .../primalpottery/wheel/WheelInteraction.java | 4 +- .../primalpottery/forge/DyePotRecipe.java | 34 +++ .../forge/FirePotteryRecipe.java | 4 +- .../forge/ForgeTemplateItem.java | 25 ++ .../primalpottery/forge/MiniatureTree.java | 133 +++++++++ .../primalpottery/forge/PaintChannel.java | 32 ++ .../primalpottery/forge/PaintSupply.java | 36 +++ .../primalpottery/forge/PaintedPotBlock.java | 70 ++++- .../primalpottery/forge/PaintedPotEntity.java | 126 +++++++- .../primalpottery/forge/PaintingMenu.java | 77 +++++ .../forge/PaintingRegistration.java | 53 ++++ .../forge/PaintingTableBlock.java | 77 +++++ .../forge/PaintingTableEntity.java | 26 ++ .../primalpottery/forge/PlanterPlants.java | 41 +++ .../primalpottery/forge/PotBounds.java | 38 +++ .../primalpottery/forge/PotteryBlockItem.java | 52 ++++ .../primalpottery/forge/PotteryNames.java | 16 + .../primalpottery/forge/PotteryTab.java | 28 ++ .../forge/PrimalPotteryForge.java | 10 +- .../primalpottery/forge/RawPotteryItem.java | 24 ++ .../primalpottery/forge/TreePlot.java | 275 ++++++++++++++++++ .../primalpottery/forge/VesselChannel.java | 39 +++ .../primalpottery/forge/VesselData.java | 75 +++++ .../forge/VesselInteractions.java | 229 +++++++++++++++ .../primalpottery/forge/VesselItem.java | 40 +++ .../primalpottery/forge/WheelEntity.java | 43 ++- .../forge/client/PaintingClient.java | 67 +++++ .../forge/client/PaintingScreen.java | 103 +++++++ .../forge/client/PlacementOutline.java | 48 +++ .../forge/client/PotContentsRenderer.java | 29 ++ .../forge/client/PotteryModel.java | 24 +- .../forge/client/PotteryQuads.java | 4 +- .../forge/client/VesselModels.java | 169 +++++++++++ .../forge/client/VesselScreen.java | 76 +++++ .../forge/client/WheelRenderer.java | 20 +- .../primalpottery/forge/dining/Dining.java | 119 ++++++++ .../forge/dining/DiningInput.java | 25 ++ .../forge/dining/DiningRegistration.java | 35 +++ .../forge/dining/DiningRenderer.java | 125 ++++++++ .../forge/dining/DiningTable.java | 83 ++++++ .../primalpottery/forge/dining/PlateMeal.java | 149 ++++++++++ forge/src/main/resources/META-INF/mods.toml | 2 +- .../blockstates/painting_table.json | 7 + .../assets/primalpottery/lang/en_us.json | 42 ++- .../primalpottery/models/block/dyed_clay.json | 5 + .../loot_tables/blocks/painting_table.json | 19 ++ .../data/primalpottery/recipes/cutlery.json | 18 ++ .../primalpottery/recipes/paint_pottery.json | 3 + .../primalpottery/recipes/painting_table.json | 25 ++ legacy/forge-1.12.2/build.gradle | 4 + .../primalpottery/legacy/DyePotRecipe.java | 35 +++ .../legacy/FirePotteryRecipe.java | 5 + .../legacy/ForgeTemplateItem.java | 23 ++ .../primalpottery/legacy/PaintChannel.java | 55 ++++ .../primalpottery/legacy/PaintSupply.java | 36 +++ .../primalpottery/legacy/PaintedPotBlock.java | 93 +++++- .../legacy/PaintedPotEntity.java | 125 +++++++- .../primalpottery/legacy/PaintingMenu.java | 90 ++++++ .../legacy/PaintingRegistration.java | 64 ++++ .../legacy/PaintingTableBlock.java | 109 +++++++ .../legacy/PaintingTableEntity.java | 23 ++ .../primalpottery/legacy/PlanterPlants.java | 65 +++++ .../primalpottery/legacy/PotBounds.java | 39 +++ .../legacy/PotteryBlockItem.java | 48 +++ .../primalpottery/legacy/PotteryNames.java | 29 ++ .../primalpottery/legacy/PotteryTab.java | 19 ++ .../legacy/PrimalPotteryForge.java | 5 +- .../primalpottery/legacy/RawPotteryItem.java | 23 +- .../primalpottery/legacy/TreePlot.java | 56 ++++ .../primalpottery/legacy/VesselChannel.java | 48 +++ .../primalpottery/legacy/VesselData.java | 75 +++++ .../legacy/VesselInteractions.java | 241 +++++++++++++++ .../primalpottery/legacy/VesselItem.java | 50 ++++ .../primalpottery/legacy/WheelEntity.java | 42 ++- .../legacy/client/PaintingClient.java | 62 ++++ .../legacy/client/PaintingScreen.java | 103 +++++++ .../legacy/client/PlacementOutline.java | 57 ++++ .../legacy/client/PotContentsRenderer.java | 11 + .../legacy/client/PotteryModel.java | 24 +- .../legacy/client/PotteryQuads.java | 4 +- .../legacy/client/VesselModels.java | 174 +++++++++++ .../legacy/client/VesselScreen.java | 85 ++++++ .../legacy/client/WheelRenderer.java | 21 +- .../primalpottery/legacy/dining/Dining.java | 120 ++++++++ .../legacy/dining/DiningInput.java | 25 ++ .../legacy/dining/DiningRegistration.java | 34 +++ .../legacy/dining/DiningRenderer.java | 132 +++++++++ .../legacy/dining/DiningTable.java | 83 ++++++ .../legacy/dining/PlateMeal.java | 152 ++++++++++ .../loading/FurnaceResultTransformer.java | 20 ++ .../blockstates/painting_table.json | 7 + .../assets/primalpottery/lang/en_us.lang | 40 +++ .../assets/primalpottery/recipes/cutlery.json | 18 ++ .../primalpottery/recipes/painting_table.json | 27 ++ .../src/main/resources/mcmod.info | 2 +- .../dining/ServingPiecesTest.java | 39 +++ .../painting/PaintBrushTest.java | 60 ++++ .../textures/block/serving_pixel.png | Bin 0 -> 77 bytes 144 files changed, 8251 insertions(+), 158 deletions(-) create mode 100644 .github/forge-display-check/1.12.2/potterycheck/DiningClientCheck.java create mode 100644 .github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java create mode 100644 .github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java create mode 100644 .github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java create mode 100644 .github/forge-display-check/1.12.2/potterycheck/VesselGameplay.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/DiningClientCheck.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/PaintingClientCheck.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/PlacementGameplay.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/VesselClientCheck.java create mode 100644 .github/forge-display-check/1.20.1/potterycheck/VesselGameplay.java create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedPlate.java rename {src => core/src}/main/java/net/modcrafters/minecraft/primalpottery/pottery/PlatterSegments.java (100%) create mode 100644 core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayout.java create mode 100644 core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayoutTest.java create mode 100644 forge/shared/dining.gradle create mode 100644 forge/shared/painting.gradle create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/CutleryModels.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Diner.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningMesh.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningScene.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningUse.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Point.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingInventory.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingPieces.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/TableSetting.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/IconPixels.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrush.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintPanel.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PigmentTanks.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/Pigments.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselMesh.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselPreviewFrame.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselRules.java create mode 100644 forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelGuides.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/DyePotRecipe.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/MiniatureTree.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintChannel.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintSupply.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingMenu.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingRegistration.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableBlock.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableEntity.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PlanterPlants.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotBounds.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryBlockItem.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryNames.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryTab.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/RawPotteryItem.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TreePlot.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselChannel.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselData.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselInteractions.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselItem.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingClient.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingScreen.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlacementOutline.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotContentsRenderer.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/Dining.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningInput.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRegistration.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRenderer.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningTable.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/PlateMeal.java create mode 100644 forge/src/main/resources/assets/primalpottery/blockstates/painting_table.json create mode 100644 forge/src/main/resources/assets/primalpottery/models/block/dyed_clay.json create mode 100644 forge/src/main/resources/data/primalpottery/loot_tables/blocks/painting_table.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/cutlery.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/paint_pottery.json create mode 100644 forge/src/main/resources/data/primalpottery/recipes/painting_table.json create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/DyePotRecipe.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintChannel.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintSupply.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingMenu.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingRegistration.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableBlock.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableEntity.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PlanterPlants.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotBounds.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryNames.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryTab.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TreePlot.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselChannel.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselData.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselItem.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingClient.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingScreen.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotContentsRenderer.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/Dining.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningInput.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRegistration.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRenderer.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningTable.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/PlateMeal.java create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/painting_table.json create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/cutlery.json create mode 100644 legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/painting_table.json create mode 100644 legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/dining/ServingPiecesTest.java create mode 100644 legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrushTest.java create mode 100644 src/main/resources/assets/primalpottery/textures/block/serving_pixel.png diff --git a/.github/forge-display-check/1.12.2/potterycheck/DiningClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DiningClientCheck.java new file mode 100644 index 0000000..83b0bf6 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/DiningClientCheck.java @@ -0,0 +1,196 @@ +package potterycheck; + +import java.util.Collections; +import java.util.concurrent.Future; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.*; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.*; +import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.legacy.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.dining.*; +import net.modcrafters.minecraft.primalpottery.dining.Diner; +import net.modcrafters.minecraft.primalpottery.dining.TableSetting; +import net.modcrafters.minecraft.primalpottery.pottery.*; + +/** One integrated-server player cooks no special test items: vanilla stew supplies the real bowl remainder. */ +final class DiningClientCheck { + private static final BlockPos PLATE = new BlockPos(55, 80, 4), PLATTER = PLATE.east(); + private static final int EDGE = 4; + private static Future pending; + private static boolean photographed; + private enum Step { STEW, AIM_AT_BREAD, RELEASE, CHECK_RELEASE, DONE } + private static volatile Step step = Step.STEW; + private static int ticks; + private static DiningClientCheck scenario; + private final WorldServer level; + private final EntityPlayerMP player; + private final GameType previousMode; + private final int previousFood; + private long started; + + private DiningClientCheck(WorldServer level, EntityPlayerMP player) { + this.level = level; + this.player = player; + previousMode = player.interactionManager.getGameType(); + previousFood = player.getFoodStats().getFoodLevel(); + } + + static boolean tick(Minecraft client) throws Exception { + if (pending != null && !pending.isDone()) return false; + if (pending != null) pending.get(); + if (step == Step.DONE) { + check(photographed, "client never received a live dining animation"); + return true; + } + if (++ticks > 1200) throw new AssertionError("Dining timed out at " + step); + PaintedPotEntity plate = client.world.getTileEntity(PLATE) instanceof PaintedPotEntity + ? (PaintedPotEntity) client.world.getTileEntity(PLATE) : null; + if (step == Step.AIM_AT_BREAD) { + if (plate == null || plate.dining.serving(EDGE).getItem() != Items.BREAD || + client.player.getHeldItemMainhand().getItem() != DiningRegistration.cutlery()) return false; + net.minecraft.client.settings.KeyBinding.setKeyBindState(client.gameSettings.keyBindUseItem.getKeyCode(), true); + client.playerController.processRightClickBlock(client.player, client.world, PLATE, EnumFacing.UP, + new net.minecraft.util.math.Vec3d(55.5, 80.04, 4 + 1./6), EnumHand.MAIN_HAND); + step = Step.RELEASE; + return false; + } + if (step == Step.RELEASE) { + if (plate == null || plate.dining.diner(EDGE) == null) return false; + Diner bite = plate.dining.diner(EDGE); + if (client.world.getTotalWorldTime() - bite.start < 32) return false; + DisplayCheck.screenshot(client, "dining-cut.png"); + net.minecraft.client.settings.KeyBinding.setKeyBindState(client.gameSettings.keyBindUseItem.getKeyCode(), false); + step = Step.CHECK_RELEASE; + return false; + } + if (!photographed && plate != null) { + Diner eating = plate.dining.diner(EDGE); + if (eating != null && client.world.getTotalWorldTime() - eating.start >= 30) { + DisplayCheck.screenshot(client, "dining.png"); + photographed = true; + } + } + net.minecraft.server.MinecraftServer server = client.getIntegratedServer(); + pending = server.addScheduledTask(() -> { + if (scenario == null) { + scenario = new DiningClientCheck(server.getWorld(0), server.getPlayerList().getPlayers().get(0)); + scenario.start(); + } else scenario.advance(); + }); + return false; + } + + private void start() { + player.setGameType(GameType.SURVIVAL); + player.getFoodStats().setFoodLevel(6); + for (int x = -1; x <= 2; x++) for (int z = -3; z <= 1; z++) + level.setBlockState(PLATE.add(x, -1, z), Blocks.STONE.getDefaultState()); + // Aim the real player at the small plate, so server reach and ray checks run on every bite. + player.connection.setPlayerLocation(55.5, 80, 2.5, 0, 43.5F); + player.setHeldItem(EnumHand.OFF_HAND, ItemStack.EMPTY); + Pottery small = new Pottery(Pottery.Size.SMALL, Collections.singletonList(new PotteryDisc(2, 8))); + Pottery platter = new Pottery(Pottery.Size.LARGE, Collections.singletonList(new PotteryDisc(3, 16))); + place(PLATE, small); + place(PLATTER, platter); + PaintedPotEntity tray = pots(PLATTER); + check(tray.layout().at(0).isPlatter() && pots(PLATE).layout().at(EDGE).isPlate(), "plate placement slots"); + + Item[] foods = {Items.APPLE, Items.BREAD, Items.CARROT, Items.POTATO, Items.BOWL, Items.STICK}; + for (int i = 0; i < foods.length; i++) { + player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(foods[i], 2)); + click(PLATTER, TableSetting.servingX(platter, i), .094, TableSetting.servingZ(platter, i)); + check(player.getHeldItemMainhand().getCount() == 1 && tray.dining.serving(i).getItem() == foods[i], "platter sector " + i); + } + click(PLATTER, TableSetting.servingX(platter, 0), .094, TableSetting.servingZ(platter, 0)); + check(player.getHeldItemMainhand().getCount() == 1 && tray.dining.serving(0).getItem() == Items.APPLE, "occupied sector"); + DiningTable restored = new DiningTable(); + restored.load(tray.writeToNBT(new NBTTagCompound())); + check(restored.hasVisuals() && restored.drops().size() == 6, "six saved servings"); + DiningTable empty = new DiningTable(); + check(!empty.hasVisuals(), "unused tile scheduled a renderer"); + empty.load(tray.getUpdateTag()); + empty.remove(0, platter); + check(!empty.hasVisuals(), "empty platter left renderer scheduled"); + for (int i = 0; i < foods.length; i++) check(restored.serving(i).getItem() == foods[i], "saved sector " + i); + player.setSneaking(true); + click(PLATTER, TableSetting.servingX(platter, 3), .094, TableSetting.servingZ(platter, 3)); + player.setSneaking(false); + check(tray.dining.serving(3).isEmpty() && tray.dining.drops().size() == 5, "isolated prop removal"); + + player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(DiningRegistration.cutlery())); + click(PLATE, TableSetting.utensilX(EDGE, true), .015, TableSetting.utensilZ(EDGE, true)); + check(player.getHeldItemMainhand().isEmpty() && !pots(PLATE).dining.utensil(EDGE).isEmpty(), "placed cutlery"); + player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(Items.MUSHROOM_STEW)); + click(PLATE, .5, .04, 1./6); + click(PLATE, .5, .04, 1./6); + check(pots(PLATE).dining.diner(EDGE).fromTable, "meal did not use table setting"); + // A second player must not be able to take the serving during any of the four bites. + net.minecraftforge.common.util.FakePlayer other = net.minecraftforge.common.util.FakePlayerFactory.getMinecraft(level); + other.setSneaking(true); + check(Dining.use(pots(PLATE), other, EnumHand.MAIN_HAND, .5, .04, 1./6), "second player action passed through"); + other.setSneaking(false); + check(pots(PLATE).dining.serving(EDGE).getItem() == Items.MUSHROOM_STEW + && pots(PLATE).dining.diner(EDGE).player == player.getEntityId(), "second player took the diner's serving"); + PlateMeal.release(player); + check(pots(PLATE).dining.diner(EDGE) == null && pots(PLATE).dining.serving(EDGE).getItem() == Items.MUSHROOM_STEW, + "canceling ate the meal"); + click(PLATE, .5, .04, 1./6); + DiningTable spectator = new DiningTable(); + spectator.load(pots(PLATE).getUpdateTag()); + check(spectator.diner(EDGE).player == player.getEntityId(), "late spectator meal sync"); + restored.load(pots(PLATE).writeToNBT(new NBTTagCompound())); + check(restored.diner(EDGE) == null && !restored.utensil(EDGE).isEmpty(), "meal persisted as active after restart"); + started = level.getTotalWorldTime(); + } + + private void advance() { + PaintedPotEntity plate = pots(PLATE); + if (step == Step.CHECK_RELEASE) { + if (plate.dining.diner(EDGE) != null) return; + check(plate.dining.serving(EDGE).getItem() == Items.BREAD, "network release consumed the bread"); + player.setGameType(previousMode); + player.getFoodStats().setFoodLevel(previousFood); + step = Step.DONE; + System.out.println("POTTERY VERIFIED dining: six platter sectors, props, cutlery, spectator sync, four bites, hunger, bowl and network release"); + return; + } + if (plate.dining.diner(EDGE) != null) { + check(level.getTotalWorldTime() - started < 150, "meal never finished"); + return; + } + check(plate.dining.serving(EDGE).getItem() == Items.BOWL && player.getFoodStats().getFoodLevel() >= 12, + "stew did not nourish the player and leave its bowl"); + check(plate.dining.utensil(EDGE).getItem() == DiningRegistration.cutlery(), "cutlery consumed"); + PlateMeal.release(player); + click(PLATE, .5, .04, 1./6); + player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(Items.BREAD)); + click(PLATE, .5, .04, 1./6); + player.setHeldItem(EnumHand.MAIN_HAND, new ItemStack(DiningRegistration.cutlery())); + player.getFoodStats().setFoodLevel(6); + player.inventoryContainer.detectAndSendChanges(); + step = Step.AIM_AT_BREAD; + } + + private PaintedPotEntity pots(BlockPos pos) { return (PaintedPotEntity) level.getTileEntity(pos); } + + private void place(BlockPos pos, Pottery shape) { + level.setBlockToAir(pos); + ItemStack stack = new ItemStack(PrimalPotteryForge.POT); + ForgeStackProfiles.INSTANCE.write(stack, shape); + player.setHeldItem(EnumHand.MAIN_HAND, stack); + stack.onItemUse(player, level, pos.down(), EnumHand.MAIN_HAND, EnumFacing.UP, .5F, 1, .16F); + } + private void click(BlockPos pos, double x, double y, double z) { + net.minecraft.block.state.IBlockState state = level.getBlockState(pos); + check(state.getBlock().onBlockActivated(level, pos, state, player, EnumHand.MAIN_HAND, EnumFacing.UP, + (float) x, (float) y, (float) z), "dining use at " + pos); + } + private static void check(boolean ok, String detail) { if (!ok) throw new AssertionError(detail); } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java index 3a0f7ba..635d523 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -33,6 +33,7 @@ public final class DisplayCheck { private static final Pottery CHECKER = checkerboardJug(); private static final ForgeTemplateCheck templates = new ForgeTemplateCheck(); + private static final PaintingClientCheck painting = new PaintingClientCheck(); private static final WheelClientCheck wheel = new WheelClientCheck(); private static boolean opening; private static boolean placed; @@ -60,7 +61,7 @@ public final class DisplayCheck { return; } if (mc.player == null || mc.world == null || ++ticks < 40) return; - if (!templates.tick() || !wheel.tick(mc)) return; + if (!templates.tick() || !wheel.tick(mc) || !VesselClientCheck.tick(mc) || !painting.tick(mc) || !DiningClientCheck.tick(mc)) return; if (!placed) { placed = true; mc.gameSettings.hideGUI = true; diff --git a/.github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java new file mode 100644 index 0000000..6724c7f --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java @@ -0,0 +1,155 @@ +package potterycheck; + +import java.util.concurrent.Future; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.*; +import net.minecraft.item.crafting.*; +import net.minecraft.util.*; +import net.minecraft.util.math.*; +import net.minecraft.world.WorldServer; +import net.modcrafters.minecraft.primalpottery.legacy.*; +import net.modcrafters.minecraft.primalpottery.legacy.client.PaintingClient; +import net.modcrafters.minecraft.primalpottery.legacy.client.PaintingScreen; +import net.modcrafters.minecraft.primalpottery.painting.*; +import net.modcrafters.minecraft.primalpottery.pottery.*; + +/** Uses native crafting, menu synchronization, brush packets and the offhand icon stamp in a real client. */ +final class PaintingClientCheck { + private static final BlockPos TABLE = new BlockPos(72,80,40); + private enum Step { SETUP, OPEN, STROKE, UNDO, REPAINT, SNAPSHOT, FIND_POT, STAMP, VERIFY, DONE } + private Step step = Step.SETUP; + private Future task; + private int ticks, ready; + private FacePaint stamped; + + public boolean tick(Minecraft client) throws Exception { + if (task != null && !task.isDone()) return false; + if (task != null) { task.get(); task = null; } + if (step == Step.DONE) return true; + if (++ticks > 1200) throw new AssertionError("Painting timed out at " + step); + net.minecraft.server.MinecraftServer server = client.getIntegratedServer(); + switch (step) { + case SETUP: + task = server.addScheduledTask(() -> prepare(server.getWorld(0),server.getPlayerList().getPlayers().get(0))); + break; + case OPEN: + if (!PaintingRegistration.dyed(client.player.getHeldItem(EnumHand.MAIN_HAND)) + || !(client.world.getTileEntity(TABLE) instanceof PaintingTableEntity)) return false; + checkModel(client, client.player.getHeldItem(EnumHand.MAIN_HAND), false); + useTable(client); + break; + case STROKE: + if (!(client.currentScreen instanceof PaintingScreen) || menu(client).profile() == null) return false; + click(client,13+14*14+3,130); + click(client,12,28); + break; + case UNDO: + if (menu(client).profile().paint().color(0) != 14 || menu(client).volume(14) != 99 || !menu(client).canUndo()) return false; + click(client,164,162); + break; + case REPAINT: + if (!(client.currentScreen instanceof PaintingScreen)) throw new AssertionError("Painting window closed while undoing brush"); + if (menu(client).profile().paint().color(0) != FacePaint.ERASE) return false; + click(client,12,28); + break; + case SNAPSHOT: + if (menu(client).profile().paint().color(0) != 14 || menu(client).volume(14) != 98 || ++ready < 4) return false; + checkModel(client, menu(client).potStack(), true); + DisplayCheck.screenshot(client, "painting.png"); + client.player.closeScreen(); + break; + case FIND_POT: + boolean returned = false; + for (int i = 0; i < 36; i++) { + ItemStack stack = client.player.inventory.getStackInSlot(i); + if (PaintingRegistration.isPot(stack) && PaintingRegistration.dyed(stack) + && PaintedPotEntity.fromStack(stack).paint().color(0) == 14) returned = true; + } + if (!returned) return false; + task = server.addScheduledTask(() -> equipStamp(server.getPlayerList().getPlayers().get(0))); + break; + case STAMP: + ItemStack icon = client.player.getHeldItem(EnumHand.OFF_HAND); + if (icon.getItem() != Items.FEATHER || !PaintingRegistration.isPot(client.player.getHeldItem(EnumHand.MAIN_HAND))) return false; + stamped = FacePaint.read(PaintingClient.pattern(client.player, icon)); + if (stamped.equals(FacePaint.EMPTY)) throw new AssertionError("Could not read the vanilla feather icon"); + useTable(client); + break; + case VERIFY: + Pottery result = ForgeStackProfiles.INSTANCE.read(client.player.getHeldItem(EnumHand.MAIN_HAND)); + if (result == null || !result.paint().equals(stamped)) return false; + if (!PaintingRegistration.dyed(client.player.getHeldItem(EnumHand.MAIN_HAND))) throw new AssertionError("Paint lost base dye"); + System.out.println("POTTERY VERIFIED painting: raw dye, furnace, screen stroke, undo, costs and feather stamp"); + break; + default: throw new AssertionError(step); + } + System.out.println("POTTERY painting " + step + " complete"); + step = Step.values()[step.ordinal()+1]; + return false; + } + + private static void checkModel(Minecraft client, ItemStack stack, boolean painted) { + int rgb = Pigments.clayTint("blue"); + int expectedColor = 0xff000000 | (rgb & 255) << 16 | rgb & 0xff00 | rgb >>> 16; + boolean dyed = false, ink = false; + net.minecraft.client.renderer.block.model.IBakedModel model = client.getRenderItem().getItemModelWithOverrides(stack, client.world, client.player); + for (net.minecraft.client.renderer.block.model.BakedQuad quad : model.getQuads(null, null, 42)) { + String texture = quad.getSprite().getIconName(); + if (texture.equals("primalpottery:block/dyed_clay") && quad.getVertexData()[3] == expectedColor) dyed = true; + if (texture.equals("primalpottery:block/paint_sheet") || texture.equals("primalpottery:block/pottery_inks")) ink = true; + } + if (!dyed || ink != painted) throw new AssertionError("Dyed vessel mesh has incorrect clay or paint at preview stage " + painted); + } + + private static PaintingMenu menu(Minecraft client) { return (PaintingMenu) client.player.openContainer; } + private static void click(Minecraft client,int x,int y) throws Exception { + PaintingScreen screen = (PaintingScreen) client.currentScreen; + x += (screen.width - PaintPanel.WIDTH)/2; + y += (screen.height - PaintPanel.HEIGHT)/2; + screen.mouseClicked(x,y,0); + screen.mouseReleased(x,y,0); + } + private static void useTable(Minecraft client) { + client.playerController.processRightClickBlock(client.player,client.world,TABLE,EnumFacing.NORTH, + new Vec3d(TABLE.getX()+.5,TABLE.getY()+.8,TABLE.getZ()), EnumHand.MAIN_HAND); + } + private static void prepare(WorldServer level, EntityPlayerMP player) { + level.setBlockState(TABLE.down(),Blocks.STONE.getDefaultState()); + level.setBlockState(TABLE.add(0,-1,-2),Blocks.STONE.getDefaultState()); + level.setBlockToAir(TABLE); + level.setBlockState(TABLE,PaintingRegistration.TABLE.getDefaultState()); + player.connection.setPlayerLocation(72.5,80,38.5,0,10); + ItemStack raw = new ItemStack(PrimalPotteryForge.RAW); + ForgeStackProfiles.INSTANCE.write(raw,Pottery.jug()); + InventoryCrafting grid = new InventoryCrafting(player.inventoryContainer,2,2); + grid.setInventorySlotContents(0,raw); + grid.setInventorySlotContents(1,new ItemStack(Items.DYE,1,4)); + ItemStack dyed = CraftingManager.findMatchingResult(grid,level); + ItemStack fired = FurnaceRecipes.instance().getSmeltingResult(dyed).copy(); + if (!PaintingRegistration.isPot(fired) || PaintingRegistration.tint(fired) != Pigments.clayTint("blue")) + throw new AssertionError("Crafting/firing did not preserve blue glaze"); + player.setHeldItem(EnumHand.MAIN_HAND,fired); + player.setHeldItem(EnumHand.OFF_HAND,ItemStack.EMPTY); + for (int i = 0; i < 16; i++) player.inventory.setInventorySlotContents(9+i, + new ItemStack(Items.DYE,3,15-i)); + player.inventoryContainer.detectAndSendChanges(); + } + + private static void equipStamp(EntityPlayerMP player) { + for (int i = 0; i < 36; i++) { + ItemStack stack = player.inventory.getStackInSlot(i); + if (!PaintingRegistration.isPot(stack) || !PaintingRegistration.dyed(stack)) continue; + if (PaintedPotEntity.fromStack(stack).paint().color(0) != 14) continue; + player.inventory.setInventorySlotContents(i,ItemStack.EMPTY); + player.setHeldItem(EnumHand.MAIN_HAND,stack); + player.setHeldItem(EnumHand.OFF_HAND,new ItemStack(Items.FEATHER)); + player.inventoryContainer.detectAndSendChanges(); + return; + } + throw new AssertionError("Closing the painting menu lost the decorated vessel"); + } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java b/.github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java new file mode 100644 index 0000000..685e704 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java @@ -0,0 +1,67 @@ +package potterycheck; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntityFurnace; +import net.minecraft.util.*; +import net.minecraft.util.math.*; +import net.minecraft.world.WorldServer; +import net.modcrafters.minecraft.primalpottery.legacy.*; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Exercises shared footprints through the block item and survival harvest, and tests hopper-style furnace input. */ +final class PlacementGameplay { + private static final BlockPos SITE = WheelGameplay.BASE.west(2); + private static final BlockPos OVEN = WheelGameplay.BASE.east(2); + private static final Pottery FIRST = Pottery.jug().withHeight(10); + private static final Pottery SECOND = Pottery.jug().withHeight(14); + + static void verify(WorldServer level, EntityPlayerMP player) { + level.setBlockToAir(SITE); + place(level, player, FIRST, .25F); + place(level, player, SECOND, .75F); + PaintedPotEntity pots = (PaintedPotEntity) level.getTileEntity(SITE); + check(pots != null && pots.layout().count() == 2, "Two distinct pottery items should share a block"); + RayTraceResult ray = new RayTraceResult(new Vec3d(SITE).addVector(.75, .5, .25), EnumFacing.UP, SITE); + ItemStack picked = level.getBlockState(SITE).getBlock().getPickBlock(level.getBlockState(SITE), ray, level, SITE, player); + net.minecraft.world.GameType previousMode = player.interactionManager.getGameType(); + player.setGameType(net.minecraft.world.GameType.SURVIVAL); + player.setPositionAndRotation(SITE.getX() + .75, SITE.getY() + 1, SITE.getZ() + .25, 0, 90); + player.interactionManager.tryHarvestBlock(SITE); + player.setGameType(previousMode); + check(ForgeStackProfiles.INSTANCE.read(picked).discs().equals(SECOND.discs()), "Picked neighbor"); + check(pots.layout().count() == 1 && pots.profile().discs().equals(FIRST.discs()), "Targeted harvest removed neighbor"); + check(!level.getEntitiesWithinAABB(net.minecraft.entity.item.EntityItem.class, new AxisAlignedBB(SITE).grow(1), + drop -> drop.getItem().getItem() == net.minecraft.item.Item.getItemFromBlock(PrimalPotteryForge.POT) + && PaintedPotEntity.fromStack(drop.getItem()).discs().equals(SECOND.discs())).isEmpty(), "Missing harvested pottery drop"); + TileEntityFurnace furnace = (TileEntityFurnace) level.getTileEntity(OVEN); + ItemStack output = shaped(false, FIRST); + furnace.setInventorySlotContents(2, output); + furnace.setInventorySlotContents(0, shaped(true, SECOND)); + furnace.setInventorySlotContents(1, new ItemStack(Items.COAL)); + tick(level, furnace); + check(furnace.getStackInSlot(2).getCount() == 1 && !furnace.getStackInSlot(0).isEmpty(), "Furnace merged different shapes"); + furnace.setInventorySlotContents(0, shaped(true, FIRST)); + tick(level, furnace); + check(furnace.getStackInSlot(2).getCount() == 2 && furnace.getStackInSlot(0).isEmpty(), "Matching pottery failed to stack"); + System.out.println("POTTERY VERIFIED selective survival harvest, pick and occupied furnace output"); + } + + private static void place(WorldServer level, EntityPlayerMP player, Pottery shape, float x) { + ItemStack item = shaped(false, shape); + player.setHeldItem(EnumHand.MAIN_HAND, item); + item.onItemUse(player, level, SITE.down(), EnumHand.MAIN_HAND, EnumFacing.UP, x, 1, .25F); + } + private static ItemStack shaped(boolean raw, Pottery shape) { + ItemStack stack = raw ? new ItemStack(PrimalPotteryForge.RAW) : new ItemStack(PrimalPotteryForge.POT); + ForgeStackProfiles.INSTANCE.write(stack, shape); + return stack; + } + private static void tick(WorldServer level, TileEntityFurnace furnace) { + for (int i = 0; i < 205; i++) furnace.update(); + } + private static void check(boolean passed, String message) { if (!passed) throw new AssertionError(message); } + private PlacementGameplay() {} +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java new file mode 100644 index 0000000..5f8ef29 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java @@ -0,0 +1,76 @@ +package potterycheck; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Future; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumHand; +import net.minecraft.server.MinecraftServer; +import net.modcrafters.minecraft.primalpottery.legacy.VesselData; +import net.modcrafters.minecraft.primalpottery.legacy.VesselInteractions; +import net.modcrafters.minecraft.primalpottery.legacy.client.VesselScreen; +import net.modcrafters.minecraft.primalpottery.legacy.client.VesselModels; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +final class VesselClientCheck { + private enum Step { EQUIP, OPEN, CLOSE_LID, REMOVE_LID, VERIFY, DONE } + private static Step step = Step.EQUIP; + private static int ticks; + private static Future setup; + private static final EnumHand HAND = EnumHand.MAIN_HAND; + + static boolean tick(Minecraft client) throws Exception { + if (step == Step.DONE) return true; + if (++ticks > 200) throw new AssertionError("Vessel client timed out at " + step); + if (setup != null && !setup.isDone()) return false; + if (setup != null) setup.get(); + MinecraftServer server = client.getIntegratedServer(); + ItemStack held = client.player.getHeldItem(HAND); + switch (step) { + case EQUIP: + List empty = Collections.emptyList(); + List water = VesselModels.append(empty, VesselGameplay.water, PotteryLayout.CENTER); + List tree = VesselModels.append(empty, VesselGameplay.planter, PotteryLayout.CENTER); + if (water.isEmpty() || tree.size() <= water.size() || tree != VesselModels.append(empty, VesselGameplay.planter, PotteryLayout.CENTER)) { + throw new AssertionError("Missing or uncached planter/fluid mesh"); + } + setup = server.addScheduledTask(() -> { + EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); + player.setHeldItem(HAND, VesselGameplay.water.copy()); + player.inventoryContainer.detectAndSendChanges(); + }); + break; + case OPEN: + if (VesselData.amount(held) <= 0) return false; + VesselInteractions.useHeld(client.player, HAND); + break; + case CLOSE_LID: + if (!(client.currentScreen instanceof VesselScreen)) return false; + click((VesselScreen) client.currentScreen); + break; + case REMOVE_LID: + if (!VesselData.lid(held)) return false; + DisplayCheck.screenshot(client, "vessel-lid.png"); + if (VesselModels.append(Collections.emptyList(), held, PotteryLayout.CENTER).isEmpty()) throw new AssertionError("Missing lid mesh"); + click((VesselScreen) client.currentScreen); + break; + case VERIFY: + if (VesselData.lid(held)) return false; + client.displayGuiScreen(null); + System.out.println("POTTERY VERIFIED vessel client: fluid/planter geometry, lid preview, equip and remove through network"); + break; + default: throw new AssertionError(step); + } + step = Step.values()[step.ordinal() + 1]; + return false; + } + + private static void click(VesselScreen screen) throws Exception { + int x = screen.width / 2; + int y = (screen.height - 172) / 2 + 152; + screen.mouseClicked(x, y, 0); + } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/VesselGameplay.java b/.github/forge-display-check/1.12.2/potterycheck/VesselGameplay.java new file mode 100644 index 0000000..94fbad4 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/VesselGameplay.java @@ -0,0 +1,117 @@ +package potterycheck; + +import java.util.Arrays; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.WorldServer; +import net.modcrafters.minecraft.primalpottery.legacy.*; +import net.modcrafters.minecraft.primalpottery.pottery.*; + +/** Uses the same held, placed and lid packet actions as the player in the disposable test world. */ +public final class VesselGameplay { + private static final EnumHand HAND = EnumHand.MAIN_HAND; + private static final BlockPos PLACED = new BlockPos(55, 80, 4); + private static final BlockPos WATER = new BlockPos(55, 81, 5); + private static final int SLOT = PotteryLayout.CENTER; + + static volatile ItemStack water, planter; + + public static void verify(WorldServer level, EntityPlayerMP player) { + ItemStack original = player.getHeldItem(HAND); + ItemStack offhand = player.getHeldItem(EnumHand.OFF_HAND); + player.setHeldItem(EnumHand.OFF_HAND, ItemStack.EMPTY); + double x = player.posX, y = player.posY, z = player.posZ; + float yaw = player.rotationYaw, pitch = player.rotationPitch; + try { + player.connection.setPlayerLocation(55.5, 80, 2.5, 0, 0); + verifyVessels(level, player); + } finally { + level.setBlockToAir(WATER); + level.setBlockToAir(PLACED); + player.connection.setPlayerLocation(x, y, z, yaw, pitch); + player.setHeldItem(HAND, original); + player.setHeldItem(EnumHand.OFF_HAND, offhand); + } + } + + private static void verifyVessels(WorldServer level, EntityPlayerMP player) { + Block block = PrimalPotteryForge.POT; + Pottery shape = new Pottery(Pottery.Size.LARGE, Arrays.asList(new PotteryDisc(1, 16, 14), new PotteryDisc(30, 16, 14), new PotteryDisc(1, 16, 0))); + int capacity = shape.classify().volume(); + require(capacity >= 1000 && shape.cover() != null, "Large planter fixture"); + ItemStack empty = new ItemStack(block); + ForgeStackProfiles.INSTANCE.write(empty, shape); + + level.setBlockState(WATER, Blocks.FLOWING_WATER.getDefaultState().withProperty(net.minecraft.block.BlockLiquid.LEVEL, 2)); + player.setHeldItem(HAND, empty.copy()); + VesselInteractions.setLid(player, HAND, null, -1, true); + require(VesselData.lid(player.getHeldItem(HAND)), "Held lid did not close"); + VesselInteractions.useHeld(player, HAND); + require(VesselData.amount(player.getHeldItem(HAND)) == 0, "Closed lid admitted water"); + VesselInteractions.setLid(player, HAND, null, -1, false); + VesselInteractions.useHeld(player, HAND); + ItemStack filled = player.getHeldItem(HAND); + require(VesselData.amount(filled) == capacity && VesselData.fluidId(filled).equals("minecraft:water"), "Flowing water fill"); + require(level.getBlockState(WATER).getBlock() == Blocks.FLOWING_WATER, "Filling consumed the water"); + water = filled.copy(); + require(filled.getMaxStackSize() == 1, "Filled vessel stack limit"); + + level.setBlockState(PLACED, block.getDefaultState()); + block.onBlockPlacedBy(level, PLACED, block.getDefaultState(), player, empty); + PaintedPotEntity tile = (PaintedPotEntity) level.getTileEntity(PLACED); + ItemStack pot = tile.stack(SLOT); + VesselInteractions.setLid(player, HAND, PLACED, SLOT, true); + require(VesselData.lid(pot), "Placed lid did not close"); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.amount(filled) == capacity && VesselData.amount(pot) == 0, "Poured through a closed lid"); + VesselInteractions.setLid(player, HAND, PLACED, SLOT, false); + VesselData.storeFluid(pot, "minecraft:lava", 42); + require(VesselInteractions.light(tile) > 0, "Lava did not emit light"); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.amount(pot) == 42 && VesselData.amount(filled) == capacity, "Mixed water and lava"); + VesselData.storeFluid(pot, "minecraft:water", 42); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.amount(pot) == capacity && VesselData.amount(filled) == 42, "Partial pour lost liquid"); + + ItemStack dirt = new ItemStack(Blocks.DIRT); + player.setHeldItem(HAND, dirt); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(!VesselData.planted(pot), "Put soil in a full pot"); + VesselData.storeFluid(pot, "", 0); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.soil(pot) == Blocks.DIRT, "Could not install soil"); + VesselInteractions.setLid(player, HAND, PLACED, SLOT, true); + require(!VesselData.lid(pot), "Closed a planted pot"); + ItemStack saplings = new ItemStack(Blocks.SAPLING, 2); + player.setHeldItem(HAND, saplings); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.plant(pot) == Blocks.SAPLING && !pot.getTagCompound().getTagList("tree", 10).hasNoTags(), "Miniature oak failed to generate"); + NBTTagList before = pot.getTagCompound().getTagList("tree", 10).copy(); + int remaining = saplings.getCount(); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(saplings.getCount() == remaining && !pot.getTagCompound().getTagList("tree", 10).equals(before), "Miniature oak reroll"); + ItemStack saved = new ItemStack(pot.writeToNBT(new net.minecraft.nbt.NBTTagCompound()).copy()); + require(saved.getTagCompound().getTagList("tree", 10).equals(pot.getTagCompound().getTagList("tree", 10)), "Planter tree lost in saved item"); + planter = saved.copy(); + List drops = VesselInteractions.dropPlanting(saved); + require(drops.size() == 2 && drops.get(0).getItem() == saplings.getItem() && drops.get(1).getItem() == new ItemStack(Blocks.DIRT).getItem() + && !VesselData.planted(saved), "Break did not return plant and soil separately"); + player.setHeldItem(HAND, ItemStack.EMPTY); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.plant(pot) == Blocks.AIR && VesselData.soil(pot) == Blocks.DIRT, "Empty hand did not remove the plant first"); + player.setHeldItem(HAND, ItemStack.EMPTY); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(!VesselData.planted(pot), "Empty hand did not remove the soil"); + System.out.println("POTTERY VERIFIED vessels: held/placed lids, flowing fill, transfer, light, soil, miniature tree, reroll and drops"); + } + + private static void require(boolean passed, String message) { + if (!passed) throw new AssertionError(message); + } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java index b43b0f8..fe8aef9 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/WheelClientCheck.java @@ -43,6 +43,8 @@ boolean tick(Minecraft client) throws Exception { case FIRE: if (gameplay.fired()) { gameplay.verify(); + PlacementGameplay.verify(server.getWorld(0), server.getPlayerList().getPlayers().get(0)); + VesselGameplay.verify(server.getWorld(0), server.getPlayerList().getPlayers().get(0)); phase = Phase.DONE; } break; diff --git a/.github/forge-display-check/1.20.1/potterycheck/DiningClientCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DiningClientCheck.java new file mode 100644 index 0000000..132832a --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/DiningClientCheck.java @@ -0,0 +1,199 @@ +package potterycheck; + +import java.util.Collections; +import java.util.concurrent.Future; +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.*; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.*; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.*; +import net.minecraftforge.registries.ForgeRegistries; +import net.modcrafters.minecraft.primalpottery.forge.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.forge.dining.*; +import net.modcrafters.minecraft.primalpottery.dining.Diner; +import net.modcrafters.minecraft.primalpottery.dining.TableSetting; +import net.modcrafters.minecraft.primalpottery.pottery.*; + +/** One integrated-server player cooks no special test items: vanilla stew supplies the real bowl remainder. */ +final class DiningClientCheck { + private static final BlockPos PLATE = new BlockPos(55, 80, 4), PLATTER = PLATE.east(); + private static final int EDGE = 4; + private static Future pending; + private static boolean photographed; + private enum Step { STEW, AIM_AT_BREAD, RELEASE, CHECK_RELEASE, DONE } + private static volatile Step step = Step.STEW; + private static int ticks; + private static DiningClientCheck scenario; + private final ServerLevel level; + private final ServerPlayer player; + private final GameType previousMode; + private final int previousFood; + private long started; + + private DiningClientCheck(ServerLevel level, ServerPlayer player) { + this.level = level; + this.player = player; + previousMode = player.gameMode.getGameModeForPlayer(); + previousFood = player.getFoodData().getFoodLevel(); + } + + static boolean tick(Minecraft client) throws Exception { + if (pending != null && !pending.isDone()) return false; + if (pending != null) pending.get(); + if (step == Step.DONE) { + check(photographed, "client never received a live dining animation"); + return true; + } + if (++ticks > 1200) throw new AssertionError("Dining timed out at " + step); + PaintedPotEntity plate = client.level.getBlockEntity(PLATE) instanceof PaintedPotEntity + ? (PaintedPotEntity) client.level.getBlockEntity(PLATE) : null; + if (step == Step.AIM_AT_BREAD) { + if (plate == null || plate.dining.serving(EDGE).getItem() != Items.BREAD || + client.player.getMainHandItem().getItem() != DiningRegistration.cutlery()) return false; + client.options.keyUse.setDown(true); + var hit = new BlockHitResult(Vec3.atLowerCornerOf(PLATE).add(.5, .04, 1./6), Direction.UP, PLATE, false); + client.gameMode.useItemOn(client.player, InteractionHand.MAIN_HAND, hit); + step = Step.RELEASE; + return false; + } + if (step == Step.RELEASE) { + if (plate == null || plate.dining.diner(EDGE) == null) return false; + Diner bite = plate.dining.diner(EDGE); + if (client.level.getGameTime() - bite.start < 32) return false; + DisplayCheck.screenshot(client, "dining-cut.png"); + client.options.keyUse.setDown(false); + step = Step.CHECK_RELEASE; + return false; + } + if (!photographed && plate != null) { + Diner eating = plate.dining.diner(EDGE); + if (eating != null && client.level.getGameTime() - eating.start >= 30) { + DisplayCheck.screenshot(client, "dining.png"); + photographed = true; + } + } + var server = client.getSingleplayerServer(); + pending = server.submit(() -> { + if (scenario == null) { + scenario = new DiningClientCheck(server.overworld(), server.getPlayerList().getPlayers().get(0)); + scenario.start(); + } else scenario.advance(); + }); + return false; + } + + private void start() { + player.setGameMode(GameType.SURVIVAL); + player.getFoodData().setFoodLevel(6); + for (int x = -1; x <= 2; x++) for (int z = -3; z <= 1; z++) + level.setBlockAndUpdate(PLATE.offset(x, -1, z), Blocks.STONE.defaultBlockState()); + // Aim the real player at the small plate, so server reach and ray checks run on every bite. + player.connection.teleport(55.5, 80, 2.5, 0, 43.5F); + player.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); + Pottery small = new Pottery(Pottery.Size.SMALL, Collections.singletonList(new PotteryDisc(2, 8))); + Pottery platter = new Pottery(Pottery.Size.LARGE, Collections.singletonList(new PotteryDisc(3, 16))); + place(PLATE, small); + place(PLATTER, platter); + PaintedPotEntity tray = pots(PLATTER); + check(tray.layout().at(0).isPlatter() && pots(PLATE).layout().at(EDGE).isPlate(), "plate placement slots"); + + Item[] foods = {Items.APPLE, Items.BREAD, Items.CARROT, Items.POTATO, Items.BOWL, Items.STICK}; + for (int i = 0; i < foods.length; i++) { + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(foods[i], 2)); + click(PLATTER, TableSetting.servingX(platter, i), .094, TableSetting.servingZ(platter, i)); + check(player.getMainHandItem().getCount() == 1 && tray.dining.serving(i).getItem() == foods[i], "platter sector " + i); + } + click(PLATTER, TableSetting.servingX(platter, 0), .094, TableSetting.servingZ(platter, 0)); + check(player.getMainHandItem().getCount() == 1 && tray.dining.serving(0).getItem() == Items.APPLE, "occupied sector"); + DiningTable restored = new DiningTable(); + restored.load(tray.saveWithoutMetadata()); + check(restored.hasVisuals() && restored.drops().size() == 6, "six saved servings"); + DiningTable empty = new DiningTable(); + check(!empty.hasVisuals(), "unused tile scheduled a renderer"); + empty.load(tray.getUpdateTag()); + empty.remove(0, platter); + check(!empty.hasVisuals(), "empty platter left renderer scheduled"); + for (int i = 0; i < foods.length; i++) check(restored.serving(i).getItem() == foods[i], "saved sector " + i); + player.setShiftKeyDown(true); + click(PLATTER, TableSetting.servingX(platter, 3), .094, TableSetting.servingZ(platter, 3)); + player.setShiftKeyDown(false); + check(tray.dining.serving(3).isEmpty() && tray.dining.drops().size() == 5, "isolated prop removal"); + + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(DiningRegistration.cutlery())); + click(PLATE, TableSetting.utensilX(EDGE, true), .015, TableSetting.utensilZ(EDGE, true)); + check(player.getMainHandItem().isEmpty() && !pots(PLATE).dining.utensil(EDGE).isEmpty(), "placed cutlery"); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.MUSHROOM_STEW)); + click(PLATE, .5, .04, 1./6); + click(PLATE, .5, .04, 1./6); + check(pots(PLATE).dining.diner(EDGE).fromTable, "meal did not use table setting"); + // A second player must not be able to take the serving during any of the four bites. + net.minecraftforge.common.util.FakePlayer other = net.minecraftforge.common.util.FakePlayerFactory.getMinecraft(level); + other.setShiftKeyDown(true); + check(Dining.use(pots(PLATE), other, InteractionHand.MAIN_HAND, .5, .04, 1./6), "second player action passed through"); + other.setShiftKeyDown(false); + check(pots(PLATE).dining.serving(EDGE).getItem() == Items.MUSHROOM_STEW + && pots(PLATE).dining.diner(EDGE).player == player.getId(), "second player took the diner's serving"); + PlateMeal.release(player); + check(pots(PLATE).dining.diner(EDGE) == null && pots(PLATE).dining.serving(EDGE).getItem() == Items.MUSHROOM_STEW, + "canceling ate the meal"); + click(PLATE, .5, .04, 1./6); + DiningTable spectator = new DiningTable(); + spectator.load(pots(PLATE).getUpdateTag()); + check(spectator.diner(EDGE).player == player.getId(), "late spectator meal sync"); + restored.load(pots(PLATE).saveWithoutMetadata()); + check(restored.diner(EDGE) == null && !restored.utensil(EDGE).isEmpty(), "meal persisted as active after restart"); + started = level.getGameTime(); + } + + private void advance() { + PaintedPotEntity plate = pots(PLATE); + if (step == Step.CHECK_RELEASE) { + if (plate.dining.diner(EDGE) != null) return; + check(plate.dining.serving(EDGE).getItem() == Items.BREAD, "network release consumed the bread"); + player.setGameMode(previousMode); + player.getFoodData().setFoodLevel(previousFood); + step = Step.DONE; + System.out.println("POTTERY VERIFIED dining: six platter sectors, props, cutlery, spectator sync, four bites, hunger, bowl and network release"); + return; + } + if (plate.dining.diner(EDGE) != null) { + check(level.getGameTime() - started < 150, "meal never finished"); + return; + } + check(plate.dining.serving(EDGE).getItem() == Items.BOWL && player.getFoodData().getFoodLevel() >= 12, + "stew did not nourish the player and leave its bowl"); + check(plate.dining.utensil(EDGE).getItem() == DiningRegistration.cutlery(), "cutlery consumed"); + PlateMeal.release(player); + click(PLATE, .5, .04, 1./6); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.BREAD)); + click(PLATE, .5, .04, 1./6); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(DiningRegistration.cutlery())); + player.getFoodData().setFoodLevel(6); + player.inventoryMenu.broadcastChanges(); + step = Step.AIM_AT_BREAD; + } + + private PaintedPotEntity pots(BlockPos pos) { return (PaintedPotEntity) level.getBlockEntity(pos); } + + private void place(BlockPos pos, Pottery shape) { + level.removeBlock(pos, false); + ItemStack stack = new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation("primalpottery", "pottery"))); + ForgeStackProfiles.INSTANCE.write(stack, shape); + player.setItemInHand(InteractionHand.MAIN_HAND, stack); + var hit = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(.5, 0, .16), Direction.UP, pos.below(), false); + stack.useOn(new UseOnContext(player, InteractionHand.MAIN_HAND, hit)); + } + private void click(BlockPos pos, double x, double y, double z) { + var hit = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(x, y, z), Direction.UP, pos, false); + check(level.getBlockState(pos).use(level, player, InteractionHand.MAIN_HAND, hit).consumesAction(), "dining use at " + pos); + } + private static void check(boolean ok, String detail) { if (!ok) throw new AssertionError(detail); } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index f0ade77..740401e 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -36,6 +36,7 @@ public final class DisplayCheck { private static final Pottery CHECKER = checkerboardJug(); private static final ForgeTemplateCheck templates = new ForgeTemplateCheck(); + private static final PaintingClientCheck painting = new PaintingClientCheck(); private static final WheelClientCheck wheel = new WheelClientCheck(); private static boolean opening; private static boolean placed; @@ -62,7 +63,7 @@ public final class DisplayCheck { return; } if (mc.player == null || mc.level == null || ++ticks < 40) return; - if (!templates.tick() || !wheel.tick(mc)) return; + if (!templates.tick() || !wheel.tick(mc) || !VesselClientCheck.tick(mc) || !painting.tick(mc) || !DiningClientCheck.tick(mc)) return; if (!placed) { placed = true; mc.options.hideGui = true; diff --git a/.github/forge-display-check/1.20.1/potterycheck/PaintingClientCheck.java b/.github/forge-display-check/1.20.1/potterycheck/PaintingClientCheck.java new file mode 100644 index 0000000..6b32785 --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/PaintingClientCheck.java @@ -0,0 +1,155 @@ +package potterycheck; + +import java.util.concurrent.Future; +import net.minecraft.client.Minecraft; +import net.minecraft.core.*; +import net.minecraft.server.level.*; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.inventory.TransientCraftingContainer; +import net.minecraft.world.item.*; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.*; +import net.modcrafters.minecraft.primalpottery.forge.*; +import net.modcrafters.minecraft.primalpottery.forge.client.PaintingClient; +import net.modcrafters.minecraft.primalpottery.forge.client.PaintingScreen; +import net.modcrafters.minecraft.primalpottery.painting.*; +import net.modcrafters.minecraft.primalpottery.pottery.*; + +/** Uses native crafting, menu synchronization, brush packets and the offhand icon stamp in a real client. */ +final class PaintingClientCheck { + private static final BlockPos TABLE = new BlockPos(72,80,40); + private enum Step { SETUP, OPEN, STROKE, UNDO, REPAINT, SNAPSHOT, FIND_POT, STAMP, VERIFY, DONE } + private Step step = Step.SETUP; + private Future task; + private int ticks, ready; + private FacePaint stamped; + + public boolean tick(Minecraft client) throws Exception { + if (task != null && !task.isDone()) return false; + if (task != null) { task.get(); task = null; } + if (step == Step.DONE) return true; + if (++ticks > 1200) throw new AssertionError("Painting timed out at " + step); + net.minecraft.client.server.IntegratedServer server = client.getSingleplayerServer(); + switch (step) { + case SETUP: + task = server.submit(() -> prepare(server.overworld(),server.getPlayerList().getPlayers().get(0))); + break; + case OPEN: + if (!PaintingRegistration.dyed(client.player.getItemInHand(InteractionHand.MAIN_HAND)) + || !(client.level.getBlockEntity(TABLE) instanceof PaintingTableEntity)) return false; + checkModel(client, client.player.getMainHandItem(), false); + useTable(client); + break; + case STROKE: + if (!(client.screen instanceof PaintingScreen) || menu(client).profile() == null) return false; + click(client,13+14*14+3,130); + click(client,12,28); + break; + case UNDO: + if (menu(client).profile().paint().color(0) != 14 || menu(client).volume(14) != 99 || !menu(client).canUndo()) return false; + click(client,164,162); + break; + case REPAINT: + if (!(client.screen instanceof PaintingScreen)) throw new AssertionError("Painting window closed while undoing brush"); + if (menu(client).profile().paint().color(0) != FacePaint.ERASE) return false; + click(client,12,28); + break; + case SNAPSHOT: + if (menu(client).profile().paint().color(0) != 14 || menu(client).volume(14) != 98 || ++ready < 4) return false; + checkModel(client, menu(client).potStack(), true); + DisplayCheck.screenshot(client, "painting.png"); + client.player.closeContainer(); + break; + case FIND_POT: + boolean returned = false; + for (int i = 0; i < 36; i++) { + ItemStack stack = client.player.getInventory().getItem(i); + if (PaintingRegistration.isPot(stack) && PaintingRegistration.dyed(stack) + && PaintedPotEntity.fromStack(stack).paint().color(0) == 14) returned = true; + } + if (!returned) return false; + task = server.submit(() -> equipStamp(server.getPlayerList().getPlayers().get(0))); + break; + case STAMP: + ItemStack icon = client.player.getItemInHand(InteractionHand.OFF_HAND); + if (icon.getItem() != Items.FEATHER || !PaintingRegistration.isPot(client.player.getItemInHand(InteractionHand.MAIN_HAND))) return false; + stamped = FacePaint.read(PaintingClient.pattern(client.player, icon)); + if (stamped.equals(FacePaint.EMPTY)) throw new AssertionError("Could not read the vanilla feather icon"); + useTable(client); + break; + case VERIFY: + Pottery result = ForgeStackProfiles.INSTANCE.read(client.player.getItemInHand(InteractionHand.MAIN_HAND)); + if (result == null || !result.paint().equals(stamped)) return false; + if (!PaintingRegistration.dyed(client.player.getItemInHand(InteractionHand.MAIN_HAND))) throw new AssertionError("Paint lost base dye"); + System.out.println("POTTERY VERIFIED painting: raw dye, furnace, screen stroke, undo, costs and feather stamp"); + break; + default: throw new AssertionError(step); + } + System.out.println("POTTERY painting " + step + " complete"); + step = Step.values()[step.ordinal()+1]; + return false; + } + + private static void checkModel(Minecraft client, ItemStack stack, boolean painted) { + int rgb = Pigments.clayTint("blue"); + int expectedColor = 0xff000000 | (rgb & 255) << 16 | rgb & 0xff00 | rgb >>> 16; + boolean dyed = false, ink = false; + var model = client.getItemRenderer().getModel(stack, client.level, client.player, 42); + for (var quad : model.getQuads(null, null, net.minecraft.util.RandomSource.create(42))) { + String texture = quad.getSprite().contents().name().toString(); + if (texture.equals("primalpottery:block/dyed_clay") && quad.getVertices()[3] == expectedColor) dyed = true; + if (texture.equals("primalpottery:block/paint_sheet") || texture.equals("primalpottery:block/pottery_inks")) ink = true; + } + if (!dyed || ink != painted) throw new AssertionError("Dyed vessel mesh has incorrect clay or paint at preview stage " + painted); + } + + private static PaintingMenu menu(Minecraft client) { return (PaintingMenu) client.player.containerMenu; } + private static void click(Minecraft client,int x,int y) throws Exception { + PaintingScreen screen = (PaintingScreen) client.screen; + x += (screen.width - PaintPanel.WIDTH)/2; + y += (screen.height - PaintPanel.HEIGHT)/2; + screen.mouseClicked(x,y,0); + screen.mouseReleased(x,y,0); + } + private static void useTable(Minecraft client) { + var hit = new BlockHitResult(Vec3.atCenterOf(TABLE),Direction.NORTH,TABLE,false); + client.gameMode.useItemOn(client.player, InteractionHand.MAIN_HAND, hit); + } + private static void prepare(ServerLevel level, ServerPlayer player) { + level.setBlockAndUpdate(TABLE.below(),Blocks.STONE.defaultBlockState()); + level.setBlockAndUpdate(TABLE.offset(0,-1,-2),Blocks.STONE.defaultBlockState()); + level.removeBlock(TABLE, false); + level.setBlockAndUpdate(TABLE,PaintingRegistration.TABLE.get().defaultBlockState()); + player.connection.teleport(72.5,80,38.5,0,10); + ItemStack raw = new ItemStack(PrimalPotteryForge.RAW.get()); + ForgeStackProfiles.INSTANCE.write(raw,Pottery.jug()); + var grid = new TransientCraftingContainer(player.inventoryMenu,2,2); + grid.setItem(0,raw); + grid.setItem(1,new ItemStack(Items.BLUE_DYE)); + ItemStack dyed = level.getRecipeManager().getRecipeFor(RecipeType.CRAFTING,grid,level).orElseThrow().assemble(grid,level.registryAccess()); + var oven = new net.minecraft.world.SimpleContainer(dyed); + ItemStack fired = level.getRecipeManager().getRecipeFor(RecipeType.SMELTING,oven,level).orElseThrow().assemble(oven,level.registryAccess()); + if (!PaintingRegistration.isPot(fired) || PaintingRegistration.tint(fired) != Pigments.clayTint("blue")) + throw new AssertionError("Crafting/firing did not preserve blue glaze"); + player.setItemInHand(InteractionHand.MAIN_HAND,fired); + player.setItemInHand(InteractionHand.OFF_HAND,ItemStack.EMPTY); + for (int i = 0; i < 16; i++) player.getInventory().setItem(9+i, + new ItemStack(DyeItem.byColor(DyeColor.byId(i)),3)); + player.inventoryMenu.broadcastChanges(); + } + + private static void equipStamp(ServerPlayer player) { + for (int i = 0; i < 36; i++) { + ItemStack stack = player.getInventory().getItem(i); + if (!PaintingRegistration.isPot(stack) || !PaintingRegistration.dyed(stack)) continue; + if (PaintedPotEntity.fromStack(stack).paint().color(0) != 14) continue; + player.getInventory().setItem(i,ItemStack.EMPTY); + player.setItemInHand(InteractionHand.MAIN_HAND,stack); + player.setItemInHand(InteractionHand.OFF_HAND,new ItemStack(Items.FEATHER)); + player.inventoryMenu.broadcastChanges(); + return; + } + throw new AssertionError("Closing the painting menu lost the decorated vessel"); + } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/PlacementGameplay.java b/.github/forge-display-check/1.20.1/potterycheck/PlacementGameplay.java new file mode 100644 index 0000000..28557e4 --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/PlacementGameplay.java @@ -0,0 +1,68 @@ +package potterycheck; + +import net.minecraft.core.*; +import net.minecraft.server.level.*; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.*; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.*; +import net.minecraft.world.phys.*; +import net.modcrafters.minecraft.primalpottery.forge.*; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Exercises shared footprints through the block item and survival harvest, and tests hopper-style furnace input. */ +final class PlacementGameplay { + private static final BlockPos SITE = WheelGameplay.BASE.west(2); + private static final BlockPos OVEN = WheelGameplay.BASE.east(2); + private static final Pottery FIRST = Pottery.jug().withHeight(10); + private static final Pottery SECOND = Pottery.jug().withHeight(14); + + static void verify(ServerLevel level, ServerPlayer player) { + level.removeBlock(SITE, false); + place(level, player, FIRST, .25F); + place(level, player, SECOND, .75F); + PaintedPotEntity pots = (PaintedPotEntity) level.getBlockEntity(SITE); + check(pots != null && pots.layout().count() == 2, "Two distinct pottery items should share a block"); + var ray = new BlockHitResult(Vec3.atLowerCornerOf(SITE).add(.75, .5, .25), Direction.UP, SITE, false); + ItemStack picked = level.getBlockState(SITE).getCloneItemStack(ray, level, SITE, player); + var previousMode = player.gameMode.getGameModeForPlayer(); + player.setGameMode(net.minecraft.world.level.GameType.SURVIVAL); + player.moveTo(SITE.getX() + .75, SITE.getY() + 1, SITE.getZ() + .25, 0, 90); + player.gameMode.destroyBlock(SITE); + player.setGameMode(previousMode); + check(ForgeStackProfiles.INSTANCE.read(picked).discs().equals(SECOND.discs()), "Picked neighbor"); + check(pots.layout().count() == 1 && pots.profile().discs().equals(FIRST.discs()), "Targeted harvest removed neighbor"); + check(!level.getEntitiesOfClass(net.minecraft.world.entity.item.ItemEntity.class, new AABB(SITE).inflate(1), + drop -> drop.getItem().getItem() == net.minecraft.world.item.Item.byBlock(level.getBlockState(SITE).getBlock()) + && PaintedPotEntity.fromStack(drop.getItem()).discs().equals(SECOND.discs())).isEmpty(), "Missing harvested pottery drop"); + FurnaceBlockEntity furnace = (FurnaceBlockEntity) level.getBlockEntity(OVEN); + ItemStack output = shaped(false, FIRST); + furnace.setItem(2, output); + furnace.setItem(0, shaped(true, SECOND)); + furnace.setItem(1, new ItemStack(Items.COAL)); + tick(level, furnace); + check(furnace.getItem(2).getCount() == 1 && !furnace.getItem(0).isEmpty(), "Furnace merged different shapes"); + furnace.setItem(0, shaped(true, FIRST)); + tick(level, furnace); + check(furnace.getItem(2).getCount() == 2 && furnace.getItem(0).isEmpty(), "Matching pottery failed to stack"); + System.out.println("POTTERY VERIFIED selective survival harvest, pick and occupied furnace output"); + } + + private static void place(ServerLevel level, ServerPlayer player, Pottery shape, float x) { + ItemStack item = shaped(false, shape); + player.setItemInHand(InteractionHand.MAIN_HAND, item); + var hit = new BlockHitResult(Vec3.atLowerCornerOf(SITE).add(x, 0, .25), Direction.UP, SITE.below(), false); + item.useOn(new UseOnContext(player, InteractionHand.MAIN_HAND, hit)); + } + private static ItemStack shaped(boolean raw, Pottery shape) { + ItemStack stack = raw ? new ItemStack(PrimalPotteryForge.RAW.get()) : new ItemStack(net.minecraftforge.registries.ForgeRegistries.ITEMS.getValue(new net.minecraft.resources.ResourceLocation("primalpottery", "pottery"))); + ForgeStackProfiles.INSTANCE.write(stack, shape); + return stack; + } + private static void tick(ServerLevel level, FurnaceBlockEntity furnace) { + for (int i = 0; i < 205; i++) AbstractFurnaceBlockEntity.serverTick(level, OVEN, level.getBlockState(OVEN), furnace); + } + private static void check(boolean passed, String message) { if (!passed) throw new AssertionError(message); } + private PlacementGameplay() {} +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/VesselClientCheck.java b/.github/forge-display-check/1.20.1/potterycheck/VesselClientCheck.java new file mode 100644 index 0000000..5329071 --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/VesselClientCheck.java @@ -0,0 +1,76 @@ +package potterycheck; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Future; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.InteractionHand; +import net.minecraft.server.MinecraftServer; +import net.modcrafters.minecraft.primalpottery.forge.VesselData; +import net.modcrafters.minecraft.primalpottery.forge.VesselInteractions; +import net.modcrafters.minecraft.primalpottery.forge.client.VesselScreen; +import net.modcrafters.minecraft.primalpottery.forge.client.VesselModels; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +final class VesselClientCheck { + private enum Step { EQUIP, OPEN, CLOSE_LID, REMOVE_LID, VERIFY, DONE } + private static Step step = Step.EQUIP; + private static int ticks; + private static Future setup; + private static final InteractionHand HAND = InteractionHand.MAIN_HAND; + + static boolean tick(Minecraft client) throws Exception { + if (step == Step.DONE) return true; + if (++ticks > 200) throw new AssertionError("Vessel client timed out at " + step); + if (setup != null && !setup.isDone()) return false; + if (setup != null) setup.get(); + MinecraftServer server = client.getSingleplayerServer(); + ItemStack held = client.player.getItemInHand(HAND); + switch (step) { + case EQUIP: + List empty = Collections.emptyList(); + List water = VesselModels.append(empty, VesselGameplay.water, PotteryLayout.CENTER); + List tree = VesselModels.append(empty, VesselGameplay.planter, PotteryLayout.CENTER); + if (water.isEmpty() || tree.size() <= water.size() || tree != VesselModels.append(empty, VesselGameplay.planter, PotteryLayout.CENTER)) { + throw new AssertionError("Missing or uncached planter/fluid mesh"); + } + setup = server.submit(() -> { + ServerPlayer player = server.getPlayerList().getPlayers().get(0); + player.setItemInHand(HAND, VesselGameplay.water.copy()); + player.inventoryMenu.broadcastChanges(); + }); + break; + case OPEN: + if (VesselData.amount(held) <= 0) return false; + VesselInteractions.useHeld(client.player, HAND); + break; + case CLOSE_LID: + if (!(client.screen instanceof VesselScreen)) return false; + click((VesselScreen) client.screen); + break; + case REMOVE_LID: + if (!VesselData.lid(held)) return false; + DisplayCheck.screenshot(client, "vessel-lid.png"); + if (VesselModels.append(Collections.emptyList(), held, PotteryLayout.CENTER).isEmpty()) throw new AssertionError("Missing lid mesh"); + click((VesselScreen) client.screen); + break; + case VERIFY: + if (VesselData.lid(held)) return false; + client.setScreen(null); + System.out.println("POTTERY VERIFIED vessel client: fluid/planter geometry, lid preview, equip and remove through network"); + break; + default: throw new AssertionError(step); + } + step = Step.values()[step.ordinal() + 1]; + return false; + } + + private static void click(VesselScreen screen) throws Exception { + int x = screen.width / 2; + int y = (screen.height - 172) / 2 + 152; + screen.mouseClicked(x, y, 0); + } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/VesselGameplay.java b/.github/forge-display-check/1.20.1/potterycheck/VesselGameplay.java new file mode 100644 index 0000000..daab7ac --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/VesselGameplay.java @@ -0,0 +1,117 @@ +package potterycheck; + +import java.util.Arrays; +import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.nbt.ListTag; +import net.modcrafters.minecraft.primalpottery.forge.*; +import net.modcrafters.minecraft.primalpottery.pottery.*; + +/** Uses the same held, placed and lid packet actions as the player in the disposable test world. */ +public final class VesselGameplay { + private static final InteractionHand HAND = InteractionHand.MAIN_HAND; + private static final BlockPos PLACED = new BlockPos(55, 80, 4); + private static final BlockPos WATER = new BlockPos(55, 81, 5); + private static final int SLOT = PotteryLayout.CENTER; + + static volatile ItemStack water, planter; + + public static void verify(ServerLevel level, ServerPlayer player) { + ItemStack original = player.getItemInHand(HAND); + ItemStack offhand = player.getItemInHand(InteractionHand.OFF_HAND); + player.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); + double x = player.getX(), y = player.getY(), z = player.getZ(); + float yaw = player.getYRot(), pitch = player.getXRot(); + try { + player.connection.teleport(55.5, 80, 2.5, 0, 0); + verifyVessels(level, player); + } finally { + level.removeBlock(WATER, false); + level.removeBlock(PLACED, false); + player.connection.teleport(x, y, z, yaw, pitch); + player.setItemInHand(HAND, original); + player.setItemInHand(InteractionHand.OFF_HAND, offhand); + } + } + + private static void verifyVessels(ServerLevel level, ServerPlayer player) { + Block block = net.minecraftforge.registries.ForgeRegistries.BLOCKS.getValue(new net.minecraft.resources.ResourceLocation("primalpottery", "pottery")); + Pottery shape = new Pottery(Pottery.Size.LARGE, Arrays.asList(new PotteryDisc(1, 16, 14), new PotteryDisc(30, 16, 14), new PotteryDisc(1, 16, 0))); + int capacity = shape.classify().volume(); + require(capacity >= 1000 && shape.cover() != null, "Large planter fixture"); + ItemStack empty = new ItemStack(block); + ForgeStackProfiles.INSTANCE.write(empty, shape); + + level.setBlockAndUpdate(WATER, net.minecraft.world.level.material.Fluids.FLOWING_WATER.getFlowing(6, false).createLegacyBlock()); + player.setItemInHand(HAND, empty.copy()); + VesselInteractions.setLid(player, HAND, null, -1, true); + require(VesselData.lid(player.getItemInHand(HAND)), "Held lid did not close"); + VesselInteractions.useHeld(player, HAND); + require(VesselData.amount(player.getItemInHand(HAND)) == 0, "Closed lid admitted water"); + VesselInteractions.setLid(player, HAND, null, -1, false); + VesselInteractions.useHeld(player, HAND); + ItemStack filled = player.getItemInHand(HAND); + require(VesselData.amount(filled) == capacity && VesselData.fluidId(filled).equals("minecraft:water"), "Flowing water fill"); + require(level.getBlockState(WATER).getBlock() == Blocks.WATER, "Filling consumed the water"); + water = filled.copy(); + require(filled.getMaxStackSize() == 1, "Filled vessel stack limit"); + + level.setBlockAndUpdate(PLACED, block.defaultBlockState()); + block.setPlacedBy(level, PLACED, block.defaultBlockState(), player, empty); + PaintedPotEntity tile = (PaintedPotEntity) level.getBlockEntity(PLACED); + ItemStack pot = tile.stack(SLOT); + VesselInteractions.setLid(player, HAND, PLACED, SLOT, true); + require(VesselData.lid(pot), "Placed lid did not close"); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.amount(filled) == capacity && VesselData.amount(pot) == 0, "Poured through a closed lid"); + VesselInteractions.setLid(player, HAND, PLACED, SLOT, false); + VesselData.storeFluid(pot, "minecraft:lava", 42); + require(VesselInteractions.light(tile) > 0, "Lava did not emit light"); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.amount(pot) == 42 && VesselData.amount(filled) == capacity, "Mixed water and lava"); + VesselData.storeFluid(pot, "minecraft:water", 42); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.amount(pot) == capacity && VesselData.amount(filled) == 42, "Partial pour lost liquid"); + + ItemStack dirt = new ItemStack(Blocks.DIRT); + player.setItemInHand(HAND, dirt); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(!VesselData.planted(pot), "Put soil in a full pot"); + VesselData.storeFluid(pot, "", 0); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.soil(pot) == Blocks.DIRT, "Could not install soil"); + VesselInteractions.setLid(player, HAND, PLACED, SLOT, true); + require(!VesselData.lid(pot), "Closed a planted pot"); + ItemStack saplings = new ItemStack(Blocks.OAK_SAPLING, 2); + player.setItemInHand(HAND, saplings); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.plant(pot) == Blocks.OAK_SAPLING && !pot.getTag().getList("tree", 10).isEmpty(), "Miniature oak failed to generate"); + ListTag before = pot.getTag().getList("tree", 10).copy(); + int remaining = saplings.getCount(); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(saplings.getCount() == remaining && !pot.getTag().getList("tree", 10).equals(before), "Miniature oak reroll"); + ItemStack saved = ItemStack.of(pot.save(new net.minecraft.nbt.CompoundTag()).copy()); + require(saved.getTag().getList("tree", 10).equals(pot.getTag().getList("tree", 10)), "Planter tree lost in saved item"); + planter = saved.copy(); + List drops = VesselInteractions.dropPlanting(saved); + require(drops.size() == 2 && drops.get(0).getItem() == saplings.getItem() && drops.get(1).getItem() == new ItemStack(Blocks.DIRT).getItem() + && !VesselData.planted(saved), "Break did not return plant and soil separately"); + player.setItemInHand(HAND, ItemStack.EMPTY); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(VesselData.plant(pot) == Blocks.AIR && VesselData.soil(pot) == Blocks.DIRT, "Empty hand did not remove the plant first"); + player.setItemInHand(HAND, ItemStack.EMPTY); + VesselInteractions.usePlaced(tile, SLOT, player, HAND); + require(!VesselData.planted(pot), "Empty hand did not remove the soil"); + System.out.println("POTTERY VERIFIED vessels: held/placed lids, flowing fill, transfer, light, soil, miniature tree, reroll and drops"); + } + + private static void require(boolean passed, String message) { + if (!passed) throw new AssertionError(message); + } +} diff --git a/.github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java b/.github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java index 8c46675..7a8ffcf 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/WheelClientCheck.java @@ -43,6 +43,8 @@ boolean tick(Minecraft client) throws Exception { case FIRE: if (gameplay.fired()) { gameplay.verify(); + PlacementGameplay.verify(server.overworld(), server.getPlayerList().getPlayers().get(0)); + VesselGameplay.verify(server.overworld(), server.getPlayerList().getPlayers().get(0)); phase = Phase.DONE; } break; diff --git a/.github/scripts/release-publish.sh b/.github/scripts/release-publish.sh index 524d52a..fef9cd8 100644 --- a/.github/scripts/release-publish.sh +++ b/.github/scripts/release-publish.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash -# Publishes the four jars for one tag: NeoForge 1.20.6, NeoForge 1.21.1, Fabric 26.3, and NeoForge 26.3. +# Publishes the six loader and Minecraft targets defined below. # Each loader gets its own Modrinth version and CurseForge file, so the download button -# is the jar for that loader. GitHub gets one release with all four attached. +# is the jar for that loader. GitHub gets one release with all six attached. # Usage: # release-publish.sh check-env # release-publish.sh classify @@ -28,36 +28,29 @@ check_env() { [[ "$CURSEFORGE_PROJECT_ID" =~ ^[0-9]+$ ]] || die "CURSEFORGE_PROJECT_ID should be the number from the CurseForge project page" } -# Sets neo_1206, neo_121, fabric_263, and neo_263. A sources jar, or a jar from another version, is ignored. +# Loader, Minecraft version, game JVM and Modrinth version suffix. +targets=( + 'Forge 1.12.2 8 1.12.2' + 'Forge 1.20.1 17 1.20.1' + 'NeoForge 1.20.6 21 1.20.6' + 'NeoForge 1.21.1 21 1.21.1' + 'Fabric 26.3 25 26.3+fabric' + 'NeoForge 26.3 25 26.3+neoforge' +) + classify() { - local dir=$1 version=$2 jar base - neo_1206='' neo_121='' fabric_263='' neo_263='' + local dir=$1 version=$2 target loader game java suffix filename + local -a matches + jar_paths=() [[ -d "$dir" ]] || die "No jar directory at ${dir}" - while IFS= read -r jar; do - base=$(basename "$jar") - case "$base" in - "primalpottery-neoforge-1.20.6-${version}.jar") - [[ -z "$neo_1206" ]] || die "Two NeoForge 1.20.6 jars named ${base}" - neo_1206=$jar - ;; - "primalpottery-neoforge-1.21.1-${version}.jar") - [[ -z "$neo_121" ]] || die "Two NeoForge 1.21.1 jars named ${base}" - neo_121=$jar - ;; - "primalpottery-fabric-26.3-${version}.jar") - [[ -z "$fabric_263" ]] || die "Two Fabric 26.3 jars named ${base}" - fabric_263=$jar - ;; - "primalpottery-neoforge-26.3-${version}.jar") - [[ -z "$neo_263" ]] || die "Two NeoForge 26.3 jars named ${base}" - neo_263=$jar - ;; - esac - done < <(find "$dir" -type f -name '*.jar' | sort) - [[ -n "$neo_1206" ]] || die "Missing primalpottery-neoforge-1.20.6-${version}.jar" - [[ -n "$neo_121" ]] || die "Missing primalpottery-neoforge-1.21.1-${version}.jar" - [[ -n "$fabric_263" ]] || die "Missing primalpottery-fabric-26.3-${version}.jar" - [[ -n "$neo_263" ]] || die "Missing primalpottery-neoforge-26.3-${version}.jar" + for target in "${targets[@]}"; do + read -r loader game java suffix <<< "$target" + filename="primalpottery-${loader,,}-${game}-${version}.jar" + mapfile -t matches < <(find "$dir" -type f -name "$filename") + [[ ${#matches[@]} -gt 0 ]] || die "Missing ${filename}" + [[ ${#matches[@]} == 1 ]] || die "Two ${loader} ${game} jars named ${filename}" + jar_paths+=("${matches[0]}") + done } http_code() { @@ -197,7 +190,8 @@ github_release() { upload() { local version=$1 notes=$2 - local jars=$3 code cf_neo_1206 cf_neo_121 cf_fabric_263 cf_neo_263 + local jars=$3 code loader game java suffix i target + local -a catalog_ids=() check_env [[ -f "$notes" ]] || die "No changelog at ${notes}" [[ -n "${TAG:-}" ]] || die "TAG is missing" @@ -230,10 +224,10 @@ upload() { # Resolve every target before the first upload, so a catalog error cannot # leave a release published only on Modrinth. - cf_neo_1206=$(curseforge_game_versions 1.20.6 NeoForge "Java 21") - cf_neo_121=$(curseforge_game_versions 1.21.1 NeoForge "Java 21") - cf_fabric_263=$(curseforge_game_versions 26.3 Fabric "Java 25") - cf_neo_263=$(curseforge_game_versions 26.3 NeoForge "Java 25") + for target in "${targets[@]}"; do + read -r loader game java suffix <<< "$target" + catalog_ids+=("$(curseforge_game_versions "$game" "$loader" "Java $java")") + done code=$(http_code "$work/files.json" \ -H "X-Api-Token: ${CURSEFORGE_TOKEN}" \ @@ -245,17 +239,15 @@ upload() { echo "CurseForge file list returned ${code}. A repeated run may upload the same jar again." >&2 fi - modrinth_upload "${version}+1.20.6" "Primal Pottery ${version} for NeoForge 1.20.6" neoforge 1.20.6 "$neo_1206" - modrinth_upload "${version}+1.21.1" "Primal Pottery ${version} for NeoForge 1.21.1" neoforge 1.21.1 "$neo_121" - modrinth_upload "${version}+26.3+fabric" "Primal Pottery ${version} for Fabric 26.3" fabric 26.3 "$fabric_263" - modrinth_upload "${version}+26.3+neoforge" "Primal Pottery ${version} for NeoForge 26.3" neoforge 26.3 "$neo_263" - - curseforge_upload "Primal Pottery ${version} for NeoForge 1.20.6" NeoForge "$neo_1206" "$cf_neo_1206" - curseforge_upload "Primal Pottery ${version} for NeoForge 1.21.1" NeoForge "$neo_121" "$cf_neo_121" - curseforge_upload "Primal Pottery ${version} for Fabric 26.3" Fabric "$fabric_263" "$cf_fabric_263" - curseforge_upload "Primal Pottery ${version} for NeoForge 26.3" NeoForge "$neo_263" "$cf_neo_263" - - github_release "$TAG" "$neo_1206" "$neo_121" "$fabric_263" "$neo_263" + for i in "${!targets[@]}"; do + read -r loader game java suffix <<< "${targets[i]}" + modrinth_upload "${version}+${suffix}" "Primal Pottery ${version} for ${loader} ${game}" "${loader,,}" "$game" "${jar_paths[i]}" + done + for i in "${!targets[@]}"; do + read -r loader game java suffix <<< "${targets[i]}" + curseforge_upload "Primal Pottery ${version} for ${loader} ${game}" "$loader" "${jar_paths[i]}" "${catalog_ids[i]}" + done + github_release "$TAG" "${jar_paths[@]}" } [[ $# -ge 1 ]] || die "Usage: release-publish.sh check-env|classify|upload ..." @@ -266,7 +258,7 @@ case "$cmd" in classify) [[ $# -eq 2 ]] || die "Usage: release-publish.sh classify " classify "$1" "$2" - printf '%s\n' "$neo_1206" "$neo_121" "$fabric_263" "$neo_263" + printf '%s\n' "${jar_paths[@]}" ;; upload) [[ $# -eq 3 ]] || die "Usage: release-publish.sh upload " diff --git a/.github/scripts/test_curseforge_versions.py b/.github/scripts/test_curseforge_versions.py index 0d4e3e6..733788e 100644 --- a/.github/scripts/test_curseforge_versions.py +++ b/.github/scripts/test_curseforge_versions.py @@ -14,6 +14,7 @@ resolve = runpy.run_path(str(Path(__file__).with_name("curseforge-version-ids.py")))["resolve"] TYPES = [ + {"id": 90010, "slug": "minecraft-1-12"}, {"id": 2, "slug": "java"}, {"id": 615, "slug": "addons"}, {"id": 75208, "slug": "environment"}, @@ -23,6 +24,11 @@ {"id": 88556, "slug": "minecraft-26-3"}, ] VERSIONS = [ + {"id": 90011, "gameVersionTypeID": 90010, "name": "1.12.2"}, + {"id": 90012, "gameVersionTypeID": 66006, "name": "1.20.1"}, + {"id": 90013, "gameVersionTypeID": 68441, "name": "Forge"}, + {"id": 90014, "gameVersionTypeID": 2, "name": "Java 8"}, + {"id": 90015, "gameVersionTypeID": 2, "name": "Java 17"}, {"id": 99901, "gameVersionTypeID": 75208, "name": "Client"}, {"id": 99902, "gameVersionTypeID": 75208, "name": "Server"}, {"id": 7499, "gameVersionTypeID": 68441, "name": "Fabric"}, @@ -84,6 +90,22 @@ def test_required_environment_is_not_silently_omitted(self): with self.assertRaisesRegex(ValueError, "environment"): resolve(versions, TYPES, "26.3", "Fabric", "Java 25") + def test_missing_and_duplicate_forge_jars(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + command = [os.environ.get("BASH_EXECUTABLE", "bash"), Path(__file__).with_name("release-publish.sh").resolve().as_posix(), + "classify", root.as_posix(), "1"] + for target in ("forge-1.12.2", "forge-1.20.1", "neoforge-1.20.6", "neoforge-1.21.1", "fabric-26.3", "neoforge-26.3"): + (root / f"primalpottery-{target}-1.jar").touch() + self.assertEqual(len(subprocess.check_output(command, text=True).splitlines()), 6) + jar = root / "primalpottery-forge-1.12.2-1.jar" + jar.unlink() + self.assertIn("Missing", subprocess.run(command, capture_output=True, text=True).stderr) + jar.touch() + (root / "second").mkdir() + (root / "second" / jar.name).touch() + self.assertIn("Two Forge", subprocess.run(command, capture_output=True, text=True).stderr) + def test_publisher_preflight_and_resolved_upload_metadata(self): for valid in (False, True): with self.subTest(valid=valid), tempfile.TemporaryDirectory(prefix="curseforge-test-") as folder: @@ -92,7 +114,7 @@ def test_publisher_preflight_and_resolved_upload_metadata(self): (root / "versions.json").write_text(json.dumps(versions), encoding="utf-8") (root / "types.json").write_text(json.dumps(TYPES), encoding="utf-8") (root / "notes.md").write_text("- Release notes.\n", encoding="utf-8") - for target in ("neoforge-1.20.6", "neoforge-1.21.1", "fabric-26.3", "neoforge-26.3"): + for target in ("forge-1.12.2", "forge-1.20.1", "neoforge-1.20.6", "neoforge-1.21.1", "fabric-26.3", "neoforge-26.3"): (root / f"primalpottery-{target}-0.0.2-alpha.jar").touch() trace = root / "uploads.txt" env = dict(os.environ, MODRINTH_TOKEN="test", CURSEFORGE_TOKEN="test", @@ -125,8 +147,10 @@ def test_publisher_preflight_and_resolved_upload_metadata(self): if valid: self.assertEqual(result.returncode, 0, result.stderr) uploads = trace.read_text().splitlines() - self.assertEqual(len(uploads), 9) - self.assertEqual(uploads[4:8], [ + self.assertEqual(len(uploads), 13) + self.assertEqual(uploads[6:12], [ + "CurseForge [90011, 90013, 99901, 99902, 90014]", + "CurseForge [90012, 90013, 99901, 99902, 90015]", "CurseForge [12060, 10150, 99901, 99902, 11135]", "CurseForge [11779, 10150, 99901, 99902, 11135]", "CurseForge [17045, 7499, 99901, 99902, 14454]", diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ee13050..e17ac8d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -181,9 +181,44 @@ jobs: !**/*-javadoc.jar !**/*-dev.jar + forge: + name: Forge ${{ matrix.minecraft }} + needs: notes + runs-on: ubuntu-latest + strategy: + matrix: + include: + - minecraft: '1.12.2' + java: '8' + directory: legacy/forge-1.12.2 + task: build + jars: legacy/forge-1.12.2/build/libs + - minecraft: '1.20.1' + java: '21' + directory: . + task: :forge:build + jars: forge/build/libs + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: ${{ matrix.java }} + - uses: gradle/actions/setup-gradle@v6 + - name: Set the published version + run: bash .github/scripts/release-version.sh write gradle.properties "${{ needs.notes.outputs.version }}" + - name: Build remapped jar + working-directory: ${{ matrix.directory }} + run: ./gradlew ${{ matrix.task }} + - uses: actions/upload-artifact@v7 + with: + name: jars-forge-${{ matrix.minecraft }} + if-no-files-found: error + path: ${{ matrix.jars }}/primalpottery-forge-${{ matrix.minecraft }}-${{ needs.notes.outputs.version }}.jar + publish: name: Publish - needs: [notes, mc-26-3, mc-1-20-6, mc-1-21-1] + needs: [notes, forge, mc-26-3, mc-1-20-6, mc-1-21-1] runs-on: ubuntu-latest permissions: contents: write diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java index cf28fa7..c60eb22 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/BakedVessels.java @@ -16,21 +16,49 @@ public abstract class BakedVessels { private static final class Key { final List discs; final FacePaint paint; - Key(Pottery pot) { discs = pot.discs(); paint = pot.paint(); } - @Override public int hashCode() { return discs.hashCode() * 31 + paint.hashCode(); } + final int slot, tint; + final boolean plate; + final Pottery.Size size; + Key(Pottery pot, int slot, int tint) { plate = pot.isPlate(); size = pot.size(); this.tint = tint; discs = pot.discs(); paint = pot.paint(); this.slot = slot; } + @Override public int hashCode() { return (((discs.hashCode() * 31 + paint.hashCode()) * 31 + slot) * 31 + tint) * 31 + size.ordinal() * 2 + (plate ? 1 : 0); } @Override public boolean equals(Object obj) { if (!(obj instanceof Key)) return false; Key other = (Key) obj; - return discs.equals(other.discs) && paint.equals(other.paint); + return size == other.size && plate == other.plate && tint == other.tint && slot == other.slot && discs.equals(other.discs) && paint.equals(other.paint); } } - public synchronized List model(Pottery pot) { - Key key = new Key(pot); + public List model(Pottery pot) { return model(pot, -1); } + + public List model(Pottery pot, int tint) { return model(pot, PotteryLayout.CENTER, tint); } + + public List placed(PotteryLayout layout) { + int first = layout.first(); + if (first < 0) return Collections.emptyList(); + if (layout.count() == 1) return model(layout.at(first), first, layout.tint(first)); + List faces = new ArrayList<>(); + for (int i = first; i < PotteryLayout.COUNT; i++) { + if (layout.at(i) != null) faces.addAll(model(layout.at(i), i, layout.tint(i))); + } + return faces; + } + + public synchronized List model(Pottery pot, int slot, int tint) { + // Large vessels are centered just like an inventory model. + if (pot.size() == Pottery.Size.LARGE) slot = PotteryLayout.CENTER; + Key key = new Key(pot, slot, tint); List cached = models.get(key); if (cached != null) return cached; List faces = new ArrayList<>(); - new PaintedVessel(pot, (a, b, c, d, ink) -> faces.add(bake(a, b, c, d, ink)), paintTile(pot.paint())); + PaintedVessel.Faces sink = (a, b, c, d, ink) -> faces.add(bake(a, b, c, d, ink, tint)); + if (slot != PotteryLayout.CENTER) { + double x = PotteryLayout.centerX(slot, pot), z = PotteryLayout.centerZ(slot, pot); + double scale = PotteryLayout.scale(slot, pot); + PaintedVessel.Faces centered = sink; + sink = (a, b, c, d, ink) -> centered.quad(a.placed(x, z, scale), b.placed(x, z, scale), + c.placed(x, z, scale), d.placed(x, z, scale), ink); + } + new PaintedVessel(pot, sink, paintTile(pot.paint())); List model = Collections.unmodifiableList(faces); if (model.size() > MAX_QUADS) return model; Iterator> oldest = models.values().iterator(); @@ -46,6 +74,9 @@ public synchronized List model(Pottery pot) { protected PaintedVessel.PaintTile paintTile(FacePaint paint) { return null; } + protected Q bake(PaintedVessel.Vertex a, PaintedVessel.Vertex b, PaintedVessel.Vertex c, + PaintedVessel.Vertex d, int pigment, int tint) { return bake(a, b, c, d, pigment); } + protected abstract Q bake(PaintedVessel.Vertex a, PaintedVessel.Vertex b, PaintedVessel.Vertex c, PaintedVessel.Vertex d, int pigment); } diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedPlate.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedPlate.java new file mode 100644 index 0000000..1888528 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedPlate.java @@ -0,0 +1,106 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.ArrayList; +import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.Faces; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; +import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.Vertex; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile.Station; + +/** Maps a four-column motif onto each octagonal sector, following the clay from floor to rim. */ +final class PaintedPlate { + private static final int COLUMNS = 4; + private static final double ARC = Math.PI / 4; + + private PaintedPlate() {} + + static void draw(Pottery plate, Faces faces, PaintTile tile) { + List path = surface(plate); + double[] distance = new double[path.size()]; + for (int i = 1; i < path.size(); i++) { + Station a = path.get(i - 1), b = path.get(i); + distance[i] = distance[i - 1] + Math.hypot(b.radius() - a.radius(), b.y() - a.y()); + } + double length = distance[distance.length - 1]; + if (length == 0) return; + for (int side = 0; side < 8; side++) { + Sector sector = new Sector((side + 0.5) * ARC); + for (int i = 1; i < path.size(); i++) { + double from = distance[i - 1] * FacePaint.SIDE / length; + double to = distance[i] * FacePaint.SIDE / length; + if (to == from) continue; + Strip strip = new Strip(sector, path.get(i - 1), path.get(i), from, to); + for (int column = 0; column < COLUMNS; column++) { + if (tile != null) { + strip.draw(faces, tile, column, from, to, PaintedVessel.PAINT_TEXTURE); + } else { + strip.paintCells(faces, plate.paint(), column); + } + } + } + } + } + + private static List surface(Pottery plate) { + PotteryDisc rim = plate.discs().get(0); + List path = new ArrayList<>(); + if (rim.innerRadius() > 0) { + List cavity = PotteryProfile.cavity(plate.discs()); + path.add(new Station(cavity.get(0).y(), 0)); + path.addAll(cavity); + } else { + path.add(new Station(plate.height(), 0)); + } + path.add(new Station(plate.height(), rim.radius())); + return path; + } + + private static final class Sector { + final double x, z, dx, dz; + + Sector(double angle) { + x = Math.cos(angle); + z = Math.sin(angle); + dx = Math.cos(angle + ARC) - x; + dz = Math.sin(angle + ARC) - z; + } + } + + private static final class Strip { + final Sector side; + final Station low, high; + final double from, to; + + Strip(Sector side, Station low, Station high, double from, double to) { + this.side = side; + this.low = low; + this.high = high; + this.from = from; + this.to = to; + } + + void paintCells(Faces faces, FacePaint paint, int column) { + int end = Math.min(FacePaint.SIDE, (int) Math.ceil(to)); + for (int row = (int) from; row < end; row++) { + int color = paint.color(column * FacePaint.SIDE + row); + if (color != FacePaint.ERASE) draw(faces, null, column, Math.max(from, row), Math.min(to, row + 1), color); + } + } + + void draw(Faces faces, PaintTile tile, int column, double start, double end, int ink) { + double left = column / (double) COLUMNS, right = (column + 1) / (double) COLUMNS; + double v = tile == null ? 8 : tile.v(column + 0.5); + faces.quad(vertex(tile, start, left, v), vertex(tile, start, right, v), + vertex(tile, end, right, v), vertex(tile, end, left, v), ink); + } + + Vertex vertex(PaintTile tile, double distance, double across, double v) { + double t = (distance - from) / (to - from); + // The inward and upward offsets clear both vertical cavity walls and the flat plate floor. + double radius = Math.max(0, low.radius() + t * (high.radius() - low.radius()) - 0.008) / 32; + double y = (low.y() + t * (high.y() - low.y()) + 0.012) / 32; + return new Vertex(0.5 + radius * (side.x + across * side.dx), y, + 0.5 + radius * (side.z + across * side.dz), tile == null ? 8 : tile.u(distance), v); + } + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java index 0255bfe..d0de26a 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java @@ -26,6 +26,10 @@ public interface Faces { public static final class Vertex { public final float x, y, z, u, v; + Vertex placed(double centerX, double centerZ, double scale) { + return new Vertex(centerX + (x - .5) * scale, y * scale, centerZ + (z - .5) * scale, u, v); + } + Vertex(double x, double y, double z, double u, double v) { this.x = (float) x; this.y = (float) y; @@ -41,6 +45,9 @@ public static final class PaintTile { private final boolean opaque; + double u(double px) { return u + size * px / 16; } + double v(double px) { return v + size * px / 16; } + public PaintTile(double u, double v, double size, boolean opaque) { this.opaque = opaque; this.u = u; @@ -68,13 +75,14 @@ public PaintedVessel(Pottery pot, Faces faces, PaintTile tile) { double middle = pot.height() * 0.48; paintSpan = Math.min(2 * Math.sin(Math.PI / 8) * PotteryProfile.sample(outside, middle), pot.height() * 0.84); paintTop = middle + paintSpan / 2; - if (tile == null) findMatchingRows(pot.paint().pixels()); + if (tile == null && !pot.isPlate()) findMatchingRows(pot.paint().pixels()); surface(outside, true); surface(PotteryProfile.profile(pot.discs(), true), false); PotteryDisc lip = pot.discs().get(0); PotteryDisc foot = pot.discs().get(pot.discs().size() - 1); ring(pot.height(), lip.radius(), lip.innerRadius(), true); ring(0, foot.radius(), foot.innerRadius(), false); + if (pot.isPlate() && !FacePaint.EMPTY.equals(pot.paint())) PaintedPlate.draw(pot, faces, tile); } private void findMatchingRows(String pixels) { @@ -95,11 +103,11 @@ private void surface(List outline, boolean outside) { continue; } if (low.radius() == 0 && high.radius() == 0) continue; - boolean covered = outside && tile != null && tile.opaque && paintSpan > 0 + boolean covered = outside && !pot.isPlate() && tile != null && tile.opaque && paintSpan > 0 && low.y() >= paintTop - paintSpan && high.y() <= paintTop; for (int side = 0; side < SIDES; side++) { if (!covered) clayWall(low, high, side, outside); - if (outside && !FacePaint.EMPTY.equals(pot.paint())) paint(low, high, side); + if (outside && !pot.isPlate() && !FacePaint.EMPTY.equals(pot.paint())) paint(low, high, side); } } } diff --git a/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PlatterSegments.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PlatterSegments.java similarity index 100% rename from src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PlatterSegments.java rename to core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PlatterSegments.java diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayout.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayout.java new file mode 100644 index 0000000..790ad64 --- /dev/null +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayout.java @@ -0,0 +1,95 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +/** Four corner vessels or four edge plates. Large pottery occupies the whole block. + * CENTER preserves the position of single-pot saves from the first Forge preview. */ +public final class PotteryLayout { + public static final int CENTER = 8, COUNT = 9; + private static final double[] X = {.25, .75, .75, .25, .5, 5./6, .5, 1./6, .5}; + private static final double[] Z = {.25, .25, .75, .75, 1./6, .5, 5./6, .5, .5}; + private final Pottery[] pots; + + private final int[] tints; + + public PotteryLayout() { + pots = new Pottery[COUNT]; + tints = new int[COUNT]; + java.util.Arrays.fill(tints, -1); + } + private PotteryLayout(Pottery[] pots, int[] tints) { this.pots = pots; this.tints = tints; } + public Pottery at(int slot) { return slot < 0 || slot >= COUNT ? null : pots[slot]; } + public PotteryLayout with(int slot, Pottery pot) { + return with(slot, pot, -1); + } + public int tint(int slot) { return tints[slot]; } + public PotteryLayout with(int slot, Pottery pot, int tint) { + int[] colors = tints.clone(); + colors[slot] = tint; + Pottery[] changed = pots.clone(); + changed[slot] = pot; + return new PotteryLayout(changed, colors); + } + + public int first() { + for (int i = 0; i < COUNT; i++) if (pots[i] != null) return i; + return -1; + } + public int count() { + int count = 0; + for (Pottery pot : pots) if (pot != null) count++; + return count; + } + public static double centerX(int slot, Pottery pot) { return pot.size() == Pottery.Size.LARGE ? .5 : X[slot]; } + public static double centerZ(int slot, Pottery pot) { return pot.size() == Pottery.Size.LARGE ? .5 : Z[slot]; } + public static double scale(int slot, Pottery pot) { return slot >= 4 && slot < CENTER && pot.isPlate() ? 2./3 : 1; } + public static int preferred(Pottery pot, double x, double z) { + if (pot.size() == Pottery.Size.LARGE) return 0; + if (!pot.isPlate()) return x < .5 ? (z < .5 ? 0 : 3) : (z < .5 ? 1 : 2); + if (Math.abs(x - .5) > Math.abs(z - .5)) return x > .5 ? 5 : 7; + return z > .5 ? 6 : 4; + } + + public int destination(Pottery pot, double x, double z, boolean sneak, int faceX, int faceZ) { + int slot = preferred(pot, x, z); + if (fits(slot, pot)) return slot; + if (!sneak || pot.size() == Pottery.Size.LARGE) return -1; + if (pot.isPlate()) { + for (int step = 1; step < 4; step++) { + int next = 4 + (slot - 4 + step) % 4; + if (fits(next, pot)) return next; + } + } else { + // Prefer the side the player clicked, then the two edge-sharing neighbors. + int beside = preferred(pot, X[slot] + .5 * faceX, Z[slot] + .5 * faceZ); + if (fits(beside, pot)) return beside; + int first = Math.min((slot + 1) % 4, (slot + 3) % 4); + int second = Math.max((slot + 1) % 4, (slot + 3) % 4); + if (fits(first, pot)) return first; + if (fits(second, pot)) return second; + } + return -1; + } + + public boolean fits(int slot, Pottery pot) { + if (slot < 0 || slot >= COUNT || pots[slot] != null) return false; + if (slot == CENTER) return first() < 0; + if (pot.size() == Pottery.Size.LARGE) return slot == 0 && first() < 0; + if ((slot >= 4) != pot.isPlate()) return false; + for (int i = 0; i < COUNT; i++) { + if (pots[i] == null) continue; + if (i == CENTER || pots[i].size() == Pottery.Size.LARGE) return false; + if ((i < 4) != (slot < 4) && Math.abs(X[i] - X[slot]) < 5./12 - 1e-8 + && Math.abs(Z[i] - Z[slot]) < 5./12 - 1e-8) return false; + } + return true; + } + + public int hit(double x, double z) { + if (pots[CENTER] != null) return CENTER; + if (pots[0] != null && pots[0].size() == Pottery.Size.LARGE) return 0; + for (int slot = 4; slot < CENTER; slot++) { + if (pots[slot] != null && Math.abs(x - X[slot]) <= 1./6 + 1e-6 && Math.abs(z - Z[slot]) <= 1./6 + 1e-6) return slot; + } + int corner = x < .5 ? (z < .5 ? 0 : 3) : (z < .5 ? 1 : 2); + return pots[corner] == null ? -1 : corner; + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java index 2f2acf8..4c4c747 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java @@ -4,11 +4,14 @@ /** Packs cached block-model vertices. Each Forge adapter supplies its atlas UVs, native stride and quad factory. */ public abstract class VesselQuadPacker extends BakedVessels { - private final S clay; + private final S clay, dyedClay; private final S inks; private final int stride; - protected VesselQuadPacker(S clay, S inks, int stride) { + protected VesselQuadPacker(S clay, S inks, int stride) { this(clay, inks, clay, stride); } + + protected VesselQuadPacker(S clay, S inks, S dyedClay, int stride) { + this.dyedClay = dyedClay; this.clay = clay; this.inks = inks; this.stride = stride; @@ -22,30 +25,38 @@ protected VesselQuadPacker(S clay, S inks, int stride) { protected abstract Q quad(int[] data, S sprite, float nx, float ny, float nz); @Override protected final Q bake(Vertex a, Vertex b, Vertex c, Vertex d, int pigment) { + return bake(a,b,c,d,pigment,-1); + } + + @Override protected final Q bake(Vertex a, Vertex b, Vertex c, Vertex d, int pigment, int tint) { // Diagonals also give floor triangles a normal when their two centre vertices coincide. float ax = c.x - a.x, ay = c.y - a.y, az = c.z - a.z; float bx = d.x - b.x, by = d.y - b.y, bz = d.z - b.z; float nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx; float length = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); int normal = length == 0 ? 0 : pack(nx / length) | pack(ny / length) << 8 | pack(nz / length) << 16; - S sprite = pigment == PaintedVessel.CLAY ? clay : inks; + S sprite = pigment == PaintedVessel.CLAY ? (tint < 0 ? clay : dyedClay) : inks; + int color = -1; + if (pigment == PaintedVessel.CLAY && tint >= 0) { + color = 0xff000000 | (tint & 255) << 16 | (tint & 0xff00) | tint >>> 16; + } if (pigment == PaintedVessel.PAINT_TEXTURE) sprite = paintSheet(); int[] data = new int[stride * 4]; - write(data, 0, a, sprite, normal, pigment); - write(data, stride, b, sprite, normal, pigment); - write(data, stride * 2, c, sprite, normal, pigment); - write(data, stride * 3, d, sprite, normal, pigment); + write(data, 0, a, sprite, normal, pigment, color); + write(data, stride, b, sprite, normal, pigment, color); + write(data, stride * 2, c, sprite, normal, pigment, color); + write(data, stride * 3, d, sprite, normal, pigment, color); return quad(data, sprite, nx, ny, nz); } - private void write(int[] data, int index, Vertex point, S sprite, int normal, int pigment) { + private void write(int[] data, int index, Vertex point, S sprite, int normal, int pigment, int color) { // Each ink occupies one cell in the 8-column, 4-row palette. Sample its centre at every vertex. float x = pigment < 0 ? point.u : (pigment % 8 + .5F) * 2; float y = pigment < 0 ? point.v : (pigment / 8 + .5F) * 4; data[index] = Float.floatToRawIntBits(point.x); data[index + 1] = Float.floatToRawIntBits(point.y); data[index + 2] = Float.floatToRawIntBits(point.z); - data[index + 3] = 0xffffffff; + data[index + 3] = color; data[index + 4] = Float.floatToRawIntBits(u(sprite, x)); data[index + 5] = Float.floatToRawIntBits(v(sprite, y)); data[index + stride - 1] = normal; diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java index 8ba3240..9f9ef30 100644 --- a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java @@ -25,6 +25,20 @@ private static final class FaceCounter extends BakedVessels { assertTrue(counter.model(PaintedVessel.SAMPLE).stream().anyMatch(ink -> ink >= 0)); } + @Test public void platePaintRepeatsOneRadialCellAroundAllEightSectors() { + Pottery plate = new Pottery(Arrays.asList(new PotteryDisc(1, 8))).withPaint(FacePaint.EMPTY.with(63, 14)); + int[] painted = {0}; + new PaintedVessel(plate, (a, b, c, d, ink) -> { + if (ink == PaintedVessel.CLAY) return; + assertEquals(14, ink); + assertTrue(a.y > plate.height() / 32); + assertEquals(a.y, d.y, 0.00001); + assertTrue(Math.hypot(d.x - .5, d.z - .5) > Math.hypot(a.x - .5, a.z - .5)); + painted[0]++; + }); + assertEquals(8, painted[0]); + } + @Test public void contiguousRowsBecomeOneBandOnEachOfEightFlatFaces() { char[] pixels = FacePaint.EMPTY.pixels().toCharArray(); Arrays.fill(pixels, 5 * 16, 11 * 16, 'C'); diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayoutTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayoutTest.java new file mode 100644 index 0000000..07b96f7 --- /dev/null +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PotteryLayoutTest.java @@ -0,0 +1,34 @@ +package net.modcrafters.minecraft.primalpottery.pottery; + +import java.util.Collections; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PotteryLayoutTest { + private final Pottery jug = Pottery.jug(); + private final Pottery plate = new Pottery(Collections.singletonList(new PotteryDisc(1, 8))); + + @Test public void occupiedCornerUsesClickedSideOnlyWhenSneaking() { + PotteryLayout layout = new PotteryLayout().with(0, jug); + assertEquals(-1, layout.destination(jug, .25, .25, false, 1, 0)); + assertEquals(1, layout.destination(jug, .25, .25, true, 1, 0)); + assertEquals(3, layout.destination(jug, .25, .25, true, 0, 1)); + assertEquals(-1, layout.hit(.75, .75)); + assertEquals(0, layout.hit(.25, .25)); + } + @Test public void edgePlateBlocksOnlyTheTwoOverlappingCorners() { + PotteryLayout layout = new PotteryLayout().with(4, plate); + assertEquals(4, layout.hit(.5, .15)); + assertFalse(layout.fits(0, jug)); + assertFalse(layout.fits(1, jug)); + assertTrue(layout.fits(2, jug)); + assertTrue(layout.fits(3, jug)); + assertEquals(5, layout.destination(plate, .5, .15, true, 0, 0)); + } + @Test public void historicalCenteredVesselKeepsItsWholeFootprintUntilPickedUp() { + PotteryLayout layout = new PotteryLayout().with(PotteryLayout.CENTER, jug); + assertEquals(PotteryLayout.CENTER, layout.hit(.25, .25)); + assertFalse(layout.fits(0, jug)); + assertEquals(-1, layout.with(PotteryLayout.CENTER, null).first()); + } +} diff --git a/forge/build.gradle b/forge/build.gradle index 69b7fbc..f2630e5 100644 --- a/forge/build.gradle +++ b/forge/build.gradle @@ -39,3 +39,7 @@ legacyForge { ext.potteryAssets = file('../src/main/resources/assets/primalpottery') apply from: 'shared/wheel-models.gradle' + +apply from: 'shared/dining.gradle' + +apply from: 'shared/painting.gradle' diff --git a/forge/shared/dining.gradle b/forge/shared/dining.gradle new file mode 100644 index 0000000..c161584 --- /dev/null +++ b/forge/shared/dining.gradle @@ -0,0 +1,7 @@ +processResources { + from(project.ext.potteryAssets) { + include 'models/item/cutlery.json', 'textures/item/cutlery.png', + 'textures/block/cutlery.png', 'textures/block/serving_pixel.png' + into 'assets/primalpottery' + } +} diff --git a/forge/shared/painting.gradle b/forge/shared/painting.gradle new file mode 100644 index 0000000..0719c79 --- /dev/null +++ b/forge/shared/painting.gradle @@ -0,0 +1,11 @@ +processResources { + from(project.ext.potteryAssets) { + include 'models/item/painting_table.json', 'textures/block/painting_table.png', 'textures/block/dyed_clay.png' + into 'assets/primalpottery' + } + from(project.ext.potteryAssets) { + include 'models/block/painting_table.json' + filter { line -> line.replace('primalpottery:block/painting_table_planks', 'primalpottery:block/painting_table') } + into 'assets/primalpottery' + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/CutleryModels.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/CutleryModels.java new file mode 100644 index 0000000..79e3633 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/CutleryModels.java @@ -0,0 +1,121 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +/** Tip at Z=0, grip toward +Z. The fork, spoon and knife use successive bands of cutlery.png. */ +final class CutleryModels { + static final DiningMesh FORK = fork(); + static final DiningMesh SPOON = spoon(); + static final DiningMesh KNIFE = knife(); + + private CutleryModels() {} + + // Heights at the left edge, center line and right edge of a transverse section. + private static final class Section { + final double z, left, right, leftY, centerY, rightY, thickness; + Section(double z, double left, double right, double leftY, double centerY, double rightY, double thickness) { + this.z = z; this.left = left; this.right = right; this.leftY = leftY; + this.centerY = centerY; this.rightY = rightY; this.thickness = thickness; + } + Point[] ring() { + double mid = (left + right) * 0.5; + return new Point[] { + new Point(left, leftY, z), new Point(mid, centerY, z), new Point(right, rightY, z), + new Point(right, rightY - thickness, z), new Point(mid, centerY - thickness, z), + new Point(left, leftY - thickness, z) + }; + } + } + + private static Section symmetric(double z, double radius, double edge, double middle, double thickness) { + return new Section(z, -radius, radius, edge, middle, edge, thickness); + } + + private static DiningMesh fork() { + DiningMesh mesh = new DiningMesh(); + // Slightly shorter outer tines follow the curve of the shoulder. + for (int i = 0; i < 3; i++) { + double x = (i - 1) * 0.49; + double tip = Math.abs(i - 1) * 0.13; + strip(mesh, 0, i * 0.37, i * 0.37 + 0.26, + new Section(tip, x - 0.048, x + 0.048, 0.09, 0.11, 0.09, 0.05), + new Section(0.68, x - 0.105, x + 0.105, 0.11, 0.15, 0.11, 0.08), + new Section(1.38, x - 0.135, x + 0.135, 0.23, 0.27, 0.23, 0.11)); + } + strip(mesh, 0, 0, 1, symmetric(1.38, 0.625, 0.23, 0.27, 0.11), + symmetric(1.67, 0.60, 0.26, 0.31, 0.13), symmetric(2.12, 0.26, 0.26, 0.32, 0.14), + symmetric(2.4, 0.13, 0.21, 0.26, 0.12), collar()); + grip(mesh, 0); + return mesh; + } + + private static DiningMesh spoon() { + DiningMesh mesh = new DiningMesh(); + // Raised lip and sunken center taper into the neck of the spoon. + strip(mesh, 1, 0, 1, symmetric(0.02, 0.14, 0.35, 0.34, 0.08), + symmetric(0.26, 0.51, 0.38, 0.23, 0.09), symmetric(0.73, 0.77, 0.40, 0.12, 0.10), + symmetric(1.22, 0.79, 0.41, 0.12, 0.10), symmetric(1.73, 0.61, 0.38, 0.17, 0.10), + symmetric(2.20, 0.28, 0.32, 0.24, 0.11), symmetric(2.43, 0.13, 0.24, 0.27, 0.12), + collar()); + grip(mesh, 1); + return mesh; + } + + private static DiningMesh knife() { + DiningMesh mesh = new DiningMesh(); + // The cutting edge faces the plate. A rounded nose and a deeper heel give the blade its sweep. + strip(mesh, 2, 0, 1, new Section(0.02, 0.15, 0.25, 0.15, 0.18, 0.18, 0.06), + new Section(0.32, -0.07, 0.35, 0.12, 0.25, 0.23, 0.07), + new Section(0.95, -0.39, 0.36, 0.10, 0.28, 0.26, 0.08), + new Section(2.75, -0.56, 0.32, 0.09, 0.29, 0.25, 0.08), + new Section(3.30, -0.53, 0.29, 0.10, 0.28, 0.24, 0.08), + new Section(3.47, -0.18, 0.25, 0.18, 0.26, 0.23, 0.12), collar()); + grip(mesh, 2); + return mesh; + } + + private static Section collar() { + return symmetric(3.68, 0.19, 0.22, 0.29, 0.13); + } + + private static void grip(DiningMesh mesh, int band) { + strip(mesh, band, 0, 1, collar(), symmetric(3.85, 0.28, 0.28, 0.39, 0.18), + symmetric(4.12, 0.27, 0.29, 0.40, 0.20), symmetric(4.65, 0.24, 0.28, 0.43, 0.19), + symmetric(6.6, 0.32, 0.28, 0.44, 0.21), symmetric(7.09, 0.32, 0.25, 0.39, 0.21), + symmetric(7.30, 0.20, 0.22, 0.32, 0.16)); + } + + private static void strip(DiningMesh mesh, int band, double leftU, double rightU, Section... sections) { + // Sample pixel centers inside each eight-pixel band of the 32px atlas. + float left = (float) ((2.5 + 10 * band + 7 * leftU) / 2); + float right = (float) ((2.5 + 10 * band + 7 * rightU) / 2); + float mid = (left + right) / 2; + float[] u = {left, mid, right, right, mid, left}; + Point[] start = sections[0].ring(); + cap(mesh, start, u, false); + for (int row = 1; row < sections.length; row++) { + Point[] end = sections[row].ring(); + for (int i = 0; i < start.length; i++) { + int j = (i + 1) % start.length; + face(mesh, start[i], end[i], end[j], start[j], u[i], u[i], u[j], u[j]); + } + start = end; + } + cap(mesh, start, u, true); + } + + private static void cap(DiningMesh mesh, Point[] ring, float[] u, boolean back) { + for (int i = 0; i < 2; i++) { + int a = i, b = i + 1, c = 4 - i, d = 5 - i; + if (back) face(mesh, ring[d], ring[c], ring[b], ring[a], u[d], u[c], u[b], u[a]); + else face(mesh, ring[a], ring[b], ring[c], ring[d], u[a], u[b], u[c], u[d]); + } + } + + private static void face(DiningMesh mesh, Point a, Point b, Point c, Point d, float... u) { + DiningMesh.Face face = new DiningMesh.Face(0xffffff, a, b, c, d); + for (int i = 0; i < 4; i++) { + face.u[i] = u[i] / 16; + face.v[i] = (float) ((0.5 + 31 * face.vertices[i].z / 7.30) / 32); + } + mesh.faces.add(face); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Diner.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Diner.java new file mode 100644 index 0000000..daac09a --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Diner.java @@ -0,0 +1,34 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +/** The shared clock for four bites, including the movement of both utensils. */ +public final class Diner { + public final int player, duration; + public final long start; + public final boolean cutlery, fromTable, left; + public Diner(int player, long start, int duration, boolean cutlery, boolean fromTable, boolean left) { + this.player = player; + this.start = start; + this.duration = Math.max(1, duration); + this.cutlery = cutlery; + this.fromTable = fromTable; + this.left = left; + } + public double cycle(double time) { + return Math.max(0, Math.min(Math.nextDown(4.0), 4 * (time - start) / duration)); + } + public long lastSwallow() { return start + (long) Math.ceil(3.79 * duration / 4); } + public boolean beat(long time, double fraction) { + int bite = (int) cycle(time); + return time - start == (long) Math.ceil((bite + fraction) * duration / 4); + } + public double lift(double time) { + double cycle = cycle(time); + double phase = cycle - (int) cycle; + if (cycle >= 3) phase = Math.min(.79, phase); + return smooth((phase - .42) / .31) * (1 - smooth((phase - .81) / .19)); + } + private static double smooth(double value) { + double t = Math.max(0, Math.min(1, value)); + return t * t * (3 - 2 * t); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningMesh.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningMesh.java new file mode 100644 index 0000000..cf228bd --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningMesh.java @@ -0,0 +1,30 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +import java.util.ArrayList; +import java.util.List; + +public final class DiningMesh { + public final List faces = new ArrayList<>(); + public static final class Face { + public final Point[] vertices; + public final Point normal; + public final float[] u = new float[4], v = new float[4]; + public final int rgb; + public Face(int rgb, Point a, Point b, Point c, Point d) { + vertices = new Point[]{a,b,c,d}; + normal = b.subtract(a).cross(c.subtract(a)).normalize(); + this.rgb = rgb; + } + } + void pixel(double x, double z, double right, double front, int rgb) { + double y = 1. / 16; + Point a = new Point(x, 0, z), b = new Point(right, 0, z), c = new Point(right, 0, front), d = new Point(x, 0, front); + Point e = a.add(0,y,0), f = b.add(0,y,0), g = c.add(0,y,0), h = d.add(0,y,0); + faces.add(new Face(rgb, a,b,c,d)); + faces.add(new Face(rgb, h,g,f,e)); + faces.add(new Face(rgb, e,f,b,a)); + faces.add(new Face(rgb, f,g,c,b)); + faces.add(new Face(rgb, g,h,d,c)); + faces.add(new Face(rgb, h,e,a,d)); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningScene.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningScene.java new file mode 100644 index 0000000..e20dcfb --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningScene.java @@ -0,0 +1,106 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +import java.util.Map; +import java.util.WeakHashMap; +import net.modcrafters.minecraft.primalpottery.pottery.PlatterSegments; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +/** All animation runs off the server start tick. Units are 32nds of a block in the native renderers. */ +public abstract class DiningScene { + private static final Map PIECES = new WeakHashMap<>(); + protected abstract boolean empty(S stack); + protected abstract boolean soup(S food); + protected abstract Point mouth(int player); + protected abstract int[] pixels(S item); + protected abstract void item(S stack, Point at, double width); + protected abstract void mesh(DiningMesh mesh, boolean food, Point at, double yaw, double pitch, double roll, double scale); + protected abstract void arm(int player, boolean right, Point grip); + + public void draw(PotteryLayout layout, ServingInventory table, double time) { + Pottery large = layout.at(0); + boolean platter = large != null && large.isPlatter(); + for (int slot = 0; slot < PotteryLayout.COUNT; slot++) { + Pottery dish = platter && slot < PlatterSegments.COUNT ? large : layout.at(slot); + if (dish == null || !dish.isPlate()) continue; + S food = table.serving(slot); + Diner diner = table.diner(slot); + if (diner != null && time - diner.start > diner.duration + 3) diner = null; + boolean stew = !empty(food) && soup(food); + if (TableSetting.edge(slot) && !empty(table.utensil(slot))) { + setting(slot, diner != null && diner.fromTable, stew); + } + if (empty(food)) continue; + Point base = new Point(TableSetting.servingX(dish, slot) * 32, dish.height() + .06, TableSetting.servingZ(dish, slot) * 32); + double width = TableSetting.foodWidth(dish, slot) * 32; + Point mouth = diner == null ? null : mouth(diner.player); + if (mouth != null && meal(diner, time, base, mouth, width, food, stew)) continue; + item(food, base.add(0, width / 32, 0), width); + } + } + + private void setting(int slot, boolean inUse, boolean soup) { + int dx = TableSetting.dx(slot), dz = TableSetting.dz(slot); + Point fork = new Point(TableSetting.utensilX(slot, true) * 32 - 3.4 * dx, .13, TableSetting.utensilZ(slot, true) * 32 - 3.4 * dz); + Point right = new Point(TableSetting.utensilX(slot, false) * 32 - 3.4 * dx, .13, TableSetting.utensilZ(slot, false) * 32 - 3.4 * dz); + double yaw = Math.toDegrees(Math.atan2(dx, dz)); + if (!inUse || soup) { + mesh(CutleryModels.FORK, false, fork, yaw, 0, 0, .93); + mesh(CutleryModels.KNIFE, false, right.add(-.68 * dz, 0, .68 * dx), yaw, 0, 0, .93); + } + if (!inUse || !soup) mesh(CutleryModels.SPOON, false, right.add(.68 * dz, 0, -.68 * dx), yaw, 0, 0, .93); + } + + private boolean meal(Diner diner, double time, Point base, Point mouth, double width, S food, boolean soup) { + double cycle = diner.cycle(time); + double lift = diner.lift(time); + if (!diner.cutlery) { + Point raised = base.lerp(mouth, .35 + .62 * Math.abs(Math.sin(cycle * Math.PI))); + item(food, raised, width); + arm(diner.player, !diner.left, raised); + return true; + } + int bite = (int) cycle, next = Math.min(3, bite + 1); + double phase = bite == 3 ? Math.min(.79, cycle - bite) : cycle - bite; + double returning = smooth((phase - .81) / .19); + double yaw = Math.toDegrees(Math.atan2(mouth.x - base.x, mouth.z - base.z)); + double side = diner.left ? -1 : 1; + ServingPieces pieces = soup ? ServingPieces.EMPTY : PIECES.computeIfAbsent(diner, + d -> new ServingPieces(pixels(food), mouth.subtract(base), side)); + Point contact = base.add(pieces.centers[bite].scale(width)); + Point fork = contact.lerp(base.add(pieces.centers[next].scale(width)), returning).lerp(mouth, lift) + .add(0, 2.4 * Math.sin(lift * Math.PI) + 1.2 * (1 - smooth(phase / .17) + smooth((phase - .88) / .12)), 0); + if (pieces.available) { + for (int i = bite; i < 4; i++) { + if (i == bite && bite != 3 && phase >= .79) continue; + Point shift = i == bite ? fork.subtract(contact).scale(smooth((phase - .32) / .1)) : Point.ZERO; + mesh(pieces.meshes[i], true, base.add(shift), 0, 0, 0, width); + } + } + held(soup ? CutleryModels.SPOON : CutleryModels.FORK, diner, !diner.left, fork, yaw + side * (22 + 32 * lift), -21 + 25 * lift, 0); + if (!soup) { + double stroke = phase / .42; + double saw = bite < 3 && stroke < 1 ? Math.sin(stroke * Math.PI * 4) * Math.sin(stroke * Math.PI) : 0; + double radians = Math.toRadians(yaw); + Point edge = pieces.available ? base.add(pieces.edges[bite].lerp(pieces.edges[next], returning).scale(width)) + : base.add(side * .55 * Math.cos(radians), 0, -side * .55 * Math.sin(radians)); + Point knife = edge.add(saw * Math.sin(radians), .28 + 1.8 * lift, saw * Math.cos(radians)); + held(CutleryModels.KNIFE, diner, diner.left, knife, yaw - side * 24, -17, 68); + } + return pieces.available; + } + + private void held(DiningMesh tool, Diner diner, boolean right, Point tip, double yaw, double pitch, double roll) { + mesh(tool, false, tip, yaw, pitch, roll, 2.5); + // Rotate the grip point with exactly the same Z-X-Y rotations used to submit the mesh. + double a = Math.toRadians(yaw), b = Math.toRadians(pitch), c = Math.toRadians(roll); + double x = -.25 * Math.sin(c), y = .25 * Math.cos(c), z = 6.55; + double gy = y * Math.cos(b) - z * Math.sin(b), gz = z * Math.cos(b) + y * Math.sin(b); + arm(diner.player, right, tip.add(2.5 * (x * Math.cos(a) + gz * Math.sin(a)), + 2.5 * gy - 1.35, 2.5 * (gz * Math.cos(a) - x * Math.sin(a)))); + } + private static double smooth(double t) { + t = Math.max(0, Math.min(1, t)); + return t * t * (3 - 2 * t); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningUse.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningUse.java new file mode 100644 index 0000000..a96c02b --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/DiningUse.java @@ -0,0 +1,112 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +/** Routes an interaction to an individual serving or utensil setting. Only the server moves stacks. */ +public abstract class DiningUse { + protected final ServingInventory table; + private final S empty; + protected DiningUse(ServingInventory table, S empty) { this.table = table; this.empty = empty; } + protected abstract boolean server(); + protected abstract boolean empty(S stack); + protected abstract boolean tool(S stack); + protected abstract boolean displayable(S stack); + protected abstract boolean sneaking(); + protected abstract H main(); + protected abstract H off(); + protected abstract S held(H hand); + protected abstract S takeOne(H hand); + protected abstract void give(H hand, S stack); + protected abstract void stow(S stack); + protected abstract boolean eat(int dish, int serving, H hand); + protected abstract void takeDish(int dish, H hand); + protected abstract void sync(); + + public boolean use(PotteryLayout layout, H hand, double x, double y, double z) { + H toolHand = cutleryHand(); + int setting = TableSetting.settingAt(x, y, z, layout); + if (useSetting(setting, hand, toolHand)) return true; + + int slot = layout.hit(x, z); + Pottery dish = layout.at(slot); + if (dish == null || !dish.isPlate()) return false; + int serving = TableSetting.serving(dish, slot, x, z); + if (table.diner(serving) != null) return true; + S food = table.serving(serving); + if (sneaking()) return pickUp(slot, dish, serving, food, hand); + if (toolHand != null && (!empty(food) || tool(held(hand)) || empty(held(main())))) { + return useCutlery(slot, dish, serving, food, toolHand); + } + if (!empty(food) && empty(held(hand))) return eatOrTake(slot, serving, food, hand); + return offerItem(serving, food, hand); + } + + private H cutleryHand() { + if (tool(held(main()))) return main(); + return tool(held(off())) ? off() : null; + } + + private boolean useSetting(int slot, H hand, H toolHand) { + if (slot < 0) return false; + if (toolHand != null) return placeTool(slot, toolHand); + if (empty(table.utensil(slot)) || !empty(held(hand))) return false; + if (server()) { + give(hand, table.utensil(slot)); + table.placeTool(slot, empty); + sync(); + } + return true; + } + + private boolean pickUp(int slot, Pottery dish, int serving, S shown, H hand) { + if (!empty(shown)) { + if (server()) stowServing(serving, shown); + return true; + } + if (table.occupied(slot, dish)) return true; + if (hand != main() || !empty(held(hand))) return false; + if (server()) takeDish(slot, hand); + return true; + } + + private boolean useCutlery(int slot, Pottery dish, int serving, S shown, H hand) { + if (empty(shown)) return dish.isPlatter() || placeTool(slot, hand); + if (!eat(slot, serving, hand) && server()) stowServing(serving, shown); + return true; + } + + private void stowServing(int serving, S shown) { + table.serve(serving, empty); + stow(shown); + sync(); + } + + private boolean eatOrTake(int slot, int serving, S shown, H hand) { + if (!eat(slot, serving, hand) && server()) { + table.serve(serving, empty); + give(hand, shown); + sync(); + } + return true; + } + + private boolean offerItem(int serving, S shown, H hand) { + H source = empty(held(hand)) && empty(held(main())) && displayable(held(off())) ? off() : hand; + if (empty(held(source))) return true; + if (!displayable(held(source))) return false; + if (empty(shown) && server()) { + table.serve(serving, takeOne(source)); + sync(); + } + return true; + } + + private boolean placeTool(int slot, H hand) { + if (TableSetting.edge(slot) && empty(table.utensil(slot)) && server()) { + table.placeTool(slot, takeOne(hand)); + sync(); + } + return true; + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Point.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Point.java new file mode 100644 index 0000000..af9190a --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/Point.java @@ -0,0 +1,18 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +/** A position in the table model, measured in 32nds of a block. */ +public final class Point { + public static final Point ZERO = new Point(0, 0, 0); + public final double x, y, z; + public Point(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } + public Point add(double x, double y, double z) { return new Point(this.x + x, this.y + y, this.z + z); } + public Point add(Point p) { return add(p.x, p.y, p.z); } + public Point subtract(Point p) { return add(-p.x, -p.y, -p.z); } + public Point scale(double s) { return new Point(x * s, y * s, z * s); } + public Point lerp(Point p, double t) { return add((p.x - x) * t, (p.y - y) * t, (p.z - z) * t); } + public Point cross(Point p) { return new Point(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); } + public Point normalize() { + double n = Math.sqrt(x*x + y*y + z*z); + return n > 0 ? scale(1 / n) : ZERO; + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingInventory.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingInventory.java new file mode 100644 index 0000000..283816a --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingInventory.java @@ -0,0 +1,80 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.PlatterSegments; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +/** Empty pots allocate no stack or diner arrays. World rendering checks one counter per tile. */ +public abstract class ServingInventory { + private List servings, cutlery; + private Diner[] diners; + private int displayedStacks; + private final S empty; + + protected ServingInventory(S empty) { this.empty = empty; } + protected abstract boolean empty(S stack); + + public S serving(int slot) { return servings == null ? empty : servings.get(slot); } + public S utensil(int slot) { return cutlery == null ? empty : cutlery.get(slot); } + public Diner diner(int slot) { return diners == null ? null : diners[slot]; } + public boolean seated(int player) { + if (diners != null) for (Diner diner : diners) if (diner != null && diner.player == player) return true; + return false; + } + public void setDiner(int slot, Diner diner) { + if (diners == null) { + if (diner == null) return; + diners = new Diner[PotteryLayout.COUNT]; + } + diners[slot] = diner; + } + public void placeTool(int slot, S stack) { cutlery = replace(cutlery, slot, stack); } + public void serve(int slot, S stack) { servings = replace(servings, slot, stack); } + private List replace(List slots, int slot, S stack) { + boolean present = !empty(stack); + if (slots == null) { + if (!present) return null; + slots = new ArrayList<>(Collections.nCopies(PotteryLayout.COUNT, empty)); + } + boolean wasPresent = !empty(slots.set(slot, stack)); + if (wasPresent != present) displayedStacks += present ? 1 : -1; + return slots; + } + protected void clear() { + servings = null; + cutlery = null; + diners = null; + displayedStacks = 0; + } + public boolean hasVisuals() { return displayedStacks != 0; } + + public boolean occupied(int slot, Pottery dish) { + if (!dish.isPlatter()) return !empty(serving(slot)); + for (int i = 0; i < PlatterSegments.COUNT; i++) if (!empty(serving(i))) return true; + return false; + } + public List remove(int slot, Pottery dish) { + List drops = new ArrayList<>(); + if (dish == null || !dish.isPlate()) return drops; + collect(drops, utensil(slot)); + placeTool(slot, empty); + int first = dish.isPlatter() ? 0 : slot; + int end = dish.isPlatter() ? PlatterSegments.COUNT : slot + 1; + for (int i = first; i < end; i++) { + collect(drops, serving(i)); + serve(i, empty); + setDiner(i, null); + } + return drops; + } + public List drops() { + List drops = new ArrayList<>(displayedStacks); + if (servings != null) for (S stack : servings) collect(drops, stack); + if (cutlery != null) for (S stack : cutlery) collect(drops, stack); + return drops; + } + private void collect(List drops, S stack) { if (!empty(stack)) drops.add(stack); } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingPieces.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingPieces.java new file mode 100644 index 0000000..9624294 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/ServingPieces.java @@ -0,0 +1,75 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +import java.util.Arrays; + +final class ServingPieces { + static final ServingPieces EMPTY = new ServingPieces(); + final DiningMesh[] meshes = new DiningMesh[4]; + final Point[] centers = new Point[4]; + final Point[] edges = new Point[4]; + boolean available; + + private ServingPieces() { + Arrays.fill(centers, Point.ZERO); + Arrays.fill(edges, Point.ZERO); + } + + ServingPieces(int[] pixels, Point towardDiner, double handSide) { + this(); + if (pixels == null) return; + boolean acrossX = Math.abs(towardDiner.z) >= Math.abs(towardDiner.x); + boolean reverse = handSide * (acrossX ? towardDiner.z : -towardDiner.x) > 0; + int[] counts = new int[16]; + int total = 0; + for (int i = 0; i < pixels.length; i++) { + if ((pixels[i] >>> 24) < 32) continue; + int axis = acrossX ? 15 - i % 16 : i / 16; + counts[reverse ? 15 - axis : axis]++; + total++; + } + if (total == 0) return; + double[] cuts = cutPositions(counts, total); + for (int bite = 0; bite < 4; bite++) { + meshes[bite] = new DiningMesh(); + double lo = reverse ? 16 - cuts[bite + 1] : cuts[bite]; + double hi = reverse ? 16 - cuts[bite] : cuts[bite + 1]; + Point sum = Point.ZERO; + double area = 0; + for (int i = 0; i < pixels.length; i++) { + if ((pixels[i] >>> 24) < 32) continue; + // FIXED displays a generated item from its back, mirrored across X. + int x = 15 - i % 16, z = i / 16; + int axis = acrossX ? x : z; + double start = Math.max(lo, axis), end = Math.min(hi, axis + 1); + if (end <= start) continue; + double x0 = unit(acrossX ? start : x), x1 = unit(acrossX ? end : x + 1); + double z0 = unit(acrossX ? z : start), z1 = unit(acrossX ? z + 1 : end); + meshes[bite].pixel(x0, z0, x1, z1, pixels[i] & 0xffffff); + double weight = end - start; + sum = sum.add((x0 + x1) * 0.5 * weight, 0, (z0 + z1) * 0.5 * weight); + area += weight; + } + Point center = sum.scale(1 / area); + centers[bite] = center; + double edge = unit(reverse ? lo : hi); + edges[bite] = acrossX ? new Point(edge, 0, center.z) : new Point(center.x, 0, edge); + } + available = true; + } + + private static double unit(double pixel) { + return pixel / 16 - 0.5; + } + + private static double[] cutPositions(int[] counts, int total) { + double[] cuts = new double[4 + 1]; + cuts[4] = counts.length; + int column = 0, before = 0; + for (int bite = 1; bite < 4; bite++) { + double target = (double) total * bite / 4; + while (before + counts[column] < target) before += counts[column++]; + cuts[bite] = column + (target - before) / counts[column]; + } + return cuts; + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/TableSetting.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/TableSetting.java new file mode 100644 index 0000000..329b35e --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/dining/TableSetting.java @@ -0,0 +1,54 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +import net.modcrafters.minecraft.primalpottery.pottery.PlatterSegments; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +/** Positions in block coordinates, shared by rendering and selection. */ +public final class TableSetting { + private static final int[] DX = {0, 1, 0, -1}, DZ = {-1, 0, 1, 0}; + + public static boolean edge(int slot) { return slot >= 4 && slot < 8; } + public static int dx(int slot) { return DX[slot - 4]; } + public static int dz(int slot) { return DZ[slot - 4]; } + public static double utensilX(int slot, boolean fork) { + return .5 + dx(slot) * .3825 + dz(slot) * (fork ? -.205 : .217); + } + public static double utensilZ(int slot, boolean fork) { + return .5 + dz(slot) * .3825 - dx(slot) * (fork ? -.205 : .217); + } + public static int settingAt(double x, double y, double z, PotteryLayout layout) { + if (y < -.0001 || y > .0401) return -1; + for (int slot = 4; slot < 8; slot++) { + if (layout.at(slot) == null) continue; + if (onStrip(slot, x, z, true) || onStrip(slot, x, z, false)) return slot; + } + return -1; + } + private static boolean onStrip(int slot, double x, double z, boolean fork) { + return Math.abs(x - utensilX(slot, fork)) <= halfX(slot, fork) + 1e-6 + && Math.abs(z - utensilZ(slot, fork)) <= halfZ(slot, fork) + 1e-6; + } + public static double halfX(int slot, boolean fork) { + return dx(slot) == 0 ? (fork ? .028 : .047) : .1125; + } + public static double halfZ(int slot, boolean fork) { + return dz(slot) == 0 ? (fork ? .028 : .047) : .1125; + } + public static int serving(Pottery dish, int slot, double x, double z) { + return dish.isPlatter() ? PlatterSegments.at(x - .5, z - .5) : slot; + } + public static double servingX(Pottery dish, int serving) { + return dish.isPlatter() ? .5 + Math.cos(PlatterSegments.centerAngle(serving)) * dish.widestRadius() * .6 / 32 + : PotteryLayout.centerX(serving, dish); + } + public static double servingZ(Pottery dish, int serving) { + return dish.isPlatter() ? .5 + Math.sin(PlatterSegments.centerAngle(serving)) * dish.widestRadius() * .6 / 32 + : PotteryLayout.centerZ(serving, dish); + } + public static double foodWidth(Pottery dish, int serving) { + return dish.isPlatter() ? dish.widestRadius() * .46 / 32 + : dish.discs().get(0).radius() * 1.4 * PotteryLayout.scale(serving, dish) / 32; + } + private TableSetting() {} +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/IconPixels.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/IconPixels.java new file mode 100644 index 0000000..17ae929 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/IconPixels.java @@ -0,0 +1,59 @@ +package net.modcrafters.minecraft.primalpottery.painting; + +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; + +/** Composites the front faces of a flat item model and quantizes them to the tank palette. */ +public final class IconPixels { + private IconPixels() {} + + public static boolean spriteVertex(boolean frontOrBack, boolean south, float x, float y, float z) { + if (!frontOrBack) return z >= 7.5f/16 && z <= 8.5f/16; + return (x == 0 || x == 1) && (y == 0 || y == 1) && z == (south ? 8.5f : 7.5f)/16; + } + public static void sampleFrame(int[] pixels, java.util.function.IntBinaryOperator argbAt, + int left, int top, int width, int height, int tint) { + for (int i = 0; i < pixels.length; i++) { + int x = left + (2 * (i % 16) + 1) * width / 32, y = top + (2 * (i / 16) + 1) * height / 32; + pixels[i] = composite(pixels[i], argbAt.applyAsInt(x, y), tint); + } + } + + static int composite(int back, int front, int tint) { + int alpha = (front >>> 24) * (tint >>> 24) / 255; + if (alpha == 0) return back; + int behind = (back >>> 24) * (255 - alpha) / 255; + int combined = alpha + behind; + int result = combined << 24; + for (int shift = 0; shift <= 16; shift += 8) { + int ink = (front >>> shift & 255) * (tint >>> shift & 255) / 255; + result |= ((ink * alpha + (back >>> shift & 255) * behind) / combined) << shift; + } + return result; + } + + public static String quantize(int[] pixels) { + StringBuilder paint = new StringBuilder(FacePaint.CELLS); + boolean visible = false; + for (int argb : pixels) { + if ((argb >>> 24) == 0) { + paint.append('.'); + continue; + } + visible = true; + int closest = 0, bestDistance = Integer.MAX_VALUE; + for (int dye = 0; dye < FacePaint.COLORS; dye++) { + int rgb = Pigments.ink(dye); + int r = (argb >>> 16 & 255) - (rgb >>> 16 & 255); + int g = (argb >>> 8 & 255) - (rgb >>> 8 & 255); + int b = (argb & 255) - (rgb & 255); + int distance = 3*r*r + 6*g*g + 2*b*b; + if (distance < bestDistance) { + bestDistance = distance; + closest = dye; + } + } + paint.append((char) ('A' + closest)); + } + return visible ? paint.toString() : ""; + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrush.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrush.java new file mode 100644 index 0000000..910dc1e --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrush.java @@ -0,0 +1,43 @@ +package net.modcrafters.minecraft.primalpottery.painting; + +import java.util.ArrayDeque; +import java.util.Deque; +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** One brush history belongs to one open menu. All mutations are made on the server thread. */ +public final class PaintBrush { + public static final int UNDO = (FacePaint.COLORS + 1) * FacePaint.CELLS; + private static final class Edit { + final int cell, previous; + Edit(int cell, int previous) { this.cell = cell; this.previous = previous; } + } + private final Deque history = new ArrayDeque<>(); + public static int stroke(int cell, int color) { return (color + 1) * FacePaint.CELLS + cell; } + private static int pigment(int color) { + if (color < FacePaint.COLORS) return color; + if (color < 18) return 0; + return color < 20 ? 4 : 13; + } + public int undoCost() { return history.isEmpty() ? 0 : pigment(history.peekLast().previous) + 2; } + + public Pottery apply(Pottery pot, int action, PigmentTanks tanks, PigmentTanks.Stock stock) { + if (action < 0 || action > UNDO || pot == null) return null; + Edit last = history.peekLast(); + if (action == UNDO && last == null) return null; + int cell = action == UNDO ? last.cell : action % FacePaint.CELLS; + int color = action == UNDO ? last.previous : action / FacePaint.CELLS - 1; + if (cell >= pot.paintColumns() * FacePaint.SIDE || color == pot.paint().color(cell)) return null; + if (color != FacePaint.ERASE) { + int[] cost = new int[FacePaint.COLORS]; + cost[pigment(color)] = 1; + if (tanks.spend(cost, stock) >= 0) return null; + } + if (action == UNDO) history.removeLast(); + else { + if (history.size() >= FacePaint.CELLS) history.removeFirst(); + history.addLast(new Edit(cell, pot.paint().color(cell))); + } + return pot.withPaint(pot.paint().with(cell, color)); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintPanel.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintPanel.java new file mode 100644 index 0000000..174a4e1 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PaintPanel.java @@ -0,0 +1,92 @@ +package net.modcrafters.minecraft.primalpottery.painting; + +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Pixels and hit tests are in GUI units, relative to the frame. */ +public final class PaintPanel { + public interface View { + Pottery profile(); + int tint(); + int volume(int dye); + int count(int dye); + boolean canUndo(); + } + public interface Canvas { + void rect(int x, int y, int w, int h, int color); + void text(String label, int x, int y, float scale); + void preview(Pottery pot, float yaw, float tilt); + void stroke(int action); + } + + public static final int WIDTH = 248, HEIGHT = 182; + private static final int PIXEL = 6, Y = 26, TANK = 13, SWATCH = 12, STRIDE = 14; + private int selected, columns = FacePaint.SIDE, last = -1; + private float yaw, tilt = 30; + private boolean turning; + private double lastX, lastY; + private final View view; + private final Canvas canvas; + + public PaintPanel(View view, Canvas canvas) { this.view = view; this.canvas = canvas; } + public int selected() { return selected; } + public void erase() { selected = FacePaint.ERASE; } + private int gridX() { return 10 + (FacePaint.SIDE - columns) * PIXEL / 2; } + private int cell(int x, int y) { return columns == FacePaint.SIDE ? y * FacePaint.SIDE + x : x * FacePaint.SIDE + y; } + public int tank(double x, double y) { + int dx = (int) Math.floor(x) - TANK; + return dx >= 0 && dx / STRIDE < 16 && dx % STRIDE < SWATCH && y >= 127 && y < 148 ? dx / STRIDE : -1; + } + + public void draw() { + canvas.rect(0,0,WIDTH,HEIGHT,0xff393330); + canvas.rect(1,1,WIDTH-3,HEIGHT-3,0xfff4efeb); + canvas.rect(3,3,WIDTH-6,HEIGHT-6,0xffc9c3be); + canvas.rect(8,5,18,18,0xff665a51); + canvas.rect(9,6,16,16,0xff9b9087); + Pottery pot = view.profile(); + int next = pot == null ? 16 : pot.paintColumns(); + if (next != columns) { columns = next; tilt = columns == 16 ? 30 : 65; } + FacePaint pattern = pot == null ? FacePaint.EMPTY : pot.paint(); + int clay = view.tint() < 0 ? 0x92583e : view.tint(); + canvas.rect(gridX()-1, Y-1, columns*PIXEL+2, 98, 0xff594236); + for (int row = 0; row < 16; row++) for (int col = 0; col < columns; col++) { + int color = pattern.color(cell(col,row)); + canvas.rect(gridX()+col*PIXEL,Y+row*PIXEL,5,5,0xff000000 | (color < 0 ? clay : Pigments.ink(color))); + } + canvas.rect(114,25,124,98,0xff916953); + if (pot != null) canvas.preview(pot, yaw, tilt); + for (int color = 0; color < FacePaint.COLORS; color++) { + int x = TANK + STRIDE * color; + canvas.rect(x,127,SWATCH,SWATCH, selected == color ? 0xffffffff : 0xff695e56); + canvas.rect(x+1,128,SWATCH-2,SWATCH-2,0xff000000 | Pigments.ink(color)); + canvas.rect(x,140,SWATCH,2,0xff40352d); + canvas.rect(x,140,(view.volume(color)*SWATCH+99)/100,2,0xfff3dec1); + canvas.text("+" + view.count(color), x, 144, .65F); + } + } + + public boolean press(double x, double y, int button) { + last = -1; + if (button == 0 && x >= 114 && x < 238 && y >= 25 && y < 123) { + turning = true; lastX = x; lastY = y; return true; + } + int dye = tank(x,y); + if (button == 0 && dye >= 0) { selected = dye; return true; } + return drag(x,y,button); + } + public boolean drag(double x, double y, int button) { + if (turning) { + yaw += (float) (x - lastX) * 2; + tilt = Math.max(5, Math.min(85, tilt + (float)(y - lastY))); + lastX = x; lastY = y; + return true; + } + if (x < gridX() || x >= gridX()+columns*PIXEL || y < Y || y >= Y+96 || button < 0 || button > 1) return false; + int target = cell((int)(x-gridX())/PIXEL, (int)(y-Y)/PIXEL); + if (target != last && view.profile() != null) canvas.stroke(PaintBrush.stroke(target, button == 1 ? FacePaint.ERASE : selected)); + last = target; + return true; + } + public void release() { turning = false; last = -1; } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PigmentTanks.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PigmentTanks.java new file mode 100644 index 0000000..a938e62 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/PigmentTanks.java @@ -0,0 +1,54 @@ +package net.modcrafters.minecraft.primalpottery.painting; + +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; + +/** Each physical table owns its paint, each viewer supplies their own dye. */ +public final class PigmentTanks { + public interface Stock { + int count(int color); + void consume(int color, int count); + } + public interface Shortage { + void missing(int color, int volume); + } + + public static final int REFILL = 100; + private final int[] amounts = new int[FacePaint.COLORS]; + public int get(int color) { return amounts[color]; } + public void set(int color, int value) { amounts[color] = Math.max(0, Math.min(REFILL, value)); } + + /** Plan all refills before changing either inventory. Returns the first unavailable pigment or -1. */ + public int spend(int[] cost, Stock stock) { + return spend(cost, stock, (color, volume) -> {}); + } + + private int spend(int[] cost, Stock stock, Shortage onShortage) { + int firstShortage = -1; + int[] refills = new int[amounts.length]; + for (int i = 0; i < amounts.length; i++) { + int deficit = cost[i] - amounts[i]; + if (deficit <= 0) continue; + refills[i] = (deficit + REFILL - 1) / REFILL; + int available = stock.count(i); + if (refills[i] > available) { + if (firstShortage == -1) firstShortage = i; + onShortage.missing(i, deficit - REFILL * available); + } + } + if (firstShortage != -1) return firstShortage; + for (int i = 0; i < amounts.length; i++) { + if (refills[i] != 0) stock.consume(i, refills[i]); + amounts[i] += refills[i] * REFILL - cost[i]; + } + return -1; + } + + public int stamp(FacePaint before, FacePaint after, Stock stock, Shortage onShortage) { + int[] cost = new int[amounts.length]; + for (int i = 0; i < FacePaint.CELLS; i++) { + int color = after.color(i); + if (color != FacePaint.ERASE && color != before.color(i)) cost[color]++; + } + return spend(cost, stock, onShortage); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/Pigments.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/Pigments.java new file mode 100644 index 0000000..e2ddc19 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/painting/Pigments.java @@ -0,0 +1,19 @@ +package net.modcrafters.minecraft.primalpottery.painting; + +import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; + +/** Vanilla dyes in wool-colour order on both Forge versions. */ +public final class Pigments { + public static final String[] NAMES = {"white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", + "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black"}; + private static final int[] GLAZE = {0xffffff,0xff5500,0xff2bd6,0x2ecfff,0xffea00,0x7dff1a,0xff5c9d,0x5a5a5a, + 0xc6c6c6,0x00e5e5,0xc43bff,0x2f4bff,0xc46a28,0x3dcc12,0xff2a2a,0x1a1a1a}; + private static final int[] INK = {0xf9fffe,0xf9801d,0xc74ebd,0x3ab3da,0xfed83d,0x80c71f,0xf38baa,0x474f52, + 0x9d9d97,0x169c9c,0x8932b8,0x3c44aa,0x835432,0x5e7c16,0xb02e26,0x1d1d21}; + public static int clayTint(String name) { + for (int i = 0; i < NAMES.length; i++) if (NAMES[i].equals(name)) return GLAZE[i]; + return -1; + } + public static int ink(int color) { return color < 16 ? INK[color] : FacePaint.flowerRgb(color); } + private Pigments() {} +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselMesh.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselMesh.java new file mode 100644 index 0000000..8042709 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselMesh.java @@ -0,0 +1,112 @@ +package net.modcrafters.minecraft.primalpottery.vessel; + +import java.util.ArrayList; +import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; + +/** Bakes a fitted lid, the fill line and the soil surface into the same local space as the pot. */ +public abstract class VesselMesh { + protected final List faces = new ArrayList<>(); + protected final double x, z, scale; + protected final Pottery pot; + private final int stride; + + protected VesselMesh(Pottery pot, int slot, int stride) { + this.pot = pot; + this.stride = stride; + x = PotteryLayout.centerX(slot, pot); + z = PotteryLayout.centerZ(slot, pot); + scale = PotteryLayout.scale(slot, pot) / 32; + } + + protected abstract float u(S sprite, double pixel); + protected abstract float v(S sprite, double pixel); + protected abstract Q makeQuad(int[] vertices, S sprite, double nx, double ny, double nz); + + protected void lid(S sprite, int color, boolean beside) { + Pottery.Cover cover = pot.cover(); + if (cover == null) return; + double bottom = beside ? 0 : cover.top() + cover.layer(); + cylinder(sprite, color, bottom, Pottery.PIXEL, cover.radius()); + cylinder(sprite, color, bottom + Pottery.PIXEL, Pottery.PIXEL, Math.min(Pottery.PIXEL, cover.radius() / 2)); + } + + protected double surface(S sprite, int color, int amount, boolean soil) { + double height = VesselRules.surface(pot, amount, soil); + if (height <= 0) return 0; + double radius = PotteryProfile.sample(PotteryProfile.cavity(pot.discs()), height); + cap(sprite, color, height, Math.max(0, radius - (soil ? 0 : .05)), true); + return height * scale; + } + + protected double radiusAt(double modelHeight) { + return PotteryProfile.sample(PotteryProfile.cavity(pot.discs()), modelHeight / scale); + } + + private void cylinder(S sprite, int color, double y, double h, double r) { + cap(sprite, color, y + h, r, true); + cap(sprite, color, y, r, false); + for (int i = 0; i < 8; i++) { + double[] a = point(i, y, r), b = point(i, y + h, r), c = point(i + 1, y + h, r), d = point(i + 1, y, r); + face(sprite, color, a, b, c, d, false); + } + } + + private void cap(S sprite, int color, double y, double r, boolean up) { + for (int i = 0; i < 8; i += 2) { + double[] center = {0, y, 0}, a = point(i, y, r), b = point(i + 1, y, r), c = point(i + 2, y, r); + if (up) face(sprite, color, center, c, b, a, true); + else face(sprite, color, center, a, b, c, true); + } + } + + private static double[] point(int i, double y, double r) { + double angle = (i + .5) * Math.PI / 4; + return new double[]{r * Math.cos(angle), y, r * Math.sin(angle)}; + } + + private void face(S sprite, int color, double[] a, double[] b, double[] c, double[] d, boolean planar) { + double ax = c[0] - a[0], ay = c[1] - a[1], az = c[2] - a[2]; + double bx = d[0] - b[0], by = d[1] - b[1], bz = d[2] - b[2]; + double nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx; + double norm = Math.sqrt(nx * nx + ny * ny + nz * nz); + if (norm < 1e-8) return; + int normal = pack(nx / norm) | pack(ny / norm) << 8 | pack(nz / norm) << 16; + int[] data = new int[stride * 4]; + double[][] corners = {a, b, c, d}; + for (int i = 0; i < 4; i++) { + int k = i * stride; + double[] from = corners[i]; + data[k] = Float.floatToRawIntBits((float) (x + from[0] * scale)); + data[k + 1] = Float.floatToRawIntBits((float) (from[1] * scale)); + data[k + 2] = Float.floatToRawIntBits((float) (z + from[2] * scale)); + data[k + 3] = abgr(color); + double texU = planar ? Math.max(0, Math.min(16, 8 + from[0] / 2)) : (i >= 2 ? 16 : 0); + double texV = planar ? Math.max(0, Math.min(16, 8 + from[2] / 2)) : (i == 0 || i == 3 ? 16 : 0); + data[k + 4] = Float.floatToRawIntBits(u(sprite, texU)); + data[k + 5] = Float.floatToRawIntBits(v(sprite, texV)); + data[k + stride - 1] = normal; + } + faces.add(makeQuad(data, sprite, nx, ny, nz)); + } + + protected static int abgr(int rgb) { + return 0xff000000 | (rgb & 255) << 16 | (rgb & 0x00ff00) | ((rgb >>> 16) & 255); + } + private static int pack(double value) { return ((int) Math.round(value * 127)) & 255; } + + /** Translate a native plant-model quad and resolve its tint while preserving UVs, lights and normals. */ + protected static int[] transform(int[] data, double x, double y, double z, double size, int tint) { + data = data.clone(); + int stride = data.length / 4; + for (int i = 0; i < data.length; i += stride) { + data[i] = Float.floatToRawIntBits((float) (x + size * Float.intBitsToFloat(data[i]))); + data[i + 1] = Float.floatToRawIntBits((float) (y + size * Float.intBitsToFloat(data[i + 1]))); + data[i + 2] = Float.floatToRawIntBits((float) (z + size * Float.intBitsToFloat(data[i + 2]))); + if (tint != -1) data[i + 3] = abgr(tint); + } + return data; + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselPreviewFrame.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselPreviewFrame.java new file mode 100644 index 0000000..0e6a5bd --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselPreviewFrame.java @@ -0,0 +1,32 @@ +package net.modcrafters.minecraft.primalpottery.vessel; + +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Fits the native item model and its detached lid into a 152 by 96 pixel preview. + * Both Forge targets ship the same GUI transform (30 degree tilt, 1.75 scale, 4 pixels up). */ +public final class VesselPreviewFrame { + private static final double PIXELS_PER_UNIT = 16 * 1.75 / 32; + private static final double TILT = Math.toRadians(30); + private final double scale, originY, radius, lidRadius, separation; + + public VesselPreviewFrame(Pottery pot, double extraRadius, double extraHeight, boolean planted) { + Pottery.Cover cover = planted ? null : pot.cover(); + radius = Math.max(pot.widestRadius(), extraRadius); + lidRadius = cover == null ? 0 : cover.radius(); + separation = cover == null ? 0 : radius + lidRadius + Math.max(2, radius * .2); + double width = cover == null ? 2 * radius : radius + separation + lidRadius; + double height = Math.max(extraHeight, pot.height() + (cover == null ? 0 : cover.layer() + 2 * Pottery.PIXEL)); + double projected = Math.cos(TILT) * height + 2 * Math.max(radius, lidRadius) * Math.sin(TILT); + scale = Math.min(144 / Math.max(1, width * PIXELS_PER_UNIT), 88 / Math.max(1, projected * PIXELS_PER_UNIT)); + double center = 4 - (height / 2 - 16) * Math.cos(TILT) * PIXELS_PER_UNIT; + originY = 74 - center * scale; + } + + public float scale() { return (float) scale; } + public float y() { return (float) originY; } + public float x(boolean beside, boolean lid) { + double center = beside ? (separation + lidRadius - radius) / 2 : 0; + double modelX = lid ? separation : 0; + return (float) (88 + ((modelX - center) * PIXELS_PER_UNIT - 8) * scale); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselRules.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselRules.java new file mode 100644 index 0000000..de4ad00 --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/vessel/VesselRules.java @@ -0,0 +1,38 @@ +package net.modcrafters.minecraft.primalpottery.vessel; + +import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; + +/** Fluid amounts are millilitres; saved geometry is measured in 32nds of a block. */ +public final class VesselRules { + private VesselRules() {} + + public static int transfer(String from, int held, String into, int stored, int capacity) { + if (held <= 0 || from.isEmpty() || (stored > 0 && !from.equals(into))) return 0; + return Math.max(0, Math.min(held, capacity - stored)); + } + + public static int planterCapacity(Pottery pot) { + return pot.size() == Pottery.Size.LARGE ? 1000 : 250; + } + + /** Returns the action-bar translation for the first unmet planting requirement. */ + public static String soilWarning(Pottery pot, boolean closed, int liquid, boolean planted) { + if (pot.classify().volume() < planterCapacity(pot)) return "message.primalpottery.soil.capacity"; + if (closed) return "message.primalpottery.soil.lid"; + if (liquid > 0) return "message.primalpottery.soil.liquid"; + if (planted) return "message.primalpottery.soil.occupied"; + return null; + } + + public static double surface(Pottery pot, int amount, boolean soil) { + List wall = PotteryProfile.cavity(pot.discs()); + int capacity = pot.classify().volume(); + if (wall.isEmpty() || capacity == 0) return 0; + double bottom = wall.get(0).y(), top = wall.get(wall.size() - 1).y(); + double maximum = top - Math.min(soil ? .25 : .1, (top - bottom) / 2); + return soil ? maximum : Math.min(maximum, PotteryProfile.fillHeight(wall, + PotteryProfile.volume(wall) * Math.min(amount, capacity) / capacity)); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelGuides.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelGuides.java new file mode 100644 index 0000000..f0b629c --- /dev/null +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelGuides.java @@ -0,0 +1,78 @@ +package net.modcrafters.minecraft.primalpottery.wheel; + +import java.util.ArrayList; +import java.util.List; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile.Station; + +/** Timber profiles on the four edges of the wheel. The carved side follows the installed blueprint. */ +public final class WheelGuides { + public interface VertexSink { + void vertex(float x, float y, float z, float u, float v, float nx, float ny, float nz); + } + + private final List vertices = new ArrayList<>(); + private int turn; + + public WheelGuides(Pottery pattern) { + List wall = PotteryProfile.profile(pattern.discs(), false); + if (wall.isEmpty()) return; + double back = Math.max(30, 18 + pattern.widestRadius()); + double[] clearance = new double[wall.size()]; + for (int i = wall.size() - 1; i >= 0; i--) { + Station point = wall.get(i); + clearance[i] = 18 + point.radius(); + if (i + 1 < wall.size()) clearance[i] = Math.max(clearance[i], clearance[i + 1] - (wall.get(i + 1).y() - point.y()) / 2); + } + for (turn = 0; turn < 4; turn++) { + double outside = back; + double inside = 16 + wall.get(0).radius(); + double y = 31; + // The one-unit foot sits on the worktop below the rotor. + section(Math.min(28, back - 2), 31, back, Math.min(28, back - 2), 32, back); + for (int i = 1; i < wall.size(); i++) { + Station point = wall.get(i); + y = 32 + wall.get(i - 1).y(); + double nextY = 32 + point.y(); + double nextInside = 16 + point.radius(); + double nextOutside = Math.max(clearance[i], outside - (nextY - y) / 2); + section(inside, y, outside, nextInside, nextY, nextOutside); + inside = nextInside; + outside = nextOutside; + } + double top = 32 + wall.get(wall.size() - 1).y(); + face(inside, top, 17, outside, top, 17, outside, top, 15, inside, top, 15); + } + } + + private void section(double in, double y, double out, double nextIn, double nextY, double nextOut) { + face(out, y, 17, out, y, 15, nextOut, nextY, 15, nextOut, nextY, 17); + face(in, y, 17, out, y, 17, nextOut, nextY, 17, nextIn, nextY, 17); + face(out, y, 15, in, y, 15, nextIn, nextY, 15, nextOut, nextY, 15); + face(in, y, 15, in, y, 17, nextIn, nextY, 17, nextIn, nextY, 15); + } + private void face(double... p) { + double ax = p[3]-p[0], ay = p[4]-p[1], az = p[5]-p[2]; + double bx = p[9]-p[0], by = p[10]-p[1], bz = p[11]-p[2]; + double nx = ay*bz-az*by, ny = az*bx-ax*bz, nz = ax*by-ay*bx; + double length = Math.sqrt(nx*nx + ny*ny + nz*nz); + if (length == 0) return; + for (int i = 0; i < p.length; i += 3) { + double x = p[i] - 16, y = p[i+1], z = p[i+2] - 16; + double u = Math.abs(nx) > Math.abs(nz) ? p[i+2] / 2 : p[i] / 2; + vertices.add(new float[]{(float) (.5 + rotatedX(x,z)/32), (float) (y/32), (float) (.5 + rotatedZ(x,z)/32), + (float) Math.min(15.99, u), (float) Math.min(15.99, Math.max(0, (y-31)/2)), + (float) (rotatedX(nx,nz)/length), (float) (ny/length), (float) (rotatedZ(nx,nz)/length)}); + } + } + private double rotatedX(double x, double z) { + switch (turn) { case 1: return -z; case 2: return -x; case 3: return z; default: return x; } + } + private double rotatedZ(double x, double z) { + switch (turn) { case 1: return x; case 2: return -z; case 3: return -x; default: return z; } + } + public void draw(VertexSink output) { + for (float[] v : vertices) output.vertex(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]); + } +} diff --git a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java index 3584a0d..ba25b42 100644 --- a/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java +++ b/forge/shared/src/main/java/net/modcrafters/minecraft/primalpottery/wheel/WheelInteraction.java @@ -34,7 +34,9 @@ public boolean use(WheelClay clay, double x, double y, double z, boolean server) } Pottery.Size size = Pottery.formed(blueprint()).size(); Pottery raw = rawShape(); - if (raw == null ? !holdsClay(size) : raw.size() != size) return false; + if (raw != null && raw.size() != size) return false; + // A clay block clicked on the small head must stay in the hand instead of placing above the wheel. + if (raw == null && !holdsClay(size)) return holdsClay(Pottery.Size.LARGE); if (server) { clay.start(raw, blueprint()); consumeClay(); diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/DyePotRecipe.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/DyePotRecipe.java new file mode 100644 index 0000000..102de7b --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/DyePotRecipe.java @@ -0,0 +1,34 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.RegistryAccess; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.*; +import net.minecraft.world.level.Level; +import net.modcrafters.minecraft.primalpottery.painting.Pigments; + +public final class DyePotRecipe extends CustomRecipe { + DyePotRecipe(ResourceLocation id, CraftingBookCategory category) { super(id, category); } + @Override public RecipeSerializer getSerializer() { return PaintingRegistration.DYE_RECIPE.get(); } + @Override public boolean canCraftInDimensions(int width, int height) { return width == height && (width == 2 || width == 3); } + @Override public boolean matches(CraftingContainer grid, Level level) { return !result(grid).isEmpty(); } + @Override public ItemStack assemble(CraftingContainer grid, RegistryAccess registries) { return result(grid); } + + private ItemStack result(CraftingContainer grid) { + ItemStack raw = ItemStack.EMPTY; + int color = -1; + for (int i = 0; i < grid.getContainerSize(); i++) { + ItemStack stack = grid.getItem(i); + if (stack.isEmpty()) continue; + if (stack.getItem() == PrimalPotteryForge.RAW.get() && raw.isEmpty() && !PaintingRegistration.dyed(stack)) raw = stack; + else if (color == -1 && PaintingRegistration.color(stack) >= 0) color = PaintingRegistration.color(stack); + else return ItemStack.EMPTY; + } + if (raw.isEmpty() || color < 0) return ItemStack.EMPTY; + ItemStack result = raw.copy(); + result.setCount(1); + result.getOrCreateTag().putString("dye", Pigments.NAMES[color]); + return result; + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java index 6788703..3381e6e 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/FirePotteryRecipe.java @@ -18,7 +18,9 @@ private FirePotteryRecipe(ResourceLocation id) { ItemStack fired = new ItemStack(PrimalPotteryForge.ITEM.get()); ItemStack raw = furnace.getItem(0); if (raw.hasTag()) fired.setTag(raw.getTag().copy()); - return fired; + // Forge's furnace compares item IDs before growing an occupied output slot. + ItemStack output = furnace.getContainerSize() > 2 ? furnace.getItem(2) : ItemStack.EMPTY; + return output.isEmpty() || ItemStack.isSameItemSameTags(output, fired) ? fired : ItemStack.EMPTY; } @Override public RecipeSerializer getSerializer() { return PrimalPotteryForge.FIRING.get(); } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java index 92123f7..2410a0b 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/ForgeTemplateItem.java @@ -1,5 +1,14 @@ package net.modcrafters.minecraft.primalpottery.forge; +import net.minecraft.world.InteractionResult; + +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; +import java.util.List; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.context.UseOnContext; + import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; @@ -22,4 +31,20 @@ public InteractionResultHolder use(Level level, Player player, Intera if (player instanceof ServerPlayer server) TemplateChannel.EDITS.open(server, hand, kind); return InteractionResultHolder.sidedSuccess(player.getItemInHand(hand), level.isClientSide); } + + @Override public InteractionResult useOn(UseOnContext context) { + Player player = context.getPlayer(); + if (player == null) return InteractionResult.PASS; + return use(context.getLevel(), player, context.getHand()).getResult(); + } + + @Override public void appendHoverText(ItemStack stack, Level level, List lines, TooltipFlag flag) { + if (kind != kind.blueprint()) return; + Pottery profile = ForgeStackProfiles.INSTANCE.read(stack); + if (profile == null || profile.size() != kind.size) profile = PotteryTemplates.fresh(kind.size); + Pottery.Info info = profile.classify(); + lines.add(Component.translatable("tooltip.primalpottery.type", Component.translatable(info.type().tooltipKey()))); + lines.add(Component.translatable(kind.size == Pottery.Size.LARGE ? "tooltip.primalpottery.wheel_clay_block" : "tooltip.primalpottery.wheel_clay_ball")); + if (info.volume() > 0) lines.add(Component.translatable("tooltip.primalpottery.capacity", info.volume())); + } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/MiniatureTree.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/MiniatureTree.java new file mode 100644 index 0000000..01a836b --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/MiniatureTree.java @@ -0,0 +1,133 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.worldgen.features.TreeFeatures; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.SaplingBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; +import javax.annotation.Nullable; + +/** Above-ground block states placed by the sapling's worldgen feature, in generator coordinates. */ +public final class MiniatureTree { + static final int LIMIT = 8192; + private final Map voxels; + + MiniatureTree(Map voxels) { + this.voxels = Map.copyOf(voxels); + } + + public Map voxels() { + return this.voxels; + } + + public static boolean isSapling(Block block) { + return block instanceof SaplingBlock || block == Blocks.AZALEA || block == Blocks.FLOWERING_AZALEA; + } + + public static @Nullable MiniatureTree grow(ServerLevel level, Block plant) { + return grow(level, plant, null); + } + + public static @Nullable MiniatureTree grow(ServerLevel level, Block plant, @Nullable MiniatureTree previous) { + RandomSource random = RandomSource.create(level.getRandom().nextLong()); + var key = switch (BuiltInRegistries.BLOCK.getKey(plant).getPath()) { + case "oak_sapling" -> random.nextInt(10) == 0 ? TreeFeatures.FANCY_OAK : TreeFeatures.OAK; + case "birch_sapling" -> TreeFeatures.BIRCH; + case "spruce_sapling" -> TreeFeatures.SPRUCE; + case "jungle_sapling" -> TreeFeatures.JUNGLE_TREE_NO_VINE; + case "dark_oak_sapling" -> TreeFeatures.DARK_OAK; + case "acacia_sapling" -> TreeFeatures.ACACIA; + case "cherry_sapling" -> TreeFeatures.CHERRY; + case "mangrove_propagule" -> random.nextFloat() < 0.85F ? TreeFeatures.TALL_MANGROVE : TreeFeatures.MANGROVE; + case "azalea", "flowering_azalea" -> TreeFeatures.AZALEA_TREE; + default -> null; + }; + if (key == null) { + return null; + } + var feature = level.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).getHolder(key); + if (feature.isEmpty()) { + return null; + } + for (int attempt = 0; attempt < 4; attempt++) { + TreePlot plot = new TreePlot(level, random); + if (feature.get().value().place(plot, level.getChunkSource().getGenerator(), random, BlockPos.ZERO)) { + MiniatureTree tree = plot.harvest(); + if (tree != null && (previous == null || !tree.voxels.equals(previous.voxels))) { + return tree; + } + } + } + return null; + } + + ListTag save() { + Map> groups = new HashMap<>(); + this.voxels.forEach((pos, state) -> groups.computeIfAbsent(state, ignored -> new ArrayList<>()) + .add((pos.getX() + 32) | ((pos.getZ() + 32) << 6) | (pos.getY() << 12))); + ListTag list = new ListTag(); + groups.forEach((state, positions) -> { + CompoundTag group = new CompoundTag(); + group.putString("block", BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()); + CompoundTag properties = new CompoundTag(); + for (Property property : state.getProperties()) { + properties.putString(property.getName(), propertyValue(state, property)); + } + if (!properties.isEmpty()) { + group.put("properties", properties); + } + group.putIntArray("positions", positions.stream().mapToInt(Integer::intValue).toArray()); + list.add(group); + }); + return list; + } + + private static > String propertyValue(BlockState state, Property property) { + return property.getName(state.getValue(property)); + } + + private static > BlockState withProperty(BlockState state, Property property, String value) { + return property.getValue(value).map(parsed -> state.setValue(property, parsed)).orElse(state); + } + + public static @Nullable MiniatureTree load(ListTag list) { + Map voxels = new HashMap<>(); + for (int i = 0; i < list.size(); i++) { + CompoundTag group = list.getCompound(i); + ResourceLocation id = ResourceLocation.tryParse(group.getString("block")); + if (id == null || !BuiltInRegistries.BLOCK.containsKey(id)) { + continue; + } + BlockState state = BuiltInRegistries.BLOCK.get(id).defaultBlockState(); + int[] positions = group.getIntArray("positions"); + CompoundTag properties = group.getCompound("properties"); + for (Property property : state.getProperties()) { + if (properties.contains(property.getName())) { + state = withProperty(state, property, properties.getString(property.getName())); + } + } + if (positions.length > LIMIT - voxels.size()) { + return null; + } + for (int p : positions) { + if (p >= 0 && p < (1 << 18) && !state.isAir()) { + voxels.put(new BlockPos((p & 63) - 32, p >> 12, ((p >> 6) & 63) - 32), state); + } + } + } + return voxels.isEmpty() ? null : new MiniatureTree(voxels); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintChannel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintChannel.java new file mode 100644 index 0000000..5509f59 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintChannel.java @@ -0,0 +1,32 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.Optional; +import net.minecraft.core.BlockPos; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.*; +import net.minecraftforge.network.simple.SimpleChannel; + +public final class PaintChannel { + private static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( + new ResourceLocation("primalpottery","paint"), () -> "1", "1"::equals, "1"::equals); + private record Stroke(int window, int action) {} + private record Stamp(BlockPos pos, int item, String pattern) {} + static void register() { + CHANNEL.registerMessage(0, Stroke.class, (m,b) -> { b.writeVarInt(m.window); b.writeVarInt(m.action); }, + b -> new Stroke(b.readVarInt(), b.readVarInt()), (m,ctx) -> { + var player = ctx.get().getSender(); + ctx.get().enqueueWork(() -> { + if (player.containerMenu instanceof PaintingMenu menu && menu.containerId == m.window) menu.apply(player, m.action); + }); + ctx.get().setPacketHandled(true); + }, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + CHANNEL.registerMessage(1, Stamp.class, (m,b) -> { b.writeBlockPos(m.pos); b.writeVarInt(m.item); b.writeUtf(m.pattern, 256); }, + b -> new Stamp(b.readBlockPos(), b.readVarInt(), b.readUtf(256)), (m,ctx) -> { + var player = ctx.get().getSender(); + ctx.get().enqueueWork(() -> PaintingTableBlock.stamp(player, m.pos, m.item, m.pattern)); + ctx.get().setPacketHandled(true); + }, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + } + public static void stroke(int window, int action) { CHANNEL.sendToServer(new Stroke(window, action)); } + public static void stamp(BlockPos pos, int item, String pattern) { CHANNEL.sendToServer(new Stamp(pos, item, pattern)); } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintSupply.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintSupply.java new file mode 100644 index 0000000..7059de2 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintSupply.java @@ -0,0 +1,36 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.entity.player.Inventory; +import net.modcrafters.minecraft.primalpottery.painting.PigmentTanks; + +/** Optionally reserve the offhand icon when the player uses a dye itself as a stamp. */ +final class PaintSupply implements PigmentTanks.Stock { + private final Inventory inventory; + private final ItemStack icon; + + PaintSupply(Inventory inventory, ItemStack icon) { + this.inventory = inventory; + this.icon = icon; + } + + private int available(ItemStack stack, int color) { + if (PaintingRegistration.color(stack) != color) return 0; + return stack.getCount() - (stack == icon ? 1 : 0); + } + public int count(int color) { + int n = 0; + for (int i = 0; i < inventory.getContainerSize(); i++) n += available(inventory.getItem(i), color); + return n; + } + public void consume(int color, int count) { + for (int i = 0; i < inventory.getContainerSize() && count > 0; i++) { + ItemStack stack = inventory.getItem(i); + int take = Math.min(count, available(stack, color)); + if (take == 0) continue; + stack.shrink(take); + count -= take; + } + inventory.setChanged(); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java index 244f77f..06d13cb 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java @@ -15,27 +15,89 @@ import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.shapes.Shapes; +import net.modcrafters.minecraft.primalpottery.forge.dining.Dining; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; public final class PaintedPotBlock extends BaseEntityBlock { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 8, 12); - PaintedPotBlock() { super(Properties.of().strength(0.5F).noOcclusion()); } + PaintedPotBlock() { super(Properties.of().strength(0.5F).noOcclusion().dynamicShape()); } @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new PaintedPotEntity(pos, state); } @Override public RenderShape getRenderShape(BlockState state) { return RenderShape.MODEL; } - @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { return SHAPE; } + @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { + if (!(level.getBlockEntity(pos) instanceof PaintedPotEntity pots)) return SHAPE; + VoxelShape outline = Shapes.empty(); + for (int i = 0; i < PotteryLayout.COUNT; i++) { + if (pots.layout().at(i) != null) outline = Shapes.or(outline, Shapes.create(PotBounds.box(i, pots.layout().at(i)))); + } + return Dining.outline(pots, outline); + } @Override public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) { if (!level.isClientSide && level.getBlockEntity(pos) instanceof PaintedPotEntity pot) pot.install(stack); } + @Override public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) { + return level.getBlockEntity(pos) instanceof PaintedPotEntity pots ? pots.emission() : 0; + } + @Override public net.minecraft.world.InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, + net.minecraft.world.InteractionHand hand, BlockHitResult hit) { + if (!(level.getBlockEntity(pos) instanceof PaintedPotEntity pots)) return net.minecraft.world.InteractionResult.PASS; + var point = hit.getLocation().subtract(pos.getX(), pos.getY(), pos.getZ()); + if (Dining.use(pots, player, hand, point.x, point.y, point.z)) return net.minecraft.world.InteractionResult.sidedSuccess(level.isClientSide); + int slot = pots.hit(point.x, point.z); + if (slot < 0) return net.minecraft.world.InteractionResult.PASS; + if (player.isShiftKeyDown() && player.getItemInHand(hand).isEmpty()) { + if (!level.isClientSide) { + ItemStack removed = pots.take(slot); + for (ItemStack plant : VesselInteractions.dropPlanting(removed)) popResource(level, pos, plant); + popResource(level, pos, removed); + if (pots.layout().first() < 0) level.removeBlock(pos, false); + } + return net.minecraft.world.InteractionResult.sidedSuccess(level.isClientSide); + } + return VesselInteractions.usePlaced(pots, slot, player, hand) ? net.minecraft.world.InteractionResult.sidedSuccess(level.isClientSide) + : net.minecraft.world.InteractionResult.PASS; + } + @Override public List getDrops(BlockState state, LootParams.Builder loot) { return loot.getOptionalParameter(LootContextParams.BLOCK_ENTITY) instanceof PaintedPotEntity pot - ? List.of(pot.pickup()) : List.of(new ItemStack(this)); + ? pot.drops() : List.of(new ItemStack(this)); } @Override public ItemStack getCloneItemStack(BlockState state, HitResult hit, BlockGetter level, BlockPos pos, Player player) { - return level.getBlockEntity(pos) instanceof PaintedPotEntity pot ? pot.pickup() : new ItemStack(this); + if (!(level.getBlockEntity(pos) instanceof PaintedPotEntity pots)) return new ItemStack(this); + ItemStack setting = Dining.pickSetting(pots, hit.getLocation()); + if (!setting.isEmpty()) return setting; + if (pots.layout().count() == 1) return pots.pickup(); + var point = hit.getLocation(); + int slot = pots.hit(point.x - pos.getX(), point.z - pos.getZ()); + return pots.stack(slot).copy(); + } + + @Override public boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player, + boolean harvest, net.minecraft.world.level.material.FluidState fluid) { + if (level.getBlockEntity(pos) instanceof PaintedPotEntity pots && Dining.breakSetting(pots, player)) return false; + if (level.getBlockEntity(pos) instanceof PaintedPotEntity pots && pots.layout().count() > 1) { + if (!level.isClientSide) { + var from = player.getEyePosition(); + var to = from.add(player.getLookAngle().scale(player.getBlockReach() + 1)); + int slot = PotBounds.nearest(pots.layout(), pos, from, to); + if (slot < 0) return false; + var dishes = pots.dining.remove(slot, pots.layout().at(slot)); + ItemStack removed = pots.take(slot); + if (!player.getAbilities().instabuild) { + for (ItemStack dish : dishes) popResource(level, pos, dish); + for (ItemStack plant : VesselInteractions.dropPlanting(removed)) popResource(level, pos, plant); + popResource(level, pos, removed); + } + } + return false; + } + return super.onDestroyedByPlayer(state, level, pos, player, harvest, fluid); } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java index 76a6c9b..a30724a 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotEntity.java @@ -1,7 +1,12 @@ package net.modcrafters.minecraft.primalpottery.forge; +import net.modcrafters.minecraft.primalpottery.forge.dining.DiningTable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; @@ -10,50 +15,141 @@ import net.minecraftforge.client.model.data.ModelProperty; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +/** Each slot keeps the complete native stack so pickup preserves finishes, contents and planter data. */ public final class PaintedPotEntity extends BlockEntity { public static final ModelProperty PROFILE = new ModelProperty<>(); - private Pottery pot = PaintedVessel.SAMPLE; + public static final ModelProperty STACKS = new ModelProperty<>(); + public static final ModelProperty LAYOUT = new ModelProperty<>(); + public final DiningTable dining = new DiningTable(); + private ItemStack[] snapshot; + private int emission; + int emission() { return emission; } + private final ItemStack[] pots = new ItemStack[PotteryLayout.COUNT]; + private PotteryLayout layout = new PotteryLayout(); - PaintedPotEntity(BlockPos pos, BlockState state) { + public PaintedPotEntity(BlockPos pos, BlockState state) { super(PrimalPotteryForge.ENTITY.get(), pos, state); + Arrays.fill(pots, ItemStack.EMPTY); + put(PotteryLayout.CENTER, new ItemStack(PrimalPotteryForge.ITEM.get())); } + public ItemStack[] snapshot() { + if (snapshot == null) snapshot = Arrays.stream(pots).map(ItemStack::copy).toArray(ItemStack[]::new); + return snapshot; + } + public int hit(double x, double z) { return layout.hit(x, z); } + public PotteryLayout layout() { return layout; } + public Pottery profile() { return layout.at(layout.first()); } + public ItemStack stack(int slot) { return layout.at(slot) == null ? ItemStack.EMPTY : pots[slot]; } public static Pottery fromStack(ItemStack stack) { Pottery profile = ForgeStackProfiles.INSTANCE.read(stack); return profile == null ? PaintedVessel.SAMPLE : profile; } - void install(ItemStack stack) { - pot = fromStack(stack); + private void put(int slot, ItemStack stack) { + snapshot = null; + pots[slot] = stack; + layout = layout.with(slot, stack.isEmpty() ? null : fromStack(stack), PaintingRegistration.tint(stack)); + } + void install(ItemStack stack) { installAt(PotteryLayout.CENTER, stack); } + void installAt(int slot, ItemStack stack) { + ItemStack single = stack.copy(); + single.setCount(1); + ForgeStackProfiles.INSTANCE.write(single, fromStack(stack)); + put(slot, single); + sync(); + } + void moveInitial(int slot) { + if (slot != PotteryLayout.CENTER && layout.count() == 1 && !pots[PotteryLayout.CENTER].isEmpty()) { + ItemStack first = pots[PotteryLayout.CENTER]; + put(PotteryLayout.CENTER, ItemStack.EMPTY); + put(slot, first); + sync(); + } + } + + public ItemStack take(int slot) { + ItemStack stack = stack(slot); + if (!stack.isEmpty()) { + put(slot, ItemStack.EMPTY); + sync(); + } + return stack; + } + public void sync() { + int previous = emission; + emission = VesselInteractions.light(this); + snapshot = null; setChanged(); + if (level == null) return; + if (emission != previous) level.getChunkSource().getLightEngine().checkBlock(worldPosition); level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 3); } - - ItemStack pickup() { - ItemStack result = new ItemStack(PrimalPotteryForge.ITEM.get()); - ForgeStackProfiles.INSTANCE.write(result, pot); + ItemStack pickup() { return stack(layout.first()).copy(); } + List drops() { + List result = new ArrayList<>(); + for (ItemStack pot : pots) { + if (pot.isEmpty()) continue; + ItemStack drop = pot.copy(); + result.addAll(VesselInteractions.dropPlanting(drop)); + result.add(drop); + } + result.addAll(dining.drops()); return result; } - @Override public ModelData getModelData() { return ModelData.builder().with(PROFILE, pot).build(); } - @Override protected void saveAdditional(CompoundTag tag) { super.saveAdditional(tag); - tag.put("pottery", ForgePotteryTags.save(pot)); + dining.save(tag); + ListTag slots = new ListTag(); + for (int i = 0; i < pots.length; i++) { + if (pots[i].isEmpty()) continue; + CompoundTag entry = pots[i].save(new CompoundTag()); + entry.putByte("slot", (byte) i); + slots.add(entry); + } + tag.put("pots", slots); + if (profile() != null) tag.put("pottery", ForgePotteryTags.save(profile())); } - @Override public void load(CompoundTag tag) { super.load(tag); - pot = ForgePotteryTags.load(tag.getCompound("pottery")); + dining.load(tag); + snapshot = null; + Arrays.fill(pots, ItemStack.EMPTY); + layout = new PotteryLayout(); + if (tag.contains("pots", 9)) { + ListTag slots = tag.getList("pots", 10); + for (int i = 0; i < slots.size(); i++) { + CompoundTag entry = slots.getCompound(i); + int slot = entry.getByte("slot"); + ItemStack stack = ItemStack.of(entry); + if (slot >= 0 && slot < pots.length && stack.getItem() == PrimalPotteryForge.ITEM.get()) { + stack.setCount(1); + put(slot, stack); + } + } + } else { + ItemStack single = new ItemStack(PrimalPotteryForge.ITEM.get()); + ForgeStackProfiles.INSTANCE.write(single, ForgePotteryTags.load(tag.getCompound("pottery"))); + put(PotteryLayout.CENTER, single); + } + emission = VesselInteractions.light(this); if (level != null && level.isClientSide) { requestModelDataUpdate(); level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 8); } } - @Override public CompoundTag getUpdateTag() { return saveWithoutMetadata(); } - + @Override public ModelData getModelData() { + return ModelData.builder().with(PROFILE, profile()).with(LAYOUT, layout).with(STACKS, snapshot()).build(); + } + @Override public CompoundTag getUpdateTag() { + CompoundTag tag = saveWithoutMetadata(); + dining.writeDiners(tag); + return tag; + } @Override public ClientboundBlockEntityDataPacket getUpdatePacket() { return ClientboundBlockEntityDataPacket.create(this); } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingMenu.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingMenu.java new file mode 100644 index 0000000..240cafa --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingMenu.java @@ -0,0 +1,77 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.player.*; +import net.minecraft.world.inventory.*; +import net.minecraft.world.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.painting.*; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PaintingMenu extends AbstractContainerMenu implements PaintPanel.View { + private final SimpleContainer work = new SimpleContainer(1); + private final PaintingTableEntity table; + private final PaintSupply supply; + private ItemStack cachedStack = ItemStack.EMPTY; + private Pottery cachedProfile; + private final PaintBrush brush = new PaintBrush(); + private final int[] levels = new int[33]; + + public PaintingMenu(int id, Inventory inventory, PaintingTableEntity table) { + super(PaintingRegistration.MENU.get(), id); + this.table = table; + this.supply = new PaintSupply(inventory, ItemStack.EMPTY); + addSlot(new Slot(work, 0, 9, 6) { + @Override public boolean mayPlace(ItemStack stack) { return false; } + @Override public boolean mayPickup(Player player) { return false; } + }); + addDataSlots(new ContainerData() { + public int getCount() { return levels.length; } + public int get(int i) { return table == null ? levels[i] : field(i); } + public void set(int i, int value) { levels[i] = value; } + }); + } + + private int field(int index) { + if (index < 16) return table.tanks.get(index); + if (index < 32) return supply.count(index - 16); + return brush.undoCost(); + } + + public ItemStack potStack() { return work.getItem(0); } + public void accept(ItemStack held) { + if (PaintingRegistration.isPot(held)) work.setItem(0, held.split(1)); + } + public Pottery profile() { + ItemStack current = potStack(); + if (cachedStack != current) { + cachedStack = current; + cachedProfile = current.isEmpty() ? null : PaintedPotEntity.fromStack(current); + } + return cachedProfile; + } + public int tint() { return PaintingRegistration.tint(potStack()); } + public int volume(int i) { return table == null ? levels[i] : field(i); } + public int count(int i) { return table == null ? levels[16+i] : field(16+i); } + public boolean canUndo() { + int cost = table == null ? levels[32] : brush.undoCost(); + return cost == 1 || cost >= 2 && (volume(cost-2) > 0 || count(cost-2) > 0); + } + @Override public boolean stillValid(Player player) { + return table == null || !table.isRemoved() && table.getLevel() == player.level() + && player.distanceToSqr(net.minecraft.world.phys.Vec3.atCenterOf(table.getBlockPos())) <= 64; + } + void apply(Player player, int action) { + if (table == null || player.isSpectator() || !stillValid(player) || potStack().getCount() != 1) return; + Pottery result = brush.apply(profile(), action, table.tanks, supply); + if (result == null) return; + ForgeStackProfiles.INSTANCE.write(potStack(), result); + cachedProfile = result; + table.setChanged(); + broadcastChanges(); + } + @Override public ItemStack quickMoveStack(Player player, int index) { return ItemStack.EMPTY; } + @Override public void removed(Player player) { + super.removed(player); + if (!player.level().isClientSide) clearContainer(player, work); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingRegistration.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingRegistration.java new file mode 100644 index 0000000..c9baa33 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingRegistration.java @@ -0,0 +1,53 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.*; +import net.minecraft.world.item.crafting.*; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.registries.*; +import net.modcrafters.minecraft.primalpottery.painting.Pigments; + +public final class PaintingRegistration { + private static final String MOD = "primalpottery"; + private static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD); + private static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD); + private static final DeferredRegister> ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MOD); + private static final DeferredRegister> MENUS = DeferredRegister.create(ForgeRegistries.MENU_TYPES, MOD); + private static final DeferredRegister> RECIPES = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, MOD); + public static final RegistryObject TABLE = BLOCKS.register("painting_table", PaintingTableBlock::new); + private static final RegistryObject TABLE_ITEM = ITEMS.register("painting_table", () -> new BlockItem(TABLE.get(), new Item.Properties())); + static final RegistryObject> ENTITY = ENTITIES.register("painting_table", + () -> BlockEntityType.Builder.of(PaintingTableEntity::new, TABLE.get()).build(null)); + public static final RegistryObject> MENU = MENUS.register("painting_table", + () -> new MenuType<>((id, inventory) -> new PaintingMenu(id, inventory, null), FeatureFlags.DEFAULT_FLAGS)); + static final RegistryObject> DYE_RECIPE = RECIPES.register("paint_pottery", + () -> new SimpleCraftingRecipeSerializer<>(DyePotRecipe::new)); + public static void register(IEventBus bus) { + BLOCKS.register(bus); + ITEMS.register(bus); + ENTITIES.register(bus); + MENUS.register(bus); + RECIPES.register(bus); + bus.addListener((BuildCreativeModeTabContentsEvent event) -> { + if (event.getTabKey() == CreativeModeTabs.INGREDIENTS) event.accept(TABLE_ITEM.get()); + }); + PaintChannel.register(); + } + public static int color(ItemStack stack) { + if (!(stack.getItem() instanceof DyeItem dye) || dye != DyeItem.byColor(dye.getDyeColor())) return -1; + return dye.getDyeColor().getId(); + } + public static ItemStack dye(int color) { + return new ItemStack(DyeItem.byColor(DyeColor.byId(color))); + } + public static int tint(ItemStack stack) { + return stack.hasTag() ? Pigments.clayTint(stack.getTag().getString("dye")) : -1; + } + public static boolean dyed(ItemStack stack) { return tint(stack) != -1; } + public static boolean isPot(ItemStack stack) { return stack.getItem() == PrimalPotteryForge.ITEM.get(); } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableBlock.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableBlock.java new file mode 100644 index 0000000..fc19388 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableBlock.java @@ -0,0 +1,77 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.*; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.shapes.*; +import net.modcrafters.minecraft.primalpottery.pottery.*; +import net.modcrafters.minecraft.primalpottery.painting.PigmentTanks; + +public final class PaintingTableBlock extends Block implements EntityBlock { + PaintingTableBlock() { + super(Properties.of().strength(2).noOcclusion()); + } + private static final VoxelShape SHAPE = Shapes.or(box(0,12,0,16,16,16), box(1,0,1,4,12,4), + box(12,0,1,15,12,4), box(1,0,12,4,12,15), box(12,0,12,15,12,15)); + @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { return SHAPE; } + @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new PaintingTableEntity(pos, state); } + @Override public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + if (player.containerMenu != player.inventoryMenu) return InteractionResult.SUCCESS; + if (canStamp(player)) { + if (level.isClientSide) net.modcrafters.minecraft.primalpottery.forge.client.PaintingClient.sendStamp(player, pos); + } else if (!level.isClientSide) open(player, pos); + return InteractionResult.sidedSuccess(level.isClientSide); + } + private static void open(Player player, BlockPos pos) { + if (!(player.level().getBlockEntity(pos) instanceof PaintingTableEntity table)) return; + player.openMenu(new SimpleMenuProvider((id, inv, p) -> new PaintingMenu(id, inv, table), + Component.translatable("block.primalpottery.painting_table"))); + if (!(player.containerMenu instanceof PaintingMenu menu)) return; + ItemStack main = player.getMainHandItem(); + menu.accept(PaintingRegistration.isPot(main) ? main : player.getOffhandItem()); + } + private static boolean canStamp(Player player) { + ItemStack held = player.getMainHandItem(), icon = player.getOffhandItem(); + return PaintingRegistration.isPot(held) && !icon.isEmpty() && !(icon.getItem() instanceof BlockItem) + && !PaintedPotEntity.fromStack(held).isPlate(); + } + static void stamp(Player player, BlockPos pos, int itemId, String pixels) { + Level level = player.level(); + ItemStack icon = player.getOffhandItem(); + if (player.isSpectator() || !canStamp(player) || player.containerMenu != player.inventoryMenu + || !level.hasChunkAt(pos) || !level.mayInteract(player, pos) + || player.distanceToSqr(net.minecraft.world.phys.Vec3.atCenterOf(pos)) > 36 + || Item.getId(icon.getItem()) != itemId + || !(level.getBlockEntity(pos) instanceof PaintingTableEntity)) return; + if (pixels.isEmpty()) { open(player, pos); return; } + if (pixels.length() != FacePaint.CELLS || !pixels.chars().allMatch(c -> c == '.' || c >= 'A' && c < 'A' + 16)) return; + FacePaint pattern = FacePaint.read(pixels); + ItemStack held = player.getMainHandItem(); + Pottery pot = PaintedPotEntity.fromStack(held); + if (pattern.equals(FacePaint.EMPTY) || pattern.equals(pot.paint())) return; + PaintingTableEntity table = (PaintingTableEntity) level.getBlockEntity(pos); + var missing = Component.empty(); + PigmentTanks.Shortage report = (color, amount) -> { + if (!missing.getSiblings().isEmpty()) missing.append(", "); + missing.append(Component.translatable("message.primalpottery.paint.amount", PaintingRegistration.dye(color).getHoverName(), amount)); + }; + if (table.tanks.stamp(pot.paint(), pattern, new PaintSupply(player.getInventory(), icon), report) >= 0) { + player.displayClientMessage(Component.translatable("message.primalpottery.paint.missing", missing, icon.getHoverName()), false); + return; + } + ItemStack result = held.split(1); + ForgeStackProfiles.INSTANCE.write(result, pot.withPaint(pattern)); + if (held.isEmpty()) player.setItemInHand(InteractionHand.MAIN_HAND, result); + else if (!player.getInventory().add(result)) player.drop(result, false); + table.setChanged(); + player.displayClientMessage(Component.translatable("message.primalpottery.paint.stamped", icon.getHoverName()), true); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableEntity.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableEntity.java new file mode 100644 index 0000000..7860921 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintingTableEntity.java @@ -0,0 +1,26 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.modcrafters.minecraft.primalpottery.painting.PigmentTanks; +import net.modcrafters.minecraft.primalpottery.painting.Pigments; + +public final class PaintingTableEntity extends BlockEntity { + public final PigmentTanks tanks = new PigmentTanks(); + + PaintingTableEntity(BlockPos pos, BlockState state) { super(PaintingRegistration.ENTITY.get(), pos, state); } + + @Override public void saveAdditional(CompoundTag tag) { + super.saveAdditional(tag); + CompoundTag paint = new CompoundTag(); + for (int i = 0; i < Pigments.NAMES.length; i++) paint.putInt(Pigments.NAMES[i], tanks.get(i)); + tag.put("tanks", paint); + } + @Override public void load(CompoundTag tag) { + super.load(tag); + CompoundTag paint = tag.getCompound("tanks"); + for (int i = 0; i < Pigments.NAMES.length; i++) tanks.set(i, paint.getInt(Pigments.NAMES[i])); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PlanterPlants.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PlanterPlants.java new file mode 100644 index 0000000..a0d891b --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PlanterPlants.java @@ -0,0 +1,41 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.Set; +import java.util.stream.Collectors; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PlanterPlants { + private PlanterPlants() {} + + private static final class Flowers { + static final Set POTTED = BuiltInRegistries.BLOCK.stream() + .filter(block -> block instanceof FlowerPotBlock && BuiltInRegistries.BLOCK.getKey(block).getNamespace().equals("minecraft")) + .map(block -> ((FlowerPotBlock) block).getContent()) + .filter(block -> block != Blocks.AIR).collect(Collectors.toSet()); + } + public static boolean tall(Block block) { + return block.defaultBlockState().hasProperty(BlockStateProperties.DOUBLE_BLOCK_HALF) + && (block.defaultBlockState().is(BlockTags.FLOWERS) || block == Blocks.TALL_GRASS || block == Blocks.LARGE_FERN); + } + static boolean soil(Block block) { + return block == Blocks.DIRT || block == Blocks.GRASS_BLOCK || block == Blocks.SAND; + } + + static boolean accepts(Pottery.Size size, Block block) { + return block == Blocks.GRASS || Flowers.POTTED.contains(block) || size == Pottery.Size.LARGE && tall(block); + } + static boolean sapling(Block block) { return MiniatureTree.isSapling(block); } + static boolean grow(ServerLevel level, Block block, ItemStack stack) { + MiniatureTree previous = MiniatureTree.load(stack.getOrCreateTag().getList("tree", 10)); + MiniatureTree tree = MiniatureTree.grow(level, block, previous); + if (tree == null) return false; + stack.getOrCreateTag().put("tree", tree.save()); + return true; + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotBounds.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotBounds.java new file mode 100644 index 0000000..46621cc --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotBounds.java @@ -0,0 +1,38 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +public final class PotBounds { + private PotBounds() {} + public static AABB box(int slot, Pottery pot) { + double x = PotteryLayout.centerX(slot, pot), z = PotteryLayout.centerZ(slot, pot); + double radius = pot.size() == Pottery.Size.LARGE ? .5 : .25; + double height = pot.size() == Pottery.Size.LARGE ? 1 : .5; + if (pot.isPlate()) { + radius = pot.isPlatter() ? pot.widestRadius() / 32 : 1./6; + height = pot.isPlatter() ? pot.height() / 32 : 3./32; + } + return new AABB(x - radius, 0, z - radius, x + radius, height, z + radius); + } + + static int nearest(PotteryLayout layout, BlockPos pos, Vec3 from, Vec3 to) { + int nearest = -1; + double distance = Double.POSITIVE_INFINITY; + for (int i = 0; i < PotteryLayout.COUNT; i++) { + Pottery pot = layout.at(i); + if (pot == null) continue; + var hit = box(i, pot).move(pos).clip(from, to); + if (hit.isEmpty()) continue; + double candidate = from.distanceToSqr(hit.get()); + if (candidate < distance) { + distance = candidate; + nearest = i; + } + } + return nearest; + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryBlockItem.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryBlockItem.java new file mode 100644 index 0000000..5a5917e --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryBlockItem.java @@ -0,0 +1,52 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +public final class PotteryBlockItem extends VesselItem { + PotteryBlockItem(Block pottery) { super(pottery, new Properties().stacksTo(1)); } + + @Override protected InteractionResult placeVessel(UseOnContext context) { + Level level = context.getLevel(); + BlockPos clicked = context.getClickedPos(); + Direction face = context.getClickedFace(); + ItemStack held = context.getItemInHand(); + Player player = context.getPlayer(); + Pottery profile = PaintedPotEntity.fromStack(held); + double x = context.getClickLocation().x - clicked.getX() - face.getStepX() * 1e-6; + double z = context.getClickLocation().z - clicked.getZ() - face.getStepZ() * 1e-6; + var existing = level.getBlockEntity(clicked); + if (!(existing instanceof PaintedPotEntity) && face == Direction.UP) existing = level.getBlockEntity(clicked.above()); + if (existing instanceof PaintedPotEntity pottery) { + int slot = pottery.layout().destination(profile, x, z, player != null && player.isShiftKeyDown(), + face.getStepX(), face.getStepZ()); + if (slot < 0 || player != null && !player.mayUseItemAt(pottery.getBlockPos(), face, held)) return InteractionResult.FAIL; + if (!level.isClientSide) { + pottery.installAt(slot, held); + level.playSound(null, pottery.getBlockPos(), net.minecraft.sounds.SoundEvents.DECORATED_POT_PLACE, net.minecraft.sounds.SoundSource.BLOCKS, 1, .8F); + if (player == null || !player.getAbilities().instabuild) held.shrink(1); + } + return InteractionResult.sidedSuccess(level.isClientSide); + } + var placement = new net.minecraft.world.item.context.BlockPlaceContext(context); + BlockPos dest = placement.getClickedPos(); + InteractionResult result = super.placeVessel(context); + if (result.consumesAction() && !level.isClientSide && level.getBlockEntity(dest) instanceof PaintedPotEntity pottery) { + pottery.moveInitial(PotteryLayout.preferred(profile, x, z)); + } + return result; + } + + @Override public net.minecraft.network.chat.Component getName(ItemStack stack) { + return PotteryNames.display(stack, false); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryNames.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryNames.java new file mode 100644 index 0000000..931ef60 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryNames.java @@ -0,0 +1,16 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.world.item.ItemStack; + +final class PotteryNames { + private PotteryNames() {} + + static Component display(ItemStack stack, boolean raw) { + MutableComponent shape = Component.translatable(PaintedPotEntity.fromStack(stack).classify().type().shapeKey()); + MutableComponent name = raw ? Component.translatable("item.primalpottery.raw_shape", shape) : shape; + int tint = PaintingRegistration.tint(stack); + return tint < 0 ? name : name.withStyle(style -> style.withColor(tint)); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryTab.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryTab.java new file mode 100644 index 0000000..b666246 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PotteryTab.java @@ -0,0 +1,28 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.registries.DeferredRegister; +import net.modcrafters.minecraft.primalpottery.forge.dining.DiningRegistration; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; + +final class PotteryTab { + static void register(IEventBus bus) { + DeferredRegister tabs = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, "primalpottery"); + tabs.register("primalpottery", () -> CreativeModeTab.builder() + .title(Component.translatable("itemGroup.primalpottery")) + .icon(() -> new ItemStack(PrimalPotteryForge.WHEEL.get())) + .displayItems((parameters, items) -> { + items.accept(PrimalPotteryForge.WHEEL.get()); + items.accept(PaintingRegistration.TABLE.get()); + items.accept(DiningRegistration.cutlery()); + items.accept(PrimalPotteryForge.template(TemplateKind.SMALL_RAW)); + items.accept(PrimalPotteryForge.template(TemplateKind.LARGE_RAW)); + }).build()); + tabs.register(bus); + } + private PotteryTab() {} +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java index d5bf10c..fcaf8bf 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PrimalPotteryForge.java @@ -20,12 +20,12 @@ public final class PrimalPotteryForge { private static final DeferredRegister> ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, MOD_ID); static final RegistryObject POT = BLOCKS.register("pottery", PaintedPotBlock::new); - static final RegistryObject ITEM = ITEMS.register("pottery", () -> new BlockItem(POT.get(), new Item.Properties().stacksTo(1))); - static final RegistryObject> ENTITY = ENTITIES.register("pottery", + static final RegistryObject ITEM = ITEMS.register("pottery", () -> new PotteryBlockItem(POT.get())); + public static final RegistryObject> ENTITY = ENTITIES.register("pottery", () -> BlockEntityType.Builder.of(PaintedPotEntity::new, POT.get()).build(null)); public static final RegistryObject WHEEL = BLOCKS.register("pottery_wheel", WheelBlock::new); - public static final RegistryObject RAW = ITEMS.register("raw_pottery", () -> new Item(new Item.Properties().stacksTo(1))); + public static final RegistryObject RAW = ITEMS.register("raw_pottery", RawPotteryItem::new); private static final RegistryObject WHEEL_ITEM = ITEMS.register("pottery_wheel", () -> new BlockItem(WHEEL.get(), new Item.Properties())); public static final RegistryObject> WHEEL_ENTITY = ENTITIES.register("pottery_wheel", @@ -53,6 +53,10 @@ public PrimalPotteryForge() { event.accept(TEMPLATES.get(TemplateKind.LARGE_RAW).get()); } }); + PotteryTab.register(bus); + PaintingRegistration.register(bus); + VesselChannel.register(); + net.modcrafters.minecraft.primalpottery.forge.dining.DiningRegistration.register(bus); RECIPES.register(bus); BLOCKS.register(bus); ITEMS.register(bus); diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/RawPotteryItem.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/RawPotteryItem.java new file mode 100644 index 0000000..a2d21d3 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/RawPotteryItem.java @@ -0,0 +1,24 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.List; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.*; +import net.minecraft.world.level.Level; + +final class RawPotteryItem extends Item { + RawPotteryItem() { super(new Properties()); } + @Override public Component getName(ItemStack stack) { return PotteryNames.display(stack, true); } + @Override public int getMaxStackSize(ItemStack stack) { + return PaintedPotEntity.fromStack(stack).size().emptyStackLimit; + } + + @Override public void appendHoverText(ItemStack stack, Level level, List lines, TooltipFlag flag) { + lines.add(Component.translatable("tooltip.primalpottery.needs_firing").withStyle(ChatFormatting.GRAY)); + if (!PaintingRegistration.dyed(stack)) { + lines.add(Component.translatable("tooltip.primalpottery.can_be_dyed").withStyle(ChatFormatting.GRAY)); + } + int capacity = PaintedPotEntity.fromStack(stack).classify().volume(); + if (capacity > 0) lines.add(Component.translatable("tooltip.primalpottery.will_contain", capacity).withStyle(ChatFormatting.DARK_GRAY)); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TreePlot.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TreePlot.java new file mode 100644 index 0000000..74f5575 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/TreePlot.java @@ -0,0 +1,275 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkSource; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.gameevent.GameEvent; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.lighting.LevelLightEngine; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.storage.LevelData; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.ticks.BlackholeTickAccess; +import net.minecraft.world.ticks.LevelTickAccess; +import javax.annotation.Nullable; + +/** A flat, private patch of soil for one vanilla feature invocation. All block writes are local. */ +final class TreePlot implements WorldGenLevel { + private final ServerLevel context; + private final RandomSource random; + private final Map blocks = new HashMap<>(); + private boolean overflow; + + TreePlot(ServerLevel context, RandomSource random) { + this.context = context; + this.random = random; + } + + @Nullable MiniatureTree harvest() { + Map visible = new HashMap<>(); + this.blocks.forEach((pos, state) -> { + if (pos.getY() >= 0 && !state.isAir()) { + visible.put(pos, state); + } + }); + return this.overflow || visible.isEmpty() ? null : new MiniatureTree(visible); + } + + @Override + public BlockState getBlockState(BlockPos pos) { + return this.blocks.getOrDefault(pos, pos.getY() < 0 ? Blocks.DIRT.defaultBlockState() : Blocks.AIR.defaultBlockState()); + } + + @Override + public boolean setBlock(BlockPos pos, BlockState state, int flags, int recursion) { + if (pos.getX() < -32 || pos.getX() >= 32 || pos.getZ() < -32 || pos.getZ() >= 32 + || pos.getY() < -16 || pos.getY() >= 64 || this.blocks.size() >= MiniatureTree.LIMIT && !this.blocks.containsKey(pos)) { + this.overflow = true; + return false; + } + this.blocks.put(pos.immutable(), state); + return true; + } + + @Override + public boolean removeBlock(BlockPos pos, boolean moving) { + return this.setBlock(pos, Blocks.AIR.defaultBlockState(), 0); + } + + @Override + public boolean destroyBlock(BlockPos pos, boolean drops, @Nullable Entity breaker, int recursion) { + return this.removeBlock(pos, false); + } + + @Override + public boolean isStateAtPosition(BlockPos pos, Predicate predicate) { + return predicate.test(this.getBlockState(pos)); + } + + @Override + public boolean isFluidAtPosition(BlockPos pos, Predicate predicate) { + return predicate.test(this.getFluidState(pos)); + } + + @Override + public FluidState getFluidState(BlockPos pos) { + return this.getBlockState(pos).getFluidState(); + } + + @Override + public int getHeight(Heightmap.Types type, int x, int z) { + for (int y = 63; y >= 0; y--) { + if (type.isOpaque().test(this.getBlockState(new BlockPos(x, y, z)))) { + return y + 1; + } + } + return 0; + } + + @Override + public List getEntities(@Nullable Entity except, AABB bounds, Predicate filter) { + return List.of(); + } + + @Override + public List getEntities(EntityTypeTest type, AABB bounds, Predicate filter) { + return List.of(); + } + + @Override + public int getMinBuildHeight() { return -16; } + + @Override + public float getShade(net.minecraft.core.Direction direction, boolean shade) { return 1; } + + @Override + public void playSound(@Nullable Player player, BlockPos pos, SoundEvent sound, SoundSource source, float volume, float pitch) {} + + @Override + public void levelEvent(@Nullable Player player, int type, BlockPos pos, int data) {} + + @Override + public void gameEvent(GameEvent event, Vec3 position, GameEvent.Context context) {} + + @Override + public void addParticle(ParticleOptions particle, double x, double y, double z, double dx, double dy, double dz) {} + + @Override + public int getHeight() { + return 80; + } + + @Override + public RandomSource getRandom() { + return this.random; + } + + @Override + public long getSeed() { + return this.context.getSeed(); + } + + @Override + public long nextSubTickCount() { + return 0; + } + + @Override + public List players() { + return List.of(); + } + + @Override + public boolean addFreshEntity(Entity entity) { + return false; + } + + @Override + public @Nullable BlockEntity getBlockEntity(BlockPos pos) { + return null; + } + + @Override + public @Nullable ChunkAccess getChunk(int x, int z, ChunkStatus status, boolean create) { + return null; + } + + @Override + public boolean hasChunk(int x, int z) { + return false; + } + + @Override + public int getSkyDarken() { + return 0; + } + + @Override + public int getSeaLevel() { + return 0; + } + + @Override + public boolean isClientSide() { + return false; + } + + @Override + public LevelTickAccess getBlockTicks() { + return BlackholeTickAccess.emptyLevelList(); + } + + @Override + public LevelTickAccess getFluidTicks() { + return BlackholeTickAccess.emptyLevelList(); + } + + @Override + public ServerLevel getLevel() { + return this.context; + } + + @Override + public MinecraftServer getServer() { + return this.context.getServer(); + } + + @Override + public ChunkSource getChunkSource() { + return this.context.getChunkSource(); + } + + @Override + public LevelData getLevelData() { + return this.context.getLevelData(); + } + + @Override + public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { + return new DifficultyInstance(this.context.getDifficulty(), 0, 0, 0); + } + + @Override + public RegistryAccess registryAccess() { + return this.context.registryAccess(); + } + + @Override + public FeatureFlagSet enabledFeatures() { + return this.context.enabledFeatures(); + } + + @Override + public BiomeManager getBiomeManager() { + return this.context.getBiomeManager(); + } + + @Override + public Holder getUncachedNoiseBiome(int x, int y, int z) { + return this.context.getUncachedNoiseBiome(x, y, z); + } + + @Override + public DimensionType dimensionType() { + return this.context.dimensionType(); + } + + @Override + public WorldBorder getWorldBorder() { + return this.context.getWorldBorder(); + } + + @Override + public LevelLightEngine getLightEngine() { + return this.context.getLightEngine(); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselChannel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselChannel.java new file mode 100644 index 0000000..ed76bf0 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselChannel.java @@ -0,0 +1,39 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.Optional; +import net.minecraft.core.BlockPos; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.InteractionHand; +import net.minecraftforge.network.NetworkDirection; +import net.minecraftforge.network.NetworkRegistry; +import net.minecraftforge.network.simple.SimpleChannel; + +public final class VesselChannel { + private static final SimpleChannel NETWORK = NetworkRegistry.newSimpleChannel( + new ResourceLocation("primalpottery", "lids"), () -> "1", "1"::equals, "1"::equals); + public static void register() { + NETWORK.registerMessage(0, Message.class, Message::write, Message::read, (message, supplier) -> { + var ctx = supplier.get(); + ctx.enqueueWork(() -> VesselInteractions.setLid(ctx.getSender(), message.hand, message.pos, message.slot, message.closed)); + ctx.setPacketHandled(true); + }, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + } + public static void send(InteractionHand hand, BlockPos pos, int slot, boolean closed) { + NETWORK.sendToServer(new Message(hand, pos, slot, closed)); + } + private record Message(InteractionHand hand, BlockPos pos, int slot, boolean closed) { + void write(FriendlyByteBuf out) { + out.writeEnum(hand); + out.writeBoolean(pos != null); + if (pos != null) { out.writeBlockPos(pos); out.writeByte(slot); } + out.writeBoolean(closed); + } + static Message read(FriendlyByteBuf in) { + InteractionHand hand = in.readEnum(InteractionHand.class); + BlockPos pos = in.readBoolean() ? in.readBlockPos() : null; + return new Message(hand, pos, pos == null ? -1 : in.readUnsignedByte(), in.readBoolean()); + } + } + private VesselChannel() {} +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselData.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselData.java new file mode 100644 index 0000000..bc46fc2 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselData.java @@ -0,0 +1,75 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Fluids; +import net.minecraft.nbt.CompoundTag; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class VesselData { + private VesselData() {} + + public static boolean lid(ItemStack stack) { return stack.hasTag() && stack.getTag().getBoolean("lid"); } + public static boolean planted(ItemStack stack) { return soil(stack) != Blocks.AIR; } + public static boolean hasExtras(ItemStack stack) { + return stack.hasTag() && (stack.getTag().getBoolean("lid") || stack.getTag().contains("soil") || stack.getTag().contains("fluid")); + } + public static CompoundTag data(ItemStack stack) { + return stack.getOrCreateTag(); + } + public static int amount(ItemStack stack) { + if (!stack.hasTag() || !stack.getTag().contains("fluid") || fluid(stack) == null) return 0; + return Math.max(0, Math.min(stack.getTag().getInt("amount"), PaintedPotEntity.fromStack(stack).classify().volume())); + } + public static String fluidId(ItemStack stack) { + return stack.hasTag() ? stack.getTag().getString("fluid") : ""; + } + public static Fluid fluid(ItemStack stack) { + String id = fluidId(stack); + if (id.isEmpty()) return null; + ResourceLocation key = ResourceLocation.tryParse(id); + Fluid fluid = key == null ? Fluids.EMPTY : BuiltInRegistries.FLUID.get(key); + return fluid == Fluids.EMPTY ? null : fluid; + } + public static void storeFluid(ItemStack stack, String id, int amount) { + CompoundTag tag = data(stack); + if (amount <= 0) { + tag.remove("fluid"); + tag.remove("amount"); + } else { + tag.putString("fluid", id); + tag.putInt("amount", amount); + } + } + + public static Block soil(ItemStack stack) { return block(stack, "soil"); } + public static Block plant(ItemStack stack) { return block(stack, "plant"); } + private static Block block(ItemStack stack, String key) { + if (!stack.hasTag()) return Blocks.AIR; + String id = stack.getTag().getString(key); + if (id.isEmpty()) return Blocks.AIR; + ResourceLocation name = ResourceLocation.tryParse(id); + return name == null ? Blocks.AIR : BuiltInRegistries.BLOCK.get(name); + } + static void setBlock(ItemStack pot, String key, Block block) { + CompoundTag tag = data(pot); + if (block == Blocks.AIR) { + tag.remove(key); + } else { + tag.putString(key, BuiltInRegistries.BLOCK.getKey(block).toString()); + } + } + public static int light(ItemStack pot) { + if (amount(pot) <= 0) return 0; + Fluid fluid = fluid(pot); + return fluid.defaultFluidState().createLegacyBlock().getLightEmission(); + } + + public static int limit(ItemStack stack) { + return planted(stack) || amount(stack) > 0 ? 1 : PaintedPotEntity.fromStack(stack).size().emptyStackLimit; + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselInteractions.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselInteractions.java new file mode 100644 index 0000000..e81a46a --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselInteractions.java @@ -0,0 +1,229 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.*; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.*; +import net.minecraft.world.phys.*; +import net.minecraftforge.common.ForgeMod; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.modcrafters.minecraft.primalpottery.vessel.VesselRules; +import net.modcrafters.minecraft.primalpottery.forge.client.VesselScreen; + +public final class VesselInteractions { + private VesselInteractions() {} + + public static int light(PaintedPotEntity pottery) { + int maximum = 0; + for (int i = 0; i < PotteryLayout.COUNT; i++) maximum = Math.max(maximum, VesselData.light(pottery.stack(i))); + return maximum; + } + public static int fluidColor(ItemStack pot) { + String id = VesselData.fluidId(pot); + if (id.equals("minecraft:water") || id.equals("water")) return 0x3f76e4; + if (id.equals("minecraft:lava") || id.equals("lava")) return 0xff7800; + return 0xffffff; + } + static Component fluidName(ItemStack pot) { + Fluid fluid = VesselData.fluid(pot); + if (fluid == null) return Component.translatable("gui.primalpottery.lid.empty"); + Component name = fluid.getFluidType().getDescription(); + return fluid == Fluids.WATER ? name.copy().withStyle(style -> style.withColor(0x3f76e4)) : name; + } + public static Component contentsLabel(ItemStack pot) { + Pottery.Info info = PaintedPotEntity.fromStack(pot).classify(); + if (!info.type().isVessel()) return Component.translatable("pottery.primalpottery.type.lump"); + return Component.translatable("gui.primalpottery.lid.contents", fluidName(pot), VesselData.amount(pot), info.volume()); + } + + private static void editOne(Player player, InteractionHand hand, Consumer edit) { + ItemStack current = player.getItemInHand(hand); + if (current.getCount() == 1) { + edit.accept(current); + return; + } + ItemStack one = current.split(1); + edit.accept(one); + player.setItemInHand(hand, one); + give(player, current); + } + private static void give(Player player, ItemStack stack) { + if (!stack.isEmpty() && !player.getInventory().add(stack)) player.drop(stack, false); + } + + public static InteractionResult useHeld(Player player, InteractionHand hand) { + ItemStack pot = player.getItemInHand(hand); + if (PaintedPotEntity.fromStack(pot).isPlate()) return InteractionResult.PASS; + InteractionResult fill = fillLookedAt(player, hand); + if (fill != InteractionResult.PASS) return fill; + if (player.level().isClientSide) VesselScreen.open(hand, null, -1, pot); + return InteractionResult.SUCCESS; + } + + public static InteractionResult beforePlace(UseOnContext context) { + Player player = context.getPlayer(); + if (player == null) return InteractionResult.PASS; + InteractionHand hand = context.getHand(); + Level world = context.getLevel(); + InteractionResult fill = fillLookedAt(player, hand); + if (fill != InteractionResult.PASS) return fill; + BlockPlaceContext place = new BlockPlaceContext(context); + BlockState state = world.getBlockState(place.getClickedPos()); + if (place.canPlace() && !state.getFluidState().isEmpty()) { + boolean source = state.getFluidState().isSource() && (state.is(Blocks.WATER) || state.is(Blocks.LAVA)); + if (!(source && player.isShiftKeyDown() && VesselData.amount(context.getItemInHand()) > 0)) return InteractionResult.FAIL; + } + return InteractionResult.PASS; + } + + private static InteractionResult fillLookedAt(Player player, InteractionHand hand) { + ItemStack pot = player.getItemInHand(hand); + int capacity = PaintedPotEntity.fromStack(pot).classify().volume(); + if (capacity <= 0 || VesselData.amount(pot) > 0) return InteractionResult.PASS; + Level world = player.level(); + Vec3 eye = player.getEyePosition(); + Vec3 end = eye.add(player.getLookAngle().scale(player.getAttributeValue(ForgeMod.BLOCK_REACH.get()))); + BlockHitResult hit = world.clip(new ClipContext(eye, end, ClipContext.Block.OUTLINE, ClipContext.Fluid.ANY, player)); + if (hit.getType() != HitResult.Type.BLOCK) return InteractionResult.PASS; + BlockPos pos = hit.getBlockPos(); + BlockState state = world.getBlockState(pos); + FluidState liquid = state.getFluidState(); + if (liquid.isEmpty() || !state.is(liquid.createLegacyBlock().getBlock())) return InteractionResult.PASS; + if (!world.mayInteract(player, pos) || !player.mayUseItemAt(pos.relative(hit.getDirection()), hit.getDirection(), pot)) return InteractionResult.FAIL; + if (!world.isClientSide && !VesselData.lid(pot) && !VesselData.planted(pot)) { + Fluid fluid = liquid.getType() instanceof FlowingFluid flowing ? flowing.getSource() : liquid.getType(); + editOne(player, hand, one -> VesselData.storeFluid(one, BuiltInRegistries.FLUID.getKey(fluid).toString(), capacity)); + fluid.getPickupSound().ifPresent(sound -> world.playSound(null, pos, sound, SoundSource.BLOCKS, 1, 1)); + } + return InteractionResult.SUCCESS; + } + + public static boolean usePlaced(PaintedPotEntity pottery, int slot, Player player, InteractionHand hand) { + ItemStack pot = pottery.stack(slot); + if (pot.isEmpty() || pottery.layout().at(slot).isPlate()) return false; + ItemStack held = player.getItemInHand(hand); + if (held.isEmpty() && hand == InteractionHand.MAIN_HAND && !player.isShiftKeyDown()) { + ItemStack offhand = player.getItemInHand(InteractionHand.OFF_HAND); + if (offhand.getItem() instanceof BlockItem) { + Block offer = ((BlockItem) offhand.getItem()).getBlock(); + if (PlanterPlants.soil(offer) || PlanterPlants.accepts(pottery.layout().at(slot).size(), offer)) held = offhand; + } + } + Level world = player.level(); + BlockPos pos = pottery.getBlockPos(); + if (held.isEmpty()) { + if (player.isShiftKeyDown()) return false; + if (VesselData.planted(pot)) { + if (!world.isClientSide) { + give(player, takePlanting(pot)); + pottery.sync(); + } + } else if (world.isClientSide) VesselScreen.open(hand, pos, slot, pot); + return true; + } + if (held.getItem() == pot.getItem()) { + int amount = VesselData.amount(held); + if (amount <= 0 || player.isShiftKeyDown()) return false; + if (world.isClientSide || VesselData.lid(pot) || VesselData.planted(pot) || VesselData.lid(held)) return true; + String id = VesselData.fluidId(held); + int stored = VesselData.amount(pot); + int move = VesselRules.transfer(id, amount, VesselData.fluidId(pot), stored, PaintedPotEntity.fromStack(pot).classify().volume()); + if (move > 0) { + VesselData.storeFluid(pot, id, stored + move); + VesselData.storeFluid(held, id, amount - move); + pottery.sync(); + world.getChunkSource().getLightEngine().checkBlock(pos); + VesselData.fluid(pot).getPickupSound().ifPresent(sound -> world.playSound(null, pos, sound, SoundSource.BLOCKS, 1, 1)); + } + return true; + } + if (!(held.getItem() instanceof BlockItem)) return false; + Block offered = ((BlockItem) held.getItem()).getBlock(); + return plant(pottery, pot, held, offered, player); + } + + private static boolean plant(PaintedPotEntity pottery, ItemStack pot, ItemStack held, Block offered, Player player) { + Pottery shape = PaintedPotEntity.fromStack(pot); + boolean soil = PlanterPlants.soil(offered); + if (soil) { + String warning = VesselRules.soilWarning(shape, VesselData.lid(pot), VesselData.amount(pot), VesselData.planted(pot)); + if (warning != null) { + if (!player.level().isClientSide) player.displayClientMessage(Component.translatable(warning, VesselRules.planterCapacity(shape)), true); + return true; + } + } else if (!PlanterPlants.accepts(shape.size(), offered)) { + return VesselData.planted(pot); + } + boolean tree = !soil && shape.size() == Pottery.Size.LARGE && PlanterPlants.sapling(offered); + boolean reroll = tree && VesselData.plant(pot) == offered; + if (!soil && (!VesselData.planted(pot) || (VesselData.plant(pot) != Blocks.AIR && !reroll))) return true; + if (!player.level().isClientSide) { + if (tree && !PlanterPlants.grow((ServerLevel) player.level(), offered, pot)) return true; + VesselData.setBlock(pot, soil ? "soil" : "plant", offered); + if (!reroll && !player.getAbilities().instabuild) held.shrink(1); + pottery.sync(); + player.level().playSound(null, pottery.getBlockPos(), offered.defaultBlockState().getSoundType() + .getPlaceSound(), SoundSource.BLOCKS, 1, 1); + } + return true; + } + + private static ItemStack takePlanting(ItemStack pot) { + String key = VesselData.plant(pot) != Blocks.AIR ? "plant" : "soil"; + Block removed = key.equals("plant") ? VesselData.plant(pot) : VesselData.soil(pot); + ItemStack drop = new ItemStack(removed); + VesselData.setBlock(pot, key, Blocks.AIR); + VesselData.data(pot).remove("tree"); + return drop; + } + public static List dropPlanting(ItemStack pot) { + List drops = new ArrayList<>(); + while (VesselData.planted(pot)) drops.add(takePlanting(pot)); + return drops; + } + + public static void setLid(Player player, InteractionHand hand, BlockPos pos, int slot, boolean closed) { + if (player.isSpectator()) return; + PaintedPotEntity pottery = null; + ItemStack stack; + if (pos == null) { + stack = player.getItemInHand(hand); + if (!(stack.getItem() instanceof VesselItem)) return; + } else { + Level world = player.level(); + if (!world.hasChunkAt(pos) || !world.mayInteract(player, pos)) return; + double reach = player.getAttributeValue(ForgeMod.BLOCK_REACH.get()) + 1; + if (player.distanceToSqr(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5) > reach * reach) return; + if (!(world.getBlockEntity(pos) instanceof PaintedPotEntity)) return; + pottery = (PaintedPotEntity) world.getBlockEntity(pos); + stack = pottery.stack(slot); + } + if (stack.isEmpty() || VesselData.lid(stack) == closed || VesselData.planted(stack) + || closed && PaintedPotEntity.fromStack(stack).cover() == null) return; + Consumer change = one -> { + if (closed) VesselData.data(one).putBoolean("lid", true); + else VesselData.data(one).remove("lid"); + }; + if (pottery == null) editOne(player, hand, change); + else { + change.accept(stack); + pottery.sync(); + } + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselItem.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselItem.java new file mode 100644 index 0000000..91a7a18 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/VesselItem.java @@ -0,0 +1,40 @@ +package net.modcrafters.minecraft.primalpottery.forge; + +import java.util.List; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.world.*; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.*; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public class VesselItem extends BlockItem { + public VesselItem(Block block, Properties properties) { super(block, properties); } + @Override public int getMaxStackSize(ItemStack stack) { return VesselData.limit(stack); } + @Override public InteractionResultHolder use(Level level, Player player, InteractionHand hand) { + return new InteractionResultHolder<>(VesselInteractions.useHeld(player, hand), player.getItemInHand(hand)); + } + @Override public InteractionResult useOn(UseOnContext context) { + InteractionResult guard = VesselInteractions.beforePlace(context); + return guard == InteractionResult.PASS ? placeVessel(context) : guard; + } + protected InteractionResult placeVessel(UseOnContext context) { + return super.useOn(context); + } + @Override public boolean isBarVisible(ItemStack stack) { return VesselData.amount(stack) > 0; } + @Override public int getBarWidth(ItemStack stack) { + int capacity = PaintedPotEntity.fromStack(stack).classify().volume(); + return capacity <= 0 ? 0 : Math.max(1, Math.round(13F * VesselData.amount(stack) / capacity)); + } + @Override public int getBarColor(ItemStack stack) { return VesselInteractions.fluidColor(stack); } + @Override public void appendHoverText(ItemStack stack, Level level, List lines, TooltipFlag flag) { + int capacity = PaintedPotEntity.fromStack(stack).classify().volume(); + if (capacity > 0) lines.add(Component.translatable("tooltip.primalpottery.capacity", capacity)); + int amount = VesselData.amount(stack); + if (amount > 0) lines.add(Component.translatable("tooltip.primalpottery.contents", VesselInteractions.fluidName(stack), amount)); + if (VesselData.lid(stack)) lines.add(Component.translatable("gui.primalpottery.lid.closed").withStyle(ChatFormatting.GRAY)); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java index f4f3679..812d88b 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/WheelEntity.java @@ -10,6 +10,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; import net.modcrafters.minecraft.primalpottery.pottery.WheelClay; import net.modcrafters.minecraft.primalpottery.template.TemplateKind; @@ -25,6 +26,14 @@ public final class WheelEntity extends BlockEntity { super(PrimalPotteryForge.WHEEL_ENTITY.get(), pos, state); } + public Pottery templateProfile() { + if (installed.isEmpty()) return null; + Pottery saved = ForgeStackProfiles.INSTANCE.read(installed); + Pottery.Size size = installed.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT) + ? Pottery.Size.LARGE : Pottery.Size.SMALL; + return saved != null && saved.size() == size ? saved : PotteryTemplates.fresh(size); + } + public ItemStack blueprintStack() { return installed; } public ItemStack visibleClay() { @@ -51,11 +60,33 @@ ItemStack takeBlueprint() { } public void tick() { - if (!clay.tick() || level.isClientSide) return; + if (!clay.tick()) return; + if (level.isClientSide) { + if (clay.target() != null && level.random.nextInt(3) == 0) spitClay(); + return; + } if (clay.momentum() == 0) synchronize(); else setChanged(); } + + private void spitClay() { + Pottery shape = clay.shape(); + if (shape == null) return; + double height = shape.height() * (.25 + .65 * level.random.nextDouble()); + double radius = PotteryProfile.sample(PotteryProfile.profile(shape.discs(), false), height) / 32; + double angle = level.random.nextDouble() * 2 * Math.PI; + double dx = Math.cos(angle), dz = Math.sin(angle); + double x = worldPosition.getX() + .5 + dx * radius, z = worldPosition.getZ() + .5 + dz * radius; + double y = worldPosition.getY() + 1 + height / 32; + double vx = .035 * dx - .1 * dz, vz = .035 * dz + .1 * dx; + boolean water = level.random.nextInt(4) == 0; + var particle = water ? net.minecraft.core.particles.ParticleTypes.SPLASH + : new net.minecraft.core.particles.BlockParticleOption(net.minecraft.core.particles.ParticleTypes.BLOCK, + net.minecraft.world.level.block.Blocks.CLAY.defaultBlockState()); + level.addParticle(particle, x, y, z, vx, water ? 0 : .08, vz); + } + boolean use(Player player, InteractionHand hand, double x, double y, double z) { ItemStack held = player.getItemInHand(hand); boolean server = !level.isClientSide; @@ -66,15 +97,9 @@ public boolean holdingBlueprint() { } public boolean emptyHand() { return held.isEmpty(); } public boolean hasBlueprint() { return !installed.isEmpty(); } - public Pottery blueprint() { - if (installed.isEmpty()) return null; - Pottery saved = ForgeStackProfiles.INSTANCE.read(installed); - Pottery.Size size = installed.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT) - ? Pottery.Size.LARGE : Pottery.Size.SMALL; - return saved != null && saved.size() == size ? saved : PotteryTemplates.fresh(size); - } + public Pottery blueprint() { return templateProfile(); } public Pottery rawShape() { - return held.getItem() == PrimalPotteryForge.RAW.get() ? ForgeStackProfiles.INSTANCE.read(held) : null; + return held.getItem() == PrimalPotteryForge.RAW.get() && !PaintingRegistration.dyed(held) ? ForgeStackProfiles.INSTANCE.read(held) : null; } public boolean holdsClay(Pottery.Size size) { return held.getItem() == (size == Pottery.Size.LARGE ? Items.CLAY : Items.CLAY_BALL); diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingClient.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingClient.java new file mode 100644 index 0000000..adf5728 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingClient.java @@ -0,0 +1,67 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import net.modcrafters.minecraft.primalpottery.forge.PaintChannel; +import net.modcrafters.minecraft.primalpottery.forge.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.painting.IconPixels; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.MenuScreens; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.*; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.*; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.ModelEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; + +@Mod.EventBusSubscriber(modid="primalpottery", bus=Mod.EventBusSubscriber.Bus.MOD, value=Dist.CLIENT) +public final class PaintingClient { + @SubscribeEvent public static void setup(FMLClientSetupEvent event) { + event.enqueueWork(() -> MenuScreens.register(PaintingRegistration.MENU.get(), PaintingScreen::new)); + } + @SubscribeEvent public static void registerModel(ModelEvent.RegisterAdditional event) { + event.register(new ResourceLocation("primalpottery", "block/dyed_clay")); + } + public static void sendStamp(Player player, BlockPos pos) { + ItemStack icon = player.getOffhandItem(); + PaintChannel.stamp(pos, Item.getId(icon.getItem()), pattern(player, icon)); + } + public static String pattern(Player player, ItemStack icon) { + int[] pixels = iconPixels(player, icon); + return pixels == null ? "" : IconPixels.quantize(pixels); + } + + /** Returns the composited icon in row-major ARGB order, or null for a model that is not a flat sprite. */ + public static int[] iconPixels(Player player, ItemStack icon) { + var client = Minecraft.getInstance(); + var model = client.getItemRenderer().getModel(icon, player.level(), player, 42); + if (icon.is(Items.TRIDENT) || icon.is(Items.SPYGLASS)) { + var id = net.minecraft.core.registries.BuiltInRegistries.ITEM.getKey(icon.getItem()); + model = client.getModelManager().getModel(new net.minecraft.client.resources.model.ModelResourceLocation(id, "inventory")); + } + if (model.isCustomRenderer() || model.isGui3d()) return null; + int[] pixels = new int[256]; + boolean foundFront = false; + for (BakedQuad quad : model.getQuads(null, null, RandomSource.create(42))) { + Direction face = quad.getDirection(); + int[] vertices = quad.getVertices(); + for (int i = 0; i < vertices.length; i += vertices.length/4) { + if (!IconPixels.spriteVertex(face.getAxis() == Direction.Axis.Z, face == Direction.SOUTH, + Float.intBitsToFloat(vertices[i]),Float.intBitsToFloat(vertices[i+1]),Float.intBitsToFloat(vertices[i+2]))) return null; + } + if (face != Direction.SOUTH) continue; + foundFront = true; + int tint = quad.isTinted() ? client.getItemColors().getColor(icon,quad.getTintIndex()) : -1; + var sprite = quad.getSprite(); + if (sprite.contents().name().getPath().equals("missingno")) return null; + IconPixels.sampleFrame(pixels, (x,y) -> { + int abgr = sprite.getPixelRGBA(0,x,y); + return abgr & 0xff00ff00 | (abgr & 255) << 16 | (abgr >>> 16 & 255); + },0,0,sprite.contents().width(),sprite.contents().height(), tint | 0xff000000); + } + return foundFront ? pixels : null; + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingScreen.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingScreen.java new file mode 100644 index 0000000..04ce01e --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PaintingScreen.java @@ -0,0 +1,103 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import com.mojang.math.Axis; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.resources.language.I18n; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.modcrafters.minecraft.primalpottery.painting.*; +import net.modcrafters.minecraft.primalpottery.forge.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.forge.PaintChannel; +import net.modcrafters.minecraft.primalpottery.forge.PaintingMenu; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PaintingScreen extends AbstractContainerScreen implements PaintPanel.Canvas { + private final PaintPanel panel; + private Button undo; + private GuiGraphics gui; + public PaintingScreen(PaintingMenu menu, Inventory inv, Component title) { + super(menu, inv, title); + imageWidth = PaintPanel.WIDTH; + imageHeight = PaintPanel.HEIGHT; + panel = new PaintPanel(menu, this); + } + private int left() { return leftPos; } + private int top() { return topPos; } + private static String label(String key, Object... args) { return I18n.get("gui.primalpottery.paint." + key,args); } + + @Override protected void init() { + super.init(); + addRenderableWidget(Button.builder(Component.literal(label("erase")), b -> panel.erase()).bounds(left()+94,top()+156,48,18).build()); + undo = addRenderableWidget(Button.builder(Component.translatable("gui.primalpottery.template.undo"), + b -> stroke(PaintBrush.UNDO)).bounds(left()+145,top()+156,44,18).build()); + addRenderableWidget(Button.builder(Component.translatable("gui.done"), b -> onClose()).bounds(left()+192,top()+156,46,18).build()); + } + @Override public void render(GuiGraphics graphics, int mx, int my, float tick) { + renderBackground(graphics); + undo.active = menu.canUndo(); + super.render(graphics,mx,my,tick); + int color = panel.tank(mx-left(), my-top()); + if (color >= 0) graphics.renderComponentTooltip(font, java.util.List.of( + PaintingRegistration.dye(color).getHoverName(), + Component.literal(label("volume", menu.volume(color))), + Component.literal(label("stock", menu.count(color))), + Component.literal(label(menu.volume(color) > 0 || menu.count(color) > 0 ? "refill" : "missing"))), mx, my); + } + @Override protected void renderLabels(GuiGraphics graphics, int mx, int my) {} + @Override protected void renderBg(GuiGraphics graphics, float tick, int mx, int my) { + gui = graphics; drawPanel(); gui = null; + } + + private void drawPanel() { + panel.draw(); + text(I18n.get("block.primalpottery.painting_table"),33,10,1); + int dye = panel.selected(); + text(dye < 0 ? label("erase") : PaintingRegistration.dye(dye).getHoverName().getString(),10,154,1); + if (dye >= 0) text(label("volume",menu.volume(dye)),10,166,1); + if (menu.potStack().isEmpty()) { text(label("hold"),119,51,1); text(label("reopen"),119,63,1); } + else if (menu.profile().isPlate()) { text(label("center"),74,26,.8F); text(label("rim"),74,113,.8F); } + } + + public void rect(int x,int y,int w,int h,int color) { + if (w > 0) gui.fill(left()+x,top()+y,left()+x+w,top()+y+h,color); + } + public void text(String label,int x,int y,float scale) { + var pose = gui.pose(); + pose.pushPose(); + pose.translate(left()+x,top()+y,0); + pose.scale(scale,scale,1); + gui.drawString(font,label,0,0,0xff392f29,false); + pose.popPose(); + } + public void preview(Pottery pot, float yaw, float tilt) { + float size = (float)(86 * 32 / Math.max(1, Math.hypot(pot.height(), pot.widestRadius()*2))); + gui.flush(); + var pose = gui.pose(); + pose.pushPose(); + pose.translate(left()+176,top()+74,80); + pose.scale(size,-size,size); + pose.mulPose(Axis.XP.rotationDegrees(tilt)); + pose.mulPose(Axis.YP.rotationDegrees(yaw)); + pose.translate(0,.5-pot.height()/64,0); + minecraft.getItemRenderer().renderStatic(menu.potStack(), ItemDisplayContext.NONE, 0xf000f0, + OverlayTexture.NO_OVERLAY, pose, gui.bufferSource(), minecraft.level, 0); + gui.flush(); + pose.popPose(); + } + public void stroke(int action) { PaintChannel.stroke(menu.containerId, action); } + + @Override public boolean mouseClicked(double x,double y,int button) { + undo.active = menu.canUndo(); + return panel.press(x-left(),y-top(),button) || super.mouseClicked(x,y,button); + } + @Override public boolean mouseDragged(double x,double y,int button,double dx,double dy) { + return panel.drag(x-left(),y-top(),button) || super.mouseDragged(x,y,button,dx,dy); + } + @Override public boolean mouseReleased(double x,double y,int button) { + panel.release(); return super.mouseReleased(x,y,button); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlacementOutline.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlacementOutline.java new file mode 100644 index 0000000..a4093b5 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlacementOutline.java @@ -0,0 +1,48 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.forge.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.forge.PotBounds; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.core.Direction; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.RenderHighlightEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) +public final class PlacementOutline { + @SubscribeEvent public static void draw(RenderHighlightEvent.Block event) { + var client = Minecraft.getInstance(); + var player = client.player; + if (player == null || client.level == null) return; + var held = player.getMainHandItem().isEmpty() ? player.getOffhandItem() : player.getMainHandItem(); + if (!PaintingRegistration.isPot(held)) return; + var hit = event.getTarget(); + var pos = hit.getBlockPos(); + Direction face = hit.getDirection(); + var entity = client.level.getBlockEntity(pos); + if (!(entity instanceof PaintedPotEntity)) { + if (face != Direction.UP) return; + pos = pos.above(); + entity = client.level.getBlockEntity(pos); + } + double x = hit.getLocation().x - pos.getX() - face.getStepX() * 1e-6; + double z = hit.getLocation().z - pos.getZ() - face.getStepZ() * 1e-6; + Pottery shape = PaintedPotEntity.fromStack(held); + int slot = entity instanceof PaintedPotEntity pots + ? pots.layout().destination(shape, x, z, player.isShiftKeyDown(), face.getStepX(), face.getStepZ()) + : PotteryLayout.preferred(shape, x, z); + if (slot < 0) return; + var camera = event.getCamera().getPosition(); + var box = PotBounds.box(slot, shape).move(pos).move(-camera.x, -camera.y, -camera.z); + LevelRenderer.renderLineBox(event.getPoseStack(), event.getMultiBufferSource().getBuffer(RenderType.lines()), + box.inflate(.002), 0, 0, 0, .42F); + event.setCanceled(true); + } + private PlacementOutline() {} +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotContentsRenderer.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotContentsRenderer.java new file mode 100644 index 0000000..427dfdd --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotContentsRenderer.java @@ -0,0 +1,29 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.world.phys.Vec3; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.EntityRenderersEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.forge.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.forge.dining.DiningRenderer; + +@Mod.EventBusSubscriber(modid = "primalpottery", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) +public final class PotContentsRenderer implements BlockEntityRenderer { + @SubscribeEvent public static void register(EntityRenderersEvent.RegisterRenderers event) { + event.registerBlockEntityRenderer(PrimalPotteryForge.ENTITY.get(), context -> new PotContentsRenderer()); + } + + @Override public boolean shouldRender(PaintedPotEntity tile, Vec3 camera) { + return tile.dining.hasVisuals() && BlockEntityRenderer.super.shouldRender(tile, camera); + } + + @Override public void render(PaintedPotEntity tile, float partial, PoseStack pose, MultiBufferSource buffers, + int light, int overlay) { + DiningRenderer.draw(tile, partial, pose, buffers, light, overlay); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java index e707d8a..c2563e5 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java @@ -24,6 +24,8 @@ import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.modcrafters.minecraft.primalpottery.forge.PaintingRegistration; @Mod.EventBusSubscriber(modid = "primalpottery", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public final class PotteryModel extends BakedModelWrapper { @@ -33,7 +35,7 @@ public final class PotteryModel extends BakedModelWrapper { private final List item; private final ItemOverrides overrides = new ItemOverrides() { @Override public BakedModel resolve(BakedModel model, ItemStack stack, ClientLevel world, LivingEntity entity, int seed) { - return new PotteryModel(originalModel, bakery, bakery.model(PaintedPotEntity.fromStack(stack))); + return new PotteryModel(originalModel, bakery, VesselModels.append(bakery.model(PaintedPotEntity.fromStack(stack), PaintingRegistration.tint(stack)), stack, PotteryLayout.CENTER)); } }; @@ -58,11 +60,27 @@ private PotteryModel(BakedModel base, PotteryQuads bakery, List item) var sheet = event.getModels().get(PAINT_SHEET).getParticleIcon(); event.getModels().replaceAll((key, base) -> { if (!key.getNamespace().equals("primalpottery") || !(key.getPath().equals("pottery") || key.getPath().equals("raw_pottery"))) return base; - var bakery = new PotteryQuads(base.getParticleIcon(), inks, sheet); + var bakery = new PotteryQuads(base.getParticleIcon(), inks, sheet, + event.getModels().get(new ResourceLocation("primalpottery", "block/dyed_clay")).getParticleIcon()); return new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE)); }); } + private List placed(PotteryLayout layout, ItemStack[] stacks) { + if (stacks == null) return bakery.placed(layout); + int first = layout.first(); + if (first < 0) return java.util.Collections.emptyList(); + if (layout.count() == 1) return placedSlot(layout, stacks, first); + List quads = new java.util.ArrayList<>(); + for (int i = first; i < PotteryLayout.COUNT; i++) { + if (layout.at(i) != null) quads.addAll(placedSlot(layout, stacks, i)); + } + return quads; + } + private List placedSlot(PotteryLayout layout, ItemStack[] stacks, int slot) { + return VesselModels.append(bakery.model(layout.at(slot), slot, layout.tint(slot)), stacks[slot], slot); + } + @Override public ItemOverrides getOverrides() { return overrides; } @Override public List getQuads(BlockState state, Direction side, RandomSource random) { @@ -71,6 +89,8 @@ private PotteryModel(BakedModel base, PotteryQuads bakery, List item) @Override public List getQuads(BlockState state, Direction side, RandomSource random, ModelData data, RenderType type) { if (side != null) return List.of(); + var layout = data.get(PaintedPotEntity.LAYOUT); + if (layout != null) return placed(layout, data.get(PaintedPotEntity.STACKS)); Pottery profile = data.get(PaintedPotEntity.PROFILE); return profile == null ? item : bakery.model(profile); } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java index 3a84a82..af403c4 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java @@ -12,8 +12,8 @@ final class PotteryQuads extends VesselQuadPacker private final PaintSheet sheet; private final int[] palette; - PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite sheet) { - super(clay, inks, 8); + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite sheet, TextureAtlasSprite dyed) { + super(clay, inks, dyed, 8); // A resource pack can animate the ink palette. Its original sprite keeps that animation live. boolean staticPalette = inks.contents().getUniqueFrames().limit(2).count() == 1; this.sheet = staticPalette && sheet instanceof PaintSheet custom && custom.supportsTiles() ? custom : null; diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java new file mode 100644 index 0000000..265de33 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java @@ -0,0 +1,169 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import java.util.*; +import java.lang.ref.WeakReference; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.RandomSource; +import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.DoubleBlockHalf; +import net.minecraft.world.level.material.Fluid; +import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; +import net.modcrafters.minecraft.primalpottery.forge.MiniatureTree; +import net.modcrafters.minecraft.primalpottery.forge.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.forge.VesselData; +import net.modcrafters.minecraft.primalpottery.forge.PlanterPlants; +import net.modcrafters.minecraft.primalpottery.vessel.VesselMesh; +import net.modcrafters.minecraft.primalpottery.vessel.VesselPreviewFrame; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +public final class VesselModels extends VesselMesh { + // A screen owns its lid-only preview stack. World and inventory models always use their complete vessel. + private static volatile WeakReference previewLid = new WeakReference<>(null); + + static ItemStack detachedLid(ItemStack vessel) { + ItemStack lid = vessel.copy(); + previewLid = new WeakReference<>(lid); + return lid; + } + + static VesselPreviewFrame frame(ItemStack pot) { + boolean planted = VesselData.planted(pot); + double radius = 0, height = 0; + if (planted) { + for (BakedQuad quad : append(Collections.emptyList(), pot, PotteryLayout.CENTER)) { + int[] vertices = quad.getVertices(); + for (int i = 0; i < vertices.length; i += vertices.length / 4) { + double x = Float.intBitsToFloat(vertices[i]) - .5; + double z = Float.intBitsToFloat(vertices[i + 2]) - .5; + radius = Math.max(radius, 32 * Math.hypot(x, z)); + height = Math.max(height, 32 * Float.intBitsToFloat(vertices[i + 1])); + } + } + } + return new VesselPreviewFrame(PaintedPotEntity.fromStack(pot), radius, height, planted); + } + + private static final Map CACHE = new WeakHashMap<>(); + private static final class Cached { + final CompoundTag tag; + final List body, decorated; + final int slot; + Cached(ItemStack pot, int slot, List body, List decorated) { + this.tag = pot.getTag() == null ? null : pot.getTag().copy(); + this.slot = slot; + this.body = body; + this.decorated = decorated; + } + } + + private VesselModels(ItemStack stack, int slot) { super(PaintedPotEntity.fromStack(stack), slot, 8); } + public static List append(List body, ItemStack stack, int slot) { + boolean lidOnly = previewLid.get() == stack; + if (!lidOnly && !VesselData.hasExtras(stack)) return body; + synchronized (CACHE) { + Cached cached = CACHE.get(stack); + if (cached != null && cached.slot == slot && cached.body == body && Objects.equals(cached.tag, stack.getTag())) return cached.decorated; + VesselModels mesh = new VesselModels(stack, slot); + if (lidOnly) { + mesh.lid(stack, true); + } else { + mesh.faces.addAll(body); + mesh.decorate(stack); + } + List decorated = Collections.unmodifiableList(mesh.faces); + CACHE.put(stack, new Cached(stack, slot, body, decorated)); + return decorated; + } + } + + private static TextureAtlasSprite sprite(ResourceLocation id) { + return Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(id); + } + + private void lid(ItemStack stack, boolean beside) { + int tint = PaintingRegistration.tint(stack); + lid(sprite(new ResourceLocation("primalpottery", tint == -1 ? "block/fired_clay" : "block/dyed_clay")), tint, beside); + } + + private void decorate(ItemStack stack) { + if (VesselData.lid(stack)) { + lid(stack, false); + return; + } + Block soil = VesselData.soil(stack); + if (soil == Blocks.AIR) { + Fluid fluid = VesselData.fluid(stack); + if (fluid != null) { + ResourceLocation texture = IClientFluidTypeExtensions.of(fluid).getStillTexture(); + if (texture != null) { + int color = IClientFluidTypeExtensions.of(fluid).getTintColor(); + surface(sprite(texture), color, VesselData.amount(stack), false); + } + } + return; + } + boolean grass = soil == Blocks.GRASS_BLOCK; + String texture = grass ? "grass_block_top" : soil == Blocks.SAND ? "sand" : "dirt"; + double ground = surface(sprite(new ResourceLocation("minecraft", "block/" + texture)), grass ? 0x78a753 : -1, 0, true); + Block plant = VesselData.plant(stack); + if (plant == Blocks.AIR) return; + if (stack.getTag().contains("tree", 9)) { + tree(stack, ground); + return; + } + BlockState state = plant.defaultBlockState(); + double size = plant == Blocks.CACTUS ? Math.min(14, radiusAt(ground) * 1.8) * scale : 14 * scale; + model(state, x - size / 2, ground, z - size / 2, size, null, null); + if (PlanterPlants.tall(plant)) { + model(state.setValue(BlockStateProperties.DOUBLE_BLOCK_HALF, DoubleBlockHalf.UPPER), + x - size / 2, ground + size, z - size / 2, size, null, null); + } + } + private void tree(ItemStack stack, double ground) { + MiniatureTree tree = MiniatureTree.load(stack.getTag().getList("tree", 10)); + if (tree == null) return; + Map voxels = tree.voxels(); + double size = 4 * scale; + voxels.forEach((pos, state) -> model(state, x + (pos.getX() - .5) * size, + ground + pos.getY() * size, z + (pos.getZ() - .5) * size, size, voxels, pos)); + } + + private void model(BlockState state, double bx, double by, double bz, double size, + Map tree, BlockPos pos) { + BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state); + boolean visible = tree == null; + for (Direction face : Direction.values()) { + BlockState neighbor = tree == null ? null : tree.get(pos.relative(face)); + if (neighbor != null && (neighbor.canOcclude() || neighbor.getBlock() == state.getBlock())) continue; + visible = true; + appendModel(model.getQuads(state, face, RandomSource.create(42)), state, bx, by, bz, size); + } + if (visible) appendModel(model.getQuads(state, null, RandomSource.create(42)), state, bx, by, bz, size); + } + private void appendModel(List source, BlockState state, double bx, double by, double bz, double size) { + for (BakedQuad quad : source) { + int tint = quad.isTinted() ? Minecraft.getInstance().getBlockColors().getColor(state, null, null, quad.getTintIndex()) : -1; + int[] data = transform(quad.getVertices(), bx, by, bz, size, tint); + faces.add(new BakedQuad(data, -1, quad.getDirection(), quad.getSprite(), quad.isShade())); + } + } + @Override protected float u(TextureAtlasSprite sprite, double pixel) { return sprite.getU(pixel); } + @Override protected float v(TextureAtlasSprite sprite, double pixel) { return sprite.getV(pixel); } + @Override protected BakedQuad makeQuad(int[] vertices, TextureAtlasSprite sprite, double nx, double ny, double nz) { + return new BakedQuad(vertices, -1, Direction.getNearest((float) nx, (float) ny, (float) nz), + sprite, true); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java new file mode 100644 index 0000000..bd86aa7 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java @@ -0,0 +1,76 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.forge.VesselChannel; +import net.modcrafters.minecraft.primalpottery.forge.VesselInteractions; +import net.modcrafters.minecraft.primalpottery.forge.VesselData; +import net.minecraft.client.Minecraft; +import net.modcrafters.minecraft.primalpottery.vessel.VesselPreviewFrame; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; + +public final class VesselScreen extends Screen { + private final InteractionHand hand; + private final BlockPos pos; + private final int slot; + private final ItemStack preview, detachedLid; + private final VesselPreviewFrame frame; + private int left, top; + private VesselScreen(InteractionHand hand, BlockPos pos, int slot, ItemStack stack) { + super(Component.translatable("block.primalpottery.pottery")); + this.hand = hand; + this.pos = pos; + this.slot = slot; + preview = stack.copy(); + preview.setCount(1); + frame = VesselModels.frame(preview); + detachedLid = !VesselData.planted(stack) && PaintedPotEntity.fromStack(stack).cover() != null + ? VesselModels.detachedLid(stack) : ItemStack.EMPTY; + } + public static void open(InteractionHand hand, BlockPos pos, int slot, ItemStack stack) { + Minecraft.getInstance().setScreen(new VesselScreen(hand, pos, slot, stack)); + } + private Component label() { + return Component.translatable(VesselData.lid(preview) ? "gui.primalpottery.lid.remove" : "gui.primalpottery.lid.put_on"); + } + private void toggle() { + boolean closed = !VesselData.lid(preview); + if (closed) VesselData.data(preview).putBoolean("lid", true); + else VesselData.data(preview).remove("lid"); + VesselChannel.send(hand, pos, slot, closed); + } + @Override public boolean isPauseScreen() { return false; } + @Override public void init() { + left = (width - 176) / 2; + top = (height - 172) / 2; + Button button = addRenderableWidget(Button.builder(label(), b -> { toggle(); b.setMessage(label()); }) + .bounds(left + 8, top + 144, 160, 20).build()); + button.active = !VesselData.planted(preview) && (VesselData.lid(preview) || PaintedPotEntity.fromStack(preview).cover() != null); + } + @Override public void render(GuiGraphics gui, int mouseX, int mouseY, float partialTick) { + renderBackground(gui); + gui.fill(left, top, left + 176, top + 172, 0xff514b46); + gui.fill(left + 2, top + 2, left + 174, top + 170, 0xffcbc6be); + gui.fillGradient(left + 8, top + 23, left + 168, top + 124, 0xff744b3b, 0xffa56f50); + gui.drawString(font, title, left + 88 - font.width(title) / 2, top + 8, 0x302a27, false); + Component contents = VesselInteractions.contentsLabel(preview); + gui.drawString(font, contents, left + 88 - font.width(contents) / 2, top + 132, 0x302a27, false); + boolean beside = !VesselData.lid(preview) && !detachedLid.isEmpty(); + drawPot(gui, preview, left + frame.x(beside, false), top + frame.y()); + if (beside) drawPot(gui, detachedLid, left + frame.x(true, true), top + frame.y()); + super.render(gui, mouseX, mouseY, partialTick); + } + + private void drawPot(GuiGraphics gui, ItemStack stack, float x, float y) { + gui.pose().pushPose(); + gui.pose().translate(x, y, 40); + gui.pose().scale(frame.scale(), frame.scale(), 1); + gui.renderItem(stack, 0, 0); + gui.pose().popPose(); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java index 445937c..723c285 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/WheelRenderer.java @@ -1,5 +1,9 @@ package net.modcrafters.minecraft.primalpottery.forge.client; +import java.util.Map; +import java.util.WeakHashMap; +import net.modcrafters.minecraft.primalpottery.wheel.WheelGuides; + import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; import net.minecraft.client.Minecraft; @@ -22,6 +26,8 @@ public final class WheelRenderer implements BlockEntityRenderer { event.registerBlockEntityRenderer(PrimalPotteryForge.WHEEL_ENTITY.get(), context -> new WheelRenderer()); } + private final Map guides = new WeakHashMap<>(); + @Override public void render(WheelEntity wheel, float partial, PoseStack pose, MultiBufferSource buffers, int light, int overlay) { Minecraft client = Minecraft.getInstance(); pose.pushPose(); @@ -35,12 +41,12 @@ public final class WheelRenderer implements BlockEntityRenderer { client.getItemRenderer().renderStatic(wheel.visibleClay(), ItemDisplayContext.NONE, light, overlay, pose, buffers, wheel.getLevel(), 0); pose.popPose(); - pose.pushPose(); - pose.translate(.14, .98, .14); - pose.mulPose(Axis.XP.rotationDegrees(90)); - pose.scale(.23F, .23F, .23F); - client.getItemRenderer().renderStatic(wheel.blueprintStack(), ItemDisplayContext.NONE, light, overlay, - pose, buffers, wheel.getLevel(), 0); - pose.popPose(); + if (wheel.blueprintStack().isEmpty()) return; + var boards = guides.computeIfAbsent(wheel.blueprintStack(), ignored -> new WheelGuides(wheel.templateProfile())); + var wood = client.getBlockRenderer().getBlockModel(net.minecraft.world.level.block.Blocks.OAK_PLANKS.defaultBlockState()).getParticleIcon(); + var output = buffers.getBuffer(RenderType.solid()); + boards.draw((x, y, z, u, v, nx, ny, nz) -> output.vertex(pose.last().pose(), x, y, z).color(255,255,255,255) + .uv(wood.getU(u), wood.getV(v)).overlayCoords(overlay).uv2(light) + .normal(pose.last().normal(), nx, ny, nz).endVertex()); } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/Dining.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/Dining.java new file mode 100644 index 0000000..5fb6540 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/Dining.java @@ -0,0 +1,119 @@ +package net.modcrafters.minecraft.primalpottery.forge.dining; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.*; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.modcrafters.minecraft.primalpottery.dining.DiningUse; +import net.modcrafters.minecraft.primalpottery.dining.TableSetting; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; + +@Mod.EventBusSubscriber(modid = "primalpottery") +public final class Dining { + public static boolean use(PaintedPotEntity tile, Player player, InteractionHand hand, double x, double y, double z) { + if (PlateMeal.blocksRepeat(player)) return true; + DiningUse action = new DiningUse(tile.dining, ItemStack.EMPTY) { + protected boolean server() { return !player.level().isClientSide; } + protected boolean empty(ItemStack stack) { return stack.isEmpty(); } + protected boolean tool(ItemStack stack) { return stack.getItem() == DiningRegistration.cutlery(); } + protected boolean displayable(ItemStack stack) { + return !stack.isEmpty() && (stack.isEdible() || !(stack.getItem() instanceof BlockItem)); + } + protected boolean sneaking() { return player.isShiftKeyDown(); } + protected InteractionHand main() { return InteractionHand.MAIN_HAND; } + protected InteractionHand off() { return InteractionHand.OFF_HAND; } + protected ItemStack held(InteractionHand h) { return player.getItemInHand(h); } + protected ItemStack takeOne(InteractionHand h) { + if (!player.getAbilities().instabuild) return held(h).split(1); + ItemStack one = held(h).copy(); + one.setCount(1); + return one; + } + protected void give(InteractionHand h, ItemStack stack) { player.setItemInHand(h, stack); } + protected void stow(ItemStack stack) { + if (!player.getInventory().add(stack)) player.drop(stack, false); + } + protected boolean eat(int slot, int serving, InteractionHand h) { return PlateMeal.start(tile, slot, serving, player, h); } + protected void takeDish(int slot, InteractionHand h) { + java.util.List loose = tile.dining.remove(slot, tile.layout().at(slot)); + give(h, tile.take(slot)); + for (ItemStack drop : loose) stow(drop); + if (tile.layout().count() == 0) player.level().removeBlock(tile.getBlockPos(), false); + } + protected void sync() { tile.sync(); } + }; + return action.use(tile.layout(), hand, x, y, z); + } + + /** A utensil can sit over an empty part of the footprint where the ray hits the support. */ + @SubscribeEvent public static void support(PlayerInteractEvent.RightClickBlock event) { + Player player = event.getEntity(); + if (player.isSpectator()) return; + Vec3 hit = event.getHitVec().getLocation(); + BlockPos clicked = event.getPos(); + boolean top = event.getFace() == Direction.UP; + var tile = player.level().getBlockEntity(clicked); + boolean support = !(tile instanceof PaintedPotEntity); + if (support && top) { + clicked = clicked.above(); + tile = player.level().getBlockEntity(clicked); + } + if (!(tile instanceof PaintedPotEntity)) return; + PaintedPotEntity pots = (PaintedPotEntity) tile; + double x = hit.x - clicked.getX(), y = hit.y - clicked.getY(), z = hit.z - clicked.getZ(); + int setting = TableSetting.settingAt(x, y, z, pots.layout()); + if (support && setting < 0 || !support && setting < 0 && !player.isShiftKeyDown()) return; + if (!use(pots, player, event.getHand(), x, y, z)) return; + event.setCancellationResult(InteractionResult.SUCCESS); + event.setCanceled(true); + } + + static BlockHitResult aim(Player player) { + HitResult hit = player.pick(player.getBlockReach(), 1, false); + return hit.getType() == HitResult.Type.BLOCK ? (BlockHitResult) hit : null; + } + + public static VoxelShape outline(PaintedPotEntity tile, VoxelShape shape) { + if (!tile.dining.hasVisuals()) return shape; + for (int slot = 4; slot < 8; slot++) { + if (tile.dining.utensil(slot).isEmpty()) continue; + for (int side = 0; side < 2; side++) { + boolean fork = side == 0; + double x = TableSetting.utensilX(slot, fork), z = TableSetting.utensilZ(slot, fork); + double w = TableSetting.halfX(slot, fork), d = TableSetting.halfZ(slot, fork); + shape = Shapes.or(shape, Shapes.box(x - w, 0, z - d, x + w, .04, z + d)); + } + } + return shape; + } + + public static ItemStack pickSetting(PaintedPotEntity tile, Vec3 hit) { + BlockPos pos = tile.getBlockPos(); + int slot = TableSetting.settingAt(hit.x - pos.getX(), hit.y - pos.getY(), hit.z - pos.getZ(), tile.layout()); + return slot < 0 ? ItemStack.EMPTY : tile.dining.utensil(slot).copy(); + } + + public static boolean breakSetting(PaintedPotEntity tile, Player player) { + BlockHitResult ray = aim(player); + if (ray == null || !ray.getBlockPos().equals(tile.getBlockPos())) return false; + Vec3 p = ray.getLocation(); + BlockPos pos = ray.getBlockPos(); + int setting = TableSetting.settingAt(p.x - pos.getX(), p.y - pos.getY(), p.z - pos.getZ(), tile.layout()); + if (setting < 0 || tile.dining.utensil(setting).isEmpty()) return false; + if (!player.level().isClientSide) { + if (!player.getAbilities().instabuild) player.drop(tile.dining.utensil(setting), false); + tile.dining.placeTool(setting, ItemStack.EMPTY); + tile.sync(); + } + return true; + } + private Dining() {} +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningInput.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningInput.java new file mode 100644 index 0000000..978d738 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningInput.java @@ -0,0 +1,25 @@ +package net.modcrafters.minecraft.primalpottery.forge.dining; + +import net.minecraft.client.Minecraft; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) +public final class DiningInput { + private static boolean pressed; + static void begin() { pressed = true; } + static boolean holdingUse() { return pressed; } + @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END || !pressed) return; + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.getConnection() == null) { + pressed = false; + } else if (mc.screen != null || !mc.options.keyUse.isDown()) { + pressed = false; + DiningRegistration.release(); + } + } + private DiningInput() {} +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRegistration.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRegistration.java new file mode 100644 index 0000000..e126693 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRegistration.java @@ -0,0 +1,35 @@ +package net.modcrafters.minecraft.primalpottery.forge.dining; + +import java.util.Optional; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.CreativeModeTabs; +import net.minecraft.world.item.Item; +import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.network.NetworkDirection; +import net.minecraftforge.network.NetworkRegistry; +import net.minecraftforge.network.simple.SimpleChannel; +import net.minecraftforge.registries.*; + +public final class DiningRegistration { + private static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, "primalpottery"); + private static final RegistryObject CUTLERY = ITEMS.register("cutlery", () -> new Item(new Item.Properties().stacksTo(1))); + private static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( + new ResourceLocation("primalpottery", "dining"), () -> "1", "1"::equals, "1"::equals); + + public static void register(IEventBus bus) { + ITEMS.register(bus); + bus.addListener((BuildCreativeModeTabContentsEvent event) -> { + if (event.getTabKey() == CreativeModeTabs.TOOLS_AND_UTILITIES) event.accept(CUTLERY.get()); + }); + CHANNEL.registerMessage(0, Released.class, (message, buffer) -> {}, buffer -> new Released(), (message, context) -> { + var player = context.get().getSender(); + context.get().enqueueWork(() -> PlateMeal.release(player)); + context.get().setPacketHandled(true); + }, Optional.of(NetworkDirection.PLAY_TO_SERVER)); + } + public static Item cutlery() { return CUTLERY.get(); } + public static void release() { CHANNEL.sendToServer(new Released()); } + private record Released() {} + private DiningRegistration() {} +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRenderer.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRenderer.java new file mode 100644 index 0000000..c7a554b --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningRenderer.java @@ -0,0 +1,125 @@ +package net.modcrafters.minecraft.primalpottery.forge.dining; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.Axis; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.renderer.*; +import net.minecraft.client.renderer.entity.player.PlayerRenderer; +import net.modcrafters.minecraft.primalpottery.forge.client.PaintingClient; +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.*; +import net.minecraft.world.phys.Vec3; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.RenderHandEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.modcrafters.minecraft.primalpottery.dining.DiningMesh; +import net.modcrafters.minecraft.primalpottery.dining.DiningScene; +import net.modcrafters.minecraft.primalpottery.dining.Point; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Dist.CLIENT) +public final class DiningRenderer extends DiningScene { + private static final ResourceLocation TOOLS = new ResourceLocation("primalpottery", "textures/block/cutlery.png"); + private static final ResourceLocation PIXEL = new ResourceLocation("primalpottery", "textures/block/serving_pixel.png"); + private final Minecraft mc = Minecraft.getInstance(); + private final PaintedPotEntity tile; + private final float partial; + private final PoseStack pose; + private final MultiBufferSource buffers; + private final int light, overlay; + private DiningRenderer(PaintedPotEntity tile, float partial, PoseStack pose, MultiBufferSource buffers, int light, int overlay) { + this.tile = tile; + this.partial = partial; + this.pose = pose; + this.buffers = buffers; + this.light = light; + this.overlay = overlay; + } + + @SubscribeEvent public static void hand(RenderHandEvent event) { + Minecraft mc = Minecraft.getInstance(); + if (mc.level == null || mc.player == null || !(mc.hitResult instanceof net.minecraft.world.phys.BlockHitResult hit)) return; + if (mc.level.getBlockEntity(hit.getBlockPos()) instanceof PaintedPotEntity tile + && tile.dining.seated(mc.player.getId())) event.setCanceled(true); + } + + public static void draw(PaintedPotEntity tile, float partial, PoseStack pose, MultiBufferSource buffers, int light, int overlay) { + if (!tile.dining.hasVisuals()) return; + pose.pushPose(); + pose.scale(1F / 32, 1F / 32, 1F / 32); + new DiningRenderer(tile, partial, pose, buffers, light, overlay).draw(tile.layout(), tile.dining, tile.getLevel().getGameTime() + partial); + pose.popPose(); + } + @Override protected boolean empty(ItemStack stack) { return stack.isEmpty(); } + @Override protected boolean soup(ItemStack stack) { + return stack.getItem() == Items.MUSHROOM_STEW || stack.getItem() == Items.RABBIT_STEW || stack.getItem() == Items.BEETROOT_SOUP || stack.getItem() == Items.SUSPICIOUS_STEW; + } + @Override protected Point mouth(int id) { + Entity eater = tile.getLevel().getEntity(id); + if (!(eater instanceof Player)) return null; + Vec3 point = eater.getEyePosition(partial).add(eater.getViewVector(partial).scale(.65)).add(0, -.11, 0); + return local(point); + } + private Point local(Vec3 point) { + return new Point(point.x - tile.getBlockPos().getX(), point.y - tile.getBlockPos().getY(), + point.z - tile.getBlockPos().getZ()).scale(32); + } + @Override protected int[] pixels(ItemStack stack) { + return PaintingClient.iconPixels(mc.player, stack); + } + @Override protected void item(ItemStack stack, Point at, double width) { + pose.pushPose(); + pose.translate(at.x, at.y, at.z); + pose.mulPose(Axis.XP.rotationDegrees(-90)); + pose.scale((float) width, (float) width, (float) width); + mc.getItemRenderer().renderStatic(stack, ItemDisplayContext.FIXED, light, overlay, pose, buffers, tile.getLevel(), 0); + pose.popPose(); + } + @Override protected void mesh(DiningMesh model, boolean food, Point at, double yaw, double pitch, double roll, double scale) { + pose.pushPose(); + pose.translate(at.x, at.y, at.z); + pose.mulPose(Axis.YP.rotationDegrees((float) yaw)); + pose.mulPose(Axis.XP.rotationDegrees((float) pitch)); + pose.mulPose(Axis.ZP.rotationDegrees((float) roll)); + pose.scale((float) scale, (float) scale, (float) scale); + VertexConsumer buffer = buffers.getBuffer(RenderType.entityCutoutNoCull(food ? PIXEL : TOOLS)); + for (DiningMesh.Face face : model.faces) { + for (int i = 0; i < 4; i++) { + Point p = face.vertices[i]; + buffer.vertex(pose.last().pose(), (float) p.x, (float) p.y, (float) p.z) + .color(face.rgb >> 16 & 255, face.rgb >> 8 & 255, face.rgb & 255, 255) + .uv(face.u[i], face.v[i]).overlayCoords(overlay).uv2(light) + .normal(pose.last().normal(), (float)face.normal.x, (float)face.normal.y, (float)face.normal.z).endVertex(); + } + } + pose.popPose(); + } + + @Override protected void arm(int player, boolean right, Point grip) { + if (mc.player == null || mc.player.getId() != player || !mc.options.getCameraType().isFirstPerson() || mc.options.hideGui + || mc.player.isInvisible()) return; + Point eye = local(mc.player.getEyePosition(partial)); + double turn = Math.toRadians(mc.player.getViewYRot(partial)); + double side = right ? 1 : -1; + Point elbow = eye.add(-side * 15 * Math.cos(turn) + 4 * Math.sin(turn), -16, -side * 15 * Math.sin(turn) - 4 * Math.cos(turn)); + Point reach = grip.subtract(elbow); + float yaw = (float) Math.toDegrees(Math.atan2(reach.x, reach.z)); + float pitch = (float) Math.toDegrees(Math.atan2(Math.hypot(reach.x, reach.z), reach.y)); + float length = (float) Math.sqrt(reach.x * reach.x + reach.y * reach.y + reach.z * reach.z); + pose.pushPose(); + pose.translate(grip.x, grip.y, grip.z); + pose.mulPose(Axis.YP.rotationDegrees(yaw)); + pose.mulPose(Axis.XP.rotationDegrees(pitch)); + pose.scale(20, length * 16 / 12, 20); + pose.translate((right ? 6.6 : -6.6) / 16, -11. / 16, 0); + PlayerRenderer renderer = (PlayerRenderer) mc.getEntityRenderDispatcher().getRenderer((AbstractClientPlayer) mc.player); + if (right) renderer.renderRightHand(pose, buffers, light, mc.player); else renderer.renderLeftHand(pose, buffers, light, mc.player); + pose.popPose(); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningTable.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningTable.java new file mode 100644 index 0000000..19d81f7 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/DiningTable.java @@ -0,0 +1,83 @@ +package net.modcrafters.minecraft.primalpottery.forge.dining; + +import java.util.function.IntFunction; +import java.util.function.ObjIntConsumer; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.world.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.dining.Diner; +import net.modcrafters.minecraft.primalpottery.dining.ServingInventory; + +public final class DiningTable extends ServingInventory { + public DiningTable() { super(ItemStack.EMPTY); } + @Override protected boolean empty(ItemStack stack) { return stack.isEmpty(); } + + public void save(CompoundTag data) { + if (!hasVisuals()) { + data.remove("servings"); + data.remove("utensils"); + return; + } + saveStacks(data, "servings", this::serving); + saveStacks(data, "utensils", this::utensil); + } + + private void saveStacks(CompoundTag data, String key, IntFunction stacks) { + ListTag list = new ListTag(); + for (int i = 0; i < PotteryLayout.COUNT; i++) { + ItemStack stack = stacks.apply(i); + if (stack.isEmpty()) continue; + CompoundTag entry = stack.save(new CompoundTag()); + entry.putByte("slot", (byte) i); + list.add(entry); + } + if (list.size() > 0) data.put(key, list); + else data.remove(key); + } + public void load(CompoundTag data) { + clear(); + loadStacks(data, "servings", (stack, slot) -> serve(slot, stack)); + loadStacks(data, "utensils", (stack, slot) -> placeTool(slot, stack)); + ListTag list = data.getList("diners", 10); + for (int i = 0; i < list.size(); i++) { + CompoundTag entry = list.getCompound(i); + int slot = entry.getByte("slot"); + if (slot < 0 || slot >= PotteryLayout.COUNT) continue; + setDiner(slot, new Diner(entry.getInt("player"), entry.getLong("start"), entry.getInt("duration"), + entry.getBoolean("cutlery"), entry.getBoolean("from_table"), entry.getBoolean("left"))); + } + } + private void loadStacks(CompoundTag data, String key, ObjIntConsumer slots) { + ListTag list = data.getList(key, 10); + for (int i = 0; i < list.size(); i++) { + CompoundTag entry = list.getCompound(i); + int slot = entry.getByte("slot"); + if (slot < 0 || slot >= PotteryLayout.COUNT) continue; + ItemStack stack = ItemStack.of(entry); + if (!stack.isEmpty()) { + stack.setCount(1); + slots.accept(stack, slot); + } + } + } + /** A player who starts watching the chunk mid-meal sees its current animation. */ + public void writeDiners(CompoundTag data) { + ListTag list = new ListTag(); + for (int i = 0; i < PotteryLayout.COUNT; i++) { + Diner diner = diner(i); + if (diner == null) continue; + CompoundTag entry = new CompoundTag(); + entry.putByte("slot", (byte) i); + entry.putInt("player", diner.player); + entry.putLong("start", diner.start); + entry.putInt("duration", diner.duration); + entry.putBoolean("cutlery", diner.cutlery); + entry.putBoolean("from_table", diner.fromTable); + entry.putBoolean("left", diner.left); + list.add(entry); + } + if (list.size() > 0) data.put("diners", list); + else data.remove("diners"); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/PlateMeal.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/PlateMeal.java new file mode 100644 index 0000000..51a84c6 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/dining/PlateMeal.java @@ -0,0 +1,149 @@ +package net.modcrafters.minecraft.primalpottery.forge.dining; + +import java.util.Map; +import java.util.WeakHashMap; +import net.minecraft.core.BlockPos; +import net.minecraft.core.particles.*; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.sounds.*; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.phys.*; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.entity.player.PlayerEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.event.ForgeEventFactory; +import net.modcrafters.minecraft.primalpottery.dining.Diner; +import net.modcrafters.minecraft.primalpottery.dining.TableSetting; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; + +@Mod.EventBusSubscriber(modid = "primalpottery") +public final class PlateMeal { + // All accesses are on the server thread. Client input only sends the release transition. + private static final Map ACTIVE = new WeakHashMap<>(); + private static final Map FINISHED_PRESS = new WeakHashMap<>(); + private final PaintedPotEntity tile; + private final int dish, serving; + private final InteractionHand hand; + private final Diner diner; + private final ItemStack displayed, held; + private final boolean toolInHand; + + private PlateMeal(PaintedPotEntity tile, int dish, int serving, InteractionHand hand, Diner diner, Player player) { + this.tile = tile; + this.dish = dish; + this.serving = serving; + this.hand = hand; + this.diner = diner; + this.held = player.getItemInHand(hand); + this.displayed = tile.dining.serving(serving); + toolInHand = held.getItem() == DiningRegistration.cutlery(); + } + + static boolean blocksRepeat(Player player) { + return player.level().isClientSide ? DiningInput.holdingUse() : FINISHED_PRESS.containsKey(player); + } + + static boolean start(PaintedPotEntity tile, int dish, int serving, Player player, InteractionHand hand) { + ItemStack food = tile.dining.serving(serving); + if (!canEat(player, food)) return false; + if (player.level().isClientSide) { + DiningInput.begin(); + return true; + } + if (ACTIVE.containsKey(player) || tile.dining.diner(serving) != null) return true; + boolean heldTool = player.getItemInHand(hand).getItem() == DiningRegistration.cutlery(); + boolean tableTool = !heldTool && player.getItemInHand(InteractionHand.MAIN_HAND).isEmpty() + && player.getItemInHand(InteractionHand.OFF_HAND).isEmpty() && !tile.dining.utensil(serving).isEmpty(); + int ticks = ForgeEventFactory.onItemUseStart(player, food, food.getUseDuration()); + if (ticks <= 0) return false; + boolean left = (player.getMainArm() == HumanoidArm.LEFT) == (hand == InteractionHand.MAIN_HAND); + Diner diner = new Diner(player.getId(), player.level().getGameTime(), heldTool || tableTool ? Math.max(96, ticks) : ticks, + heldTool || tableTool, tableTool, left); + ACTIVE.put(player, new PlateMeal(tile, dish, serving, hand, diner, player)); + tile.dining.setDiner(serving, diner); + tile.sync(); + return true; + } + + private static boolean canEat(Player player, ItemStack food) { + if (food.isEmpty() || player.isSpectator() || player.getCooldowns().isOnCooldown(food.getItem())) return false; + var properties = food.getFoodProperties(player); + return properties != null && player.canEat(properties.canAlwaysEat()); + } + + private boolean valid(Player player) { + if (!player.isAlive() || player.isShiftKeyDown() || tile.isRemoved() + || tile.getLevel() != player.level() || !canEat(player, displayed) + || tile.dining.diner(serving) != diner || tile.dining.serving(serving) != displayed) return false; + ItemStack current = player.getItemInHand(hand); + if (toolInHand ? current != held : !current.isEmpty()) return false; + if (diner.fromTable && (tile.dining.utensil(serving).isEmpty() || !player.getItemInHand(InteractionHand.OFF_HAND).isEmpty())) return false; + BlockHitResult hit = Dining.aim(player); + if (hit == null || !tile.getBlockPos().equals(hit.getBlockPos())) return false; + double x = hit.getLocation().x - tile.getBlockPos().getX(), z = hit.getLocation().z - tile.getBlockPos().getZ(); + Pottery shape = tile.layout().at(dish); + return shape != null && tile.layout().hit(x, z) == dish && TableSetting.serving(shape, dish, x, z) == serving; + } + + @SubscribeEvent public static void tick(TickEvent.PlayerTickEvent event) { + Player player = event.player; + if (event.phase != TickEvent.Phase.END || player.level().isClientSide) return; + PlateMeal meal = ACTIVE.get(player); + if (meal == null) return; + if (!meal.valid(player)) { meal.stop(player); return; } + long time = player.level().getGameTime(); + meal.effects(player, time); + if (time - meal.diner.start >= meal.diner.duration) { + meal.finish(player); + FINISHED_PRESS.put(player, true); + } + } + + public static void release(Player player) { + FINISHED_PRESS.remove(player); + PlateMeal meal = ACTIVE.get(player); + if (meal == null) return; + if (meal.diner.cutlery && player.level().getGameTime() >= meal.diner.lastSwallow() && meal.valid(player)) meal.finish(player); + else meal.stop(player); + } + + private void effects(Player player, long time) { + long elapsed = time - diner.start; + if (diner.cutlery && diner.beat(time, .12)) { + player.level().playSound(null, tile.getBlockPos(), SoundEvents.DECORATED_POT_HIT, SoundSource.PLAYERS, .32F, 1.65F); + } + if (diner.cutlery ? !diner.beat(time, .79) : elapsed < 5 || elapsed % 5 != 0) return; + Pottery plate = tile.layout().at(dish); + double x = tile.getBlockPos().getX() + TableSetting.servingX(plate, serving); + double y = tile.getBlockPos().getY() + plate.height() / 32 + .04; + double z = tile.getBlockPos().getZ() + TableSetting.servingZ(plate, serving); + ((ServerLevel) player.level()).sendParticles(new ItemParticleOption(ParticleTypes.ITEM, displayed), x, y, z, 3, .04, .035, .04, .025); + player.level().playSound(null, tile.getBlockPos(), SoundEvents.GENERIC_EAT, SoundSource.PLAYERS, .55F, 1F); + } + + private void finish(Player player) { + ItemStack working = displayed.copy(); + ItemStack result = working.finishUsingItem(player.level(), player); + result = ForgeEventFactory.onItemUseFinish(player, displayed.copy(), 0, result); + tile.dining.serve(serving, result); + stop(player); + } + private void stop(Player player) { + ACTIVE.remove(player); + if (!tile.isRemoved() && tile.dining.diner(serving) == diner) { + tile.dining.setDiner(serving, null); + tile.sync(); + } + } + @SubscribeEvent public static void logout(PlayerEvent.PlayerLoggedOutEvent event) { + Player player = event.getEntity(); + FINISHED_PRESS.remove(player); + PlateMeal meal = ACTIVE.get(player); + if (meal != null) meal.stop(player); + } +} diff --git a/forge/src/main/resources/META-INF/mods.toml b/forge/src/main/resources/META-INF/mods.toml index 6ec0832..74759c8 100644 --- a/forge/src/main/resources/META-INF/mods.toml +++ b/forge/src/main/resources/META-INF/mods.toml @@ -5,7 +5,7 @@ license="MIT" modId="primalpottery" version="${file.jarVersion}" displayName="Primal Pottery" -description="Shape clay on a wheel. Forge preview with placeable painted pottery." +description="Shape clay on a pottery wheel, fire and paint your creations, grow plants and serve meals." [[dependencies.primalpottery]] modId="minecraft" mandatory=true diff --git a/forge/src/main/resources/assets/primalpottery/blockstates/painting_table.json b/forge/src/main/resources/assets/primalpottery/blockstates/painting_table.json new file mode 100644 index 0000000..4b31b63 --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/blockstates/painting_table.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "primalpottery:block/painting_table" + } + } +} diff --git a/forge/src/main/resources/assets/primalpottery/lang/en_us.json b/forge/src/main/resources/assets/primalpottery/lang/en_us.json index 984b10a..2227d14 100644 --- a/forge/src/main/resources/assets/primalpottery/lang/en_us.json +++ b/forge/src/main/resources/assets/primalpottery/lang/en_us.json @@ -25,5 +25,45 @@ "pottery.primalpottery.shape.bowl": "Bowl", "pottery.primalpottery.shape.pottery": "Pottery", "block.primalpottery.pottery_wheel": "Pottery Wheel", - "item.primalpottery.raw_pottery": "Unfired Pottery" + "item.primalpottery.raw_pottery": "Unfired Pottery", + "item.primalpottery.cutlery": "Cutlery", + "gui.primalpottery.lid.put_on": "Put on lid", + "gui.primalpottery.lid.remove": "Remove lid", + "gui.primalpottery.lid.empty": "Empty", + "gui.primalpottery.lid.contents": "%s \u00b7 %s / %s mL", + "message.primalpottery.soil.capacity": "Too small for soil. This pottery needs at least %s mL of capacity.", + "message.primalpottery.soil.lid": "Remove the lid before adding soil.", + "message.primalpottery.soil.liquid": "Empty the liquid before adding soil.", + "message.primalpottery.soil.occupied": "This pottery already contains soil.", + "gui.primalpottery.lid.closed": "Lid fitted", + "block.primalpottery.painting_table": "Pottery Painting Table", + "gui.primalpottery.paint.center": "Center", + "gui.primalpottery.paint.rim": "Rim", + "gui.primalpottery.paint.erase": "Eraser", + "gui.primalpottery.paint.undo_cost": "Undo the last square. Restoring a color uses 1 mL of that paint.", + "gui.primalpottery.paint.volume": "%s / 100 mL", + "gui.primalpottery.paint.refill": "1 mL per square. One matching dye refills 100 mL.", + "gui.primalpottery.paint.missing": "Tank empty. Carry matching dye to paint.", + "gui.primalpottery.paint.hold": "Hold fired pottery", + "gui.primalpottery.paint.reopen": "and reopen the table.", + "gui.primalpottery.paint.stock": "%s matching dye in inventory", + "message.primalpottery.paint.missing": "Need %s to paint %s onto pottery.", + "message.primalpottery.paint.amount": "%s (%s mL)", + "message.primalpottery.paint.stamped": "Painted pottery with %s.", + "itemGroup.primalpottery": "Primal Pottery", + "item.primalpottery.raw_shape": "Raw %s", + "tooltip.primalpottery.type": "Type: %s", + "tooltip.primalpottery.needs_firing": "Needs firing", + "tooltip.primalpottery.can_be_dyed": "Can be dyed", + "tooltip.primalpottery.will_contain": "Will contain %s mL", + "tooltip.primalpottery.wheel_clay_block": "Wheel needs a clay block", + "tooltip.primalpottery.wheel_clay_ball": "Wheel needs a clay ball", + "tooltip.primalpottery.capacity": "Capacity: %s mL", + "pottery.primalpottery.type.plate": "Plate", + "pottery.primalpottery.type.platter": "Serving Platter", + "tooltip.primalpottery.contents": "%s: %s mL", + "pottery.primalpottery.type.lump": "Lump", + "pottery.primalpottery.type.pot": "Bowl", + "pottery.primalpottery.type.jar": "Pottery", + "pottery.primalpottery.type.jug": "Jug" } diff --git a/forge/src/main/resources/assets/primalpottery/models/block/dyed_clay.json b/forge/src/main/resources/assets/primalpottery/models/block/dyed_clay.json new file mode 100644 index 0000000..afd364b --- /dev/null +++ b/forge/src/main/resources/assets/primalpottery/models/block/dyed_clay.json @@ -0,0 +1,5 @@ +{ + "textures": { + "particle": "primalpottery:block/dyed_clay" + } +} diff --git a/forge/src/main/resources/data/primalpottery/loot_tables/blocks/painting_table.json b/forge/src/main/resources/data/primalpottery/loot_tables/blocks/painting_table.json new file mode 100644 index 0000000..966fbb7 --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/loot_tables/blocks/painting_table.json @@ -0,0 +1,19 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "primalpottery:painting_table" + } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } + ] + } + ] +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/cutlery.json b/forge/src/main/resources/data/primalpottery/recipes/cutlery.json new file mode 100644 index 0000000..c265fdc --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/cutlery.json @@ -0,0 +1,18 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "III", + "SSS" + ], + "key": { + "I": { + "item": "minecraft:iron_nugget" + }, + "S": { + "item": "minecraft:stick" + } + }, + "result": { + "item": "primalpottery:cutlery" + } +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/paint_pottery.json b/forge/src/main/resources/data/primalpottery/recipes/paint_pottery.json new file mode 100644 index 0000000..9054e40 --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/paint_pottery.json @@ -0,0 +1,3 @@ +{ + "type": "primalpottery:paint_pottery" +} diff --git a/forge/src/main/resources/data/primalpottery/recipes/painting_table.json b/forge/src/main/resources/data/primalpottery/recipes/painting_table.json new file mode 100644 index 0000000..31c66df --- /dev/null +++ b/forge/src/main/resources/data/primalpottery/recipes/painting_table.json @@ -0,0 +1,25 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " DF", + "PPP", + "S S" + ], + "key": { + "D": { + "item": "minecraft:white_dye" + }, + "F": { + "item": "minecraft:flower_pot" + }, + "P": { + "tag": "minecraft:planks" + }, + "S": { + "item": "minecraft:stick" + } + }, + "result": { + "item": "primalpottery:painting_table" + } +} diff --git a/legacy/forge-1.12.2/build.gradle b/legacy/forge-1.12.2/build.gradle index 2cc4bd5..b71919b 100644 --- a/legacy/forge-1.12.2/build.gradle +++ b/legacy/forge-1.12.2/build.gradle @@ -82,3 +82,7 @@ test { ext.potteryAssets = file('../../src/main/resources/assets/primalpottery') apply from: '../../forge/shared/wheel-models.gradle' + +apply from: '../../forge/shared/dining.gradle' + +apply from: '../../forge/shared/painting.gradle' diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/DyePotRecipe.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/DyePotRecipe.java new file mode 100644 index 0000000..cbc9434 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/DyePotRecipe.java @@ -0,0 +1,35 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraftforge.registries.IForgeRegistryEntry; +import net.modcrafters.minecraft.primalpottery.painting.Pigments; + +public final class DyePotRecipe extends IForgeRegistryEntry.Impl implements IRecipe { + @Override public boolean canFit(int width, int height) { return width == height && (width == 2 || width == 3); } + @Override public boolean matches(InventoryCrafting grid, World level) { return !result(grid).isEmpty(); } + @Override public ItemStack getRecipeOutput() { return ItemStack.EMPTY; } + @Override public boolean isDynamic() { return true; } + @Override public ItemStack getCraftingResult(InventoryCrafting grid) { return result(grid); } + + private ItemStack result(InventoryCrafting grid) { + ItemStack raw = ItemStack.EMPTY; + int color = -1; + for (int i = 0; i < grid.getSizeInventory(); i++) { + ItemStack stack = grid.getStackInSlot(i); + if (stack.isEmpty()) continue; + if (stack.getItem() == PrimalPotteryForge.RAW && raw.isEmpty() && !PaintingRegistration.dyed(stack)) raw = stack; + else if (color == -1 && PaintingRegistration.color(stack) >= 0) color = PaintingRegistration.color(stack); + else return ItemStack.EMPTY; + } + if (raw.isEmpty() || color < 0) return ItemStack.EMPTY; + ItemStack result = raw.copy(); + result.setCount(1); + if (!result.hasTagCompound()) result.setTagCompound(new NBTTagCompound()); + result.getTagCompound().setString("dye", Pigments.NAMES[color]); + return result; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java index bf86e97..20e7313 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe.java @@ -6,6 +6,11 @@ public final class FirePotteryRecipe { private FirePotteryRecipe() {} + public static boolean canCombine(ItemStack output, ItemStack result) { + return output.isItemEqual(result) && (result.getItem() != net.minecraft.item.Item.getItemFromBlock(PrimalPotteryForge.POT) + || ItemStack.areItemStackTagsEqual(output, result)); + } + public static ItemStack preserveProfile(ItemStack result, ItemStack input) { if (input.isEmpty() || !(input.getItem() instanceof RawPotteryItem) || result.isEmpty() || result.getItem() != net.minecraft.item.Item.getItemFromBlock(PrimalPotteryForge.POT)) return result; diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java index 5c6bb46..9d6e577 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/ForgeTemplateItem.java @@ -1,5 +1,13 @@ package net.modcrafters.minecraft.primalpottery.legacy; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; +import java.util.List; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.translation.I18n; + import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -27,4 +35,19 @@ public ActionResult onItemRightClick(World world, EntityPlayer player if (player instanceof EntityPlayerMP) TemplateChannel.EDITS.open((EntityPlayerMP) player, hand, kind); return new ActionResult<>(EnumActionResult.SUCCESS, player.getHeldItem(hand)); } + + @Override public EnumActionResult onItemUse(EntityPlayer player, World level, BlockPos pos, EnumHand hand, + EnumFacing face, float x, float y, float z) { + return onItemRightClick(level, player, hand).getType(); + } + + @Override public void addInformation(ItemStack stack, World level, List lines, ITooltipFlag flag) { + if (kind != kind.blueprint()) return; + Pottery profile = ForgeStackProfiles.INSTANCE.read(stack); + if (profile == null || profile.size() != kind.size) profile = PotteryTemplates.fresh(kind.size); + Pottery.Info info = profile.classify(); + lines.add(I18n.translateToLocalFormatted("tooltip.primalpottery.type", I18n.translateToLocalFormatted(info.type().tooltipKey()))); + lines.add(I18n.translateToLocalFormatted(kind.size == Pottery.Size.LARGE ? "tooltip.primalpottery.wheel_clay_block" : "tooltip.primalpottery.wheel_clay_ball")); + if (info.volume() > 0) lines.add(I18n.translateToLocalFormatted("tooltip.primalpottery.capacity", info.volume())); + } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintChannel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintChannel.java new file mode 100644 index 0000000..880fe18 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintChannel.java @@ -0,0 +1,55 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import io.netty.buffer.ByteBuf; +import java.nio.charset.StandardCharsets; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.network.simpleimpl.*; +import net.minecraftforge.fml.relauncher.Side; + +public final class PaintChannel { + private static final SimpleNetworkWrapper CHANNEL = NetworkRegistry.INSTANCE.newSimpleChannel("pottery_paint"); + static void register() { + CHANNEL.registerMessage((Stroke message, MessageContext ctx) -> { + EntityPlayerMP player = ctx.getServerHandler().player; + player.getServerWorld().addScheduledTask(() -> { + if (player.openContainer instanceof PaintingMenu && player.openContainer.windowId == message.window) + ((PaintingMenu)player.openContainer).apply(player, message.action); + }); + return null; + }, Stroke.class, 0, Side.SERVER); + CHANNEL.registerMessage((Stamp message, MessageContext ctx) -> { + EntityPlayerMP player = ctx.getServerHandler().player; + player.getServerWorld().addScheduledTask(() -> PaintingTableBlock.stamp(player, message.pos, message.item, message.pattern)); + return null; + }, Stamp.class, 1, Side.SERVER); + } + public static void stroke(int window, int action) { CHANNEL.sendToServer(new Stroke(window, action)); } + public static void stamp(BlockPos pos, int item, String pattern) { CHANNEL.sendToServer(new Stamp(pos, item, pattern)); } + + public static final class Stroke implements IMessage { + private int window, action; + public Stroke() {} + Stroke(int window, int action) { this.window = window; this.action = action; } + public void toBytes(ByteBuf b) { b.writeInt(window); b.writeInt(action); } + public void fromBytes(ByteBuf b) { window = b.readInt(); action = b.readInt(); } + } + public static final class Stamp implements IMessage { + private BlockPos pos; + private int item; + private String pattern; + public Stamp() {} + Stamp(BlockPos pos, int item, String pattern) { this.pos = pos; this.item = item; this.pattern = pattern; } + public void toBytes(ByteBuf b) { + b.writeLong(pos.toLong()); b.writeInt(item); b.writeBytes(pattern.getBytes(StandardCharsets.US_ASCII)); + } + public void fromBytes(ByteBuf b) { + pos = BlockPos.fromLong(b.readLong()); item = b.readInt(); + int len = b.readableBytes(); + if (len != 0 && len != 256) throw new io.netty.handler.codec.DecoderException("Invalid icon stamp dimensions"); + pattern = b.toString(b.readerIndex(), len, StandardCharsets.US_ASCII); + b.skipBytes(len); + } + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintSupply.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintSupply.java new file mode 100644 index 0000000..5f4972b --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintSupply.java @@ -0,0 +1,36 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.item.ItemStack; +import net.minecraft.entity.player.InventoryPlayer; +import net.modcrafters.minecraft.primalpottery.painting.PigmentTanks; + +/** Optionally reserve the offhand icon when the player uses a dye itself as a stamp. */ +final class PaintSupply implements PigmentTanks.Stock { + private final InventoryPlayer inventory; + private final ItemStack icon; + + PaintSupply(InventoryPlayer inventory, ItemStack icon) { + this.inventory = inventory; + this.icon = icon; + } + + private int available(ItemStack stack, int color) { + if (PaintingRegistration.color(stack) != color) return 0; + return stack.getCount() - (stack == icon ? 1 : 0); + } + public int count(int color) { + int n = 0; + for (int i = 0; i < inventory.getSizeInventory(); i++) n += available(inventory.getStackInSlot(i), color); + return n; + } + public void consume(int color, int count) { + for (int i = 0; i < inventory.getSizeInventory() && count > 0; i++) { + ItemStack stack = inventory.getStackInSlot(i); + int take = Math.min(count, available(stack, color)); + if (take == 0) continue; + stack.shrink(take); + count -= take; + } + inventory.markDirty(); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java index 4307999..c0d54b5 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java @@ -15,6 +15,7 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; import net.minecraft.world.ChunkCache; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -23,6 +24,8 @@ import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.legacy.dining.Dining; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; public final class PaintedPotBlock extends Block implements ITileEntityProvider { public static final IUnlistedProperty PROFILE = new IUnlistedProperty() { @@ -31,6 +34,18 @@ public final class PaintedPotBlock extends Block implements ITileEntityProvider public boolean isValid(Pottery pot) { return pot != null; } public String valueToString(Pottery pot) { return pot.cacheKey(); } }; + public static final IUnlistedProperty LAYOUT = new IUnlistedProperty() { + public String getName() { return "layout"; } + public Class getType() { return PotteryLayout.class; } + public boolean isValid(PotteryLayout layout) { return layout != null; } + public String valueToString(PotteryLayout layout) { return Integer.toString(layout.count()); } + }; + public static final IUnlistedProperty STACKS = new IUnlistedProperty() { + public String getName() { return "vessels"; } + public Class getType() { return ItemStack[].class; } + public boolean isValid(ItemStack[] stacks) { return stacks != null; } + public String valueToString(ItemStack[] stacks) { return Integer.toString(stacks.length); } + }; private static final AxisAlignedBB BOUNDS = new AxisAlignedBB(.25, 0, .25, .75, .5, .75); PaintedPotBlock() { @@ -40,36 +55,104 @@ public final class PaintedPotBlock extends Block implements ITileEntityProvider } @Override protected BlockStateContainer createBlockState() { - return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{PROFILE}); + return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{PROFILE, LAYOUT, STACKS}); } @Override public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { TileEntity tile = world instanceof ChunkCache ? ((ChunkCache) world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos); - return tile instanceof PaintedPotEntity ? ((IExtendedBlockState)state).withProperty(PROFILE, ((PaintedPotEntity)tile).profile()) : state; + return tile instanceof PaintedPotEntity ? ((IExtendedBlockState)state).withProperty(PROFILE, ((PaintedPotEntity)tile).profile()).withProperty(LAYOUT, ((PaintedPotEntity)tile).layout()).withProperty(STACKS, ((PaintedPotEntity)tile).snapshot()) : state; } @Override public TileEntity createNewTileEntity(World world, int metadata) { return new PaintedPotEntity(); } @Override public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT_MIPPED; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return false; } - @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { return BOUNDS; } + @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { + TileEntity tile = world.getTileEntity(pos); + if (!(tile instanceof PaintedPotEntity)) return BOUNDS; + PotteryLayout layout = ((PaintedPotEntity) tile).layout(); + AxisAlignedBB bounds = null; + for (int i = 0; i < PotteryLayout.COUNT; i++) { + if (layout.at(i) == null) continue; + AxisAlignedBB next = PotBounds.box(i, layout.at(i)); + bounds = bounds == null ? next : bounds.union(next); + } + return bounds == null ? BOUNDS : bounds; + } + @Override public RayTraceResult collisionRayTrace(IBlockState state, World level, BlockPos pos, Vec3d from, Vec3d to) { + TileEntity tile = level.getTileEntity(pos); + if (!(tile instanceof PaintedPotEntity)) return super.collisionRayTrace(state, level, pos, from, to); + PotteryLayout layout = ((PaintedPotEntity) tile).layout(); + int slot = PotBounds.nearest(layout, pos, from, to); + RayTraceResult hit = slot < 0 ? null : rayTrace(pos, from, to, PotBounds.box(slot, layout.at(slot))); + return Dining.hitSetting((PaintedPotEntity) tile, from, to, hit); + } @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { TileEntity tile = world.getTileEntity(pos); if (!world.isRemote && tile instanceof PaintedPotEntity) ((PaintedPotEntity)tile).install(stack); } + @Override public int getLightValue(IBlockState state, IBlockAccess world, BlockPos pos) { + TileEntity tile = world instanceof ChunkCache ? ((ChunkCache) world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) + : world.getTileEntity(pos); + return tile instanceof PaintedPotEntity ? ((PaintedPotEntity) tile).emission() : 0; + } + @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, + net.minecraft.util.EnumHand hand, net.minecraft.util.EnumFacing face, float x, float y, float z) { + TileEntity tile = world.getTileEntity(pos); + if (!(tile instanceof PaintedPotEntity)) return false; + PaintedPotEntity pots = (PaintedPotEntity) tile; + if (Dining.use(pots, player, hand, x, y, z)) return true; + int slot = pots.hit(x, z); + if (slot < 0) return false; + if (player.isSneaking() && player.getHeldItem(hand).isEmpty()) { + if (!world.isRemote) { + ItemStack removed = pots.take(slot); + for (ItemStack plant : VesselInteractions.dropPlanting(removed)) spawnAsEntity(world, pos, plant); + spawnAsEntity(world, pos, removed); + if (pots.layout().first() < 0) world.setBlockToAir(pos); + } + return true; + } + return VesselInteractions.usePlaced(pots, slot, player, hand); + } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult hit, World world, BlockPos pos, EntityPlayer player) { TileEntity tile = world.getTileEntity(pos); - return tile instanceof PaintedPotEntity ? ((PaintedPotEntity)tile).pickup() : new ItemStack(this); + if (!(tile instanceof PaintedPotEntity)) return new ItemStack(this); + PaintedPotEntity pots = (PaintedPotEntity) tile; + ItemStack setting = Dining.pickSetting(pots, hit.hitVec); + if (!setting.isEmpty()) return setting; + if (pots.layout().count() == 1) return pots.pickup(); + return pots.stack(pots.hit(hit.hitVec.x - pos.getX(), hit.hitVec.z - pos.getZ())).copy(); } @Override public void getDrops(NonNullList drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { TileEntity tile = world.getTileEntity(pos); - drops.add(tile instanceof PaintedPotEntity ? ((PaintedPotEntity)tile).pickup() : new ItemStack(this)); + if (tile instanceof PaintedPotEntity) drops.addAll(((PaintedPotEntity) tile).drops()); + else drops.add(new ItemStack(this)); } // Forge requests player drops after removedByPlayer. Keep the profile alive until harvest completes. @Override public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) { + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof PaintedPotEntity && Dining.breakSetting((PaintedPotEntity) tile, player)) return false; + if (tile instanceof PaintedPotEntity && ((PaintedPotEntity) tile).layout().count() > 1) { + if (!world.isRemote) { + PaintedPotEntity pots = (PaintedPotEntity) tile; + Vec3d from = player.getPositionEyes(1); + double reach = player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue() + 1; + int slot = PotBounds.nearest(pots.layout(), pos, from, from.add(player.getLookVec().scale(reach))); + if (slot < 0) return false; + java.util.List dishes = pots.dining.remove(slot, pots.layout().at(slot)); + ItemStack removed = pots.take(slot); + if (!player.capabilities.isCreativeMode) { + for (ItemStack dish : dishes) spawnAsEntity(world, pos, dish); + for (ItemStack plant : VesselInteractions.dropPlanting(removed)) spawnAsEntity(world, pos, plant); + spawnAsEntity(world, pos, removed); + } + } + return false; + } return willHarvest || super.removedByPlayer(state, world, pos, player, false); } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java index a079977..35dfdc9 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotEntity.java @@ -1,52 +1,147 @@ package net.modcrafters.minecraft.primalpottery.legacy; +import net.modcrafters.minecraft.primalpottery.legacy.dining.DiningTable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +/** Each slot keeps the complete native stack so pickup preserves finishes, contents and planter data. */ public final class PaintedPotEntity extends TileEntity { - private Pottery pot = PaintedVessel.SAMPLE; + public final DiningTable dining = new DiningTable(); + private ItemStack[] snapshot; + private int emission; + int emission() { return emission; } + private final ItemStack[] pots = new ItemStack[PotteryLayout.COUNT]; + private PotteryLayout layout = new PotteryLayout(); - public Pottery profile() { return pot; } + public PaintedPotEntity() { + Arrays.fill(pots, ItemStack.EMPTY); + put(PotteryLayout.CENTER, new ItemStack(PrimalPotteryForge.POT)); + } + public ItemStack[] snapshot() { + if (snapshot == null) snapshot = Arrays.stream(pots).map(ItemStack::copy).toArray(ItemStack[]::new); + return snapshot; + } + public int hit(double x, double z) { return layout.hit(x, z); } + public PotteryLayout layout() { return layout; } + public Pottery profile() { return layout.at(layout.first()); } + public ItemStack stack(int slot) { return layout.at(slot) == null ? ItemStack.EMPTY : pots[slot]; } public static Pottery fromStack(ItemStack stack) { Pottery profile = ForgeStackProfiles.INSTANCE.read(stack); return profile == null ? PaintedVessel.SAMPLE : profile; } - void install(ItemStack stack) { - pot = fromStack(stack); + private void put(int slot, ItemStack stack) { + snapshot = null; + pots[slot] = stack; + layout = layout.with(slot, stack.isEmpty() ? null : fromStack(stack), PaintingRegistration.tint(stack)); + } + void install(ItemStack stack) { installAt(PotteryLayout.CENTER, stack); } + void installAt(int slot, ItemStack stack) { + ItemStack single = stack.copy(); + single.setCount(1); + ForgeStackProfiles.INSTANCE.write(single, fromStack(stack)); + put(slot, single); + sync(); + } + void moveInitial(int slot) { + if (slot != PotteryLayout.CENTER && layout.count() == 1 && !pots[PotteryLayout.CENTER].isEmpty()) { + ItemStack first = pots[PotteryLayout.CENTER]; + put(PotteryLayout.CENTER, ItemStack.EMPTY); + put(slot, first); + sync(); + } + } + + public ItemStack take(int slot) { + ItemStack stack = stack(slot); + if (!stack.isEmpty()) { + put(slot, ItemStack.EMPTY); + sync(); + } + return stack; + } + public void sync() { + int previous = emission; + emission = VesselInteractions.light(this); + snapshot = null; markDirty(); + if (world == null) return; + if (emission != previous) world.checkLight(pos); IBlockState state = world.getBlockState(pos); world.notifyBlockUpdate(pos, state, state, 3); } - - ItemStack pickup() { - ItemStack result = new ItemStack(PrimalPotteryForge.POT); - ForgeStackProfiles.INSTANCE.write(result, pot); + ItemStack pickup() { return stack(layout.first()).copy(); } + List drops() { + List result = new ArrayList<>(); + for (ItemStack pot : pots) { + if (pot.isEmpty()) continue; + ItemStack drop = pot.copy(); + result.addAll(VesselInteractions.dropPlanting(drop)); + result.add(drop); + } + result.addAll(dining.drops()); return result; } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); - tag.setTag("pottery", ForgePotteryTags.save(pot)); + dining.save(tag); + NBTTagList slots = new NBTTagList(); + for (int i = 0; i < pots.length; i++) { + if (pots[i].isEmpty()) continue; + NBTTagCompound entry = pots[i].writeToNBT(new NBTTagCompound()); + entry.setByte("slot", (byte) i); + slots.appendTag(entry); + } + tag.setTag("pots", slots); + if (profile() != null) tag.setTag("pottery", ForgePotteryTags.save(profile())); return tag; } - @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); - pot = ForgePotteryTags.load(tag.getCompoundTag("pottery")); + dining.load(tag); + snapshot = null; + Arrays.fill(pots, ItemStack.EMPTY); + layout = new PotteryLayout(); + if (tag.hasKey("pots", 9)) { + NBTTagList slots = tag.getTagList("pots", 10); + for (int i = 0; i < slots.tagCount(); i++) { + NBTTagCompound entry = slots.getCompoundTagAt(i); + int slot = entry.getByte("slot"); + ItemStack stack = new ItemStack(entry); + if (slot >= 0 && slot < pots.length && stack.getItem() == net.minecraft.item.Item.getItemFromBlock(PrimalPotteryForge.POT)) { + stack.setCount(1); + put(slot, stack); + } + } + } else { + ItemStack single = new ItemStack(PrimalPotteryForge.POT); + ForgeStackProfiles.INSTANCE.write(single, ForgePotteryTags.load(tag.getCompoundTag("pottery"))); + put(PotteryLayout.CENTER, single); + } + emission = VesselInteractions.light(this); } - @Override public NBTTagCompound getUpdateTag() { return writeToNBT(new NBTTagCompound()); } - - @Override public SPacketUpdateTileEntity getUpdatePacket() { return new SPacketUpdateTileEntity(pos, 0, getUpdateTag()); } - + @Override public NBTTagCompound getUpdateTag() { + NBTTagCompound tag = writeToNBT(new NBTTagCompound()); + dining.writeDiners(tag); + return tag; + } + @Override public SPacketUpdateTileEntity getUpdatePacket() { + return new SPacketUpdateTileEntity(pos, 0, getUpdateTag()); + } @Override public void onDataPacket(NetworkManager network, SPacketUpdateTileEntity packet) { readFromNBT(packet.getNbtCompound()); world.markBlockRangeForRenderUpdate(pos, pos); diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingMenu.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingMenu.java new file mode 100644 index 0000000..971f751 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingMenu.java @@ -0,0 +1,90 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.entity.player.*; +import net.minecraft.inventory.*; +import net.minecraft.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.painting.*; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PaintingMenu extends Container implements PaintPanel.View { + private final InventoryBasic work = new InventoryBasic("Pottery", false, 1); + private final PaintingTableEntity table; + private final PaintSupply supply; + private ItemStack cachedStack = ItemStack.EMPTY; + private Pottery cachedProfile; + private final PaintBrush brush = new PaintBrush(); + private final int[] levels = new int[33]; + + public PaintingMenu(EntityPlayer owner, PaintingTableEntity table) { + InventoryPlayer inventory = owner.inventory; + this.table = table; + this.supply = new PaintSupply(inventory, ItemStack.EMPTY); + addSlotToContainer(new Slot(work, 0, 9, 6) { + @Override public boolean isItemValid(ItemStack stack) { return false; } + @Override public boolean canTakeStack(EntityPlayer player) { return false; } + }); + + } + + private int field(int index) { + if (index < 16) return table.tanks.get(index); + if (index < 32) return supply.count(index - 16); + return brush.undoCost(); + } + + @Override public void addListener(IContainerListener listener) { + super.addListener(listener); + if (table != null) for (int i = 0; i < levels.length; i++) listener.sendWindowProperty(this, i, field(i)); + } + @Override public void detectAndSendChanges() { + super.detectAndSendChanges(); + if (table == null) return; + for (int i = 0; i < levels.length; i++) { + int value = field(i); + if (levels[i] == value) continue; + levels[i] = value; + for (IContainerListener listener : listeners) listener.sendWindowProperty(this, i, value); + } + } + @Override public void updateProgressBar(int id, int value) { + if (id >= 0 && id < levels.length) levels[id] = value; + } + + public ItemStack potStack() { return work.getStackInSlot(0); } + public void accept(ItemStack held) { + if (PaintingRegistration.isPot(held)) work.setInventorySlotContents(0, held.splitStack(1)); + } + public Pottery profile() { + ItemStack current = potStack(); + if (cachedStack != current) { + cachedStack = current; + cachedProfile = current.isEmpty() ? null : PaintedPotEntity.fromStack(current); + } + return cachedProfile; + } + public int tint() { return PaintingRegistration.tint(potStack()); } + public int volume(int i) { return table == null ? levels[i] : field(i); } + public int count(int i) { return table == null ? levels[16+i] : field(16+i); } + public boolean canUndo() { + int cost = table == null ? levels[32] : brush.undoCost(); + return cost == 1 || cost >= 2 && (volume(cost-2) > 0 || count(cost-2) > 0); + } + @Override public boolean canInteractWith(EntityPlayer player) { + return table == null || !table.isInvalid() && table.getWorld() == player.world + && player.getDistanceSqToCenter(table.getPos()) <= 64; + } + void apply(EntityPlayer player, int action) { + if (table == null || player.isSpectator() || !canInteractWith(player) || potStack().getCount() != 1) return; + Pottery result = brush.apply(profile(), action, table.tanks, supply); + if (result == null) return; + ForgeStackProfiles.INSTANCE.write(potStack(), result); + cachedProfile = result; + table.markDirty(); + detectAndSendChanges(); + } + @Override public ItemStack transferStackInSlot(EntityPlayer player, int index) { return ItemStack.EMPTY; } + @Override public void onContainerClosed(EntityPlayer player) { + super.onContainerClosed(player); + if (!player.world.isRemote) clearContainer(player, player.world, work); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingRegistration.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingRegistration.java new file mode 100644 index 0000000..edad088 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingRegistration.java @@ -0,0 +1,64 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.*; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.event.RegistryEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.network.IGuiHandler; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.registry.GameRegistry; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.modcrafters.minecraft.primalpottery.painting.Pigments; + +public final class PaintingRegistration implements IGuiHandler { + public static final PaintingTableBlock TABLE = new PaintingTableBlock(); + static Object mod; + public static void register(Object instance) { + mod = instance; + NetworkRegistry.INSTANCE.registerGuiHandler(instance, new PaintingRegistration()); + GameRegistry.registerTileEntity(PaintingTableEntity.class, new ResourceLocation("primalpottery", "painting_table")); + PaintChannel.register(); + } + @Mod.EventBusSubscriber(modid = "primalpottery") + public static final class Registry { + @SubscribeEvent public static void blocks(RegistryEvent.Register event) { + event.getRegistry().register(TABLE.setRegistryName("primalpottery", "painting_table")); + } + @SubscribeEvent public static void items(RegistryEvent.Register event) { + event.getRegistry().register(new ItemBlock(TABLE).setRegistryName(TABLE.getRegistryName())); + } + @SubscribeEvent public static void recipes(RegistryEvent.Register event) { + event.getRegistry().register(new DyePotRecipe().setRegistryName("primalpottery", "paint_pottery")); + } + } + + public Object getServerGuiElement(int id, EntityPlayer player, World level, int x, int y, int z) { + if (id != 23 || !(level.getTileEntity(new BlockPos(x,y,z)) instanceof PaintingTableEntity)) return null; + return new PaintingMenu(player, (PaintingTableEntity) level.getTileEntity(new BlockPos(x,y,z))); + } + @SideOnly(Side.CLIENT) + public Object getClientGuiElement(int id, EntityPlayer player, World level, int x, int y, int z) { + return id == 23 ? new net.modcrafters.minecraft.primalpottery.legacy.client.PaintingScreen(new PaintingMenu(player, null)) : null; + } + public static int color(ItemStack stack) { + return stack.getItem() == Items.DYE && stack.getMetadata() >= 0 && stack.getMetadata() <= 15 ? 15 - stack.getMetadata() : -1; + } + public static ItemStack dye(int color) { + return new ItemStack(Items.DYE, 1, 15 - color); + } + public static int tint(ItemStack stack) { + return stack.hasTagCompound() ? Pigments.clayTint(stack.getTagCompound().getString("dye")) : -1; + } + public static boolean dyed(ItemStack stack) { return tint(stack) != -1; } + public static boolean isPot(ItemStack stack) { return stack.getItem() == Item.getItemFromBlock(PrimalPotteryForge.POT); } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableBlock.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableBlock.java new file mode 100644 index 0000000..e96e925 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableBlock.java @@ -0,0 +1,109 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.block.state.IBlockState; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.*; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.TextComponentTranslation; +import net.minecraft.world.World; +import net.modcrafters.minecraft.primalpottery.pottery.*; +import net.modcrafters.minecraft.primalpottery.painting.PigmentTanks; + +public final class PaintingTableBlock extends Block { + private static final AxisAlignedBB[] SHAPE = { + box(0, 12, 0, 16, 16, 16), box(1, 0, 1, 4, 12, 4), box(12, 0, 1, 15, 12, 4), + box(1, 0, 12, 4, 12, 15), box(12, 0, 12, 15, 12, 15) + }; + + private static AxisAlignedBB box(int x, int y, int z, int endX, int endY, int endZ) { + return new AxisAlignedBB(x / 16d, y / 16d, z / 16d, endX / 16d, endY / 16d, endZ / 16d); + } + + PaintingTableBlock() { + super(Material.WOOD); + setHardness(2); + setUnlocalizedName("primalpottery.painting_table"); + setCreativeTab(CreativeTabs.DECORATIONS); + } + @Override public boolean hasTileEntity(IBlockState state) { return true; } + @Override public TileEntity createTileEntity(World level, IBlockState state) { return new PaintingTableEntity(); } + @Override public boolean isOpaqueCube(IBlockState state) { return false; } + @Override public boolean isFullCube(IBlockState state) { return false; } + @Override public void addCollisionBoxToList(IBlockState state, World level, BlockPos pos, AxisAlignedBB entityBox, + List collisions, Entity entity, boolean actualState) { + for (AxisAlignedBB part : SHAPE) addCollisionBoxToList(pos, entityBox, collisions, part); + } + + @Override public RayTraceResult collisionRayTrace(IBlockState state, World level, BlockPos pos, Vec3d from, Vec3d to) { + RayTraceResult nearest = null; + for (AxisAlignedBB part : SHAPE) { + RayTraceResult hit = rayTrace(pos, from, to, part); + if (hit != null && (nearest == null || from.squareDistanceTo(hit.hitVec) < from.squareDistanceTo(nearest.hitVec))) nearest = hit; + } + return nearest; + } + + @Override public boolean onBlockActivated(World level, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, + EnumFacing face, float x, float y, float z) { + if (player.openContainer != player.inventoryContainer) return true; + if (canStamp(player)) { + if (level.isRemote) net.modcrafters.minecraft.primalpottery.legacy.client.PaintingClient.sendStamp(player, pos); + } else if (!level.isRemote) open(player, pos); + return true; + } + private static void open(EntityPlayer player, BlockPos pos) { + player.openGui(PaintingRegistration.mod, 23, player.world, pos.getX(), pos.getY(), pos.getZ()); + if (!(player.openContainer instanceof PaintingMenu)) return; + PaintingMenu menu = (PaintingMenu) player.openContainer; + ItemStack main = player.getHeldItemMainhand(); + menu.accept(PaintingRegistration.isPot(main) ? main : player.getHeldItemOffhand()); + } + private static boolean canStamp(EntityPlayer player) { + ItemStack held = player.getHeldItemMainhand(), icon = player.getHeldItemOffhand(); + return PaintingRegistration.isPot(held) && !icon.isEmpty() && !(icon.getItem() instanceof ItemBlock) + && !PaintedPotEntity.fromStack(held).isPlate(); + } + static void stamp(EntityPlayer player, BlockPos pos, int itemId, String pixels) { + World level = player.world; + ItemStack icon = player.getHeldItemOffhand(); + if (player.isSpectator() || !canStamp(player) || player.openContainer != player.inventoryContainer + || !level.isBlockLoaded(pos) || !level.isBlockModifiable(player, pos) + || player.getDistanceSqToCenter(pos) > 36 + || net.minecraft.item.Item.getIdFromItem(icon.getItem()) != itemId + || !(level.getTileEntity(pos) instanceof PaintingTableEntity)) return; + if (pixels.isEmpty()) { open(player, pos); return; } + if (pixels.length() != FacePaint.CELLS || !pixels.chars().allMatch(c -> c == '.' || c >= 'A' && c < 'A' + 16)) return; + FacePaint pattern = FacePaint.read(pixels); + ItemStack held = player.getHeldItemMainhand(); + Pottery pot = PaintedPotEntity.fromStack(held); + if (pattern.equals(FacePaint.EMPTY) || pattern.equals(pot.paint())) return; + PaintingTableEntity table = (PaintingTableEntity) level.getTileEntity(pos); + TextComponentString missing = new TextComponentString(""); + PigmentTanks.Shortage report = (color, amount) -> { + if (!missing.getSiblings().isEmpty()) missing.appendText(", "); + missing.appendSibling(new TextComponentTranslation("message.primalpottery.paint.amount", PaintingRegistration.dye(color).getTextComponent(), amount)); + }; + if (table.tanks.stamp(pot.paint(), pattern, new PaintSupply(player.inventory, icon), report) >= 0) { + player.sendMessage(new TextComponentTranslation("message.primalpottery.paint.missing", missing, icon.getTextComponent())); + return; + } + ItemStack result = held.splitStack(1); + ForgeStackProfiles.INSTANCE.write(result, pot.withPaint(pattern)); + if (held.isEmpty()) player.setHeldItem(EnumHand.MAIN_HAND, result); + else if (!player.inventory.addItemStackToInventory(result)) player.dropItem(result, false); + table.markDirty(); + player.sendStatusMessage(new TextComponentTranslation("message.primalpottery.paint.stamped", icon.getTextComponent()), true); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableEntity.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableEntity.java new file mode 100644 index 0000000..05fe6e7 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintingTableEntity.java @@ -0,0 +1,23 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.modcrafters.minecraft.primalpottery.painting.PigmentTanks; +import net.modcrafters.minecraft.primalpottery.painting.Pigments; + +public final class PaintingTableEntity extends TileEntity { + public final PigmentTanks tanks = new PigmentTanks(); + + @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { + super.writeToNBT(tag); + NBTTagCompound paint = new NBTTagCompound(); + for (int i = 0; i < Pigments.NAMES.length; i++) paint.setInteger(Pigments.NAMES[i], tanks.get(i)); + tag.setTag("tanks", paint); + return tag; + } + @Override public void readFromNBT(NBTTagCompound tag) { + super.readFromNBT(tag); + NBTTagCompound paint = tag.getCompoundTag("tanks"); + for (int i = 0; i < Pigments.NAMES.length; i++) tanks.set(i, paint.getInteger(Pigments.NAMES[i])); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PlanterPlants.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PlanterPlants.java new file mode 100644 index 0000000..a47719e --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PlanterPlants.java @@ -0,0 +1,65 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import java.util.*; +import net.minecraft.block.Block; +import net.minecraft.block.BlockSapling; +import net.minecraft.block.BlockPlanks; +import net.minecraft.block.BlockOldLog; +import net.minecraft.block.BlockOldLeaf; +import net.minecraft.block.BlockLeaves; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.WorldServer; +import net.minecraft.world.gen.feature.*; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PlanterPlants { + private PlanterPlants() {} + + static boolean sapling(Block block) { return block instanceof BlockSapling; } + public static boolean tall(Block block) { return block == Blocks.DOUBLE_PLANT; } + static boolean soil(Block block) { + return block == Blocks.DIRT || block == Blocks.GRASS || block == Blocks.SAND; + } + + static boolean accepts(Pottery.Size size, Block block, int meta) { + return block == Blocks.RED_FLOWER || block == Blocks.YELLOW_FLOWER || block == Blocks.SAPLING + || block == Blocks.RED_MUSHROOM || block == Blocks.BROWN_MUSHROOM || block == Blocks.CACTUS + || block == Blocks.DEADBUSH || block == Blocks.TALLGRASS && meta != 0 + || size == Pottery.Size.LARGE && tall(block); + } + + private static WorldGenerator feature(int meta, Random random) { + switch (BlockPlanks.EnumType.byMetadata(meta)) { + case BIRCH: return new WorldGenBirchTree(false, false); + case SPRUCE: return new WorldGenTaiga2(false); + case DARK_OAK: return new WorldGenCanopyTree(false); + case ACACIA: return new WorldGenSavannaTree(false); + case JUNGLE: + IBlockState log = Blocks.LOG.getDefaultState().withProperty(BlockOldLog.VARIANT, BlockPlanks.EnumType.JUNGLE); + IBlockState leaves = Blocks.LEAVES.getDefaultState().withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE) + .withProperty(BlockLeaves.CHECK_DECAY, false); + return new WorldGenTrees(false, 4 + random.nextInt(7), log, leaves, false); + default: return random.nextInt(10) == 0 ? new WorldGenBigTree(false) : new WorldGenTrees(false); + } + } + + static boolean grow(WorldServer world, Block block, int meta, ItemStack pot) { + Random random = new Random(world.rand.nextLong()); + NBTTagList previous = VesselData.data(pot).getTagList("tree", 10); + WorldGenerator feature = feature(meta, random); + for (int attempt = 0; attempt < 4; attempt++) { + TreePlot plot = new TreePlot(world); + if (!feature.generate(plot, random, TreePlot.ROOT)) continue; + NBTTagList tree = plot.harvest(); + if (tree != null && !previous.equals(tree)) { + VesselData.data(pot).setTag("tree", tree); + return true; + } + } + return false; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotBounds.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotBounds.java new file mode 100644 index 0000000..06c3754 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotBounds.java @@ -0,0 +1,39 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +public final class PotBounds { + private PotBounds() {} + public static AxisAlignedBB box(int slot, Pottery pot) { + double x = PotteryLayout.centerX(slot, pot), z = PotteryLayout.centerZ(slot, pot); + double radius = pot.size() == Pottery.Size.LARGE ? .5 : .25; + double height = pot.size() == Pottery.Size.LARGE ? 1 : .5; + if (pot.isPlate()) { + radius = pot.isPlatter() ? pot.widestRadius() / 32 : 1./6; + height = pot.isPlatter() ? pot.height() / 32 : 3./32; + } + return new AxisAlignedBB(x - radius, 0, z - radius, x + radius, height, z + radius); + } + + static int nearest(PotteryLayout layout, BlockPos pos, Vec3d from, Vec3d to) { + int nearest = -1; + double distance = Double.POSITIVE_INFINITY; + for (int i = 0; i < PotteryLayout.COUNT; i++) { + Pottery pot = layout.at(i); + if (pot == null) continue; + RayTraceResult hit = box(i, pot).offset(pos).calculateIntercept(from, to); + if (hit == null) continue; + double candidate = from.squareDistanceTo(hit.hitVec); + if (candidate < distance) { + distance = candidate; + nearest = i; + } + } + return nearest; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java new file mode 100644 index 0000000..a247669 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java @@ -0,0 +1,48 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +public final class PotteryBlockItem extends VesselItem { + PotteryBlockItem(Block pottery) { super(pottery); setMaxStackSize(1); } + + @Override protected EnumActionResult placeVessel(EntityPlayer player, World level, BlockPos clicked, EnumHand hand, + EnumFacing face, float hitX, float hitY, float hitZ) { + ItemStack held = player.getHeldItem(hand); + BlockPos dest = level.getBlockState(clicked).getBlock().isReplaceable(level, clicked) ? clicked : clicked.offset(face); + TileEntity existing = level.getTileEntity(clicked); + if (!(existing instanceof PaintedPotEntity) && face == EnumFacing.UP) existing = level.getTileEntity(clicked.up()); + double x = hitX - face.getDirectionVec().getX() * 1e-6; + double z = hitZ - face.getDirectionVec().getZ() * 1e-6; + Pottery profile = PaintedPotEntity.fromStack(held); + if (existing instanceof PaintedPotEntity) { + PaintedPotEntity pottery = (PaintedPotEntity) existing; + int slot = pottery.layout().destination(profile, x, z, player.isSneaking(), + face.getDirectionVec().getX(), face.getDirectionVec().getZ()); + if (slot < 0 || !player.canPlayerEdit(pottery.getPos(), face, held)) return EnumActionResult.FAIL; + if (!level.isRemote) { + pottery.installAt(slot, held); + level.playSound(null, pottery.getPos(), net.minecraft.init.SoundEvents.BLOCK_STONE_PLACE, net.minecraft.util.SoundCategory.BLOCKS, 1, .8F); + if (!player.capabilities.isCreativeMode) held.shrink(1); + } + return EnumActionResult.SUCCESS; + } + EnumActionResult placed = super.placeVessel(player, level, clicked, hand, face, hitX, hitY, hitZ); + if (placed == EnumActionResult.SUCCESS && !level.isRemote && level.getTileEntity(dest) instanceof PaintedPotEntity) { + ((PaintedPotEntity) level.getTileEntity(dest)).moveInitial(PotteryLayout.preferred(profile, x, z)); + } + return placed; + } + + @Override public String getItemStackDisplayName(ItemStack stack) { + return PotteryNames.display(stack, false); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryNames.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryNames.java new file mode 100644 index 0000000..07b326e --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryNames.java @@ -0,0 +1,29 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.translation.I18n; +import net.modcrafters.minecraft.primalpottery.painting.Pigments; + +final class PotteryNames { + private PotteryNames() {} + + private static final TextFormatting[] DYE_TEXT = { + TextFormatting.WHITE, TextFormatting.GOLD, TextFormatting.LIGHT_PURPLE, TextFormatting.AQUA, + TextFormatting.YELLOW, TextFormatting.GREEN, TextFormatting.LIGHT_PURPLE, TextFormatting.DARK_GRAY, + TextFormatting.GRAY, TextFormatting.DARK_AQUA, TextFormatting.DARK_PURPLE, TextFormatting.BLUE, + TextFormatting.GOLD, TextFormatting.DARK_GREEN, TextFormatting.RED, TextFormatting.BLACK + }; + + static String display(ItemStack stack, boolean raw) { + String shape = I18n.translateToLocal(PaintedPotEntity.fromStack(stack).classify().type().shapeKey()); + String name = raw ? I18n.translateToLocalFormatted("item.primalpottery.raw_shape", shape) : shape; + if (stack.hasTagCompound()) { + String dye = stack.getTagCompound().getString("dye"); + for (int i = 0; i < Pigments.NAMES.length; i++) { + if (Pigments.NAMES[i].equals(dye)) return DYE_TEXT[i] + name + TextFormatting.RESET; + } + } + return name; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryTab.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryTab.java new file mode 100644 index 0000000..956226d --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryTab.java @@ -0,0 +1,19 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.modcrafters.minecraft.primalpottery.legacy.dining.DiningRegistration; +import net.modcrafters.minecraft.primalpottery.template.TemplateKind; + +final class PotteryTab extends CreativeTabs { + PotteryTab() { super("primalpottery"); } + @Override public ItemStack getTabIconItem() { return new ItemStack(PrimalPotteryForge.WHEEL); } + @Override public void displayAllRelevantItems(NonNullList items) { + items.add(new ItemStack(PrimalPotteryForge.WHEEL)); + items.add(new ItemStack(PaintingRegistration.TABLE)); + items.add(new ItemStack(DiningRegistration.cutlery())); + items.add(new ItemStack(PrimalPotteryForge.template(TemplateKind.SMALL_RAW))); + items.add(new ItemStack(PrimalPotteryForge.template(TemplateKind.LARGE_RAW))); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java index 796750a..c0b87e4 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PrimalPotteryForge.java @@ -29,6 +29,9 @@ public static Item template(TemplateKind kind) { @Mod.EventHandler public void setup(FMLPreInitializationEvent event) { GameRegistry.registerTileEntity(WheelEntity.class, new ResourceLocation("primalpottery", "pottery_wheel")); + new PotteryTab(); + VesselChannel.register(); + PaintingRegistration.register(this); TemplateChannel.register(); GameRegistry.registerTileEntity(PaintedPotEntity.class, ID); } @@ -50,6 +53,6 @@ public static Item template(TemplateKind kind) { TEMPLATES.put(kind, template); event.getRegistry().register(template); } - event.getRegistry().register(new ItemBlock(POT).setRegistryName(ID).setMaxStackSize(1)); + event.getRegistry().register(new PotteryBlockItem(POT).setRegistryName(ID)); } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java index 62cb633..c4d012d 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/RawPotteryItem.java @@ -1,6 +1,25 @@ package net.modcrafters.minecraft.primalpottery.legacy; +import java.util.List; +import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.util.text.translation.I18n; +import net.minecraft.world.World; -/** Marker used by the legacy furnace before the mod registry is available during vanilla bootstrap. */ -final class RawPotteryItem extends Item {} +final class RawPotteryItem extends Item { + @Override public String getItemStackDisplayName(ItemStack stack) { return PotteryNames.display(stack, true); } + @Override public int getItemStackLimit(ItemStack stack) { + return PaintedPotEntity.fromStack(stack).size().emptyStackLimit; + } + + @Override public void addInformation(ItemStack stack, World level, List lines, ITooltipFlag flag) { + lines.add(TextFormatting.GRAY + I18n.translateToLocal("tooltip.primalpottery.needs_firing")); + if (!PaintingRegistration.dyed(stack)) { + lines.add(TextFormatting.GRAY + I18n.translateToLocal("tooltip.primalpottery.can_be_dyed")); + } + int capacity = PaintedPotEntity.fromStack(stack).classify().volume(); + if (capacity > 0) lines.add(TextFormatting.DARK_GRAY + I18n.translateToLocalFormatted("tooltip.primalpottery.will_contain", capacity)); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TreePlot.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TreePlot.java new file mode 100644 index 0000000..0028488 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/TreePlot.java @@ -0,0 +1,56 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import java.util.*; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.nbt.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.*; +import net.minecraft.world.chunk.IChunkProvider; + +/** A private patch of soil for vanilla's 1.12 tree generators. It has no loaded chunks. */ +final class TreePlot extends World { + static final BlockPos ROOT = new BlockPos(0, 32, 0); + private final Map blocks = new HashMap<>(); + private boolean overflow; + + TreePlot(WorldServer context) { + super(context.getSaveHandler(), context.getWorldInfo(), new WorldProviderSurface(), context.profiler, false); + } + @Override protected IChunkProvider createChunkProvider() { return null; } + @Override protected boolean isChunkLoaded(int x, int z, boolean empty) { return false; } + @Override public IBlockState getBlockState(BlockPos pos) { + return blocks.getOrDefault(pos, pos.getY() < ROOT.getY() ? Blocks.DIRT.getDefaultState() : Blocks.AIR.getDefaultState()); + } + @Override public boolean setBlockState(BlockPos pos, IBlockState state, int flags) { + int y = pos.getY() - ROOT.getY(); + if (pos.getX() < -32 || pos.getX() >= 32 || pos.getZ() < -32 || pos.getZ() >= 32 + || y < -16 || y >= 64 || blocks.size() >= 8192 && !blocks.containsKey(pos)) { + overflow = true; + return false; + } + blocks.put(pos.toImmutable(), state); + return true; + } + + NBTTagList harvest() { + if (overflow) return null; + Map> byState = new LinkedHashMap<>(); + blocks.forEach((pos, state) -> { + int y = pos.getY() - ROOT.getY(); + if (y >= 0 && state.getBlock() != Blocks.AIR) { + byState.computeIfAbsent(state, ignored -> new ArrayList<>()).add((pos.getX() + 32) | (pos.getZ() + 32) << 6 | y << 12); + } + }); + NBTTagList groups = new NBTTagList(); + byState.forEach((state, positions) -> { + NBTTagCompound group = new NBTTagCompound(); + group.setString("block", state.getBlock().getRegistryName().toString()); + group.setInteger("meta", state.getBlock().getMetaFromState(state)); + group.setIntArray("positions", positions.stream().mapToInt(Integer::intValue).toArray()); + groups.appendTag(group); + }); + return groups.hasNoTags() ? null : groups; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselChannel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselChannel.java new file mode 100644 index 0000000..116b6ea --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselChannel.java @@ -0,0 +1,48 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.network.simpleimpl.*; +import net.minecraftforge.fml.relauncher.Side; + +public final class VesselChannel { + private static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel("pottery_lids"); + + public static void register() { + NETWORK.registerMessage((Message packet, MessageContext ctx) -> { + EntityPlayerMP player = ctx.getServerHandler().player; + player.getServerWorld().addScheduledTask(() -> + VesselInteractions.setLid(player, packet.hand, packet.pos, packet.slot, packet.closed)); + return null; + }, Message.class, 0, Side.SERVER); + } + public static void send(EnumHand hand, BlockPos pos, int slot, boolean closed) { + Message msg = new Message(); + msg.hand = hand; + msg.pos = pos; + msg.slot = slot; + msg.closed = closed; + NETWORK.sendToServer(msg); + } + public static final class Message implements IMessage { + private EnumHand hand; + private BlockPos pos; + private int slot; + private boolean closed; + public void toBytes(ByteBuf out) { + out.writeBoolean(hand == EnumHand.MAIN_HAND); + out.writeBoolean(pos != null); + if (pos != null) { out.writeLong(pos.toLong()); out.writeByte(slot); } + out.writeBoolean(closed); + } + public void fromBytes(ByteBuf in) { + hand = in.readBoolean() ? EnumHand.MAIN_HAND : EnumHand.OFF_HAND; + if (in.readBoolean()) { pos = BlockPos.fromLong(in.readLong()); slot = in.readUnsignedByte(); } + closed = in.readBoolean(); + } + } + private VesselChannel() {} +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselData.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselData.java new file mode 100644 index 0000000..c1309ff --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselData.java @@ -0,0 +1,75 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class VesselData { + private VesselData() {} + + public static boolean lid(ItemStack stack) { return stack.hasTagCompound() && stack.getTagCompound().getBoolean("lid"); } + public static boolean planted(ItemStack stack) { return soil(stack) != Blocks.AIR; } + public static boolean hasExtras(ItemStack stack) { + return stack.hasTagCompound() && (stack.getTagCompound().getBoolean("lid") || stack.getTagCompound().hasKey("soil") || stack.getTagCompound().hasKey("fluid")); + } + public static NBTTagCompound data(ItemStack stack) { + if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound()); + return stack.getTagCompound(); + } + public static int amount(ItemStack stack) { + if (!stack.hasTagCompound() || !stack.getTagCompound().hasKey("fluid") || fluid(stack) == null) return 0; + return Math.max(0, Math.min(stack.getTagCompound().getInteger("amount"), PaintedPotEntity.fromStack(stack).classify().volume())); + } + public static String fluidId(ItemStack stack) { + return stack.hasTagCompound() ? stack.getTagCompound().getString("fluid") : ""; + } + public static Fluid fluid(ItemStack stack) { + String id = fluidId(stack); + if (id.isEmpty()) return null; + return FluidRegistry.getFluid(id.startsWith("minecraft:") ? id.substring(10) : id); + } + public static void storeFluid(ItemStack stack, String id, int amount) { + NBTTagCompound tag = data(stack); + if (amount <= 0) { + tag.removeTag("fluid"); + tag.removeTag("amount"); + } else { + tag.setString("fluid", id); + tag.setInteger("amount", amount); + } + } + + public static Block soil(ItemStack stack) { return block(stack, "soil"); } + public static Block plant(ItemStack stack) { return block(stack, "plant"); } + private static Block block(ItemStack stack, String key) { + if (!stack.hasTagCompound()) return Blocks.AIR; + String id = stack.getTagCompound().getString(key); + if (id.isEmpty()) return Blocks.AIR; + Block result = Block.getBlockFromName(id); + return result == null ? Blocks.AIR : result; + } + static void setBlock(ItemStack pot, String key, Block block, int metadata) { + NBTTagCompound tag = data(pot); + if (block == Blocks.AIR) { + tag.removeTag(key); + tag.removeTag(key + "_meta"); + } else { + tag.setString(key, block.getRegistryName().toString()); + tag.setInteger(key + "_meta", metadata); + } + } + public static int light(ItemStack pot) { + if (amount(pot) <= 0) return 0; + Fluid fluid = fluid(pot); + return Math.min(15, Math.max(0, fluid.getLuminosity())); + } + + public static int limit(ItemStack stack) { + return planted(stack) || amount(stack) > 0 ? 1 : PaintedPotEntity.fromStack(stack).size().emptyStackLimit; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java new file mode 100644 index 0000000..cc60f00 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java @@ -0,0 +1,241 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.block.*; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.resources.I18n; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.util.*; +import net.minecraft.util.math.*; +import net.minecraft.util.text.TextComponentTranslation; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.IFluidBlock; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.modcrafters.minecraft.primalpottery.vessel.VesselRules; +import net.modcrafters.minecraft.primalpottery.legacy.client.VesselScreen; + +public final class VesselInteractions { + private VesselInteractions() {} + + public static int light(PaintedPotEntity pottery) { + int maximum = 0; + for (int i = 0; i < PotteryLayout.COUNT; i++) maximum = Math.max(maximum, VesselData.light(pottery.stack(i))); + return maximum; + } + public static int fluidColor(ItemStack pot) { + String id = VesselData.fluidId(pot); + if (id.equals("minecraft:water") || id.equals("water")) return 0x3f76e4; + if (id.equals("minecraft:lava") || id.equals("lava")) return 0xff7800; + return 0xffffff; + } + static String fluidName(ItemStack pot) { + Fluid fluid = VesselData.fluid(pot); + if (fluid == null) return I18n.format("gui.primalpottery.lid.empty"); + return fluid.getLocalizedName(new net.minecraftforge.fluids.FluidStack(fluid, VesselData.amount(pot))); + } + public static String contentsLabel(ItemStack pot) { + Pottery.Info info = PaintedPotEntity.fromStack(pot).classify(); + if (!info.type().isVessel()) return I18n.format("pottery.primalpottery.type.lump"); + return I18n.format("gui.primalpottery.lid.contents", fluidName(pot), VesselData.amount(pot), info.volume()); + } + + private static void editOne(EntityPlayer player, EnumHand hand, Consumer edit) { + ItemStack current = player.getHeldItem(hand); + if (current.getCount() == 1) { + edit.accept(current); + return; + } + ItemStack one = current.splitStack(1); + edit.accept(one); + player.setHeldItem(hand, one); + give(player, current); + } + private static void give(EntityPlayer player, ItemStack stack) { + if (!stack.isEmpty() && !player.inventory.addItemStackToInventory(stack)) player.dropItem(stack, false); + } + + public static EnumActionResult useHeld(EntityPlayer player, EnumHand hand) { + ItemStack pot = player.getHeldItem(hand); + if (PaintedPotEntity.fromStack(pot).isPlate()) return EnumActionResult.PASS; + EnumActionResult fill = fillLookedAt(player, hand); + if (fill != EnumActionResult.PASS) return fill; + if (player.world.isRemote) VesselScreen.open(hand, null, -1, pot); + return EnumActionResult.SUCCESS; + } + + public static EnumActionResult beforePlace(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing face) { + + EnumActionResult fill = fillLookedAt(player, hand); + if (fill != EnumActionResult.PASS) return fill; + BlockPos target = world.getBlockState(pos).getBlock().isReplaceable(world, pos) ? pos : pos.offset(face); + IBlockState state = world.getBlockState(target); + Fluid fluid = fluidAt(state.getBlock()); + if (fluid != null) { + boolean source = state.getBlock() instanceof BlockLiquid && state.getValue(BlockLiquid.LEVEL) == 0; + if (!(source && player.isSneaking() && VesselData.amount(player.getHeldItem(hand)) > 0)) return EnumActionResult.FAIL; + } + return EnumActionResult.PASS; + } + + private static Fluid fluidAt(Block block) { + if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) return FluidRegistry.WATER; + if (block == Blocks.LAVA || block == Blocks.FLOWING_LAVA) return FluidRegistry.LAVA; + return block instanceof IFluidBlock ? ((IFluidBlock) block).getFluid() : FluidRegistry.lookupFluidForBlock(block); + } + + private static EnumActionResult fillLookedAt(EntityPlayer player, EnumHand hand) { + ItemStack pot = player.getHeldItem(hand); + int capacity = PaintedPotEntity.fromStack(pot).classify().volume(); + if (capacity <= 0 || VesselData.amount(pot) > 0) return EnumActionResult.PASS; + World world = player.world; + Vec3d eye = player.getPositionEyes(1); + Vec3d end = eye.add(player.getLook(1).scale(player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue())); + RayTraceResult stop = world.rayTraceBlocks(eye, end, false, true, false); + if (stop != null) end = stop.hitVec; + // The 1.12 bucket ray only collides with sources. Inspect the cells before the first solid face for flowing liquid. + Vec3d ray = end.subtract(eye); + int steps = Math.max(1, (int) Math.ceil(ray.lengthVector() * 32)); + for (int i = 0; i <= steps; i++) { + Vec3d sample = eye.add(ray.scale((double) i / steps)); + BlockPos pos = new BlockPos(sample); + IBlockState state = world.getBlockState(pos); + Fluid fluid = fluidAt(state.getBlock()); + if (fluid == null) continue; + if (state.getBlock() instanceof BlockLiquid && sample.y - pos.getY() > + 1 - BlockLiquid.getLiquidHeightPercent(state.getValue(BlockLiquid.LEVEL))) continue; + if (!world.isBlockModifiable(player, pos) || !player.canPlayerEdit(pos, EnumFacing.UP, pot)) return EnumActionResult.FAIL; + if (!world.isRemote && !VesselData.lid(pot) && !VesselData.planted(pot)) { + String id = fluid == FluidRegistry.WATER ? "minecraft:water" : fluid == FluidRegistry.LAVA ? "minecraft:lava" : fluid.getName(); + editOne(player, hand, one -> VesselData.storeFluid(one, id, capacity)); + world.playSound(null, pos, fluid.getFillSound(), SoundCategory.BLOCKS, 1, 1); + } + return EnumActionResult.SUCCESS; + } + return EnumActionResult.PASS; + } + + public static boolean usePlaced(PaintedPotEntity pottery, int slot, EntityPlayer player, EnumHand hand) { + ItemStack pot = pottery.stack(slot); + if (pot.isEmpty() || pottery.layout().at(slot).isPlate()) return false; + ItemStack held = player.getHeldItem(hand); + if (held.isEmpty() && hand == EnumHand.MAIN_HAND && !player.isSneaking()) { + ItemStack offhand = player.getHeldItem(EnumHand.OFF_HAND); + if (offhand.getItem() instanceof ItemBlock) { + Block offer = ((ItemBlock) offhand.getItem()).getBlock(); + if (PlanterPlants.soil(offer) || PlanterPlants.accepts(pottery.layout().at(slot).size(), offer, offhand.getMetadata())) held = offhand; + } + } + World world = player.world; + BlockPos pos = pottery.getPos(); + if (held.isEmpty()) { + if (player.isSneaking()) return false; + if (VesselData.planted(pot)) { + if (!world.isRemote) { + give(player, takePlanting(pot)); + pottery.sync(); + } + } else if (world.isRemote) VesselScreen.open(hand, pos, slot, pot); + return true; + } + if (held.getItem() == pot.getItem()) { + int amount = VesselData.amount(held); + if (amount <= 0 || player.isSneaking()) return false; + if (world.isRemote || VesselData.lid(pot) || VesselData.planted(pot) || VesselData.lid(held)) return true; + String id = VesselData.fluidId(held); + int stored = VesselData.amount(pot); + int move = VesselRules.transfer(id, amount, VesselData.fluidId(pot), stored, PaintedPotEntity.fromStack(pot).classify().volume()); + if (move > 0) { + VesselData.storeFluid(pot, id, stored + move); + VesselData.storeFluid(held, id, amount - move); + pottery.sync(); + world.checkLight(pos); + Fluid liquid = VesselData.fluid(pot); + if (liquid != null && liquid.getFillSound() != null) world.playSound(null, pos, liquid.getFillSound(), SoundCategory.BLOCKS, 1, 1); + } + return true; + } + if (!(held.getItem() instanceof ItemBlock)) return false; + Block offered = ((ItemBlock) held.getItem()).getBlock(); + return plant(pottery, pot, held, offered, player); + } + + private static boolean plant(PaintedPotEntity pottery, ItemStack pot, ItemStack held, Block offered, EntityPlayer player) { + Pottery shape = PaintedPotEntity.fromStack(pot); + boolean soil = PlanterPlants.soil(offered); + int meta = held.getMetadata(); + if (soil) { + String warning = VesselRules.soilWarning(shape, VesselData.lid(pot), VesselData.amount(pot), VesselData.planted(pot)); + if (warning != null) { + if (!player.world.isRemote) player.sendStatusMessage(new TextComponentTranslation(warning, VesselRules.planterCapacity(shape)), true); + return true; + } + } else if (!PlanterPlants.accepts(shape.size(), offered, meta)) { + return VesselData.planted(pot); + } + boolean tree = !soil && shape.size() == Pottery.Size.LARGE && PlanterPlants.sapling(offered); + boolean reroll = tree && VesselData.plant(pot) == offered && pot.getTagCompound().getInteger("plant_meta") == meta; + if (!soil && (!VesselData.planted(pot) || (VesselData.plant(pot) != Blocks.AIR && !reroll))) return true; + if (!player.world.isRemote) { + if (tree && !PlanterPlants.grow((WorldServer) player.world, offered, meta, pot)) return true; + VesselData.setBlock(pot, soil ? "soil" : "plant", offered, meta); + if (!reroll && !player.capabilities.isCreativeMode) held.shrink(1); + pottery.sync(); + player.world.playSound(null, pottery.getPos(), offered.getDefaultState().getBlock().getSoundType() + .getPlaceSound(), SoundCategory.BLOCKS, 1, 1); + } + return true; + } + + private static ItemStack takePlanting(ItemStack pot) { + String key = VesselData.plant(pot) != Blocks.AIR ? "plant" : "soil"; + Block removed = key.equals("plant") ? VesselData.plant(pot) : VesselData.soil(pot); + ItemStack drop = new ItemStack(removed, 1, pot.getTagCompound().getInteger(key + "_meta")); + VesselData.setBlock(pot, key, Blocks.AIR, 0); + VesselData.data(pot).removeTag("tree"); + return drop; + } + public static List dropPlanting(ItemStack pot) { + List drops = new ArrayList<>(); + while (VesselData.planted(pot)) drops.add(takePlanting(pot)); + return drops; + } + + public static void setLid(EntityPlayer player, EnumHand hand, BlockPos pos, int slot, boolean closed) { + if (player.isSpectator()) return; + PaintedPotEntity pottery = null; + ItemStack stack; + if (pos == null) { + stack = player.getHeldItem(hand); + if (!(stack.getItem() instanceof VesselItem)) return; + } else { + World world = player.world; + if (!world.isBlockLoaded(pos) || !world.isBlockModifiable(player, pos)) return; + double reach = player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue() + 1; + if (player.getDistanceSq(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5) > reach * reach) return; + if (!(world.getTileEntity(pos) instanceof PaintedPotEntity)) return; + pottery = (PaintedPotEntity) world.getTileEntity(pos); + stack = pottery.stack(slot); + } + if (stack.isEmpty() || VesselData.lid(stack) == closed || VesselData.planted(stack) + || closed && PaintedPotEntity.fromStack(stack).cover() == null) return; + Consumer change = one -> { + if (closed) VesselData.data(one).setBoolean("lid", true); + else VesselData.data(one).removeTag("lid"); + }; + if (pottery == null) editOne(player, hand, change); + else { + change.accept(stack); + pottery.sync(); + } + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselItem.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselItem.java new file mode 100644 index 0000000..baebd04 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselItem.java @@ -0,0 +1,50 @@ +package net.modcrafters.minecraft.primalpottery.legacy; + +import java.util.List; +import javax.annotation.Nullable; +import net.minecraft.block.Block; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.client.resources.I18n; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.util.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public class VesselItem extends ItemBlock { + public VesselItem(Block block) { super(block); } + @Override public int getItemStackLimit(ItemStack stack) { return VesselData.limit(stack); } + @Override public ActionResult onItemRightClick(World world, EntityPlayer player, EnumHand hand) { + EnumActionResult result = VesselInteractions.useHeld(player, hand); + return new ActionResult<>(result, player.getHeldItem(hand)); + } + @Override public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, + EnumFacing face, float x, float y, float z) { + EnumActionResult guard = VesselInteractions.beforePlace(player, world, pos, hand, face); + return guard == EnumActionResult.PASS ? placeVessel(player, world, pos, hand, face, x, y, z) : guard; + } + protected EnumActionResult placeVessel(EntityPlayer player, World world, BlockPos pos, EnumHand hand, + EnumFacing face, float x, float y, float z) { + return super.onItemUse(player, world, pos, hand, face, x, y, z); + } + @Override public boolean showDurabilityBar(ItemStack stack) { return VesselData.amount(stack) > 0; } + @Override public double getDurabilityForDisplay(ItemStack stack) { + int capacity = PaintedPotEntity.fromStack(stack).classify().volume(); + return capacity > 0 ? 1 - (double) VesselData.amount(stack) / capacity : 1; + } + @Override public int getRGBDurabilityForDisplay(ItemStack stack) { + return VesselInteractions.fluidColor(stack); + } + @Override @SideOnly(Side.CLIENT) + public void addInformation(ItemStack stack, @Nullable World world, List lines, ITooltipFlag flag) { + int capacity = PaintedPotEntity.fromStack(stack).classify().volume(); + if (capacity > 0) lines.add(I18n.format("tooltip.primalpottery.capacity", capacity)); + int amount = VesselData.amount(stack); + if (amount > 0) lines.add(I18n.format("tooltip.primalpottery.contents", VesselInteractions.fluidName(stack), amount)); + if (VesselData.lid(stack)) lines.add(I18n.format("gui.primalpottery.lid.closed")); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java index e48ff3c..d366ee8 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/WheelEntity.java @@ -13,6 +13,7 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.ITickable; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryProfile; import net.modcrafters.minecraft.primalpottery.pottery.PotteryTemplates; import net.modcrafters.minecraft.primalpottery.pottery.WheelClay; import net.modcrafters.minecraft.primalpottery.template.TemplateKind; @@ -24,6 +25,14 @@ public final class WheelEntity extends TileEntity implements ITickable { private ItemStack visual = ItemStack.EMPTY; private Pottery visualProfile; + public Pottery templateProfile() { + if (installed.isEmpty()) return null; + Pottery saved = ForgeStackProfiles.INSTANCE.read(installed); + Pottery.Size size = installed.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT) + ? Pottery.Size.LARGE : Pottery.Size.SMALL; + return saved != null && saved.size() == size ? saved : PotteryTemplates.fresh(size); + } + public ItemStack blueprintStack() { return installed; } public ItemStack visibleClay() { @@ -50,11 +59,32 @@ ItemStack takeBlueprint() { } public void update() { - if (!clay.tick() || world.isRemote) return; + if (!clay.tick()) return; + if (world.isRemote) { + if (clay.target() != null && world.rand.nextInt(3) == 0) spitClay(); + return; + } if (clay.momentum() == 0) synchronize(); else markDirty(); } + + private void spitClay() { + Pottery shape = clay.shape(); + if (shape == null) return; + double height = shape.height() * (.25 + .65 * world.rand.nextDouble()); + double radius = PotteryProfile.sample(PotteryProfile.profile(shape.discs(), false), height) / 32; + double angle = world.rand.nextDouble() * 2 * Math.PI; + double dx = Math.cos(angle), dz = Math.sin(angle); + double x = pos.getX() + .5 + dx * radius, z = pos.getZ() + .5 + dz * radius; + double y = pos.getY() + 1 + height / 32; + double vx = .035 * dx - .1 * dz, vz = .035 * dz + .1 * dx; + boolean water = world.rand.nextInt(4) == 0; + net.minecraft.util.EnumParticleTypes particle = water ? net.minecraft.util.EnumParticleTypes.WATER_SPLASH : net.minecraft.util.EnumParticleTypes.BLOCK_DUST; + world.spawnParticle(particle, x, y, z, vx, water ? 0 : .08, vz, + net.minecraft.block.Block.getStateId(net.minecraft.init.Blocks.CLAY.getDefaultState())); + } + boolean use(EntityPlayer player, EnumHand hand, double x, double y, double z) { ItemStack held = player.getHeldItem(hand); boolean server = !world.isRemote; @@ -65,15 +95,9 @@ public boolean holdingBlueprint() { } public boolean emptyHand() { return held.isEmpty(); } public boolean hasBlueprint() { return !installed.isEmpty(); } - public Pottery blueprint() { - if (installed.isEmpty()) return null; - Pottery saved = ForgeStackProfiles.INSTANCE.read(installed); - Pottery.Size size = installed.getItem() == PrimalPotteryForge.template(TemplateKind.LARGE_BLUEPRINT) - ? Pottery.Size.LARGE : Pottery.Size.SMALL; - return saved != null && saved.size() == size ? saved : PotteryTemplates.fresh(size); - } + public Pottery blueprint() { return templateProfile(); } public Pottery rawShape() { - return held.getItem() == PrimalPotteryForge.RAW ? ForgeStackProfiles.INSTANCE.read(held) : null; + return held.getItem() == PrimalPotteryForge.RAW && !PaintingRegistration.dyed(held) ? ForgeStackProfiles.INSTANCE.read(held) : null; } public boolean holdsClay(Pottery.Size size) { return held.getItem() == (size == Pottery.Size.LARGE ? Item.getItemFromBlock(Blocks.CLAY) : Items.CLAY_BALL); diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingClient.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingClient.java new file mode 100644 index 0000000..8638451 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingClient.java @@ -0,0 +1,62 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import net.modcrafters.minecraft.primalpottery.legacy.PaintChannel; +import net.modcrafters.minecraft.primalpottery.legacy.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.painting.IconPixels; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.*; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.*; +import net.minecraft.util.*; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.client.event.*; +import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.relauncher.Side; + +@Mod.EventBusSubscriber(modid="primalpottery", value=Side.CLIENT) +public final class PaintingClient { + @SubscribeEvent public static void registerModel(ModelRegistryEvent event) { + Item table = Item.getItemFromBlock(PaintingRegistration.TABLE); + ModelLoader.setCustomModelResourceLocation(table, 0, new ModelResourceLocation(table.getRegistryName(), "inventory")); + } + @SubscribeEvent public static void stitch(TextureStitchEvent.Pre event) { + event.getMap().registerSprite(new ResourceLocation("primalpottery", "block/dyed_clay")); + } + public static void sendStamp(EntityPlayer player, BlockPos pos) { + ItemStack icon = player.getHeldItemOffhand(); + PaintChannel.stamp(pos, Item.getIdFromItem(icon.getItem()), pattern(player, icon)); + } + public static String pattern(EntityPlayer player, ItemStack icon) { + int[] pixels = iconPixels(player, icon); + return pixels == null ? "" : IconPixels.quantize(pixels); + } + + /** Returns the composited icon in row-major ARGB order, or null for a model that is not a flat sprite. */ + public static int[] iconPixels(EntityPlayer player, ItemStack icon) { + Minecraft client = Minecraft.getMinecraft(); + IBakedModel model = client.getRenderItem().getItemModelWithOverrides(icon, player.world, player); + if (model.isBuiltInRenderer() || model.isGui3d()) return null; + int[] pixels = new int[256]; + boolean foundFront = false; + for (BakedQuad quad : model.getQuads(null, null, 42)) { + EnumFacing face = quad.getFace(); + int[] vertices = quad.getVertexData(); + for (int i = 0; i < vertices.length; i += vertices.length/4) { + if (!IconPixels.spriteVertex(face.getAxis() == EnumFacing.Axis.Z, face == EnumFacing.SOUTH, + Float.intBitsToFloat(vertices[i]),Float.intBitsToFloat(vertices[i+1]),Float.intBitsToFloat(vertices[i+2]))) return null; + } + if (face != EnumFacing.SOUTH) continue; + foundFront = true; + int tint = quad.hasTintIndex() ? client.getItemColors().colorMultiplier(icon,quad.getTintIndex()) : -1; + TextureAtlasSprite sprite = quad.getSprite(); + if (sprite.getIconName().equals("missingno") || sprite.getFrameCount() == 0) return null; + int[] frame = sprite.getFrameTextureData(0)[0]; + IconPixels.sampleFrame(pixels, (x,y) -> frame[y*sprite.getIconWidth()+x],0,0, + sprite.getIconWidth(),sprite.getIconHeight(), tint | 0xff000000); + } + return foundFront ? pixels : null; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingScreen.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingScreen.java new file mode 100644 index 0000000..3be3169 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PaintingScreen.java @@ -0,0 +1,103 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import java.io.IOException; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.resources.I18n; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.modcrafters.minecraft.primalpottery.painting.*; +import net.modcrafters.minecraft.primalpottery.legacy.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.legacy.PaintChannel; +import net.modcrafters.minecraft.primalpottery.legacy.PaintingMenu; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +public final class PaintingScreen extends GuiContainer implements PaintPanel.Canvas { + private final PaintPanel panel; + private final PaintingMenu menu; + private GuiButton undo; + public PaintingScreen(PaintingMenu menu) { + super(menu); + this.menu = menu; + xSize = PaintPanel.WIDTH; + ySize = PaintPanel.HEIGHT; + panel = new PaintPanel(menu, this); + } + private int left() { return guiLeft; } + private int top() { return guiTop; } + private static String label(String key, Object... args) { return I18n.format("gui.primalpottery.paint." + key,args); } + + @Override public void initGui() { + super.initGui(); + addButton(new GuiButton(0,left()+94,top()+156,48,18,label("erase"))); + undo = addButton(new GuiButton(1,left()+145,top()+156,44,18,I18n.format("gui.primalpottery.template.undo"))); + addButton(new GuiButton(2,left()+192,top()+156,46,18,I18n.format("gui.done"))); + } + @Override protected void actionPerformed(GuiButton b) { + if (b.id == 0) panel.erase(); + else if (b == undo) stroke(PaintBrush.UNDO); + else mc.player.closeScreen(); + } + @Override public void drawScreen(int x, int y, float tick) { + drawDefaultBackground(); + undo.enabled = menu.canUndo(); + super.drawScreen(x,y,tick); + int color = panel.tank(x-left(), y-top()); + if (color >= 0) drawHoveringText(java.util.Arrays.asList( + PaintingRegistration.dye(color).getDisplayName(), + label("volume", menu.volume(color)), label("stock", menu.count(color)), + label(menu.volume(color) > 0 || menu.count(color) > 0 ? "refill" : "missing")), x, y); + } + @Override protected void drawGuiContainerForegroundLayer(int x,int y) {} + @Override protected void drawGuiContainerBackgroundLayer(float tick, int mx, int my) { + drawPanel(); + } + + private void drawPanel() { + panel.draw(); + text(I18n.format("tile.primalpottery.painting_table.name"),33,10,1); + int dye = panel.selected(); + text(dye < 0 ? label("erase") : PaintingRegistration.dye(dye).getDisplayName(),10,154,1); + if (dye >= 0) text(label("volume",menu.volume(dye)),10,166,1); + if (menu.potStack().isEmpty()) { text(label("hold"),119,51,1); text(label("reopen"),119,63,1); } + else if (menu.profile().isPlate()) { text(label("center"),74,26,.8F); text(label("rim"),74,113,.8F); } + } + + public void rect(int x,int y,int w,int h,int color) { + if (w > 0) drawRect(left()+x,top()+y,left()+x+w,top()+y+h,color); + } + public void text(String label,int x,int y,float scale) { + GlStateManager.pushMatrix(); + GlStateManager.translate(left()+x,top()+y,0); + GlStateManager.scale(scale,scale,1); + fontRenderer.drawString(label,0,0,0xff392f29); + GlStateManager.popMatrix(); + } + public void preview(Pottery pot, float yaw, float tilt) { + float size = (float)(86 * 32 / Math.max(1, Math.hypot(pot.height(), pot.widestRadius()*2))); + GlStateManager.pushMatrix(); + GlStateManager.translate(left()+176,top()+74,80); + GlStateManager.scale(size,-size,size); + GlStateManager.rotate(tilt,1,0,0); + GlStateManager.rotate(yaw,0,1,0); + GlStateManager.translate(0,.5-pot.height()/64,0); + RenderHelper.enableStandardItemLighting(); + GlStateManager.enableDepth(); + mc.getRenderItem().renderItem(menu.potStack(), ItemCameraTransforms.TransformType.NONE); + RenderHelper.disableStandardItemLighting(); + GlStateManager.popMatrix(); + } + public void stroke(int action) { PaintChannel.stroke(menu.windowId, action); } + + @Override public void mouseClicked(int x,int y,int button) throws IOException { + undo.enabled = menu.canUndo(); + if (!panel.press(x-left(),y-top(),button)) super.mouseClicked(x,y,button); + } + @Override public void mouseClickMove(int x,int y,int button,long time) { + if (!panel.drag(x-left(),y-top(),button)) super.mouseClickMove(x,y,button,time); + } + @Override public void mouseReleased(int x,int y,int button) { + panel.release(); super.mouseReleased(x,y,button); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java new file mode 100644 index 0000000..ae1e0df --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java @@ -0,0 +1,57 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.legacy.PotBounds; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderGlobal; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.*; +import net.minecraftforge.client.event.DrawBlockHighlightEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.relauncher.Side; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) +public final class PlacementOutline { + @SubscribeEvent public static void draw(DrawBlockHighlightEvent event) { + EntityPlayer player = event.getPlayer(); + ItemStack held = player.getHeldItemMainhand().isEmpty() ? player.getHeldItemOffhand() : player.getHeldItemMainhand(); + RayTraceResult hit = event.getTarget(); + if (!PaintingRegistration.isPot(held) || hit.typeOfHit != RayTraceResult.Type.BLOCK) return; + BlockPos pos = hit.getBlockPos(); + EnumFacing face = hit.sideHit; + TileEntity entity = player.world.getTileEntity(pos); + if (!(entity instanceof PaintedPotEntity)) { + if (face != EnumFacing.UP) return; + pos = pos.up(); + entity = player.world.getTileEntity(pos); + } + double x = hit.hitVec.x - pos.getX() - face.getDirectionVec().getX() * 1e-6; + double z = hit.hitVec.z - pos.getZ() - face.getDirectionVec().getZ() * 1e-6; + Pottery shape = PaintedPotEntity.fromStack(held); + int slot = entity instanceof PaintedPotEntity + ? ((PaintedPotEntity) entity).layout().destination(shape, x, z, player.isSneaking(), face.getDirectionVec().getX(), face.getDirectionVec().getZ()) + : PotteryLayout.preferred(shape, x, z); + if (slot < 0) return; + float partial = event.getPartialTicks(); + Vec3d camera = player.getPositionEyes(partial).subtract(0, player.getEyeHeight(), 0); + AxisAlignedBB box = PotBounds.box(slot, shape).offset(pos).offset(-camera.x, -camera.y, -camera.z); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + GlStateManager.glLineWidth(2); + RenderGlobal.drawSelectionBoundingBox(box.grow(.002), 0, 0, 0, .42F); + GlStateManager.depthMask(true); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + event.setCanceled(true); + } + private PlacementOutline() {} +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotContentsRenderer.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotContentsRenderer.java new file mode 100644 index 0000000..7fe2c5f --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotContentsRenderer.java @@ -0,0 +1,11 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.dining.DiningRenderer; + +public final class PotContentsRenderer extends TileEntitySpecialRenderer { + @Override public void render(PaintedPotEntity tile, double x, double y, double z, float partial, int destroy, float alpha) { + DiningRenderer.draw(tile, x, y, z, partial); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java index 07b32fb..11a3978 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java @@ -32,6 +32,8 @@ import net.modcrafters.minecraft.primalpottery.template.TemplateKind; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.modcrafters.minecraft.primalpottery.legacy.PaintingRegistration; import org.apache.commons.lang3.tuple.Pair; @Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) @@ -42,7 +44,7 @@ public final class PotteryModel extends BakedModelWrapper { private final List item; private final ItemOverrideList overrides = new ItemOverrideList(Collections.emptyList()) { @Override public IBakedModel handleItemState(IBakedModel model, ItemStack stack, World world, EntityLivingBase entity) { - return new PotteryModel(originalModel, bakery, bakery.model(PaintedPotEntity.fromStack(stack))); + return new PotteryModel(originalModel, bakery, VesselModels.append(bakery.model(PaintedPotEntity.fromStack(stack), PaintingRegistration.tint(stack)), stack, PotteryLayout.CENTER)); } }; @@ -60,6 +62,7 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item new ModelResourceLocation(PrimalPotteryForge.RAW.getRegistryName(), "inventory")); net.minecraftforge.fml.client.registry.ClientRegistry.bindTileEntitySpecialRenderer( net.modcrafters.minecraft.primalpottery.legacy.WheelEntity.class, new WheelRenderer()); + net.minecraftforge.fml.client.registry.ClientRegistry.bindTileEntitySpecialRenderer(PaintedPotEntity.class, new PotContentsRenderer()); for (TemplateKind kind : TemplateKind.values()) { ModelLoader.setCustomModelResourceLocation(PrimalPotteryForge.template(kind), 0, new ModelResourceLocation(new ResourceLocation("primalpottery", kind.id), "inventory")); @@ -81,11 +84,26 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item new ModelResourceLocation(PrimalPotteryForge.ID, "inventory"), new ModelResourceLocation(PrimalPotteryForge.RAW.getRegistryName(), "inventory")}) { IBakedModel base = event.getModelRegistry().getObject(key); - PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks, sheet); + PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks, sheet, Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("primalpottery:block/dyed_clay")); event.getModelRegistry().putObject(key, new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE))); } } + private List placed(PotteryLayout layout, ItemStack[] stacks) { + if (stacks == null) return bakery.placed(layout); + int first = layout.first(); + if (first < 0) return java.util.Collections.emptyList(); + if (layout.count() == 1) return placedSlot(layout, stacks, first); + List quads = new java.util.ArrayList<>(); + for (int i = first; i < PotteryLayout.COUNT; i++) { + if (layout.at(i) != null) quads.addAll(placedSlot(layout, stacks, i)); + } + return quads; + } + private List placedSlot(PotteryLayout layout, ItemStack[] stacks, int slot) { + return VesselModels.append(bakery.model(layout.at(slot), slot, layout.tint(slot)), stacks[slot], slot); + } + @Override public ItemOverrideList getOverrides() { return overrides; } @Override public Pair handlePerspective(ItemCameraTransforms.TransformType type) { @@ -95,6 +113,8 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item @Override public List getQuads(IBlockState state, EnumFacing side, long seed) { if (side != null) return Collections.emptyList(); if (state instanceof IExtendedBlockState) { + net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout layout = ((IExtendedBlockState) state).getValue(PaintedPotBlock.LAYOUT); + if (layout != null) return placed(layout, ((IExtendedBlockState) state).getValue(PaintedPotBlock.STACKS)); Pottery profile = ((IExtendedBlockState) state).getValue(PaintedPotBlock.PROFILE); if (profile != null) return bakery.model(profile); } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java index 443d452..6e8d93a 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java @@ -13,8 +13,8 @@ final class PotteryQuads extends VesselQuadPacker private final PaintSheet sheet; private final int[] palette; - PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite atlasSprite) { - super(clay, inks, DefaultVertexFormats.ITEM.getIntegerSize()); + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite atlasSprite, TextureAtlasSprite dyed) { + super(clay, inks, dyed, DefaultVertexFormats.ITEM.getIntegerSize()); PaintSheet candidate = atlasSprite instanceof PaintSheet ? (PaintSheet) atlasSprite : null; sheet = candidate != null && candidate.supportsTiles() && !inks.hasAnimationMetadata() ? candidate : null; palette = sheet == null ? null : PaintSheetTiles.palette(inks.getIconWidth(), inks.getIconHeight(), diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java new file mode 100644 index 0000000..651e928 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java @@ -0,0 +1,174 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import java.util.*; +import java.lang.ref.WeakReference; +import net.minecraft.block.Block; +import net.minecraft.block.BlockDoublePlant; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.*; +import net.minecraft.util.*; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fluids.Fluid; +import net.modcrafters.minecraft.primalpottery.legacy.PaintingRegistration; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.VesselData; +import net.modcrafters.minecraft.primalpottery.legacy.PlanterPlants; +import net.modcrafters.minecraft.primalpottery.vessel.VesselMesh; +import net.modcrafters.minecraft.primalpottery.vessel.VesselPreviewFrame; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; + +public final class VesselModels extends VesselMesh { + // A screen owns its lid-only preview stack. World and inventory models always use their complete vessel. + private static volatile WeakReference previewLid = new WeakReference<>(null); + + static ItemStack detachedLid(ItemStack vessel) { + ItemStack lid = vessel.copy(); + previewLid = new WeakReference<>(lid); + return lid; + } + + static VesselPreviewFrame frame(ItemStack pot) { + boolean planted = VesselData.planted(pot); + double radius = 0, height = 0; + if (planted) { + for (BakedQuad quad : append(Collections.emptyList(), pot, PotteryLayout.CENTER)) { + int[] vertices = quad.getVertexData(); + for (int i = 0; i < vertices.length; i += vertices.length / 4) { + double x = Float.intBitsToFloat(vertices[i]) - .5; + double z = Float.intBitsToFloat(vertices[i + 2]) - .5; + radius = Math.max(radius, 32 * Math.hypot(x, z)); + height = Math.max(height, 32 * Float.intBitsToFloat(vertices[i + 1])); + } + } + } + return new VesselPreviewFrame(PaintedPotEntity.fromStack(pot), radius, height, planted); + } + + private static final Map CACHE = new WeakHashMap<>(); + private static final class Cached { + final NBTTagCompound tag; + final List body, decorated; + final int slot; + Cached(ItemStack pot, int slot, List body, List decorated) { + this.tag = pot.getTagCompound() == null ? null : pot.getTagCompound().copy(); + this.slot = slot; + this.body = body; + this.decorated = decorated; + } + } + + private VesselModels(ItemStack stack, int slot) { super(PaintedPotEntity.fromStack(stack), slot, 7); } + public static List append(List body, ItemStack stack, int slot) { + boolean lidOnly = previewLid.get() == stack; + if (!lidOnly && !VesselData.hasExtras(stack)) return body; + synchronized (CACHE) { + Cached cached = CACHE.get(stack); + if (cached != null && cached.slot == slot && cached.body == body && Objects.equals(cached.tag, stack.getTagCompound())) return cached.decorated; + VesselModels mesh = new VesselModels(stack, slot); + if (lidOnly) { + mesh.lid(stack, true); + } else { + mesh.faces.addAll(body); + mesh.decorate(stack); + } + List decorated = Collections.unmodifiableList(mesh.faces); + CACHE.put(stack, new Cached(stack, slot, body, decorated)); + return decorated; + } + } + + private static TextureAtlasSprite sprite(ResourceLocation id) { + return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(id.toString()); + } + + private void lid(ItemStack stack, boolean beside) { + int tint = PaintingRegistration.tint(stack); + lid(sprite(new ResourceLocation("primalpottery", tint == -1 ? "block/fired_clay" : "block/dyed_clay")), tint, beside); + } + + private void decorate(ItemStack stack) { + if (VesselData.lid(stack)) { + lid(stack, false); + return; + } + Block soil = VesselData.soil(stack); + if (soil == Blocks.AIR) { + Fluid fluid = VesselData.fluid(stack); + if (fluid != null) { + ResourceLocation texture = fluid.getStill(); + if (texture != null) { + int color = fluid == net.minecraftforge.fluids.FluidRegistry.WATER ? 0x3f76e4 : fluid.getColor(); + surface(sprite(texture), color, VesselData.amount(stack), false); + } + } + return; + } + boolean grass = soil == Blocks.GRASS; + String texture = grass ? "grass_top" : soil == Blocks.SAND ? "sand" : "dirt"; + double ground = surface(sprite(new ResourceLocation("minecraft", "blocks/" + texture)), grass ? 0x78a753 : -1, 0, true); + Block plant = VesselData.plant(stack); + if (plant == Blocks.AIR) return; + if (stack.getTagCompound().hasKey("tree", 9)) { + tree(stack, ground); + return; + } + IBlockState state = plant.getStateFromMeta(stack.getTagCompound().getInteger("plant_meta")); + double size = plant == Blocks.CACTUS ? Math.min(14, radiusAt(ground) * 1.8) * scale : 14 * scale; + model(state, x - size / 2, ground, z - size / 2, size, null, null); + if (PlanterPlants.tall(plant)) { + model(state.withProperty(BlockDoublePlant.HALF, BlockDoublePlant.EnumBlockHalf.UPPER), + x - size / 2, ground + size, z - size / 2, size, null, null); + } + } + private void tree(ItemStack stack, double ground) { + Map voxels = new HashMap<>(); + NBTTagList groups = stack.getTagCompound().getTagList("tree", 10); + for (int i = 0; i < groups.tagCount(); i++) { + NBTTagCompound group = groups.getCompoundTagAt(i); + Block block = Block.getBlockFromName(group.getString("block")); + if (block == null || block == Blocks.AIR) continue; + IBlockState state = block.getStateFromMeta(group.getInteger("meta")); + int[] positions = group.getIntArray("positions"); + if (positions.length > 8192 - voxels.size()) return; + for (int pos : positions) { + if (pos >= 0 && pos < (1 << 18)) voxels.put(new BlockPos((pos & 63) - 32, pos >>> 12, ((pos >>> 6) & 63) - 32), state); + } + } + double size = 4 * scale; + voxels.forEach((pos, state) -> model(state, x + (pos.getX() - .5) * size, + ground + pos.getY() * size, z + (pos.getZ() - .5) * size, size, voxels, pos)); + } + + private void model(IBlockState state, double bx, double by, double bz, double size, + Map tree, BlockPos pos) { + IBakedModel model = Minecraft.getMinecraft().getBlockRendererDispatcher().getModelForState(state); + boolean visible = tree == null; + for (EnumFacing face : EnumFacing.values()) { + IBlockState neighbor = tree == null ? null : tree.get(pos.offset(face)); + if (neighbor != null && (neighbor.isOpaqueCube() || neighbor.getBlock() == state.getBlock())) continue; + visible = true; + appendModel(model.getQuads(state, face, 42L), state, bx, by, bz, size); + } + if (visible) appendModel(model.getQuads(state, null, 42L), state, bx, by, bz, size); + } + private void appendModel(List source, IBlockState state, double bx, double by, double bz, double size) { + for (BakedQuad quad : source) { + int tint = quad.hasTintIndex() ? Minecraft.getMinecraft().getBlockColors().colorMultiplier(state, null, null, quad.getTintIndex()) : -1; + int[] data = transform(quad.getVertexData(), bx, by, bz, size, tint); + faces.add(new BakedQuad(data, -1, quad.getFace(), quad.getSprite(), quad.shouldApplyDiffuseLighting(), quad.getFormat())); + } + } + @Override protected float u(TextureAtlasSprite sprite, double pixel) { return sprite.getInterpolatedU(pixel); } + @Override protected float v(TextureAtlasSprite sprite, double pixel) { return sprite.getInterpolatedV(pixel); } + @Override protected BakedQuad makeQuad(int[] vertices, TextureAtlasSprite sprite, double nx, double ny, double nz) { + return new BakedQuad(vertices, -1, EnumFacing.getFacingFromVector((float) nx, (float) ny, (float) nz), + sprite, true, DefaultVertexFormats.ITEM); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java new file mode 100644 index 0000000..b23b198 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java @@ -0,0 +1,85 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.VesselChannel; +import net.modcrafters.minecraft.primalpottery.legacy.VesselInteractions; +import net.modcrafters.minecraft.primalpottery.legacy.VesselData; +import net.minecraft.client.Minecraft; +import net.modcrafters.minecraft.primalpottery.vessel.VesselPreviewFrame; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.resources.I18n; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; + +public final class VesselScreen extends GuiScreen { + private final EnumHand hand; + private final BlockPos pos; + private final int slot; + private final ItemStack preview, detachedLid; + private final VesselPreviewFrame frame; + private int left, top; + private VesselScreen(EnumHand hand, BlockPos pos, int slot, ItemStack stack) { + this.hand = hand; + this.pos = pos; + this.slot = slot; + preview = stack.copy(); + preview.setCount(1); + frame = VesselModels.frame(preview); + detachedLid = !VesselData.planted(stack) && PaintedPotEntity.fromStack(stack).cover() != null + ? VesselModels.detachedLid(stack) : ItemStack.EMPTY; + } + public static void open(EnumHand hand, BlockPos pos, int slot, ItemStack stack) { + Minecraft.getMinecraft().displayGuiScreen(new VesselScreen(hand, pos, slot, stack)); + } + private String label() { + return I18n.format(VesselData.lid(preview) ? "gui.primalpottery.lid.remove" : "gui.primalpottery.lid.put_on"); + } + private void toggle() { + boolean closed = !VesselData.lid(preview); + if (closed) VesselData.data(preview).setBoolean("lid", true); + else VesselData.data(preview).removeTag("lid"); + VesselChannel.send(hand, pos, slot, closed); + } + @Override public boolean doesGuiPauseGame() { return false; } + @Override public void initGui() { + left = (width - 176) / 2; + top = (height - 172) / 2; + GuiButton button = addButton(new GuiButton(0, left + 8, top + 144, 160, 20, label())); + button.enabled = !VesselData.planted(preview) && (VesselData.lid(preview) || PaintedPotEntity.fromStack(preview).cover() != null); + } + @Override public void mouseClicked(int x, int y, int button) throws java.io.IOException { + super.mouseClicked(x, y, button); + } + @Override protected void actionPerformed(GuiButton button) { + toggle(); + button.displayString = label(); + } + @Override public void drawScreen(int mouseX, int mouseY, float partialTick) { + drawDefaultBackground(); + drawRect(left, top, left + 176, top + 172, 0xff514b46); + drawRect(left + 2, top + 2, left + 174, top + 170, 0xffcbc6be); + drawGradientRect(left + 8, top + 23, left + 168, top + 124, 0xff744b3b, 0xffa56f50); + String title = I18n.format("tile.primalpottery.pottery.name"); + fontRenderer.drawString(title, left + 88 - fontRenderer.getStringWidth(title) / 2, top + 8, 0x302a27); + String contents = VesselInteractions.contentsLabel(preview); + fontRenderer.drawString(contents, left + 88 - fontRenderer.getStringWidth(contents) / 2, top + 132, 0x302a27); + boolean beside = !VesselData.lid(preview) && !detachedLid.isEmpty(); + drawPot(preview, left + frame.x(beside, false), top + frame.y()); + if (beside) drawPot(detachedLid, left + frame.x(true, true), top + frame.y()); + super.drawScreen(mouseX, mouseY, partialTick); + } + + private void drawPot(ItemStack stack, float x, float y) { + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, 40); + GlStateManager.scale(frame.scale(), frame.scale(), 1); + RenderHelper.enableGUIStandardItemLighting(); + itemRender.renderItemAndEffectIntoGUI(stack, 0, 0); + RenderHelper.disableStandardItemLighting(); + GlStateManager.popMatrix(); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java index 273646d..75bd93f 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/WheelRenderer.java @@ -1,5 +1,9 @@ package net.modcrafters.minecraft.primalpottery.legacy.client; +import java.util.Map; +import java.util.WeakHashMap; +import net.modcrafters.minecraft.primalpottery.wheel.WheelGuides; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderItem; @@ -15,6 +19,8 @@ public final class WheelRenderer extends TileEntitySpecialRenderer private static final ModelResourceLocation ROTOR = new ModelResourceLocation("primalpottery:wheel_rotor", "inventory"); private final ItemStack wheelItem = new ItemStack(PrimalPotteryForge.WHEEL); + private final Map guides = new WeakHashMap<>(); + @Override public void render(WheelEntity wheel, double x, double y, double z, float partial, int destroy, float alpha) { Minecraft client = Minecraft.getMinecraft(); RenderItem items = client.getRenderItem(); @@ -26,11 +32,18 @@ public final class WheelRenderer extends TileEntitySpecialRenderer GlStateManager.translate(0, 1, 0); items.renderItem(wheel.visibleClay(), ItemCameraTransforms.TransformType.NONE); GlStateManager.popMatrix(); + if (wheel.blueprintStack().isEmpty()) return; + WheelGuides boards = guides.computeIfAbsent(wheel.blueprintStack(), ignored -> new WheelGuides(wheel.templateProfile())); + net.minecraft.client.renderer.texture.TextureAtlasSprite wood = client.getTextureMapBlocks().getAtlasSprite("minecraft:blocks/planks_oak"); + net.minecraft.client.renderer.Tessellator tessellator = net.minecraft.client.renderer.Tessellator.getInstance(); + net.minecraft.client.renderer.BufferBuilder output = tessellator.getBuffer(); GlStateManager.pushMatrix(); - GlStateManager.translate(x + .14, y + .98, z + .14); - GlStateManager.rotate(90, 1, 0, 0); - GlStateManager.scale(.23, .23, .23); - items.renderItem(wheel.blueprintStack(), ItemCameraTransforms.TransformType.NONE); + GlStateManager.translate(x, y, z); + bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + output.begin(org.lwjgl.opengl.GL11.GL_QUADS, net.minecraft.client.renderer.vertex.DefaultVertexFormats.POSITION_TEX_NORMAL); + boards.draw((vx, vy, vz, u, v, nx, ny, nz) -> output.pos(vx, vy, vz) + .tex(wood.getInterpolatedU(u), wood.getInterpolatedV(v)).normal(nx, ny, nz).endVertex()); + tessellator.draw(); GlStateManager.popMatrix(); } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/Dining.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/Dining.java new file mode 100644 index 0000000..9f479ba --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/Dining.java @@ -0,0 +1,120 @@ +package net.modcrafters.minecraft.primalpottery.legacy.dining; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.*; +import net.minecraft.util.*; +import net.minecraft.util.math.*; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.modcrafters.minecraft.primalpottery.dining.DiningUse; +import net.modcrafters.minecraft.primalpottery.dining.TableSetting; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; + +@Mod.EventBusSubscriber(modid = "primalpottery") +public final class Dining { + public static boolean use(PaintedPotEntity tile, EntityPlayer player, EnumHand hand, double x, double y, double z) { + if (PlateMeal.blocksRepeat(player)) return true; + DiningUse action = new DiningUse(tile.dining, ItemStack.EMPTY) { + protected boolean server() { return !player.world.isRemote; } + protected boolean empty(ItemStack stack) { return stack.isEmpty(); } + protected boolean tool(ItemStack stack) { return stack.getItem() == DiningRegistration.cutlery(); } + protected boolean displayable(ItemStack stack) { + return !stack.isEmpty() && (stack.getItem() instanceof ItemFood || !(stack.getItem() instanceof ItemBlock)); + } + protected boolean sneaking() { return player.isSneaking(); } + protected EnumHand main() { return EnumHand.MAIN_HAND; } + protected EnumHand off() { return EnumHand.OFF_HAND; } + protected ItemStack held(EnumHand h) { return player.getHeldItem(h); } + protected ItemStack takeOne(EnumHand h) { + if (!player.capabilities.isCreativeMode) return held(h).splitStack(1); + ItemStack one = held(h).copy(); + one.setCount(1); + return one; + } + protected void give(EnumHand h, ItemStack stack) { player.setHeldItem(h, stack); } + protected void stow(ItemStack stack) { + if (!player.inventory.addItemStackToInventory(stack)) player.dropItem(stack, false); + } + protected boolean eat(int slot, int serving, EnumHand h) { return PlateMeal.start(tile, slot, serving, player, h); } + protected void takeDish(int slot, EnumHand h) { + java.util.List loose = tile.dining.remove(slot, tile.layout().at(slot)); + give(h, tile.take(slot)); + for (ItemStack drop : loose) stow(drop); + if (tile.layout().count() == 0) player.world.setBlockToAir(tile.getPos()); + } + protected void sync() { tile.sync(); } + }; + return action.use(tile.layout(), hand, x, y, z); + } + + /** A utensil can sit over an empty part of the footprint where the ray hits the support. */ + @SubscribeEvent public static void support(PlayerInteractEvent.RightClickBlock event) { + EntityPlayer player = event.getEntityPlayer(); + if (player.isSpectator()) return; + Vec3d hit = event.getHitVec(); + if (hit == null) return; + BlockPos clicked = event.getPos(); + boolean top = event.getFace() == EnumFacing.UP; + net.minecraft.tileentity.TileEntity tile = player.world.getTileEntity(clicked); + boolean support = !(tile instanceof PaintedPotEntity); + if (support && top) { + clicked = clicked.up(); + tile = player.world.getTileEntity(clicked); + } + if (!(tile instanceof PaintedPotEntity)) return; + PaintedPotEntity pots = (PaintedPotEntity) tile; + double x = hit.x - clicked.getX(), y = hit.y - clicked.getY(), z = hit.z - clicked.getZ(); + int setting = TableSetting.settingAt(x, y, z, pots.layout()); + if (support && setting < 0 || !support && setting < 0 && !player.isSneaking()) return; + if (!use(pots, player, event.getHand(), x, y, z)) return; + event.setCancellationResult(EnumActionResult.SUCCESS); + event.setCanceled(true); + } + + static RayTraceResult aim(EntityPlayer player) { + Vec3d eye = player.getPositionEyes(1); + double reach = player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue(); + return player.world.rayTraceBlocks(eye, eye.add(player.getLookVec().scale(reach)), false, false, false); + } + + public static RayTraceResult hitSetting(PaintedPotEntity tile, Vec3d from, Vec3d to, RayTraceResult best) { + if (!tile.dining.hasVisuals()) return best; + for (int slot = 4; slot < 8; slot++) { + if (tile.dining.utensil(slot).isEmpty()) continue; + for (int side = 0; side < 2; side++) { + boolean fork = side == 0; + double x = TableSetting.utensilX(slot, fork), z = TableSetting.utensilZ(slot, fork); + double w = TableSetting.halfX(slot, fork), d = TableSetting.halfZ(slot, fork); + AxisAlignedBB bounds = new AxisAlignedBB(x - w, 0, z - d, x + w, .04, z + d).offset(tile.getPos()); + RayTraceResult hit = bounds.calculateIntercept(from, to); + if (hit != null && (best == null || from.squareDistanceTo(hit.hitVec) < from.squareDistanceTo(best.hitVec))) { + best = new RayTraceResult(hit.hitVec, hit.sideHit, tile.getPos()); + } + } + } + return best; + } + + public static ItemStack pickSetting(PaintedPotEntity tile, Vec3d hit) { + BlockPos pos = tile.getPos(); + int slot = TableSetting.settingAt(hit.x - pos.getX(), hit.y - pos.getY(), hit.z - pos.getZ(), tile.layout()); + return slot < 0 ? ItemStack.EMPTY : tile.dining.utensil(slot).copy(); + } + + public static boolean breakSetting(PaintedPotEntity tile, EntityPlayer player) { + RayTraceResult ray = aim(player); + if (ray == null || !ray.getBlockPos().equals(tile.getPos())) return false; + Vec3d p = ray.hitVec; + BlockPos pos = ray.getBlockPos(); + int setting = TableSetting.settingAt(p.x - pos.getX(), p.y - pos.getY(), p.z - pos.getZ(), tile.layout()); + if (setting < 0 || tile.dining.utensil(setting).isEmpty()) return false; + if (!player.world.isRemote) { + if (!player.capabilities.isCreativeMode) player.dropItem(tile.dining.utensil(setting), false); + tile.dining.placeTool(setting, ItemStack.EMPTY); + tile.sync(); + } + return true; + } + private Dining() {} +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningInput.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningInput.java new file mode 100644 index 0000000..63c2b85 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningInput.java @@ -0,0 +1,25 @@ +package net.modcrafters.minecraft.primalpottery.legacy.dining; + +import net.minecraft.client.Minecraft; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.relauncher.Side; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) +public final class DiningInput { + private static boolean pressed; + static void begin() { pressed = true; } + static boolean holdingUse() { return pressed; } + @SubscribeEvent public static void tick(TickEvent.ClientTickEvent event) { + if (event.phase != TickEvent.Phase.END || !pressed) return; + Minecraft mc = Minecraft.getMinecraft(); + if (mc.player == null || mc.getConnection() == null) { + pressed = false; + } else if (mc.currentScreen != null || !mc.gameSettings.keyBindUseItem.isKeyDown()) { + pressed = false; + DiningRegistration.release(); + } + } + private DiningInput() {} +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRegistration.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRegistration.java new file mode 100644 index 0000000..8dff333 --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRegistration.java @@ -0,0 +1,34 @@ +package net.modcrafters.minecraft.primalpottery.legacy.dining; + +import io.netty.buffer.ByteBuf; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraftforge.event.RegistryEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.network.simpleimpl.*; +import net.minecraftforge.fml.relauncher.Side; + +@Mod.EventBusSubscriber(modid = "primalpottery") +public final class DiningRegistration { + public static final Item CUTLERY = new Item().setMaxStackSize(1).setCreativeTab(CreativeTabs.TOOLS) + .setRegistryName("primalpottery", "cutlery").setUnlocalizedName("primalpottery.cutlery"); + private static final SimpleNetworkWrapper CHANNEL = NetworkRegistry.INSTANCE.newSimpleChannel("pottery_dining"); + + @SubscribeEvent public static void register(RegistryEvent.Register event) { + event.getRegistry().register(CUTLERY); + CHANNEL.registerMessage((Released m, MessageContext ctx) -> { + net.minecraft.entity.player.EntityPlayerMP player = ctx.getServerHandler().player; + player.getServerWorld().addScheduledTask(() -> PlateMeal.release(player)); + return null; + }, Released.class, 0, Side.SERVER); + } + public static Item cutlery() { return CUTLERY; } + public static void release() { CHANNEL.sendToServer(new Released()); } + public static final class Released implements IMessage { + public void toBytes(ByteBuf buffer) {} + public void fromBytes(ByteBuf buffer) {} + } + private DiningRegistration() {} +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRenderer.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRenderer.java new file mode 100644 index 0000000..b27538e --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningRenderer.java @@ -0,0 +1,132 @@ +package net.modcrafters.minecraft.primalpottery.legacy.dining; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.*; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.client.renderer.entity.RenderPlayer; +import net.modcrafters.minecraft.primalpottery.legacy.client.PaintingClient; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.Vec3d; +import net.minecraftforge.client.event.ModelRegistryEvent; +import net.minecraftforge.client.event.RenderHandEvent; +import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.relauncher.Side; +import org.lwjgl.opengl.GL11; +import net.modcrafters.minecraft.primalpottery.dining.DiningMesh; +import net.modcrafters.minecraft.primalpottery.dining.DiningScene; +import net.modcrafters.minecraft.primalpottery.dining.Point; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; + +@Mod.EventBusSubscriber(modid = "primalpottery", value = Side.CLIENT) +public final class DiningRenderer extends DiningScene { + private static final ResourceLocation TOOLS = new ResourceLocation("primalpottery", "textures/block/cutlery.png"); + private static final ResourceLocation PIXEL = new ResourceLocation("primalpottery", "textures/block/serving_pixel.png"); + private final Minecraft mc = Minecraft.getMinecraft(); + private final PaintedPotEntity tile; + private final float partial; + + private DiningRenderer(PaintedPotEntity tile, float partial) { + this.tile = tile; + this.partial = partial; + } + + @SubscribeEvent public static void register(ModelRegistryEvent event) { + ModelLoader.setCustomModelResourceLocation(DiningRegistration.cutlery(), 0, new ModelResourceLocation("primalpottery:cutlery", "inventory")); + } + + @SubscribeEvent public static void hand(RenderHandEvent event) { + Minecraft mc = Minecraft.getMinecraft(); + if (mc.world == null || mc.player == null || mc.objectMouseOver == null + || mc.objectMouseOver.typeOfHit != net.minecraft.util.math.RayTraceResult.Type.BLOCK) return; + net.minecraft.tileentity.TileEntity tile = mc.world.getTileEntity(mc.objectMouseOver.getBlockPos()); + if (tile instanceof PaintedPotEntity && ((PaintedPotEntity) tile).dining.seated(mc.player.getEntityId())) event.setCanceled(true); + } + + public static void draw(PaintedPotEntity tile, double x, double y, double z, float partial) { + if (!tile.dining.hasVisuals()) return; + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, z); + GlStateManager.scale(1./32, 1./32, 1./32); + new DiningRenderer(tile, partial).draw(tile.layout(), tile.dining, tile.getWorld().getTotalWorldTime() + partial); + GlStateManager.popMatrix(); + } + @Override protected boolean empty(ItemStack stack) { return stack.isEmpty(); } + @Override protected boolean soup(ItemStack stack) { + return stack.getItem() == Items.MUSHROOM_STEW || stack.getItem() == Items.RABBIT_STEW || stack.getItem() == Items.BEETROOT_SOUP; + } + @Override protected Point mouth(int id) { + Entity eater = tile.getWorld().getEntityByID(id); + if (!(eater instanceof EntityPlayer)) return null; + Vec3d point = eater.getPositionEyes(partial).add(eater.getLook(partial).scale(.65)).addVector(0, -.11, 0); + return local(point); + } + private Point local(Vec3d point) { + return new Point(point.x - tile.getPos().getX(), point.y - tile.getPos().getY(), + point.z - tile.getPos().getZ()).scale(32); + } + @Override protected int[] pixels(ItemStack stack) { + return PaintingClient.iconPixels(mc.player, stack); + } + @Override protected void item(ItemStack stack, Point at, double width) { + GlStateManager.pushMatrix(); + GlStateManager.translate(at.x, at.y, at.z); + GlStateManager.rotate(-90, 1, 0, 0); + GlStateManager.scale(width, width, width); + mc.getRenderItem().renderItem(stack, ItemCameraTransforms.TransformType.FIXED); + GlStateManager.popMatrix(); + } + @Override protected void mesh(DiningMesh model, boolean food, Point at, double yaw, double pitch, double roll, double scale) { + GlStateManager.pushMatrix(); + GlStateManager.translate(at.x, at.y, at.z); + GlStateManager.rotate((float)yaw, 0, 1, 0); + GlStateManager.rotate((float)pitch, 1, 0, 0); + GlStateManager.rotate((float)roll, 0, 0, 1); + GlStateManager.scale(scale, scale, scale); + mc.getTextureManager().bindTexture(food ? PIXEL : TOOLS); + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder buffer = tessellator.getBuffer(); + buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR_NORMAL); + for (DiningMesh.Face face : model.faces) { + for (int i = 0; i < 4; i++) { + Point p = face.vertices[i]; + buffer.pos(p.x, p.y, p.z).tex(face.u[i], face.v[i]) + .color(face.rgb >> 16 & 255, face.rgb >> 8 & 255, face.rgb & 255, 255) + .normal((float)face.normal.x, (float)face.normal.y, (float)face.normal.z).endVertex(); + } + } + tessellator.draw(); + GlStateManager.color(1,1,1,1); + GlStateManager.popMatrix(); + } + + @Override protected void arm(int player, boolean right, Point grip) { + if (mc.player == null || mc.player.getEntityId() != player || mc.gameSettings.thirdPersonView != 0 || mc.gameSettings.hideGUI + || mc.player.isInvisible()) return; + Point eye = local(mc.player.getPositionEyes(partial)); + double turn = Math.toRadians(mc.player.prevRotationYaw + (mc.player.rotationYaw - mc.player.prevRotationYaw) * partial); + double side = right ? 1 : -1; + Point elbow = eye.add(-side * 15 * Math.cos(turn) + 4 * Math.sin(turn), -16, -side * 15 * Math.sin(turn) - 4 * Math.cos(turn)); + Point reach = grip.subtract(elbow); + float yaw = (float) Math.toDegrees(Math.atan2(reach.x, reach.z)); + float pitch = (float) Math.toDegrees(Math.atan2(Math.hypot(reach.x, reach.z), reach.y)); + float length = (float) Math.sqrt(reach.x * reach.x + reach.y * reach.y + reach.z * reach.z); + GlStateManager.pushMatrix(); + GlStateManager.translate(grip.x, grip.y, grip.z); + GlStateManager.rotate(yaw, 0, 1, 0); + GlStateManager.rotate(pitch, 1, 0, 0); + GlStateManager.scale(20, length * 16 / 12, 20); + GlStateManager.translate((right ? 6.6 : -6.6) / 16, -11. / 16, 0); + mc.getTextureManager().bindTexture(mc.player.getLocationSkin()); + RenderPlayer renderer = mc.getRenderManager().getSkinMap().get(mc.player.getSkinType()); + if (right) renderer.renderRightArm(mc.player); else renderer.renderLeftArm(mc.player); + GlStateManager.popMatrix(); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningTable.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningTable.java new file mode 100644 index 0000000..61d173a --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/DiningTable.java @@ -0,0 +1,83 @@ +package net.modcrafters.minecraft.primalpottery.legacy.dining; + +import java.util.function.IntFunction; +import java.util.function.ObjIntConsumer; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.item.ItemStack; +import net.modcrafters.minecraft.primalpottery.dining.Diner; +import net.modcrafters.minecraft.primalpottery.dining.ServingInventory; + +public final class DiningTable extends ServingInventory { + public DiningTable() { super(ItemStack.EMPTY); } + @Override protected boolean empty(ItemStack stack) { return stack.isEmpty(); } + + public void save(NBTTagCompound data) { + if (!hasVisuals()) { + data.removeTag("servings"); + data.removeTag("utensils"); + return; + } + saveStacks(data, "servings", this::serving); + saveStacks(data, "utensils", this::utensil); + } + + private void saveStacks(NBTTagCompound data, String key, IntFunction stacks) { + NBTTagList list = new NBTTagList(); + for (int i = 0; i < PotteryLayout.COUNT; i++) { + ItemStack stack = stacks.apply(i); + if (stack.isEmpty()) continue; + NBTTagCompound entry = stack.writeToNBT(new NBTTagCompound()); + entry.setByte("slot", (byte) i); + list.appendTag(entry); + } + if (list.tagCount() > 0) data.setTag(key, list); + else data.removeTag(key); + } + public void load(NBTTagCompound data) { + clear(); + loadStacks(data, "servings", (stack, slot) -> serve(slot, stack)); + loadStacks(data, "utensils", (stack, slot) -> placeTool(slot, stack)); + NBTTagList list = data.getTagList("diners", 10); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound entry = list.getCompoundTagAt(i); + int slot = entry.getByte("slot"); + if (slot < 0 || slot >= PotteryLayout.COUNT) continue; + setDiner(slot, new Diner(entry.getInteger("player"), entry.getLong("start"), entry.getInteger("duration"), + entry.getBoolean("cutlery"), entry.getBoolean("from_table"), entry.getBoolean("left"))); + } + } + private void loadStacks(NBTTagCompound data, String key, ObjIntConsumer slots) { + NBTTagList list = data.getTagList(key, 10); + for (int i = 0; i < list.tagCount(); i++) { + NBTTagCompound entry = list.getCompoundTagAt(i); + int slot = entry.getByte("slot"); + if (slot < 0 || slot >= PotteryLayout.COUNT) continue; + ItemStack stack = new ItemStack(entry); + if (!stack.isEmpty()) { + stack.setCount(1); + slots.accept(stack, slot); + } + } + } + /** A player who starts watching the chunk mid-meal sees its current animation. */ + public void writeDiners(NBTTagCompound data) { + NBTTagList list = new NBTTagList(); + for (int i = 0; i < PotteryLayout.COUNT; i++) { + Diner diner = diner(i); + if (diner == null) continue; + NBTTagCompound entry = new NBTTagCompound(); + entry.setByte("slot", (byte) i); + entry.setInteger("player", diner.player); + entry.setLong("start", diner.start); + entry.setInteger("duration", diner.duration); + entry.setBoolean("cutlery", diner.cutlery); + entry.setBoolean("from_table", diner.fromTable); + entry.setBoolean("left", diner.left); + list.appendTag(entry); + } + if (list.tagCount() > 0) data.setTag("diners", list); + else data.removeTag("diners"); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/PlateMeal.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/PlateMeal.java new file mode 100644 index 0000000..3427c1b --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/dining/PlateMeal.java @@ -0,0 +1,152 @@ +package net.modcrafters.minecraft.primalpottery.legacy.dining; + +import java.util.Map; +import java.util.WeakHashMap; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.SoundEvents; +import net.minecraft.item.Item; +import net.minecraft.item.ItemFood; +import net.minecraft.item.ItemStack; +import net.minecraft.util.*; +import net.minecraft.util.math.*; +import net.minecraft.world.WorldServer; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.PlayerEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.common.ObfuscationReflectionHelper; +import net.minecraftforge.event.ForgeEventFactory; +import net.modcrafters.minecraft.primalpottery.dining.Diner; +import net.modcrafters.minecraft.primalpottery.dining.TableSetting; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; + +@Mod.EventBusSubscriber(modid = "primalpottery") +public final class PlateMeal { + // All accesses are on the server thread. Client input only sends the release transition. + private static final Map ACTIVE = new WeakHashMap<>(); + private static final Map FINISHED_PRESS = new WeakHashMap<>(); + private final PaintedPotEntity tile; + private final int dish, serving; + private final EnumHand hand; + private final Diner diner; + private final ItemStack displayed, held; + private final boolean toolInHand; + + private PlateMeal(PaintedPotEntity tile, int dish, int serving, EnumHand hand, Diner diner, EntityPlayer player) { + this.tile = tile; + this.dish = dish; + this.serving = serving; + this.hand = hand; + this.diner = diner; + this.held = player.getHeldItem(hand); + this.displayed = tile.dining.serving(serving); + toolInHand = held.getItem() == DiningRegistration.cutlery(); + } + + static boolean blocksRepeat(EntityPlayer player) { + return player.world.isRemote ? DiningInput.holdingUse() : FINISHED_PRESS.containsKey(player); + } + + static boolean start(PaintedPotEntity tile, int dish, int serving, EntityPlayer player, EnumHand hand) { + ItemStack food = tile.dining.serving(serving); + if (!canEat(player, food)) return false; + if (player.world.isRemote) { + DiningInput.begin(); + return true; + } + if (ACTIVE.containsKey(player) || tile.dining.diner(serving) != null) return true; + boolean heldTool = player.getHeldItem(hand).getItem() == DiningRegistration.cutlery(); + boolean tableTool = !heldTool && player.getHeldItem(EnumHand.MAIN_HAND).isEmpty() + && player.getHeldItem(EnumHand.OFF_HAND).isEmpty() && !tile.dining.utensil(serving).isEmpty(); + int ticks = ForgeEventFactory.onItemUseStart(player, food, food.getMaxItemUseDuration()); + if (ticks <= 0) return false; + boolean left = (player.getPrimaryHand() == EnumHandSide.LEFT) == (hand == EnumHand.MAIN_HAND); + Diner diner = new Diner(player.getEntityId(), player.world.getTotalWorldTime(), heldTool || tableTool ? Math.max(96, ticks) : ticks, + heldTool || tableTool, tableTool, left); + ACTIVE.put(player, new PlateMeal(tile, dish, serving, hand, diner, player)); + tile.dining.setDiner(serving, diner); + tile.sync(); + return true; + } + + private static boolean canEat(EntityPlayer player, ItemStack food) { + if (food.isEmpty() || player.isSpectator() || player.getCooldownTracker().hasCooldown(food.getItem())) return false; + if (!(food.getItem() instanceof ItemFood)) return false; + if (player.canEat(false)) return true; + boolean alwaysEdible = ObfuscationReflectionHelper.getPrivateValue(ItemFood.class, (ItemFood) food.getItem(), "field_77852_bZ"); + return player.canEat(alwaysEdible); + } + + private boolean valid(EntityPlayer player) { + if (!player.isEntityAlive() || player.isSneaking() || tile.isInvalid() + || tile.getWorld() != player.world || !canEat(player, displayed) + || tile.dining.diner(serving) != diner || tile.dining.serving(serving) != displayed) return false; + ItemStack current = player.getHeldItem(hand); + if (toolInHand ? current != held : !current.isEmpty()) return false; + if (diner.fromTable && (tile.dining.utensil(serving).isEmpty() || !player.getHeldItem(EnumHand.OFF_HAND).isEmpty())) return false; + RayTraceResult hit = Dining.aim(player); + if (hit == null || !tile.getPos().equals(hit.getBlockPos())) return false; + double x = hit.hitVec.x - tile.getPos().getX(), z = hit.hitVec.z - tile.getPos().getZ(); + Pottery shape = tile.layout().at(dish); + return shape != null && tile.layout().hit(x, z) == dish && TableSetting.serving(shape, dish, x, z) == serving; + } + + @SubscribeEvent public static void tick(TickEvent.PlayerTickEvent event) { + EntityPlayer player = event.player; + if (event.phase != TickEvent.Phase.END || player.world.isRemote) return; + PlateMeal meal = ACTIVE.get(player); + if (meal == null) return; + if (!meal.valid(player)) { meal.stop(player); return; } + long time = player.world.getTotalWorldTime(); + meal.effects(player, time); + if (time - meal.diner.start >= meal.diner.duration) { + meal.finish(player); + FINISHED_PRESS.put(player, true); + } + } + + public static void release(EntityPlayer player) { + FINISHED_PRESS.remove(player); + PlateMeal meal = ACTIVE.get(player); + if (meal == null) return; + if (meal.diner.cutlery && player.world.getTotalWorldTime() >= meal.diner.lastSwallow() && meal.valid(player)) meal.finish(player); + else meal.stop(player); + } + + private void effects(EntityPlayer player, long time) { + long elapsed = time - diner.start; + if (diner.cutlery && diner.beat(time, .12)) { + player.world.playSound(null, tile.getPos(), SoundEvents.BLOCK_STONE_HIT, SoundCategory.PLAYERS, .32F, 1.65F); + } + if (diner.cutlery ? !diner.beat(time, .79) : elapsed < 5 || elapsed % 5 != 0) return; + Pottery plate = tile.layout().at(dish); + double x = tile.getPos().getX() + TableSetting.servingX(plate, serving); + double y = tile.getPos().getY() + plate.height() / 32 + .04; + double z = tile.getPos().getZ() + TableSetting.servingZ(plate, serving); + ((WorldServer) player.world).spawnParticle(EnumParticleTypes.ITEM_CRACK, x, y, z, 3, .04, .035, .04, + .025, Item.getIdFromItem(displayed.getItem()), displayed.getMetadata()); + player.world.playSound(null, tile.getPos(), SoundEvents.ENTITY_GENERIC_EAT, SoundCategory.PLAYERS, .55F, 1F); + } + + private void finish(EntityPlayer player) { + ItemStack working = displayed.copy(); + ItemStack result = working.onItemUseFinish(player.world, player); + result = ForgeEventFactory.onItemUseFinish(player, displayed.copy(), 0, result); + tile.dining.serve(serving, result); + stop(player); + } + private void stop(EntityPlayer player) { + ACTIVE.remove(player); + if (!tile.isInvalid() && tile.dining.diner(serving) == diner) { + tile.dining.setDiner(serving, null); + tile.sync(); + } + } + @SubscribeEvent public static void logout(PlayerEvent.PlayerLoggedOutEvent event) { + EntityPlayer player = event.player; + FINISHED_PRESS.remove(player); + PlateMeal meal = ACTIVE.get(player); + if (meal != null) meal.stop(player); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java index 1731e3c..b797af6 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/loading/FurnaceResultTransformer.java @@ -11,6 +11,7 @@ public final class FurnaceResultTransformer implements IClassTransformer { private static final String HOOK = "net/modcrafters/minecraft/primalpottery/legacy/FirePotteryRecipe"; public byte[] transform(String name, String mappedName, byte[] bytes) { + if ("net.minecraft.tileentity.TileEntityFurnace".equals(mappedName)) return checkOutput(bytes); if (!"net.minecraft.item.crafting.FurnaceRecipes".equals(mappedName)) return bytes; ClassNode recipes = new ClassNode(); new ClassReader(bytes).accept(recipes, 0); @@ -32,4 +33,23 @@ public byte[] transform(String name, String mappedName, byte[] bytes) { } throw new IllegalStateException("Missing Forge 1.12.2 furnace recipe lookup"); } + + private byte[] checkOutput(byte[] bytes) { + ClassNode furnace = new ClassNode(); + new ClassReader(bytes).accept(furnace, 0); + for (MethodNode method : furnace.methods) { + if (!(method.name.equals("canSmelt") || method.name.equals("func_145948_k")) || !method.desc.equals("()Z")) continue; + for (AbstractInsnNode instruction : method.instructions.toArray()) { + if (!(instruction instanceof MethodInsnNode)) continue; + MethodInsnNode call = (MethodInsnNode) instruction; + if ((call.name.equals("isItemEqual") || call.name.equals("func_77969_a")) && call.desc.equals("(" + STACK + ")Z")) { + method.instructions.set(call, new MethodInsnNode(Opcodes.INVOKESTATIC, HOOK, "canCombine", "(" + STACK + STACK + ")Z", false)); + ClassWriter writer = new ClassWriter(0); + furnace.accept(writer); + return writer.toByteArray(); + } + } + } + throw new IllegalStateException("Missing Forge 1.12.2 furnace output comparison"); + } } diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/painting_table.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/painting_table.json new file mode 100644 index 0000000..329dbec --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/blockstates/painting_table.json @@ -0,0 +1,7 @@ +{ + "variants": { + "normal": { + "model": "primalpottery:painting_table" + } + } +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang index f28a5e8..a17d445 100644 --- a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/lang/en_us.lang @@ -25,3 +25,43 @@ pottery.primalpottery.shape.bowl=Bowl pottery.primalpottery.shape.pottery=Pottery tile.primalpottery.pottery_wheel.name=Pottery Wheel item.primalpottery.raw_pottery.name=Unfired Pottery +item.primalpottery.cutlery.name=Cutlery +gui.primalpottery.lid.put_on=Put on lid +gui.primalpottery.lid.remove=Remove lid +gui.primalpottery.lid.empty=Empty +gui.primalpottery.lid.contents=%s · %s / %s mL +message.primalpottery.soil.capacity=Too small for soil. This pottery needs at least %s mL of capacity. +message.primalpottery.soil.lid=Remove the lid before adding soil. +message.primalpottery.soil.liquid=Empty the liquid before adding soil. +message.primalpottery.soil.occupied=This pottery already contains soil. +gui.primalpottery.lid.closed=Lid fitted +gui.primalpottery.paint.center=Center +gui.primalpottery.paint.rim=Rim +gui.primalpottery.paint.erase=Eraser +gui.primalpottery.paint.undo_cost=Undo the last square. Restoring a color uses 1 mL of that paint. +gui.primalpottery.paint.volume=%s / 100 mL +gui.primalpottery.paint.refill=1 mL per square. One matching dye refills 100 mL. +gui.primalpottery.paint.missing=Tank empty. Carry matching dye to paint. +gui.primalpottery.paint.hold=Hold fired pottery +gui.primalpottery.paint.reopen=and reopen the table. +gui.primalpottery.paint.stock=%s matching dye in inventory +message.primalpottery.paint.missing=Need %s to paint %s onto pottery. +message.primalpottery.paint.amount=%s (%s mL) +message.primalpottery.paint.stamped=Painted pottery with %s. +tile.primalpottery.painting_table.name=Pottery Painting Table +itemGroup.primalpottery=Primal Pottery +item.primalpottery.raw_shape=Raw %s +tooltip.primalpottery.type=Type: %s +tooltip.primalpottery.needs_firing=Needs firing +tooltip.primalpottery.can_be_dyed=Can be dyed +tooltip.primalpottery.will_contain=Will contain %s mL +tooltip.primalpottery.wheel_clay_block=Wheel needs a clay block +tooltip.primalpottery.wheel_clay_ball=Wheel needs a clay ball +tooltip.primalpottery.capacity=Capacity: %s mL +pottery.primalpottery.type.plate=Plate +pottery.primalpottery.type.platter=Serving Platter +tooltip.primalpottery.contents=%s: %s mL +pottery.primalpottery.type.lump=Lump +pottery.primalpottery.type.pot=Bowl +pottery.primalpottery.type.jar=Pottery +pottery.primalpottery.type.jug=Jug diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/cutlery.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/cutlery.json new file mode 100644 index 0000000..c265fdc --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/cutlery.json @@ -0,0 +1,18 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "III", + "SSS" + ], + "key": { + "I": { + "item": "minecraft:iron_nugget" + }, + "S": { + "item": "minecraft:stick" + } + }, + "result": { + "item": "primalpottery:cutlery" + } +} diff --git a/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/painting_table.json b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/painting_table.json new file mode 100644 index 0000000..6873cdf --- /dev/null +++ b/legacy/forge-1.12.2/src/main/resources/assets/primalpottery/recipes/painting_table.json @@ -0,0 +1,27 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " DF", + "PPP", + "S S" + ], + "key": { + "D": { + "item": "minecraft:dye", + "data": 15 + }, + "F": { + "item": "minecraft:flower_pot" + }, + "P": { + "type": "forge:ore_dict", + "ore": "plankWood" + }, + "S": { + "item": "minecraft:stick" + } + }, + "result": { + "item": "primalpottery:painting_table" + } +} diff --git a/legacy/forge-1.12.2/src/main/resources/mcmod.info b/legacy/forge-1.12.2/src/main/resources/mcmod.info index ec20409..df975ed 100644 --- a/legacy/forge-1.12.2/src/main/resources/mcmod.info +++ b/legacy/forge-1.12.2/src/main/resources/mcmod.info @@ -1 +1 @@ -[{"modid":"primalpottery","name":"Primal Pottery","version":"${version}","mcversion":"1.12.2","description":"Placeable painted pottery.","authorList":["modcrafters"]}] +[{"modid":"primalpottery","name":"Primal Pottery","version":"${version}","mcversion":"1.12.2","description":"Shape clay on a pottery wheel, fire and paint your creations, grow plants and serve meals.","authorList":["modcrafters"]}] diff --git a/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/dining/ServingPiecesTest.java b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/dining/ServingPiecesTest.java new file mode 100644 index 0000000..26627f1 --- /dev/null +++ b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/dining/ServingPiecesTest.java @@ -0,0 +1,39 @@ +package net.modcrafters.minecraft.primalpottery.dining; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +final class ServingPiecesTest { + @Test void sparseIconHasFourEqualEdibleAreasInEveryDirection() { + int[] pixels = new int[256]; + for (int i : new int[]{0, 1, 2, 16, 227}) pixels[i] = 0xffce721e; + // The almost invisible edge does not contribute to any of the four bites. + pixels[15] = 0x08ffffff; + for (Point approach : new Point[]{new Point(0, 0, 1), new Point(1, 0, 0)}) { + for (double hand : new double[]{-1, 1}) { + ServingPieces cut = new ServingPieces(pixels, approach, hand); + assertTrue(cut.available); + for (DiningMesh bite : cut.meshes) { + double top = 0; + for (DiningMesh.Face face : bite.faces) { + if (face.normal.y <= .99) continue; + Point diagonal = face.vertices[2].subtract(face.vertices[0]); + top += Math.abs(diagonal.x * diagonal.z); + } + assertEquals(5.0 / (256 * 4), top, 1e-10); + } + } + } + assertFalse(new ServingPieces(new int[256], Point.ZERO, 1).available); + assertFalse(new ServingPieces(null, Point.ZERO, 1).available); + } + + @Test void releaseCanOnlySwallowAfterAllFourBites() { + Diner eater = new Diner(1, 100, 96, true, true, false); + assertEquals(191, eater.lastSwallow()); + assertTrue(eater.beat(119, .79)); + assertTrue(eater.beat(191, .79)); + assertEquals(3, (int) eater.cycle(400)); + assertEquals(1, eater.lift(400), 1e-10); + } +} diff --git a/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrushTest.java b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrushTest.java new file mode 100644 index 0000000..9dc4893 --- /dev/null +++ b/legacy/forge-1.12.2/src/test/java/net/modcrafters/minecraft/primalpottery/painting/PaintBrushTest.java @@ -0,0 +1,60 @@ +package net.modcrafters.minecraft.primalpottery.painting; + +import java.util.Collections; +import net.modcrafters.minecraft.primalpottery.pottery.*; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class PaintBrushTest { + private final int[] dyes = new int[FacePaint.COLORS]; + private final PigmentTanks tanks = new PigmentTanks(); + private final PigmentTanks.Stock stock = new PigmentTanks.Stock() { + public int count(int color) { return dyes[color]; } + public void consume(int color, int count) { dyes[color] -= count; } + }; + private final PaintBrush brush = new PaintBrush(); + + @Test void stampChecksEveryPigmentBeforeSpendingAnyDye() { + FacePaint pattern = FacePaint.EMPTY.with(0, 0).with(1, 0).with(2, 14); + dyes[0] = 1; + int[] shortage = new int[FacePaint.COLORS]; + PigmentTanks.Shortage report = (color, amount) -> shortage[color] = amount; + assertEquals(14, tanks.stamp(FacePaint.EMPTY, pattern, stock, report)); + assertEquals(1, shortage[14]); + assertEquals(0, shortage[0]); + assertEquals(1, dyes[0]); + assertEquals(0, tanks.get(0)); + dyes[14] = 1; + assertEquals(-1, tanks.stamp(FacePaint.EMPTY, pattern, stock, report)); + assertEquals(0, dyes[0]); + assertEquals(0, dyes[14]); + assertEquals(98, tanks.get(0)); + assertEquals(99, tanks.get(14)); + assertEquals(-1, tanks.stamp(pattern, pattern, stock, report)); + assertEquals(98, tanks.get(0)); + } + + @Test void undoRestoresThePreviousPigmentOnlyWhenItCanBePaidFor() { + Pottery original = Pottery.jug().withPaint(FacePaint.EMPTY.with(35, 18)); + Pottery erased = brush.apply(original, PaintBrush.stroke(35, FacePaint.ERASE), tanks, stock); + assertEquals(FacePaint.ERASE, erased.paint().color(35)); + assertNull(brush.apply(erased, PaintBrush.UNDO, tanks, stock)); + dyes[4] = 1; + Pottery restored = brush.apply(erased, PaintBrush.UNDO, tanks, stock); + assertEquals(original.paint(), restored.paint()); + assertEquals(99, tanks.get(4)); + assertEquals(0, brush.undoCost()); + } + + @Test void platesOnlyAcceptFourColumnsOfSixteenRadialCells() { + Pottery plate = new Pottery(Collections.singletonList(new PotteryDisc(1, 8))); + tanks.set(14, 2); + assertTrue(plate.isPlate()); + assertNull(brush.apply(plate, PaintBrush.stroke(64, 14), tanks, stock)); + Pottery painted = brush.apply(plate, PaintBrush.stroke(63, 14), tanks, stock); + assertEquals(14, painted.paint().color(63)); + assertEquals(1, tanks.get(14)); + assertEquals(FacePaint.EMPTY, brush.apply(painted, PaintBrush.UNDO, tanks, stock).paint()); + assertEquals(1, tanks.get(14)); + } +} diff --git a/src/main/resources/assets/primalpottery/textures/block/serving_pixel.png b/src/main/resources/assets/primalpottery/textures/block/serving_pixel.png new file mode 100644 index 0000000000000000000000000000000000000000..4ca3388b73255f6de5d2c3f03cbe86b950af655e GIT binary patch literal 77 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61SBU+%rFB|BAzaeAr-fhfA}jUNL)2omG~oz afnojHzw)^+7MudgGkCiCxvX Date: Thu, 3 Dec 2026 05:29:20 +0200 Subject: [PATCH 17/22] Share versioned IntelliJ runs for every loader target Co-authored-by: Face of Cat --- .run/Fabric 26.3 Client.run.xml | 14 ++++++++++++++ .run/Fabric 26.3 Server.run.xml | 14 ++++++++++++++ .run/Forge 1.12.2 Client.run.xml | 14 ++++++++++++++ .run/Forge 1.12.2 Server.run.xml | 14 ++++++++++++++ .run/Forge 1.20.1 Client.run.xml | 14 ++++++++++++++ .run/Forge 1.20.1 Server.run.xml | 14 ++++++++++++++ .run/NeoForge 1.20.6 Client.run.xml | 14 ++++++++++++++ .run/NeoForge 1.20.6 GameTest Server.run.xml | 14 ++++++++++++++ .run/NeoForge 1.20.6 Server.run.xml | 14 ++++++++++++++ .run/NeoForge 1.21.1 Client.run.xml | 14 ++++++++++++++ .run/NeoForge 1.21.1 GameTest Server.run.xml | 14 ++++++++++++++ .run/NeoForge 1.21.1 Server.run.xml | 14 ++++++++++++++ .run/NeoForge 26.3 Client.run.xml | 14 ++++++++++++++ .run/NeoForge 26.3 GameTest Server.run.xml | 14 ++++++++++++++ .run/NeoForge 26.3 Server.run.xml | 14 ++++++++++++++ forge/build.gradle | 2 ++ forge/legacy-runs.gradle | 20 ++++++++++++++++++++ 17 files changed, 232 insertions(+) create mode 100644 .run/Fabric 26.3 Client.run.xml create mode 100644 .run/Fabric 26.3 Server.run.xml create mode 100644 .run/Forge 1.12.2 Client.run.xml create mode 100644 .run/Forge 1.12.2 Server.run.xml create mode 100644 .run/Forge 1.20.1 Client.run.xml create mode 100644 .run/Forge 1.20.1 Server.run.xml create mode 100644 .run/NeoForge 1.20.6 Client.run.xml create mode 100644 .run/NeoForge 1.20.6 GameTest Server.run.xml create mode 100644 .run/NeoForge 1.20.6 Server.run.xml create mode 100644 .run/NeoForge 1.21.1 Client.run.xml create mode 100644 .run/NeoForge 1.21.1 GameTest Server.run.xml create mode 100644 .run/NeoForge 1.21.1 Server.run.xml create mode 100644 .run/NeoForge 26.3 Client.run.xml create mode 100644 .run/NeoForge 26.3 GameTest Server.run.xml create mode 100644 .run/NeoForge 26.3 Server.run.xml create mode 100644 forge/legacy-runs.gradle diff --git a/.run/Fabric 26.3 Client.run.xml b/.run/Fabric 26.3 Client.run.xml new file mode 100644 index 0000000..c745668 --- /dev/null +++ b/.run/Fabric 26.3 Client.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/Fabric 26.3 Server.run.xml b/.run/Fabric 26.3 Server.run.xml new file mode 100644 index 0000000..735db42 --- /dev/null +++ b/.run/Fabric 26.3 Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/Forge 1.12.2 Client.run.xml b/.run/Forge 1.12.2 Client.run.xml new file mode 100644 index 0000000..1c7fef5 --- /dev/null +++ b/.run/Forge 1.12.2 Client.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/Forge 1.12.2 Server.run.xml b/.run/Forge 1.12.2 Server.run.xml new file mode 100644 index 0000000..46064a9 --- /dev/null +++ b/.run/Forge 1.12.2 Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/Forge 1.20.1 Client.run.xml b/.run/Forge 1.20.1 Client.run.xml new file mode 100644 index 0000000..bbabe6a --- /dev/null +++ b/.run/Forge 1.20.1 Client.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/Forge 1.20.1 Server.run.xml b/.run/Forge 1.20.1 Server.run.xml new file mode 100644 index 0000000..b9427ef --- /dev/null +++ b/.run/Forge 1.20.1 Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 1.20.6 Client.run.xml b/.run/NeoForge 1.20.6 Client.run.xml new file mode 100644 index 0000000..3b36b01 --- /dev/null +++ b/.run/NeoForge 1.20.6 Client.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 1.20.6 GameTest Server.run.xml b/.run/NeoForge 1.20.6 GameTest Server.run.xml new file mode 100644 index 0000000..955fca1 --- /dev/null +++ b/.run/NeoForge 1.20.6 GameTest Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 1.20.6 Server.run.xml b/.run/NeoForge 1.20.6 Server.run.xml new file mode 100644 index 0000000..f709566 --- /dev/null +++ b/.run/NeoForge 1.20.6 Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 1.21.1 Client.run.xml b/.run/NeoForge 1.21.1 Client.run.xml new file mode 100644 index 0000000..848530d --- /dev/null +++ b/.run/NeoForge 1.21.1 Client.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 1.21.1 GameTest Server.run.xml b/.run/NeoForge 1.21.1 GameTest Server.run.xml new file mode 100644 index 0000000..66b1ead --- /dev/null +++ b/.run/NeoForge 1.21.1 GameTest Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 1.21.1 Server.run.xml b/.run/NeoForge 1.21.1 Server.run.xml new file mode 100644 index 0000000..d6ec55b --- /dev/null +++ b/.run/NeoForge 1.21.1 Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 26.3 Client.run.xml b/.run/NeoForge 26.3 Client.run.xml new file mode 100644 index 0000000..60b55d4 --- /dev/null +++ b/.run/NeoForge 26.3 Client.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 26.3 GameTest Server.run.xml b/.run/NeoForge 26.3 GameTest Server.run.xml new file mode 100644 index 0000000..bfc2a58 --- /dev/null +++ b/.run/NeoForge 26.3 GameTest Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/.run/NeoForge 26.3 Server.run.xml b/.run/NeoForge 26.3 Server.run.xml new file mode 100644 index 0000000..9ee37fc --- /dev/null +++ b/.run/NeoForge 26.3 Server.run.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/forge/build.gradle b/forge/build.gradle index f2630e5..f351553 100644 --- a/forge/build.gradle +++ b/forge/build.gradle @@ -43,3 +43,5 @@ apply from: 'shared/wheel-models.gradle' apply from: 'shared/dining.gradle' apply from: 'shared/painting.gradle' + +apply from: 'legacy-runs.gradle' diff --git a/forge/legacy-runs.gradle b/forge/legacy-runs.gradle new file mode 100644 index 0000000..81abe27 --- /dev/null +++ b/forge/legacy-runs.gradle @@ -0,0 +1,20 @@ +// ForgeGradle 3 needs its own Gradle 5 build running on a full JDK 8. +def legacyDirectory = rootProject.file('legacy/forge-1.12.2') +def legacyJdk = javaToolchains.compilerFor { + languageVersion = JavaLanguageVersion.of(8) +} + +['Client', 'Server'].each { target -> + tasks.register("runLegacy${target}", Exec) { + group = 'mod development' + description = "Launch the Forge 1.12.2 ${target.toLowerCase()} using the legacy wrapper." + workingDir legacyDirectory + standardInput = System.in + args '-classpath', 'gradle/wrapper/gradle-wrapper.jar', 'org.gradle.wrapper.GradleWrapperMain', "run${target}" + doFirst { + def jdk = legacyJdk.get().metadata.installationPath + executable jdk.file('bin/java').asFile + environment 'JAVA_HOME', jdk.asFile.absolutePath + } + } +} From 71ac5c1a862200b52c8d79d043a65573464e5655 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 05:47:46 +0200 Subject: [PATCH 18/22] Wait for the legacy player to reach the painting test table Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/PaintingClientCheck.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java index 6724c7f..b909890 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/PaintingClientCheck.java @@ -19,7 +19,9 @@ /** Uses native crafting, menu synchronization, brush packets and the offhand icon stamp in a real client. */ final class PaintingClientCheck { - private static final BlockPos TABLE = new BlockPos(72,80,40); + // Keep the table and the player's footing in the already-loaded wheel test chunk. + private static final BlockPos TABLE = WheelGameplay.BASE.east(); + private static final BlockPos STAND = TABLE.north(2); private enum Step { SETUP, OPEN, STROKE, UNDO, REPAINT, SNAPSHOT, FIND_POT, STAMP, VERIFY, DONE } private Step step = Step.SETUP; private Future task; @@ -30,14 +32,17 @@ public boolean tick(Minecraft client) throws Exception { if (task != null && !task.isDone()) return false; if (task != null) { task.get(); task = null; } if (step == Step.DONE) return true; - if (++ticks > 1200) throw new AssertionError("Painting timed out at " + step); + if (++ticks > 1200) throw new AssertionError("Painting timed out at " + step + + ", screen=" + client.currentScreen + ", player=" + client.player.getPositionVector() + + ", held=" + client.player.getHeldItemMainhand() + ", menu=" + client.player.openContainer); net.minecraft.server.MinecraftServer server = client.getIntegratedServer(); switch (step) { case SETUP: task = server.addScheduledTask(() -> prepare(server.getWorld(0),server.getPlayerList().getPlayers().get(0))); break; case OPEN: - if (!PaintingRegistration.dyed(client.player.getHeldItem(EnumHand.MAIN_HAND)) + if (client.player.getDistanceSq(STAND.getX() + .5, STAND.getY(), STAND.getZ() + .5) > .25 + || !PaintingRegistration.dyed(client.player.getHeldItem(EnumHand.MAIN_HAND)) || !(client.world.getTileEntity(TABLE) instanceof PaintingTableEntity)) return false; checkModel(client, client.player.getHeldItem(EnumHand.MAIN_HAND), false); useTable(client); @@ -119,10 +124,10 @@ private static void useTable(Minecraft client) { } private static void prepare(WorldServer level, EntityPlayerMP player) { level.setBlockState(TABLE.down(),Blocks.STONE.getDefaultState()); - level.setBlockState(TABLE.add(0,-1,-2),Blocks.STONE.getDefaultState()); + level.setBlockState(STAND.down(), Blocks.STONE.getDefaultState()); level.setBlockToAir(TABLE); level.setBlockState(TABLE,PaintingRegistration.TABLE.getDefaultState()); - player.connection.setPlayerLocation(72.5,80,38.5,0,10); + player.connection.setPlayerLocation(STAND.getX() + .5, STAND.getY(), STAND.getZ() + .5, 0, 10); ItemStack raw = new ItemStack(PrimalPotteryForge.RAW); ForgeStackProfiles.INSTANCE.write(raw,Pottery.jug()); InventoryCrafting grid = new InventoryCrafting(player.inventoryContainer,2,2); From 29b2d1a4e6ef7b4984fef4aafb13bf79462299c6 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 06:10:54 +0200 Subject: [PATCH 19/22] Fit legacy pottery icons and allow placement in free corners Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/DisplayCheck.java | 5 +- .../potterycheck/InventoryIconCheck.java | 74 ++++++++++++++++ .../potterycheck/PlacementClientCheck.java | 86 +++++++++++++++++++ .../potterycheck/PlacementGameplay.java | 2 +- .../potterycheck/VesselClientCheck.java | 5 +- .../legacy/PotteryBlockItem.java | 22 +++-- .../legacy/VesselInteractions.java | 3 +- .../client/InventoryPotteryTransform.java | 55 ++++++++++++ .../legacy/client/PlacementOutline.java | 15 ++-- .../legacy/client/PotteryModel.java | 12 ++- .../legacy/client/VesselScreen.java | 17 ++++ 11 files changed, 274 insertions(+), 22 deletions(-) create mode 100644 .github/forge-display-check/1.12.2/potterycheck/InventoryIconCheck.java create mode 100644 .github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/InventoryPotteryTransform.java diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java index 635d523..78afdbc 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -35,6 +35,7 @@ public final class DisplayCheck { private static final ForgeTemplateCheck templates = new ForgeTemplateCheck(); private static final PaintingClientCheck painting = new PaintingClientCheck(); private static final WheelClientCheck wheel = new WheelClientCheck(); + private static final PlacementClientCheck sharedPlacement = new PlacementClientCheck(); private static boolean opening; private static boolean placed; private static int ticks; @@ -61,7 +62,8 @@ public final class DisplayCheck { return; } if (mc.player == null || mc.world == null || ++ticks < 40) return; - if (!templates.tick() || !wheel.tick(mc) || !VesselClientCheck.tick(mc) || !painting.tick(mc) || !DiningClientCheck.tick(mc)) return; + if (!templates.tick() || !wheel.tick(mc) || !VesselClientCheck.tick(mc) || !sharedPlacement.tick(mc) + || !painting.tick(mc) || !DiningClientCheck.tick(mc)) return; if (!placed) { placed = true; mc.gameSettings.hideGUI = true; @@ -98,6 +100,7 @@ private static void install(WorldServer level) { if (referenceStarted != 0) { if (mc.player.posX > 39 && System.nanoTime() - referenceStarted > 4_000_000_000L) { screenshot(mc, "reference.png"); + InventoryIconCheck.verify(mc); mc.shutdown(); } return; diff --git a/.github/forge-display-check/1.12.2/potterycheck/InventoryIconCheck.java b/.github/forge-display-check/1.12.2/potterycheck/InventoryIconCheck.java new file mode 100644 index 0000000..1c4bda7 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/InventoryIconCheck.java @@ -0,0 +1,74 @@ +package potterycheck; + +import java.awt.Rectangle; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import javax.imageio.ImageIO; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ScreenShotHelper; +import net.modcrafters.minecraft.primalpottery.legacy.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.legacy.PrimalPotteryForge; +import net.modcrafters.minecraft.primalpottery.legacy.VesselData; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; + +final class InventoryIconCheck { + private static final int BACKGROUND = 0xff8b8b8b; + private static final int CELL = 32; + + static void verify(Minecraft client) throws IOException { + ItemStack tall = new ItemStack(PrimalPotteryForge.POT); + ForgeStackProfiles.INSTANCE.write(tall, Pottery.jug().withHeight(16)); + tall.getTagCompound().setString("dye", "lime"); + ItemStack wide = new ItemStack(PrimalPotteryForge.RAW); + ForgeStackProfiles.INSTANCE.write(wide, new Pottery(Pottery.Size.LARGE, + Arrays.asList(new PotteryDisc(1, 16), new PotteryDisc(1, 16, 14)))); + ItemStack closed = VesselGameplay.water.copy(); + VesselData.data(closed).setBoolean("lid", true); + ItemStack[] pots = { tall, wide, closed, VesselGameplay.planter }; + + client.entityRenderer.setupOverlayRendering(); + RenderHelper.disableStandardItemLighting(); + Gui.drawRect(0, 0, pots.length * CELL, CELL, 0xffc6c6c6); + for (int i = 0; i < pots.length; i++) { + int x = i * CELL + 8; + Gui.drawRect(x - 1, 7, x + 17, 25, 0xffffffff); + Gui.drawRect(x - 1, 7, x + 16, 24, 0xff373737); + Gui.drawRect(x, 8, x + 16, 24, BACKGROUND); + } + BufferedImage empty = ScreenShotHelper.createScreenshot(client.displayWidth, client.displayHeight, client.getFramebuffer()); + RenderHelper.enableGUIStandardItemLighting(); + for (int i = 0; i < pots.length; i++) { + client.getRenderItem().renderItemAndEffectIntoGUI(pots[i], i * CELL + 8, 8); + } + RenderHelper.disableStandardItemLighting(); + BufferedImage image = ScreenShotHelper.createScreenshot(client.displayWidth, client.displayHeight, client.getFramebuffer()); + int scale = new ScaledResolution(client).getScaleFactor(); + ImageIO.write(image.getSubimage(0, 0, pots.length * CELL * scale, CELL * scale), "png", + new File("screenshots/inventory-icons.png")); + for (int i = 0; i < pots.length; i++) { + Rectangle bounds = new Rectangle(); + for (int y = 0; y < CELL * scale; y++) { + for (int x = 0; x < CELL * scale; x++) { + int screenX = i * CELL * scale + x; + if (image.getRGB(screenX, y) != empty.getRGB(screenX, y)) { + Rectangle pixel = new Rectangle(x, y, 1, 1); + bounds = bounds.isEmpty() ? pixel : bounds.union(pixel); + } + } + } + // The slot starts at (8,8) in each cell. Its inner 14 pixels leave a margin on every side. + Rectangle interior = new Rectangle(9 * scale, 9 * scale, 14 * scale, 14 * scale); + if (bounds.isEmpty() || !interior.contains(bounds)) { + throw new AssertionError("Pottery icon " + i + " drew " + bounds + " outside " + interior); + } + } + System.out.println("POTTERY VERIFIED inventory slot margins for dyed jug, raw platter, lidded vessel and tree planter"); + } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java new file mode 100644 index 0000000..e3f1fe2 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java @@ -0,0 +1,86 @@ +package potterycheck; + +import java.util.concurrent.Future; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.*; +import net.minecraft.util.math.*; +import net.minecraft.world.GameType; +import net.modcrafters.minecraft.primalpottery.legacy.*; +import net.modcrafters.minecraft.primalpottery.legacy.client.VesselScreen; +import net.modcrafters.minecraft.primalpottery.pottery.Pottery; + +/** Click the exposed support beside the vessel left by the selective harvest check. */ +final class PlacementClientCheck { + private enum Step { SETUP, PLACE, CHECK_OCCUPIED, OPEN_LID, DONE } + private static final BlockPos SITE = PlacementGameplay.SITE; + private Step step = Step.SETUP; + private Future task; + private GameType previousMode; + private int ticks; + + boolean tick(Minecraft client) throws Exception { + if (task != null && !task.isDone()) return false; + if (task != null) { task.get(); task = null; } + if (step == Step.DONE) return true; + if (++ticks > 200) throw new AssertionError("Shared placement timed out at " + step); + MinecraftServer server = client.getIntegratedServer(); + ItemStack held = client.player.getHeldItemMainhand(); + PaintedPotEntity pots = (PaintedPotEntity) client.world.getTileEntity(SITE); + switch (step) { + case SETUP: + task = server.addScheduledTask(() -> { + EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); + previousMode = player.interactionManager.getGameType(); + player.setGameType(GameType.SURVIVAL); + player.connection.setPlayerLocation(SITE.getX() + .5, SITE.getY(), SITE.getZ() - 1.5, 0, 30); + ItemStack pair = new ItemStack(PrimalPotteryForge.POT, 2); + ForgeStackProfiles.INSTANCE.write(pair, Pottery.jug().withHeight(14)); + player.setHeldItem(EnumHand.MAIN_HAND, pair); + player.setHeldItem(EnumHand.OFF_HAND, ItemStack.EMPTY); + player.inventoryContainer.detectAndSendChanges(); + }); + break; + case PLACE: + if (pots == null || pots.layout().count() != 1 || held.getCount() != 2 + || !PaintingRegistration.isPot(held) || client.playerController.isInCreativeMode()) return false; + if (click(client, SITE.down(), 1) != EnumActionResult.SUCCESS) throw new AssertionError("Second pot rejected on support"); + break; + case CHECK_OCCUPIED: + if (pots == null || pots.layout().at(1) == null || held.getCount() != 1) return false; + if (pots.layout().count() != 2 || pots.layout().at(0) == null) throw new AssertionError("Lost first pot"); + if (click(client, SITE, .25) != EnumActionResult.FAIL) throw new AssertionError("Replaced occupied pot"); + // Vanilla retries a failed block click as item-in-air use with the same crosshair hit. + RayTraceResult previous = client.objectMouseOver; + try { + client.objectMouseOver = new RayTraceResult(hit(SITE, .25), EnumFacing.UP, SITE); + client.playerController.processRightClick(client.player, client.world, EnumHand.MAIN_HAND); + if (client.currentScreen != null) throw new AssertionError("Blocked placement opened a screen"); + } finally { client.objectMouseOver = previous; } + task = server.addScheduledTask(() -> { + EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); + player.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); + player.inventoryContainer.detectAndSendChanges(); + }); + break; + case OPEN_LID: + if (!held.isEmpty()) return false; + click(client, SITE, .25); + if (!(client.currentScreen instanceof VesselScreen)) throw new AssertionError("Empty-hand lid did not open"); + client.displayGuiScreen(null); + task = server.addScheduledTask(() -> server.getPlayerList().getPlayers().get(0).setGameType(previousMode)); + System.out.println("POTTERY VERIFIED shared placement: two corners, survival cost, occupied slot and empty-hand lid"); + break; + default: throw new AssertionError(step); + } + step = Step.values()[step.ordinal() + 1]; + return false; + } + + private static Vec3d hit(BlockPos pos, double y) { return new Vec3d(pos).addVector(.75, y, .25); } + private static EnumActionResult click(Minecraft client, BlockPos pos, double y) { + return client.playerController.processRightClickBlock(client.player, client.world, pos, EnumFacing.UP, hit(pos, y), EnumHand.MAIN_HAND); + } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java b/.github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java index 685e704..507368b 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java +++ b/.github/forge-display-check/1.12.2/potterycheck/PlacementGameplay.java @@ -13,7 +13,7 @@ /** Exercises shared footprints through the block item and survival harvest, and tests hopper-style furnace input. */ final class PlacementGameplay { - private static final BlockPos SITE = WheelGameplay.BASE.west(2); + static final BlockPos SITE = WheelGameplay.BASE.west(2); private static final BlockPos OVEN = WheelGameplay.BASE.east(2); private static final Pottery FIRST = Pottery.jug().withHeight(10); private static final Pottery SECOND = Pottery.jug().withHeight(14); diff --git a/.github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java index 5f8ef29..29aa426 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/VesselClientCheck.java @@ -10,7 +10,6 @@ import net.minecraft.util.EnumHand; import net.minecraft.server.MinecraftServer; import net.modcrafters.minecraft.primalpottery.legacy.VesselData; -import net.modcrafters.minecraft.primalpottery.legacy.VesselInteractions; import net.modcrafters.minecraft.primalpottery.legacy.client.VesselScreen; import net.modcrafters.minecraft.primalpottery.legacy.client.VesselModels; import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; @@ -45,7 +44,9 @@ static boolean tick(Minecraft client) throws Exception { break; case OPEN: if (VesselData.amount(held) <= 0) return false; - VesselInteractions.useHeld(client.player, HAND); + client.player.rotationPitch = -90; + client.entityRenderer.getMouseOver(1); + client.playerController.processRightClick(client.player, client.world, HAND); break; case CLOSE_LID: if (!(client.currentScreen instanceof VesselScreen)) return false; diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java index a247669..7f4b5fd 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PotteryBlockItem.java @@ -2,29 +2,41 @@ import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; public final class PotteryBlockItem extends VesselItem { PotteryBlockItem(Block pottery) { super(pottery); setMaxStackSize(1); } + public static PaintedPotEntity existingAt(World level, BlockPos clicked, EnumFacing face) { + TileEntity tile = level.getTileEntity(clicked); + if (!(tile instanceof PaintedPotEntity) && face == EnumFacing.UP) tile = level.getTileEntity(clicked.up()); + return tile instanceof PaintedPotEntity ? (PaintedPotEntity) tile : null; + } + + @Override @SideOnly(Side.CLIENT) + public boolean canPlaceBlockOnSide(World level, BlockPos pos, EnumFacing face, EntityPlayer player, ItemStack held) { + // The 1.12 client checks whole-block placement before it sends the click to the server. + // An existing pottery block handles its own slot and edit checks in placeVessel. + return existingAt(level, pos, face) != null || super.canPlaceBlockOnSide(level, pos, face, player, held); + } + @Override protected EnumActionResult placeVessel(EntityPlayer player, World level, BlockPos clicked, EnumHand hand, EnumFacing face, float hitX, float hitY, float hitZ) { ItemStack held = player.getHeldItem(hand); BlockPos dest = level.getBlockState(clicked).getBlock().isReplaceable(level, clicked) ? clicked : clicked.offset(face); - TileEntity existing = level.getTileEntity(clicked); - if (!(existing instanceof PaintedPotEntity) && face == EnumFacing.UP) existing = level.getTileEntity(clicked.up()); + PaintedPotEntity pottery = existingAt(level, clicked, face); double x = hitX - face.getDirectionVec().getX() * 1e-6; double z = hitZ - face.getDirectionVec().getZ() * 1e-6; Pottery profile = PaintedPotEntity.fromStack(held); - if (existing instanceof PaintedPotEntity) { - PaintedPotEntity pottery = (PaintedPotEntity) existing; + if (pottery != null) { int slot = pottery.layout().destination(profile, x, z, player.isSneaking(), face.getDirectionVec().getX(), face.getDirectionVec().getZ()); if (slot < 0 || !player.canPlayerEdit(pottery.getPos(), face, held)) return EnumActionResult.FAIL; diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java index cc60f00..a74c4b8 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/VesselInteractions.java @@ -69,7 +69,7 @@ public static EnumActionResult useHeld(EntityPlayer player, EnumHand hand) { if (PaintedPotEntity.fromStack(pot).isPlate()) return EnumActionResult.PASS; EnumActionResult fill = fillLookedAt(player, hand); if (fill != EnumActionResult.PASS) return fill; - if (player.world.isRemote) VesselScreen.open(hand, null, -1, pot); + if (player.world.isRemote) VesselScreen.openHeld(hand, pot); return EnumActionResult.SUCCESS; } @@ -130,6 +130,7 @@ public static boolean usePlaced(PaintedPotEntity pottery, int slot, EntityPlayer ItemStack held = player.getHeldItem(hand); if (held.isEmpty() && hand == EnumHand.MAIN_HAND && !player.isSneaking()) { ItemStack offhand = player.getHeldItem(EnumHand.OFF_HAND); + if (offhand.getItem() instanceof PotteryBlockItem) return false; if (offhand.getItem() instanceof ItemBlock) { Block offer = ((ItemBlock) offhand.getItem()).getBlock(); if (PlanterPlants.soil(offer) || PlanterPlants.accepts(pottery.layout().at(slot).size(), offer, offhand.getMetadata())) held = offhand; diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/InventoryPotteryTransform.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/InventoryPotteryTransform.java new file mode 100644 index 0000000..b35e9bf --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/InventoryPotteryTransform.java @@ -0,0 +1,55 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import com.google.common.collect.MapMaker; +import java.util.List; +import java.util.Map; +import javax.vecmath.Matrix4f; +import javax.vecmath.Point3f; +import net.minecraft.client.renderer.block.model.BakedQuad; + +/** Centers the visible mesh inside a 16-pixel slot with a one-pixel margin. */ +final class InventoryPotteryTransform { + private static final float USABLE_WIDTH = 14f / 16f; + private final Matrix4f camera = new Matrix4f(); + // Weak keys compare baked lists by identity and let evicted pottery meshes be collected. + private final Map, Matrix4f> fitted = new MapMaker().weakKeys().makeMap(); + + InventoryPotteryTransform(Matrix4f camera) { + this.camera.setIdentity(); + if (camera != null) this.camera.set(camera); + } + + Matrix4f forMesh(List mesh) { + return fitted.computeIfAbsent(mesh, this::fit); + } + + private Matrix4f fit(List mesh) { + if (mesh.isEmpty()) return camera; + float minX = Float.POSITIVE_INFINITY, minY = Float.POSITIVE_INFINITY; + float maxX = Float.NEGATIVE_INFINITY, maxY = Float.NEGATIVE_INFINITY; + Point3f point = new Point3f(); + for (BakedQuad quad : mesh) { + int[] vertices = quad.getVertexData(); + int stride = quad.getFormat().getIntegerSize(); + for (int i = 0; i < vertices.length; i += stride) { + // RenderItem subtracts the block center before applying the GUI camera. + point.set(Float.intBitsToFloat(vertices[i]) - .5f, + Float.intBitsToFloat(vertices[i + 1]) - .5f, + Float.intBitsToFloat(vertices[i + 2]) - .5f); + camera.transform(point); + minX = Math.min(minX, point.x); + maxX = Math.max(maxX, point.x); + minY = Math.min(minY, point.y); + maxY = Math.max(maxY, point.y); + } + } + float extent = Math.max(maxX - minX, maxY - minY); + float scale = extent > USABLE_WIDTH ? USABLE_WIDTH / extent : 1f; + Matrix4f fit = new Matrix4f(); + fit.set(scale); + fit.m03 = -scale * (minX + maxX) / 2; + fit.m13 = -scale * (minY + maxY) / 2; + fit.mul(camera); + return fit; + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java index ae1e0df..07d314f 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlacementOutline.java @@ -3,13 +3,13 @@ import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; import net.modcrafters.minecraft.primalpottery.legacy.PaintingRegistration; import net.modcrafters.minecraft.primalpottery.legacy.PotBounds; +import net.modcrafters.minecraft.primalpottery.legacy.PotteryBlockItem; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; import net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.*; import net.minecraftforge.client.event.DrawBlockHighlightEvent; @@ -26,17 +26,14 @@ public final class PlacementOutline { if (!PaintingRegistration.isPot(held) || hit.typeOfHit != RayTraceResult.Type.BLOCK) return; BlockPos pos = hit.getBlockPos(); EnumFacing face = hit.sideHit; - TileEntity entity = player.world.getTileEntity(pos); - if (!(entity instanceof PaintedPotEntity)) { - if (face != EnumFacing.UP) return; - pos = pos.up(); - entity = player.world.getTileEntity(pos); - } + PaintedPotEntity pottery = PotteryBlockItem.existingAt(player.world, pos, face); + if (pottery == null && face != EnumFacing.UP) return; + pos = pottery == null ? pos.up() : pottery.getPos(); double x = hit.hitVec.x - pos.getX() - face.getDirectionVec().getX() * 1e-6; double z = hit.hitVec.z - pos.getZ() - face.getDirectionVec().getZ() * 1e-6; Pottery shape = PaintedPotEntity.fromStack(held); - int slot = entity instanceof PaintedPotEntity - ? ((PaintedPotEntity) entity).layout().destination(shape, x, z, player.isSneaking(), face.getDirectionVec().getX(), face.getDirectionVec().getZ()) + int slot = pottery != null + ? pottery.layout().destination(shape, x, z, player.isSneaking(), face.getDirectionVec().getX(), face.getDirectionVec().getZ()) : PotteryLayout.preferred(shape, x, z); if (slot < 0) return; float partial = event.getPartialTicks(); diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java index 11a3978..97943c4 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java @@ -42,16 +42,20 @@ public final class PotteryModel extends BakedModelWrapper { private static final ResourceLocation PAINT_SHEET = new ResourceLocation("primalpottery", "block/paint_sheet"); private final PotteryQuads bakery; private final List item; + private final InventoryPotteryTransform inventory; private final ItemOverrideList overrides = new ItemOverrideList(Collections.emptyList()) { @Override public IBakedModel handleItemState(IBakedModel model, ItemStack stack, World world, EntityLivingBase entity) { - return new PotteryModel(originalModel, bakery, VesselModels.append(bakery.model(PaintedPotEntity.fromStack(stack), PaintingRegistration.tint(stack)), stack, PotteryLayout.CENTER)); + List body = bakery.model(PaintedPotEntity.fromStack(stack), PaintingRegistration.tint(stack)); + return new PotteryModel(originalModel, bakery, VesselModels.append(body, stack, PotteryLayout.CENTER), + VesselScreen.isPreviewStack(stack) ? null : inventory); } }; - private PotteryModel(IBakedModel base, PotteryQuads bakery, List item) { + private PotteryModel(IBakedModel base, PotteryQuads bakery, List item, InventoryPotteryTransform inventory) { super(base); this.bakery = bakery; this.item = item; + this.inventory = inventory; } @SubscribeEvent public static void register(ModelRegistryEvent event) { @@ -85,7 +89,8 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item new ModelResourceLocation(PrimalPotteryForge.RAW.getRegistryName(), "inventory")}) { IBakedModel base = event.getModelRegistry().getObject(key); PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks, sheet, Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("primalpottery:block/dyed_clay")); - event.getModelRegistry().putObject(key, new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE))); + InventoryPotteryTransform inventory = new InventoryPotteryTransform(base.handlePerspective(ItemCameraTransforms.TransformType.GUI).getRight()); + event.getModelRegistry().putObject(key, new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE), inventory)); } } @@ -107,6 +112,7 @@ private List placedSlot(PotteryLayout layout, ItemStack[] stacks, int @Override public ItemOverrideList getOverrides() { return overrides; } @Override public Pair handlePerspective(ItemCameraTransforms.TransformType type) { + if (type == ItemCameraTransforms.TransformType.GUI && inventory != null) return Pair.of(this, inventory.forMesh(item)); return Pair.of(this, originalModel.handlePerspective(type).getRight()); } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java index b23b198..a5bdf69 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselScreen.java @@ -1,6 +1,7 @@ package net.modcrafters.minecraft.primalpottery.legacy.client; import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; +import net.modcrafters.minecraft.primalpottery.legacy.PotteryBlockItem; import net.modcrafters.minecraft.primalpottery.legacy.VesselChannel; import net.modcrafters.minecraft.primalpottery.legacy.VesselInteractions; import net.modcrafters.minecraft.primalpottery.legacy.VesselData; @@ -14,6 +15,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; public final class VesselScreen extends GuiScreen { private final EnumHand hand; @@ -35,6 +37,21 @@ private VesselScreen(EnumHand hand, BlockPos pos, int slot, ItemStack stack) { public static void open(EnumHand hand, BlockPos pos, int slot, ItemStack stack) { Minecraft.getMinecraft().displayGuiScreen(new VesselScreen(hand, pos, slot, stack)); } + public static void openHeld(EnumHand hand, ItemStack stack) { + Minecraft client = Minecraft.getMinecraft(); + RayTraceResult hit = client.objectMouseOver; + // Minecraft also calls item-in-air use after an occupied slot rejects placement. + if (hit != null && hit.typeOfHit == RayTraceResult.Type.BLOCK + && PotteryBlockItem.existingAt(client.world, hit.getBlockPos(), hit.sideHit) != null) return; + open(hand, null, -1, stack); + } + /** These two screen-owned copies share one camera so their sizes and positions match. */ + static boolean isPreviewStack(ItemStack stack) { + GuiScreen screen = Minecraft.getMinecraft().currentScreen; + if (!(screen instanceof VesselScreen)) return false; + VesselScreen vessel = (VesselScreen) screen; + return stack == vessel.preview || stack == vessel.detachedLid; + } private String label() { return I18n.format(VesselData.lid(preview) ? "gui.primalpottery.lid.remove" : "gui.primalpottery.lid.put_on"); } From 17b5aa899070f7bc2a593efc53838a9db65f30ae Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 06:48:41 +0200 Subject: [PATCH 20/22] Fit Forge 1.20.1 pottery icons and correct planter light and clay shading Co-authored-by: Face of Cat --- .../1.20.1/potterycheck/DisplayCheck.java | 42 +++++++++--- .../potterycheck/PotteryRenderCheck.java | 66 +++++++++++++++++++ .../primalpottery/pottery/PaintedVessel.java | 14 ++-- .../pottery/PaintedVesselTest.java | 11 ++++ .../primalpottery/forge/PaintedPotBlock.java | 4 ++ .../client/InventoryPotteryTransform.java | 52 +++++++++++++++ .../primalpottery/forge/client/PlantQuad.java | 31 +++++++++ .../forge/client/PotteryModel.java | 35 ++++++++-- .../forge/client/PotteryQuads.java | 30 ++++++++- .../forge/client/VesselModels.java | 6 +- .../forge/client/VesselScreen.java | 4 ++ 11 files changed, 274 insertions(+), 21 deletions(-) create mode 100644 .github/forge-display-check/1.20.1/potterycheck/PotteryRenderCheck.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/InventoryPotteryTransform.java create mode 100644 forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlantQuad.java diff --git a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java index 740401e..47759ea 100644 --- a/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.20.1/potterycheck/DisplayCheck.java @@ -11,6 +11,9 @@ import net.minecraft.client.Minecraft; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.forge.ForgeStackProfiles; +import net.modcrafters.minecraft.primalpottery.forge.PrimalPotteryForge; import net.modcrafters.minecraft.primalpottery.forge.ForgePotteryTags; import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; import net.minecraft.client.Screenshot; @@ -104,6 +107,7 @@ private static void install(ServerLevel level) { if (referenceStarted == 0) referenceStarted = System.nanoTime(); if (System.nanoTime() - referenceStarted > 4_000_000_000L) { screenshot(mc, "reference.png"); + PotteryRenderCheck.verify(mc); mc.stop(); } return; @@ -178,19 +182,39 @@ private static void showReference(Minecraft mc) { server.execute(() -> { ServerLevel level = server.overworld(); var block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation("primalpottery", "pottery")); - level.setBlockAndUpdate(new BlockPos(40, 79, -2), Blocks.STONE.defaultBlockState()); - level.setBlockAndUpdate(new BlockPos(40, 80, 0), Blocks.STONE.defaultBlockState()); - level.setBlockAndUpdate(new BlockPos(40, 81, 0), block.defaultBlockState()); - BlockPos neighbor = new BlockPos(39, 81, 0); - level.setBlockAndUpdate(neighbor.below(), Blocks.STONE.defaultBlockState()); - level.setBlockAndUpdate(neighbor, block.defaultBlockState()); + level.setBlockAndUpdate(new BlockPos(40, 79, -3), Blocks.STONE.defaultBlockState()); + for (int x = 38; x <= 42; x++) { + for (int y = 80; y <= 84; y++) level.setBlockAndUpdate(new BlockPos(x, y, 1), Blocks.OAK_PLANKS.defaultBlockState()); + } + ItemStack planter = VesselGameplay.planter.copy(); + Pottery vase = new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(5, 8, 6), new PotteryDisc(6, 13, 11), + new PotteryDisc(7, 15, 13), new PotteryDisc(7, 10, 8), new PotteryDisc(2, 10))); + ForgeStackProfiles.INSTANCE.write(planter, vase); + ItemStack dyed = new ItemStack(block); + ForgeStackProfiles.INSTANCE.write(dyed, vase); + dyed.getOrCreateTag().putString("dye", "magenta"); ItemStack checker = new ItemStack(block); checker.addTagElement("pottery", ForgePotteryTags.save(CHECKER)); - block.setPlacedBy(level, neighbor, block.defaultBlockState(), null, checker); + var display = List.of(checker, planter, dyed); + for (int i = 0; i < display.size(); i++) { + BlockPos pos = new BlockPos(39 + i, 81, 0); + level.setBlockAndUpdate(pos.below(), Blocks.STONE.defaultBlockState()); + level.setBlockAndUpdate(pos, block.defaultBlockState()); + block.setPlacedBy(level, pos, block.defaultBlockState(), null, display.get(i)); + } var player = server.getPlayerList().getPlayers().get(0); - player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, new ItemStack(block)); + ItemStack raw = new ItemStack(PrimalPotteryForge.RAW.get()); + ForgeStackProfiles.INSTANCE.write(raw, new Pottery(Pottery.Size.LARGE, List.of(new PotteryDisc(2, 16)))); + ItemStack closed = VesselGameplay.water.copy(); + closed.getOrCreateTag().putBoolean("lid", true); + player.getInventory().clearContent(); + player.getInventory().setItem(2, raw); + player.getInventory().setItem(3, dyed); + player.getInventory().setItem(4, planter); + player.getInventory().setItem(5, checker); + player.getInventory().setItem(6, closed); player.inventoryMenu.broadcastChanges(); - player.connection.teleport(40.5, 80, -1.5, 0, 15); + player.connection.teleport(40.5, 80, -2.5, 0, -6); }); } diff --git a/.github/forge-display-check/1.20.1/potterycheck/PotteryRenderCheck.java b/.github/forge-display-check/1.20.1/potterycheck/PotteryRenderCheck.java new file mode 100644 index 0000000..9c76ec3 --- /dev/null +++ b/.github/forge-display-check/1.20.1/potterycheck/PotteryRenderCheck.java @@ -0,0 +1,66 @@ +package potterycheck; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraftforge.client.model.IQuadTransformer; +import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; +import org.joml.Vector3f; + +final class PotteryRenderCheck { + static void verify(Minecraft client) { + for (int slot = 2; slot <= 6; slot++) checkIcon(client, client.player.getInventory().getItem(slot)); + + BlockPos pos = new BlockPos(40, 81, 0); + var planter = (PaintedPotEntity) client.level.getBlockEntity(pos); + var state = client.level.getBlockState(pos); + if (state.getShadeBrightness(client.level, pos) < 1) throw new AssertionError("Large planter casts a full-cube shadow"); + var model = client.getBlockRenderer().getBlockModel(state); + var data = model.getModelData(client.level, pos, state, planter.getModelData()); + boolean underside = false, wall = false; + for (var quad : model.getQuads(state, null, RandomSource.create(42), data, null)) { + String texture = quad.getSprite().contents().name().getPath(); + if (texture.endsWith("_leaves") && quad.getDirection() == Direction.DOWN) { + underside = true; + if (quad.hasAmbientOcclusion() || LightTexture.sky(quad.getVertices()[IQuadTransformer.UV2]) == 0) { + throw new AssertionError("Sunlit miniature leaves sampled the dark support"); + } + } + int normalX = (byte) quad.getVertices()[IQuadTransformer.NORMAL]; + if (texture.equals("block/fired_clay") && quad.getDirection() == Direction.NORTH && normalX == 0) { + wall = true; + int brightness = quad.getVertices()[IQuadTransformer.COLOR] & 255; + if (quad.isShade() || quad.hasAmbientOcclusion() || brightness < 190 || brightness > 215) { + throw new AssertionError("Inconsistent directional shade on north wall: " + brightness); + } + } + } + if (!underside || !wall) throw new AssertionError("Missing tree or clay in reference scene"); + System.out.println("POTTERY VERIFIED icon bounds, canopy light and curved clay shading after reload"); + } + + private static void checkIcon(Minecraft client, ItemStack stack) { + var model = client.getItemRenderer().getModel(stack, client.level, client.player, 0); + PoseStack pose = new PoseStack(); + model = model.applyTransform(ItemDisplayContext.GUI, pose, false); + pose.translate(-.5f, -.5f, -.5f); + var quads = model.getQuads(null, null, RandomSource.create(42)); + if (stack.isEmpty() || quads.isEmpty()) throw new AssertionError("Missing inventory model for " + stack); + Vector3f point = new Vector3f(); + for (var quad : quads) { + int[] vertices = quad.getVertices(); + for (int i = 0; i < vertices.length; i += IQuadTransformer.STRIDE) { + point.set(Float.intBitsToFloat(vertices[i]), Float.intBitsToFloat(vertices[i + 1]), Float.intBitsToFloat(vertices[i + 2])); + pose.last().pose().transformPosition(point); + if (Math.max(Math.abs(point.x), Math.abs(point.y)) * 16 > 7.001f) { + throw new AssertionError("Inventory icon crossed its one-pixel margin: " + stack); + } + } + } + } +} diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java index d0de26a..2c769d0 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVessel.java @@ -9,6 +9,7 @@ public final class PaintedVessel { static final int PAINT_TEXTURE = -2; private static final int SIDES = 8; private static final double UNITS = 32; + private static final double HALF_FACET_U = Math.sin(Math.PI / SIDES) * 16 / UNITS; private static final double[] X = new double[SIDES + 1]; private static final double[] Z = new double[SIDES + 1]; static { @@ -113,10 +114,15 @@ private void surface(List outline, boolean outside) { } private void clayWall(PotteryProfile.Station low, PotteryProfile.Station high, int side, boolean outside) { - Vertex a = vertex(side, low.radius(), low.y(), 0, 16); - Vertex b = vertex(side + 1, low.radius(), low.y(), 16, 16); - Vertex c = vertex(side + 1, high.radius(), high.y(), 16, 0); - Vertex d = vertex(side, high.radius(), high.y(), 0, 0); + // Carry the clay grain across profile joints. Repeating a whole sprite on each + // thin ring creates horizontal bands even under uniform lighting. + double center = 8 + 4 * Math.cos((side + 1) * 2 * Math.PI / SIDES); + double bottomV = (pot.height() - low.y()) * 16 / UNITS; + double topV = (pot.height() - high.y()) * 16 / UNITS; + Vertex a = vertex(side, low.radius(), low.y(), center - low.radius() * HALF_FACET_U, bottomV); + Vertex b = vertex(side + 1, low.radius(), low.y(), center + low.radius() * HALF_FACET_U, bottomV); + Vertex c = vertex(side + 1, high.radius(), high.y(), center + high.radius() * HALF_FACET_U, topV); + Vertex d = vertex(side, high.radius(), high.y(), center - high.radius() * HALF_FACET_U, topV); if (outside) faces.quad(b, a, d, c, CLAY); else faces.quad(a, b, c, d, CLAY); } diff --git a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java index 9f9ef30..2b85926 100644 --- a/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java +++ b/core/src/test/java/net/modcrafters/minecraft/primalpottery/pottery/PaintedVesselTest.java @@ -6,6 +6,17 @@ import static org.junit.Assert.*; public class PaintedVesselTest { + @Test public void curvedWallsKeepOneTextureScaleAcrossRings() { + Pottery jug = Pottery.jug(); + new PaintedVessel(jug, (a, b, c, d, ink) -> { + if (a.y == c.y || ink != PaintedVessel.CLAY) return; + for (PaintedVessel.Vertex point : Arrays.asList(a, b, c, d)) { + assertEquals(jug.height() / 2 - point.y * 16, point.v, .0001); + assertTrue(point.u >= 0 && point.u <= 16); + } + }); + } + private static final class FaceCounter extends BakedVessels { int builds; @Override protected Integer bake(PaintedVessel.Vertex a, PaintedVessel.Vertex b, diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java index 06d13cb..697ea5c 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/PaintedPotBlock.java @@ -28,6 +28,10 @@ public final class PaintedPotBlock extends BaseEntityBlock { @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new PaintedPotEntity(pos, state); } @Override public RenderShape getRenderShape(BlockState state) { return RenderShape.MODEL; } + @Override public float getShadeBrightness(BlockState state, BlockGetter level, BlockPos pos) { + // A large pot has a full selection box, but its curved sides leave the corners open. + return 1f; + } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { if (!(level.getBlockEntity(pos) instanceof PaintedPotEntity pots)) return SHAPE; VoxelShape outline = Shapes.empty(); diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/InventoryPotteryTransform.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/InventoryPotteryTransform.java new file mode 100644 index 0000000..16df724 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/InventoryPotteryTransform.java @@ -0,0 +1,52 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import com.google.common.collect.MapMaker; +import com.mojang.blaze3d.vertex.PoseStack; +import java.util.List; +import java.util.Map; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemTransform; +import org.joml.Matrix4f; +import org.joml.Vector3f; + +/** Measure the projected silhouette once per baked mesh, including lids and plants. */ +final class InventoryPotteryTransform { + private static final float USABLE_SIZE = 14f / 16f; + private record Fit(float x, float y, float scale) {} + + private final Matrix4f camera; + // Weak keys compare by identity and release entries when the bakery evicts a mesh. + private final Map, Fit> fits = new MapMaker().weakKeys().makeMap(); + + InventoryPotteryTransform(ItemTransform transform) { + PoseStack pose = new PoseStack(); + transform.apply(false, pose); + pose.translate(-.5f, -.5f, -.5f); + camera = pose.last().pose(); + } + + void apply(PoseStack pose, List mesh) { + if (mesh.isEmpty()) return; + Fit fit = fits.computeIfAbsent(mesh, this::measure); + pose.translate(fit.x(), fit.y(), 0); + pose.scale(fit.scale(), fit.scale(), fit.scale()); + } + + private Fit measure(List mesh) { + Vector3f min = new Vector3f(Float.POSITIVE_INFINITY); + Vector3f max = new Vector3f(Float.NEGATIVE_INFINITY); + Vector3f vertex = new Vector3f(); + for (BakedQuad quad : mesh) { + int[] data = quad.getVertices(); + for (int i = 0; i < data.length; i += data.length / 4) { + vertex.set(Float.intBitsToFloat(data[i]), Float.intBitsToFloat(data[i + 1]), Float.intBitsToFloat(data[i + 2])); + camera.transformPosition(vertex); + min.min(vertex); + max.max(vertex); + } + } + float extent = Math.max(max.x - min.x, max.y - min.y); + float scale = extent > USABLE_SIZE ? USABLE_SIZE / extent : 1; + return new Fit(-(min.x + max.x) * scale / 2, -(min.y + max.y) * scale / 2, scale); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlantQuad.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlantQuad.java new file mode 100644 index 0000000..27aa049 --- /dev/null +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PlantQuad.java @@ -0,0 +1,31 @@ +package net.modcrafters.minecraft.primalpottery.forge.client; + +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.LightLayer; +import net.minecraftforge.client.model.IQuadTransformer; + +/** A miniature block samples light where it grows, even above the planter's block. */ +final class PlantQuad extends BakedQuad { + private final BlockPos cell; + + PlantQuad(int[] vertices, BakedQuad source, BlockPos cell) { + super(vertices, -1, source.getDirection(), source.getSprite(), source.isShade(), false); + this.cell = cell; + } + + BakedQuad lit(BlockAndTintGetter level, BlockPos origin) { + BlockPos pos = origin.offset(cell); + int block = level.getBrightness(LightLayer.BLOCK, pos); + int sky = level.getBrightness(LightLayer.SKY, pos); + // Keep the cached mesh independent of the world. Forge combines UV2 with its + // ordinary face light, which can come from the opaque support below a large pot. + int[] data = getVertices().clone(); + for (int i = IQuadTransformer.UV2; i < data.length; i += IQuadTransformer.STRIDE) { + data[i] = LightTexture.pack(Math.max(block, LightTexture.block(data[i])), Math.max(sky, LightTexture.sky(data[i]))); + } + return new BakedQuad(data, -1, getDirection(), getSprite(), isShade(), false); + } +} diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java index c2563e5..4b6b478 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryModel.java @@ -7,18 +7,22 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemOverrides; import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.client.event.RegisterTextureAtlasSpriteLoadersEvent; import net.minecraftforge.client.model.BakedModelWrapper; import net.minecraftforge.client.model.data.ModelData; +import net.minecraftforge.client.model.data.ModelProperty; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.modcrafters.minecraft.primalpottery.forge.PaintedPotEntity; @@ -29,20 +33,25 @@ @Mod.EventBusSubscriber(modid = "primalpottery", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public final class PotteryModel extends BakedModelWrapper { + private static final ModelProperty> LIT_PLANTER = new ModelProperty<>(); private static final ResourceLocation INKS = new ResourceLocation("primalpottery", "block/pottery_inks"); private static final ResourceLocation PAINT_SHEET = new ResourceLocation("primalpottery", "block/paint_sheet"); private final PotteryQuads bakery; private final List item; + private final InventoryPotteryTransform inventory; private final ItemOverrides overrides = new ItemOverrides() { @Override public BakedModel resolve(BakedModel model, ItemStack stack, ClientLevel world, LivingEntity entity, int seed) { - return new PotteryModel(originalModel, bakery, VesselModels.append(bakery.model(PaintedPotEntity.fromStack(stack), PaintingRegistration.tint(stack)), stack, PotteryLayout.CENTER)); + var body = bakery.model(PaintedPotEntity.fromStack(stack), PaintingRegistration.tint(stack)); + return new PotteryModel(originalModel, bakery, VesselModels.append(body, stack, PotteryLayout.CENTER), + VesselScreen.isPreviewStack(stack) ? null : inventory); } }; - private PotteryModel(BakedModel base, PotteryQuads bakery, List item) { + private PotteryModel(BakedModel base, PotteryQuads bakery, List item, InventoryPotteryTransform inventory) { super(base); this.bakery = bakery; this.item = item; + this.inventory = inventory; } @SubscribeEvent public static void register(ModelEvent.RegisterAdditional event) { @@ -60,9 +69,11 @@ private PotteryModel(BakedModel base, PotteryQuads bakery, List item) var sheet = event.getModels().get(PAINT_SHEET).getParticleIcon(); event.getModels().replaceAll((key, base) -> { if (!key.getNamespace().equals("primalpottery") || !(key.getPath().equals("pottery") || key.getPath().equals("raw_pottery"))) return base; + boolean inventoryModel = key instanceof ModelResourceLocation model && model.getVariant().equals("inventory"); var bakery = new PotteryQuads(base.getParticleIcon(), inks, sheet, - event.getModels().get(new ResourceLocation("primalpottery", "block/dyed_clay")).getParticleIcon()); - return new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE)); + event.getModels().get(new ResourceLocation("primalpottery", "block/dyed_clay")).getParticleIcon(), inventoryModel); + var inventory = new InventoryPotteryTransform(base.getTransforms().getTransform(ItemDisplayContext.GUI)); + return new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE), inventory); }); } @@ -83,12 +94,27 @@ private List placedSlot(PotteryLayout layout, ItemStack[] stacks, int @Override public ItemOverrides getOverrides() { return overrides; } + @Override public ModelData getModelData(BlockAndTintGetter level, BlockPos pos, BlockState state, ModelData data) { + var layout = data.get(PaintedPotEntity.LAYOUT); + var stacks = data.get(PaintedPotEntity.STACKS); + if (layout == null || stacks == null) return data; + for (ItemStack stack : stacks) { + if (!stack.hasTag() || !stack.getTag().contains("plant")) continue; + var lit = placed(layout, stacks).stream() + .map(quad -> quad instanceof PlantQuad plant ? plant.lit(level, pos) : quad).toList(); + return data.derive().with(LIT_PLANTER, lit).build(); + } + return data; + } + @Override public List getQuads(BlockState state, Direction side, RandomSource random) { return side == null ? item : List.of(); } @Override public List getQuads(BlockState state, Direction side, RandomSource random, ModelData data, RenderType type) { if (side != null) return List.of(); + var planter = data.get(LIT_PLANTER); + if (planter != null) return planter; var layout = data.get(PaintedPotEntity.LAYOUT); if (layout != null) return placed(layout, data.get(PaintedPotEntity.STACKS)); Pottery profile = data.get(PaintedPotEntity.PROFILE); @@ -98,6 +124,7 @@ private List placedSlot(PotteryLayout layout, ItemStack[] stacks, int @Override public List getRenderPasses(ItemStack stack, boolean fabulous) { return List.of(this); } @Override public BakedModel applyTransform(ItemDisplayContext context, PoseStack pose, boolean leftHand) { + if (context == ItemDisplayContext.GUI && inventory != null) inventory.apply(pose, item); getTransforms().getTransform(context).apply(leftHand, pose); return this; } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java index af403c4..63d2720 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java @@ -3,6 +3,7 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import net.minecraftforge.client.model.lighting.QuadLighter; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; import net.modcrafters.minecraft.primalpottery.pottery.PaintSheetTiles; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; @@ -11,9 +12,12 @@ final class PotteryQuads extends VesselQuadPacker { private final PaintSheet sheet; private final int[] palette; + private final boolean inventoryModel; - PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite sheet, TextureAtlasSprite dyed) { + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite sheet, TextureAtlasSprite dyed, + boolean inventoryModel) { super(clay, inks, dyed, 8); + this.inventoryModel = inventoryModel; // A resource pack can animate the ink palette. Its original sprite keeps that animation live. boolean staticPalette = inks.contents().getUniqueFrames().limit(2).count() == 1; this.sheet = staticPalette && sheet instanceof PaintSheet custom && custom.supportsTiles() ? custom : null; @@ -31,6 +35,28 @@ final class PotteryQuads extends VesselQuadPacker @Override protected float v(TextureAtlasSprite sprite, float pixels) { return sprite.getV(pixels); } @Override protected BakedQuad quad(int[] vertices, TextureAtlasSprite sprite, float nx, float ny, float nz) { - return new BakedQuad(vertices, -1, Direction.getNearest(nx, ny, nz), sprite, true); + Direction face = Direction.getNearest(nx, ny, nz); + if (inventoryModel) return new BakedQuad(vertices, -1, face, sprite, true); + + // Axis-based block lighting flips abruptly between neighboring rings of a curved wall. + // Bake the directional component only. Minecraft still supplies the local sky and block light. + float shade = wallShade(nx, ny, nz); + for (int i = 3; i < vertices.length; i += 8) { + int color = vertices[i]; + int r = Math.round((color & 255) * shade); + int g = Math.round((color >>> 8 & 255) * shade); + int b = Math.round((color >>> 16 & 255) * shade); + vertices[i] = (color & 0xff000000) | b << 16 | g << 8 | r; + } + return new BakedQuad(vertices, -1, face, sprite, false, false); + } + + private static float wallShade(float nx, float ny, float nz) { + float radial = (float) Math.hypot(nx, nz); + if (radial == 0) return ny < 0 ? .5f : 1f; + // Match the restrained fired-clay tilt in the modern pottery renderer. + float slope = Math.max(-.99f, Math.min(.99f, ny / radial)) * .30f; + float length = (float) Math.sqrt(1 + slope * slope); + return QuadLighter.calculateShade(nx / radial / length, slope / length, nz / radial / length, false); } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java index 265de33..093373d 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselModels.java @@ -154,16 +154,18 @@ private void model(BlockState state, double bx, double by, double bz, double siz if (visible) appendModel(model.getQuads(state, null, RandomSource.create(42)), state, bx, by, bz, size); } private void appendModel(List source, BlockState state, double bx, double by, double bz, double size) { + if (source.isEmpty()) return; + BlockPos cell = BlockPos.containing(bx + size / 2, by + size / 2, bz + size / 2); for (BakedQuad quad : source) { int tint = quad.isTinted() ? Minecraft.getInstance().getBlockColors().getColor(state, null, null, quad.getTintIndex()) : -1; int[] data = transform(quad.getVertices(), bx, by, bz, size, tint); - faces.add(new BakedQuad(data, -1, quad.getDirection(), quad.getSprite(), quad.isShade())); + faces.add(new PlantQuad(data, quad, cell)); } } @Override protected float u(TextureAtlasSprite sprite, double pixel) { return sprite.getU(pixel); } @Override protected float v(TextureAtlasSprite sprite, double pixel) { return sprite.getV(pixel); } @Override protected BakedQuad makeQuad(int[] vertices, TextureAtlasSprite sprite, double nx, double ny, double nz) { return new BakedQuad(vertices, -1, Direction.getNearest((float) nx, (float) ny, (float) nz), - sprite, true); + sprite, true, false); } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java index bd86aa7..eb96f8b 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/VesselScreen.java @@ -35,6 +35,10 @@ private VesselScreen(InteractionHand hand, BlockPos pos, int slot, ItemStack sta public static void open(InteractionHand hand, BlockPos pos, int slot, ItemStack stack) { Minecraft.getInstance().setScreen(new VesselScreen(hand, pos, slot, stack)); } + static boolean isPreviewStack(ItemStack stack) { + return Minecraft.getInstance().screen instanceof VesselScreen screen + && (stack == screen.preview || stack == screen.detachedLid); + } private Component label() { return Component.translatable(VesselData.lid(preview) ? "gui.primalpottery.lid.remove" : "gui.primalpottery.lid.put_on"); } From 8c0e9e338d8156c30caa13ba997ace1c301c20d6 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 10:39:15 +0200 Subject: [PATCH 21/22] Light miniature trees at canopy height and soften curved pottery shading on Forge 1.12.2 Co-authored-by: Face of Cat --- .../1.12.2/potterycheck/DisplayCheck.java | 38 +++++++++--- .../1.12.2/potterycheck/LightingCheck.java | 62 +++++++++++++++++++ .../potterycheck/PlacementClientCheck.java | 7 ++- .../pottery/VesselQuadPacker.java | 27 ++++++++ .../forge/client/PotteryQuads.java | 20 +----- .../primalpottery/legacy/PaintedPotBlock.java | 24 ++++++- .../legacy/client/PlantQuad.java | 40 ++++++++++++ .../legacy/client/PotteryModel.java | 15 ++++- .../legacy/client/PotteryQuads.java | 9 ++- .../legacy/client/VesselModels.java | 2 +- 10 files changed, 208 insertions(+), 36 deletions(-) create mode 100644 .github/forge-display-check/1.12.2/potterycheck/LightingCheck.java create mode 100644 legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlantQuad.java diff --git a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java index 78afdbc..c695c82 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/DisplayCheck.java @@ -11,6 +11,8 @@ import net.minecraft.client.Minecraft; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; import net.modcrafters.minecraft.primalpottery.pottery.Pottery; +import net.modcrafters.minecraft.primalpottery.pottery.PotteryDisc; +import net.modcrafters.minecraft.primalpottery.legacy.ForgeStackProfiles; import net.modcrafters.minecraft.primalpottery.legacy.ForgePotteryTags; import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotEntity; import net.minecraft.client.gui.GuiMainMenu; @@ -100,6 +102,7 @@ private static void install(WorldServer level) { if (referenceStarted != 0) { if (mc.player.posX > 39 && System.nanoTime() - referenceStarted > 4_000_000_000L) { screenshot(mc, "reference.png"); + LightingCheck.verify(mc); InventoryIconCheck.verify(mc); mc.shutdown(); } @@ -151,19 +154,36 @@ private static void showReference(Minecraft mc) { net.minecraft.server.MinecraftServer server = mc.getIntegratedServer(); server.addScheduledTask(() -> { WorldServer level = server.getWorld(0); - level.setBlockState(new BlockPos(40, 79, -2), Blocks.STONE.getDefaultState()); - level.setBlockState(new BlockPos(40, 80, 0), Blocks.STONE.getDefaultState()); - level.setBlockState(new BlockPos(40, 81, 0), PrimalPotteryForge.POT.getDefaultState()); - BlockPos neighbor = new BlockPos(39, 81, 0); - level.setBlockState(neighbor.down(), Blocks.STONE.getDefaultState()); - level.setBlockState(neighbor, PrimalPotteryForge.POT.getDefaultState()); + level.setBlockState(new BlockPos(40, 79, -3), Blocks.STONE.getDefaultState()); + for (int x = 38; x <= 42; x++) { + for (int y = 80; y <= 84; y++) level.setBlockState(new BlockPos(x, y, 1), Blocks.PLANKS.getDefaultState()); + for (int z = -2; z <= 0; z++) level.setBlockState(new BlockPos(x, 84, z), Blocks.PLANKS.getDefaultState()); + } + level.setBlockState(new BlockPos(39, 83, 0), Blocks.GLOWSTONE.getDefaultState()); + Pottery vase = new Pottery(Pottery.Size.LARGE, Arrays.asList(new PotteryDisc(5, 8, 6), new PotteryDisc(6, 13, 11), + new PotteryDisc(7, 15, 13), new PotteryDisc(7, 10, 8), new PotteryDisc(2, 10))); + ItemStack planter = VesselGameplay.planter.copy(); + LightingCheck.tallTree(planter); + ForgeStackProfiles.INSTANCE.write(planter, vase); + ItemStack dyed = new ItemStack(PrimalPotteryForge.POT); + ForgeStackProfiles.INSTANCE.write(dyed, vase); + dyed.getTagCompound().setString("dye", "magenta"); ItemStack checker = new ItemStack(PrimalPotteryForge.POT); checker.setTagInfo("pottery", ForgePotteryTags.save(CHECKER)); - PrimalPotteryForge.POT.onBlockPlacedBy(level, neighbor, level.getBlockState(neighbor), null, checker); + ItemStack[] display = {checker, planter, dyed}; + for (int i = 0; i < display.length; i++) { + BlockPos pos = new BlockPos(39 + i, 81, 0); + level.setBlockState(pos.down(), Blocks.STONE.getDefaultState()); + level.setBlockState(pos, PrimalPotteryForge.POT.getDefaultState()); + PrimalPotteryForge.POT.onBlockPlacedBy(level, pos, level.getBlockState(pos), null, display[i]); + } net.minecraft.entity.player.EntityPlayerMP player = server.getPlayerList().getPlayers().get(0); - player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(PrimalPotteryForge.POT)); + player.inventory.clear(); + player.inventory.setInventorySlotContents(3, dyed); + player.inventory.setInventorySlotContents(4, planter); + player.inventory.setInventorySlotContents(5, checker); player.inventoryContainer.detectAndSendChanges(); - player.connection.setPlayerLocation(40.5, 80, -1.5, 0, 15); + player.connection.setPlayerLocation(40.5, 80, -2.5, 0, -11); }); } diff --git a/.github/forge-display-check/1.12.2/potterycheck/LightingCheck.java b/.github/forge-display-check/1.12.2/potterycheck/LightingCheck.java new file mode 100644 index 0000000..33bf273 --- /dev/null +++ b/.github/forge-display-check/1.12.2/potterycheck/LightingCheck.java @@ -0,0 +1,62 @@ +package potterycheck; + +import java.util.stream.IntStream; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +final class LightingCheck { + // A repeatable canopy two blocks above the soil, beside the overhead light. + static void tallTree(ItemStack stack) { + NBTTagList tree = new NBTTagList(); + tree.appendTag(group("minecraft:log", IntStream.range(0, 15).map(y -> voxel(0, y, 0)))); + tree.appendTag(group("minecraft:leaves", IntStream.range(0, 98) + .map(i -> voxel(i % 7 - 3, 15 + i / 49, i / 7 % 7 - 3)))); + stack.getTagCompound().setTag("tree", tree); + } + + static void verify(Minecraft mc) { + BlockPos pos = new BlockPos(40, 81, 0); + IBlockState state = mc.world.getBlockState(pos); + IBakedModel model = mc.getBlockRendererDispatcher().getModelForState(state); + IBlockState extended = state.getBlock().getExtendedState(state, mc.world, pos); + int canopy = mc.world.getCombinedLight(pos.up(2), 0); + if ((canopy & 255) <= (mc.world.getCombinedLight(pos, 0) & 255)) throw new AssertionError("Missing canopy light"); + boolean wall = false, leaves = false; + for (BakedQuad quad : model.getQuads(extended, null, 0)) { + String sprite = quad.getSprite().getIconName(); + int[] data = quad.getVertexData(); + if (sprite.contains("leaves") && quad.getFace() == EnumFacing.DOWN) { + if (!quad.getFormat().equals(DefaultVertexFormats.BLOCK) || data[6] != canopy) + throw new AssertionError("Incorrect leaf light " + data[6] + " expected " + canopy); + leaves = true; + } + if (sprite.equals("primalpottery:block/fired_clay") && quad.getFace() == EnumFacing.NORTH && (byte) data[6] == 0) { + int shade = data[3] & 255; + if (quad.shouldApplyDiffuseLighting() || shade < 190 || shade > 215) + throw new AssertionError("Incorrect clay wall shade " + shade); + wall = true; + } + } + if (!leaves || !wall) throw new AssertionError("Missing lighting fixture leaves=" + leaves + " wall=" + wall); + System.out.println("POTTERY VERIFIED canopy light and clay wall shading"); + } + + private static int voxel(int x, int y, int z) { + return (x + 32) | ((z + 32) << 6) | (y << 12); + } + + private static NBTTagCompound group(String block, IntStream voxels) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setString("block", block); + tag.setIntArray("positions", voxels.toArray()); + return tag; + } +} diff --git a/.github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java b/.github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java index e3f1fe2..fcd9786 100644 --- a/.github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java +++ b/.github/forge-display-check/1.12.2/potterycheck/PlacementClientCheck.java @@ -14,7 +14,7 @@ /** Click the exposed support beside the vessel left by the selective harvest check. */ final class PlacementClientCheck { - private enum Step { SETUP, PLACE, CHECK_OCCUPIED, OPEN_LID, DONE } + private enum Step { SETUP, PLACE, CLICK, CHECK_OCCUPIED, OPEN_LID, DONE } private static final BlockPos SITE = PlacementGameplay.SITE; private Step step = Step.SETUP; private Future task; @@ -46,6 +46,11 @@ boolean tick(Minecraft client) throws Exception { case PLACE: if (pots == null || pots.layout().count() != 1 || held.getCount() != 2 || !PaintingRegistration.isPot(held) || client.playerController.isInCreativeMode()) return false; + // Let the server process the teleport acknowledgement before the placement packet. + if (client.player.getDistanceSq(SITE) > 9) return false; + task = server.addScheduledTask(() -> {}); + break; + case CLICK: if (click(client, SITE.down(), 1) != EnumActionResult.SUCCESS) throw new AssertionError("Second pot rejected on support"); break; case CHECK_OCCUPIED: diff --git a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java index 4c4c747..d81f84f 100644 --- a/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java +++ b/core/src/main/java/net/modcrafters/minecraft/primalpottery/pottery/VesselQuadPacker.java @@ -63,4 +63,31 @@ private void write(int[] data, int index, Vertex point, S sprite, int normal, in } private static int pack(float value) { return Math.round(value * 127) & 255; } + + @FunctionalInterface + protected interface Diffuse { + float shade(float x, float y, float z); + } + + protected final void shadeWall(int[] vertices, float nx, float ny, float nz, Diffuse diffuse) { + // Axis-based block lighting flips abruptly between neighboring rings of a curved wall. + // Bake the directional component only. Minecraft still supplies the local sky and block light. + float shade = wallShade(nx, ny, nz, diffuse); + for (int i = 3; i < vertices.length; i += stride) { + int color = vertices[i]; + int r = Math.round((color & 255) * shade); + int g = Math.round((color >>> 8 & 255) * shade); + int b = Math.round((color >>> 16 & 255) * shade); + vertices[i] = (color & 0xff000000) | b << 16 | g << 8 | r; + } + } + + private static float wallShade(float nx, float ny, float nz, Diffuse diffuse) { + float radial = (float) Math.hypot(nx, nz); + if (radial == 0) return ny < 0 ? .5f : 1f; + // Match the restrained fired-clay tilt in the modern pottery renderer. + float slope = Math.max(-.99f, Math.min(.99f, ny / radial)) * .30f; + float length = (float) Math.sqrt(1 + slope * slope); + return diffuse.shade(nx / radial / length, slope / length, nz / radial / length); + } } diff --git a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java index 63d2720..ba74483 100644 --- a/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java +++ b/forge/src/main/java/net/modcrafters/minecraft/primalpottery/forge/client/PotteryQuads.java @@ -38,25 +38,7 @@ final class PotteryQuads extends VesselQuadPacker Direction face = Direction.getNearest(nx, ny, nz); if (inventoryModel) return new BakedQuad(vertices, -1, face, sprite, true); - // Axis-based block lighting flips abruptly between neighboring rings of a curved wall. - // Bake the directional component only. Minecraft still supplies the local sky and block light. - float shade = wallShade(nx, ny, nz); - for (int i = 3; i < vertices.length; i += 8) { - int color = vertices[i]; - int r = Math.round((color & 255) * shade); - int g = Math.round((color >>> 8 & 255) * shade); - int b = Math.round((color >>> 16 & 255) * shade); - vertices[i] = (color & 0xff000000) | b << 16 | g << 8 | r; - } + shadeWall(vertices, nx, ny, nz, (x, y, z) -> QuadLighter.calculateShade(x, y, z, false)); return new BakedQuad(vertices, -1, face, sprite, false, false); } - - private static float wallShade(float nx, float ny, float nz) { - float radial = (float) Math.hypot(nx, nz); - if (radial == 0) return ny < 0 ? .5f : 1f; - // Match the restrained fired-clay tilt in the modern pottery renderer. - float slope = Math.max(-.99f, Math.min(.99f, ny / radial)) * .30f; - float length = (float) Math.sqrt(1 + slope * slope); - return QuadLighter.calculateShade(nx / radial / length, slope / length, nz / radial / length, false); - } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java index c0d54b5..4aba4ed 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/PaintedPotBlock.java @@ -46,6 +46,15 @@ public final class PaintedPotBlock extends Block implements ITileEntityProvider public boolean isValid(ItemStack[] stacks) { return stacks != null; } public String valueToString(ItemStack[] stacks) { return Integer.toString(stacks.length); } }; + public interface PlantLight { + int at(BlockPos cell); + } + public static final IUnlistedProperty PLANT_LIGHT = new IUnlistedProperty() { + public String getName() { return "plant_light"; } + public Class getType() { return PlantLight.class; } + public boolean isValid(PlantLight light) { return light != null; } + public String valueToString(PlantLight light) { return "local"; } + }; private static final AxisAlignedBB BOUNDS = new AxisAlignedBB(.25, 0, .25, .75, .5, .75); PaintedPotBlock() { @@ -55,12 +64,23 @@ public final class PaintedPotBlock extends Block implements ITileEntityProvider } @Override protected BlockStateContainer createBlockState() { - return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{PROFILE, LAYOUT, STACKS}); + return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{PROFILE, LAYOUT, STACKS, PLANT_LIGHT}); } @Override public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { TileEntity tile = world instanceof ChunkCache ? ((ChunkCache) world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos); - return tile instanceof PaintedPotEntity ? ((IExtendedBlockState)state).withProperty(PROFILE, ((PaintedPotEntity)tile).profile()).withProperty(LAYOUT, ((PaintedPotEntity)tile).layout()).withProperty(STACKS, ((PaintedPotEntity)tile).snapshot()) : state; + if (!(tile instanceof PaintedPotEntity)) return state; + PaintedPotEntity pot = (PaintedPotEntity) tile; + ItemStack[] stacks = pot.snapshot(); + IExtendedBlockState extended = ((IExtendedBlockState) state).withProperty(PROFILE, pot.profile()) + .withProperty(LAYOUT, pot.layout()).withProperty(STACKS, stacks); + for (ItemStack stack : stacks) { + if (stack != null && stack.hasTagCompound() && stack.getTagCompound().hasKey("plant")) { + BlockPos origin = pos.toImmutable(); + return extended.withProperty(PLANT_LIGHT, cell -> world.getCombinedLight(origin.add(cell), 0)); + } + } + return extended; } @Override public TileEntity createNewTileEntity(World world, int metadata) { return new PaintedPotEntity(); } @Override public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT_MIPPED; } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlantQuad.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlantQuad.java new file mode 100644 index 0000000..da6f99a --- /dev/null +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PlantQuad.java @@ -0,0 +1,40 @@ +package net.modcrafters.minecraft.primalpottery.legacy.client; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.util.math.BlockPos; +import net.modcrafters.minecraft.primalpottery.legacy.PaintedPotBlock.PlantLight; + +/** Keep world light out of cached plant geometry and inventory models. */ +final class PlantQuad extends BakedQuad { + private final BlockPos cell; + + PlantQuad(int[] vertices, BakedQuad source, BlockPos cell) { + super(vertices, -1, source.getFace(), source.getSprite(), source.shouldApplyDiffuseLighting(), source.getFormat()); + this.cell = cell; + } + + static List lit(List mesh, PlantLight light) { + List result = new ArrayList<>(mesh.size()); + for (BakedQuad quad : mesh) { + result.add(quad instanceof PlantQuad ? ((PlantQuad) quad).lit(light) : quad); + } + return result; + } + + private BakedQuad lit(PlantLight light) { + // In 1.12 the seventh word holds a normal for ITEM and lightmap UVs for BLOCK. + // Forge reconstructs the face normal for BLOCK when it pipes the quad. + boolean block = getFormat().equals(DefaultVertexFormats.BLOCK); + if (!block && !getFormat().equals(DefaultVertexFormats.ITEM)) return this; + int[] data = getVertexData().clone(); + int packed = light.at(cell); + for (int i = 6; i < data.length; i += 7) { + int old = block ? data[i] : 0; + data[i] = Math.max(old & 0xffff, packed & 0xffff) | Math.max(old >>> 16, packed >>> 16) << 16; + } + return new BakedQuad(data, -1, getFace(), getSprite(), shouldApplyDiffuseLighting(), DefaultVertexFormats.BLOCK); + } +} diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java index 97943c4..d2e0391 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryModel.java @@ -88,7 +88,9 @@ private PotteryModel(IBakedModel base, PotteryQuads bakery, List item new ModelResourceLocation(PrimalPotteryForge.ID, "inventory"), new ModelResourceLocation(PrimalPotteryForge.RAW.getRegistryName(), "inventory")}) { IBakedModel base = event.getModelRegistry().getObject(key); - PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks, sheet, Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("primalpottery:block/dyed_clay")); + PotteryQuads bakery = new PotteryQuads(base.getParticleTexture(), inks, sheet, + Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("primalpottery:block/dyed_clay"), + "inventory".equals(key.getVariant())); InventoryPotteryTransform inventory = new InventoryPotteryTransform(base.handlePerspective(ItemCameraTransforms.TransformType.GUI).getRight()); event.getModelRegistry().putObject(key, new PotteryModel(base, bakery, bakery.model(PaintedVessel.SAMPLE), inventory)); } @@ -109,6 +111,10 @@ private List placedSlot(PotteryLayout layout, ItemStack[] stacks, int return VesselModels.append(bakery.model(layout.at(slot), slot, layout.tint(slot)), stacks[slot], slot); } + // The miniature canopy extends outside the cube used for Forge's corner interpolation. + @Override public boolean isAmbientOcclusion() { return false; } + @Override public boolean isAmbientOcclusion(IBlockState state) { return false; } + @Override public ItemOverrideList getOverrides() { return overrides; } @Override public Pair handlePerspective(ItemCameraTransforms.TransformType type) { @@ -120,7 +126,12 @@ private List placedSlot(PotteryLayout layout, ItemStack[] stacks, int if (side != null) return Collections.emptyList(); if (state instanceof IExtendedBlockState) { net.modcrafters.minecraft.primalpottery.pottery.PotteryLayout layout = ((IExtendedBlockState) state).getValue(PaintedPotBlock.LAYOUT); - if (layout != null) return placed(layout, ((IExtendedBlockState) state).getValue(PaintedPotBlock.STACKS)); + if (layout != null) { + IExtendedBlockState extended = (IExtendedBlockState) state; + List mesh = placed(layout, extended.getValue(PaintedPotBlock.STACKS)); + PaintedPotBlock.PlantLight light = extended.getValue(PaintedPotBlock.PLANT_LIGHT); + return light == null ? mesh : PlantQuad.lit(mesh, light); + } Pottery profile = ((IExtendedBlockState) state).getValue(PaintedPotBlock.PROFILE); if (profile != null) return bakery.model(profile); } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java index 6e8d93a..0f35ee4 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/PotteryQuads.java @@ -4,6 +4,7 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.EnumFacing; +import net.minecraftforge.client.model.pipeline.LightUtil; import net.modcrafters.minecraft.primalpottery.pottery.FacePaint; import net.modcrafters.minecraft.primalpottery.pottery.PaintSheetTiles; import net.modcrafters.minecraft.primalpottery.pottery.PaintedVessel.PaintTile; @@ -12,9 +13,12 @@ final class PotteryQuads extends VesselQuadPacker { private final PaintSheet sheet; private final int[] palette; + private final boolean inventoryModel; - PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite atlasSprite, TextureAtlasSprite dyed) { + PotteryQuads(TextureAtlasSprite clay, TextureAtlasSprite inks, TextureAtlasSprite atlasSprite, TextureAtlasSprite dyed, + boolean inventoryModel) { super(clay, inks, dyed, DefaultVertexFormats.ITEM.getIntegerSize()); + this.inventoryModel = inventoryModel; PaintSheet candidate = atlasSprite instanceof PaintSheet ? (PaintSheet) atlasSprite : null; sheet = candidate != null && candidate.supportsTiles() && !inks.hasAnimationMetadata() ? candidate : null; palette = sheet == null ? null : PaintSheetTiles.palette(inks.getIconWidth(), inks.getIconHeight(), @@ -31,6 +35,7 @@ final class PotteryQuads extends VesselQuadPacker @Override protected float v(TextureAtlasSprite sprite, float pixels) { return sprite.getInterpolatedV(pixels); } @Override protected BakedQuad quad(int[] vertices, TextureAtlasSprite sprite, float nx, float ny, float nz) { - return new BakedQuad(vertices, -1, EnumFacing.getFacingFromVector(nx, ny, nz), sprite, true, DefaultVertexFormats.ITEM); + if (!inventoryModel) shadeWall(vertices, nx, ny, nz, LightUtil::diffuseLight); + return new BakedQuad(vertices, -1, EnumFacing.getFacingFromVector(nx, ny, nz), sprite, inventoryModel, DefaultVertexFormats.ITEM); } } diff --git a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java index 651e928..f16fd3e 100644 --- a/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java +++ b/legacy/forge-1.12.2/src/main/java/net/modcrafters/minecraft/primalpottery/legacy/client/VesselModels.java @@ -162,7 +162,7 @@ private void appendModel(List source, IBlockState state, double bx, d for (BakedQuad quad : source) { int tint = quad.hasTintIndex() ? Minecraft.getMinecraft().getBlockColors().colorMultiplier(state, null, null, quad.getTintIndex()) : -1; int[] data = transform(quad.getVertexData(), bx, by, bz, size, tint); - faces.add(new BakedQuad(data, -1, quad.getFace(), quad.getSprite(), quad.shouldApplyDiffuseLighting(), quad.getFormat())); + faces.add(new PlantQuad(data, quad, new BlockPos(bx + size / 2, by + size / 2, bz + size / 2))); } } @Override protected float u(TextureAtlasSprite sprite, double pixel) { return sprite.getInterpolatedU(pixel); } From c64a83cc3a6edf696c3a72c4525650a9f69268a1 Mon Sep 17 00:00:00 2001 From: Face o' Cat Date: Thu, 3 Dec 2026 13:16:07 +0200 Subject: [PATCH 22/22] Announce Forge support and validate the full publishing catalog before release Co-authored-by: Face of Cat --- .github/scripts/release-publish.sh | 29 ++++++++++++++++---------- .github/workflows/release-metadata.yml | 6 +----- CHANGELOG.md | 2 ++ 3 files changed, 21 insertions(+), 16 deletions(-) diff --git a/.github/scripts/release-publish.sh b/.github/scripts/release-publish.sh index fef9cd8..4af3e03 100644 --- a/.github/scripts/release-publish.sh +++ b/.github/scripts/release-publish.sh @@ -4,6 +4,7 @@ # is the jar for that loader. GitHub gets one release with all six attached. # Usage: # release-publish.sh check-env +# release-publish.sh check-catalog # release-publish.sh classify # release-publish.sh upload set -euo pipefail @@ -61,8 +62,15 @@ http_code() { printf '%s' "$code" } -curseforge_game_versions() { - python3 "$here/curseforge-version-ids.py" "$versions_file" "$types_file" "$@" +resolve_catalog() { + local versions_file=$1 types_file=$2 target loader game java suffix ids + catalog_ids=() + for target in "${targets[@]}"; do + read -r loader game java suffix <<< "$target" + ids=$(python3 "$here/curseforge-version-ids.py" "$versions_file" "$types_file" "$game" "$loader" "Java $java") + catalog_ids+=("$ids") + echo "$loader $game (Java $java) -> $ids" + done } modrinth_upload() { @@ -211,23 +219,18 @@ upload() { cat "$work/versions.json" >&2 exit 1 } - versions_file=$work/versions.json - types_file=$work/types.json - code=$(http_code "$types_file" \ + code=$(http_code "$work/types.json" \ -H "X-Api-Token: ${CURSEFORGE_TOKEN}" \ https://minecraft.curseforge.com/api/game/version-types) [[ "$code" == 200 ]] || { echo "CurseForge game version types returned ${code}" >&2 - cat "$types_file" >&2 + cat "$work/types.json" >&2 exit 1 } # Resolve every target before the first upload, so a catalog error cannot # leave a release published only on Modrinth. - for target in "${targets[@]}"; do - read -r loader game java suffix <<< "$target" - catalog_ids+=("$(curseforge_game_versions "$game" "$loader" "Java $java")") - done + resolve_catalog "$work/versions.json" "$work/types.json" code=$(http_code "$work/files.json" \ -H "X-Api-Token: ${CURSEFORGE_TOKEN}" \ @@ -250,11 +253,15 @@ upload() { github_release "$TAG" "${jar_paths[@]}" } -[[ $# -ge 1 ]] || die "Usage: release-publish.sh check-env|classify|upload ..." +[[ $# -ge 1 ]] || die "Usage: release-publish.sh check-env|check-catalog|classify|upload ..." cmd=$1 shift case "$cmd" in check-env) check_env ;; + check-catalog) + [[ $# -eq 2 ]] || die "Usage: release-publish.sh check-catalog " + resolve_catalog "$1" "$2" + ;; classify) [[ $# -eq 2 ]] || die "Usage: release-publish.sh classify " classify "$1" "$2" diff --git a/.github/workflows/release-metadata.yml b/.github/workflows/release-metadata.yml index 8fc75a6..b5d762d 100644 --- a/.github/workflows/release-metadata.yml +++ b/.github/workflows/release-metadata.yml @@ -20,8 +20,4 @@ jobs: https://minecraft.curseforge.com/api/game/versions > versions.json curl --fail-with-body -sS -H "X-Api-Token: ${CURSEFORGE_TOKEN}" \ https://minecraft.curseforge.com/api/game/version-types > types.json - jq --slurpfile types types.json '[$types[0][] | select(.slug == "environment") | .id] as $ids | [.[] | select(.gameVersionTypeID as $id | $ids | index($id))]' versions.json - python3 .github/scripts/curseforge-version-ids.py versions.json types.json 1.20.6 NeoForge "Java 21" - python3 .github/scripts/curseforge-version-ids.py versions.json types.json 1.21.1 NeoForge "Java 21" - python3 .github/scripts/curseforge-version-ids.py versions.json types.json 26.3 Fabric "Java 25" - python3 .github/scripts/curseforge-version-ids.py versions.json types.json 26.3 NeoForge "Java 25" + bash .github/scripts/release-publish.sh check-catalog versions.json types.json diff --git a/CHANGELOG.md b/CHANGELOG.md index bf361a0..72007a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ After publishing, the action commits the next development version and changelog ## Unreleased +- Primal Pottery now runs on Forge for Minecraft 1.12.2 and 1.20.1. Shape and fire pottery, paint it, fit lids, grow miniature trees, and serve meals on plates and platters. + - Craft a cutlery set with three iron nuggets above three sticks. Hold use to cut a serving into four bites, or set the utensils beside a small plate and eat with both hands empty. Right-click the utensils to take them back. - Picking up a clay block or a clay ball unlocks the pottery wheel and both blank template recipes. A stamped template unlocks the recipe to turn it back into a blank of the same size.