Init for multiloader

This commit is contained in:
lukasabbe
2025-06-12 20:34:08 +02:00
commit 8f402847a0
78 changed files with 2313 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
* text eol=lf
*.bat text eol=crlf
*.patch text eol=lf
*.java text eol=lf
*.gradle text eol=crlf
*.png binary
*.gif binary
*.exe binary
*.dll binary
*.jar binary
*.lzma binary
*.zip binary
*.pyd binary
*.cfg text eol=lf
*.jks binary
+24
View File
@@ -0,0 +1,24 @@
# eclipse
bin
*.launch
.settings
.metadata
.classpath
.project
# idea
out
*.ipr
*.iws
*.iml
.idea/*
!.idea/scopes
# gradle
build
.gradle
# other
eclipse
run
runs
+121
View File
@@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
+32
View File
@@ -0,0 +1,32 @@
# MultiLoader Template
This project provides a Gradle project template that can compile Minecraft mods for multiple modloaders using a common project for the sources. This project does not require any third party libraries or dependencies. If you have any questions or want to discuss the project, please join our [Discord](https://discord.myceliummod.network).
## Getting Started
### IntelliJ IDEA
This guide will show how to import the MultiLoader Template into IntelliJ IDEA. The setup process is roughly equivalent to setting up the modloaders independently and should be very familiar to anyone who has worked with their MDKs.
1. Clone or download this repository to your computer.
2. Configure the project by setting the properties in the `gradle.properties` file. You will also need to change the `rootProject.name` property in `settings.gradle`, this should match the folder name of your project, or else IDEA may complain.
3. Open the template's root folder as a new project in IDEA. This is the folder that contains this README.md file and the gradlew executable.
4. If your default JVM/JDK is not Java 21 you will encounter an error when opening the project. This error is fixed by going to `File > Settings > Build, Execution, Deployment > Build Tools > Gradle > Gradle JVM` and changing the value to a valid Java 21 JVM. You will also need to set the Project SDK to Java 21. This can be done by going to `File > Project Structure > Project SDK`. Once both have been set open the Gradle tab in IDEA and click the refresh button to reload the project.
5. Open your Run/Debug Configurations. Under the `Application` category there should now be options to run Fabric and NeoForge projects. Select one of the client options and try to run it.
6. Assuming you were able to run the game in step 5 your workspace should now be set up.
### Eclipse
While it is possible to use this template in Eclipse it is not recommended. During the development of this template multiple critical bugs and quirks related to Eclipse were found at nearly every level of the required build tools. While we continue to work with these tools to report and resolve issues support for projects like these are not there yet. For now Eclipse is considered unsupported by this project. The development cycle for build tools is notoriously slow so there are no ETAs available.
## Development Guide
When using this template the majority of your mod should be developed in the `common` project. The `common` project is compiled against the vanilla game and is used to hold code that is shared between the different loader-specific versions of your mod. The `common` project has no knowledge or access to ModLoader specific code, apis, or concepts. Code that requires something from a specific loader must be done through the project that is specific to that loader, such as the `fabric` or `neoforge` projects.
Loader specific projects such as the `fabric` and `neoforge` project are used to load the `common` project into the game. These projects also define code that is specific to that loader. Loader specific projects can access all the code in the `common` project. It is important to remember that the `common` project can not access code from loader specific projects.
## Removing Platforms and Loaders
While this template has support for many modloaders, new loaders may appear in the future, and existing loaders may become less relevant.
Removing loader specific projects is as easy as deleting the folder, and removing the `include("projectname")` line from the `settings.gradle` file.
For example if you wanted to remove support for `forge` you would follow the following steps:
1. Delete the subproject folder. For example, delete `MultiLoader-Template/forge`.
2. Remove the project from `settings.gradle`. For example, remove `include("forge")`.
+7
View File
@@ -0,0 +1,7 @@
plugins {
// see https://fabricmc.net/develop/ for new versions
id 'fabric-loom' version '1.10-SNAPSHOT' apply false
// see https://projects.neoforged.net/neoforged/moddevgradle for new versions
id 'net.neoforged.moddev' version '2.0.62-beta' apply false
}
+3
View File
@@ -0,0 +1,3 @@
plugins {
id 'groovy-gradle-plugin'
}
@@ -0,0 +1,133 @@
plugins {
id 'java-library'
id 'maven-publish'
}
base {
archivesName = "${mod_id}-${project.name}-${minecraft_version}"
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(java_version)
withSourcesJar()
withJavadocJar()
}
repositories {
mavenCentral()
// https://docs.gradle.org/current/userguide/declaring_repositories.html#declaring_content_exclusively_found_in_one_repository
exclusiveContent {
forRepository {
maven {
name = 'Sponge'
url = 'https://repo.spongepowered.org/repository/maven-public'
}
}
filter { includeGroupAndSubgroups('org.spongepowered') }
}
exclusiveContent {
forRepositories(
maven {
name = 'ParchmentMC'
url = 'https://maven.parchmentmc.org/'
},
maven {
name = "NeoForge"
url = 'https://maven.neoforged.net/releases'
}
)
filter { includeGroup('org.parchmentmc.data') }
}
maven {
name = 'BlameJared'
url = 'https://maven.blamejared.com'
}
}
// Declare capabilities on the outgoing configurations.
// Read more about capabilities here: https://docs.gradle.org/current/userguide/component_capabilities.html#sec:declaring-additional-capabilities-for-a-local-component
['apiElements', 'runtimeElements', 'sourcesElements', 'javadocElements'].each { variant ->
configurations."$variant".outgoing {
capability("$group:${project.name}:$version")
capability("$group:${base.archivesName.get()}:$version")
capability("$group:$mod_id-${project.name}-${minecraft_version}:$version")
capability("$group:$mod_id:$version")
}
publishing.publications.configureEach {
suppressPomMetadataWarningsFor(variant)
}
}
sourcesJar {
from(rootProject.file('LICENSE')) {
rename { "${it}_${mod_name}" }
}
}
jar {
from(rootProject.file('LICENSE')) {
rename { "${it}_${mod_name}" }
}
manifest {
attributes([
'Specification-Title' : mod_name,
'Specification-Vendor' : mod_author,
'Specification-Version' : project.jar.archiveVersion,
'Implementation-Title' : project.name,
'Implementation-Version': project.jar.archiveVersion,
'Implementation-Vendor' : mod_author,
'Built-On-Minecraft' : minecraft_version
])
}
}
processResources {
var expandProps = [
'version' : version,
'group' : project.group, //Else we target the task's group.
'minecraft_version' : minecraft_version,
'minecraft_version_range' : minecraft_version_range,
'fabric_version' : fabric_version,
'fabric_loader_version' : fabric_loader_version,
'mod_name' : mod_name,
'mod_author' : mod_author,
'mod_id' : mod_id,
'license' : license,
'description' : project.description,
'neoforge_version' : neoforge_version,
'neoforge_loader_version_range': neoforge_loader_version_range,
"forge_version": forge_version,
"forge_loader_version_range": forge_loader_version_range,
'credits' : credits,
'java_version' : java_version
]
var jsonExpandProps = expandProps.collectEntries {
key, value -> [(key): value instanceof String ? value.replace("\n", "\\\\n") : value]
}
filesMatching(['META-INF/mods.toml', 'META-INF/neoforge.mods.toml']) {
expand expandProps
}
filesMatching(['pack.mcmeta', 'fabric.mod.json', '*.mixins.json']) {
expand jsonExpandProps
}
inputs.properties(expandProps)
}
publishing {
publications {
register('mavenJava', MavenPublication) {
artifactId base.archivesName.get()
from components.java
}
}
repositories {
maven {
url System.getenv('local_maven_url')
}
}
}
@@ -0,0 +1,44 @@
plugins {
id 'multiloader-common'
}
configurations {
commonJava{
canBeResolved = true
}
commonResources{
canBeResolved = true
}
}
dependencies {
compileOnly(project(':common')) {
capabilities {
requireCapability "$group:$mod_id"
}
}
commonJava project(path: ':common', configuration: 'commonJava')
commonResources project(path: ':common', configuration: 'commonResources')
}
tasks.named('compileJava', JavaCompile) {
dependsOn(configurations.commonJava)
source(configurations.commonJava)
}
processResources {
dependsOn(configurations.commonResources)
from(configurations.commonResources)
}
tasks.named('javadoc', Javadoc).configure {
dependsOn(configurations.commonJava)
source(configurations.commonJava)
}
tasks.named('sourcesJar', Jar) {
dependsOn(configurations.commonJava)
from(configurations.commonJava)
dependsOn(configurations.commonResources)
from(configurations.commonResources)
}
+47
View File
@@ -0,0 +1,47 @@
plugins {
id 'multiloader-common'
id 'net.neoforged.moddev'
}
neoForge {
neoFormVersion = neo_form_version
// Automatically enable AccessTransformers if the file exists
def at = file('src/main/resources/META-INF/accesstransformer.cfg')
if (at.exists()) {
accessTransformers.from(at.absolutePath)
}
parchment {
minecraftVersion = parchment_minecraft
mappingsVersion = parchment_version
}
}
dependencies {
compileOnly group: 'org.spongepowered', name: 'mixin', version: '0.8.5'
// fabric and neoforge both bundle mixinextras, so it is safe to use it in common
compileOnly group: 'io.github.llamalad7', name: 'mixinextras-common', version: '0.3.5'
annotationProcessor group: 'io.github.llamalad7', name: 'mixinextras-common', version: '0.3.5'
implementation "org.yaml:snakeyaml:${project.YAML_snake}"
}
configurations {
shadowCommon
implementation.extendsFrom shadowCommon
runtimeClasspath.extendsFrom shadowCommon
commonJava {
canBeResolved = false
canBeConsumed = true
}
commonResources {
canBeResolved = false
canBeConsumed = true
}
}
artifacts {
commonJava sourceSets.main.java.sourceDirectories.singleFile
commonResources sourceSets.main.resources.sourceDirectories.singleFile
}
@@ -0,0 +1,24 @@
package com.lukasabbe.bookshelfinspector;
import com.lukasabbe.bookshelfinspector.network.Handlers;
import com.lukasabbe.bookshelfinspector.network.packets.ModCheckPayload;
import com.lukasabbe.bookshelfinspector.platform.Services;
import net.minecraft.server.MinecraftServer;
public class BookshelfInspector {
public static MinecraftServer serverInstance;
public static Handlers networkHandlers;
public static void init() {
registerEvents();
networkHandlers = new Handlers();
}
private static void registerEvents(){
Services.EVENTS_HELPER.registerOnPlayerJoinEvent((player, server) -> {
serverInstance = server;
Services.NETWORK_HELPER.sendPacketFromServer(player, new ModCheckPayload(true));
});
}
}
@@ -0,0 +1,23 @@
package com.lukasabbe.bookshelfinspector;
import com.lukasabbe.bookshelfinspector.config.Config;
import com.lukasabbe.bookshelfinspector.data.BookData;
import com.lukasabbe.bookshelfinspector.data.BookShelfData;
import com.lukasabbe.bookshelfinspector.platform.Services;
public class BookshelfInspectorClient {
public static BookData currentBookData = BookData.empty();
public static BookShelfData bookShelfData = new BookShelfData();
public static boolean modAvailable = false;
public static Config config = new Config();
public static void clientInit(){
config.loadConfig();
Services.EVENTS_HELPER.registerOnPlayerDisconnect(() -> {
modAvailable = false;
bookShelfData = new BookShelfData();
});
}
}
@@ -0,0 +1,17 @@
package com.lukasabbe.bookshelfinspector;
import net.minecraft.resources.ResourceLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Constants {
public static final String MOD_ID = "bookshelfinspector";
public static final String MOD_NAME = "Bookshelf Inspector";
public static final Logger LOG = LoggerFactory.getLogger(MOD_NAME);
//Packets
public static final ResourceLocation BOOK_SHELF_INVENTORY_REQUEST_PACKET_ID = ResourceLocation.fromNamespaceAndPath(MOD_ID,"book_shelf_inventory_request");
public static final ResourceLocation BOOK_SHELF_INVENTORY_PACKET_ID = ResourceLocation.fromNamespaceAndPath(MOD_ID,"book_shelf_inventory");
public static final ResourceLocation MOD_CHECK_PACKET_ID = ResourceLocation.fromNamespaceAndPath(MOD_ID,"mod_check");
public static final ResourceLocation LECTERN_INVENTORY_REQUEST_PACKET_ID = ResourceLocation.fromNamespaceAndPath(MOD_ID, "lectern_inventory_request");
}
@@ -0,0 +1,67 @@
package com.lukasabbe.bookshelfinspector.config;
import com.lukasabbe.bookshelfinspector.platform.Services;
import org.yaml.snakeyaml.Yaml;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
public class Config {
public boolean lecternToggle = true;
public int scale = 10;
public boolean useRoman = false;
public void loadConfig(){
Path configPath = Services.PLATFORM.getConfigPath("bookshelfinspector-config.yml");
if(!Files.exists(configPath))createConfig(configPath);
Yaml yaml = new Yaml();
try{
Map<String, Object> configMap = yaml.load(new FileReader(configPath.toFile()));
if(configMap.containsKey("lectern-toggle")){
lecternToggle = (boolean) configMap.get("lectern-toggle");
}
if(configMap.containsKey("scale")){
scale = (int) configMap.get("scale");
}
if(configMap.containsKey("roman")){
useRoman = (boolean) configMap.get("roman");
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private void createConfig(Path configPath){
Path defaultConfigPath = Services.PLATFORM.getFileInModContainer("bookshelfinspector", "bookshelfinspector-config.yml");
try {
Files.copy(defaultConfigPath, configPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void saveConfig(){
Path configPath = Services.PLATFORM.getConfigPath("bookshelfinspector-config.yml");
if(!Files.exists(configPath)) createConfig(configPath);
Yaml yaml = new Yaml();
try{
Map<String, Object> configMap = yaml.load(new FileReader(configPath.toFile()));
configMap.put("lectern-toggle",lecternToggle);
configMap.put("scale",scale);
configMap.put("roman", useRoman);
FileWriter writer = new FileWriter(configPath.toString());
yaml.dump(configMap,writer);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,20 @@
package com.lukasabbe.bookshelfinspector.data;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
public class BookData {
public ItemStack itemStack;
public BlockPos pos;
public int slotId;
public BookData(ItemStack itemStack, BlockPos pos, int slotId) {
this.itemStack = itemStack;
this.pos = pos;
this.slotId = slotId;
}
public static BookData empty(){
return new BookData(ItemStack.EMPTY, null, -1);
}
}
@@ -0,0 +1,10 @@
package com.lukasabbe.bookshelfinspector.data;
import net.minecraft.core.BlockPos;
public class BookShelfData {
public boolean isCurrentBookDataToggled = false;
public BlockPos latestPos = null;
public boolean requestSent = false;
public int currentSlotInt = -1;
}
@@ -0,0 +1,10 @@
package com.lukasabbe.bookshelfinspector.data;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.block.Block;
public class Tags {
public static final TagKey<Block> CHISELED_BOOKSHELVES = TagKey.create(Registries.BLOCK, ResourceLocation.fromNamespaceAndPath("c", "chiseled_bookshelves"));
}
@@ -0,0 +1,15 @@
package com.lukasabbe.bookshelfinspector.mixin;
import net.minecraft.world.level.block.ChiseledBookShelfBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import java.util.OptionalInt;
@Mixin(ChiseledBookShelfBlock.class)
public interface BookshelfInvoker {
@Invoker("getHitSlot")
OptionalInt invokerGetSlotForHitPos(BlockHitResult hit, BlockState state);
}
@@ -0,0 +1,25 @@
package com.lukasabbe.bookshelfinspector.mixin;
import com.lukasabbe.bookshelfinspector.Constants;
import com.lukasabbe.bookshelfinspector.renderer.Inspector;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(LocalPlayer.class)
public class BookshelfMixin {
@Shadow @Final protected Minecraft minecraft;
@Unique private final Inspector bookshelfInspectorMultiloader$inspector = new Inspector();
@Inject(method = "tick", at= @At(value = "INVOKE", target = "Ljava/util/List;iterator()Ljava/util/Iterator;"))
public void injectTick(CallbackInfo ci){
bookshelfInspectorMultiloader$inspector.inspect(this.minecraft);
}
}
@@ -0,0 +1,24 @@
package com.lukasabbe.bookshelfinspector.mixin;
import com.lukasabbe.bookshelfinspector.Constants;
import com.lukasabbe.bookshelfinspector.renderer.HudRenderer;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiGraphics;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Gui.class)
public class InGameHudMixin {
@Shadow @Final private Minecraft minecraft;
@Inject(method = "render",at=@At("RETURN"))
public void render(GuiGraphics context, DeltaTracker tickCounter, CallbackInfo ci){
HudRenderer.hudRender(context, minecraft);
}
}
@@ -0,0 +1,21 @@
package com.lukasabbe.bookshelfinspector.network;
import com.lukasabbe.bookshelfinspector.network.client.BookShelfInventoryHandlerServer;
import com.lukasabbe.bookshelfinspector.network.client.ModServerPayloadHandler;
import com.lukasabbe.bookshelfinspector.network.server.BookShelfInventoryRequestServerPayloadHandler;
import com.lukasabbe.bookshelfinspector.network.server.LecternInventoryRequestServerPayloadHandler;
public class Handlers {
public BookShelfInventoryHandlerServer bookShelfInventoryHandlerServer;
public ModServerPayloadHandler modServerPayloadHandler;
public BookShelfInventoryRequestServerPayloadHandler bookShelfInventoryRequestServerPayloadHandler;
public LecternInventoryRequestServerPayloadHandler lecternInventoryRequestServerPayloadHandler;
public Handlers(){
bookShelfInventoryHandlerServer = new BookShelfInventoryHandlerServer();
modServerPayloadHandler = new ModServerPayloadHandler();
bookShelfInventoryRequestServerPayloadHandler = new BookShelfInventoryRequestServerPayloadHandler();
lecternInventoryRequestServerPayloadHandler = new LecternInventoryRequestServerPayloadHandler();
}
}
@@ -0,0 +1,24 @@
package com.lukasabbe.bookshelfinspector.network.client;
import com.lukasabbe.bookshelfinspector.BookshelfInspectorClient;
import com.lukasabbe.bookshelfinspector.data.BookData;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryPayload;
import com.lukasabbe.bookshelfinspector.platform.handlers.ClientPayloadHandler;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.item.Items;
public class BookShelfInventoryHandlerServer implements ClientPayloadHandler<BookShelfInventoryPayload> {
@Override
public void receive(BookShelfInventoryPayload bookShelfInventoryPayload, LocalPlayer player) {
BookshelfInspectorClient.bookShelfData.requestSent = false;
if(bookShelfInventoryPayload.itemStack().is(Items.AIR)){
BookshelfInspectorClient.bookShelfData.isCurrentBookDataToggled = false;
BookshelfInspectorClient.currentBookData = BookData.empty();
BookshelfInspectorClient.currentBookData.slotId = -2;
}
else{
BookshelfInspectorClient.bookShelfData.isCurrentBookDataToggled = true;
BookshelfInspectorClient.currentBookData = new BookData(bookShelfInventoryPayload.itemStack(),bookShelfInventoryPayload.pos(),bookShelfInventoryPayload.slotNum());
}
}
}
@@ -0,0 +1,15 @@
package com.lukasabbe.bookshelfinspector.network.client;
import com.lukasabbe.bookshelfinspector.BookshelfInspectorClient;
import com.lukasabbe.bookshelfinspector.Constants;
import com.lukasabbe.bookshelfinspector.network.packets.ModCheckPayload;
import com.lukasabbe.bookshelfinspector.platform.handlers.ClientPayloadHandler;
import net.minecraft.client.player.LocalPlayer;
public class ModServerPayloadHandler implements ClientPayloadHandler<ModCheckPayload> {
@Override
public void receive(ModCheckPayload payload, LocalPlayer player) {
Constants.LOG.info("[bookshelfinspector] Connected to server");
BookshelfInspectorClient.modAvailable = true;
}
}
@@ -0,0 +1,22 @@
package com.lukasabbe.bookshelfinspector.network.packets;
import com.lukasabbe.bookshelfinspector.Constants;
import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.world.item.ItemStack;
import org.jetbrains.annotations.NotNull;
public record BookShelfInventoryPayload(ItemStack itemStack, BlockPos pos, int slotNum) implements CustomPacketPayload {
public static final CustomPacketPayload.Type<BookShelfInventoryPayload> ID = new CustomPacketPayload.Type<>(Constants.BOOK_SHELF_INVENTORY_PACKET_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, BookShelfInventoryPayload> CODEC = StreamCodec.composite(
ItemStack.OPTIONAL_STREAM_CODEC, BookShelfInventoryPayload::itemStack,
BlockPos.STREAM_CODEC, BookShelfInventoryPayload::pos,
ByteBufCodecs.INT, BookShelfInventoryPayload::slotNum,
BookShelfInventoryPayload::new
);
@Override
public @NotNull Type<? extends CustomPacketPayload> type() { return ID; }
}
@@ -0,0 +1,22 @@
package com.lukasabbe.bookshelfinspector.network.packets;
import com.lukasabbe.bookshelfinspector.Constants;
import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import org.jetbrains.annotations.NotNull;
public record BookShelfInventoryRequestPayload(BlockPos pos, int slotNum) implements CustomPacketPayload {
public static final CustomPacketPayload.Type<BookShelfInventoryRequestPayload> ID = new CustomPacketPayload.Type<>(Constants.BOOK_SHELF_INVENTORY_REQUEST_PACKET_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, BookShelfInventoryRequestPayload> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC,BookShelfInventoryRequestPayload::pos,
ByteBufCodecs.INT, BookShelfInventoryRequestPayload::slotNum,
BookShelfInventoryRequestPayload::new);
@Override
public @NotNull Type<? extends CustomPacketPayload> type() { return ID; }
}
@@ -0,0 +1,20 @@
package com.lukasabbe.bookshelfinspector.network.packets;
import com.lukasabbe.bookshelfinspector.Constants;
import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import org.jetbrains.annotations.NotNull;
public record LecternInventoryRequestPayload(BlockPos pos) implements CustomPacketPayload {
public static final CustomPacketPayload.Type<LecternInventoryRequestPayload> ID = new CustomPacketPayload.Type<>(Constants.LECTERN_INVENTORY_REQUEST_PACKET_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, LecternInventoryRequestPayload> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC,LecternInventoryRequestPayload::pos,
LecternInventoryRequestPayload::new);
@Override
public @NotNull Type<? extends CustomPacketPayload> type() { return ID; }
}
@@ -0,0 +1,20 @@
package com.lukasabbe.bookshelfinspector.network.packets;
import com.lukasabbe.bookshelfinspector.Constants;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import org.jetbrains.annotations.NotNull;
public record ModCheckPayload(boolean modActivated) implements CustomPacketPayload {
public static final CustomPacketPayload.Type<ModCheckPayload> ID = new CustomPacketPayload.Type<>(Constants.MOD_CHECK_PACKET_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ModCheckPayload> CODEC = StreamCodec.composite(
ByteBufCodecs.BOOL, ModCheckPayload::modActivated,
ModCheckPayload::new
);
@Override
public @NotNull Type<? extends CustomPacketPayload> type() { return ID; }
}
@@ -0,0 +1,25 @@
package com.lukasabbe.bookshelfinspector.network.server;
import com.lukasabbe.bookshelfinspector.BookshelfInspector;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryPayload;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.platform.Services;
import com.lukasabbe.bookshelfinspector.platform.handlers.ServerPayloadHandler;
import com.lukasabbe.bookshelfinspector.util.BookshelfTools;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
public class BookShelfInventoryRequestServerPayloadHandler implements ServerPayloadHandler<BookShelfInventoryRequestPayload> {
@Override
public void receive(BookShelfInventoryRequestPayload bookShelfInventoryRequestPayload, ServerPlayer player) {
if(BookshelfInspector.serverInstance == null) return;
ItemStack stack = BookshelfTools.getItemById(bookShelfInventoryRequestPayload.pos(),bookShelfInventoryRequestPayload.slotNum(), player);
if(stack == null){
Services.NETWORK_HELPER.sendPacketFromServer(player, new BookShelfInventoryPayload(Items.AIR.getDefaultInstance(), bookShelfInventoryRequestPayload.pos(), bookShelfInventoryRequestPayload.slotNum()));
return;
}
Services.NETWORK_HELPER.sendPacketFromServer(player, new BookShelfInventoryPayload(stack, bookShelfInventoryRequestPayload.pos(), bookShelfInventoryRequestPayload.slotNum()));
}
}
@@ -0,0 +1,26 @@
package com.lukasabbe.bookshelfinspector.network.server;
import com.lukasabbe.bookshelfinspector.BookshelfInspector;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryPayload;
import com.lukasabbe.bookshelfinspector.network.packets.LecternInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.platform.Services;
import com.lukasabbe.bookshelfinspector.platform.handlers.ServerPayloadHandler;
import com.lukasabbe.bookshelfinspector.util.LecternTools;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
public class LecternInventoryRequestServerPayloadHandler implements ServerPayloadHandler<LecternInventoryRequestPayload> {
@Override
public void receive(LecternInventoryRequestPayload lecternInventoryRequestPayload, ServerPlayer player) {
if(BookshelfInspector.serverInstance == null) return;
ItemStack stack = LecternTools.getItemStack(lecternInventoryRequestPayload.pos(), player);
if(stack == null){
Services.NETWORK_HELPER.sendPacketFromServer(player, new BookShelfInventoryPayload(Items.AIR.getDefaultInstance(), lecternInventoryRequestPayload.pos(), 0));
return;
}
Services.NETWORK_HELPER.sendPacketFromServer(player, new BookShelfInventoryPayload(stack, lecternInventoryRequestPayload.pos(), 0));
}
}
@@ -0,0 +1,34 @@
package com.lukasabbe.bookshelfinspector.platform;
import com.lukasabbe.bookshelfinspector.Constants;
import com.lukasabbe.bookshelfinspector.platform.services.IEventHelper;
import com.lukasabbe.bookshelfinspector.platform.services.INetworkHelper;
import com.lukasabbe.bookshelfinspector.platform.services.IPlatformHelper;
import java.util.ServiceLoader;
// Service loaders are a built-in Java feature that allow us to locate implementations of an interface that vary from one
// environment to another. In the context of MultiLoader we use this feature to access a mock API in the common code that
// is swapped out for the platform specific implementation at runtime.
public class Services {
// In this example we provide a platform helper which provides information about what platform the mod is running on.
// For example this can be used to check if the code is running on Forge vs Fabric, or to ask the modloader if another
// mod is loaded.
public static final IPlatformHelper PLATFORM = load(IPlatformHelper.class);
public static final INetworkHelper NETWORK_HELPER = load(INetworkHelper.class);
public static final IEventHelper EVENTS_HELPER = load(IEventHelper.class);
// This code is used to load a service for the current environment. Your implementation of the service must be defined
// manually by including a text file in META-INF/services named with the fully qualified class name of the service.
// Inside the file you should write the fully qualified class name of the implementation to load for the platform. For
// example our file on Forge points to ForgePlatformHelper while Fabric points to FabricPlatformHelper.
public static <T> T load(Class<T> clazz) {
final T loadedService = ServiceLoader.load(clazz)
.findFirst()
.orElseThrow(() -> new NullPointerException("Failed to load service for " + clazz.getName()));
Constants.LOG.debug("Loaded {} for service {}", loadedService, clazz);
return loadedService;
}
}
@@ -0,0 +1,8 @@
package com.lukasabbe.bookshelfinspector.platform.handlers;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
public interface ClientPayloadHandler<T extends CustomPacketPayload> {
void receive(T payload, LocalPlayer player);
}
@@ -0,0 +1,5 @@
package com.lukasabbe.bookshelfinspector.platform.handlers;
public interface OnPlayerDisconnectEvent {
void onDisconnect();
}
@@ -0,0 +1,8 @@
package com.lukasabbe.bookshelfinspector.platform.handlers;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
public interface OnPlayerJoinEvent {
void onPlayerJoin(ServerPlayer handler, MinecraftServer server);
}
@@ -0,0 +1,8 @@
package com.lukasabbe.bookshelfinspector.platform.handlers;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.level.ServerPlayer;
public interface ServerPayloadHandler<T extends CustomPacketPayload> {
void receive(T payload, ServerPlayer player);
}
@@ -0,0 +1,9 @@
package com.lukasabbe.bookshelfinspector.platform.services;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerDisconnectEvent;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerJoinEvent;
public interface IEventHelper {
void registerOnPlayerJoinEvent(OnPlayerJoinEvent event);
void registerOnPlayerDisconnect(OnPlayerDisconnectEvent event);
}
@@ -0,0 +1,9 @@
package com.lukasabbe.bookshelfinspector.platform.services;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.level.ServerPlayer;
public interface INetworkHelper {
void sendPacketFromServer(ServerPlayer player, CustomPacketPayload payload);
void sendPacketFromClient(CustomPacketPayload payload);
}
@@ -0,0 +1,20 @@
package com.lukasabbe.bookshelfinspector.platform.services;
import java.nio.file.Path;
public interface IPlatformHelper {
String getPlatformName();
boolean isModLoaded(String modId);
boolean isDevelopmentEnvironment();
Path getConfigPath(String file);
Path getFileInModContainer(String mod, String fileName);
default String getEnvironmentName() {
return isDevelopmentEnvironment() ? "development" : "production";
}
}
@@ -0,0 +1,90 @@
package com.lukasabbe.bookshelfinspector.renderer;
import com.lukasabbe.bookshelfinspector.BookshelfInspectorClient;
import com.lukasabbe.bookshelfinspector.Constants;
import com.lukasabbe.bookshelfinspector.data.BookData;
import com.lukasabbe.bookshelfinspector.util.RomanNumerals;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.core.Holder;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.tags.EnchantmentTags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.ItemEnchantments;
public class HudRenderer {
public static void hudRender(GuiGraphics context, Minecraft client){
if(!BookshelfInspectorClient.modAvailable) return;
if(client.options.hideGui) return;
if(!BookshelfInspectorClient.bookShelfData.isCurrentBookDataToggled) return;
final BookData currentBookData = BookshelfInspectorClient.currentBookData;
final int screenWidth = client.getWindow().getGuiScaledWidth();
final int screenHeight = client.getWindow().getGuiScaledHeight();
final int x = screenWidth / 2;
final int y = screenHeight / 2;
final ItemStack itemStack = currentBookData.itemStack;
int color = 0xFFFFFFFF;
final Integer colorValue = itemStack.getRarity().color().getColor();
if(colorValue != null){
color = colorValue;
}
float scaleFactor = ((float) BookshelfInspectorClient.config.scale /10);
drawScaledText(context, itemStack.getHoverName(), x,y+((int)(10*scaleFactor)), color, client.font);
ItemEnchantments storedComponents = itemStack.getComponents().get(DataComponents.STORED_ENCHANTMENTS);
if(storedComponents != null){
int i = ((int)(20*scaleFactor));
for(Holder<Enchantment> enchantment : storedComponents.keySet()){
String lvl = "";
final int level = storedComponents.getLevel(enchantment);
if(level != 1)
lvl = String.valueOf(level);
final MutableComponent enchantmentText;
if(!BookshelfInspectorClient.config.useRoman || level == -1)
enchantmentText = enchantment.value().description().copy().append(" " + lvl);
else if (level != 1)
enchantmentText = enchantment.value().description().copy().append(" " + RomanNumerals.toRoman(level));
else
enchantmentText = enchantment.value().description().copy();
if(enchantment.is(EnchantmentTags.CURSE)) {
ComponentUtils.mergeStyles(enchantmentText, Style.EMPTY.withColor(ChatFormatting.RED));
}else {
ComponentUtils.mergeStyles(enchantmentText, Style.EMPTY.withColor(ChatFormatting.GRAY));
}
drawScaledText(context, enchantmentText, x,y+i, 0xFFFFFFFF,client.font);
i+=(int)(10*scaleFactor);
}
}
var writtenBookContentComponent = itemStack.getComponents().get(DataComponents.WRITTEN_BOOK_CONTENT);
if(writtenBookContentComponent != null){
drawScaledText(context, Component.translatable("book.byAuthor",writtenBookContentComponent.author()), x,y+(int)(20*scaleFactor), 0xFFFFFFFF, client.font);
}
}
private static void drawScaledText(GuiGraphics context, Component text, int centerX, int y, int color, Font textRenderer){
PoseStack stack = context.pose();
stack.pushPose();
stack.translate(centerX,y,0);
final float scale = (float) BookshelfInspectorClient.config.scale / 10;
stack.scale(scale, scale, scale);
stack.translate(-centerX,-y,0);
context.drawCenteredString(textRenderer,text,centerX,y,color);
stack.popPose();
}
}
@@ -0,0 +1,121 @@
package com.lukasabbe.bookshelfinspector.renderer;
import com.lukasabbe.bookshelfinspector.BookshelfInspectorClient;
import com.lukasabbe.bookshelfinspector.data.BookData;
import com.lukasabbe.bookshelfinspector.data.Tags;
import com.lukasabbe.bookshelfinspector.mixin.BookshelfInvoker;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.network.packets.LecternInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.platform.Services;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.ChiseledBookShelfBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import java.util.OptionalInt;
import static com.lukasabbe.bookshelfinspector.BookshelfInspectorClient.*;
public class Inspector {
public void inspect(Minecraft client){
if(!modAvailable) return;
if(client.cameraEntity == null || client.player == null) return;
//Send raycast max 5 blocks
HitResult hit = client.cameraEntity.pick(5f,0f,false);
//find block hit, if not found block returns
final HitResult.Type type = hit.getType();
if(type != HitResult.Type.BLOCK) {
resetBookShelfData();
return;
}
final BlockHitResult blockHitResult = (BlockHitResult) hit;
BlockPos pos = blockHitResult.getBlockPos();
if(bookShelfData.latestPos == null)
bookShelfData.latestPos = pos;
//If you look at a new block
if(!bookShelfData.latestPos.equals(pos)){
resetBookShelfData();
currentBookData = BookData.empty();
}
bookShelfData.latestPos = pos;
if(client.player.level().getBlockState(pos).is(Tags.CHISELED_BOOKSHELVES)){
bookShelfInspect(pos, blockHitResult, client);
}else if(client.player.level().getBlockState(pos).is(Blocks.LECTERN) && config.lecternToggle){
lecternInspect(pos);
}else{
bookShelfData.requestSent = false; // Just for servers that don't have the latest version of mod
if(!bookShelfData.isCurrentBookDataToggled) return;
resetBookShelfData();
}
}
private void lecternInspect(BlockPos pos){
//Checks if there is saved data.
final BookData currentBookData = BookshelfInspectorClient.currentBookData;
if(currentBookData.pos != null && currentBookData.pos.equals(pos)) return;
if(!bookShelfData.requestSent){
bookShelfData.requestSent = true;
Services.NETWORK_HELPER.sendPacketFromClient(new LecternInventoryRequestPayload(pos));
}
}
private void bookShelfInspect(BlockPos pos, BlockHitResult blockHitResult, Minecraft client){
final BlockState blockState = client.player.level().getBlockState(pos);
//Gets index position for a book in the bookshelf
ChiseledBookShelfBlock bookshelfBlock = (ChiseledBookShelfBlock) blockState.getBlock();
OptionalInt optionalInt = ((BookshelfInvoker)bookshelfBlock).invokerGetSlotForHitPos(blockHitResult,blockState);
//if the position is empty, return
if(optionalInt.isEmpty()) {
resetBookShelfData();
return;
}
//Checks if there is saved data.
final BookData currentBookData = BookshelfInspectorClient.currentBookData;
//Changes the id for the new one if it's new.
final int temp = bookShelfData.currentSlotInt;
final int slotNum = optionalInt.getAsInt();
bookShelfData.currentSlotInt = slotNum;
if(currentBookData.slotId!= slotNum && currentBookData.slotId!=-2 && !bookShelfData.requestSent){
bookShelfData.requestSent = true;
Services.NETWORK_HELPER.sendPacketFromClient(new BookShelfInventoryRequestPayload(pos, slotNum));
}
else {
if(temp == slotNum)
bookShelfData.isCurrentBookDataToggled = currentBookData.slotId != -2;
else{
bookShelfData.isCurrentBookDataToggled = false;
BookshelfInspectorClient.currentBookData = BookData.empty();
}
}
}
private void resetBookShelfData(){
if(!bookShelfData.isCurrentBookDataToggled) return;
bookShelfData.isCurrentBookDataToggled = false;
currentBookData = BookData.empty();
}
}
@@ -0,0 +1,28 @@
package com.lukasabbe.bookshelfinspector.util;
import com.lukasabbe.bookshelfinspector.BookshelfInspector;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.entity.ChiseledBookShelfBlockEntity;
import java.util.Optional;
public class BookshelfTools {
public static ItemStack getItemById(BlockPos pos, int slotNum, Player player){
final Level world = BookshelfInspector.serverInstance.getPlayerList().getPlayer(player.getUUID()).level();
final Optional<ChiseledBookShelfBlockEntity> blockEntityOptional = world.getBlockEntity(pos, BlockEntityType.CHISELED_BOOKSHELF);
if(blockEntityOptional.isEmpty()) return null;
final ChiseledBookShelfBlockEntity blockEntity = blockEntityOptional.get();
final ItemStack stack = blockEntity.getItem(slotNum);
if(stack.isEmpty()) return null;
return stack;
}
}
@@ -0,0 +1,24 @@
package com.lukasabbe.bookshelfinspector.util;
import com.lukasabbe.bookshelfinspector.BookshelfInspector;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.entity.LecternBlockEntity;
import java.util.Optional;
public class LecternTools {
public static ItemStack getItemStack(BlockPos pos, Player player){
final Level world = BookshelfInspector.serverInstance.getPlayerList().getPlayer(player.getUUID()).level();
Optional<LecternBlockEntity> blockEntityOptional = world.getBlockEntity(pos, BlockEntityType.LECTERN);
if(blockEntityOptional.isEmpty()) return null;
LecternBlockEntity lecternBlock = blockEntityOptional.get();
return lecternBlock.getBook();
}
}
@@ -0,0 +1,33 @@
package com.lukasabbe.bookshelfinspector.util;
import java.util.TreeMap;
public class RomanNumerals {
private final static TreeMap<Integer, String> map = new TreeMap<>();
static {
map.put(1000, "M");
map.put(900, "CM");
map.put(500, "D");
map.put(400, "CD");
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");
}
public static String toRoman(int number){
int key = map.floorKey(number);
if(number == key){
return map.get(number);
}
return map.get(key) + toRoman(number-key);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

@@ -0,0 +1,10 @@
{
"bookshelfinspector.config.title": "Bookshelf Inspector Config",
"bookshelfinspector.config.category": "Settings",
"bookshelfinspector.config.lectern.toggle": "Turn OFF or ON lectern support",
"bookshelfinspector.config.lectern.toggle.tooltip": "This will turn OFF/ON the visibility of lectern inspection",
"bookshelfinspector.config.scale": "Change the scale of the text",
"bookshelfinspector.config.scale.tooltip": "Change the scale of the text by dragging the slider",
"bookshelfinspector.config.roman_scale": "Use roman numerals!",
"bookshelfinspector.config.roman_scale.tooltip": "Use roman numerals or arabic numerals"
}
@@ -0,0 +1,10 @@
{
"bookshelfinspector.config.title": "Bookshelf Inspector Config",
"bookshelfinspector.config.category": "Inställningar",
"bookshelfinspector.config.lectern.toggle": "Stäng AV eller PÅ läspulpet stöd",
"bookshelfinspector.config.lectern.toggle.tooltip": "Denna inställning kommer stänga av eller på synligeten av läspulpet inspektion",
"bookshelfinspector.config.scale": "Ändra storleken på texten",
"bookshelfinspector.config.scale.tooltip": "Du kan göra det igenom att dra på den nedan",
"bookshelfinspector.config.roman_scale": "Använd romerska siffror",
"bookshelfinspector.config.roman_scale.tooltip": "Använd romerska siffror eller arabiska siffror"
}
@@ -0,0 +1,3 @@
lectern-toggle: true
scale: 10
roman: false
@@ -0,0 +1,19 @@
{
"required": true,
"minVersion": "0.8",
"package": "com.lukasabbe.bookshelfinspector.mixin",
"refmap": "${mod_id}.refmap.json",
"compatibilityLevel": "JAVA_18",
"mixins": [
],
"client": [
"BookshelfMixin",
"InGameHudMixin",
"BookshelfInvoker"
],
"server": [],
"injectors": {
"defaultRequire": 1
}
}
@@ -0,0 +1,6 @@
{
"replace": false,
"values": [
"minecraft:chiseled_bookshelf"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"pack": {
"description": "${mod_name}",
"pack_format": 8
}
}
+46
View File
@@ -0,0 +1,46 @@
plugins {
id 'multiloader-loader'
id 'fabric-loom'
}
repositories {
maven { url "https://maven.shedaniel.me/" }
maven { url "https://maven.terraformersmc.com/releases/" }
}
dependencies {
minecraft "com.mojang:minecraft:${minecraft_version}"
mappings loom.layered {
officialMojangMappings()
parchment("org.parchmentmc.data:parchment-${parchment_minecraft}:${parchment_version}@zip")
}
modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${fabric_version}"
modApi "me.shedaniel.cloth:cloth-config-fabric:${project.cloth_config}"
modApi "com.terraformersmc:modmenu:${project.mod_menu}"
include(implementation("org.yaml:snakeyaml:${project.YAML_snake}"))
}
loom {
def aw = project(':common').file("src/main/resources/${mod_id}.accesswidener")
if (aw.exists()) {
accessWidenerPath.set(aw)
}
mixin {
defaultRefmapName.set("${mod_id}.refmap.json")
}
runs {
client {
client()
setConfigName('Fabric Client')
ideConfigGenerated(true)
runDir('runs/client')
}
server {
server()
setConfigName('Fabric Server')
ideConfigGenerated(true)
runDir('runs/server')
}
}
}
@@ -0,0 +1,33 @@
package com.lukasabbe.bookshelfinspector;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryPayload;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.network.packets.LecternInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.network.packets.ModCheckPayload;
import com.lukasabbe.bookshelfinspector.network.server.BookShelfInventoryRequestServerPayloadHandler;
import com.lukasabbe.bookshelfinspector.network.server.LecternInventoryRequestServerPayloadHandler;
import com.lukasabbe.bookshelfinspector.platform.Services;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
public class BookshelfInspectorFabric implements ModInitializer {
@Override
public void onInitialize() {
PayloadTypeRegistry.playC2S().register(BookShelfInventoryRequestPayload.ID, BookShelfInventoryRequestPayload.CODEC);
PayloadTypeRegistry.playC2S().register(LecternInventoryRequestPayload.ID, LecternInventoryRequestPayload.CODEC);
PayloadTypeRegistry.playS2C().register(BookShelfInventoryPayload.ID, BookShelfInventoryPayload.CODEC);
PayloadTypeRegistry.playS2C().register(ModCheckPayload.ID, ModCheckPayload.CODEC);
ServerPlayNetworking.registerGlobalReceiver(
BookShelfInventoryRequestPayload.ID,
(payload, context) -> BookshelfInspector.networkHandlers.bookShelfInventoryRequestServerPayloadHandler.receive(payload, context.player()));
ServerPlayNetworking.registerGlobalReceiver(
LecternInventoryRequestPayload.ID,
((payload, context) -> BookshelfInspector.networkHandlers.lecternInventoryRequestServerPayloadHandler.receive(payload, context.player())));
BookshelfInspector.init();
}
}
@@ -0,0 +1,19 @@
package com.lukasabbe.bookshelfinspector;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryPayload;
import com.lukasabbe.bookshelfinspector.network.packets.ModCheckPayload;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
public class BookshelfInspectorFabricClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
ClientPlayNetworking.registerGlobalReceiver(
BookShelfInventoryPayload.ID,
((payload, context) -> BookshelfInspector.networkHandlers.bookShelfInventoryHandlerServer.receive(payload, context.player())));
ClientPlayNetworking.registerGlobalReceiver(
ModCheckPayload.ID,
((payload, context) -> BookshelfInspector.networkHandlers.modServerPayloadHandler.receive(payload, context.player())));
BookshelfInspectorClient.clientInit();
}
}
@@ -0,0 +1,42 @@
package com.lukasabbe.bookshelfinspector;
import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import com.terraformersmc.modmenu.api.ModMenuApi;
import me.shedaniel.clothconfig2.api.ConfigBuilder;
import me.shedaniel.clothconfig2.api.ConfigEntryBuilder;
import net.minecraft.network.chat.Component;
public class ModMenu implements ModMenuApi {
@Override
public ConfigScreenFactory<?> getModConfigScreenFactory() {
return parent -> {
ConfigBuilder builder = ConfigBuilder
.create()
.setParentScreen(parent)
.setTitle(Component.translatable("bookshelfinspector.config.title"));
ConfigEntryBuilder entryBuilder = builder.entryBuilder();
builder
.getOrCreateCategory(Component.translatable("bookshelfinspector.config.category"))
.addEntry(entryBuilder
.startBooleanToggle(Component.translatable("bookshelfinspector.config.lectern.toggle"), BookshelfInspectorClient.config.lecternToggle)
.setTooltip(Component.translatable("bookshelfinspector.config.lectern.toggle.tooltip"))
.setDefaultValue(true)
.setSaveConsumer(val -> BookshelfInspectorClient.config.lecternToggle = val).build())
.addEntry(entryBuilder
.startIntSlider(Component.translatable("bookshelfinspector.config.scale"),BookshelfInspectorClient.config.scale,0,20)
.setTooltip(Component.translatable("bookshelfinspector.config.scale.tooltip"))
.setDefaultValue(10).setSaveConsumer(val -> BookshelfInspectorClient.config.scale = val)
.build())
.addEntry(entryBuilder
.startBooleanToggle(Component.translatable("bookshelfinspector.config.roman_scale"), BookshelfInspectorClient.config.useRoman)
.setTooltip(Component.translatable("bookshelfinspector.config.roman_scale.tooltip"))
.setDefaultValue(false)
.setSaveConsumer(val -> BookshelfInspectorClient.config.useRoman = val)
.build());
builder.setSavingRunnable(BookshelfInspectorClient.config::saveConfig);
return builder.build();
};
}
}
@@ -0,0 +1,19 @@
package com.lukasabbe.bookshelfinspector.platform;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerDisconnectEvent;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerJoinEvent;
import com.lukasabbe.bookshelfinspector.platform.services.IEventHelper;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
public class FabricEventHelper implements IEventHelper {
@Override
public void registerOnPlayerJoinEvent(OnPlayerJoinEvent event) {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> event.onPlayerJoin(handler.getPlayer(), server));
}
@Override
public void registerOnPlayerDisconnect(OnPlayerDisconnectEvent event) {
ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> event.onDisconnect());
}
}
@@ -0,0 +1,20 @@
package com.lukasabbe.bookshelfinspector.platform;
import com.lukasabbe.bookshelfinspector.platform.services.INetworkHelper;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.level.ServerPlayer;
public class FabricNetworkHelper implements INetworkHelper {
@Override
public void sendPacketFromServer(ServerPlayer player, CustomPacketPayload payload) {
ServerPlayNetworking.send(player, payload);
}
@Override
public void sendPacketFromClient(CustomPacketPayload payload) {
ClientPlayNetworking.send(payload);
}
}
@@ -0,0 +1,39 @@
package com.lukasabbe.bookshelfinspector.platform;
import com.lukasabbe.bookshelfinspector.platform.services.IPlatformHelper;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import java.nio.file.Path;
public class FabricPlatformHelper implements IPlatformHelper {
@Override
public String getPlatformName() {
return "Fabric";
}
@Override
public boolean isModLoaded(String modId) {
return FabricLoader.getInstance().isModLoaded(modId);
}
@Override
public boolean isDevelopmentEnvironment() {
return FabricLoader.getInstance().isDevelopmentEnvironment();
}
@Override
public Path getConfigPath(String file) {
return FabricLoader.getInstance().getConfigDir().resolve(file);
}
@Override
public Path getFileInModContainer(String mod, String fileName) {
if(FabricLoader.getInstance().getModContainer(mod).isEmpty()) return null;
ModContainer modContainer = FabricLoader.getInstance().getModContainer(mod).get();
return modContainer.findPath(fileName).orElseThrow();
}
}
@@ -0,0 +1 @@
com.lukasabbe.bookshelfinspector.platform.FabricEventHelper
@@ -0,0 +1 @@
com.lukasabbe.bookshelfinspector.platform.FabricNetworkHelper
@@ -0,0 +1 @@
com.lukasabbe.bookshelfinspector.platform.FabricPlatformHelper
+38
View File
@@ -0,0 +1,38 @@
{
"schemaVersion": 1,
"id": "${mod_id}",
"version": "${version}",
"name": "${mod_name}",
"description": "${description}",
"authors": [
"${mod_author}"
],
"contact": {
"homepage": "https://modrinth.com/mod/bookshelf-inspector",
"sources": "https://github.com/lukasabbe/bookshelf-inspector"
},
"license": "${license}",
"environment": "*",
"icon": "assets/bookshelfinspector/icon.png",
"entrypoints": {
"main": [
"com.lukasabbe.bookshelfinspector.BookshelfInspectorFabric"
],
"client": [
"com.lukasabbe.bookshelfinspector.BookshelfInspectorFabricClient"
],
"modmenu": [
"com.lukasabbe.bookshelfinspector.ModMenu"
]
},
"mixins": [
"bookshelfinspector.mixins.json"
],
"depends": {
"fabricloader": ">=${fabric_loader_version}",
"fabric-api": "*",
"minecraft": "~${minecraft_version}",
"java": ">=${java_version}"
}
}
+44
View File
@@ -0,0 +1,44 @@
# Important Notes:
# Every field you add must be added to buildSrc/src/main/groovy/multiloader-common.gradle expandProps map.
# Project
version=1.0+1.21.5
group=com.lukasabbe.bookshelfinspector
java_version=21
# Common
minecraft_version=1.21.5
mod_name=BookshelfInspector
mod_author=Lukasabbe
mod_id=bookshelfinspector
license=MIT
credits=
description=Inspect any book in a chiseled bookshelf.
minecraft_version_range=[1.21.5, 1.22)
## This is the version of minecraft that the 'common' project uses, you can find a list of all versions here
## https://projects.neoforged.net/neoforged/neoform
neo_form_version=1.21.5-20250325.162830
# The version of ParchmentMC that is used, see https://parchmentmc.org/docs/getting-started#choose-a-version for new versions
parchment_minecraft=1.21.4
parchment_version=2025.03.23
# Fabric
fabric_version=0.119.5+1.21.5
fabric_loader_version=0.16.10
# Forge
forge_version=55.0.1
forge_loader_version_range=[55,)
# NeoForge
neoforge_version=21.5.4-beta
neoforge_loader_version_range=[4,)
# Gradle
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
# Global dep
YAML_snake=2.4
cloth_config=18.0.145
mod_menu=14.0.0-rc.2
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-8.12-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
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=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+46
View File
@@ -0,0 +1,46 @@
plugins {
id 'multiloader-loader'
id 'net.neoforged.moddev'
}
repositories {
maven { url "https://maven.shedaniel.me/" }
mavenCentral()
}
neoForge {
version = neoforge_version
// Automatically enable neoforge AccessTransformers if the file exists
def at = project(':common').file('src/main/resources/META-INF/accesstransformer.cfg')
if (at.exists()) {
accessTransformers.from(at.absolutePath)
}
parchment {
minecraftVersion = parchment_minecraft
mappingsVersion = parchment_version
}
dependencies {
api "me.shedaniel.cloth:cloth-config-neoforge:${cloth_config}"
}
runs {
configureEach {
systemProperty('neoforge.enabledGameTestNamespaces', mod_id)
ideName = "NeoForge ${it.name.capitalize()} (${project.path})" // Unify the run config names with fabric
}
client {
client()
}
data {
clientData()
}
server {
server()
}
}
mods {
"${mod_id}" {
sourceSet sourceSets.main
}
}
}
sourceSets.main.resources { srcDir 'src/generated/resources' }
@@ -0,0 +1,18 @@
package com.lukasabbe.bookshelfinspector;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModList;
import net.neoforged.fml.ModLoadingContext;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.client.gui.IConfigScreenFactory;
@Mod(Constants.MOD_ID)
public class BookshelfInspectorNeoForge {
public BookshelfInspectorNeoForge(IEventBus eventBus) {
EventHandler.init();
eventBus.addListener(NetworkHandler::registerPayloads);
BookshelfInspector.init();
ModLoadingContext.get().registerExtensionPoint(IConfigScreenFactory.class, () -> (client, parent) -> ClothConfigGenerator.createConfig(parent));
}
}
@@ -0,0 +1,12 @@
package com.lukasabbe.bookshelfinspector;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.common.Mod;
@Mod(value = Constants.MOD_ID, dist = Dist.CLIENT)
public class BookshelfInspectorNeoForgeClient {
public BookshelfInspectorNeoForgeClient(IEventBus bus) {
BookshelfInspectorClient.clientInit();
}
}
@@ -0,0 +1,38 @@
package com.lukasabbe.bookshelfinspector;
import me.shedaniel.clothconfig2.api.ConfigBuilder;
import me.shedaniel.clothconfig2.api.ConfigEntryBuilder;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
public class ClothConfigGenerator {
public static Screen createConfig(Screen parent){
ConfigBuilder builder = ConfigBuilder
.create()
.setParentScreen(parent)
.setTitle(Component.translatable("bookshelfinspector.config.title"));
ConfigEntryBuilder entryBuilder = builder.entryBuilder();
builder
.getOrCreateCategory(Component.translatable("bookshelfinspector.config.category"))
.addEntry(entryBuilder
.startBooleanToggle(Component.translatable("bookshelfinspector.config.lectern.toggle"), BookshelfInspectorClient.config.lecternToggle)
.setTooltip(Component.translatable("bookshelfinspector.config.lectern.toggle.tooltip"))
.setDefaultValue(true)
.setSaveConsumer(val -> BookshelfInspectorClient.config.lecternToggle = val).build())
.addEntry(entryBuilder
.startIntSlider(Component.translatable("bookshelfinspector.config.scale"),BookshelfInspectorClient.config.scale,0,20)
.setTooltip(Component.translatable("bookshelfinspector.config.scale.tooltip"))
.setDefaultValue(10).setSaveConsumer(val -> BookshelfInspectorClient.config.scale = val)
.build())
.addEntry(entryBuilder
.startBooleanToggle(Component.translatable("bookshelfinspector.config.roman_scale"), BookshelfInspectorClient.config.useRoman)
.setTooltip(Component.translatable("bookshelfinspector.config.roman_scale.tooltip"))
.setDefaultValue(false)
.setSaveConsumer(val -> BookshelfInspectorClient.config.useRoman = val)
.build());
builder.setSavingRunnable(BookshelfInspectorClient.config::saveConfig);
return builder.build();
}
}
@@ -0,0 +1,30 @@
package com.lukasabbe.bookshelfinspector;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerDisconnectEvent;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerJoinEvent;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import java.util.ArrayList;
import java.util.List;
public class EventHandler {
public static List<OnPlayerJoinEvent> playerJoinEvents = new ArrayList<>();
public static List<OnPlayerDisconnectEvent> playerDisconnectEvents = new ArrayList<>();
public static void init(){
NeoForge.EVENT_BUS.addListener(EventHandler::onJoin);
NeoForge.EVENT_BUS.addListener(EventHandler::onDisconnect);
}
private static void onJoin(PlayerEvent.PlayerLoggedInEvent event){
playerJoinEvents.forEach(onPlayerJoinEvent -> onPlayerJoinEvent.onPlayerJoin((ServerPlayer) event.getEntity(),event.getEntity().getServer()));
}
private static void onDisconnect(ClientPlayerNetworkEvent.LoggingOut event){
playerDisconnectEvents.forEach(OnPlayerDisconnectEvent::onDisconnect);
}
}
@@ -0,0 +1,40 @@
package com.lukasabbe.bookshelfinspector;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryPayload;
import com.lukasabbe.bookshelfinspector.network.packets.BookShelfInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.network.packets.LecternInventoryRequestPayload;
import com.lukasabbe.bookshelfinspector.network.packets.ModCheckPayload;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import net.neoforged.neoforge.network.registration.PayloadRegistrar;
public class NetworkHandler {
@SubscribeEvent
public static void registerPayloads(final RegisterPayloadHandlersEvent event){
final PayloadRegistrar registrar = event.registrar("1");
registrar.playToServer(
BookShelfInventoryRequestPayload.ID,
BookShelfInventoryRequestPayload.CODEC,
((payload, context) -> BookshelfInspector.networkHandlers.bookShelfInventoryRequestServerPayloadHandler.receive(payload, (ServerPlayer) context.player()))
);
registrar.playToServer(
LecternInventoryRequestPayload.ID,
LecternInventoryRequestPayload.CODEC,
((payload, context) -> BookshelfInspector.networkHandlers.lecternInventoryRequestServerPayloadHandler.receive(payload, (ServerPlayer) context.player()))
);
registrar.playToClient(
BookShelfInventoryPayload.ID,
BookShelfInventoryPayload.CODEC,
((payload, context) -> BookshelfInspector.networkHandlers.bookShelfInventoryHandlerServer.receive(payload, (LocalPlayer) context.player()))
);
registrar.playToClient(
ModCheckPayload.ID,
ModCheckPayload.CODEC,
((payload, context) -> BookshelfInspector.networkHandlers.modServerPayloadHandler.receive(payload, (LocalPlayer) context.player()))
);
}
}
@@ -0,0 +1,18 @@
package com.lukasabbe.bookshelfinspector.platform;
import com.lukasabbe.bookshelfinspector.EventHandler;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerDisconnectEvent;
import com.lukasabbe.bookshelfinspector.platform.handlers.OnPlayerJoinEvent;
import com.lukasabbe.bookshelfinspector.platform.services.IEventHelper;
public class NeoForgeEventHelper implements IEventHelper {
@Override
public void registerOnPlayerJoinEvent(OnPlayerJoinEvent event) {
EventHandler.playerJoinEvents.add(event);
}
@Override
public void registerOnPlayerDisconnect(OnPlayerDisconnectEvent event) {
EventHandler.playerDisconnectEvents.add(event);
}
}
@@ -0,0 +1,18 @@
package com.lukasabbe.bookshelfinspector.platform;
import com.lukasabbe.bookshelfinspector.platform.services.INetworkHelper;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.neoforge.network.PacketDistributor;
public class NeoForgeNetworkHelper implements INetworkHelper {
@Override
public void sendPacketFromServer(ServerPlayer player, CustomPacketPayload payload) {
PacketDistributor.sendToPlayer(player, payload);
}
@Override
public void sendPacketFromClient(CustomPacketPayload payload) {
PacketDistributor.sendToServer(payload);
}
}
@@ -0,0 +1,43 @@
package com.lukasabbe.bookshelfinspector.platform;
import com.lukasabbe.bookshelfinspector.platform.services.IPlatformHelper;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.ModList;
import net.neoforged.fml.config.ModConfig;
import net.neoforged.fml.loading.FMLLoader;
import net.neoforged.fml.loading.FMLPaths;
import java.nio.file.Path;
public class NeoForgePlatformHelper implements IPlatformHelper {
@Override
public String getPlatformName() {
return "NeoForge";
}
@Override
public boolean isModLoaded(String modId) {
return ModList.get().isLoaded(modId);
}
@Override
public boolean isDevelopmentEnvironment() {
return !FMLLoader.isProduction();
}
@Override
public Path getConfigPath(String file) {
return FMLPaths.CONFIGDIR.get().resolve(file);
}
@Override
public Path getFileInModContainer(String mod, String fileName) {
if(ModList.get().getModContainerById(mod).isEmpty()) return null;
ModContainer container = ModList.get().getModContainerById(mod).get();
return container.getModInfo().getOwningFile().getFile().findResource(fileName);
}
}
@@ -0,0 +1,34 @@
modLoader = "javafml" #mandatory
loaderVersion = "${neoforge_loader_version_range}" #mandatory
license = "${license}" # Review your options at https://choosealicense.com/.
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
[[mods]] #mandatory
modId = "${mod_id}" #mandatory
version = "${version}" #mandatory
displayName = "${mod_name}" #mandatory
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional (see https://docs.neoforged.net/docs/misc/updatechecker/)
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional (displayed in the mod UI)
logoFile="${mod_id}.png" #optional
credits="${credits}" #optional
authors = "${mod_author}" #optional
description = '''${description}''' #mandatory (Supports multiline text)
[[mixins]]
config = "${mod_id}.mixins.json"
[[dependencies.${mod_id}]] #optional
modId = "neoforge" #mandatory
type="required" #mandatory (Can be one of "required", "optional", "incompatible" or "discouraged")
versionRange = "[${neoforge_version},)" #mandatory
ordering = "NONE" # The order that this dependency should load in relation to your mod, required to be either 'BEFORE' or 'AFTER' if the dependency is not mandatory
side = "BOTH" # Side this dependency is applied on - 'BOTH', 'CLIENT' or 'SERVER'
[[dependencies.${mod_id}]]
modId = "minecraft"
type="required" #mandatory (Can be one of "required", "optional", "incompatible" or "discouraged")
versionRange = "${minecraft_version_range}"
ordering = "NONE"
side = "BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"
@@ -0,0 +1 @@
com.lukasabbe.bookshelfinspector.platform.NeoForgeEventHelper
@@ -0,0 +1 @@
com.lukasabbe.bookshelfinspector.platform.NeoForgeNetworkHelper
@@ -0,0 +1 @@
com.lukasabbe.bookshelfinspector.platform.NeoForgePlatformHelper
+51
View File
@@ -0,0 +1,51 @@
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
exclusiveContent {
forRepository {
maven {
name = 'Fabric'
url = uri('https://maven.fabricmc.net')
}
}
filter {
includeGroup('net.fabricmc')
includeGroup('fabric-loom')
}
}
exclusiveContent {
forRepository {
maven {
name = 'Sponge'
url = uri('https://repo.spongepowered.org/repository/maven-public')
}
}
filter {
includeGroupAndSubgroups("org.spongepowered")
}
}
exclusiveContent {
forRepository {
maven {
name = 'Forge'
url = uri('https://maven.minecraftforge.net')
}
}
filter {
includeGroupAndSubgroups('net.minecraftforge')
}
}
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0'
}
// This should match the folder name of the project, or else IDEA may complain (see https://youtrack.jetbrains.com/issue/IDEA-317606)
rootProject.name = 'BookshelfInspectorMultiloader'
include('common')
include('fabric')
include('neoforge')