Compare commits

..

60 Commits
master ... 1.20

Author SHA1 Message Date
470b5839a4 尝试修复客户端崩溃问题 2026-05-31 21:52:07 +08:00
GiantLuigi4
594c4decf3 improve keyboard camera 2024-10-21 23:53:07 -04:00
GiantLuigi4
ecb0dcee56 bump version, very start of audio stuff, fix a strange crash where camera is null 2024-10-19 00:53:48 -04:00
GiantLuigi4
cc18c6f793 improve handling of errors in the wd scheme
also config for join message
2024-10-18 00:11:58 -04:00
GiantLuigi4
6e712fc8da fix minisrv 2024-10-17 23:07:02 -04:00
GiantLuigi4
06e722cb7c screens can now be mined with a pickaxe 2024-10-17 12:36:11 -04:00
ds58
2ffe983e12
Merge pull request #17 from OtterCodes101/1.20
Add Modrinth link
2024-08-09 10:14:31 -05:00
OtterDev
5462ec7e93
Update README.md 2023-12-13 08:53:10 -07:00
GiantLuigi4
a603bdc8df - fix issues with minepad cursor lock
- keyboard now enables mouse controls
- fix some issues with the keyboard camera
- helper methods on the screen block entity for dealing with hit results
- update non-english language files to json
2023-11-29 13:54:42 -05:00
GiantLuigi4
21ffc08fcf keyboard camera mode config, fix some bugs with the ElementCenterQuery, fix ownership theif interacting with the wrong side 2023-11-27 18:05:18 -05:00
GiantLuigi4
cc0803de11 screen configurator now uses the correct direction 2023-11-27 15:24:43 -05:00
GiantLuigi4
7e7133e08c tweaks to js handling 2023-11-27 15:18:30 -05:00
GiantLuigi4
2e30446281 fix load distance 2023-11-27 11:18:12 -05:00
GiantLuigi4
9452482254 some refactoring 2023-11-27 10:35:26 -05:00
GiantLuigi4
91557161e0 pointer lock support 2023-11-26 00:46:53 -05:00
GiantLuigi4
85b076d638 ok I can push this too 2023-11-25 16:29:41 -05:00
GiantLuigi4
5292e97a8f start work on pointer lock api 2023-11-25 16:29:04 -05:00
GiantLuigi4
f843376f7a better mouse movement 2023-11-24 18:04:09 -05:00
GiantLuigi4
84d475d61c use a proper inverse of hit2px for the coordinate calculation for the keyboard camera 2023-11-22 23:59:18 -05:00
GiantLuigi4
f3f3cff079 not the best code quality, but it works how I wanted it to work 2023-11-22 22:52:08 -05:00
GiantLuigi4
fe81c18b5b I believe I have messed up... 2023-11-22 21:59:14 -05:00
GiantLuigi4
ec904c199e Merge remote-tracking branch 'origin/1.20' into 1.20
# Conflicts:
#	src/main/java/net/montoyo/wd/block/ScreenBlock.java
#	src/main/java/net/montoyo/wd/client/ClientProxy.java
#	src/main/java/net/montoyo/wd/client/gui/GuiKeyboard.java
#	src/main/java/net/montoyo/wd/client/gui/GuiScreenConfig.java
#	src/main/java/net/montoyo/wd/client/renderers/ScreenRenderer.java
#	src/main/java/net/montoyo/wd/controls/builtin/ManageRightsAndUpdgradesControl.java
#	src/main/java/net/montoyo/wd/data/ScreenConfigData.java
#	src/main/java/net/montoyo/wd/entity/AbstractInterfaceBlockEntity.java
#	src/main/java/net/montoyo/wd/entity/KeyboardBlockEntity.java
#	src/main/java/net/montoyo/wd/entity/RedstoneControlBlockEntity.java
#	src/main/java/net/montoyo/wd/entity/RemoteControlBlockEntity.java
#	src/main/java/net/montoyo/wd/entity/ScreenBlockEntity.java
#	src/main/java/net/montoyo/wd/item/ItemLaserPointer.java
#	src/main/java/net/montoyo/wd/item/ItemLinker.java
#	src/main/java/net/montoyo/wd/item/ItemOwnershipThief.java
#	src/main/java/net/montoyo/wd/item/ItemScreenConfigurator.java
#	src/main/java/net/montoyo/wd/net/client_bound/S2CMessageAddScreen.java
2023-11-22 21:54:43 -05:00
GiantLuigi4
281eb51c0d keyboard camera prototype 2023-11-22 21:48:54 -05:00
GiantLuigi4
3d2f786049 split "Screen" class out of TileEntityScreen 2023-11-22 15:51:38 -05:00
GiantLuigi4
3ca9f6ceb1
Merge pull request #7 from CinemaMod/format
Format
2023-11-11 18:05:22 -05:00
GiantLuigi4
92bd6924b0 undo cleanup of mouse handling, because it did not work 2023-11-11 17:59:15 -05:00
ds58
639fdefcce 2.0.1-1.20.1 2023-11-11 15:44:59 -06:00
ds58
1de20710fe Fix mcef dependency version in mods.toml 2023-11-11 15:44:22 -06:00
ds58
5b37a39dbc
Update README.md 2023-11-10 23:36:42 -06:00
ds58
0bc5b3b67d
Update README.md 2023-11-10 23:36:14 -06:00
ds58
dbd8fba683
Update README.md 2023-11-10 23:31:09 -06:00
ds58
d6da33da63 Merge branch '1.20' of https://github.com/CinemaMod/webdisplays into 1.20 2023-11-10 23:10:01 -06:00
ds58
2969470796 Update mods.toml 2023-11-10 23:09:32 -06:00
GiantLuigi4
074cedc85c some restructuring 2023-11-11 00:06:56 -05:00
GiantLuigi4
a4b4162fa9 modernize naming pt1 2023-11-10 23:58:05 -05:00
GiantLuigi4
a2f81aeeac modernize naming pt0 2023-11-10 23:57:02 -05:00
ds58
c2d6f01991
Add some images to README 2023-11-10 22:50:25 -06:00
GiantLuigi4
a9d9dcfecf format. 2023-11-10 23:50:06 -05:00
ds58
96d7c92c37 MIT License, start new README, gradle.properties cleanup 2023-11-10 22:46:18 -06:00
ds58
6869461124 Update Specification-Title in MANIFEST 2023-11-10 21:55:38 -06:00
ds58
66212d2d16 Make gradlew executable, remove libs dir 2023-11-10 21:54:56 -06:00
GiantLuigi4
aa8c545089 screens now get removed properly, TileEntityScreen has had ctrl+alt+l applied to it, and gradle has been cleaned up 2023-11-10 22:09:39 -05:00
GiantLuigi4
5ac5bada9d vivecraft support's back 2023-10-19 09:52:26 -04:00
GiantLuigi4
2a2d3077f4 update to latest MCEF, fix a potential rendering crash for the event that MCEF doesn't initalize properly 2023-10-19 00:21:03 -04:00
GiantLuigi4
92d5da727e update cursor textures 2023-09-27 23:16:07 -04:00
GiantLuigi4
ce718eeea2 minepad stuff 2023-09-27 22:33:13 -04:00
GiantLuigi4
e0ab3d2495 Merge remote-tracking branch 'origin/1.20' into 1.20
# Conflicts:
#	src/main/java/net/montoyo/wd/WebDisplays.java
2023-09-27 21:44:30 -04:00
GiantLuigi4
a4f8b630ef Packet for turning off a screen, start working on schema stuff 2023-09-27 21:36:35 -04:00
GiantLuigi4
3548b5806c fix some bugs with text fields 2023-09-27 15:04:52 -04:00
GiantLuigi4
95dc94d108 fix gui rendering, fix sounds being null, reimplement crosshair rendering 2023-09-27 14:41:35 -04:00
GiantLuigi4
48a46969ba sounds now work and the minepad now renders properly in hand 2023-09-24 22:52:29 -04:00
GiantLuigi4
42421a031a fix a dumb 2023-09-22 17:37:02 -04:00
GiantLuigi4
583fcc7be8 ack3 2023-09-22 17:30:26 -04:00
GiantLuigi4
2fc7c49977 ack2 2023-09-22 16:51:50 -04:00
GiantLuigi4
260027f12e ack 2023-09-22 16:51:36 -04:00
GiantLuigi4
5281694d6a fix a bunch of stuff that I intentionally broke 2023-09-22 16:25:45 -04:00
GiantLuigi4
2c931928d8 things are just barely able to be considered as working 2023-09-22 15:40:17 -04:00
GiantLuigi4
0867dd68d7 mod compiles, things *really* don't work 2023-09-22 15:26:43 -04:00
GiantLuigi4
f7f92cd19c lot of the work is done 2023-09-22 13:56:23 -04:00
GiantLuigi4
76a2a704dd update gradle 2023-09-21 22:40:01 -04:00
261 changed files with 6564 additions and 5915 deletions

22
LICENSE
View File

@ -1 +1,21 @@
This mod and its source code is now in public domain. Feel free to do whatever you want with it; make forks, distribute it... whatever I would appreciate it, of course, if you credited me 😊 Thank you! MIT License
Copyright (c) 2023 CinemaMod Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,15 +1,25 @@
# WebDisplays for Minecraft 1.19.2 # WebDisplays
This is a fork of the Web Displays mod from 1.12, updated to work on 1.19, and with some bug fixes and reworking. WebDisplays is a mod for creating and interacting with web browsers in Minecraft. You can create screens in your world and browse the internet.
### Wiki WebDisplays was originally written by montoyo. It is currently maintained by CinemaMod Group.
* The Wiki that details all blocks/items can be found on my website https://montoyo.net/wdwiki/
### Delayed things Discussion: https://discord.gg/rNrh5kW8Ty
* Plugin API
* The Shop ## Install
* CC Interface, if CC gets updated... Download WebDisplays from either:
* Center camera to screen when using keyboard - CurseForge: https://legacy.curseforge.com/minecraft/mc-mods/webdisplays
* minePad management: check GuiContainer.draggedStack for minePad - Modrinth: https://modrinth.com/mod/webdisplays
* In-game command to add/remove blacklisted domains
* Config: RPMP (Real pixels per Minecraft pixels) **WebDisplays Requires MCEF!** You must install MCEF in order for WebDisplays to work.
* Disable miniserv in solo
Download MCEF from either:
- CurseForge: https://legacy.curseforge.com/minecraft/mc-mods/mcef
- Modrinth: https://modrinth.com/mod/mcef
<img src='https://github.com/CinemaMod/webdisplays/assets/30220598/2acfd365-fa87-4adb-970a-33bb5c79f7ba' width='500'>
<img src='https://github.com/CinemaMod/webdisplays/assets/30220598/4e9985a3-d09f-4ab4-8016-37733d4f4a99' width='500'>
## Wiki
[Outdated Wiki from the original creator](https://montoyo.net/wdwiki/index.php?title=Main_Page)
[Outdated Getting Started](https://montoyo.net/wdwiki/index.php?title=Screen)

12
TODO.md Normal file
View File

@ -0,0 +1,12 @@
### Delayed things
* Plugin API
* Center camera to screen when using keyboard
* Allow actual cursor to be used via aiming it at the screen
* maybe aim at the focused element instead of the center of the screen, depends on if that information can be extracted
* minePad management: check GuiContainer.draggedStack for minePad
* In-game command to add/remove blacklisted domains
* CC Interface (for when it's actually possible, since the screens are client only currently, but a config option is planned to change that)
* Redstone controls (same reason as CC interface)
* Potentially redo minisrv logic?
* Perhaps hook it up to vanilla networking
* Maybe don't use it at all in single player

View File

@ -1,140 +1,179 @@
plugins { plugins {
id 'eclipse' id 'java'
id 'idea'
id 'maven-publish' id 'maven-publish'
id 'net.minecraftforge.gradle' version '5.1.+' id 'com.github.johnrengelman.shadow' version '8.1.1'
id 'org.spongepowered.mixin' version '0.7.+' id 'net.neoforged.moddev.legacyforge' version '2.0.103'
} }
version = mod_version // Only add ProGuard if building with it
group = maven_group // http://maven.apache.org/guides/mini/guide-naming-conventions.html def enableProguard = project.hasProperty("enableProguard") && project.enableProguard.toBoolean()
archivesBaseName = archives_base_name if (enableProguard) {
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.guardsquare:proguard-gradle:7.7.0'
}
}
}
base {
archivesName = mod_id
}
group = mod_group_id
version = "${minecraft_version}-${mod_version}"
java.toolchain.languageVersion = JavaLanguageVersion.of(17) java.toolchain.languageVersion = JavaLanguageVersion.of(17)
println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch')) println "Java: ${System.getProperty 'java.version'}"
minecraft {
mappings channel: 'official', version: '1.19.2'
accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') repositories {
mavenCentral()
maven { url = "https://libraries.minecraft.net/" }
maven { url = "https://cursemaven.com" }
maven { url = "https://maven.parchmentmc.org" }
maven { url = 'https://mcef-download.cinemamod.com/repositories/releases/' }
maven { url = "https://dl.cloudsmith.io/public/geckolib3/geckolib/maven/" }
maven { url = "https://maven.theillusivec4.top/" }
maven { url = "https://repo.lucko.me/" }
maven { url = "https://maven.kosmx.dev/" }
maven { url = "https://modmaven.dev" }
flatDir { dir "libs" }
}
legacyForge {
version = "${minecraft_version}-${forge_version}"
// Access transformer
accessTransformers = files("src/main/resources/META-INF/accesstransformer.cfg")
// Parchment mappings
parchment {
minecraftVersion = minecraft_version
mappingsVersion = mapping_lasting_version
}
runs { runs {
client { configureEach {
properties 'mixin.env.remapRefMap': 'true' systemProperty 'forge.logging.console.level', 'debug'
property 'mixin.env.refMapRemappingFile', "${project.projectDir}/build/createSrgToMcp/output.srg" logLevel = org.slf4j.event.Level.DEBUG
workingDirectory project.file('run') }
arg "-mixin.config=webdisplays.mixins.json"
property 'forge.logging.console.level', 'debug'
mods { client {
webdisplays { client()
source sourceSets.main programArgument "-mixin.config=${mod_id}.mixins.json"
} systemProperty 'mixin.debug.export', 'true'
}
} }
server { server {
properties 'mixin.env.remapRefMap': 'true' server()
property 'mixin.env.refMapRemappingFile', "${project.projectDir}/build/createSrgToMcp/output.srg" programArgument "-mixin.config=${mod_id}.mixins.json"
workingDirectory project.file('run')
arg "-mixin.config=webdisplays.mixins.json"
property 'forge.logging.console.level', 'debug'
mods {
webdisplays {
source sourceSets.main
}
}
} }
data { data {
workingDirectory project.file('run') data()
properties 'mixin.env.remapRefMap': 'true' programArguments.addAll '--mod', mod_id, '--all',
property 'mixin.env.refMapRemappingFile', "${project.projectDir}/build/createSrgToMcp/output.srg" '--output', file('src/generated/resources/').absolutePath,
property 'forge.logging.console.level', 'debug' '--existing', file('src/main/resources/').absolutePath
args '--mod', 'webdisplays', '--all', '--output', file('src/generated/resources/'), '--existing', sourceSets.main.resources.srcDirs[0] }
mods { }
webdisplays {
source sourceSets.main mods {
} "${mod_id}" {
} sourceSet sourceSets.main
} }
} }
} }
repositories{ sourceSets.main.resources {
maven { url "https://maven.shedaniel.me/" } srcDir 'src/generated/resources'
maven { url 'https://jitpack.io' }
maven {
name = "cursemaven"
url = "https://www.cursemaven.com"
}
flatDir { dirs 'libs' }
} }
dependencies { dependencies {
minecraft 'net.minecraftforge:forge:1.19.2-43.2.10' // MCEF dependency
annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' modImplementation("com.cinemamod:mcef-forge:2.1.1-1.20.1") {
transitive = false
implementation fg.deobf("com.github.Mysticpasta1:mcef-forge:2ec6581622") }
implementation fg.deobf("curse.maven:SU-370704:4485052")
implementation fg.deobf("curse.maven:spark-361579:4381167")
// implementation fg.deobf("flatdir.lib:mcef:1.2.4") // Optional mods (make sure versions exist)
// implementation fg.deobf("flatdir.lib:smallerunits:2.1.3") modRuntimeOnly "curse.maven:spark-361579:4738952"
modCompileOnly "curse.maven:vivecraft-667903:4794431"
modImplementation "software.bernie.geckolib:geckolib-forge-${minecraft_version}:${geckolib_version}"
modCompileOnly "top.theillusivec4.curios:curios-forge:${curios_version}:api"
modRuntimeOnly "top.theillusivec4.curios:curios-forge:${curios_version}"
compileOnly fg.deobf("curse.maven:vivecraft-667903:4409427") // Mixin Extras
compileOnly annotationProcessor("io.github.llamalad7:mixinextras-common:0.4.1")
modImplementation "io.github.llamalad7:mixinextras-forge:0.4.1"
} }
sourceSets { tasks.named('jar', Jar) {
main.resources.srcDirs += 'src/generated/resources'
}
// Example for how to get properties into the manifest for reading by the runtime..
jar {
manifest { manifest {
attributes([ attributes([
"Specification-Title": "webdisplays", 'Specification-Title': mod_name,
"Specification-Vendor": "webdisplays", 'Specification-Vendor': mod_authors,
"Specification-Version": "1", // We are version 1 of ourselves 'Specification-Version': '1',
"Implementation-Title": project.name, 'Implementation-Title': project.name,
"Implementation-Version": "${version}", 'Implementation-Version': project.version,
"Implementation-Vendor" :"webdisplays", 'Implementation-Vendor': mod_authors,
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), 'MixinConfigs': "${mod_id}.mixins.json"
"MixinConfigs": "webdisplays.mixins.json"
]) ])
} }
// Exclude ProGuard renamed files if ProGuard is used
if (enableProguard) {
exclude 'META-INF/versions/**'
}
} }
// Example configuration to allow publishing using the maven-publish task // Generate sources jar
// we define a custom artifact that is sourced from the reobfJar output task tasks.register('sourcesJar', Jar) {
// and then declare that to be published dependsOn classes
// Note you'll need to add a repository here archiveClassifier = 'sources'
def reobfFile = file("$buildDir/reobfJar/output.jar") from sourceSets.main.allSource
def reobfArtifact = artifacts.add('default', reobfFile) {
type 'jar'
builtBy 'reobfJar'
} }
// Reobfuscation handling
tasks.named('reobfJar') {
if (enableProguard) {
dependsOn 'proguard'
input = file("${buildDir}/libs/${mod_id}-${minecraft_version}-${mod_version}-proguard.jar")
} else {
dependsOn 'jar'
input = tasks.jar.archiveFile.get().asFile
}
}
// ProGuard configuration (if enabled)
if (enableProguard) {
tasks.register('proguard', proguard.gradle.ProGuardTask) {
dependsOn tasks.jar
configuration 'proguard.pro'
libraryjars "${System.getProperty('java.home')}/jmods"
def inputJar = tasks.jar.archiveFile.get().asFile
injars inputJar
outjars "${buildDir}/libs/${mod_id}-${minecraft_version}-${mod_version}-proguard.jar"
}
}
publishing { publishing {
publications { publications {
mavenJava(MavenPublication) { mavenJava(MavenPublication) {
artifact reobfArtifact artifactId = mod_id
artifact reobfJar
artifact sourcesJar
} }
} }
repositories { repositories {
maven { maven {
url "file:///${project.projectDir}/mcmodsrepo" name = "local"
url = layout.buildDirectory.dir("repo")
} }
} }
}
apply plugin: 'org.spongepowered.mixin'
mixin {
add sourceSets.main, "webdisplays.refmap.json"
}
task deobfJar(type: Jar) {
from sourceSets.main.output
classifier = 'deobf'
} }

File diff suppressed because one or more lines are too long

View File

@ -1,17 +1,36 @@
# Done to increase the memory available to gradle. # Gradle settings
org.gradle.jvmargs=-Xmx3G org.gradle.jvmargs=-Xmx3G
loom.platform=forge org.gradle.daemon=false
org.gradle.parallel=true
org.gradle.caching=true
# Fabric Properties # ProGuard
# check these on https://fabricmc.net/develop enableProguard=false
minecraft_version=1.19.2
yarn_mappings=1.19.2+build.28
loader_version=0.14.14
# Mod Properties # Mod properties
mod_version = 1.3.3 mod_id=webdisplays
maven_group = net.montoyo.wd mod_name=WebDisplays
archives_base_name = webdisplays mod_version=2.0.3
mod_group_id=com.cinemamod
mod_authors=CinemaMod Group
mod_description=Web browser displays for Minecraft
mod_license=All Rights Reserved
mod_credits=CinemaMod Group
# Dependencies # Minecraft/Forge versions
forge_version=1.19.2-43.2.6 minecraft_version=1.20.1
forge_version=47.3.4
minecraft_version_range=[1.20.1,1.21)
forge_version_range=[47,)
loader_version_range=[47,)
# Parchment mappings
mapping_channel=parchment
mapping_version=2023.09.03-1.20.1
mapping_lasting_version=2023.09.03
# Other mod versions
jei_version=15.20.0.112
player_anim_version=1.0.2-rc1+1.20
geckolib_version=4.2.1
curios_version=5.5.0+1.20.1

View File

@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip

0
gradlew vendored Normal file → Executable file
View File

View File

@ -1,20 +1,11 @@
pluginManagement { pluginManagement {
repositories { repositories {
mavenLocal()
gradlePluginPortal() gradlePluginPortal()
maven { url = 'https://maven.minecraftforge.net/' } maven { url = 'https://maven.neoforged.net/releases' }
} maven { url = 'https://maven.parchmentmc.org' } // Add this line
resolutionStrategy {
eachPlugin {
switch (requested.id.toString()) {
case "net.minecraftforge.gradle": {
useModule("${requested.id}:ForgeGradle:${requested.version}")
break
}
case "org.spongepowered.mixin": {
useModule("org.spongepowered:mixingradle:${requested.version}")
break;
}
}
}
} }
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
} }

View File

@ -4,6 +4,7 @@
package net.montoyo.wd; package net.montoyo.wd;
import com.cinemamod.mcef.MCEF;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
@ -13,15 +14,21 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraftforge.common.MinecraftForge; import net.minecraft.world.phys.Vec3;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.server.ServerLifecycleHooks; import net.minecraftforge.server.ServerLifecycleHooks;
import net.montoyo.mcef.api.CefInitEvent;
import net.montoyo.wd.core.HasAdvancement; import net.montoyo.wd.core.HasAdvancement;
import net.montoyo.wd.core.JSServerRequest; import net.montoyo.wd.core.JSServerRequest;
import net.montoyo.wd.data.GuiData; import net.montoyo.wd.data.GuiData;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import org.joml.Vector3d;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.UUID; import java.util.UUID;
@ -31,22 +38,22 @@ public class SharedProxy {
} }
public void init() { public void init() {
MinecraftForge.EVENT_BUS.addListener(this::onCefInit); MCEF.scheduleForInit((cef) -> onCefInit());
} }
public void postInit() { public void postInit() {
} }
public void onCefInit(CefInitEvent event) { public void onCefInit() {
} }
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true)
public Level getWorld(ResourceKey<Level> dim) { public Level getWorld(ResourceKey<Level> dim) {
return getServer().getLevel(dim); return getServer().getLevel(dim);
} }
public BlockGetter getWorld(NetworkEvent.Context context) { public BlockGetter getWorld(NetworkEvent.Context context) {
if (context.getSender() != null) return context.getSender().level; if (context.getSender() != null) return context.getSender().level();
return null; return null;
} }
@ -58,7 +65,7 @@ public class SharedProxy {
Log.error("Called SharedProxy.displayGui() on server side..."); Log.error("Called SharedProxy.displayGui() on server side...");
} }
public void trackScreen(TileEntityScreen tes, boolean track) { public void trackScreen(ScreenBlockEntity tes, boolean track) {
} }
public void onAutocompleteResult(NameUUIDPair pairs[]) { public void onAutocompleteResult(NameUUIDPair pairs[]) {
@ -121,4 +128,21 @@ public class SharedProxy {
public boolean isShiftDown() { public boolean isShiftDown() {
return false; return false;
} }
public double distanceTo(ScreenBlockEntity tes, Vec3 position) {
double dist = Double.POSITIVE_INFINITY;
for (int i = 0; i < tes.screenCount(); i++) {
ScreenData scrn = tes.getScreen(i);
Vector3d pos = new Vector3d(
scrn.side.right.x * scrn.size.x / 2d + scrn.size.y * scrn.side.up.x / 2d,
scrn.side.right.y * scrn.size.x / 2d + scrn.size.y * scrn.side.up.y / 2d,
scrn.side.right.z * scrn.size.x / 2d + scrn.size.y * scrn.side.up.z / 2d
).add(tes.getBlockPos().getX(), tes.getBlockPos().getY(), tes.getBlockPos().getZ());
double dist2 = position.distanceToSqr(pos.x, pos.y, pos.z);
dist = Math.min(dist, dist2);
}
return dist;
}
} }

View File

@ -38,20 +38,21 @@ import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ForgeRegistries;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.client.gui.camera.KeyboardCamera;
import net.montoyo.wd.config.ClientConfig; import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.config.CommonConfig; import net.montoyo.wd.config.CommonConfig;
import net.montoyo.wd.controls.ScreenControlRegistry; import net.montoyo.wd.controls.ScreenControlRegistry;
import net.montoyo.wd.core.*; import net.montoyo.wd.core.*;
import net.montoyo.wd.init.BlockInit;
import net.montoyo.wd.init.ItemInit;
import net.montoyo.wd.init.TileInit;
import net.montoyo.wd.miniserv.server.Server; import net.montoyo.wd.miniserv.server.Server;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageServerInfo; import net.montoyo.wd.net.client_bound.S2CMessageServerInfo;
import net.montoyo.wd.registry.BlockRegistry;
import net.montoyo.wd.registry.ItemRegistry;
import net.montoyo.wd.registry.TileRegistry;
import net.montoyo.wd.registry.WDTabs;
import net.montoyo.wd.utilities.DistSafety; import net.montoyo.wd.utilities.DistSafety;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import java.io.*; import java.io.*;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -66,14 +67,6 @@ public class WebDisplays {
public static SharedProxy PROXY = null; public static SharedProxy PROXY = null;
public static final boolean cursorSupport;
static {
ArtifactVersion ver = ModList.get().getModFileById("forgecef").getMods().get(0).getVersion();
cursorSupport = (ver.getMajorVersion() >= 1 && ver.getMinorVersion() >= 2 && ver.getIncrementalVersion() >= 4);
}
public static WDCreativeTab CREATIVE_TAB;
public static final ResourceLocation ADV_PAD_BREAK = new ResourceLocation("webdisplays", "webdisplays/pad_break"); public static final ResourceLocation ADV_PAD_BREAK = new ResourceLocation("webdisplays", "webdisplays/pad_break");
public static final String BLACKLIST_URL = "mod://webdisplays/blacklisted.html"; public static final String BLACKLIST_URL = "mod://webdisplays/blacklisted.html";
public static final Gson GSON = new Gson(); public static final Gson GSON = new Gson();
@ -122,13 +115,13 @@ public class WebDisplays {
// proxies are annoying, so from now on, I'mma be just registering stuff in here // proxies are annoying, so from now on, I'mma be just registering stuff in here
FMLJavaModLoadingContext.get().getModEventBus().addListener(ClientProxy::onKeybindRegistry); FMLJavaModLoadingContext.get().getModEventBus().addListener(ClientProxy::onKeybindRegistry);
MinecraftForge.EVENT_BUS.addListener(ClientProxy::onDrawSelection); MinecraftForge.EVENT_BUS.addListener(ClientProxy::onDrawSelection);
MinecraftForge.EVENT_BUS.addListener(KeyboardCamera::updateCamera);
MinecraftForge.EVENT_BUS.addListener(KeyboardCamera::gameTick);
ClientConfig.init(); ClientConfig.init();
} }
CommonConfig.init(); CommonConfig.init();
CREATIVE_TAB = new WDCreativeTab();
//Criterions //Criterions
criterionPadBreak = new Criterion("pad_break"); criterionPadBreak = new Criterion("pad_break");
criterionUpgradeScreen = new Criterion("upgrade_screen"); criterionUpgradeScreen = new Criterion("upgrade_screen");
@ -140,9 +133,10 @@ public class WebDisplays {
WDNetworkRegistry.init(); WDNetworkRegistry.init();
SOUNDS.register(bus); SOUNDS.register(bus);
onRegisterSounds(); onRegisterSounds();
BlockInit.init(bus); WDTabs.init(bus);
ItemInit.init(bus); BlockRegistry.init(bus);
TileInit.init(bus); ItemRegistry.init(bus);
TileRegistry.init(bus);
PROXY.preInit(); PROXY.preInit();
@ -178,12 +172,12 @@ public class WebDisplays {
} }
public void onRegisterSounds() { public void onRegisterSounds() {
registerSound("keyboard_type"); soundTyping = registerSound("keyboard_type");
registerSound( "upgrade_add"); soundUpgradeAdd = registerSound("upgrade_add");
registerSound( "upgrade_del"); soundUpgradeDel = registerSound("upgrade_del");
registerSound("screencfg_open"); soundScreenCfg = registerSound("screencfg_open");
registerSound("server"); soundServer = registerSound("server");
registerSound("ironic"); soundIronic = registerSound("ironic");
} }
ArrayList<ResourceKey<Level>> serverStartedDimensions = new ArrayList<>(); ArrayList<ResourceKey<Level>> serverStartedDimensions = new ArrayList<>();
@ -259,10 +253,10 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onToss(ItemTossEvent ev) { public void onToss(ItemTossEvent ev) {
if(!ev.getEntity().getLevel().isClientSide) { if(!ev.getEntity().level().isClientSide) {
ItemStack is = ev.getEntity().getItem(); ItemStack is = ev.getEntity().getItem();
if(is.getItem() == ItemInit.MINEPAD.get()) { if(is.getItem() == ItemRegistry.MINEPAD.get()) {
CompoundTag tag = is.getTag(); CompoundTag tag = is.getTag();
if(tag == null) { if(tag == null) {
@ -280,12 +274,12 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onPlayerCraft(PlayerEvent.ItemCraftedEvent ev) { public void onPlayerCraft(PlayerEvent.ItemCraftedEvent ev) {
if(CommonConfig.hardRecipes && ItemInit.isCompCraftItem(ev.getCrafting().getItem()) && (CraftComponent.EXTCARD.makeItemStack().is(ev.getCrafting().getItem()))) { if(CommonConfig.hardRecipes && ItemRegistry.isCompCraftItem(ev.getCrafting().getItem()) && (CraftComponent.EXTCARD.makeItemStack().is(ev.getCrafting().getItem()))) {
if((ev.getEntity() instanceof ServerPlayer && !hasPlayerAdvancement((ServerPlayer) ev.getEntity(), ADV_PAD_BREAK)) || PROXY.hasClientPlayerAdvancement(ADV_PAD_BREAK) != HasAdvancement.YES) { if((ev.getEntity() instanceof ServerPlayer && !hasPlayerAdvancement((ServerPlayer) ev.getEntity(), ADV_PAD_BREAK)) || PROXY.hasClientPlayerAdvancement(ADV_PAD_BREAK) != HasAdvancement.YES) {
ev.getCrafting().setDamageValue(CraftComponent.BADEXTCARD.ordinal()); ev.getCrafting().setDamageValue(CraftComponent.BADEXTCARD.ordinal());
if(!ev.getEntity().getLevel().isClientSide) if(!ev.getEntity().level().isClientSide)
ev.getEntity().getLevel().playSound(null, ev.getEntity().getX(), ev.getEntity().getY(), ev.getEntity().getZ(), SoundEvents.ITEM_BREAK, SoundSource.MASTER, 1.0f, 1.0f); ev.getEntity().level().playSound(null, ev.getEntity().getX(), ev.getEntity().getY(), ev.getEntity().getZ(), SoundEvents.ITEM_BREAK, SoundSource.MASTER, 1.0f, 1.0f);
} }
} }
} }
@ -297,7 +291,11 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onLogIn(PlayerEvent.PlayerLoggedInEvent ev) { public void onLogIn(PlayerEvent.PlayerLoggedInEvent ev) {
if(!ev.getEntity().getLevel().isClientSide && ev.getEntity() instanceof ServerPlayer) { if (!CommonConfig.joinMessage) {
return;
}
if(!ev.getEntity().level().isClientSide && ev.getEntity() instanceof ServerPlayer) {
IWDDCapability cap = ev.getEntity().getCapability(WDDCapability.Provider.cap, null).orElseThrow(RuntimeException::new); IWDDCapability cap = ev.getEntity().getCapability(WDDCapability.Provider.cap, null).orElseThrow(RuntimeException::new);
if(cap.isFirstRun()) { if(cap.isFirstRun()) {
@ -320,7 +318,7 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onLogOut(PlayerEvent.PlayerLoggedOutEvent ev) { public void onLogOut(PlayerEvent.PlayerLoggedOutEvent ev) {
if(!ev.getEntity().getLevel().isClientSide) if(!ev.getEntity().level().isClientSide)
Server.getInstance().getClientManager().revokeClientKey(ev.getEntity().getGameProfile().getId()); Server.getInstance().getClientManager().revokeClientKey(ev.getEntity().getGameProfile().getId());
} }
@ -361,7 +359,7 @@ public class WebDisplays {
if(sb.toString().equals("ironic he could save others from death but not himself")) { if(sb.toString().equals("ironic he could save others from death but not himself")) {
Player ply = ev.getPlayer(); Player ply = ev.getPlayer();
ply.getLevel().playSound(null, ply.getX(), ply.getY(), ply.getZ(), soundIronic, SoundSource.PLAYERS, 1.0f, 1.0f); ply.level().playSound(null, ply.getX(), ply.getY(), ply.getZ(), soundIronic, SoundSource.PLAYERS, 1.0f, 1.0f);
} }
} }
@ -386,11 +384,12 @@ public class WebDisplays {
public static DeferredRegister<SoundEvent> SOUNDS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, "webdisplays"); public static DeferredRegister<SoundEvent> SOUNDS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, "webdisplays");
private static void registerSound(String resName) { private static SoundEvent registerSound(String resName) {
ResourceLocation resLoc = new ResourceLocation("webdisplays", resName); ResourceLocation resLoc = new ResourceLocation("webdisplays", resName);
SoundEvent ret = new SoundEvent(resLoc); SoundEvent ret = SoundEvent.createVariableRangeEvent(resLoc);
SOUNDS.register(resName, () -> ret); SOUNDS.register(resName, () -> ret);
return ret;
} }
private static void registerTrigger(Criterion ... criteria) { private static void registerTrigger(Criterion ... criteria) {

View File

@ -26,14 +26,13 @@ import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.wd.core.DefaultPeripheral; import net.montoyo.wd.core.DefaultPeripheral;
import net.montoyo.wd.entity.TileEntityKeyboard; import net.montoyo.wd.entity.KeyboardBlockEntity;
import net.montoyo.wd.item.ItemLinker; import net.montoyo.wd.item.ItemLinker;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageCloseGui; import net.montoyo.wd.net.client_bound.S2CMessageCloseGui;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class BlockKeyboardLeft extends BlockPeripheral { public class KeyboardBlockLeft extends PeripheralBlock {
public static final EnumProperty<DefaultPeripheral> TYPE = EnumProperty.create("type", DefaultPeripheral.class); public static final EnumProperty<DefaultPeripheral> TYPE = EnumProperty.create("type", DefaultPeripheral.class);
public static final DirectionProperty FACING = DirectionProperty.create("facing", Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST); public static final DirectionProperty FACING = DirectionProperty.create("facing", Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST);
// public static final DirectionProperty HALF = DirectionProperty.create("facing", Direction.EAST, Direction.WEST); // public static final DirectionProperty HALF = DirectionProperty.create("facing", Direction.EAST, Direction.WEST);
@ -47,25 +46,25 @@ public class BlockKeyboardLeft extends BlockPeripheral {
private static final Property<?>[] properties = new Property<?>[] {TYPE, FACING}; private static final Property<?>[] properties = new Property<?>[] {TYPE, FACING};
public BlockKeyboardLeft() { public KeyboardBlockLeft() {
super(DefaultPeripheral.KEYBOARD); super(DefaultPeripheral.KEYBOARD);
} }
// TODO: make non static (for extensibility purposes) // TODO: make non static (for extensibility purposes)
public static TileEntityKeyboard getTileEntity(BlockState state, Level world, BlockPos pos) { public static KeyboardBlockEntity getTileEntity(BlockState state, Level world, BlockPos pos) {
if (state.getBlock() instanceof BlockKeyboardLeft) { if (state.getBlock() instanceof KeyboardBlockLeft) {
BlockEntity te = world.getBlockEntity(pos); // TODO: check? BlockEntity te = world.getBlockEntity(pos); // TODO: check?
if (te instanceof TileEntityKeyboard) if (te instanceof KeyboardBlockEntity)
return (TileEntityKeyboard) te; return (KeyboardBlockEntity) te;
} }
BlockPos relative = pos.relative(BlockKeyboardLeft.mapDirection(state.getValue(FACING).getOpposite())); BlockPos relative = pos.relative(KeyboardBlockLeft.mapDirection(state.getValue(FACING).getOpposite()));
BlockState ns = world.getBlockState(relative); BlockState ns = world.getBlockState(relative);
if (ns.getBlock() instanceof BlockPeripheral) { if (ns.getBlock() instanceof PeripheralBlock) {
BlockEntity te = world.getBlockEntity(relative); // TODO: check? BlockEntity te = world.getBlockEntity(relative); // TODO: check?
if (te instanceof TileEntityKeyboard) if (te instanceof KeyboardBlockEntity)
return (TileEntityKeyboard) te; return (KeyboardBlockEntity) te;
} }
return null; return null;
@ -90,7 +89,7 @@ public class BlockKeyboardLeft extends BlockPeripheral {
public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) {
double rpos = (entity.getY() - ((double) pos.getY())) * 16.0; double rpos = (entity.getY() - ((double) pos.getY())) * 16.0;
if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) { if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) {
TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, world, pos); KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, world, pos);
if (tek != null) if (tek != null)
tek.simulateCat(entity); tek.simulateCat(entity);
@ -102,7 +101,7 @@ public class BlockKeyboardLeft extends BlockPeripheral {
if (player.getItemInHand(hand).getItem() instanceof ItemLinker) if (player.getItemInHand(hand).getItem() instanceof ItemLinker)
return InteractionResult.PASS; return InteractionResult.PASS;
TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, level, pos); KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, level, pos);
if (tek != null) if (tek != null)
return tek.onRightClick(player, hand); return tek.onRightClick(player, hand);
@ -120,10 +119,10 @@ public class BlockKeyboardLeft extends BlockPeripheral {
} }
private static void removeRightPiece(BlockState state, Level world, BlockPos pos) { private static void removeRightPiece(BlockState state, Level world, BlockPos pos) {
BlockPos relative = pos.relative(BlockKeyboardLeft.mapDirection(state.getValue(FACING))); BlockPos relative = pos.relative(KeyboardBlockLeft.mapDirection(state.getValue(FACING)));
BlockState ns = world.getBlockState(relative); BlockState ns = world.getBlockState(relative);
if (ns.getBlock() instanceof BlockKeyboardRight) if (ns.getBlock() instanceof KeyboardBlockRight)
world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3); world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3);
} }

View File

@ -17,39 +17,37 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.DirectionProperty; import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.wd.core.IPeripheral; import net.montoyo.wd.core.IPeripheral;
import net.montoyo.wd.entity.TileEntityKeyboard; import net.montoyo.wd.entity.KeyboardBlockEntity;
import net.montoyo.wd.item.ItemLinker; import net.montoyo.wd.item.ItemLinker;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageCloseGui; import net.montoyo.wd.net.client_bound.S2CMessageCloseGui;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.montoyo.wd.block.BlockKeyboardLeft.KEYBOARD_AABBS; import static net.montoyo.wd.block.KeyboardBlockLeft.KEYBOARD_AABBS;
import static net.montoyo.wd.block.BlockPeripheral.point; import static net.montoyo.wd.block.PeripheralBlock.point;
// TODO: merge into KeyboardLeft // TODO: merge into KeyboardLeft
public class BlockKeyboardRight extends Block implements IPeripheral { public class KeyboardBlockRight extends Block implements IPeripheral {
public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING;
public BlockKeyboardRight() { public KeyboardBlockRight() {
super(Properties.of(Material.STONE) super(Properties.copy(Blocks.STONE)
.strength(1.5f, 10.f)); .strength(1.5f, 10.f));
} }
private static void removeLeftPiece(BlockState state, Level world, BlockPos pos) { private static void removeLeftPiece(BlockState state, Level world, BlockPos pos) {
BlockPos relative = pos.relative(BlockKeyboardLeft.mapDirection(state.getValue(FACING).getOpposite())); BlockPos relative = pos.relative(KeyboardBlockLeft.mapDirection(state.getValue(FACING).getOpposite()));
BlockState ns = world.getBlockState(relative); BlockState ns = world.getBlockState(relative);
if (ns.getBlock() instanceof BlockKeyboardLeft) if (ns.getBlock() instanceof KeyboardBlockLeft)
world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3); world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3);
} }
@ -84,7 +82,7 @@ public class BlockKeyboardRight extends Block implements IPeripheral {
@Override @Override
public boolean connect(Level world, BlockPos pos, BlockState state, Vector3i scrPos, BlockSide scrSide) { public boolean connect(Level world, BlockPos pos, BlockState state, Vector3i scrPos, BlockSide scrSide) {
TileEntityKeyboard keyboard = BlockKeyboardLeft.getTileEntity(state, world, pos); KeyboardBlockEntity keyboard = KeyboardBlockLeft.getTileEntity(state, world, pos);
return keyboard != null && keyboard.connect(world, pos, state, scrPos, scrSide); return keyboard != null && keyboard.connect(world, pos, state, scrPos, scrSide);
} }
@ -92,7 +90,7 @@ public class BlockKeyboardRight extends Block implements IPeripheral {
public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) {
double rpos = (entity.getY() - ((double) pos.getY())) * 16.0; double rpos = (entity.getY() - ((double) pos.getY())) * 16.0;
if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) { if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) {
TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, world, pos); KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, world, pos);
if (tek != null) if (tek != null)
tek.simulateCat(entity); tek.simulateCat(entity);
@ -104,7 +102,7 @@ public class BlockKeyboardRight extends Block implements IPeripheral {
if (player.getItemInHand(hand).getItem() instanceof ItemLinker) if (player.getItemInHand(hand).getItem() instanceof ItemLinker)
return InteractionResult.PASS; return InteractionResult.PASS;
TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, level, pos); KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, level, pos);
if (tek != null) if (tek != null)
return tek.onRightClick(player, hand); return tek.onRightClick(player, hand);

View File

@ -15,33 +15,33 @@ import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion; import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.PushReaction; import net.minecraft.world.level.material.PushReaction;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.mcef.utilities.Log;
import net.montoyo.wd.core.DefaultPeripheral; import net.montoyo.wd.core.DefaultPeripheral;
import net.montoyo.wd.entity.TileEntityInterfaceBase; import net.montoyo.wd.entity.AbstractInterfaceBlockEntity;
import net.montoyo.wd.entity.TileEntityPeripheralBase; import net.montoyo.wd.entity.AbstractPeripheralBlockEntity;
import net.montoyo.wd.entity.TileEntityServer; import net.montoyo.wd.entity.ServerBlockEntity;
import net.montoyo.wd.item.ItemLinker; import net.montoyo.wd.item.ItemLinker;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageCloseGui; import net.montoyo.wd.net.client_bound.S2CMessageCloseGui;
import net.montoyo.wd.utilities.Log;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class BlockPeripheral extends WDBlockContainer { public class PeripheralBlock extends WDContainerBlock {
DefaultPeripheral type; DefaultPeripheral type;
public BlockPeripheral(DefaultPeripheral type) { public PeripheralBlock(DefaultPeripheral type) {
super(BlockBehaviour.Properties.of(Material.STONE).strength(1.5f, 10.f)); super(BlockBehaviour.Properties.copy(Blocks.STONE).strength(1.5f, 10.f));
this.type = type; this.type = type;
} }
@ -49,12 +49,12 @@ public class BlockPeripheral extends WDBlockContainer {
@Override @Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
BlockEntityType.BlockEntitySupplier<? extends BlockEntity> cls = type.getTEClass(); BlockEntityType.BlockEntitySupplier<? extends BlockEntity> cls = type.getTEClass();
if(cls == null) if (cls == null)
return null; return null;
try { try {
return cls.create(pos, state); return cls.create(pos, state);
} catch(Throwable t) { } catch (Throwable t) {
Log.errorEx("Couldn't instantiate peripheral TileEntity:", t); Log.errorEx("Couldn't instantiate peripheral TileEntity:", t);
} }
@ -68,18 +68,18 @@ public class BlockPeripheral extends WDBlockContainer {
@Override @Override
public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
if(player.isShiftKeyDown()) if (player.isShiftKeyDown())
return InteractionResult.FAIL; return InteractionResult.FAIL;
if(player.getItemInHand(hand).getItem() instanceof ItemLinker) if (player.getItemInHand(hand).getItem() instanceof ItemLinker)
return InteractionResult.FAIL; return InteractionResult.FAIL;
BlockEntity te = world.getBlockEntity(pos); BlockEntity te = world.getBlockEntity(pos);
if(te instanceof TileEntityPeripheralBase) if (te instanceof AbstractPeripheralBlockEntity)
return ((TileEntityPeripheralBase) te).onRightClick(player, hand); return ((AbstractPeripheralBlockEntity) te).onRightClick(player, hand);
else if(te instanceof TileEntityServer) { else if (te instanceof ServerBlockEntity) {
((TileEntityServer) te).onPlayerRightClick(player); ((ServerBlockEntity) te).onPlayerRightClick(player);
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} else } else
return InteractionResult.FAIL; return InteractionResult.FAIL;
@ -92,16 +92,16 @@ public class BlockPeripheral extends WDBlockContainer {
@Override @Override
public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) {
if(world.isClientSide) if (world.isClientSide)
return; return;
if(placer instanceof Player) { if (placer instanceof Player) {
BlockEntity te = world.getBlockEntity(pos); BlockEntity te = world.getBlockEntity(pos);
if(te instanceof TileEntityServer) if (te instanceof ServerBlockEntity)
((TileEntityServer) te).setOwner((Player) placer); ((ServerBlockEntity) te).setOwner((Player) placer);
else if(te instanceof TileEntityInterfaceBase) else if (te instanceof AbstractInterfaceBlockEntity)
((TileEntityInterfaceBase) te).setOwner((Player) placer); ((AbstractInterfaceBlockEntity) te).setOwner((Player) placer);
} }
} }
@ -113,13 +113,13 @@ public class BlockPeripheral extends WDBlockContainer {
@Override @Override
public void neighborChanged(BlockState state, Level world, BlockPos pos, Block neighborType, BlockPos neighbor, boolean isMoving) { public void neighborChanged(BlockState state, Level world, BlockPos pos, Block neighborType, BlockPos neighbor, boolean isMoving) {
BlockEntity te = world.getBlockEntity(pos); BlockEntity te = world.getBlockEntity(pos);
if(te instanceof TileEntityPeripheralBase) if (te instanceof AbstractPeripheralBlockEntity)
((TileEntityPeripheralBase) te).onNeighborChange(neighborType, neighbor); ((AbstractPeripheralBlockEntity) te).onNeighborChange(neighborType, neighbor);
} }
@Override @Override
public void playerDestroy(Level world, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack tool) { public void playerDestroy(Level world, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack tool) {
if(!world.isClientSide) { if (!world.isClientSide) {
WDNetworkRegistry.INSTANCE.send(PacketDistributor.NEAR.with(() -> point(world, pos)), new S2CMessageCloseGui(pos)); WDNetworkRegistry.INSTANCE.send(PacketDistributor.NEAR.with(() -> point(world, pos)), new S2CMessageCloseGui(pos));
} }
super.playerDestroy(world, player, pos, state, blockEntity, tool); super.playerDestroy(world, player, pos, state, blockEntity, tool);
@ -133,7 +133,7 @@ public class BlockPeripheral extends WDBlockContainer {
public static PacketDistributor.TargetPoint point(Player exclude, Level world, BlockPos bp) { public static PacketDistributor.TargetPoint point(Player exclude, Level world, BlockPos bp) {
return new PacketDistributor.TargetPoint((ServerPlayer) exclude, bp.getX(), bp.getY(), bp.getZ(), 64.0, world.dimension()); return new PacketDistributor.TargetPoint((ServerPlayer) exclude, bp.getX(), bp.getY(), bp.getZ(), 64.0, world.dimension());
} }
public static PacketDistributor.TargetPoint point(Level world, BlockPos bp) { public static PacketDistributor.TargetPoint point(Level world, BlockPos bp) {
return new PacketDistributor.TargetPoint(bp.getX(), bp.getY(), bp.getZ(), 64.0, world.dimension()); return new PacketDistributor.TargetPoint(bp.getX(), bp.getY(), bp.getZ(), 64.0, world.dimension());
} }

View File

@ -13,10 +13,8 @@ import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.RenderShape;
@ -34,64 +32,32 @@ import net.montoyo.wd.core.DefaultUpgrade;
import net.montoyo.wd.core.IUpgrade; import net.montoyo.wd.core.IUpgrade;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.SetURLData; import net.montoyo.wd.data.SetURLData;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.init.BlockInit; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.item.ItemLaserPointer; import net.montoyo.wd.item.ItemLaserPointer;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.math.Vector3f;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.serialization.Util;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class BlockScreen extends BaseEntityBlock { public class ScreenBlock extends BaseEntityBlock {
public static final BooleanProperty hasTE = BooleanProperty.create("haste"); public static final BooleanProperty hasTE = BooleanProperty.create("haste");
public static final BooleanProperty emitting = BooleanProperty.create("emitting"); public static final BooleanProperty emitting = BooleanProperty.create("emitting");
private static final Property<?>[] properties = new Property<?>[]{hasTE, emitting}; private static final Property<?>[] properties = new Property<?>[]{hasTE, emitting};
public BlockScreen(Properties properties) { public ScreenBlock(Properties properties) {
super(properties.strength(1.5f, 10.f)); super(properties.strength(1.5f, 10.f));
this.registerDefaultState(this.defaultBlockState().setValue(hasTE, false).setValue(emitting, false)); this.registerDefaultState(this.defaultBlockState().setValue(hasTE, false).setValue(emitting, false));
} }
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(properties);
}
@Override
public RenderShape getRenderShape(BlockState state) {
return RenderShape.MODEL;
}
public static boolean isntScreenBlock(Level world, Vector3i pos) {
return world.getBlockState(pos.toBlock()).getBlock() != BlockInit.blockScreen.get();
}
@org.jetbrains.annotations.Nullable
@Override
public BlockState getStateForPlacement(BlockPlaceContext context) {
return super.getStateForPlacement(context);
}
@Override
public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor level, BlockPos currentPos, BlockPos neighborPos) {
return super.updateShape(state, direction, neighborState, level, currentPos, neighborPos);
}
public int getMetaFromState(BlockState state) {
int ret = 0;
if (state.getValue(hasTE))
ret |= 1;
if (state.getValue(emitting))
ret |= 2;
return ret;
}
@Override @Override
public void onRemove(BlockState p_60515_, Level p_60516_, BlockPos p_60517_, BlockState p_60518_, boolean p_60519_) { public void onRemove(BlockState p_60515_, Level p_60516_, BlockPos p_60517_, BlockState p_60518_, boolean p_60519_) {
// TODO: make this also get called on client? // TODO: make this also get called on client?
if (p_60518_.getBlock() == p_60515_.getBlock()) return; if (p_60518_.getBlock() == p_60515_.getBlock()) return;
for (BlockSide value : BlockSide.values()) { for (BlockSide value : BlockSide.values()) {
Vector3i vec = new Vector3i(p_60517_.getX(), p_60517_.getY(), p_60517_.getZ()); Vector3i vec = new Vector3i(p_60517_.getX(), p_60517_.getY(), p_60517_.getZ());
Multiblock.findOrigin(p_60516_, vec, value, null); Multiblock.findOrigin(p_60516_, vec, value, null);
@ -118,7 +84,7 @@ public class BlockScreen extends BaseEntityBlock {
return InteractionResult.FAIL; return InteractionResult.FAIL;
else if (heldItem.getItem() instanceof ItemLaserPointer) else if (heldItem.getItem() instanceof ItemLaserPointer)
return InteractionResult.FAIL; // laser pointer already handles stuff return InteractionResult.FAIL; // laser pointer already handles stuff
// handling the off hand leads to double clicking // handling the off hand leads to double clicking
if (!isUpgrade && hand == InteractionHand.OFF_HAND) if (!isUpgrade && hand == InteractionHand.OFF_HAND)
return InteractionResult.FAIL; return InteractionResult.FAIL;
@ -132,13 +98,13 @@ public class BlockScreen extends BaseEntityBlock {
BlockSide side = BlockSide.values()[hit.getDirection().ordinal()]; BlockSide side = BlockSide.values()[hit.getDirection().ordinal()];
Multiblock.findOrigin(world, pos, side, null); Multiblock.findOrigin(world, pos, side, null);
TileEntityScreen te = (TileEntityScreen) world.getBlockEntity(pos.toBlock()); ScreenBlockEntity te = (ScreenBlockEntity) world.getBlockEntity(pos.toBlock());
if (te != null && te.getScreen(side) != null) { if (te != null && te.getScreen(side) != null) {
TileEntityScreen.Screen scr = te.getScreen(side); ScreenData scr = te.getScreen(side);
if (sneaking) { //Right Click if (sneaking) { //Right Click
if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) if ((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0)
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
else else
(new SetURLData(pos, scr.side, scr.url)).sendTo((ServerPlayer) player); (new SetURLData(pos, scr.side, scr.url)).sendTo((ServerPlayer) player);
@ -170,11 +136,11 @@ public class BlockScreen extends BaseEntityBlock {
} }
Vector2i tmp = new Vector2i(); Vector2i tmp = new Vector2i();
float hitX = ((float) hit.getLocation().x) - (float) te.getBlockPos().getX(); float hitX = ((float) hit.getLocation().x) - (float) te.getBlockPos().getX();
float hitY = ((float) hit.getLocation().y) - (float) te.getBlockPos().getY(); float hitY = ((float) hit.getLocation().y) - (float) te.getBlockPos().getY();
float hitZ = ((float) hit.getLocation().z) - (float) te.getBlockPos().getZ(); float hitZ = ((float) hit.getLocation().z) - (float) te.getBlockPos().getZ();
if (hit2pixels(side, hit.getBlockPos(), new Vector3i(hit.getBlockPos()), scr, hitX, hitY, hitZ, tmp)) if (hit2pixels(side, hit.getBlockPos(), new Vector3i(hit.getBlockPos()), scr, hitX, hitY, hitZ, tmp))
te.click(side, tmp); te.click(side, tmp);
return InteractionResult.CONSUME; return InteractionResult.CONSUME;
@ -208,7 +174,7 @@ public class BlockScreen extends BaseEntityBlock {
if (te == null) { if (te == null) {
BlockPos bp = pos.toBlock(); BlockPos bp = pos.toBlock();
world.setBlockAndUpdate(bp, world.getBlockState(bp).setValue(hasTE, true)); world.setBlockAndUpdate(bp, world.getBlockState(bp).setValue(hasTE, true));
te = (TileEntityScreen) world.getBlockEntity(bp); te = (ScreenBlockEntity) world.getBlockEntity(bp);
created = true; created = true;
} }
@ -218,94 +184,79 @@ public class BlockScreen extends BaseEntityBlock {
@Override @Override
public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos source, public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos source,
boolean isMoving){ boolean isMoving) {
if (block != this && !world.isClientSide && !state.getValue(emitting)) { if (block != this && !world.isClientSide && !state.getValue(emitting)) {
for (BlockSide side : BlockSide.values()) { for (BlockSide side : BlockSide.values()) {
Vector3i vec = new Vector3i(pos); Vector3i vec = new Vector3i(pos);
Multiblock.findOrigin(world, vec, side, null); Multiblock.findOrigin(world, vec, side, null);
TileEntityScreen tes = (TileEntityScreen) world.getBlockEntity(vec.toBlock()); ScreenBlockEntity tes = (ScreenBlockEntity) world.getBlockEntity(vec.toBlock());
if (tes != null && tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) { if (tes != null && tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) {
Direction facing = Direction.from2DDataValue(side.reverse().ordinal()); //Opposite face Direction facing = Direction.from2DDataValue(side.reverse().ordinal()); //Opposite face
vec.sub(pos.getX(), pos.getY(), pos.getZ()).neg(); vec.sub(pos.getX(), pos.getY(), pos.getZ()).neg();
tes.updateJSRedstone(side, new Vector2i(vec.dot(side.right), vec.dot(side.up)), world.getSignal(pos, facing)); // tes.updateJSRedstone(side, new Vector2i(vec.dot(side.right), vec.dot(side.up)), world.getSignal(pos, facing));
} }
} }
} }
} }
public static boolean hit2pixels(BlockSide side, BlockPos bpos, Vector3i pos, TileEntityScreen.Screen scr, float hitX, float hitY, float hitZ, Vector2i dst) { public static boolean hit2pixels(BlockSide side, BlockPos bpos, Vector3i pos, ScreenData scr, float hitX, float hitY, float hitZ, Vector2i dst) {
if(side.right.x < 0) if(side.right.x < 0)
hitX -= 1.f; hitX -= 1.f;
if(side.right.z < 0 || side == BlockSide.TOP || side == BlockSide.BOTTOM) if(side.right.z < 0 || side == BlockSide.TOP || side == BlockSide.BOTTOM)
hitZ -= 1.f; hitZ -= 1.f;
Vector3f rel = new Vector3f(bpos.getX(), bpos.getY(), bpos.getZ()); Vector3f rel = new Vector3f(hitX, hitY, hitZ);
rel.sub((float) pos.x, (float) pos.y, (float) pos.z);
rel.add(hitX, hitY, hitZ); // this dot is acting as a "get distance from plane" where the plane is the edge of the screen
float cx = rel.dot(side.right.toFloat()) - 2.f / 16.f; float cx = rel.dot(side.right.toFloat()) - 2.f / 16.f;
float cy = rel.dot(side.up.toFloat()) - 2.f / 16.f; float cy = rel.dot(side.up.toFloat()) - 2.f / 16.f;
float sw = ((float) scr.size.x) - 4.f / 16.f; float sw = ((float) scr.size.x) - 4.f / 16.f;
float sh = ((float) scr.size.y) - 4.f / 16.f; float sh = ((float) scr.size.y) - 4.f / 16.f;
cx /= sw; cx /= sw;
cy /= sh; cy /= sh;
if(cx >= 0.f && cx <= 1.0 && cy >= 0.f && cy <= 1.f) { if (cx >= 0.f && cx <= 1.0 && cy >= 0.f && cy <= 1.f) {
if(side != BlockSide.BOTTOM) if (side != BlockSide.BOTTOM)
cy = 1.f - cy; cy = 1.f - cy;
switch(scr.rotation) { switch (scr.rotation) {
case ROT_90: case ROT_90:
cy = 1.0f - cy; cy = 1.0f - cy;
break; break;
case ROT_180: case ROT_180:
cx = 1.0f - cx; cx = 1.0f - cx;
cy = 1.0f - cy; cy = 1.0f - cy;
break; break;
case ROT_270: case ROT_270:
cx = 1.0f - cx; cx = 1.0f - cx;
break; break;
default:
break;
} }
cx *= (float) scr.resolution.x; cx *= (float) scr.resolution.x;
cy *= (float) scr.resolution.y; cy *= (float) scr.resolution.y;
if(scr.rotation.isVertical) { if (scr.rotation.isVertical) {
dst.x = (int) cy; dst.x = (int) cy;
dst.y = (int) cx; dst.y = (int) cx;
} else { } else {
dst.x = (int) cx; dst.x = (int) cx;
dst.y = (int) cy; dst.y = (int) cy;
} }
return true; return true;
} }
return false; return false;
} }
@org.jetbrains.annotations.Nullable
@Override
public BlockEntity newBlockEntity (BlockPos pos, BlockState state){
int meta = getMetaFromState(state);
if ((meta & 1) == 0)
return null;
return ((meta & 1) == 0) ? null : new TileEntityScreen(pos, state);
}
/************************************************* DESTRUCTION HANDLING *************************************************/ /************************************************* DESTRUCTION HANDLING *************************************************/
private void onDestroy (Level world, BlockPos pos, Player ply){ private void onDestroy(Level world, BlockPos pos, Player ply) {
if (!world.isClientSide) { if (!world.isClientSide) {
Vector3i bp = new Vector3i(pos); Vector3i bp = new Vector3i(pos);
Multiblock.BlockOverride override = new Multiblock.BlockOverride(bp, Multiblock.OverrideAction.SIMULATE); Multiblock.BlockOverride override = new Multiblock.BlockOverride(bp, Multiblock.OverrideAction.SIMULATE);
@ -315,28 +266,28 @@ public class BlockScreen extends BaseEntityBlock {
} }
} }
private void destroySide (Level world, Vector3i pos, BlockSide side, Multiblock.BlockOverride override, Player private void destroySide(Level world, Vector3i pos, BlockSide side, Multiblock.BlockOverride override, Player
source){ source) {
Multiblock.findOrigin(world, pos, side, override); Multiblock.findOrigin(world, pos, side, override);
BlockPos bp = pos.toBlock(); BlockPos bp = pos.toBlock();
BlockEntity te = world.getBlockEntity(bp); BlockEntity te = world.getBlockEntity(bp);
if (te instanceof TileEntityScreen) { if (te instanceof ScreenBlockEntity) {
((TileEntityScreen) te).onDestroy(source); ((ScreenBlockEntity) te).onDestroy(source);
world.setBlock(bp, world.getBlockState(bp).setValue(hasTE, false), Block.UPDATE_ALL_IMMEDIATE); //Destroy tile entity. world.setBlock(bp, world.getBlockState(bp).setValue(hasTE, false), Block.UPDATE_ALL_IMMEDIATE); //Destroy tile entity.
} }
} }
@Override @Override
public boolean onDestroyedByPlayer (BlockState state, Level level, BlockPos pos, Player player, public boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player,
boolean willHarvest, FluidState fluid){ boolean willHarvest, FluidState fluid) {
onDestroy(level, pos, player); onDestroy(level, pos, player);
return super.onDestroyedByPlayer(state, level, pos, player, willHarvest, fluid); return super.onDestroyedByPlayer(state, level, pos, player, willHarvest, fluid);
} }
@Override @Override
public void setPlacedBy (Level world, @NotNull BlockPos pos, @NotNull BlockState public void setPlacedBy(Level world, @NotNull BlockPos pos, @NotNull BlockState
state, @org.jetbrains.annotations.Nullable LivingEntity whoDidThisShit, @NotNull ItemStack stack){ state, @org.jetbrains.annotations.Nullable LivingEntity whoDidThisShit, @NotNull ItemStack stack) {
if (world.isClientSide) if (world.isClientSide)
return; return;
@ -351,25 +302,42 @@ public class BlockScreen extends BaseEntityBlock {
neighbors[5] = new Vector3i(pos.getX(), pos.getY(), pos.getZ() - 1); neighbors[5] = new Vector3i(pos.getX(), pos.getY(), pos.getZ() - 1);
for (Vector3i neighbor : neighbors) { for (Vector3i neighbor : neighbors) {
if (world.getBlockState(neighbor.toBlock()).getBlock() instanceof BlockScreen) { if (world.getBlockState(neighbor.toBlock()).getBlock() instanceof ScreenBlock) {
for (BlockSide bs : BlockSide.values()) for (BlockSide bs : BlockSide.values())
destroySide(world, neighbor.clone(), bs, override, (whoDidThisShit instanceof Player) ? ((Player) whoDidThisShit) : null); destroySide(world, neighbor.clone(), bs, override, (whoDidThisShit instanceof Player) ? ((Player) whoDidThisShit) : null);
} }
} }
} }
/************************************************* STUFF THAT'S UNLIKELY TO BE TOUCHED BUT NEEDS TO BE HERE *************************************************/
@Override @Override
public @NotNull PushReaction getPistonPushReaction (BlockState state){ public @NotNull PushReaction getPistonPushReaction(BlockState state) {
return PushReaction.IGNORE; return PushReaction.IGNORE;
} }
@Override @Override
public int getSignal (BlockState state, BlockGetter level, BlockPos pos, Direction direction){ public int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
return state.getValue(emitting) ? 15 : 0; return state.getValue(emitting) ? 15 : 0;
} }
@Override @Override
public boolean isSignalSource (BlockState state){ public boolean isSignalSource(BlockState state) {
return state.getValue(emitting); return state.getValue(emitting);
} }
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return state.getValue(hasTE) ? new ScreenBlockEntity(pos, state) : null;
}
@Override
public RenderShape getRenderShape(BlockState state) {
return RenderShape.MODEL;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(properties);
}
} }

View File

@ -7,11 +7,11 @@ package net.montoyo.wd.block;
import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.BlockItem;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.BaseEntityBlock;
public abstract class WDBlockContainer extends BaseEntityBlock { public abstract class WDContainerBlock extends BaseEntityBlock {
protected static BlockItem itemBlock; protected static BlockItem itemBlock;
public WDBlockContainer(Properties arg) { public WDContainerBlock(Properties arg) {
super(arg); super(arg);
} }

View File

@ -7,48 +7,48 @@ import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.block.BlockKeyboardLeft; import net.montoyo.wd.block.KeyboardBlockLeft;
import net.montoyo.wd.init.BlockInit; import net.montoyo.wd.registry.BlockRegistry;
public class KeyboardItem extends BlockItem { public class KeyboardItem extends BlockItem {
public KeyboardItem(Block arg, Properties arg2) { public KeyboardItem(Block arg, Properties arg2) {
super(arg, arg2); super(arg, arg2);
} }
@Override @Override
protected boolean placeBlock(BlockPlaceContext arg, BlockState arg2) { protected boolean placeBlock(BlockPlaceContext arg, BlockState arg2) {
Direction facing = arg.getHorizontalDirection(); Direction facing = arg.getHorizontalDirection();
arg2 = arg2.setValue(BlockKeyboardLeft.FACING, facing); arg2 = arg2.setValue(KeyboardBlockLeft.FACING, facing);
Direction d = BlockKeyboardLeft.mapDirection(facing); Direction d = KeyboardBlockLeft.mapDirection(facing);
if (isValid(arg.getClickedPos(), arg.getLevel(), arg2, d)) { if (isValid(arg.getClickedPos(), arg.getLevel(), arg2, d)) {
Block kbRight = BlockInit.blockKbRight.get(); Block kbRight = BlockRegistry.blockKbRight.get();
BlockState rightState = kbRight.defaultBlockState(); BlockState rightState = kbRight.defaultBlockState();
rightState = rightState.setValue(BlockKeyboardLeft.FACING, facing); rightState = rightState.setValue(KeyboardBlockLeft.FACING, facing);
if (!arg.getLevel().setBlock( if (!arg.getLevel().setBlock(
arg.getClickedPos().relative(d), arg.getClickedPos().relative(d),
rightState, rightState,
11 11
)) return false; )) return false;
return arg.getLevel().setBlock(arg.getClickedPos(), arg2, 11);// 161 return arg.getLevel().setBlock(arg.getClickedPos(), arg2, 11);// 161
} else if (isValid(arg.getClickedPos().relative(d.getOpposite(), 2), arg.getLevel(), arg2, d)) { } else if (isValid(arg.getClickedPos().relative(d.getOpposite(), 2), arg.getLevel(), arg2, d)) {
Block kbRight = BlockInit.blockKbRight.get(); Block kbRight = BlockRegistry.blockKbRight.get();
BlockState rightState = kbRight.defaultBlockState(); BlockState rightState = kbRight.defaultBlockState();
rightState = rightState.setValue(BlockKeyboardLeft.FACING, facing); rightState = rightState.setValue(KeyboardBlockLeft.FACING, facing);
if (!arg.getLevel().setBlock( if (!arg.getLevel().setBlock(
arg.getClickedPos(), arg.getClickedPos(),
rightState, rightState,
11 11
)) return false; )) return false;
return arg.getLevel().setBlock(arg.getClickedPos().relative(d.getOpposite()), arg2, 11);// 161 return arg.getLevel().setBlock(arg.getClickedPos().relative(d.getOpposite()), arg2, 11);// 161
} }
return false; return false;
} }
private boolean isValid(BlockPos pos, Level level, BlockState state, Direction d) { private boolean isValid(BlockPos pos, Level level, BlockState state, Direction d) {
return level.getBlockState(pos.relative(d)).isAir(); return level.getBlockState(pos.relative(d)).isAir();
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,372 +1,370 @@
/* ///*
* Copyright (C) 2018 BARBOTIN Nicolas // * Copyright (C) 2018 BARBOTIN Nicolas
*/ // */
//
package net.montoyo.wd.client; //package net.montoyo.wd.client;
//
import net.minecraft.client.Minecraft; //import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos; //import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; //import net.minecraft.core.Direction;
import net.minecraft.world.item.ItemStack; //import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist; //import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; //import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.mcef.api.IBrowser; //import net.montoyo.wd.block.BlockScreen;
import net.montoyo.mcef.api.IJSQueryCallback; //import net.montoyo.wd.core.DefaultUpgrade;
import net.montoyo.wd.block.BlockScreen; //import net.montoyo.wd.core.IScreenQueryHandler;
import net.montoyo.wd.core.DefaultUpgrade; //import net.montoyo.wd.core.IUpgrade;
import net.montoyo.wd.core.IScreenQueryHandler; //import net.montoyo.wd.core.JSServerRequest;
import net.montoyo.wd.core.IUpgrade; //import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.core.JSServerRequest; //import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.entity.TileEntityScreen; //import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.net.WDNetworkRegistry; //import net.montoyo.wd.utilities.*;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; //
import net.montoyo.wd.utilities.*; //import java.util.*;
//
import java.util.*; //@OnlyIn(Dist.CLIENT)
//public final class JSQueryDispatcher {
@OnlyIn(Dist.CLIENT) //
public final class JSQueryDispatcher { // private static final class QueryData {
//
private static final class QueryData { // private final IBrowser browser;
// private final String query;
private final IBrowser browser; // private final String args;
private final String query; // private final IJSQueryCallback callback;
private final String args; //
private final IJSQueryCallback callback; // private QueryData(IBrowser b, String q, String a, IJSQueryCallback cb) {
// browser = b;
private QueryData(IBrowser b, String q, String a, IJSQueryCallback cb) { // query = q;
browser = b; // args = a;
query = q; // callback = cb;
args = a; // }
callback = cb; //
} // }
//
} // public static final class ServerQuery {
//
public static final class ServerQuery { // private static int lastId = 0;
//
private static int lastId = 0; // private final TileEntityScreen tes;
// private final BlockSide side;
private final TileEntityScreen tes; // private final IJSQueryCallback callback;
private final BlockSide side; // private final int id;
private final IJSQueryCallback callback; //
private final int id; // private ServerQuery(TileEntityScreen t, BlockSide s, IJSQueryCallback cb) {
// tes = t;
private ServerQuery(TileEntityScreen t, BlockSide s, IJSQueryCallback cb) { // side = s;
tes = t; // callback = cb;
side = s; // id = lastId++;
callback = cb; // }
id = lastId++; //
} // public TileEntityScreen getTileEntity() {
// return tes;
public TileEntityScreen getTileEntity() { // }
return tes; //
} // public BlockSide getSide() {
// return side;
public BlockSide getSide() { // }
return side; //
} // public TileEntityScreen.Screen getScreen() {
// return tes.getScreen(side);
public TileEntityScreen.Screen getScreen() { // }
return tes.getScreen(side); //
} // public void success(String resp) {
// callback.success(resp);
public void success(String resp) { // }
callback.success(resp); //
} // public void error(int errId, String errStr) {
// callback.failure(errId, errStr);
public void error(int errId, String errStr) { // }
callback.failure(errId, errStr); //
} // }
//
} // private final ClientProxy proxy;
// private final ArrayDeque<QueryData> queue = new ArrayDeque<>();
private final ClientProxy proxy; // private final ClientProxy.ScreenSidePair lookupResult = new ClientProxy.ScreenSidePair();
private final ArrayDeque<QueryData> queue = new ArrayDeque<>(); // private final HashMap<String, IScreenQueryHandler> handlers = new HashMap<>();
private final ClientProxy.ScreenSidePair lookupResult = new ClientProxy.ScreenSidePair(); // private final ArrayList<ServerQuery> serverQueries = new ArrayList<>();
private final HashMap<String, IScreenQueryHandler> handlers = new HashMap<>(); // private final Minecraft mc = Minecraft.getInstance();
private final ArrayList<ServerQuery> serverQueries = new ArrayList<>(); //
private final Minecraft mc = Minecraft.getInstance(); // public JSQueryDispatcher(ClientProxy proxy) {
// this.proxy = proxy;
public JSQueryDispatcher(ClientProxy proxy) { // registerDefaults();
this.proxy = proxy; // }
registerDefaults(); //
} // public void enqueueQuery(IBrowser b, String q, String a, IJSQueryCallback cb) {
// synchronized(queue) {
public void enqueueQuery(IBrowser b, String q, String a, IJSQueryCallback cb) { // queue.offer(new QueryData(b, q, a, cb));
synchronized(queue) { // }
queue.offer(new QueryData(b, q, a, cb)); // }
} //
} // public void handleQueries() {
// while(true) {
public void handleQueries() { // QueryData next;
while(true) { // synchronized(queue) {
QueryData next; // next = queue.poll();
synchronized(queue) { // }
next = queue.poll(); //
} // if(next == null)
// break;
if(next == null) //
break; // if(proxy.findScreenFromBrowser(next.browser, lookupResult)) {
// Object[] args = (next.args == null) ? new Object[0] : parseArgs(next.args);
if(proxy.findScreenFromBrowser(next.browser, lookupResult)) { //
Object[] args = (next.args == null) ? new Object[0] : parseArgs(next.args); // if(args == null)
// next.callback.failure(400, "Malformed request parameters");
if(args == null) // else {
next.callback.failure(400, "Malformed request parameters"); // try {
else { // handlers.get(next.query).handleQuery(next.callback, lookupResult.tes, lookupResult.side, args);
try { // } catch(Throwable t) {
handlers.get(next.query).handleQuery(next.callback, lookupResult.tes, lookupResult.side, args); // Log.warningEx("Could not execute JS query %s(%s)", t, next.query, (next.args == null) ? "" : next.args);
} catch(Throwable t) { // next.callback.failure(500, "Internal error");
Log.warningEx("Could not execute JS query %s(%s)", t, next.query, (next.args == null) ? "" : next.args); // }
next.callback.failure(500, "Internal error"); // }
} // } else
} // next.callback.failure(403, "A screen is required");
} else // }
next.callback.failure(403, "A screen is required"); // }
} //
} // public boolean canHandleQuery(String q) {
// return handlers.containsKey(q);
public boolean canHandleQuery(String q) { // }
return handlers.containsKey(q); //
} // private static Object[] parseArgs(String args) {
// ArrayList<String> array = new ArrayList<>();
private static Object[] parseArgs(String args) { // int lastIdx = 0;
ArrayList<String> array = new ArrayList<>(); // boolean inString = false;
int lastIdx = 0; // boolean escape = false;
boolean inString = false; // boolean hadString = false;
boolean escape = false; //
boolean hadString = false; // for(int i = 0; i < args.length(); i++) {
// char chr = args.charAt(i);
for(int i = 0; i < args.length(); i++) { //
char chr = args.charAt(i); // if(inString) {
// if(escape)
if(inString) { // escape = false;
if(escape) // else {
escape = false; // if(chr == '\"')
else { // inString = false;
if(chr == '\"') // else if(chr == '\\')
inString = false; // escape = true;
else if(chr == '\\') // }
escape = true; // } else if(chr == '\"') {
} // if(hadString)
} else if(chr == '\"') { // return null;
if(hadString) //
return null; // inString = true;
// hadString = true;
inString = true; // } else if(chr == ',') {
hadString = true; // array.add(args.substring(lastIdx, i).trim());
} else if(chr == ',') { // lastIdx = i + 1;
array.add(args.substring(lastIdx, i).trim()); // hadString = false;
lastIdx = i + 1; // }
hadString = false; // }
} //
} // if(inString)
// return null; //Non terminated string
if(inString) //
return null; //Non terminated string // array.add(args.substring(lastIdx).trim());
// Object[] ret = new Object[array.size()];
array.add(args.substring(lastIdx).trim()); //
Object[] ret = new Object[array.size()]; // for(int i = 0; i < ret.length; i++) {
// String str = array.get(i);
for(int i = 0; i < ret.length; i++) { // if(str.isEmpty())
String str = array.get(i); // return null; //Nah...
if(str.isEmpty()) //
return null; //Nah... // if(str.charAt(0) == '\"') //String
// ret[i] = str.substring(1, str.length() - 1);
if(str.charAt(0) == '\"') //String // else {
ret[i] = str.substring(1, str.length() - 1); // try {
else { // ret[i] = Double.parseDouble(str);
try { // } catch(NumberFormatException ex) {
ret[i] = Double.parseDouble(str); // return null;
} catch(NumberFormatException ex) { // }
return null; // }
} // }
} //
} // return ret;
// }
return ret; //
} // public void register(String query, IScreenQueryHandler handler) {
// handlers.put(query.toLowerCase(), handler);
public void register(String query, IScreenQueryHandler handler) { // }
handlers.put(query.toLowerCase(), handler); //
} // public ServerQuery fulfillQuery(int id) {
// int toRemove = -1;
public ServerQuery fulfillQuery(int id) { //
int toRemove = -1; // for(int i = 0; i < serverQueries.size(); i++) {
// ServerQuery sq = serverQueries.get(i);
for(int i = 0; i < serverQueries.size(); i++) { //
ServerQuery sq = serverQueries.get(i); // if(sq.id == id) {
// toRemove = i;
if(sq.id == id) { // break;
toRemove = i; // }
break; // }
} //
} // if(toRemove < 0)
// return null;
if(toRemove < 0) // else
return null; // return serverQueries.remove(toRemove);
else // }
return serverQueries.remove(toRemove); //
} // private void makeServerQuery(TileEntityScreen tes, BlockSide side, IJSQueryCallback cb, JSServerRequest type, Object ... data) {
// ServerQuery ret = new ServerQuery(tes, side, cb);
private void makeServerQuery(TileEntityScreen tes, BlockSide side, IJSQueryCallback cb, JSServerRequest type, Object ... data) { // serverQueries.add(ret);
ServerQuery ret = new ServerQuery(tes, side, cb); //
serverQueries.add(ret); // WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.jsRequest(tes, side, ret.id, type, data));
// }
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.jsRequest(tes, side, ret.id, type, data)); //
} // private void registerDefaults() {
// VideoType.registerQueries(this);
private void registerDefaults() { //
VideoType.registerQueries(this); // register("GetSize", (cb, tes, side, args) -> {
// Vector2i size = tes.getScreen(side).size;
register("GetSize", (cb, tes, side, args) -> { // cb.success("{\"x\":" + size.x + ",\"y\":" + size.y + "}");
Vector2i size = tes.getScreen(side).size; // });
cb.success("{\"x\":" + size.x + ",\"y\":" + size.y + "}"); //
}); // register("GetRedstoneAt", (cb, tes, side, args) -> {
// if(!tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) {
register("GetRedstoneAt", (cb, tes, side, args) -> { // cb.failure(403, "Missing upgrade");
if(!tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) { // return;
cb.failure(403, "Missing upgrade"); // }
return; //
} // if(args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) {
// TileEntityScreen.Screen scr = tes.getScreen(side);
if(args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) { // int x = ((Double) args[0]).intValue();
TileEntityScreen.Screen scr = tes.getScreen(side); // int y = ((Double) args[1]).intValue();
int x = ((Double) args[0]).intValue(); //
int y = ((Double) args[1]).intValue(); // if(x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y)
// cb.failure(403, "Out of range");
if(x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y) // else {
cb.failure(403, "Out of range"); // BlockPos bpos = (new Vector3i(tes.getBlockPos())).addMul(side.right, x).addMul(side.up, y).toBlock();
else { // int level = tes.getLevel().getBlockState(bpos).getValue(BlockScreen.emitting) ? 0 : tes.getLevel().getSignal(bpos, Direction.values()[side.reverse().ordinal()]);
BlockPos bpos = (new Vector3i(tes.getBlockPos())).addMul(side.right, x).addMul(side.up, y).toBlock(); // cb.success("{\"level\":" + level + "}");
int level = tes.getLevel().getBlockState(bpos).getValue(BlockScreen.emitting) ? 0 : tes.getLevel().getSignal(bpos, Direction.values()[side.reverse().ordinal()]); // }
cb.success("{\"level\":" + level + "}"); // } else
} // cb.failure(400, "Wrong arguments");
} else // });
cb.failure(400, "Wrong arguments"); //
}); // register("GetRedstoneArray", (cb, tes, side, args) -> {
// if(tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) {
register("GetRedstoneArray", (cb, tes, side, args) -> { // final Direction facing = Direction.values()[side.reverse().ordinal()];
if(tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) { // final StringJoiner resp = new StringJoiner(",", "{\"levels\":[", "]}");
final Direction facing = Direction.values()[side.reverse().ordinal()]; //
final StringJoiner resp = new StringJoiner(",", "{\"levels\":[", "]}"); // tes.forEachScreenBlocks(side, bp -> {
// if(tes.getLevel().getBlockState(bp).getValue(BlockScreen.emitting))
tes.forEachScreenBlocks(side, bp -> { // resp.add("0");
if(tes.getLevel().getBlockState(bp).getValue(BlockScreen.emitting)) // else
resp.add("0"); // resp.add("" + tes.getLevel().getSignal(bp, facing));
else // });
resp.add("" + tes.getLevel().getSignal(bp, facing)); //
}); // cb.success(resp.toString());
// } else
cb.success(resp.toString()); // cb.failure(403, "Missing upgrade");
} else // });
cb.failure(403, "Missing upgrade"); //
}); // register("ClearRedstone", (cb, tes, side, args) -> {
// if(tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) {
register("ClearRedstone", (cb, tes, side, args) -> { // if(tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId()))
if(tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) { // makeServerQuery(tes, side, cb, JSServerRequest.CLEAR_REDSTONE);
if(tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())) // else
makeServerQuery(tes, side, cb, JSServerRequest.CLEAR_REDSTONE); // cb.success("{\"status\":\"notOwner\"}");
else // } else
cb.success("{\"status\":\"notOwner\"}"); // cb.failure(403, "Missing upgrade");
} else // });
cb.failure(403, "Missing upgrade"); //
}); // register("SetRedstoneAt", (cb, tes, side, args) -> {
// if(args.length != 3 || !Arrays.stream(args).allMatch((obj) -> obj instanceof Double)) {
register("SetRedstoneAt", (cb, tes, side, args) -> { // cb.failure(400, "Wrong arguments");
if(args.length != 3 || !Arrays.stream(args).allMatch((obj) -> obj instanceof Double)) { // return;
cb.failure(400, "Wrong arguments"); // }
return; //
} // if(!tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) {
// cb.failure(403, "Missing upgrade");
if(!tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) { // return;
cb.failure(403, "Missing upgrade"); // }
return; //
} // if(!tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())) {
// cb.success("{\"status\":\"notOwner\"}");
if(!tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())) { // return;
cb.success("{\"status\":\"notOwner\"}"); // }
return; //
} // int x = ((Double) args[0]).intValue();
// int y = ((Double) args[1]).intValue();
int x = ((Double) args[0]).intValue(); // boolean state = ((Double) args[2]) > 0.0;
int y = ((Double) args[1]).intValue(); //
boolean state = ((Double) args[2]) > 0.0; // Vector2i size = tes.getScreen(side).size;
// if(x < 0 || x >= size.x || y < 0 || y >= size.y) {
Vector2i size = tes.getScreen(side).size; // cb.failure(403, "Out of range");
if(x < 0 || x >= size.x || y < 0 || y >= size.y) { // return;
cb.failure(403, "Out of range"); // }
return; //
} // makeServerQuery(tes, side, cb, JSServerRequest.SET_REDSTONE_AT, x, y, state);
// });
makeServerQuery(tes, side, cb, JSServerRequest.SET_REDSTONE_AT, x, y, state); //
}); // register("IsEmitting", (cb, tes, side, args) -> {
// if(!tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) {
register("IsEmitting", (cb, tes, side, args) -> { // cb.failure(403, "Missing upgrade");
if(!tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) { // return;
cb.failure(403, "Missing upgrade"); // }
return; //
} // if(args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) {
// TileEntityScreen.Screen scr = tes.getScreen(side);
if(args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) { // int x = ((Double) args[0]).intValue();
TileEntityScreen.Screen scr = tes.getScreen(side); // int y = ((Double) args[1]).intValue();
int x = ((Double) args[0]).intValue(); //
int y = ((Double) args[1]).intValue(); // if(x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y)
// cb.failure(403, "Out of range");
if(x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y) // else {
cb.failure(403, "Out of range"); // BlockPos bpos = (new Vector3i(tes.getBlockPos())).addMul(side.right, x).addMul(side.up, y).toBlock();
else { // boolean e = tes.getLevel().getBlockState(bpos).getValue(BlockScreen.emitting);
BlockPos bpos = (new Vector3i(tes.getBlockPos())).addMul(side.right, x).addMul(side.up, y).toBlock(); // cb.success("{\"emitting\":" + (e ? "true" : "false") + "}");
boolean e = tes.getLevel().getBlockState(bpos).getValue(BlockScreen.emitting); // }
cb.success("{\"emitting\":" + (e ? "true" : "false") + "}"); // } else
} // cb.failure(400, "Wrong arguments");
} else // });
cb.failure(400, "Wrong arguments"); //
}); // register("GetEmissionArray", (cb, tes, side, args) -> {
// if(tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) {
register("GetEmissionArray", (cb, tes, side, args) -> { // final StringJoiner resp = new StringJoiner(",", "{\"emission\":[", "]}");
if(tes.hasUpgrade(side, DefaultUpgrade.REDOUTPUT)) { // tes.forEachScreenBlocks(side, bp -> resp.add(tes.getLevel().getBlockState(bp).getValue(BlockScreen.emitting) ? "1" : "0"));
final StringJoiner resp = new StringJoiner(",", "{\"emission\":[", "]}"); // cb.success(resp.toString());
tes.forEachScreenBlocks(side, bp -> resp.add(tes.getLevel().getBlockState(bp).getValue(BlockScreen.emitting) ? "1" : "0")); // } else
cb.success(resp.toString()); // cb.failure(403, "Missing upgrade");
} else // });
cb.failure(403, "Missing upgrade"); //
}); // register("GetLocation", (cb, tes, side, args) -> {
// if(!tes.hasUpgrade(side, DefaultUpgrade.GPS)) {
register("GetLocation", (cb, tes, side, args) -> { // cb.failure(403, "Missing upgrade");
if(!tes.hasUpgrade(side, DefaultUpgrade.GPS)) { // return;
cb.failure(403, "Missing upgrade"); // }
return; //
} // BlockPos bp = tes.getBlockPos();
// cb.success("{\"x\":" + bp.getX() + ",\"y\":" + bp.getY() + ",\"z\":" + bp.getZ() + ",\"side\":\"" + side + "\"}");
BlockPos bp = tes.getBlockPos(); // });
cb.success("{\"x\":" + bp.getX() + ",\"y\":" + bp.getY() + ",\"z\":" + bp.getZ() + ",\"side\":\"" + side + "\"}"); //
}); // register("GetUpgrades", (cb, tes, side, args) -> {
// final StringBuilder sb = new StringBuilder("{\"upgrades\":[");
register("GetUpgrades", (cb, tes, side, args) -> { // final ArrayList<ItemStack> upgrades = tes.getScreen(side).upgrades;
final StringBuilder sb = new StringBuilder("{\"upgrades\":["); //
final ArrayList<ItemStack> upgrades = tes.getScreen(side).upgrades; // for(int i = 0; i < upgrades.size(); i++) {
// if(i > 0)
for(int i = 0; i < upgrades.size(); i++) { // sb.append(',');
if(i > 0) //
sb.append(','); // sb.append('\"');
// sb.append(Util.addSlashes(((IUpgrade) upgrades.get(i).getItem()).getJSName(upgrades.get(i))));
sb.append('\"'); // sb.append('\"');
sb.append(Util.addSlashes(((IUpgrade) upgrades.get(i).getItem()).getJSName(upgrades.get(i)))); // }
sb.append('\"'); //
} // cb.success(sb.append("]}").toString());
// });
cb.success(sb.append("]}").toString()); //
}); // register("IsOwner", (cb, tes, side, args) -> {
// boolean res = (tes.getScreen(side).owner != null && tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId()));
register("IsOwner", (cb, tes, side, args) -> { // cb.success("{\"isOwner\":" + (res ? "true}" : "false}"));
boolean res = (tes.getScreen(side).owner != null && tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())); // });
cb.success("{\"isOwner\":" + (res ? "true}" : "false}")); //
}); // register("GetRotation", (cb, tes, side, args) -> cb.success("{\"rotation\":" + tes.getScreen(side).rotation.ordinal() + "}"));
// register("GetSide", (cb, tes, side, args) -> cb.success("{\"side\":" + tes.getScreen(side).side.ordinal() + "}"));
register("GetRotation", (cb, tes, side, args) -> cb.success("{\"rotation\":" + tes.getScreen(side).rotation.ordinal() + "}")); // }
register("GetSide", (cb, tes, side, args) -> cb.success("{\"side\":" + tes.getScreen(side).side.ordinal() + "}")); //
} //}
}

View File

@ -4,103 +4,127 @@
package net.montoyo.wd.client; package net.montoyo.wd.client;
import net.montoyo.mcef.api.IScheme;
import net.montoyo.mcef.api.ISchemeResponseData;
import net.montoyo.mcef.api.ISchemeResponseHeaders;
import net.montoyo.mcef.api.SchemePreResponse;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.miniserv.Constants; import net.montoyo.wd.miniserv.Constants;
import net.montoyo.wd.miniserv.client.Client; import net.montoyo.wd.miniserv.client.Client;
import net.montoyo.wd.miniserv.client.ClientTaskGetFile; import net.montoyo.wd.miniserv.client.ClientTaskGetFile;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
import org.cef.callback.CefCallback;
import org.cef.handler.CefResourceHandler;
import org.cef.misc.IntRef;
import org.cef.misc.StringRef;
import org.cef.network.CefRequest;
import org.cef.network.CefResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID; import java.util.UUID;
public class WDScheme implements IScheme { public class WDScheme implements CefResourceHandler {
private static final String ERROR_PAGE = "<!DOCTYPE html><html><head></head><body><h1>%d %s</h1><hr /><i>Miniserv powered by WebDisplays</i></body></html>"; private static final String ERROR_PAGE = "<!DOCTYPE html><html><head></head><body><h1>%d %s</h1><hr /><i>Miniserv powered by WebDisplays</i></body></html>";
private ClientTaskGetFile task; private ClientTaskGetFile task;
private boolean isErrorPage; private boolean isErrorPage;
String url;
boolean onlyError = false;
public WDScheme(String url) {
this.url = url;
}
@Override @Override
public SchemePreResponse processRequest(String url) { public boolean processRequest(CefRequest cefRequest, CefCallback cefCallback) {
url = url.substring("wd://".length()); url = cefRequest.getURL();
url = url.substring("webdisplays://".length());
int pos = url.indexOf('/'); int pos = url.indexOf('/');
if(pos < 0) if (pos < 0)
return SchemePreResponse.NOT_HANDLED; return false;
String uuidStr = url.substring(0, pos); String uuidStr = url.substring(0, pos);
String fileStr = url.substring(pos + 1); String fileStr = url.substring(pos + 1);
try { fileStr = URLDecoder.decode(fileStr, StandardCharsets.UTF_8);
fileStr = URLDecoder.decode(fileStr, "UTF-8");
} catch(UnsupportedEncodingException ex) {
Log.warningEx("UTF-8 isn't supported... yeah... and I'm a billionaire...", ex);
}
if(uuidStr.isEmpty() || Util.isFileNameInvalid(fileStr)) if (uuidStr.isEmpty() || Util.isFileNameInvalid(fileStr)) {
return SchemePreResponse.NOT_HANDLED; // invalid URL or no UUID
onlyError = true;
cefCallback.Continue();
return true;
}
UUID uuid; UUID uuid;
try { try {
uuid = UUID.fromString(uuidStr); uuid = UUID.fromString(uuidStr);
} catch(IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return SchemePreResponse.NOT_HANDLED; //Invalid UUID // invalid UUID
onlyError = true;
cefCallback.Continue();
return true;
} }
task = new ClientTaskGetFile(uuid, fileStr); task = new ClientTaskGetFile(uuid, fileStr);
return Client.getInstance().addTask(task) ? SchemePreResponse.HANDLED_CONTINUE : SchemePreResponse.NOT_HANDLED; boolean doContinue = Client.getInstance().addTask(task);
if (doContinue) cefCallback.Continue();
return doContinue;
} }
@Override @Override
public void getResponseHeaders(ISchemeResponseHeaders resp) { public void getResponseHeaders(CefResponse cefResponse, IntRef contentLength, StringRef redir) {
Log.info("Waiting for response..."); int status;
int status = task.waitForResponse(); if (onlyError) {
Log.info("Got response %d", status); status = Constants.GETF_STATUS_BAD_NAME;
} else {
Log.info("Waiting for response...");
status = task.waitForResponse();
Log.info("Got response %d", status);
if(status == 0) { if (status == 0) {
//OK //OK
int extPos = task.getFileName().lastIndexOf('.'); int extPos = task.getFileName().lastIndexOf('.');
if(extPos >= 0) { if (extPos >= 0) {
String mime = ((ClientProxy) WebDisplays.PROXY).getMCEF().mimeTypeFromExtension(task.getFileName().substring(extPos + 1)); String mime = mapMime(task.getFileName().substring(extPos + 1));
if(mime != null) if (mime != null)
resp.setMimeType(mime); cefResponse.setMimeType(mime);
}
cefResponse.setStatus(200);
cefResponse.setStatusText("OK");
contentLength.set(0);
return;
} }
resp.setStatus(200);
resp.setStatusText("OK");
resp.setResponseLength(-1);
return;
} }
int errCode; int errCode;
String errStr; String errStr;
if(status == Constants.GETF_STATUS_NOT_FOUND) { if (status == Constants.GETF_STATUS_NOT_FOUND) {
errCode = 404; errCode = 404;
errStr = "Not Found"; errStr = "Not Found";
} else if (status == Constants.GETF_STATUS_TIMED_OUT) {
errCode = 408;
errStr = "Timed Out";
} else if (status == Constants.GETF_STATUS_BAD_NAME) {
errCode = 418;
errStr = "I'm a teapot";
} else { } else {
errCode = 500; errCode = 500;
errStr = "Internal Server Error"; errStr = "Internal Server Error";
} }
resp.setStatus(errCode); // reporting the actual status and text makes CEF not display the page
resp.setStatusText(errStr); cefResponse.setStatus(200);
cefResponse.setStatusText("OK");
cefResponse.setMimeType("text/html");
try { dataToWrite = String.format(ERROR_PAGE, errCode, errStr).getBytes(StandardCharsets.UTF_8);
dataToWrite = String.format(ERROR_PAGE, errCode, errStr).getBytes("UTF-8"); dataOffset = 0;
dataOffset = 0; amountToWrite = dataToWrite.length;
amountToWrite = dataToWrite.length; isErrorPage = true;
isErrorPage = true; contentLength.set(0);
resp.setResponseLength(amountToWrite);
} catch(UnsupportedEncodingException ex) {
resp.setResponseLength(0);
}
} }
private byte[] dataToWrite; private byte[] dataToWrite;
@ -108,10 +132,10 @@ public class WDScheme implements IScheme {
private int amountToWrite; private int amountToWrite;
@Override @Override
public boolean readResponse(ISchemeResponseData data) { public boolean readResponse(byte[] output, int bytesToRead, IntRef bytesRead, CefCallback cefCallback) {
if(dataToWrite == null) { if (dataToWrite == null) {
if(isErrorPage) { if (isErrorPage) {
data.setAmountRead(0); bytesRead.set(0);
return false; return false;
} }
@ -119,25 +143,25 @@ public class WDScheme implements IScheme {
dataOffset = 3; //packet ID + size dataOffset = 3; //packet ID + size
amountToWrite = task.getDataLength(); amountToWrite = task.getDataLength();
if(amountToWrite <= 0) { if (amountToWrite <= 0) {
dataToWrite = null; dataToWrite = null;
data.setAmountRead(0); bytesRead.set(0);
return false; return false;
} }
} }
int toWrite = data.getBytesToRead(); int toWrite = bytesToRead;
if(toWrite > amountToWrite) if (toWrite > amountToWrite)
toWrite = amountToWrite; toWrite = amountToWrite;
System.arraycopy(dataToWrite, dataOffset, data.getDataArray(), 0, toWrite); System.arraycopy(dataToWrite, dataOffset, output, 0, toWrite);
data.setAmountRead(toWrite); bytesRead.set(toWrite);
dataOffset += toWrite; dataOffset += toWrite;
amountToWrite -= toWrite; amountToWrite -= toWrite;
if(amountToWrite <= 0) { if (amountToWrite <= 0) {
if(!isErrorPage) if (!isErrorPage)
task.nextData(); task.nextData();
dataToWrite = null; dataToWrite = null;
@ -146,4 +170,46 @@ public class WDScheme implements IScheme {
return true; return true;
} }
@Override
public void cancel() {
Log.info("Scheme query canceled or finished.");
if (!onlyError)
task.cancel();
}
public static String mapMime(String ext) {
switch (ext) {
case "htm":
case "html":
return "text/html";
case "css":
return "text/css";
case "js":
return "text/javascript";
case "png":
return "image/png";
case "jpg":
case "jpeg":
return "image/jpeg";
case "gif":
return "image/gif";
case "svg":
return "image/svg+xml";
case "xml":
return "text/xml";
case "txt":
return "text/plain";
default:
return null;
}
}
} }

View File

@ -0,0 +1,116 @@
package net.montoyo.wd.client.audio;
import net.minecraft.client.resources.sounds.Sound;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.sounds.AudioStream;
import net.minecraft.client.sounds.SoundBufferLibrary;
import net.minecraft.client.sounds.SoundManager;
import net.minecraft.client.sounds.WeighedSoundEvents;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.util.valueproviders.SampledFloat;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.entity.ScreenData;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public class WDAudioSource implements SoundInstance {
private static final ResourceLocation location = new ResourceLocation("webdisplays:audio_source");
private static final WeighedSoundEvents events = new WeighedSoundEvents(
location, "webdisplays.browser"
);
private static final SampledFloat CONST_1 = new SampledFloat() {
@Override
public float sample(RandomSource pRandom) {
return 1.0f;
}
};
private final Sound sound = new Sound(
"unused",
CONST_1,
CONST_1,
1, Sound.Type.SOUND_EVENT,
true, false,
100
);
ScreenBlockEntity blockEntity;
ScreenData data;
public WDAudioSource(ScreenBlockEntity blockEntity, ScreenData data) {
this.blockEntity = blockEntity;
this.data = data;
}
@Override
public ResourceLocation getLocation() {
return location;
}
@Nullable
@Override
public WeighedSoundEvents resolve(SoundManager pManager) {
return events;
}
@Override
public CompletableFuture<AudioStream> getStream(SoundBufferLibrary soundBuffers, Sound sound, boolean looping) {
return null;
}
@Override
public Sound getSound() {
return sound;
}
@Override
public SoundSource getSource() {
return SoundSource.RECORDS;
}
@Override
public boolean isLooping() {
return true;
}
@Override
public boolean isRelative() {
return false;
}
@Override
public int getDelay() {
return 0;
}
@Override
public float getVolume() {
return blockEntity.ytVolume;
}
@Override
public float getPitch() {
return 1;
}
@Override
public double getX() {
return blockEntity.getBlockPos().getX();
}
@Override
public double getY() {
return blockEntity.getBlockPos().getY();
}
@Override
public double getZ() {
return blockEntity.getBlockPos().getZ();
}
@Override
public Attenuation getAttenuation() {
return Attenuation.LINEAR;
}
}

View File

@ -4,42 +4,59 @@
package net.montoyo.wd.client.gui; package net.montoyo.wd.client.gui;
import com.cinemamod.mcef.MCEFBrowser;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLPaths; import net.minecraftforge.fml.loading.FMLPaths;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.gui.camera.KeyboardCamera;
import net.montoyo.wd.client.gui.controls.Button; import net.montoyo.wd.client.gui.controls.Button;
import net.montoyo.wd.client.gui.controls.Control; import net.montoyo.wd.client.gui.controls.Control;
import net.montoyo.wd.client.gui.controls.Label; import net.montoyo.wd.client.gui.controls.Label;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.controls.builtin.ClickControl;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.TypeData; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.serialization.TypeData;
import net.montoyo.wd.utilities.serialization.Util;
import org.cef.browser.CefBrowser;
import org.cef.misc.CefCursorType;
import org.joml.Matrix4f;
import org.joml.Vector4f;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import org.vivecraft.gameplay.VRPlayer; import org.vivecraft.client_vr.gameplay.VRPlayer;
import org.vivecraft.gameplay.screenhandlers.KeyboardHandler; import org.vivecraft.client_vr.gameplay.screenhandlers.KeyboardHandler;
import java.io.*; import java.io.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public class GuiKeyboard extends WDScreen { public class GuiKeyboard extends WDScreen {
private static final String WARNING_FNAME = "wd_keyboard_warning.txt"; private static final String WARNING_FNAME = "wd_keyboard_warning.txt";
private TileEntityScreen tes; private ScreenBlockEntity tes;
private BlockSide side; private BlockSide side;
private ScreenData data;
private final ArrayList<TypeData> evStack = new ArrayList<>(); private final ArrayList<TypeData> evStack = new ArrayList<>();
private BlockPos kbPos; private BlockPos kbPos;
private boolean showWarning = true; private boolean showWarning = true;
@ -54,7 +71,7 @@ public class GuiKeyboard extends WDScreen {
super(Component.nullToEmpty(null)); super(Component.nullToEmpty(null));
} }
public GuiKeyboard(TileEntityScreen tes, BlockSide side, BlockPos kbPos) { public GuiKeyboard(ScreenBlockEntity tes, BlockSide side, BlockPos kbPos) {
this(); this();
this.tes = tes; this.tes = tes;
this.side = side; this.side = side;
@ -67,7 +84,7 @@ public class GuiKeyboard extends WDScreen {
} }
private static final boolean vivecraftPresent; private static final boolean vivecraftPresent;
static { static {
boolean vivePres = false; boolean vivePres = false;
if (ModList.get().isLoaded("vivecraft")) vivePres = true; if (ModList.get().isLoaded("vivecraft")) vivePres = true;
@ -89,7 +106,7 @@ public class GuiKeyboard extends WDScreen {
} }
vivecraftPresent = vivePres; vivecraftPresent = vivePres;
} }
@Override @Override
public void init() { public void init() {
super.init(); super.init();
@ -135,43 +152,68 @@ public class GuiKeyboard extends WDScreen {
defaultBackground = showWarning; defaultBackground = showWarning;
syncTicks = 5; syncTicks = 5;
if (vivecraftPresent) if (vivecraftPresent)
if (VRPlayer.get() != null) if (VRPlayer.get() != null)
KeyboardHandler.setOverlayShowing(true); KeyboardHandler.setOverlayShowing(true);
KeyboardCamera.focus(tes, side);
data = tes.getScreen(side);
CefBrowser browser = data.browser;
((MCEFBrowser) browser).setCursor(CefCursorType.fromId(data.mouseType));
((MCEFBrowser) browser).setCursorChangeListener((id) -> {
data.mouseType = id;
((MCEFBrowser) browser).setCursor(CefCursorType.fromId(id));
});
} }
@Override @Override
public void onClose() { public void removed() {
super.removed();
if (vivecraftPresent) if (vivecraftPresent)
if (VRPlayer.get() != null) if (VRPlayer.get() != null)
KeyboardHandler.setOverlayShowing(false); KeyboardHandler.setOverlayShowing(false);
super.onClose(); KeyboardCamera.focus(null, null);
CefBrowser browser = data.browser;
if (browser instanceof MCEFBrowser mcef) {
mcef.setCursor(CefCursorType.POINTER);
mcef.setCursorChangeListener((cursor) -> data.mouseType = cursor);
}
} }
@Override
public void onClose() {
removed();
super.onClose();
this.minecraft.popGuiLayer();
}
@Override @Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) { public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if(quitOnEscape && keyCode == GLFW.GLFW_KEY_ESCAPE) if (quitOnEscape && keyCode == GLFW.GLFW_KEY_ESCAPE) {
Minecraft.getInstance().setScreen(null); onClose();
addKey(new TypeData(TypeData.Action.PRESS, keyCode, modifiers)); return true;
}
addKey(new TypeData(TypeData.Action.PRESS, keyCode, modifiers, scanCode));
return super.keyPressed(keyCode, scanCode, modifiers); return super.keyPressed(keyCode, scanCode, modifiers);
} }
@Override @Override
public boolean charTyped(char codePoint, int modifiers) { public boolean charTyped(char codePoint, int modifiers) {
addKey(new TypeData(TypeData.Action.TYPE, codePoint, modifiers)); addKey(new TypeData(TypeData.Action.TYPE, codePoint, modifiers, 0));
return super.charTyped(codePoint, modifiers); return super.charTyped(codePoint, modifiers);
} }
@Override @Override
public boolean keyReleased(int keyCode, int scanCode, int modifiers) { public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
addKey(new TypeData(TypeData.Action.RELEASE, keyCode, modifiers)); addKey(new TypeData(TypeData.Action.RELEASE, keyCode, modifiers, scanCode));
return super.keyPressed(keyCode, scanCode, modifiers); return super.keyPressed(keyCode, scanCode, modifiers);
} }
void addKey(TypeData data) { void addKey(TypeData data) {
tes.type(side, "[" + WebDisplays.GSON.toJson(data) + "]", kbPos); tes.type(side, "[" + WebDisplays.GSON.toJson(data) + "]", kbPos);
evStack.add(data); evStack.add(data);
if (!evStack.isEmpty() && !syncRequested()) if (!evStack.isEmpty() && !syncRequested())
requestSync(); requestSync();
@ -241,4 +283,89 @@ public class GuiKeyboard extends WDScreen {
return bp.equals(kbPos) || (bp.equals(tes.getBlockPos()) && side == this.side); return bp.equals(kbPos) || (bp.equals(tes.getBlockPos()) && side == this.side);
} }
protected void mouse(double mouseX, double mouseY, Consumer<Vector2i> func) {
float pct = Minecraft.getInstance().getPartialTick();
double fov = Minecraft.getInstance().gameRenderer.getFov(
Minecraft.getInstance().getEntityRenderDispatcher().camera,
pct, true
);
mouseX /= width;
mouseY /= height;
mouseX -= 0.5;
mouseY -= 0.5;
mouseY = -mouseY;
Matrix4f proj = Minecraft.getInstance().gameRenderer.getProjectionMatrix(fov);
Entity e = Minecraft.getInstance().getEntityRenderDispatcher().camera.getEntity();
PoseStack camera = new PoseStack();
float[] angle = KeyboardCamera.getAngle(e, pct);
camera.mulPose(Axis.XP.rotationDegrees(angle[0]));
camera.mulPose(Axis.YP.rotationDegrees(angle[1] + 180.0F));
Vector4f coord = new Vector4f(2f * (float) mouseX, 2 * (float) mouseY, 0, 1f);
coord.add(proj.invert().transform(coord));
coord = camera.last().pose().invert().transform(coord);
Vec3 vec3 = e.getEyePosition(pct);
Vec3 vec31 = new Vec3(coord.x, coord.y, coord.z).normalize();
BlockHitResult result = tes.trace(side, vec3, vec31);
if (result.getType() != HitResult.Type.MISS) {
tes.interact(result, func);
}
}
@Override
public void mouseMoved(double mouseX, double mouseY) {
mouse(mouseX, mouseY, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserMove(tes, side, hit));
});
super.mouseMoved(mouseX, mouseY);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
mouse(mouseX, mouseY, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
tes.handleMouseEvent(side, ClickControl.ControlType.DOWN, hit, button);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserDown(tes, side, hit, button));
});
KeyboardCamera.setMouse(button, true);
return super.mouseClicked(mouseX, mouseY, button);
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
mouse(mouseX, mouseY, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
tes.handleMouseEvent(side, ClickControl.ControlType.UP, hit, button);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserUp(tes, side, button));
});
KeyboardCamera.setMouse(button, false);
return super.mouseReleased(mouseX, mouseY, button);
}
@Override
public void tick() {
double mouseX = Minecraft.getInstance().mouseHandler.xpos() / Minecraft.getInstance().getWindow().getWidth();
double mouseY = Minecraft.getInstance().mouseHandler.ypos() / Minecraft.getInstance().getWindow().getHeight();
mouse(mouseX * width, mouseY * height, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserMove(tes, side, hit));
});
super.tick();
}
} }

View File

@ -4,16 +4,27 @@
package net.montoyo.wd.client.gui; package net.montoyo.wd.client.gui;
import com.cinemamod.mcef.MCEFBrowser;
import com.google.gson.JsonObject;
import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*; import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.Tesselator;
import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.locale.Language;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.browser.WDBrowser;
import org.cef.browser.CefBrowserOsr; import net.montoyo.wd.utilities.browser.handlers.js.Scripts;
import net.montoyo.wd.utilities.data.BlockSide;
import org.cef.misc.CefCursorType;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import java.util.Optional; import java.util.Optional;
@ -23,217 +34,324 @@ import static net.minecraftforge.api.distmarker.Dist.CLIENT;
@OnlyIn(CLIENT) @OnlyIn(CLIENT)
public class GuiMinePad extends WDScreen { public class GuiMinePad extends WDScreen {
private ClientProxy.PadData pad; private ClientProxy.PadData pad;
private double vx; private double vx;
private double vy; private double vy;
private double vw; private double vw;
private double vh; private double vh;
public GuiMinePad() { public GuiMinePad() {
super(Component.nullToEmpty(null)); super(Component.nullToEmpty(null));
} }
public GuiMinePad(ClientProxy.PadData pad) { public GuiMinePad(ClientProxy.PadData pad) {
this(); this();
this.pad = pad; this.pad = pad;
}
if (WebDisplays.cursorSupport)
pad.view.allowCursorChanges(true);
}
@Override int trueWidth, trueHeight;
public void init() {
vw = ((double) width) - 32.0f;
vh = vw / WebDisplays.PAD_RATIO;
vx = 16.0f;
vy = (((double) height) - vh) / 2.0f;
this.width = (int) vw;
this.height = (int) vh;
super.init();
}
private static void addRect(BufferBuilder bb, double x, double y, double w, double h) { @Override
bb.vertex(x, y, 0.0).color(255, 255, 255, 255).endVertex(); public void init() {
bb.vertex(x + w, y, 0.0).color(255, 255, 255, 255).endVertex(); vw = ((double) width) - 32.0f;
bb.vertex(x + w, y + h, 0.0).color(255, 255, 255, 255).endVertex(); vh = vw / WebDisplays.PAD_RATIO;
bb.vertex(x, y + h, 0.0).color(255, 255, 255, 255).endVertex(); vx = 16.0f;
} vy = (((double) height) - vh) / 2.0f;
@Override trueWidth = width;
public void render(PoseStack poseStack, int mouseX, int mouseY, float ptt) { trueHeight = height;
renderBackground(poseStack);
RenderSystem.disableTexture(); this.width = (int) vw;
RenderSystem.disableCull(); this.height = (int) vh;
RenderSystem.setShaderColor(0.73f, 0.73f, 0.73f, 1.0f);
Tesselator t = Tesselator.getInstance(); super.init();
BufferBuilder bb = t.getBuilder();
bb.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
addRect(bb, vx, vy - 16, vw, 16);
addRect(bb, vx, vy + vh, vw, 16);
addRect(bb, vx - 16, vy, 16, vh);
addRect(bb, vx + vw, vy, 16, vh);
t.end();
RenderSystem.enableTexture(); ((MCEFBrowser) pad.view).setCursor(CefCursorType.fromId(pad.activeCursor));
((MCEFBrowser) pad.view).setCursorChangeListener((id) -> {
pad.activeCursor = id;
((MCEFBrowser) pad.view).setCursor(CefCursorType.fromId(id));
});
}
if (pad.view != null) { private static void addRect(BufferBuilder bb, double x, double y, double w, double h) {
pad.view.draw(poseStack, vx, vy + vh, vx + vw, vy); bb.vertex(x, y, 0.0).color(255, 255, 255, 255).endVertex();
} bb.vertex(x + w, y, 0.0).color(255, 255, 255, 255).endVertex();
bb.vertex(x + w, y + h, 0.0).color(255, 255, 255, 255).endVertex();
bb.vertex(x, y + h, 0.0).color(255, 255, 255, 255).endVertex();
}
RenderSystem.enableCull(); @Override
} public void render(GuiGraphics graphics, int mouseX, int mouseY, float ptt) {
width = trueWidth;
height = trueHeight;
renderBackground(graphics);
width = (int) vw;
height = (int) vh;
@Override RenderSystem.disableCull();
public boolean keyPressed(int keyCode, int scanCode, int modifiers) { RenderSystem.setShaderColor(0.73f, 0.73f, 0.73f, 1.0f);
return this.keyChanged(keyCode, scanCode, modifiers, true) || super.keyPressed(keyCode, scanCode, modifiers);
}
@Override Tesselator t = Tesselator.getInstance();
public boolean keyReleased(int keyCode, int scanCode, int modifiers) { BufferBuilder bb = t.getBuilder();
return this.keyChanged(keyCode, scanCode, modifiers, false) || super.keyReleased(keyCode, scanCode, modifiers); bb.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
} addRect(bb, vx, vy - 16, vw, 16);
addRect(bb, vx, vy + vh, vw, 16);
@Override addRect(bb, vx - 16, vy, 16, vh);
public boolean charTyped(char codePoint, int modifiers) { addRect(bb, vx + vw, vy, 16, vh);
if (pad.view != null) { t.end();
pad.view.injectKeyTyped((int) codePoint, modifiers);
return true; if (pad.view != null) {
} else { // pad.view.draw(poseStack, vx, vy + vh, vx + vw, vy);
return super.charTyped(codePoint, modifiers); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
} RenderSystem.disableDepthTest();
} RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
RenderSystem.setShaderTexture(0, ((MCEFBrowser) pad.view).getRenderer().getTextureID());
/* copied from MCEF */ t = Tesselator.getInstance();
public boolean keyChanged(int keyCode, int scanCode, int modifiers, boolean pressed) { BufferBuilder buffer = t.getBuilder();
assert minecraft != null; buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
if (keyCode == GLFW.GLFW_KEY_ESCAPE) { double x1 = vx;
minecraft.setScreen(null); double y1 = vy;
return true; double x2 = vx + vw;
} double y2 = vy + vh;
buffer.vertex(graphics.pose().last().pose(), (float) x1, (float) y1, 0.0f).uv(0.0F, 0.0F).color(255, 255, 255, 255).endVertex();
InputConstants.Key iuKey = InputConstants.getKey(keyCode, scanCode); buffer.vertex(graphics.pose().last().pose(), (float) x2, (float) y1, 0.0f).uv(1.0F, 0.0F).color(255, 255, 255, 255).endVertex();
String keystr = iuKey.getDisplayName().getString(); buffer.vertex(graphics.pose().last().pose(), (float) x2, (float) y2, 0.0f).uv(1.0F, 1.0F).color(255, 255, 255, 255).endVertex();
buffer.vertex(graphics.pose().last().pose(), (float) x1, (float) y2, 0.0f).uv(0.0F, 1.0F).color(255, 255, 255, 255).endVertex();
t.end();
RenderSystem.enableDepthTest();
}
RenderSystem.enableCull();
graphics.drawString(
minecraft.font, Language.getInstance().getOrDefault(
"webdisplays.gui.minepad.close"
), (int) vx + 4, (int) vy - minecraft.font.lineHeight - 3, 16777215, true
);
}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
return this.keyChanged(keyCode, scanCode, modifiers, true) || super.keyPressed(keyCode, scanCode, modifiers);
}
@Override
public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
return this.keyChanged(keyCode, scanCode, modifiers, false) || super.keyReleased(keyCode, scanCode, modifiers);
}
@Override
public boolean charTyped(char codePoint, int modifiers) {
if (pad.view != null) {
((MCEFBrowser) pad.view).sendKeyTyped(codePoint, modifiers);
return true;
} else {
return super.charTyped(codePoint, modifiers);
}
}
/* copied from MCEF */
public boolean keyChanged(int keyCode, int scanCode, int modifiers, boolean pressed) {
assert minecraft != null;
if ((modifiers & GLFW.GLFW_MOD_SHIFT) == GLFW.GLFW_MOD_SHIFT && keyCode == GLFW.GLFW_KEY_ESCAPE) {
onClose();
return true;
}
InputConstants.Key iuKey = InputConstants.getKey(keyCode, scanCode);
String keystr = iuKey.getDisplayName().getString();
// System.out.println("KEY STR " + keystr); // System.out.println("KEY STR " + keystr);
if (keystr.length() == 0) if (keystr.length() == 0)
return false; return false;
char key = keystr.charAt(keystr.length() - 1);
if(keystr.equals("Enter")) {
keyCode = 10;
key = '\n';
}
if (pad.view != null) {
if (pressed)
pad.view.injectKeyPressedByKeyCode(keyCode, key, modifiers);
else
pad.view.injectKeyReleasedByKeyCode(keyCode, key, modifiers);
if (pressed && key == '\n')
if (modifiers != 0) pad.view.injectKeyTyped('\r', modifiers);
return true;
}
return false;
}
@Override char key = keystr.charAt(keystr.length() - 1);
public void mouseMoved(double mouseX, double mouseY) {
super.mouseMoved(mouseX, mouseY);
mouse(-1, false, (int) mouseX, (int) mouseY, 0);
}
@Override if (keystr.equals("Enter")) {
public boolean mouseClicked(double mouseX, double mouseY, int button) { keyCode = 10;
mouse(button, true, (int) mouseX, (int) mouseY, 0); key = '\n';
return super.mouseClicked(mouseX, mouseY, button); }
}
@Override if (pad.view != null) {
public boolean mouseReleased(double mouseX, double mouseY, int button) { if (pressed)
mouse(button, false, (int) mouseX, (int) mouseY, 0); ((MCEFBrowser) pad.view).sendKeyPress(keyCode, scanCode, modifiers);
return super.mouseReleased(mouseX, mouseY, button); else
} ((MCEFBrowser) pad.view).sendKeyRelease(keyCode, scanCode, modifiers);
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) {
mouse(button, true, (int) mouseX, (int) mouseY, 0);
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY);
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
mouse(-1, false, (int) mouseX, (int) mouseY, amount);
return super.mouseScrolled(mouseX, mouseY, amount);
}
public void mouse(int btn, boolean pressed, int sx, int sy, double scrollAmount) { if (pressed && key == '\n')
double mx = (sx - vx) / vw; if (modifiers != 0) ((MCEFBrowser) pad.view).sendKeyTyped('\r', modifiers);
double my = (sy - vy) / vh; return true;
}
if (pad.view != null && mx >= 0 && mx <= 1) { return false;
int wheel = (int) scrollAmount; }
//Scale again according to the webview @Override
sx = (int) (mx * WebDisplays.INSTANCE.padResX); public void mouseMoved(double mouseX, double mouseY) {
sy = (int) (my * WebDisplays.INSTANCE.padResY); super.mouseMoved(mouseX, mouseY);
mouse(-1, false, (int) mouseX, (int) mouseY, 0);
if (wheel != 0) }
pad.view.injectMouseWheel(sx, sy, (hasControlDown() && ! hasAltDown() && !hasShiftDown()) ? GLFW.GLFW_MOD_CONTROL : 0, wheel, 0);
if (btn == -1)
pad.view.injectMouseMove(sx, sy, 0, sy < 0);
else
pad.view.injectMouseButton(sx, sy, 0, btn + 1, pressed, 1);
}
}
public static Optional<Character> getChar(int keyCode, int scanCode) { @Override
String keystr = GLFW.glfwGetKeyName(keyCode, scanCode); public boolean mouseClicked(double mouseX, double mouseY, int button) {
if(keystr == null){ mouse(button, true, (int) mouseX, (int) mouseY, 0);
keystr = "\0"; return super.mouseClicked(mouseX, mouseY, button);
} }
if(keyCode == GLFW.GLFW_KEY_ENTER){
keystr = "\n";
}
if(keystr.length() == 0){
return Optional.empty();
}
return Optional.of(keystr.charAt(keystr.length() - 1)); @Override
} public boolean mouseReleased(double mouseX, double mouseY, int button) {
mouse(button, false, (int) mouseX, (int) mouseY, 0);
return super.mouseReleased(mouseX, mouseY, button);
}
@Override @Override
public void tick() { public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
if(pad.view == null) double mx = (mouseX - vx) / vw;
minecraft.setScreen(null); //In case the user dies with the pad in the hand double my = (mouseY - vy) / vh;
} int sx = (int) (mx * WebDisplays.INSTANCE.padResX);
int sy = (int) (my * WebDisplays.INSTANCE.padResY);
// TODO: this doesn't work, and I don't understand why?
((MCEFBrowser) pad.view).sendMouseWheel(sx, sy, amount, (hasControlDown() && !hasAltDown() && !hasShiftDown()) ? GLFW.GLFW_MOD_CONTROL : 0);
@Override return super.mouseScrolled(mouseX, mouseY, amount);
public boolean isForBlock(BlockPos bp, BlockSide side) { }
return false;
} public void capturedMouse(double scaledX, double scaledY, int sx, int sy) {
double centerX = (int) (0.5 * (double) this.minecraft.getWindow().getGuiScaledWidth());
@Override double centerY = (int) (0.5 * (double) this.minecraft.getWindow().getGuiScaledHeight());
public void removed() {
super.removed(); if (sx == (int) centerX && sy == (int) centerY) return;
if (pad.view instanceof CefBrowserOsr osr) {
osr.allowCursorChanges(true); double mx = (centerX - vx) / vw;
osr.onCursorChange(null, 0); double my = (centerY - vy) / vh;
} double scaledCentX = (mx * WebDisplays.INSTANCE.padResX);
} double scaledCentY = (my * WebDisplays.INSTANCE.padResY);
@Override double deltX = scaledX - scaledCentX;
public void onClose() { double deltY = scaledY - scaledCentY;
super.onClose();
if (WebDisplays.cursorSupport) { String scr = Scripts.MOUSE_EVENT;
pad.view.allowCursorChanges(false); pad.view.executeJavaScript(
if (pad.view instanceof CefBrowserOsr osr) scr
osr.onCursorChange(null, 0); .replace("%xCoord%", "" + (int) centerX)
} .replace("%yCoord%", "" + (int) centerY)
} .replace("%xDelta%", "" + (deltX))
.replace("%yDelta%", "" + (deltY)),
"WebDisplays", 0
);
// lock mouse
try {
double xpos = (this.minecraft.getWindow().getScreenWidth() / 2);
double ypos = (this.minecraft.getWindow().getScreenHeight() / 2);
GLFW.glfwSetCursorPos(minecraft.getWindow().getWindow(), xpos, ypos);
} catch (Throwable ignored) {
}
}
public void mouse(int btn, boolean pressed, int sx, int sy, double scrollAmount) {
double mx = (sx - vx) / vw;
double my = (sy - vy) / vh;
if (pad.view != null && mx >= 0 && mx <= 1) {
//Scale again according to the webview
int scaledX = (int) (mx * WebDisplays.INSTANCE.padResX);
int scaledY = (int) (my * WebDisplays.INSTANCE.padResY);
if (btn == -1) {
if (locked)
capturedMouse(mx * WebDisplays.INSTANCE.padResX, my * WebDisplays.INSTANCE.padResY, sx, sy);
else ((MCEFBrowser) pad.view).sendMouseMove(scaledX, scaledY);
} else if (pressed)
((MCEFBrowser) pad.view).sendMousePress(scaledX, scaledY, btn);
else ((MCEFBrowser) pad.view).sendMouseRelease(scaledX, scaledY, btn);
pad.view.setFocus(true);
}
}
public static Optional<Character> getChar(int keyCode, int scanCode) {
String keystr = GLFW.glfwGetKeyName(keyCode, scanCode);
if (keystr == null) {
keystr = "\0";
}
if (keyCode == GLFW.GLFW_KEY_ENTER) {
keystr = "\n";
}
if (keystr.length() == 0) {
return Optional.empty();
}
return Optional.of(keystr.charAt(keystr.length() - 1));
}
@Override
public void tick() {
if (pad.view == null)
minecraft.setScreen(null); //In case the user dies with the pad in the hand
pollElement();
}
@Override
public boolean isForBlock(BlockPos bp, BlockSide side) {
return false;
}
@Override
public void removed() {
super.removed();
InputConstants.updateRawMouseInput(
minecraft.getWindow().getWindow(),
Minecraft.getInstance().options.rawMouseInput().get()
);
if (pad.view instanceof MCEFBrowser browser) {
browser.setCursor(CefCursorType.POINTER);
browser.setCursorChangeListener((cursor) -> {
pad.activeCursor = cursor;
});
}
}
@Override
public void onClose() {
super.onClose();
removed();
this.minecraft.popGuiLayer();
}
boolean locked = false;
double lockCenterX = -1;
double lockCenterY = -1;
protected void updateCrd(JsonObject obj) {
if (obj.getAsJsonPrimitive("exists").getAsBoolean()) {
locked = true;
RenderSystem.recordRenderCall(() -> {
InputConstants.updateRawMouseInput(
minecraft.getWindow().getWindow(),
obj.getAsJsonPrimitive("unadjust").getAsBoolean()
);
GLFW.glfwSetInputMode(Minecraft.getInstance().getWindow().getWindow(), 208897, GLFW.GLFW_CURSOR_DISABLED);
});
lockCenterX = obj.getAsJsonPrimitive("x").getAsDouble() + obj.getAsJsonPrimitive("w").getAsDouble() / 2;
lockCenterY = obj.getAsJsonPrimitive("y").getAsDouble() + obj.getAsJsonPrimitive("h").getAsDouble() / 2;
} else {
if (locked) {
locked = false;
RenderSystem.recordRenderCall(()->{
InputConstants.updateRawMouseInput(
minecraft.getWindow().getWindow(),
Minecraft.getInstance().options.rawMouseInput().get()
);
GLFW.glfwSetInputMode(Minecraft.getInstance().getWindow().getWindow(), 208897, GLFW.GLFW_CURSOR_NORMAL);
GLFW.glfwSetCursor(Minecraft.getInstance().getWindow().getWindow(), CefCursorType.fromId(pad.activeCursor).glfwId);
});
}
}
}
protected void pollElement() {
if (pad.view instanceof WDBrowser browser) {
JsonObject object = browser.pointerLockElement().getObj();
if (object != null) updateCrd(object);
}
}
} }

View File

@ -7,17 +7,11 @@ package net.montoyo.wd.client.gui;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.montoyo.mcef.api.API;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.client.gui.controls.Button; import net.montoyo.wd.client.gui.controls.Button;
import net.montoyo.wd.client.gui.controls.TextField; import net.montoyo.wd.client.gui.controls.TextField;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.net.server_bound.C2SMessageRedstoneCtrl; import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Util;
import net.montoyo.wd.utilities.Vector3i;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -53,18 +47,18 @@ public class GuiRedstoneCtrl extends WDScreen {
tfFallingEdge.setText(fallingEdgeURL); tfFallingEdge.setText(fallingEdgeURL);
} }
@GuiSubscribe // @GuiSubscribe
public void onClick(Button.ClickEvent ev) { // public void onClick(Button.ClickEvent ev) {
if(ev.getSource() == btnOk) { // if(ev.getSource() == btnOk) {
API mcef = ((ClientProxy) WebDisplays.PROXY).getMCEF(); // API mcef = ((ClientProxy) WebDisplays.PROXY).getMCEF();
//
String rising = mcef.punycode(Util.addProtocol(tfRisingEdge.getText())); // String rising = mcef.punycode(Util.addProtocol(tfRisingEdge.getText()));
String falling = mcef.punycode(Util.addProtocol(tfFallingEdge.getText())); // String falling = mcef.punycode(Util.addProtocol(tfFallingEdge.getText()));
WDNetworkRegistry.INSTANCE.sendToServer(new C2SMessageRedstoneCtrl(pos, rising, falling)); // WDNetworkRegistry.INSTANCE.sendToServer(new C2SMessageRedstoneCtrl(pos, rising, falling));
} // }
//
minecraft.setScreen(null); // minecraft.setScreen(null);
} // }
@Override @Override
public boolean isForBlock(BlockPos bp, BlockSide side) { public boolean isForBlock(BlockPos bp, BlockSide side) {

View File

@ -15,11 +15,16 @@ import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.gui.controls.*; import net.montoyo.wd.client.gui.controls.*;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.item.WDItem; import net.montoyo.wd.item.WDItem;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -30,7 +35,7 @@ import java.util.UUID;
public class GuiScreenConfig extends WDScreen { public class GuiScreenConfig extends WDScreen {
//Screen data //Screen data
private final TileEntityScreen tes; private final ScreenBlockEntity tes;
private final BlockSide side; private final BlockSide side;
private NameUUIDPair owner; private NameUUIDPair owner;
private NameUUIDPair[] friends; private NameUUIDPair[] friends;
@ -119,7 +124,7 @@ public class GuiScreenConfig extends WDScreen {
private CheckBox[] friendBoxes; private CheckBox[] friendBoxes;
private CheckBox[] otherBoxes; private CheckBox[] otherBoxes;
public GuiScreenConfig(Component component, TileEntityScreen tes, BlockSide side, NameUUIDPair[] friends, int fr, int or) { public GuiScreenConfig(Component component, ScreenBlockEntity tes, BlockSide side, NameUUIDPair[] friends, int fr, int or) {
super(component); super(component);
this.tes = tes; this.tes = tes;
this.side = side; this.side = side;
@ -147,7 +152,7 @@ public class GuiScreenConfig extends WDScreen {
boxOClick.setUserdata(ScreenRights.INTERACT); boxOClick.setUserdata(ScreenRights.INTERACT);
boxOSetUrl.setUserdata(ScreenRights.CHANGE_URL); boxOSetUrl.setUserdata(ScreenRights.CHANGE_URL);
TileEntityScreen.Screen scr = tes.getScreen(side); ScreenData scr = tes.getScreen(side);
if(scr != null) { if(scr != null) {
owner = scr.owner; owner = scr.owner;
rotation = scr.rotation; rotation = scr.rotation;
@ -191,7 +196,7 @@ public class GuiScreenConfig extends WDScreen {
} }
private void clickSetRes() { private void clickSetRes() {
TileEntityScreen.Screen scr = tes.getScreen(side); ScreenData scr = tes.getScreen(side);
if(scr == null) if(scr == null)
return; //WHATDAFUQ? return; //WHATDAFUQ?

File diff suppressed because it is too large Load Diff

View File

@ -15,14 +15,14 @@ import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.client.gui.controls.Button; import net.montoyo.wd.client.gui.controls.Button;
import net.montoyo.wd.client.gui.controls.TextField; import net.montoyo.wd.client.gui.controls.TextField;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.item.ItemMinePad2; import net.montoyo.wd.item.ItemMinePad2;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageMinepadUrl; import net.montoyo.wd.net.server_bound.C2SMessageMinepadUrl;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
@ -32,7 +32,7 @@ import java.util.UUID;
public class GuiSetURL2 extends WDScreen { public class GuiSetURL2 extends WDScreen {
//Screen data //Screen data
private TileEntityScreen tileEntity; private ScreenBlockEntity tileEntity;
private BlockSide screenSide; private BlockSide screenSide;
private Vector3i remoteLocation; private Vector3i remoteLocation;
@ -55,7 +55,7 @@ public class GuiSetURL2 extends WDScreen {
@FillControl @FillControl
private Button btnOk; private Button btnOk;
public GuiSetURL2(TileEntityScreen tes, BlockSide side, String url, Vector3i rl) { public GuiSetURL2(ScreenBlockEntity tes, BlockSide side, String url, Vector3i rl) {
super(Component.nullToEmpty(null)); super(Component.nullToEmpty(null));
tileEntity = tes; tileEntity = tes;
screenSide = side; screenSide = side;
@ -120,13 +120,13 @@ public class GuiSetURL2 extends WDScreen {
if (!url.isEmpty()) { if (!url.isEmpty()) {
try { try {
TileEntityScreen.url(url); ScreenBlockEntity.url(url);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
url = Util.addProtocol(url); url = Util.addProtocol(url);
url = ((ClientProxy) WebDisplays.PROXY).getMCEF().punycode(url); // url = ((ClientProxy) WebDisplays.PROXY).getMCEF().punycode(url);
if (isPad) { if (isPad) {
UUID uuid = getUUID(); UUID uuid = getUUID();

View File

@ -7,6 +7,7 @@ package net.montoyo.wd.client.gui;
import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.platform.Lighting;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.resources.language.I18n; import net.minecraft.client.resources.language.I18n;
@ -77,15 +78,16 @@ public class RenderRecipe extends Screen {
Log.info("Loaded %d recipes", recipes.size()); Log.info("Loaded %d recipes", recipes.size());
nextRecipe(); nextRecipe();
} }
@Override @Override
public void render(PoseStack poseStack, int mouseX, int mouseY, float partialTick) { public void render(GuiGraphics context, int mouseX, int mouseY, float partialTick) {
renderBackground(poseStack); // renderBackground(poseStack);
renderBackground(context);
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
RenderSystem.setShaderTexture(0, CRAFTING_TABLE_GUI_TEXTURES); RenderSystem.setShaderTexture(0, CRAFTING_TABLE_GUI_TEXTURES);
blit(poseStack, x, y, 0, 0, SIZE_X, SIZE_Y); // context.blit(x, y, 0, 0, SIZE_X, SIZE_Y);
font.draw(poseStack, I18n.get("container.crafting"), x + 28, y + 6, 0x404040); // font.draw(poseStack, I18n.get("container.crafting"), x + 28, y + 6, 0x404040);
Lighting.setupForFlatItems(); Lighting.setupForFlatItems();
// RenderSystem.disableLighting(); //TODO: Need this? // RenderSystem.disableLighting(); //TODO: Need this?
@ -98,15 +100,15 @@ public class RenderRecipe extends Screen {
int x = this.x + 30 + sx * 18; int x = this.x + 30 + sx * 18;
int y = this.y + 17 + sy * 18; int y = this.y + 17 + sy * 18;
renderItem.renderAndDecorateItem(minecraft.player, is, x, y, 0); context.renderItem(is, x, y);
renderItem.renderGuiItemDecorations(font, is, x, y, null); context.renderItemDecorations(font, is, x, y);
} }
} }
} }
if(recipeResult != null) { if(recipeResult != null) {
renderItem.renderAndDecorateItem(minecraft.player, recipeResult, x + 124, y + 35, 0); context.renderItem(recipeResult, x, y);
renderItem.renderGuiItemDecorations(font, recipeResult, x + 124, y + 35, null); context.renderItemDecorations(font, recipeResult, x, y);
} }
// GlStateManager.enableLighting(); // GlStateManager.enableLighting();
@ -127,7 +129,7 @@ public class RenderRecipe extends Screen {
} }
} }
recipeResult = recipe.getResultItem(); // recipeResult = recipe.getResultItem();
} }
private void nextRecipe() { private void nextRecipe() {

View File

@ -7,8 +7,9 @@ package net.montoyo.wd.client.gui;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
@ -25,6 +26,10 @@ import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageACQuery; import net.montoyo.wd.net.server_bound.C2SMessageACQuery;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.data.Bounds;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
@ -111,10 +116,12 @@ public abstract class WDScreen extends Screen {
} }
@Override @Override
public void render(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void render(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(defaultBackground) if(defaultBackground)
renderBackground(poseStack); renderBackground(poseStack);
RenderSystem.setShaderColor(1.f, 1.f, 1.f, 1.f);
for(Control ctrl: controls) for(Control ctrl: controls)
ctrl.draw(poseStack, mouseX, mouseY, ptt); ctrl.draw(poseStack, mouseX, mouseY, ptt);
@ -136,9 +143,20 @@ public abstract class WDScreen extends Screen {
public boolean mouseClicked(double mouseX, double mouseY, int button) { public boolean mouseClicked(double mouseX, double mouseY, int button) {
boolean clicked = false; boolean clicked = false;
Control clickedEl = null;
for(Control ctrl: controls) { for(Control ctrl: controls) {
clicked = ctrl.mouseClicked(mouseX, mouseY, button); clicked = ctrl.mouseClicked(mouseX, mouseY, button);
if (clicked) break; // don't assume the compiler will optimize stuff if (clicked) {
clickedEl = ctrl;
break; // don't assume the compiler will optimize stuff
}
}
if (clicked) {
for (Control control : controls) {
if (control != clickedEl)
control.unfocus();
}
} }
return clicked; return clicked;
@ -167,7 +185,7 @@ public abstract class WDScreen extends Screen {
@Override @Override
protected void init() { protected void init() {
CURRENT_SCREEN = this; CURRENT_SCREEN = this;
minecraft.keyboardHandler.setSendRepeatsToGui(true); // minecraft.keyboardHandler.setSendRepeatsToGui(true);
} }
@Override @Override
@ -180,7 +198,7 @@ public abstract class WDScreen extends Screen {
for(Control ctrl : controls) for(Control ctrl : controls)
ctrl.destroy(); ctrl.destroy();
Minecraft.getInstance().keyboardHandler.setSendRepeatsToGui(false); // Minecraft.getInstance().keyboardHandler.setSendRepeatsToGui(false);
CURRENT_SCREEN = null; CURRENT_SCREEN = null;
} }
@ -362,12 +380,12 @@ public abstract class WDScreen extends Screen {
} }
} }
public void drawItemStackTooltip(PoseStack poseStack, ItemStack is, int x, int y) { public void drawItemStackTooltip(GuiGraphics poseStack, ItemStack is, int x, int y) {
renderTooltip(poseStack, is, x, y); //Since it's protected... poseStack.renderTooltip(Minecraft.getInstance().font, is, x, y); //Since it's protected...
} }
public void drawTooltip(PoseStack poseStack, List<String> lines, int x, int y) { public void drawTooltip(GuiGraphics poseStack, List<String> lines, int x, int y) {
renderTooltip(poseStack, lines.stream().map(a -> FormattedCharSequence.forward(a, Style.EMPTY)).collect(Collectors.toList()), x, y, font); //This is also protected... poseStack.renderTooltip(Minecraft.getInstance().font, lines.stream().map(a -> FormattedCharSequence.forward(a, Style.EMPTY)).collect(Collectors.toList()), x, y); //This is also protected...
} }
public void requirePostDraw(Control ctrl) { public void requirePostDraw(Control ctrl) {

View File

@ -0,0 +1,273 @@
package net.montoyo.wd.client.gui.camera;
import net.minecraft.client.Minecraft;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.ViewportEvent;
import net.minecraftforge.event.TickEvent;
import net.montoyo.wd.client.gui.GuiKeyboard;
import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.utilities.browser.WDBrowser;
import net.montoyo.wd.utilities.browser.handlers.js.queries.ElementCenterQuery;
import net.montoyo.wd.utilities.data.BlockSide;
public class KeyboardCamera {
private static ScreenBlockEntity tes;
private static BlockSide side;
private static double oxCrd = -1;
private static double xCrd = -1;
private static double nxCrd = -1;
private static double oyCrd = -1;
private static double yCrd = -1;
private static double nyCrd = -1;
private static double nextX = -1;
private static double nextY = -1;
private static double focalX = -1;
private static double focalY = -1;
private static final boolean[] mouseStatus = new boolean[2];
protected static Vec2 pxToHit(ScreenData scr, Vec2 dst) {
float cx, cy;
if (scr.rotation.isVertical) {
cy = dst.x;
cx = dst.y;
} else {
cx = dst.x;
cy = dst.y;
}
cx /= (float) scr.resolution.x;
cy /= (float) scr.resolution.y;
switch (scr.rotation) {
case ROT_270:
cx = 1.0f - cx;
break;
case ROT_180:
cx = 1.0f - cx;
cy = 1.0f - cy;
break;
case ROT_90:
cy = 1.0f - cy;
break;
}
if (side != BlockSide.BOTTOM)
cy = 1.0f - cy;
float swInverse = (((float) scr.size.x) - 4.f / 16.f);
float shInverse = (((float) scr.size.y) - 4.f / 16.f);
cx *= swInverse;
cy *= shInverse;
if (side.right.x > 0 || side.right.z > 0)
cx += 1.f;
if (side == BlockSide.TOP || side == BlockSide.BOTTOM)
cy -= 1.f;
return new Vec2(cx + (2 / 16f), cy + (2 / 16f));
}
protected static void updateCrd(ElementCenterQuery lock) {
ScreenData scr = tes.getScreen(side);
if (scr != null) {
Vec2 c;
if (!mouseStatus[0] && !mouseStatus[1]) {
if (lock.hasFocused()) {
if (ClientConfig.Input.keyboardCamera) {
nextX = lock.getX();
nextY = lock.getY();
c = pxToHit(scr, new Vec2((float) nextX, (float) nextY));
} else c = new Vec2(scr.size.x / 2f, scr.size.y / 2f);
} else c = new Vec2(scr.size.x / 2f, scr.size.y / 2f);
// } else c = new Vec2((float) focalX, (float) focalY);
} else return;
focalX = c.x;
focalY = c.y;
nextX = c.x;
nextY = c.y;
if (nextX < 0) nextX = 0;
else if (nextX > scr.size.x) nextX = scr.size.x;
if (nextY < 0) nextY = 0;
else if (nextY > scr.size.y) nextY = scr.size.y;
float scl = Math.max(scr.size.x, scr.size.y);
double mx = Minecraft.getInstance().mouseHandler.xpos();
mx /= Minecraft.getInstance().getWindow().getWidth();
double my = Minecraft.getInstance().mouseHandler.ypos();
my /= Minecraft.getInstance().getWindow().getHeight();
Vec2 v2 = new Vec2((float) mx, (float) my).add(-0.5f);
nextX += v2.x * scl;
nextY -= v2.y * scl;
}
}
protected static void pollElement() {
ScreenBlockEntity teTmp = tes;
BlockSide sdTmp = side;
// async nonsense can occur here
if (teTmp == null || sdTmp == null) return;
ScreenData scr = teTmp.getScreen(sdTmp);
if (scr != null) {
if (scr.browser instanceof WDBrowser wdBrowser) {
wdBrowser.focusedElement().dispatch(scr.browser);
updateCrd(((WDBrowser) scr.browser).focusedElement());
}
}
}
public static float[] getAngle(Entity e, double pct) {
BlockEntity tes = KeyboardCamera.tes;
BlockSide side = KeyboardCamera.side;
if (tes == null) return new float[]{Float.NaN, 0};
if (side == null) return new float[]{Float.NaN, 0};
double coxCrd = Mth.lerp(0.5 * pct, oxCrd, xCrd);
double coyCrd = Mth.lerp(0.5 * pct, oyCrd, yCrd);
double focalX = tes.getBlockPos().getX() +
side.right.x * (coxCrd - 1) + side.up.x * coyCrd + Math.abs(side.forward.x) * 0.5;
double focalY = tes.getBlockPos().getY() +
side.right.y * (coxCrd - 1) + side.up.y * coyCrd + Math.abs(side.forward.y) * 0.5;
double focalZ = tes.getBlockPos().getZ() +
side.right.z * (coxCrd - 1) + side.up.z * coyCrd + Math.abs(side.forward.z) * 0.5;
focalX += side.forward.x * 0.5f;
focalY += side.forward.y * 0.5f;
focalZ += side.forward.z * 0.5f;
float[] angle = lookAt(
e, EntityAnchorArgument.Anchor.EYES,
new Vec3(focalX, focalY, focalZ)
);
return angle;
}
public static void setMouse(int side, boolean pressed) {
mouseStatus[side] = pressed;
}
public static void updateCamera(ViewportEvent.ComputeCameraAngles event) {
if (tes == null) {
xCrd = -1;
yCrd = -1;
return; // nothing to do
}
if (xCrd == -1) return;
if (yCrd == -1) return;
float[] angle = getAngle(event.getCamera().getEntity(), event.getPartialTick());
if (Float.isNaN(angle[0])) return;
// float xRot = event.getYaw(); // left right
// float yRot = event.getPitch(); // up down
// TODO: smooth in/out
event.setYaw(angle[1]);
event.setPitch(angle[0]);
}
public static void focus(ScreenBlockEntity screen, BlockSide side) {
KeyboardCamera.tes = screen;
KeyboardCamera.side = side;
}
public static float[] lookAt(Entity entity, EntityAnchorArgument.Anchor pAnchor, Vec3 pTarget) {
Vec3 vec3 = pAnchor.apply(entity);
double d0 = pTarget.x - vec3.x;
double d1 = pTarget.y - vec3.y;
double d2 = pTarget.z - vec3.z;
double d3 = Math.sqrt(d0 * d0 + d2 * d2);
float xr = (Mth.wrapDegrees((float) (-(Mth.atan2(d1, d3) * (double) (180F / (float) Math.PI)))));
float yr = (Mth.wrapDegrees((float) (Mth.atan2(d2, d0) * (double) (180F / (float) Math.PI)) - 90.0F));
return new float[]{xr, yr};
}
protected static int delay = 8;
public static void gameTick(TickEvent.ClientTickEvent event) {
if (mouseStatus[0] || mouseStatus[1]) {
oxCrd = Mth.lerp(0.5, oxCrd, xCrd);
oyCrd = Mth.lerp(0.5, oyCrd, yCrd);
return;
}
if (event.phase.equals(TickEvent.Phase.END)) {
if (side == null) {
delay = 1;
oxCrd = -1;
oyCrd = -1;
xCrd = -1;
yCrd = -1;
nxCrd = -1;
nyCrd = -1;
return;
}
if (!(Minecraft.getInstance().screen instanceof GuiKeyboard)) {
tes = null;
side = null;
return;
}
pollElement();
double anxx = nextX;
double anxy = nextY;
if (
anxx == -1 || anxy == -1 ||
nxCrd == -1 || nyCrd == -1 ||
oxCrd == -1 || oyCrd == -1 ||
xCrd == -1 || yCrd == -1
) {
ScreenData data = tes.getScreen(side);
if (data == null)
return;
anxx = data.size.x / 2.0;
anxy = data.size.y / 2.0;
if (nxCrd == -1) {
oxCrd = xCrd = anxx;
oyCrd = yCrd = anxy;
}
}
nxCrd = anxx;
nyCrd = anxy;
oxCrd = Mth.lerp(0.5, oxCrd, xCrd);
xCrd = Mth.lerp(0.15, xCrd, nxCrd);
oyCrd = Mth.lerp(0.5, oyCrd, yCrd);
yCrd = Mth.lerp(0.15, yCrd, nyCrd);
}
}
}

View File

@ -5,10 +5,16 @@
package net.montoyo.wd.client.gui.controls; package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentContents;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import java.util.function.Supplier;
public class Button extends Control { public class Button extends Control {
protected final net.minecraft.client.gui.components.Button btn; protected final net.minecraft.client.gui.components.Button btn;
@ -31,17 +37,23 @@ public class Button extends Control {
} }
} }
public Button() { public Button() {
btn = new net.minecraft.client.gui.components.Button(0,0, 0, 0, Component.nullToEmpty(null), a -> {}); btn = net.minecraft.client.gui.components.Button.builder(Component.nullToEmpty(""), a -> {})
.bounds(0, 0, 0, 0)
.build();
} }
public Button(String text, int x, int y, int width) { public Button(String text, int x, int y, int width) {
btn = new net.minecraft.client.gui.components.Button(x, y, width, 20, Component.nullToEmpty(text), a -> {}); btn = net.minecraft.client.gui.components.Button.builder(Component.nullToEmpty(text), a -> {})
.bounds(x, y, width, 20)
.build();
} }
public Button(String text, int x, int y) { public Button(String text, int x, int y) {
btn = new net.minecraft.client.gui.components.Button(0, 0, x, y, Component.nullToEmpty(text), a -> {}); btn = net.minecraft.client.gui.components.Button.builder(Component.nullToEmpty(text), a -> {})
.bounds(0, 0, x, y)
.build();
} }
@Override @Override
@ -71,7 +83,8 @@ public class Button extends Control {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
btn.setFGColor(16777215);
btn.render(poseStack, mouseX, mouseY, ptt); btn.render(poseStack, mouseX, mouseY, ptt);
} }
@ -103,18 +116,17 @@ public class Button extends Control {
@Override @Override
public void setPos(int x, int y) { public void setPos(int x, int y) {
btn.x = x; btn.setPosition(x, y);
btn.y = y;
} }
@Override @Override
public int getX() { public int getX() {
return btn.x; return btn.getX();
} }
@Override @Override
public int getY() { public int getY() {
return btn.y; return btn.getY();
} }
public net.minecraft.client.gui.components.Button getMcButton() { public net.minecraft.client.gui.components.Button getMcButton() {
@ -204,8 +216,10 @@ public class Button extends Control {
@Override @Override
public void load(JsonOWrapper json) { public void load(JsonOWrapper json) {
super.load(json); super.load(json);
btn.x = json.getInt("x", 0); btn.setPosition(
btn.y = json.getInt("y", 0); json.getInt("x", 0),
json.getInt("y", 0)
);
btn.setWidth(json.getInt("width", 200)); btn.setWidth(json.getInt("width", 200));
btn.setHeight(json.getInt("height", 20)); btn.setHeight(json.getInt("height", 20));
btn.setMessage(Component.nullToEmpty(tr(json.getString("label", btn.getMessage().getContents().toString())))); btn.setMessage(Component.nullToEmpty(tr(json.getString("label", btn.getMessage().getContents().toString()))));

View File

@ -7,6 +7,9 @@ package net.montoyo.wd.client.gui.controls;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundEvents;
@ -75,20 +78,19 @@ public class CheckBox extends BasicControl {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(visible) { if(visible) {
// GlStateManager.disableAlpha(); // GlStateManager.disableAlpha();
poseStack.pushPose(); poseStack.pose().pushPose();
RenderSystem.setShaderTexture(2, checked ? texChecked : texUnchecked);
RenderSystem.bindTexture(2);
RenderSystem.enableBlend(); RenderSystem.enableBlend();
fillTexturedRect(poseStack, x, y, WIDTH, HEIGHT, 0.0, 0.0, 1.0, 1.0); poseStack.blit(
checked ? texChecked : texUnchecked, x, y, 0, 0, 0, WIDTH, HEIGHT, WIDTH, HEIGHT
);
RenderSystem.disableBlend(); RenderSystem.disableBlend();
RenderSystem.bindTexture(-1);
poseStack.popPose(); poseStack.pose().popPose();
boolean inside = (!disabled && mouseX >= x && mouseX <= x + WIDTH + 2 + labelW && mouseY >= y && mouseY < y + HEIGHT); boolean inside = (!disabled && mouseX >= x && mouseX <= x + WIDTH + 2 + labelW && mouseY >= y && mouseY < y + HEIGHT);
font.draw(poseStack, label, x + WIDTH + 2, y + 4, inside ? 0xFF0080FF : COLOR_WHITE); poseStack.drawString(Minecraft.getInstance().font, label, x + WIDTH + 2, y + 4, inside ? 0xFF0080FF : COLOR_WHITE, false);
} }
} }
@ -134,7 +136,7 @@ public class CheckBox extends BasicControl {
} }
@Override @Override
public void postDraw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void postDraw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(tooltip != null && !disabled && mouseX >= x && mouseX <= x + WIDTH + 2 + labelW && mouseY >= y && mouseY < y + HEIGHT) if(tooltip != null && !disabled && mouseX >= x && mouseX <= x + WIDTH + 2 + labelW && mouseY >= y && mouseY < y + HEIGHT)
parent.drawTooltip(poseStack, tooltip, mouseX, mouseY); parent.drawTooltip(poseStack, tooltip, mouseX, mouseY);
} }

View File

@ -5,6 +5,7 @@
package net.montoyo.wd.client.gui.controls; package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.GuiGraphics;
import net.montoyo.wd.client.gui.loading.GuiLoader; import net.montoyo.wd.client.gui.loading.GuiLoader;
import net.montoyo.wd.client.gui.loading.JsonAWrapper; import net.montoyo.wd.client.gui.loading.JsonAWrapper;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
@ -137,13 +138,13 @@ public abstract class Container extends BasicControl {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(visible) { if(visible) {
mouseX -= x + paddingX; mouseX -= x + paddingX;
mouseY -= y + paddingY; mouseY -= y + paddingY;
poseStack.pushPose(); poseStack.pose().pushPose();
poseStack.translate(x + paddingX, y + paddingY, 0.0); poseStack.pose().translate(x + paddingX, y + paddingY, 0.0);
if(disabled) { if(disabled) {
for(Control ctrl : childs) for(Control ctrl : childs)
@ -153,7 +154,7 @@ public abstract class Container extends BasicControl {
ctrl.draw(poseStack, mouseX, mouseY, ptt); ctrl.draw(poseStack, mouseX, mouseY, ptt);
} }
poseStack.popPose(); poseStack.pose().popPose();
} }
} }
@ -188,4 +189,10 @@ public abstract class Container extends BasicControl {
return null; return null;
} }
@Override
public void unfocus() {
for (Control control : childs) {
control.unfocus();
}
}
} }

View File

@ -8,19 +8,24 @@ import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*; import com.mojang.blaze3d.vertex.*;
import com.mojang.math.Matrix4f;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font; import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.language.I18n; import net.minecraft.client.resources.language.I18n;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.WDScreen; import net.montoyo.wd.client.gui.WDScreen;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.utilities.Bounds; import net.montoyo.wd.utilities.data.Bounds;
import org.joml.Matrix4f;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; import java.util.Arrays;
import static org.lwjgl.opengl.GL11.glEnable;
import static com.mojang.math.Axis.XP;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public abstract class Control { public abstract class Control {
@ -74,6 +79,9 @@ public abstract class Control {
return false; return false;
} }
public void unfocus() {
}
public boolean mouseReleased(double mouseX, double mouseY, int state) { public boolean mouseReleased(double mouseX, double mouseY, int state) {
return false; return false;
} }
@ -90,10 +98,10 @@ public abstract class Control {
return false; return false;
} }
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
} }
public void postDraw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void postDraw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
} }
public void destroy() { public void destroy() {
@ -109,7 +117,7 @@ public abstract class Control {
public abstract int getHeight(); public abstract int getHeight();
public abstract void setPos(int x, int y); public abstract void setPos(int x, int y);
public void fillRect(int x, double y, int w, int h, int color) { public void fillRect(MultiBufferSource.BufferSource source, int x, double y, int w, int h, int color) {
double x1 = (double) x; double x1 = (double) x;
double y1 = (double) y; double y1 = (double) y;
double x2 = (double) (x + w); double x2 = (double) (x + w);
@ -119,34 +127,38 @@ public abstract class Control {
int g = (color >> 8 ) & 0xFF; int g = (color >> 8 ) & 0xFF;
int b = color & 0xFF; int b = color & 0xFF;
RenderSystem.setShaderColor(((float) r) / 255.f, ((float) g) / 255.f, ((float) b) / 255.f, ((float) a) / 255.f); float[] sdrCol = Arrays.copyOf(RenderSystem.getShaderColor(), 4);
RenderSystem.disableTexture(); RenderSystem.setShaderColor(1, 1, 1, 1f);
// RenderSystem.disableTexture();
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
vBuffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION); VertexConsumer consumer = source.getBuffer(RenderType.gui());
vBuffer.vertex(x1, y2, 0.0).endVertex(); consumer.vertex(x1, y2, 0.0).color(r, g, b, a).endVertex();
vBuffer.vertex(x2, y2, 0.0).endVertex(); consumer.vertex(x2, y2, 0.0).color(r, g, b, a).endVertex();
vBuffer.vertex(x2, y1, 0.0).endVertex(); consumer.vertex(x2, y1, 0.0).color(r, g, b, a).endVertex();
vBuffer.vertex(x1, y1, 0.0).endVertex(); consumer.vertex(x1, y1, 0.0).color(r, g, b, a).endVertex();
tessellator.end();
RenderSystem.setShaderColor(sdrCol[0], sdrCol[1], sdrCol[2], sdrCol[3]);
RenderSystem.disableBlend(); RenderSystem.disableBlend();
RenderSystem.enableTexture();glEnable(GL_TEXTURE_2D); // RenderSystem.enableTexture();
} }
public void fillTexturedRect(PoseStack poseStack, int x, int y, int w, int h, double u1, double v1, double u2, double v2) { public void fillTexturedRect(PoseStack poseStack, int x, int y, int w, int h, double u1, double v1, double u2, double v2) {
double x1 = (double) x; float x1 = x;
double y1 = (double) y; float y1 = y;
double x2 = (double) (x + w); float x2 = (x + w);
double y2 = (double) (y + h); float y2 = (y + h);
vBuffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); RenderSystem.setShader(GameRenderer::getPositionColorTexShader);
vBuffer.vertex(x1, y2, 0.0).uv((float) u1, (float) v2).color(255, 255, 255, 255).endVertex(); Matrix4f p = poseStack.last().pose();
vBuffer.vertex(x2, y2, 0.0).uv((float) u2, (float) v2).color(255, 255, 255, 255).endVertex(); vBuffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR_TEX);
vBuffer.vertex(x2, y1, 0.0).uv((float) u2, (float) v1).color(255, 255, 255, 255).endVertex(); vBuffer.vertex(p, x1, y2, 0.0f).color(255, 255, 255, 255).uv((float) u1, (float) v2).endVertex();
vBuffer.vertex(x1, y1, 0.0).uv((float) u1, (float) v1).color(255, 255, 255, 255).endVertex(); vBuffer.vertex(p, x2, y2, 0.0f).color(255, 255, 255, 255).uv((float) u2, (float) v2).endVertex();
tessellator.end(); vBuffer.vertex(p, x2, y1, 0.0f).color(255, 255, 255, 255).uv((float) u2, (float) v1).endVertex();
vBuffer.vertex(p, x1, y1, 0.0f).color(255, 255, 255, 255).uv((float) u1, (float) v1).endVertex();
BufferUploader.drawWithShader(vBuffer.end());
} }
public static void blend(boolean enable) { public static void blend(boolean enable) {
@ -164,11 +176,11 @@ public abstract class Control {
RenderSystem.setShaderTexture(0, resLoc); RenderSystem.setShaderTexture(0, resLoc);
} }
public void drawBorder(PoseStack poseStack, int x, int y, int w, int h, int color) { public void drawBorder(GuiGraphics poseStack, int x, int y, int w, int h, int color) {
drawBorder(poseStack, x, y, w, h, color, 1.0); drawBorder(poseStack, x, y, w, h, color, 1.0);
} }
public void drawBorder(PoseStack poseStack, int x, int y, int w, int h, int color, double sz) { public void drawBorder(GuiGraphics poseStack, int x, int y, int w, int h, int color, double sz) {
double x1 = (double) x; double x1 = (double) x;
double y1 = (double) y; double y1 = (double) y;
double x2 = (double) (x + w); double x2 = (double) (x + w);
@ -178,8 +190,9 @@ public abstract class Control {
int g = (color >> 8 ) & 0xFF; int g = (color >> 8 ) & 0xFF;
int b = color & 0xFF; int b = color & 0xFF;
float[] sdrCol = Arrays.copyOf(RenderSystem.getShaderColor(), 4);
RenderSystem.setShaderColor(((float) r) / 255.f, ((float) g) / 255.f, ((float) b) / 255.f, ((float) a) / 255.f); RenderSystem.setShaderColor(((float) r) / 255.f, ((float) g) / 255.f, ((float) b) / 255.f, ((float) a) / 255.f);
RenderSystem.enableTexture(); // RenderSystem.enableTexture();
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
@ -209,36 +222,46 @@ public abstract class Control {
vBuffer.vertex(x2 - sz, y1, 0.0).endVertex(); vBuffer.vertex(x2 - sz, y1, 0.0).endVertex();
tessellator.end(); tessellator.end();
RenderSystem.setShaderColor(sdrCol[0], sdrCol[1], sdrCol[2], sdrCol[3]);
RenderSystem.disableBlend(); RenderSystem.disableBlend();
RenderSystem.enableTexture(); // RenderSystem.enableTexture();
} }
public PoseStack beginFramebuffer(RenderTarget fbo, float vpW, float vpH) { public GuiGraphics beginFramebuffer(RenderTarget fbo, float vpW, float vpH) {
GuiGraphics tmpGraphics = new GuiGraphics(Minecraft.getInstance(), Minecraft.getInstance().renderBuffers().bufferSource());
fbo.bindWrite(true); fbo.bindWrite(true);
RenderSystem.backupProjectionMatrix(); RenderSystem.backupProjectionMatrix();
RenderSystem.setProjectionMatrix(Matrix4f.orthographic(0.0f, vpW, vpH, 0.0f, -1.0f,1.0f)); RenderSystem.setProjectionMatrix(new Matrix4f().ortho(0.0f, vpW, vpH, 0.0f, -1.0f,1.0f), VertexSorting.ORTHOGRAPHIC_Z);
PoseStack poseStack = RenderSystem.getModelViewStack(); tmpGraphics.pose().last().pose().set(RenderSystem.getModelViewStack().last().pose());
tmpGraphics.pose().last().normal().set(RenderSystem.getModelViewStack().last().normal());
PoseStack poseStack = tmpGraphics.pose();
poseStack.pushPose(); poseStack.pushPose();
poseStack.setIdentity(); poseStack.setIdentity();
// poseStack.mulPose(Vector3f.XP.rotationDegrees(180.0f)); poseStack.mulPose(XP.rotationDegrees(180.0f));
RenderSystem.getModelViewStack().pushPose();
RenderSystem.getModelViewStack().last().pose().set(poseStack.last().pose());
RenderSystem.getModelViewStack().last().normal().set(poseStack.last().normal());
RenderSystem.applyModelViewMatrix(); RenderSystem.applyModelViewMatrix();
if(!fbo.useDepth) if(!fbo.useDepth)
RenderSystem.disableDepthTest(); RenderSystem.disableDepthTest();
return poseStack; return tmpGraphics;
} }
public void endFramebuffer(PoseStack poseStack, RenderTarget fbo) { public void endFramebuffer(GuiGraphics poseStack, RenderTarget fbo) {
if(!fbo.useDepth) if(!fbo.useDepth)
RenderSystem.enableDepthTest(); RenderSystem.enableDepthTest();
RenderSystem.colorMask(true, true, true, true); RenderSystem.colorMask(true, true, true, true);
RenderSystem.restoreProjectionMatrix(); RenderSystem.restoreProjectionMatrix();
poseStack.popPose(); poseStack.pose().popPose();
RenderSystem.getModelViewStack().popPose();
RenderSystem.applyModelViewMatrix(); RenderSystem.applyModelViewMatrix();
fbo.unbindWrite(); fbo.unbindWrite();
mc.getMainRenderTarget().bindWrite(true); mc.getMainRenderTarget().bindWrite(true);

View File

@ -7,12 +7,13 @@ package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.utilities.Bounds; import net.montoyo.wd.utilities.data.Bounds;
import static org.lwjgl.opengl.GL11.*; import java.util.Arrays;
public class ControlGroup extends Container { public class ControlGroup extends Container {
@ -94,22 +95,23 @@ public class ControlGroup extends Container {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
super.draw(poseStack, mouseX, mouseY, ptt); super.draw(poseStack, mouseX, mouseY, ptt);
if(visible) { if(visible) {
poseStack.pushPose(); poseStack.pose().pushPose();
float[] sdrCol = Arrays.copyOf(RenderSystem.getShaderColor(), 4);
RenderSystem.setShaderColor(0.5f, 0.5f, 0.5f, 1.f); RenderSystem.setShaderColor(0.5f, 0.5f, 0.5f, 1.f);
RenderSystem.disableTexture(); // RenderSystem.disableTexture();
RenderSystem.enableBlend(); RenderSystem.enableBlend();
RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
double x1 = (double) x; double x1 = x;
double y1 = (double) y; double y1 = y;
double x2 = (double) (x + width); double x2 = (x + width);
double y2 = (double) (y + height); double y2 = (y + height);
double bp = 4.0; double bp = 4.0;
double lw = (double) labelW; double lw = labelW;
x1 += bp; x1 += bp;
y1 += bp; y1 += bp;
@ -158,12 +160,14 @@ public class ControlGroup extends Container {
vBuffer.vertex(x2 - 1.0, y1, 0.0).endVertex(); vBuffer.vertex(x2 - 1.0, y1, 0.0).endVertex();
tessellator.end(); tessellator.end();
RenderSystem.setShaderColor(sdrCol[0], sdrCol[1], sdrCol[2], sdrCol[3]);
RenderSystem.disableBlend(); RenderSystem.disableBlend();
RenderSystem.enableTexture(); // RenderSystem.enableTexture();
poseStack.popPose(); poseStack.pose().popPose();
if(labelW != 0) if(labelW != 0)
font.drawShadow(poseStack, label, x + 10 + ((int) bp), y, labelColor, labelShadowed); poseStack.drawString(Minecraft.getInstance().font, label, x + 10 + ((int) bp), y, labelColor, labelShadowed);
} }
} }
@ -176,6 +180,13 @@ public class ControlGroup extends Container {
height = bounds.getHeight() + paddingY * 2; height = bounds.getHeight() + paddingY * 2;
} }
@Override
public void unfocus() {
for (Control control : childs) {
control.unfocus();
}
}
@Override @Override
public void load(JsonOWrapper json) { public void load(JsonOWrapper json) {
super.load(json); super.load(json);

View File

@ -6,8 +6,10 @@ package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
public class Icon extends BasicControl { public class Icon extends BasicControl {
@ -44,17 +46,17 @@ public class Icon extends BasicControl {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(texture != null) { if(texture != null) {
poseStack.pushPose(); poseStack.pose().pushPose();
RenderSystem.enableTexture(); // RenderSystem.enableTexture();
RenderSystem.setShaderTexture(1, texture); RenderSystem.setShaderTexture(1, texture);
RenderSystem.bindTexture(1); RenderSystem.bindTexture(1);
RenderSystem.enableBlend(); RenderSystem.enableBlend();
fillTexturedRect(poseStack, x, y, width, height, u1, v1, u2, v2); fillTexturedRect(poseStack.pose(), x, y, width, height, u1, v1, u2, v2);
RenderSystem.disableBlend(); RenderSystem.disableBlend();
RenderSystem.bindTexture(-1); RenderSystem.bindTexture(-1);
poseStack.popPose(); poseStack.pose().popPose();
} }
} }

View File

@ -5,6 +5,8 @@
package net.montoyo.wd.client.gui.controls; package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
public class Label extends BasicControl { public class Label extends BasicControl {
@ -72,9 +74,12 @@ public class Label extends BasicControl {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(visible) if(visible)
font.drawShadow(poseStack, label, x, y, color, shadowed); poseStack.drawString(
Minecraft.getInstance().font,
label, x, y, color, shadowed
);
} }
@Override @Override

View File

@ -9,12 +9,17 @@ import com.mojang.blaze3d.pipeline.TextureTarget;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import java.util.ArrayList; import java.util.ArrayList;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL11.GL_NEAREST;
public class List extends BasicControl { public class List extends BasicControl {
@ -96,19 +101,21 @@ public class List extends BasicControl {
if(fbo != null) if(fbo != null)
fbo.destroyBuffers(); fbo.destroyBuffers();
fbo = new TextureTarget(parent.screen2DisplayX(width), parent.screen2DisplayY(height), false, Minecraft.ON_OSX); fbo = new TextureTarget(parent.screen2DisplayX(width), parent.screen2DisplayY(height), true, Minecraft.ON_OSX);
fbo.setFilterMode(GL_NEAREST); fbo.setFilterMode(GL_NEAREST);
fbo.bindWrite(false); fbo.bindWrite(true);
RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 1.f); //Set alpha to 1 RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 1.f); //Set alpha to 1
RenderSystem.clearDepth(GL_COLOR_BUFFER_BIT); RenderSystem.clearDepth(GL_COLOR_BUFFER_BIT);
fbo.unbindWrite(); fbo.unbindWrite();
mc.getMainRenderTarget().bindWrite(true);
update = true; update = true;
} }
private void renderToFBO() { private void renderToFBO(MultiBufferSource.BufferSource source) {
PoseStack poseStack = beginFramebuffer(fbo, width, height); GuiGraphics graphics = beginFramebuffer(fbo, width, height);
poseStack.pushPose(); GL11.glColorMask(true, true, true, true);
fillRect(0, 0, width, height, COLOR_BLACK); RenderSystem.applyModelViewMatrix();
graphics.fill(0, 0, width, height, COLOR_BLACK);
RenderSystem.setShaderColor(1.f, 1.f, 1.f, 1.f); RenderSystem.setShaderColor(1.f, 1.f, 1.f, 1.f);
int offset = 4 - getYOffset(); int offset = 4 - getYOffset();
@ -120,13 +127,13 @@ public class List extends BasicControl {
break; break;
int color = (i == selected) ? selColor : COLOR_WHITE; int color = (i == selected) ? selColor : COLOR_WHITE;
font.draw(poseStack, content.get(i).text, 4, i * 12 + offset, color); graphics.drawString(font, content.get(i).text, 4, i * 12 + offset, color);
} }
} }
drawBorder(poseStack, 0, 0, width, height, 0xFF808080); graphics.renderOutline(0, 0, width, height, 0xFF808080);
endFramebuffer(poseStack, fbo); graphics.flush();
poseStack.popPose(); endFramebuffer(graphics, fbo);
} }
@Override @Override
@ -311,19 +318,18 @@ public class List extends BasicControl {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics graphics, int mouseX, int mouseY, float ptt) {
if(visible) { if(visible) {
if(update) { if(update) {
renderToFBO(); renderToFBO(graphics.bufferSource());
update = false; update = false;
} }
fbo.bindRead(); //TODO: Make sure is right RenderSystem.setShaderTexture(0, fbo.getColorTextureId());
RenderSystem.setShaderColor(1.f, 1.f, 1.f, 1.f); RenderSystem.setShaderColor(1.f, 1.f, 1.f, 1.f);
fillTexturedRect(poseStack, x, y, width, height, 0.0, 1.0, 1.0, 0.0); fillTexturedRect(graphics.pose(), x, y, width, height, 0.0, 1.0, 1.0, 0.0);
fbo.unbindRead();
fillRect(x + width - 5, y + 1 + scrollPos, 4, scrollSize, (scrolling || isInScrollbar(mouseX, mouseY)) ? 0xFF202020 : 0xFF404040); fillRect(graphics.bufferSource(), x + width - 5, y + 1 + scrollPos, 4, scrollSize, (scrolling || isInScrollbar(mouseX, mouseY)) ? 0xFF202020 : 0xFF404040);
} }
} }

View File

@ -5,6 +5,7 @@
package net.montoyo.wd.client.gui.controls; package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.components.EditBox;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
@ -98,15 +99,18 @@ public class TextField extends Control {
public TextField() { public TextField() {
field = new EditBox(font, 1, 1, 198, 20, Component.nullToEmpty("")); field = new EditBox(font, 1, 1, 198, 20, Component.nullToEmpty(""));
setFocused(false);
} }
public TextField(int x, int y, int width, int height) { public TextField(int x, int y, int width, int height) {
field = new EditBox(font, x + 1, y + 1, width - 2, height - 2, Component.nullToEmpty("")); field = new EditBox(font, x + 1, y + 1, width - 2, height - 2, Component.nullToEmpty(""));
setFocused(false);
} }
public TextField(int x, int y, int width, int height, String text) { public TextField(int x, int y, int width, int height, String text) {
field = new EditBox(font, x + 1, y + 1, width - 2, height - 2, Component.nullToEmpty("")); field = new EditBox(font, x + 1, y + 1, width - 2, height - 2, Component.nullToEmpty(""));
field.setValue(text); field.setValue(text);
setFocused(false);
} }
// TODO: make this public static in CefBrowserOSR // TODO: make this public static in CefBrowserOSR
@ -165,9 +169,18 @@ public class TextField extends Control {
@Override @Override
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
return field.mouseClicked(mouseX, mouseY, mouseButton); if (field.mouseClicked(mouseX, mouseY, mouseButton)) {
setFocused(true);
return true;
}
return false;
} }
@Override
public void unfocus() {
setFocused(false);
}
@Override @Override
public boolean mouseReleased(double mouseX, double mouseY, int state) { public boolean mouseReleased(double mouseX, double mouseY, int state) {
return field.mouseReleased(mouseX, mouseY, state); return field.mouseReleased(mouseX, mouseY, state);
@ -190,7 +203,7 @@ public class TextField extends Control {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
field.render(poseStack, mouseX, mouseY, ptt); field.render(poseStack, mouseX, mouseY, ptt);
} }
@ -241,23 +254,26 @@ public class TextField extends Control {
@Override @Override
public void setPos(int x, int y) { public void setPos(int x, int y) {
field.x = x + 1; field.setPosition(
field.y = y + 1; x + 1,
y + 1
);
} }
@Override @Override
public int getX() { public int getX() {
return field.x - 1; return field.getX() - 1;
} }
@Override @Override
public int getY() { public int getY() {
return field.y - 1; return field.getY() - 1;
} }
public void setDisabled(boolean en) { public void setDisabled(boolean en) {
enabled = !en; enabled = !en;
field.setFocus(enabled); if (!en)
field.setFocused(false);
} }
public boolean isDisabled() { public boolean isDisabled() {
@ -265,12 +281,11 @@ public class TextField extends Control {
} }
public void enable() { public void enable() {
field.setFocus(true);
enabled = true; enabled = true;
} }
public void disable() { public void disable() {
field.setFocus(false); field.setFocused(false);
enabled = false; enabled = false;
} }
@ -291,7 +306,7 @@ public class TextField extends Control {
} }
public void setFocused(boolean val) { public void setFocused(boolean val) {
field.setFocus(val); field.setFocused(val);
} }
public boolean hasFocus() { public boolean hasFocus() {
@ -299,7 +314,7 @@ public class TextField extends Control {
} }
public void focus() { public void focus() {
field.setFocus(true); field.setFocused(true);
} }
public void setTextColor(int color) { public void setTextColor(int color) {
@ -336,8 +351,10 @@ public class TextField extends Control {
@Override @Override
public void load(JsonOWrapper json) { public void load(JsonOWrapper json) {
super.load(json); super.load(json);
field.x = json.getInt("x", 0) + 1; field.setPosition(
field.y = json.getInt("y", 0) + 1; json.getInt("x", 0) + 1,
json.getInt("y", 0) + 1
);
field.setWidth(json.getInt("width", 200) - 2); field.setWidth(json.getInt("width", 200) - 2);
field.setHeight(json.getInt("height", 22) - 2); field.setHeight(json.getInt("height", 22) - 2);
field.setValue(tr(json.getString("text", ""))); field.setValue(tr(json.getString("text", "")));
@ -350,7 +367,7 @@ public class TextField extends Control {
field.setTextColor(textColor); field.setTextColor(textColor);
field.setTextColorUneditable(disabledColor); field.setTextColorUneditable(disabledColor);
field.setFocus(enabled); setFocused(false);
} }
} }

View File

@ -6,6 +6,8 @@ package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
@ -26,23 +28,23 @@ public class UpgradeGroup extends BasicControl {
} }
@Override @Override
public void draw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void draw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(upgrades != null) { if(upgrades != null) {
int x = this.x; int x = this.x;
for(ItemStack is: upgrades) { for(ItemStack is: upgrades) {
if(is == overStack && !disabled) if(is == overStack && !disabled)
fillRect(x, y, 16, 16, 0x80FF0000); fillRect(poseStack.bufferSource(), x, y, 16, 16, 0x80FF0000);
renderItem.renderAndDecorateItem(mc.player, is, x, y, 0); poseStack.renderItem(is, x, y);
renderItem.renderAndDecorateItem(is, font.lineHeight, x, y); //TODO is lineHeight right? poseStack.renderItemDecorations(font, is, x, y);
x += 18; x += 18;
} }
} }
} }
@Override @Override
public void postDraw(PoseStack poseStack, int mouseX, int mouseY, float ptt) { public void postDraw(GuiGraphics poseStack, int mouseX, int mouseY, float ptt) {
if(overStack != null) if(overStack != null)
parent.drawItemStackTooltip(poseStack, overStack, mouseX, mouseY); parent.drawItemStackTooltip(poseStack, overStack, mouseX, mouseY);
} }

View File

@ -6,7 +6,7 @@ package net.montoyo.wd.client.gui.controls;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
import net.montoyo.wd.utilities.VideoType; import net.montoyo.wd.utilities.VideoType;
import java.net.MalformedURLException; import java.net.MalformedURLException;

View File

@ -6,8 +6,6 @@ package net.montoyo.wd.client.renderers;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*; import com.mojang.blaze3d.vertex.*;
import com.mojang.math.Matrix4f;
import com.mojang.math.Vector3f;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
@ -18,8 +16,11 @@ import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.init.ItemInit; import net.montoyo.wd.registry.ItemRegistry;
import net.montoyo.wd.item.ItemLaserPointer; import net.montoyo.wd.item.ItemLaserPointer;
import org.joml.Matrix4f;
import static com.mojang.math.Axis.*;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public final class LaserPointerRenderer implements IItemRenderer { public final class LaserPointerRenderer implements IItemRenderer {
@ -38,14 +39,14 @@ public final class LaserPointerRenderer implements IItemRenderer {
ClientProxy.mouseOn || ClientProxy.mouseOn ||
ItemLaserPointer.isOn() ItemLaserPointer.isOn()
) && ) &&
mc.player.getItemInHand(InteractionHand.MAIN_HAND).getItem().equals(ItemInit.LASER_POINTER.get()) && mc.player.getItemInHand(InteractionHand.MAIN_HAND).getItem().equals(ItemRegistry.LASER_POINTER.get()) &&
(mc.hitResult == null || mc.hitResult.getType() == HitResult.Type.BLOCK || mc.hitResult.getType() == HitResult.Type.MISS); (mc.hitResult == null || mc.hitResult.getType() == HitResult.Type.BLOCK || mc.hitResult.getType() == HitResult.Type.MISS);
} }
@Override @Override
public boolean render(PoseStack poseStack, ItemStack is, float handSideSign, float swingProgress, float equipProgress, MultiBufferSource multiBufferSource, int packedLight) { public boolean render(PoseStack poseStack, ItemStack is, float handSideSign, float swingProgress, float equipProgress, MultiBufferSource multiBufferSource, int packedLight) {
RenderSystem.disableCull(); RenderSystem.disableCull();
RenderSystem.disableTexture(); // RenderSystem.disableTexture();
RenderSystem.enableDepthTest(); RenderSystem.enableDepthTest();
RenderSystem.enableBlend(); RenderSystem.enableBlend();
@ -61,12 +62,12 @@ public final class LaserPointerRenderer implements IItemRenderer {
poseStack.pushPose(); poseStack.pushPose();
poseStack.translate(handSideSign * -0.4f * sinSqrtSwingProg1, (float) (0.2f * Math.sin(sqrtSwingProg * PI * 2.0f)), (float) (-0.2f * Math.sin(swingProgress * PI))); poseStack.translate(handSideSign * -0.4f * sinSqrtSwingProg1, (float) (0.2f * Math.sin(sqrtSwingProg * PI * 2.0f)), (float) (-0.2f * Math.sin(swingProgress * PI)));
poseStack.translate(handSideSign * 0.56f, -0.52f - equipProgress * 0.6f, -0.72f); poseStack.translate(handSideSign * 0.56f, -0.52f - equipProgress * 0.6f, -0.72f);
poseStack.mulPose(Vector3f.YP.rotationDegrees((float) (handSideSign * (45.0f - Math.sin(swingProgress * swingProgress * PI) * 20.0f)))); poseStack.mulPose(YP.rotationDegrees((float) (handSideSign * (45.0f - Math.sin(swingProgress * swingProgress * PI) * 20.0f))));
poseStack.mulPose(Vector3f.ZP.rotationDegrees(handSideSign * sinSqrtSwingProg1 * -20.0f)); poseStack.mulPose(ZP.rotationDegrees(handSideSign * sinSqrtSwingProg1 * -20.0f));
poseStack.mulPose(Vector3f.XP.rotationDegrees(sinSqrtSwingProg1 * -80.0f)); poseStack.mulPose(XP.rotationDegrees(sinSqrtSwingProg1 * -80.0f));
poseStack.mulPose(Vector3f.YP.rotationDegrees(handSideSign * -30.0f)); poseStack.mulPose(YP.rotationDegrees(handSideSign * -30.0f));
poseStack.translate(0.0f, 0.2f, 0.0f); poseStack.translate(0.0f, 0.2f, 0.0f);
poseStack.mulPose(Vector3f.XP.rotationDegrees(10.0f)); poseStack.mulPose(XP.rotationDegrees(10.0f));
poseStack.scale(1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f); poseStack.scale(1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f);
var matrix = poseStack.last().pose(); var matrix = poseStack.last().pose();
@ -98,7 +99,7 @@ public final class LaserPointerRenderer implements IItemRenderer {
RenderSystem.disableBlend(); RenderSystem.disableBlend();
RenderSystem.disableDepthTest(); RenderSystem.disableDepthTest();
RenderSystem.enableTexture(); //Fix for shitty minecraft fire // RenderSystem.enableTexture(); //Fix for shitty minecraft fire
RenderSystem.enableCull(); RenderSystem.enableCull();
poseStack.popPose(); poseStack.popPose();

View File

@ -4,10 +4,11 @@
package net.montoyo.wd.client.renderers; package net.montoyo.wd.client.renderers;
import com.cinemamod.mcef.MCEFBrowser;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.*;
import com.mojang.math.Vector3f;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.entity.player.PlayerRenderer; import net.minecraft.client.renderer.entity.player.PlayerRenderer;
@ -22,11 +23,13 @@ import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.config.ClientConfig; import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.item.ItemMinePad2; import net.montoyo.wd.item.ItemMinePad2;
import static com.mojang.math.Axis.*;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public final class MinePadRenderer implements IItemRenderer { public final class MinePadRenderer implements IItemRenderer {
private static final float PI = (float) Math.PI; private static final float PI = (float) Math.PI;
private final Minecraft mc = Minecraft.getInstance(); private final Minecraft mc = Minecraft.getInstance();
private final ResourceLocation tex = new ResourceLocation("webdisplays", "textures/models/minepad.png"); private final ResourceLocation tex = new ResourceLocation("webdisplays", "textures/item/model/minepad.png");
private final ModelMinePad model = new ModelMinePad(); private final ModelMinePad model = new ModelMinePad();
private final ClientProxy clientProxy = (ClientProxy) WebDisplays.PROXY; private final ClientProxy clientProxy = (ClientProxy) WebDisplays.PROXY;
@ -76,18 +79,18 @@ public final class MinePadRenderer implements IItemRenderer {
stack.pushPose(); stack.pushPose();
stack.translate(handSideSign * -0.4f * sinSqrtSwingProg1, 0.2f * sinSqrtSwingProg2, -0.2f * sinSwingProg1); stack.translate(handSideSign * -0.4f * sinSqrtSwingProg1, 0.2f * sinSqrtSwingProg2, -0.2f * sinSwingProg1);
stack.translate(handSideSign * 0.56f, -0.52f - equipProgress * 0.6f, -0.72f); stack.translate(handSideSign * 0.56f, -0.52f - equipProgress * 0.6f, -0.72f);
stack.mulPose(Vector3f.YP.rotationDegrees(handSideSign * (45.0f - sinSwingProg2 * 20.0f))); stack.mulPose(YP.rotationDegrees(handSideSign * (45.0f - sinSwingProg2 * 20.0f)));
stack.mulPose(Vector3f.ZP.rotationDegrees(handSideSign * sinSqrtSwingProg1 * -20.0f)); stack.mulPose(ZP.rotationDegrees(handSideSign * sinSqrtSwingProg1 * -20.0f));
stack.mulPose(Vector3f.XP.rotationDegrees(sinSqrtSwingProg1 * -80.0f)); stack.mulPose(XP.rotationDegrees(sinSqrtSwingProg1 * -80.0f));
stack.mulPose(Vector3f.YP.rotationDegrees(handSideSign * -45.0f)); stack.mulPose(YP.rotationDegrees(handSideSign * -45.0f));
if (sideHold) { if (sideHold) {
stack.translate(0.0f, 0.0f, -0.2f); stack.translate(0.0f, 0.0f, -0.2f);
stack.mulPose(Vector3f.YP.rotationDegrees(20.0f * -handSideSign)); stack.mulPose(YP.rotationDegrees(20.0f * -handSideSign));
float total = 0.475f; float total = 0.475f;
float off = -0.025f; // gotta love magic numbers float off = -0.025f; // gotta love magic numbers
stack.translate(-(total - off) + (off * handSideSign), -0.1f, 0.0f); stack.translate(-(total - off) + (off * handSideSign), -0.1f, 0.0f);
stack.mulPose(Vector3f.ZP.rotationDegrees(1.0f)); stack.mulPose(ZP.rotationDegrees(1.0f));
} else if (handSideSign >= 0) // right hand } else if (handSideSign >= 0) // right hand
stack.translate(-1.065f, 0.0f, 0.0f); stack.translate(-1.065f, 0.0f, 0.0f);
else // left hand else // left hand
@ -112,8 +115,20 @@ public final class MinePadRenderer implements IItemRenderer {
double y2 = 14.0 / 32.0 + 0.002; double y2 = 14.0 / 32.0 + 0.002;
stack.translate(0.063f, 0.28f, 0.001f); stack.translate(0.063f, 0.28f, 0.001f);
RenderSystem.setShaderTexture(0, tex); // RenderSystem.setShaderTexture(0, tex);
pd.view.draw(stack, x1, y1, x2, y2);
RenderSystem.disableDepthTest();
RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
RenderSystem.setShaderTexture(0, ((MCEFBrowser) pd.view).getRenderer().getTextureID());
Tesselator t = Tesselator.getInstance();
BufferBuilder buffer = t.getBuilder();
buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
buffer.vertex(stack.last().pose(), (float) x1, (float) y1, 0.0f).uv(0.0F, 1.0F).color(255, 255, 255, 255).endVertex();
buffer.vertex(stack.last().pose(), (float) x2, (float) y1, 0.0f).uv(1.0F, 1.0F).color(255, 255, 255, 255).endVertex();
buffer.vertex(stack.last().pose(), (float) x2, (float) y2, 0.0f).uv(1.0F, 0.0F).color(255, 255, 255, 255).endVertex();
buffer.vertex(stack.last().pose(), (float) x1, (float) y2, 0.0f).uv(0.0F, 0.0F).color(255, 255, 255, 255).endVertex();
t.end();
RenderSystem.enableDepthTest();
} }
} }
@ -129,13 +144,13 @@ public final class MinePadRenderer implements IItemRenderer {
float tz = -0.4f * sinSwingProg1; float tz = -0.4f * sinSwingProg1;
stack.translate(handSideSign * (tx + 0.64000005f), ty - 0.6f - equipProgress * 0.6f, tz - 0.71999997f); stack.translate(handSideSign * (tx + 0.64000005f), ty - 0.6f - equipProgress * 0.6f, tz - 0.71999997f);
stack.mulPose(Vector3f.YP.rotationDegrees(handSideSign * 45.0f)); stack.mulPose(YP.rotationDegrees(handSideSign * 45.0f));
stack.mulPose(Vector3f.YP.rotationDegrees(handSideSign * sinSqrtSwingProg1 * 70.0f)); stack.mulPose(YP.rotationDegrees(handSideSign * sinSqrtSwingProg1 * 70.0f));
stack.mulPose(Vector3f.ZP.rotationDegrees(handSideSign * sinSwingProg2 * -20.0f)); stack.mulPose(ZP.rotationDegrees(handSideSign * sinSwingProg2 * -20.0f));
stack.translate(-handSideSign, 3.6f, 3.5f); stack.translate(-handSideSign, 3.6f, 3.5f);
stack.mulPose(Vector3f.ZP.rotationDegrees(handSideSign * 120.0f)); stack.mulPose(ZP.rotationDegrees(handSideSign * 120.0f));
stack.mulPose(Vector3f.XP.rotationDegrees(200.0f)); stack.mulPose(XP.rotationDegrees(200.0f));
stack.mulPose(Vector3f.YP.rotationDegrees(handSideSign * -135.0f)); stack.mulPose(YP.rotationDegrees(handSideSign * -135.0f));
stack.translate(handSideSign * 5.6f, 0.0f, 0.0f); stack.translate(handSideSign * 5.6f, 0.0f, 0.0f);
PlayerRenderer playerRenderer = (PlayerRenderer) mc.getEntityRenderDispatcher().getRenderer(mc.player); PlayerRenderer playerRenderer = (PlayerRenderer) mc.getEntityRenderDispatcher().getRenderer(mc.player);

View File

@ -6,7 +6,6 @@ package net.montoyo.wd.client.renderers;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*; import com.mojang.blaze3d.vertex.*;
import com.mojang.math.Matrix4f;
import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
@ -15,6 +14,7 @@ import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import org.joml.Matrix4f;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public final class ModelMinePad { public final class ModelMinePad {
@ -48,7 +48,7 @@ public final class ModelMinePad {
float z = 0; float z = 0;
VertexConsumer consumer = buffers.getBuffer(RenderType.entityCutout(new ResourceLocation("webdisplays:textures/models/minepad_item.png"))); VertexConsumer consumer = buffers.getBuffer(RenderType.entityCutout(new ResourceLocation("webdisplays:textures/item/model/minepad_item.png")));
consumer.vertex(positionMatrix, (float) x1, (float) y1 - padding, z).color(255, 255, 255, 255).uv(1f / width, 12f / height).overlayCoords(OverlayTexture.NO_OVERLAY).uv2(LightTexture.FULL_BRIGHT).normal(0.25f, 0.5f, 1).endVertex(); consumer.vertex(positionMatrix, (float) x1, (float) y1 - padding, z).color(255, 255, 255, 255).uv(1f / width, 12f / height).overlayCoords(OverlayTexture.NO_OVERLAY).uv2(LightTexture.FULL_BRIGHT).normal(0.25f, 0.5f, 1).endVertex();
consumer.vertex(positionMatrix, (float) x2, (float) y1 - padding, z).color(255, 255, 255, 255).uv(19f / width, 12f / height).overlayCoords(OverlayTexture.NO_OVERLAY).uv2(LightTexture.FULL_BRIGHT).normal(0.25f, 0.5f, 1).endVertex(); consumer.vertex(positionMatrix, (float) x2, (float) y1 - padding, z).color(255, 255, 255, 255).uv(19f / width, 12f / height).overlayCoords(OverlayTexture.NO_OVERLAY).uv2(LightTexture.FULL_BRIGHT).normal(0.25f, 0.5f, 1).endVertex();

View File

@ -19,9 +19,9 @@ import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.model.data.ModelProperty; import net.minecraftforge.client.model.data.ModelProperty;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Vector3f; import net.montoyo.wd.utilities.math.Vector3f;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;

View File

@ -21,7 +21,7 @@ import java.util.function.Function;
public class ScreenModelLoader implements IGeometryLoader<ScreenModelLoader.ScreenModelGeometry> { public class ScreenModelLoader implements IGeometryLoader<ScreenModelLoader.ScreenModelGeometry> {
public static final ResourceLocation SCREEN_LOADER = new ResourceLocation("webdisplays", "screen_loader"); public static final ResourceLocation SCREEN_LOADER = new ResourceLocation("webdisplays", "screen_loader");
public static final ResourceLocation SCREEN_SIDE = new ResourceLocation("webdisplays", "blocks/screen"); public static final ResourceLocation SCREEN_SIDE = new ResourceLocation("webdisplays", "block/screen");
private static final ResourceLocation[] SIDES = new ResourceLocation[16]; private static final ResourceLocation[] SIDES = new ResourceLocation[16];
public static final Material[] MATERIALS_SIDES = new Material[16]; public static final Material[] MATERIALS_SIDES = new Material[16];
@ -39,16 +39,27 @@ public class ScreenModelLoader implements IGeometryLoader<ScreenModelLoader.Scre
} }
public static class ScreenModelGeometry implements IUnbakedGeometry<ScreenModelGeometry> { public static class ScreenModelGeometry implements IUnbakedGeometry<ScreenModelGeometry> {
@Override @Override
public BakedModel bake(IGeometryBakingContext iGeometryBakingContext, ModelBakery arg, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides itemOverrides, ResourceLocation arg4) { public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) {
return new ScreenBaker(modelState, spriteGetter, itemOverrides, iGeometryBakingContext.getTransforms()); return new ScreenBaker(modelState, spriteGetter, overrides, context.getTransforms());
} }
// @Override
// public void resolveParents(Function<ResourceLocation, UnbakedModel> modelGetter, IGeometryBakingContext context) {
// IUnbakedGeometry.super.resolveParents(modelGetter, context);
// }
// @Override
// public Set<String> getConfigurableComponentNames() {
// return IUnbakedGeometry.super.getConfigurableComponentNames();
// }
@Override // TODO: ?
public Collection<Material> getMaterials(IGeometryBakingContext iGeometryBakingContext, Function<ResourceLocation, UnbakedModel> function, Set<Pair<String, String>> set) { // @Override
return Arrays.asList(MATERIALS_SIDES); // public Collection<Material> getMaterials(IGeometryBakingContext iGeometryBakingContext, Function<ResourceLocation, UnbakedModel> function, Set<Pair<String, String>> set) {
} // return Arrays.asList(MATERIALS_SIDES);
// }
} }
} }

View File

@ -4,26 +4,30 @@
package net.montoyo.wd.client.renderers; package net.montoyo.wd.client.renderers;
import com.cinemamod.mcef.MCEFBrowser;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*; import com.mojang.blaze3d.vertex.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.utilities.Vector3f; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.utilities.math.Vector3f;
import net.montoyo.wd.utilities.math.Vector3i;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static com.mojang.math.Vector3f.*; import static com.mojang.math.Axis.*;
public class ScreenRenderer implements BlockEntityRenderer<TileEntityScreen> { public class ScreenRenderer implements BlockEntityRenderer<ScreenBlockEntity> {
public ScreenRenderer() { public ScreenRenderer() {
} }
public static class ScreenRendererProvider implements BlockEntityRendererProvider<TileEntityScreen> { public static class ScreenRendererProvider implements BlockEntityRendererProvider<ScreenBlockEntity> {
@Override @Override
public @NotNull BlockEntityRenderer<TileEntityScreen> create(@NotNull Context arg) { public @NotNull BlockEntityRenderer<ScreenBlockEntity> create(@NotNull Context arg) {
return new ScreenRenderer(); return new ScreenRenderer();
} }
} }
@ -33,19 +37,22 @@ public class ScreenRenderer implements BlockEntityRenderer<TileEntityScreen> {
private final Vector3f tmpf = new Vector3f(); private final Vector3f tmpf = new Vector3f();
@Override @Override
public void render(TileEntityScreen te, float partialTick, @NotNull PoseStack poseStack, @NotNull MultiBufferSource bufferSource, int packedLight, int packedOverlay) { public void render(ScreenBlockEntity te, float partialTick, @NotNull PoseStack poseStack, @NotNull MultiBufferSource bufferSource, int packedLight, int packedOverlay) {
if (!te.isLoaded()) if (!te.isLoaded())
return; return;
//Disable lighting //Disable lighting
RenderSystem.enableTexture(); // RenderSystem.enableTexture();
// RenderSystem.disableCull(); // RenderSystem.disableCull();
RenderSystem.disableBlend(); RenderSystem.disableBlend();
for (int i = 0; i < te.screenCount(); i++) { for (int i = 0; i < te.screenCount(); i++) {
TileEntityScreen.Screen scr = te.getScreen(i); ScreenData scr = te.getScreen(i);
if (scr.browser == null) { if (scr.browser == null) {
scr.createBrowser(true); double dist = WebDisplays.PROXY.distanceTo(te, Minecraft.getInstance().getEntityRenderDispatcher().camera.getPosition());
if (dist <= WebDisplays.INSTANCE.loadDistance2 * 16)
scr.createBrowser(te, true);
else continue;
} }
// TODO: manually backface cull the screens // TODO: manually backface cull the screens
@ -118,7 +125,7 @@ public class ScreenRenderer implements BlockEntityRenderer<TileEntityScreen> {
//TODO: don't use tesselator //TODO: don't use tesselator
RenderSystem.enableDepthTest(); RenderSystem.enableDepthTest();
RenderSystem.setShader(GameRenderer::getPositionTexColorShader); RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
RenderSystem._setShaderTexture(0, scr.browser.getTextureID()); RenderSystem._setShaderTexture(0, ((MCEFBrowser) scr.browser).getRenderer().getTextureID());
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
builder.vertex(poseStack.last().pose(), -sw, -sh, 0.505f).uv(0.f, 1.f).color(1.f, 1.f, 1.f, 1.f).endVertex(); builder.vertex(poseStack.last().pose(), -sw, -sh, 0.505f).uv(0.f, 1.f).color(1.f, 1.f, 1.f, 1.f).endVertex();

View File

@ -38,7 +38,7 @@ public class ClientConfig {
"Due to how web browsers work however, the larger this value is, the smaller text is", "Due to how web browsers work however, the larger this value is, the smaller text is",
"Also, higher values will invariably lag more", "Also, higher values will invariably lag more",
"A good goto value for this would be the height of your monitor, in pixels", "A good goto value for this would be the height of your monitor, in pixels",
"A standard monitor is (at least currently) 1080" "A standard monitor is (at least currently) 1080",
}) })
@Translation("config.webdisplays.pad_res") @Translation("config.webdisplays.pad_res")
@IntRange(minV = 0, maxV = Integer.MAX_VALUE) @IntRange(minV = 0, maxV = Integer.MAX_VALUE)
@ -53,55 +53,70 @@ public class ClientConfig {
@Translation("config.webdisplays.side_pad") @Translation("config.webdisplays.side_pad")
@Default(valueBoolean = true) @Default(valueBoolean = true)
public static boolean sidePad = true; public static boolean sidePad = true;
@Name("switch_buttons")
@Comment("If the left and right buttons should be swapped when using a laser")
@Translation("config.webdisplays.switch_buttons")
@DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
@Default(valueD = 30)
public static boolean switchButtons = true;
@Comment({ @Comment({
"AutoVolume makes audio fade off based on distance", "Options relating to input handling"
"Currently, this seems to not work"
}) })
@CFGSegment("auto_volume") @CFGSegment("input")
public static class AutoVolumeControl { public static class Input {
@Name("enabled") @Name("keyboard_camera")
@Comment("Whether or not auto volume should be enabled") @Comment({
@Translation("config.webdisplays.auto_vol") "If this is on, then the camera will try to focus on the selected element while a keyboard is in use",
"Elsewise, it'll try to focus on the center of the screen",
})
@Translation("config.webdisplays.keyboard_camera")
@Default(valueBoolean = true) @Default(valueBoolean = true)
public static boolean enableAutoVolume = true; public static boolean keyboardCamera = true;
@Name("youtube_volume") @Name("switch_buttons")
@Comment("How loud youtube should be by default") @Comment("If the left and right buttons should be swapped when using a laser")
@Translation("config.webdisplays.yt_vol") @Translation("config.webdisplays.switch_buttons")
@DoubleRange(minV = 0, maxV = 100)
@Default(valueD = 100)
public static double ytVolume = 100.0;
@Name("dist0")
@Comment("Distance after which you can't hear anything (in blocks)")
@Translation("config.webdisplays.d0")
@DoubleRange(minV = 0, maxV = Double.MAX_VALUE) @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
@Default(valueD = 30) @Default(valueD = 30)
public static double dist0 = 30.0; public static boolean switchButtons = true;
@Name("dist100")
@Comment("Distance after which the sound starts dropping (in blocks)")
@Translation("config.webdisplays.d100")
@DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
@Default(valueD = 10)
public static double dist100 = 10.0;
} }
// @Comment({
// "AutoVolume makes audio fade off based on distance",
// "Currently, this seems to not work"
// })
// @CFGSegment("auto_volume")
// public static class AutoVolumeControl {
// @Name("enabled")
// @Comment("Whether or not auto volume should be enabled")
// @Translation("config.webdisplays.auto_vol")
// @Default(valueBoolean = true)
// public static boolean enableAutoVolume = true;
//
// @Name("youtube_volume")
// @Comment("How loud youtube should be by default")
// @Translation("config.webdisplays.yt_vol")
// @DoubleRange(minV = 0, maxV = 100)
// @Default(valueD = 100)
// public static double ytVolume = 100.0;
//
// @Name("dist0")
// @Comment("Distance after which you can't hear anything (in blocks)")
// @Translation("config.webdisplays.d0")
// @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
// @Default(valueD = 30)
// public static double dist0 = 30.0;
//
// @Name("dist100")
// @Comment("Distance after which the sound starts dropping (in blocks)")
// @Translation("config.webdisplays.d100")
// @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
// @Default(valueD = 10)
// public static double dist100 = 10.0;
// }
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static void postLoad() { public static void postLoad() {
if (unloadDistance < loadDistance + 2.0) if (unloadDistance < loadDistance + 2.0)
unloadDistance = loadDistance + 2.0; unloadDistance = loadDistance + 2.0;
if (AutoVolumeControl.dist0 < AutoVolumeControl.dist100 + 0.1) // if (AutoVolumeControl.dist0 < AutoVolumeControl.dist100 + 0.1)
AutoVolumeControl.dist0 = AutoVolumeControl.dist100 + 0.1; // AutoVolumeControl.dist0 = AutoVolumeControl.dist100 + 0.1;
// cache pad resolution // cache pad resolution
WebDisplays.INSTANCE.padResY = padResolution; WebDisplays.INSTANCE.padResY = padResolution;
@ -111,8 +126,8 @@ public class ClientConfig {
WebDisplays.INSTANCE.unloadDistance2 = unloadDistance * unloadDistance; WebDisplays.INSTANCE.unloadDistance2 = unloadDistance * unloadDistance;
WebDisplays.INSTANCE.loadDistance2 = loadDistance * loadDistance; WebDisplays.INSTANCE.loadDistance2 = loadDistance * loadDistance;
WebDisplays.INSTANCE.ytVolume = (float) AutoVolumeControl.ytVolume; // WebDisplays.INSTANCE.ytVolume = (float) AutoVolumeControl.ytVolume;
WebDisplays.INSTANCE.avDist100 = (float) AutoVolumeControl.dist100; // WebDisplays.INSTANCE.avDist100 = (float) AutoVolumeControl.dist100;
WebDisplays.INSTANCE.avDist0 = (float) AutoVolumeControl.dist0; // WebDisplays.INSTANCE.avDist0 = (float) AutoVolumeControl.dist0;
} }
} }

View File

@ -18,13 +18,18 @@ public class CommonConfig {
public static void init() { public static void init() {
// loads the class // loads the class
} }
@Name("hard_recipes") @Name("hard_recipes")
@Comment("If true, breaking the minePad is required to craft upgrades.") @Comment("If true, breaking the minePad is required to craft upgrades.")
@Translation("config.webdisplays.hard_recipes") @Translation("config.webdisplays.hard_recipes")
@IntRange(minV = 0, maxV = Integer.MAX_VALUE)
@Default(valueBoolean = true) @Default(valueBoolean = true)
public static boolean hardRecipes = true; public static boolean hardRecipes = true;
@Name("join_message")
@Comment("Whether or not webdisplays should thank the user for using the mod")
@Translation("config.webdisplays.join_message")
@Default(valueBoolean = true)
public static boolean joinMessage = true;
@Name("disable_ownership_thief") @Name("disable_ownership_thief")
@Comment("If true, the ownership thief item will be disabled") @Comment("If true, the ownership thief item will be disabled")

View File

@ -8,8 +8,8 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import java.util.Objects; import java.util.Objects;
import java.util.function.Function; import java.util.function.Function;
@ -22,9 +22,9 @@ public abstract class ScreenControl {
} }
public abstract void write(FriendlyByteBuf buf); public abstract void write(FriendlyByteBuf buf);
public abstract void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException; public abstract void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public abstract void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx); public abstract void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx);
public void checkPerms(int perms, Function<Integer, Boolean> checker, ServerPlayer player) throws MissingPermissionException { public void checkPerms(int perms, Function<Integer, Boolean> checker, ServerPlayer player) throws MissingPermissionException {
if (!checker.apply(perms)) { if (!checker.apply(perms)) {

View File

@ -8,8 +8,8 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.builtin.*; import net.montoyo.wd.controls.builtin.*;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -32,7 +32,7 @@ public class ScreenControlRegistry {
if (FMLEnvironment.dist.isClient()) { if (FMLEnvironment.dist.isClient()) {
boolean shouldThrow = false; boolean shouldThrow = false;
try { try {
Method m = type.clazz.getMethod("handleClient", BlockPos.class, BlockSide.class, TileEntityScreen.class, NetworkEvent.Context.class); Method m = type.clazz.getMethod("handleClient", BlockPos.class, BlockSide.class, ScreenBlockEntity.class, NetworkEvent.Context.class);
OnlyIn onlyIn = m.getAnnotation(OnlyIn.class); OnlyIn onlyIn = m.getAnnotation(OnlyIn.class);
if (onlyIn == null) shouldThrow = true; if (onlyIn == null) shouldThrow = true;
Dist d = onlyIn.value(); // idc if this throws, lol Dist d = onlyIn.value(); // idc if this throws, lol
@ -63,6 +63,7 @@ public class ScreenControlRegistry {
register(ManageRightsAndUpdgradesControl.id, new ScreenControlType<>(ManageRightsAndUpdgradesControl.class, ManageRightsAndUpdgradesControl::new)); register(ManageRightsAndUpdgradesControl.id, new ScreenControlType<>(ManageRightsAndUpdgradesControl.class, ManageRightsAndUpdgradesControl::new));
register(ClickControl.id, new ScreenControlType<>(ClickControl.class, ClickControl::new)); register(ClickControl.id, new ScreenControlType<>(ClickControl.class, ClickControl::new));
register(OwnerControl.id, new ScreenControlType<>(OwnerControl.class, OwnerControl::new)); register(OwnerControl.id, new ScreenControlType<>(OwnerControl.class, OwnerControl::new));
register(TurnOffControl.id, new ScreenControlType<>(TurnOffControl.class, (buf) -> TurnOffControl.INSTANCE));
} }
public static ScreenControl parse(FriendlyByteBuf buf) { public static ScreenControl parse(FriendlyByteBuf buf) {

View File

@ -9,8 +9,8 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import java.util.function.Function; import java.util.function.Function;
@ -35,7 +35,7 @@ public class AutoVolumeControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
// I feel like there's probably a better permission category // I feel like there's probably a better permission category
checkPerms(ScreenRights.MANAGE_UPGRADES, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.MANAGE_UPGRADES, permissionChecker, ctx.getSender());
tes.setAutoVolume(side, autoVol); tes.setAutoVolume(side, autoVol);
@ -43,7 +43,7 @@ public class AutoVolumeControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
tes.setAutoVolume(side, autoVol); tes.setAutoVolume(side, autoVol);
} }
} }

View File

@ -8,9 +8,9 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Vector2i; import net.montoyo.wd.utilities.math.Vector2i;
import java.util.function.Function; import java.util.function.Function;
@ -47,13 +47,13 @@ public class ClickControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
throw new RuntimeException("Cannot call click control on server"); throw new RuntimeException("Cannot call click control on server");
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
if (coord != null) if (coord != null)
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1); tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1);

View File

@ -10,9 +10,8 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.JSServerRequest; import net.montoyo.wd.core.JSServerRequest;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Log;
import java.util.function.Function; import java.util.function.Function;
@ -49,15 +48,15 @@ public class JSRequestControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
if (reqType == null || data == null) Log.warning("Caught invalid JS request from player %s (UUID %s)", player.getName(), player.getGameProfile().getId().toString()); // if (reqType == null || data == null) Log.warning("Caught invalid JS request from player %s (UUID %s)", player.getName(), player.getGameProfile().getId().toString());
else tes.handleJSRequest(player, side, reqId, reqType, data); // else tes.handleJSRequest(player, side, reqId, reqType, data);
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
throw new RuntimeException("TODO"); throw new RuntimeException("TODO");
} }
} }

View File

@ -9,8 +9,8 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import java.util.function.Function; import java.util.function.Function;
@ -39,14 +39,14 @@ public class KeyTypedControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender());
tes.type(side, text, soundPos, ctx.getSender()); tes.type(side, text, soundPos, ctx.getSender());
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
tes.type(side, text, soundPos); tes.type(side, text, soundPos);
} }
} }

View File

@ -9,9 +9,9 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Vector2i; import net.montoyo.wd.utilities.math.Vector2i;
import java.util.function.Function; import java.util.function.Function;
@ -54,7 +54,7 @@ public class LaserControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
// feel like this makes sense, but I wanna get opinions first // feel like this makes sense, but I wanna get opinions first
// checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender()); // checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender());
ServerPlayer sender = ctx.getSender(); ServerPlayer sender = ctx.getSender();
@ -67,7 +67,7 @@ public class LaserControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
if (coord != null) if (coord != null)
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1); tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1);

View File

@ -11,8 +11,9 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.data.BlockSide;
import java.util.function.Function; import java.util.function.Function;
@ -79,7 +80,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
switch (type) { switch (type) {
case UPGRADES -> { case UPGRADES -> {
@ -89,7 +90,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
else tes.removeUpgrade(side, toRemove, player); else tes.removeUpgrade(side, toRemove, player);
} }
case RIGHTS -> { case RIGHTS -> {
TileEntityScreen.Screen scr = tes.getScreen(side); ScreenData scr = tes.getScreen(side);
int fr = scr.owner.uuid.equals(player.getGameProfile().getId()) ? friendRights : scr.friendRights; int fr = scr.owner.uuid.equals(player.getGameProfile().getId()) ? friendRights : scr.friendRights;
int or = (scr.rightsFor(player) & ScreenRights.MANAGE_OTHER_RIGHTS) == 0 ? scr.otherRights : otherRights; int or = (scr.rightsFor(player) & ScreenRights.MANAGE_OTHER_RIGHTS) == 0 ? scr.otherRights : otherRights;
@ -102,7 +103,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
switch (type) { switch (type) {
case UPGRADES -> { case UPGRADES -> {
@ -111,7 +112,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
else tes.removeUpgrade(side, toRemove, player); else tes.removeUpgrade(side, toRemove, player);
} }
case RIGHTS -> { case RIGHTS -> {
TileEntityScreen.Screen scr = tes.getScreen(side); ScreenData scr = tes.getScreen(side);
int fr = friendRights; int fr = friendRights;
int or = otherRights; int or = otherRights;

View File

@ -10,9 +10,9 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.NameUUIDPair; import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import java.util.function.Function; import java.util.function.Function;
@ -41,7 +41,7 @@ public class ModifyFriendListControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
checkPerms(ScreenRights.MANAGE_FRIEND_LIST, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.MANAGE_FRIEND_LIST, permissionChecker, ctx.getSender());
if (adding) tes.addFriend(player, side, friend); if (adding) tes.addFriend(player, side, friend);
@ -50,7 +50,7 @@ public class ModifyFriendListControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
throw new RuntimeException("TODO"); throw new RuntimeException("TODO");
} }
} }

View File

@ -8,9 +8,9 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.NameUUIDPair; import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import java.util.function.Function; import java.util.function.Function;
@ -35,13 +35,13 @@ public class OwnerControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
throw new RuntimeException("Cannot handle ownership theft packet from server"); throw new RuntimeException("Cannot handle ownership theft packet from server");
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
tes.getScreen(side).owner = owner; tes.getScreen(side).owner = owner;
} }
} }

View File

@ -9,10 +9,10 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Rotation; import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.Vector2i; import net.montoyo.wd.utilities.math.Vector2i;
import java.util.function.Function; import java.util.function.Function;
@ -55,7 +55,7 @@ public class ScreenModifyControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
checkPerms(ScreenRights.MODIFY_SCREEN, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.MODIFY_SCREEN, permissionChecker, ctx.getSender());
switch (type) { switch (type) {
case RESOLUTION -> tes.setResolution(side, res); case RESOLUTION -> tes.setResolution(side, res);
@ -65,7 +65,7 @@ public class ScreenModifyControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
switch (type) { switch (type) {
case RESOLUTION -> tes.setResolution(side, res); case RESOLUTION -> tes.setResolution(side, res);
case ROTATION -> tes.setRotation(side, rotation); case ROTATION -> tes.setRotation(side, rotation);

View File

@ -9,9 +9,9 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
import java.util.function.Function; import java.util.function.Function;
@ -41,7 +41,7 @@ public class SetURLControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
// TODO: deal with remote // TODO: deal with remote
checkPerms(ScreenRights.CHANGE_URL, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.CHANGE_URL, permissionChecker, ctx.getSender());
try { try {
@ -53,7 +53,7 @@ public class SetURLControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
try { try {
tes.setScreenURL(side, url); tes.setScreenURL(side, url);
} catch (Throwable err) { } catch (Throwable err) {

View File

@ -0,0 +1,48 @@
package net.montoyo.wd.controls.builtin;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.data.BlockSide;
import java.util.function.Function;
public class TurnOffControl extends ScreenControl {
public static final ResourceLocation id = new ResourceLocation("webdisplays:deactivate");
public static final TurnOffControl INSTANCE = new TurnOffControl();
public TurnOffControl() {
super(id);
}
@Override
public void write(FriendlyByteBuf buf) {
}
@Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
throw new RuntimeException("Cannot handle deactivation packet from server");
}
@Override
@OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) {
if (side != null) {
WebDisplays.PROXY.closeGui(pos, side);
tes.disableScreen(side);
} else {
for (BlockSide value : BlockSide.values()) {
WebDisplays.PROXY.closeGui(pos, value);
tes.disableScreen(value);
}
}
}
}

View File

@ -1,24 +0,0 @@
/*
* Copyright (C) 2018 BARBOTIN Nicolas
*/
package net.montoyo.wd.core;
public enum AdvancementIcon {
WEB_DISPLAYS("wd"),
BROKEN_PAD("brokenpad"),
PIGEON("pigeon");
private final String name;
AdvancementIcon(String n) {
name = n;
}
@Override
public String toString() {
return name;
}
}

View File

@ -7,6 +7,7 @@ package net.montoyo.wd.core;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
// TODO: bring this back when SSR is implemented
public class CCArguments implements IComputerArgs { public class CCArguments implements IComputerArgs {
private final Object[] args; private final Object[] args;

View File

@ -5,7 +5,7 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.montoyo.wd.init.ItemInit; import net.montoyo.wd.registry.ItemRegistry;
public enum CraftComponent { public enum CraftComponent {
STONEKEY("stonekey", "StoneKey"), STONEKEY("stonekey", "StoneKey"),
@ -32,6 +32,6 @@ public enum CraftComponent {
} }
public ItemStack makeItemStack() { public ItemStack makeItemStack() {
return new ItemStack(ItemInit.getComputerCraftItem(ordinal()).get(), 1); return new ItemStack(ItemRegistry.getComputerCraftItem(ordinal()).get(), 1);
} }
} }

View File

@ -7,6 +7,7 @@ package net.montoyo.wd.core;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import net.minecraft.advancements.CriterionTrigger; import net.minecraft.advancements.CriterionTrigger;
import net.minecraft.advancements.critereon.AbstractCriterionTriggerInstance; import net.minecraft.advancements.critereon.AbstractCriterionTriggerInstance;
import net.minecraft.advancements.critereon.ContextAwarePredicate;
import net.minecraft.advancements.critereon.DeserializationContext; import net.minecraft.advancements.critereon.DeserializationContext;
import net.minecraft.advancements.critereon.EntityPredicate; import net.minecraft.advancements.critereon.EntityPredicate;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
@ -19,10 +20,8 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
public class Criterion implements CriterionTrigger<Criterion.Instance> { public class Criterion implements CriterionTrigger<Criterion.Instance> {
public static class Instance extends AbstractCriterionTriggerInstance { public static class Instance extends AbstractCriterionTriggerInstance {
public Instance(ResourceLocation id, ContextAwarePredicate arg2) {
public Instance(ResourceLocation id, EntityPredicate.Composite arg2) {
super(id, arg2); super(id, arg2);
} }
} }
@ -60,16 +59,15 @@ public class Criterion implements CriterionTrigger<Criterion.Instance> {
@Override @Override
public @NotNull Instance createInstance(JsonObject json, DeserializationContext context) { public @NotNull Instance createInstance(JsonObject json, DeserializationContext context) {
return new Instance(id, EntityPredicate.Composite.fromJson(json, "instance", context)); return new Instance(id, EntityPredicate.fromJson(json, "instance", context));
} }
public void trigger(PlayerAdvancements ply) { public void trigger(PlayerAdvancements ply) {
ArrayList<Listener<Instance>> listeners = map.get(ply); ArrayList<Listener<Instance>> listeners = map.get(ply);
if(listeners != null) { if (listeners != null) {
Listener[] copy = listeners.toArray(new Listener[0]); //We need to make a copy, otherwise we get a ConcurrentModificationException Listener[] copy = listeners.toArray(new Listener[0]); //We need to make a copy, otherwise we get a ConcurrentModificationException
Arrays.stream(copy).forEach(l -> l.run(ply)); Arrays.stream(copy).forEach(l -> l.run(ply));
} }
} }
} }

View File

@ -8,23 +8,22 @@ import net.minecraft.util.StringRepresentable;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType;
import net.montoyo.wd.entity.TileEntityKeyboard; import net.montoyo.wd.entity.KeyboardBlockEntity;
import net.montoyo.wd.entity.TileEntityRCtrl; import net.montoyo.wd.entity.RemoteControlBlockEntity;
import net.montoyo.wd.entity.TileEntityRedCtrl; import net.montoyo.wd.entity.RedstoneControlBlockEntity;
import net.montoyo.wd.entity.TileEntityServer; import net.montoyo.wd.entity.ServerBlockEntity;
import net.montoyo.wd.init.BlockInit; import net.montoyo.wd.registry.BlockRegistry;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier; import java.util.function.Supplier;
public enum DefaultPeripheral implements StringRepresentable { public enum DefaultPeripheral implements StringRepresentable {
KEYBOARD("keyboard", "Keyboard", KeyboardBlockEntity::new, BlockRegistry.KEYBOARD_BLOCK), //WITH FACING (< 3)
KEYBOARD("keyboard", "Keyboard", TileEntityKeyboard::new, BlockInit.blockKeyBoard), //WITH FACING (< 3)
// CC_INTERFACE("ccinterface", "ComputerCraft_Interface", TileEntityCCInterface.class), // CC_INTERFACE("ccinterface", "ComputerCraft_Interface", TileEntityCCInterface.class),
// OC_INTERFACE("cointerface", "OpenComputers_Interface", TileEntityOCInterface.class), // OC_INTERFACE("cointerface", "OpenComputers_Interface", TileEntityOCInterface.class),
REMOTE_CONTROLLER("remotectrl", "Remote_Controller", TileEntityRCtrl::new ,BlockInit.blockRControl), //WITHOUT FACING (>= 3) REMOTE_CONTROLLER("remotectrl", "Remote_Controller", RemoteControlBlockEntity::new , BlockRegistry.REMOTE_CONTROLLER_BLOCK), //WITHOUT FACING (>= 3)
REDSTONE_CONTROLLER("redstonectrl", "Redstone_Controller", TileEntityRedCtrl::new ,BlockInit.blockRedControl), REDSTONE_CONTROLLER("redstonectrl", "Redstone_Controller", RedstoneControlBlockEntity::new , BlockRegistry.REDSTONE_CONTROL_BLOCK),
SERVER("server", "Server", TileEntityServer::new, BlockInit.blockServer); SERVER("server", "Server", ServerBlockEntity::new, BlockRegistry.SERVER_BLOCK);
private final String name; private final String name;
private final String wikiName; private final String wikiName;

View File

@ -5,9 +5,7 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
public enum HasAdvancement { public enum HasAdvancement {
DONT_KNOW, DONT_KNOW,
YES, YES,
NO NO
} }

View File

@ -7,10 +7,8 @@ package net.montoyo.wd.core;
import java.util.Map; import java.util.Map;
public interface IComputerArgs { public interface IComputerArgs {
String checkString(int i); String checkString(int i);
int checkInteger(int i); int checkInteger(int i);
Map checkTable(int i); Map checkTable(int i);
int count(); int count();
} }

View File

@ -7,11 +7,9 @@ package net.montoyo.wd.core;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
public interface IPeripheral { public interface IPeripheral {
boolean connect(Level world, BlockPos blockPos, BlockState blockState, Vector3i screenPos, BlockSide screenSide); boolean connect(Level world, BlockPos blockPos, BlockState blockState, Vector3i screenPos, BlockSide screenSide);
} }

View File

@ -1,19 +1,17 @@
/* ///*
* Copyright (C) 2018 BARBOTIN Nicolas // * Copyright (C) 2018 BARBOTIN Nicolas
*/ // */
//
package net.montoyo.wd.core; //package net.montoyo.wd.core;
//
import net.montoyo.mcef.api.IJSQueryCallback; //import net.montoyo.mcef.api.IJSQueryCallback;
import net.montoyo.wd.entity.TileEntityScreen; //import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.BlockSide; //import net.montoyo.wd.utilities.orientation.BlockSide;
//
import javax.annotation.Nonnull; //import javax.annotation.Nonnull;
//
public interface IScreenQueryHandler { //public interface IScreenQueryHandler {
// //args is an array of Doubles or Strings
//args is an array of Doubles or Strings // //The screen DOES exist, so scr.getScreen(side) is never null
//The screen DOES exist, so scr.getScreen(side) is never null // void handleQuery(@Nonnull IJSQueryCallback cb, @Nonnull TileEntityScreen scr, @Nonnull BlockSide side, @Nonnull Object[] args);
void handleQuery(@Nonnull IJSQueryCallback cb, @Nonnull TileEntityScreen scr, @Nonnull BlockSide side, @Nonnull Object[] args); //}
}

View File

@ -6,17 +6,15 @@ package net.montoyo.wd.core;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public interface IUpgrade { public interface IUpgrade {
void onInstall(@Nonnull ScreenBlockEntity tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is);
void onInstall(@Nonnull TileEntityScreen tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is); boolean onRemove(@Nonnull ScreenBlockEntity tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is); //Return true to prevent dropping
boolean onRemove(@Nonnull TileEntityScreen tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is); //Return true to prevent dropping
boolean isSameUpgrade(@Nonnull ItemStack myStack, @Nonnull ItemStack otherStack); //myStack.getItem() is an instance of this class boolean isSameUpgrade(@Nonnull ItemStack myStack, @Nonnull ItemStack otherStack); //myStack.getItem() is an instance of this class
String getJSName(@Nonnull ItemStack is); //modname:upgradename String getJSName(@Nonnull ItemStack is); //modname:upgradename
} }

View File

@ -5,9 +5,7 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
public interface IWDDCapability { public interface IWDDCapability {
boolean isFirstRun(); boolean isFirstRun();
void clearFirstRun(); void clearFirstRun();
void cloneTo(IWDDCapability dst); void cloneTo(IWDDCapability dst);
} }

View File

@ -5,10 +5,9 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
public enum JSServerRequest { public enum JSServerRequest {
CLEAR_REDSTONE, CLEAR_REDSTONE,
SET_REDSTONE_AT(Integer.class, Integer.class, Boolean.class); SET_REDSTONE_AT(Integer.class, Integer.class, Boolean.class);
@ -50,5 +49,4 @@ public enum JSServerRequest {
return ret; return ret;
} }
} }

View File

@ -7,7 +7,6 @@ package net.montoyo.wd.core;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
public class MissingPermissionException extends Exception { public class MissingPermissionException extends Exception {
private final int permission; private final int permission;
private final ServerPlayer player; private final ServerPlayer player;
@ -24,5 +23,4 @@ public class MissingPermissionException extends Exception {
public ServerPlayer getPlayer() { public ServerPlayer getPlayer() {
return player; return player;
} }
} }

View File

@ -10,7 +10,6 @@ import java.util.Optional;
@Optional.Interface(iface = "net.montoyo.wd.core.IComputerArgs", modid = "opencomputers") @Optional.Interface(iface = "net.montoyo.wd.core.IComputerArgs", modid = "opencomputers")
public class OCArguments implements IComputerArgs { public class OCArguments implements IComputerArgs {
//Keep this as an "Object" so that it doesn't crash if OC is absent //Keep this as an "Object" so that it doesn't crash if OC is absent
private final Object args; private final Object args;
@ -41,5 +40,4 @@ public class OCArguments implements IComputerArgs {
public int count() { public int count() {
return ((Arguments) args).count(); return ((Arguments) args).count();
} }
} */ } */

View File

@ -5,9 +5,10 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
public abstract class ScreenRights { public abstract class ScreenRights {
public static final int CHANGE_URL = 1; //Change URL AND run JavaScript public static final int CHANGE_URL = 1; //Change URL AND run JavaScript
/** use {@link ScreenRights#INTERACT instead} */ /**
* use {@link ScreenRights#INTERACT instead}
*/
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true)
public static final int CLICK = 2; //Click AND type public static final int CLICK = 2; //Click AND type
public static final int INTERACT = 2; //Click AND type public static final int INTERACT = 2; //Click AND type
@ -21,5 +22,4 @@ public abstract class ScreenRights {
public static final int NONE = 0; public static final int NONE = 0;
public static final int ALL = 0xFF; public static final int ALL = 0xFF;
public static final int DEFAULTS = CHANGE_URL | INTERACT | MANAGE_UPGRADES | MODIFY_SCREEN; public static final int DEFAULTS = CHANGE_URL | INTERACT | MANAGE_UPGRADES | MODIFY_SCREEN;
} }

View File

@ -1,21 +0,0 @@
/*
* Copyright (C) 2018 BARBOTIN Nicolas
*/
package net.montoyo.wd.core;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.ItemStack;
import net.montoyo.wd.init.BlockInit;
public class WDCreativeTab extends CreativeModeTab {
public WDCreativeTab() {
super("webdisplays");
}
@Override
public ItemStack makeIcon() {
return new ItemStack(BlockInit.blockScreen.get());
}
}

View File

@ -18,14 +18,11 @@ import javax.annotation.Nonnull;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
public class WDDCapability implements IWDDCapability { public class WDDCapability implements IWDDCapability {
public static class Factory implements Callable<IWDDCapability> { public static class Factory implements Callable<IWDDCapability> {
@Override @Override
public IWDDCapability call() { public IWDDCapability call() {
return new WDDCapability(); return new WDDCapability();
} }
} }
public static class Provider implements ICapabilitySerializable<CompoundTag> { public static class Provider implements ICapabilitySerializable<CompoundTag> {
@ -38,7 +35,7 @@ public class WDDCapability implements IWDDCapability {
@NotNull @NotNull
@Override @Override
public <T> LazyOptional<T> getCapability(@NotNull Capability<T> capability, @org.jetbrains.annotations.Nullable Direction arg) { public <T> LazyOptional<T> getCapability(@NotNull Capability<T> capability, @org.jetbrains.annotations.Nullable Direction arg) {
return cap == capability ? INSTANCE.cast() : LazyOptional.empty(); return cap == capability ? INSTANCE.cast() : LazyOptional.empty();
} }
@Override @Override
@ -78,8 +75,7 @@ public class WDDCapability implements IWDDCapability {
@Override @Override
public void cloneTo(IWDDCapability dst) { public void cloneTo(IWDDCapability dst) {
if(!isFirstRun()) if (!isFirstRun())
dst.clearFirstRun(); dst.clearFirstRun();
} }
} }

View File

@ -18,53 +18,54 @@ import java.util.HashMap;
import java.util.function.Supplier; import java.util.function.Supplier;
public abstract class GuiData { public abstract class GuiData {
public static GuiData read(String name, FriendlyByteBuf buf) { public static GuiData read(String name, FriendlyByteBuf buf) {
GuiType type = dataTable.get(name); GuiType type = dataTable.get(name);
GuiData data = type.create(); GuiData data = type.create();
data.deserialize(buf); data.deserialize(buf);
return data; return data;
} }
protected static class GuiType {
Class<? extends GuiData> clazz;
Supplier<GuiData> constructor;
public GuiType(Class<? extends GuiData> clazz, Supplier<GuiData> constructor) {
this.clazz = clazz;
this.constructor = constructor;
}
public GuiData create() {
return constructor.get();
}
}
private static final HashMap<String, GuiType> dataTable = new HashMap<>();
static {
dataTable.put("SetURL", new GuiType(SetURLData.class, SetURLData::new));
dataTable.put("ScreenConfig", new GuiType(ScreenConfigData.class, ScreenConfigData::new));
dataTable.put("Keyboard", new GuiType(KeyboardData.class, KeyboardData::new));
dataTable.put("RedstoneCtrl", new GuiType(RedstoneCtrlData.class, RedstoneCtrlData::new));
dataTable.put("Server", new GuiType(ServerData.class, ServerData::new));
}
public static Class<? extends GuiData> classOf(String name) {
return dataTable.get(name).clazz;
}
public GuiData() {
}
@OnlyIn(Dist.CLIENT) protected static class GuiType {
public abstract Screen createGui(Screen old, Level world); Class<? extends GuiData> clazz;
Supplier<GuiData> constructor;
public abstract String getName();
public GuiType(Class<? extends GuiData> clazz, Supplier<GuiData> constructor) {
public void sendTo(ServerPlayer player) { this.clazz = clazz;
WDNetworkRegistry.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new S2CMessageOpenGui(this)); this.constructor = constructor;
} }
public GuiData create() {
return constructor.get();
}
}
private static final HashMap<String, GuiType> dataTable = new HashMap<>();
static {
dataTable.put("SetURL", new GuiType(SetURLData.class, SetURLData::new));
dataTable.put("ScreenConfig", new GuiType(ScreenConfigData.class, ScreenConfigData::new));
dataTable.put("Keyboard", new GuiType(KeyboardData.class, KeyboardData::new));
dataTable.put("RedstoneCtrl", new GuiType(RedstoneCtrlData.class, RedstoneCtrlData::new));
dataTable.put("Server", new GuiType(ServerData.class, ServerData::new));
}
public static Class<? extends GuiData> classOf(String name) {
return dataTable.get(name).clazz;
}
public GuiData() {
}
@OnlyIn(Dist.CLIENT)
public abstract Screen createGui(Screen old, Level world);
public abstract String getName();
public void sendTo(ServerPlayer player) {
WDNetworkRegistry.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new S2CMessageOpenGui(this));
}
public abstract void serialize(FriendlyByteBuf buf); public abstract void serialize(FriendlyByteBuf buf);
public abstract void deserialize(FriendlyByteBuf buf); public abstract void deserialize(FriendlyByteBuf buf);
} }

View File

@ -12,23 +12,22 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiKeyboard; import net.montoyo.wd.client.gui.GuiKeyboard;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
public class KeyboardData extends GuiData { public class KeyboardData extends GuiData {
public Vector3i pos; public Vector3i pos;
public BlockSide side; public BlockSide side;
public int kbX; public int kbX;
public int kbY; public int kbY;
public int kbZ; public int kbZ;
public KeyboardData() { public KeyboardData() {
} }
public KeyboardData(TileEntityScreen tes, BlockSide side, BlockPos kbPos) { public KeyboardData(ScreenBlockEntity tes, BlockSide side, BlockPos kbPos) {
pos = new Vector3i(tes.getBlockPos()); pos = new Vector3i(tes.getBlockPos());
this.side = side; this.side = side;
kbX = kbPos.getX(); kbX = kbPos.getX();
@ -40,19 +39,19 @@ public class KeyboardData extends GuiData {
@Override @Override
public Screen createGui(Screen old, Level world) { public Screen createGui(Screen old, Level world) {
BlockEntity te = world.getBlockEntity(pos.toBlock()); BlockEntity te = world.getBlockEntity(pos.toBlock());
if(te == null || !(te instanceof TileEntityScreen)) { if (te == null || !(te instanceof ScreenBlockEntity)) {
Log.error("TileEntity at %s is not a screen; can't open keyboard!", pos.toString()); Log.error("TileEntity at %s is not a screen; can't open keyboard!", pos.toString());
return null; return null;
} }
return new GuiKeyboard((TileEntityScreen) te, side, new BlockPos(kbX, kbY, kbZ)); return new GuiKeyboard((ScreenBlockEntity) te, side, new BlockPos(kbX, kbY, kbZ));
} }
@Override @Override
public String getName() { public String getName() {
return "Keyboard"; return "Keyboard";
} }
@Override @Override
public void serialize(FriendlyByteBuf buf) { public void serialize(FriendlyByteBuf buf) {
buf.writeInt(pos.x); buf.writeInt(pos.x);

View File

@ -13,19 +13,18 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiRedstoneCtrl; import net.montoyo.wd.client.gui.GuiRedstoneCtrl;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
public class RedstoneCtrlData extends GuiData { public class RedstoneCtrlData extends GuiData {
public ResourceLocation dimension; public ResourceLocation dimension;
public Vector3i pos; public Vector3i pos;
public String risingEdgeURL; public String risingEdgeURL;
public String fallingEdgeURL; public String fallingEdgeURL;
public RedstoneCtrlData() { public RedstoneCtrlData() {
super(); super();
} }
public RedstoneCtrlData(ResourceLocation d, BlockPos p, String r, String f) { public RedstoneCtrlData(ResourceLocation d, BlockPos p, String r, String f) {
dimension = d; dimension = d;
pos = new Vector3i(p); pos = new Vector3i(p);
@ -43,7 +42,7 @@ public class RedstoneCtrlData extends GuiData {
public String getName() { public String getName() {
return "RedstoneCtrl"; return "RedstoneCtrl";
} }
@Override @Override
public void serialize(FriendlyByteBuf buf) { public void serialize(FriendlyByteBuf buf) {
buf.writeUtf(dimension.toString()); buf.writeUtf(dimension.toString());
@ -51,7 +50,7 @@ public class RedstoneCtrlData extends GuiData {
buf.writeUtf(risingEdgeURL); buf.writeUtf(risingEdgeURL);
buf.writeUtf(fallingEdgeURL); buf.writeUtf(fallingEdgeURL);
} }
@Override @Override
public void deserialize(FriendlyByteBuf buf) { public void deserialize(FriendlyByteBuf buf) {
dimension = new ResourceLocation(buf.readUtf()); dimension = new ResourceLocation(buf.readUtf());

View File

@ -13,28 +13,28 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.wd.client.gui.GuiScreenConfig; import net.montoyo.wd.client.gui.GuiScreenConfig;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageOpenGui; import net.montoyo.wd.net.client_bound.S2CMessageOpenGui;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.NameUUIDPair; import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
public class ScreenConfigData extends GuiData { public class ScreenConfigData extends GuiData {
public boolean onlyUpdate;
public boolean onlyUpdate; public Vector3i pos;
public Vector3i pos; public BlockSide side;
public BlockSide side; public NameUUIDPair[] friends;
public NameUUIDPair[] friends; public int friendRights;
public int friendRights; public int otherRights;
public int otherRights;
public ScreenConfigData() {
}
public ScreenConfigData(Vector3i pos, BlockSide side, TileEntityScreen.Screen scr) { public ScreenConfigData() {
}
public ScreenConfigData(Vector3i pos, BlockSide side, ScreenData scr) {
this.pos = pos; this.pos = pos;
this.side = side; this.side = side;
friends = scr.friends.toArray(new NameUUIDPair[0]); friends = scr.friends.toArray(new NameUUIDPair[0]);
@ -63,12 +63,12 @@ public class ScreenConfigData extends GuiData {
return null; return null;
BlockEntity te = world.getBlockEntity(pos.toBlock()); BlockEntity te = world.getBlockEntity(pos.toBlock());
if (te == null || !(te instanceof TileEntityScreen)) { if (te == null || !(te instanceof ScreenBlockEntity)) {
Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString()); Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString());
return null; return null;
} }
return new GuiScreenConfig(Component.nullToEmpty(""), (TileEntityScreen) te, side, friends, friendRights, otherRights); return new GuiScreenConfig(Component.nullToEmpty(""), (ScreenBlockEntity) te, side, friends, friendRights, otherRights);
} }
@Override @Override

View File

@ -12,17 +12,16 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiServer; import net.montoyo.wd.client.gui.GuiServer;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.utilities.NameUUIDPair; import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
public class ServerData extends GuiData { public class ServerData extends GuiData {
public Vector3i pos; public Vector3i pos;
public NameUUIDPair owner; public NameUUIDPair owner;
public ServerData() { public ServerData() {
} }
public ServerData(BlockPos bp, NameUUIDPair owner) { public ServerData(BlockPos bp, NameUUIDPair owner) {
pos = new Vector3i(bp); pos = new Vector3i(bp);
this.owner = owner; this.owner = owner;
@ -38,13 +37,13 @@ public class ServerData extends GuiData {
public String getName() { public String getName() {
return "Server"; return "Server";
} }
@Override @Override
public void serialize(FriendlyByteBuf buf) { public void serialize(FriendlyByteBuf buf) {
BufferUtils.writeVec3i(buf, pos); BufferUtils.writeVec3i(buf, pos);
owner.writeTo(buf); owner.writeTo(buf);
} }
@Override @Override
public void deserialize(FriendlyByteBuf buf) { public void deserialize(FriendlyByteBuf buf) {
pos = BufferUtils.readVec3i(buf); pos = BufferUtils.readVec3i(buf);

View File

@ -12,23 +12,22 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiSetURL2; import net.montoyo.wd.client.gui.GuiSetURL2;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
public class SetURLData extends GuiData { public class SetURLData extends GuiData {
public Vector3i pos; public Vector3i pos;
public BlockSide side; public BlockSide side;
public String url; public String url;
public boolean isRemote; public boolean isRemote;
public Vector3i remoteLocation; public Vector3i remoteLocation;
public SetURLData() { public SetURLData() {
} }
public SetURLData(Vector3i pos, BlockSide side, String url) { public SetURLData(Vector3i pos, BlockSide side, String url) {
this.pos = pos; this.pos = pos;
this.side = side; this.side = side;
@ -50,19 +49,19 @@ public class SetURLData extends GuiData {
@Override @Override
public Screen createGui(Screen old, Level world) { public Screen createGui(Screen old, Level world) {
BlockEntity te = world.getBlockEntity(pos.toBlock()); BlockEntity te = world.getBlockEntity(pos.toBlock());
if(te == null || !(te instanceof TileEntityScreen)) { if (te == null || !(te instanceof ScreenBlockEntity)) {
Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString()); Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString());
return null; return null;
} }
return new GuiSetURL2((TileEntityScreen) te, side, url, isRemote ? remoteLocation : null); return new GuiSetURL2((ScreenBlockEntity) te, side, url, isRemote ? remoteLocation : null);
} }
@Override @Override
public String getName() { public String getName() {
return "SetURL"; return "SetURL";
} }
@Override @Override
public void serialize(FriendlyByteBuf buf) { public void serialize(FriendlyByteBuf buf) {
BufferUtils.writeVec3i(buf, pos); BufferUtils.writeVec3i(buf, pos);
@ -71,7 +70,7 @@ public class SetURLData extends GuiData {
buf.writeBoolean(isRemote); buf.writeBoolean(isRemote);
if (isRemote) BufferUtils.writeVec3i(buf, remoteLocation); if (isRemote) BufferUtils.writeVec3i(buf, remoteLocation);
} }
@Override @Override
public void deserialize(FriendlyByteBuf buf) { public void deserialize(FriendlyByteBuf buf) {
pos = BufferUtils.readVec3i(buf); pos = BufferUtils.readVec3i(buf);

View File

@ -13,7 +13,11 @@ import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.core.IComputerArgs; import net.montoyo.wd.core.IComputerArgs;
import net.montoyo.wd.core.IUpgrade; import net.montoyo.wd.core.IUpgrade;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import net.montoyo.wd.utilities.serialization.TypeData;
import net.montoyo.wd.utilities.serialization.Util;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
@ -23,9 +27,8 @@ import java.lang.annotation.Target;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase { public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlockEntity {
public AbstractInterfaceBlockEntity(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) {
public TileEntityInterfaceBase(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) {
super(arg, arg2, arg3); super(arg, arg2, arg3);
} }
@ -108,7 +111,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
throw new IllegalArgumentException("invalid right name"); throw new IllegalArgumentException("invalid right name");
} }
TileEntityScreen tes = getConnectedScreenEx(); ScreenBlockEntity tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
else else
@ -119,7 +122,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
public Object[] hasUpgrade(IComputerArgs args) { public Object[] hasUpgrade(IComputerArgs args) {
String name = args.checkString(0); String name = args.checkString(0);
TileEntityScreen tes = getConnectedScreenEx(); ScreenBlockEntity tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
else else
@ -128,7 +131,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
@ComputerFunc @ComputerFunc
public Object[] getSize(IComputerArgs args) { public Object[] getSize(IComputerArgs args) {
TileEntityScreen tes = getConnectedScreenEx(); ScreenBlockEntity tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -140,7 +143,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
@ComputerFunc @ComputerFunc
public Object[] getResolution(IComputerArgs args) { public Object[] getResolution(IComputerArgs args) {
TileEntityScreen tes = getConnectedScreenEx(); ScreenBlockEntity tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -152,7 +155,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
@ComputerFunc @ComputerFunc
public Object[] getRotation(IComputerArgs args) { public Object[] getRotation(IComputerArgs args) {
TileEntityScreen tes = getConnectedScreenEx(); ScreenBlockEntity tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -162,7 +165,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
@ComputerFunc @ComputerFunc
public Object[] getURL(IComputerArgs args) { public Object[] getURL(IComputerArgs args) {
TileEntityScreen tes = getConnectedScreenEx(); ScreenBlockEntity tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -206,12 +209,12 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
// throw new IllegalArgumentException("bad action name"); // throw new IllegalArgumentException("bad action name");
// } // }
TileEntityScreen scr = getConnectedScreenEx(); ScreenBlockEntity scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
else { else {
TileEntityScreen.Screen scrscr = scr.getScreen(screenSide); ScreenData scrscr = scr.getScreen(screenSide);
if((scrscr.rightsFor(owner.uuid) & ScreenRights.INTERACT) == 0) if((scrscr.rightsFor(owner.uuid) & ScreenRights.INTERACT) == 0)
return err("restrictions"); return err("restrictions");
@ -245,7 +248,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
} }
private Object[] realType(String what) { private Object[] realType(String what) {
TileEntityScreen scr = getConnectedScreenEx(); ScreenBlockEntity scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -317,7 +320,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
code = ((Double) oCode).intValue(); code = ((Double) oCode).intValue();
} }
data.add(new TypeData(dataAction, code, 0)); data.add(new TypeData(dataAction, code, 0, 0));
} }
return realType(WebDisplays.GSON.toJson(data)); return realType(WebDisplays.GSON.toJson(data));
@ -326,7 +329,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
@ComputerFunc @ComputerFunc
public Object[] setURL(IComputerArgs args) { public Object[] setURL(IComputerArgs args) {
String url = args.checkString(0); String url = args.checkString(0);
TileEntityScreen scr = getConnectedScreenEx(); ScreenBlockEntity scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -346,7 +349,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
public Object[] setResolution(IComputerArgs args) { public Object[] setResolution(IComputerArgs args) {
int rx = args.checkInteger(0); int rx = args.checkInteger(0);
int ry = args.checkInteger(1); int ry = args.checkInteger(1);
TileEntityScreen scr = getConnectedScreenEx(); ScreenBlockEntity scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -369,7 +372,7 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
rot /= 90; rot /= 90;
rot &= 3; rot &= 3;
TileEntityScreen scr = getConnectedScreenEx(); ScreenBlockEntity scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -384,14 +387,14 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
@ComputerFunc @ComputerFunc
public Object[] runJS(IComputerArgs args) { public Object[] runJS(IComputerArgs args) {
String code = args.checkString(0); String code = args.checkString(0);
TileEntityScreen scr = getConnectedScreenEx(); ScreenBlockEntity scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
else if((scr.getScreen(screenSide).rightsFor(owner.uuid) & ScreenRights.CHANGE_URL) == 0) else if((scr.getScreen(screenSide).rightsFor(owner.uuid) & ScreenRights.CHANGE_URL) == 0)
return err("restrictions"); return err("restrictions");
else { else {
scr.evalJS(screenSide, code); // scr.evalJS(screenSide, code);
return TRUE; return TRUE;
} }
} }
@ -406,5 +409,4 @@ public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
return null; return null;
} }
} }

View File

@ -16,29 +16,28 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunk;
import net.montoyo.wd.core.IPeripheral; import net.montoyo.wd.core.IPeripheral;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Objects; import java.util.Objects;
public abstract class TileEntityPeripheralBase extends BlockEntity implements IPeripheral { public abstract class AbstractPeripheralBlockEntity extends BlockEntity implements IPeripheral {
protected Vector3i screenPos; protected Vector3i screenPos;
protected BlockSide screenSide; protected BlockSide screenSide;
public TileEntityPeripheralBase(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) { public AbstractPeripheralBlockEntity(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) {
super(arg, arg2, arg3); super(arg, arg2, arg3);
} }
// TODO // TODO
@Override @Override
public void load(CompoundTag tag) { public void load(CompoundTag tag) {
super.load(tag); super.load(tag);
if(tag.contains("WDScreen", 10)) { if (tag.contains("WDScreen", 10)) {
CompoundTag scr = tag.getCompound("WDScreen"); CompoundTag scr = tag.getCompound("WDScreen");
screenPos = new Vector3i(scr.getInt("X"), scr.getInt("Y"), scr.getInt("Z")); screenPos = new Vector3i(scr.getInt("X"), scr.getInt("Y"), scr.getInt("Z"));
screenSide = BlockSide.values()[scr.getByte("Side")]; screenSide = BlockSide.values()[scr.getByte("Side")];
@ -47,28 +46,28 @@ public abstract class TileEntityPeripheralBase extends BlockEntity implements IP
screenSide = null; screenSide = null;
} }
} }
@Override @Override
protected void saveAdditional(CompoundTag tag) { protected void saveAdditional(CompoundTag tag) {
super.saveAdditional(tag); super.saveAdditional(tag);
if(screenPos != null && screenSide != null) { if (screenPos != null && screenSide != null) {
CompoundTag scr = new CompoundTag(); CompoundTag scr = new CompoundTag();
scr.putInt("X", screenPos.x); scr.putInt("X", screenPos.x);
scr.putInt("Y", screenPos.y); scr.putInt("Y", screenPos.y);
scr.putInt("Z", screenPos.z); scr.putInt("Z", screenPos.z);
scr.putByte("Side", (byte) screenSide.ordinal()); scr.putByte("Side", (byte) screenSide.ordinal());
tag.put("WDScreen", scr); tag.put("WDScreen", scr);
} }
} }
// this is not used for loading from disk, so I'm marking it final // this is not used for loading from disk, so I'm marking it final
@Override @Override
public final void deserializeNBT(CompoundTag tag) { public final void deserializeNBT(CompoundTag tag) {
super.deserializeNBT(tag); super.deserializeNBT(tag);
} }
// this is not used for writing to disk, so I'm marking it final // this is not used for writing to disk, so I'm marking it final
@Override @Override
@Nonnull @Nonnull
@ -79,12 +78,12 @@ public abstract class TileEntityPeripheralBase extends BlockEntity implements IP
@Override @Override
public boolean connect(Level world_, BlockPos blockPos, BlockState blockState, Vector3i pos, BlockSide side) { public boolean connect(Level world_, BlockPos blockPos, BlockState blockState, Vector3i pos, BlockSide side) {
BlockEntity te = world_.getBlockEntity(pos.toBlock()); BlockEntity te = world_.getBlockEntity(pos.toBlock());
if(te == null || !(te instanceof TileEntityScreen)) { if (!(te instanceof ScreenBlockEntity)) {
Log.error("TileEntityPeripheralBase.connect(): Tile entity at %s is not a screen!", pos.toString()); Log.error("TileEntityPeripheralBase.connect(): Tile entity at %s is not a screen!", pos.toString());
return false; return false;
} }
if(((TileEntityScreen) te).getScreen(side) == null) { if (((ScreenBlockEntity) te).getScreen(side) == null) {
Log.error("TileEntityPeripheralBase.connect(): There is no screen at %s on side %s!", pos.toString(), side.toString()); Log.error("TileEntityPeripheralBase.connect(): There is no screen at %s on side %s!", pos.toString(), side.toString());
return false; return false;
} }
@ -108,31 +107,31 @@ public abstract class TileEntityPeripheralBase extends BlockEntity implements IP
} }
@Nullable @Nullable
public TileEntityScreen getConnectedScreen() { public ScreenBlockEntity getConnectedScreen() {
if(screenPos == null || screenSide == null) if (screenPos == null || screenSide == null)
return null; return null;
BlockEntity te = level.getBlockEntity(screenPos.toBlock()); BlockEntity te = level.getBlockEntity(screenPos.toBlock());
if(te == null || !(te instanceof TileEntityScreen) || ((TileEntityScreen) te).getScreen(screenSide) == null) { if (!(te instanceof ScreenBlockEntity) || ((ScreenBlockEntity) te).getScreen(screenSide) == null) {
screenPos = null; screenPos = null;
screenSide = null; screenSide = null;
setChanged(); setChanged();
return null; return null;
} }
return (TileEntityScreen) te; return (ScreenBlockEntity) te;
} }
@Nullable @Nullable
public TileEntityScreen getConnectedScreenEx() { public ScreenBlockEntity getConnectedScreenEx() {
if(screenPos == null || screenSide == null) if (screenPos == null || screenSide == null)
return null; return null;
BlockEntity te = level.getBlockEntity(screenPos.toBlock()); BlockEntity te = level.getBlockEntity(screenPos.toBlock());
if(te == null || !(te instanceof TileEntityScreen) || ((TileEntityScreen) te).getScreen(screenSide) == null) if (!(te instanceof ScreenBlockEntity) || ((ScreenBlockEntity) te).getScreen(screenSide) == null)
return null; return null;
return (TileEntityScreen) te; return (ScreenBlockEntity) te;
} }
@Nullable @Nullable

View File

@ -3,6 +3,7 @@
*/ */
package net.montoyo.wd.entity; package net.montoyo.wd.entity;
/* /*
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaException;
@ -19,18 +20,17 @@ import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
@Optional.Interface(iface = "dan200.computercraft.api.peripheral.IPeripheral", modid = "computercraft") @Optional.Interface(iface = "dan200.computercraft.api.peripheral.IPeripheral", modid = "computercraft")
public class TileEntityCCInterface extends TileEntityInterfaceBase implements IPeripheral { public class CCInterfaceBlockEntity extends AbstractInterfaceBlockEntity implements IPeripheral {
private static final String[] METHOD_NAMES; private static final String[] METHOD_NAMES;
private static final Method[] METHODS; private static final Method[] METHODS;
static { static {
ArrayList<String> names = new ArrayList<>(); ArrayList<String> names = new ArrayList<>();
ArrayList<Method> methods = new ArrayList<>(); ArrayList<Method> methods = new ArrayList<>();
Method[] src = TileEntityInterfaceBase.class.getMethods(); Method[] src = AbstractInterfaceBlockEntity.class.getMethods();
for(Method m: src) { for(Method m: src) {
if(m.getAnnotation(TileEntityInterfaceBase.ComputerFunc.class) != null) { if(m.getAnnotation(AbstractInterfaceBlockEntity.ComputerFunc.class) != null) {
if(m.getParameterCount() != 1 || m.getParameterTypes()[0] != IComputerArgs.class) if(m.getParameterCount() != 1 || m.getParameterTypes()[0] != IComputerArgs.class)
throw new RuntimeException("Found @ComputerFunc method with invalid arguments"); throw new RuntimeException("Found @ComputerFunc method with invalid arguments");
@ -79,5 +79,4 @@ public class TileEntityCCInterface extends TileEntityInterfaceBase implements IP
public boolean equals(@Nullable IPeripheral periph) { public boolean equals(@Nullable IPeripheral periph) {
return periph == this; return periph == this;
} }
}*/ }*/

View File

@ -15,15 +15,14 @@ import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.KeyboardData; import net.montoyo.wd.data.KeyboardData;
import net.montoyo.wd.init.TileInit; import net.montoyo.wd.registry.TileRegistry;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
public class TileEntityKeyboard extends TileEntityPeripheralBase {
public class KeyboardBlockEntity extends AbstractPeripheralBlockEntity {
private static final String RANDOM_CHARS = "AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn0123456789"; //Yes I have an AZERTY keyboard, u care? private static final String RANDOM_CHARS = "AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn0123456789"; //Yes I have an AZERTY keyboard, u care?
public TileEntityKeyboard(BlockPos arg2, BlockState arg3) { public KeyboardBlockEntity(BlockPos arg2, BlockState arg3) {
super(TileInit.KEYBOARD.get(), arg2, arg3); super(TileRegistry.KEYBOARD.get(), arg2, arg3);
} }
@Override @Override
@ -36,13 +35,13 @@ public class TileEntityKeyboard extends TileEntityPeripheralBase {
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
TileEntityScreen tes = getConnectedScreen(); ScreenBlockEntity tes = getConnectedScreen();
if(tes == null) { if(tes == null) {
Util.toast(player, "notLinked"); Util.toast(player, "notLinked");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
TileEntityScreen.Screen scr = tes.getScreen(screenSide); ScreenData scr = tes.getScreen(screenSide);
if((scr.rightsFor(player) & ScreenRights.INTERACT) == 0) { if((scr.rightsFor(player) & ScreenRights.INTERACT) == 0) {
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@ -56,10 +55,10 @@ public class TileEntityKeyboard extends TileEntityPeripheralBase {
if(!isScreenChunkLoaded()) if(!isScreenChunkLoaded())
return; return;
TileEntityScreen tes = getConnectedScreen(); ScreenBlockEntity tes = getConnectedScreen();
if(tes != null) { if(tes != null) {
TileEntityScreen.Screen scr = tes.getScreen(screenSide); ScreenData scr = tes.getScreen(screenSide);
boolean ok; boolean ok;
if(ent instanceof Player) if(ent instanceof Player)
@ -72,10 +71,9 @@ public class TileEntityKeyboard extends TileEntityPeripheralBase {
tes.type(screenSide, "t" + rnd, getBlockPos()); tes.type(screenSide, "t" + rnd, getBlockPos());
Player owner = level.getPlayerByUUID(scr.owner.uuid); Player owner = level.getPlayerByUUID(scr.owner.uuid);
if(owner != null && owner instanceof ServerPlayer && ent instanceof Ocelot) if(owner instanceof ServerPlayer && ent instanceof Ocelot)
WebDisplays.INSTANCE.criterionKeyboardCat.trigger(((ServerPlayer) owner).getAdvancements()); WebDisplays.INSTANCE.criterionKeyboardCat.trigger(((ServerPlayer) owner).getAdvancements());
} }
} }
} }
} }

View File

@ -13,8 +13,7 @@ import net.minecraftforge.fml.common.Optional;
import net.montoyo.wd.core.OCArguments; import net.montoyo.wd.core.OCArguments;
@Optional.Interface(iface = "li.cil.oc.api.network.SimpleComponent", modid = "opencomputers") @Optional.Interface(iface = "li.cil.oc.api.network.SimpleComponent", modid = "opencomputers")
public class TileEntityOCInterface extends TileEntityInterfaceBase implements SimpleComponent { public class OCInterfaceBlockEntity extends AbstractInterfaceBlockEntity implements SimpleComponent {
@Override @Override
public String getComponentName() { public String getComponentName() {
return "webdisplays"; return "webdisplays";
@ -133,5 +132,4 @@ public class TileEntityOCInterface extends TileEntityInterfaceBase implements Si
public Object[] unlink(Context ctx, Arguments args) { public Object[] unlink(Context ctx, Arguments args) {
return unlink(new OCArguments(args)); return unlink(new OCArguments(args));
} }
}*/ }*/

View File

@ -14,30 +14,29 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.RedstoneCtrlData; import net.montoyo.wd.data.RedstoneCtrlData;
import net.montoyo.wd.init.TileInit; import net.montoyo.wd.registry.TileRegistry;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
import java.io.IOException; import java.io.IOException;
public class TileEntityRedCtrl extends TileEntityPeripheralBase { public class RedstoneControlBlockEntity extends AbstractPeripheralBlockEntity {
private String risingEdgeURL = ""; private String risingEdgeURL = "";
private String fallingEdgeURL = ""; private String fallingEdgeURL = "";
private boolean state = false; private boolean state = false;
public TileEntityRedCtrl(BlockPos arg2, BlockState arg3) { public RedstoneControlBlockEntity(BlockPos arg2, BlockState arg3) {
super(TileInit.REDSTONE_CONTROLLER.get(), arg2, arg3); super(TileRegistry.REDSTONE_CONTROLLER.get(), arg2, arg3);
} }
@Override @Override
public void load(CompoundTag tag) { public void load(CompoundTag tag) {
super.load(tag); super.load(tag);
risingEdgeURL = tag.getString("RisingEdgeURL"); risingEdgeURL = tag.getString("RisingEdgeURL");
fallingEdgeURL = tag.getString("FallingEdgeURL"); fallingEdgeURL = tag.getString("FallingEdgeURL");
state = tag.getBoolean("Powered"); state = tag.getBoolean("Powered");
} }
@Override @Override
protected void saveAdditional(CompoundTag tag) { protected void saveAdditional(CompoundTag tag) {
super.saveAdditional(tag); super.saveAdditional(tag);
@ -45,24 +44,24 @@ public class TileEntityRedCtrl extends TileEntityPeripheralBase {
tag.putString("FallingEdgeURL", fallingEdgeURL); tag.putString("FallingEdgeURL", fallingEdgeURL);
tag.putBoolean("Powered", state); tag.putBoolean("Powered", state);
} }
@Override @Override
public InteractionResult onRightClick(Player player, InteractionHand hand) { public InteractionResult onRightClick(Player player, InteractionHand hand) {
if(level.isClientSide) if (level.isClientSide)
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
if(!isScreenChunkLoaded()) { if (!isScreenChunkLoaded()) {
Util.toast(player, "chunkUnloaded"); Util.toast(player, "chunkUnloaded");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
TileEntityScreen tes = getConnectedScreen(); ScreenBlockEntity tes = getConnectedScreen();
if(tes == null) { if (tes == null) {
Util.toast(player, "notLinked"); Util.toast(player, "notLinked");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
TileEntityScreen.Screen scr = tes.getScreen(screenSide); ScreenData scr = tes.getScreen(screenSide);
if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) { if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) {
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@ -76,10 +75,10 @@ public class TileEntityRedCtrl extends TileEntityPeripheralBase {
public void onNeighborChange(Block neighborType, BlockPos neighborPos) { public void onNeighborChange(Block neighborType, BlockPos neighborPos) {
boolean hasPower = (level.hasNeighborSignal(getBlockPos()) || level.hasNeighborSignal(getBlockPos().above())); //Same as dispenser boolean hasPower = (level.hasNeighborSignal(getBlockPos()) || level.hasNeighborSignal(getBlockPos().above())); //Same as dispenser
if(hasPower != state) { if (hasPower != state) {
state = hasPower; state = hasPower;
if(state) //Rising edge if (state) //Rising edge
changeURL(risingEdgeURL); changeURL(risingEdgeURL);
else //Falling edge else //Falling edge
changeURL(fallingEdgeURL); changeURL(fallingEdgeURL);
@ -93,11 +92,11 @@ public class TileEntityRedCtrl extends TileEntityPeripheralBase {
} }
private void changeURL(String url) { private void changeURL(String url) {
if(level.isClientSide || url.isEmpty()) if (level.isClientSide || url.isEmpty())
return; return;
if(isScreenChunkLoaded()) { if (isScreenChunkLoaded()) {
TileEntityScreen tes = getConnectedScreen(); ScreenBlockEntity tes = getConnectedScreen();
if (tes != null) if (tes != null)
try { try {

View File

@ -12,31 +12,31 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.SetURLData; import net.montoyo.wd.data.SetURLData;
import net.montoyo.wd.init.TileInit; import net.montoyo.wd.registry.TileRegistry;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
public class TileEntityRCtrl extends TileEntityPeripheralBase { public class RemoteControlBlockEntity extends AbstractPeripheralBlockEntity {
public TileEntityRCtrl(BlockPos arg2, BlockState arg3) { public RemoteControlBlockEntity(BlockPos arg2, BlockState arg3) {
super(TileInit.REMOTE_CONTROLLER.get(), arg2, arg3); super(TileRegistry.REMOTE_CONTROLLER.get(), arg2, arg3);
} }
@Override @Override
public InteractionResult onRightClick(Player player, InteractionHand hand) { public InteractionResult onRightClick(Player player, InteractionHand hand) {
if(level.isClientSide) if (level.isClientSide)
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
if(!isScreenChunkLoaded()) { if (!isScreenChunkLoaded()) {
Util.toast(player, "chunkUnloaded"); Util.toast(player, "chunkUnloaded");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
TileEntityScreen tes = getConnectedScreen(); ScreenBlockEntity tes = getConnectedScreen();
if(tes == null) { if (tes == null) {
Util.toast(player, "notLinked"); Util.toast(player, "notLinked");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
TileEntityScreen.Screen scr = tes.getScreen(screenSide); ScreenData scr = tes.getScreen(screenSide);
if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) { if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) {
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@ -45,5 +45,4 @@ public class TileEntityRCtrl extends TileEntityPeripheralBase {
(new SetURLData(screenPos, screenSide, scr.url, getBlockPos())).sendTo((ServerPlayer) player); (new SetURLData(screenPos, screenSide, scr.url, getBlockPos())).sendTo((ServerPlayer) player);
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
} }

View File

@ -0,0 +1,211 @@
package net.montoyo.wd.entity;
import com.cinemamod.mcef.MCEF;
import com.cinemamod.mcef.MCEFBrowser;
import com.cinemamod.mcef.listeners.MCEFCursorChangeListener;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.config.CommonConfig;
import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.browser.InWorldQueries;
import net.montoyo.wd.utilities.browser.WDBrowser;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import org.cef.browser.CefBrowser;
import java.util.ArrayList;
import java.util.UUID;
public class ScreenData {
public BlockSide side;
public Vector2i size;
public Vector2i resolution;
public Rotation rotation = Rotation.ROT_0;
public String url;
protected VideoType videoType;
public NameUUIDPair owner;
public ArrayList<NameUUIDPair> friends;
public int friendRights;
public int otherRights;
public CefBrowser browser;
public ArrayList<ItemStack> upgrades;
public boolean doTurnOnAnim;
public long turnOnTime;
public Player laserUser;
public final Vector2i lastMousePos = new Vector2i();
public NibbleArray redstoneStatus; //null on client
public boolean autoVolume = true;
public int mouseType;
public static ScreenData deserialize(CompoundTag tag) {
ScreenData ret = new ScreenData();
ret.side = BlockSide.values()[tag.getByte("Side")];
ret.size = new Vector2i(tag.getInt("Width"), tag.getInt("Height"));
ret.resolution = new Vector2i(tag.getInt("ResolutionX"), tag.getInt("ResolutionY"));
ret.rotation = Rotation.values()[tag.getByte("Rotation")];
ret.url = tag.getString("URL");
ret.videoType = VideoType.getTypeFromURL(ret.url);
if (ret.resolution.x <= 0 || ret.resolution.y <= 0) {
float psx = ((float) ret.size.x) * 16.f - 4.f;
float psy = ((float) ret.size.y) * 16.f - 4.f;
psx *= 8.f; //TODO: Use ratio in config file
psy *= 8.f;
ret.resolution.x = (int) psx;
ret.resolution.y = (int) psy;
}
if (tag.contains("OwnerName")) {
String name = tag.getString("OwnerName");
UUID uuid = tag.getUUID("OwnerUUID");
ret.owner = new NameUUIDPair(name, uuid);
}
ListTag friends = tag.getList("Friends", 10);
ret.friends = new ArrayList<>(friends.size());
for (int i = 0; i < friends.size(); i++) {
CompoundTag nf = friends.getCompound(i);
NameUUIDPair pair = new NameUUIDPair(nf.getString("Name"), nf.getUUID("UUID"));
ret.friends.add(pair);
}
ret.friendRights = tag.getByte("FriendRights");
ret.otherRights = tag.getByte("OtherRights");
ListTag upgrades = tag.getList("Upgrades", 10);
ret.upgrades = new ArrayList<>();
for (int i = 0; i < upgrades.size(); i++)
ret.upgrades.add(ItemStack.of(upgrades.getCompound(i)));
if (tag.contains("AutoVolume"))
ret.autoVolume = tag.getBoolean("AutoVolume");
return ret;
}
public CompoundTag serialize() {
CompoundTag tag = new CompoundTag();
tag.putByte("Side", (byte) side.ordinal());
tag.putInt("Width", size.x);
tag.putInt("Height", size.y);
tag.putInt("ResolutionX", resolution.x);
tag.putInt("ResolutionY", resolution.y);
tag.putByte("Rotation", (byte) rotation.ordinal());
tag.putString("URL", url);
if (owner == null)
Log.warning("Found TES with NO OWNER!!");
else {
tag.putString("OwnerName", owner.name);
tag.putUUID("OwnerUUID", owner.uuid);
}
ListTag list = new ListTag();
for (NameUUIDPair f : friends) {
CompoundTag nf = new CompoundTag();
nf.putString("Name", f.name);
nf.putUUID("UUID", f.uuid);
list.add(nf);
}
tag.put("Friends", list);
tag.putByte("FriendRights", (byte) friendRights);
tag.putByte("OtherRights", (byte) otherRights);
list = new ListTag();
for (ItemStack is : upgrades)
list.add(is.save(new CompoundTag()));
tag.put("Upgrades", list);
tag.putBoolean("AutoVolume", autoVolume);
return tag;
}
public int rightsFor(Player ply) {
return rightsFor(ply.getGameProfile().getId());
}
public int rightsFor(UUID uuid) {
if (owner.uuid.equals(uuid))
return ScreenRights.ALL;
return friends.stream().anyMatch(f -> f.uuid.equals(uuid)) ? friendRights : otherRights;
}
public void setupRedstoneStatus(Level world, BlockPos start) {
if (world.isClientSide()) {
Log.warning("Called Screen.setupRedstoneStatus() on client.");
return;
}
if (redstoneStatus != null) {
Log.warning("Called Screen.setupRedstoneStatus() on server, but redstone status is non-null");
return;
}
Direction[] VALUES = Direction.values();
redstoneStatus = new NibbleArray(size.x * size.y);
final Direction facing = VALUES[side.reverse().ordinal()];
final ScreenIterator it = new ScreenIterator(start, side, size);
while (it.hasNext()) {
int idx = it.getIndex();
redstoneStatus.set(idx, world.getSignal(it.next(), facing));
}
}
public void clampResolution() {
if (resolution.x > CommonConfig.Screen.maxResolutionX) {
float newY = ((float) resolution.y) * ((float) CommonConfig.Screen.maxResolutionX) / ((float) resolution.x);
resolution.x = CommonConfig.Screen.maxResolutionX;
resolution.y = (int) newY;
}
if (resolution.y > CommonConfig.Screen.maxResolutionY) {
float newX = ((float) resolution.x) * ((float) CommonConfig.Screen.maxResolutionY) / ((float) resolution.y);
resolution.x = (int) newX;
resolution.y = CommonConfig.Screen.maxResolutionY;
}
}
public void createBrowser(ScreenBlockEntity be, boolean doAnim) {
if (WebDisplays.PROXY instanceof ClientProxy) {
browser = WDBrowser.createBrowser(WebDisplays.applyBlacklist(url != null ? url : "https://www.google.com"), false);
// set screen
if (browser instanceof MCEFBrowser mcefBrowser) {
if (rotation.isVertical)
mcefBrowser.resize(resolution.y, resolution.x);
else
mcefBrowser.resize(resolution.x, resolution.y);
mcefBrowser.setCursorChangeListener((type) -> mouseType = type);
}
// setup screen as in world
if (browser instanceof WDBrowser wdBrowser) {
InWorldQueries.attach(be, side, wdBrowser);
}
doTurnOnAnim = doAnim;
turnOnTime = System.currentTimeMillis();
}
}
}

View File

@ -12,16 +12,15 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.data.ServerData; import net.montoyo.wd.data.ServerData;
import net.montoyo.wd.init.TileInit; import net.montoyo.wd.registry.TileRegistry;
import net.montoyo.wd.utilities.NameUUIDPair; import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
public class TileEntityServer extends BlockEntity {
public class ServerBlockEntity extends BlockEntity {
private NameUUIDPair owner; private NameUUIDPair owner;
public TileEntityServer(BlockPos arg2, BlockState arg3) { public ServerBlockEntity(BlockPos arg2, BlockState arg3) {
super(TileInit.SERVER.get(), arg2, arg3); super(TileRegistry.SERVER.get(), arg2, arg3);
} }
@Override @Override
@ -29,7 +28,7 @@ public class TileEntityServer extends BlockEntity {
super.load(tag); super.load(tag);
owner = Util.readOwnerFromNBT(tag); owner = Util.readOwnerFromNBT(tag);
} }
@Override @Override
protected void saveAdditional(CompoundTag tag) { protected void saveAdditional(CompoundTag tag) {
super.saveAdditional(tag); super.saveAdditional(tag);
@ -42,13 +41,12 @@ public class TileEntityServer extends BlockEntity {
} }
public void onPlayerRightClick(Player ply) { public void onPlayerRightClick(Player ply) {
if(level.isClientSide) if (level.isClientSide)
return; return;
if( WebDisplays.INSTANCE.miniservPort == 0) if (WebDisplays.INSTANCE.miniservPort == 0)
Util.toast(ply, "noMiniserv"); Util.toast(ply, "noMiniserv");
else if(owner != null && ply instanceof ServerPlayer) else if (owner != null && ply instanceof ServerPlayer)
(new ServerData(getBlockPos(), owner)).sendTo((ServerPlayer) ply); (new ServerData(getBlockPos(), owner)).sendTo((ServerPlayer) ply);
} }
} }

View File

@ -1,32 +0,0 @@
package net.montoyo.wd.init;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.material.Material;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import net.montoyo.wd.block.BlockKeyboardLeft;
import net.montoyo.wd.block.BlockKeyboardRight;
import net.montoyo.wd.block.BlockPeripheral;
import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.core.DefaultPeripheral;
public class BlockInit {
public static void init(IEventBus bus) {
BLOCKS.register(bus);
}
public static DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, "webdisplays");
public static final RegistryObject<BlockScreen> blockScreen = BLOCKS.register("screen", () -> new BlockScreen(BlockBehaviour.Properties.of(Material.STONE)));
public static final RegistryObject<BlockKeyboardLeft> blockKeyBoard = BlockInit.BLOCKS.register("kb_left", BlockKeyboardLeft::new);
public static final RegistryObject<BlockKeyboardRight> blockKbRight = BLOCKS.register("kb_right", BlockKeyboardRight::new);
public static final RegistryObject<BlockPeripheral> blockRedControl = BlockInit.BLOCKS.register("redctrl", () -> new BlockPeripheral(DefaultPeripheral.REDSTONE_CONTROLLER));
public static final RegistryObject<BlockPeripheral> blockRControl = BlockInit.BLOCKS.register("rctrl", () -> new BlockPeripheral(DefaultPeripheral.REMOTE_CONTROLLER));
public static final RegistryObject<BlockPeripheral> blockServer = BlockInit.BLOCKS.register("server", () -> new BlockPeripheral(DefaultPeripheral.SERVER));
}

View File

@ -1,39 +0,0 @@
package net.montoyo.wd.init;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import net.montoyo.wd.core.DefaultPeripheral;
import net.montoyo.wd.entity.*;
import java.util.Locale;
public class TileInit {
public static final DeferredRegister<BlockEntityType<?>> TILE_TYPES = DeferredRegister
.create(ForgeRegistries.BLOCK_ENTITY_TYPES, "webdisplays");
//Register tile entities
public static final RegistryObject<BlockEntityType<TileEntityScreen>> SCREEN_BLOCK_ENTITY = TILE_TYPES
.register("screen", () -> BlockEntityType.Builder
.of(TileEntityScreen::new, BlockInit.blockScreen.get()).build(null));
public static final RegistryObject<BlockEntityType<?>> KEYBOARD = TILE_TYPES.register("kb_left", () -> BlockEntityType.Builder
.of(TileEntityKeyboard::new, BlockInit.blockKeyBoard.get()).build(null));
public static final RegistryObject<BlockEntityType<?>> REMOTE_CONTROLLER = TILE_TYPES.register("rctrl",
() -> BlockEntityType.Builder.of(TileEntityRCtrl::new, BlockInit.blockRControl.get()).build(null)); //WITHOUT FACING (>= 3)
public static final RegistryObject<BlockEntityType<?>> REDSTONE_CONTROLLER = TILE_TYPES.register("redctrl",
() -> BlockEntityType.Builder.of(TileEntityRedCtrl::new, BlockInit.blockRedControl.get()).build(null));
public static final RegistryObject<BlockEntityType<?>> SERVER = TILE_TYPES.register("server" ,
() -> BlockEntityType.Builder.of(TileEntityServer::new, BlockInit.blockServer.get()).build(null));
public static void init(IEventBus bus) {
TILE_TYPES.register(bus);
}
}

View File

@ -10,11 +10,10 @@ import net.montoyo.wd.core.CraftComponent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class ItemCraftComponent extends ItemMulti implements WDItem { public class ItemCraftComponent extends ItemMulti implements WDItem {
public ItemCraftComponent(Properties properties) { public ItemCraftComponent(Properties properties) {
super(CraftComponent.class, properties super(CraftComponent.class, properties
//setRegistryName("craftcomp"); // .tab(WebDisplays.CREATIVE_TAB)
.tab(WebDisplays.CREATIVE_TAB)); );
//Hide the bad extension card from the creative tab //Hide the bad extension card from the creative tab
creativeTabItems.clear(CraftComponent.BADEXTCARD.ordinal()); creativeTabItems.clear(CraftComponent.BADEXTCARD.ordinal());

View File

@ -11,21 +11,20 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.block.ScreenBlock;
import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.client.JSQueryDispatcher;
import net.montoyo.wd.config.ClientConfig; import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.controls.builtin.ClickControl; import net.montoyo.wd.controls.builtin.ClickControl;
import net.montoyo.wd.core.DefaultUpgrade; import net.montoyo.wd.core.DefaultUpgrade;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.init.BlockInit; import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.registry.BlockRegistry;
import net.montoyo.wd.utilities.Multiblock; import net.montoyo.wd.utilities.Multiblock;
import net.montoyo.wd.utilities.Vector2i; import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.math.Vector3i;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -34,13 +33,13 @@ public class ItemLaserPointer extends Item implements WDItem {
public ItemLaserPointer(Properties properties) { public ItemLaserPointer(Properties properties) {
super(properties super(properties
//setRegistryName("laserpointer")
.stacksTo(1) .stacksTo(1)
.tab(WebDisplays.CREATIVE_TAB)); // .tab(WebDisplays.CREATIVE_TAB)
);
} }
//Laser pointer //Laser pointer
private static TileEntityScreen pointedScreen; private static ScreenBlockEntity pointedScreen;
private static BlockSide pointedScreenSide; private static BlockSide pointedScreenSide;
private static long lastPointPacket; private static long lastPointPacket;
@ -54,16 +53,16 @@ public class ItemLaserPointer extends Item implements WDItem {
BlockPos bpos = result.getBlockPos(); BlockPos bpos = result.getBlockPos();
if (result.getType() == HitResult.Type.BLOCK && mc.level.getBlockState(bpos).getBlock() == BlockInit.blockScreen.get()) { if (result.getType() == HitResult.Type.BLOCK && mc.level.getBlockState(bpos).getBlock() == BlockRegistry.SCREEN_BLOCk.get()) {
Vector3i pos = new Vector3i(result.getBlockPos()); Vector3i pos = new Vector3i(result.getBlockPos());
BlockSide side = BlockSide.values()[result.getDirection().ordinal()]; BlockSide side = BlockSide.values()[result.getDirection().ordinal()];
Multiblock.findOrigin(mc.level, pos, side, null); Multiblock.findOrigin(mc.level, pos, side, null);
TileEntityScreen te = (TileEntityScreen) mc.level.getBlockEntity(pos.toBlock()); ScreenBlockEntity te = (ScreenBlockEntity) mc.level.getBlockEntity(pos.toBlock());
if (te != null && te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side' if (te != null && te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side'
//Since rights aren't synchronized, let the server check them for us... //Since rights aren't synchronized, let the server check them for us...
TileEntityScreen.Screen scr = te.getScreen(side); ScreenData scr = te.getScreen(side);
if (scr.browser != null) { if (scr.browser != null) {
float hitX = ((float) result.getLocation().x) - (float) pos.x; float hitX = ((float) result.getLocation().x) - (float) pos.x;
@ -71,7 +70,7 @@ public class ItemLaserPointer extends Item implements WDItem {
float hitZ = ((float) result.getLocation().z) - (float) pos.z; float hitZ = ((float) result.getLocation().z) - (float) pos.z;
Vector2i tmp = new Vector2i(); Vector2i tmp = new Vector2i();
if (BlockScreen.hit2pixels(side, bpos, new Vector3i(result.getBlockPos()), scr, hitX, hitY, hitZ, tmp)) { if (ScreenBlock.hit2pixels(side, bpos, new Vector3i(result.getBlockPos()), scr, hitX, hitY, hitZ, tmp)) {
laserClick(te, side, scr, tmp); laserClick(te, side, scr, tmp);
} }
} }
@ -79,11 +78,11 @@ public class ItemLaserPointer extends Item implements WDItem {
} }
} }
public static void deselect(Minecraft mc, JSQueryDispatcher jsDispatcher) { public static void deselect(Minecraft mc) {
deselectScreen(); deselectScreen();
} }
private static void laserClick(TileEntityScreen tes, BlockSide side, TileEntityScreen.Screen scr, Vector2i hit) { private static void laserClick(ScreenBlockEntity tes, BlockSide side, ScreenData scr, Vector2i hit) {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1); tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
if (pointedScreen == tes && pointedScreenSide == side) { if (pointedScreen == tes && pointedScreenSide == side) {
long t = System.currentTimeMillis(); long t = System.currentTimeMillis();
@ -107,7 +106,7 @@ public class ItemLaserPointer extends Item implements WDItem {
} }
public static void press(boolean press, int button) { public static void press(boolean press, int button) {
if (button <= 1 && ClientConfig.switchButtons) if (button <= 1 && ClientConfig.Input.switchButtons)
button = 1 - button; button = 1 - button;
if (button == 0) left = press; if (button == 0) left = press;
@ -121,32 +120,23 @@ public class ItemLaserPointer extends Item implements WDItem {
BlockSide side = BlockSide.values()[result.getDirection().ordinal()]; BlockSide side = BlockSide.values()[result.getDirection().ordinal()];
Multiblock.findOrigin(mc.level, pos, side, null); Multiblock.findOrigin(mc.level, pos, side, null);
float hitX = ((float) result.getLocation().x) - (float) pos.x;
float hitY = ((float) result.getLocation().y) - (float) pos.y;
float hitZ = ((float) result.getLocation().z) - (float) pos.z;
Vector2i tmp = new Vector2i();
BlockEntity be = mc.level.getBlockEntity(pos.toBlock()); BlockEntity be = mc.level.getBlockEntity(pos.toBlock());
if (!(be instanceof TileEntityScreen)) return; if (!(be instanceof ScreenBlockEntity)) return;
//noinspection PatternVariableCanBeUsed //noinspection PatternVariableCanBeUsed
TileEntityScreen te = (TileEntityScreen) be; ScreenBlockEntity te = (ScreenBlockEntity) be;
if (te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side' if (te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side'
//Since rights aren't synchronized, let the server check them for us... int finalButton = button;
TileEntityScreen.Screen scr = te.getScreen(side); te.interact(result, (hit) -> {
te.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
if (scr.browser != null) { te.handleMouseEvent(side, press ? ClickControl.ControlType.DOWN : ClickControl.ControlType.UP, hit, finalButton);
if (BlockScreen.hit2pixels(side, result.getBlockPos(), new Vector3i(result.getBlockPos()), scr, hitX, hitY, hitZ, tmp)) {
te.handleMouseEvent(side, ClickControl.ControlType.MOVE, tmp, -1); if (press)
te.handleMouseEvent(side, press ? ClickControl.ControlType.DOWN : ClickControl.ControlType.UP, tmp, button); WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserDown(te, side, hit, finalButton));
else
if (press) WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserUp(te, side, finalButton));
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserDown(te, side, tmp, button)); });
else
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserUp(te, side, button));
}
}
} }
} }

View File

@ -14,46 +14,46 @@ import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.block.BlockScreen; import net.montoyo.wd.block.ScreenBlock;
import net.montoyo.wd.core.IPeripheral; import net.montoyo.wd.core.IPeripheral;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.TileEntityScreen; import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.utilities.BlockSide; import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Multiblock; import net.montoyo.wd.utilities.Multiblock;
import net.montoyo.wd.utilities.Util; import net.montoyo.wd.utilities.serialization.Util;
import net.montoyo.wd.utilities.Vector3i; import net.montoyo.wd.utilities.math.Vector3i;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class ItemLinker extends Item implements WDItem { public class ItemLinker extends Item implements WDItem {
public ItemLinker(Properties properties) { public ItemLinker(Properties properties) {
super(properties super(properties
//setRegistryName("linker"); .stacksTo(1)
.stacksTo(1) // .tab(WebDisplays.CREATIVE_TAB)
.tab(WebDisplays.CREATIVE_TAB)); );
} }
@Override @Override
public InteractionResult useOn(UseOnContext context) { public InteractionResult useOn(UseOnContext context) {
if(context.getLevel().isClientSide()) if (context.getLevel().isClientSide())
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
ItemStack stack = context.getPlayer().getItemInHand(context.getHand()); ItemStack stack = context.getPlayer().getItemInHand(context.getHand());
CompoundTag tag = stack.getTag(); CompoundTag tag = stack.getTag();
if(tag != null) { if (tag != null) {
if(tag.contains("ScreenX") && tag.contains("ScreenY") && tag.contains("ScreenZ") && tag.contains("ScreenSide")) { if (tag.contains("ScreenX") && tag.contains("ScreenY") && tag.contains("ScreenZ") && tag.contains("ScreenSide")) {
BlockState state = context.getLevel().getBlockState(context.getClickedPos()); BlockState state = context.getLevel().getBlockState(context.getClickedPos());
IPeripheral target; IPeripheral target;
if(state.getBlock() instanceof IPeripheral) if (state.getBlock() instanceof IPeripheral)
target = (IPeripheral) state.getBlock(); target = (IPeripheral) state.getBlock();
else { else {
BlockEntity te = context.getLevel().getBlockEntity(context.getClickedPos()); BlockEntity te = context.getLevel().getBlockEntity(context.getClickedPos());
if(te == null || !(te instanceof IPeripheral)) { if (te == null || !(te instanceof IPeripheral)) {
if(context.getPlayer().isShiftKeyDown()) { if (context.getPlayer().isShiftKeyDown()) {
Util.toast(context.getPlayer(), ChatFormatting.GOLD, "linkAbort"); Util.toast(context.getPlayer(), ChatFormatting.GOLD, "linkAbort");
stack.setTag(null); stack.setTag(null);
} else } else
@ -68,10 +68,10 @@ public class ItemLinker extends Item implements WDItem {
Vector3i tePos = new Vector3i(tag.getInt("ScreenX"), tag.getInt("ScreenY"), tag.getInt("ScreenZ")); Vector3i tePos = new Vector3i(tag.getInt("ScreenX"), tag.getInt("ScreenY"), tag.getInt("ScreenZ"));
BlockSide scrSide = BlockSide.values()[tag.getByte("ScreenSide")]; BlockSide scrSide = BlockSide.values()[tag.getByte("ScreenSide")];
if(target.connect(context.getLevel(), context.getClickedPos(), state, tePos, scrSide)) { if (target.connect(context.getLevel(), context.getClickedPos(), state, tePos, scrSide)) {
Util.toast(context.getPlayer(), ChatFormatting.AQUA, "linked"); Util.toast(context.getPlayer(), ChatFormatting.AQUA, "linked");
if(context.getPlayer() instanceof ServerPlayer) if (context.getPlayer() instanceof ServerPlayer)
WebDisplays.INSTANCE.criterionLinkPeripheral.trigger(((ServerPlayer) context.getPlayer()).getAdvancements()); WebDisplays.INSTANCE.criterionLinkPeripheral.trigger(((ServerPlayer) context.getPlayer()).getAdvancements());
} else } else
Util.toast(context.getPlayer(), "linkError"); Util.toast(context.getPlayer(), "linkError");
@ -81,7 +81,7 @@ public class ItemLinker extends Item implements WDItem {
} }
} }
if(!(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof BlockScreen)) { if (!(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof ScreenBlock)) {
Util.toast(context.getPlayer(), "notAScreen"); Util.toast(context.getPlayer(), "notAScreen");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
@ -91,15 +91,15 @@ public class ItemLinker extends Item implements WDItem {
Multiblock.findOrigin(context.getLevel(), pos, side, null); Multiblock.findOrigin(context.getLevel(), pos, side, null);
BlockEntity te = context.getLevel().getBlockEntity(pos.toBlock()); BlockEntity te = context.getLevel().getBlockEntity(pos.toBlock());
if(te == null || !(te instanceof TileEntityScreen)) { if (te == null || !(te instanceof ScreenBlockEntity)) {
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
TileEntityScreen.Screen scr = ((TileEntityScreen) te).getScreen(side); ScreenData scr = ((ScreenBlockEntity) te).getScreen(side);
if(scr == null) if(scr == null)
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
else if((scr.rightsFor(context.getPlayer()) & ScreenRights.MANAGE_UPGRADES) == 0) else if ((scr.rightsFor(context.getPlayer()) & ScreenRights.MANAGE_UPGRADES) == 0)
Util.toast(context.getPlayer(), "restrictions"); Util.toast(context.getPlayer(), "restrictions");
else { else {
tag = new CompoundTag(); tag = new CompoundTag();
@ -120,5 +120,4 @@ public class ItemLinker extends Item implements WDItem {
public String getWikiName(@Nonnull ItemStack is) { public String getWikiName(@Nonnull ItemStack is) {
return is.getItem().getName(is).getString(); return is.getItem().getName(is).getString();
} }
} }

Some files were not shown because too many files have changed in this diff Show More