This commit is contained in:
LZX committed 2026-06-28 16:37:02 +08:00
commit 8593736bf4
117 files changed
+3577

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# Disable autocrlf on generated files, they always generate with LF
# Add any extra files or paths here to make git stop saying they
# are changed when only line endings change.
src/generated/**/.cache/* text eol=lf
src/generated/**/*.json text eol=lf
+30
View File
@@ -0,0 +1,30 @@
name: Build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Setup JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
# This is needed to be able to run ./gradlew below
# You can run `git update-index --chmod +x gradlew` then remove this step.
- name: Make Gradle wrapper executable
run: chmod +x ./gradlew
- name: Build with Gradle
run: ./gradlew build
+40
View File
@@ -0,0 +1,40 @@
### Gradle ###
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/**/build/
### IntelliJ IDEA ###
.idea/
*.iws
*.iml
*.ipr
out/
!**/src/**/out/
.run/
### Eclipse ###
.apt_generated
.classpath
.eclipse/
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/**/bin/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
### Minecraft Modding ###
run/
!**/src/**/run/
**/src/generated/**/.cache/
repo/
!**/src/**/repo/
+25
View File
@@ -0,0 +1,25 @@
Installation information
=======
This template repository can be directly cloned to get you started with a new
mod. Simply create a new repository cloned from this one, by following the
instructions provided by [GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template).
Once you have your clone, simply open the repository in the IDE of your choice. The usual recommendation for an IDE is either IntelliJ IDEA or Eclipse.
If at any point you are missing libraries in your IDE, or you've run into problems you can
run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything
{this does not affect your code} and then start the process again.
Mapping Names:
============
By default, the MDK is configured to use the official mapping names from Mojang for methods and fields
in the Minecraft codebase. These names are covered by a specific license. All modders should be aware of this
license. For the latest license text, refer to the mapping file itself, or the reference copy here:
https://github.com/NeoForged/NeoForm/blob/main/Mojang.md
Additional Resources:
==========
Community Documentation: https://docs.neoforged.net/
NeoForged Discord: https://discord.neoforged.net/
+24
View File
@@ -0,0 +1,24 @@
MIT License
Copyright (c) 2023 NeoForged project
This license applies to the template files as supplied by github.com/NeoForged/MDK
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+195
View File
@@ -0,0 +1,195 @@
plugins {
id 'java-library'
id 'maven-publish'
id 'net.neoforged.moddev' version '2.0.141'
id 'idea'
}
tasks.named('wrapper', Wrapper).configure {
// Define wrapper values here so as to not have to always do so when updating gradlew.properties.
// Switching this to Wrapper.DistributionType.ALL will download the full gradle sources that comes with
// documentation attached on cursor hover of gradle classes and methods. However, this comes with increased
// file size for Gradle. If you do switch this to ALL, run the Gradle wrapper task twice afterwards.
// (Verify by checking gradle/wrapper/gradle-wrapper.properties to see if distributionUrl now points to `-all`)
distributionType = Wrapper.DistributionType.BIN
}
version = mod_version
group = mod_group_id
sourceSets.main.resources {
// Include resources generated by data generators.
srcDir('src/generated/resources')
// Exclude common development only resources from finalized outputs
exclude("**/*.bbmodel") // BlockBench project files
exclude("src/generated/**/.cache") // datagen cache files
}
repositories {
// Add here additional repositories if required by some of the dependencies below.
}
base {
archivesName = mod_id
}
// Mojang ships Java 21 to end users in 1.21.1, so mods should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
neoForge {
// Specify the version of NeoForge to use.
version = project.neo_version
parchment {
mappingsVersion = project.parchment_mappings_version
minecraftVersion = project.parchment_minecraft_version
}
// This line is optional. Access Transformers are automatically detected
// accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
client()
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
server {
server()
programArgument '--nogui'
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
type = "gameTestServer"
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
data {
data()
// example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
// gameDirectory = project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
}
// applies to all the run configs above
configureEach {
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
systemProperty 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
logLevel = org.slf4j.event.Level.DEBUG
}
}
mods {
// define mod <-> source bindings
// these are used to tell the game which sources are for which mod
// multi mod projects should define one per mod
"${mod_id}" {
sourceSet(sourceSets.main)
}
}
}
// Sets up a dependency configuration called 'localRuntime'.
// This configuration should be used instead of 'runtimeOnly' to declare
// a dependency that will be present for runtime testing but that is
// "optional", meaning it will not be pulled by dependents of this mod.
configurations {
runtimeClasspath.extendsFrom localRuntime
}
dependencies {
implementation 'net.objecthunter:exp4j:0.4.8'
jarJar('net.objecthunter:exp4j:0.4.8')
additionalRuntimeClasspath 'net.objecthunter:exp4j:0.4.8'
// Example optional mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
// compileOnly "mezz.jei:jei-${mc_version}-neoforge-api:${jei_version}"
// We add the full version to localRuntime, not runtimeOnly, so that we do not publish a dependency on it
// localRuntime "mezz.jei:jei-${mc_version}-neoforge:${jei_version}"
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// The group id is ignored when searching -- in this case, it is "blank"
// implementation "blank:coolmod-${mc_version}:${coolmod_version}"
// Example mod dependency using a file as dependency
// implementation files("libs/coolmod-${mc_version}-${coolmod_version}.jar")
// Example project dependency using a sister or child project:
// implementation project(":myproject")
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) {
var replaceProperties = [
minecraft_version : minecraft_version,
minecraft_version_range: minecraft_version_range,
neo_version : neo_version,
loader_version_range : loader_version_range,
mod_id : mod_id,
mod_name : mod_name,
mod_license : mod_license,
mod_version : mod_version,
]
inputs.properties replaceProperties
expand replaceProperties
from "src/main/templates"
into "build/generated/sources/modMetadata"
}
// Include the output of "generateModMetadata" as an input directory for the build
// this works with both building through Gradle and the IDE.
sourceSets.main.resources.srcDir generateModMetadata
// To avoid having to run "generateModMetadata" manually, make it run on every project reload
neoForge.ideSyncTask generateModMetadata
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
register('mavenJava', MavenPublication) {
from components.java
}
}
repositories {
maven {
url "file://${project.projectDir}/repo"
}
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior.
idea {
module {
downloadSources = true
downloadJavadoc = true
}
}
+39
View File
@@ -0,0 +1,39 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
org.gradle.jvmargs=-Xmx1G
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=true
#read more on this at https://github.com/neoforged/ModDevGradle?tab=readme-ov-file#better-minecraft-parameter-names--javadoc-parchment
# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started
parchment_minecraft_version=1.21.1
parchment_mappings_version=2024.11.17
# Environment Properties
# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge
# The Minecraft version must agree with the Neo version to get a valid artifact
minecraft_version=1.21.1
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[1.21.1]
# The Neo version must agree with the Minecraft version to get a valid artifact
neo_version=21.1.234
# The loader version range can only use the major version of FML as bounds
loader_version_range=[1,)
## Mod Properties
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=lzxnoneterraria
# The human-readable display name for the mod.
mod_name=Lzxnone Terraria
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved
# The mod version. See https://semver.org/
mod_version=1.0.0
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=com.lzxnone.terraria
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+251
View File
@@ -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="\\\"\\\""
# 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" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@"
Vendored
+94
View File
@@ -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=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
: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
+9
View File
@@ -0,0 +1,9 @@
pluginManagement {
repositories {
gradlePluginPortal()
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
}
@@ -0,0 +1,10 @@
package com.lzxnone.terraria;
import net.neoforged.neoforge.common.ModConfigSpec;
public class Config {
private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder();
static final ModConfigSpec SPEC = BUILDER.build();
}
@@ -0,0 +1,45 @@
package com.lzxnone.terraria;
import com.lzxnone.terraria.block.ModBlocks;
import com.lzxnone.terraria.creative_mode_tab.ModCreativeModeTabs;
import com.lzxnone.terraria.effect.ModEffects;
import com.lzxnone.terraria.entity.ModEntities;
import com.lzxnone.terraria.entity.summon.BeeSummon;
import com.lzxnone.terraria.item.ModItems;
import com.lzxnone.terraria.particle.ModParticles;
import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent;
import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.config.ModConfig;
import net.neoforged.fml.ModContainer;
@Mod(LzxnoneTerraria.MODID)
public class LzxnoneTerraria {
public static final String MODID = "lzxnoneterraria";
public static final Logger LOGGER = LogUtils.getLogger();
public LzxnoneTerraria(IEventBus modEventBus, ModContainer modContainer) {
//注册
ModBlocks.BLOCKS.register(modEventBus);
ModItems.ITEMS.register(modEventBus);
ModEffects.MOB_EFFECTS.register(modEventBus);
ModEntities.ENTITY_TYPES.register(modEventBus);
ModParticles.PARTICLE_TYPES.register(modEventBus);
ModSounds.SOUND_EVENTS.register(modEventBus);
ModCreativeModeTabs.CREATIVE_MODE_TABS.register(modEventBus);
//实体属性创建
modEventBus.addListener(this::onEntityAttributeCreation);
//配置
modContainer.registerConfig(ModConfig.Type.COMMON, Config.SPEC);
}
public void onEntityAttributeCreation(EntityAttributeCreationEvent event) {
event.put(ModEntities.BEE_SUMMON.get(), BeeSummon.createAttributes().build());
}
}
@@ -0,0 +1,43 @@
package com.lzxnone.terraria;
import com.lzxnone.terraria.entity.ModEntities;
import com.lzxnone.terraria.entity.projectile.TextureProjectileRenderer;
import com.lzxnone.terraria.particle.*;
import net.minecraft.client.renderer.entity.BeeRenderer;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.client.event.EntityRenderersEvent;
import net.neoforged.neoforge.client.event.RegisterParticleProvidersEvent;
import net.neoforged.neoforge.client.gui.ConfigurationScreen;
import net.neoforged.neoforge.client.gui.IConfigScreenFactory;
@Mod(value = LzxnoneTerraria.MODID, dist = Dist.CLIENT)
public class LzxnoneTerrariaClient {
public LzxnoneTerrariaClient(ModContainer container, IEventBus modEventBus) {
container.registerExtensionPoint(IConfigScreenFactory.class, ConfigurationScreen::new);
//Entity渲染
modEventBus.addListener(EntityRenderersEvent.RegisterRenderers.class, event -> {
event.registerEntityRenderer(ModEntities.TEXTURE_PROJECTILE.get(), TextureProjectileRenderer::new);
});
modEventBus.addListener(EntityRenderersEvent.RegisterRenderers.class, event -> {
event.registerEntityRenderer(ModEntities.BEE_SUMMON.get(), BeeRenderer::new);
});
//粒子渲染
modEventBus.addListener(RegisterParticleProvidersEvent.class, event -> {
event.registerSpriteSet(ModParticles.DUST_PARTICLE.get(), DustParticle.Provider::new);
});
modEventBus.addListener(RegisterParticleProvidersEvent.class, event -> {
event.registerSpriteSet(ModParticles.STAR_PARTICLE.get(), StarParticle.Provider::new);
});
modEventBus.addListener(RegisterParticleProvidersEvent.class, event -> {
event.registerSpriteSet(ModParticles.EXPLODE_PARTICLE.get(), ExplodeParticle.Provider::new);
});
modEventBus.addListener(RegisterParticleProvidersEvent.class, event -> {
event.registerSpriteSet(ModParticles.SEEDLER_THORN_PARTICLE.get(), SeedlerThornParticle.Provider::new);
});
}
}
@@ -0,0 +1,38 @@
package com.lzxnone.terraria;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvent;
import net.neoforged.neoforge.registries.DeferredRegister;
import java.util.function.Supplier;
public class ModSounds {
public static final DeferredRegister<SoundEvent> SOUND_EVENTS =
DeferredRegister.create(Registries.SOUND_EVENT, LzxnoneTerraria.MODID);
public static final Supplier<SoundEvent> BEAM =
SOUND_EVENTS.register("beam",
() -> SoundEvent.createVariableRangeEvent(
ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "beam")));
public static final Supplier<SoundEvent> MAX_MANA =
SOUND_EVENTS.register("max_mana",
() -> SoundEvent.createVariableRangeEvent(
ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "max_mana")));
public static final Supplier<SoundEvent> WAVE =
SOUND_EVENTS.register("wave",
() -> SoundEvent.createVariableRangeEvent(
ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "wave")));
public static final Supplier<SoundEvent> STAR_FALL =
SOUND_EVENTS.register("star_fall",
() -> SoundEvent.createVariableRangeEvent(
ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "star_fall")));
public static final Supplier<SoundEvent> STAR_COLLIDE =
SOUND_EVENTS.register("star_collide",
() -> SoundEvent.createVariableRangeEvent(
ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "star_collide")));
public static final Supplier<SoundEvent> BOOM =
SOUND_EVENTS.register("boom",
() -> SoundEvent.createVariableRangeEvent(
ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "boom")));
}
@@ -0,0 +1,8 @@
package com.lzxnone.terraria.block;
import com.lzxnone.terraria.LzxnoneTerraria;
import net.neoforged.neoforge.registries.DeferredRegister;
public class ModBlocks {
public static final DeferredRegister.Blocks BLOCKS = DeferredRegister.createBlocks(LzxnoneTerraria.MODID);
}
@@ -0,0 +1,32 @@
package com.lzxnone.terraria.creative_mode_tab;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.lzxnone.terraria.item.ModItems;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.CreativeModeTabs;
import net.neoforged.neoforge.registries.DeferredHolder;
import net.neoforged.neoforge.registries.DeferredRegister;
public class ModCreativeModeTabs {
public static final DeferredRegister<CreativeModeTab> CREATIVE_MODE_TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, LzxnoneTerraria.MODID);
public static final DeferredHolder<CreativeModeTab, CreativeModeTab> WEAPON_TAB = CREATIVE_MODE_TABS.register("weapon_tab", () -> CreativeModeTab.builder()
.title(Component.translatable("itemGroup.lzxnoneterraria.weapon"))
.withTabsBefore(CreativeModeTabs.COMBAT)
.icon(() -> ModItems.TERRA_BLADE.get().getDefaultInstance())
.displayItems((parameters, output) -> {
output.accept(ModItems.COPPER_SHORTSWORD.get());
output.accept(ModItems.ENCHANTED_SWORD.get());
output.accept(ModItems.BEE_KEEPER.get());
output.accept(ModItems.STARFURY.get());
output.accept(ModItems.SEEDLER.get());
output.accept(ModItems.THE_HORSEMANS_BLADE.get());
output.accept(ModItems.INFLUX_WAVER.get());
output.accept(ModItems.STAR_WRATH.get());
output.accept(ModItems.MEOWMERE.get());
output.accept(ModItems.TERRA_BLADE.get());
output.accept(ModItems.ZENITH.get());
}).build());
}
@@ -0,0 +1,10 @@
package com.lzxnone.terraria.effect;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectCategory;
public class ConfusedEffect extends MobEffect {
public ConfusedEffect() {
super(MobEffectCategory.HARMFUL, 0xFF00FF);
}
}
@@ -0,0 +1,67 @@
package com.lzxnone.terraria.effect;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.client.event.RenderLivingEvent;
import org.joml.Matrix4f;
@EventBusSubscriber(modid = LzxnoneTerraria.MODID, value = Dist.CLIENT)
public class EffectIconRenderer {
private static final ResourceLocation CONFUSED_ICON =
ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "textures/mob_effect_display/confused.png");
@SubscribeEvent
public static void onRenderLiving(RenderLivingEvent.Post<?, ?> event) {
LivingEntity entity = event.getEntity();
if(entity.hasEffect(ModEffects.CONFUSED)) {
renderIcon(event, CONFUSED_ICON);
}
}
public static void renderIcon(RenderLivingEvent.Post<?, ?> event, ResourceLocation icon) {
LivingEntity entity = event.getEntity();
PoseStack poseStack = event.getPoseStack();
MultiBufferSource buffer = event.getMultiBufferSource();
poseStack.pushPose();
float heightOffset = entity.getBbHeight() + 0.8F;
poseStack.translate(0.0F, heightOffset, 0.0F);
float partialTicks = event.getPartialTick();
float headYaw = net.minecraft.util.Mth.rotLerp(partialTicks, entity.yHeadRotO, entity.yHeadRot);
poseStack.mulPose(com.mojang.math.Axis.YP.rotationDegrees(-headYaw));
float scale = 0.5F;
poseStack.scale(scale, -scale, scale);
Matrix4f matrix = poseStack.last().pose();
VertexConsumer builder = buffer.getBuffer(RenderType.entityCutoutNoCull(icon));
// 光照
int light = event.getPackedLight();
builder.addVertex(matrix, -0.5F, -0.5F, 0).setColor(255, 255, 255, 255)
.setUv(0, 0).setOverlay(OverlayTexture.NO_OVERLAY).setLight(light).setNormal(0, 0, -1);
builder.addVertex(matrix, -0.5F, 0.5F, 0).setColor(255, 255, 255, 255)
.setUv(0, 1).setOverlay(OverlayTexture.NO_OVERLAY).setLight(light).setNormal(0, 0, -1);
builder.addVertex(matrix, 0.5F, 0.5F, 0).setColor(255, 255, 255, 255)
.setUv(1, 1).setOverlay(OverlayTexture.NO_OVERLAY).setLight(light).setNormal(0, 0, -1);
builder.addVertex(matrix, 0.5F, -0.5F, 0).setColor(255, 255, 255, 255)
.setUv(1, 0).setOverlay(OverlayTexture.NO_OVERLAY).setLight(light).setNormal(0, 0, -1);
poseStack.popPose();
}
}
@@ -0,0 +1,58 @@
package com.lzxnone.terraria.effect;
import com.lzxnone.terraria.LzxnoneTerraria;
import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket;
import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.player.Player;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.entity.living.MobEffectEvent;
import net.neoforged.neoforge.event.tick.EntityTickEvent;
@EventBusSubscriber(modid = LzxnoneTerraria.MODID)
public class EffectLogicHandler {
@SubscribeEvent
public static void onEffectAdded(MobEffectEvent.Added event) {
LivingEntity entity = event.getEntity();
if(!entity.level().isClientSide() && !(entity instanceof Player)) {
if(entity.level() instanceof ServerLevel serverLevel) {
serverLevel.getChunkSource().broadcast(entity,
new ClientboundUpdateMobEffectPacket(entity.getId(), event.getEffectInstance(), false));
}
}
}
@SubscribeEvent
public static void onEffectRemoved(MobEffectEvent.Remove event) {
LivingEntity entity = event.getEntity();
if(!entity.level().isClientSide() && !(entity instanceof Player)) {
if(entity.level() instanceof ServerLevel serverLevel) {
serverLevel.getChunkSource().broadcast(entity,
new ClientboundRemoveMobEffectPacket(entity.getId(), event.getEffectInstance().getEffect()));
}
}
}
@SubscribeEvent
public static void onEffectExpired(MobEffectEvent.Expired event) {
LivingEntity entity = event.getEntity();
if (!entity.level().isClientSide() && !(entity instanceof Player)) {
if (entity.level() instanceof ServerLevel serverLevel) {
serverLevel.getChunkSource().broadcast(entity,
new ClientboundRemoveMobEffectPacket(entity.getId(), event.getEffectInstance().getEffect()));
}
}
}
@SubscribeEvent
public static void onLivingTick(EntityTickEvent.Post event) {
if(!event.getEntity().level().isClientSide() && event.getEntity() instanceof PathfinderMob mob) {
}
}
}
@@ -0,0 +1,15 @@
package com.lzxnone.terraria.effect;
import com.lzxnone.terraria.LzxnoneTerraria;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.effect.MobEffect;
import net.neoforged.neoforge.registries.DeferredHolder;
import net.neoforged.neoforge.registries.DeferredRegister;
public class ModEffects {
public static final DeferredRegister<MobEffect> MOB_EFFECTS =
DeferredRegister.create(BuiltInRegistries.MOB_EFFECT, LzxnoneTerraria.MODID);
public static final DeferredHolder<MobEffect, ConfusedEffect> CONFUSED =
MOB_EFFECTS.register("confused", ConfusedEffect::new);
}
@@ -0,0 +1,33 @@
package com.lzxnone.terraria.entity;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.lzxnone.terraria.entity.projectile.TextureProjectile;
import com.lzxnone.terraria.entity.summon.BeeSummon;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.neoforged.neoforge.registries.DeferredRegister;
import java.util.function.Supplier;
public class ModEntities {
public static final DeferredRegister<EntityType<?>> ENTITY_TYPES =
DeferredRegister.create(Registries.ENTITY_TYPE, LzxnoneTerraria.MODID);
public static final Supplier<EntityType<TextureProjectile>> TEXTURE_PROJECTILE =
ENTITY_TYPES.register("texture_projectile", () -> EntityType.Builder.of(
TextureProjectile::new, MobCategory.MISC)
.sized(0.5f, 0.5f)
.clientTrackingRange(1024)
.updateInterval(1)
.build("texture_projectile")
);
public static final Supplier<EntityType<BeeSummon>> BEE_SUMMON =
ENTITY_TYPES.register("bee_summon", () -> EntityType.Builder.of(
BeeSummon::new, MobCategory.MISC)
.sized(0.7F, 0.6F)
.clientTrackingRange(8)
.build("bee_summon")
);
}
@@ -0,0 +1,15 @@
package com.lzxnone.terraria.entity.projectile;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
public interface IProjectileBehavior {
default void onMoving(TextureProjectile projectile) {}
default void onHitEntity(TextureProjectile projectile, EntityHitResult result) {}
default void onHitBlock(TextureProjectile projectile, BlockHitResult result) {}
default void onDied(TextureProjectile projectile) {
if(!projectile.level().isClientSide()) {
projectile.discard();
}
}
}
@@ -0,0 +1,49 @@
package com.lzxnone.terraria.entity.projectile;
import com.lzxnone.terraria.item.weapon.melee.EnchantedSword;
import com.lzxnone.terraria.item.weapon.melee.Seedler;
import com.lzxnone.terraria.item.weapon.melee.Starfury;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import java.util.HashMap;
import java.util.Map;
public class ProjectileBehaviors {
private static final Map<String, IProjectileBehavior> BEHAVIORS = new HashMap<>();
public static final String DEFAULT = "default";
public static final String ENCHANTED_SWORD_BEAM = "enchanted_sword_beam";
public static final String STARFURY_STAR = "starfury_star";
public static final String SEEDLER_NUT = "seedler_nut";
public static final String SEEDLER_THORN = "seedler_thorn";
static {
BEHAVIORS.put(DEFAULT, new IProjectileBehavior() {
@Override
public void onHitEntity(TextureProjectile projectile, EntityHitResult result) {
if(projectile.level().isClientSide()) return;
projectile.discard();
}
@Override
public void onHitBlock(TextureProjectile projectile, BlockHitResult result) {
if(projectile.level().isClientSide()) return;
if(!projectile.level().getBlockState(result.getBlockPos()).getCollisionShape(projectile.level(), result.getBlockPos()).isEmpty()) {
projectile.discard();
}
}
@Override
public void onDied(TextureProjectile projectile) {
projectile.discard();
}
});
BEHAVIORS.put(ENCHANTED_SWORD_BEAM, EnchantedSword.PROJECTILE_BEHAVIOR);
BEHAVIORS.put(STARFURY_STAR, Starfury.PROJECTILE_BEHAVIOR);
BEHAVIORS.put(SEEDLER_NUT, Seedler.NUT_PROJECTILE_BEHAVIOR);
BEHAVIORS.put(SEEDLER_THORN, Seedler.THORN_PROJECTILE_BEHAVIOR);
}
public static IProjectileBehavior getBehavior(String id) {
return BEHAVIORS.getOrDefault(id, BEHAVIORS.get(DEFAULT));
}
}
@@ -0,0 +1,260 @@
package com.lzxnone.terraria.entity.projectile;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.*;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
import org.joml.Vector3f;
public class TextureProjectile extends Projectile {
public static final EntityDataAccessor<String> BEHAVIOR =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.STRING);
public static final EntityDataAccessor<ItemStack> ITEM =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.ITEM_STACK);
public static final EntityDataAccessor<Vector3f> ORIGIN =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.VECTOR3);
public static final EntityDataAccessor<Vector3f> DIRECTION =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.VECTOR3);
public static final EntityDataAccessor<Vector3f> UP =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.VECTOR3);
public static final EntityDataAccessor<Vector3f> RIGHT =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.VECTOR3);
public static final EntityDataAccessor<Float> SCALE_X =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.FLOAT);
public static final EntityDataAccessor<Float> SCALE_Y =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.FLOAT);
public static final EntityDataAccessor<Integer> RXP =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<Integer> RYP =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<Integer> RZP =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<Integer> RXPS =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<Integer> RYPS =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<Integer> RZPS =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<Boolean> GLOW =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.BOOLEAN);
public static final EntityDataAccessor<Integer> AGE =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<Integer> LIFETIME =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.INT);
public static final EntityDataAccessor<String> EXPRESSION_X =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.STRING); //右
public static final EntityDataAccessor<String> EXPRESSION_Y =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.STRING); //上
public static final EntityDataAccessor<String> EXPRESSION_Z =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.STRING); //前
public static final EntityDataAccessor<CompoundTag> CUSTOM_DATA =
SynchedEntityData.defineId(TextureProjectile.class, EntityDataSerializers.COMPOUND_TAG);
public boolean isInit = false;
public Expression exprX;
public Expression exprY;
public Expression exprZ;
public Vec3 prevPos;
public Vec3 prevDeltaMovement;
public boolean positionOverridden = false;
public TextureProjectile(EntityType<TextureProjectile> type, Level level) {
super(type, level);
this.setNoGravity(true);
}
@Override
protected void defineSynchedData(SynchedEntityData.Builder builder) {
builder.define(BEHAVIOR, "default");
builder.define(ITEM, ItemStack.EMPTY);
builder.define(ORIGIN, new Vector3f(0, 0, 0));
builder.define(DIRECTION, new Vector3f(0, 0, 1));
builder.define(UP, new Vector3f(0, 1, 0));
builder.define(RIGHT, new Vector3f(1, 0, 0));
builder.define(SCALE_X, 1.0f);
builder.define(SCALE_Y, 1.0f);
builder.define(RXP, 0);
builder.define(RYP, 0);
builder.define(RZP, 0);
builder.define(RXPS, 0);
builder.define(RYPS, 0);
builder.define(RZPS, 0);
builder.define(GLOW, false);
builder.define(AGE, 0);
builder.define(LIFETIME, 60);
builder.define(EXPRESSION_X, "0");
builder.define(EXPRESSION_Y, "0");
builder.define(EXPRESSION_Z, "0");
builder.define(CUSTOM_DATA, new CompoundTag());
}
@Override
public void onSyncedDataUpdated(EntityDataAccessor<?> key) {
super.onSyncedDataUpdated(key);
if(!isInit) return;
if(key.equals(TextureProjectile.EXPRESSION_Y) && exprY != null) {
this.exprY = new ExpressionBuilder(this.entityData.get(TextureProjectile.EXPRESSION_Y)).variables("t").build();
}else if (key.equals(TextureProjectile.EXPRESSION_Z) && exprZ != null) {
this.exprZ = new ExpressionBuilder(this.entityData.get(TextureProjectile.EXPRESSION_Z)).variables("t").build();
}else if (key.equals(TextureProjectile.EXPRESSION_X) && exprX != null) {
this.exprX = new ExpressionBuilder(this.entityData.get(TextureProjectile.EXPRESSION_X)).variables("t").build();
}
}
@Override
public void tick() {
super.tick();
if(!isInit) {
this.exprX = new ExpressionBuilder(this.entityData.get(EXPRESSION_X)).variables("t").build();
this.exprY = new ExpressionBuilder(this.entityData.get(EXPRESSION_Y)).variables("t").build();
this.exprZ = new ExpressionBuilder(this.entityData.get(EXPRESSION_Z)).variables("t").build();
isInit = true;
}
this.prevPos = this.position();
this.prevDeltaMovement = this.getDeltaMovement();
double valX = this.exprX.setVariable("t", this.entityData.get(AGE)).evaluate();
double valY = this.exprY.setVariable("t", this.entityData.get(AGE)).evaluate();
double valZ = this.exprZ.setVariable("t", this.entityData.get(AGE)).evaluate();
Vector3f origin = this.entityData.get(ORIGIN);
Vector3f right = this.entityData.get(RIGHT);
Vector3f up = this.entityData.get(UP);
Vector3f dir = this.entityData.get(DIRECTION);
double newX = origin.x + (valX * right.x) + (valY * up.x) + (valZ * dir.x);
double newY = origin.y + (valX * right.y) + (valY * up.y) + (valZ * dir.y);
double newZ = origin.z + (valX * right.z) + (valY * up.z) + (valZ * dir.z);
Vec3 nextPos = new Vec3(newX, newY, newZ);
this.setDeltaMovement(nextPos.subtract(this.position()));
HitResult hitResult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity);
if(hitResult.getType() != HitResult.Type.MISS) {
this.onHit(hitResult);
}
if(!this.positionOverridden) {
this.setPos(nextPos);
}
this.positionOverridden = false;
ProjectileBehaviors.getBehavior(this.entityData.get(BEHAVIOR)).onMoving(this);
if(this.entityData.get(AGE) > this.entityData.get(LIFETIME)) {
ProjectileBehaviors.getBehavior(this.entityData.get(BEHAVIOR)).onDied(this);
}
this.entityData.set(AGE, this.entityData.get(AGE) + 1);
}
@Override
protected void addAdditionalSaveData(CompoundTag tag) {
tag.putString("behavior", this.entityData.get(BEHAVIOR));
ItemStack stack = this.entityData.get(ITEM);
if(!stack.isEmpty()) tag.put("item", stack.save(this.level().registryAccess()));
tag.putFloat("originX", this.entityData.get(ORIGIN).x);
tag.putFloat("originY", this.entityData.get(ORIGIN).y);
tag.putFloat("originZ", this.entityData.get(ORIGIN).z);
tag.putFloat("dirX", this.entityData.get(DIRECTION).x);
tag.putFloat("dirY", this.entityData.get(DIRECTION).y);
tag.putFloat("dirZ", this.entityData.get(DIRECTION).z);
tag.putFloat("upX", this.entityData.get(UP).x);
tag.putFloat("upY", this.entityData.get(UP).y);
tag.putFloat("upZ", this.entityData.get(UP).z);
tag.putFloat("rightX", this.entityData.get(RIGHT).x);
tag.putFloat("rightY", this.entityData.get(RIGHT).y);
tag.putFloat("rightZ", this.entityData.get(RIGHT).z);
tag.putFloat("scaleX", this.entityData.get(SCALE_X));
tag.putFloat("scaleY", this.entityData.get(SCALE_Y));
tag.putInt("rxp", this.entityData.get(RXP));
tag.putInt("ryp", this.entityData.get(RYP));
tag.putInt("rzp", this.entityData.get(RZP));
tag.putInt("rxps", this.entityData.get(RXPS));
tag.putInt("ryps", this.entityData.get(RYPS));
tag.putInt("rzps", this.entityData.get(RZPS));
tag.putBoolean("glow", this.entityData.get(GLOW));
tag.putInt("age", this.entityData.get(AGE));
tag.putInt("lifetime", this.entityData.get(LIFETIME));
tag.putString("expressionX", this.entityData.get(EXPRESSION_X));
tag.putString("expressionY", this.entityData.get(EXPRESSION_Y));
tag.putString("expressionZ", this.entityData.get(EXPRESSION_Z));
tag.put("customData", this.entityData.get(CUSTOM_DATA));
}
@Override
protected void readAdditionalSaveData(CompoundTag tag) {
if(tag.contains("behavior")) this.entityData.set(BEHAVIOR, tag.getString("behavior"));
if(tag.contains("item")) {
ItemStack.parse(this.level().registryAccess(), tag.getCompound("item"))
.ifPresent(stack -> this.entityData.set(ITEM, stack));
}
Vector3f origin = new Vector3f();
if(tag.contains("originX")) origin.x = tag.getFloat("originX");
if(tag.contains("originY")) origin.y = tag.getFloat("originY");
if(tag.contains("originZ")) origin.z = tag.getFloat("originZ");
this.entityData.set(ORIGIN, origin);
Vector3f dir = new Vector3f();
if(tag.contains("dirX")) dir.x = tag.getFloat("dirX");
if(tag.contains("dirY")) dir.y = tag.getFloat("dirY");
if(tag.contains("dirZ")) dir.z = tag.getFloat("dirZ");
this.entityData.set(DIRECTION, dir);
Vector3f up = this.entityData.get(UP);
tag.putFloat("upX", up.x);
tag.putFloat("upY", up.y);
tag.putFloat("upZ", up.z);
this.entityData.set(UP, up);
Vector3f right = this.entityData.get(RIGHT);
tag.putFloat("rightX", right.x);
tag.putFloat("rightY", right.y);
tag.putFloat("rightZ", right.z);
this.entityData.set(RIGHT, right);
if(tag.contains("scaleX")) this.entityData.set(SCALE_X, tag.getFloat("scaleX"));
if(tag.contains("scaleY")) this.entityData.set(SCALE_Y, tag.getFloat("scaleY"));
if(tag.contains("rxp")) this.entityData.set(RXP, tag.getInt("rxp"));
if(tag.contains("ryp")) this.entityData.set(RYP, tag.getInt("ryp"));
if(tag.contains("rzp")) this.entityData.set(RZP, tag.getInt("rzp"));
if(tag.contains("rxps")) this.entityData.set(RXPS, tag.getInt("rxps"));
if(tag.contains("ryps")) this.entityData.set(RYPS, tag.getInt("ryps"));
if(tag.contains("rzps")) this.entityData.set(RZPS, tag.getInt("rzps"));
if(tag.contains("glow")) this.entityData.set(GLOW, tag.getBoolean("glow"));
if(tag.contains("age")) this.entityData.set(AGE, tag.getInt("age"));
if(tag.contains("lifetime")) this.entityData.set(LIFETIME, tag.getInt("lifetime"));
if(tag.contains("expressionX")) this.entityData.set(EXPRESSION_X, tag.getString("expressionX"));
if(tag.contains("expressionY")) this.entityData.set(EXPRESSION_Y, tag.getString("expressionY"));
if(tag.contains("expressionZ")) this.entityData.set(EXPRESSION_Z, tag.getString("expressionZ"));
if(tag.contains("customData")) this.entityData.set(CUSTOM_DATA, tag.getCompound("customData"));
}
@Override
public void lerpTo(double x, double y, double z, float yaw, float pitch, int posRotationIncrements) {}
@Override
protected void onHitEntity(EntityHitResult result) {
super.onHitEntity(result);
Entity target = result.getEntity();
Entity owner = this.getOwner();
if(owner != null && target.getUUID().equals(owner.getUUID())) return;
ProjectileBehaviors.getBehavior(this.entityData.get(BEHAVIOR)).onHitEntity(this, result);
}
@Override
protected void onHitBlock(BlockHitResult result) {
super.onHitBlock(result);
ProjectileBehaviors.getBehavior(this.entityData.get(BEHAVIOR)).onHitBlock(this, result);
}
}
@@ -0,0 +1,89 @@
package com.lzxnone.terraria.entity.projectile;
import com.lzxnone.terraria.utils.MathUtil;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
import org.joml.Matrix3f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
public class TextureProjectileRenderer extends EntityRenderer<Entity> {
public TextureProjectileRenderer(EntityRendererProvider.Context context) {
super(context);
}
@Override
public void render(Entity entity, float entityYaw, float partialTick,
PoseStack poseStack, MultiBufferSource bufferSource, int packedLight) {
if(!(entity instanceof TextureProjectile proj)) return;
if(!proj.isInit || proj.getEntityData().get(TextureProjectile.AGE) < 2) return;
ItemStack stack = proj.getEntityData().get(TextureProjectile.ITEM);
if(stack.isEmpty()) return;
float scaleX = proj.getEntityData().get(TextureProjectile.SCALE_X);
float scaleY = proj.getEntityData().get(TextureProjectile.SCALE_Y);
poseStack.pushPose();
// 缩放
poseStack.scale(scaleX, scaleY, scaleX);
// 朝飞行方向旋转
Vec3 velCurrent = entity.getDeltaMovement();
Vec3 velOld = proj.prevDeltaMovement;
Vector3f velForRot;
if(velCurrent.lengthSqr() > 0.0001) {
velForRot = new Vector3f(
(float) Mth.lerp(partialTick, velOld.x, velCurrent.x),
(float) Mth.lerp(partialTick, velOld.y, velCurrent.y),
(float) Mth.lerp(partialTick, velOld.z, velCurrent.z)
);
} else {
velForRot = new Vector3f(proj.getEntityData().get(TextureProjectile.DIRECTION));
}
Vector3f[] dirs = MathUtil.computeProjectileDir(velForRot);
Matrix3f rotMatrix = new Matrix3f().set(dirs[2], dirs[1], dirs[0]);
poseStack.mulPose(new Quaternionf().setFromNormalized(rotMatrix));
poseStack.mulPose(Axis.XP.rotationDegrees(proj.getEntityData().get(TextureProjectile.RXP) + proj.getEntityData().get(TextureProjectile.RXPS) * proj.getEntityData().get(TextureProjectile.AGE)));
poseStack.mulPose(Axis.YP.rotationDegrees(proj.getEntityData().get(TextureProjectile.RYP) + proj.getEntityData().get(TextureProjectile.RYPS) * proj.getEntityData().get(TextureProjectile.AGE)));
poseStack.mulPose(Axis.ZP.rotationDegrees(proj.getEntityData().get(TextureProjectile.RZP) + proj.getEntityData().get(TextureProjectile.RZPS) * proj.getEntityData().get(TextureProjectile.AGE)));
Minecraft.getInstance().getItemRenderer().renderStatic(
stack,
ItemDisplayContext.NONE,
proj.getEntityData().get(TextureProjectile.GLOW) ? LightTexture.FULL_BRIGHT : packedLight,
OverlayTexture.NO_OVERLAY,
poseStack,
bufferSource,
entity.level(),
0
);
poseStack.popPose();
super.render(entity, entityYaw, partialTick, poseStack, bufferSource, packedLight);
}
@Override
public ResourceLocation getTextureLocation(Entity entity) {
return ResourceLocation.parse("lzxnoneterraria:textures/particle/enchanted_sword_beam.png");
}
}
@@ -0,0 +1,184 @@
package com.lzxnone.terraria.entity.summon;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.control.FlyingMoveControl;
import net.minecraft.world.entity.ai.control.LookControl;
import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal;
import net.minecraft.world.entity.animal.Bee;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class BeeSummon extends Bee {
public static final int LIFETIME = 1200;
public static final int MAX_ATTACK_COUNT = 2;
public int customAge = 0;
public int customAttackCount = 0;
public UUID owner = null;
public BeeSummon(EntityType<? extends Bee> entityType, Level level) {
super(entityType, level);
this.moveControl = new FlyingMoveControl(this, 45, true);
this.lookControl = new LookControl(this);
this.navigation = createNavigation(level);
}
public static AttributeSupplier.@NotNull Builder createAttributes() {
return Bee.createAttributes()
.add(Attributes.MAX_HEALTH, MAX_ATTACK_COUNT)
.add(Attributes.SCALE, 0.5)
.add(Attributes.ATTACK_DAMAGE, 2.0)
.add(Attributes.FOLLOW_RANGE, 32);
}
@Override
public void tick() {
super.tick();
if(!this.level().isClientSide()) {
if(owner == null || this.level().getPlayerByUUID(owner) == null) {
discard();
}
this.customAge++;
if(this.customAge >= LIFETIME) {
this.discard();
}
Player player = this.level().getPlayerByUUID(owner);
LivingEntity target = null;
if(player != null) {
LivingEntity playerAttackTarget = player.getLastHurtMob();
if(playerAttackTarget != null && playerAttackTarget.isAlive() && this.distanceToSqr(playerAttackTarget) <= 1024) {
target = playerAttackTarget;
}
if(target == null) {
LivingEntity playerAttacker = player.getLastHurtByMob();
if(playerAttacker != null && playerAttacker.isAlive() && this.distanceToSqr(playerAttacker) <= 1024) {
target = playerAttacker;
}
}
}
if(target != null) {
this.setTarget(target);
}
target = this.getTarget();
if(target != null && target.isAlive()) {
double dist = this.distanceToSqr(target);
if(dist > 256) {
flyTowards(target.getBoundingBox().getCenter(), 1, 0.5);
}else if(dist > 64) {
flyTowards(target.getBoundingBox().getCenter(), 0.75, 0.5);
}else if(dist > 4) {
flyTowards(target.getBoundingBox().getCenter(), 0.5, 0.5);
}else {
this.doHurtTarget(target);
}
}else if(player != null) {
Vec3 hoverPos = player.position().add(0, 1.5, 0);
if(this.distanceToSqr(player) > 64) {
flyTowards(hoverPos, 0.75, 0.5);
}else {
this.setDeltaMovement(this.getDeltaMovement().scale(0.8));
}
}
}
}
private void flyTowards(Vec3 destination, double acceleration, double friction) {
Vec3 myPos = this.getBoundingBox().getCenter();
Vec3 dir = destination.subtract(myPos);
if(dir.lengthSqr() > 0.05) {
dir = dir.normalize().scale(acceleration);
Vec3 newMovement = this.getDeltaMovement().add(dir).scale(friction);
this.setDeltaMovement(newMovement);
this.getLookControl().setLookAt(destination.x, destination.y, destination.z, 30.0F, 30.0F);
this.setYRot((float)(Math.atan2(newMovement.z, newMovement.x) * (180F / Math.PI)) - 90.0F);
}
}
@Override
protected void registerGoals() {
super.registerGoals();
this.goalSelector.removeAllGoals(goal -> true);
this.targetSelector.removeAllGoals(goal -> true);
this.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(this, Monster.class, false));
}
@Override
public boolean doHurtTarget(Entity target) {
if(owner == null) return false;
Player player = this.level().getPlayerByUUID(owner);
if(player == null) return false;
DamageSource damageSource = this.damageSources().mobAttack(player);
boolean isHurt = target.hurt(damageSource, (float) this.getAttributeValue(Attributes.ATTACK_DAMAGE));
if(isHurt) {
this.customAttackCount++;
if(this.customAttackCount >= MAX_ATTACK_COUNT) {
this.discard();
}else {
this.setHealth(this.getHealth() - 1);
}
}
return isHurt;
}
@Override
public boolean isInvulnerable() {
return true;
}
@Override
public boolean isAttackable() {
return false;
}
@Override
public boolean isPickable() {
return false;
}
@Override
public boolean hurt(DamageSource source, float amount) {
return false;
}
@Override
public boolean isPushable() {
return false;
}
@Override
public void addAdditionalSaveData(@NotNull CompoundTag tag) {
super.addAdditionalSaveData(tag);
tag.putInt("customAttackCount", this.customAttackCount);
tag.putInt("customAge", this.customAge);
if(this.owner != null) tag.putUUID("owner", this.owner);
}
@Override
public void readAdditionalSaveData(@NotNull CompoundTag tag) {
super.readAdditionalSaveData(tag);
if(tag.contains("customAttackCount")) this.customAttackCount = tag.getInt("customAttackCount");
if(tag.contains("customAge")) this.customAge = tag.getInt("customAge");
if(tag.contains("owner")) this.owner = tag.getUUID("owner");
}
}
@@ -0,0 +1,64 @@
package com.lzxnone.terraria.goal;
import com.lzxnone.terraria.effect.ModEffects;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.phys.Vec3;
import java.util.EnumSet;
public class ConfusedEffectGoal extends Goal {
private final PathfinderMob mob;
private Vec3 fleePos;
public ConfusedEffectGoal(PathfinderMob mob) {
this.mob = mob;
this.setFlags(EnumSet.of(Goal.Flag.MOVE, Goal.Flag.LOOK));
}
@Override
public boolean canUse() {
return this.mob.hasEffect(ModEffects.CONFUSED) && this.mob.getTarget() != null;
}
@Override
public void start() {
this.updateFleePosition();
}
@Override
public boolean canContinueToUse() {
return this.canUse() && !this.mob.getNavigation().isDone();
}
@Override
public void tick() {
LivingEntity target = this.mob.getTarget();
if(target == null) return;
this.updateFleePosition();
if(this.fleePos != null) {
this.mob.getLookControl().setLookAt(this.fleePos.x, this.fleePos.y, this.fleePos.z);
}
}
private void updateFleePosition() {
LivingEntity target = this.mob.getTarget();
if(target == null) return;
//Vec3 pos = DefaultRandomPos.getPosAway(this.mob, 16, 7, target.position());
//if(pos == null) {
Vec3 revertDirection = this.mob.position().subtract(target.position()).normalize();
Vec3 pos = this.mob.position().add(revertDirection.scale(5.0));
//}
this.fleePos = pos;
this.mob.getNavigation().moveTo(this.fleePos.x, this.fleePos.y, this.fleePos.z, 1);
}
@Override
public void stop() {
this.fleePos = null;
this.mob.getNavigation().stop();
}
}
@@ -0,0 +1,17 @@
package com.lzxnone.terraria.goal;
import com.lzxnone.terraria.LzxnoneTerraria;
import net.minecraft.world.entity.PathfinderMob;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
@EventBusSubscriber(modid = LzxnoneTerraria.MODID)
public class GoalManager {
@SubscribeEvent
public static void onEntityJoin(EntityJoinLevelEvent event) {
if(!event.getLevel().isClientSide() && event.getEntity() instanceof PathfinderMob mob) {
mob.goalSelector.addGoal(0, new ConfusedEffectGoal(mob));
}
}
}
@@ -0,0 +1,10 @@
package com.lzxnone.terraria.item;
import net.neoforged.neoforge.event.entity.player.AttackEntityEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
public interface IItemWaveBehavior {
default void onLeftClickAir(PlayerInteractEvent.LeftClickEmpty event) {}
default void onLeftClickBlock(PlayerInteractEvent.LeftClickBlock event) {}
default void onAttackEntity(AttackEntityEvent event) {}
}
@@ -0,0 +1,23 @@
package com.lzxnone.terraria.item;
import com.lzxnone.terraria.item.weapon.melee.BeeKeeper;
import java.util.HashMap;
import java.util.Map;
public class ItemWaveBehaviors {
private static final Map<String, IItemWaveBehavior> BEHAVIORS = new HashMap<>();
public static final String DEFAULT = "default";
public static final String BEE_KEEPER = "bee_keeper";
static {
BEHAVIORS.put(DEFAULT, new IItemWaveBehavior() {
});
BEHAVIORS.put(BEE_KEEPER, BeeKeeper.ITEM_WAVE_BEHAVIOR);
}
public static IItemWaveBehavior getBehavior(String id) {
return BEHAVIORS.getOrDefault(id, BEHAVIORS.get(DEFAULT));
}
}
@@ -0,0 +1,30 @@
package com.lzxnone.terraria.item;
import com.lzxnone.terraria.LzxnoneTerraria;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.entity.player.AttackEntityEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
@EventBusSubscriber(modid = LzxnoneTerraria.MODID)
public class ModItemEvents {
@SubscribeEvent
public static void onLeftClickAir(PlayerInteractEvent.LeftClickEmpty event) {
ResourceLocation id = BuiltInRegistries.ITEM.getKey(event.getEntity().getMainHandItem().getItem());
if(id.getNamespace().equals("lzxnoneterraria")) ItemWaveBehaviors.getBehavior(id.getPath()).onLeftClickAir(event);
}
@SubscribeEvent
public static void onLeftClickBlock(PlayerInteractEvent.LeftClickBlock event) {
ResourceLocation id = BuiltInRegistries.ITEM.getKey(event.getEntity().getMainHandItem().getItem());
if(id.getNamespace().equals("lzxnoneterraria")) ItemWaveBehaviors.getBehavior(id.getPath()).onLeftClickBlock(event);
}
@SubscribeEvent
public static void onAttackEntity(AttackEntityEvent event) {
ResourceLocation id = BuiltInRegistries.ITEM.getKey(event.getEntity().getMainHandItem().getItem());
if(id.getNamespace().equals("lzxnoneterraria")) ItemWaveBehaviors.getBehavior(id.getPath()).onAttackEntity(event);
}
}
@@ -0,0 +1,40 @@
package com.lzxnone.terraria.item;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.lzxnone.terraria.item.projectile.EnchantedSwordBeam;
import com.lzxnone.terraria.item.projectile.SeedlerNut;
import com.lzxnone.terraria.item.projectile.SeedlerThorn;
import com.lzxnone.terraria.item.projectile.StarfuryStar;
import com.lzxnone.terraria.item.weapon.melee.*;
import net.minecraft.world.item.Item;
import net.neoforged.neoforge.registries.DeferredItem;
import net.neoforged.neoforge.registries.DeferredRegister;
public class ModItems {
public static final DeferredRegister.Items ITEMS = DeferredRegister.createItems(LzxnoneTerraria.MODID);
public static final DeferredItem<CopperShortsword> COPPER_SHORTSWORD = ITEMS.register("copper_shortsword", CopperShortsword::new);
public static final DeferredItem<EnchantedSword> ENCHANTED_SWORD = ITEMS.register("enchanted_sword", EnchantedSword::new);
public static final DeferredItem<Item> BEE_KEEPER = ITEMS.register("bee_keeper", BeeKeeper::new);
public static final DeferredItem<Item> STARFURY = ITEMS.register("starfury", Starfury::new);
public static final DeferredItem<Item> SEEDLER = ITEMS.register("seedler", Seedler::new);
public static final DeferredItem<Item> INFLUX_WAVER = ITEMS.register("influx_waver",
() -> new Item(new Item.Properties()));
public static final DeferredItem<Item> MEOWMERE = ITEMS.register("meowmere",
() -> new Item(new Item.Properties()));
public static final DeferredItem<Item> STAR_WRATH = ITEMS.register("star_wrath",
() -> new Item(new Item.Properties()));
public static final DeferredItem<Item> TERRA_BLADE = ITEMS.register("terra_blade",
() -> new Item(new Item.Properties()));
public static final DeferredItem<Item> THE_HORSEMANS_BLADE = ITEMS.register("the_horsemans_blade",
() -> new Item(new Item.Properties()));
public static final DeferredItem<Item> ZENITH = ITEMS.register("zenith",
() -> new Item(new Item.Properties()));
//弹射物
public static final DeferredItem<EnchantedSwordBeam> ENCHANTED_SWORD_BEAM = ITEMS.register("enchanted_sword_beam", EnchantedSwordBeam::new);
public static final DeferredItem<StarfuryStar> STARFURY_STAR = ITEMS.register("starfury_star", StarfuryStar::new);
public static final DeferredItem<SeedlerNut> SEEDLER_NUT = ITEMS.register("seedler_nut", SeedlerNut::new);
public static final DeferredItem<SeedlerThorn> SEEDLER_THORN = ITEMS.register("seedler_thorn", SeedlerThorn::new);
}
@@ -0,0 +1,58 @@
package com.lzxnone.terraria.item;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Tier;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.block.Block;
public enum ModTiers implements Tier {
COPPER(BlockTags.INCORRECT_FOR_IRON_TOOL, 200, 4.0F, 1.0F, 5, Ingredient.EMPTY),
ENCHANTED_SWORD(BlockTags.INCORRECT_FOR_DIAMOND_TOOL, 500, 6.0F, 3.0F, 14, Ingredient.EMPTY);
private final TagKey<Block> tag;
private final int uses;
private final float speed;
private final float attackDamageBonus;
private final int enchantmentValue;
private final Ingredient repairIngredient;
ModTiers(TagKey<Block> tag, int uses, float speed, float attackDamageBonus, int enchantmentValue, Ingredient repairIngredient) {
this.tag = tag;
this.uses = uses;
this.speed = speed;
this.attackDamageBonus = attackDamageBonus;
this.enchantmentValue = enchantmentValue;
this.repairIngredient = repairIngredient;
}
@Override
public int getUses() {
return this.uses;
}
@Override
public float getSpeed() {
return this.speed;
}
@Override
public float getAttackDamageBonus() {
return this.attackDamageBonus;
}
@Override
public TagKey<Block> getIncorrectBlocksForDrops() {
return this.tag;
}
@Override
public int getEnchantmentValue() {
return this.enchantmentValue;
}
@Override
public Ingredient getRepairIngredient() {
return this.repairIngredient;
}
}
@@ -0,0 +1,9 @@
package com.lzxnone.terraria.item.projectile;
import net.minecraft.world.item.Item;
public class EnchantedSwordBeam extends Item {
public EnchantedSwordBeam() {
super(new Item.Properties());
}
}
@@ -0,0 +1,9 @@
package com.lzxnone.terraria.item.projectile;
import net.minecraft.world.item.Item;
public class SeedlerNut extends Item{
public SeedlerNut() {
super(new Item.Properties());
}
}
@@ -0,0 +1,9 @@
package com.lzxnone.terraria.item.projectile;
import net.minecraft.world.item.Item;
public class SeedlerThorn extends Item {
public SeedlerThorn() {
super(new Item.Properties());
}
}
@@ -0,0 +1,9 @@
package com.lzxnone.terraria.item.projectile;
import net.minecraft.world.item.Item;
public class StarfuryStar extends Item {
public StarfuryStar() {
super(new Item.Properties());
}
}
@@ -0,0 +1,67 @@
package com.lzxnone.terraria.item.weapon.melee;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.lzxnone.terraria.effect.ModEffects;
import com.lzxnone.terraria.entity.ModEntities;
import com.lzxnone.terraria.entity.summon.BeeSummon;
import com.lzxnone.terraria.item.IItemWaveBehavior;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.Tiers;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import net.neoforged.neoforge.event.entity.player.AttackEntityEvent;
public class BeeKeeper extends SwordItem {
public BeeKeeper() {
super(Tiers.IRON, new Item.Properties().attributes(ItemAttributeModifiers.builder()
.add(Attributes.ATTACK_DAMAGE,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_damage"), 5, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.add(Attributes.ATTACK_SPEED,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_speed"), -2.4, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.build()
));
}
public static final IItemWaveBehavior ITEM_WAVE_BEHAVIOR = new IItemWaveBehavior() {
@Override
public void onAttackEntity(AttackEntityEvent event) {
Player player = event.getEntity();
if(!player.level().isClientSide()) {
ItemStack itemStack = player.getMainHandItem();
if(itemStack.isEmpty()) return;
Item item = itemStack.getItem();
if(item instanceof BeeKeeper && !player.getCooldowns().isOnCooldown(item)) {
Entity target = event.getTarget();
if(target instanceof LivingEntity livingTarget) {
livingTarget.addEffect(new MobEffectInstance(
ModEffects.CONFUSED,
40,
0
));
}
int count = player.level().random.nextInt(3) + 1;
while(count-- > 0) {
BeeSummon bee = ModEntities.BEE_SUMMON.get().create(player.level());
if(bee != null) {
bee.owner = player.getUUID();
bee.setPos(target.position());
player.level().addFreshEntity(bee);
}
}
player.getCooldowns().addCooldown(item, 40);
}
}
}
};
}
@@ -0,0 +1,25 @@
package com.lzxnone.terraria.item.weapon.melee;
import com.lzxnone.terraria.LzxnoneTerraria;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Tiers;
import net.minecraft.world.item.component.ItemAttributeModifiers;
public class CopperShortsword extends SwordItem {
public CopperShortsword() {
super(Tiers.STONE, new Item.Properties().attributes(ItemAttributeModifiers.builder()
.add(Attributes.ATTACK_DAMAGE,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_damage"), 2, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.add(Attributes.ATTACK_SPEED,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_speed"), -1, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.build()
));
}
}
@@ -0,0 +1,160 @@
package com.lzxnone.terraria.item.weapon.melee;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.lzxnone.terraria.ModSounds;
import com.lzxnone.terraria.entity.ModEntities;
import com.lzxnone.terraria.entity.projectile.IProjectileBehavior;
import com.lzxnone.terraria.entity.projectile.ProjectileBehaviors;
import com.lzxnone.terraria.entity.projectile.TextureProjectile;
import com.lzxnone.terraria.item.ModItems;
import com.lzxnone.terraria.particle.DustParticleOptions;
import com.lzxnone.terraria.particle.ModParticles;
import com.lzxnone.terraria.utils.MathUtil;
import net.minecraft.core.component.DataComponents;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Tiers;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.Vec3;
import org.joml.Vector3f;
public class EnchantedSword extends SwordItem {
public EnchantedSword() {
super(Tiers.IRON, new Item.Properties().attributes(ItemAttributeModifiers.builder()
.add(Attributes.ATTACK_DAMAGE,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_damage"), 4,
AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.add(Attributes.ATTACK_SPEED,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_speed"), -2.4,
AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.build()
));
}
public static final IProjectileBehavior PROJECTILE_BEHAVIOR = new IProjectileBehavior() {
@Override
public void onMoving(TextureProjectile projectile) {
projectile.level().addParticle(
ModParticles.COLORFUL_PARTICLE,
projectile.getX(), projectile.getY(), projectile.getZ(),
(Math.random() * 2 - 1) * 0.1, (Math.random() * 2 - 1) * 0.1, (Math.random() * 2 - 1) * 0.1
);
}
@Override
public void onHitEntity(TextureProjectile projectile, EntityHitResult result) {
if(!projectile.level().isClientSide()) {
if(result.getEntity() instanceof LivingEntity target) {
if(target.hurt(projectile.damageSources().thrown(projectile, projectile.getOwner()), 5.5f)) {
((ServerLevel) projectile.level()).sendParticles(
ModParticles.COLORFUL_PARTICLE,
projectile.getX(), projectile.getY(), projectile.getZ(),
25,
0.2, 0.2, 0.2,
0.2
);
projectile.discard();
}
}
}
}
@Override
public void onHitBlock(TextureProjectile projectile, BlockHitResult result) {
if(projectile.level().isClientSide()) return;
if(!projectile.level().getBlockState(result.getBlockPos()).getCollisionShape(projectile.level(), result.getBlockPos()).isEmpty()) {
projectile.discard();
}
}
};
@Override
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
ItemStack stack = player.getItemInHand(hand);
if(!level.isClientSide()) {
Vec3 lookVec = player.getLookAngle();
Vector3f[] dirs = MathUtil.computeProjectileDir(
MathUtil.toVector3f(lookVec)
);
TextureProjectile projectile = new TextureProjectile(ModEntities.TEXTURE_PROJECTILE.get(), level);
projectile.setOwner(player);
Vec3 pos = new Vec3(player.getX(), player.getEyeY() - 0.1, player.getZ());
projectile.setPos(pos);
projectile.getEntityData().set(TextureProjectile.BEHAVIOR, ProjectileBehaviors.ENCHANTED_SWORD_BEAM);
projectile.getEntityData().set(TextureProjectile.ORIGIN, MathUtil.toVector3f(pos));
projectile.getEntityData().set(TextureProjectile.DIRECTION, dirs[0]);
projectile.getEntityData().set(TextureProjectile.UP, dirs[1]);
projectile.getEntityData().set(TextureProjectile.RIGHT, dirs[2]);
projectile.getEntityData().set(TextureProjectile.ITEM, new ItemStack(ModItems.ENCHANTED_SWORD_BEAM.get()));
projectile.getEntityData().set(TextureProjectile.SCALE_X, 0.5f);
projectile.getEntityData().set(TextureProjectile.SCALE_Y, 0.5f);
projectile.getEntityData().set(TextureProjectile.RXP, 90);
projectile.getEntityData().set(TextureProjectile.RZP, 45);
projectile.getEntityData().set(TextureProjectile.RYPS, 10);
projectile.getEntityData().set(TextureProjectile.GLOW, true);
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Z, "t");
projectile.setDeltaMovement(MathUtil.toVec3(dirs[0]));
level.addFreshEntity(projectile);
((ServerLevel) player.level()).sendParticles(
ModParticles.COLORFUL_PARTICLE,
player.getX(), player.getY() + 0.5, player.getZ(),
25,
0.2, 0.2, 0.2,
0.2
);
player.level().playSound(null, player, ModSounds.BEAM.get(), SoundSource.PLAYERS, 4.0F, 1.0F);
}
player.getCooldowns().addCooldown(stack.getItem(), 15);
return InteractionResultHolder.sidedSuccess(stack, level.isClientSide());
}
@Override
public void inventoryTick(ItemStack stack, Level level, net.minecraft.world.entity.Entity entity, int slotId, boolean isSelected) {
super.inventoryTick(stack, level, entity, slotId, isSelected);
if(isSelected && entity instanceof Player player) {
boolean currentlyOnCooldown = player.getCooldowns().isOnCooldown(this);
boolean wasOnCooldown = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY)
.copyTag().getBoolean("WasOnCooldown");
if(wasOnCooldown && !currentlyOnCooldown) {
if(level.isClientSide()) {
player.playSound(ModSounds.MAX_MANA.get(), 4.0F, 1.0F);
}else {
((ServerLevel) player.level()).sendParticles(
ModParticles.MAX_MANA_PARTICLE,
player.getX(), player.getY() + 0.5, player.getZ(),
5,
0.2, 0.2, 0.2,
0.2
);
}
}
CustomData.update(DataComponents.CUSTOM_DATA, stack,
tag -> tag.putBoolean("WasOnCooldown", currentlyOnCooldown));
}
}
}
@@ -0,0 +1,303 @@
package com.lzxnone.terraria.item.weapon.melee;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.lzxnone.terraria.ModSounds;
import com.lzxnone.terraria.entity.ModEntities;
import com.lzxnone.terraria.entity.projectile.IProjectileBehavior;
import com.lzxnone.terraria.entity.projectile.ProjectileBehaviors;
import com.lzxnone.terraria.entity.projectile.TextureProjectile;
import com.lzxnone.terraria.item.ModItems;
import com.lzxnone.terraria.particle.ModParticles;
import com.lzxnone.terraria.utils.MathUtil;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.Tiers;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.Vec3;
import net.objecthunter.exp4j.ExpressionBuilder;
import org.joml.Vector3f;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
public class Seedler extends SwordItem {
public Seedler() {
super(Tiers.DIAMOND, new Item.Properties().attributes(ItemAttributeModifiers.builder()
.add(Attributes.ATTACK_DAMAGE,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_damage"), 8, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.add(Attributes.ATTACK_SPEED,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_speed"), -2.4, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.build()
));
}
public static final double GRAVITY = 0.1; //重力
public static final double NORMAL_DAMPING = 0.6;
public static final double TANGENT_DAMPING = 0.9;
public static final IProjectileBehavior NUT_PROJECTILE_BEHAVIOR = new IProjectileBehavior() {
@Override
public void onHitBlock(TextureProjectile projectile, BlockHitResult result) {
if(projectile.level().isClientSide()) return;
int age = projectile.getEntityData().get(TextureProjectile.AGE);
int currentLifetime = projectile.getEntityData().get(TextureProjectile.LIFETIME);
int remainingLifetime = currentLifetime - age;
if(remainingLifetime <= 0) {
this.onDied(projectile);
return;
}
CompoundTag customData = projectile.getEntityData().get(TextureProjectile.CUSTOM_DATA);
double oldVy = customData.getDouble("vy");
double vz = customData.getDouble("vz");
double vy = oldVy - GRAVITY * age;
Vector3f dir = projectile.getEntityData().get(TextureProjectile.DIRECTION);
Vector3f up = projectile.getEntityData().get(TextureProjectile.UP);
Vec3 velocity = new Vec3(
vy * up.x() + vz * dir.x(),
vy * up.y() + vz * dir.y(),
vy * up.z() + vz * dir.z()
);
Vec3 normal = Vec3.atLowerCornerOf(result.getDirection().getNormal());
Vec3 reflected = velocity.subtract(normal.scale(2 * velocity.dot(normal)));
double normalMag = reflected.dot(normal);
Vec3 tangentDir = reflected.subtract(normal.scale(normalMag));
double tangentMag = tangentDir.length();
Vec3 finalVelocity = normal.scale(normalMag * NORMAL_DAMPING);
if(tangentMag > 0.0001) {
finalVelocity = finalVelocity.add(tangentDir.normalize().scale(tangentMag * TANGENT_DAMPING));
}
double newVz = Math.sqrt(finalVelocity.x * finalVelocity.x + finalVelocity.z * finalVelocity.z);
double newVy = finalVelocity.y;
boolean isBounced = false;
//竖直弹射时
if(newVy < 0.1 && newVy > 0.0001) {
newVy = 0;
String newExprY = String.format(Locale.US, "-%.4f*t*t", GRAVITY * 0.5);
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Y, newExprY);
projectile.exprY = new ExpressionBuilder(newExprY).variables("t").build();
}else if(newVy >= 0.1) {
String newExprY = String.format(Locale.US, "%.3f*t - %.4f*t*t", newVy, GRAVITY * 0.5);
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Y, newExprY);
projectile.exprY = new ExpressionBuilder(newExprY).variables("t").build();
}
if(Math.abs(normal.y) >= 0.999 && newVy >= 0.1) isBounced = true;
//水平弹射时
if(newVz < 0.1 && newVz > 0.0001) {
newVz = 0;
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Z, "0");
projectile.exprZ = new ExpressionBuilder("0").variables("t").build();
Vec3 reflectedH = new Vec3(reflected.x, 0, reflected.z).normalize();
Vector3f[] newDirs = MathUtil.computeProjectileDir(MathUtil.toVector3f(reflectedH));
projectile.getEntityData().set(TextureProjectile.DIRECTION, newDirs[0]);
projectile.getEntityData().set(TextureProjectile.RIGHT, newDirs[2]);
}else if(newVz >= 0.1) {
String newExprZ = String.format(Locale.US, "%.3f*t", newVz);
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Z, newExprZ);
projectile.exprZ = new ExpressionBuilder(newExprZ).variables("t").build();
Vec3 reflectedH = new Vec3(reflected.x, 0, reflected.z).normalize();
Vector3f[] newDirs = MathUtil.computeProjectileDir(MathUtil.toVector3f(reflectedH));
projectile.getEntityData().set(TextureProjectile.DIRECTION, newDirs[0]);
projectile.getEntityData().set(TextureProjectile.RIGHT, newDirs[2]);
}
if((Math.abs(normal.x) >= 0.999 || Math.abs(normal.z) >= 0.999) && newVz >= 0.1) isBounced = true;
Vec3 hitPos = result.getLocation();
Vec3 offsetPos = hitPos.add(normal.scale(isBounced ? 0.1 : 0));
projectile.getEntityData().set(TextureProjectile.ORIGIN, MathUtil.toVector3f(offsetPos));
projectile.getEntityData().set(TextureProjectile.AGE, 0);
projectile.getEntityData().set(TextureProjectile.LIFETIME, remainingLifetime);
customData.putDouble("vz", newVz);
customData.putDouble("vy", newVy);
projectile.getEntityData().set(TextureProjectile.CUSTOM_DATA, customData);
projectile.setPos(offsetPos);
projectile.positionOverridden = true;
}
@Override
public void onDied(TextureProjectile projectile) {
if(!projectile.level().isClientSide()) {
Vec3 pos = projectile.position();
Level level = projectile.level();
((ServerLevel) level).sendParticles(
ModParticles.EXPLODE_PARTICLE.get(),
pos.x, pos.y, pos.z, 1, 0.2, 0.2, 0.2, 0.2
);
((ServerLevel) level).sendParticles(
ModParticles.EXPLODE_FLAME_PARTICLE,
pos.x, pos.y, pos.z, 10, 0.2, 0.2, 0.2, 0.2
);
((ServerLevel) level).sendParticles(
ModParticles.SMOKE_PARTICLE,
pos.x, pos.y, pos.z, 10, 0.2, 0.2, 0.2, 0.2
);
level.playSound(null, pos.x, pos.y, pos.z,
ModSounds.BOOM.get(), SoundSource.PLAYERS, 4.0F, 1.0F);
Entity owner = projectile.getOwner();
List<LivingEntity> targets = level.getEntitiesOfClass(
LivingEntity.class,
AABB.ofSize(pos, 64, 64, 64),
e -> e.isAlive() && e != owner && !e.isSpectator()
);
targets.sort(Comparator.comparingDouble(e -> e.distanceToSqr(pos)));
int count = projectile.getRandom().nextInt(4) + 4;
for(int i = 0; i < count; i++) {
Vec3 dir;
if(i < targets.size()) {
Vec3 tPos = targets.get(i).getEyePosition();
dir = new Vec3(tPos.x - pos.x, tPos.y - pos.y, tPos.z - pos.z).normalize();
}else {
float yaw = projectile.getRandom().nextFloat() * (float)Math.PI * 2;
float pitch = (projectile.getRandom().nextFloat() - 0.5f) * 0.5f;
dir = new Vec3(-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch),
Math.cos(yaw) * Math.cos(pitch));
}
Vector3f[] dirs = MathUtil.computeProjectileDir(MathUtil.toVector3f(dir));
TextureProjectile proj = new TextureProjectile(ModEntities.TEXTURE_PROJECTILE.get(), level);
proj.setOwner(owner);
proj.setPos(pos);
proj.getEntityData().set(TextureProjectile.BEHAVIOR, ProjectileBehaviors.SEEDLER_THORN);
proj.getEntityData().set(TextureProjectile.ORIGIN, MathUtil.toVector3f(pos));
proj.getEntityData().set(TextureProjectile.DIRECTION, dirs[0]);
proj.getEntityData().set(TextureProjectile.UP, dirs[1]);
proj.getEntityData().set(TextureProjectile.RIGHT, dirs[2]);
proj.getEntityData().set(TextureProjectile.ITEM, new ItemStack(ModItems.SEEDLER_THORN.get()));
proj.getEntityData().set(TextureProjectile.SCALE_X, 0.5f);
proj.getEntityData().set(TextureProjectile.SCALE_Y, 0.5f);
proj.getEntityData().set(TextureProjectile.RXP, 90);
proj.getEntityData().set(TextureProjectile.LIFETIME, 30);
proj.getEntityData().set(TextureProjectile.EXPRESSION_Z, "t*2");
proj.setDeltaMovement(MathUtil.toVec3(dirs[0]));
level.addFreshEntity(proj);
}
projectile.discard();
}
}
@Override
public void onHitEntity(TextureProjectile projectile, EntityHitResult result) {
if(!projectile.level().isClientSide()) {
if(result.getEntity() instanceof LivingEntity target) {
this.onDied(projectile);
}
}
}
};
public static final IProjectileBehavior THORN_PROJECTILE_BEHAVIOR = new IProjectileBehavior() {
@Override
public void onMoving(TextureProjectile projectile) {
projectile.level().addParticle(
ModParticles.SEEDLER_THORN_PARTICLE.get(),
projectile.getX(), projectile.getY(), projectile.getZ(),
0, 0, 0
);
}
@Override
public void onHitEntity(TextureProjectile projectile, EntityHitResult result) {
if(!projectile.level().isClientSide()) {
if(result.getEntity() instanceof LivingEntity target) {
if(target.hurt(projectile.damageSources().thrown(projectile, projectile.getOwner()), 7f)) projectile.discard();
}
}
}
@Override
public void onHitBlock(TextureProjectile projectile, BlockHitResult result) {
if(projectile.level().isClientSide()) return;
if(!projectile.level().getBlockState(result.getBlockPos()).getCollisionShape(projectile.level(), result.getBlockPos()).isEmpty()) {
projectile.discard();
}
}
};
@Override
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
ItemStack stack = player.getItemInHand(hand);
if(!level.isClientSide()) {
Vec3 lookVec = player.getLookAngle();
float yaw = player.getYRot();
Vec3 horizontalDir = new Vec3(
-Math.sin(yaw * Math.PI / 180),
0,
Math.cos(yaw * Math.PI / 180)
);
Vector3f[] dirs = MathUtil.computeProjectileDir(
MathUtil.toVector3f(horizontalDir)
);
double vz = Math.sqrt(lookVec.x * lookVec.x + lookVec.z * lookVec.z) * 1.5;
double vy = lookVec.y * 1.5;
String exprZ = String.format(Locale.US, "%.3f*t", vz);
String exprY = String.format(Locale.US, "%.3f*t - %.4f*t*t", vy, GRAVITY * 0.5);
CompoundTag customData = new CompoundTag();
customData.putDouble("vz", vz);
customData.putDouble("vy", vy);
TextureProjectile projectile = new TextureProjectile(ModEntities.TEXTURE_PROJECTILE.get(), level);
projectile.setOwner(player);
Vec3 pos = new Vec3(player.getX(), player.getEyeY() - 0.1, player.getZ());
projectile.setPos(pos);
projectile.getEntityData().set(TextureProjectile.BEHAVIOR, ProjectileBehaviors.SEEDLER_NUT);
projectile.getEntityData().set(TextureProjectile.ORIGIN, MathUtil.toVector3f(pos));
projectile.getEntityData().set(TextureProjectile.DIRECTION, dirs[0]);
projectile.getEntityData().set(TextureProjectile.UP, dirs[1]);
projectile.getEntityData().set(TextureProjectile.RIGHT, dirs[2]);
projectile.getEntityData().set(TextureProjectile.ITEM, new ItemStack(ModItems.SEEDLER_NUT.get()));
projectile.getEntityData().set(TextureProjectile.SCALE_X, 0.5f);
projectile.getEntityData().set(TextureProjectile.SCALE_Y, 0.5f);
projectile.getEntityData().set(TextureProjectile.RXPS, 10);
projectile.getEntityData().set(TextureProjectile.LIFETIME, (int) (7 + Math.random() * 36));
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Z, exprZ);
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Y, exprY);
projectile.getEntityData().set(TextureProjectile.CUSTOM_DATA, customData);
projectile.setDeltaMovement(MathUtil.toVec3(dirs[0]));
level.addFreshEntity(projectile);
}
player.getCooldowns().addCooldown(stack.getItem(), 10);
return InteractionResultHolder.sidedSuccess(stack, level.isClientSide());
}
}
@@ -0,0 +1,224 @@
package com.lzxnone.terraria.item.weapon.melee;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.lzxnone.terraria.ModSounds;
import com.lzxnone.terraria.entity.ModEntities;
import com.lzxnone.terraria.entity.projectile.IProjectileBehavior;
import com.lzxnone.terraria.entity.projectile.ProjectileBehaviors;
import com.lzxnone.terraria.entity.projectile.TextureProjectile;
import com.lzxnone.terraria.item.ModItems;
import com.lzxnone.terraria.particle.ModParticles;
import com.lzxnone.terraria.utils.MathUtil;
import net.minecraft.core.component.DataComponents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.Tiers;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.*;
import org.joml.Vector3f;
public class Starfury extends SwordItem {
public Starfury() {
super(Tiers.IRON, new Item.Properties().attributes(ItemAttributeModifiers.builder()
.add(Attributes.ATTACK_DAMAGE,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_damage"), 5, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.add(Attributes.ATTACK_SPEED,
new AttributeModifier(ResourceLocation.fromNamespaceAndPath(LzxnoneTerraria.MODID, "base_attack_speed"), -2.4, AttributeModifier.Operation.ADD_VALUE),
EquipmentSlotGroup.MAINHAND)
.build()
));
}
public static final IProjectileBehavior PROJECTILE_BEHAVIOR = new IProjectileBehavior() {
@Override
public void onMoving(TextureProjectile projectile) {
projectile.level().addParticle(
ModParticles.STAR_PARTICLE.get(),
projectile.getX(), projectile.getY(), projectile.getZ(),
(Math.random() * 2 - 1) * 0.1, (Math.random() * 2 - 1) * 0.1, (Math.random() * 2 - 1) * 0.1
);
}
@Override
public void onHitEntity(TextureProjectile projectile, EntityHitResult result) {
if(!projectile.level().isClientSide()) {
if(result.getEntity() instanceof LivingEntity target) {
target.hurt(projectile.damageSources().thrown(projectile, projectile.getOwner()), 8f);
}
}
}
@Override
public void onHitBlock(TextureProjectile projectile, BlockHitResult result) {
if(projectile.level().isClientSide()) return;
CompoundTag customData = projectile.getEntityData().get(TextureProjectile.CUSTOM_DATA);
if(!customData.contains("targetLifetime")) return;
int targetLifetime = customData.getInt("targetLifetime");
int age = projectile.getEntityData().get(TextureProjectile.AGE);
if(age < targetLifetime + 1) {
EntityHitResult entityHit = ProjectileUtil.getEntityHitResult(
projectile.level(),
projectile,
projectile.position(),
projectile.position().add(projectile.getDeltaMovement()),
projectile.getBoundingBox()
.expandTowards(projectile.getDeltaMovement())
.inflate(1.0),
entity -> !entity.isSpectator() && entity.isPickable() && entity != projectile.getOwner()
);
if(entityHit != null) {
this.onHitEntity(projectile, entityHit);
}
return;
}
if(!projectile.level().getBlockState(result.getBlockPos()).getCollisionShape(projectile.level(), result.getBlockPos()).isEmpty()) {
((ServerLevel) projectile.level()).sendParticles(
ModParticles.STAR_PARTICLE.get(),
projectile.getX(), projectile.getY(), projectile.getZ(),
25,
0.2, 0.2, 0.2,
0.2
);
projectile.level().playSound(null, projectile, ModSounds.STAR_COLLIDE.get(), SoundSource.PLAYERS, 4.0F, 1.0F);
projectile.discard();
}
}
@Override
public void onDied(TextureProjectile projectile) {
if(!projectile.level().isClientSide()) {
projectile.level().playSound(null, projectile, ModSounds.STAR_COLLIDE.get(), SoundSource.PLAYERS, 4.0F, 1.0F);
projectile.discard();
}
}
};
@Override
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
ItemStack itemstack = player.getItemInHand(hand);
if(!level.isClientSide() && level instanceof ServerLevel serverLevel) {
Vec3 targetPos = getTargetPosition(player, serverLevel, 24.0D);
double spawnHeight = 20.0D;
double slantOffset = 2.0D;
Vec3 spawnPos = new Vec3(
targetPos.x + slantOffset * (Math.random() * 2 - 1),
targetPos.y + spawnHeight,
targetPos.z + slantOffset * (Math.random() * 2 - 1)
);
Vector3f[] dirs = MathUtil.computeProjectileDir(
MathUtil.toVector3f(new Vec3(targetPos.x - spawnPos.x, targetPos.y - spawnPos.y, targetPos.z - spawnPos.z))
);
TextureProjectile projectile = new TextureProjectile(ModEntities.TEXTURE_PROJECTILE.get(), level);
projectile.setOwner(player);
projectile.setPos(spawnPos);
projectile.getEntityData().set(TextureProjectile.BEHAVIOR, ProjectileBehaviors.STARFURY_STAR);
projectile.getEntityData().set(TextureProjectile.ORIGIN, MathUtil.toVector3f(spawnPos));
projectile.getEntityData().set(TextureProjectile.ITEM, new ItemStack(ModItems.STARFURY_STAR.get()));
projectile.getEntityData().set(TextureProjectile.LIFETIME, 300);
projectile.getEntityData().set(TextureProjectile.DIRECTION, dirs[0]);
projectile.getEntityData().set(TextureProjectile.UP, dirs[1]);
projectile.getEntityData().set(TextureProjectile.RIGHT, dirs[2]);
projectile.getEntityData().set(TextureProjectile.SCALE_X, 1f);
projectile.getEntityData().set(TextureProjectile.SCALE_Y, 2f);
projectile.getEntityData().set(TextureProjectile.GLOW, true);
projectile.getEntityData().set(TextureProjectile.RXP, 90);
projectile.getEntityData().set(TextureProjectile.RZP, 90);
projectile.getEntityData().set(TextureProjectile.EXPRESSION_Z, "t*2");
CompoundTag customData = new CompoundTag();
customData.putInt("targetLifetime", (int) Math.floor(targetPos.distanceTo(spawnPos) / 2.0D));
projectile.getEntityData().set(TextureProjectile.CUSTOM_DATA, customData);
projectile.setDeltaMovement(MathUtil.toVec3(dirs[0]));
level.addFreshEntity(projectile);
((ServerLevel) player.level()).sendParticles(
ModParticles.STAR_PARTICLE.get(),
player.getX(), player.getY() + 0.5, player.getZ(),
25,
0.2, 0.2, 0.2,
0.2
);
player.level().playSound(null, player, ModSounds.STAR_FALL.get(), SoundSource.PLAYERS, 4.0F, 1.0F);
}
player.getCooldowns().addCooldown(this, 13);
return InteractionResultHolder.sidedSuccess(itemstack, level.isClientSide());
}
private Vec3 getTargetPosition(Player player, Level level, double maxRange) {
Vec3 eyePos = player.getEyePosition(1.0F);
Vec3 lookVec = player.getLookAngle();
Vec3 maxRangeEnd = eyePos.add(lookVec.scale(maxRange));
BlockHitResult blockHit = level.clip(new ClipContext(
eyePos, maxRangeEnd,
ClipContext.Block.COLLIDER,
ClipContext.Fluid.NONE,
player
));
Vec3 finalTarget = maxRangeEnd;
if(blockHit.getType() != HitResult.Type.MISS) {
finalTarget = blockHit.getLocation();
}
AABB searchBox = player.getBoundingBox().expandTowards(lookVec.scale(maxRange)).inflate(1.0D);
EntityHitResult entityHit = ProjectileUtil.getEntityHitResult(
level, player, eyePos, finalTarget, searchBox,
entity -> !entity.isSpectator() && entity.isPickable() && entity != player
);
if(entityHit != null) {
finalTarget = entityHit.getLocation();
}
return finalTarget;
}
@Override
public void inventoryTick(ItemStack stack, Level level, net.minecraft.world.entity.Entity entity, int slotId, boolean isSelected) {
super.inventoryTick(stack, level, entity, slotId, isSelected);
if(isSelected && entity instanceof Player player) {
boolean currentlyOnCooldown = player.getCooldowns().isOnCooldown(this);
boolean wasOnCooldown = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY)
.copyTag().getBoolean("WasOnCooldown");
if(wasOnCooldown && !currentlyOnCooldown) {
if(level.isClientSide()) {
player.playSound(ModSounds.MAX_MANA.get(), 4.0F, 1.0F);
}else {
((ServerLevel) player.level()).sendParticles(
ModParticles.MAX_MANA_PARTICLE,
player.getX(), player.getY() + 0.5, player.getZ(),
5,
0.2, 0.2, 0.2,
0.2
);
}
}
CustomData.update(DataComponents.CUSTOM_DATA, stack,
tag -> tag.putBoolean("WasOnCooldown", currentlyOnCooldown));
}
}
}
@@ -0,0 +1,120 @@
package com.lzxnone.terraria.particle;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Camera;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.*;
import net.minecraft.client.renderer.LightTexture;
import org.joml.Vector3f;
public class DustParticle extends TextureSheetParticle {
private final SpriteSet sprites;
private final float rotSpeed;
private final float baseSize;
public float initSize;
public float initRotSpeed;
public int initLifetime;
public boolean glow;
public Vector3f[] colors = new Vector3f[]{ new Vector3f(1.0F, 1.0F, 1.0F) };
protected DustParticle(ClientLevel level, double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed,
DustParticleOptions options, SpriteSet spriteSet) {
super(level, x, y, z, xSpeed, ySpeed, zSpeed);
this.sprites = spriteSet;
this.friction = 0.9F;
this.gravity = 0.0F;
this.xd = xSpeed;
this.yd = ySpeed;
this.zd = zSpeed;
this.initSize = options.initSize;
this.initRotSpeed = options.initRotSpeed;
this.initLifetime = options.initLifetime;
this.glow = options.glow;
this.baseSize = initSize + (this.random.nextFloat() * initSize);
this.quadSize = baseSize;
this.roll = this.random.nextFloat() * ((float)Math.PI * 2F);
this.oRoll = this.roll;
this.rotSpeed = (this.random.nextFloat() - 0.5F) * initRotSpeed;
this.lifetime = initLifetime + this.random.nextInt(initLifetime / 2);
Vector3f[] palette = options.colors != null ? options.colors : this.colors;
int randomIndex = this.random.nextInt(palette.length);
this.rCol = palette[randomIndex].x;
this.gCol = palette[randomIndex].y;
this.bCol = palette[randomIndex].z;
this.setSpriteFromAge(spriteSet);
}
@Override
public void tick() {
super.tick();
this.oRoll = this.roll;
this.roll += this.rotSpeed;
float lifeRatio = (float) this.age / (float) this.lifetime;
this.quadSize = this.baseSize * (1.0F - lifeRatio);
this.alpha = 1.0F - lifeRatio;
}
@Override
public void render(VertexConsumer buffer, Camera camera, float partialTick) {
if(this.alpha <= 0.01F) return;
float coloredR = this.rCol;
float coloredG = this.gCol;
float coloredB = this.bCol;
this.setSprite(this.sprites.get(0, 1));
this.rCol = coloredR;
this.gCol = coloredG;
this.bCol = coloredB;
super.render(buffer, camera, partialTick);
this.setSprite(this.sprites.get(1, 1));
this.rCol = 1.0F;
this.gCol = 1.0F;
this.bCol = 1.0F;
super.render(buffer, camera, partialTick);
this.rCol = coloredR;
this.gCol = coloredG;
this.bCol = coloredB;
}
@Override
public int getLightColor(float partialTick) {
return glow ? LightTexture.FULL_BRIGHT : super.getLightColor(partialTick);
}
@Override
public ParticleRenderType getRenderType() {
return ModParticleRenderTypes.TRANSLUCENT_EMISSIVE;
}
public static class Provider implements ParticleProvider<DustParticleOptions> {
private final SpriteSet spriteSet;
public Provider(SpriteSet spriteSet) {
this.spriteSet = spriteSet;
}
@Override
public Particle createParticle(DustParticleOptions type, ClientLevel level,
double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed) {
return new DustParticle(level, x, y, z, xSpeed, ySpeed, zSpeed, type, this.spriteSet);
}
}
}
@@ -0,0 +1,89 @@
package com.lzxnone.terraria.particle;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleType;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import org.joml.Vector3f;
import java.util.Arrays;
public class DustParticleOptions implements ParticleOptions {
public final float initSize;
public final float initRotSpeed;
public final int initLifetime;
public final boolean glow;
public final Vector3f[] colors;
public DustParticleOptions(float initSize, float initRotSpeed, int initLifetime,
boolean glow, Vector3f[] colors) {
this.initSize = initSize;
this.initRotSpeed = initRotSpeed;
this.initLifetime = initLifetime;
this.glow = glow;
this.colors = colors;
}
public DustParticleOptions() {
this(0.05f, 0.5f, 40, true, null);
}
@Override
public ParticleType<?> getType() {
return ModParticles.DUST_PARTICLE.get();
}
private static final Codec<Vector3f[]> COLORS_CODEC =
Codec.FLOAT.listOf().listOf().xmap(
lists -> lists.stream().map(l -> new Vector3f(l.get(0), l.get(1), l.get(2))).toArray(Vector3f[]::new),
arr -> Arrays.stream(arr).map(c -> java.util.List.of(c.x, c.y, c.z)).toList()
);
public static final MapCodec<DustParticleOptions> CODEC = RecordCodecBuilder.mapCodec(instance ->
instance.group(
Codec.FLOAT.optionalFieldOf("initSize", 0.05f).forGetter(o -> o.initSize),
Codec.FLOAT.optionalFieldOf("initRotSpeed", 0.5f).forGetter(o -> o.initRotSpeed),
Codec.INT.optionalFieldOf("initLifetime", 40).forGetter(o -> o.initLifetime),
Codec.BOOL.optionalFieldOf("glow", true).forGetter(o -> o.glow),
COLORS_CODEC.optionalFieldOf("colors", null).forGetter(o -> o.colors)
).apply(instance, DustParticleOptions::new)
);
public static final StreamCodec<RegistryFriendlyByteBuf, DustParticleOptions> STREAM_CODEC =
new StreamCodec<>() {
@Override
public DustParticleOptions decode(RegistryFriendlyByteBuf buf) {
float size = buf.readFloat();
float rotSpeed = buf.readFloat();
int lifetime = buf.readInt();
boolean glowFlag = buf.readBoolean();
int colorCount = buf.readVarInt();
Vector3f[] cols = colorCount > 0 ? new Vector3f[colorCount] : null;
for (int i = 0; i < colorCount; i++) {
cols[i] = new Vector3f(buf.readFloat(), buf.readFloat(), buf.readFloat());
}
return new DustParticleOptions(size, rotSpeed, lifetime, glowFlag, cols);
}
@Override
public void encode(RegistryFriendlyByteBuf buf, DustParticleOptions opts) {
buf.writeFloat(opts.initSize);
buf.writeFloat(opts.initRotSpeed);
buf.writeInt(opts.initLifetime);
buf.writeBoolean(opts.glow);
if (opts.colors != null) {
buf.writeVarInt(opts.colors.length);
for (Vector3f c : opts.colors) {
buf.writeFloat(c.x);
buf.writeFloat(c.y);
buf.writeFloat(c.z);
}
} else {
buf.writeVarInt(0);
}
}
};
}
@@ -0,0 +1,66 @@
package com.lzxnone.terraria.particle;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.*;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.core.particles.SimpleParticleType;
public class ExplodeParticle extends TextureSheetParticle {
private final float rotSpeed;
private final float baseSize;
protected ExplodeParticle(ClientLevel level, double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed, SpriteSet spriteSet) {
super(level, x, y, z, xSpeed, ySpeed, zSpeed);
this.friction = 0.9F;
this.gravity = 0.0F;
this.xd = xSpeed;
this.yd = ySpeed;
this.zd = zSpeed;
this.baseSize = 0.5F + (this.random.nextFloat() * 0.1F);
this.quadSize = baseSize;
this.roll = this.random.nextFloat() * ((float)Math.PI * 2F);
this.oRoll = this.roll;
this.rotSpeed = (this.random.nextFloat() - 0.5F) * 0.5F;
this.lifetime = 40 + this.random.nextInt(10);
this.pickSprite(spriteSet);
}
@Override
public void tick() {
super.tick();
this.oRoll = this.roll;
this.roll += this.rotSpeed;
float lifeRatio = (float) this.age / (float) this.lifetime;
this.quadSize = this.baseSize * (1.0F - lifeRatio);
this.alpha = 1.0F - lifeRatio;
}
@Override
public ParticleRenderType getRenderType() {
return ModParticleRenderTypes.TRANSLUCENT_EMISSIVE;
}
public static class Provider implements ParticleProvider<SimpleParticleType> {
private final SpriteSet spriteSet;
public Provider(SpriteSet spriteSet) {
this.spriteSet = spriteSet;
}
@Override
public Particle createParticle(SimpleParticleType type, ClientLevel level,
double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed) {
return new ExplodeParticle(level, x, y, z, xSpeed, ySpeed, zSpeed, this.spriteSet);
}
}
}
@@ -0,0 +1,30 @@
package com.lzxnone.terraria.particle;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.Tesselator;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.ParticleRenderType;
import net.minecraft.client.renderer.texture.TextureManager;
public final class ModParticleRenderTypes {
public static final ParticleRenderType TRANSLUCENT_EMISSIVE = new ParticleRenderType() {
@Override
public BufferBuilder begin(Tesselator tesselator, TextureManager textureManager) {
Minecraft.getInstance().gameRenderer.lightTexture().turnOnLightLayer();
return ParticleRenderType.PARTICLE_SHEET_TRANSLUCENT.begin(tesselator, textureManager);
}
@Override
public String toString() {
return "lzxnoneterraria:translucent_emissive";
}
@Override
public boolean isTranslucent() {
return true;
}
};
private ModParticleRenderTypes() {}
}
@@ -0,0 +1,72 @@
package com.lzxnone.terraria.particle;
import com.lzxnone.terraria.LzxnoneTerraria;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.particles.ParticleType;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.core.particles.SimpleParticleType;
import net.minecraft.core.registries.Registries;
import net.neoforged.neoforge.registries.DeferredRegister;
import org.joml.Vector3f;
import java.util.function.Supplier;
public class ModParticles {
public static final DeferredRegister<ParticleType<?>> PARTICLE_TYPES =
DeferredRegister.create(Registries.PARTICLE_TYPE, LzxnoneTerraria.MODID);
public static final DustParticleOptions MAX_MANA_PARTICLE = new DustParticleOptions(
0.25f, 0.5f, 40, true, new Vector3f[]{
new Vector3f(0.5F, 0.35F, 0.9F),
}
);
public static final DustParticleOptions SMOKE_PARTICLE = new DustParticleOptions(
0.025f, 0.5f, 40, true, new Vector3f[]{
new Vector3f(0.7F, 0.7F, 0.7F),
}
);
public static final DustParticleOptions EXPLODE_FLAME_PARTICLE = new DustParticleOptions(
0.05f, 0.5f, 40, true, new Vector3f[]{
new Vector3f(1.0F, 0.8F, 0.5F),
new Vector3f(1.0F, 0.5F, 0.0F),
new Vector3f(1.0F, 0.9F, 0.0F),
}
);
public static final DustParticleOptions COLORFUL_PARTICLE = new DustParticleOptions(
0.025f, 0.5f, 40, true, new Vector3f[]{
new Vector3f(0.0F, 1.0F, 1.0F), // 0: 青色 (Cyan)
new Vector3f(0.1F, 0.4F, 1.0F), // 1: 蓝色 (Blue)
new Vector3f(1.0F, 1.0F, 0.6F), // 2: 淡黄 (Light Yellow)
new Vector3f(1.0F, 0.9F, 0.0F), // 3: 黄色 (Yellow)
new Vector3f(0.5F, 1.0F, 0.5F), // 4: 淡绿 (Light Green)
new Vector3f(0.0F, 1.0F, 0.2F), // 5: 绿色 (Green)
new Vector3f(1.0F, 0.6F, 0.8F), // 6: 粉红 (Pink)
new Vector3f(1.0F, 0.0F, 1.0F), // 7: 品红 (Magenta)
new Vector3f(1.0F, 0.8F, 0.5F), // 8: 淡橙 (Light Orange)
new Vector3f(1.0F, 0.5F, 0.0F), // 9: 橙色 (Orange)
new Vector3f(0.7F, 0.7F, 0.7F) // 10: 淡灰 (Light Gray)
}
);
public static final Supplier<ParticleType<DustParticleOptions>> DUST_PARTICLE =
PARTICLE_TYPES.register("dust_particle", () -> new ParticleType<>(false) {
@Override
public MapCodec<DustParticleOptions> codec() {
return DustParticleOptions.CODEC;
}
@Override
public StreamCodec<? super RegistryFriendlyByteBuf, DustParticleOptions> streamCodec() {
return DustParticleOptions.STREAM_CODEC;
}
});
public static final Supplier<SimpleParticleType> STAR_PARTICLE =
PARTICLE_TYPES.register("star_particle", () -> new SimpleParticleType(true));
public static final Supplier<SimpleParticleType> EXPLODE_PARTICLE =
PARTICLE_TYPES.register("explode_particle", () -> new SimpleParticleType(true));
public static final Supplier<SimpleParticleType> SEEDLER_THORN_PARTICLE =
PARTICLE_TYPES.register("seedler_thorn_particle", () -> new SimpleParticleType(true));
}
@@ -0,0 +1,57 @@
package com.lzxnone.terraria.particle;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.*;
import net.minecraft.core.particles.SimpleParticleType;
public class SeedlerThornParticle extends TextureSheetParticle {
private final float baseSize;
protected SeedlerThornParticle(ClientLevel level, double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed, SpriteSet spriteSet) {
super(level, x, y, z, xSpeed, ySpeed, zSpeed);
this.friction = 0.9F;
this.gravity = 0.0F;
this.xd = xSpeed;
this.yd = ySpeed;
this.zd = zSpeed;
this.baseSize = 0.075F + (this.random.nextFloat() * 0.05F);
this.quadSize = baseSize;
this.lifetime = 25;
this.pickSprite(spriteSet);
}
@Override
public void tick() {
super.tick();
float lifeRatio = (float) this.age / (float) this.lifetime;
this.quadSize = this.baseSize * (1.0F - lifeRatio);
this.alpha = 1.0F - lifeRatio;
}
@Override
public ParticleRenderType getRenderType() {
return ModParticleRenderTypes.TRANSLUCENT_EMISSIVE;
}
public static class Provider implements ParticleProvider<SimpleParticleType> {
private final SpriteSet spriteSet;
public Provider(SpriteSet spriteSet) {
this.spriteSet = spriteSet;
}
@Override
public Particle createParticle(SimpleParticleType type, ClientLevel level,
double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed) {
return new SeedlerThornParticle(level, x, y, z, xSpeed, ySpeed, zSpeed, this.spriteSet);
}
}
}
@@ -0,0 +1,77 @@
package com.lzxnone.terraria.particle;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.*;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.core.particles.SimpleParticleType;
import org.joml.Vector3f;
public class StarParticle extends TextureSheetParticle {
private final float baseSize;
private static final Vector3f[] COLOR_PALETTE = new Vector3f[]{
new Vector3f(1.0F, 0.9F, 0.0F), // 0: 黄色 (Yellow)
new Vector3f(0.5F, 0.8F, 1.0F), // 1: 淡蓝 (Light Blue)
new Vector3f(1.0F, 0.0F, 1.0F), // 2: 品红 (Magenta)
new Vector3f(0.7F, 0.7F, 0.7F) // 3: 淡灰 (Light Gray)
};
protected StarParticle(ClientLevel level, double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed, SpriteSet spriteSet) {
super(level, x, y, z, xSpeed, ySpeed, zSpeed);
this.friction = 0.9F;
this.gravity = 0.0F;
this.xd = xSpeed;
this.yd = ySpeed;
this.zd = zSpeed;
this.baseSize = 0.025F + (this.random.nextFloat() * 0.1F);
this.quadSize = baseSize;
this.lifetime = 40 + this.random.nextInt(10);
int randomIndex = this.random.nextInt(COLOR_PALETTE.length);
Vector3f chosenColor = COLOR_PALETTE[randomIndex];
this.rCol = chosenColor.x;
this.gCol = chosenColor.y;
this.bCol = chosenColor.z;
this.setSpriteFromAge(spriteSet);
}
@Override
public void tick() {
super.tick();
float lifeRatio = (float) this.age / (float) this.lifetime;
this.quadSize = this.baseSize * (1.0F - lifeRatio);
this.alpha = 1.0F - lifeRatio;
}
@Override
public int getLightColor(float partialTick) {
return LightTexture.FULL_BRIGHT;
}
@Override
public ParticleRenderType getRenderType() {
return ModParticleRenderTypes.TRANSLUCENT_EMISSIVE;
}
public static class Provider implements ParticleProvider<SimpleParticleType> {
private final SpriteSet spriteSet;
public Provider(SpriteSet spriteSet) {
this.spriteSet = spriteSet;
}
@Override
public Particle createParticle(SimpleParticleType type, ClientLevel level,
double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed) {
return new StarParticle(level, x, y, z, xSpeed, ySpeed, zSpeed, this.spriteSet);
}
}
}
@@ -0,0 +1,29 @@
package com.lzxnone.terraria.utils;
import net.minecraft.world.phys.Vec3;
import org.joml.Vector3f;
public class MathUtil {
public static Vector3f[] computeProjectileDir(Vector3f tempDir) {
Vector3f dir = new Vector3f(tempDir.x, tempDir.y, tempDir.z).normalize();
// 方向接近垂直时用 X 轴,否则用 Y 轴做参考向量
Vector3f ref = Math.abs(dir.y) > 0.999f ? new Vector3f(1, 0, 0) : new Vector3f(0, 1, 0);
Vector3f right = new Vector3f();
ref.cross(dir, right).normalize();
Vector3f up = new Vector3f();
dir.cross(right, up).normalize();
return new Vector3f[]{dir, up, right};
}
public static Vector3f toVector3f(Vec3 vec3) {
return new Vector3f((float) vec3.x, (float) vec3.y, (float) vec3.z);
}
public static Vec3 toVec3(Vector3f vector3f) {
return new Vec3(vector3f.x, vector3f.y, vector3f.z);
}
}
@@ -0,0 +1,20 @@
{
"itemGroup.lzxnoneterraria.weapon": "Terraria Weapon",
"itemGroup.lzxnoneterraria.block": "Terraria Block",
"item.lzxnoneterraria.bee_keeper": "Bee Keeper",
"item.lzxnoneterraria.copper_shortsword": "Copper Shortsword",
"item.lzxnoneterraria.enchanted_sword": "Enchanted Sword",
"item.lzxnoneterraria.influx_waver": "Influx Waver",
"item.lzxnoneterraria.meowmere": "Meowmere",
"item.lzxnoneterraria.seedler": "Seedler",
"item.lzxnoneterraria.star_wrath": "Star Wrath",
"item.lzxnoneterraria.starfury": "Starfury",
"item.lzxnoneterraria.terra_blade": "Terra Blade",
"item.lzxnoneterraria.the_horsemans_blade": "The Horseman's Blade",
"item.lzxnoneterraria.zenith": "Zenith",
"entity.lzxnoneterraria.bee_summon": "Bee",
"effect.lzxnoneterraria.confused": "Confused"
}
@@ -0,0 +1,20 @@
{
"itemGroup.lzxnoneterraria.weapon": "泰拉瑞亚 武器",
"itemGroup.lzxnoneterraria.block": "泰拉瑞亚 方块",
"item.lzxnoneterraria.bee_keeper": "养蜂人",
"item.lzxnoneterraria.copper_shortsword": "铜短剑",
"item.lzxnoneterraria.enchanted_sword": "附魔剑",
"item.lzxnoneterraria.influx_waver": "波涌之刃",
"item.lzxnoneterraria.meowmere": "彩虹喵之刃",
"item.lzxnoneterraria.seedler": "种子弯刀",
"item.lzxnoneterraria.star_wrath": "狂星之怒",
"item.lzxnoneterraria.starfury": "星怒",
"item.lzxnoneterraria.terra_blade": "泰拉刃",
"item.lzxnoneterraria.the_horsemans_blade": "无头骑士剑",
"item.lzxnoneterraria.zenith": "天顶剑",
"entity.lzxnoneterraria.bee_summon": "蜜蜂",
"effect.lzxnoneterraria.confused": "困惑"
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/bee_keeper"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/copper_shortsword"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/enchanted_sword"
}
}
@@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "lzxnoneterraria:item/enchanted_sword_beam"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/influx_waver"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/meowmere"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/seedler"
}
}
@@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "lzxnoneterraria:item/seedler_nut"
}
}
@@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "lzxnoneterraria:item/seedler_thorn"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/star_wrath"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/starfury"
}
}
@@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "lzxnoneterraria:item/starfury_star"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/terra_blade"
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/the_horsemans_blade"
}
}
@@ -0,0 +1,25 @@
{
"parent": "item/handheld",
"display": {
"thirdperson_righthand": {
"rotation": [0, 90, 55],
"translation": [0, 4.0, 3.0],
"scale": [0.85, 0.85, 0.85]
},
"thirdperson_lefthand": {
"rotation": [0, -90, -55],
"translation": [0, 4.0, 3.0],
"scale": [0.85, 0.85, 0.85]
},
"firstperson_righthand": {
"rotation": [0, 90, 25],
"translation": [1.13, 6.2, 0.0],
"scale": [0.68, 0.68, 0.68]
},
"firstperson_lefthand": {
"rotation": [0, -90, -25],
"translation": [1.13, 3.2, 3.0],
"scale": [0.68, 0.68, 0.68]
}
}
}
@@ -0,0 +1,6 @@
{
"parent": "lzxnoneterraria:item/weapon",
"textures": {
"layer0": "lzxnoneterraria:item/zenith"
}
}
@@ -0,0 +1,6 @@
{
"textures": [
"lzxnoneterraria:dust_particle_arms",
"lzxnoneterraria:dust_particle_center"
]
}
@@ -0,0 +1,6 @@
{
"textures": [
"lzxnoneterraria:enchanted_sword_beam_particle_arms",
"lzxnoneterraria:enchanted_sword_beam_particle_center"
]
}
@@ -0,0 +1,5 @@
{
"textures": [
"lzxnoneterraria:explode_particle"
]
}
@@ -0,0 +1,5 @@
{
"textures": [
"lzxnoneterraria:max_mana_particle"
]
}
@@ -0,0 +1,8 @@
{
"textures": [
"lzxnoneterraria:seedler_thorn_particle0",
"lzxnoneterraria:seedler_thorn_particle1",
"lzxnoneterraria:seedler_thorn_particle2",
"lzxnoneterraria:seedler_thorn_particle3"
]
}
@@ -0,0 +1,5 @@
{
"textures": [
"lzxnoneterraria:star_particle"
]
}
@@ -0,0 +1,20 @@
{
"wave": {
"sounds": ["lzxnoneterraria:wave"]
},
"max_mana": {
"sounds": ["lzxnoneterraria:max_mana"]
},
"beam": {
"sounds": ["lzxnoneterraria:beam"]
},
"star_fall": {
"sounds": ["lzxnoneterraria:star_fall"]
},
"star_collide": {
"sounds": ["lzxnoneterraria:star_collide"]
},
"boom": {
"sounds": ["lzxnoneterraria:boom"]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 819 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 355 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 348 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 305 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 625 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 431 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 B

Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more