first commit

This commit is contained in:
2026-09-09 03:08:43 -05:00
commit 0c3c1ffb56
378 changed files with 84045 additions and 0 deletions
+210
View File
@@ -0,0 +1,210 @@
buildscript {
repositories {
gradlePluginPortal()
}
dependencies {
classpath "io.github.fourlastor:construo:2.1.0"
if(enableGraalNative == 'true') {
classpath "org.graalvm.buildtools.native:org.graalvm.buildtools.native.gradle.plugin:0.9.28"
}
}
}
plugins {
id "application"
}
apply plugin: 'io.github.fourlastor.construo'
apply plugin: 'org.jetbrains.kotlin.jvm'
import io.github.fourlastor.construo.Target
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
sourceSets.main.resources.srcDirs += [ rootProject.file('assets').path ]
application.mainClass = 'own.planetslivewallpaper.lwjgl3.Lwjgl3Launcher'
application.applicationName = appName
eclipse.project.name = appName + '-lwjgl3'
java.sourceCompatibility = 21
java.targetCompatibility = 21
if (JavaVersion.current().isJava9Compatible()) {
compileJava.options.release.set(21)
}
kotlin.compilerOptions.jvmTarget.set(JvmTarget.JVM_21)
dependencies {
implementation "com.badlogicgames.gdx:gdx-backend-lwjgl3:$gdxVersion"
implementation "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
implementation project(':core')
if(enableGraalNative == 'true') {
implementation "io.github.berstanio:gdx-svmhelper-backend-lwjgl3:$graalHelperVersion"
}
// Forces LWJGL3 to use at least $lwjgl3Version, currently 3.4.3, to avoid warnings on Java 25 and up.
constraints{
implementation("org.lwjgl:lwjgl:$lwjgl3Version")
implementation("org.lwjgl:lwjgl-glfw:$lwjgl3Version")
implementation("org.lwjgl:lwjgl-jemalloc:$lwjgl3Version")
implementation("org.lwjgl:lwjgl-openal:$lwjgl3Version")
implementation("org.lwjgl:lwjgl-opengl:$lwjgl3Version")
implementation("org.lwjgl:lwjgl-stb:$lwjgl3Version")
}
}
def os = System.properties['os.name'].toLowerCase(Locale.ROOT)
run {
workingDir = rootProject.file('assets').path
// You can uncomment the next line if your IDE claims a build failure even when the app closed properly.
//setIgnoreExitValue(true)
jvmArgs += "--enable-native-access=ALL-UNNAMED"
if (os.contains('mac')) jvmArgs += "-XstartOnFirstThread"
}
jar {
// sets the name of the .jar file this produces to the name of the game or app, with the version after.
archiveFileName.set("${appName}-${projectVersion}.jar")
// the duplicatesStrategy matters starting in Gradle 7.0; this setting works.
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
dependsOn configurations.runtimeClasspath
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
// these "exclude" lines remove some unnecessary duplicate files in the output JAR.
exclude('META-INF/INDEX.LIST', 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA')
dependencies {
exclude('META-INF/INDEX.LIST', 'META-INF/maven/**')
}
// setting the manifest makes the JAR runnable.
// enabling native access helps avoid a warning when Java 24 or later runs the JAR.
// setting Multi-Release to true allows LWJGL3 to use different classes on recent Java versions.
manifest {
attributes 'Main-Class': application.mainClass, 'Enable-Native-Access': 'ALL-UNNAMED', 'Multi-Release': 'true'
}
// this last step may help on some OSes that need extra instruction to make runnable JARs.
doLast {
file(archiveFile).setExecutable(true, false)
}
}
// Builds a JAR that only includes the files needed to run on macOS, not Windows or Linux.
// The file size for a Mac-only JAR is about 7MB smaller than a cross-platform JAR.
tasks.register("jarMac") {
dependsOn("jar")
group("build")
jar.archiveFileName.set("${appName}-${projectVersion}-mac.jar")
jar.exclude("windows/x86/**", "windows/x64/**", "linux/arm32/**", "linux/arm64/**", "linux/x64/**", "**/*.dll", "**/*.so",
'META-INF/INDEX.LIST', 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA')
dependencies {
jar.exclude("windows/x86/**", "windows/x64/**", "linux/arm32/**", "linux/arm64/**", "linux/x64/**",
'META-INF/INDEX.LIST', 'META-INF/maven/**')
}
}
// Builds a JAR that only includes the files needed to run on Linux, not Windows or macOS.
// The file size for a Linux-only JAR is about 5MB smaller than a cross-platform JAR.
tasks.register("jarLinux") {
dependsOn("jar")
group("build")
jar.archiveFileName.set("${appName}-${projectVersion}-linux.jar")
jar.exclude("windows/x86/**", "windows/x64/**", "macos/arm64/**", "macos/x64/**", "**/*.dll", "**/*.dylib",
'META-INF/INDEX.LIST', 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA')
dependencies {
jar.exclude("windows/x86/**", "windows/x64/**", "macos/arm64/**", "macos/x64/**",
'META-INF/INDEX.LIST', 'META-INF/maven/**')
}
}
// Builds a JAR that only includes the files needed to run on Windows, not Linux or macOS.
// The file size for a Windows-only JAR is about 6MB smaller than a cross-platform JAR.
tasks.register("jarWin") {
dependsOn("jar")
group("build")
jar.archiveFileName.set("${appName}-${projectVersion}-win.jar")
jar.exclude("macos/arm64/**", "macos/x64/**", "linux/arm32/**", "linux/arm64/**", "linux/x64/**", "**/*.dylib", "**/*.so",
'META-INF/INDEX.LIST', 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA')
dependencies {
jar.exclude("macos/arm64/**", "macos/x64/**", "linux/arm32/**", "linux/arm64/**", "linux/x64/**",
'META-INF/INDEX.LIST', 'META-INF/maven/**')
}
}
construo {
// name of the executable
name.set(appName)
// human-readable name, used for example in the `.app` name for macOS
humanName.set(appName)
jlink {
guessModulesFromJar.set(false)
// You may need to add more modules, as needed.
modules.addAll("java.base", "java.management", "java.desktop", "jdk.unsupported")
}
targets.configure {
register("linuxX64", Target.Linux) {
architecture.set(Target.Architecture.X86_64)
jdkUrl.set("https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.10%2B7/OpenJDK21U-jdk_x64_linux_hotspot_21.0.10_7.tar.gz")
// Linux does not currently have a way to set the icon on the executable
}
register("macM1", Target.MacOs) {
architecture.set(Target.Architecture.AARCH64)
jdkUrl.set("https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.10%2B7/OpenJDK21U-jdk_aarch64_mac_hotspot_21.0.10_7.tar.gz")
// macOS needs an identifier
identifier.set("own.planetslivewallpaper." + appName)
// Optional: icon for macOS, as an ICNS file
macIcon.set(project.file("icons/logo.icns"))
}
register("macX64", Target.MacOs) {
architecture.set(Target.Architecture.X86_64)
jdkUrl.set("https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.10%2B7/OpenJDK21U-jdk_x64_mac_hotspot_21.0.10_7.tar.gz")
// macOS needs an identifier
identifier.set("own.planetslivewallpaper." + appName)
// Optional: icon for macOS, as an ICNS file
macIcon.set(project.file("icons/logo.icns"))
}
register("winX64", Target.Windows) {
architecture.set(Target.Architecture.X86_64)
// Optional: icon for Windows, as a PNG
icon.set(project.file("icons/logo.png"))
jdkUrl.set("https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.10%2B7/OpenJDK21U-jdk_x64_windows_hotspot_21.0.10_7.zip")
// Uncomment the next line to show a console when the game runs, to print messages.
//useConsole.set(true)
}
}
}
// Equivalent to the jar task; here for compatibility with gdx-setup.
tasks.register('dist') {
dependsOn 'jar'
}
distributions {
main {
contents {
into('libs') {
project.configurations.runtimeClasspath.files.findAll { file ->
file.getName() != project.tasks.jar.outputs.files.singleFile.name
}.each { file ->
exclude file.name
}
}
}
}
}
startScripts.dependsOn(':lwjgl3:jar')
startScripts.classpath = project.tasks.jar.outputs.files
// Helps if debugging on Linux with an Nvidia GPU.
// This means StartupHelper won't try to restart the JVM, which can prevent debugging.
// This only applies to Gradle tasks, not main methods debugged when launching a main() method directly.
// As a more general solution, set the environment variable __GL_THREADED_OPTIMIZATIONS to 0 globally, on Linux
// machines with Nvidia GPUs where you need to debug LWJGL3 apps and games.
// You can also set __GL_THREADED_OPTIMIZATIONS to 0 in run configurations, which you would need per main() method.
// StartupHelper will still restart the JVM to set this environment variable when run as a distributable JAR, which is
// a good thing for end users. They won't need to ever set the debug-specific environment variable.
tasks.withType(JavaExec.class).configureEach {
environment("__GL_THREADED_OPTIMIZATIONS", 0)
}
if(enableGraalNative == 'true') {
apply from: file("nativeimage.gradle")
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.
+54
View File
@@ -0,0 +1,54 @@
project(":lwjgl3") {
apply plugin: "org.graalvm.buildtools.native"
graalvmNative {
binaries {
main {
imageName = appName
mainClass = application.mainClass
requiredVersion = '23.0'
buildArgs.add("-march=compatibility")
jvmArgs.addAll("-Dfile.encoding=UTF8")
sharedLibrary = false
resources.autodetect()
}
}
}
run {
doNotTrackState("Running the app should not be affected by Graal.")
}
// Modified from https://lyze.dev/2021/04/29/libGDX-Internal-Assets-List/ ; thanks again, Lyze!
// This creates a resource-config.json file based on the contents of the assets folder (and the libGDX icons).
// This file is used by Graal Native to embed those specific files.
// This has to run before nativeCompile, so it runs at the start of an unrelated resource-handling command.
generateResourcesConfigFile.doFirst {
def assetsFolder = new File("${project.rootDir}/assets/")
def lwjgl3 = project(':lwjgl3')
def resFolder = new File("${lwjgl3.projectDir}/src/main/resources/META-INF/native-image/${lwjgl3.ext.appName}")
resFolder.mkdirs()
def resFile = new File(resFolder, "resource-config.json")
resFile.delete()
resFile.append(
"""{
"resources":{
"includes":[
{
"pattern": ".*(""")
// This adds every filename in the assets/ folder to a pattern that adds those files as resources.
fileTree(assetsFolder).each {
// The backslash-Q and backslash-E escape the start and end of a literal string, respectively.
resFile.append("\\\\Q${it.name}\\\\E|")
}
// We also match all of the window icon images this way and the font files that are part of libGDX.
resFile.append(
"""libgdx.+\\\\.png|lsans.+)"
}
]},
"bundles":[]
}"""
)
}
}
@@ -0,0 +1,46 @@
@file:JvmName("Lwjgl3Launcher")
package own.planetslivewallpaper.lwjgl3
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration
import own.planetslivewallpaper.Main
/** Launches the desktop (LWJGL3) application. */
fun main() {
// This handles macOS support and helps on Windows.
if (StartupHelper.startNewJvmIfRequired())
return
Lwjgl3Application(Main(), Lwjgl3ApplicationConfiguration().apply {
setTitle("OwnPlanetsLiveWallpaper")
//// Vsync limits the frames per second to what your hardware can display, and helps eliminate
//// screen tearing. This setting doesn't always work on Linux, so the line after is a safeguard.
useVsync(true)
//// Limits FPS to the refresh rate of the currently active monitor, plus 1 to try to match fractional
//// refresh rates. The Vsync setting above should limit the actual FPS to match the monitor.
setForegroundFPS(Lwjgl3ApplicationConfiguration.getDisplayMode().refreshRate + 1)
//// If you remove the above line and set Vsync to false, you can get unlimited FPS, which can be
//// useful for testing performance, but can also be very stressful to some hardware.
//// You may also need to configure GPU drivers to fully disable Vsync; this can cause screen tearing.
//get exact screen size
val primaryMode = Lwjgl3ApplicationConfiguration.getDisplayMode()
val desktopWidth = primaryMode.width
val desktopHeight = primaryMode.height
setWindowedMode(desktopWidth, desktopHeight)
//// You can change these files; they are in lwjgl3/src/main/resources/ .
//// They can also be loaded from the root of assets/ .
setWindowIcon(*(arrayOf(128, 64, 32, 16).map { "element1.png" }.toTypedArray()))
//// This could improve compatibility with Windows machines with buggy OpenGL drivers, Macs
//// with Apple Silicon that have to emulate compatibility with OpenGL anyway, and more.
//// This uses the dependency `com.badlogicgames.gdx:gdx-lwjgl3-angle` to function.
//// You would need to add this line to lwjgl3/build.gradle , below the dependency on `gdx-backend-lwjgl3`:
//// implementation "com.badlogicgames.gdx:gdx-lwjgl3-angle:$gdxVersion"
//// You can choose to add the following line and the mentioned dependency if you want; they
//// are not intended for games that use GL30 (which is compatibility with OpenGL ES 3.0).
//// Know that it might not work well in some cases.
// setOpenGLEmulation(Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20, 0, 0)
})
}
@@ -0,0 +1,173 @@
/*
* Copyright 2020 damios
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Note, the above license and copyright applies to this file only.
package own.planetslivewallpaper.lwjgl3
import com.badlogic.gdx.Version
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3NativesLoader
import org.lwjgl.system.JNI
import org.lwjgl.system.linux.UNISTD
import org.lwjgl.system.macosx.LibC
import org.lwjgl.system.macosx.ObjCRuntime
import java.io.File
import java.lang.management.ManagementFactory
/**
* A helper object for game startup, featuring three utilities related to LWJGL3 on various operating systems.
*
* The utilities are as follows:
* - Windows: Prevents a common crash related to LWJGL3's extraction of shared library files.
* - macOS: Spawns a child JVM process with `-XstartOnFirstThread` in the JVM args (if it was not already). This is required for LWJGL3 to work on macOS.
* - Linux (NVIDIA GPUs only): Spawns a child JVM process with the `__GL_THREADED_OPTIMIZATIONS` [Environment Variable][System.getenv] set to `0` (if it was not already). This is required for LWJGL3 to work on Linux with NVIDIA GPUs.
*
* [Based on this java-gaming.org post by kappa](https://jvm-gaming.org/t/starting-jvm-on-mac-with-xstartonfirstthread-programmatically/57547)
* @author damios
*/
object StartupHelper {
private const val JVM_RESTARTED_ARG = "jvmIsRestarted"
/**
* Must only be called on Linux. Check OS first (or use short-circuit evaluation)!
* @return whether NVIDIA drivers are present on Linux.
*/
fun isLinuxNvidia(): Boolean = File("/proc/driver").list { _, path: String -> "NVIDIA" in path.uppercase() }.isNullOrEmpty().not()
/**
* Applies the utilities as described by [StartupHelper]'s KDoc.
*
* All [Environment Variables][System.getenv] are copied to the child JVM process (if it is spawned), as specified by [ProcessBuilder.environment]; the same applies for [System Properties][System.getProperties].
*
* **Usage:**
*
* ```
* fun main() {
* if (StartupHelper.startNewJvmIfRequired()) return
* // ...
* }
* ```
* @param inheritIO whether I/O should be inherited in the child JVM process. Please note that enabling this will block the thread until the child JVM process stops executing.
* @return whether a child JVM process was spawned or not.
*/
@JvmOverloads
fun startNewJvmIfRequired(inheritIO: Boolean = true): Boolean {
val osName: String = System.getProperty("os.name").lowercase()
if ("mac" in osName) return startNewJvm0(isMac = true, inheritIO)
if ("windows" in osName) {
// Here, we are trying to work around an issue with how LWJGL3 loads its extracted .dll files.
// By default, LWJGL3 extracts to the directory specified by "java.io.tmpdir": usually, the user's home.
// If the user's name has non-ASCII (or some non-alphanumeric) characters in it, that would fail.
// By extracting to the relevant "ProgramData" folder, which is usually "C:\ProgramData", we avoid this.
// We also temporarily change the "user.name" property to one without any chars that would be invalid.
// We revert our changes immediately after loading LWJGL3 natives.
val programData: String = System.getenv("ProgramData") ?: "C:\\Temp"
val prevTmpDir: String = System.getProperty("java.io.tmpdir", programData)
val prevUser: String = System.getProperty("user.name", "libGDX_User")
System.setProperty("java.io.tmpdir", "$programData\\libGDX-temp")
System.setProperty(
"user.name",
"User_${prevUser.hashCode()}_GDX${Version.VERSION}".replace('.', '_')
)
Lwjgl3NativesLoader.load()
System.setProperty("java.io.tmpdir", prevTmpDir)
System.setProperty("user.name", prevUser)
return false
}
return startNewJvm0(isMac = false, inheritIO)
}
private const val MAC_JRE_ERR_MSG: String = "A Java installation could not be found. If you are distributing this app with a bundled JRE, be sure to set the '-XstartOnFirstThread' argument manually!"
private const val LINUX_JRE_ERR_MSG: String = "A Java installation could not be found. If you are distributing this app with a bundled JRE, be sure to set the environment variable '__GL_THREADED_OPTIMIZATIONS' to '0'!"
private const val CHILD_LOOP_ERR_MSG: String = "The current JVM process is a spawned child JVM process, but StartupHelper has attempted to spawn another child JVM process! This is a broken state, and should not normally happen! Your game may crash or not function properly!"
/**
* Spawns a child JVM process if on macOS or NVIDIA Linux.
*
* All [Environment Variables][System.getenv] are copied to the child JVM process (if it is spawned), as specified by [ProcessBuilder.environment]; the same applies for [System Properties][System.getProperties].
*
* @param isMac whether the current OS is macOS. If this is `false` then the current OS is assumed to be Linux (and an immediate check for NVIDIA drivers is performed).
* @param inheritIO whether I/O should be inherited in the child JVM process. Please note that enabling this will block the thread until the child JVM process stops executing.
* @return whether a child JVM process was spawned or not.
*/
fun startNewJvm0(isMac: Boolean, inheritIO: Boolean): Boolean {
val processID: Long = if (isMac) LibC.getpid() else UNISTD.getpid().toLong()
if (!isMac) {
// No need to restart non-NVIDIA Linux
if (!isLinuxNvidia()) return false
// check whether __GL_THREADED_OPTIMIZATIONS is already disabled
if (System.getenv("__GL_THREADED_OPTIMIZATIONS") == "0") return false
} else {
// There is no need for -XstartOnFirstThread on Graal native image
if (System.getProperty("org.graalvm.nativeimage.imagecode", "").isNotEmpty()) return false
// Checks if we are already on the main thread, such as from running via Construo.
val objcMsgSend: Long = ObjCRuntime.getLibrary().getFunctionAddress("objc_msgSend")
val nsThread: Long = ObjCRuntime.objc_getClass("NSThread")
val currentThread: Long = JNI.invokePPP(nsThread, ObjCRuntime.sel_getUid("currentThread"), objcMsgSend)
val isMainThread: Boolean = JNI.invokePPZ(currentThread, ObjCRuntime.sel_getUid("isMainThread"), objcMsgSend)
if (isMainThread) return false
if (System.getenv("JAVA_STARTED_ON_FIRST_THREAD_$processID") == "1") return false
}
// Check whether this JVM process is a child JVM process already.
// This state shouldn't (usually) be reachable, but this stops us from endlessly spawning new child JVM processes.
if (System.getProperty(JVM_RESTARTED_ARG) == "true") {
System.err.println(CHILD_LOOP_ERR_MSG)
return false
}
// Spawn the child JVM process with updated environment variables or JVM args
val jvmArgs: MutableList<String> = mutableListOf()
// The following line is used assuming you target Java 8, the minimum for LWJGL3.
val javaExecPath = "${System.getProperty("java.home")}/bin/java"
// If targeting Java 9 or higher, you could use the following instead of the above line:
//val javaExecPath = ProcessHandle.current().info().command().orElseThrow()
if (!File(javaExecPath).exists()) {
System.err.println(if (isMac) MAC_JRE_ERR_MSG else LINUX_JRE_ERR_MSG)
return false
}
jvmArgs += javaExecPath
if (isMac) jvmArgs += "-XstartOnFirstThread"
jvmArgs += "-D$JVM_RESTARTED_ARG=true"
jvmArgs += ManagementFactory.getRuntimeMXBean().inputArguments
jvmArgs += "-cp"
jvmArgs += System.getProperty("java.class.path")
jvmArgs += System.getenv("JAVA_MAIN_CLASS_$processID") ?: run {
val trace: Array<StackTraceElement> = Thread.currentThread().stackTrace
if (trace.isNotEmpty()) return@run trace[trace.lastIndex].className
else {
System.err.println("The main class could not be determined through stacktrace.")
return false
}
}
try {
val processBuilder = ProcessBuilder(jvmArgs)
if (!isMac) processBuilder.environment()["__GL_THREADED_OPTIMIZATIONS"] = "0"
if (!inheritIO) processBuilder.start()
else processBuilder.inheritIO().start().waitFor()
} catch (e: Exception) {
System.err.println("There was a problem restarting the JVM.")
e.printStackTrace()
}
return true
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB