commit c56e854dffd317cf1c5af30083c474ee0ff3f9a7 Author: Logan Saso Date: Sat Oct 4 21:30:39 2025 -0700 Vibe code a forcefield renderer diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..38c3dd9 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,11 @@ +{ + "permissions": { + "allow": [ + "WebSearch", + "Bash(./gradlew:*)", + "Bash(jar tf:*)" + ], + "deny": [], + "ask": [] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..59b7c60 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +.gradle/ +build/ +.idea/ +*.iml +*.ipr +*.iws +out/ +bin/ +.classpath +.project +.settings/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c04459f --- /dev/null +++ b/README.md @@ -0,0 +1,93 @@ +# RegionForcefield + +A Minecraft plugin that renders visible particle forcefields around WorldGuard regions that players cannot enter. + +## Features + +- Automatically detects WorldGuard regions with `entry deny` flag +- Renders particle forcefields only visible to players who cannot enter +- Configurable particle color, size, spacing, and render distance +- Supports cuboid and polygonal region types +- Performance-optimized with distance-based rendering +- Clean, readable, and well-documented code + +## Requirements + +- Paper 1.21.8 or higher +- WorldGuard 7.0.14 or higher +- Java 21 + +## Installation + +1. Build the plugin: + ```bash + ./gradlew build + ``` + +2. Copy `build/libs/RegionForcefield-1.0.0.jar` to your server's `plugins/` folder + +3. Restart your server + +4. Configure the plugin by editing `plugins/RegionForcefield/config.yml` + +## Usage + +Once installed, the plugin automatically works with your existing WorldGuard regions: + +1. Create a WorldGuard region: `/rg define myregion` +2. Set the entry flag to deny: `/rg flag myregion entry deny` +3. Players who cannot enter the region will see a cyan forcefield around it + +### Permissions + +Players who are members or owners of a region can enter it even if entry is denied for others. These players will not see the forcefield. + +## Configuration + +Edit `plugins/RegionForcefield/config.yml`: + +```yaml +# Update frequency (20 ticks = 1 second) +update-interval-ticks: 20 + +# Maximum render distance in blocks +max-render-distance: 100 + +# Spacing between particles +particle-spacing: 0.5 + +# Render walls or just edges +render-walls: true + +# Particle color (RGB 0-255) +particle-color: + red: 0 + green: 255 + blue: 255 + +# Particle size (0.5-2.0 recommended) +particle-size: 1.0 +``` + +## Performance Tips + +- Reduce `max-render-distance` for servers with many regions +- Increase `particle-spacing` to reduce particle count +- Set `render-walls: false` to only show edges +- Increase `update-interval-ticks` if you don't need real-time updates + +## Building from Source + +```bash +./gradlew build +``` + +The compiled JAR will be in `build/libs/` + +## License + +This project is provided as-is for educational purposes. + +## Support + +For issues or feature requests, please open an issue on the project repository. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..d0495ea --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + java + id("com.gradleup.shadow") version "9.2.2" +} + +group = "loganintech" +version = "1.0.0" + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://maven.enginehub.org/repo/") +} + +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + compileOnly("com.sk89q.worldguard:worldguard-bukkit:7.0.14") + + implementation("org.jetbrains:annotations:24.1.0") +} + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(21)) +} + +tasks { + shadowJar { + archiveClassifier.set("") + minimize() + } + + processResources { + val props = mapOf("version" to version) + inputs.properties(props) + filteringCharset = "UTF-8" + filesMatching("plugin.yml") { + expand(props) + } + } + + build { + dependsOn(shadowJar) + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..4ea4ae3 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2G +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9bbc975 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@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=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..d7a32c0 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "RegionForcefield" diff --git a/src/main/java/loganintech/regionforcefield/RegionForcefieldPlugin.java b/src/main/java/loganintech/regionforcefield/RegionForcefieldPlugin.java new file mode 100644 index 0000000..d2ac239 --- /dev/null +++ b/src/main/java/loganintech/regionforcefield/RegionForcefieldPlugin.java @@ -0,0 +1,65 @@ +package loganintech.regionforcefield; + +import loganintech.regionforcefield.forcefield.ForcefieldRenderer; +import loganintech.regionforcefield.region.RegionPermissionChecker; +import loganintech.regionforcefield.task.ForcefieldUpdateTask; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; + +/** + * Main plugin class for RegionForcefield. + * Displays particle forcefields around WorldGuard regions that players cannot enter. + */ +public final class RegionForcefieldPlugin extends JavaPlugin { + + private RegionPermissionChecker permissionChecker; + private ForcefieldRenderer forcefieldRenderer; + private ForcefieldUpdateTask updateTask; + + @Override + public void onEnable() { + // Save default config + saveDefaultConfig(); + + // Initialize components + this.permissionChecker = new RegionPermissionChecker(); + this.forcefieldRenderer = new ForcefieldRenderer(this); + + // Start the periodic update task + this.updateTask = new ForcefieldUpdateTask(this, permissionChecker, forcefieldRenderer); + long updateInterval = getConfig().getLong("update-interval-ticks", 20L); + updateTask.runTaskTimer(this, 0L, updateInterval); + + getLogger().info("RegionForcefield has been enabled!"); + } + + @Override + public void onDisable() { + // Cancel the update task + if (updateTask != null) { + updateTask.cancel(); + } + + getLogger().info("RegionForcefield has been disabled!"); + } + + /** + * Gets the region permission checker. + * + * @return the permission checker + */ + @NotNull + public RegionPermissionChecker getPermissionChecker() { + return permissionChecker; + } + + /** + * Gets the forcefield renderer. + * + * @return the forcefield renderer + */ + @NotNull + public ForcefieldRenderer getForcefieldRenderer() { + return forcefieldRenderer; + } +} diff --git a/src/main/java/loganintech/regionforcefield/forcefield/ForcefieldRenderer.java b/src/main/java/loganintech/regionforcefield/forcefield/ForcefieldRenderer.java new file mode 100644 index 0000000..b559b8c --- /dev/null +++ b/src/main/java/loganintech/regionforcefield/forcefield/ForcefieldRenderer.java @@ -0,0 +1,208 @@ +package loganintech.regionforcefield.forcefield; + +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; +import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * Renders particle forcefields around protected regions. + */ +public class ForcefieldRenderer { + + private final Plugin plugin; + private final double particleSpacing; + private final Particle.DustOptions dustOptions; + + /** + * Creates a new forcefield renderer. + * + * @param plugin the plugin instance + */ + public ForcefieldRenderer(@NotNull Plugin plugin) { + this.plugin = plugin; + this.particleSpacing = plugin.getConfig().getDouble("particle-spacing", 0.5); + + // Get color from config or use default (cyan) + int red = plugin.getConfig().getInt("particle-color.red", 0); + int green = plugin.getConfig().getInt("particle-color.green", 255); + int blue = plugin.getConfig().getInt("particle-color.blue", 255); + float size = (float) plugin.getConfig().getDouble("particle-size", 1.0); + + this.dustOptions = new Particle.DustOptions(Color.fromRGB(red, green, blue), size); + } + + /** + * Renders a forcefield around a region for a specific player. + * + * @param player the player to show the forcefield to + * @param region the region to render + * @param world the world the region is in + */ + public void renderForcefield(@NotNull Player player, @NotNull ProtectedRegion region, @NotNull World world) { + if (region instanceof ProtectedCuboidRegion) { + renderCuboidForcefield(player, (ProtectedCuboidRegion) region, world); + } else if (region instanceof ProtectedPolygonalRegion) { + renderPolygonalForcefield(player, (ProtectedPolygonalRegion) region, world); + } else { + // For other region types, fall back to rendering a bounding box + renderBoundingBoxForcefield(player, region, world); + } + } + + /** + * Renders a forcefield for a cuboid region. + */ + private void renderCuboidForcefield(@NotNull Player player, @NotNull ProtectedCuboidRegion region, @NotNull World world) { + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + + // Render vertical edges + renderVerticalEdges(player, world, min, max); + + // Render horizontal edges at top and bottom + renderHorizontalEdges(player, world, min, max); + + // Optionally render faces (walls) + if (plugin.getConfig().getBoolean("render-walls", true)) { + renderWalls(player, world, min, max); + } + } + + /** + * Renders a forcefield for a polygonal region. + */ + private void renderPolygonalForcefield(@NotNull Player player, @NotNull ProtectedPolygonalRegion region, @NotNull World world) { + List points = region.getPoints(); + int minY = region.getMinimumPoint().y(); + int maxY = region.getMaximumPoint().y(); + + // Render vertical walls between each pair of points + for (int i = 0; i < points.size(); i++) { + BlockVector2 point1 = points.get(i); + BlockVector2 point2 = points.get((i + 1) % points.size()); + + renderVerticalWall(player, world, point1.x(), point1.z(), point2.x(), point2.z(), minY, maxY); + } + } + + /** + * Renders a bounding box forcefield for unsupported region types. + */ + private void renderBoundingBoxForcefield(@NotNull Player player, @NotNull ProtectedRegion region, @NotNull World world) { + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + + renderVerticalEdges(player, world, min, max); + renderHorizontalEdges(player, world, min, max); + } + + /** + * Renders the vertical edges of a cuboid. + */ + private void renderVerticalEdges(@NotNull Player player, @NotNull World world, @NotNull BlockVector3 min, @NotNull BlockVector3 max) { + // Four vertical edges + renderLine(player, world, min.x(), min.y(), min.z(), min.x(), max.y(), min.z()); + renderLine(player, world, max.x(), min.y(), min.z(), max.x(), max.y(), min.z()); + renderLine(player, world, min.x(), min.y(), max.z(), min.x(), max.y(), max.z()); + renderLine(player, world, max.x(), min.y(), max.z(), max.x(), max.y(), max.z()); + } + + /** + * Renders the horizontal edges of a cuboid. + */ + private void renderHorizontalEdges(@NotNull Player player, @NotNull World world, @NotNull BlockVector3 min, @NotNull BlockVector3 max) { + // Bottom edges + renderLine(player, world, min.x(), min.y(), min.z(), max.x(), min.y(), min.z()); + renderLine(player, world, min.x(), min.y(), max.z(), max.x(), min.y(), max.z()); + renderLine(player, world, min.x(), min.y(), min.z(), min.x(), min.y(), max.z()); + renderLine(player, world, max.x(), min.y(), min.z(), max.x(), min.y(), max.z()); + + // Top edges + renderLine(player, world, min.x(), max.y(), min.z(), max.x(), max.y(), min.z()); + renderLine(player, world, min.x(), max.y(), max.z(), max.x(), max.y(), max.z()); + renderLine(player, world, min.x(), max.y(), min.z(), min.x(), max.y(), max.z()); + renderLine(player, world, max.x(), max.y(), min.z(), max.x(), max.y(), max.z()); + } + + /** + * Renders the walls (faces) of a cuboid. + */ + private void renderWalls(@NotNull Player player, @NotNull World world, @NotNull BlockVector3 min, @NotNull BlockVector3 max) { + // North wall (min Z) + renderVerticalWall(player, world, min.x(), min.z(), max.x(), min.z(), min.y(), max.y()); + + // South wall (max Z) + renderVerticalWall(player, world, min.x(), max.z(), max.x(), max.z(), min.y(), max.y()); + + // West wall (min X) + renderVerticalWall(player, world, min.x(), min.z(), min.x(), max.z(), min.y(), max.y()); + + // East wall (max X) + renderVerticalWall(player, world, max.x(), min.z(), max.x(), max.z(), min.y(), max.y()); + } + + /** + * Renders a vertical wall between two points. + */ + private void renderVerticalWall(@NotNull Player player, @NotNull World world, + double x1, double z1, double x2, double z2, + double minY, double maxY) { + double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(z2 - z1, 2)); + int horizontalSteps = (int) Math.ceil(distance / particleSpacing); + int verticalSteps = (int) Math.ceil((maxY - minY) / particleSpacing); + + for (int i = 0; i <= horizontalSteps; i++) { + double t = horizontalSteps > 0 ? (double) i / horizontalSteps : 0; + double x = x1 + (x2 - x1) * t; + double z = z1 + (z2 - z1) * t; + + for (int j = 0; j <= verticalSteps; j++) { + double y = minY + (maxY - minY) * ((double) j / verticalSteps); + spawnParticle(player, world, x, y, z); + } + } + } + + /** + * Renders a line of particles between two points. + */ + private void renderLine(@NotNull Player player, @NotNull World world, + double x1, double y1, double z1, + double x2, double y2, double z2) { + double distance = Math.sqrt( + Math.pow(x2 - x1, 2) + + Math.pow(y2 - y1, 2) + + Math.pow(z2 - z1, 2) + ); + + int steps = (int) Math.ceil(distance / particleSpacing); + + for (int i = 0; i <= steps; i++) { + double t = steps > 0 ? (double) i / steps : 0; + double x = x1 + (x2 - x1) * t; + double y = y1 + (y2 - y1) * t; + double z = z1 + (z2 - z1) * t; + + spawnParticle(player, world, x, y, z); + } + } + + /** + * Spawns a single particle at the specified location for a player. + */ + private void spawnParticle(@NotNull Player player, @NotNull World world, double x, double y, double z) { + Location location = new Location(world, x, y, z); + player.spawnParticle(Particle.DUST, location, 1, 0, 0, 0, 0, dustOptions); + } +} diff --git a/src/main/java/loganintech/regionforcefield/region/RegionPermissionChecker.java b/src/main/java/loganintech/regionforcefield/region/RegionPermissionChecker.java new file mode 100644 index 0000000..c72d9f6 --- /dev/null +++ b/src/main/java/loganintech/regionforcefield/region/RegionPermissionChecker.java @@ -0,0 +1,74 @@ +package loganintech.regionforcefield.region; + +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldguard.LocalPlayer; +import com.sk89q.worldguard.WorldGuard; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.flags.Flags; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.HashSet; +import java.util.Set; + +/** + * Checks whether players have permission to enter WorldGuard regions. + */ +public class RegionPermissionChecker { + + /** + * Gets all regions in a world that the specified player cannot enter. + * + * @param player the player to check + * @param world the world to check regions in + * @return a set of regions the player cannot enter + */ + @NotNull + public Set getBlockedRegions(@NotNull Player player, @NotNull World world) { + Set blockedRegions = new HashSet<>(); + + // Get the region manager for this world + RegionManager regionManager = WorldGuard.getInstance() + .getPlatform() + .getRegionContainer() + .get(BukkitAdapter.adapt(world)); + + if (regionManager == null) { + return blockedRegions; + } + + // Convert Bukkit player to WorldGuard LocalPlayer + LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player); + + // Check each region + for (ProtectedRegion region : regionManager.getRegions().values()) { + if (!canEnterRegion(localPlayer, region)) { + blockedRegions.add(region); + } + } + + return blockedRegions; + } + + /** + * Checks if a player can enter a specific region. + * + * @param player the player to check + * @param region the region to check + * @return true if the player can enter, false otherwise + */ + private boolean canEnterRegion(@NotNull LocalPlayer player, @NotNull ProtectedRegion region) { + // Check the ENTRY flag + // If ENTRY is set to DENY, the player cannot enter unless they have bypass permissions + if (region.getFlag(Flags.ENTRY) == com.sk89q.worldguard.protection.flags.StateFlag.State.DENY) { + // Check if the player is a member or owner of the region + return region.isMember(player) || region.isOwner(player); + } + + // If ENTRY is not explicitly denied, the player can enter + return true; + } +} diff --git a/src/main/java/loganintech/regionforcefield/task/ForcefieldUpdateTask.java b/src/main/java/loganintech/regionforcefield/task/ForcefieldUpdateTask.java new file mode 100644 index 0000000..7e978d8 --- /dev/null +++ b/src/main/java/loganintech/regionforcefield/task/ForcefieldUpdateTask.java @@ -0,0 +1,82 @@ +package loganintech.regionforcefield.task; + +import loganintech.regionforcefield.RegionForcefieldPlugin; +import loganintech.regionforcefield.forcefield.ForcefieldRenderer; +import loganintech.regionforcefield.region.RegionPermissionChecker; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; + +import java.util.Set; + +/** + * Periodic task that updates and renders forcefields for all online players. + */ +public class ForcefieldUpdateTask extends BukkitRunnable { + + private final RegionForcefieldPlugin plugin; + private final RegionPermissionChecker permissionChecker; + private final ForcefieldRenderer forcefieldRenderer; + private final int maxRenderDistance; + + /** + * Creates a new forcefield update task. + * + * @param plugin the plugin instance + * @param permissionChecker the permission checker + * @param forcefieldRenderer the forcefield renderer + */ + public ForcefieldUpdateTask(@NotNull RegionForcefieldPlugin plugin, + @NotNull RegionPermissionChecker permissionChecker, + @NotNull ForcefieldRenderer forcefieldRenderer) { + this.plugin = plugin; + this.permissionChecker = permissionChecker; + this.forcefieldRenderer = forcefieldRenderer; + this.maxRenderDistance = plugin.getConfig().getInt("max-render-distance", 100); + } + + @Override + public void run() { + // Iterate through all online players + for (Player player : plugin.getServer().getOnlinePlayers()) { + // Get all regions the player cannot enter in their current world + Set blockedRegions = permissionChecker.getBlockedRegions(player, player.getWorld()); + + // Render forcefields for nearby blocked regions + for (ProtectedRegion region : blockedRegions) { + if (isRegionNearPlayer(player, region)) { + forcefieldRenderer.renderForcefield(player, region, player.getWorld()); + } + } + } + } + + /** + * Checks if a region is near enough to a player to render. + * + * @param player the player + * @param region the region + * @return true if the region should be rendered for this player + */ + private boolean isRegionNearPlayer(@NotNull Player player, @NotNull ProtectedRegion region) { + // Get player's position + double playerX = player.getLocation().getX(); + double playerY = player.getLocation().getY(); + double playerZ = player.getLocation().getZ(); + + // Get region's center (approximate) + double regionCenterX = (region.getMinimumPoint().x() + region.getMaximumPoint().x()) / 2.0; + double regionCenterY = (region.getMinimumPoint().y() + region.getMaximumPoint().y()) / 2.0; + double regionCenterZ = (region.getMinimumPoint().z() + region.getMaximumPoint().z()) / 2.0; + + // Calculate distance + double distance = Math.sqrt( + Math.pow(playerX - regionCenterX, 2) + + Math.pow(playerY - regionCenterY, 2) + + Math.pow(playerZ - regionCenterZ, 2) + ); + + return distance <= maxRenderDistance; + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..5e3c502 --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1,25 @@ +# RegionForcefield Configuration + +# How often to update forcefields (in ticks, 20 ticks = 1 second) +update-interval-ticks: 20 + +# Maximum distance (in blocks) at which forcefields will be rendered +# Reducing this can improve performance on servers with many regions +max-render-distance: 100 + +# Distance between particles (in blocks) +# Smaller values = more particles = more detailed forcefields but more performance intensive +particle-spacing: 0.5 + +# Whether to render the walls (faces) of regions, or just the edges +# Setting to false will only render the outlines/edges +render-walls: true + +# Particle color (RGB values from 0-255) +particle-color: + red: 0 + green: 255 + blue: 255 + +# Particle size (recommended range: 0.5 to 2.0) +particle-size: 1.0 diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..d348244 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,8 @@ +name: RegionForcefield +version: ${version} +main: loganintech.regionforcefield.RegionForcefieldPlugin +api-version: '1.21' +depend: [WorldGuard] +author: loganintech +description: Renders visible forcefields around WorldGuard regions that players cannot enter +website: https://github.com/loganintech