40 Commits
v1.2.0 ... main

Author SHA1 Message Date
Martin Prokoph
cd9bae83ca Update WATERMeDIA to 2.1.x 2024-12-31 12:39:22 +01:00
Martin Prokoph
fcdde95971 Remove leftover field in Neoforge 2024-07-07 19:09:36 +02:00
Martin Prokoph
22d3d621da Fix GIFHandler 2024-07-07 18:55:21 +02:00
Martin Prokoph
3b3009fefb Improve Media Handler API
- Also fix logspam
2024-07-07 18:54:15 +02:00
Martin Prokoph
9c550dcd7d Update properties for release 2024-07-03 21:43:51 +02:00
Martin Prokoph
b61a85b5f7 Fix #24 2024-07-03 14:37:26 +02:00
Martin Prokoph
3d532a9c2f Further improvements 2024-07-03 14:03:21 +02:00
Martin Prokoph
db1f6b5896 Further improve Redstone Check 2024-07-03 12:45:46 +02:00
Martin Prokoph
87518c0c11 Improve redstone check 2024-07-03 12:43:11 +02:00
Martin Prokoph
a8e3ae2ffd Split PictureSign and Picture rendering classes 2024-07-03 12:24:40 +02:00
Martin Prokoph
bb5055bf34 Improve PictureSign Renderer
- Allows other mods to also make use of the render methods (Decorative mod update? ;) )
2024-07-03 12:15:13 +02:00
Martin Prokoph
8536139272 Better error handling & translations
- There is now a detailed error message on the surface when a picture/GIF/video could not be loaded
- Made more strings translatable
2024-07-02 23:19:47 +02:00
Martin Prokoph
dd33f55735 Fix video end time and log spam 2024-06-28 15:46:23 +02:00
Martin Prokoph
ea8e6663ab Preview v2 2024-06-28 12:08:54 +02:00
Martin Prokoph
2af17988b0 I hate typos 2024-06-28 10:14:43 +02:00
Martin Prokoph
c7c7372858 Some further improvements 2024-06-28 09:02:14 +02:00
Martin Prokoph
a84ecf359e Some further code cleanup 2024-06-27 14:18:12 +02:00
Martin Prokoph
1196cf05bf Make MediaHandler an abstract system
- Allows for alternative multimedia backend implementations (i.e. #23)
2024-06-27 14:13:27 +02:00
Martin Prokoph
a85a09d554 Add features of #14
- Add support for local images
- Add support for referencing Minecraft textures
Big thanks to @Hendrix-Shen

- Code cleanup
2024-06-27 12:10:05 +02:00
Martin Prokoph
a46d69cf8d Move Simplified Chinese translation to correct folder 2024-06-27 11:14:55 +02:00
Martin Prokoph
46c0daae4d Merge pull request #11 from Frost-ZX/main
Add Simplified Chinese localization
2024-06-27 11:12:58 +02:00
Martin Prokoph
41deb1be8c Allow defining the media volume via JSON
- Also verify JSON hosting website is safe to avoid IP-Grabbers on multiplayer servers
2024-06-27 11:07:45 +02:00
Martin Prokoph
2b3b25d8f3 Fix some issues related to multimedia 2024-06-21 15:10:40 +02:00
Martin Prokoph
38b50a6082 Positional audio 2024-06-21 00:41:39 +02:00
Martin Prokoph
479542175b Re-add Iris compatibility 2024-06-20 23:23:08 +02:00
Martin Prokoph
ce1bc60a87 Neoforge support 2024-06-20 23:14:29 +02:00
Martin Prokoph
64dfcd8a87 Add support for GIFs and Music 2024-06-20 21:32:06 +02:00
Martin Prokoph
948c7f47d1 Huge code cleanup, Architectury & Watermedia
- A huge cleanup of the codebase
- Make use of the Architectury build system
- Replaced VideoLib with WATERMeDIA (More features, better stability, multiplatform support)
2024-06-20 17:55:40 +02:00
Motschen
24b9d4f5b7 PictureSign 2.0.0-beta.2 - 1.20.2
- Ported to 1.20.2
- Updated MidnightLib & VideoLib
- No more crashes when VLC is not installed
- Video now gets properly cleared on disconnect
- Fixed the helper screen not saving changes permanently
2023-11-10 19:16:07 +01:00
Motschen
96469a3e75 PictureSign 2.0 Beta 1 - Video support & rotations
- Port to 1.20.1
- Add support for video playback using VLCj
  - YouTube videos are being played using Invidious, as VLC currently doesn't support YouTube playback
- Add ability to rotate images (on X, Y & Z-axis; only with exceedVanillaLineLength enabled)
- Marginally improve PictureSign helper screen
  - Way less bugs
  - GUI for Video & Rotation
- Support for Hanging signs
- Improved config screen
- Ability to select shader program pictures are being rendered with when using Iris
- Brightness of images is now based on light level at sign position by default
- Ability to load URLs defined in JSON files, allowing for very long URLs like those of Twitch.tv streams, as well as start and stop times for videos
2023-07-29 18:58:36 +02:00
Motschen
358340b2cc Some more refinement 2023-01-04 17:05:56 +01:00
Motschen
d19f537c83 Add possibility to fetch info from JSON files
- Allows for display of images and videos with URLs exceeding the sign's character limit (Twitch Livestreams, anyone?)
- For videos, a custom start and end time can be specified
2023-01-01 19:15:44 +01:00
Frost-ZX
2ac0cbe512 Update Simplified Chinese translation 2022-12-31 20:50:45 +08:00
Motschen
cf917cae64 Some more fixes and improvements 2022-12-26 22:27:58 +01:00
Motschen
29982f838d Improve video support 2022-12-26 22:12:57 +01:00
Motschen
c801e8ecd8 Add video support 2022-12-26 20:30:27 +01:00
Frost-ZX
5649403565 Add Simplified Chinese localization 2022-09-04 13:17:01 +08:00
Motschen
c32654d5d5 PictureSign 1.4.1 - Update to 1.19 2022-06-18 09:29:09 +02:00
Motschen
faaff873da PictureSign 1.4.0 - Assisting UI and Bugfixes 2022-05-27 15:50:08 +02:00
Motschen
69cf564ae7 PictureSign 1.3.0 - Enable translucency in pictures
Also use Iris API instead of internal references
2022-04-29 14:37:25 +02:00
59 changed files with 2556 additions and 525 deletions

3
.gitignore vendored
View File

@@ -22,4 +22,5 @@ bin/
# fabric
run/
run/
/.architectury-transformer

View File

@@ -1,87 +1,82 @@
plugins {
id 'fabric-loom' version '0.8-SNAPSHOT'
id 'maven-publish'
id "architectury-plugin" version "3.4-SNAPSHOT"
id "dev.architectury.loom" version "1.6-SNAPSHOT" apply false
id "me.shedaniel.unified-publishing" version "0.1.+" apply false
id 'com.github.johnrengelman.shadow' version '8.1.1' apply false
}
sourceCompatibility = JavaVersion.VERSION_16
targetCompatibility = JavaVersion.VERSION_16
archivesBaseName = project.archives_base_name
version = project.mod_version
group = project.maven_group
minecraft {
architectury {
minecraft = rootProject.minecraft_version
}
repositories {
maven {
url = "https://api.modrinth.com/maven"
}
maven { url 'https://jitpack.io' }
}
dependencies {
//to change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
subprojects {
apply plugin: "dev.architectury.loom"
repositories {
maven {
url = "https://api.modrinth.com/maven"
}
maven { url 'https://jitpack.io' }
}
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
modImplementation "maven.modrinth:iris:${project.iris_version}"
modImplementation "maven.modrinth:midnightlib:${project.midnightlib_version}"
include "maven.modrinth:midnightlib:${project.midnightlib_version}"
}
processResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
dependencies {
minecraft "com.mojang:minecraft:${rootProject.minecraft_version}"
implementation "com.github.SrRapero720.watermedia:build:${rootProject.watermedia_version}"
// The following line declares the mojmap mappings, you may use other mappings as well
//mappings loom.officialMojangMappings()
// The following line declares the yarn mappings you may select this one as well.
mappings loom.layered {
it.mappings("net.fabricmc:yarn:$rootProject.yarn_mappings:v2")
it.mappings("dev.architectury:yarn-mappings-patch-neoforge:$rootProject.yarn_mappings_patch_neoforge_version")
}
}
}
tasks.withType(JavaCompile).configureEach {
// ensure that the encoding is set to UTF-8, no matter what the system default is
// this fixes some edge cases with special characters not displaying correctly
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
// If Javadoc is generated, this must be specified in that task too.
it.options.encoding = "UTF-8"
// Minecraft 1.17 (21w19a) upwards uses Java 16.
it.options.release = 16
}
allprojects {
apply plugin: "java"
apply plugin: "architectury-plugin"
apply plugin: "maven-publish"
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
archivesBaseName = rootProject.archives_base_name
version = rootProject.mod_version
group = rootProject.maven_group
jar {
from("LICENSE") {
rename { "${it}_${project.archivesBaseName}"}
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
}
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
// add all the jars that should be included when publishing to maven
artifact(remapJar) {
builtBy remapJar
}
artifact(sourcesJar) {
builtBy remapSourcesJar
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
options.release = 21
}
ext {
releaseChangelog = {
def changes = new StringBuilder()
changes << "## PictureSign v$project.version for $project.minecraft_version\n[View the changelog](https://www.github.com/TeamMidnightDust/PictureSign/commits/)"
def proc = "git log --max-count=1 --pretty=format:%s".execute()
proc.in.eachLine { line ->
def processedLine = line.toString()
if (!processedLine.contains("New translations") && !processedLine.contains("Merge") && !processedLine.contains("branch")) {
changes << "\n- ${processedLine.capitalize()}"
}
}
proc.waitFor()
return changes.toString()
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
java {
withSourcesJar()
}
}

25
common/build.gradle Normal file
View File

@@ -0,0 +1,25 @@
architectury {
common(rootProject.enabled_platforms.split(","))
}
dependencies {
// We depend on fabric loader here to use the fabric @Environment annotations and get the mixin dependencies
// Do NOT use other classes from fabric loader
modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}"
modCompileOnlyApi "maven.modrinth:midnightlib:${rootProject.midnightlib_version}-fabric"
modCompileOnly "maven.modrinth:iris:${project.iris_version}"
}
publishing {
publications {
mavenCommon(MavenPublication) {
artifactId = rootProject.archives_base_name
from components.java
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
}
}

View File

@@ -0,0 +1,35 @@
package eu.midnightdust.picturesign;
import eu.midnightdust.lib.util.PlatformFunctions;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.util.GIFHandler;
import eu.midnightdust.picturesign.util.MediaHandler;
import eu.midnightdust.picturesign.util.WaterGIFHandler;
import eu.midnightdust.picturesign.util.WaterMediaHandler;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import net.minecraft.util.Identifier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.glfw.GLFW;
public class PictureSignClient {
public static Logger LOGGER = LogManager.getLogger("PictureSign");
public static final String MOD_ID = "picturesign";
public static String[] clipboard = new String[4];
public static final MinecraftClient client = MinecraftClient.getInstance();
public static final KeyBinding BINDING_COPY_SIGN = new KeyBinding("key."+MOD_ID+".copy_sign",
InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_U, "key.categories."+MOD_ID);
public static void init() {
PictureSignConfig.init(MOD_ID, PictureSignConfig.class);
if (PlatformFunctions.isModLoaded("watermedia")) {
MediaHandler.registerHandler(WaterMediaHandler::new);
GIFHandler.registerHandler(WaterGIFHandler::new);
}
}
public static Identifier id(String path) {
return Identifier.of(MOD_ID, path);
}
}

View File

@@ -0,0 +1,48 @@
package eu.midnightdust.picturesign.config;
import com.google.common.collect.Lists;
import eu.midnightdust.lib.config.MidnightConfig;
import net.minecraft.client.gl.ShaderProgram;
import net.minecraft.client.render.GameRenderer;
import java.util.List;
import java.util.function.Supplier;
public class PictureSignConfig extends MidnightConfig {
private static final String general = "1general";
private static final String advanced = "advanced";
@Entry(category = general) public static boolean enabled = true;
@Entry(category = general) public static boolean enableMultimediaSigns = true;
@Entry(min = 0, max = 1000, isSlider = true, category = general) public static int audioDistanceMultiplier = 30;
@Entry(category = general) public static boolean translucency = false;
@Entry(category = general) public static boolean fullBrightPicture = false;
@Entry(category = general) public static boolean helperUi = true;
@Entry(category = general) public static boolean exceedVanillaLineLength = true;
@Entry(category = advanced) public static boolean debug = false;
@Entry(min = 1, max = 10, isSlider = true, category = advanced) public static int maxThreads = 4;
@Entry(min = 0, max = 2048, isSlider = true, category = general) public static int signRenderDistance = 64;
@Entry(category = advanced) public static boolean safeMode = true;
@Entry(category = advanced) public static List<String> safeProviders = Lists.newArrayList("https://i.imgur.com/", "https://i.ibb.co/", "https://pictshare.net/", "https://iili.io/");
@Entry(category = advanced) public static List<String> safeGifProviders = Lists.newArrayList("https://i.imgur.com/", "https://media1.tenor.com/");
@Entry(category = advanced) public static List<String> safeMultimediaProviders = Lists.newArrayList("https://youtube.com/", "https://www.youtube.com/", "https://youtu.be/","https://vimeo.com/");
@Entry(category = advanced) public static List<String> safeJsonProviders = Lists.newArrayList("https://github.com/", "https://gist.github.com/", "https://www.jsonkeeper.com/", "https://api.npoint.io/", "https://api.jsonsilo.com/");
@Comment(category = general) public static Comment ebeWarning;
@Entry(category = advanced) public static MissingImageMode missingImageMode = MissingImageMode.BLACK;
@Entry(category = advanced) public static PictureShader pictureShader = PictureShader.PosColTexLight;
public enum MissingImageMode {
BLACK, MISSING_TEXTURE, TRANSPARENT
}
public enum PictureShader {
PosColTexLight(GameRenderer::getPositionColorTexLightmapProgram),
RenderTypeCutout(GameRenderer::getRenderTypeCutoutProgram),
PosTex(GameRenderer::getPositionTexProgram),
PosTexCol(GameRenderer::getPositionTexColorProgram);
PictureShader(Supplier<ShaderProgram> program) {
this.program = program;
}
public final Supplier<ShaderProgram> program;
}
}

View File

@@ -0,0 +1,41 @@
package eu.midnightdust.picturesign.mixin;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.render.PictureSignRenderer;
import eu.midnightdust.picturesign.util.PictureSignType;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.BlockEntityRenderer;
import net.minecraft.client.render.block.entity.HangingSignBlockEntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import org.spongepowered.asm.mixin.Mixin;
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;
import static eu.midnightdust.picturesign.util.PictureSignType.isCandidate;
import static eu.midnightdust.picturesign.util.PictureSignType.isNotOfType;
@Mixin(HangingSignBlockEntityRenderer.class)
public abstract class MixinHangingSignBlockEntityRenderer implements BlockEntityRenderer<SignBlockEntity> {
@Unique PictureSignRenderer psRenderer = new PictureSignRenderer();
@Inject(at = @At("HEAD"), method = "render")
public void ps$onRender(SignBlockEntity sign, float f, MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int light, int overlay, CallbackInfo ci) {
if (PictureSignConfig.enabled) {
if (isCandidate(sign, true) && isNotOfType(sign, PictureSignType.NONE, true)) psRenderer.render(sign, matrixStack, vertexConsumerProvider, light, overlay, true);
if (isCandidate(sign, false) && isNotOfType(sign, PictureSignType.NONE, false)) psRenderer.render(sign, matrixStack, vertexConsumerProvider, light, overlay, false);
}
}
@Unique
@Override
public int getRenderDistance() {
return PictureSignConfig.signRenderDistance;
}
@Unique
@Override
public boolean rendersOutsideBoundingBox(SignBlockEntity sign) {
return PictureSignConfig.enabled && PictureSignType.hasPicture(sign);
}
}

View File

@@ -0,0 +1,30 @@
package eu.midnightdust.picturesign.mixin;
import eu.midnightdust.picturesign.util.MediaHandler;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import static eu.midnightdust.picturesign.PictureSignClient.id;
@Mixin(value = SignBlockEntity.class, priority = 1100)
public abstract class MixinSignBlockEntity extends BlockEntity {
public MixinSignBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
}
@Override
@Unique
public void markRemoved() {
Identifier videoId = id(pos.getX() + "_" + pos.getY() + "_" + pos.getZ() + "_f");
Identifier videoId2 = id(pos.getX() + "_" + pos.getY() + "_" + pos.getZ() + "_b");
MediaHandler.closePlayer(videoId);
MediaHandler.closePlayer(videoId2);
super.markRemoved();
}
}

View File

@@ -0,0 +1,55 @@
package eu.midnightdust.picturesign.mixin;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.render.PictureSignRenderer;
import eu.midnightdust.picturesign.util.PictureSignType;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.BlockEntityRenderer;
import net.minecraft.client.render.block.entity.BlockEntityRendererFactory;
import net.minecraft.client.render.block.entity.SignBlockEntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Mixin;
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;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import static eu.midnightdust.picturesign.PictureSignClient.client;
import static eu.midnightdust.picturesign.util.PictureSignType.isCandidate;
import static eu.midnightdust.picturesign.util.PictureSignType.isNotOfType;
import static eu.midnightdust.picturesign.util.PictureSignType.hasPicture;
@Mixin(SignBlockEntityRenderer.class)
public abstract class MixinSignBlockEntityRenderer implements BlockEntityRenderer<SignBlockEntity> {
@Unique private PictureSignRenderer psRenderer;
@Inject(at = @At("TAIL"), method = "<init>")
public void ps$onInit(BlockEntityRendererFactory.Context ctx, CallbackInfo ci) {
psRenderer = new PictureSignRenderer();
}
@Inject(at = @At("HEAD"), method = "render")
public void ps$onRender(SignBlockEntity sign, float f, MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int light, int overlay, CallbackInfo ci) {
if (PictureSignConfig.enabled && psRenderer != null) {
if (isCandidate(sign, true) && isNotOfType(sign, PictureSignType.NONE, true)) psRenderer.render(sign, matrixStack, vertexConsumerProvider, light, overlay, true);
if (isCandidate(sign, false) && isNotOfType(sign, PictureSignType.NONE, false)) psRenderer.render(sign, matrixStack, vertexConsumerProvider, light, overlay, false);
}
}
@Inject(at = @At("HEAD"), method = "shouldRender", cancellable = true)
private static void shouldRender(BlockPos pos, int signColor, CallbackInfoReturnable<Boolean> cir) {
if (PictureSignConfig.enabled && client.world != null && hasPicture((SignBlockEntity) client.world.getBlockEntity(pos))) cir.setReturnValue(true);
}
@Unique
@Override
public int getRenderDistance() {
return PictureSignConfig.signRenderDistance;
}
@Unique
@Override
public boolean rendersOutsideBoundingBox(SignBlockEntity sign) {
return PictureSignConfig.enabled && hasPicture(sign);
}
}

View File

@@ -0,0 +1,80 @@
package eu.midnightdust.picturesign.mixin;
import eu.midnightdust.picturesign.PictureSignClient;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.screen.PictureSignHelperScreen;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.ingame.AbstractSignEditScreen;
import net.minecraft.client.gui.widget.TextIconButtonWidget;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
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;
import java.util.Objects;
import static eu.midnightdust.picturesign.PictureSignClient.id;
@Mixin(AbstractSignEditScreen.class)
public abstract class MixinSignEditScreen extends Screen {
@Shadow @Final private SignBlockEntity blockEntity;
@Shadow @Final private String[] messages;
@Shadow @Final private boolean front;
@Unique private static final Identifier PICTURESIGN_ICON_TEXTURE = id("icon/picturesign");
@Unique private static final Identifier CLIPBOARD_ICON_TEXTURE = id("icon/clipboard");
@Unique private static final Identifier TRASHBIN_ICON_TEXTURE = id("icon/trashbin");
@Unique private static boolean switchScreen = false;
protected MixinSignEditScreen(Text title) {
super(title);
}
@Inject(at = @At("TAIL"),method = "init")
private void picturesign$init(CallbackInfo ci) {
if (PictureSignClient.clipboard != null && PictureSignClient.clipboard[0] != null) {
TextIconButtonWidget clipboardBuilder = TextIconButtonWidget.builder(Text.empty(), (buttonWidget) -> {
for (int i = 0; i < 4; i++) {
messages[i] = PictureSignClient.clipboard[i];
int finalI = i;
blockEntity.changeText(changer -> changer.withMessage(finalI, Text.of(messages[finalI])), front);
}
}, true).texture(CLIPBOARD_ICON_TEXTURE, 16, 16).dimension(20, 20).build();
clipboardBuilder.setPosition(this.width - 84, this.height - 40);
this.addDrawableChild(clipboardBuilder);
}
if (PictureSignConfig.helperUi) {
TextIconButtonWidget trashbinBuilder = TextIconButtonWidget.builder(Text.empty(), (buttonWidget) -> {
for (int i = 0; i < 4; i++) {
messages[i] = "";
int finalI = i;
blockEntity.changeText(changer -> changer.withMessage(finalI, Text.empty()), front);
}
}, true).texture(TRASHBIN_ICON_TEXTURE, 16, 16).dimension(20, 20).build();
trashbinBuilder.setPosition(this.width - 62, this.height - 40);
this.addDrawableChild(trashbinBuilder);
TextIconButtonWidget picturesignBuilder = TextIconButtonWidget.builder(Text.empty(), (buttonWidget) -> {
switchScreen = true;
Objects.requireNonNull(client).setScreen(new PictureSignHelperScreen(this.blockEntity, front, false));
}, true).texture(PICTURESIGN_ICON_TEXTURE, 16, 16).dimension(20, 20).build();
picturesignBuilder.setPosition(this.width - 40, this.height - 40);
this.addDrawableChild(picturesignBuilder);
}
}
@Inject(at = @At("HEAD"), method = "removed", cancellable = true)
private void picturesign$removed(CallbackInfo ci) {
if (switchScreen) {
switchScreen = false;
ci.cancel();
}
}
}

View File

@@ -0,0 +1,267 @@
package eu.midnightdust.picturesign.render;
import com.mojang.blaze3d.systems.RenderSystem;
import eu.midnightdust.lib.util.PlatformFunctions;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.util.GIFHandler;
import eu.midnightdust.picturesign.util.IrisCompat;
import eu.midnightdust.picturesign.util.MediaHandler;
import eu.midnightdust.picturesign.util.PictureDownloader;
import eu.midnightdust.picturesign.util.PictureSignType;
import eu.midnightdust.picturesign.util.PictureURLUtils;
import eu.midnightdust.picturesign.util.records.MediaJsonInfo;
import eu.midnightdust.picturesign.util.records.PictureDimensions;
import eu.midnightdust.picturesign.util.records.PictureOffset;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.BufferRenderer;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.VertexFormat;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.state.property.Properties;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RotationAxis;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import java.util.Iterator;
import static eu.midnightdust.picturesign.PictureSignClient.client;
import static eu.midnightdust.picturesign.PictureSignClient.id;
import static eu.midnightdust.picturesign.util.PictureSignType.GIF;
import static eu.midnightdust.picturesign.util.PictureSignType.PICTURE;
import static net.minecraft.client.texture.TextureManager.MISSING_IDENTIFIER;
public class PictureRenderer {
private boolean isSafeUrl;
private boolean isSafeJsonUrl;
public static final Text ERROR = Text.translatable("picturesign.error");
public static final Text MISSING_VLC = ERROR.copy().append(Text.translatable("picturesign.error.missingVLC"));
public static final Text MISSING_WATERMEDIA = ERROR.copy().append(Text.translatable("picturesign.error.missingWatermedia"));
public static final Text IMAGE_NOT_FOUND = ERROR.copy().append(Text.translatable("picturesign.error.imageNotFound"));
public static final Text UNKNOWN_FILETYPE = ERROR.copy().append(Text.translatable("picturesign.error.unknownFiletype"));
public static final Text UNKNOWN_SIGNTYPE = ERROR.copy().append(Text.translatable("picturesign.error.unknownSigntype"));
public static final Text UNSAFE_JSON_URL = ERROR.copy().append(Text.translatable("picturesign.error.unsafeJsonUrl"));
public static final Text UNSAFE_URL = ERROR.copy().append(Text.translatable("picturesign.error.unsafeUrl"));
public static final Identifier RAW_TEXTURE = id("internal_raw_texture");
public void render(BlockEntity blockEntity, PictureSignType type, String url, PictureDimensions dimensions, PictureOffset offset, boolean front, MatrixStack matrixStack, VertexConsumerProvider vertices, int light, int overlay) {
Text errorMessage = null;
MediaJsonInfo info = null;
if (!url.contains("://") && !url.startsWith("file:") && !url.startsWith("rp:")) {
url = "https://" + url;
}
checkJsonUrlSafety(url);
if (url.endsWith(".json") || isSafeJsonUrl) {
if (PictureSignConfig.safeMode && !isSafeJsonUrl) errorMessage = UNSAFE_JSON_URL;
if (errorMessage == null) {
info = PictureURLUtils.infoFromJson(url);
if (info == null) return;
url = info.url();
if (!url.contains("://")) {
url = "https://" + url;
}
}
}
if ((type == PICTURE && !url.contains(".png") && !url.contains(".jpg") && !url.contains(".jpeg") && !url.startsWith("rp:"))
|| (type == GIF && !url.contains(".gif"))) errorMessage = UNKNOWN_FILETYPE;
if (PictureSignConfig.safeMode && !url.startsWith("file:") && !url.startsWith("rp:") && !isUrlSafe(type, url)) errorMessage = UNSAFE_URL;
if (!PictureSignConfig.enableMultimediaSigns && type != PICTURE && type != GIF) return;
if (!MediaHandler.hasValidImplementation() && type != PICTURE) errorMessage = MISSING_WATERMEDIA;
if (url.startsWith("https://www.youtube.com/watch?v=")) {
url = url.replace("https://www.", "https://");
}
BlockPos pos = blockEntity.getPos();
String videoSuffix = front ? "_f" : "_b";
Identifier videoId = id(pos.getX() + "_" + pos.getY() + "_" + pos.getZ() + videoSuffix);
MediaHandler mediaHandler = null;
GIFHandler gifHandler = null;
if (errorMessage == null) {
if ((type.isVideo || type.isAudio) && MediaHandler.hasValidImplementation()) mediaHandler = MediaHandler.getOrCreate(videoId, pos);
else if (type == GIF && GIFHandler.hasValidImplementation()) gifHandler = GIFHandler.getOrCreate(videoId);
else {
MediaHandler.closePlayer(videoId);
GIFHandler.closePlayer(videoId);
}
}
if (isDisabledViaRedstone(blockEntity.getWorld(), pos)) {
if (mediaHandler != null && mediaHandler.isWorking() && !mediaHandler.isStopped()) mediaHandler.stop();
return;
}
else if (mediaHandler != null && mediaHandler.isDeactivated) {
if (mediaHandler.isWorking() && mediaHandler.isStopped())
mediaHandler.restart();
}
PictureDownloader.PictureData data = null;
if (errorMessage == null && type == PICTURE) {
data = PictureDownloader.getInstance().getPicture(url);
if (data == null || data.identifier == null) errorMessage = IMAGE_NOT_FOUND;
}
else if (mediaHandler != null) {
if (!mediaHandler.isReady()) errorMessage = MISSING_VLC;
else {
if (!mediaHandler.playbackStarted && !mediaHandler.hasMedia()) {
mediaHandler.play(url, type.isVideo);
if (info != null && info.start() > 0) mediaHandler.setTime(info.start());
mediaHandler.setRepeat(type.isLooped);
}
if (info != null && info.volume() >= 0) mediaHandler.setMaxVolume(info.volume());
mediaHandler.setVolumeBasedOnDistance();
if (info != null && info.start() > 0 && mediaHandler.getTime() < info.start())
mediaHandler.setTime(info.start());
if (info != null && info.end() > 0 && mediaHandler.getTime() > info.end()) {
if (type.isLooped) mediaHandler.setTime(info.start() > 0 ? info.start() : 0);
else mediaHandler.stop();
}
}
}
else if (type == GIF && gifHandler != null) {
if (!gifHandler.hasMedia() && !gifHandler.playbackStarted) {
gifHandler.play(url);
}
}
else if (errorMessage == null) errorMessage = UNKNOWN_SIGNTYPE;
if (type.isAudio || offset == null) return;
Tessellator tessellator = Tessellator.getInstance();
int l = PictureSignConfig.fullBrightPicture ? 15728880 : light;
if (PlatformFunctions.isModLoaded("iris") && IrisCompat.isShaderPackInUse())
RenderSystem.setShader(PictureSignConfig.pictureShader.program);
else RenderSystem.setShader(GameRenderer::getPositionColorTexLightmapProgram);
Identifier texture = getMissingTexture();
if (errorMessage == null) {
if (type == PICTURE) {
assert data != null;
texture = data.identifier;
} else if (type.isVideo && mediaHandler != null) {
if (mediaHandler.isWorking()) {
mediaHandler.preRender();
int rawTexture = mediaHandler.getTexture();
if (rawTexture != -1) {
RenderSystem.setShaderTexture(0, rawTexture);
texture = RAW_TEXTURE;
}
}
} else if (gifHandler != null) {
if (gifHandler.isWorking()) {
RenderSystem.setShaderTexture(0, gifHandler.getTexture());
texture = RAW_TEXTURE;
}
}
}
if (texture == null) return;
if (texture != RAW_TEXTURE) RenderSystem.setShaderTexture(0, texture);
if (PictureSignConfig.translucency) RenderSystem.enableBlend();
else RenderSystem.disableBlend();
RenderSystem.enableDepthTest();
RenderSystem.depthMask(true);
matrixStack.push();
matrixStack.translate(offset.xOffset() + dimensions.x(), dimensions.y(), offset.zOffset() + dimensions.z());
matrixStack.multiply(RotationAxis.POSITIVE_Y.rotationDegrees(offset.yRotation() + dimensions.yRot()));
matrixStack.multiply(RotationAxis.POSITIVE_X.rotationDegrees(dimensions.xRot()));
matrixStack.multiply(RotationAxis.POSITIVE_Z.rotationDegrees(dimensions.zRot()));
Matrix4f matrix4f = matrixStack.peek().getPositionMatrix();
BufferBuilder buffer = tessellator.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR_TEXTURE_LIGHT);
buffer.vertex(matrix4f, dimensions.width(), 0.0F, 1.0F).color(255, 255, 255, 255).texture(1.0F, 1.0F).light(l).overlay(overlay);
buffer.vertex(matrix4f, dimensions.width(), dimensions.height(), 1.0F).color(255, 255, 255, 255).texture(1.0F, 0.0F).light(l).overlay(overlay);
buffer.vertex(matrix4f, 0.0F, dimensions.height(), 1.0F).color(255, 255, 255, 255).texture(0.0F, 0.0F).light(l).overlay(overlay);
buffer.vertex(matrix4f, 0.0F, 0.0F, 1.0F).color(255, 255, 255, 255).texture(0.0F, 1.0F).light(l).overlay(overlay);
BufferRenderer.drawWithGlobalProgram(buffer.end());
if (errorMessage != null) renderErrorMessage(errorMessage, client.textRenderer, matrixStack, vertices, dimensions.width(), dimensions.height());
matrixStack.pop();
RenderSystem.disableBlend();
RenderSystem.disableDepthTest();
}
private static void renderErrorMessage(Text error, @NotNull TextRenderer textRenderer, @NotNull MatrixStack matrices, VertexConsumerProvider vertices, float width, float height) {
float scale = Math.min(width, height) / 100;
matrices.translate(0, height, 1.005f);
matrices.multiply(RotationAxis.POSITIVE_Y.rotationDegrees(180));
matrices.multiply(RotationAxis.POSITIVE_Z.rotationDegrees(180));
matrices.scale(scale,scale,scale);
int wrappedY = 0;
for(Iterator<OrderedText> textIterator = textRenderer.wrapLines(error, MathHelper.floor(width/scale)).iterator(); textIterator.hasNext(); wrappedY += 9) {
renderTextWithShadow(textIterator.next(), wrappedY, textRenderer, matrices.peek().getPositionMatrix(), vertices);
}
}
private static void renderTextWithShadow(OrderedText text, int wrappedY, @NotNull TextRenderer textRenderer, Matrix4f matrix, VertexConsumerProvider vertices) {
textRenderer.draw(text, 0, wrappedY, 0xFFFFFF, false, matrix, vertices, TextRenderer.TextLayerType.POLYGON_OFFSET, 0, 15728880);
matrix.translate(0, 0, 0.025f);
textRenderer.draw(text, 1, wrappedY + 1, 0x555555, false, matrix, vertices, TextRenderer.TextLayerType.POLYGON_OFFSET, 0, 15728880);
matrix.translate(0, 0, -0.025f);
}
private static final Identifier BLACK_TEXTURE = id("textures/black.png");
public @Nullable Identifier getMissingTexture() {
return switch (PictureSignConfig.missingImageMode) {
case BLACK -> BLACK_TEXTURE;
case MISSING_TEXTURE -> MISSING_IDENTIFIER;
default -> null;
};
}
public void checkJsonUrlSafety(String jsonUrl) {
isSafeJsonUrl = false;
PictureSignConfig.safeJsonProviders.forEach(safe -> {
if (!isSafeJsonUrl) isSafeJsonUrl = jsonUrl.startsWith(safe);
});
}
public boolean isUrlSafe(PictureSignType type, String url) {
isSafeUrl = false;
if (type == PICTURE) {
PictureSignConfig.safeProviders.forEach(safe -> {
if (!isSafeUrl) isSafeUrl = url.startsWith(safe);
});
}
else if (type == GIF) {
PictureSignConfig.safeGifProviders.forEach(safe -> {
if (!isSafeUrl) isSafeUrl = url.startsWith(safe);
});
}
else if (type.isVideo || type.isAudio) {
PictureSignConfig.safeMultimediaProviders.forEach(safe -> {
if (!isSafeUrl) isSafeUrl = url.startsWith(safe);
});
}
return isSafeUrl;
}
public boolean isDisabledViaRedstone(World world, BlockPos pos) {
if (world == null) return false;
BlockState state = world.getBlockState(pos.down()).contains(Properties.LIT) ? world.getBlockState(pos.down()) : world.getBlockState(pos.up());
if (state.contains(Properties.LIT)) return state.get(Properties.LIT).equals(false);
return false;
}
}

View File

@@ -0,0 +1,89 @@
package eu.midnightdust.picturesign.render;
import eu.midnightdust.picturesign.util.records.PictureDimensions;
import eu.midnightdust.picturesign.util.records.PictureOffset;
import eu.midnightdust.picturesign.util.PictureSignType;
import eu.midnightdust.picturesign.util.PictureURLUtils;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.state.property.Properties;
import net.minecraft.util.math.Direction;
import static eu.midnightdust.picturesign.util.PictureSignType.getType;
public class PictureSignRenderer extends PictureRenderer {
public void render(SignBlockEntity signBlockEntity, MatrixStack matrixStack, VertexConsumerProvider vertices, int light, int overlay, boolean front) {
String lastLine = signBlockEntity.getText(front).getMessage(3, false).getString();
if (!lastLine.matches("(.*\\d:.*\\d:.*\\d:.*\\d:.*\\d)")) return;
PictureDimensions dimensions = getDimensions(signBlockEntity.getText(front).getMessage(2, false).getString(), lastLine);
PictureSignType type = getType(signBlockEntity, front);
super.render(signBlockEntity, type, PictureURLUtils.getLink(signBlockEntity, front), dimensions, getOffset(signBlockEntity, front, type), front, matrixStack, vertices, light, overlay);
}
private static PictureDimensions getDimensions(String thirdLine, String forthLine) {
String[] scale = forthLine.split(":");
float width = 0;
float height = 0;
float x = 0;
float y = 0;
float z = 0;
try {
width = Float.parseFloat(scale[0]);
height = Float.parseFloat(scale[1]);
x = Float.parseFloat(scale[2]);
y = Float.parseFloat(scale[3]);
z = Float.parseFloat(scale[4]);
}
catch (NumberFormatException ignored) {}
boolean hasRotation = thirdLine.matches("(.*\\d:.*\\d:.*\\d)");
float xRot = 0;
float yRot = 0;
float zRot = 0;
if (hasRotation) {
String[] rotation = thirdLine.split(":");
try {
xRot = Float.parseFloat(rotation[0]);
yRot = Float.parseFloat(rotation[1]);
zRot = Float.parseFloat(rotation[2]);
} catch (NumberFormatException ignored) {
}
}
return new PictureDimensions(width, height, x, y, z, xRot, yRot, zRot);
}
private static PictureOffset getOffset(BlockEntity blockEntity, boolean front, PictureSignType type) {
if (type.isAudio) return null;
float xOffset = 0.0F;
float zOffset = 0.0F;
float yRotation = 0;
if (blockEntity.getCachedState().contains(Properties.HORIZONTAL_FACING)) {
Direction direction = blockEntity.getCachedState().get(Properties.HORIZONTAL_FACING);
switch (direction) {
case NORTH -> {
zOffset = 1.01F;
xOffset = 1.0F;
yRotation = 180;
}
case SOUTH -> zOffset = 0.010F;
case EAST -> {
zOffset = 1.01F;
yRotation = 90;
}
case WEST -> {
yRotation = -90;
xOffset = 1.01F;
}
}
}
else if (blockEntity.getCachedState().contains(Properties.ROTATION)) {
yRotation = blockEntity.getCachedState().get(Properties.ROTATION) * -22.5f;
}
else return null;
if (!front) yRotation -= 180f;
return new PictureOffset(xOffset, zOffset, yRotation);
}
}

View File

@@ -0,0 +1,395 @@
package eu.midnightdust.picturesign.screen;
import eu.midnightdust.picturesign.PictureSignClient;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.util.NetworkUtil;
import eu.midnightdust.picturesign.util.PictureSignType;
import eu.midnightdust.picturesign.util.PictureURLUtils;
import net.minecraft.block.AbstractSignBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.HangingSignBlock;
import net.minecraft.block.SignBlock;
import net.minecraft.block.WallHangingSignBlock;
import net.minecraft.block.WoodType;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.ingame.HangingSignEditScreen;
import net.minecraft.client.gui.screen.ingame.SignEditScreen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.gui.widget.SliderWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.gui.widget.TextIconButtonWidget;
import net.minecraft.client.render.DiffuseLighting;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.TexturedRenderLayers;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.SignBlockEntityRenderer;
import net.minecraft.client.util.SpriteIdentifier;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.network.packet.c2s.play.UpdateSignC2SPacket;
import net.minecraft.screen.ScreenTexts;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import static eu.midnightdust.picturesign.PictureSignClient.id;
public class PictureSignHelperScreen extends Screen {
private static final Identifier TEXTSIGN_ICON_TEXTURE = id("icon/textsign");
private static final Identifier CLIPBOARD_ICON_TEXTURE = id("icon/clipboard");
private static final Identifier TRASHBIN_ICON_TEXTURE = id("icon/trashbin");
private final SignBlockEntity sign;
private SignBlockEntityRenderer.SignModel model;
protected String[] text;
private final boolean front;
private final boolean isHanging;
protected final WoodType signType;
private static boolean switchScreen = false;
private final List<ClickableWidget> pictureWidgets = new ArrayList<>();
private PictureSignType type = PictureSignType.PICTURE;
public PictureSignHelperScreen(SignBlockEntity sign, boolean front, boolean filtered) {
super((sign.getCachedState().getBlock() instanceof HangingSignBlock || sign.getCachedState().getBlock() instanceof WallHangingSignBlock) ? Text.translatable("hanging_sign.edit") : Text.translatable("sign.edit"));
this.text = IntStream.range(0, 4).mapToObj((row) ->
sign.getText(front).getMessage(row, filtered)).map(Text::getString).toArray(String[]::new);
this.sign = sign;
this.signType = AbstractSignBlock.getWoodType(sign.getCachedState().getBlock());
this.isHanging = sign.getCachedState().getBlock() instanceof HangingSignBlock || sign.getCachedState().getBlock() instanceof WallHangingSignBlock;
this.front = front;
}
protected void init() {
super.init();
if (this.client == null) return;
text = IntStream.range(0, 4).mapToObj((row) ->
sign.getText(front).getMessage(row, false)).map(Text::getString).toArray(String[]::new);
if (!text[3].matches("(.*\\d:.*\\d:.*\\d:.*\\d:.*\\d)")) text[3] = "1:1:0:0:0";
if (!text[0].startsWith("!")) text[0] = PictureSignType.PICTURE.format+text[0];
if (text[2].isBlank() && PictureSignConfig.exceedVanillaLineLength) text[2] = "0:0:0";
for (int i = 0; i < 4; i++) {
int finalI = i;
sign.changeText(changer -> changer.withMessage(finalI, Text.of(text[finalI])), front);
}
this.addDrawableChild(ButtonWidget.builder(ScreenTexts.DONE, (button) -> this.finishEditing()).dimensions(this.width / 2 - 100, this.height / 4 + 120, 200, 20).build());
if (PictureSignClient.clipboard != null && PictureSignClient.clipboard[0] != null) {
TextIconButtonWidget clipboardBuilder = TextIconButtonWidget.builder(Text.empty(), (buttonWidget) -> {
for (int i = 0; i < 4; i++) {
text[i] = PictureSignClient.clipboard[i];
int finalI = i;
sign.changeText(changer -> changer.withMessage(finalI, Text.of(text[finalI])), front);
}
assert client != null;
client.setScreen(this);
}, true).texture(CLIPBOARD_ICON_TEXTURE, 16, 16).dimension(20, 20).build();
clipboardBuilder.setPosition(this.width - 84, this.height - 40);
this.addDrawableChild(clipboardBuilder);
}
if (PictureSignConfig.helperUi) {
TextIconButtonWidget trashbinBuilder = TextIconButtonWidget.builder(Text.empty(), (buttonWidget) -> {
for (int i = 0; i < 4; i++) {
text[i] = "";
int finalI = i;
sign.changeText(changer -> changer.withMessage(finalI, Text.empty()), front);
}
assert client != null;
client.setScreen(this);
}, true).texture(TRASHBIN_ICON_TEXTURE, 16, 16).dimension(20, 20).build();
trashbinBuilder.setPosition(this.width - 62, this.height - 40);
this.addDrawableChild(trashbinBuilder);
TextIconButtonWidget textsignBuilder = TextIconButtonWidget.builder(Text.empty(), (buttonWidget) -> {
switchScreen = true;
Objects.requireNonNull(client).setScreen(isHanging ? new HangingSignEditScreen(this.sign, false, front) : new SignEditScreen(this.sign, front, false));
}, true).texture(TEXTSIGN_ICON_TEXTURE, 16, 16).dimension(20, 20).build();
textsignBuilder.setPosition(this.width - 40, this.height - 40);
this.addDrawableChild(textsignBuilder);
}
type = PictureSignType.getType(text[0]);
this.addDrawableChild(ButtonWidget.builder(type.name, (buttonWidget) -> {
text[0] = text[0].replace(type.format, "");
type = type.next();
text[0] = type.format + text[0];
buttonWidget.setMessage(type.name);
sign.changeText(changer -> changer.withMessage(0, Text.of(text[0])), front);
}).dimensions(this.width / 2,this.height / 5 + 70,40,20).build());
TextFieldWidget linkWidget = new TextFieldWidget(textRenderer,this.width / 2 - 175,this.height / 5 + 13,215,40, Text.of("url"));
linkWidget.setMaxLength(900);
linkWidget.setText(PictureURLUtils.getLink(sign, front));
linkWidget.setChangedListener(s -> {
String[] lines = breakLink(type.format, PictureURLUtils.shortenLink(s));
for (int i = 0; i < (PictureSignConfig.exceedVanillaLineLength ? 2 : 3); i++) {
text[i] = lines[i];
int finalI = i;
sign.changeText(changer -> changer.withMessage(finalI, Text.of(text[finalI])), front);
}
});
this.addDrawableChild(linkWidget);
String[] initialDimensions = text[3].split(":");
TextFieldWidget widthWidget = new TextFieldWidget(textRenderer,this.width / 2 - 175,this.height / 5 + 70,30,20, Text.of("width"));
TextFieldWidget heightWidget = new TextFieldWidget(textRenderer,this.width / 2 - 140,this.height / 5 + 70,30,20, Text.of("height"));
TextFieldWidget posXWidget = new TextFieldWidget(textRenderer,this.width / 2 - 105,this.height / 5 + 70,30,20, Text.of("posX"));
TextFieldWidget posYWidget = new TextFieldWidget(textRenderer,this.width / 2 - 70,this.height / 5 + 70,30,20, Text.of("posY"));
TextFieldWidget posZWidget = new TextFieldWidget(textRenderer,this.width / 2 - 35,this.height / 5 + 70,30,20, Text.of("posZ"));
widthWidget.setText(initialDimensions[0]);
heightWidget.setText(initialDimensions[1]);
posXWidget.setText(initialDimensions[2]);
posYWidget.setText(initialDimensions[3]);
posZWidget.setText(initialDimensions[4]);
widthWidget.setChangedListener(s -> applyPosition(s, 0));
heightWidget.setChangedListener(s -> applyPosition(s, 1));
posXWidget.setChangedListener(s -> applyPosition(s, 2));
posYWidget.setChangedListener(s -> applyPosition(s, 3));
posZWidget.setChangedListener(s -> applyPosition(s, 4));
this.addDrawableChild(widthWidget);
this.addDrawableChild(heightWidget);
this.addDrawableChild(posXWidget);
this.addDrawableChild(posYWidget);
this.addDrawableChild(posZWidget);
pictureWidgets.add(widthWidget);
pictureWidgets.add(heightWidget);
pictureWidgets.add(posXWidget);
pictureWidgets.add(posYWidget);
pictureWidgets.add(posZWidget);
if (text[2].matches("(.*\\d:.*\\d:.*\\d)")) addRotationWidgets();
this.model = SignBlockEntityRenderer.createSignModel(this.client.getEntityModelLoader(), AbstractSignBlock.getWoodType(sign.getCachedState().getBlock()));
}
public void applyPosition(String position, int index) {
String[] dimensions = new String[5];
for (int i = 0; i < dimensions.length; ++i){
if (text[3].split(":").length > i)
dimensions[i] = text[3].split(":")[i];
}
dimensions[index] = position;
StringBuilder mergedDimensions = new StringBuilder();
for (int i = 0; i < 5; ++i) {
if (dimensions[i] == null) dimensions[i] = "";
mergedDimensions.append(dimensions[i]);
if (i < 4)mergedDimensions.append(":");
}
text[3] = String.valueOf(mergedDimensions);
sign.changeText(changer -> changer.withMessage(3, Text.of(text[3])), front);
}
public void addRotationWidgets() {
String[] initialRotation = text[2].split(":");
RotationSliderWidget rotXWidget = new RotationSliderWidget(this.width / 2 - 176,this.height / 5 + 100,70,20, Integer.parseInt(initialRotation[0]));
RotationSliderWidget rotYWidget = new RotationSliderWidget(this.width / 2 - 103,this.height / 5 + 100,70,20, Integer.parseInt(initialRotation[1]));
RotationSliderWidget rotZWidget = new RotationSliderWidget(this.width / 2 - 30,this.height / 5 + 100,70,20, Integer.parseInt(initialRotation[2]));
rotXWidget.setChangedListener(s -> applyRotation(s, 0));
rotYWidget.setChangedListener(s -> applyRotation(s, 1));
rotZWidget.setChangedListener(s -> applyRotation(s, 2));
this.addDrawableChild(rotXWidget);
this.addDrawableChild(rotYWidget);
this.addDrawableChild(rotZWidget);
pictureWidgets.add(rotXWidget);
pictureWidgets.add(rotYWidget);
pictureWidgets.add(rotZWidget);
}
public void applyRotation(int rotation, int index) {
String[] dimensions = new String[3];
for (int i = 0; i < dimensions.length; ++i){
if (text[2].split(":").length > i)
dimensions[i] = text[2].split(":")[i];
}
dimensions[index] = String.valueOf(rotation);
StringBuilder mergedDimensions = new StringBuilder();
for (int i = 0; i < 3; ++i) {
if (dimensions[i] == null) dimensions[i] = "";
mergedDimensions.append(dimensions[i]);
if (i < 2)mergedDimensions.append(":");
}
text[2] = String.valueOf(mergedDimensions);
sign.changeText(changer -> changer.withMessage(2, Text.of(text[2])), front);
}
public static class RotationSliderWidget extends SliderWidget {
private Consumer<Integer> changedListener;
public RotationSliderWidget(int x, int y, int width, int height, int rot) {
super(x, y, width, height, Text.of(String.valueOf(rot)), rot / (360d));
}
protected void updateMessage() {
this.setMessage(Text.of(String.valueOf(getValue())));
}
@Override
protected void applyValue() {
changedListener.accept(getValue());
}
protected int getValue() {
return Double.valueOf(this.value * (360)).intValue();
}
public void setChangedListener(Consumer<Integer> changedListener) {
this.changedListener = changedListener;
}
}
private void finishEditing() {
assert this.client != null;
switchScreen = false;
this.client.setScreen(null);
}
public void removed() {
if (this.client == null || switchScreen) return;
for (int i = 0; i < 4; i++) {
int finalI = i;
sign.changeText(changer -> changer.withMessage(finalI, Text.of(text[finalI])), front);
}
NetworkUtil.sendPacket(new UpdateSignC2SPacket(this.sign.getPos(), front, this.text[0], this.text[1], this.text[2], this.text[3]));
}
private String[] breakLink(String prefix, String link) {
Text linkText = Text.of(prefix+link);
String[] brokenLink = new String[3];
assert client != null;
List<OrderedText> text = client.textRenderer.wrapLines(linkText, 90);
for (int i = 0; i < text.size(); i++) {
String textLine = orderedToString(text.get(i));
if (i < (PictureSignConfig.exceedVanillaLineLength ? 2 : 3))
brokenLink[i] = textLine;
else if (PictureSignConfig.exceedVanillaLineLength) brokenLink[1] += textLine;
}
return brokenLink;
}
private String orderedToString(OrderedText ordered) {
StringBuilder string = new StringBuilder();
ordered.accept((i, style, codePoint) -> {
string.append(Character.toString(codePoint));
return true;
}); return string.toString();
}
@Override
public boolean shouldPause() {
return false;
}
public void tick() {
super.tick();
if (!this.sign.getType().supports(this.sign.getCachedState())) {
this.finishEditing();
}
}
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta);
if (this.client == null) return;
DiffuseLighting.disableGuiDepthLighting();
String enabledWebsites = "";
if (PictureSignConfig.safeMode) {
if (type.equals(PictureSignType.PICTURE)) enabledWebsites = "(imgur.com/imgbb.com/iili.io/pictshare.net)";
else if (type.equals(PictureSignType.GIF)) enabledWebsites = "(imgur.com/tenor.com)";
else if (type.isVideo) enabledWebsites = "(youtube.com/youtu.be/vimeo.com)";
else if (type.isAudio) enabledWebsites = "(youtube.com/youtu.be/vimeo.com/freesound.org)";
}
if (type.isAudio) pictureWidgets.forEach(widget -> widget.active = false);
else pictureWidgets.forEach(widget -> widget.active = true);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.link", enabledWebsites),
this.width / 2 - 175, this.height / 5 + 3, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.width"),this.width / 2 - 175, this.height / 5 + 60, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.height"),this.width / 2 - 140, this.height / 5 + 60, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.pos_x"),this.width / 2 - 105, this.height / 5 + 60, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.pos_y"),this.width / 2 - 70, this.height / 5 + 60, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.pos_z"),this.width / 2 - 35, this.height / 5 + 60, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.mode"),this.width / 2, this.height / 5 + 60, -8816268);
if (text[2].matches("(.*\\d:.*\\d:.*\\d)")) {
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.rot_x"),this.width / 2 - 175, this.height / 5 + 92, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.rot_y"),this.width / 2 - 103, this.height / 5 + 92, -8816268);
context.drawTextWithShadow(textRenderer, Text.translatable("picturesign.helper.rot_z"),this.width / 2 - 30, this.height / 5 + 92, -8816268);
}
context.drawCenteredTextWithShadow(this.textRenderer, this.title, this.width / 2, 40, 16777215);
MatrixStack matrices = context.getMatrices();
matrices.push();
VertexConsumerProvider.Immediate immediate = this.client.getBufferBuilders().getEntityVertexConsumers();
translateForRender(context);
renderSignBackground(context, sign.getCachedState());
int i = this.sign.getText(front).getColor().getSignColor();
matrices.pop();
matrices.push();
context.getMatrices().translate((float)this.width / 2.0F + 100, this.height / 5f + 47.5f, 400.0F);
if (sign.getCachedState().getBlock() instanceof SignBlock) context.getMatrices().translate(0,-15f,0);
else if (isHanging) context.getMatrices().translate(0,17f,0);
Vector3f vector3f = this.getTextScale();
context.getMatrices().scale(vector3f.x(), vector3f.y(), vector3f.z());
Matrix4f matrix4f = matrices.peek().getPositionMatrix();
int m;
String string;
for(m = 0; m < this.text.length; ++m) {
string = this.text[m];
if (string != null) {
if (this.textRenderer.isRightToLeft()) {
string = this.textRenderer.mirror(string);
}
float n = (float)(-this.client.textRenderer.getWidth(string) / 2);
this.client.textRenderer.draw(string, n, (float)(m * 10 - this.text.length * 5), i, false, matrix4f, immediate, TextRenderer.TextLayerType.NORMAL, 0, 15728880, false);
}
}
immediate.draw();
matrices.pop();
DiffuseLighting.enableGuiDepthLighting();
}
protected void translateForRender(DrawContext context) {
MatrixStack matrices = context.getMatrices();
if (isHanging) {
matrices.translate((float)this.width / 2.0F + 100, this.height / 5f + 50, 50.0F);
}
else {
matrices.push();
matrices.translate(this.width / 2f + 100, this.height / 5f - 60, 50.0);
matrices.scale(93.75F, -93.75F, 93.75F);
matrices.translate(0.0, -1.3125, 0.0);
}
}
protected void renderSignBackground(DrawContext context, BlockState state) {
if (!isHanging && this.client != null) {
VertexConsumerProvider.Immediate immediate = this.client.getBufferBuilders().getEntityVertexConsumers();
MatrixStack matrices = context.getMatrices();
boolean bl = state.getBlock() instanceof SignBlock;
if (!bl) {
matrices.translate(0.0, -0.15625, 0.0);
}
matrices.push();
matrices.scale(0.6666667F, -0.6666667F, -0.6666667F);
SpriteIdentifier spriteIdentifier = TexturedRenderLayers.getSignTextureId(AbstractSignBlock.getWoodType(state.getBlock()));
SignBlockEntityRenderer.SignModel var10002 = this.model;
Objects.requireNonNull(var10002);
VertexConsumer vertexConsumer = spriteIdentifier.getVertexConsumer(immediate, var10002::getLayer);
this.model.stick.visible = bl;
this.model.root.render(matrices, vertexConsumer, 15728880, OverlayTexture.DEFAULT_UV);
matrices.pop();
matrices.translate(0.0, 0.3333333432674408, 0.046666666865348816);
matrices.scale(0.010416667F, -0.010416667F, 0.010416667F);
}
else {
MatrixStack matrices = context.getMatrices();
matrices.scale(4.5F, 4.5F, 1.0F);
context.drawTexture(Identifier.ofVanilla("textures/gui/hanging_signs/" + this.signType.name() + ".png"), -8, -8, 0.0F, 0.0F, 16, 16, 16, 16);
}
}
protected Vector3f getTextScale() {
return isHanging ? new Vector3f(1.0F, 1.0F, 1.0F) : new Vector3f(0.9765628F, 0.9765628F, 0.9765628F);
}
}

View File

@@ -0,0 +1,63 @@
package eu.midnightdust.picturesign.util;
import net.minecraft.util.Identifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
public class GIFHandler {
private static final List<Function<Identifier, GIFHandler>> implementations = new ArrayList<>();
public static Map<Identifier, GIFHandler> gifHandlers = new HashMap<>();
public final Identifier id;
public boolean playbackStarted;
public GIFHandler(Identifier id) {
this.id = id;
gifHandlers.put(id, this);
}
public static void registerHandler(Function<Identifier, GIFHandler> handler) {
implementations.add(handler);
}
public static boolean hasValidImplementation() {
return !implementations.isEmpty();
}
public static GIFHandler getOrCreate(Identifier id) {
if (gifHandlers.containsKey(id)) return gifHandlers.get(id);
AtomicReference<GIFHandler> handler = new AtomicReference<>();
implementations.forEach(impl -> {
handler.set(impl.apply(id));
});
return handler.get();
}
public void tick() {
}
public void closePlayer() {
gifHandlers.remove(this.id);
}
public static void closePlayer(Identifier videoId) {
if (gifHandlers.containsKey(videoId)) gifHandlers.get(videoId).closePlayer();
}
public static void closeAll() {
gifHandlers.forEach((id, handler) -> handler.closePlayer());
gifHandlers.clear();
}
public void play(String url) {
this.playbackStarted = true;
}
public boolean hasMedia() {
return false;
}
public int getTexture() {
return -1;
}
public boolean isWorking() {
return false;
}
}

View File

@@ -0,0 +1,9 @@
package eu.midnightdust.picturesign.util;
import net.irisshaders.iris.api.v0.IrisApi;
public class IrisCompat {
public static boolean isShaderPackInUse() {
return IrisApi.getInstance().isShaderPackInUse();
}
}

View File

@@ -0,0 +1,108 @@
package eu.midnightdust.picturesign.util;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import org.jetbrains.annotations.ApiStatus;
import org.watermedia.api.player.videolan.VideoPlayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import static eu.midnightdust.picturesign.PictureSignClient.client;
public abstract class MediaHandler {
private static final List<BiFunction<Identifier, BlockPos, MediaHandler>> implementations = new ArrayList<>();
public static Map<Identifier, MediaHandler> mediaHandlers = new HashMap<>();
public final Identifier id;
public final BlockPos pos;
public boolean playbackStarted = false;
public boolean isDeactivated;
int maxVolume = 100;
public MediaHandler(Identifier id, BlockPos pos) {
this.id = id;
this.pos = pos;
}
public static void registerHandler(BiFunction<Identifier, BlockPos, MediaHandler> handler) {
implementations.add(handler);
}
public static boolean hasValidImplementation() {
return !implementations.isEmpty();
}
public static MediaHandler getOrCreate(Identifier id, BlockPos pos) {
if (mediaHandlers.containsKey(id)) return mediaHandlers.get(id);
AtomicReference<MediaHandler> handler = new AtomicReference<>();
implementations.forEach(impl -> {
handler.set(impl.apply(id, pos));
});
return handler.get();
}
public void setVolumeBasedOnDistance() {
if (!isWorking() || client.player == null) return;
Vec3d playerPos = client.player.getPos();
if (PictureSignConfig.audioDistanceMultiplier == 0) {
setVolume(0);
return;
}
double distance = this.pos.getSquaredDistance(playerPos) / PictureSignConfig.audioDistanceMultiplier;
setVolume((int) Math.clamp(maxVolume-distance, 0, 100));
}
@ApiStatus.Internal
public void setVolume(int volume) {} // Please use 'setMaxVolume' to adjust the playback volume
public void setMaxVolume(int volume) {
maxVolume = volume;
}
public void closePlayer() {}
public static void closePlayer(Identifier videoId) {
if (mediaHandlers.get(videoId) instanceof MediaHandler mediaHandler) mediaHandler.closePlayer();
}
public static void closeAll() {
mediaHandlers.forEach(((id, player) -> player.closePlayer()));
mediaHandlers.clear();
}
public void stop() {
isDeactivated = true;
}
public boolean isStopped() {
return false;
}
public boolean isPaused() {
return false;
}
public void pause() {}
public void restart() {}
public void play(String url, boolean isVideo) {
}
public boolean hasMedia() {
return true;
}
public void setRepeat(boolean value) {}
public long getTime() {
return -1;
}
public void setTime(long value) {
}
public void preRender() {
}
public int getTexture() {
return -1;
}
public boolean isReady() {
return false;
}
public boolean isWorking() {
return false;
}
}

View File

@@ -0,0 +1,11 @@
package eu.midnightdust.picturesign.util;
import dev.architectury.injectables.annotations.ExpectPlatform;
import net.minecraft.network.packet.Packet;
public class NetworkUtil {
@ExpectPlatform
public static void sendPacket(Packet<?> packet) {
throw new AssertionError();
}
}

View File

@@ -0,0 +1,161 @@
package eu.midnightdust.picturesign.util;
import eu.midnightdust.picturesign.PictureSignClient;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.NativeImageBackedTexture;
import net.minecraft.util.Identifier;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import static eu.midnightdust.picturesign.PictureSignClient.MOD_ID;
import static java.util.concurrent.Executors.newFixedThreadPool;
public class PictureDownloader {
public static class PictureData {
public String url;
public Identifier identifier;
public PictureData(String url) {
this.url = url;
}
}
static PictureDownloader downloader = new PictureDownloader();
public static PictureDownloader getInstance() {
return downloader;
}
// Create a service for downloading the picture
private final ExecutorService service = newFixedThreadPool(PictureSignConfig.maxThreads);
private final Hashtable<String, PictureData> cache = new Hashtable<>();
private final Object mutex = new Object();
// Downloads the picture, or returns the cached picture
public PictureData getPicture(String url) {
synchronized (mutex) {
// Try to get the picture from cache
PictureData data = this.cache.get(url);
if (data == null) {
// Download the picture if not in cache
this.loadPicture(url);
return null;
}
if (data.identifier == null) {
return null;
}
return data;
}
}
// Download the image and save it in cache
private void loadPicture(String url) {
if (url.startsWith("file:")) loadLocalPicture(url);
else if (url.startsWith("rp:")) loadResourcePackTexture(url);
else downloadPicture(url);
}
private void downloadPicture(String url) {
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Started downloading picture: " + url);
this.cache.put(url, new PictureData(url));
service.submit(() -> {
try {
BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
File file = File.createTempFile("."+MOD_ID, "temp");
file.deleteOnExit();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
out.write(dataBuffer, 0, bytesRead);
}
out.close();
Identifier texture = convert2png(file);
// Cache the downloaded picture
synchronized (mutex) {
PictureData data = this.cache.get(url);
data.identifier = texture;
}
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Finished downloading picture: " + url);
} catch (IOException error) {
PictureSignClient.LOGGER.error("Error downloading picture: " + error);
}
});
}
private void loadLocalPicture(String url) {
String realPath = url.replace("file:", "");
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Started loading local picture: " + url);
this.cache.put(url, new PictureData(url));
service.submit(() -> {
try {
File file = new File(realPath);
Identifier texture = convert2png(file);
synchronized (mutex) {
PictureData data = this.cache.get(url);
data.identifier = texture;
}
} catch (IOException error) {
PictureSignClient.LOGGER.error("Error loading local picture: " + error);
}
});
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Finished loading local picture: " + url);
}
private void loadResourcePackTexture(String url) {
String realIdentifierPath = url.replace("rp:", "");
if (!realIdentifierPath.endsWith(".png")) realIdentifierPath += ".png";
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Started loading resource pack picture: " + url);
Identifier id = Identifier.tryParse(realIdentifierPath);
if (id == null) {
PictureSignClient.LOGGER.error("Unable to locate resource texture: " + url);
return;
}
this.cache.put(url, new PictureData(url));
service.submit(() -> {
synchronized (mutex) {
PictureData data = this.cache.get(url);
data.identifier = id;
}
});
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Finished loading resource pack picture: " + url);
}
private static Identifier convert2png(File file) throws IOException {
BufferedImage bufferedImage = ImageIO.read(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
NativeImage nativeImage = NativeImage.read(inputStream);
NativeImageBackedTexture nativeImageBackedTexture = new NativeImageBackedTexture(nativeImage);
return MinecraftClient.getInstance().getTextureManager().registerDynamicTexture("picturesign/image",
nativeImageBackedTexture);
}
}

View File

@@ -0,0 +1,63 @@
package eu.midnightdust.picturesign.util;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.text.Text;
public enum PictureSignType {
NONE(Text.empty(), "", false, false, false),
PICTURE(Text.translatable("picturesign.type.image"), "!PS:", false, false, false),
GIF(Text.translatable("picturesign.type.gif"), "!GS:", true, false, false),
VIDEO(Text.translatable("picturesign.type.video"), "!VS:", false, true, false),
LOOPED_VIDEO(Text.translatable("picturesign.type.video_loop"), "!LS:", true, true, false),
AUDIO(Text.translatable("picturesign.type.audio"), "!AS:", false, false, true),
LOOPED_AUDIO(Text.translatable("picturesign.type.audio_loop"), "!ALS:", true, false, true);
public final Text name;
public final String format;
public final boolean isLooped;
public final boolean isVideo;
public final boolean isAudio;
PictureSignType(Text name, String format, boolean isLooped, boolean isVideo, boolean isAudio) {
this.name = name;
this.format = format;
this.isLooped = isLooped;
this.isVideo = isVideo;
this.isAudio = isAudio;
}
public static PictureSignType getType(SignBlockEntity signBlockEntity, boolean front) {
if (signBlockEntity == null) return PictureSignType.NONE;
return getType(signBlockEntity.getText(front).getMessage(0,false).getString());
}
public static PictureSignType getType(String lineOne) {
if (lineOne.startsWith("!PS:")) return PICTURE;
else if (lineOne.startsWith("!GS:")) return GIF;
else if (lineOne.startsWith("!VS:")) return VIDEO;
else if (lineOne.startsWith("!LS:")) return LOOPED_VIDEO;
else if (lineOne.startsWith("!AS:")) return AUDIO;
else if (lineOne.startsWith("!LAS:")) return LOOPED_AUDIO;
else return NONE;
}
public PictureSignType next() {
return switch (this) {
case PICTURE -> GIF;
case GIF -> VIDEO;
case VIDEO -> LOOPED_VIDEO;
case LOOPED_VIDEO -> AUDIO;
case AUDIO -> LOOPED_AUDIO;
case LOOPED_AUDIO -> PICTURE;
default -> NONE;
};
}
public static boolean isCandidate(SignBlockEntity signBlockEntity, boolean front) {
return signBlockEntity.getText(front).getMessage(0,false).getString().startsWith("!");
}
public static boolean isNotOfType(SignBlockEntity signBlockEntity, PictureSignType type, boolean front) {
return getType(signBlockEntity, front) != type;
}
public static boolean hasPicture(SignBlockEntity signBlockEntity) {
return isNotOfType(signBlockEntity, NONE, true) || isNotOfType(signBlockEntity, NONE, false);
}
}

View File

@@ -0,0 +1,99 @@
package eu.midnightdust.picturesign.util;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import eu.midnightdust.picturesign.PictureSignClient;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.util.records.MediaJsonInfo;
import net.minecraft.block.entity.SignBlockEntity;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class PictureURLUtils {
public static final Type STRING_TYPE = new TypeToken<Map<String, String>>(){}.getType();
public static final Map<String, MediaJsonInfo> cachedJsonData = new HashMap<>();
private static final Gson GSON = new GsonBuilder().create();
public static MediaJsonInfo infoFromJson(String pathToJson) {
if (cachedJsonData.containsKey(pathToJson)) return cachedJsonData.get(pathToJson);
MediaJsonInfo result = null;
URL json = toURL(pathToJson);
Map<String, String> jsonData = null;
try (Reader reader = new InputStreamReader(json.openStream())) {
jsonData = GSON.fromJson(reader, STRING_TYPE);
} catch (MalformedURLException error) {
PictureSignClient.LOGGER.error("Unable to load url from JSON because of connection problems: " + error.getMessage());
} catch (IOException error) {
PictureSignClient.LOGGER.error("Unable to load url from JSON because of an I/O Exception: " + error.getMessage());
}
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("JsonData: "+jsonData);
if (jsonData != null && !jsonData.isEmpty() && jsonData.containsKey("url")) {
result = new MediaJsonInfo(jsonData.get("url"), getDurationMillis(jsonData.getOrDefault("start_at", "")),
getDurationMillis(jsonData.getOrDefault("end_at", "")), Integer.parseInt(jsonData.getOrDefault("volume", "-1")));
PictureSignClient.LOGGER.info("URL successfully loaded from JSON!");
} else {
PictureSignClient.LOGGER.warn("Unable to load url from JSON");
}
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Result: "+result);
cachedJsonData.put(pathToJson, result);
return result;
}
private static long getDurationMillis(String duration) {
if (duration.isEmpty()) return -1;
String[] splitDuration = duration.split(":");
if (splitDuration.length != 4) return -1;
return TimeUnit.MILLISECONDS.convert(Duration.parse("PT" + splitDuration[0]+"H" + splitDuration[1]+"M" + splitDuration[2]+"S")) + Long.parseLong(splitDuration[3]);
}
public static URL toURL(String string) {
URL result = null;
try { result = URI.create(string).toURL(); }
catch (MalformedURLException e) {PictureSignClient.LOGGER.warn("Malformed URL: " + e);}
return result;
}
public static String getLink(SignBlockEntity signBlockEntity, boolean front) {
String text = signBlockEntity.getText(front).getMessage(0, false).getString() +
signBlockEntity.getText(front).getMessage(1, false).getString();
if (!signBlockEntity.getText(front).getMessage(2, false).getString().matches("(.*\\d:.*\\d:.*\\d)")) text += signBlockEntity.getText(front).getMessage(2, false).getString();
String url = text.replaceAll("!PS:", "")
.replaceAll("!GS:", "")
.replaceAll("!VS:", "")
.replaceAll("!LS:", "")
.replaceAll("!AS:", "")
.replaceAll("!ALS:", "")
.replaceAll(" ","");
if (url.startsWith("ps:")) url = url.replace("ps:", "https://pictshare.net/");
if (url.startsWith("imgur:")) url = url.replace("imgur:", "https://i.imgur.com/");
if (url.startsWith("imgbb:")) url = url.replace("imgbb:", "https://i.ibb.co/");
if (url.startsWith("iili:")) url = url.replace("iili:", "https://iili.io/");
if (url.startsWith("tenor:")) url = url.replace("tenor:", "https://media1.tenor.com/m/");
if (url.startsWith("yt:")) url = url.replace("yt:", "https://youtu.be/");
return url;
}
public static String shortenLink(String url) {
if (url.contains("pictshare.net/")) url = url.replace("pictshare.net/", "ps:");
if (url.contains("media1.tenor.com/m/")) url = url.replace("media1.tenor.com/m/", "tenor:");
if (url.contains("i.imgur.com/")) url = url.replace("i.imgur.com/", "imgur:");
if (url.contains("i.ibb.co/:")) url = url.replace("i.ibb.co/", "imgbb:");
if (url.contains("iili.io/")) url = url.replace("iili.io/", "iili:");
if (url.contains("www.youtube.com/")) url = url.replace("www.youtube.com/", "yt:");
if (url.contains("youtu.be/")) url = url.replace("youtu.be/", "yt:");
if (url.startsWith("https://")) {
url = url.replace("https://", "");
}
if (url.contains("watch?v=")) url = url.replace("watch?v=", "");
if (url.contains("&pp=")) url = url.split("&pp=")[0];
return url;
}
}

View File

@@ -0,0 +1,52 @@
package eu.midnightdust.picturesign.util;
import net.minecraft.util.Identifier;
import org.watermedia.api.image.ImageAPI;
import org.watermedia.api.image.ImageCache;
import org.watermedia.api.math.MathAPI;
import java.net.URI;
import static eu.midnightdust.picturesign.PictureSignClient.client;
public class WaterGIFHandler extends GIFHandler {
private ImageCache player;
private int tick = 0;
public WaterGIFHandler(Identifier id) {
super(id);
}
@Override
public void tick() {
if (player != null && player.getRenderer() != null && tick < player.getRenderer().duration) tick += 1;
else tick = 0;
}
@Override
public void closePlayer() {
player.release();
player = null;
super.closePlayer();
}
@Override
public void play(String url) {
this.player = ImageAPI.getCache(URI.create(url), client);
player.load();
super.play(url);
}
@Override
public boolean hasMedia() {
return player != null && player.getStatus() == ImageCache.Status.READY;
}
@Override
public int getTexture() {
return player.getRenderer().texture(tick,
(MathAPI.tickToMs(client.getRenderTickCounter().getTickDelta(true))), true);
}
@Override
public boolean isWorking() {
if (player != null && player.getException() != null) player.getException().fillInStackTrace();
return player != null && player.getStatus() == ImageCache.Status.READY && player.getRenderer() != null;
}
}

View File

@@ -0,0 +1,106 @@
package eu.midnightdust.picturesign.util;
import net.minecraft.client.MinecraftClient;
import net.minecraft.sound.SoundCategory;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import org.lwjgl.opengl.GL11;
import org.watermedia.api.player.PlayerAPI;
import org.watermedia.api.player.videolan.BasePlayer;
import org.watermedia.api.player.videolan.MusicPlayer;
import org.watermedia.api.player.videolan.VideoPlayer;
import java.net.URI;
import static eu.midnightdust.picturesign.PictureSignClient.client;
public class WaterMediaHandler extends MediaHandler {
private BasePlayer player;
public WaterMediaHandler(Identifier id, BlockPos pos) {
super(id, pos);
mediaHandlers.put(id, this);
}
@Override
public void setVolume(int volume) {
player.setVolume((int) (volume * MinecraftClient.getInstance().options.getSoundVolume(SoundCategory.MASTER)));
}
@Override
public void closePlayer() {
if (player != null) {
player.stop();
player.release();
}
//mediaPlayers.remove(id);
player = null;
}
@Override
public void stop() {
player.stop();
super.stop();
}
@Override
public boolean isStopped() {
return player.isStopped();
}
@Override
public boolean isPaused() {
return player.isPaused();
}
@Override
public void pause() {
player.pause();
}
@Override
public void restart() {
player.play();
}
@Override
public void play(String url, boolean isVideo) {
this.player = isVideo ? new VideoPlayer(client) : new MusicPlayer();
mediaHandlers.put(id, this);
if (player.isBroken()) return;
player.start(URI.create(url));
this.playbackStarted = true;
}
@Override
public boolean hasMedia() {
return player != null && player.isPlaying();
}
@Override
public void setRepeat(boolean value) {
player.setRepeatMode(true);
}
@Override
public long getTime() {
return player.getTime();
}
@Override
public void setTime(long value) {
player.seekTo(value);
}
@Override
public void preRender() {
if (player instanceof VideoPlayer videoPlayer) {
videoPlayer.preRender();
}
}
@Override
public int getTexture() {
if (player instanceof VideoPlayer videoPlayer) {
return videoPlayer.texture();
}
return -1;
}
@Override
public boolean isReady() {
return PlayerAPI.isReady();
}
@Override
public boolean isWorking() {
return mediaHandlers.containsKey(id) && mediaHandlers.get(id) instanceof WaterMediaHandler waterMediaHandler
&& waterMediaHandler.player != null && !waterMediaHandler.player.isBroken();
}
}

View File

@@ -0,0 +1,4 @@
package eu.midnightdust.picturesign.util.records;
public record MediaJsonInfo(String url, long start, long end, int volume) {
}

View File

@@ -0,0 +1,4 @@
package eu.midnightdust.picturesign.util.records;
public record PictureDimensions(float width, float height, float x, float y, float z, float xRot, float yRot, float zRot) {
}

View File

@@ -0,0 +1,4 @@
package eu.midnightdust.picturesign.util.records;
public record PictureOffset(float xOffset, float zOffset, float yRotation) {
}

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -0,0 +1,50 @@
{
"picturesign.midnightconfig.title":"PictureSign Konfiguration",
"picturesign.midnightconfig.enabled":"Aktiviere Bilder",
"picturesign.midnightconfig.enableMultimediaSigns":"Aktiviere Multimedia",
"picturesign.midnightconfig.audioDistanceMultiplier":"Audio-Distanz Multiplikator",
"picturesign.midnightconfig.translucency":"Aktiviere Lichtdurchlässigkeit",
"picturesign.midnightconfig.translucency.tooltip":"Lichtdurchlässigkeit funktioniert teilweise nicht richtig\nbei Block-Entities (und dementsprechend Schildern)",
"picturesign.midnightconfig.helperUi":"Aktiviere Hilfsoberfäche",
"picturesign.midnightconfig.exceedVanillaLineLength":"Überschreite die Vanilla Zeilenlänge",
"picturesign.midnightconfig.debug":"Debug-Modus",
"picturesign.midnightconfig.maxThreads":"Maximale Download-Threads",
"picturesign.midnightconfig.signRenderDistance":"Schildsichtweite",
"picturesign.midnightconfig.safeMode":"Sicherer Modus",
"picturesign.midnightconfig.safeMode.tooltip":"Lädt nur Bilder von vertrauten Seiten",
"picturesign.midnightconfig.ebeWarning":"§cWenn du die Mod 'Enhanced Block Entities' benutzt, stelle sicher, dass du alles in Relation zu Schildern in der EBE Config deaktiviert hast!",
"picturesign.midnightconfig.safeProviders":"Sichere Bildanbieter",
"picturesign.midnightconfig.safeGifProviders":"Sichere GIF-Anbieter",
"picturesign.midnightconfig.safeMultimediaProviders":"Sichere Multimedia-Anbieter",
"picturesign.midnightconfig.safeJsonProviders":"Sichere JSON-Anbieter",
"picturesign.midnightconfig.missingImageMode":"Darstellung fehlender Texturen",
"picturesign.midnightconfig.enum.MissingImageMode.BLACK":"Schwarz",
"picturesign.midnightconfig.enum.MissingImageMode.MISSING_TEXTURE":"Schwarz & Lila",
"picturesign.midnightconfig.enum.MissingImageMode.TRANSPARENT":"Transparent",
"key.picturesign.copy_sign": "Text eines Schildes kopieren",
"key.picturesign.edit_sign":"Schild bearbeiten",
"picturesign.midnightconfig.category.1general": "Generell",
"picturesign.midnightconfig.category.advanced": "Fortgeschritten",
"picturesign.midnightconfig.fullBrightPicture": "Höchste Helligkeit",
"picturesign.midnightconfig.fullBrightPicture.tooltip": "Sorgt dafür, dass Bilder immer vollkommen beleuchtet dargestellt werden",
"picturesign.midnightconfig.pictureShader": "Render-Programm",
"picturesign.midnightconfig.pictureShader.tooltip": "Wähle das Shader-Programm, mit dem die Bilder dargestellt werden, was nützlich ist, wenn diese mit Shaderpacks nicht richtig dargestellt werden",
"picturesign.type.image": "Bild",
"picturesign.helper.width": "Breite",
"picturesign.helper.height": "Höhe",
"picturesign.helper.mode": "Modus",
"picturesign.error": "FEHLER: ",
"picturesign.error.imageNotFound": "Das angegebene Bild konnte nicht gefunden werden.\nBist du offline oder ist die Website down?",
"picturesign.error.missingVLC": "VLC ist nicht installiert oder konnte nicht gefunden werden.",
"picturesign.error.missingWatermedia": "Installiere WATERMeDIA, um GIFs, Videos und Audios zu genießen.",
"picturesign.error.unknownFiletype": "Der Dateityp des Bildes wird nicht von PictureSign unterstützt.",
"picturesign.error.unknownSigntype": "Diese Version von PictureSign unterstützt keine Schilder des angegebenen Typen.",
"picturesign.error.unsafeJsonUrl": "Die angegebene JSON URL ist nicht als sicher bekannt.\nNutze einen anderen Anbieter oder ändere die PictureSign Konfiguration.",
"picturesign.error.unsafeUrl": "Die angegebene URL ist nicht als sicher bekannt.\nNutze einen anderen Anbieter oder ändere die PictureSign Konfiguration."
}

View File

@@ -0,0 +1,66 @@
{
"picturesign.midnightconfig.title":"PictureSign Config",
"picturesign.midnightconfig.category.1general":"General",
"picturesign.midnightconfig.category.advanced":"Advanced",
"picturesign.midnightconfig.enabled":"Enable Pictures",
"picturesign.midnightconfig.enableMultimediaSigns":"Enable Multimedia",
"picturesign.midnightconfig.audioDistanceMultiplier":"Audio Distance Multiplier",
"picturesign.midnightconfig.translucency":"Enable Translucency",
"picturesign.midnightconfig.translucency.tooltip":"Translucency doesn't work too great on block entities\n(and therefore signs)",
"picturesign.midnightconfig.fullBrightPicture":"Full-bright Pictures",
"picturesign.midnightconfig.fullBrightPicture.tooltip":"Makes pictures always appear fully lit",
"picturesign.midnightconfig.helperUi":"Enable Helper UI",
"picturesign.midnightconfig.exceedVanillaLineLength":"Exceed vanilla line length",
"picturesign.midnightconfig.debug":"Debug mode",
"picturesign.midnightconfig.maxThreads":"Max download threads",
"picturesign.midnightconfig.signRenderDistance":"Sign render distance",
"picturesign.midnightconfig.safeMode":"Safe mode",
"picturesign.midnightconfig.safeMode.tooltip":"Only load images from trusted providers",
"picturesign.midnightconfig.ebeWarning":"§cIf you are using the mod 'Enhanced Block Entities' make sure to disable anything sign-related in it's config!",
"picturesign.midnightconfig.safeProviders":"Safe Image Providers",
"picturesign.midnightconfig.safeGifProviders":"Safe GIF Providers",
"picturesign.midnightconfig.safeMultimediaProviders":"Safe Multimedia Providers",
"picturesign.midnightconfig.safeJsonProviders":"Safe JSON Providers",
"picturesign.midnightconfig.missingImageMode":"Missing image mode",
"picturesign.midnightconfig.enum.MissingImageMode.BLACK":"Black",
"picturesign.midnightconfig.enum.MissingImageMode.MISSING_TEXTURE":"Black & Purple",
"picturesign.midnightconfig.enum.MissingImageMode.TRANSPARENT":"Transparent",
"picturesign.midnightconfig.pictureShader":"Render Program",
"picturesign.midnightconfig.pictureShader.tooltip":"Select the shader program to draw pictures with when using shaderpacks where they appear black/buggy",
"picturesign.midnightconfig.enum.PictureShader.PosColTexLight":"PosColTexLight",
"picturesign.midnightconfig.enum.PictureShader.RenderTypeCutout":"RenderTypeCutout",
"picturesign.midnightconfig.enum.PictureShader.PosTex":"PosTex",
"picturesign.midnightconfig.enum.PictureShader.PosColTex":"PosColTex",
"picturesign.midnightconfig.enum.PictureShader.PosTexCol":"PosTexCol",
"key.picturesign.copy_sign":"Copy Text from Sign",
"key.picturesign.edit_sign":"Edit Sign",
"key.categories.picturesign":"PictureSign",
"picturesign.type.image": "Image",
"picturesign.type.gif": "GIF",
"picturesign.type.video": "Video",
"picturesign.type.video_loop": "Video Loop",
"picturesign.type.audio": "Audio",
"picturesign.type.audio_loop": "Audio Loop",
"picturesign.helper.link": "Link %s",
"picturesign.helper.width": "Width",
"picturesign.helper.height": "Height",
"picturesign.helper.pos_x": "PosX",
"picturesign.helper.pos_y": "PosY",
"picturesign.helper.pos_z": "PosZ",
"picturesign.helper.rot_x": "RotX",
"picturesign.helper.rot_y": "RotY",
"picturesign.helper.rot_z": "RotZ",
"picturesign.helper.mode": "Mode",
"picturesign.error": "ERROR: ",
"picturesign.error.imageNotFound": "The specified image could not be found.\nAre you offline or is the website down?",
"picturesign.error.missingVLC": "VLC is not installed or could not be found.",
"picturesign.error.missingWatermedia": "Install WATERMeDIA to enjoy GIFs, videos and audios.",
"picturesign.error.unknownFiletype": "The filetype of the specified image is not supported by PictureSign.",
"picturesign.error.unknownSigntype": "This version of PictureSign does not support signs of the specified type.",
"picturesign.error.unsafeJsonUrl": "The provided JSON URL is not known to be safe.\nUpload to a different provider or change the PictureSign config.",
"picturesign.error.unsafeUrl": "The provided URL is not known to be safe.\nUpload to a different provider or change the PictureSign config."
}

View File

@@ -0,0 +1,20 @@
{
"picturesign.midnightconfig.title":"PictureSign 配置",
"picturesign.midnightconfig.enabled":"启用图片",
"picturesign.midnightconfig.enableVideoSigns":"启用视频",
"picturesign.midnightconfig.translucency":"启用半透明",
"picturesign.midnightconfig.translucency.tooltip":"半透明在方块实体上的效果并不是很好\n因此告示牌也是",
"picturesign.midnightconfig.helperUi":"启用辅助界面",
"picturesign.midnightconfig.exceedVanillaLineLength":"超出原版行长度",
"picturesign.midnightconfig.debug":"调试模式",
"picturesign.midnightconfig.maxThreads":"最大下载线程数",
"picturesign.midnightconfig.signRenderDistance":"告示牌渲染距离",
"picturesign.midnightconfig.safeMode":"安全模式",
"picturesign.midnightconfig.safeMode.tooltip":"仅加载来自受信任网站的图片",
"picturesign.midnightconfig.ebeWarning":"§c如果您使用了“Enhanced Block Entities”模组",
"picturesign.midnightconfig.ebeWarning2":"§c请确保在其配置中禁用了所有与告示牌相关的特性",
"key.picturesign.copy_sign":"从告示牌复制文本",
"key.picturesign.edit_sign":"编辑告示牌",
"key.categories.picturesign":"PictureSign"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

@@ -0,0 +1,14 @@
{
"required": true,
"package": "eu.midnightdust.picturesign.mixin",
"compatibilityLevel": "JAVA_17",
"client": [
"MixinSignBlockEntityRenderer",
"MixinHangingSignBlockEntityRenderer",
"MixinSignEditScreen",
"MixinSignBlockEntity"
],
"injectors": {
"defaultRequire": 1
}
}

106
fabric/build.gradle Normal file
View File

@@ -0,0 +1,106 @@
plugins {
id 'com.github.johnrengelman.shadow'
id "me.shedaniel.unified-publishing"
}
architectury {
platformSetupLoomIde()
fabric()
}
loom {
}
configurations {
common
shadowCommon // Don't use shadow from the shadow plugin since it *excludes* files.
compileClasspath.extendsFrom common
runtimeClasspath.extendsFrom common
developmentFabric.extendsFrom common
archivesBaseName = rootProject.archives_base_name + "-fabric"
}
dependencies {
modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}"
modApi "net.fabricmc.fabric-api:fabric-api:${rootProject.fabric_api_version}"
modImplementation include ("maven.modrinth:midnightlib:${rootProject.midnightlib_version}-fabric")
common(project(path: ":common", configuration: "namedElements")) { transitive false }
shadowCommon(project(path: ":common", configuration: "transformProductionFabric")) { transitive false }
}
processResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
shadowJar {
exclude "architectury.common.json"
configurations = [project.configurations.shadowCommon]
archiveClassifier = "dev-shadow"
}
remapJar {
input.set shadowJar.archiveFile
dependsOn shadowJar
}
sourcesJar {
def commonSources = project(":common").sourcesJar
dependsOn commonSources
from commonSources.archiveFile.map { zipTree(it) }
}
components.java {
withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) {
skip()
}
}
unifiedPublishing {
project {
displayName = "PictureSign $project.version - Fabric $project.minecraft_version"
releaseType = "$project.release_type"
changelog = releaseChangelog()
gameVersions = []
gameLoaders = ["fabric","quilt"]
mainPublication remapJar
relations {
depends {
curseforge = "fabric-api"
modrinth = "fabric-api"
}
depends {
curseforge = "watermedia"
modrinth = "watermedia"
}
includes {
curseforge = "midnightlib"
modrinth = "midnightlib"
}
}
var CURSEFORGE_TOKEN = project.findProperty("CURSEFORGE_TOKEN") ?: System.getenv("CURSEFORGE_TOKEN")
if (CURSEFORGE_TOKEN != null) {
curseforge {
token = CURSEFORGE_TOKEN
id = rootProject.curseforge_id
gameVersions.addAll "Java 21", project.minecraft_version
}
}
var MODRINTH_TOKEN = project.findProperty("MODRINTH_TOKEN") ?: System.getenv("MODRINTH_TOKEN")
if (MODRINTH_TOKEN != null) {
modrinth {
token = MODRINTH_TOKEN
id = rootProject.modrinth_id
version = "$project.version-$project.name"
gameVersions.addAll project.minecraft_version
}
}
}
}

View File

@@ -0,0 +1,53 @@
package eu.midnightdust.picturesign.fabric;
import eu.midnightdust.picturesign.PictureSignClient;
import eu.midnightdust.picturesign.util.GIFHandler;
import eu.midnightdust.picturesign.util.MediaHandler;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientBlockEntityEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.BlockPos;
import static eu.midnightdust.picturesign.PictureSignClient.BINDING_COPY_SIGN;
import static eu.midnightdust.picturesign.PictureSignClient.id;
import static eu.midnightdust.picturesign.PictureSignClient.clipboard;
public class PictureSignClientFabric implements ClientModInitializer {
@Override
public void onInitializeClient() {
PictureSignClient.init();
KeyBindingHelper.registerKeyBinding(BINDING_COPY_SIGN);
ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> {
if (MediaHandler.hasValidImplementation()) MediaHandler.closeAll();
});
ClientBlockEntityEvents.BLOCK_ENTITY_UNLOAD.register((blockEntity, world) -> {
if (MediaHandler.hasValidImplementation()) {
BlockPos pos = blockEntity.getPos();
Identifier videoId = id(pos.getX() + "_" + pos.getY() + "_" + pos.getZ()+"_f");
MediaHandler.closePlayer(videoId);
Identifier videoId2 = id(pos.getX() + "_" + pos.getY() + "_" + pos.getZ()+"_b");
MediaHandler.closePlayer(videoId2);
}
});
ClientTickEvents.END_CLIENT_TICK.register(client -> {
GIFHandler.gifHandlers.forEach(((identifier, handler) -> handler.tick()));
if (!BINDING_COPY_SIGN.isPressed()) return;
BINDING_COPY_SIGN.setPressed(false);
if (client.player == null || client.world == null || client.crosshairTarget == null || client.crosshairTarget.getType() != HitResult.Type.BLOCK) return;
if (client.crosshairTarget.getType() == HitResult.Type.BLOCK && client.world.getBlockState(BlockPos.ofFloored(client.crosshairTarget.getPos())).hasBlockEntity()) {
if (client.world.getBlockEntity(BlockPos.ofFloored(client.crosshairTarget.getPos())) instanceof SignBlockEntity sign) {
boolean front = sign.isPlayerFacingFront(client.player);
for (int i = 0; i < 4; i++) {
clipboard[i] = sign.getText(front).getMessage(i, false).getString();
}
}
}
});
}
}

View File

@@ -0,0 +1,15 @@
package eu.midnightdust.picturesign.util.fabric;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.packet.Packet;
import static eu.midnightdust.picturesign.PictureSignClient.client;
public class NetworkUtilImpl {
private static final ClientPlayNetworkHandler handler = client.getNetworkHandler();
public static void sendPacket(Packet<?> packet) {
if (handler != null)
handler.sendPacket(packet);
}
}

View File

@@ -4,11 +4,15 @@
"version": "${version}",
"name": "PictureSign",
"description": "Use signs to display custom images completely client-side!",
"description": "Use signs to display custom images and videos completely client-side!",
"authors": [
"Motschen",
"TeamMidnightDust"
],
"contributors": [
"Hendrix-Shen",
"Frost-ZX"
],
"contact": {
"homepage": "https://www.midnightdust.eu/",
"sources": "https://github.com/TeamMidnightDust/PictureSign",
@@ -21,13 +25,19 @@
"environment": "client",
"entrypoints": {
"client": [
"eu.midnightdust.picturesign.PictureSignClient"
"eu.midnightdust.picturesign.fabric.PictureSignClientFabric"
]
},
"depends": {
"midnightlib": "*"
},
"recommends": {
"watermedia": "*"
},
"breaks": {
"watermedia": "<2.1.0"
},
"mixins": [
"picturesign.mixins.json"
]

View File

@@ -1,19 +1,27 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
org.gradle.jvmargs=-Xmx2048M
# Fabric Properties
# check these on https://fabricmc.net/use
minecraft_version=1.17.1
yarn_mappings=1.17.1+build.61
loader_version=0.11.7
minecraft_version=1.21
yarn_mappings=1.21+build.2
enabled_platforms=fabric,neoforge
# Mod Properties
mod_version = 1.2.0
maven_group = eu.midnightdust
archives_base_name = picturesign
archives_base_name=picturesign
mod_version=2.0.1
maven_group=eu.midnightdust
release_type=release
curseforge_id=533897
modrinth_id=9WP2dmkk
# Dependencies
# currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api
fabric_version=0.40.1+1.17
midnightlib_version=0.2.9
iris_version=mc1.17.1-1.1.2
midnightlib_version=1.6.3
watermedia_version=2.1.2
iris_version=1.6.17+1.20.4
# The latest Iris version causes the build to fail, but we don't need that anyway
fabric_loader_version=0.15.11
fabric_api_version=0.100.1+1.21
neoforge_version=21.0.14-beta
yarn_mappings_patch_neoforge_version = 1.21+build.4
quilt_loader_version=0.19.0-beta.18
quilt_fabric_api_version=7.0.1+0.83.0-1.20

Binary file not shown.

View File

@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

41
gradlew vendored
View File

@@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# 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/.
@@ -80,13 +80,11 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# 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"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -133,22 +131,29 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
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
@@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# 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" \
@@ -205,6 +214,12 @@ set -- \
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.

181
gradlew.bat vendored
View File

@@ -1,89 +1,92 @@
@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
@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=.
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%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
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%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@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
@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

116
neoforge/build.gradle Normal file
View File

@@ -0,0 +1,116 @@
plugins {
id 'com.github.johnrengelman.shadow'
id "me.shedaniel.unified-publishing"
}
repositories {
maven {
name = 'NeoForged'
url = 'https://maven.neoforged.net/releases'
}
}
architectury {
platformSetupLoomIde()
neoForge()
}
loom {
accessWidenerPath = project(":common").loom.accessWidenerPath
}
configurations {
common {
canBeResolved = true
canBeConsumed = false
}
compileClasspath.extendsFrom common
runtimeClasspath.extendsFrom common
developmentNeoForge.extendsFrom common
// Files in this configuration will be bundled into your mod using the Shadow plugin.
// Don't use the `shadow` configuration from the plugin itself as it's meant for excluding files.
shadowBundle {
canBeResolved = true
canBeConsumed = false
}
archivesBaseName = rootProject.archives_base_name + "-neoforge"
}
dependencies {
neoForge "net.neoforged:neoforge:$rootProject.neoforge_version"
modImplementation include ("maven.modrinth:midnightlib:${rootProject.midnightlib_version}-neoforge")
common(project(path: ':common', configuration: 'namedElements')) { transitive false }
shadowBundle project(path: ':common', configuration: 'transformProductionNeoForge')
}
processResources {
inputs.property 'version', project.version
filesMatching('META-INF/neoforge.mods.toml') {
expand version: project.version
}
}
shadowJar {
configurations = [project.configurations.shadowBundle]
archiveClassifier = 'dev-shadow'
}
remapJar {
input.set shadowJar.archiveFile
}
sourcesJar {
def commonSources = project(":common").sourcesJar
dependsOn commonSources
from commonSources.archiveFile.map { zipTree(it) }
}
components.java {
withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) {
skip()
}
}
unifiedPublishing {
project {
displayName = "PictureSign $project.version - NeoForge $project.minecraft_version"
releaseType = "$project.release_type"
changelog = releaseChangelog()
gameVersions = []
gameLoaders = ["neoforge"]
mainPublication remapJar
relations {
depends {
curseforge = "watermedia"
modrinth = "watermedia"
}
includes {
curseforge = "midnightlib"
modrinth = "midnightlib"
}
}
var CURSEFORGE_TOKEN = project.findProperty("CURSEFORGE_TOKEN") ?: System.getenv("CURSEFORGE_TOKEN")
if (CURSEFORGE_TOKEN != null) {
curseforge {
token = CURSEFORGE_TOKEN
id = rootProject.curseforge_id
gameVersions.addAll "Java 21", project.minecraft_version
}
}
var MODRINTH_TOKEN = project.findProperty("MODRINTH_TOKEN") ?: System.getenv("MODRINTH_TOKEN")
if (MODRINTH_TOKEN != null) {
modrinth {
token = MODRINTH_TOKEN
id = rootProject.modrinth_id
version = "$project.version-$project.name"
gameVersions.addAll project.minecraft_version
}
}
}
}

View File

@@ -0,0 +1 @@
loom.platform=neoforge

View File

@@ -0,0 +1,17 @@
package eu.midnightdust.picturesign.neoforge;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent;
import static eu.midnightdust.picturesign.PictureSignClient.MOD_ID;
import static eu.midnightdust.picturesign.PictureSignClient.BINDING_COPY_SIGN;
@EventBusSubscriber(modid = MOD_ID, bus = EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public class PictureSignClientEvents {
@SubscribeEvent
public static void registerKeybinding(RegisterKeyMappingsEvent event) {
event.register(BINDING_COPY_SIGN);
}
}

View File

@@ -0,0 +1,54 @@
package eu.midnightdust.picturesign.neoforge;
import eu.midnightdust.picturesign.util.GIFHandler;
import eu.midnightdust.picturesign.util.MediaHandler;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.BlockPos;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent;
import net.neoforged.neoforge.client.event.ClientTickEvent;
import net.neoforged.neoforge.event.level.ChunkEvent;
import static eu.midnightdust.picturesign.PictureSignClient.id;
import static eu.midnightdust.picturesign.PictureSignClient.client;
import static eu.midnightdust.picturesign.PictureSignClient.clipboard;
import static eu.midnightdust.picturesign.PictureSignClient.MOD_ID;
import static eu.midnightdust.picturesign.PictureSignClient.BINDING_COPY_SIGN;
@EventBusSubscriber(modid = MOD_ID, bus = EventBusSubscriber.Bus.GAME, value = Dist.CLIENT)
public class PictureSignClientGameEvents {
@SubscribeEvent()
public static void sendPacketOnLogin(ClientPlayerNetworkEvent.LoggingIn event) {
if (MediaHandler.hasValidImplementation()) MediaHandler.closeAll();
}
@SubscribeEvent
public static void onBlockEntityUnload(ChunkEvent.Unload event) {
if (MediaHandler.hasValidImplementation()) {
for (BlockPos pos : event.getChunk().getBlockEntityPositions()) {
Identifier videoId = id(pos.getX() + "_" + pos.getY() + "_" + pos.getZ() + "_f");
MediaHandler.closePlayer(videoId);
Identifier videoId2 = id(pos.getX() + "_" + pos.getY() + "_" + pos.getZ() + "_b");
MediaHandler.closePlayer(videoId2);
}
}
}
@SubscribeEvent
public static void endClientTick(ClientTickEvent.Post event) {
GIFHandler.gifHandlers.forEach(((identifier, handler) -> handler.tick()));
if (!BINDING_COPY_SIGN.isPressed()) return;
BINDING_COPY_SIGN.setPressed(false);
if (client.player == null || client.world == null || client.crosshairTarget == null || client.crosshairTarget.getType() != HitResult.Type.BLOCK) return;
if (client.crosshairTarget.getType() == HitResult.Type.BLOCK && client.world.getBlockState(BlockPos.ofFloored(client.crosshairTarget.getPos())).hasBlockEntity()) {
if (client.world.getBlockEntity(BlockPos.ofFloored(client.crosshairTarget.getPos())) instanceof SignBlockEntity sign) {
boolean front = sign.isPlayerFacingFront(client.player);
for (int i = 0; i < 4; i++) {
clipboard[i] = sign.getText(front).getMessage(i, false).getString();
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
package eu.midnightdust.picturesign.neoforge;
import eu.midnightdust.picturesign.PictureSignClient;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.fml.common.Mod;
import static eu.midnightdust.picturesign.PictureSignClient.MOD_ID;
@SuppressWarnings("all")
@Mod(value = MOD_ID, dist = Dist.CLIENT)
public class PictureSignClientNeoForge {
public PictureSignClientNeoForge() {
PictureSignClient.init();
}
}

View File

@@ -0,0 +1,15 @@
package eu.midnightdust.picturesign.util.neoforge;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.packet.Packet;
import static eu.midnightdust.picturesign.PictureSignClient.client;
public class NetworkUtilImpl {
private static final ClientPlayNetworkHandler handler = client.getNetworkHandler();
public static void sendPacket(Packet<?> packet) {
if (handler != null)
handler.send(packet);
}
}

View File

@@ -0,0 +1,38 @@
modLoader = "javafml"
loaderVersion = "[2,)"
#issueTrackerURL = ""
license = "MIT License"
[[mods]]
modId = "picturesign"
version = "${version}"
displayName = "PictureSign"
logoFile = "icon.png"
authors = "Motschen, TeamMidnightDust"
description = '''
Use signs to display custom images and videos completely client-side!
'''
[[mixins]]
config = "picturesign.mixins.json"
[[dependencies.picturesign]]
modId = "neoforge"
mandatory = true
versionRange = "[21.0,)"
ordering = "NONE"
side = "BOTH"
[[dependencies.picturesign]]
modId = "minecraft"
mandatory = true
versionRange = "[1.21,)"
ordering = "NONE"
side = "BOTH"
[[dependencies.picturesign]]
modId = "midnightlib"
mandatory = true
versionRange = "[1.0,)"
ordering = "AFTER"
side = "BOTH"

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -1,10 +1,15 @@
pluginManagement {
repositories {
jcenter()
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
maven { url "https://maven.fabricmc.net/" }
maven { url "https://maven.architectury.dev/" }
maven { url "https://maven.neoforged.net/releases" }
gradlePluginPortal()
}
}
include("common")
include("fabric")
//include("quilt")
include("neoforge")
rootProject.name = "picturesign"

View File

@@ -1,109 +0,0 @@
package eu.midnightdust.picturesign;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.NativeImageBackedTexture;
import net.minecraft.util.Identifier;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import static java.util.concurrent.Executors.newFixedThreadPool;
public class PictureDownloader {
public static class PictureData {
public String url;
public Identifier identifier;
public PictureData(String url) {
this.url = url;
}
}
static PictureDownloader downloader = new PictureDownloader();
public static PictureDownloader getInstance() {
return downloader;
}
// Create a service for downloading the picture
private final ExecutorService service = newFixedThreadPool(PictureSignConfig.maxThreads);
private final Hashtable<String, PictureData> cache = new Hashtable<>();
private final Object mutex = new Object();
// Downloads the picture, or returns the cached picture
public PictureData getPicture(String url) {
synchronized (mutex) {
// Try to get the picture from cache
PictureData data = this.cache.get(url);
if (data == null) {
// Download the picture if not in cache
this.downloadPicture(url);
return null;
}
if (data.identifier == null) {
return null;
}
return data;
}
}
// Download the image and save it in cache
private void downloadPicture(String url) {
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Started downloading picture: " + url);
this.cache.put(url, new PictureData(url));
service.submit(() -> {
try {
BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
File file = File.createTempFile(".picturesign", "temp");
file.deleteOnExit();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
out.write(dataBuffer, 0, bytesRead);
}
out.close();
// Convert to png
BufferedImage bufferedImage = ImageIO.read(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
NativeImage nativeImage = NativeImage.read(inputStream);
NativeImageBackedTexture nativeImageBackedTexture = new NativeImageBackedTexture(nativeImage);
Identifier texture = MinecraftClient.getInstance().getTextureManager().registerDynamicTexture("picturesign/image",
nativeImageBackedTexture);
// Cache the downloaded picture
synchronized (mutex) {
PictureData data = this.cache.get(url);
data.identifier = texture;
}
if (PictureSignConfig.debug) PictureSignClient.LOGGER.info("Finished downloading picture: " + url);
} catch (IOException error) {
PictureSignClient.LOGGER.error("Error downloading picture: " + error);
}
});
}
}

View File

@@ -1,14 +0,0 @@
package eu.midnightdust.picturesign;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import net.fabricmc.api.ClientModInitializer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class PictureSignClient implements ClientModInitializer {
public static Logger LOGGER = LogManager.getLogger("PictureSign");
@Override
public void onInitializeClient() {
PictureSignConfig.init("picturesign", PictureSignConfig.class);
}
}

View File

@@ -1,13 +0,0 @@
package eu.midnightdust.picturesign.config;
import eu.midnightdust.lib.config.MidnightConfig;
public class PictureSignConfig extends MidnightConfig {
@Entry public static boolean enabled = true;
@Entry public static boolean debug = false;
@Entry(min = 1, max = 10) public static int maxThreads = 4;
@Entry(min = 0, max = 4096) public static int signRenderDistance = 64;
@Entry public static boolean safeMode = true;
@Comment public static Comment ebeWarning;
@Comment public static Comment ebeWarning2;
}

View File

@@ -1,41 +0,0 @@
package eu.midnightdust.picturesign.mixin;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import eu.midnightdust.picturesign.render.PictureSignRenderer;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.client.render.*;
import net.minecraft.client.render.block.entity.BlockEntityRenderer;
import net.minecraft.client.render.block.entity.SignBlockEntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import org.spongepowered.asm.mixin.Mixin;
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;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(SignBlockEntityRenderer.class)
public abstract class MixinSignBlockEntityRenderer implements BlockEntityRenderer<SignBlockEntity> {
PictureSignRenderer psRenderer = new PictureSignRenderer();
@Inject(at = @At("HEAD"), method = "render")
public void ps$onRender(SignBlockEntity signBlockEntity, float f, MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int light, int overlay, CallbackInfo ci) {
if (PictureSignConfig.enabled && signBlockEntity.getTextOnRow(0,false).getString().matches("(!PS:.*)")) {
psRenderer.render(signBlockEntity, matrixStack, light, overlay);
}
}
@Inject(at = @At("HEAD"), method = "shouldRender", cancellable = true)
private static void shouldRender(SignBlockEntity sign, int signColor, CallbackInfoReturnable<Boolean> cir) {
if (PictureSignConfig.enabled && sign.getTextOnRow(0,false).getString().matches("(!PS:.*)")) cir.setReturnValue(true);
}
@Unique
@Override
public int getRenderDistance() {
return PictureSignConfig.signRenderDistance;
}
@Unique
@Override
public boolean rendersOutsideBoundingBox(SignBlockEntity sign) {
return PictureSignConfig.enabled && sign.getTextOnRow(0, false).getString().matches("(!PS:.*)");
}
}

View File

@@ -1,137 +0,0 @@
package eu.midnightdust.picturesign.render;
import com.mojang.blaze3d.systems.RenderSystem;
import eu.midnightdust.picturesign.PictureDownloader;
import eu.midnightdust.picturesign.config.PictureSignConfig;
import net.coderbot.iris.Iris;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.block.Blocks;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.client.render.*;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.state.property.Properties;
import net.minecraft.util.math.*;
import net.minecraft.world.World;
import java.util.Arrays;
import java.util.List;
public class PictureSignRenderer {
public void render(SignBlockEntity signBlockEntity, MatrixStack matrixStack, int light, int overlay) {
String text = signBlockEntity.getTextOnRow(0, false).getString() +
signBlockEntity.getTextOnRow(1, false).getString() +
signBlockEntity.getTextOnRow(2, false).getString();
String url = text.replaceAll("!PS:", "").replaceAll(" ","");
if (url.contains("imgur:")) url = url.replace("imgur:", "https://i.imgur.com/");
if (url.contains("imgbb:")) url = url.replace("imgbb:", "https://i.ibb.co/");
if (!url.contains("https://") && !url.contains("http://")) {
url = "https://" + url;
}
if (!url.contains(".png") && !url.contains(".jpg") && !url.contains(".jpeg")) return;
if (PictureSignConfig.safeMode && !url.contains("//i.imgur.com/") && !url.contains("//i.ibb.co/")) return;
World world = signBlockEntity.getWorld();
BlockPos pos = signBlockEntity.getPos();
if (world != null && (world.getBlockState(pos.down()).getBlock().equals(Blocks.REDSTONE_TORCH) || world.getBlockState(pos.down()).getBlock().equals(Blocks.REDSTONE_WALL_TORCH)) && world.getBlockState(pos.down()).get(Properties.LIT).equals(false)) return;
if (world != null && (world.getBlockState(pos.up()).getBlock().equals(Blocks.REDSTONE_TORCH) || world.getBlockState(pos.up()).getBlock().equals(Blocks.REDSTONE_WALL_TORCH)) && world.getBlockState(pos.up()).get(Properties.LIT).equals(false)) return;
String lastLine = signBlockEntity.getTextOnRow(3, false).getString();
if (!lastLine.matches("(.*\\d:.*\\d:.*\\d:.*\\d:.*\\d)")) return;
List<String> scale = Arrays.stream(lastLine.split(":")).toList();
float width = 0;
float height = 0;
float x = 0;
float y = 0;
float z = 0;
try {
width = Float.parseFloat(scale.get(0));
height = Float.parseFloat(scale.get(1));
x = Float.parseFloat(scale.get(2));
y = Float.parseFloat(scale.get(3));
z = Float.parseFloat(scale.get(4));
}
catch (NumberFormatException ignored) {}
// Download the picture data
PictureDownloader.PictureData data = PictureDownloader.getInstance().getPicture(url);
if (data == null || data.identifier == null) {
return;
}
float xOffset = 0.0F;
float zOffset = 0.0F;
Quaternion yRotation = Vec3f.POSITIVE_Y.getDegreesQuaternion(0F);
if (signBlockEntity.getCachedState().contains(Properties.HORIZONTAL_FACING)) {
Direction direction = signBlockEntity.getCachedState().get(Properties.HORIZONTAL_FACING);
switch (direction) {
case NORTH -> {
zOffset = 1.01F;
xOffset = 1.0F;
yRotation = Vec3f.POSITIVE_Y.getDegreesQuaternion(180.0F);
}
case SOUTH -> zOffset = 0.010F;
case EAST -> {
zOffset = 1.01F;
yRotation = Vec3f.POSITIVE_Y.getDegreesQuaternion(90.0F);
}
case WEST -> {
yRotation = Vec3f.POSITIVE_Y.getDegreesQuaternion(-90.0F);
xOffset = 1.01F;
}
}
}
else if (signBlockEntity.getCachedState().contains(Properties.ROTATION)) {
yRotation = Vec3f.POSITIVE_Y.getDegreesQuaternion(signBlockEntity.getCachedState().get(Properties.ROTATION) * -22.5f);
}
else return;
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
matrixStack.push();
int l;
if (FabricLoader.getInstance().isModLoaded("iris") && Iris.getIrisConfig().areShadersEnabled() && Iris.getCurrentPack().isPresent()) {
RenderSystem.setShader(GameRenderer::getRenderTypeCutoutShader);
l = 230;
}
else {
RenderSystem.setShader(GameRenderer::getPositionColorTexLightmapShader);
l = light;
}
RenderSystem.setShaderTexture(0, data.identifier);
RenderSystem.disableBlend();
RenderSystem.enableDepthTest();
RenderSystem.depthMask(true);
matrixStack.translate(xOffset + x, 0.00F + y, zOffset + z);
matrixStack.multiply(yRotation);
Matrix4f matrix4f = matrixStack.peek().getModel();
buffer.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR_TEXTURE_LIGHT);
buffer.vertex(matrix4f, width, 0.0F, 1.0F).color(255, 255, 255, 255).texture(1.0F, 1.0F).light(l).overlay(overlay)
.next();
buffer.vertex(matrix4f, width, height, 1.0F).color(255, 255, 255, 255).texture(1.0F, 0.0F).light(l).overlay(overlay)
.next();
buffer.vertex(matrix4f, 0.0F, height, 1.0F).color(255, 255, 255, 255).texture(0.0F, 0.0F).light(l).overlay(overlay)
.next();
buffer.vertex(matrix4f, 0.0F, 0.0F, 1.0F).color(255, 255, 255, 255).texture(0.0F, 1.0F).light(l).overlay(overlay)
.next();
tessellator.draw();
matrixStack.pop();
RenderSystem.disableDepthTest();
}
}

View File

@@ -1,12 +0,0 @@
{
"picturesign.midnightconfig.title":"PictureSign Config",
"picturesign.midnightconfig.enabled":"Enabled",
"picturesign.midnightconfig.debug":"Send debug info",
"picturesign.midnightconfig.maxThreads":"Max download threads",
"picturesign.midnightconfig.signRenderDistance":"Sign render distance",
"picturesign.midnightconfig.safeMode":"Safe mode",
"picturesign.midnightconfig.safeMode.tooltip":"Only load images from imgur.com and imgbb.com",
"picturesign.midnightconfig.ebeWarning":"§cIf you are using the mod 'Enhanced Block Entities'",
"picturesign.midnightconfig.ebeWarning2":"§cmake sure to disable anything sign-related in it's config!"
}

View File

@@ -1,11 +0,0 @@
{
"required": true,
"package": "eu.midnightdust.picturesign.mixin",
"compatibilityLevel": "JAVA_16",
"client": [
"MixinSignBlockEntityRenderer"
],
"injectors": {
"defaultRequire": 1
}
}