commit 3331ab745b80625c64bdb1b063fa99db2feb5eb3 Author: Dark98 Date: Mon Nov 30 20:45:03 2026 +0000 feat(web): add 2006Scape TeaVM WebGL2 client with mobile support and classic 2006 UI Initializes the TeaVM-based 2006Scape-Web client repository with WebGL2 117HD rendering, WebSocket networking, SpessaSynth MIDI/PCM audio, and mobile-compatible touch/viewport controls. Preserves Revision 377 cache preloading via IndexedDB and localStorage-backed script and config persistence. ### Core Web Runtime & Rendering - WebLauncher & DesktopHooks: - Added TeaVM entry point with URL/localStorage option parsing, async 377 cache preloading, and WebSocket port routing. - Implemented DesktopHooks.boxReflectValue using JSWrapper.isJava/maybeUnwrap to box TeaVM reflection primitives, plus localStorage persistence for plugin settings and imported scripts. - WebHd117Renderer & RSImageProducer: - Implemented WebGL2 117HD rendering with 4x4 chunked static scenery VBOs and 0x010203 transparency sentinel so 0x000000 black UI elements stay opaque. - WebReflectionSupplier: - Exposed PluginContext, PluginGraphics, ScriptInterpreter, ID lists, and Math/System/String/collection methods for TeaVM runtime reflection. ### Mobile & Classic 2006 Web UI - index.html & RSApplet: - Styled the page to match the classic 2006 RuneScape webclient with optional classic navbar (auto-hidden below 765px), 1999-2006 Jagex footer, and responsive Fixed/Resizable/Fullscreen scaling. - Added Options modal (auto-login, server, world, 117HD, display mode, navbar) with scrollable body in mobile landscape. - Implemented Android-parity touch controls (tap, 450ms long-press right-click, 1-finger camera drag, 2-finger pinch zoom clamped to -1..8, and auto-keyboard on input fields). diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..84d2250 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/ +.gradle/ +.idea/ +*.iml diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..a833fdd --- /dev/null +++ b/build.gradle @@ -0,0 +1,130 @@ +plugins { + id 'java' + id 'org.teavm' version '0.10.2' +} + +group = 'org.scape2006.web' +version = '1.0.0' + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + +repositories { + mavenCentral() +} + +def findClientDir(String subpath) { + def candidates = [ + file("../2006Scape/2006Scape Client/${subpath}"), + file("../../2006Scape/2006Scape Client/${subpath}"), + file("../2006Scape Client/${subpath}") + ] + for (cand in candidates) { + if (cand.exists()) return cand + } + return file("../2006Scape/2006Scape Client/${subpath}") +} + +def sharedClientSrc = findClientDir("src/main/java") +def sharedClientRes = findClientDir("src/main/resources") +def sharedClientDir = layout.buildDirectory.dir("generated/sources/sharedClient/java") + +def syncSharedSources = tasks.register('syncSharedSources') { + inputs.dir(sharedClientSrc) + outputs.dir(sharedClientDir) + doLast { + def targetPkgDir = file("${sharedClientDir.get().asFile}/org/scape2006/web") + targetPkgDir.deleteDir() + targetPkgDir.mkdirs() + def excluded = [ + 'RSApplet.java', 'RSImageProducer.java', 'RSFrame.java', + 'Main.java', 'LocalGame.java', 'Class56_Sub1_Sub1.java', + 'DesktopHooks.java', 'AndroidHooks.java', 'DesktopHd117Renderer.java', + 'SoundPlayer.java', 'Midi.java', 'Client.java', + 'RSSocket.java', 'Signlink.java', 'Decompressor.java', + 'ExternalPluginLoader.java' + ] as Set + fileTree(sharedClientSrc).visit { element -> + if (element.directory) return + if (excluded.contains(element.name)) return + def dest = new File(targetPkgDir, element.name) + def src = element.file.text + src = src.replace('java.net.Socket', 'org.scape2006.web.net.Socket') + src = src.replace('java.net.InetAddress', 'org.scape2006.web.net.InetAddress') + src = src.replace('java.net.InetSocketAddress', 'org.scape2006.web.net.InetSocketAddress') + if (element.name == 'Game.java') { + src = src.replace('Signlink.reporterror("glfc_ex "', 'Signlink.reporterror("glfc_ex " + _ex + " | "') + } + dest.text = "package org.scape2006.web;\n" + src + } + } +} + +sourceSets { + main { + java { + srcDirs = ['src/main/java', sharedClientDir] + } + resources { + srcDirs = ['src/main/resources', sharedClientRes] + } + } +} + +tasks.named('compileJava').configure { + dependsOn syncSharedSources + options.encoding = 'UTF-8' +} + +dependencies { + implementation teavm.libs.jso + implementation teavm.libs.jsoApis + compileOnly 'org.teavm:teavm-classlib:0.10.2' + compileOnly 'org.teavm:teavm-core:0.10.2' +} + +teavm { + all { + mainClass = 'org.scape2006.web.WebLauncher' + } + js { + addedToWebApp = true + targetFileName = 'client.js' + obfuscated = false + sourceMap = true + } +} + +tasks.named('generateJavaScript').configure { + doLast { + def jsFile = file("${buildDir}/generated/teavm/js/js/client.js") + if (!jsFile.exists()) { + jsFile = file("${buildDir}/generated/teavm/js/client.js") + } + if (jsFile.exists()) { + def text = jsFile.text + def target = '$rt_createMultiArrayImpl = (cls, arrays, dimensions, start) => {' + if (text.contains(target)) { + jsFile.text = text.replace(target, target + ' start = start | 0;') + } + } + } +} + +tasks.register('dist', Copy) { + dependsOn 'generateJavaScript' + from('src/main/webapp') + from(sharedClientRes) { + include 'hud_minimap_bezel.png', 'hud_minimap_hole.png', 'hud_chat_frame.png', 'navbar*.gif' + } + from(layout.buildDirectory.dir('generated/teavm/js')) { + into 'js' + } + into layout.buildDirectory.dir('dist') +} + +tasks.named('build').configure { + dependsOn 'dist' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..2b338a9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..99fbfa0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Nov 11 18:20:34 PST 2021 +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..3427607 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|grep -E -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|grep -E -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..deb5638 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = '2006Scape-Web' diff --git a/src/main/java/org/scape2006/web/AndroidHooks.java b/src/main/java/org/scape2006/web/AndroidHooks.java new file mode 100644 index 0000000..bab5140 --- /dev/null +++ b/src/main/java/org/scape2006/web/AndroidHooks.java @@ -0,0 +1,32 @@ +package org.scape2006.web; + +/** + * Web stub for AndroidHooks so shared code guarded by ClientSettings.ANDROID compiles cleanly. + */ +public final class AndroidHooks { + + private AndroidHooks() {} + + public static boolean isAppInBackground() { return false; } + public static void decodeImage(Sprite sprite, byte[] abyte0) {} + public static String getClipBoard() { return ""; } + public static void takeScreenshot(Game game, boolean sendMessage, String... subfolders) {} + public static void showErrorScreen(Game game, boolean loadingError, boolean genericLoadingError, boolean rsAlreadyLoaded) {} + public static void playSound(byte[] buffer, int offset, int length, int level, int delay) {} + public static void setSoundVolume(int config) {} + public static String getCacheDir() { return "/cache/"; } + public static void playMidi(String location, int midiVolume) {} + public static void stopMidi() {} + public static boolean setMidiVolume(int value) { return false; } + public static Object getMusicPlayer() { return null; } + public static void pauseMidi() {} + public static void resumeMidi() {} + public static void showKeyboard() {} + public static void hideKeyboard() {} + public static void drawModernMinimap(Object graphics, int[] minimapPixels, int windowWidth) {} + public static Object getRenderGraphics(Object screenGraphics) { return screenGraphics; } + public static void flip(Object screenGraphics) {} + public static void loadExternalDexPlugins(java.io.File file, java.util.List plugins, java.util.List scripts) {} + public static void showPluginManagerDialog(Game game) {} + public static void openScriptsFolder() {} +} diff --git a/src/main/java/org/scape2006/web/Decompressor.java b/src/main/java/org/scape2006/web/Decompressor.java new file mode 100644 index 0000000..cf83203 --- /dev/null +++ b/src/main/java/org/scape2006/web/Decompressor.java @@ -0,0 +1,190 @@ +package org.scape2006.web; + +import java.io.IOException; + +/** + * Web Decompressor operating on VirtualFile buffers instead of RandomAccessFile. + */ +final class Decompressor { + + private final byte[] buffer = new byte[520]; + private final VirtualFile dataFile; + private final VirtualFile indexFile; + private final int anInt311; + + public Decompressor(VirtualFile dataFile, VirtualFile indexFile, int id) { + this.anInt311 = id; + this.dataFile = dataFile; + this.indexFile = indexFile; + } + + public synchronized byte[] decompress(int i) { + try { + seekTo(indexFile, i * 6L); + int l; + for (int j = 0; j < 6; j += l) { + l = indexFile.read(buffer, j, 6 - j); + if (l == -1) { + return null; + } + } + + int i1 = ((buffer[0] & 0xff) << 16) + ((buffer[1] & 0xff) << 8) + (buffer[2] & 0xff); + int j1 = ((buffer[3] & 0xff) << 16) + ((buffer[4] & 0xff) << 8) + (buffer[5] & 0xff); + if (j1 <= 0 || j1 > dataFile.length() / 520L) { + return null; + } + byte[] abyte0 = new byte[i1]; + int k1 = 0; + for (int l1 = 0; k1 < i1; l1++) { + if (j1 == 0) { + return null; + } + seekTo(dataFile, j1 * 520L); + int k = 0; + int i2 = i1 - k1; + if (i2 > 512) { + i2 = 512; + } + int j2; + for (; k < i2 + 8; k += j2) { + j2 = dataFile.read(buffer, k, i2 + 8 - k); + if (j2 == -1) { + return null; + } + } + + int k2 = ((buffer[0] & 0xff) << 8) + (buffer[1] & 0xff); + int l2 = ((buffer[2] & 0xff) << 8) + (buffer[3] & 0xff); + int i3 = ((buffer[4] & 0xff) << 16) + ((buffer[5] & 0xff) << 8) + (buffer[6] & 0xff); + int j3 = buffer[7] & 0xff; + if (k2 != i || l2 != l1 || j3 != anInt311) { + return null; + } + if (i3 < 0 || i3 > dataFile.length() / 520L) { + return null; + } + for (int k3 = 0; k3 < i2; k3++) { + abyte0[k1++] = buffer[k3 + 8]; + } + j1 = i3; + } + return abyte0; + } catch (IOException ex) { + return null; + } + } + + public synchronized boolean method234(int i, byte[] abyte0, int j) { + boolean flag = method235(true, j, i, abyte0); + if (!flag) { + flag = method235(false, j, i, abyte0); + } + return flag; + } + + private synchronized boolean method235(boolean flag, int j, int k, byte[] abyte0) { + try { + int l; + if (flag) { + seekTo(indexFile, j * 6L); + int k1; + for (int i1 = 0; i1 < 6; i1 += k1) { + k1 = indexFile.read(buffer, i1, 6 - i1); + if (k1 == -1) { + return false; + } + } + l = ((buffer[3] & 0xff) << 16) + ((buffer[4] & 0xff) << 8) + (buffer[5] & 0xff); + if (l <= 0 || l > dataFile.length() / 520L) { + return false; + } + } else { + l = (int) ((dataFile.length() + 519L) / 520L); + if (l == 0) { + l = 1; + } + } + buffer[0] = (byte) (k >> 16); + buffer[1] = (byte) (k >> 8); + buffer[2] = (byte) k; + buffer[3] = (byte) (l >> 16); + buffer[4] = (byte) (l >> 8); + buffer[5] = (byte) l; + seekTo(indexFile, j * 6L); + indexFile.write(buffer, 0, 6); + + int j1 = 0; + for (int l1 = 0; j1 < k; l1++) { + int i2 = 0; + if (flag) { + seekTo(dataFile, l * 520L); + int j2; + int i3; + for (j2 = 0; j2 < 8; j2 += i3) { + i3 = dataFile.read(buffer, j2, 8 - j2); + if (i3 == -1) { + break; + } + } + if (j2 == 8) { + int j3 = ((buffer[0] & 0xff) << 8) + (buffer[1] & 0xff); + int k3 = ((buffer[2] & 0xff) << 8) + (buffer[3] & 0xff); + i2 = ((buffer[4] & 0xff) << 16) + ((buffer[5] & 0xff) << 8) + (buffer[6] & 0xff); + int l3 = buffer[7] & 0xff; + if (j3 != j || k3 != l1 || l3 != anInt311) { + return false; + } + if (i2 < 0 || i2 > dataFile.length() / 520L) { + return false; + } + } + } + if (i2 == 0) { + flag = false; + i2 = (int) ((dataFile.length() + 519L) / 520L); + if (i2 == 0) { + i2++; + } + if (i2 == l) { + i2++; + } + } + if (k - j1 <= 512) { + i2 = 0; + } + buffer[0] = (byte) (j >> 8); + buffer[1] = (byte) j; + buffer[2] = (byte) (l1 >> 8); + buffer[3] = (byte) l1; + buffer[4] = (byte) (i2 >> 16); + buffer[5] = (byte) (i2 >> 8); + buffer[6] = (byte) i2; + buffer[7] = (byte) anInt311; + seekTo(dataFile, l * 520L); + dataFile.write(buffer, 0, 8); + int k2 = k - j1; + if (k2 > 512) { + k2 = 512; + } + dataFile.write(abyte0, j1, k2); + j1 += k2; + l = i2; + } + return true; + } catch (IOException ex) { + return false; + } + } + + private synchronized void seekTo(VirtualFile file, long pos) throws IOException { + if (pos < 0 || pos > 0x3c00000L) { + pos = 0x3c00000L; + try { + Thread.sleep(1000L); + } catch (Exception ignored) { + } + } + file.seek(pos); + } +} diff --git a/src/main/java/org/scape2006/web/DesktopHooks.java b/src/main/java/org/scape2006/web/DesktopHooks.java new file mode 100644 index 0000000..76147af --- /dev/null +++ b/src/main/java/org/scape2006/web/DesktopHooks.java @@ -0,0 +1,644 @@ +package org.scape2006.web; + +import org.teavm.interop.Async; +import org.teavm.interop.AsyncCallback; +import org.teavm.jso.JSBody; +import org.teavm.jso.JSByRef; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; +import org.teavm.jso.dom.html.HTMLCanvasElement; +import org.teavm.jso.typedarrays.Uint8Array; +import org.teavm.jso.typedarrays.Uint8ClampedArray; + +/** + * Web implementation of DesktopHooks for TeaVM. + * Bridges audio (Web Audio + SpessaSynth), clipboard, screenshots, and 117HD backend init. + */ +public final class DesktopHooks { + + private static volatile float soundVolume = 1.0f; + private static volatile float midiVolume = 0.7f; + private static int lastCssWidth = -1; + private static int lastCssHeight = -1; + + private DesktopHooks() {} + + @JSFunctor + public interface ImageDecodeCallback extends JSObject { + void onDecoded(int width, int height, Uint8ClampedArray rgba); + } + + public static void decodeImage(Sprite sprite, byte[] data, Object component) { + if (sprite == null || data == null || data.length == 0) return; + Uint8Array u8 = Uint8Array.create(data.length); + u8.set(data, 0); + decodeImageAsync(u8, sprite); + } + + @Async + private static native void decodeImageAsync(Uint8Array data, Sprite sprite); + + private static void decodeImageAsync(Uint8Array data, Sprite sprite, AsyncCallback callback) { + jsDecodeImage(data, (width, height, rgba) -> { + if (width > 0 && height > 0 && rgba != null) { + sprite.width = width; + sprite.height = height; + sprite.trimWidth = width; + sprite.trimHeight = height; + sprite.anInt1442 = 0; + sprite.anInt1443 = 0; + int count = width * height; + sprite.pixels = new int[count]; + for (int i = 0, j = 0; i < count; i++, j += 4) { + sprite.pixels[i] = ((rgba.get(j) & 255) << 16) + | ((rgba.get(j + 1) & 255) << 8) + | (rgba.get(j + 2) & 255); + } + } else { + RSApplet.appendLog("[DesktopHooks] decodeImage returned 0x0 (bytes=" + data.getLength() + ")"); + } + callback.complete(null); + }); + } + + @JSBody(params = {"bytes", "cb"}, script = + "var blob = new Blob([bytes]);\n" + + "var url = URL.createObjectURL(blob);\n" + + "var img = new Image();\n" + + "img.onload = function() {\n" + + " try {\n" + + " var c = document.createElement('canvas');\n" + + " c.width = img.naturalWidth || img.width;\n" + + " c.height = img.naturalHeight || img.height;\n" + + " var ctx = c.getContext('2d');\n" + + " ctx.drawImage(img, 0, 0);\n" + + " var imgData = ctx.getImageData(0, 0, c.width, c.height);\n" + + " URL.revokeObjectURL(url);\n" + + " cb(c.width, c.height, imgData.data);\n" + + " } catch (e) {\n" + + " URL.revokeObjectURL(url);\n" + + " cb(0, 0, null);\n" + + " }\n" + + "};\n" + + "img.onerror = function() {\n" + + " URL.revokeObjectURL(url);\n" + + " cb(0, 0, null);\n" + + "};\n" + + "img.src = url;") + private static native void jsDecodeImage(Uint8Array bytes, ImageDecodeCallback cb); + + public static String getClipBoard() { + return ""; + } + + public static void takeScreenshot(Game game, boolean sendMessage, String... subfolders) { + ensureHudAssets(); + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + if (canvas != null) { + downloadCanvasPng(canvas, "2006scape_" + System.currentTimeMillis() + ".png"); + } + } + + public static void showErrorScreen(Game game, boolean loadingError, boolean genericLoadingError, boolean rsAlreadyLoaded) { + System.err.println("[2006Scape-Web] Error screen: loading=" + loadingError + " generic=" + genericLoadingError); + } + + public static void checkJavaVersion() {} + + public static void playSound(byte[] buffer, int offset, int length, int level, int delay) { + if (buffer == null || length <= 0 || offset + length > buffer.length) return; + Uint8Array arr = Uint8Array.create(length); + for (int i = 0; i < length; i++) { + arr.set(i, (short) (buffer[offset + i] & 0xFF)); + } + float vol = soundVolume * Math.max(0f, Math.min(1f, level / 100.0f)); + jsPlayPcm(arr, vol); + } + + public static void setSoundVolume(int config) { + // RS volume config: 0 (max) to 4 (off) + soundVolume = (config >= 4) ? 0.0f : Math.max(0.0f, 1.0f - (config * 0.25f)); + } + + public static String getParameter(String s) { + return getUrlParam(s); + } + + public static void showDocument(Object caller, String s) { + if (s != null && !s.isEmpty()) { + openUrl(s); + } + } + + public static void playSignlinkMidi(String location, int vol) { + midiVolume = Math.max(0.0f, Math.min(1.0f, vol / 255.0f)); + jsSetMidiVolume(midiVolume); + } + + public static void playMidiBytes(byte[] midiBytes, int vol) { + if (midiBytes == null || midiBytes.length == 0) return; + midiVolume = Math.max(0.0f, Math.min(1.0f, vol / 255.0f)); + Uint8Array arr = Uint8Array.create(midiBytes.length); + arr.set(midiBytes, 0); + jsPlayMidi(arr, midiVolume); + } + + public static boolean setSignlinkVolume(int vol) { + midiVolume = Math.max(0.0f, Math.min(1.0f, vol / 255.0f)); + jsSetMidiVolume(midiVolume); + return true; + } + + public static void stopSignlinkMidi() { + jsStopMidi(); + } + + private static int[] modernTabPixels = null; + private static boolean[] modernTabMask = null; + private static boolean hudImagesRequested = false; + + public static void drawModernMinimap(Object graphics, int[] minimapPixels, int windowWidth) { + if (minimapPixels == null || minimapPixels.length < 172 * 156) return; + ensureHudAssets(); + ensureHudAssets(); + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + if (canvas == null) return; + Uint8ClampedArray rgba = toRgbaOpaque(minimapPixels, 172 * 156); + jsDrawModernMinimap(canvas, rgba, windowWidth); + } + + public static void drawModernChat(Object graphics, int[] chatContentPixels, int[] chatButtonsPixels, int windowHeight) { + ensureHudAssets(); + ensureHudAssets(); + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + if (canvas == null) return; + Uint8ClampedArray contentRgba = (chatContentPixels != null && chatContentPixels.length >= 479 * 96) + ? toRgbaOpaque(chatContentPixels, 479 * 96) : null; + Uint8ClampedArray buttonsRgba = (chatButtonsPixels != null && chatButtonsPixels.length >= 496 * 50) + ? toRgbaOpaque(chatButtonsPixels, 496 * 50) : null; + jsDrawModernChat(canvas, contentRgba, buttonsRgba, windowHeight); + } + + public static void drawModernTab(Object graphics, int[] topTabPixels, int[] leftPillarTopPixels, + int[] leftPillarMidPixels, int[] leftPillarBotPixels, + int[] tabBodyPixels, int[] rightPillarPixels, int[] bottomTabPixels, + int windowWidth, int windowHeight) { + ensureHudAssets(); + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + if (canvas == null) return; + if (modernTabPixels == null) { + modernTabPixels = new int[249 * 343]; + modernTabMask = new boolean[249 * 343]; + for (int y = 0; y < 343; y++) { + for (int x = 0; x < 249; x++) { + modernTabMask[y * 249 + x] = ModernLayout.isInsideTabArea(x, y); + } + } + } + if (topTabPixels != null && topTabPixels.length >= 249 * 45) { + System.arraycopy(topTabPixels, 0, modernTabPixels, 0, 249 * 45); + } + if (leftPillarTopPixels != null && leftPillarTopPixels.length >= 37 * 133) { + for (int y = 0; y < 133; y++) { + System.arraycopy(leftPillarTopPixels, y * 37, modernTabPixels, (45 + y) * 249, 37); + } + } + if (leftPillarMidPixels != null && leftPillarMidPixels.length >= 553 * 19) { + for (int y = 0; y < 19; y++) { + System.arraycopy(leftPillarMidPixels, y * 553 + 516, modernTabPixels, (178 + y) * 249, 37); + } + } + if (leftPillarBotPixels != null && leftPillarBotPixels.length >= 57 * 109) { + for (int y = 0; y < 109; y++) { + System.arraycopy(leftPillarBotPixels, y * 57 + 20, modernTabPixels, (197 + y) * 249, 37); + } + } + if (tabBodyPixels != null && tabBodyPixels.length >= 190 * 261) { + for (int y = 0; y < 261; y++) { + System.arraycopy(tabBodyPixels, y * 190, modernTabPixels, (45 + y) * 249 + 37, 190); + } + } + if (rightPillarPixels != null && rightPillarPixels.length >= 22 * 261) { + for (int y = 0; y < 261; y++) { + System.arraycopy(rightPillarPixels, y * 22, modernTabPixels, (45 + y) * 249 + 227, 22); + } + } + if (bottomTabPixels != null && bottomTabPixels.length >= 269 * 37) { + for (int y = 0; y < 37; y++) { + System.arraycopy(bottomTabPixels, y * 269 + 20, modernTabPixels, (306 + y) * 249, 249); + } + } + Uint8ClampedArray rgba = Uint8ClampedArray.create(249 * 343 * 4); + int total = 249 * 343; + for (int i = 0, j = 0; i < total; i++, j += 4) { + if (modernTabMask[i]) { + int c = modernTabPixels[i]; + rgba.set(j, (short) ((c >> 16) & 255)); + rgba.set(j + 1, (short) ((c >> 8) & 255)); + rgba.set(j + 2, (short) (c & 255)); + rgba.set(j + 3, (short) 255); + } else { + rgba.set(j + 3, (short) 0); + } + } + jsDrawModernTab(canvas, rgba, windowWidth - 249, windowHeight - 343); + } + + public static Object getRenderGraphics(Object screenGraphics) { return screenGraphics; } + public static void flip(Object screenGraphics) {} + + public static void checkResize(Object comp) { + if (ClientSettings.ANDROID) { + return; + } + int desiredMode = jsGetDisplayMode(); + if (desiredMode >= 0) { + boolean wantResizable = (desiredMode != 0); + if (wantResizable != ClientSettings.RESIZABLE) { + ClientSettings.RESIZABLE = wantResizable; + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + HTMLCanvasElement glCanvas = (HTMLCanvasElement) org.teavm.jso.dom.html.HTMLDocument.current().getElementById("gl-canvas"); + if (!wantResizable) { + lastCssWidth = -1; + lastCssHeight = -1; + if (canvas != null) { + canvas.setWidth(765); + canvas.setHeight(503); + jsSetCanvasFillStyle(canvas, 765, 503); + } + if (glCanvas != null) { + glCanvas.setWidth(765); + glCanvas.setHeight(503); + } + jsSyncNavbarWidth(765); + if (comp instanceof Game) { + ((Game) comp).switchToFixedLayout(); + } else { + ModernLayout.updateWindowSize(765, 503); + ClientSettings.VIEWPORT_WIDTH = 512; + ClientSettings.VIEWPORT_HEIGHT = 334; + } + return; + } + } + } + if (!ClientSettings.RESIZABLE) { + return; + } + ensureHudAssets(); + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + if (canvas == null) return; + int rawW = Math.max(1, getStageWidth()); + int rawH = Math.max(1, getStageHeight()); + double minScale = Math.max(1.0, Math.max(765.0 / rawW, 503.0 / rawH)); + int w = Math.max(765, (int) Math.round(rawW * minScale)); + int h = Math.max(503, (int) Math.round(rawH * minScale)); + boolean fullRes = "true".equalsIgnoreCase(getParameter("fullres")) || HD117Pipeline.isGpuActive(); + if (!fullRes && w > 1280) { + w = 1280; + h = Math.max(503, (int) Math.round(rawH * (1280.0 / rawW))); + } + boolean sizeChanged = (w != ModernLayout.windowWidth || h != ModernLayout.windowHeight || canvas.getWidth() != w || canvas.getHeight() != h); + boolean cssChanged = (rawW != lastCssWidth || rawH != lastCssHeight); + if (sizeChanged) { + canvas.setWidth(w); + canvas.setHeight(h); + HTMLCanvasElement glCanvas = (HTMLCanvasElement) org.teavm.jso.dom.html.HTMLDocument.current().getElementById("gl-canvas"); + if (glCanvas != null) { + glCanvas.setWidth(w); + glCanvas.setHeight(h); + } + if (comp instanceof Game) { + ((Game) comp).applyWindowSize(w, h); + } else { + ModernLayout.updateWindowSize(w, h); + ClientSettings.VIEWPORT_WIDTH = ClientSettings.isDesktopModern() ? w : 512; + ClientSettings.VIEWPORT_HEIGHT = ClientSettings.isDesktopModern() ? h : 334; + } + } + if (sizeChanged || cssChanged) { + lastCssWidth = rawW; + lastCssHeight = rawH; + jsSetCanvasFillStyle(canvas, rawW, rawH); + jsSyncNavbarWidth(rawW); + } + } + + @JSBody(script = "return typeof window.scapeDisplayMode === 'number' ? window.scapeDisplayMode : -1;") + private static native int jsGetDisplayMode(); + + @JSBody(params = {"canvas", "sw", "sh"}, script = + "canvas.style.width = sw + 'px';\n" + + "canvas.style.height = sh + 'px';") + private static native void jsSetCanvasFillStyle(HTMLCanvasElement canvas, int sw, int sh); + + @JSBody(params = {"sw"}, script = + "var nav = document.getElementById('rs-navbar');\n" + + "if (nav) nav.style.width = sw + 'px';") + private static native void jsSyncNavbarWidth(int sw); + + public static void updateLoginTile(int[] tilePixels, int fixedX, int fixedY, int width, int height) { + if (tilePixels == null || tilePixels.length < width * height) return; + Uint8ClampedArray rgba = toRgbaOpaque(tilePixels, width * height); + jsUpdateLoginTile(rgba, fixedX, fixedY, width, height); + } + + public static void drawScaledLoginTile(Object screenGraphics, int[] tilePixels, int fixedX, int fixedY, int width, int height) { + updateLoginTile(tilePixels, fixedX, fixedY, width, height); + if (fixedX == 0 && fixedY == 0 && width == 128 && height == 265) { + return; + } + redrawScaledLoginScreen(screenGraphics); + } + + public static void redrawScaledLoginScreen(Object screenGraphics) { + ensureHudAssets(); + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + if (canvas == null) return; + int w = ModernLayout.windowWidth; + int h = ModernLayout.windowHeight; + if (w <= 0 || h <= 0) return; + int[] bounds = ModernLayout.getScaledScreenBounds(w, h); + jsRedrawScaledLogin(canvas, w, h, bounds[0], bounds[1], bounds[2], bounds[3]); + } + + private static Uint8ClampedArray toRgbaOpaque(int[] pixels, int count) { + Uint8ClampedArray rgba = Uint8ClampedArray.create(count * 4); + jsCopyRgbToRgba(pixels, rgba, count); + return rgba; + } + + @JSBody(params = {"src", "dstBytes", "count"}, script = + "var dst = new Uint32Array(dstBytes.buffer);\n" + + "for (var i = 0; i < count; i++) {\n" + + " var c = src[i];\n" + + " dst[i] = -16777216 | ((c & 255) << 16) | (c & 65280) | ((c >> 16) & 255);\n" + + "}") + private static native void jsCopyRgbToRgba(@JSByRef int[] src, Uint8ClampedArray dstBytes, int count); + + private static void ensureHudAssets() { + if (!hudImagesRequested) { + hudImagesRequested = true; + jsInitHudAssets(); + } + } + + @JSBody(script = + "var s = document.getElementById('stage');\n" + + "var w = s ? s.clientWidth : window.innerWidth;\n" + + "if (window.visualViewport) w = Math.min(w, Math.floor(window.visualViewport.width));\n" + + "return w;") + private static native int getStageWidth(); + + @JSBody(script = + "var s = document.getElementById('stage');\n" + + "var h = s ? s.clientHeight : window.innerHeight;\n" + + "if (window.visualViewport) h = Math.min(h, Math.floor(window.visualViewport.height));\n" + + "var nav = document.getElementById('rs-navbar');\n" + + "if (nav && nav.offsetHeight > 0) h -= 25;\n" + + "return h;") + private static native int getStageHeight(); + + @JSBody(script = + "if (window.scapeHud) return;\n" + + "function loadImg(src) { var img = new Image(); img.src = src; return img; }\n" + + "var lc = document.createElement('canvas'); lc.width = 765; lc.height = 503;\n" + + "var mc = document.createElement('canvas'); mc.width = 249; mc.height = 168;\n" + + "var mContent = document.createElement('canvas'); mContent.width = 172; mContent.height = 156;\n" + + "var cc = document.createElement('canvas'); cc.width = 519; cc.height = 165;\n" + + "var cContent = document.createElement('canvas'); cContent.width = 479; cContent.height = 96;\n" + + "var cButtons = document.createElement('canvas'); cButtons.width = 496; cButtons.height = 50;\n" + + "var tc = document.createElement('canvas'); tc.width = 249; tc.height = 343;\n" + + "window.scapeHud = {\n" + + " minimapBezel: loadImg('hud_minimap_bezel.png'),\n" + + " minimapHole: loadImg('hud_minimap_hole.png'),\n" + + " chatFrame: loadImg('hud_chat_frame.png'),\n" + + " loginCanvas: lc, loginCtx: lc.getContext('2d'),\n" + + " mc: mc, mcCtx: mc.getContext('2d'), mContent: mContent, mContentCtx: mContent.getContext('2d'),\n" + + " cc: cc, ccCtx: cc.getContext('2d'), cContent: cContent, cContentCtx: cContent.getContext('2d'), cButtons: cButtons, cButtonsCtx: cButtons.getContext('2d'),\n" + + " tc: tc, tcCtx: tc.getContext('2d')\n" + + "};") + private static native void jsInitHudAssets(); + + @JSBody(params = {"canvas", "rgba", "winW"}, script = + "var h = window.scapeHud; if (!h || !h.minimapBezel.complete || !h.minimapHole.complete) return;\n" + + "var id = h.mContentCtx.createImageData(172, 156); id.data.set(rgba); h.mContentCtx.putImageData(id, 0, 0);\n" + + "var g = h.mcCtx; g.clearRect(0, 0, 249, 168);\n" + + "g.globalCompositeOperation = 'source-over'; g.drawImage(h.mContent, 34, 4);\n" + + "g.globalCompositeOperation = 'destination-in'; g.drawImage(h.minimapHole, 0, 0);\n" + + "g.globalCompositeOperation = 'source-over'; g.drawImage(h.minimapBezel, 0, 0);\n" + + "canvas.getContext('2d').drawImage(h.mc, winW - 249, 0);") + private static native void jsDrawModernMinimap(HTMLCanvasElement canvas, Uint8ClampedArray rgba, int winW); + + @JSBody(params = {"canvas", "contentRgba", "buttonsRgba", "winH"}, script = + "var h = window.scapeHud; if (!h || !h.chatFrame.complete) return;\n" + + "var g = h.ccCtx; g.clearRect(0, 0, 519, 165);\n" + + "g.globalCompositeOperation = 'source-over'; g.drawImage(h.chatFrame, 0, 0);\n" + + "if (contentRgba) { var id1 = h.cContentCtx.createImageData(479, 96); id1.data.set(contentRgba); h.cContentCtx.putImageData(id1, 0, 0); g.drawImage(h.cContent, 17, 19); }\n" + + "if (buttonsRgba) { var id2 = h.cButtonsCtx.createImageData(496, 50); id2.data.set(buttonsRgba); h.cButtonsCtx.putImageData(id2, 0, 0); g.drawImage(h.cButtons, 0, 115); }\n" + + "canvas.getContext('2d').drawImage(h.cc, 0, winH - 165);") + private static native void jsDrawModernChat(HTMLCanvasElement canvas, Uint8ClampedArray contentRgba, Uint8ClampedArray buttonsRgba, int winH); + + @JSBody(params = {"canvas", "rgba", "x", "y"}, script = + "var hh = window.scapeHud; if (!hh) return;\n" + + "var id = hh.tcCtx.createImageData(249, 343); id.data.set(rgba); hh.tcCtx.putImageData(id, 0, 0);\n" + + "canvas.getContext('2d').drawImage(hh.tc, x, y);") + private static native void jsDrawModernTab(HTMLCanvasElement canvas, Uint8ClampedArray rgba, int x, int y); + + @JSBody(params = {"rgba", "fx", "fy", "w", "h"}, script = + "if (!window.scapeLoginBuf) {\n" + + " var lc = document.createElement('canvas'); lc.width = 765; lc.height = 503;\n" + + " window.scapeLoginBuf = { c: lc, ctx: lc.getContext('2d') };\n" + + "}\n" + + "var b = window.scapeLoginBuf;\n" + + "var id = b.ctx.createImageData(w, h); id.data.set(rgba); b.ctx.putImageData(id, fx, fy);") + private static native void jsUpdateLoginTile(Uint8ClampedArray rgba, int fx, int fy, int w, int h); + + @JSBody(params = {"canvas", "winW", "winH", "dx", "dy", "dw", "dh"}, script = + "var b = window.scapeLoginBuf; if (!b) return;\n" + + "var ctx = canvas.getContext('2d');\n" + + "ctx.fillStyle = '#000'; ctx.fillRect(0, 0, winW, winH);\n" + + "ctx.imageSmoothingEnabled = true;\n" + + "ctx.drawImage(b.c, dx, dy, dw, dh);") + private static native void jsRedrawScaledLogin(HTMLCanvasElement canvas, int winW, int winH, int dx, int dy, int dw, int dh); + + public static void initHdBackend() { + if (HD117Pipeline.backend == null) { + HD117Pipeline.backend = new WebHd117Renderer(); + } + } + + @JSBody(params = {"arr", "vol"}, script = + "if (window.scapeWebAudio && window.scapeWebAudio.playPcm) window.scapeWebAudio.playPcm(arr, vol);") + private static native void jsPlayPcm(Uint8Array arr, float vol); + + @JSBody(params = {"arr", "vol"}, script = + "if (window.scapeWebAudio && window.scapeWebAudio.playMidi) window.scapeWebAudio.playMidi(arr, vol);") + private static native void jsPlayMidi(Uint8Array arr, float vol); + + @JSBody(params = {"vol"}, script = + "if (window.scapeWebAudio && window.scapeWebAudio.setMidiVolume) window.scapeWebAudio.setMidiVolume(vol);") + private static native void jsSetMidiVolume(float vol); + + @JSBody(script = + "if (window.scapeWebAudio && window.scapeWebAudio.stopMidi) window.scapeWebAudio.stopMidi();") + private static native void jsStopMidi(); + + @JSBody(params = {"canvas", "filename"}, script = + "var a = document.createElement('a');\n" + + "a.download = filename;\n" + + "a.href = canvas.toDataURL('image/png');\n" + + "a.click();") + private static native void downloadCanvasPng(HTMLCanvasElement canvas, String filename); + + @JSBody(params = {"name"}, script = + "var p = new URLSearchParams(window.location.search);\n" + + "return p.get(name) || '';") + private static native String getUrlParam(String name); + + @JSBody(params = {"url"}, script = "window.open(url, '_blank');") + private static native void openUrl(String url); + + @JSFunctor + public interface HttpFetchCallback extends JSObject { + void onComplete(int status, String body); + } + + public static String httpGet(String url) throws java.io.IOException { + if (url == null || url.contains(".git/info/refs")) { + throw new java.io.IOException("Skipped in browser"); + } + String res = fetchTextAsync(url); + if (res == null) { + throw new java.io.IOException("Network error"); + } + if (res.startsWith("__HTTP_ERR__:")) { + throw new java.io.IOException(res.substring("__HTTP_ERR__:".length())); + } + return res; + } + + @Async + private static native String fetchTextAsync(String url); + + private static void fetchTextAsync(String url, AsyncCallback callback) { + jsFetchText(url, (status, body) -> { + if (status >= 200 && status < 300) { + callback.complete(body != null ? body : ""); + } else { + callback.complete("__HTTP_ERR__:HTTP " + status); + } + }); + } + + @JSBody(params = {"url", "cb"}, script = + "fetch(url).then(function(r) {\n" + + " if (!r.ok) { cb(r.status, ''); return; }\n" + + " r.text().then(function(t) { cb(r.status, t); }, function() { cb(-1, ''); });\n" + + "}).catch(function() { cb(-1, ''); });") + private static native void jsFetchText(String url, HttpFetchCallback cb); + + public static boolean saveExternalScript(String fileName, String content) { + if (fileName == null || content == null) return false; + jsSaveScript(fileName, content); + return true; + } + + public static boolean deleteExternalScript(String fileName) { + if (fileName == null) return false; + return jsDeleteScript(fileName); + } + + public static String loadPluginConfig() { + return jsLoadPluginConfig(); + } + + public static boolean savePluginConfig(String content) { + if (content == null) return false; + jsSavePluginConfig(content); + return true; + } + + @JSBody(script = "return window.localStorage ? window.localStorage.getItem('2006scape_plugin_settings') : null;") + private static native String jsLoadPluginConfig(); + + @JSBody(params = {"content"}, script = + "if (window.localStorage) window.localStorage.setItem('2006scape_plugin_settings', content);") + private static native void jsSavePluginConfig(String content); + + public static void yieldUi() { + try { + Thread.sleep(1L); + } catch (InterruptedException ignored) {} + } + + public static Object boxReflectValue(Object v, Class declaredType) { + if (v == null) return null; + if (v instanceof Number || v instanceof Boolean || v instanceof String) { + return v; + } + if (org.teavm.jso.impl.JSWrapper.isJava(v)) { + return v; + } + JSObject js = org.teavm.jso.impl.JSWrapper.maybeUnwrap(v); + if (jsIsUndefined(js)) { + return null; + } + if (jsIsNumber(js)) { + double d = jsAsDouble(js); + if (declaredType == long.class || declaredType == Long.class) { + return Long.valueOf((long) d); + } + if (declaredType == double.class || declaredType == Double.class) { + return Double.valueOf(d); + } + if (declaredType == float.class || declaredType == Float.class) { + return Float.valueOf((float) d); + } + if (d == Math.floor(d) && d >= Integer.MIN_VALUE && d <= Integer.MAX_VALUE) { + return Integer.valueOf((int) d); + } + return Double.valueOf(d); + } + if (jsIsBoolean(js)) { + return Boolean.valueOf(jsAsBoolean(js)); + } + if (jsIsString(js)) { + return jsAsString(js); + } + return v; + } + + @JSBody(params = {"v"}, script = "return v === undefined || v === null;") + private static native boolean jsIsUndefined(JSObject v); + + @JSBody(params = {"v"}, script = "return typeof v === 'number';") + private static native boolean jsIsNumber(JSObject v); + + @JSBody(params = {"v"}, script = "return v;") + private static native double jsAsDouble(JSObject v); + + @JSBody(params = {"v"}, script = "return typeof v === 'boolean';") + private static native boolean jsIsBoolean(JSObject v); + + @JSBody(params = {"v"}, script = "return !!v;") + private static native boolean jsAsBoolean(JSObject v); + + @JSBody(params = {"v"}, script = "return typeof v === 'string';") + private static native boolean jsIsString(JSObject v); + + @JSBody(params = {"v"}, script = "return v;") + private static native String jsAsString(JSObject v); + + @JSBody(params = {"name", "content"}, script = + "if (window.localStorage) window.localStorage.setItem('2006scape_script_' + name, content);") + private static native void jsSaveScript(String name, String content); + + @JSBody(params = {"name"}, script = + "if (!window.localStorage) return false;\n" + + "var k = '2006scape_script_' + name;\n" + + "if (window.localStorage.getItem(k) === null) return false;\n" + + "window.localStorage.removeItem(k);\n" + + "return true;") + private static native boolean jsDeleteScript(String name); +} diff --git a/src/main/java/org/scape2006/web/ExternalPluginLoader.java b/src/main/java/org/scape2006/web/ExternalPluginLoader.java new file mode 100644 index 0000000..2a66044 --- /dev/null +++ b/src/main/java/org/scape2006/web/ExternalPluginLoader.java @@ -0,0 +1,69 @@ +package org.scape2006.web; + +import org.teavm.jso.JSBody; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/** + * Web ExternalPluginLoader. + * Loads .script / .bsh / .java source scripts from browser localStorage virtual FS + * and compiles them via ScriptInterpreter. Skips .jar/.dex binary bytecode in browser sandboxes. + */ +public class ExternalPluginLoader { + + private static final String SCRIPT_PREFIX = "2006scape_script_"; + + public static class LoadedContainer { + public final List plugins = new ArrayList<>(); + public final List scripts = new ArrayList<>(); + public final List errors = new ArrayList<>(); + } + + public static LoadedContainer loadExternal(File baseDir) { + LoadedContainer container = new LoadedContainer(); + int count = getLocalStorageLength(); + for (int i = 0; i < count; i++) { + String key = getLocalStorageKey(i); + if (key != null && key.startsWith(SCRIPT_PREFIX)) { + String fileName = key.substring(SCRIPT_PREFIX.length()); + String source = getLocalStorageValue(key); + if (source != null && !source.isEmpty()) { + try { + loadSourceString(fileName, source, "script", container); + } catch (Throwable t) { + container.errors.add(fileName + ": " + t.getMessage()); + } + } + } + } + return container; + } + + public static void loadSourceString(String fileName, String source, String defaultType, LoadedContainer container) { + ScriptInterpreter.ScriptMetadata meta = ScriptInterpreter.parseMetadata(source); + if ("Unnamed Script".equals(meta.name)) { + int dot = fileName.lastIndexOf('.'); + String clean = (dot != -1) ? fileName.substring(0, dot) : fileName; + meta.name = clean.replace('_', ' '); + } + if (meta.type == null || meta.type.isEmpty()) { + meta.type = defaultType; + } + ScriptInterpreter.Environment env = ScriptInterpreter.compile(source); + if ("plugin".equalsIgnoreCase(meta.type)) { + container.plugins.add(new ScriptInterpreter.InterpretedPlugin(meta, env)); + } else { + container.scripts.add(new ScriptInterpreter.InterpretedScript(meta, env)); + } + } + + @JSBody(script = "return window.localStorage ? window.localStorage.length : 0;") + private static native int getLocalStorageLength(); + + @JSBody(params = {"index"}, script = "return window.localStorage ? window.localStorage.key(index) : null;") + private static native String getLocalStorageKey(int index); + + @JSBody(params = {"key"}, script = "return window.localStorage ? window.localStorage.getItem(key) : null;") + private static native String getLocalStorageValue(String key); +} diff --git a/src/main/java/org/scape2006/web/RSApplet.java b/src/main/java/org/scape2006/web/RSApplet.java new file mode 100644 index 0000000..ef5d8eb --- /dev/null +++ b/src/main/java/org/scape2006/web/RSApplet.java @@ -0,0 +1,862 @@ +package org.scape2006.web; + +import org.teavm.jso.JSBody; +import org.teavm.jso.JSExceptions; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; +import org.teavm.jso.dom.events.KeyboardEvent; +import org.teavm.jso.dom.events.MouseEvent; +import org.teavm.jso.dom.events.WheelEvent; +import org.teavm.jso.dom.html.HTMLCanvasElement; + +import java.net.MalformedURLException; +import java.net.URL; + +/** + * Web version of RSApplet. + * Provides the game loop, timing, DOM mouse/keyboard/wheel input bindings, and lifecycle for Game. + */ +public class RSApplet implements Runnable { + + public static boolean ctrlDown = false; + public static boolean shiftDown = false; + public static boolean removeShiftDropOnMenuOpen = false; + + public static final int TARGET_DEFAULT = 0; + public static final int TARGET_VIEWPORT = 1; + public static final int TARGET_TAB = 2; + public static final int TARGET_CHAT = 3; + public static final int TARGET_MINIMAP = 4; + public static int touchTargetArea = TARGET_DEFAULT; + + public int myWidth = 765; + public int myHeight = 503; + public RSImageProducer fullGameScreen; + public Object gameFrame = null; + public Object graphics = new Object(); + + public boolean shouldDebug = false; + public int fps; + + public int anInt4 = 0; + public int delayTime = 20; + public int minDelay = 1; + public final long[] aLongArray7 = new long[10]; + + public int idleTime; + + public int clickType; + public int mouseX; + public int mouseY; + public int clickMode1; + public int clickMode2; + public int clickMode3; + public int saveClickX; + public int saveClickY; + public int clickX; + public int clickY; + public long clickTime; + public long aLong29; + public boolean mouseWheelDown = false; + public int mouseWheelX = 0; + public int mouseWheelY = 0; + public boolean awtFocus = true; + + public final int[] keyArray = new int[128]; + public final int[] charQueue = new int[128]; + public int readIndex; + public int writeIndex; + + private boolean domBound = false; + + public RSApplet() { + } + + public void initClientFrame(int height, int width) { + myWidth = width; + myHeight = height; + fullGameScreen = new RSImageProducer(myWidth, myHeight, null); + bindDomEvents(); + startRunnable(this, 1); + } + + public void createClientFrame(int height, int width) { + initClientFrame(height, width); + } + + private void bindDomEvents() { + if (domBound) return; + domBound = true; + HTMLCanvasElement canvas = RSImageProducer.getCanvas(); + if (canvas == null) return; + + canvas.addEventListener("contextmenu", evt -> evt.preventDefault()); + + canvas.addEventListener("mousedown", evt -> { + MouseEvent me = (MouseEvent) evt; + canvas.focus(); + int rawX = getCanvasX(canvas, me); + int rawY = getCanvasY(canvas, me); + idleTime = 0; + if (me.getButton() == 1) { + mouseWheelDown = true; + mouseWheelX = rawX; + mouseWheelY = rawY; + return; + } + if (ClientSettings.isDesktopModern()) { + touchTargetArea = ModernLayout.hit(rawX, rawY); + int[] gameCoords = ModernLayout.toGameCoords(touchTargetArea, rawX, rawY); + clickX = gameCoords[0]; + clickY = gameCoords[1]; + mouseX = gameCoords[0]; + mouseY = gameCoords[1]; + } else { + touchTargetArea = 0; + clickX = rawX; + clickY = rawY; + mouseX = rawX; + mouseY = rawY; + } + clickTime = System.currentTimeMillis(); + if (me.getButton() == 2) { + clickMode1 = 2; + clickMode2 = 2; + } else { + clickMode1 = 1; + clickMode2 = 1; + } + }); + + canvas.addEventListener("mouseup", evt -> { + MouseEvent me = (MouseEvent) evt; + idleTime = 0; + clickMode2 = 0; + if (me.getButton() == 1) { + mouseWheelDown = false; + } + }); + + canvas.addEventListener("mousemove", evt -> { + MouseEvent me = (MouseEvent) evt; + int rawX = getCanvasX(canvas, me); + int rawY = getCanvasY(canvas, me); + if (mouseWheelDown) { + int dx = mouseWheelX - rawX; + int dy = mouseWheelY - rawY; + mouseWheelX = rawX; + mouseWheelY = rawY; + mouseWheelDragged(dx, dy); + return; + } + if (ClientSettings.isDesktopModern()) { + touchTargetArea = ModernLayout.hit(rawX, rawY); + int[] gameCoords = ModernLayout.toGameCoords(touchTargetArea, rawX, rawY); + mouseX = gameCoords[0]; + mouseY = gameCoords[1]; + } else { + touchTargetArea = 0; + mouseX = rawX; + mouseY = rawY; + } + idleTime = 0; + }); + + canvas.addEventListener("wheel", evt -> { + WheelEvent we = (WheelEvent) evt; + evt.preventDefault(); + idleTime = 0; + int rot = we.getDeltaY() > 0 ? 1 : -1; + handleMouseWheel(rot, isWheelCtrlKey(we)); + }); + + canvas.addEventListener("keydown", evt -> { + KeyboardEvent ke = (KeyboardEvent) evt; + int code = ke.getKeyCode(); + if (code == 8 || code == 9 || code == 37 || code == 38 || code == 39 || code == 40) { + evt.preventDefault(); + } + String key = ke.getKey(); + char keyChar = (key != null && key.length() == 1) ? key.charAt(0) : 0; + handleKeyPressed(code, keyChar, ke.isCtrlKey(), ke.isShiftKey()); + }); + + canvas.addEventListener("keyup", evt -> { + KeyboardEvent ke = (KeyboardEvent) evt; + int code = ke.getKeyCode(); + String key = ke.getKey(); + char keyChar = (key != null && key.length() == 1) ? key.charAt(0) : 0; + handleKeyReleased(code, keyChar, ke.isCtrlKey(), ke.isShiftKey()); + }); + + canvas.addEventListener("focus", evt -> awtFocus = true); + canvas.addEventListener("blur", evt -> { + awtFocus = false; + for (int i = 0; i < keyArray.length; i++) { + keyArray[i] = 0; + } + ctrlDown = false; + shiftDown = false; + }); + + installMobileInputBridge( + canvas, + (rawX, rawY, phase, extra) -> onMobileTouchEvent(rawX, rawY, phase, extra), + (dx, dy) -> { + idleTime = 0; + handleCameraDrag(dx * 2, dy * 2); + }, + (rot) -> { + idleTime = 0; + handleMouseWheel(rot, true); + }, + (code, keyChar, isDown) -> { + if (isDown) { + handleKeyPressed(code, (char) keyChar, false, false); + } else { + handleKeyReleased(code, (char) keyChar, false, false); + } + } + ); + } + + // Android-parity touch state + private boolean touchStartedInViewport = false; + private boolean isTouchOverDraggableItem = false; + private boolean isItemDragActive = false; + private boolean isTouchOverScrollBar = false; + private boolean isTouchLongPressTriggered = false; + private int initialGameTouchX = 0; + private int initialGameTouchY = 0; + + private int[] toGameTouchCoords(int rawX, int rawY) { + if (ClientSettings.isDesktopModern()) { + touchTargetArea = ModernLayout.hit(rawX, rawY); + return ModernLayout.toGameCoords(touchTargetArea, rawX, rawY); + } else { + touchTargetArea = 0; + return new int[]{rawX, rawY}; + } + } + + /** + * Handles touch phases from JS: + * phase 0 = down, 1 = drag move, 2 = up/tap, 3 = long-press, 4 = cancel + * returns bitmask: bit 0 = touchStartedInViewport, bit 1 = isTouchOverScrollBar, bit 2 = isTouchOverDraggableItem + */ + private int onMobileTouchEvent(int rawX, int rawY, int phase, int extra) { + int[] gc = toGameTouchCoords(rawX, rawY); + int gx = gc[0], gy = gc[1]; + Game g = (this instanceof Game) ? (Game) this : null; + + if (phase == 0) { // touchstart + awtFocus = true; + isTouchLongPressTriggered = false; + isItemDragActive = false; + if (ClientSettings.isDesktopModern()) { + touchStartedInViewport = (touchTargetArea == TARGET_VIEWPORT); + } else { + touchStartedInViewport = (gx >= 4 && gx <= 516 && gy >= 4 && gy <= 338); + } + if (PluginPanelUI.isModalOpen() && PluginPanelUI.isModalAt(gx, gy)) { + touchStartedInViewport = false; + } + if (touchStartedInViewport) { + jsBlurMobileKeyboard(); + } + initialGameTouchX = gx; + initialGameTouchY = gy; + isTouchOverDraggableItem = (g != null) && !touchStartedInViewport && g.canDragItemAt(gx, gy); + isTouchOverScrollBar = (g != null) && g.isScrollBarAt(gx, gy); + + if (!touchStartedInViewport && !isTouchOverDraggableItem) { + boolean isChatPromptTap = (g != null) && (g.inputDialogState != 0 || g.messagePromptRaised) + && (ClientSettings.isDesktopModern() ? (touchTargetArea == TARGET_CHAT) : (gx >= 0 && gx <= 516 && gy >= 357 && gy <= 467)); + if (!isChatPromptTap) { + handleTouchDown(gx, gy); + } + } + int mask = 0; + if (touchStartedInViewport) mask |= 1; + if (isTouchOverScrollBar) mask |= 2; + if (isTouchOverDraggableItem) mask |= 4; + return mask; + } else if (phase == 1) { // touchmove (non-camera) + if (g != null && g.isScrollBarAt(gx, gy)) { + isTouchOverScrollBar = true; + } + if (isTouchOverDraggableItem && extra == 1 && !isTouchLongPressTriggered && g != null) { + if (!isItemDragActive) { + isItemDragActive = g.startItemDrag(initialGameTouchX, initialGameTouchY); + } + if (isItemDragActive) { + handleTouchMove(gx, gy); + g.needDrawTabArea = true; + } + } else { + handleTouchMove(gx, gy); + } + } else if (phase == 3) { // long-press -> right-click + if (!isTouchOverScrollBar) { + isTouchLongPressTriggered = true; + handleTouchClick(gx, gy, true); + jsScheduleTouchUp(() -> handleTouchUp()); + } + } else if (phase == 2) { // touchend: extra == 1 means tap (not dragging & not long-pressed) + if (isItemDragActive && g != null) { + handleTouchMove(gx, gy); + g.needDrawTabArea = true; + handleTouchUp(); + } else if (extra == 1 && !isTouchLongPressTriggered) { + boolean isChatPromptTap = (g != null) && (g.inputDialogState != 0 || g.messagePromptRaised) + && (ClientSettings.isDesktopModern() ? (touchTargetArea == TARGET_CHAT) : (gx >= 0 && gx <= 516 && gy >= 357 && gy <= 467)); + if (!isChatPromptTap) { + handleTouchClick(gx, gy, false); + } + if (g != null) { + checkShowMobileKeyboard(g, gx, gy); + } + jsScheduleTouchUp(() -> handleTouchUp()); + } else { + handleTouchUp(); + } + isTouchLongPressTriggered = false; + touchStartedInViewport = false; + isTouchOverDraggableItem = false; + isItemDragActive = false; + isTouchOverScrollBar = false; + } else if (phase == 4) { // cancel + if (isItemDragActive || isTouchOverScrollBar) { + handleTouchUp(); + } + isTouchLongPressTriggered = false; + touchStartedInViewport = false; + isTouchOverDraggableItem = false; + isItemDragActive = false; + isTouchOverScrollBar = false; + } + return 0; + } + + @JSFunctor + public interface TouchUpCallback extends JSObject { + void run(); + } + + @JSBody(params = {"cb"}, script = "setTimeout(function() { cb(); }, 40);") + private static native void jsScheduleTouchUp(TouchUpCallback cb); + + private void checkShowMobileKeyboard(Game g, int gx, int gy) { + if (PluginPanelUI.isSearchFocused()) { + jsFocusMobileKeyboard(); + return; + } + if (g.loggedIn) { + if (g.fullScreenInterfaceId != -1 || g.welcomeScreenRaised || g.dialogID != -1 || g.backDialogID != -1 || g.aString844 != null) { + jsBlurMobileKeyboard(); + return; + } + if (ClientSettings.isDesktopModern()) { + if (touchTargetArea == TARGET_CHAT && gy >= 357 && gy < 453 && gx < 480) { + jsFocusMobileKeyboard(); + } else { + jsBlurMobileKeyboard(); + } + return; + } + if (g.inputDialogState != 0 || g.messagePromptRaised) { + if (gx >= 0 && gx <= 516 && gy >= 357 && gy < 467) { + jsFocusMobileKeyboard(); + } else { + jsBlurMobileKeyboard(); + } + return; + } + if (gx >= 0 && gx < 450 && gy >= 357 && gy < 467) { + jsFocusMobileKeyboard(); + } else { + jsBlurMobileKeyboard(); + } + return; + } + if (g.loginScreenState == 2 && gy >= 235 && gy <= 295 && gx >= 200 && gx <= 565) { + jsFocusMobileKeyboard(); + } else { + jsBlurMobileKeyboard(); + } + } + + @JSBody(script = + "var kb = document.getElementById('mobile-kb-input');\n" + + "if (kb) { kb.value = ' '; kb.focus(); try { kb.setSelectionRange(1, 1); } catch (_) {} }") + private static native void jsFocusMobileKeyboard(); + + @JSBody(script = + "var kb = document.getElementById('mobile-kb-input');\n" + + "if (kb && document.activeElement === kb) kb.blur();") + private static native void jsBlurMobileKeyboard(); + + @JSFunctor + public interface TouchActionCallback extends JSObject { + int onTouch(int rawX, int rawY, int phase, int extra); + } + + @JSFunctor + public interface TouchDragCallback extends JSObject { + void onDrag(int dx, int dy); + } + + @JSFunctor + public interface TouchPinchCallback extends JSObject { + void onPinch(int rot); + } + + @JSFunctor + public interface VirtualKeyCallback extends JSObject { + void onKey(int code, int keyChar, boolean isDown); + } + + @JSBody(params = {"canvas", "onTouch", "onDrag", "onPinch", "onVKey"}, script = + "var lpTimer = null;\n" + + "var startX = 0, startY = 0, lastX = 0, lastY = 0;\n" + + "var dragging = false, longPressed = false, pinching = false;\n" + + "var inViewport = false, overScrollbar = false;\n" + + "var lastPinchDist = 0;\n" + + "function toCanvas(t) {\n" + + " var r = canvas.getBoundingClientRect();\n" + + " return [Math.floor((t.clientX - r.left) * (canvas.width / r.width)),\n" + + " Math.floor((t.clientY - r.top) * (canvas.height / r.height))];\n" + + "}\n" + + "function clearLp() { if (lpTimer) { clearTimeout(lpTimer); lpTimer = null; } }\n" + + "canvas.addEventListener('touchstart', function(e) {\n" + + " e.preventDefault();\n" + + " clearLp();\n" + + " if (e.touches.length === 2) {\n" + + " pinching = true; dragging = false;\n" + + " var dx = e.touches[0].clientX - e.touches[1].clientX;\n" + + " var dy = e.touches[0].clientY - e.touches[1].clientY;\n" + + " lastPinchDist = Math.hypot(dx, dy);\n" + + " return;\n" + + " }\n" + + " if (e.touches.length !== 1) return;\n" + + " pinching = false; dragging = false; longPressed = false;\n" + + " var p = toCanvas(e.touches[0]);\n" + + " startX = lastX = p[0]; startY = lastY = p[1];\n" + + " var mask = onTouch(p[0], p[1], 0, 0);\n" + + " inViewport = (mask & 1) !== 0;\n" + + " overScrollbar = (mask & 2) !== 0;\n" + + " if (!overScrollbar) {\n" + + " lpTimer = setTimeout(function() {\n" + + " if (!dragging && !pinching) {\n" + + " longPressed = true;\n" + + " onTouch(lastX, lastY, 3, 0);\n" + + " }\n" + + " }, 450);\n" + + " }\n" + + "}, { passive: false });\n" + + "canvas.addEventListener('touchmove', function(e) {\n" + + " e.preventDefault();\n" + + " if (e.touches.length === 2) {\n" + + " clearLp(); pinching = true;\n" + + " var dx = e.touches[0].clientX - e.touches[1].clientX;\n" + + " var dy = e.touches[0].clientY - e.touches[1].clientY;\n" + + " var dist = Math.hypot(dx, dy);\n" + + " if (Math.abs(dist - lastPinchDist) > 12) {\n" + + " onPinch(dist > lastPinchDist ? -1 : 1);\n" + + " lastPinchDist = dist;\n" + + " }\n" + + " return;\n" + + " }\n" + + " if (e.touches.length !== 1 || pinching) return;\n" + + " var p = toCanvas(e.touches[0]);\n" + + " if (!dragging && (Math.abs(p[0] - startX) > 10 || Math.abs(p[1] - startY) > 10)) {\n" + + " dragging = true; clearLp();\n" + + " }\n" + + " if (inViewport && dragging) {\n" + + " onDrag(lastX - p[0], p[1] - lastY);\n" + + " lastX = p[0]; lastY = p[1];\n" + + " } else {\n" + + " onTouch(p[0], p[1], 1, dragging ? 1 : 0);\n" + + " lastX = p[0]; lastY = p[1];\n" + + " }\n" + + "}, { passive: false });\n" + + "canvas.addEventListener('touchend', function(e) {\n" + + " e.preventDefault();\n" + + " clearLp();\n" + + " if (e.touches.length === 0) {\n" + + " onTouch(startX, startY, 2, (!dragging && !longPressed && !pinching) ? 1 : 0);\n" + + " dragging = false; pinching = false; longPressed = false; inViewport = false; overScrollbar = false;\n" + + " }\n" + + "}, { passive: false });\n" + + "canvas.addEventListener('touchcancel', function() {\n" + + " clearLp();\n" + + " onTouch(startX, startY, 4, 0);\n" + + " dragging = false; pinching = false; longPressed = false; inViewport = false; overScrollbar = false;\n" + + "});\n" + + "var kb = document.getElementById('mobile-kb-input');\n" + + "if (kb) {\n" + + " var kbHandledBefore = false;\n" + + " kb.addEventListener('focus', function() {\n" + + " kb.value = ' ';\n" + + " try { kb.setSelectionRange(1, 1); } catch (_) {}\n" + + " });\n" + + " kb.addEventListener('beforeinput', function(be) {\n" + + " kbHandledBefore = false;\n" + + " if (be.inputType === 'deleteContentBackward') {\n" + + " be.preventDefault();\n" + + " kbHandledBefore = true;\n" + + " onVKey(8, 0, true); onVKey(8, 0, false);\n" + + " } else if (be.inputType === 'insertLineBreak' || be.inputType === 'insertParagraph') {\n" + + " be.preventDefault();\n" + + " kbHandledBefore = true;\n" + + " onVKey(13, 0, true); onVKey(13, 0, false);\n" + + " }\n" + + " });\n" + + " kb.addEventListener('input', function() {\n" + + " var v = kb.value;\n" + + " if (v.length === 0) {\n" + + " if (!kbHandledBefore) { onVKey(8, 0, true); onVKey(8, 0, false); }\n" + + " } else {\n" + + " var start = (v.charAt(0) === ' ') ? 1 : 0;\n" + + " for (var i = start; i < v.length; i++) {\n" + + " var c = v.charCodeAt(i);\n" + + " if (c === 10 || c === 13) {\n" + + " onVKey(13, 0, true); onVKey(13, 0, false);\n" + + " } else {\n" + + " onVKey(0, c, true); onVKey(0, c, false);\n" + + " }\n" + + " }\n" + + " }\n" + + " kbHandledBefore = false;\n" + + " kb.value = ' ';\n" + + " try { kb.setSelectionRange(1, 1); } catch (_) {}\n" + + " });\n" + + " kb.addEventListener('keydown', function(ke) {\n" + + " if (ke.keyCode === 13 || ke.key === 'Enter') {\n" + + " ke.preventDefault();\n" + + " onVKey(13, 0, true); onVKey(13, 0, false);\n" + + " } else if (ke.keyCode === 8 || ke.key === 'Backspace') {\n" + + " if (kb.value.length <= 1) {\n" + + " ke.preventDefault();\n" + + " onVKey(8, 0, true); onVKey(8, 0, false);\n" + + " }\n" + + " }\n" + + " });\n" + + "}") + private static native void installMobileInputBridge(HTMLCanvasElement canvas, TouchActionCallback onTouch, + TouchDragCallback onDrag, TouchPinchCallback onPinch, VirtualKeyCallback onVKey); + + @JSBody(params = {"canvas", "me"}, script = + "var r = canvas.getBoundingClientRect();\n" + + "return Math.floor((me.clientX - r.left) * (canvas.width / r.width));") + private static native int getCanvasX(HTMLCanvasElement canvas, MouseEvent me); + + @JSBody(params = {"canvas", "me"}, script = + "var r = canvas.getBoundingClientRect();\n" + + "return Math.floor((me.clientY - r.top) * (canvas.height / r.height));") + private static native int getCanvasY(HTMLCanvasElement canvas, MouseEvent me); + + public void startRunnable(Runnable runnable, int priority) { + Thread thread = new Thread(runnable, "WebClientThread"); + thread.setDaemon(true); + thread.start(); + } + + @Override + public void run() { + startUp(); + int opos = 0; + int ratio = 256; + int delay = 1; + int count = 0; + + for (int i = 0; i < 10; i++) { + aLongArray7[i] = System.currentTimeMillis(); + } + + while (anInt4 >= 0) { + if (anInt4 > 0) { + anInt4--; + if (anInt4 == 0) { + exit(); + return; + } + } + + int r = ratio; + int d = delay; + ratio = 300; + delay = 1; + long now = System.currentTimeMillis(); + + if (aLongArray7[opos] == 0L) { + ratio = r; + delay = d; + } else if (now > aLongArray7[opos]) { + ratio = (int) ((long) (2560 * delayTime) / (now - aLongArray7[opos])); + } + + if (ratio < 25) ratio = 25; + if (ratio > 256) { + ratio = 256; + delay = (int) ((long) delayTime - (now - aLongArray7[opos]) / 10L); + } + + if (delay > delayTime) delay = delayTime; + aLongArray7[opos] = now; + opos = (opos + 1) % 10; + + if (delay > 1) { + for (int j = 0; j < 10; j++) { + if (aLongArray7[j] != 0L) { + aLongArray7[j] += delay; + } + } + } + + if (delay < minDelay) delay = minDelay; + + try { + Thread.sleep(delay); + } catch (InterruptedException ignored) {} + + for (; count < 256; count += ratio) { + clickMode3 = clickMode1; + saveClickX = clickX; + saveClickY = clickY; + aLong29 = clickTime; + clickMode1 = 0; + try { + processGameLoop(); + } catch (Throwable t) { + JSObject jex = JSExceptions.getJSException(t); + jsLogError("Loop error", t.toString(), jex); + reportCrashWithStack("Loop error: " + t, jex); + } + readIndex = writeIndex; + } + + count &= 0xff; + if (delayTime > 0) { + fps = (1000 * ratio) / (delayTime * 256); + } + + try { + processDrawing(); + } catch (Throwable t) { + JSObject jex = JSExceptions.getJSException(t); + jsLogError("Draw error", t.toString(), jex); + reportCrashWithStack("Draw error: " + t, jex); + } + + if (shouldDebug) { + System.out.println("FPS: " + fps); + } + } + + if (anInt4 == -1) { + exit(); + } + } + + public void exit() { + anInt4 = -2; + cleanUpForQuit(); + } + + public void setFPS(int targetFps) { + delayTime = 1000 / targetFps; + } + + public void handleKeyPressed(int keyCode, char keyChar, boolean isCtrl, boolean isShift) { + idleTime = 0; + ctrlDown = isCtrl; + shiftDown = isShift; + + int ch = mapKey(keyCode, keyChar); + if (ch > 0 && ch < 128) { + keyArray[ch] = 1; + } + if (ch > 4) { + charQueue[writeIndex] = ch; + writeIndex = (writeIndex + 1) & 0x7f; + } + } + + public void handleKeyReleased(int keyCode, char keyChar, boolean isCtrl, boolean isShift) { + idleTime = 0; + ctrlDown = isCtrl; + shiftDown = isShift; + + int ch = mapKey(keyCode, keyChar); + if (ch > 0 && ch < 128) { + keyArray[ch] = 0; + } + } + + private int mapKey(int keyCode, char keyChar) { + int ch = keyChar; + if (ch < 30) ch = 0; + if (keyCode == 37) ch = 1; + if (keyCode == 39) ch = 2; + if (keyCode == 38) ch = 3; + if (keyCode == 40) ch = 4; + if (keyCode == 17) ch = 5; + if (keyCode == 8) ch = 8; + if (keyCode == 46 || keyCode == 127) ch = 8; + if (keyCode == 9) ch = 9; + if (keyCode == 13 || keyCode == 10) ch = 10; + if (keyCode >= 112 && keyCode <= 123) ch = (1008 + keyCode) - 112; + if (keyCode == 36) ch = 1000; + if (keyCode == 35) ch = 1001; + if (keyCode == 33) ch = 1002; + if (keyCode == 34) ch = 1003; + return ch; + } + + public void handleTouchClick(int x, int y, boolean isRightClick) { + mouseX = x; + mouseY = y; + clickX = x; + clickY = y; + clickTime = System.currentTimeMillis(); + clickMode1 = isRightClick ? 2 : 1; + clickMode2 = clickMode1; + idleTime = 0; + } + + public void handleTouchDown(int x, int y) { + mouseX = x; + mouseY = y; + clickX = x; + clickY = y; + clickTime = System.currentTimeMillis(); + clickMode2 = 1; + idleTime = 0; + } + + public void handleTouchMove(int x, int y) { + mouseX = x; + mouseY = y; + idleTime = 0; + } + + public void handleTouchUp() { + clickMode2 = 0; + idleTime = 0; + } + + public void handleCameraDrag(int deltaX, int deltaY) { + mouseWheelDown = true; + mouseWheelDragged(deltaX, deltaY); + mouseWheelDown = false; + } + + void mouseWheelDragged(int param1, int param2) {} + + public void handleMouseWheel(int rotation, boolean isCtrl) { + idleTime = 0; + if (isCtrl || !ClientSettings.CONTROL_KEY_ZOOMING) { + Game.zoom = Math.max(-1, Math.min(8, Game.zoom + rotation)); + } + } + + public int readChar(int dummy) { + int k = -1; + if (writeIndex != readIndex) { + k = charQueue[readIndex]; + readIndex = (readIndex + 1) & 0x7f; + } + return k; + } + + public Object getGameComponent() { + return RSImageProducer.getCanvas(); + } + + public URL getCodeBase() { + try { + return new URL("http://" + ClientSettings.SERVER_IP + "/"); + } catch (MalformedURLException e) { + return null; + } + } + + void startUp() {} + void processGameLoop() {} + void processDrawing() {} + void cleanUpForQuit() {} + void raiseWelcomeScreen() {} + + void drawLoadingText(int percentage, String text) { + drawCanvasLoadingBar(RSImageProducer.getCanvas(), percentage, text); + } + + @JSBody(params = {"canvas", "pct", "text"}, script = + "if (!canvas) return;\n" + + "var ctx = canvas.getContext('2d');\n" + + "if (!ctx) return;\n" + + "var w = canvas.width, h = canvas.height;\n" + + "ctx.fillStyle = '#000';\n" + + "ctx.fillRect(0, 0, w, h);\n" + + "var bw = 304, bh = 34, x = (w - bw) / 2, y = h / 2 - 18;\n" + + "ctx.strokeStyle = '#8c1111';\n" + + "ctx.lineWidth = 2;\n" + + "ctx.strokeRect(x, y, bw, bh);\n" + + "ctx.fillStyle = '#8c1111';\n" + + "var fw = Math.min(300, Math.max(0, pct * 3));\n" + + "if (fw > 0) ctx.fillRect(x + 2, y + 2, fw, bh - 4);\n" + + "ctx.fillStyle = '#ffffff';\n" + + "ctx.font = 'bold 13px sans-serif';\n" + + "ctx.textAlign = 'center';\n" + + "ctx.fillText(text || '', w / 2, y + 22);") + private static native void drawCanvasLoadingBar(HTMLCanvasElement canvas, int pct, String text); + + public String getParameter(String s) { + return DesktopHooks.getParameter(s); + } + + @JSBody(params = {"we"}, script = "return !!(we && we.ctrlKey);") + private static native boolean isWheelCtrlKey(WheelEvent we); + + @JSBody(params = {"msg"}, script = + "var box = document.getElementById('err-box');\n" + + "if (!box) {\n" + + " box = document.createElement('pre');\n" + + " box.id = 'err-box';\n" + + " box.style.cssText = 'position:fixed;bottom:8px;left:8px;max-width:95vw;max-height:200px;overflow:auto;background:rgba(0,0,0,0.88);color:#ff8080;font-size:11px;padding:8px;border:1px solid #833;z-index:9999;margin:0;';\n" + + " document.body.appendChild(box);\n" + + "}\n" + + "if (box.textContent.length < 4000) box.textContent += msg + '\\n';") + public static native void appendLog(String msg); + + @JSBody(params = {"msg", "jsEx"}, script = + "var el = document.getElementById('status-badge');\n" + + "if (el) { el.textContent = msg; el.style.color = '#ff6b6b'; }\n" + + "var box = document.getElementById('err-box');\n" + + "if (!box) {\n" + + " box = document.createElement('pre');\n" + + " box.id = 'err-box';\n" + + " box.style.cssText = 'position:fixed;bottom:8px;left:8px;max-width:95vw;max-height:180px;overflow:auto;background:rgba(0,0,0,0.85);color:#ff8080;font-size:11px;padding:8px;border:1px solid #833;z-index:9999;margin:0;';\n" + + " document.body.appendChild(box);\n" + + "}\n" + + "box.textContent = msg + '\\n' + (jsEx && jsEx.stack ? jsEx.stack : '');") + private static native void reportCrashWithStack(String msg, JSObject jsEx); + + private static void reportCrash(String msg) { + reportCrashWithStack(msg, null); + } + + @JSBody(params = {"label", "msg", "jsEx"}, script = + "console.error('[2006Scape-Web]', label, msg, jsEx, jsEx && jsEx.stack ? jsEx.stack : '');") + private static native void jsLogError(String label, String msg, JSObject jsEx); + + @JSBody(params = {"pct", "text"}, script = + "var ov = document.getElementById('loading-overlay');\n" + + "var fill = document.getElementById('progress-fill');\n" + + "var lbl = document.getElementById('loading-text');\n" + + "if (fill) fill.style.width = Math.max(0, Math.min(100, pct)) + '%';\n" + + "if (lbl && text) lbl.textContent = text;\n" + + "if (ov && pct >= 100) ov.classList.add('hidden');") + public static native void updateLoadingOverlay(int pct, String text); +} diff --git a/src/main/java/org/scape2006/web/RSImageProducer.java b/src/main/java/org/scape2006/web/RSImageProducer.java new file mode 100644 index 0000000..a3439d7 --- /dev/null +++ b/src/main/java/org/scape2006/web/RSImageProducer.java @@ -0,0 +1,101 @@ +package org.scape2006.web; + +import org.teavm.jso.JSBody; +import org.teavm.jso.JSByRef; +import org.teavm.jso.canvas.CanvasRenderingContext2D; +import org.teavm.jso.canvas.ImageData; +import org.teavm.jso.dom.html.HTMLCanvasElement; +import org.teavm.jso.dom.html.HTMLDocument; + +/** + * Web RSImageProducer backed by HTML5 Canvas 2D ImageData. + */ +public final class RSImageProducer { + + public static final int GAME_WIDTH = 765; + public static final int GAME_HEIGHT = 503; + public static final int[] masterScreenBuffer = new int[GAME_WIDTH * GAME_HEIGHT]; + public static final Object masterBufferLock = new Object(); + + public final int[] anIntArray315; + public final int anInt316; // width + public final int anInt317; // height + + private static HTMLCanvasElement canvas; + private static CanvasRenderingContext2D ctx2d; + private ImageData imageData; + + public RSImageProducer(int width, int height, Object component) { + this.anInt316 = width; + this.anInt317 = height; + this.anIntArray315 = new int[width * height]; + ensureCanvas(); + if (ctx2d != null) { + this.imageData = ctx2d.createImageData(width, height); + } + initDrawingArea(); + } + + public static HTMLCanvasElement getCanvas() { + ensureCanvas(); + return canvas; + } + + private static void ensureCanvas() { + if (canvas == null) { + HTMLDocument doc = HTMLDocument.current(); + canvas = (HTMLCanvasElement) doc.getElementById("game-canvas"); + if (canvas != null) { + ctx2d = (CanvasRenderingContext2D) canvas.getContext("2d"); + } + } + } + + public void initDrawingArea() { + DrawingArea.initDrawingArea(anInt317, anInt316, anIntArray315); + Texture.textureInt1 = anInt316 / 2; + if (ClientSettings.RESIZABLE && anInt316 < anInt317) { + Texture.textureInt2 = (int) (anInt317 * 0.38f); + } else { + Texture.textureInt2 = anInt317 / 2; + } + } + + public void drawGraphics(int y, Object graphics, int x) { + if (anIntArray315 == null) return; + if (ClientSettings.isDesktopModern() && !ModernLayout.inGame) { + DesktopHooks.drawScaledLoginTile(graphics, anIntArray315, x, y, anInt316, anInt317); + return; + } + ensureCanvas(); + if (ctx2d == null) return; + if (imageData == null || imageData.getWidth() != anInt316 || imageData.getHeight() != anInt317) { + imageData = ctx2d.createImageData(anInt316, anInt317); + } + boolean gpuViewport = HD117Pipeline.isGpuActive() && anInt316 == ClientSettings.VIEWPORT_WIDTH && anInt317 == ClientSettings.VIEWPORT_HEIGHT; + if (gpuViewport) { + blitOverlayPixelsToImageData(anIntArray315, imageData); + } else { + blitPixelsToImageData(anIntArray315, imageData); + } + ctx2d.putImageData(imageData, x, y); + } + + @JSBody(params = {"pixels", "imgData"}, script = + "var dst = new Uint32Array(imgData.data.buffer);\n" + + "var len = pixels.length;\n" + + "for (var i = 0; i < len; i++) {\n" + + " var c = pixels[i];\n" + + " dst[i] = -16777216 | ((c & 255) << 16) | (c & 65280) | ((c >> 16) & 255);\n" + + "}") + private static native void blitPixelsToImageData(@JSByRef int[] pixels, ImageData imgData); + + @JSBody(params = {"pixels", "imgData"}, script = + "var dst = new Uint32Array(imgData.data.buffer);\n" + + "var len = pixels.length;\n" + + "for (var i = 0; i < len; i++) {\n" + + " var c = pixels[i];\n" + + " dst[i] = (c === 66051) ? 0 : (-16777216 | ((c & 255) << 16) | (c & 65280) | ((c >> 16) & 255));\n" + + "}") + private static native void blitOverlayPixelsToImageData(@JSByRef int[] pixels, ImageData imgData); +} diff --git a/src/main/java/org/scape2006/web/RSSocket.java b/src/main/java/org/scape2006/web/RSSocket.java new file mode 100644 index 0000000..d94f36f --- /dev/null +++ b/src/main/java/org/scape2006/web/RSSocket.java @@ -0,0 +1,145 @@ +package org.scape2006.web; + +import org.scape2006.web.net.Socket; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * Browser-safe RSSocket backed by WebSocketAdapter. + */ +final class RSSocket implements Runnable { + + private final InputStream inputStream; + private final OutputStream outputStream; + private final Socket socket; + private boolean closed; + private final RSApplet rsApplet; + private byte[] buffer; + private int writeIndex; + private int buffIndex; + private boolean isWriter; + private boolean hasIOError; + + public RSSocket(RSApplet applet, Socket socket) throws IOException { + this.closed = false; + this.isWriter = false; + this.hasIOError = false; + this.rsApplet = applet; + this.socket = socket; + this.socket.setSoTimeout(30000); + this.socket.setTcpNoDelay(true); + this.inputStream = socket.getInputStream(); + this.outputStream = socket.getOutputStream(); + } + + public void close() { + closed = true; + try { + if (inputStream != null) inputStream.close(); + if (outputStream != null) outputStream.close(); + if (socket != null) socket.close(); + } catch (IOException ignored) { + } + isWriter = false; + synchronized (this) { + notifyAll(); + } + buffer = null; + } + + public int read() throws IOException { + if (closed) return 0; + return inputStream.read(); + } + + public int available() throws IOException { + if (closed) return 0; + return inputStream.available(); + } + + public void flushInputStream(byte[] dst, int len) throws IOException { + int off = 0; + if (closed) return; + while (len > 0) { + int n = inputStream.read(dst, off, len); + if (n <= 0) { + throw new IOException("EOF"); + } + off += n; + len -= n; + } + } + + public void queueBytes(int len, byte[] src) throws IOException { + if (closed) return; + if (hasIOError) { + hasIOError = false; + throw new IOException("Error in writer thread"); + } + if (buffer == null) { + buffer = new byte[5000]; + } + synchronized (this) { + for (int i = 0; i < len; i++) { + buffer[buffIndex] = src[i]; + buffIndex = (buffIndex + 1) % 5000; + if (buffIndex == (writeIndex + 4900) % 5000) { + throw new IOException("buffer overflow"); + } + } + if (!isWriter) { + isWriter = true; + rsApplet.startRunnable(this, 3); + } + notifyAll(); + } + } + + @Override + public void run() { + while (isWriter) { + int count; + int offset; + synchronized (this) { + if (buffIndex == writeIndex) { + try { + wait(); + } catch (InterruptedException ignored) { + } + } + if (!isWriter) return; + offset = writeIndex; + count = (buffIndex >= writeIndex) ? (buffIndex - writeIndex) : (5000 - writeIndex); + } + if (count > 0) { + try { + outputStream.write(buffer, offset, count); + } catch (IOException ex) { + hasIOError = true; + } + writeIndex = (writeIndex + count) % 5000; + try { + if (buffIndex == writeIndex) { + outputStream.flush(); + } + } catch (IOException ex) { + hasIOError = true; + } + } + } + } + + public void printDebug() { + System.out.println("dummy:" + closed); + System.out.println("tcycl:" + writeIndex); + System.out.println("tnum:" + buffIndex); + System.out.println("writer:" + isWriter); + System.out.println("ioerror:" + hasIOError); + try { + System.out.println("available:" + available()); + } catch (IOException ignored) { + } + } +} diff --git a/src/main/java/org/scape2006/web/Signlink.java b/src/main/java/org/scape2006/web/Signlink.java new file mode 100644 index 0000000..16d8591 --- /dev/null +++ b/src/main/java/org/scape2006/web/Signlink.java @@ -0,0 +1,127 @@ +package org.scape2006.web; + +import org.scape2006.web.net.InetAddress; +import org.scape2006.web.net.Socket; +import org.teavm.jso.JSBody; +import java.io.IOException; + +/** + * Web Signlink implementation backed by in-memory VirtualFiles and WebSocketAdapter. + */ +public final class Signlink { + + public static Object mainapp = null; + public static int storeid = 32; + public static boolean reporterror = true; + public static String errorname = ""; + public static String dns = null; + public static boolean sunjava = false; + public static int wavevol = 0; + public static String midi = null; + public static int midifade = 0; + public static int midiVolume = 255; + public static int fadeValue = 0; + + public static VirtualFile cache_dat = new VirtualFile(null); + public static final VirtualFile[] cache_idx = new VirtualFile[]{ + new VirtualFile(null), + new VirtualFile(null), + new VirtualFile(null), + new VirtualFile(null), + new VirtualFile(null) + }; + + private static byte[] lastWaveBytes = null; + private static int lastWaveLength = 0; + + private Signlink() {} + + public static void startpriv(InetAddress addr) { + // No-op on web; cache is preloaded by WebLauncher + } + + public static String findcachedir() { + return "/cache/"; + } + + public static Socket opensocket(int port) throws IOException { + int wsPort = mapTcpPortToWebSocketPort(port); + String host = ClientSettings.SERVER_IP; + if (host == null || host.isEmpty() || "127.0.0.1".equals(host) || "localhost".equals(host)) { + host = getBrowserHostname(); + if (host == null || host.isEmpty()) { + host = "127.0.0.1"; + } + } + String proto = isSecureOrigin() ? "wss://" : "ws://"; + String url = proto + host + ":" + wsPort + "/"; + return new WebSocketAdapter(url); + } + + private static int mapTcpPortToWebSocketPort(int tcpPort) { + if (WebLauncher.overrideWsPort > 0) { + return WebLauncher.overrideWsPort; + } + // +1000 offset matching 2006Scape Server's Constants.WEBSOCKET_PORT: + // World 1: 43594 -> 44594, World 2+: 43596 + world -> 44596 + world + if (tcpPort >= 43594 && tcpPort <= 43999) { + return tcpPort + 1000; + } + return 44594; + } + + public static void startthread(Runnable runnable, int priority) { + Thread t = new Thread(runnable); + t.setDaemon(true); + t.start(); + } + + public static void dnslookup(String s) { + dns = s; + } + + public static void reporterror(String s) { + if (reporterror) { + System.err.println("[2006Scape-Web] " + s); + RSApplet.appendLog("[Signlink] " + s); + } + } + + public static boolean wavesave(byte[] data, int len) { + if (data == null || len <= 0) return false; + lastWaveBytes = data; + lastWaveLength = len; + DesktopHooks.playSound(data, 0, len, 100, 0); + return true; + } + + public static boolean wavereplay() { + if (lastWaveBytes != null && lastWaveLength > 0) { + DesktopHooks.playSound(lastWaveBytes, 0, lastWaveLength, 100, 0); + return true; + } + return false; + } + + public static void saveMidi(byte[] data, int len) { + midisave(data, len); + } + + public static void midisave(byte[] data, int len) { + if (data != null && len > 0) { + byte[] copy = new byte[len]; + System.arraycopy(data, 0, copy, 0, len); + DesktopHooks.playMidiBytes(copy, midiVolume); + } + } + + public static void close() { + // Nothing to close synchronously + } + + @JSBody(script = "return window.location.hostname || '127.0.0.1';") + private static native String getBrowserHostname(); + + @JSBody(script = "return window.location.protocol === 'https:';") + private static native boolean isSecureOrigin(); +} diff --git a/src/main/java/org/scape2006/web/VirtualFile.java b/src/main/java/org/scape2006/web/VirtualFile.java new file mode 100644 index 0000000..05a5efb --- /dev/null +++ b/src/main/java/org/scape2006/web/VirtualFile.java @@ -0,0 +1,63 @@ +package org.scape2006.web; + +import java.io.IOException; +import java.util.Arrays; + +/** + * In-memory random-access file buffer replacing java.io.RandomAccessFile for TeaVM. + */ +public final class VirtualFile { + + private byte[] data; + private int length; + private int pos; + + public VirtualFile(byte[] initialData) { + if (initialData != null) { + this.data = initialData; + this.length = initialData.length; + } else { + this.data = new byte[0]; + this.length = 0; + } + this.pos = 0; + } + + public synchronized void seek(long offset) throws IOException { + if (offset < 0) { + throw new IOException("Negative seek offset: " + offset); + } + this.pos = (int) offset; + } + + public synchronized long length() { + return length; + } + + public synchronized int read(byte[] dst, int off, int len) { + if (pos >= length) { + return -1; + } + int avail = Math.min(len, length - pos); + System.arraycopy(data, pos, dst, off, avail); + pos += avail; + return avail; + } + + public synchronized void write(byte[] src, int off, int len) { + int end = pos + len; + if (end > data.length) { + int newCap = Math.max(end, data.length + (data.length >> 1) + 4096); + data = Arrays.copyOf(data, newCap); + } + System.arraycopy(src, off, data, pos, len); + pos = end; + if (pos > length) { + length = pos; + } + } + + public synchronized byte[] toByteArray() { + return Arrays.copyOf(data, length); + } +} diff --git a/src/main/java/org/scape2006/web/WebGL2.java b/src/main/java/org/scape2006/web/WebGL2.java new file mode 100644 index 0000000..756400c --- /dev/null +++ b/src/main/java/org/scape2006/web/WebGL2.java @@ -0,0 +1,130 @@ +package org.scape2006.web; + +import org.teavm.jso.JSBody; +import org.teavm.jso.JSObject; +import org.teavm.jso.dom.html.HTMLCanvasElement; +import org.teavm.jso.typedarrays.Float32Array; +import org.teavm.jso.typedarrays.Uint8Array; + +/** + * TeaVM JSO bindings for WebGL 2.0 (OpenGL ES 3.0) used by WebHd117Renderer. + */ +public interface WebGL2 extends JSObject { + + int COLOR_BUFFER_BIT = 0x00004000; + int DEPTH_BUFFER_BIT = 0x00000100; + int TRIANGLES = 0x0004; + int LEQUAL = 0x0203; + int SRC_ALPHA = 0x0302; + int ONE_MINUS_SRC_ALPHA = 0x0303; + int DEPTH_TEST = 0x0B71; + int BLEND = 0x0BE2; + int POLYGON_OFFSET_FILL = 0x8037; + int FLOAT = 0x1406; + int UNSIGNED_BYTE = 0x1401; + int UNSIGNED_INT = 0x1405; + int RGBA = 0x1908; + int RGBA8 = 0x8058; + int DEPTH_COMPONENT = 0x1902; + int DEPTH_COMPONENT24 = 0x81A6; + int TEXTURE_2D = 0x0DE1; + int TEXTURE_2D_ARRAY = 0x8C1A; + int TEXTURE0 = 0x84C0; + int TEXTURE1 = 0x84C1; + int TEXTURE2 = 0x84C2; + int TEXTURE_MIN_FILTER = 0x2801; + int TEXTURE_MAG_FILTER = 0x2800; + int TEXTURE_WRAP_S = 0x2802; + int TEXTURE_WRAP_T = 0x2803; + int NEAREST = 0x2600; + int LINEAR = 0x2601; + int LINEAR_MIPMAP_LINEAR = 0x2703; + int REPEAT = 0x2901; + int CLAMP_TO_EDGE = 0x812F; + int ARRAY_BUFFER = 0x8892; + int STATIC_DRAW = 0x88E4; + int STREAM_DRAW = 0x88E0; + int FRAMEBUFFER = 0x8D40; + int RENDERBUFFER = 0x8D41; + int COLOR_ATTACHMENT0 = 0x8CE0; + int DEPTH_ATTACHMENT = 0x8D00; + int NONE = 0; + int VERTEX_SHADER = 0x8B31; + int FRAGMENT_SHADER = 0x8B30; + int COMPILE_STATUS = 0x8B81; + int LINK_STATUS = 0x8B82; + + interface Buffer extends JSObject {} + interface Framebuffer extends JSObject {} + interface Renderbuffer extends JSObject {} + interface Program extends JSObject {} + interface Shader extends JSObject {} + interface Texture extends JSObject {} + interface UniformLocation extends JSObject {} + + @JSBody(params = {"canvas"}, script = + "return canvas.getContext('webgl2', { alpha: true, antialias: false, preserveDrawingBuffer: false });") + static WebGL2 getContext(HTMLCanvasElement canvas) { + return null; + } + + void viewport(int x, int y, int width, int height); + void clearColor(float r, float g, float b, float a); + void clear(int mask); + void enable(int cap); + void disable(int cap); + void depthFunc(int func); + void depthMask(boolean flag); + void blendFunc(int sfactor, int dfactor); + void polygonOffset(float factor, float units); + + Shader createShader(int type); + void shaderSource(Shader shader, String source); + void compileShader(Shader shader); + boolean getShaderParameter(Shader shader, int pname); + String getShaderInfoLog(Shader shader); + void deleteShader(Shader shader); + + Program createProgram(); + void attachShader(Program program, Shader shader); + void linkProgram(Program program); + boolean getProgramParameter(Program program, int pname); + String getProgramInfoLog(Program program); + void useProgram(Program program); + + UniformLocation getUniformLocation(Program program, String name); + void uniform1i(UniformLocation loc, int v); + void uniform1f(UniformLocation loc, float v); + void uniform3f(UniformLocation loc, float x, float y, float z); + void uniform4fv(UniformLocation loc, Float32Array v); + void uniformMatrix4fv(UniformLocation loc, boolean transpose, Float32Array value); + + Buffer createBuffer(); + void bindBuffer(int target, Buffer buffer); + void bufferData(int target, int size, int usage); + void bufferData(int target, Float32Array data, int usage); + void bufferSubData(int target, int offset, Float32Array data); + void enableVertexAttribArray(int index); + void disableVertexAttribArray(int index); + void vertexAttribPointer(int index, int size, int type, boolean normalized, int stride, int offset); + void drawArrays(int mode, int first, int count); + + Texture createTexture(); + void activeTexture(int texture); + void bindTexture(int target, Texture texture); + void texParameteri(int target, int pname, int param); + void texImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Uint8Array pixels); + void texImage3D(int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, Uint8Array pixels); + void generateMipmap(int target); + + Framebuffer createFramebuffer(); + void bindFramebuffer(int target, Framebuffer fb); + void framebufferTexture2D(int target, int attachment, int textarget, Texture texture, int level); + Renderbuffer createRenderbuffer(); + void bindRenderbuffer(int target, Renderbuffer rb); + void renderbufferStorage(int target, int internalformat, int width, int height); + void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, Renderbuffer rb); + void drawBuffers(int[] buffers); + + void readPixels(int x, int y, int width, int height, int format, int type, Uint8Array pixels); +} diff --git a/src/main/java/org/scape2006/web/WebHd117Renderer.java b/src/main/java/org/scape2006/web/WebHd117Renderer.java new file mode 100644 index 0000000..b10a54f --- /dev/null +++ b/src/main/java/org/scape2006/web/WebHd117Renderer.java @@ -0,0 +1,867 @@ +package org.scape2006.web; + +import org.teavm.jso.JSBody; +import org.teavm.jso.JSByRef; +import org.teavm.jso.dom.html.HTMLCanvasElement; +import org.teavm.jso.dom.html.HTMLDocument; +import org.teavm.jso.typedarrays.Float32Array; +import org.teavm.jso.typedarrays.Int32Array; +import org.teavm.jso.typedarrays.Uint8Array; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; + +/** + * WebGL 2.0 (GLSL ES 3.00) 117HD Hardware Renderer for 2006Scape-Web. + * Reuses HD117Pipeline shaders, HdSceneUploader, HdMaterial, and HdProceduralGenerator. + */ +public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend { + + private int shadowMapSize = 1024; + private final HdProceduralGenerator procGen = new HdProceduralGenerator(); + private final HdSceneUploader sceneUploader = new HdSceneUploader(); + + private WebGL2 gl = null; + private boolean glInitialized = false; + private boolean glFailed = false; + + private WebGL2.Program shadowProgram = null; + private WebGL2.Program sceneProgram = null; + + private WebGL2.UniformLocation uShadowLightViewProj; + private WebGL2.UniformLocation uShadowDiffuseArray; + + private WebGL2.UniformLocation uSceneViewProj; + private WebGL2.UniformLocation uSceneLightViewProj; + private WebGL2.UniformLocation uSceneDiffuseArray; + private WebGL2.UniformLocation uSceneNormalArray; + private WebGL2.UniformLocation uSceneShadowMap; + private WebGL2.UniformLocation uSceneCameraPos; + private WebGL2.UniformLocation uSceneSunDir; + private WebGL2.UniformLocation uSceneSunColor; + private WebGL2.UniformLocation uSceneAmbientColor; + private WebGL2.UniformLocation uSceneSkyColor; + private WebGL2.UniformLocation uSceneFogColor; + private WebGL2.UniformLocation uSceneFogMin; + private WebGL2.UniformLocation uSceneFogMax; + private WebGL2.UniformLocation uSceneTime; + private WebGL2.UniformLocation uSceneShadowTexelSize; + private WebGL2.UniformLocation uSceneShadowsEnabled; + private WebGL2.UniformLocation uSceneShadowSoftPcf; + private WebGL2.UniformLocation uSceneGroundTextures; + private WebGL2.UniformLocation uSceneNormalMapping; + private WebGL2.UniformLocation uSceneWaterShader; + private WebGL2.UniformLocation uSceneSaturation; + private WebGL2.UniformLocation uSceneBrightness; + private WebGL2.UniformLocation uSceneContrastCurve; + private WebGL2.UniformLocation uSceneLightCount; + private WebGL2.UniformLocation uSceneLightPosRad; + private WebGL2.UniformLocation uSceneLightColorInt; + + private WebGL2.Texture diffuseArrayTex = null; + private WebGL2.Texture normalArrayTex = null; + private boolean materialsInitialized = false; + + private final WebGL2.Buffer[] terrainVbos = new WebGL2.Buffer[4]; + private final int[] terrainBucketCounts = new int[4]; + private final WebGL2.Buffer[][] staticOpaqueVbos = new WebGL2.Buffer[4][HdSceneUploader.CHUNKS_PER_PLANE]; + private final int[][] staticOpaqueCounts = new int[4][HdSceneUploader.CHUNKS_PER_PLANE]; + private final WebGL2.Buffer[][] staticTransVbos = new WebGL2.Buffer[4][HdSceneUploader.CHUNKS_PER_PLANE]; + private final int[][] staticTransCounts = new int[4][HdSceneUploader.CHUNKS_PER_PLANE]; + private final int[][] uploadedChunkGen = new int[4][HdSceneUploader.CHUNKS_PER_PLANE]; + private final boolean[] chunkVisible = new boolean[HdSceneUploader.CHUNKS_PER_PLANE]; + private int uploadedTerrainGenId = -1; + private WebGL2.Buffer sceneVbo = null; + private WebGL2.Buffer transVbo = null; + private int sceneVboCapacity = 0; + private int transVboCapacity = 0; + + private WebGL2.Framebuffer shadowFbo = null; + private WebGL2.Texture shadowDepthTex = null; + private HTMLCanvasElement glCanvas = null; + + private Float32Array scratchF32 = Float32Array.create(65536); + + private int camX, camY, camZ, camPitch, camYaw; + private final float[] viewProjMatrix = new float[16]; + private final float[] lightViewMatrix = new float[16]; + private final float[] lightProjMatrix = new float[16]; + private final float[] lightViewProjMatrix = new float[16]; + private final Float32Array viewProjF32 = Float32Array.create(16); + private final Float32Array lightViewProjF32 = Float32Array.create(16); + + private final float[] sunDir = {-0.52f, -0.74f, -0.42f}; + private final float[] sunColor = {0.88f, 0.84f, 0.76f}; + private final float[] ambientColor = {0.46f, 0.52f, 0.62f}; + private final float[] skyColor = {0.62f, 0.78f, 0.94f}; + private final float[] fogColor = {0.68f, 0.81f, 0.94f}; + private float fogMin = 2100.0f; + private float fogMax = 3500.0f; + + private static final int MAX_ACTIVE_LIGHTS = 16; + private final Float32Array activeLightPosRad = Float32Array.create(MAX_ACTIVE_LIGHTS * 4); + private final Float32Array activeLightColorInt = Float32Array.create(MAX_ACTIVE_LIGHTS * 4); + private int activeLightCount = 0; + + private final long startTimeMs = System.currentTimeMillis(); + private boolean sceneLoaded = false; + private boolean loggedFirstFrame = false; + private Game lastGame = null; + private ObjectManager lastObjectManager = null; + private WorldController lastWorldController = null; + + public WebHd117Renderer() { + float len = (float) Math.sqrt(sunDir[0] * sunDir[0] + sunDir[1] * sunDir[1] + sunDir[2] * sunDir[2]); + sunDir[0] /= len; + sunDir[1] /= len; + sunDir[2] /= len; + } + + @Override + public boolean isGpuReady() { + return !glFailed; + } + + @Override + public void onSceneLoad(Game game, ObjectManager objectManager, WorldController worldController) { + this.lastGame = game; + this.lastObjectManager = objectManager; + this.lastWorldController = worldController; + try { + procGen.generateSceneData(game, objectManager, worldController); + sceneUploader.setSceneContext(procGen, worldController); + sceneLoaded = true; + } catch (Throwable t) { + System.err.println("[WebHd117Renderer] Error generating scene data: " + t.getMessage()); + } + } + + @Override + public void beginFrame(Game game, int xCam, int yCam, int zCam, int pitch, int yaw) { + if (glFailed) return; + if (!sceneLoaded && game != null && game.worldController != null) { + sceneUploader.setSceneContext(procGen, game.worldController); + sceneLoaded = true; + } + this.camX = xCam; + this.camY = yCam; + this.camZ = zCam; + this.camPitch = pitch; + this.camYaw = yaw; + updateEnvironmentProfile(game); + sceneUploader.resetFrame(); + } + + @Override + public void drawSimpleTile(Class43 tile, int plane, int tileX, int tileZ) { + if (!glFailed) sceneUploader.appendSimpleTile(tile, plane, tileX, tileZ); + } + + @Override + public void drawShapedTile(Class40 tile, int plane, int tileX, int tileZ) { + if (!glFailed) sceneUploader.appendShapedTile(tile, plane, tileX, tileZ); + } + + @Override + public void drawModel(Model model, int orientation, int sinPitch, int cosPitch, int sinYaw, int cosYaw, + int relX, int relY, int relZ, int uid) { + if (!glFailed) sceneUploader.appendModel(model, orientation, relX, relY, relZ, uid); + } + + @Override + public void endFrame(int[] dstPixels, int width, int height) { + if (glFailed || dstPixels == null || width <= 0 || height <= 0 || dstPixels.length < width * height) { + return; + } + if (!ensureGlContext()) return; + if (!materialsInitialized) initMaterials(); + + this.camX = WorldController.anInt455; + this.camY = WorldController.anInt456; + this.camZ = WorldController.anInt457; + + sceneUploader.rebuildDirtyChunks(); + + int curTerrainGen = sceneUploader.getTerrainGenerationId(); + if (curTerrainGen != uploadedTerrainGenId) { + for (int b = 0; b < 4; b++) { + int cnt = sceneUploader.getStaticTerrainVertexCount(b); + terrainBucketCounts[b] = cnt; + if (cnt > 0) { + float[] tb = sceneUploader.getStaticTerrainBucket(b); + if (tb != null) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, terrainVbos[b]); + gl.bufferData(WebGL2.ARRAY_BUFFER, toFloat32Array(tb, cnt * 16), WebGL2.STATIC_DRAW); + } + } + } + uploadedTerrainGenId = curTerrainGen; + } + + for (int b = 0; b < 4; b++) { + for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) { + int gen = sceneUploader.getStaticSceneryChunkGen(b, c); + if (gen != uploadedChunkGen[b][c]) { + uploadedChunkGen[b][c] = gen; + int soCnt = sceneUploader.getStaticSceneryOpaqueCount(b, c); + staticOpaqueCounts[b][c] = soCnt; + if (soCnt > 0) { + float[] sb = sceneUploader.getStaticSceneryOpaqueBucket(b, c); + if (sb != null) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, staticOpaqueVbos[b][c]); + gl.bufferData(WebGL2.ARRAY_BUFFER, toFloat32Array(sb, soCnt * 16), WebGL2.STATIC_DRAW); + } + } + int stCnt = sceneUploader.getStaticSceneryTransCount(b, c); + staticTransCounts[b][c] = stCnt; + if (stCnt > 0) { + float[] stb = sceneUploader.getStaticSceneryTransBucket(b, c); + if (stb != null) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, staticTransVbos[b][c]); + gl.bufferData(WebGL2.ARRAY_BUFFER, toFloat32Array(stb, stCnt * 16), WebGL2.STATIC_DRAW); + } + } + } + } + } + + int opaqueCount = sceneUploader.getOpaqueVertexCount(); + int transCount = sceneUploader.getTransVertexCount(); + if (opaqueCount > 0) { + sceneVboCapacity = uploadStreamVbo(sceneVbo, sceneVboCapacity, opaqueCount, sceneUploader.getOpaqueStaging()); + } + if (transCount > 0) { + transVboCapacity = uploadStreamVbo(transVbo, transVboCapacity, transCount, sceneUploader.getTransStaging()); + } + + computeCameraAndLightMatrices(width, height); + selectActiveLights(); + + boolean shadowsOn = HD117Pipeline.cfgShadowsEnabled; + int desiredShadowSize = HD117Pipeline.cfgShadowResolution; + if (shadowsOn && desiredShadowSize != shadowMapSize && + (desiredShadowSize == 512 || desiredShadowSize == 1024 || desiredShadowSize == 2048)) { + shadowMapSize = desiredShadowSize; + gl.bindTexture(WebGL2.TEXTURE_2D, shadowDepthTex); + gl.texImage2D(WebGL2.TEXTURE_2D, 0, WebGL2.DEPTH_COMPONENT24, + shadowMapSize, shadowMapSize, 0, WebGL2.DEPTH_COMPONENT, WebGL2.UNSIGNED_INT, null); + } + + int maxPlane = WorldController.hdMaxPlane; + float maxChunkDist = fogMax + HdSceneUploader.CHUNK_RADIUS; + float maxChunkDistSq = maxChunkDist * maxChunkDist; + boolean hasStaticOpaque = false; + boolean hasStaticTrans = false; + for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) { + int cx = c / HdSceneUploader.CHUNKS_PER_AXIS; + int cz = c % HdSceneUploader.CHUNKS_PER_AXIS; + float centerX = (cx * HdSceneUploader.CHUNK_TILE_SIZE + HdSceneUploader.CHUNK_TILE_SIZE * 0.5f) * 128.0f; + float centerZ = (cz * HdSceneUploader.CHUNK_TILE_SIZE + HdSceneUploader.CHUNK_TILE_SIZE * 0.5f) * 128.0f; + float dx = centerX - camX; + float dz = centerZ - camZ; + boolean vis = (dx * dx + dz * dz) <= maxChunkDistSq; + chunkVisible[c] = vis; + if (vis) { + for (int b = 0; b <= maxPlane; b++) { + if (staticOpaqueCounts[b][c] > 0) hasStaticOpaque = true; + if (staticTransCounts[b][c] > 0) hasStaticTrans = true; + } + } + } + + // Pass 1: Shadow Depth Map + if (shadowsOn && (opaqueCount > 0 || hasStaticOpaque)) { + gl.bindFramebuffer(WebGL2.FRAMEBUFFER, shadowFbo); + gl.viewport(0, 0, shadowMapSize, shadowMapSize); + gl.enable(WebGL2.DEPTH_TEST); + gl.depthFunc(WebGL2.LEQUAL); + gl.depthMask(true); + gl.disable(WebGL2.BLEND); + gl.enable(WebGL2.POLYGON_OFFSET_FILL); + gl.polygonOffset(1.5f, 3.0f); + gl.clear(WebGL2.DEPTH_BUFFER_BIT); + + gl.useProgram(shadowProgram); + gl.uniformMatrix4fv(uShadowLightViewProj, false, lightViewProjF32); + gl.activeTexture(WebGL2.TEXTURE0); + gl.bindTexture(WebGL2.TEXTURE_2D_ARRAY, diffuseArrayTex); + gl.uniform1i(uShadowDiffuseArray, 0); + + for (int b = 0; b <= maxPlane; b++) { + for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) { + if (!chunkVisible[c]) continue; + int soCnt = staticOpaqueCounts[b][c]; + if (soCnt > 0) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, staticOpaqueVbos[b][c]); + bindShadowAttribs(); + gl.drawArrays(WebGL2.TRIANGLES, 0, soCnt); + } + } + } + if (opaqueCount > 0) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, sceneVbo); + bindShadowAttribs(); + gl.drawArrays(WebGL2.TRIANGLES, 0, opaqueCount); + } + + gl.disableVertexAttribArray(0); + gl.disableVertexAttribArray(2); + gl.disableVertexAttribArray(4); + gl.disable(WebGL2.POLYGON_OFFSET_FILL); + } + + // Pass 2: Main 117HD Scene directly onto #gl-canvas default framebuffer (zero readPixels!) + int targetCanvasW = ClientSettings.isDesktopModern() ? width : 765; + int targetCanvasH = ClientSettings.isDesktopModern() ? height : 503; + if (glCanvas.getWidth() != targetCanvasW || glCanvas.getHeight() != targetCanvasH + || jsGetDrawingBufferWidth(gl) != targetCanvasW || jsGetDrawingBufferHeight(gl) != targetCanvasH) { + glCanvas.setWidth(targetCanvasW); + glCanvas.setHeight(targetCanvasH); + } + int canvasH = glCanvas.getHeight(); + int vpX = ClientSettings.isDesktopModern() ? 0 : 4; + int vpY = ClientSettings.isDesktopModern() ? 0 : Math.max(0, canvasH - 4 - height); + gl.bindFramebuffer(WebGL2.FRAMEBUFFER, null); + gl.viewport(vpX, vpY, width, height); + gl.clearColor(fogColor[0], fogColor[1], fogColor[2], 1.0f); + gl.clear(WebGL2.COLOR_BUFFER_BIT | WebGL2.DEPTH_BUFFER_BIT); + gl.enable(WebGL2.DEPTH_TEST); + gl.depthFunc(WebGL2.LEQUAL); + gl.depthMask(true); + + boolean hasTerrain = false; + for (int b = 0; b <= maxPlane; b++) { + if (terrainBucketCounts[b] > 0) { hasTerrain = true; break; } + } + + if (hasTerrain || hasStaticOpaque || hasStaticTrans || opaqueCount > 0 || transCount > 0) { + gl.enable(WebGL2.BLEND); + gl.blendFunc(WebGL2.SRC_ALPHA, WebGL2.ONE_MINUS_SRC_ALPHA); + + gl.useProgram(sceneProgram); + gl.uniformMatrix4fv(uSceneViewProj, false, viewProjF32); + gl.uniformMatrix4fv(uSceneLightViewProj, false, lightViewProjF32); + gl.uniform3f(uSceneCameraPos, (float) camX, (float) camY, (float) camZ); + gl.uniform3f(uSceneSunDir, sunDir[0], sunDir[1], sunDir[2]); + gl.uniform3f(uSceneSunColor, sunColor[0], sunColor[1], sunColor[2]); + gl.uniform3f(uSceneAmbientColor, ambientColor[0], ambientColor[1], ambientColor[2]); + gl.uniform3f(uSceneSkyColor, skyColor[0], skyColor[1], skyColor[2]); + gl.uniform3f(uSceneFogColor, fogColor[0], fogColor[1], fogColor[2]); + gl.uniform1f(uSceneFogMin, HD117Pipeline.cfgAtmosphericFog ? fogMin : 999999.0f); + gl.uniform1f(uSceneFogMax, HD117Pipeline.cfgAtmosphericFog ? fogMax : 1000000.0f); + gl.uniform1f(uSceneTime, (System.currentTimeMillis() - startTimeMs) * 0.001f); + gl.uniform1f(uSceneShadowTexelSize, 1.0f / shadowMapSize); + gl.uniform1i(uSceneShadowsEnabled, shadowsOn ? 1 : 0); + gl.uniform1i(uSceneShadowSoftPcf, HD117Pipeline.cfgShadowSoftPcf ? 1 : 0); + gl.uniform1i(uSceneGroundTextures, HD117Pipeline.cfgGroundTextures ? 1 : 0); + gl.uniform1i(uSceneNormalMapping, HD117Pipeline.cfgNormalMapping ? 1 : 0); + gl.uniform1i(uSceneWaterShader, HD117Pipeline.cfgWaterShader ? 1 : 0); + gl.uniform1f(uSceneSaturation, HD117Pipeline.cfgSaturation); + gl.uniform1f(uSceneBrightness, HD117Pipeline.cfgBrightness); + gl.uniform1i(uSceneContrastCurve, HD117Pipeline.cfgContrastCurve ? 1 : 0); + + gl.uniform1i(uSceneLightCount, activeLightCount); + if (activeLightCount > 0) { + gl.uniform4fv(uSceneLightPosRad, activeLightPosRad); + gl.uniform4fv(uSceneLightColorInt, activeLightColorInt); + } + + gl.activeTexture(WebGL2.TEXTURE0); + gl.bindTexture(WebGL2.TEXTURE_2D_ARRAY, diffuseArrayTex); + gl.uniform1i(uSceneDiffuseArray, 0); + + gl.activeTexture(WebGL2.TEXTURE1); + gl.bindTexture(WebGL2.TEXTURE_2D_ARRAY, normalArrayTex); + gl.uniform1i(uSceneNormalArray, 1); + + gl.activeTexture(WebGL2.TEXTURE2); + gl.bindTexture(WebGL2.TEXTURE_2D, shadowDepthTex); + gl.uniform1i(uSceneShadowMap, 2); + + gl.depthMask(true); + for (int b = 0; b <= maxPlane; b++) { + int cnt = terrainBucketCounts[b]; + if (cnt > 0) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, terrainVbos[b]); + bindSceneVertexAttribs(); + gl.drawArrays(WebGL2.TRIANGLES, 0, cnt); + } + } + + for (int b = 0; b <= maxPlane; b++) { + for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) { + if (!chunkVisible[c]) continue; + int soCnt = staticOpaqueCounts[b][c]; + if (soCnt > 0) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, staticOpaqueVbos[b][c]); + bindSceneVertexAttribs(); + gl.drawArrays(WebGL2.TRIANGLES, 0, soCnt); + } + } + } + + if (opaqueCount > 0) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, sceneVbo); + bindSceneVertexAttribs(); + gl.depthMask(true); + gl.drawArrays(WebGL2.TRIANGLES, 0, opaqueCount); + } + + for (int b = 0; b <= maxPlane; b++) { + for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) { + if (!chunkVisible[c]) continue; + int stCnt = staticTransCounts[b][c]; + if (stCnt > 0) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, staticTransVbos[b][c]); + bindSceneVertexAttribs(); + gl.depthMask(false); + gl.drawArrays(WebGL2.TRIANGLES, 0, stCnt); + gl.depthMask(true); + } + } + } + + if (transCount > 0) { + gl.bindBuffer(WebGL2.ARRAY_BUFFER, transVbo); + bindSceneVertexAttribs(); + gl.depthMask(false); + gl.drawArrays(WebGL2.TRIANGLES, 0, transCount); + gl.depthMask(true); + } + + unbindSceneVertexAttribs(); + } + + if (!loggedFirstFrame) { + loggedFirstFrame = true; + int err = getGlError(gl); + if (err != 0) { + RSApplet.appendLog("[WebHd117Renderer] glErr=" + err); + } + } + // Clear dstPixels to sentinel 0x010203 (transparent) so 0x000000 black UI/shadows stay opaque on #game-canvas above #gl-canvas + Arrays.fill(dstPixels, 0, width * height, 0x010203); + } + + @Override + public void onStaticChunkInvalidated(int tileX, int tileZ) { + sceneUploader.invalidateChunk(tileX, tileZ); + } + + @Override + public void onToggle(boolean enabled) { + if (enabled && !sceneLoaded && lastObjectManager != null && lastWorldController != null) { + onSceneLoad(lastGame, lastObjectManager, lastWorldController); + } + } + + private Float32Array toFloat32Array(float[] src, int floatCount) { + if (scratchF32.getLength() < floatCount) { + int newCap = Math.max(floatCount, scratchF32.getLength() * 2); + scratchF32 = Float32Array.create(newCap); + } + copyFloatArray(scratchF32, src, floatCount); + return floatSubarray(scratchF32, 0, floatCount); + } + + @JSBody(params = {"dst", "src", "count"}, script = "dst.set(src.subarray(0, count), 0);") + private static native void copyFloatArray(Float32Array dst, @JSByRef float[] src, int count); + + @JSBody(params = {"arr", "start", "end"}, script = "return arr.subarray(start, end);") + private static native Float32Array floatSubarray(Float32Array arr, int start, int end); + + private int uploadStreamVbo(WebGL2.Buffer vbo, int currentCapacity, int vertexCount, float[] buf) { + int requiredBytes = vertexCount * HdSceneUploader.BYTES_PER_VERTEX; + gl.bindBuffer(WebGL2.ARRAY_BUFFER, vbo); + if (requiredBytes > currentCapacity) { + int newCap = Math.max(requiredBytes, currentCapacity + (currentCapacity >> 1)); + gl.bufferData(WebGL2.ARRAY_BUFFER, newCap, WebGL2.STREAM_DRAW); + currentCapacity = newCap; + } + gl.bufferSubData(WebGL2.ARRAY_BUFFER, 0, toFloat32Array(buf, vertexCount * 16)); + return currentCapacity; + } + + private void bindShadowAttribs() { + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 3, WebGL2.FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, 0); + gl.enableVertexAttribArray(2); + gl.vertexAttribPointer(2, 2, WebGL2.FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, 6 * 4); + gl.enableVertexAttribArray(4); + gl.vertexAttribPointer(4, 4, WebGL2.FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, 12 * 4); + } + + private void bindSceneVertexAttribs() { + final int stride = HdSceneUploader.BYTES_PER_VERTEX; + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 3, WebGL2.FLOAT, false, stride, 0); + gl.enableVertexAttribArray(1); + gl.vertexAttribPointer(1, 3, WebGL2.FLOAT, false, stride, 3 * 4); + gl.enableVertexAttribArray(2); + gl.vertexAttribPointer(2, 2, WebGL2.FLOAT, false, stride, 6 * 4); + gl.enableVertexAttribArray(3); + gl.vertexAttribPointer(3, 4, WebGL2.FLOAT, false, stride, 8 * 4); + gl.enableVertexAttribArray(4); + gl.vertexAttribPointer(4, 4, WebGL2.FLOAT, false, stride, 12 * 4); + } + + private void unbindSceneVertexAttribs() { + for (int i = 0; i < 5; i++) { + gl.disableVertexAttribArray(i); + } + } + + private void initMaterials() { + final int size = HdMaterial.TEX_SIZE; + final int layers = HdMaterial.LAYER_COUNT; + final int totalBytes = layers * size * size * 4; + + ByteBuffer diffuseBuf = ByteBuffer.allocate(totalBytes).order(ByteOrder.nativeOrder()); + ByteBuffer normalBuf = ByteBuffer.allocate(totalBytes).order(ByteOrder.nativeOrder()); + HdMaterial.populateTextureBuffers(diffuseBuf, normalBuf); + + diffuseArrayTex = uploadTextureArray(diffuseBuf.array(), size, layers); + normalArrayTex = uploadTextureArray(normalBuf.array(), size, layers); + materialsInitialized = true; + } + + private WebGL2.Texture uploadTextureArray(byte[] data, int size, int layers) { + WebGL2.Texture tex = gl.createTexture(); + gl.bindTexture(WebGL2.TEXTURE_2D_ARRAY, tex); + Uint8Array u8 = Uint8Array.create(data.length); + u8.set(data, 0); + gl.texImage3D(WebGL2.TEXTURE_2D_ARRAY, 0, WebGL2.RGBA8, size, size, layers, 0, WebGL2.RGBA, WebGL2.UNSIGNED_BYTE, u8); + gl.generateMipmap(WebGL2.TEXTURE_2D_ARRAY); + gl.texParameteri(WebGL2.TEXTURE_2D_ARRAY, WebGL2.TEXTURE_MIN_FILTER, WebGL2.LINEAR_MIPMAP_LINEAR); + gl.texParameteri(WebGL2.TEXTURE_2D_ARRAY, WebGL2.TEXTURE_MAG_FILTER, WebGL2.LINEAR); + gl.texParameteri(WebGL2.TEXTURE_2D_ARRAY, WebGL2.TEXTURE_WRAP_S, WebGL2.REPEAT); + gl.texParameteri(WebGL2.TEXTURE_2D_ARRAY, WebGL2.TEXTURE_WRAP_T, WebGL2.REPEAT); + gl.bindTexture(WebGL2.TEXTURE_2D_ARRAY, null); + return tex; + } + + private boolean ensureGlContext() { + if (glInitialized) return true; + try { + glCanvas = (HTMLCanvasElement) HTMLDocument.current().getElementById("gl-canvas"); + if (glCanvas == null) { + glFailed = true; + return false; + } + gl = WebGL2.getContext(glCanvas); + if (gl == null) { + glFailed = true; + return false; + } + + shadowProgram = createProgram(HD117Pipeline.SHADOW_VERT, HD117Pipeline.SHADOW_FRAG); + String sceneFragRgba = HD117Pipeline.SCENE_FRAG_DIRECT.replace("col.b, col.g, col.r", "col.r, col.g, col.b"); + sceneProgram = createProgram(HD117Pipeline.SCENE_VERT, sceneFragRgba); + if (shadowProgram == null || sceneProgram == null) { + glFailed = true; + return false; + } + + uShadowLightViewProj = gl.getUniformLocation(shadowProgram, "uLightViewProj"); + uShadowDiffuseArray = gl.getUniformLocation(shadowProgram, "uDiffuseArray"); + + uSceneViewProj = gl.getUniformLocation(sceneProgram, "uViewProj"); + uSceneLightViewProj = gl.getUniformLocation(sceneProgram, "uLightViewProj"); + uSceneDiffuseArray = gl.getUniformLocation(sceneProgram, "uDiffuseArray"); + uSceneNormalArray = gl.getUniformLocation(sceneProgram, "uNormalArray"); + uSceneShadowMap = gl.getUniformLocation(sceneProgram, "uShadowMap"); + uSceneCameraPos = gl.getUniformLocation(sceneProgram, "uCameraPos"); + uSceneSunDir = gl.getUniformLocation(sceneProgram, "uSunDir"); + uSceneSunColor = gl.getUniformLocation(sceneProgram, "uSunColor"); + uSceneAmbientColor = gl.getUniformLocation(sceneProgram, "uAmbientColor"); + uSceneSkyColor = gl.getUniformLocation(sceneProgram, "uSkyColor"); + uSceneFogColor = gl.getUniformLocation(sceneProgram, "uFogColor"); + uSceneFogMin = gl.getUniformLocation(sceneProgram, "uFogMin"); + uSceneFogMax = gl.getUniformLocation(sceneProgram, "uFogMax"); + uSceneTime = gl.getUniformLocation(sceneProgram, "uTime"); + uSceneShadowTexelSize = gl.getUniformLocation(sceneProgram, "uShadowTexelSize"); + uSceneShadowsEnabled = gl.getUniformLocation(sceneProgram, "uShadowsEnabled"); + uSceneShadowSoftPcf = gl.getUniformLocation(sceneProgram, "uShadowSoftPcf"); + uSceneGroundTextures = gl.getUniformLocation(sceneProgram, "uGroundTextures"); + uSceneNormalMapping = gl.getUniformLocation(sceneProgram, "uNormalMapping"); + uSceneWaterShader = gl.getUniformLocation(sceneProgram, "uWaterShader"); + uSceneSaturation = gl.getUniformLocation(sceneProgram, "uSaturation"); + uSceneBrightness = gl.getUniformLocation(sceneProgram, "uBrightness"); + uSceneContrastCurve = gl.getUniformLocation(sceneProgram, "uContrastCurve"); + uSceneLightCount = gl.getUniformLocation(sceneProgram, "uLightCount"); + uSceneLightPosRad = gl.getUniformLocation(sceneProgram, "uLightPosRad"); + uSceneLightColorInt = gl.getUniformLocation(sceneProgram, "uLightColorInt"); + + for (int i = 0; i < 4; i++) { + terrainVbos[i] = gl.createBuffer(); + for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) { + staticOpaqueVbos[i][c] = gl.createBuffer(); + staticTransVbos[i][c] = gl.createBuffer(); + } + } + sceneVbo = gl.createBuffer(); + transVbo = gl.createBuffer(); + + shadowDepthTex = gl.createTexture(); + gl.bindTexture(WebGL2.TEXTURE_2D, shadowDepthTex); + gl.texImage2D(WebGL2.TEXTURE_2D, 0, WebGL2.DEPTH_COMPONENT24, shadowMapSize, shadowMapSize, 0, + WebGL2.DEPTH_COMPONENT, WebGL2.UNSIGNED_INT, null); + gl.texParameteri(WebGL2.TEXTURE_2D, WebGL2.TEXTURE_MIN_FILTER, WebGL2.LINEAR); + gl.texParameteri(WebGL2.TEXTURE_2D, WebGL2.TEXTURE_MAG_FILTER, WebGL2.LINEAR); + gl.texParameteri(WebGL2.TEXTURE_2D, WebGL2.TEXTURE_WRAP_S, WebGL2.CLAMP_TO_EDGE); + gl.texParameteri(WebGL2.TEXTURE_2D, WebGL2.TEXTURE_WRAP_T, WebGL2.CLAMP_TO_EDGE); + gl.texParameteri(WebGL2.TEXTURE_2D, 0x884C /* TEXTURE_COMPARE_MODE */, 0x884E /* COMPARE_REF_TO_TEXTURE */); + gl.texParameteri(WebGL2.TEXTURE_2D, 0x884D /* TEXTURE_COMPARE_FUNC */, WebGL2.LEQUAL); + + shadowFbo = gl.createFramebuffer(); + gl.bindFramebuffer(WebGL2.FRAMEBUFFER, shadowFbo); + gl.framebufferTexture2D(WebGL2.FRAMEBUFFER, WebGL2.DEPTH_ATTACHMENT, WebGL2.TEXTURE_2D, shadowDepthTex, 0); + drawBuffersNone(gl); + gl.bindFramebuffer(WebGL2.FRAMEBUFFER, null); + + glInitialized = true; + return true; + } catch (Throwable t) { + RSApplet.appendLog("[WebHd117Renderer] WebGL2 init failed: " + t); + glFailed = true; + return false; + } + } + + @JSBody(params = {"gl"}, script = "gl.drawBuffers([0]);") + private static native void drawBuffersNone(WebGL2 gl); + + @JSBody(params = {"gl"}, script = "return gl.getError();") + private static native int getGlError(WebGL2 gl); + + private WebGL2.Program createProgram(String vertSrc, String fragSrc) { + WebGL2.Shader vs = compileShader(WebGL2.VERTEX_SHADER, vertSrc); + WebGL2.Shader fs = compileShader(WebGL2.FRAGMENT_SHADER, fragSrc); + if (vs == null || fs == null) return null; + WebGL2.Program prog = gl.createProgram(); + gl.attachShader(prog, vs); + gl.attachShader(prog, fs); + gl.linkProgram(prog); + if (!gl.getProgramParameter(prog, WebGL2.LINK_STATUS)) { + RSApplet.appendLog("[WebHd117Renderer] Link error: " + gl.getProgramInfoLog(prog)); + return null; + } + return prog; + } + + private WebGL2.Shader compileShader(int type, String src) { + if (src != null && src.contains("precision highp float;")) { + src = src.replace("precision highp float;", + "precision highp float;\nprecision highp sampler2DShadow;\nprecision highp sampler2DArray;"); + } + WebGL2.Shader shader = gl.createShader(type); + gl.shaderSource(shader, src); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, WebGL2.COMPILE_STATUS)) { + RSApplet.appendLog("[WebHd117Renderer] Shader error: " + gl.getShaderInfoLog(shader)); + gl.deleteShader(shader); + return null; + } + return shader; + } + + private void computeCameraAndLightMatrices(int width, int height) { + double yawRad = (camYaw & 2047) * (2.0 * Math.PI / 2048.0); + double pitchRad = (camPitch & 2047) * (2.0 * Math.PI / 2048.0); + float sinY = (float) Math.sin(yawRad); + float cosY = (float) Math.cos(yawRad); + float sinP = (float) Math.sin(pitchRad); + float cosP = (float) Math.cos(pitchRad); + + float r0x = cosY, r0y = 0.0f, r0z = sinY; + float r1x = sinP * sinY, r1y = cosP, r1z = -sinP * cosY; + float r2x = -cosP * sinY, r2y = sinP, r2z = cosP * cosY; + + float tx = -(r0x * camX + r0y * camY + r0z * camZ); + float ty = -(r1x * camX + r1y * camY + r1z * camZ); + float tz = -(r2x * camX + r2y * camY + r2z * camZ); + + float cx = Texture.textureInt1; + float cy = Texture.textureInt2; + float fov = 512.0f; + + float sx = (2.0f * fov) / width; + float ox = (2.0f * cx / width) - 1.0f; + float sy = -(2.0f * fov) / height; + float oy = 1.0f - (2.0f * cy / height); + + float near = 50.0f; + float far = Math.max(5400.0f, fogMax + 600.0f); + float sz = (far + near) / (far - near); + float oz = -(2.0f * far * near) / (far - near); + + viewProjMatrix[0] = sx * r0x + ox * r2x; + viewProjMatrix[4] = sx * r0y + ox * r2y; + viewProjMatrix[8] = sx * r0z + ox * r2z; + viewProjMatrix[12] = sx * tx + ox * tz; + + viewProjMatrix[1] = sy * r1x + oy * r2x; + viewProjMatrix[5] = sy * r1y + oy * r2y; + viewProjMatrix[9] = sy * r1z + oy * r2z; + viewProjMatrix[13] = sy * ty + oy * tz; + + viewProjMatrix[2] = sz * r2x; + viewProjMatrix[6] = sz * r2y; + viewProjMatrix[10] = sz * r2z; + viewProjMatrix[14] = sz * tz + oz; + + viewProjMatrix[3] = r2x; + viewProjMatrix[7] = r2y; + viewProjMatrix[11] = r2z; + viewProjMatrix[15] = tz; + + for (int i = 0; i < 16; i++) { + viewProjF32.set(i, viewProjMatrix[i]); + } + + float focusDist = 800.0f + Math.max(0, Game.zoom) * 140.0f; + float centerX = (float) Math.floor((camX + r2x * focusDist) / 16.0f) * 16.0f; + float centerY = (float) Math.floor((camY + r2y * focusDist) / 16.0f) * 16.0f; + float centerZ = (float) Math.floor((camZ + r2z * focusDist) / 16.0f) * 16.0f; + + float eyeX = centerX + sunDir[0] * 3600.0f; + float eyeY = centerY + sunDir[1] * 3600.0f; + float eyeZ = centerZ + sunDir[2] * 3600.0f; + + setLookAtM(lightViewMatrix, eyeX, eyeY, eyeZ, centerX, centerY, centerZ, 0.0f, -1.0f, 0.0f); + float orthoHalf = 2600.0f + Math.max(0, Game.zoom) * 180.0f; + orthoM(lightProjMatrix, -orthoHalf, orthoHalf, -orthoHalf, orthoHalf, 100.0f, 7200.0f); + multiplyMM(lightViewProjMatrix, lightProjMatrix, lightViewMatrix); + for (int i = 0; i < 16; i++) { + lightViewProjF32.set(i, lightViewProjMatrix[i]); + } + } + + private void selectActiveLights() { + activeLightCount = 0; + if (!HD117Pipeline.cfgDynamicLights) return; + int total = procGen.sceneLightCount; + if (total <= 0) return; + + float timeSec = (System.currentTimeMillis() - startTimeMs) * 0.001f; + float flicker = 0.94f + 0.06f * (float) Math.sin(timeSec * 9.0); + for (int i = 0; i < total && activeLightCount < MAX_ACTIVE_LIGHTS; i++) { + int src = i * 4; + float lx = procGen.sceneLightPosRad[src]; + float ly = procGen.sceneLightPosRad[src + 1]; + float lz = procGen.sceneLightPosRad[src + 2]; + float dx = lx - camX; + float dz = lz - camZ; + if (dx * dx + dz * dz < 3200.0f * 3200.0f) { + int dst = activeLightCount * 4; + activeLightPosRad.set(dst, lx); + activeLightPosRad.set(dst + 1, ly); + activeLightPosRad.set(dst + 2, lz); + activeLightPosRad.set(dst + 3, procGen.sceneLightPosRad[src + 3]); + + activeLightColorInt.set(dst, procGen.sceneLightColorInt[src]); + activeLightColorInt.set(dst + 1, procGen.sceneLightColorInt[src + 1]); + activeLightColorInt.set(dst + 2, procGen.sceneLightColorInt[src + 2]); + activeLightColorInt.set(dst + 3, procGen.sceneLightColorInt[src + 3] * flicker); + activeLightCount++; + } + } + } + + private void updateEnvironmentProfile(Game game) { + float pX = 52.0f * 128.0f; + float pZ = 52.0f * 128.0f; + if (game != null && game.myPlayer != null) { + pX = game.myPlayer.x; + pZ = game.myPlayer.y; + } + float camDistToPlayer = (float) Math.hypot(camX - pX, camZ - pZ); + float baseDist = WorldController.drawDistance * 144.0f; + fogMax = Math.max(4800.0f, baseDist + camDistToPlayer + Math.max(0, Game.zoom) * 200.0f); + fogMin = fogMax * 0.75f; + + int worldX = 3222; + int worldY = 3218; + if (game != null && game.myPlayer != null) { + worldX = game.baseX + game.myPlayer.smallX[0]; + worldY = game.baseY + game.myPlayer.smallY[0]; + } + + if (worldY >= 6000) { + if ((worldX >= 2360 && worldX <= 2500 && worldY >= 5000 && worldY <= 5200) + || (worldX >= 2800 && worldX <= 2900 && worldY >= 9500)) { + setColors(1.10f, 0.55f, 0.28f, 0.52f, 0.24f, 0.16f, 0.34f, 0.12f, 0.06f); + fogMin = fogMax * 0.55f; + } else { + setColors(0.75f, 0.74f, 0.72f, 0.38f, 0.42f, 0.50f, 0.10f, 0.12f, 0.16f); + fogMin = fogMax * 0.60f; + } + } else if (worldY >= 3520 && worldY <= 4000) { + setColors(0.82f, 0.74f, 0.68f, 0.44f, 0.40f, 0.42f, 0.25f, 0.20f, 0.20f); + } else if (worldX >= 3400 && worldX <= 3600 && worldY >= 3150 && worldY <= 3550) { + setColors(0.78f, 0.84f, 0.72f, 0.38f, 0.48f, 0.42f, 0.22f, 0.28f, 0.23f); + } else { + setColors(1.12f, 1.01f, 0.86f, 0.48f, 0.57f, 0.70f, 0.66f, 0.79f, 0.92f); + } + } + + private void setColors(float sr, float sg, float sb, float ar, float ag, float ab, float fr, float fg, float fb) { + sunColor[0] = sr; sunColor[1] = sg; sunColor[2] = sb; + ambientColor[0] = ar; ambientColor[1] = ag; ambientColor[2] = ab; + fogColor[0] = fr; fogColor[1] = fg; fogColor[2] = fb; + skyColor[0] = fr; skyColor[1] = fg; skyColor[2] = fb; + } + + private static void setLookAtM(float[] rm, float eyeX, float eyeY, float eyeZ, + float centerX, float centerY, float centerZ, + float upX, float upY, float upZ) { + float fx = centerX - eyeX, fy = centerY - eyeY, fz = centerZ - eyeZ; + float rlf = 1.0f / (float) Math.sqrt(fx * fx + fy * fy + fz * fz); + fx *= rlf; fy *= rlf; fz *= rlf; + float sx = fy * upZ - fz * upY; + float sy = fz * upX - fx * upZ; + float sz = fx * upY - fy * upX; + float rls = 1.0f / (float) Math.sqrt(sx * sx + sy * sy + sz * sz); + sx *= rls; sy *= rls; sz *= rls; + float ux = sy * fz - sz * fy; + float uy = sz * fx - sx * fz; + float uz = sx * fy - sy * fx; + rm[0] = sx; rm[4] = sy; rm[8] = sz; rm[12] = -(sx * eyeX + sy * eyeY + sz * eyeZ); + rm[1] = ux; rm[5] = uy; rm[9] = uz; rm[13] = -(ux * eyeX + uy * eyeY + uz * eyeZ); + rm[2] = -fx; rm[6] = -fy; rm[10] = -fz; rm[14] = (fx * eyeX + fy * eyeY + fz * eyeZ); + rm[3] = 0; rm[7] = 0; rm[11] = 0; rm[15] = 1.0f; + } + + private static void orthoM(float[] m, float left, float right, float bottom, float top, float near, float far) { + float r_w = 1.0f / (right - left); + float r_h = 1.0f / (top - bottom); + float r_d = 1.0f / (far - near); + for (int i = 0; i < 16; i++) m[i] = 0.0f; + m[0] = 2.0f * r_w; + m[5] = 2.0f * r_h; + m[10] = -2.0f * r_d; + m[12] = -(right + left) * r_w; + m[13] = -(top + bottom) * r_h; + m[14] = -(far + near) * r_d; + m[15] = 1.0f; + } + + private static void multiplyMM(float[] result, float[] lhs, float[] rhs) { + for (int col = 0; col < 4; col++) { + for (int row = 0; row < 4; row++) { + float sum = 0.0f; + for (int k = 0; k < 4; k++) { + sum += lhs[k * 4 + row] * rhs[col * 4 + k]; + } + result[col * 4 + row] = sum; + } + } + } + + @org.teavm.jso.JSBody(params = {"gl"}, script = "return gl ? (gl.drawingBufferWidth | 0) : 0;") + private static native int jsGetDrawingBufferWidth(WebGL2 gl); + + @org.teavm.jso.JSBody(params = {"gl"}, script = "return gl ? (gl.drawingBufferHeight | 0) : 0;") + private static native int jsGetDrawingBufferHeight(WebGL2 gl); +} diff --git a/src/main/java/org/scape2006/web/WebLauncher.java b/src/main/java/org/scape2006/web/WebLauncher.java new file mode 100644 index 0000000..ed1d5f2 --- /dev/null +++ b/src/main/java/org/scape2006/web/WebLauncher.java @@ -0,0 +1,159 @@ +package org.scape2006.web; + +import org.teavm.jso.JSBody; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; +import org.teavm.jso.typedarrays.Uint8Array; + +/** + * TeaVM browser entrypoint for 2006Scape-Web. + * Preloads the 377 cache via IndexedDB / HTTP fetch, initializes 117HD WebGL2, and boots Game. + */ +public final class WebLauncher { + + public static int overrideWsPort = -1; + private static volatile boolean cacheReady = false; + + @JSFunctor + public interface CacheCallback extends JSObject { + void onComplete(Uint8Array dat, Uint8Array idx0, Uint8Array idx1, Uint8Array idx2, Uint8Array idx3, Uint8Array idx4); + } + + public static void main(String[] args) { + String worldParam = DesktopHooks.getParameter("world"); + String optWorld = getSavedOption("world"); + if (!worldParam.isEmpty()) { + try { + ClientSettings.SERVER_WORLD = Integer.parseInt(worldParam); + } catch (NumberFormatException ignored) {} + } else if (!optWorld.isEmpty()) { + try { + ClientSettings.SERVER_WORLD = Integer.parseInt(optWorld); + } catch (NumberFormatException ignored) {} + } + String serverParam = DesktopHooks.getParameter("server"); + String optServer = getSavedOption("server"); + if (!serverParam.isEmpty()) { + ClientSettings.SERVER_IP = serverParam; + } else if (!optServer.isEmpty()) { + ClientSettings.SERVER_IP = optServer; + } else { + ClientSettings.SERVER_IP = "192.168.1.88"; + } + String wsPortParam = DesktopHooks.getParameter("wsPort"); + if (!wsPortParam.isEmpty()) { + try { + overrideWsPort = Integer.parseInt(wsPortParam); + } catch (NumberFormatException ignored) {} + } + String hdParam = DesktopHooks.getParameter("hd"); + String optHd = getSavedOption("hd"); + if ("true".equalsIgnoreCase(hdParam) || "1".equals(hdParam)) { + ClientSettings.HD_117 = true; + } else if ("false".equalsIgnoreCase(hdParam) || "0".equals(hdParam)) { + ClientSettings.HD_117 = false; + } else if ("true".equalsIgnoreCase(optHd)) { + ClientSettings.HD_117 = true; + } + String resizeParam = DesktopHooks.getParameter("resize"); + String optMode = getSavedOption("displayMode"); + if (!resizeParam.isEmpty()) { + ClientSettings.RESIZABLE = "true".equalsIgnoreCase(resizeParam) || "1".equals(resizeParam); + } else if ("1".equals(optMode) || "2".equals(optMode)) { + ClientSettings.RESIZABLE = true; + } else { + ClientSettings.RESIZABLE = false; + } + String navbarParam = DesktopHooks.getParameter("navbar"); + String optNavbar = getSavedOption("navbar"); + if ("false".equalsIgnoreCase(navbarParam) || "0".equals(navbarParam)) { + ClientSettings.SHOW_NAVBAR = false; + } else if ("true".equalsIgnoreCase(navbarParam) || "1".equals(navbarParam)) { + ClientSettings.SHOW_NAVBAR = true; + } else if ("false".equalsIgnoreCase(optNavbar)) { + ClientSettings.SHOW_NAVBAR = false; + } else if ("true".equalsIgnoreCase(optNavbar)) { + ClientSettings.SHOW_NAVBAR = true; + } + initNavbar(ClientSettings.SHOW_NAVBAR, ClientSettings.NAV_MAINMENU_LINK, ClientSettings.NAV_WORLDMAP_LINK, ClientSettings.NAV_MANUAL_LINK, ClientSettings.NAV_RULES_LINK); + + // Keep desktop/mouse layout in browser; Signlink.mainapp non-null routes sockets via Signlink.opensocket() + ClientSettings.ANDROID = false; + Signlink.mainapp = new Object(); + HD117Pipeline.useStaticScenery = true; + DesktopHooks.initHdBackend(); + + RSApplet.updateLoadingOverlay(10, "Loading 377 cache from IndexedDB / HTTP..."); + preloadCache((dat, idx0, idx1, idx2, idx3, idx4) -> { + if (dat != null && dat.getLength() > 0) { + Signlink.cache_dat = new VirtualFile(toByteArray(dat)); + } + Uint8Array[] idxs = {idx0, idx1, idx2, idx3, idx4}; + for (int i = 0; i < 5; i++) { + if (idxs[i] != null && idxs[i].getLength() > 0) { + Signlink.cache_idx[i] = new VirtualFile(toByteArray(idxs[i])); + } + } + cacheReady = true; + }); + + // Wait for async cache preload inside TeaVM's coroutine thread before launching Game + Thread bootThread = new Thread(() -> { + while (!cacheReady) { + try { + Thread.sleep(25L); + } catch (InterruptedException ignored) {} + } + RSApplet.updateLoadingOverlay(100, "Starting 2006Scape..."); + setStatusBadge("WS Port " + (overrideWsPort > 0 ? overrideWsPort : (ClientSettings.SERVER_WORLD == 1 ? 44594 : 44596 + ClientSettings.SERVER_WORLD))); + Game game = new Game(); + Game.server = ClientSettings.SERVER_IP; + if ("true".equalsIgnoreCase(getSavedOption("autoLogin"))) { + String u = getSavedOption("username"); + String p = getSavedOption("password"); + if (!u.isEmpty()) { + game.myUsername = u; + game.myPassword = p; + } + } + Game.nodeID = 10; + Game.portOff = 0; + Game.setHighMem(); + Game.isMembers = true; + Signlink.storeid = 32; + game.createClientFrame(503, 765); + }, "WebBootThread"); + bootThread.start(); + } + + private static byte[] toByteArray(Uint8Array arr) { + int len = arr.getLength(); + byte[] out = new byte[len]; + for (int i = 0; i < len; i++) { + out[i] = (byte) arr.get(i); + } + return out; + } + + @JSBody(params = {"text"}, script = + "var el = document.getElementById('status-badge');\n" + + "if (el) el.textContent = text;") + private static native void setStatusBadge(String text); + + @JSBody(params = {"cb"}, script = "window.scapePreloadCache(cb);") + private static native void preloadCache(CacheCallback cb); + + @JSBody(params = {"visible", "mainMenuUrl", "worldMapUrl", "manualUrl", "rulesUrl"}, script = + "if (window.scapeInitNavbar) window.scapeInitNavbar(visible, mainMenuUrl, worldMapUrl, manualUrl, rulesUrl);") + private static native void initNavbar(boolean visible, String mainMenuUrl, String worldMapUrl, String manualUrl, String rulesUrl); + + @JSBody(params = {"key"}, script = + "try {\n" + + " var raw = window.localStorage ? window.localStorage.getItem('2006scape_web_options') : null;\n" + + " if (!raw) return '';\n" + + " var obj = JSON.parse(raw);\n" + + " var v = obj ? obj[key] : '';\n" + + " return (v === undefined || v === null) ? '' : String(v);\n" + + "} catch (_) { return ''; }") + private static native String getSavedOption(String key); +} diff --git a/src/main/java/org/scape2006/web/WebReflectionSupplier.java b/src/main/java/org/scape2006/web/WebReflectionSupplier.java new file mode 100644 index 0000000..41e56f3 --- /dev/null +++ b/src/main/java/org/scape2006/web/WebReflectionSupplier.java @@ -0,0 +1,130 @@ +package org.scape2006.web; + +import org.teavm.classlib.ReflectionContext; +import org.teavm.classlib.ReflectionSupplier; +import org.teavm.model.ClassReader; +import org.teavm.model.FieldReader; +import org.teavm.model.MethodDescriptor; +import org.teavm.model.MethodReader; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * TeaVM ReflectionSupplier ensuring ScriptInterpreter can reflectively invoke + * PluginContext, PluginGraphics, ClientScript, and game entity APIs at runtime. + */ +public final class WebReflectionSupplier implements ReflectionSupplier { + + private static final Set SCRIPTABLE_CLASSES = new HashSet<>(); + + static { + String p = "org.scape2006.web."; + SCRIPTABLE_CLASSES.add(p + "PluginContext"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$WorldArea"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$NpcWrapper"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$PlayerWrapper"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$GroundItemWrapper"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$SceneObjectWrapper"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$InventoryItemWrapper"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$Prayer"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$Spell"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$Query"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$NpcQuery"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$GroundItemQuery"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$ObjectQuery"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$InventoryQuery"); + SCRIPTABLE_CLASSES.add(p + "PluginContext$PlayerQuery"); + SCRIPTABLE_CLASSES.add(p + "PluginGraphics"); + SCRIPTABLE_CLASSES.add(p + "PluginConfigItem"); + SCRIPTABLE_CLASSES.add(p + "ClientScript"); + SCRIPTABLE_CLASSES.add(p + "ClientPlugin"); + SCRIPTABLE_CLASSES.add(p + "ClientSettings"); + SCRIPTABLE_CLASSES.add(p + "ScriptLogger"); + SCRIPTABLE_CLASSES.add(p + "Game"); + SCRIPTABLE_CLASSES.add(p + "Player"); + SCRIPTABLE_CLASSES.add(p + "NPC"); + SCRIPTABLE_CLASSES.add(p + "Item"); + SCRIPTABLE_CLASSES.add(p + "ItemDef"); + SCRIPTABLE_CLASSES.add(p + "EntityDef"); + SCRIPTABLE_CLASSES.add(p + "ObjectDef"); + SCRIPTABLE_CLASSES.add(p + "Skills"); + SCRIPTABLE_CLASSES.add(p + "RSInterface"); + SCRIPTABLE_CLASSES.add(p + "RSColors"); + SCRIPTABLE_CLASSES.add(p + "ItemID"); + SCRIPTABLE_CLASSES.add(p + "StaticItemList"); + SCRIPTABLE_CLASSES.add(p + "SkillID"); + SCRIPTABLE_CLASSES.add(p + "NpcID"); + SCRIPTABLE_CLASSES.add(p + "StaticNpcList"); + SCRIPTABLE_CLASSES.add(p + "ObjectID"); + SCRIPTABLE_CLASSES.add(p + "StaticObjectList"); + SCRIPTABLE_CLASSES.add(p + "ScriptInterpreter"); + SCRIPTABLE_CLASSES.add(p + "ScriptInterpreter$Environment"); + SCRIPTABLE_CLASSES.add(p + "ScriptInterpreter$InterpretedScript"); + SCRIPTABLE_CLASSES.add(p + "ScriptInterpreter$InterpretedPlugin"); + } + + @Override + public Collection getAccessibleFields(ReflectionContext context, String className) { + if (!SCRIPTABLE_CLASSES.contains(className)) { + return Collections.emptyList(); + } + ClassReader cls = context.getClassSource().get(className); + if (cls == null) { + return Collections.emptyList(); + } + List fields = new ArrayList<>(); + for (FieldReader f : cls.getFields()) { + fields.add(f.getName()); + } + return fields; + } + + @Override + public Collection getAccessibleMethods(ReflectionContext context, String className) { + boolean isLangMath = "java.lang.Math".equals(className); + boolean isLangSys = "java.lang.System".equals(className); + boolean isLangStr = "java.lang.String".equals(className); + boolean isUtilColl = "java.util.List".equals(className) || "java.util.ArrayList".equals(className) + || "java.util.Collection".equals(className) || "java.util.Map".equals(className) + || "java.util.HashMap".equals(className) + || "java.util.Collections$EmptyList".equals(className) + || "java.util.Collections$SingletonList".equals(className) + || "java.util.Arrays$ArrayList".equals(className); + if (!SCRIPTABLE_CLASSES.contains(className) && !isLangMath && !isLangSys && !isLangStr && !isUtilColl) { + return Collections.emptyList(); + } + ClassReader cls = context.getClassSource().get(className); + if (cls == null) { + return Collections.emptyList(); + } + List methods = new ArrayList<>(); + for (MethodReader m : cls.getMethods()) { + String name = m.getName(); + if (isLangSys) { + if (!"currentTimeMillis".equals(name) && !"nanoTime".equals(name)) continue; + } else if (isLangMath) { + if (!"max".equals(name) && !"min".equals(name) && !"abs".equals(name) + && !"round".equals(name) && !"floor".equals(name) && !"ceil".equals(name) + && !"sqrt".equals(name) && !"pow".equals(name) && !"hypot".equals(name) + && !"random".equals(name)) continue; + } else if (isLangStr) { + if (!"length".equals(name) && !"equals".equals(name) && !"equalsIgnoreCase".equals(name) + && !"contains".equals(name) && !"startsWith".equals(name) && !"endsWith".equals(name) + && !"toLowerCase".equals(name) && !"toUpperCase".equals(name) && !"trim".equals(name) + && !"substring".equals(name) && !"indexOf".equals(name) && !"replace".equals(name) + && !"isEmpty".equals(name) && !"valueOf".equals(name)) continue; + } else if (isUtilColl) { + if (!"size".equals(name) && !"isEmpty".equals(name) && !"get".equals(name) + && !"add".equals(name) && !"remove".equals(name) && !"clear".equals(name) + && !"contains".equals(name) && !"containsKey".equals(name) && !"put".equals(name)) continue; + } + methods.add(m.getDescriptor()); + } + return methods; + } +} diff --git a/src/main/java/org/scape2006/web/WebSocketAdapter.java b/src/main/java/org/scape2006/web/WebSocketAdapter.java new file mode 100644 index 0000000..f6daff6 --- /dev/null +++ b/src/main/java/org/scape2006/web/WebSocketAdapter.java @@ -0,0 +1,208 @@ +package org.scape2006.web; + +import org.teavm.jso.JSBody; +import org.teavm.jso.JSObject; +import org.teavm.jso.dom.events.Event; +import org.teavm.jso.dom.events.EventListener; +import org.teavm.jso.dom.events.MessageEvent; +import org.teavm.jso.typedarrays.ArrayBuffer; +import org.teavm.jso.typedarrays.Uint8Array; +import org.teavm.jso.websocket.WebSocket; + +import org.scape2006.web.net.Socket; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * Browser WebSocket-backed java.net.Socket adapter for TeaVM. + * Translates raw TCP stream reads/writes into binary WebSocket frames. + */ +public final class WebSocketAdapter extends Socket { + + private static final int BUFFER_CAPACITY = 262144; // 256 KB ring buffer + + private final WebSocket ws; + private final byte[] rxBuffer = new byte[BUFFER_CAPACITY]; + private int rxHead = 0; + private int rxTail = 0; + private int rxCount = 0; + + private volatile boolean open = false; + private volatile boolean closed = false; + private volatile String errorMsg = null; + + private final InputStream inputStream = new WsInputStream(); + private final OutputStream outputStream = new WsOutputStream(); + + public WebSocketAdapter(String url) { + this.ws = WebSocket.create(url); + this.ws.setBinaryType("arraybuffer"); + + this.ws.onOpen(evt -> open = true); + this.ws.onClose(evt -> { + open = false; + closed = true; + }); + this.ws.onError(evt -> { + errorMsg = "WebSocket error on " + url; + closed = true; + }); + this.ws.onMessage((MessageEvent evt) -> { + JSObject data = evt.getData(); + if (data != null) { + ArrayBuffer buf = (ArrayBuffer) data; + Uint8Array arr = Uint8Array.create(buf); + int len = arr.getLength(); + synchronized (rxBuffer) { + for (int i = 0; i < len; i++) { + if (rxCount >= BUFFER_CAPACITY) { + // Drop oldest byte on overflow to prevent lockup + rxHead = (rxHead + 1) % BUFFER_CAPACITY; + rxCount--; + } + rxBuffer[rxTail] = (byte) arr.get(i); + rxTail = (rxTail + 1) % BUFFER_CAPACITY; + rxCount++; + } + } + } + }); + } + + public boolean isConnected() { + return open && !closed; + } + + @Override + public InputStream getInputStream() { + return inputStream; + } + + @Override + public OutputStream getOutputStream() { + return outputStream; + } + + @Override + public void setSoTimeout(int timeout) { + // Handled non-blocking via WebSocket events + } + + @Override + public void setTcpNoDelay(boolean on) { + // No-op for WebSocket + } + + @Override + public void close() { + closed = true; + open = false; + try { + ws.close(); + } catch (Throwable ignored) { + } + } + + @JSBody(params = {"ws", "arr"}, script = "ws.send(arr);") + private static native void sendBytes(WebSocket ws, Uint8Array arr); + + private void waitForOpen() throws IOException { + long deadline = System.currentTimeMillis() + 10000L; + while (!open && !closed) { + if (System.currentTimeMillis() > deadline) { + closed = true; + throw new IOException("WebSocket connection timed out"); + } + try { + Thread.sleep(10L); + } catch (InterruptedException e) { + throw new IOException("Interrupted while connecting"); + } + } + if (closed) { + throw new IOException(errorMsg != null ? errorMsg : "WebSocket closed"); + } + } + + private final class WsInputStream extends InputStream { + @Override + public int available() { + synchronized (rxBuffer) { + return rxCount; + } + } + + @Override + public int read() throws IOException { + while (true) { + synchronized (rxBuffer) { + if (rxCount > 0) { + int b = rxBuffer[rxHead] & 0xFF; + rxHead = (rxHead + 1) % BUFFER_CAPACITY; + rxCount--; + return b; + } + } + if (closed) { + return -1; + } + try { + Thread.sleep(2L); + } catch (InterruptedException e) { + throw new IOException("Interrupted"); + } + } + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (len <= 0) return 0; + while (true) { + synchronized (rxBuffer) { + if (rxCount > 0) { + int toRead = Math.min(len, rxCount); + for (int i = 0; i < toRead; i++) { + b[off + i] = rxBuffer[rxHead]; + rxHead = (rxHead + 1) % BUFFER_CAPACITY; + rxCount--; + } + return toRead; + } + } + if (closed) { + return -1; + } + try { + Thread.sleep(2L); + } catch (InterruptedException e) { + throw new IOException("Interrupted"); + } + } + } + } + + private final class WsOutputStream extends OutputStream { + @Override + public void write(int b) throws IOException { + write(new byte[]{(byte) b}, 0, 1); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (len <= 0) return; + if (!open) { + waitForOpen(); + } + if (closed) { + throw new IOException("WebSocket is closed"); + } + Uint8Array arr = Uint8Array.create(len); + for (int i = 0; i < len; i++) { + arr.set(i, (short) (b[off + i] & 0xFF)); + } + sendBytes(ws, arr); + } + } +} diff --git a/src/main/java/org/scape2006/web/net/InetAddress.java b/src/main/java/org/scape2006/web/net/InetAddress.java new file mode 100644 index 0000000..4f15211 --- /dev/null +++ b/src/main/java/org/scape2006/web/net/InetAddress.java @@ -0,0 +1,27 @@ +package org.scape2006.web.net; + +import java.net.UnknownHostException; + +/** + * TeaVM-compatible InetAddress stub replacing java.net.InetAddress. + */ +public final class InetAddress { + + private final String host; + + private InetAddress(String host) { + this.host = host; + } + + public static InetAddress getByName(String host) throws UnknownHostException { + return new InetAddress(host != null ? host : "127.0.0.1"); + } + + public static InetAddress getLocalHost() throws UnknownHostException { + return new InetAddress("127.0.0.1"); + } + + public String getHostName() { + return host; + } +} diff --git a/src/main/java/org/scape2006/web/net/InetSocketAddress.java b/src/main/java/org/scape2006/web/net/InetSocketAddress.java new file mode 100644 index 0000000..b2a9563 --- /dev/null +++ b/src/main/java/org/scape2006/web/net/InetSocketAddress.java @@ -0,0 +1,23 @@ +package org.scape2006.web.net; + +/** + * TeaVM-compatible InetSocketAddress stub replacing java.net.InetSocketAddress. + */ +public final class InetSocketAddress { + + private final InetAddress addr; + private final int port; + + public InetSocketAddress(InetAddress addr, int port) { + this.addr = addr; + this.port = port; + } + + public InetAddress getAddress() { + return addr; + } + + public int getPort() { + return port; + } +} diff --git a/src/main/java/org/scape2006/web/net/Socket.java b/src/main/java/org/scape2006/web/net/Socket.java new file mode 100644 index 0000000..8fa91cc --- /dev/null +++ b/src/main/java/org/scape2006/web/net/Socket.java @@ -0,0 +1,31 @@ +package org.scape2006.web.net; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * TeaVM-compatible Socket base class replacing java.net.Socket. + */ +public class Socket { + + public Socket() {} + + public Socket(InetAddress address, int port) throws IOException {} + + public void connect(InetSocketAddress endpoint, int timeout) throws IOException {} + + public InputStream getInputStream() throws IOException { + return null; + } + + public OutputStream getOutputStream() throws IOException { + return null; + } + + public void setSoTimeout(int timeout) throws IOException {} + + public void setTcpNoDelay(boolean on) throws IOException {} + + public void close() throws IOException {} +} diff --git a/src/main/resources/META-INF/services/org.teavm.classlib.ReflectionSupplier b/src/main/resources/META-INF/services/org.teavm.classlib.ReflectionSupplier new file mode 100644 index 0000000..b54350f --- /dev/null +++ b/src/main/resources/META-INF/services/org.teavm.classlib.ReflectionSupplier @@ -0,0 +1 @@ +org.scape2006.web.WebReflectionSupplier diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html new file mode 100644 index 0000000..13bde53 --- /dev/null +++ b/src/main/webapp/index.html @@ -0,0 +1,685 @@ + + + + + + RuneScape - Free Multiplayer Online Game + + + + +
+
+ +
+ + +
+ +
+
+
2006Scape Web Client
+
+
Initializing TeaVM runtime...
+
+
+ + +
+
+
+ Client Options + +
+
+
+
Auto-Login
+ + + +
+
+
Server & World
+ + +
+
+
Display & Graphics
+ + + +
+
+ +
+
+ + + + + +