From bfae9f9bc5ff5a69bca6de49efba5ba234165c5f Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Mon, 19 Oct 2026 20:23:42 +0200 Subject: [PATCH] feat(generator): validate every jump on the block grid and keep 2-4 block gaps --- .../options/section/OptionGeneration.java | 67 +++++- .../jump/calculation/JumpCalculator.java | 205 ++++++++---------- .../jump/calculation/JumpOffsetGenerator.java | 6 +- .../constraints/JumpConstraintsResolver.java | 98 +++++++++ .../jump/placement/BlockTargetSelector.java | 4 +- .../generator/jump/spacing/CourseSpacing.java | 90 ++++++++ src/main/resources/config.yml | 18 ++ src/main/resources/generation.yml | 30 +-- .../jump/calculation/JumpCalculatorTest.java | 63 ++++-- .../jump/spacing/CourseSpacingTest.java | 61 ++++++ 10 files changed, 496 insertions(+), 146 deletions(-) create mode 100644 src/main/java/dev/loki/loparkour/generator/jump/constraints/JumpConstraintsResolver.java create mode 100644 src/main/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacing.java create mode 100644 src/test/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacingTest.java diff --git a/src/main/java/dev/loki/loparkour/config/options/section/OptionGeneration.java b/src/main/java/dev/loki/loparkour/config/options/section/OptionGeneration.java index 7747380..cf58b09 100644 --- a/src/main/java/dev/loki/loparkour/config/options/section/OptionGeneration.java +++ b/src/main/java/dev/loki/loparkour/config/options/section/OptionGeneration.java @@ -2,15 +2,18 @@ package dev.loki.loparkour.config.options.section; import dev.loki.loparkour.LoParkour; import dev.loki.loparkour.config.core.Config; +import org.jetbrains.annotations.NotNull; /** - * Generation-related configuration options (bounds, memory, jump validation). + * Generation-related configuration options (bounds, memory, jump validation, + * course spacing). * *

Block-type weights are not read here — they live in * {@code GeneratorProfileManager} / {@code GenerationProfileLoader}, which resolve * the {@code advanced.*} paths (see TODO: {@code generation.type|normal|special} * in generation.yml is currently ignored).

*/ +@SuppressWarnings("PMD.TooManyMethods") // flat, static config accessors grouped by section public final class OptionGeneration { private static final double DEFAULT_MAX_JUMP_DISTANCE = 5.0; @@ -22,6 +25,12 @@ public final class OptionGeneration { private static final int DEFAULT_TRAIL_KEEP_BEHIND = 10; private static final int DEFAULT_MIN_Y = 100; private static final int DEFAULT_MAX_Y = 200; + private static final int DEFAULT_COURSE_MIN_GAP = 2; + private static final int DEFAULT_COURSE_START_MAX_GAP = 3; + private static final int DEFAULT_COURSE_MAX_GAP = 4; + private static final int DEFAULT_COURSE_START_JUMPS = 5; + private static final int VANILLA_MAX_GAP = 4; + private static final int MAX_COURSE_START_JUMPS = 1000; private OptionGeneration() { } @@ -42,10 +51,17 @@ public final class OptionGeneration { private static double maxVerticalUp; private static double maxVerticalDown; + // ── Course spacing (gap bounds between consecutive blocks) ───────────────── + private static int courseMinGap; + private static int courseStartMaxGap; + private static int courseMaxGap; + private static int courseStartJumps; + public static void init() { initBounds(); initJumpValidation(); initMemory(); + initCourseSpacing(); } private static void initBounds() { @@ -82,6 +98,35 @@ public final class OptionGeneration { ? Config.CONFIG.getInt("memory.trail-keep-behind") : DEFAULT_TRAIL_KEEP_BEHIND; } + private static void initCourseSpacing() { + courseMinGap = readClampedGap("course-spacing.min-gap", DEFAULT_COURSE_MIN_GAP); + courseStartMaxGap = readClampedGap("course-spacing.start-max-gap", DEFAULT_COURSE_START_MAX_GAP); + courseMaxGap = readClampedGap("course-spacing.max-gap", DEFAULT_COURSE_MAX_GAP); + courseStartJumps = Config.CONFIG.isPath("course-spacing.start-jumps") + ? Math.max(0, Math.min(Config.CONFIG.getInt("course-spacing.start-jumps"), MAX_COURSE_START_JUMPS)) + : DEFAULT_COURSE_START_JUMPS; + + // Keep the bounds ordered: min <= startMax <= max. + courseStartMaxGap = Math.max(courseMinGap, courseStartMaxGap); + courseMaxGap = Math.max(courseStartMaxGap, courseMaxGap); + + if (courseMinGap > VANILLA_MAX_GAP) { + LoParkour.getPlugin().getLogger().severe( + "course-spacing.min-gap=" + courseMinGap + " exceeds the vanilla jump reach (" + + VANILLA_MAX_GAP + ") — clamped."); + courseMinGap = VANILLA_MAX_GAP; + courseStartMaxGap = Math.max(courseMinGap, courseStartMaxGap); + courseMaxGap = Math.max(courseStartMaxGap, courseMaxGap); + } + } + + private static int readClampedGap(@NotNull String path, int defaultValue) { + if (!Config.CONFIG.isPath(path)) { + return defaultValue; + } + return Math.max(1, Math.min(Config.CONFIG.getInt(path), VANILLA_MAX_GAP)); + } + public static int maxY() { return maxY; } @@ -121,4 +166,24 @@ public final class OptionGeneration { public static double maxVerticalDown() { return maxVerticalDown; } + + /** Minimum horizontal gap between consecutive blocks ({@code course-spacing.min-gap}). */ + public static int courseMinGap() { + return courseMinGap; + } + + /** Maximum gap during the conservative start segment ({@code course-spacing.start-max-gap}). */ + public static int courseStartMaxGap() { + return courseStartMaxGap; + } + + /** Maximum gap on a mature course ({@code course-spacing.max-gap}). */ + public static int courseMaxGap() { + return courseMaxGap; + } + + /** Number of conservative jumps after every (re)spawn ({@code course-spacing.start-jumps}). */ + public static int courseStartJumps() { + return courseStartJumps; + } } diff --git a/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculator.java b/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculator.java index 76ba57a..aa2cf37 100644 --- a/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculator.java +++ b/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculator.java @@ -2,54 +2,49 @@ package dev.loki.loparkour.generator.jump.calculation; import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator; import dev.loki.loparkour.generator.core.model.GeneratorOption; +import dev.loki.loparkour.generator.jump.constraints.JumpConstraintsResolver; +import dev.loki.loparkour.generator.jump.constraints.JumpConstraintsResolver.JumpConstraints; import dev.loki.loparkour.generator.jump.placement.BlockSelector; -import dev.loki.loparkour.util.misc.MaterialUtil; +import dev.loki.loparkour.generator.jump.spacing.CourseSpacing; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; import org.bukkit.util.BoundingBox; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; -/** - * Calculates jump positions and validates jump constraints. - */ +/** Calculates reachable jump positions within the {@link CourseSpacing} gap bounds. */ public class JumpCalculator { private static final int MIN_HEIGHT = -2; private static final int MAX_VALID_DISTANCE = 4; - private static final int DEFAULT_MAX_DISTANCE = 4; - private static final int RESTRICTED_MAX_DISTANCE = 3; + private static final int MAX_HEIGHT_UP = 1; private static final double RANDOM_OFFSET_SD = 0.5; private static final double DEFAULT_RANDOM_OFFSET_SD = 1.0; private static final int MAX_RETRY_ATTEMPTS = 10; private static final int MAX_REROLL_ATTEMPTS = 3; - private static final int SAFETY_STEP_DISTANCE = 1; - private static final int SAFETY_STEP_HEIGHT = 0; private static final double NO_LATERAL_JITTER = 0.0; private static final double ZERO_HEADING_EPSILON = 1.0E-6; - private static final int PACKED_ICE_MAX_DISTANCE = 4; - private static final int BLUE_ICE_MAX_DISTANCE = 4; - private static final int ICE_MAX_DISTANCE = 3; - private static final int DEFAULT_SPECIAL_MAX_DISTANCE = 3; + private static final double GAP_EPSILON = 1.0E-6; private final ParkourGenerator generator; private final BlockSelector blockSelector; + private final JumpConstraintsResolver constraintsResolver; public JumpCalculator(@NotNull ParkourGenerator generator, @NotNull BlockSelector blockSelector) { this.generator = generator; this.blockSelector = blockSelector; + this.constraintsResolver = new JumpConstraintsResolver(blockSelector); } /** - * Calculate the next block position based on current block and jump parameters. + * Calculates the next reachable block, or null when none exists (the attempt is skipped). */ - @NotNull + @Nullable public Block calculateNextBlock(@NotNull Block current, int distance, int height) { if (generator.state.zone() == null || generator.state.zone().length < 2) { throw new IllegalStateException("Generator zone not initialized"); @@ -61,56 +56,28 @@ public class JumpCalculator { ); generator.state.setHeading(director.getRecommendedHeading(generator.state.heading())); + final JumpConstraints constraints = constraintsResolver.resolve(current); + + final CourseSpacing spacing = CourseSpacing.fromConfig(); + final int minGap = Math.max(1, Math.min(spacing.minGap(), Math.min(constraints.maxDistance, MAX_VALID_DISTANCE))); + final int gapCeiling = Math.min(Math.min( + spacing.maxGapFor(generator.state.generatedBlocks(), generator.getDifficultyScore()), + constraints.maxDistance), MAX_VALID_DISTANCE); + int resolvedHeight = director.getRecommendedHeight(height); - - final JumpConstraints constraints = calculateJumpConstraints(current); resolvedHeight = Math.min(resolvedHeight, constraints.maxHeight); - int resolvedDistance = Math.min(distance, constraints.maxDistance); - - resolvedHeight = Math.max(MIN_HEIGHT, Math.min(2, resolvedHeight)); - resolvedDistance = Math.max(1, Math.min(MAX_VALID_DISTANCE, resolvedDistance)); + resolvedHeight = Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT_UP, resolvedHeight)); + int resolvedDistance = Math.max(minGap, Math.min(distance, gapCeiling)); if (resolvedHeight > 0) { - resolvedDistance = Math.max(resolvedDistance - resolvedHeight, 1); + resolvedDistance = Math.max(resolvedDistance - resolvedHeight, minGap); } final double randomOffsetSd = Arrays.asList(generator.generatorOptions) .contains(GeneratorOption.REDUCE_RANDOM_BLOCK_SELECTION_ANGLE) ? RANDOM_OFFSET_SD : DEFAULT_RANDOM_OFFSET_SD; final Location candidate = validateAndRetryJump(current.getLocation(), generator.state.heading(), - resolvedDistance, resolvedHeight, ThreadLocalRandom.current(), randomOffsetSd); - return candidate.getBlock(); - } - - @NotNull - public JumpConstraints calculateJumpConstraints(@NotNull Block currentBlock) { - final Material material = currentBlock.getType(); - final BlockData blockData = currentBlock.getBlockData(); - - int maxHeight = 1; - int maxDistance = DEFAULT_MAX_DISTANCE; - - if (MaterialUtil.isSlabMaterial(material)) { - if (blockData instanceof org.bukkit.block.data.type.Slab slab) { - if (slab.getType() == org.bukkit.block.data.type.Slab.Type.BOTTOM) { - maxHeight = -1; - maxDistance = RESTRICTED_MAX_DISTANCE; - } else { - maxHeight = 0; - maxDistance = RESTRICTED_MAX_DISTANCE; - } - } else { - maxHeight = 0; - maxDistance = RESTRICTED_MAX_DISTANCE; - } - } else if (material == Material.GLASS_PANE) { - maxHeight = 0; - maxDistance = RESTRICTED_MAX_DISTANCE; - } else if (blockSelector.isSpecialMaterial(material)) { - maxHeight = getSpecialMaterialMaxHeight(material); - maxDistance = getSpecialMaterialMaxDistance(material); - } - - return new JumpConstraints(maxHeight, maxDistance); + resolvedDistance, resolvedHeight, minGap, randomOffsetSd); + return candidate == null ? null : candidate.getBlock(); } @NotNull @@ -130,71 +97,83 @@ public class JumpCalculator { return Math.min(new JumpOffsetGenerator(height, distance).getRandomOffset(0, standardDeviation, random), maxJitter); } - @NotNull + /** + * Tries reachable integer block anchors; never returns an adjacent grid cell. + */ + @Nullable static Location validateAndRetryJump(@NotNull Location current, @NotNull Vector heading, int distance, int height, - @NotNull Random random, double randomOffsetSd) { - final JumpValidator validator = new JumpValidator(); - int resolvedDistance = distance; - int resolvedHeight = height; - int attempts = 0; - Location candidate = current.clone().add(offsetFor(heading, resolvedDistance, resolvedHeight, - randomOffset(resolvedHeight, resolvedDistance, randomOffsetSd, random))); - while (!validator.canJump(current, candidate) && attempts < MAX_RETRY_ATTEMPTS) { - resolvedDistance = Math.max(1, resolvedDistance - 1); - resolvedHeight = Math.max(MIN_HEIGHT, resolvedHeight - 1); - candidate = current.clone().add(offsetFor(heading, resolvedDistance, resolvedHeight, - randomOffset(resolvedHeight, resolvedDistance, randomOffsetSd, random))); - attempts++; - } - - if (validator.canJump(current, candidate)) { - return candidate; - } - return safetyFallback(current, heading, randomOffsetSd, random, validator); + int minGap, double randomOffsetSd) { + return validateAndRetryJump(current, heading, distance, height, minGap, randomOffsetSd, new JumpValidator()); } - @NotNull - static Location safetyFallback(@NotNull Location current, @NotNull Vector heading, double randomOffsetSd, - @NotNull Random random, @NotNull JumpValidator validator) { - for (int i = 0; i < MAX_REROLL_ATTEMPTS; i++) { - final Location reRolled = current.clone().add(offsetFor(heading, SAFETY_STEP_DISTANCE, SAFETY_STEP_HEIGHT, - randomOffset(SAFETY_STEP_HEIGHT, SAFETY_STEP_DISTANCE, randomOffsetSd, random))); - if (validator.canJump(current, reRolled)) { - return reRolled; + /** Package-visible variant with an injectable validator for tests. */ + @Nullable + static Location validateAndRetryJump(@NotNull Location current, @NotNull Vector heading, int distance, int height, + int minGap, double randomOffsetSd, @NotNull JumpValidator validator) { + final Random random = ThreadLocalRandom.current(); + final Vector normalized = heading.length() < ZERO_HEADING_EPSILON + ? new Vector(0, 0, 1) : heading.clone().normalize(); + final int baseDistance = Math.max(minGap, distance); + final int maxDistance = Math.min(MAX_VALID_DISTANCE, baseDistance + MAX_HEIGHT_UP); + int resolvedHeight = height; + for (int attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt++) { + // Search a small distance window: diagonal offsets can land on a + // neighbouring grid cell, so a larger step may be the closest real jump. + for (int resolvedDistance = baseDistance; resolvedDistance <= maxDistance; resolvedDistance++) { + final Location candidate = blockAnchor(current, normalized, resolvedDistance, resolvedHeight, + randomOffset(resolvedHeight, resolvedDistance, randomOffsetSd, random)); + if (isReachableBlock(current, candidate, minGap, validator)) { + return candidate; + } + } + resolvedHeight = Math.max(MIN_HEIGHT, resolvedHeight - 1); + } + return safetyFallback(current, normalized, minGap, randomOffsetSd, validator); + } + + /** Last resort: a straight, flat step starting at {@code minGap} blocks. */ + @Nullable + static Location safetyFallback(@NotNull Location current, @NotNull Vector heading, int minGap, + double randomOffsetSd, @NotNull JumpValidator validator) { + final Random random = ThreadLocalRandom.current(); + for (int distance = minGap; distance <= MAX_VALID_DISTANCE; distance++) { + for (int i = 0; i < MAX_REROLL_ATTEMPTS; i++) { + final Location reRolled = blockAnchor(current, heading, distance, 0, + randomOffset(0, distance, randomOffsetSd, random)); + if (isReachableBlock(current, reRolled, minGap, validator)) { + return reRolled; + } + } + final Location straight = blockAnchor(current, heading, distance, 0, NO_LATERAL_JITTER); + if (isReachableBlock(current, straight, minGap, validator)) { + return straight; } } - final Location straight = current.clone().add( - offsetFor(heading, SAFETY_STEP_DISTANCE, SAFETY_STEP_HEIGHT, NO_LATERAL_JITTER)); - return validator.canJump(current, straight) ? straight : current; + return null; } - private int getSpecialMaterialMaxHeight(@NotNull Material material) { - return switch (material) { - case PACKED_ICE -> 1; - case BLUE_ICE -> 1; - case ICE -> 0; - case LADDER -> 1; - default -> 0; - }; + /** Snaps a fractional offset to the integer block that will actually be placed. */ + @NotNull + private static Location blockAnchor(@NotNull Location current, @NotNull Vector heading, int distance, int height, + double randomOffset) { + final Vector offset = offsetFor(heading, distance, height, randomOffset); + // Floor to the integer block anchor without touching the world (unit tests + // use a mocked world); Location#getBlock() performs the same flooring. + return new Location(current.getWorld(), + Math.floor(current.getX() + offset.getX()), + Math.floor(current.getY() + offset.getY()), + Math.floor(current.getZ() + offset.getZ())); } - private int getSpecialMaterialMaxDistance(@NotNull Material material) { - return switch (material) { - case PACKED_ICE -> PACKED_ICE_MAX_DISTANCE; - case BLUE_ICE -> BLUE_ICE_MAX_DISTANCE; - case ICE -> ICE_MAX_DISTANCE; - case LADDER -> 2; - default -> DEFAULT_SPECIAL_MAX_DISTANCE; - }; - } - - public static class JumpConstraints { - public final int maxHeight; - public final int maxDistance; - - public JumpConstraints(int maxHeight, int maxDistance) { - this.maxHeight = maxHeight; - this.maxDistance = maxDistance; + /** @return true when the anchor clears the integer grid gap and the jump validator. */ + private static boolean isReachableBlock(@NotNull Location current, @NotNull Location candidate, int minGap, + @NotNull JumpValidator validator) { + final int dx = candidate.getBlockX() - current.getBlockX(); + final int dz = candidate.getBlockZ() - current.getBlockZ(); + if (dx == 0 && dz == 0) { + return false; } + final double blockGap = Math.sqrt(dx * dx + dz * dz); + return blockGap + GAP_EPSILON >= minGap && validator.canJump(current, candidate); } } diff --git a/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpOffsetGenerator.java b/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpOffsetGenerator.java index a34d834..876e55c 100644 --- a/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpOffsetGenerator.java +++ b/src/main/java/dev/loki/loparkour/generator/jump/calculation/JumpOffsetGenerator.java @@ -78,8 +78,10 @@ public class JumpOffsetGenerator { } private static void warnUnexpectedHeight(int y) { - dev.loki.loparkour.LoParkour.getPlugin().getLogger() - .warning("Unexpected jump height " + y + ", using default maxOffset=2"); + final dev.loki.loparkour.LoParkour plugin = dev.loki.loparkour.LoParkour.getPlugin(); + if (plugin != null) { // null outside a running server (unit tests) + plugin.getLogger().warning("Unexpected jump height " + y + ", using default maxOffset=2"); + } } /** diff --git a/src/main/java/dev/loki/loparkour/generator/jump/constraints/JumpConstraintsResolver.java b/src/main/java/dev/loki/loparkour/generator/jump/constraints/JumpConstraintsResolver.java new file mode 100644 index 0000000..202a995 --- /dev/null +++ b/src/main/java/dev/loki/loparkour/generator/jump/constraints/JumpConstraintsResolver.java @@ -0,0 +1,98 @@ +package dev.loki.loparkour.generator.jump.constraints; + +import dev.loki.loparkour.generator.jump.placement.BlockSelector; +import dev.loki.loparkour.util.misc.MaterialUtil; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; +import org.jetbrains.annotations.NotNull; + +/** + * Resolves per-material jump limits (maximum upward step and maximum gap) + * for the block a jump starts from. Slabs, panes and slippery special blocks + * get tighter limits than full solid blocks. + */ +public final class JumpConstraintsResolver { + + private static final int DEFAULT_MAX_HEIGHT = 1; + private static final int DEFAULT_MAX_DISTANCE = 4; + private static final int RESTRICTED_MAX_DISTANCE = 3; + private static final int PACKED_ICE_MAX_DISTANCE = 4; + private static final int BLUE_ICE_MAX_DISTANCE = 4; + private static final int ICE_MAX_DISTANCE = 3; + private static final int LADDER_MAX_DISTANCE = 2; + private static final int DEFAULT_SPECIAL_MAX_DISTANCE = 3; + + private final BlockSelector blockSelector; + + public JumpConstraintsResolver(@NotNull BlockSelector blockSelector) { + this.blockSelector = blockSelector; + } + + /** + * @param currentBlock the block the jump starts from + * @return the limits for jumping off this block type; never null + */ + @NotNull + public JumpConstraints resolve(@NotNull Block currentBlock) { + final Material material = currentBlock.getType(); + final BlockData blockData = currentBlock.getBlockData(); + + int maxHeight = DEFAULT_MAX_HEIGHT; + int maxDistance = DEFAULT_MAX_DISTANCE; + + if (MaterialUtil.isSlabMaterial(material)) { + if (blockData instanceof org.bukkit.block.data.type.Slab slab) { + if (slab.getType() == org.bukkit.block.data.type.Slab.Type.BOTTOM) { + maxHeight = -1; + maxDistance = RESTRICTED_MAX_DISTANCE; + } else { + maxHeight = 0; + maxDistance = RESTRICTED_MAX_DISTANCE; + } + } else { + maxHeight = 0; + maxDistance = RESTRICTED_MAX_DISTANCE; + } + } else if (material == Material.GLASS_PANE) { + maxHeight = 0; + maxDistance = RESTRICTED_MAX_DISTANCE; + } else if (blockSelector.isSpecialMaterial(material)) { + maxHeight = specialMaxHeight(material); + maxDistance = specialMaxDistance(material); + } + + return new JumpConstraints(maxHeight, maxDistance); + } + + private int specialMaxHeight(@NotNull Material material) { + return switch (material) { + case PACKED_ICE -> 1; + case BLUE_ICE -> 1; + case ICE -> 0; + case LADDER -> 1; + default -> 0; + }; + } + + private int specialMaxDistance(@NotNull Material material) { + return switch (material) { + case PACKED_ICE -> PACKED_ICE_MAX_DISTANCE; + case BLUE_ICE -> BLUE_ICE_MAX_DISTANCE; + case ICE -> ICE_MAX_DISTANCE; + case LADDER -> LADDER_MAX_DISTANCE; + default -> DEFAULT_SPECIAL_MAX_DISTANCE; + }; + } + + /** Per-material limits for one jump. */ + public static final class JumpConstraints { + public final int maxHeight; + public final int maxDistance; + + public JumpConstraints(int maxHeight, int maxDistance) { + this.maxHeight = maxHeight; + this.maxDistance = maxDistance; + } + } +} diff --git a/src/main/java/dev/loki/loparkour/generator/jump/placement/BlockTargetSelector.java b/src/main/java/dev/loki/loparkour/generator/jump/placement/BlockTargetSelector.java index d6a832b..a60eebb 100644 --- a/src/main/java/dev/loki/loparkour/generator/jump/placement/BlockTargetSelector.java +++ b/src/main/java/dev/loki/loparkour/generator/jump/placement/BlockTargetSelector.java @@ -46,7 +46,9 @@ public class BlockTargetSelector { final int distance = Probs.random(generator.state.distanceChances); final int height = forcedHeight != NO_FORCED_HEIGHT ? forcedHeight : Probs.random(generator.state.heightChances); final Block nextBlock = jumpCalculator.calculateNextBlock(current, distance, height); - blocks.add(nextBlock); + if (nextBlock != null) { + blocks.add(nextBlock); + } return blocks; } } diff --git a/src/main/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacing.java b/src/main/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacing.java new file mode 100644 index 0000000..2b9d07f --- /dev/null +++ b/src/main/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacing.java @@ -0,0 +1,90 @@ +package dev.loki.loparkour.generator.jump.spacing; + +import dev.loki.loparkour.config.options.section.OptionGeneration; +import org.jetbrains.annotations.NotNull; + +/** + * Resolves the horizontal gap bounds for a single generation step. + * + *

The first {@code startJumps} blocks of a course use a conservative + * {@code [minGap, startMaxGap]} range; afterwards the upper bound grows with the + * generator difficulty score toward {@code maxGap}. The lower bound never drops + * below {@code minGap}, so blocks are never placed directly next to each other + * ("in a row") and every gap is a real jump.

+ * + *

All values are clamped to the vanilla jump reach (1..4 blocks), so a + * misconfigured {@code course-spacing.*} section can never produce unreachable + * gaps.

+ */ +public final class CourseSpacing { + + /** Difficulty score at which the gap cap reaches {@code max-gap} (see GeneratorProfileManager). */ + private static final double FULL_DIFFICULTY_SCORE = 1.5; + + /** Largest gap a vanilla (non-sprint) jump can clear; mirrors JumpValidator.MAX_HORIZONTAL_DISTANCE. */ + private static final int VANILLA_MAX_GAP = 4; + + private static final int ABSOLUTE_MIN_GAP = 1; + + private final int minGap; + private final int startMaxGap; + private final int maxGap; + private final int startJumps; + + /** + * Creates spacing with sanitized bounds. + * + * @param minGap minimum horizontal gap between two blocks (1..4) + * @param startMaxGap maximum gap during the start segment ({@code >= minGap}) + * @param maxGap maximum gap on a mature course ({@code >= startMaxGap}) + * @param startJumps number of conservative jumps after every (re)spawn + */ + public CourseSpacing(int minGap, int startMaxGap, int maxGap, int startJumps) { + final int safeMin = clamp(minGap, ABSOLUTE_MIN_GAP, VANILLA_MAX_GAP); + this.minGap = safeMin; + this.startMaxGap = clamp(startMaxGap, safeMin, VANILLA_MAX_GAP); + this.maxGap = clamp(maxGap, this.startMaxGap, VANILLA_MAX_GAP); + this.startJumps = Math.max(0, startJumps); + } + + /** + * Spacing resolved from the {@code course-spacing.*} section of config.yml. + * + * @return sanitized spacing; never null + */ + @NotNull + public static CourseSpacing fromConfig() { + return new CourseSpacing( + OptionGeneration.courseMinGap(), + OptionGeneration.courseStartMaxGap(), + OptionGeneration.courseMaxGap(), + OptionGeneration.courseStartJumps()); + } + + /** + * Upper gap bound for one generation step. + * + * @param generatedBlocks blocks placed since the course (re)started + * @param difficultyScore generator difficulty score (roughly 0..1.5) + * @return the largest gap allowed for this step, never below {@link #minGap()} + */ + public int maxGapFor(int generatedBlocks, double difficultyScore) { + if (generatedBlocks < startJumps) { + return startMaxGap; + } + final double normalized = Math.max(0.0, Math.min(1.0, difficultyScore / FULL_DIFFICULTY_SCORE)); + final int scaled = minGap + (int) Math.ceil(normalized * (maxGap - minGap)); + return Math.max(startMaxGap, Math.min(maxGap, scaled)); + } + + /** + * @return the smallest gap ever placed; below this a step counts as "in a row" + */ + public int minGap() { + return minGap; + } + + private static int clamp(int value, int min, int max) { + return Math.max(min, Math.min(max, value)); + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 14acb7f..7d8fa13 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -150,6 +150,24 @@ jump-validation: max-vertical-up: 1.25 max-vertical-down: 3.0 +# -= Course spacing =- +# How far apart consecutive parkour blocks are placed (in blocks). +# Every gap is validated against vanilla jump physics before placement, +# so the next block is always reachable from the previous one. +# Values are clamped to the vanilla jump reach (1-4 blocks). +course-spacing: + # Minimum horizontal gap between two blocks. + # Blocks are never placed directly next to each other ("in a row"). + min-gap: 2 + # Maximum gap used during the conservative start segment (see start-jumps). + start-max-gap: 3 + # Maximum gap on a mature course; the exact cap grows with the + # adaptive difficulty of the players (start-max-gap .. max-gap). + max-gap: 4 + # Number of jumps kept conservative after every (re)spawn: + # gaps between min-gap and start-max-gap, upward steps of at most 1 block. + start-jumps: 5 + # -= Memory optimization =- memory: block-cleanup-distance: 20 diff --git a/src/main/resources/generation.yml b/src/main/resources/generation.yml index dc44ec5..bd93c52 100644 --- a/src/main/resources/generation.yml +++ b/src/main/resources/generation.yml @@ -12,12 +12,13 @@ generation: # -= Normal jump chances =- normal: # -= Distance chances =- - # The chances of the different distances in %. Can be above 100%. + # Horizontal gap in blocks between two parkour blocks, in %. + # A gap of 1 is not a jump and is therefore not offered; the code also + # clamps every gap to course-spacing.min-gap in config.yml. distance: - 1: 5 2: 35 3: 45 - 4: 15 + 4: 20 # -= Height chances =- # The chances of the different heights a jump can have in %. Can be above 100%. @@ -82,24 +83,27 @@ advanced: heading: east # -= Jump distance weights (advanced.distance.min .. max) =- + # Gap size in blocks between consecutive parkour blocks. 1 is intentionally + # not offered: a 1-block step is not a jump (course-spacing.min-gap clamps + # it anyway). 2 = easy, 4 = near the vanilla sprint-jump limit. distance: - min: 1 + min: 2 max: 4 chances: - 1: 25 - 2: 25 - 3: 25 - 4: 25 + 2: 40 + 3: 40 + 4: 20 # -= Vertical step weights (advanced.height.min .. max) =- + # A vanilla jump reaches at most ~1.25 blocks up, so positive steps are + # capped at 1; downward steps may be deeper (falling is always possible). height: min: -1 - max: 2 + max: 1 chances: - "-1": 20 - "0": 30 - 1: 30 - 2: 20 + "-1": 25 + "0": 35 + 1: 40 # -= Block type mix (default vs special vs schematic) =- type: diff --git a/src/test/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculatorTest.java b/src/test/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculatorTest.java index 20893c7..32167eb 100644 --- a/src/test/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculatorTest.java +++ b/src/test/java/dev/loki/loparkour/generator/jump/calculation/JumpCalculatorTest.java @@ -8,10 +8,9 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.Random; - import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -22,6 +21,7 @@ class JumpCalculatorTest { private static final double DELTA = 1.0E-6; private static final double DIAGONAL_UNIT = 0.7071067811865476; private static final double DEFAULT_SD = 1; + private static final int MIN_GAP = 2; @Mock private World world; @@ -64,20 +64,24 @@ class JumpCalculatorTest { } @Test - void safetyFallbackReturnsValidStepForUnitHeading() { + void safetyFallbackReturnsValidMinimalStep() { final JumpValidator validator = new JumpValidator(); - final Location fallback = JumpCalculator.safetyFallback(current, new Vector(1, 0, 0), DEFAULT_SD, new Random(42), validator); + final Location fallback = JumpCalculator.safetyFallback(current, new Vector(1, 0, 0), MIN_GAP, DEFAULT_SD, validator); - assertNotEquals(current, fallback); + assertNotNull(fallback); assertTrue(validator.canJump(current, fallback)); + assertTrue(validator.calculateHorizontalDistance(current.toVector(), fallback.toVector()) >= MIN_GAP, + "fallback must keep at least the minimum gap"); + assertBlockGap(fallback); } @Test - void safetyFallbackReturnsCurrentWhenStraightStepImpossible() { - final JumpValidator validator = new JumpValidator(); - final Location fallback = JumpCalculator.safetyFallback(current, new Vector(100, 0, 0), DEFAULT_SD, new Random(1), validator); + void safetyFallbackReturnsNullWhenEvenMinimalStepUnreachable() { + // Validator with maxHorizontal < minGap: nothing can ever be placed. + final JumpValidator impossible = new JumpValidator(4.5, 1.0, 1.25, 3.0); + final Location fallback = JumpCalculator.safetyFallback(current, new Vector(1, 0, 0), MIN_GAP, DEFAULT_SD, impossible); - assertEquals(current, fallback); + assertNull(fallback); } @Test @@ -86,10 +90,11 @@ class JumpCalculatorTest { final Vector heading = new Vector(0, 0, 1); for (int distance = 1; distance <= 4; distance++) { - for (int height = -2; height <= 1; height++) { + for (int height = -2; height <= 2; height++) { final Location result = JumpCalculator.validateAndRetryJump( - current, heading, distance, height, new Random(distance * 10 + height), DEFAULT_SD); + current, heading, distance, height, MIN_GAP, DEFAULT_SD); + assertNotNull(result, "missing candidate for distance=" + distance + " height=" + height); assertTrue(validator.canJump(current, result), "unreachable block for distance=" + distance + " height=" + height); } @@ -97,14 +102,40 @@ class JumpCalculatorTest { } @Test - void validateAndRetryJumpReturnsCurrentAsLastResort() { - final Location result = JumpCalculator.validateAndRetryJump( - current, new Vector(100, 0, 0), 4, 1, new Random(7), DEFAULT_SD); + void validateAndRetryJumpNeverPlacesAdjacentBlock() { + final Vector heading = new Vector(DIAGONAL_UNIT, 0, DIAGONAL_UNIT); - assertEquals(current, result); + for (int attempt = 0; attempt < 50; attempt++) { + final Location result = JumpCalculator.validateAndRetryJump( + current, heading, 4, 1, MIN_GAP, DEFAULT_SD); + + assertNotNull(result); + final double horizontal = new JumpValidator().calculateHorizontalDistance(current.toVector(), result.toVector()); + assertTrue(horizontal >= MIN_GAP - DELTA, + "block placed in a row: horizontal gap " + horizontal + " < min gap " + MIN_GAP); + assertBlockGap(result); + } + } + + @Test + void validateAndRetryJumpReturnsNullWhenNothingReachable() { + final JumpValidator impossible = new JumpValidator(4.5, 1.0, 1.25, 3.0); + final Location result = JumpCalculator.validateAndRetryJump( + current, new Vector(0, 0, 1), 4, 1, MIN_GAP, DEFAULT_SD, impossible); + + assertNull(result); } private static double dot(Vector a, Vector b) { return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ(); } + + /** Asserts the integer-grid distance between the current block and the placed block. */ + private void assertBlockGap(Location result) { + final int dx = result.getBlockX() - current.getBlockX(); + final int dz = result.getBlockZ() - current.getBlockZ(); + final double gridGap = Math.sqrt(dx * dx + dz * dz); + assertTrue(gridGap + DELTA >= MIN_GAP, + "blocks are adjacent on the grid: dx=" + dx + " dz=" + dz + " gap=" + gridGap); + } } diff --git a/src/test/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacingTest.java b/src/test/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacingTest.java new file mode 100644 index 0000000..41e1dde --- /dev/null +++ b/src/test/java/dev/loki/loparkour/generator/jump/spacing/CourseSpacingTest.java @@ -0,0 +1,61 @@ +package dev.loki.loparkour.generator.jump.spacing; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit tests for the gap-bounds policy between consecutive parkour blocks. + */ +class CourseSpacingTest { + + private static final CourseSpacing DEFAULTS = new CourseSpacing(2, 3, 4, 5); + + @Test + void startSegmentUsesConservativeCap() { + assertEquals(3, DEFAULTS.maxGapFor(0, 1.5)); + assertEquals(3, DEFAULTS.maxGapFor(4, 1.5)); + } + + @Test + void matureCourseGrowsWithDifficulty() { + assertEquals(3, DEFAULTS.maxGapFor(5, 0.0), "no difficulty — stay at the start cap"); + assertEquals(4, DEFAULTS.maxGapFor(5, 1.5), "full difficulty — reach max-gap"); + assertTrue(DEFAULTS.maxGapFor(5, 0.75) >= 3); + assertTrue(DEFAULTS.maxGapFor(5, 0.75) <= 4); + } + + @Test + void minGapNeverRisesAboveMaxGap() { + for (int blocks = 0; blocks < 20; blocks++) { + for (double score = 0.0; score <= 3.0; score += 0.25) { + assertTrue(DEFAULTS.maxGapFor(blocks, score) >= DEFAULTS.minGap(), + "gap cap below the minimum gap at blocks=" + blocks + " score=" + score); + } + } + } + + @Test + void outOfRangeValuesAreSanitized() { + // min-gap above the vanilla reach is clamped, bounds stay ordered. + final CourseSpacing weird = new CourseSpacing(9, 1, 12, -3); + assertEquals(4, weird.minGap()); + assertEquals(4, weird.maxGapFor(0, 1.5)); + assertEquals(4, weird.maxGapFor(100, 1.5)); + } + + @Test + void invertedBoundsAreOrdered() { + final CourseSpacing inverted = new CourseSpacing(3, 1, 2, 5); + assertEquals(3, inverted.minGap()); + assertEquals(3, inverted.maxGapFor(0, 1.5)); + assertEquals(3, inverted.maxGapFor(5, 1.5)); + } + + @Test + void zeroStartJumpsDisablesStartSegment() { + final CourseSpacing noStart = new CourseSpacing(2, 3, 4, 0); + assertEquals(3, noStart.maxGapFor(0, 0.0), "still bounded by the difficulty curve"); + } +}