feat(generator): validate every jump on the block grid and keep 2-4 block gaps

This commit is contained in:
Loki 2026-10-19 20:23:42 +02:00
parent eed73b5c44
commit bfae9f9bc5
Signed by: boba
GPG key ID: 253067914055423B
10 changed files with 496 additions and 146 deletions

View file

@ -2,15 +2,18 @@ package dev.loki.loparkour.config.options.section;
import dev.loki.loparkour.LoParkour; import dev.loki.loparkour.LoParkour;
import dev.loki.loparkour.config.core.Config; 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).
* *
* <p>Block-type weights are not read here — they live in * <p>Block-type weights are not read here — they live in
* {@code GeneratorProfileManager} / {@code GenerationProfileLoader}, which resolve * {@code GeneratorProfileManager} / {@code GenerationProfileLoader}, which resolve
* the {@code advanced.*} paths (see TODO: {@code generation.type|normal|special} * the {@code advanced.*} paths (see TODO: {@code generation.type|normal|special}
* in generation.yml is currently ignored).</p> * in generation.yml is currently ignored).</p>
*/ */
@SuppressWarnings("PMD.TooManyMethods") // flat, static config accessors grouped by section
public final class OptionGeneration { public final class OptionGeneration {
private static final double DEFAULT_MAX_JUMP_DISTANCE = 5.0; 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_TRAIL_KEEP_BEHIND = 10;
private static final int DEFAULT_MIN_Y = 100; private static final int DEFAULT_MIN_Y = 100;
private static final int DEFAULT_MAX_Y = 200; 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() { private OptionGeneration() {
} }
@ -42,10 +51,17 @@ public final class OptionGeneration {
private static double maxVerticalUp; private static double maxVerticalUp;
private static double maxVerticalDown; 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() { public static void init() {
initBounds(); initBounds();
initJumpValidation(); initJumpValidation();
initMemory(); initMemory();
initCourseSpacing();
} }
private static void initBounds() { private static void initBounds() {
@ -82,6 +98,35 @@ public final class OptionGeneration {
? Config.CONFIG.getInt("memory.trail-keep-behind") : DEFAULT_TRAIL_KEEP_BEHIND; ? 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() { public static int maxY() {
return maxY; return maxY;
} }
@ -121,4 +166,24 @@ public final class OptionGeneration {
public static double maxVerticalDown() { public static double maxVerticalDown() {
return 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;
}
} }

View file

@ -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.coordinator.ParkourGenerator;
import dev.loki.loparkour.generator.core.model.GeneratorOption; 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.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.Location;
import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.util.BoundingBox; import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
/** /** Calculates reachable jump positions within the {@link CourseSpacing} gap bounds. */
* Calculates jump positions and validates jump constraints.
*/
public class JumpCalculator { public class JumpCalculator {
private static final int MIN_HEIGHT = -2; private static final int MIN_HEIGHT = -2;
private static final int MAX_VALID_DISTANCE = 4; private static final int MAX_VALID_DISTANCE = 4;
private static final int DEFAULT_MAX_DISTANCE = 4; private static final int MAX_HEIGHT_UP = 1;
private static final int RESTRICTED_MAX_DISTANCE = 3;
private static final double RANDOM_OFFSET_SD = 0.5; private static final double RANDOM_OFFSET_SD = 0.5;
private static final double DEFAULT_RANDOM_OFFSET_SD = 1.0; private static final double DEFAULT_RANDOM_OFFSET_SD = 1.0;
private static final int MAX_RETRY_ATTEMPTS = 10; private static final int MAX_RETRY_ATTEMPTS = 10;
private static final int MAX_REROLL_ATTEMPTS = 3; 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 NO_LATERAL_JITTER = 0.0;
private static final double ZERO_HEADING_EPSILON = 1.0E-6; private static final double ZERO_HEADING_EPSILON = 1.0E-6;
private static final int PACKED_ICE_MAX_DISTANCE = 4; private static final double GAP_EPSILON = 1.0E-6;
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 final ParkourGenerator generator; private final ParkourGenerator generator;
private final BlockSelector blockSelector; private final BlockSelector blockSelector;
private final JumpConstraintsResolver constraintsResolver;
public JumpCalculator(@NotNull ParkourGenerator generator, @NotNull BlockSelector blockSelector) { public JumpCalculator(@NotNull ParkourGenerator generator, @NotNull BlockSelector blockSelector) {
this.generator = generator; this.generator = generator;
this.blockSelector = blockSelector; 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) { public Block calculateNextBlock(@NotNull Block current, int distance, int height) {
if (generator.state.zone() == null || generator.state.zone().length < 2) { if (generator.state.zone() == null || generator.state.zone().length < 2) {
throw new IllegalStateException("Generator zone not initialized"); throw new IllegalStateException("Generator zone not initialized");
@ -61,56 +56,28 @@ public class JumpCalculator {
); );
generator.state.setHeading(director.getRecommendedHeading(generator.state.heading())); 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); int resolvedHeight = director.getRecommendedHeight(height);
final JumpConstraints constraints = calculateJumpConstraints(current);
resolvedHeight = Math.min(resolvedHeight, constraints.maxHeight); resolvedHeight = Math.min(resolvedHeight, constraints.maxHeight);
int resolvedDistance = Math.min(distance, constraints.maxDistance); resolvedHeight = Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT_UP, resolvedHeight));
resolvedHeight = Math.max(MIN_HEIGHT, Math.min(2, resolvedHeight));
resolvedDistance = Math.max(1, Math.min(MAX_VALID_DISTANCE, resolvedDistance));
int resolvedDistance = Math.max(minGap, Math.min(distance, gapCeiling));
if (resolvedHeight > 0) { if (resolvedHeight > 0) {
resolvedDistance = Math.max(resolvedDistance - resolvedHeight, 1); resolvedDistance = Math.max(resolvedDistance - resolvedHeight, minGap);
} }
final double randomOffsetSd = Arrays.asList(generator.generatorOptions) final double randomOffsetSd = Arrays.asList(generator.generatorOptions)
.contains(GeneratorOption.REDUCE_RANDOM_BLOCK_SELECTION_ANGLE) ? RANDOM_OFFSET_SD : DEFAULT_RANDOM_OFFSET_SD; .contains(GeneratorOption.REDUCE_RANDOM_BLOCK_SELECTION_ANGLE) ? RANDOM_OFFSET_SD : DEFAULT_RANDOM_OFFSET_SD;
final Location candidate = validateAndRetryJump(current.getLocation(), generator.state.heading(), final Location candidate = validateAndRetryJump(current.getLocation(), generator.state.heading(),
resolvedDistance, resolvedHeight, ThreadLocalRandom.current(), randomOffsetSd); resolvedDistance, resolvedHeight, minGap, randomOffsetSd);
return candidate.getBlock(); return candidate == null ? null : 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);
} }
@NotNull @NotNull
@ -130,71 +97,83 @@ public class JumpCalculator {
return Math.min(new JumpOffsetGenerator(height, distance).getRandomOffset(0, standardDeviation, random), maxJitter); 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, static Location validateAndRetryJump(@NotNull Location current, @NotNull Vector heading, int distance, int height,
@NotNull Random random, double randomOffsetSd) { int minGap, double randomOffsetSd) {
final JumpValidator validator = new JumpValidator(); return validateAndRetryJump(current, heading, distance, height, minGap, randomOffsetSd, 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);
} }
@NotNull /** Package-visible variant with an injectable validator for tests. */
static Location safetyFallback(@NotNull Location current, @NotNull Vector heading, double randomOffsetSd, @Nullable
@NotNull Random random, @NotNull JumpValidator validator) { static Location validateAndRetryJump(@NotNull Location current, @NotNull Vector heading, int distance, int height,
for (int i = 0; i < MAX_REROLL_ATTEMPTS; i++) { int minGap, double randomOffsetSd, @NotNull JumpValidator validator) {
final Location reRolled = current.clone().add(offsetFor(heading, SAFETY_STEP_DISTANCE, SAFETY_STEP_HEIGHT, final Random random = ThreadLocalRandom.current();
randomOffset(SAFETY_STEP_HEIGHT, SAFETY_STEP_DISTANCE, randomOffsetSd, random))); final Vector normalized = heading.length() < ZERO_HEADING_EPSILON
if (validator.canJump(current, reRolled)) { ? new Vector(0, 0, 1) : heading.clone().normalize();
return reRolled; 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( return null;
offsetFor(heading, SAFETY_STEP_DISTANCE, SAFETY_STEP_HEIGHT, NO_LATERAL_JITTER));
return validator.canJump(current, straight) ? straight : current;
} }
private int getSpecialMaterialMaxHeight(@NotNull Material material) { /** Snaps a fractional offset to the integer block that will actually be placed. */
return switch (material) { @NotNull
case PACKED_ICE -> 1; private static Location blockAnchor(@NotNull Location current, @NotNull Vector heading, int distance, int height,
case BLUE_ICE -> 1; double randomOffset) {
case ICE -> 0; final Vector offset = offsetFor(heading, distance, height, randomOffset);
case LADDER -> 1; // Floor to the integer block anchor without touching the world (unit tests
default -> 0; // 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 true when the anchor clears the integer grid gap and the jump validator. */
return switch (material) { private static boolean isReachableBlock(@NotNull Location current, @NotNull Location candidate, int minGap,
case PACKED_ICE -> PACKED_ICE_MAX_DISTANCE; @NotNull JumpValidator validator) {
case BLUE_ICE -> BLUE_ICE_MAX_DISTANCE; final int dx = candidate.getBlockX() - current.getBlockX();
case ICE -> ICE_MAX_DISTANCE; final int dz = candidate.getBlockZ() - current.getBlockZ();
case LADDER -> 2; if (dx == 0 && dz == 0) {
default -> DEFAULT_SPECIAL_MAX_DISTANCE; return false;
};
}
public static class JumpConstraints {
public final int maxHeight;
public final int maxDistance;
public JumpConstraints(int maxHeight, int maxDistance) {
this.maxHeight = maxHeight;
this.maxDistance = maxDistance;
} }
final double blockGap = Math.sqrt(dx * dx + dz * dz);
return blockGap + GAP_EPSILON >= minGap && validator.canJump(current, candidate);
} }
} }

View file

@ -78,8 +78,10 @@ public class JumpOffsetGenerator {
} }
private static void warnUnexpectedHeight(int y) { private static void warnUnexpectedHeight(int y) {
dev.loki.loparkour.LoParkour.getPlugin().getLogger() final dev.loki.loparkour.LoParkour plugin = dev.loki.loparkour.LoParkour.getPlugin();
.warning("Unexpected jump height " + y + ", using default maxOffset=2"); if (plugin != null) { // null outside a running server (unit tests)
plugin.getLogger().warning("Unexpected jump height " + y + ", using default maxOffset=2");
}
} }
/** /**

View file

@ -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;
}
}
}

View file

@ -46,7 +46,9 @@ public class BlockTargetSelector {
final int distance = Probs.random(generator.state.distanceChances); final int distance = Probs.random(generator.state.distanceChances);
final int height = forcedHeight != NO_FORCED_HEIGHT ? forcedHeight : Probs.random(generator.state.heightChances); final int height = forcedHeight != NO_FORCED_HEIGHT ? forcedHeight : Probs.random(generator.state.heightChances);
final Block nextBlock = jumpCalculator.calculateNextBlock(current, distance, height); final Block nextBlock = jumpCalculator.calculateNextBlock(current, distance, height);
blocks.add(nextBlock); if (nextBlock != null) {
blocks.add(nextBlock);
}
return blocks; return blocks;
} }
} }

View file

@ -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.
*
* <p>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.</p>
*
* <p>All values are clamped to the vanilla jump reach (1..4 blocks), so a
* misconfigured {@code course-spacing.*} section can never produce unreachable
* gaps.</p>
*/
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));
}
}

View file

@ -150,6 +150,24 @@ jump-validation:
max-vertical-up: 1.25 max-vertical-up: 1.25
max-vertical-down: 3.0 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 optimization =-
memory: memory:
block-cleanup-distance: 20 block-cleanup-distance: 20

View file

@ -12,12 +12,13 @@ generation:
# -= Normal jump chances =- # -= Normal jump chances =-
normal: normal:
# -= Distance chances =- # -= 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: distance:
1: 5
2: 35 2: 35
3: 45 3: 45
4: 15 4: 20
# -= Height chances =- # -= Height chances =-
# The chances of the different heights a jump can have in %. Can be above 100%. # The chances of the different heights a jump can have in %. Can be above 100%.
@ -82,24 +83,27 @@ advanced:
heading: east heading: east
# -= Jump distance weights (advanced.distance.min .. max) =- # -= 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: distance:
min: 1 min: 2
max: 4 max: 4
chances: chances:
1: 25 2: 40
2: 25 3: 40
3: 25 4: 20
4: 25
# -= Vertical step weights (advanced.height.min .. max) =- # -= 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: height:
min: -1 min: -1
max: 2 max: 1
chances: chances:
"-1": 20 "-1": 25
"0": 30 "0": 35
1: 30 1: 40
2: 20
# -= Block type mix (default vs special vs schematic) =- # -= Block type mix (default vs special vs schematic) =-
type: type:

View file

@ -8,10 +8,9 @@ import org.junit.jupiter.api.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.assertEquals; 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; 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 DELTA = 1.0E-6;
private static final double DIAGONAL_UNIT = 0.7071067811865476; private static final double DIAGONAL_UNIT = 0.7071067811865476;
private static final double DEFAULT_SD = 1; private static final double DEFAULT_SD = 1;
private static final int MIN_GAP = 2;
@Mock @Mock
private World world; private World world;
@ -64,20 +64,24 @@ class JumpCalculatorTest {
} }
@Test @Test
void safetyFallbackReturnsValidStepForUnitHeading() { void safetyFallbackReturnsValidMinimalStep() {
final JumpValidator validator = new JumpValidator(); 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.canJump(current, fallback));
assertTrue(validator.calculateHorizontalDistance(current.toVector(), fallback.toVector()) >= MIN_GAP,
"fallback must keep at least the minimum gap");
assertBlockGap(fallback);
} }
@Test @Test
void safetyFallbackReturnsCurrentWhenStraightStepImpossible() { void safetyFallbackReturnsNullWhenEvenMinimalStepUnreachable() {
final JumpValidator validator = new JumpValidator(); // Validator with maxHorizontal < minGap: nothing can ever be placed.
final Location fallback = JumpCalculator.safetyFallback(current, new Vector(100, 0, 0), DEFAULT_SD, new Random(1), validator); 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 @Test
@ -86,10 +90,11 @@ class JumpCalculatorTest {
final Vector heading = new Vector(0, 0, 1); final Vector heading = new Vector(0, 0, 1);
for (int distance = 1; distance <= 4; distance++) { 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( 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), assertTrue(validator.canJump(current, result),
"unreachable block for distance=" + distance + " height=" + height); "unreachable block for distance=" + distance + " height=" + height);
} }
@ -97,14 +102,40 @@ class JumpCalculatorTest {
} }
@Test @Test
void validateAndRetryJumpReturnsCurrentAsLastResort() { void validateAndRetryJumpNeverPlacesAdjacentBlock() {
final Location result = JumpCalculator.validateAndRetryJump( final Vector heading = new Vector(DIAGONAL_UNIT, 0, DIAGONAL_UNIT);
current, new Vector(100, 0, 0), 4, 1, new Random(7), DEFAULT_SD);
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) { private static double dot(Vector a, Vector b) {
return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ(); 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);
}
} }

View file

@ -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");
}
}