diff --git a/.editorconfig b/.editorconfig index 6319172a3..038bc765e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -4,14 +4,12 @@ root = true [*] indent_style = space indent_size = 4 -ij_continuation_indent_size = 8 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.json] -indent_style = space indent_size = 2 max_line_length = 500 ij_json_keep_blank_lines_in_code = 0 @@ -27,12 +25,12 @@ ij_json_wrap_long_lines = false [*.java] indent_style = tab +ij_continuation_indent_size = 8 ij_java_blank_lines_before_class_end = 0 ij_java_blank_lines_after_anonymous_class_header = 0 ij_java_blank_lines_after_class_header = 0 ij_java_blank_lines_before_method_body = 0 ij_java_else_on_new_line = false -ij_continuation_indent_size = 8 ij_java_class_count_to_use_import_on_demand = 99 ij_java_names_count_to_use_import_on_demand = 99 ij_java_imports_layout = $*, |, java.**, |, javax.**, |, org.**, |, com.**, |, * diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..dd1169eae --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,47 @@ +name: build + +on: [ pull_request, push ] + +jobs: + build: + strategy: + matrix: + java: [ + 17 # Current Java LTS & minimum supported by Minecraft + ] + os: [ ubuntu-latest ] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Validate Gradle Wrapper + uses: gradle/actions/wrapper-validation@v3 + - name: Gradle Cache + uses: actions/cache@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + .gradle/loom-cache + build/ + key: ${{ runner.os }}-jdk${{ matrix.java }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle.properties', '**/gradle-wrapper.properties', '.github/workflows/build.yml') }} + - name: Setup JDK ${{ matrix.java }} + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: ${{ matrix.java }} + - name: Make Gradle Wrapper Executable + if: ${{ runner.os != 'Windows' }} + run: chmod +x ./gradlew + - name: Build + # doesn't actually publish, as no secrets are passed in, just makes sure that publishing works + run: ./gradlew publish --no-daemon + - name: Capture Build Artifacts + if: ${{ runner.os == 'Linux' && matrix.java == '17' }} + uses: actions/upload-artifact@v4 + with: + name: Artifacts + path: | + common/build/libs/ + fabric/build/libs/ + forge/build/libs/ diff --git a/.gitignore b/.gitignore index 88fc08b84..96431a961 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,4 @@ local.properties # Other mcmodsrepo src/*/generatedPackageInfos/ +*/src/*/generatedPackageInfos/ diff --git a/LICENSE.md b/LICENSE.md index 518a2732c..af23f9c4b 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,4 +1,4 @@ -Copyright (c) 2021-2023 Jozufozu +Copyright (c) 2021-2024 Jozufozu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/README.md b/README.md index 95d7ba6ba..82d4ede4b 100644 --- a/README.md +++ b/README.md @@ -46,10 +46,12 @@ repositories { } dependencies { - implementation fg.deobf("com.jozufozu.flywheel:Flywheel-Forge:${flywheel_version}") + compileOnly fg.deobf("com.jozufozu.flywheel:flywheel-forge-api-${minecraft_version}:${flywheel_version}") + runtimeOnly fg.deobf("com.jozufozu.flywheel:flywheel-forge-${minecraft_version}:${flywheel_version}") } ``` -`${flywheel_version}` gets replaced by the version of Flywheel you want to use, eg. `1.18-0.3.0.3` +`${flywheel_version}` gets replaced by the version of Flywheel you want to use, eg. `1.0.0-beta` +`${minecraft_version}` gets replaced by the version of Minecraft you're on, eg. `1.20.1` For a list of available Flywheel versions, you can check [the maven](https://maven.tterrag.com/com/jozufozu/flywheel/Flywheel-Forge/). diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 6caf08ab3..000000000 --- a/build.gradle +++ /dev/null @@ -1,205 +0,0 @@ -plugins { - id 'eclipse' - id 'idea' - id 'maven-publish' - id 'net.minecraftforge.gradle' version "${forgegradle_version}" - id 'org.parchmentmc.librarian.forgegradle' version "${librarian_version}" - id 'org.spongepowered.mixin' version "${mixingradle_version}" -} - -boolean dev = System.getenv('RELEASE') == null || System.getenv('RELEASE').equalsIgnoreCase('false'); - -ext.buildNumber = System.getenv('BUILD_NUMBER') - -group = 'com.jozufozu.flywheel' -archivesBaseName = "flywheel-forge-${artifact_minecraft_version}" -version = mod_version + (dev && buildNumber != null ? "-${buildNumber}" : '') - -java.toolchain.languageVersion = JavaLanguageVersion.of(17) - -println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" -minecraft { - mappings channel: 'parchment', version: "${parchment_version}-${minecraft_version}" - - copyIdeResources = true - - runs { - configureEach { - workingDirectory project.file('run') - - property 'forge.logging.markers', '' - property 'forge.logging.console.level', 'debug' - - property 'mixin.env.remapRefMap', 'true' - property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg" - - mods { - flywheel { - source sourceSets.main - } - } - } - - client { - property 'flw.dumpShaderSource', 'true' - property 'flw.debugMemorySafety', 'true' - } - - server { - args '--nogui' - } - } -} - -repositories { - maven { - url 'https://www.cursemaven.com' - content { - includeGroup "curse.maven" - } - } - maven { - name 'tterrag maven' - url 'https://maven.tterrag.com/' - } - maven { - name = "Modrinth" - url = "https://api.modrinth.com/maven" - content { - includeGroup "maven.modrinth" - } - } - mavenCentral() -} - -dependencies { - testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1' - minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" - - compileOnly fg.deobf("maven.modrinth:embeddium:0.3.9+mc1.20.1") - compileOnly fg.deobf("maven.modrinth:oculus:1.20.1-1.6.15a") - // implementation fg.deobf("maven.modrinth:starlight-forge:1.1.2+1.20") - - // https://discord.com/channels/313125603924639766/725850371834118214/910619168821354497 - // Prevent Mixin annotation processor from getting into IntelliJ's annotation processor settings - // This allows 'Settings > Build, Execution, and Deployment > Build Tools > Gradle > Build and run using' set to IntelliJ to work correctly - // if (System.getProperty('idea.sync.active') != 'true') { - annotationProcessor "org.spongepowered:mixin:${mixin_version}:processor" - // } -} - -test { - useJUnitPlatform() -} - -mixin { - add sourceSets.main, 'flywheel.refmap.json' - - config 'flywheel.backend.mixins.json' - config 'flywheel.impl.mixins.json' - config 'flywheel.impl.sodium.mixins.json' - - debug.verbose = true - debug.export = true -} - -idea { - // Tell IDEA to always download sources/javadoc artifacts from maven. - module { - downloadJavadoc = true - downloadSources = true - } -} - -// Workaround for SpongePowered/MixinGradle#38 -afterEvaluate { - tasks.configureReobfTaskForReobfJar.mustRunAfter(tasks.compileJava) -} - -tasks.withType(JavaCompile).configureEach { - options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation -} - -javadoc { - source = [sourceSets.main.allJava] - // prevent java 8's strict doclint for javadocs from failing builds - options.addStringOption('Xdoclint:none', '-quiet') -} - -compileJava { - options.compilerArgs = ['-Xdiags:verbose'] -} - -tasks.named('processResources', ProcessResources).configure { - var replaceProperties = [ - minecraft_version : minecraft_version, - minecraft_version_range: minecraft_version_range, - forge_version : forge_version, - forge_version_range : forge_version_range, - loader_version_range : loader_version_range, - mod_version : mod_version - ] - inputs.properties replaceProperties - - filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { - expand replaceProperties + [project: project] - } -} - -apply from: rootProject.file('gradle/package-infos.gradle') - -void addLicense(jarTask) { - jarTask.from('LICENSE.md') { - rename '(.*)\\.(.*)', '$1_' + archivesBaseName + '.$2' - } -} - -void addManifest(jarTask) { - jarTask.manifest { - attributes([ - 'Specification-Title' : 'flywheel', - // 'Specification-Vendor': 'flywheel authors', - 'Specification-Version' : '1', // We are version 1 of ourselves - 'Implementation-Title' : project.jar.archiveBaseName, - 'Implementation-Version' : project.jar.archiveVersion, - // 'Implementation-Vendor': 'flywheel authors', - 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), - ]) - } -} - -tasks.named('jar', Jar).configure { - archiveClassifier = '' - - finalizedBy 'reobfJar' - addManifest(it) - addLicense(it) -} - -java { - withSourcesJar() - withJavadocJar() -} - -publishing { - publications { - register('mavenJava', MavenPublication) { - artifact jar - artifact sourcesJar - artifact javadocJar - - artifactId = archivesBaseName - - fg.component(it) - } - } - repositories { - maven { - url "file://${project.projectDir}/mcmodsrepo" - } - - if (project.hasProperty('mavendir')) { - maven { url mavendir } - } - } -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..8704c07bc --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,15 @@ +plugins { + idea + java + id("dev.architectury.loom") apply false +} + +println("Java: ${System.getProperty("java.version")}, JVM: ${System.getProperty("java.vm.version")} (${System.getProperty("java.vendor")}), Arch: ${System.getProperty("os.arch")}") + +idea { + // Tell IDEA to always download sources/javadoc artifacts from maven. + module { + isDownloadJavadoc = true + isDownloadSources = true + } +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 000000000..312a2b4a3 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,35 @@ +plugins { + id("java-gradle-plugin") + kotlin("jvm") version "1.9.23" + `kotlin-dsl` +} + +repositories { + gradlePluginPortal() + mavenCentral() + maven("https://maven.minecraftforge.net/") { + name = "MinecraftForge" + } + maven("https://maven.architectury.dev/") { + name = "Architectury" + } + maven("https://repo.spongepowered.org/repository/maven-public") + maven("https://maven.parchmentmc.org") +} + +gradlePlugin { + plugins { + create("platformPlugin") { + id = "flywheel.platform" + implementationClass = "com.jozufozu.gradle.platform.PlatformPlugin" + } + create("subprojectPlugin") { + id = "flywheel.subproject" + implementationClass = "com.jozufozu.gradle.subproject.SubprojectPlugin" + } + } +} + +dependencies { + implementation("dev.architectury.loom:dev.architectury.loom.gradle.plugin:1.6-SNAPSHOT") +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/jarset/JarSetExtension.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/jarset/JarSetExtension.kt new file mode 100644 index 000000000..0acac776d --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/jarset/JarSetExtension.kt @@ -0,0 +1,29 @@ +package com.jozufozu.gradle.jarset + +import net.fabricmc.loom.task.RemapJarTask +import net.fabricmc.loom.task.RemapSourcesJarTask +import org.gradle.api.Project +import org.gradle.api.tasks.SourceSet +import org.gradle.jvm.tasks.Jar +import org.gradle.kotlin.dsl.named +import org.gradle.kotlin.dsl.provideDelegate + +open class JarSetExtension(private val project: Project) { + fun create(name: String, vararg sourceSetSet: SourceSet): JarTaskSet { + return JarTaskSet.create(project, name, *sourceSetSet) + } + + fun outgoing(name: String, vararg sourceSetSet: SourceSet): JarTaskSet { + return JarTaskSet.create(project, name, *sourceSetSet).also { it.createOutgoingConfiguration() } + } + + val mainSet: JarTaskSet by lazy { + val jarTask = project.tasks.named("jar") + val remapJarTask = project.tasks.named("remapJar") + val sourcesJarTask = project.tasks.named("sourcesJar") + val remapSourcesJarTask = project.tasks.named("remapSourcesJar") + val javadocJarTask = project.tasks.named("javadocJar") + + JarTaskSet(project, "main", jarTask, sourcesJarTask, javadocJarTask, remapJarTask, remapSourcesJarTask) + } +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/jarset/JarTaskSet.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/jarset/JarTaskSet.kt new file mode 100644 index 000000000..0bb7e09d2 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/jarset/JarTaskSet.kt @@ -0,0 +1,210 @@ +package com.jozufozu.gradle.jarset + +import net.fabricmc.loom.task.AbstractRemapJarTask +import net.fabricmc.loom.task.RemapJarTask +import net.fabricmc.loom.task.RemapSourcesJarTask +import org.gradle.api.Action +import org.gradle.api.Project +import org.gradle.api.file.DuplicatesStrategy +import org.gradle.api.publish.PublishingExtension +import org.gradle.api.publish.maven.MavenPublication +import org.gradle.api.tasks.AbstractCopyTask +import org.gradle.api.tasks.SourceSet +import org.gradle.api.tasks.SourceTask +import org.gradle.api.tasks.TaskProvider +import org.gradle.api.tasks.javadoc.Javadoc +import org.gradle.jvm.tasks.Jar +import org.gradle.kotlin.dsl.register +import org.gradle.kotlin.dsl.the + +class JarTaskSet( + private val project: Project, + private val name: String, + private val jar: TaskProvider, + private val sources: TaskProvider, + private val javadocJar: TaskProvider, + private val remapJar: TaskProvider, + private val remapSources: TaskProvider +) { + + fun publish(artifactId: String) { + project.the().publications { + register("${name}RemapMaven") { + artifact(remapJar) + artifact(remapSources) + artifact(javadocJar) + this.artifactId = artifactId + } + } + } + + /** + * Create a new configuration that can be consumed by other projects, and export the base jar. + */ + fun createOutgoingConfiguration() { + val config = project.configurations.register(name) { + isCanBeConsumed = true + isCanBeResolved = false + } + + project.artifacts.add(config.name, jar) + } + + /** + * Configure the assemble task to depend on the remap tasks and javadoc jar. + */ + fun addToAssemble() { + project.tasks.named("assemble").configure { + dependsOn(remapJar, remapSources, javadocJar) + } + } + + /** + * Configure the remap tasks with the given action. + */ + fun configureRemap(action: Action) { + remapJar.configure(action) + remapSources.configure(action) + } + + /** + * Configure the jar tasks with the given action. + */ + fun configureJar(action: Action) { + jar.configure(action) + sources.configure(action) + } + + /** + * Create a new JarTaskSet with the same base jars but new tasks for remapping. + */ + fun forkRemap(newName: String): JarTaskSet { + val remapJarTask = createRemapJar(project, newName, jar) + val remapSourcesTask = createRemapSourcesJar(project, newName, sources) + + return JarTaskSet(project, newName, jar, sources, javadocJar, remapJarTask, remapSourcesTask) + } + + companion object { + private const val PACKAGE_INFOS_JAVA_PATTERN = "**/package-info.java" + private const val BUILD_GROUP: String = "build" + private const val LOOM_GROUP: String = "loom" + private const val JAVADOC_CLASSIFIER: String = "javadoc" + private const val SOURCES_CLASSIFIER: String = "sources" + + /** + * We have duplicate packages between the common and platform dependent subprojects. + * In theory the package-info.java files should be identical, so just take the first one we find. + */ + fun excludeDuplicatePackageInfos(copyTask: AbstractCopyTask) { + copyTask.filesMatching(PACKAGE_INFOS_JAVA_PATTERN) { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + } + } + + /** + * The compile/javadoc tasks have a different base type that isn't so smart about exclusion handling. + */ + fun excludeDuplicatePackageInfos(sourceTask: SourceTask) { + sourceTask.exclude(PACKAGE_INFOS_JAVA_PATTERN) + } + + fun create(project: Project, name: String, vararg sourceSetSet: SourceSet): JarTaskSet { + val jarTask = createJar(project, name, sourceSetSet) + val sourcesTask = createSourcesJar(project, name, sourceSetSet) + val javadocJarTask = createJavadocJar(project, name, sourceSetSet) + + val remapJarTask = createRemapJar(project, name, jarTask) + val remapSourcesTask = createRemapSourcesJar(project, name, sourcesTask) + + return JarTaskSet(project, name, jarTask, sourcesTask, javadocJarTask, remapJarTask, remapSourcesTask) + } + + private fun createJar( + project: Project, + name: String, + sourceSetSet: Array + ): TaskProvider { + return project.tasks.register("${name}Jar") { + group = BUILD_GROUP + destinationDirectory.set(project.layout.buildDirectory.dir("devlibs/${name}")) + + for (set in sourceSetSet) { + from(set.output) + } + excludeDuplicatePackageInfos(this) + } + } + + private fun createSourcesJar( + project: Project, + name: String, + sourceSetSet: Array + ): TaskProvider { + return project.tasks.register("${name}SourcesJar") { + group = BUILD_GROUP + destinationDirectory.set(project.layout.buildDirectory.dir("devlibs/${name}")) + archiveClassifier.set(SOURCES_CLASSIFIER) + + for (set in sourceSetSet) { + from(set.allSource) + } + excludeDuplicatePackageInfos(this) + } + } + + private fun createJavadocJar( + project: Project, + name: String, + sourceSetSet: Array + ): TaskProvider { + val javadocTask = project.tasks.register("${name}Javadoc") { + group = BUILD_GROUP + setDestinationDir(project.layout.buildDirectory.dir("docs/${name}-javadoc").get().asFile) + + for (set in sourceSetSet) { + source(set.allJava) + classpath += set.compileClasspath + } + excludeDuplicatePackageInfos(this) + } + return project.tasks.register("${name}JavadocJar") { + dependsOn(javadocTask) + group = BUILD_GROUP + destinationDirectory.set(project.layout.buildDirectory.dir("libs/${name}")) + archiveClassifier.set(JAVADOC_CLASSIFIER) + + from(javadocTask.map { it.outputs }) + } + } + + private fun createRemapJar( + project: Project, + name: String, + jar: TaskProvider + ): TaskProvider { + return project.tasks.register("${name}RemapJar") { + dependsOn(jar) + group = LOOM_GROUP + destinationDirectory.set(project.layout.buildDirectory.dir("libs/${name}")) + + inputFile.set(jar.flatMap { it.archiveFile }) + } + } + + private fun createRemapSourcesJar( + project: Project, + name: String, + jar: TaskProvider + ): TaskProvider { + return project.tasks.register("${name}RemapSourcesJar") { + dependsOn(jar) + group = LOOM_GROUP + destinationDirectory.set(project.layout.buildDirectory.dir("libs/${name}")) + archiveClassifier.set(SOURCES_CLASSIFIER) + + inputFile.set(jar.flatMap { it.archiveFile }) + } + } + } +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/nullability/GeneratePackageInfosTask.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/nullability/GeneratePackageInfosTask.kt new file mode 100644 index 000000000..fbe7698cb --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/nullability/GeneratePackageInfosTask.kt @@ -0,0 +1,58 @@ +package com.jozufozu.gradle.nullability + +import org.apache.groovy.nio.extensions.NioExtensions +import org.codehaus.groovy.runtime.StringGroovyMethods +import org.gradle.api.DefaultTask +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.tasks.InputDirectory +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.SkipWhenEmpty +import org.gradle.api.tasks.TaskAction +import org.gradle.kotlin.dsl.closureOf +import java.io.BufferedWriter +import java.io.File +import java.nio.file.Files +import java.nio.file.Path + +// Adapted from https://github.com/FabricMC/fabric/blob/31787236d242247e0b6c4ae806b1cfaa7042a62c/gradle/package-info.gradle, which is licensed under Apache 2.0. +open class GeneratePackageInfosTask: DefaultTask() { + @SkipWhenEmpty + @InputDirectory + val sourceRoot: DirectoryProperty = project.objects.directoryProperty() + + @OutputDirectory + val outputDir: DirectoryProperty = project.objects.directoryProperty() + + @TaskAction + fun run() { + val output = outputDir.get().asFile.toPath() + NioExtensions.deleteDir(output) + val root = sourceRoot.get().asFile.toPath() + + NioExtensions.eachDirRecurse(root, closureOf { + val containsJava = Files.list(this).anyMatch { + Files.isRegularFile(it) && it.fileName.toString().endsWith(".java") + } + + if (containsJava && Files.notExists(resolve("package-info.java"))) { + val relativePath = root.relativize(this) + val target = output.resolve(relativePath) + Files.createDirectories(target) + + NioExtensions.withWriter(target.resolve("package-info.java"), closureOf { + val packageName = relativePath.toString().replace(File.separator, ".") + write(StringGroovyMethods.stripMargin("""@ParametersAreNonnullByDefault + |@FieldsAreNonnullByDefault + |@MethodsReturnNonnullByDefault + |package $packageName; + | + |import javax.annotation.ParametersAreNonnullByDefault; + | + |import net.minecraft.FieldsAreNonnullByDefault; + |import net.minecraft.MethodsReturnNonnullByDefault; + |""")) + }) + } + }) + } +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/nullability/PackageInfosExtension.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/nullability/PackageInfosExtension.kt new file mode 100644 index 000000000..8a45da808 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/nullability/PackageInfosExtension.kt @@ -0,0 +1,43 @@ +package com.jozufozu.gradle.nullability + +import org.gradle.api.Project +import org.gradle.api.tasks.Delete +import org.gradle.api.tasks.SourceSet +import org.gradle.kotlin.dsl.register + +open class PackageInfosExtension(private val project: Project) { + fun sources(vararg sourceSets: SourceSet) { + for (sourceSet in sourceSets) { + forSourceSet(sourceSet) + } + } + + private fun forSourceSet(sourceSet: SourceSet) { + // We have to capture the source set name for the lazy string literals, + // otherwise it'll just be whatever the last source set is in the list. + val sourceSetName = sourceSet.name + val taskName = sourceSet.getTaskName("generate", "PackageInfos") + val task = project.tasks.register(taskName) { + group = "flywheel" + description = "Generates package-info files for $sourceSetName packages." + + // Only apply to default source directory since we also add the generated + // sources to the source set. + sourceRoot.set(project.file("src/$sourceSetName/java")) + outputDir.set(project.file("src/$sourceSetName/generatedPackageInfos")) + } + sourceSet.java.srcDir(task) + + project.tasks.named("ideaSyncTask").configure { + finalizedBy(task) + } + + val cleanTask = project.tasks.register(sourceSet.getTaskName("clean", "PackageInfos")) { + group = "flywheel" + delete(project.file("src/$sourceSetName/generatedPackageInfos")) + } + project.tasks.named("clean").configure { + dependsOn(cleanTask) + } + } +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/platform/PlatformExtension.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/platform/PlatformExtension.kt new file mode 100644 index 000000000..dec97abf7 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/platform/PlatformExtension.kt @@ -0,0 +1,125 @@ +package com.jozufozu.gradle.platform + +import com.jozufozu.gradle.jarset.JarTaskSet +import net.fabricmc.loom.api.LoomGradleExtensionAPI +import org.gradle.api.Project +import org.gradle.api.tasks.SourceSet +import org.gradle.api.tasks.SourceSetContainer +import org.gradle.api.tasks.compile.JavaCompile +import org.gradle.api.tasks.javadoc.Javadoc +import org.gradle.jvm.tasks.Jar +import org.gradle.kotlin.dsl.named +import org.gradle.kotlin.dsl.provideDelegate +import org.gradle.kotlin.dsl.the +import org.gradle.kotlin.dsl.withType +import org.gradle.language.jvm.tasks.ProcessResources +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +open class PlatformExtension(val project: Project) { + var commonProject: Project by DependentProject(this.project) + + var modArtifactId: String = "flywheel-${project.name}-${project.property("artifact_minecraft_version")}" + + var apiArtifactId: String = "flywheel-${project.name}-api-${project.property("artifact_minecraft_version")}" + + private val sources = mutableSetOf() + private val commonSourceSets: SourceSetContainer by lazy { commonProject.the() } + + fun sources(vararg sourceSets: SourceSet) { + this.sources.addAll(sourceSets) + } + + fun setupLoomMod() { + project.the().mods.maybeCreate("main").apply { + sources.forEach(::sourceSet) + } + } + + fun setupLoomRuns() { + project.the().runs.apply { + named("client") { + isIdeConfigGenerated = true + + // Turn on our own debug flags + property("flw.dumpShaderSource", "true") + property("flw.debugMemorySafety", "true") + + // Turn on mixin debug flags + property("mixin.debug.export", "true") + property("mixin.debug.verbose", "true") + + // 720p baby! + programArgs("--width", "1280", "--height", "720") + } + + // We're a client mod, but we need to make sure we correctly render when playing on a server. + named("server") { + isIdeConfigGenerated = true + programArgs("--nogui") + } + } + } + + fun compileWithCommonSourceSets() { + project.tasks.apply { + withType().configureEach { + JarTaskSet.excludeDuplicatePackageInfos(this) + } + + sources.forEach { + val commonSourceSet = commonSourceSets.named(it.name).get() + + named(it.compileJavaTaskName).configure { + source(commonSourceSet.allJava) + } + named(it.processResourcesTaskName).configure { + from(commonSourceSet.resources) + } + } + } + } + + fun setupFatJar() { + project.tasks.apply { + val extraSourceSets = sources.filter { it.name != "main" }.toList() + val commonSources = sources.map { commonSourceSets.named(it.name).get() } + + named("jar").configure { + extraSourceSets.forEach { from(it.output) } + + JarTaskSet.excludeDuplicatePackageInfos(this) + } + + named("javadoc").configure { + commonSources.forEach { source(it.allJava) } + extraSourceSets.forEach { source(it.allJava) } + + JarTaskSet.excludeDuplicatePackageInfos(this) + } + + named("sourcesJar").configure { + commonSources.forEach { from(it.allJava) } + extraSourceSets.forEach { from(it.allJava) } + + JarTaskSet.excludeDuplicatePackageInfos(this) + } + } + } + + private class DependentProject(private val thisProject: Project) : ReadWriteProperty { + private var value: Project? = null + + override fun getValue(thisRef: Any?, property: KProperty<*>): Project { + return value ?: throw IllegalStateException("Property ${property.name} should be initialized before get.") + } + + override fun setValue(thisRef: Any?, property: KProperty<*>, value: Project) { + this.value = value + thisProject.evaluationDependsOn(value.path) + } + + override fun toString(): String = + "NotNullProperty(${if (value != null) "value=$value" else "value not initialized yet"})" + } +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/platform/PlatformPlugin.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/platform/PlatformPlugin.kt new file mode 100644 index 000000000..652a51121 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/platform/PlatformPlugin.kt @@ -0,0 +1,10 @@ +package com.jozufozu.gradle.platform + +import org.gradle.api.Plugin +import org.gradle.api.Project + +class PlatformPlugin: Plugin { + override fun apply(project: Project) { + project.extensions.create("platform", PlatformExtension::class.java, project) + } +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/subproject/SubprojectPlugin.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/subproject/SubprojectPlugin.kt new file mode 100644 index 000000000..d39d0d9b4 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/subproject/SubprojectPlugin.kt @@ -0,0 +1,185 @@ +package com.jozufozu.gradle.subproject + +import com.jozufozu.gradle.jarset.JarSetExtension +import com.jozufozu.gradle.nullability.PackageInfosExtension +import com.jozufozu.gradle.transitive.TransitiveSourceSetsExtension +import net.fabricmc.loom.api.LoomGradleExtensionAPI +import org.gradle.api.JavaVersion +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.plugins.BasePluginExtension +import org.gradle.api.plugins.JavaPluginExtension +import org.gradle.api.publish.PublishingExtension +import org.gradle.api.publish.tasks.GenerateModuleMetadata +import org.gradle.api.tasks.bundling.AbstractArchiveTask +import org.gradle.api.tasks.compile.JavaCompile +import org.gradle.api.tasks.javadoc.Javadoc +import org.gradle.jvm.tasks.Jar +import org.gradle.jvm.toolchain.JavaLanguageVersion +import org.gradle.kotlin.dsl.* +import org.gradle.language.jvm.tasks.ProcessResources + +class SubprojectPlugin: Plugin { + override fun apply(project: Project) { + project.extensions.create("defaultPackageInfos", PackageInfosExtension::class.java, project) + project.extensions.create("transitiveSourceSets", TransitiveSourceSetsExtension::class.java, project) + project.extensions.create("jarSets", JarSetExtension::class.java, project) + + setBaseProperties(project) + setupJava(project) + addRepositories(project) + setupLoom(project) + setupDependencies(project) + configureTasks(project) + setupPublishing(project) + } + + private fun setBaseProperties(project: Project) { + val dev = System.getenv("RELEASE")?.contentEquals("false", true) ?: true + val buildNumber = System.getenv("BUILD_NUMBER") + + val mod_version: String by project + project.group = "com.jozufozu.flywheel" + project.version = mod_version + if (dev && buildNumber != null) "-${buildNumber}" else "" + + val artifact_minecraft_version: String by project + project.the().archivesName = "flywheel-${project.name}-${artifact_minecraft_version}" + } + + @Suppress("UnstableApiUsage") + private fun setupLoom(project: Project) { + val loom = project.the() + loom.silentMojangMappingsLicense() + + loom.mixin.defaultRefmapName = "flywheel.refmap.json" + } + + private fun setupJava(project: Project) { + val java_version: String by project + + project.the().apply { + val javaVersion = JavaVersion.toVersion(java_version) + sourceCompatibility = javaVersion + targetCompatibility = javaVersion + + toolchain.languageVersion = JavaLanguageVersion.of(java_version) + + withSourcesJar() + withJavadocJar() + } + } + + private fun addRepositories(project: Project) { + project.repositories.apply { + mavenCentral() + maven("https://maven.parchmentmc.org") { + name = "ParchmentMC" + } + maven("https://maven.tterrag.com/") { + name = "tterrag maven" + } + maven("https://www.cursemaven.com") { + name = "CurseMaven" + content { + includeGroup("curse.maven") + } + } + maven("https://api.modrinth.com/maven") { + name = "Modrinth" + content { + includeGroup("maven.modrinth") + } + } + } + } + + @Suppress("UnstableApiUsage") + private fun setupDependencies(project: Project) { + project.dependencies.apply { + val minecraft_version: String by project + val parchment_version: String by project + val loom = project.the() + + add("minecraft", "com.mojang:minecraft:${minecraft_version}") + + add("mappings", loom.layered { + officialMojangMappings() + parchment("org.parchmentmc.data:parchment-${minecraft_version}:${parchment_version}@zip") + }) + + add("api", "com.google.code.findbugs:jsr305:3.0.2") + } + } + + private fun configureTasks(project: Project) { + val java_version: String by project + + project.tasks.apply { + // make builds reproducible + withType().configureEach { + isPreserveFileTimestamps = false + isReproducibleFileOrder = true + } + + // module metadata is often broken on multi-platform projects + withType().configureEach { + enabled = false + } + + withType().configureEach { + options.encoding = "UTF-8" + options.release = Integer.parseInt(java_version) + options.compilerArgs.add("-Xdiags:verbose") + } + + withType().configureEach { + from("${project.rootDir}/LICENSE.md") { + into("META-INF") + } + } + + withType().configureEach { + options.optionFiles(project.rootProject.file("javadoc-options.txt")) + options.encoding = "UTF-8" + } + + val replaceProperties = processResourcesExpandProperties.associateWith { project.property(it) as String } + + withType().configureEach { + inputs.properties(replaceProperties) + + filesMatching(processResourcesExpandFiles) { + expand(replaceProperties) + } + } + } + } + + private fun setupPublishing(project: Project) { + project.the().repositories.apply { + maven("file://${project.rootProject.projectDir}/mcmodsrepo") + + if (project.hasProperty("mavendir")) { + maven(project.rootProject.file(project.property("mavendir") as String)) + } + } + } +} + +val processResourcesExpandFiles = listOf("pack.mcmeta", "fabric.mod.json", "META-INF/mods.toml") + +val processResourcesExpandProperties = listOf( + "mod_id", + "mod_name", + "mod_description", + "mod_license", + "mod_sources", + "mod_issues", + "mod_homepage", + "mod_version", + "minecraft_semver_version_range", + "minecraft_maven_version_range", + "fabric_api_version_range", + "forge_version_range", +) + diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/transitive/TransitiveSourceSetConfigurator.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/transitive/TransitiveSourceSetConfigurator.kt new file mode 100644 index 000000000..f91dc56a4 --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/transitive/TransitiveSourceSetConfigurator.kt @@ -0,0 +1,40 @@ +package com.jozufozu.gradle.transitive + +import org.gradle.api.tasks.SourceSet + +class TransitiveSourceSetConfigurator(private val parent: TransitiveSourceSetsExtension, private val sourceSet: SourceSet) { + internal val compileSourceSets = mutableSetOf() + internal val runtimeSourceSets = mutableSetOf() + + fun rootCompile() { + parent.compileClasspath?.let { sourceSet.compileClasspath = it } + } + + fun rootRuntime() { + parent.runtimeClasspath?.let { sourceSet.runtimeClasspath = it } + } + + fun rootImplementation() { + rootCompile() + rootRuntime() + } + + fun compile(vararg sourceSets: SourceSet) { + compileSourceSets += sourceSets + for (sourceSet in sourceSets) { + this.sourceSet.compileClasspath += sourceSet.output + } + } + + fun runtime(vararg sourceSets: SourceSet) { + runtimeSourceSets += sourceSets + for (sourceSet in sourceSets) { + this.sourceSet.runtimeClasspath += sourceSet.output + } + } + + fun implementation(vararg sourceSets: SourceSet) { + compile(*sourceSets) + runtime(*sourceSets) + } +} diff --git a/buildSrc/src/main/kotlin/com/jozufozu/gradle/transitive/TransitiveSourceSetsExtension.kt b/buildSrc/src/main/kotlin/com/jozufozu/gradle/transitive/TransitiveSourceSetsExtension.kt new file mode 100644 index 000000000..9ebbe2dab --- /dev/null +++ b/buildSrc/src/main/kotlin/com/jozufozu/gradle/transitive/TransitiveSourceSetsExtension.kt @@ -0,0 +1,61 @@ +package com.jozufozu.gradle.transitive + +import org.gradle.api.Action +import org.gradle.api.Project +import org.gradle.api.file.FileCollection +import org.gradle.api.tasks.SourceSet + +open class TransitiveSourceSetsExtension(private val project: Project) { + var compileClasspath: FileCollection? = null + var runtimeClasspath: FileCollection? = null + + private val transitives = mutableMapOf() + + fun sourceSet(sourceSet: SourceSet) { + registerSourceSet(sourceSet) + } + + fun sourceSet(sourceSet: SourceSet, action: Action) { + action.execute(registerSourceSet(sourceSet)) + } + + private fun registerSourceSet(sourceSet: SourceSet): TransitiveSourceSetConfigurator { + return transitives.computeIfAbsent(sourceSet) { TransitiveSourceSetConfigurator(this, it) } + } + + fun createCompileConfigurations() { + val configs = transitives.mapValues { (sourceSet, _) -> + project.configurations.create("for${sourceSet.name.capitalize()}") { + isCanBeConsumed = true + isCanBeResolved = false + } + } + + transitives.forEach { (sourceSet, configurator) -> + project.configurations.named(sourceSet.compileOnlyConfigurationName).configure { + extendsFrom(configs[sourceSet]) + configurator.compileSourceSets.forEach { + extendsFrom(configs[it]) + } + } + } + } + + fun createRuntimeConfigurations() { + val configs = transitives.mapValues { (sourceSet, _) -> + project.configurations.create("run${sourceSet.name.capitalize()}") { + isCanBeConsumed = true + isCanBeResolved = false + } + } + + transitives.forEach { (sourceSet, configurator) -> + project.configurations.named(sourceSet.runtimeOnlyConfigurationName).configure { + extendsFrom(configs[sourceSet]) + configurator.runtimeSourceSets.forEach { + extendsFrom(configs[it]) + } + } + } + } +} diff --git a/changelog.txt b/changelog.txt deleted file mode 100644 index 9ccbe5e24..000000000 --- a/changelog.txt +++ /dev/null @@ -1,115 +0,0 @@ -0.6.8: -Fixes - - Fix colored vertices being incorrectly rendered through instancing - - Fix some miscellaneous bugs with sodium/rubidium - - Fix memory leak associated with model storage -Technical/API - - Memory for models is freed when they are no longer in use - - Element buffers now deal in raw gl handles - - Element buffers are no longer considered part of state resoration - - Quad -> Tri element buffer properly resets itself - -0.6.7: -...is 1.19 only :ioa: - -0.6.6: -Fixes - - Fix instanced entities not rendering correctly when chunk loading is slow -Technical/API - - GL state is more reliably managed - - Slight memory improvements when using Iris/Oculus through lazy instatiation - -0.6.5: -Fixes - - Fix crash with batching backend and Rubidium - -0.6.4: -Fixes - - Fix shader detection with oculus -Technical/API - - LightUpdater is simplified to increase reliability and reflect how it is actually used - - ModelUtil is superseded by model builders, to be improved more in 0.7.0 - - VertexLists now copy input buffers to reduce memory usage - -0.6.3: -Technical/API - - Light updates are now processed in parallel. - - The light updater is now more selective of the levels it processes, fixing a memory leak. - -0.6.2: -Update to 1.18.2 - -0.6.1: -Fixes -- Fix crash when loading block entities for Flywheel to render, most common when exploring the end. -- Fix occasional visual artifacts when enabling optifine shaders. -Technical/API -- Added more debug information to the F3 screen. -- Distance update limiting can now be disabled. - -0.6.0: -With this release, Flywheel is no longer needed on servers! Forge finally has client commands, -and the /flywheel command now takes advantage of this. -Fixes - - Fix crash when running with sodium/magnesium. -Technical/API - - Backend is now a static class. - - Shaders are now compiled on-the-fly and cached. - - Significantly reduced the amount of boilerplate needed in instancing shaders. - - Struct types no longer need to be registered ahead of time. - - Simplify unnecessarily complicated game state system. - -0.5.1: -Fixes - - Fix crash on resource reload with backend off - - Fix artifacts while using Optifine shaders - - Fix crash when trying to access biomes in a VirtualRenderWorld -Technical/API - - Refactor instance renderer registration to separate client and server logic (thanks Pepper!) - - VirtualRenderWorlds now have a "biomeOffset" field which gets added when looking up biomes - - Added GlStateTracker which hooks into GlStateManager to track changes in buffer, vertex array, and program bindings - -0.5.0a: -Fixes - - Address crash experienced by some users while rendering any tile. - - Fix crash caused by loading a world with flywheel backend off. - -0.5.0: -New - - Added parallel batching backend, effectively a CPU instancer. - - Now partially compatible with starlight. -Technical/API - - Much more flexible vertex formats. - - Do instance updates/ticking entirely async. - -0.4.2-rc: -Fixes - - Partially fix crash on intel and mesa drivers (needs Create to update) - - Fix garbage rendering on AMD GPUs - -0.4.1: -Update to 1.18.1 -Changes - - Use cylindrical fog to match vanilla -Fixes - - Fix crash affecting systems that don't support persistent mapping - - Fix crash when Create contraptions extend below Y=0 - - Fix Create contraptions having misaligned light when launched after world load - - Fix minecarts disappearing on chunk reload - -0.4.0: -Update to 1.18 -Fixes - - Fix potential nullpointer rendering breaking overlay - - Fix inconsistency in minecart model - - Fix memory leak when instance worlds get reset -Technical/API - - No more MaterialSpec, everything is StructType - - Move most user facing interfaces to flywheel.api package - - Refactor InstanceData to have no package private fields - - Rename many interfaces - - All materials use the same vertex format: UNLIT_MODEL - - call #tick and #beginFrame on instance creation - - Fixes weird delay in object appearance when reloading chunks - - Add instances when chunks are built for rendering - - Server worlds are not flywheel worlds diff --git a/common/build.gradle.kts b/common/build.gradle.kts new file mode 100644 index 000000000..23d1f23b4 --- /dev/null +++ b/common/build.gradle.kts @@ -0,0 +1,80 @@ +plugins { + idea + java + `maven-publish` + id("dev.architectury.loom") + id("flywheel.subproject") +} + +val api = sourceSets.create("api") +val lib = sourceSets.create("lib") +val backend = sourceSets.create("backend") +val main = sourceSets.getByName("main") + +transitiveSourceSets { + compileClasspath = main.compileClasspath + + sourceSet(api) { + rootCompile() + } + sourceSet(lib) { + rootCompile() + compile(api) + } + sourceSet(backend) { + rootCompile() + compile(api, lib) + } + sourceSet(main) { + compile(api, lib, backend) + } + sourceSet(sourceSets.getByName("test")) { + implementation(api, lib, backend) + } +} + +defaultPackageInfos { + sources(api, lib, backend, main) +} + +jarSets { + // For sharing with other subprojects. + outgoing("commonApiOnly", api) + outgoing("commonLib", lib) + outgoing("commonBackend", backend) + outgoing("commonImpl", main) + + // For publishing. + create("api", api, lib).apply { + addToAssemble() + publish("flywheel-common-intermediary-api-${property("artifact_minecraft_version")}") + + configureJar { + manifest { + attributes("Fabric-Loom-Remap" to "true") + } + } + + // Don't publish the un-remapped jars because they don't have the correct manifest populated by Loom. + forkRemap("apiMojmap").apply { + addToAssemble() + configureRemap { + // "named" == mojmap + // We're probably remapping from named to named so Loom should noop this. + targetNamespace = "named" + } + + publish("flywheel-common-mojmap-api-${property("artifact_minecraft_version")}") + } + } +} + +dependencies { + modCompileOnly("net.fabricmc:fabric-loader:${property("fabric_loader_version")}") + + testImplementation("org.junit.jupiter:junit-jupiter:5.8.1") +} + +tasks.test { + useJUnitPlatform() +} diff --git a/src/main/java/com/jozufozu/flywheel/api/BackendImplemented.java b/common/src/api/java/com/jozufozu/flywheel/api/BackendImplemented.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/BackendImplemented.java rename to common/src/api/java/com/jozufozu/flywheel/api/BackendImplemented.java diff --git a/common/src/api/java/com/jozufozu/flywheel/api/Flywheel.java b/common/src/api/java/com/jozufozu/flywheel/api/Flywheel.java new file mode 100644 index 000000000..f410e4ac2 --- /dev/null +++ b/common/src/api/java/com/jozufozu/flywheel/api/Flywheel.java @@ -0,0 +1,14 @@ +package com.jozufozu.flywheel.api; + +import net.minecraft.resources.ResourceLocation; + +public final class Flywheel { + public static final String ID = "flywheel"; + + private Flywheel() { + } + + public static ResourceLocation rl(String path) { + return new ResourceLocation(ID, path); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/api/backend/Backend.java b/common/src/api/java/com/jozufozu/flywheel/api/backend/Backend.java similarity index 77% rename from src/main/java/com/jozufozu/flywheel/api/backend/Backend.java rename to common/src/api/java/com/jozufozu/flywheel/api/backend/Backend.java index 0d229152e..0c6e8ae40 100644 --- a/src/main/java/com/jozufozu/flywheel/api/backend/Backend.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/backend/Backend.java @@ -1,14 +1,14 @@ package com.jozufozu.flywheel.api.backend; import com.jozufozu.flywheel.api.BackendImplemented; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.jozufozu.flywheel.api.registry.IdRegistry; import net.minecraft.world.level.LevelAccessor; @BackendImplemented public interface Backend { - static IdRegistry REGISTRY = InternalFlywheelApi.INSTANCE.createIdRegistry(); + static IdRegistry REGISTRY = FlwApiLink.INSTANCE.createIdRegistry(); /** * Create a new engine instance. diff --git a/src/main/java/com/jozufozu/flywheel/api/backend/BackendManager.java b/common/src/api/java/com/jozufozu/flywheel/api/backend/BackendManager.java similarity index 54% rename from src/main/java/com/jozufozu/flywheel/api/backend/BackendManager.java rename to common/src/api/java/com/jozufozu/flywheel/api/backend/BackendManager.java index bf6e7d751..02eb06020 100644 --- a/src/main/java/com/jozufozu/flywheel/api/backend/BackendManager.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/backend/BackendManager.java @@ -1,6 +1,6 @@ package com.jozufozu.flywheel.api.backend; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; public final class BackendManager { private BackendManager() { @@ -10,18 +10,18 @@ private BackendManager() { * Get the current backend. */ public static Backend getBackend() { - return InternalFlywheelApi.INSTANCE.getBackend(); + return FlwApiLink.INSTANCE.getBackend(); } public static boolean isBackendOn() { - return InternalFlywheelApi.INSTANCE.isBackendOn(); + return FlwApiLink.INSTANCE.isBackendOn(); } public static Backend getOffBackend() { - return InternalFlywheelApi.INSTANCE.getOffBackend(); + return FlwApiLink.INSTANCE.getOffBackend(); } public static Backend getDefaultBackend() { - return InternalFlywheelApi.INSTANCE.getDefaultBackend(); + return FlwApiLink.INSTANCE.getDefaultBackend(); } } diff --git a/src/main/java/com/jozufozu/flywheel/api/backend/Engine.java b/common/src/api/java/com/jozufozu/flywheel/api/backend/Engine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/backend/Engine.java rename to common/src/api/java/com/jozufozu/flywheel/api/backend/Engine.java diff --git a/src/main/java/com/jozufozu/flywheel/api/event/RenderContext.java b/common/src/api/java/com/jozufozu/flywheel/api/event/RenderContext.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/event/RenderContext.java rename to common/src/api/java/com/jozufozu/flywheel/api/event/RenderContext.java diff --git a/src/main/java/com/jozufozu/flywheel/api/event/RenderStage.java b/common/src/api/java/com/jozufozu/flywheel/api/event/RenderStage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/event/RenderStage.java rename to common/src/api/java/com/jozufozu/flywheel/api/event/RenderStage.java diff --git a/src/main/java/com/jozufozu/flywheel/api/instance/Instance.java b/common/src/api/java/com/jozufozu/flywheel/api/instance/Instance.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/instance/Instance.java rename to common/src/api/java/com/jozufozu/flywheel/api/instance/Instance.java diff --git a/src/main/java/com/jozufozu/flywheel/api/instance/InstanceHandle.java b/common/src/api/java/com/jozufozu/flywheel/api/instance/InstanceHandle.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/instance/InstanceHandle.java rename to common/src/api/java/com/jozufozu/flywheel/api/instance/InstanceHandle.java diff --git a/src/main/java/com/jozufozu/flywheel/api/instance/InstanceType.java b/common/src/api/java/com/jozufozu/flywheel/api/instance/InstanceType.java similarity index 81% rename from src/main/java/com/jozufozu/flywheel/api/instance/InstanceType.java rename to common/src/api/java/com/jozufozu/flywheel/api/instance/InstanceType.java index 189d12906..6b84e3382 100644 --- a/src/main/java/com/jozufozu/flywheel/api/instance/InstanceType.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/instance/InstanceType.java @@ -1,6 +1,6 @@ package com.jozufozu.flywheel.api.instance; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.jozufozu.flywheel.api.layout.Layout; import com.jozufozu.flywheel.api.registry.Registry; @@ -12,7 +12,7 @@ * @param The java representation of the instance. */ public interface InstanceType { - static Registry> REGISTRY = InternalFlywheelApi.INSTANCE.createRegistry(); + static Registry> REGISTRY = FlwApiLink.INSTANCE.createRegistry(); /** * @param handle A handle that allows you to mark the instance as dirty or deleted. diff --git a/src/main/java/com/jozufozu/flywheel/api/instance/InstanceWriter.java b/common/src/api/java/com/jozufozu/flywheel/api/instance/InstanceWriter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/instance/InstanceWriter.java rename to common/src/api/java/com/jozufozu/flywheel/api/instance/InstanceWriter.java diff --git a/src/main/java/com/jozufozu/flywheel/api/instance/Instancer.java b/common/src/api/java/com/jozufozu/flywheel/api/instance/Instancer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/instance/Instancer.java rename to common/src/api/java/com/jozufozu/flywheel/api/instance/Instancer.java diff --git a/src/main/java/com/jozufozu/flywheel/api/instance/InstancerProvider.java b/common/src/api/java/com/jozufozu/flywheel/api/instance/InstancerProvider.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/instance/InstancerProvider.java rename to common/src/api/java/com/jozufozu/flywheel/api/instance/InstancerProvider.java diff --git a/common/src/api/java/com/jozufozu/flywheel/api/internal/DependencyInjection.java b/common/src/api/java/com/jozufozu/flywheel/api/internal/DependencyInjection.java new file mode 100644 index 000000000..403b4a785 --- /dev/null +++ b/common/src/api/java/com/jozufozu/flywheel/api/internal/DependencyInjection.java @@ -0,0 +1,42 @@ +package com.jozufozu.flywheel.api.internal; + +import java.lang.reflect.Constructor; + +// Adapted from https://github.com/CaffeineMC/sodium-fabric/blob/bf4fc9dab16e1cca07b2f23a1201c9bf237c8044/src/api/java/net/caffeinemc/mods/sodium/api/internal/DependencyInjection.java +public final class DependencyInjection { + private DependencyInjection() { + } + + public static T load(Class apiClass, String implClassName) { + Class implClass; + + try { + implClass = Class.forName(implClassName); + } catch (ReflectiveOperationException e) { + throw new RuntimeException("Could not find implementation", e); + } + + if (!apiClass.isAssignableFrom(implClass)) { + throw new RuntimeException("Class %s does not implement interface %s" + .formatted(implClass.getName(), apiClass.getName())); + } + + Constructor implConstructor; + + try { + implConstructor = implClass.getConstructor(); + } catch (ReflectiveOperationException e) { + throw new RuntimeException("Could not find default constructor", e); + } + + Object implInstance; + + try { + implInstance = implConstructor.newInstance(); + } catch (ReflectiveOperationException e) { + throw new RuntimeException("Could not instantiate implementation", e); + } + + return apiClass.cast(implInstance); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/api/internal/InternalFlywheelApi.java b/common/src/api/java/com/jozufozu/flywheel/api/internal/FlwApiLink.java similarity index 56% rename from src/main/java/com/jozufozu/flywheel/api/internal/InternalFlywheelApi.java rename to common/src/api/java/com/jozufozu/flywheel/api/internal/FlwApiLink.java index 72c368630..3f1e826aa 100644 --- a/src/main/java/com/jozufozu/flywheel/api/internal/InternalFlywheelApi.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/internal/FlwApiLink.java @@ -1,7 +1,5 @@ package com.jozufozu.flywheel.api.internal; -import java.lang.reflect.Constructor; - import org.jetbrains.annotations.Nullable; import com.jozufozu.flywheel.api.backend.Backend; @@ -12,8 +10,6 @@ import com.jozufozu.flywheel.api.visualization.BlockEntityVisualizer; import com.jozufozu.flywheel.api.visualization.EntityVisualizer; import com.jozufozu.flywheel.api.visualization.VisualizationManager; -import com.jozufozu.flywheel.lib.transform.PoseTransformStack; -import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.world.entity.Entity; @@ -22,43 +18,8 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; -public interface InternalFlywheelApi { - InternalFlywheelApi INSTANCE = load(); - - // Adapted from https://github.com/CaffeineMC/sodium-fabric/blob/bf4fc9dab16e1cca07b2f23a1201c9bf237c8044/src/api/java/net/caffeinemc/mods/sodium/api/internal/DependencyInjection.java - private static InternalFlywheelApi load() { - Class apiClass = InternalFlywheelApi.class; - Class implClass; - - try { - implClass = Class.forName("com.jozufozu.flywheel.impl.InternalFlywheelImpl"); - } catch (ReflectiveOperationException e) { - throw new RuntimeException("Could not find implementation", e); - } - - if (!apiClass.isAssignableFrom(implClass)) { - throw new RuntimeException("Class %s does not implement interface %s" - .formatted(implClass.getName(), apiClass.getName())); - } - - Constructor implConstructor; - - try { - implConstructor = implClass.getConstructor(); - } catch (ReflectiveOperationException e) { - throw new RuntimeException("Could not find default constructor", e); - } - - Object implInstance; - - try { - implInstance = implConstructor.newInstance(); - } catch (ReflectiveOperationException e) { - throw new RuntimeException("Could not instantiate implementation", e); - } - - return apiClass.cast(implInstance); - } +public interface FlwApiLink { + FlwApiLink INSTANCE = DependencyInjection.load(FlwApiLink.class, "com.jozufozu.flywheel.impl.FlwApiLinkImpl"); Registry createRegistry(); @@ -94,6 +55,4 @@ private static InternalFlywheelApi load() { void setVisualizer(BlockEntityType type, BlockEntityVisualizer visualizer); void setVisualizer(EntityType type, EntityVisualizer visualizer); - - PoseTransformStack getPoseTransformStackOf(PoseStack stack); } diff --git a/src/main/java/com/jozufozu/flywheel/api/internal/package-info.java b/common/src/api/java/com/jozufozu/flywheel/api/internal/package-info.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/internal/package-info.java rename to common/src/api/java/com/jozufozu/flywheel/api/internal/package-info.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/ArrayElementType.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/ArrayElementType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/ArrayElementType.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/ArrayElementType.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/ElementType.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/ElementType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/ElementType.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/ElementType.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/FloatRepr.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/FloatRepr.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/FloatRepr.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/FloatRepr.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/IntegerRepr.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/IntegerRepr.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/IntegerRepr.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/IntegerRepr.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/Layout.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/Layout.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/Layout.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/Layout.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/LayoutBuilder.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/LayoutBuilder.java similarity index 90% rename from src/main/java/com/jozufozu/flywheel/api/layout/LayoutBuilder.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/LayoutBuilder.java index 77d866199..db506cdab 100644 --- a/src/main/java/com/jozufozu/flywheel/api/layout/LayoutBuilder.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/layout/LayoutBuilder.java @@ -3,7 +3,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Range; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; @ApiStatus.NonExtendable public interface LayoutBuilder { @@ -26,6 +26,6 @@ public interface LayoutBuilder { Layout build(); static LayoutBuilder create() { - return InternalFlywheelApi.INSTANCE.createLayoutBuilder(); + return FlwApiLink.INSTANCE.createLayoutBuilder(); } } diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/MatrixElementType.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/MatrixElementType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/MatrixElementType.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/MatrixElementType.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/ScalarElementType.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/ScalarElementType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/ScalarElementType.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/ScalarElementType.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/UnsignedIntegerRepr.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/UnsignedIntegerRepr.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/UnsignedIntegerRepr.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/UnsignedIntegerRepr.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/ValueRepr.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/ValueRepr.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/ValueRepr.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/ValueRepr.java diff --git a/src/main/java/com/jozufozu/flywheel/api/layout/VectorElementType.java b/common/src/api/java/com/jozufozu/flywheel/api/layout/VectorElementType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/layout/VectorElementType.java rename to common/src/api/java/com/jozufozu/flywheel/api/layout/VectorElementType.java diff --git a/src/main/java/com/jozufozu/flywheel/api/material/CutoutShader.java b/common/src/api/java/com/jozufozu/flywheel/api/material/CutoutShader.java similarity index 58% rename from src/main/java/com/jozufozu/flywheel/api/material/CutoutShader.java rename to common/src/api/java/com/jozufozu/flywheel/api/material/CutoutShader.java index be469762f..43f8fada9 100644 --- a/src/main/java/com/jozufozu/flywheel/api/material/CutoutShader.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/material/CutoutShader.java @@ -1,12 +1,12 @@ package com.jozufozu.flywheel.api.material; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.jozufozu.flywheel.api.registry.Registry; import net.minecraft.resources.ResourceLocation; public interface CutoutShader { - static Registry REGISTRY = InternalFlywheelApi.INSTANCE.createRegistry(); + static Registry REGISTRY = FlwApiLink.INSTANCE.createRegistry(); ResourceLocation source(); } diff --git a/src/main/java/com/jozufozu/flywheel/api/material/DepthTest.java b/common/src/api/java/com/jozufozu/flywheel/api/material/DepthTest.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/material/DepthTest.java rename to common/src/api/java/com/jozufozu/flywheel/api/material/DepthTest.java diff --git a/src/main/java/com/jozufozu/flywheel/api/material/FogShader.java b/common/src/api/java/com/jozufozu/flywheel/api/material/FogShader.java similarity index 58% rename from src/main/java/com/jozufozu/flywheel/api/material/FogShader.java rename to common/src/api/java/com/jozufozu/flywheel/api/material/FogShader.java index 4d891afbd..c68759c1f 100644 --- a/src/main/java/com/jozufozu/flywheel/api/material/FogShader.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/material/FogShader.java @@ -1,12 +1,12 @@ package com.jozufozu.flywheel.api.material; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.jozufozu.flywheel.api.registry.Registry; import net.minecraft.resources.ResourceLocation; public interface FogShader { - static Registry REGISTRY = InternalFlywheelApi.INSTANCE.createRegistry(); + static Registry REGISTRY = FlwApiLink.INSTANCE.createRegistry(); ResourceLocation source(); } diff --git a/src/main/java/com/jozufozu/flywheel/api/material/Material.java b/common/src/api/java/com/jozufozu/flywheel/api/material/Material.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/material/Material.java rename to common/src/api/java/com/jozufozu/flywheel/api/material/Material.java diff --git a/src/main/java/com/jozufozu/flywheel/api/material/MaterialShaders.java b/common/src/api/java/com/jozufozu/flywheel/api/material/MaterialShaders.java similarity index 62% rename from src/main/java/com/jozufozu/flywheel/api/material/MaterialShaders.java rename to common/src/api/java/com/jozufozu/flywheel/api/material/MaterialShaders.java index 6cab5f4d1..dba708e43 100644 --- a/src/main/java/com/jozufozu/flywheel/api/material/MaterialShaders.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/material/MaterialShaders.java @@ -1,12 +1,12 @@ package com.jozufozu.flywheel.api.material; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.jozufozu.flywheel.api.registry.Registry; import net.minecraft.resources.ResourceLocation; public interface MaterialShaders { - static Registry REGISTRY = InternalFlywheelApi.INSTANCE.createRegistry(); + static Registry REGISTRY = FlwApiLink.INSTANCE.createRegistry(); ResourceLocation vertexShader(); diff --git a/src/main/java/com/jozufozu/flywheel/api/material/Transparency.java b/common/src/api/java/com/jozufozu/flywheel/api/material/Transparency.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/material/Transparency.java rename to common/src/api/java/com/jozufozu/flywheel/api/material/Transparency.java diff --git a/src/main/java/com/jozufozu/flywheel/api/material/WriteMask.java b/common/src/api/java/com/jozufozu/flywheel/api/material/WriteMask.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/material/WriteMask.java rename to common/src/api/java/com/jozufozu/flywheel/api/material/WriteMask.java diff --git a/src/main/java/com/jozufozu/flywheel/api/model/IndexSequence.java b/common/src/api/java/com/jozufozu/flywheel/api/model/IndexSequence.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/model/IndexSequence.java rename to common/src/api/java/com/jozufozu/flywheel/api/model/IndexSequence.java diff --git a/src/main/java/com/jozufozu/flywheel/api/model/Mesh.java b/common/src/api/java/com/jozufozu/flywheel/api/model/Mesh.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/model/Mesh.java rename to common/src/api/java/com/jozufozu/flywheel/api/model/Mesh.java diff --git a/src/main/java/com/jozufozu/flywheel/api/model/Model.java b/common/src/api/java/com/jozufozu/flywheel/api/model/Model.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/model/Model.java rename to common/src/api/java/com/jozufozu/flywheel/api/model/Model.java diff --git a/src/main/java/com/jozufozu/flywheel/api/registry/IdRegistry.java b/common/src/api/java/com/jozufozu/flywheel/api/registry/IdRegistry.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/registry/IdRegistry.java rename to common/src/api/java/com/jozufozu/flywheel/api/registry/IdRegistry.java diff --git a/src/main/java/com/jozufozu/flywheel/api/registry/Registry.java b/common/src/api/java/com/jozufozu/flywheel/api/registry/Registry.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/registry/Registry.java rename to common/src/api/java/com/jozufozu/flywheel/api/registry/Registry.java diff --git a/src/main/java/com/jozufozu/flywheel/api/task/Plan.java b/common/src/api/java/com/jozufozu/flywheel/api/task/Plan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/task/Plan.java rename to common/src/api/java/com/jozufozu/flywheel/api/task/Plan.java diff --git a/src/main/java/com/jozufozu/flywheel/api/task/TaskExecutor.java b/common/src/api/java/com/jozufozu/flywheel/api/task/TaskExecutor.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/task/TaskExecutor.java rename to common/src/api/java/com/jozufozu/flywheel/api/task/TaskExecutor.java diff --git a/src/main/java/com/jozufozu/flywheel/api/vertex/MutableVertexList.java b/common/src/api/java/com/jozufozu/flywheel/api/vertex/MutableVertexList.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/vertex/MutableVertexList.java rename to common/src/api/java/com/jozufozu/flywheel/api/vertex/MutableVertexList.java diff --git a/src/main/java/com/jozufozu/flywheel/api/vertex/VertexList.java b/common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexList.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/vertex/VertexList.java rename to common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexList.java diff --git a/src/main/java/com/jozufozu/flywheel/api/vertex/VertexView.java b/common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexView.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/vertex/VertexView.java rename to common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexView.java diff --git a/src/main/java/com/jozufozu/flywheel/api/vertex/VertexViewProvider.java b/common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexViewProvider.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/vertex/VertexViewProvider.java rename to common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexViewProvider.java diff --git a/src/main/java/com/jozufozu/flywheel/api/vertex/VertexViewProviderRegistry.java b/common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexViewProviderRegistry.java similarity index 62% rename from src/main/java/com/jozufozu/flywheel/api/vertex/VertexViewProviderRegistry.java rename to common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexViewProviderRegistry.java index 541e9248a..b173effb8 100644 --- a/src/main/java/com/jozufozu/flywheel/api/vertex/VertexViewProviderRegistry.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/vertex/VertexViewProviderRegistry.java @@ -1,6 +1,6 @@ package com.jozufozu.flywheel.api.vertex; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.mojang.blaze3d.vertex.VertexFormat; public final class VertexViewProviderRegistry { @@ -8,10 +8,10 @@ private VertexViewProviderRegistry() { } public static VertexViewProvider getProvider(VertexFormat format) { - return InternalFlywheelApi.INSTANCE.getVertexViewProvider(format); + return FlwApiLink.INSTANCE.getVertexViewProvider(format); } public static void setProvider(VertexFormat format, VertexViewProvider provider) { - InternalFlywheelApi.INSTANCE.setVertexViewProvider(format, provider); + FlwApiLink.INSTANCE.setVertexViewProvider(format, provider); } } diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/BlockEntityVisual.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/BlockEntityVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/BlockEntityVisual.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/BlockEntityVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/DistanceUpdateLimiter.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/DistanceUpdateLimiter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/DistanceUpdateLimiter.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/DistanceUpdateLimiter.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/DynamicVisual.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/DynamicVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/DynamicVisual.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/DynamicVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/Effect.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/Effect.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/Effect.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/Effect.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/EffectVisual.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/EffectVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/EffectVisual.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/EffectVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/EntityVisual.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/EntityVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/EntityVisual.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/EntityVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/LitVisual.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/LitVisual.java similarity index 88% rename from src/main/java/com/jozufozu/flywheel/api/visual/LitVisual.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/LitVisual.java index 13b3638ab..9408c99d9 100644 --- a/src/main/java/com/jozufozu/flywheel/api/visual/LitVisual.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/visual/LitVisual.java @@ -17,10 +17,10 @@ public interface LitVisual extends Visual { * *

Even if multiple sections are updated at the same time, this method will only be called once.

* - *

The implementation is free to parallelize calls to this method, as well as call into - * {@link DynamicVisual#beginFrame} simultaneously. It is safe to query/update light here, - * but you must ensure proper synchronization if you want to mutate anything outside this - * visual or anything that is also mutated by {@link DynamicVisual#beginFrame}.

+ *

The implementation is free to parallelize calls to this method, as well as execute the plan + * returned by {@link DynamicVisual#planFrame} simultaneously. It is safe to query/update light here, + * but you must ensure proper synchronization if you want to mutate anything outside this visual or + * anything that is also mutated within {@link DynamicVisual#planFrame}.

*/ void updateLight(); diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/TickableVisual.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/TickableVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/TickableVisual.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/TickableVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visual/Visual.java b/common/src/api/java/com/jozufozu/flywheel/api/visual/Visual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visual/Visual.java rename to common/src/api/java/com/jozufozu/flywheel/api/visual/Visual.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/BlockEntityVisualizer.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/BlockEntityVisualizer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visualization/BlockEntityVisualizer.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/BlockEntityVisualizer.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/EntityVisualizer.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/EntityVisualizer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visualization/EntityVisualizer.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/EntityVisualizer.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualEmbedding.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualEmbedding.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visualization/VisualEmbedding.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualEmbedding.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualManager.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualManager.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visualization/VisualManager.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualManager.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualizationContext.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizationContext.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visualization/VisualizationContext.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizationContext.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualizationLevel.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizationLevel.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/visualization/VisualizationLevel.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizationLevel.java diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualizationManager.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizationManager.java similarity index 87% rename from src/main/java/com/jozufozu/flywheel/api/visualization/VisualizationManager.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizationManager.java index a9f000e89..cf312b718 100644 --- a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualizationManager.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizationManager.java @@ -3,7 +3,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.jozufozu.flywheel.api.visual.Effect; import com.jozufozu.flywheel.api.visual.Visual; @@ -16,16 +16,16 @@ @ApiStatus.NonExtendable public interface VisualizationManager { static boolean supportsVisualization(@Nullable LevelAccessor level) { - return InternalFlywheelApi.INSTANCE.supportsVisualization(level); + return FlwApiLink.INSTANCE.supportsVisualization(level); } @Nullable static VisualizationManager get(@Nullable LevelAccessor level) { - return InternalFlywheelApi.INSTANCE.getVisualizationManager(level); + return FlwApiLink.INSTANCE.getVisualizationManager(level); } static VisualizationManager getOrThrow(@Nullable LevelAccessor level) { - return InternalFlywheelApi.INSTANCE.getVisualizationManagerOrThrow(level); + return FlwApiLink.INSTANCE.getVisualizationManagerOrThrow(level); } /** diff --git a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualizerRegistry.java b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizerRegistry.java similarity index 85% rename from src/main/java/com/jozufozu/flywheel/api/visualization/VisualizerRegistry.java rename to common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizerRegistry.java index 604aea42f..55e1b8e75 100644 --- a/src/main/java/com/jozufozu/flywheel/api/visualization/VisualizerRegistry.java +++ b/common/src/api/java/com/jozufozu/flywheel/api/visualization/VisualizerRegistry.java @@ -2,7 +2,7 @@ import org.jetbrains.annotations.Nullable; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; @@ -24,7 +24,7 @@ private VisualizerRegistry() { */ @Nullable public static BlockEntityVisualizer getVisualizer(BlockEntityType type) { - return InternalFlywheelApi.INSTANCE.getVisualizer(type); + return FlwApiLink.INSTANCE.getVisualizer(type); } /** @@ -35,7 +35,7 @@ public static BlockEntityVisualizer getVisual */ @Nullable public static EntityVisualizer getVisualizer(EntityType type) { - return InternalFlywheelApi.INSTANCE.getVisualizer(type); + return FlwApiLink.INSTANCE.getVisualizer(type); } /** @@ -45,7 +45,7 @@ public static EntityVisualizer getVisualizer(Entit * @param The type of the block entity. */ public static void setVisualizer(BlockEntityType type, BlockEntityVisualizer visualizer) { - InternalFlywheelApi.INSTANCE.setVisualizer(type, visualizer); + FlwApiLink.INSTANCE.setVisualizer(type, visualizer); } /** @@ -55,6 +55,6 @@ public static void setVisualizer(BlockEntityType type * @param The type of the entity. */ public static void setVisualizer(EntityType type, EntityVisualizer visualizer) { - InternalFlywheelApi.INSTANCE.setVisualizer(type, visualizer); + FlwApiLink.INSTANCE.setVisualizer(type, visualizer); } } diff --git a/src/main/java/com/jozufozu/flywheel/backend/Backends.java b/common/src/backend/java/com/jozufozu/flywheel/backend/Backends.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/backend/Backends.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/Backends.java index fa0ce5ac2..73698e28b 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/Backends.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/Backends.java @@ -1,6 +1,6 @@ package com.jozufozu.flywheel.backend; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.backend.Backend; import com.jozufozu.flywheel.backend.compile.IndirectPrograms; import com.jozufozu.flywheel.backend.compile.InstancingPrograms; diff --git a/common/src/backend/java/com/jozufozu/flywheel/backend/FlwBackend.java b/common/src/backend/java/com/jozufozu/flywheel/backend/FlwBackend.java new file mode 100644 index 000000000..8f2f5cb19 --- /dev/null +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/FlwBackend.java @@ -0,0 +1,18 @@ +package com.jozufozu.flywheel.backend; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jozufozu.flywheel.api.Flywheel; + +public final class FlwBackend { + public static final Logger LOGGER = LoggerFactory.getLogger(Flywheel.ID + "/backend"); + + private FlwBackend() { + } + + public static void init() { + ShaderIndices.init(); + Backends.init(); + } +} diff --git a/common/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplat.java b/common/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplat.java new file mode 100644 index 000000000..129515b48 --- /dev/null +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplat.java @@ -0,0 +1,13 @@ +package com.jozufozu.flywheel.backend; + +import com.jozufozu.flywheel.api.internal.DependencyInjection; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.state.BlockState; + +public interface FlwBackendXplat { + FlwBackendXplat INSTANCE = DependencyInjection.load(FlwBackendXplat.class, "com.jozufozu.flywheel.backend.FlwBackendXplatImpl"); + + int getLightEmission(BlockState state, BlockGetter level, BlockPos pos); +} diff --git a/src/main/java/com/jozufozu/flywheel/backend/InternalVertex.java b/common/src/backend/java/com/jozufozu/flywheel/backend/InternalVertex.java similarity index 96% rename from src/main/java/com/jozufozu/flywheel/backend/InternalVertex.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/InternalVertex.java index 8b6aa2cb3..bac7f639b 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/InternalVertex.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/InternalVertex.java @@ -2,7 +2,7 @@ import java.util.List; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.layout.FloatRepr; import com.jozufozu.flywheel.api.layout.Layout; import com.jozufozu.flywheel.api.layout.LayoutBuilder; diff --git a/src/main/java/com/jozufozu/flywheel/backend/LayoutAttributes.java b/common/src/backend/java/com/jozufozu/flywheel/backend/LayoutAttributes.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/LayoutAttributes.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/LayoutAttributes.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/Samplers.java b/common/src/backend/java/com/jozufozu/flywheel/backend/Samplers.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/Samplers.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/Samplers.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/ShaderIndices.java b/common/src/backend/java/com/jozufozu/flywheel/backend/ShaderIndices.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/ShaderIndices.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/ShaderIndices.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/ContextShader.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/ContextShader.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/ContextShader.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/ContextShader.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/FlwPrograms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwPrograms.java similarity index 89% rename from src/main/java/com/jozufozu/flywheel/backend/compile/FlwPrograms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwPrograms.java index 57188b533..cbe0b6877 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/FlwPrograms.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwPrograms.java @@ -7,7 +7,7 @@ import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.backend.ShaderIndices; import com.jozufozu.flywheel.backend.compile.component.UberShaderComponent; @@ -20,10 +20,9 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; public final class FlwPrograms { - public static final Logger LOGGER = LoggerFactory.getLogger(Flywheel.ID + "/shaders"); + public static final Logger LOGGER = LoggerFactory.getLogger(Flywheel.ID + "/backend/shaders"); private static final ResourceLocation COMPONENTS_HEADER_VERT = Flywheel.rl("internal/components_header.vert"); private static final ResourceLocation COMPONENTS_HEADER_FRAG = Flywheel.rl("internal/components_header.frag"); @@ -31,7 +30,7 @@ public final class FlwPrograms { private FlwPrograms() { } - private static void reload(ResourceManager resourceManager) { + static void reload(ResourceManager resourceManager) { // Reset the programs in case the ubershader load fails. InstancingPrograms.setInstance(null); IndirectPrograms.setInstance(null); @@ -119,16 +118,4 @@ private static UberShaderComponent createCutoutComponent(SourceLoader loader) { .switchOn(GlslExpr.variable("_flw_uberCutoutIndex")) .build(loader); } - - public static class ResourceReloadListener implements ResourceManagerReloadListener { - public static final ResourceReloadListener INSTANCE = new ResourceReloadListener(); - - private ResourceReloadListener() { - } - - @Override - public void onResourceManagerReload(ResourceManager manager) { - FlwPrograms.reload(manager); - } - } } diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/IndirectPrograms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/IndirectPrograms.java similarity index 85% rename from src/main/java/com/jozufozu/flywheel/backend/compile/IndirectPrograms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/IndirectPrograms.java index 3806b07d7..1856776db 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/IndirectPrograms.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/IndirectPrograms.java @@ -1,13 +1,12 @@ package com.jozufozu.flywheel.backend.compile; -import java.util.ArrayList; import java.util.List; import java.util.Map; import org.jetbrains.annotations.Nullable; import com.google.common.collect.ImmutableList; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.backend.compile.component.InstanceStructComponent; import com.jozufozu.flywheel.backend.compile.component.SsboInstanceComponent; @@ -53,22 +52,31 @@ private IndirectPrograms(Map pipeline, Map getExtensions(GlslVersion glslVersion) { - List extensions = new ArrayList<>(); + var extensions = ImmutableList.builder(); + if (glslVersion.compareTo(GlslVersion.V400) < 0) { + extensions.add("GL_ARB_gpu_shader5"); + } + if (glslVersion.compareTo(GlslVersion.V420) < 0) { + extensions.add("GL_ARB_shading_language_420pack"); + } if (glslVersion.compareTo(GlslVersion.V430) < 0) { extensions.add("GL_ARB_shader_storage_buffer_object"); } if (glslVersion.compareTo(GlslVersion.V460) < 0) { extensions.add("GL_ARB_shader_draw_parameters"); } - return extensions; + return extensions.build(); } private static List getComputeExtensions(GlslVersion glslVersion) { - List extensions = new ArrayList<>(); + var extensions = ImmutableList.builder(); + + extensions.addAll(EXTENSIONS); + if (glslVersion.compareTo(GlslVersion.V430) < 0) { extensions.add("GL_ARB_compute_shader"); } - return extensions; + return extensions.build(); } static void reload(ShaderSources sources, ImmutableList pipelineKeys, List vertexComponents, List fragmentComponents) { @@ -80,12 +88,12 @@ static void reload(ShaderSources sources, ImmutableList pipe var pipelineCompiler = PipelineCompiler.create(sources, Pipelines.INDIRECT, vertexComponents, fragmentComponents, EXTENSIONS); var cullingCompiler = createCullingCompiler(sources); - var applyCompiler = createUtilCompiler(sources); + var utilCompiler = createUtilCompiler(sources); try { var pipelineResult = pipelineCompiler.compileAndReportErrors(pipelineKeys); var cullingResult = cullingCompiler.compileAndReportErrors(createCullingKeys()); - var utils = applyCompiler.compileAndReportErrors(List.of(APPLY_SHADER_MAIN, SCATTER_SHADER_MAIN)); + var utils = utilCompiler.compileAndReportErrors(List.of(APPLY_SHADER_MAIN, SCATTER_SHADER_MAIN)); if (pipelineResult != null && cullingResult != null && utils != null) { newInstance = new IndirectPrograms(pipelineResult, cullingResult, utils.get(APPLY_SHADER_MAIN), utils.get(SCATTER_SHADER_MAIN)); @@ -96,39 +104,37 @@ static void reload(ShaderSources sources, ImmutableList pipe pipelineCompiler.delete(); cullingCompiler.delete(); - applyCompiler.delete(); + utilCompiler.delete(); setInstance(newInstance); } + /** + * A compiler for cull shaders, parameterized by the instance type. + */ private static CompilationHarness> createCullingCompiler(ShaderSources sources) { return CULL.program() .link(CULL.shader(GlCompat.MAX_GLSL_VERSION, ShaderType.COMPUTE) .nameMapper(instanceType -> "culling/" + ResourceUtil.toDebugFileNameNoExtension(instanceType.cullShader())) - .enableExtensions(EXTENSIONS) - .enableExtensions(COMPUTE_EXTENSIONS) + .requireExtensions(COMPUTE_EXTENSIONS) .define("_FLW_SUBGROUP_SIZE", GlCompat.SUBGROUP_SIZE) .withResource(CULL_SHADER_API_IMPL) .withComponent(InstanceStructComponent::new) .withResource(InstanceType::cullShader) .withComponent(SsboInstanceComponent::new) .withResource(CULL_SHADER_MAIN)) - .postLink((key, program) -> { - program.setUniformBlockBinding("_FlwFrameUniforms", Uniforms.FRAME_INDEX); - program.setUniformBlockBinding("_FlwFogUniforms", Uniforms.FOG_INDEX); - program.setUniformBlockBinding("_FlwOptionsUniforms", Uniforms.OPTIONS_INDEX); - program.setUniformBlockBinding("_FlwPlayerUniforms", Uniforms.PLAYER_INDEX); - program.setUniformBlockBinding("_FlwLevelUniforms", Uniforms.LEVEL_INDEX); - }) + .postLink((key, program) -> Uniforms.setUniformBlockBindings(program)) .harness("culling", sources); } + /** + * A compiler for utility shaders, directly compiles the shader at the resource location specified by the parameter. + */ private static CompilationHarness createUtilCompiler(ShaderSources sources) { return UTIL.program() .link(UTIL.shader(GlCompat.MAX_GLSL_VERSION, ShaderType.COMPUTE) .nameMapper(resourceLocation -> "utilities/" + ResourceUtil.toDebugFileNameNoExtension(resourceLocation)) - .enableExtensions(EXTENSIONS) - .enableExtensions(COMPUTE_EXTENSIONS) + .requireExtensions(COMPUTE_EXTENSIONS) .define("_FLW_SUBGROUP_SIZE", GlCompat.SUBGROUP_SIZE) .withResource(s -> s)) .harness("utilities", sources); diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/InstancingPrograms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/InstancingPrograms.java similarity index 81% rename from src/main/java/com/jozufozu/flywheel/backend/compile/InstancingPrograms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/InstancingPrograms.java index 8109f872c..ea29fe109 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/InstancingPrograms.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/InstancingPrograms.java @@ -9,11 +9,14 @@ import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.backend.gl.GlCompat; import com.jozufozu.flywheel.backend.gl.shader.GlProgram; +import com.jozufozu.flywheel.backend.glsl.GlslVersion; import com.jozufozu.flywheel.backend.glsl.ShaderSources; import com.jozufozu.flywheel.backend.glsl.SourceComponent; import com.jozufozu.flywheel.backend.util.AtomicReferenceCounted; public class InstancingPrograms extends AtomicReferenceCounted { + private static final List EXTENSIONS = getExtensions(GlCompat.MAX_GLSL_VERSION); + @Nullable private static InstancingPrograms instance; @@ -23,6 +26,14 @@ private InstancingPrograms(Map pipeline) { this.pipeline = pipeline; } + private static List getExtensions(GlslVersion glslVersion) { + var extensions = ImmutableList.builder(); + if (glslVersion.compareTo(GlslVersion.V330) < 0) { + extensions.add("GL_ARB_shader_bit_encoding"); + } + return extensions.build(); + } + static void reload(ShaderSources sources, ImmutableList pipelineKeys, List vertexComponents, List fragmentComponents) { if (!GlCompat.SUPPORTS_INSTANCING) { return; @@ -30,7 +41,7 @@ static void reload(ShaderSources sources, ImmutableList pipe InstancingPrograms newInstance = null; - var pipelineCompiler = PipelineCompiler.create(sources, Pipelines.INSTANCING, vertexComponents, fragmentComponents); + var pipelineCompiler = PipelineCompiler.create(sources, Pipelines.INSTANCING, vertexComponents, fragmentComponents, EXTENSIONS); try { var pipelineResult = pipelineCompiler.compileAndReportErrors(pipelineKeys); diff --git a/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutInterpreter.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/LayoutInterpreter.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/impl/layout/LayoutInterpreter.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/LayoutInterpreter.java index 3df4af593..41c5c3c15 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutInterpreter.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/LayoutInterpreter.java @@ -1,4 +1,4 @@ -package com.jozufozu.flywheel.impl.layout; +package com.jozufozu.flywheel.backend.compile; import com.jozufozu.flywheel.api.layout.ArrayElementType; import com.jozufozu.flywheel.api.layout.ElementType; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/Pipeline.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/Pipeline.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/Pipeline.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/Pipeline.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/PipelineCompiler.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/PipelineCompiler.java similarity index 81% rename from src/main/java/com/jozufozu/flywheel/backend/compile/PipelineCompiler.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/PipelineCompiler.java index a7dc27e3a..a964a8894 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/PipelineCompiler.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/PipelineCompiler.java @@ -1,10 +1,9 @@ package com.jozufozu.flywheel.backend.compile; import java.util.Collection; -import java.util.Collections; import java.util.List; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.backend.InternalVertex; import com.jozufozu.flywheel.backend.Samplers; import com.jozufozu.flywheel.backend.compile.component.InstanceStructComponent; @@ -37,7 +36,7 @@ static CompilationHarness create(ShaderSources sources, Pipe .nameLowerCase(); return "pipeline/" + pipeline.compilerMarker() + "/" + instance + "_" + context; }) - .enableExtensions(extensions) + .requireExtensions(extensions) .onCompile((key, comp) -> key.contextShader() .onCompile(comp)) .withResource(API_IMPL_VERT) @@ -55,7 +54,7 @@ static CompilationHarness create(ShaderSources sources, Pipe .nameLowerCase(); return "pipeline/" + pipeline.compilerMarker() + "/" + context; }) - .enableExtensions(extensions) + .requireExtensions(extensions) .enableExtension("GL_ARB_conservative_depth") .onCompile((key, comp) -> key.contextShader() .onCompile(comp)) @@ -71,11 +70,7 @@ static CompilationHarness create(ShaderSources sources, Pipe program.bindAttribLocation("_flw_aNormal", 5); }) .postLink((key, program) -> { - program.setUniformBlockBinding("_FlwFrameUniforms", Uniforms.FRAME_INDEX); - program.setUniformBlockBinding("_FlwFogUniforms", Uniforms.FOG_INDEX); - program.setUniformBlockBinding("_FlwOptionsUniforms", Uniforms.OPTIONS_INDEX); - program.setUniformBlockBinding("_FlwPlayerUniforms", Uniforms.PLAYER_INDEX); - program.setUniformBlockBinding("_FlwLevelUniforms", Uniforms.LEVEL_INDEX); + Uniforms.setUniformBlockBindings(program); program.bind(); @@ -91,8 +86,4 @@ static CompilationHarness create(ShaderSources sources, Pipe }) .harness(pipeline.compilerMarker(), sources); } - - static CompilationHarness create(ShaderSources sources, Pipeline pipeline, List vertexComponents, List fragmentComponents) { - return create(sources, pipeline, vertexComponents, fragmentComponents, Collections.emptyList()); - } } diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/PipelineProgramKey.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/PipelineProgramKey.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/PipelineProgramKey.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/PipelineProgramKey.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/Pipelines.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/Pipelines.java similarity index 95% rename from src/main/java/com/jozufozu/flywheel/backend/compile/Pipelines.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/Pipelines.java index 29978c1de..238d5e58b 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/Pipelines.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/Pipelines.java @@ -1,6 +1,6 @@ package com.jozufozu.flywheel.backend.compile; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.backend.Samplers; import com.jozufozu.flywheel.backend.compile.component.BufferTextureInstanceComponent; import com.jozufozu.flywheel.backend.compile.component.SsboInstanceComponent; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/SourceChecks.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/SourceChecks.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/SourceChecks.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/SourceChecks.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/component/BufferTextureInstanceComponent.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/BufferTextureInstanceComponent.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/backend/compile/component/BufferTextureInstanceComponent.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/BufferTextureInstanceComponent.java index b2218cbb9..1de3b5249 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/component/BufferTextureInstanceComponent.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/BufferTextureInstanceComponent.java @@ -2,7 +2,7 @@ import java.util.ArrayList; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.api.layout.Layout; import com.jozufozu.flywheel.backend.glsl.generate.FnSignature; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/component/InstanceAssemblerComponent.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/InstanceAssemblerComponent.java similarity index 99% rename from src/main/java/com/jozufozu/flywheel/backend/compile/component/InstanceAssemblerComponent.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/InstanceAssemblerComponent.java index 348146314..0513226c5 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/component/InstanceAssemblerComponent.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/InstanceAssemblerComponent.java @@ -19,10 +19,10 @@ import com.jozufozu.flywheel.api.layout.UnsignedIntegerRepr; import com.jozufozu.flywheel.api.layout.ValueRepr; import com.jozufozu.flywheel.api.layout.VectorElementType; +import com.jozufozu.flywheel.backend.compile.LayoutInterpreter; import com.jozufozu.flywheel.backend.glsl.SourceComponent; import com.jozufozu.flywheel.backend.glsl.generate.GlslBuilder; import com.jozufozu.flywheel.backend.glsl.generate.GlslExpr; -import com.jozufozu.flywheel.impl.layout.LayoutInterpreter; public abstract class InstanceAssemblerComponent implements SourceComponent { protected static final String STRUCT_NAME = "FlwInstance"; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/component/InstanceStructComponent.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/InstanceStructComponent.java similarity index 91% rename from src/main/java/com/jozufozu/flywheel/backend/compile/component/InstanceStructComponent.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/InstanceStructComponent.java index 49986e50f..123de197a 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/component/InstanceStructComponent.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/InstanceStructComponent.java @@ -3,12 +3,12 @@ import java.util.Collection; import java.util.Collections; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.api.layout.Layout; +import com.jozufozu.flywheel.backend.compile.LayoutInterpreter; import com.jozufozu.flywheel.backend.glsl.SourceComponent; import com.jozufozu.flywheel.backend.glsl.generate.GlslBuilder; -import com.jozufozu.flywheel.impl.layout.LayoutInterpreter; public class InstanceStructComponent implements SourceComponent { private static final String STRUCT_NAME = "FlwInstance"; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/component/SsboInstanceComponent.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/SsboInstanceComponent.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/backend/compile/component/SsboInstanceComponent.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/SsboInstanceComponent.java index a09e87ea7..f8244ffb1 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/component/SsboInstanceComponent.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/SsboInstanceComponent.java @@ -2,7 +2,7 @@ import java.util.ArrayList; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.api.layout.Layout; import com.jozufozu.flywheel.backend.engine.indirect.IndirectBuffers; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/component/StringSubstitutionComponent.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/StringSubstitutionComponent.java similarity index 96% rename from src/main/java/com/jozufozu/flywheel/backend/compile/component/StringSubstitutionComponent.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/StringSubstitutionComponent.java index 071865d80..58cbdb73b 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/component/StringSubstitutionComponent.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/StringSubstitutionComponent.java @@ -3,7 +3,7 @@ import java.util.Collection; import java.util.Map; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.backend.glsl.SourceComponent; public final class StringSubstitutionComponent implements SourceComponent { diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/component/UberShaderComponent.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/UberShaderComponent.java similarity index 99% rename from src/main/java/com/jozufozu/flywheel/backend/compile/component/UberShaderComponent.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/UberShaderComponent.java index e93c49af2..733b76776 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/component/UberShaderComponent.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/component/UberShaderComponent.java @@ -9,7 +9,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.backend.compile.core.SourceLoader; import com.jozufozu.flywheel.backend.glsl.SourceComponent; import com.jozufozu.flywheel.backend.glsl.SourceFile; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/Compilation.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/Compilation.java similarity index 95% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/Compilation.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/Compilation.java index 3fea1ffb7..d61c49133 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/core/Compilation.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/Compilation.java @@ -64,6 +64,12 @@ public void enableExtension(String ext) { .append(" : enable\n"); } + public void requireExtension(String ext) { + fullSource.append("#extension ") + .append(ext) + .append(" : require\n"); + } + public void define(String key, String value) { fullSource.append("#define ") .append(key) @@ -128,7 +134,7 @@ private static void dumpSource(String source, String fileName) { } } - private static boolean compiledSuccessfully(int handle) { + public static boolean compiledSuccessfully(int handle) { return GL20.glGetShaderi(handle, GL20.GL_COMPILE_STATUS) == GL20.GL_TRUE; } } diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/CompilationHarness.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/CompilationHarness.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/CompilationHarness.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/CompilationHarness.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/Compile.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/Compile.java similarity index 96% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/Compile.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/Compile.java index b74b71ff0..7642adb37 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/core/Compile.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/Compile.java @@ -113,6 +113,14 @@ public ShaderCompiler enableExtensions(Collection extensions) { }); } + public ShaderCompiler requireExtensions(Collection extensions) { + return onCompile(($, ctx) -> { + for (String extension : extensions) { + ctx.requireExtension(extension); + } + }); + } + @Nullable private GlShader compile(K key, ShaderCache compiler, SourceLoader loader) { var components = new ArrayList(); diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/CompilerStats.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/CompilerStats.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/CompilerStats.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/CompilerStats.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/FailedCompilation.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/FailedCompilation.java similarity index 99% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/FailedCompilation.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/FailedCompilation.java index a8c2c44da..27dc28cb1 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/compile/core/FailedCompilation.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/FailedCompilation.java @@ -8,7 +8,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.backend.glsl.SourceFile; import com.jozufozu.flywheel.backend.glsl.SourceLines; import com.jozufozu.flywheel.backend.glsl.error.ConsoleColors; diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/LinkResult.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/LinkResult.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/LinkResult.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/LinkResult.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/ProgramLinker.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/ProgramLinker.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/ProgramLinker.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/ProgramLinker.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/ShaderCache.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/ShaderCache.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/ShaderCache.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/ShaderCache.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/ShaderResult.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/ShaderResult.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/ShaderResult.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/ShaderResult.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/compile/core/SourceLoader.java b/common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/SourceLoader.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/compile/core/SourceLoader.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/compile/core/SourceLoader.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/AbstractInstancer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/AbstractInstancer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/AbstractInstancer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/AbstractInstancer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/CommonCrumbling.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/CommonCrumbling.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/CommonCrumbling.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/CommonCrumbling.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/DrawManager.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/DrawManager.java similarity index 98% rename from src/main/java/com/jozufozu/flywheel/backend/engine/DrawManager.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/DrawManager.java index c003a9264..404155aab 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/engine/DrawManager.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/DrawManager.java @@ -8,13 +8,13 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; -import com.jozufozu.flywheel.Flywheel; import com.jozufozu.flywheel.api.backend.Engine; import com.jozufozu.flywheel.api.event.RenderStage; import com.jozufozu.flywheel.api.instance.Instance; import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.api.instance.Instancer; import com.jozufozu.flywheel.api.model.Model; +import com.jozufozu.flywheel.backend.FlwBackend; import com.jozufozu.flywheel.backend.engine.embed.Environment; import com.jozufozu.flywheel.lib.util.Pair; @@ -98,7 +98,7 @@ private static boolean checkAndWarnEmptyModel(Model model) { .forEach(f -> builder.append("\n\t") .append(f.toString())); - Flywheel.LOGGER.warn(builder.toString()); + FlwBackend.LOGGER.warn(builder.toString()); return false; } diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/EngineImpl.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/EngineImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/EngineImpl.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/EngineImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/EnvironmentStorage.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/EnvironmentStorage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/EnvironmentStorage.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/EnvironmentStorage.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/GroupKey.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/GroupKey.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/GroupKey.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/GroupKey.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/IndexPool.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/IndexPool.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/IndexPool.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/IndexPool.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/InstanceHandleImpl.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/InstanceHandleImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/InstanceHandleImpl.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/InstanceHandleImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/InstancerKey.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/InstancerKey.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/InstancerKey.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/InstancerKey.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/InstancerProviderImpl.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/InstancerProviderImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/InstancerProviderImpl.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/InstancerProviderImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/MaterialEncoder.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/MaterialEncoder.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/MaterialEncoder.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/MaterialEncoder.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/MaterialRenderState.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/MaterialRenderState.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/MaterialRenderState.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/MaterialRenderState.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/MeshPool.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/MeshPool.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/MeshPool.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/MeshPool.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/TextureBinder.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/TextureBinder.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/TextureBinder.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/TextureBinder.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/AbstractEmbeddedEnvironment.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/AbstractEmbeddedEnvironment.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/AbstractEmbeddedEnvironment.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/AbstractEmbeddedEnvironment.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightTexture.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightTexture.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightTexture.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightTexture.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightVolume.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightVolume.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightVolume.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddedLightVolume.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddingUniforms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddingUniforms.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddingUniforms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/EmbeddingUniforms.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/Environment.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/Environment.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/Environment.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/Environment.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/GlobalEnvironment.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/GlobalEnvironment.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/GlobalEnvironment.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/GlobalEnvironment.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/NestedEmbeddedEnvironment.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/NestedEmbeddedEnvironment.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/NestedEmbeddedEnvironment.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/NestedEmbeddedEnvironment.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/embed/TopLevelEmbeddedEnvironment.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/TopLevelEmbeddedEnvironment.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/embed/TopLevelEmbeddedEnvironment.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/embed/TopLevelEmbeddedEnvironment.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectBuffers.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectBuffers.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectBuffers.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectBuffers.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectCullingGroup.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectCullingGroup.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectCullingGroup.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectCullingGroup.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDraw.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDraw.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDraw.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDraw.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDrawManager.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDrawManager.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDrawManager.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectDrawManager.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectInstancer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectInstancer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectInstancer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/IndirectInstancer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageArray.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageArray.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageArray.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageArray.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageBuffer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageBuffer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageBuffer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/ResizableStorageBuffer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/ScatterList.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/ScatterList.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/ScatterList.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/ScatterList.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/StagingBuffer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/StagingBuffer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/StagingBuffer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/StagingBuffer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/indirect/TransferList.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/TransferList.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/indirect/TransferList.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/indirect/TransferList.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDraw.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDraw.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDraw.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDraw.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDrawManager.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDrawManager.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDrawManager.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedDrawManager.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedInstancer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedInstancer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedInstancer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedInstancer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedRenderStage.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedRenderStage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedRenderStage.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/instancing/InstancedRenderStage.java diff --git a/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/DebugMode.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/DebugMode.java new file mode 100644 index 000000000..01ac310f1 --- /dev/null +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/DebugMode.java @@ -0,0 +1,26 @@ +package com.jozufozu.flywheel.backend.engine.uniform; + +import java.util.Locale; + +import com.mojang.serialization.Codec; + +import net.minecraft.util.StringRepresentable; + +public enum DebugMode implements StringRepresentable { + OFF, + NORMALS, + INSTANCE_ID, + LIGHT_LEVEL, + LIGHT_COLOR, + OVERLAY, + DIFFUSE, + LIGHT_VOLUME, + ; + + public static final Codec CODEC = StringRepresentable.fromEnum(DebugMode::values); + + @Override + public String getSerializedName() { + return name().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/FogUniforms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/FogUniforms.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/FogUniforms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/FogUniforms.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/FrameUniforms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/FrameUniforms.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/FrameUniforms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/FrameUniforms.java index b9437118d..e4467ab8e 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/FrameUniforms.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/FrameUniforms.java @@ -6,7 +6,7 @@ import com.jozufozu.flywheel.api.event.RenderContext; import com.jozufozu.flywheel.api.visualization.VisualizationManager; -import com.jozufozu.flywheel.config.DebugMode; +import com.jozufozu.flywheel.backend.mixin.LevelRendererAccessor; import com.jozufozu.flywheel.lib.math.MatrixMath; import net.minecraft.client.Camera; @@ -147,8 +147,7 @@ private static long writeCamera(long ptr) { } private static long writeTime(long ptr, RenderContext context) { - int ticks = context.renderer() - .getTicks(); + int ticks = ((LevelRendererAccessor) context.renderer()).flywheel$getTicks(); float partialTick = context.partialTick(); float renderTicks = ticks + partialTick; float renderSeconds = renderTicks / 20f; diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/LevelUniforms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/LevelUniforms.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/LevelUniforms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/LevelUniforms.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/OptionsUniforms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/OptionsUniforms.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/OptionsUniforms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/OptionsUniforms.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/PlayerUniforms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/PlayerUniforms.java similarity index 92% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/PlayerUniforms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/PlayerUniforms.java index 1d976226c..7bdfc44a6 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/PlayerUniforms.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/PlayerUniforms.java @@ -3,6 +3,7 @@ import org.jetbrains.annotations.Nullable; import com.jozufozu.flywheel.api.event.RenderContext; +import com.jozufozu.flywheel.backend.FlwBackendXplat; import com.jozufozu.flywheel.backend.mixin.AbstractClientPlayerAccessor; import net.minecraft.client.Minecraft; @@ -91,9 +92,10 @@ private static long writeHeldLight(long ptr, LocalPlayer player) { for (InteractionHand hand : InteractionHand.values()) { Item handItem = player.getItemInHand(hand).getItem(); - if (handItem instanceof BlockItem bitem) { - Block block = bitem.getBlock(); - int blockLight = block.defaultBlockState().getLightEmission(player.clientLevel, player.blockPosition()); + if (handItem instanceof BlockItem blockItem) { + Block block = blockItem.getBlock(); + int blockLight = FlwBackendXplat.INSTANCE + .getLightEmission(block.defaultBlockState(), player.clientLevel, player.blockPosition()); if (heldLight < blockLight) { heldLight = blockLight; } diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/UniformBuffer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/UniformBuffer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/UniformBuffer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/UniformBuffer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/UniformWriter.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/UniformWriter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/UniformWriter.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/UniformWriter.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/Uniforms.java b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/Uniforms.java similarity index 52% rename from src/main/java/com/jozufozu/flywheel/backend/engine/uniform/Uniforms.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/Uniforms.java index cd11491cc..057e506ed 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/engine/uniform/Uniforms.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/engine/uniform/Uniforms.java @@ -1,7 +1,7 @@ package com.jozufozu.flywheel.backend.engine.uniform; -import com.jozufozu.flywheel.api.event.ReloadLevelRendererEvent; import com.jozufozu.flywheel.api.event.RenderContext; +import com.jozufozu.flywheel.backend.gl.shader.GlProgram; public final class Uniforms { public static final int FRAME_INDEX = 0; @@ -10,6 +10,12 @@ public final class Uniforms { public static final int PLAYER_INDEX = 3; public static final int LEVEL_INDEX = 4; + public static final String FRAME_BLOCK_NAME = "_FlwFrameUniforms"; + public static final String FOG_BLOCK_NAME = "_FlwFogUniforms"; + public static final String OPTIONS_BLOCK_NAME = "_FlwOptionsUniforms"; + public static final String PLAYER_BLOCK_NAME = "_FlwPlayerUniforms"; + public static final String LEVEL_BLOCK_NAME = "_FlwLevelUniforms"; + private static final UniformBuffer[] ALL_BUFFERS = { FrameUniforms.BUFFER, FogUniforms.BUFFER, OptionsUniforms.BUFFER, PlayerUniforms.BUFFER, LevelUniforms.BUFFER }; private Uniforms() { @@ -33,7 +39,15 @@ private static void deleteAll() { } } - public static void onReloadLevelRenderer(ReloadLevelRendererEvent event) { + public static void setUniformBlockBindings(GlProgram program) { + program.setUniformBlockBinding(FRAME_BLOCK_NAME, FRAME_INDEX); + program.setUniformBlockBinding(FOG_BLOCK_NAME, FOG_INDEX); + program.setUniformBlockBinding(OPTIONS_BLOCK_NAME, OPTIONS_INDEX); + program.setUniformBlockBinding(PLAYER_BLOCK_NAME, PLAYER_INDEX); + program.setUniformBlockBinding(LEVEL_BLOCK_NAME, LEVEL_INDEX); + } + + public static void onReloadLevelRenderer() { deleteAll(); } } diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/Driver.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/Driver.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/Driver.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/Driver.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlCompat.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlCompat.java similarity index 63% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlCompat.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlCompat.java index fcf56a471..e284d6975 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/gl/GlCompat.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlCompat.java @@ -2,19 +2,36 @@ import java.nio.ByteBuffer; +import org.jetbrains.annotations.UnknownNullability; import org.lwjgl.PointerBuffer; import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL31C; import org.lwjgl.opengl.GLCapabilities; import org.lwjgl.opengl.KHRShaderSubgroup; import org.lwjgl.system.MemoryStack; +import com.jozufozu.flywheel.backend.FlwBackend; +import com.jozufozu.flywheel.backend.compile.core.Compilation; import com.jozufozu.flywheel.backend.glsl.GlslVersion; import com.jozufozu.flywheel.lib.math.MoreMath; public final class GlCompat { - public static final GLCapabilities CAPABILITIES = GL.getCapabilities(); + @UnknownNullability + public static final GLCapabilities CAPABILITIES; + static { + GLCapabilities caps; + try { + caps = GL.getCapabilities(); + } catch (IllegalStateException e) { + // This happens with vulkanmod installed. + FlwBackend.LOGGER.warn("Failed to get GL capabilities; default Flywheel backends will be disabled."); + caps = null; + } + CAPABILITIES = caps; + } + public static final Driver DRIVER = readVendorString(); public static final int SUBGROUP_SIZE = subgroupSize(); public static final boolean ALLOW_DSA = true; @@ -55,6 +72,10 @@ public static void safeShaderSource(int glId, CharSequence source) { } private static Driver readVendorString() { + if (CAPABILITIES == null) { + return Driver.UNKNOWN; + } + String vendor = GL20C.glGetString(GL20C.GL_VENDOR); if (vendor == null) { @@ -76,6 +97,9 @@ private static Driver readVendorString() { } private static int subgroupSize() { + if (CAPABILITIES == null) { + return 32; + } if (CAPABILITIES.GL_KHR_shader_subgroup) { return GL31C.glGetInteger(KHRShaderSubgroup.GL_SUBGROUP_SIZE_KHR); } @@ -88,38 +112,18 @@ private static int subgroupSize() { return DRIVER == Driver.AMD || DRIVER == Driver.MESA ? 64 : 32; } - private static GlslVersion maxGlslVersion() { - if (CAPABILITIES.OpenGL46) { - return GlslVersion.V460; - } else if (CAPABILITIES.OpenGL45) { - return GlslVersion.V450; - } else if (CAPABILITIES.OpenGL44) { - return GlslVersion.V440; - } else if (CAPABILITIES.OpenGL43) { - return GlslVersion.V430; - } else if (CAPABILITIES.OpenGL42) { - return GlslVersion.V420; - } else if (CAPABILITIES.OpenGL41) { - return GlslVersion.V410; - } else if (CAPABILITIES.OpenGL40) { - return GlslVersion.V400; - } else if (CAPABILITIES.OpenGL33) { - return GlslVersion.V330; - } else { - return GlslVersion.V150; - } - } - private static boolean isInstancingSupported() { - if (!CAPABILITIES.OpenGL33) { + if (CAPABILITIES == null) { return false; } - return true; + if (CAPABILITIES.OpenGL33) { + return true; + } + return CAPABILITIES.GL_ARB_shader_bit_encoding; } private static boolean isIndirectSupported() { - // The GL requirement cannot be lower because GL_ARB_compute_shader requires at least GL 4.2. - if (!CAPABILITIES.OpenGL42) { + if (CAPABILITIES == null) { return false; } if (CAPABILITIES.OpenGL46) { @@ -127,9 +131,54 @@ private static boolean isIndirectSupported() { } return CAPABILITIES.GL_ARB_compute_shader && CAPABILITIES.GL_ARB_direct_state_access + && CAPABILITIES.GL_ARB_gpu_shader5 && CAPABILITIES.GL_ARB_multi_bind && CAPABILITIES.GL_ARB_multi_draw_indirect && CAPABILITIES.GL_ARB_shader_draw_parameters - && CAPABILITIES.GL_ARB_shader_storage_buffer_object; + && CAPABILITIES.GL_ARB_shader_storage_buffer_object + && CAPABILITIES.GL_ARB_shading_language_420pack + && CAPABILITIES.GL_ARB_vertex_attrib_binding; + } + + /** + * Try to compile a shader with progressively lower glsl versions. + * The first version to compile successfully is returned. + * @return The highest glsl version that could be compiled. + */ + private static GlslVersion maxGlslVersion() { + if (CAPABILITIES == null) { + return GlslVersion.V150; + } + + var glslVersions = GlslVersion.values(); + // No need to test glsl 150 as that is guaranteed to be supported by MC. + for (int i = glslVersions.length - 1; i > 0; i--) { + var version = glslVersions[i]; + + if (canCompileVersion(version)) { + return version; + } + } + + return GlslVersion.V150; + } + + private static boolean canCompileVersion(GlslVersion version) { + int handle = GL20.glCreateShader(GL20.GL_VERTEX_SHADER); + + // Compile the simplest possible shader. + var source = """ + #version %d + void main() {} + """.formatted(version.version); + + safeShaderSource(handle, source); + GL20.glCompileShader(handle); + + boolean success = Compilation.compiledSuccessfully(handle); + + GL20.glDeleteShader(handle); + + return success; } } diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlFence.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlFence.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlFence.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlFence.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlNumericType.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlNumericType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlNumericType.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlNumericType.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlObject.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlObject.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlObject.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlObject.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlPrimitive.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlPrimitive.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlPrimitive.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlPrimitive.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlStateTracker.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlStateTracker.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlStateTracker.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlStateTracker.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlTexture.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlTexture.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlTexture.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlTexture.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/GlTextureUnit.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlTextureUnit.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/GlTextureUnit.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/GlTextureUnit.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/TextureBuffer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/TextureBuffer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/TextureBuffer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/TextureBuffer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArray.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArray.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArray.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArray.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayDSA.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayDSA.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayDSA.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayDSA.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayGL3.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayGL3.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayGL3.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArrayGL3.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArraySeparateAttributes.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArraySeparateAttributes.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArraySeparateAttributes.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/GlVertexArraySeparateAttributes.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/array/VertexAttribute.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/VertexAttribute.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/array/VertexAttribute.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/array/VertexAttribute.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/buffer/Buffer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/Buffer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/buffer/Buffer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/Buffer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/buffer/GlBuffer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/GlBuffer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/buffer/GlBuffer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/GlBuffer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferType.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferType.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferType.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferUsage.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferUsage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferUsage.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/buffer/GlBufferUsage.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/error/GlError.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/error/GlError.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/error/GlError.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/error/GlError.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/error/GlException.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/error/GlException.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/error/GlException.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/error/GlException.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/shader/GlProgram.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/shader/GlProgram.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/shader/GlProgram.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/shader/GlProgram.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/shader/GlShader.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/shader/GlShader.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/shader/GlShader.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/shader/GlShader.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/gl/shader/ShaderType.java b/common/src/backend/java/com/jozufozu/flywheel/backend/gl/shader/ShaderType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/gl/shader/ShaderType.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/gl/shader/ShaderType.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/GlslVersion.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/GlslVersion.java similarity index 87% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/GlslVersion.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/GlslVersion.java index e12d29bd5..11453eb07 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/glsl/GlslVersion.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/GlslVersion.java @@ -1,10 +1,6 @@ package com.jozufozu.flywheel.backend.glsl; public enum GlslVersion { - V110(110), - V120(120), - V130(130), - V140(140), V150(150), V330(330), V400(400), diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/LoadError.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/LoadError.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/LoadError.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/LoadError.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/LoadResult.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/LoadResult.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/LoadResult.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/LoadResult.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/ShaderSources.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/ShaderSources.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/ShaderSources.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/ShaderSources.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/SourceComponent.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/SourceComponent.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/SourceComponent.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/SourceComponent.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/SourceFile.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/SourceFile.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/SourceFile.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/SourceFile.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/SourceLines.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/SourceLines.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/SourceLines.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/SourceLines.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/ConsoleColors.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/ConsoleColors.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/ConsoleColors.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/ConsoleColors.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/ErrorBuilder.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/ErrorBuilder.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/ErrorBuilder.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/ErrorBuilder.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/ErrorLevel.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/ErrorLevel.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/ErrorLevel.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/ErrorLevel.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/Divider.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/Divider.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/Divider.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/Divider.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/ErrorLine.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/ErrorLine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/ErrorLine.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/ErrorLine.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/FileLine.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/FileLine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/FileLine.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/FileLine.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/HeaderLine.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/HeaderLine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/HeaderLine.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/HeaderLine.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/NestedLine.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/NestedLine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/NestedLine.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/NestedLine.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/SourceLine.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/SourceLine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/SourceLine.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/SourceLine.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/SpanHighlightLine.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/SpanHighlightLine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/SpanHighlightLine.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/SpanHighlightLine.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/TextLine.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/TextLine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/error/lines/TextLine.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/error/lines/TextLine.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/BinOp.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/BinOp.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/BinOp.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/BinOp.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/FnSignature.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/FnSignature.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/FnSignature.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/FnSignature.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBlock.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBlock.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBlock.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBlock.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBuilder.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBuilder.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBuilder.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslBuilder.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslExpr.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslExpr.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslExpr.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslExpr.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslFn.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslFn.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslFn.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslFn.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStmt.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStmt.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStmt.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStmt.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStruct.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStruct.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStruct.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslStruct.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslSwitch.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslSwitch.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslSwitch.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslSwitch.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslUniformBlock.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslUniformBlock.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslUniformBlock.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslUniformBlock.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslVertexInput.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslVertexInput.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/generate/GlslVertexInput.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/generate/GlslVertexInput.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/parse/Import.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/Import.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/parse/Import.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/Import.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderField.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderField.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderField.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderField.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderFunction.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderFunction.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderFunction.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderFunction.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderStruct.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderStruct.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderStruct.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderStruct.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderVariable.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderVariable.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderVariable.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/ShaderVariable.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/parse/StructField.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/StructField.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/parse/StructField.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/parse/StructField.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/span/CharPos.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/CharPos.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/span/CharPos.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/CharPos.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/span/ErrorSpan.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/ErrorSpan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/span/ErrorSpan.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/ErrorSpan.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/span/Span.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/Span.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/span/Span.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/Span.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/glsl/span/StringSpan.java b/common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/StringSpan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/glsl/span/StringSpan.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/glsl/span/StringSpan.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/mixin/AbstractClientPlayerAccessor.java b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/AbstractClientPlayerAccessor.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/mixin/AbstractClientPlayerAccessor.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/mixin/AbstractClientPlayerAccessor.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/mixin/GlStateManagerMixin.java b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/GlStateManagerMixin.java similarity index 95% rename from src/main/java/com/jozufozu/flywheel/backend/mixin/GlStateManagerMixin.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/mixin/GlStateManagerMixin.java index 695e4399d..2c0b4ecdb 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/mixin/GlStateManagerMixin.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/GlStateManagerMixin.java @@ -9,7 +9,7 @@ import com.jozufozu.flywheel.backend.gl.buffer.GlBufferType; import com.mojang.blaze3d.platform.GlStateManager; -@Mixin(GlStateManager.class) +@Mixin(value = GlStateManager.class, remap = false) abstract class GlStateManagerMixin { @Inject(method = "_glBindBuffer(II)V", at = @At("RETURN")) private static void flywheel$onBindBuffer(int target, int buffer, CallbackInfo ci) { diff --git a/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/LevelRendererAccessor.java b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/LevelRendererAccessor.java new file mode 100644 index 000000000..a22055f7b --- /dev/null +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/LevelRendererAccessor.java @@ -0,0 +1,12 @@ +package com.jozufozu.flywheel.backend.mixin; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import net.minecraft.client.renderer.LevelRenderer; + +@Mixin(LevelRenderer.class) +public interface LevelRendererAccessor { + @Accessor("ticks") + int flywheel$getTicks(); +} diff --git a/src/main/java/com/jozufozu/flywheel/backend/mixin/OptionsMixin.java b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/OptionsMixin.java similarity index 95% rename from src/main/java/com/jozufozu/flywheel/backend/mixin/OptionsMixin.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/mixin/OptionsMixin.java index e14e279df..8543d8162 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/mixin/OptionsMixin.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/OptionsMixin.java @@ -10,7 +10,7 @@ import net.minecraft.client.Options; @Mixin(Options.class) -public class OptionsMixin { +abstract class OptionsMixin { @Inject(method = "load()V", at = @At("RETURN")) private void flywheel$onLoad(CallbackInfo ci) { OptionsUniforms.update((Options) (Object) this); diff --git a/src/main/java/com/jozufozu/flywheel/backend/mixin/RenderSystemMixin.java b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/RenderSystemMixin.java similarity index 96% rename from src/main/java/com/jozufozu/flywheel/backend/mixin/RenderSystemMixin.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/mixin/RenderSystemMixin.java index c29da817b..fb12d286d 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/mixin/RenderSystemMixin.java +++ b/common/src/backend/java/com/jozufozu/flywheel/backend/mixin/RenderSystemMixin.java @@ -9,7 +9,7 @@ import com.jozufozu.flywheel.backend.gl.GlCompat; import com.mojang.blaze3d.systems.RenderSystem; -@Mixin(RenderSystem.class) +@Mixin(value = RenderSystem.class, remap = false) abstract class RenderSystemMixin { @Inject(method = "initRenderer(IZ)V", at = @At("RETURN")) private static void flywheel$onInitRenderer(CallbackInfo ci) { diff --git a/src/main/java/com/jozufozu/flywheel/backend/util/AtomicReferenceCounted.java b/common/src/backend/java/com/jozufozu/flywheel/backend/util/AtomicReferenceCounted.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/util/AtomicReferenceCounted.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/util/AtomicReferenceCounted.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/util/MemoryBuffer.java b/common/src/backend/java/com/jozufozu/flywheel/backend/util/MemoryBuffer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/util/MemoryBuffer.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/util/MemoryBuffer.java diff --git a/src/main/java/com/jozufozu/flywheel/backend/util/ReferenceCounted.java b/common/src/backend/java/com/jozufozu/flywheel/backend/util/ReferenceCounted.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/backend/util/ReferenceCounted.java rename to common/src/backend/java/com/jozufozu/flywheel/backend/util/ReferenceCounted.java diff --git a/src/main/resources/assets/flywheel/flywheel/internal/api_impl.frag b/common/src/backend/resources/assets/flywheel/flywheel/internal/api_impl.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/api_impl.frag rename to common/src/backend/resources/assets/flywheel/flywheel/internal/api_impl.frag diff --git a/src/main/resources/assets/flywheel/flywheel/internal/api_impl.vert b/common/src/backend/resources/assets/flywheel/flywheel/internal/api_impl.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/api_impl.vert rename to common/src/backend/resources/assets/flywheel/flywheel/internal/api_impl.vert diff --git a/src/main/resources/assets/flywheel/flywheel/internal/colorizer.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/colorizer.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/colorizer.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/colorizer.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/common.frag b/common/src/backend/resources/assets/flywheel/flywheel/internal/common.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/common.frag rename to common/src/backend/resources/assets/flywheel/flywheel/internal/common.frag diff --git a/src/main/resources/assets/flywheel/flywheel/internal/common.vert b/common/src/backend/resources/assets/flywheel/flywheel/internal/common.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/common.vert rename to common/src/backend/resources/assets/flywheel/flywheel/internal/common.vert diff --git a/src/main/resources/assets/flywheel/flywheel/internal/components_header.frag b/common/src/backend/resources/assets/flywheel/flywheel/internal/components_header.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/components_header.frag rename to common/src/backend/resources/assets/flywheel/flywheel/internal/components_header.frag diff --git a/src/main/resources/assets/flywheel/flywheel/internal/components_header.vert b/common/src/backend/resources/assets/flywheel/flywheel/internal/components_header.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/components_header.vert rename to common/src/backend/resources/assets/flywheel/flywheel/internal/components_header.vert diff --git a/src/main/resources/assets/flywheel/flywheel/internal/diffuse.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/diffuse.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/diffuse.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/diffuse.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/fog_distance.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/fog_distance.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/fog_distance.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/fog_distance.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/apply.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/apply.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/apply.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/apply.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/buffer_bindings.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/buffer_bindings.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/buffer_bindings.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/buffer_bindings.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/cull.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/cull.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/cull.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/cull.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/cull_api_impl.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/cull_api_impl.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/cull_api_impl.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/cull_api_impl.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/draw_command.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/draw_command.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/draw_command.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/draw_command.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/main.frag b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/main.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/main.frag rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/main.frag diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/main.vert b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/main.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/main.vert rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/main.vert diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/model_descriptor.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/model_descriptor.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/model_descriptor.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/model_descriptor.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/indirect/scatter.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/scatter.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/indirect/scatter.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/indirect/scatter.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/instancing/main.frag b/common/src/backend/resources/assets/flywheel/flywheel/internal/instancing/main.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/instancing/main.frag rename to common/src/backend/resources/assets/flywheel/flywheel/internal/instancing/main.frag diff --git a/src/main/resources/assets/flywheel/flywheel/internal/instancing/main.vert b/common/src/backend/resources/assets/flywheel/flywheel/internal/instancing/main.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/instancing/main.vert rename to common/src/backend/resources/assets/flywheel/flywheel/internal/instancing/main.vert diff --git a/src/main/resources/assets/flywheel/flywheel/internal/material.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/material.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/material.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/material.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/packed_material.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/packed_material.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/packed_material.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/packed_material.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/uniforms/fog.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/fog.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/uniforms/fog.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/fog.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/uniforms/frame.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/frame.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/uniforms/frame.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/frame.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/uniforms/level.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/level.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/uniforms/level.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/level.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/uniforms/options.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/options.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/uniforms/options.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/options.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/uniforms/player.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/player.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/uniforms/player.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/player.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/uniforms/uniforms.glsl b/common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/uniforms.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/uniforms/uniforms.glsl rename to common/src/backend/resources/assets/flywheel/flywheel/internal/uniforms/uniforms.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/internal/vertex_input.vert b/common/src/backend/resources/assets/flywheel/flywheel/internal/vertex_input.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/internal/vertex_input.vert rename to common/src/backend/resources/assets/flywheel/flywheel/internal/vertex_input.vert diff --git a/src/main/resources/flywheel.backend.mixins.json b/common/src/backend/resources/flywheel.backend.mixins.json similarity index 71% rename from src/main/resources/flywheel.backend.mixins.json rename to common/src/backend/resources/flywheel.backend.mixins.json index 25dbe6fb9..9aef02424 100644 --- a/src/main/resources/flywheel.backend.mixins.json +++ b/common/src/backend/resources/flywheel.backend.mixins.json @@ -3,14 +3,12 @@ "minVersion": "0.8", "package": "com.jozufozu.flywheel.backend.mixin", "compatibilityLevel": "JAVA_17", - "refmap": "flywheel.refmap.json", + "refmap": "backend-flywheel.refmap.json", "client": [ "AbstractClientPlayerAccessor", - "GameRendererAccessor", "GlStateManagerMixin", - "LightTextureAccessor", + "LevelRendererAccessor", "OptionsMixin", - "OverlayTextureAccessor", "RenderSystemMixin" ], "injectors": { diff --git a/src/main/java/com/jozufozu/flywheel/lib/backend/SimpleBackend.java b/common/src/lib/java/com/jozufozu/flywheel/lib/backend/SimpleBackend.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/backend/SimpleBackend.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/backend/SimpleBackend.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/box/Box.java b/common/src/lib/java/com/jozufozu/flywheel/lib/box/Box.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/box/Box.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/box/Box.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/box/MutableBox.java b/common/src/lib/java/com/jozufozu/flywheel/lib/box/MutableBox.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/box/MutableBox.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/box/MutableBox.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/AbstractInstance.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/AbstractInstance.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/instance/AbstractInstance.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/AbstractInstance.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/ColoredLitInstance.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/ColoredLitInstance.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/instance/ColoredLitInstance.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/ColoredLitInstance.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/FlatLit.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/FlatLit.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/instance/FlatLit.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/FlatLit.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/InstanceTypes.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/InstanceTypes.java similarity index 99% rename from src/main/java/com/jozufozu/flywheel/lib/instance/InstanceTypes.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/InstanceTypes.java index 2f6e8ce47..8a56570ff 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/instance/InstanceTypes.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/InstanceTypes.java @@ -3,7 +3,7 @@ import org.jetbrains.annotations.ApiStatus; import org.lwjgl.system.MemoryUtil; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.instance.InstanceType; import com.jozufozu.flywheel.api.layout.FloatRepr; import com.jozufozu.flywheel.api.layout.IntegerRepr; diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/OrientedInstance.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/OrientedInstance.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/instance/OrientedInstance.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/OrientedInstance.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/ShadowInstance.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/ShadowInstance.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/instance/ShadowInstance.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/ShadowInstance.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/SimpleInstanceType.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/SimpleInstanceType.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/instance/SimpleInstanceType.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/SimpleInstanceType.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/instance/TransformedInstance.java b/common/src/lib/java/com/jozufozu/flywheel/lib/instance/TransformedInstance.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/instance/TransformedInstance.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/instance/TransformedInstance.java diff --git a/common/src/lib/java/com/jozufozu/flywheel/lib/internal/FlwLibLink.java b/common/src/lib/java/com/jozufozu/flywheel/lib/internal/FlwLibLink.java new file mode 100644 index 000000000..cf30466a1 --- /dev/null +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/internal/FlwLibLink.java @@ -0,0 +1,15 @@ +package com.jozufozu.flywheel.lib.internal; + +import org.slf4j.Logger; + +import com.jozufozu.flywheel.api.internal.DependencyInjection; +import com.jozufozu.flywheel.lib.transform.PoseTransformStack; +import com.mojang.blaze3d.vertex.PoseStack; + +public interface FlwLibLink { + FlwLibLink INSTANCE = DependencyInjection.load(FlwLibLink.class, "com.jozufozu.flywheel.impl.FlwLibLinkImpl"); + + Logger getLogger(); + + PoseTransformStack getPoseTransformStackOf(PoseStack stack); +} diff --git a/common/src/lib/java/com/jozufozu/flywheel/lib/internal/FlwLibXplat.java b/common/src/lib/java/com/jozufozu/flywheel/lib/internal/FlwLibXplat.java new file mode 100644 index 000000000..0fb9bc58a --- /dev/null +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/internal/FlwLibXplat.java @@ -0,0 +1,30 @@ +package com.jozufozu.flywheel.lib.internal; + +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.api.internal.DependencyInjection; +import com.jozufozu.flywheel.lib.model.baked.BakedModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.BlockModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.MultiBlockModelBuilder; +import com.jozufozu.flywheel.lib.util.ShadersModHandler; + +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; + +public interface FlwLibXplat { + FlwLibXplat INSTANCE = DependencyInjection.load(FlwLibXplat.class, "com.jozufozu.flywheel.impl.FlwLibXplatImpl"); + + BlockRenderDispatcher createVanillaBlockRenderDispatcher(); + + BakedModelBuilder createBakedModelBuilder(BakedModel bakedModel); + + BlockModelBuilder createBlockModelBuilder(BlockState state); + + MultiBlockModelBuilder createMultiBlockModelBuilder(BlockAndTintGetter level, Iterable positions); + + @Nullable + ShadersModHandler.InternalHandler createIrisHandler(); +} diff --git a/common/src/lib/java/com/jozufozu/flywheel/lib/internal/package-info.java b/common/src/lib/java/com/jozufozu/flywheel/lib/internal/package-info.java new file mode 100644 index 000000000..b4efe3fa3 --- /dev/null +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/internal/package-info.java @@ -0,0 +1,12 @@ +@ApiStatus.Internal +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package com.jozufozu.flywheel.lib.internal; + +import javax.annotation.ParametersAreNonnullByDefault; + +import org.jetbrains.annotations.ApiStatus; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; diff --git a/src/main/java/com/jozufozu/flywheel/lib/light/LightPacking.java b/common/src/lib/java/com/jozufozu/flywheel/lib/light/LightPacking.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/light/LightPacking.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/light/LightPacking.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/light/LightVolume.java b/common/src/lib/java/com/jozufozu/flywheel/lib/light/LightVolume.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/light/LightVolume.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/light/LightVolume.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/CutoutShaders.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/CutoutShaders.java similarity index 96% rename from src/main/java/com/jozufozu/flywheel/lib/material/CutoutShaders.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/CutoutShaders.java index 8ce015841..e5694e97d 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/material/CutoutShaders.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/material/CutoutShaders.java @@ -2,7 +2,7 @@ import org.jetbrains.annotations.ApiStatus; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.material.CutoutShader; public class CutoutShaders { diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/FogShaders.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/FogShaders.java similarity index 93% rename from src/main/java/com/jozufozu/flywheel/lib/material/FogShaders.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/FogShaders.java index 9c23ae718..7f3630a4e 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/material/FogShaders.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/material/FogShaders.java @@ -2,7 +2,7 @@ import org.jetbrains.annotations.ApiStatus; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.material.FogShader; public class FogShaders { diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/Materials.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/Materials.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/material/Materials.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/Materials.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/SimpleCutoutShader.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleCutoutShader.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/material/SimpleCutoutShader.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleCutoutShader.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/SimpleFogShader.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleFogShader.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/material/SimpleFogShader.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleFogShader.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/SimpleMaterial.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleMaterial.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/material/SimpleMaterial.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleMaterial.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/SimpleMaterialShaders.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleMaterialShaders.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/material/SimpleMaterialShaders.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/SimpleMaterialShaders.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/material/StandardMaterialShaders.java b/common/src/lib/java/com/jozufozu/flywheel/lib/material/StandardMaterialShaders.java similarity index 95% rename from src/main/java/com/jozufozu/flywheel/lib/material/StandardMaterialShaders.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/material/StandardMaterialShaders.java index bfea555bd..715c476b1 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/material/StandardMaterialShaders.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/material/StandardMaterialShaders.java @@ -2,7 +2,7 @@ import org.jetbrains.annotations.ApiStatus; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.material.MaterialShaders; public final class StandardMaterialShaders { diff --git a/src/main/java/com/jozufozu/flywheel/lib/math/MatrixMath.java b/common/src/lib/java/com/jozufozu/flywheel/lib/math/MatrixMath.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/math/MatrixMath.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/math/MatrixMath.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/math/MoreMath.java b/common/src/lib/java/com/jozufozu/flywheel/lib/math/MoreMath.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/math/MoreMath.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/math/MoreMath.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/math/RenderMath.java b/common/src/lib/java/com/jozufozu/flywheel/lib/math/RenderMath.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/math/RenderMath.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/math/RenderMath.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/memory/AbstractMemoryBlockImpl.java b/common/src/lib/java/com/jozufozu/flywheel/lib/memory/AbstractMemoryBlockImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/memory/AbstractMemoryBlockImpl.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/memory/AbstractMemoryBlockImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/memory/DebugMemoryBlockImpl.java b/common/src/lib/java/com/jozufozu/flywheel/lib/memory/DebugMemoryBlockImpl.java similarity index 96% rename from src/main/java/com/jozufozu/flywheel/lib/memory/DebugMemoryBlockImpl.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/memory/DebugMemoryBlockImpl.java index b91dc53a6..e10b2023a 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/memory/DebugMemoryBlockImpl.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/memory/DebugMemoryBlockImpl.java @@ -2,7 +2,7 @@ import java.lang.ref.Cleaner; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.lib.internal.FlwLibLink; import com.jozufozu.flywheel.lib.util.StringUtil; class DebugMemoryBlockImpl extends AbstractMemoryBlockImpl { @@ -91,7 +91,7 @@ public void run() { builder.append("\n\t"); builder.append(frame); } - Flywheel.LOGGER.warn(builder.toString()); + FlwLibLink.INSTANCE.getLogger().warn(builder.toString()); FlwMemoryTracker.free(ptr); FlwMemoryTracker._freeCPUMemory(size); diff --git a/src/main/java/com/jozufozu/flywheel/lib/memory/FlwMemoryTracker.java b/common/src/lib/java/com/jozufozu/flywheel/lib/memory/FlwMemoryTracker.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/memory/FlwMemoryTracker.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/memory/FlwMemoryTracker.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/memory/MemoryBlock.java b/common/src/lib/java/com/jozufozu/flywheel/lib/memory/MemoryBlock.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/memory/MemoryBlock.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/memory/MemoryBlock.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/memory/MemoryBlockImpl.java b/common/src/lib/java/com/jozufozu/flywheel/lib/memory/MemoryBlockImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/memory/MemoryBlockImpl.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/memory/MemoryBlockImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/memory/TrackedMemoryBlockImpl.java b/common/src/lib/java/com/jozufozu/flywheel/lib/memory/TrackedMemoryBlockImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/memory/TrackedMemoryBlockImpl.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/memory/TrackedMemoryBlockImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/LineModelBuilder.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/LineModelBuilder.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/model/LineModelBuilder.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/LineModelBuilder.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/ModelCache.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelCache.java similarity index 82% rename from src/main/java/com/jozufozu/flywheel/lib/model/ModelCache.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelCache.java index 9f12cfc0b..016f706aa 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/ModelCache.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelCache.java @@ -8,7 +8,6 @@ import org.jetbrains.annotations.ApiStatus; -import com.jozufozu.flywheel.api.event.EndClientResourceReloadEvent; import com.jozufozu.flywheel.api.model.Model; public class ModelCache { @@ -18,7 +17,10 @@ public class ModelCache { public ModelCache(Function factory) { this.factory = factory; - ALL.add(this); + + synchronized (ALL) { + ALL.add(this); + } } public Model get(T key) { @@ -31,7 +33,7 @@ public void clear() { } @ApiStatus.Internal - public static void onEndClientResourceReload(EndClientResourceReloadEvent event) { + public static void onEndClientResourceReload() { for (ModelCache cache : ALL) { cache.clear(); } diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/ModelHolder.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelHolder.java similarity index 85% rename from src/main/java/com/jozufozu/flywheel/lib/model/ModelHolder.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelHolder.java index 84088f6e8..cc1d3d0f5 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/ModelHolder.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelHolder.java @@ -7,7 +7,6 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; -import com.jozufozu.flywheel.api.event.EndClientResourceReloadEvent; import com.jozufozu.flywheel.api.model.Model; public class ModelHolder { @@ -18,7 +17,10 @@ public class ModelHolder { public ModelHolder(Supplier factory) { this.factory = factory; - ALL.add(this); + + synchronized (ALL) { + ALL.add(this); + } } public Model get() { @@ -51,7 +53,7 @@ public void clear() { } @ApiStatus.Internal - public static void onEndClientResourceReload(EndClientResourceReloadEvent event) { + public static void onEndClientResourceReload() { for (ModelHolder holder : ALL) { holder.clear(); } diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/ModelUtil.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelUtil.java similarity index 81% rename from src/main/java/com/jozufozu/flywheel/lib/model/ModelUtil.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelUtil.java index dc2a155de..b5078b918 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/ModelUtil.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/ModelUtil.java @@ -1,6 +1,5 @@ package com.jozufozu.flywheel.lib.model; -import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.Collection; @@ -8,7 +7,6 @@ import org.joml.Vector3f; import org.joml.Vector4f; import org.lwjgl.system.MemoryUtil; -import org.slf4j.Logger; import com.jozufozu.flywheel.api.material.Material; import com.jozufozu.flywheel.api.model.Mesh; @@ -16,49 +14,28 @@ import com.jozufozu.flywheel.api.vertex.VertexList; import com.jozufozu.flywheel.api.vertex.VertexView; import com.jozufozu.flywheel.api.vertex.VertexViewProviderRegistry; +import com.jozufozu.flywheel.lib.internal.FlwLibXplat; import com.jozufozu.flywheel.lib.material.Materials; import com.jozufozu.flywheel.lib.memory.MemoryBlock; import com.jozufozu.flywheel.lib.vertex.PosVertexView; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferBuilder.DrawState; import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.logging.LogUtils; -import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.BlockRenderDispatcher; -import net.minecraft.client.renderer.block.ModelBlockRenderer; -import net.minecraftforge.fml.util.ObfuscationReflectionHelper; public final class ModelUtil { - private static final Logger LOGGER = LogUtils.getLogger(); - /** * An alternative BlockRenderDispatcher that circumvents the Forge rendering pipeline to ensure consistency. * Meant to be used for virtual rendering. */ - public static final BlockRenderDispatcher VANILLA_RENDERER = createVanillaRenderer(); + public static final BlockRenderDispatcher VANILLA_RENDERER = FlwLibXplat.INSTANCE.createVanillaBlockRenderDispatcher(); private static final float BOUNDING_SPHERE_EPSILON = 1e-4f; private ModelUtil() { } - private static BlockRenderDispatcher createVanillaRenderer() { - BlockRenderDispatcher defaultDispatcher = Minecraft.getInstance().getBlockRenderer(); - BlockRenderDispatcher dispatcher = new BlockRenderDispatcher(null, null, null); - try { - for (Field field : BlockRenderDispatcher.class.getDeclaredFields()) { - field.setAccessible(true); - field.set(dispatcher, field.get(defaultDispatcher)); - } - ObfuscationReflectionHelper.setPrivateValue(BlockRenderDispatcher.class, dispatcher, new ModelBlockRenderer(Minecraft.getInstance().getBlockColors()), "f_110900_"); - } catch (Exception e) { - LOGGER.error("Failed to initialize vanilla BlockRenderDispatcher!", e); - return defaultDispatcher; - } - return dispatcher; - } - public static MemoryBlock convertVanillaBuffer(BufferBuilder.RenderedBuffer buffer, VertexView vertexView) { DrawState drawState = buffer.drawState(); int vertexCount = drawState.vertexCount(); diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/Models.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/Models.java similarity index 95% rename from src/main/java/com/jozufozu/flywheel/lib/model/Models.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/Models.java index a0dbbd72e..ad821d6ee 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/Models.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/Models.java @@ -19,8 +19,10 @@ * method with the same parameters will return the same object. */ public final class Models { - private static final ModelCache BLOCK_STATE = new ModelCache<>(it -> new BlockModelBuilder(it).build()); - private static final ModelCache PARTIAL = new ModelCache<>(it -> new BakedModelBuilder(it.get()).build()); + private static final ModelCache BLOCK_STATE = new ModelCache<>(it -> BlockModelBuilder.create(it) + .build()); + private static final ModelCache PARTIAL = new ModelCache<>(it -> BakedModelBuilder.create(it.get()) + .build()); private static final ModelCache> TRANSFORMED_PARTIAL = new ModelCache<>(TransformedPartial::create); private Models() { @@ -85,7 +87,7 @@ private record TransformedPartial(PartialModel partial, T key, BiConsumer meshes; + private final List meshes; private final Vector4fc boundingSphere; - public SimpleModel(ImmutableList meshes) { + public SimpleModel(List meshes) { this.meshes = meshes; this.boundingSphere = ModelUtil.computeBoundingSphere(meshes); } diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/SingleMeshModel.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/SingleMeshModel.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/model/SingleMeshModel.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/SingleMeshModel.java diff --git a/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBuilder.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBuilder.java new file mode 100644 index 000000000..db51497b0 --- /dev/null +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBuilder.java @@ -0,0 +1,59 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.function.BiFunction; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.api.material.Material; +import com.jozufozu.flywheel.lib.internal.FlwLibXplat; +import com.jozufozu.flywheel.lib.model.SimpleModel; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; + +@ApiStatus.NonExtendable +public abstract class BakedModelBuilder { + final BakedModel bakedModel; + @Nullable + BlockAndTintGetter level; + @Nullable + BlockState blockState; + @Nullable + PoseStack poseStack; + @Nullable + BiFunction materialFunc; + + BakedModelBuilder(BakedModel bakedModel) { + this.bakedModel = bakedModel; + } + + public static BakedModelBuilder create(BakedModel bakedModel) { + return FlwLibXplat.INSTANCE.createBakedModelBuilder(bakedModel); + } + + public BakedModelBuilder level(BlockAndTintGetter level) { + this.level = level; + return this; + } + + public BakedModelBuilder blockState(BlockState blockState) { + this.blockState = blockState; + return this; + } + + public BakedModelBuilder poseStack(PoseStack poseStack) { + this.poseStack = poseStack; + return this; + } + + public BakedModelBuilder materialFunc(BiFunction materialFunc) { + this.materialFunc = materialFunc; + return this; + } + + public abstract SimpleModel build(); +} diff --git a/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BlockModelBuilder.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BlockModelBuilder.java new file mode 100644 index 000000000..aab97fdfe --- /dev/null +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BlockModelBuilder.java @@ -0,0 +1,51 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.function.BiFunction; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.api.material.Material; +import com.jozufozu.flywheel.lib.internal.FlwLibXplat; +import com.jozufozu.flywheel.lib.model.SimpleModel; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.renderer.RenderType; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; + +@ApiStatus.NonExtendable +public abstract class BlockModelBuilder { + final BlockState state; + @Nullable + BlockAndTintGetter level; + @Nullable + PoseStack poseStack; + @Nullable + BiFunction materialFunc; + + BlockModelBuilder(BlockState state) { + this.state = state; + } + + public static BlockModelBuilder create(BlockState state) { + return FlwLibXplat.INSTANCE.createBlockModelBuilder(state); + } + + public BlockModelBuilder level(BlockAndTintGetter level) { + this.level = level; + return this; + } + + public BlockModelBuilder poseStack(PoseStack poseStack) { + this.poseStack = poseStack; + return this; + } + + public BlockModelBuilder materialFunc(BiFunction materialFunc) { + this.materialFunc = materialFunc; + return this; + } + + public abstract SimpleModel build(); +} diff --git a/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MultiBlockModelBuilder.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MultiBlockModelBuilder.java new file mode 100644 index 000000000..fdf9db403 --- /dev/null +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MultiBlockModelBuilder.java @@ -0,0 +1,52 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.function.BiFunction; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.api.material.Material; +import com.jozufozu.flywheel.lib.internal.FlwLibXplat; +import com.jozufozu.flywheel.lib.model.SimpleModel; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.renderer.RenderType; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; + +@ApiStatus.NonExtendable +public abstract class MultiBlockModelBuilder { + final BlockAndTintGetter level; + final Iterable positions; + @Nullable + PoseStack poseStack; + boolean renderFluids = false; + @Nullable + BiFunction materialFunc; + + MultiBlockModelBuilder(BlockAndTintGetter level, Iterable positions) { + this.level = level; + this.positions = positions; + } + + public static MultiBlockModelBuilder create(BlockAndTintGetter level, Iterable positions) { + return FlwLibXplat.INSTANCE.createMultiBlockModelBuilder(level, positions); + } + + public MultiBlockModelBuilder poseStack(PoseStack poseStack) { + this.poseStack = poseStack; + return this; + } + + public MultiBlockModelBuilder enableFluidRendering() { + renderFluids = true; + return this; + } + + public MultiBlockModelBuilder materialFunc(BiFunction materialFunc) { + this.materialFunc = materialFunc; + return this; + } + + public abstract SimpleModel build(); +} diff --git a/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModel.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModel.java new file mode 100644 index 000000000..b7f4a760c --- /dev/null +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModel.java @@ -0,0 +1,53 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.resources.ResourceLocation; + +/** + * A helper class for loading and accessing JSON models not directly used by any blocks or items. + *
+ * Creating a PartialModel will make Minecraft automatically load the associated modelLocation. + * PartialModels must be initialized before the initial resource reload, otherwise an error will be thrown. + * It is recommended to do this in the client mod initializer on Fabric and the mod class constructor on Forge. + *
+ * Once Minecraft has finished baking all models, all PartialModels will have their bakedModel fields populated. + */ +public class PartialModel { + static final List ALL = new ArrayList<>(); + static boolean tooLate = false; + + protected final ResourceLocation modelLocation; + protected BakedModel bakedModel; + + public PartialModel(ResourceLocation modelLocation) { + if (tooLate) { + throw new RuntimeException("Attempted to create PartialModel with location '" + modelLocation + "' after start of initial resource reload!"); + } + + this.modelLocation = modelLocation; + + synchronized (ALL) { + ALL.add(this); + } + } + + public ResourceLocation getLocation() { + return modelLocation; + } + + public String getName() { + return getLocation() + .toString(); + } + + public BakedModel get() { + return bakedModel; + } + + protected void set(BakedModel bakedModel) { + this.bakedModel = bakedModel; + } +} diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/TransformingVertexConsumer.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/TransformingVertexConsumer.java similarity index 95% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/TransformingVertexConsumer.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/TransformingVertexConsumer.java index 09054e2b4..42f7c9f93 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/baked/TransformingVertexConsumer.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/TransformingVertexConsumer.java @@ -1,5 +1,6 @@ package com.jozufozu.flywheel.lib.model.baked; +import org.jetbrains.annotations.UnknownNullability; import org.joml.Matrix3f; import org.joml.Matrix4f; @@ -8,7 +9,9 @@ import com.mojang.blaze3d.vertex.VertexConsumer; class TransformingVertexConsumer implements VertexConsumer { + @UnknownNullability private VertexConsumer delegate; + @UnknownNullability private PoseStack poseStack; public void prepare(VertexConsumer delegate, PoseStack poseStack) { diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/VirtualBlockGetter.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/VirtualBlockGetter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/VirtualBlockGetter.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/VirtualBlockGetter.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/VirtualEmptyBlockGetter.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/VirtualEmptyBlockGetter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/VirtualEmptyBlockGetter.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/VirtualEmptyBlockGetter.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/VirtualLightEngine.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/VirtualLightEngine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/VirtualLightEngine.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/baked/VirtualLightEngine.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/part/ModelPartConverter.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/part/ModelPartConverter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/model/part/ModelPartConverter.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/part/ModelPartConverter.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/part/VertexWriter.java b/common/src/lib/java/com/jozufozu/flywheel/lib/model/part/VertexWriter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/model/part/VertexWriter.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/model/part/VertexWriter.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/BarrierPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/BarrierPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/BarrierPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/BarrierPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/Distribute.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/Distribute.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/Distribute.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/Distribute.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/DynamicNestedPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/DynamicNestedPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/DynamicNestedPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/DynamicNestedPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/Flag.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/Flag.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/Flag.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/Flag.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/ForEachPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/ForEachPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/ForEachPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/ForEachPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/ForEachSlicePlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/ForEachSlicePlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/ForEachSlicePlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/ForEachSlicePlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/IfElsePlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/IfElsePlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/IfElsePlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/IfElsePlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/MapContextPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/MapContextPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/MapContextPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/MapContextPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/NamedFlag.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/NamedFlag.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/NamedFlag.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/NamedFlag.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/NestedPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/NestedPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/NestedPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/NestedPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/PlanMap.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/PlanMap.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/PlanMap.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/PlanMap.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/RaisePlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/RaisePlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/RaisePlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/RaisePlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/RunnablePlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/RunnablePlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/RunnablePlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/RunnablePlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/SimplePlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/SimplePlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/SimplePlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/SimplePlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/SimplyComposedPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/SimplyComposedPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/SimplyComposedPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/SimplyComposedPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/StageFlag.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/StageFlag.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/StageFlag.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/StageFlag.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/SyncedPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/SyncedPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/SyncedPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/SyncedPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/Synchronizer.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/Synchronizer.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/Synchronizer.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/Synchronizer.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/UnitPlan.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/UnitPlan.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/UnitPlan.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/UnitPlan.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/functional/BooleanSupplierWithContext.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/BooleanSupplierWithContext.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/functional/BooleanSupplierWithContext.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/BooleanSupplierWithContext.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/functional/ConsumerWithContext.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/ConsumerWithContext.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/functional/ConsumerWithContext.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/ConsumerWithContext.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/functional/RunnableWithContext.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/RunnableWithContext.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/functional/RunnableWithContext.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/RunnableWithContext.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/functional/SupplierWithContext.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/SupplierWithContext.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/functional/SupplierWithContext.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/SupplierWithContext.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/task/functional/package-info.java b/common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/package-info.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/task/functional/package-info.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/task/functional/package-info.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/transform/Affine.java b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/Affine.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/transform/Affine.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/transform/Affine.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/transform/PoseTransformStack.java b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/PoseTransformStack.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/transform/PoseTransformStack.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/transform/PoseTransformStack.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/transform/Rotate.java b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/Rotate.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/transform/Rotate.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/transform/Rotate.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/transform/Scale.java b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/Scale.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/transform/Scale.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/transform/Scale.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/transform/Transform.java b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/Transform.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/transform/Transform.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/transform/Transform.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/transform/TransformStack.java b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/TransformStack.java similarity index 67% rename from src/main/java/com/jozufozu/flywheel/lib/transform/TransformStack.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/transform/TransformStack.java index 306972421..00d77576e 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/transform/TransformStack.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/TransformStack.java @@ -1,11 +1,11 @@ package com.jozufozu.flywheel.lib.transform; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.lib.internal.FlwLibLink; import com.mojang.blaze3d.vertex.PoseStack; public interface TransformStack> extends Transform { static PoseTransformStack of(PoseStack stack) { - return InternalFlywheelApi.INSTANCE.getPoseTransformStackOf(stack); + return FlwLibLink.INSTANCE.getPoseTransformStackOf(stack); } Self pushPose(); diff --git a/src/main/java/com/jozufozu/flywheel/lib/transform/Translate.java b/common/src/lib/java/com/jozufozu/flywheel/lib/transform/Translate.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/transform/Translate.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/transform/Translate.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/AtomicBitset.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/AtomicBitset.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/util/AtomicBitset.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/AtomicBitset.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/FlwUtil.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/FlwUtil.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/util/FlwUtil.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/FlwUtil.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/LevelAttached.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/LevelAttached.java similarity index 91% rename from src/main/java/com/jozufozu/flywheel/lib/util/LevelAttached.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/LevelAttached.java index e19bd7e40..e8817d6e1 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/util/LevelAttached.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/util/LevelAttached.java @@ -7,14 +7,11 @@ import java.util.function.Consumer; import java.util.function.Function; -import org.jetbrains.annotations.ApiStatus; - import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import net.minecraft.world.level.LevelAccessor; -import net.minecraftforge.event.level.LevelEvent; public final class LevelAttached { private static final ConcurrentLinkedDeque>> ALL = new ConcurrentLinkedDeque<>(); @@ -42,11 +39,6 @@ public LevelAttached(Function factory) { this(factory, t -> {}); } - @ApiStatus.Internal - public static void onUnloadLevel(LevelEvent.Unload event) { - invalidateLevel(event.getLevel()); - } - public static void invalidateLevel(LevelAccessor level) { Iterator>> iterator = ALL.iterator(); while (iterator.hasNext()) { diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/Pair.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/Pair.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/util/Pair.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/Pair.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/ResourceUtil.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/ResourceUtil.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/lib/util/ResourceUtil.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/ResourceUtil.java index 6ab2e76f7..36be0853c 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/util/ResourceUtil.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/util/ResourceUtil.java @@ -1,6 +1,6 @@ package com.jozufozu.flywheel.lib.util; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/SectionUtil.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/SectionUtil.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/util/SectionUtil.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/SectionUtil.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/ShadersModHandler.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/ShadersModHandler.java similarity index 63% rename from src/main/java/com/jozufozu/flywheel/lib/util/ShadersModHandler.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/ShadersModHandler.java index 1c70cd4c9..8ab564351 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/util/ShadersModHandler.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/util/ShadersModHandler.java @@ -4,38 +4,35 @@ import java.util.function.BooleanSupplier; import org.jetbrains.annotations.ApiStatus; -import org.slf4j.Logger; -import com.mojang.logging.LogUtils; - -import net.irisshaders.iris.api.v0.IrisApi; -import net.minecraftforge.fml.ModList; +import com.jozufozu.flywheel.lib.internal.FlwLibLink; +import com.jozufozu.flywheel.lib.internal.FlwLibXplat; public final class ShadersModHandler { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final String OPTIFINE_ROOT_PACKAGE = "net.optifine"; - private static final boolean IS_OCULUS_LOADED; + private static final boolean IS_IRIS_LOADED; private static final boolean IS_OPTIFINE_INSTALLED; private static final InternalHandler INTERNAL_HANDLER; static { + InternalHandler irisHandler = FlwLibXplat.INSTANCE + .createIrisHandler(); + IS_IRIS_LOADED = irisHandler != null; + Package optifinePackage = Package.getPackage(OPTIFINE_ROOT_PACKAGE); IS_OPTIFINE_INSTALLED = optifinePackage != null; - IS_OCULUS_LOADED = ModList.get() - .isLoaded("oculus"); - // OptiFine and Oculus are assumed to be mutually exclusive + // OptiFine and Iris/Oculus are assumed to be mutually exclusive - if (IS_OPTIFINE_INSTALLED) { - LOGGER.info("Optifine detected."); - INTERNAL_HANDLER = new Optifine(); - } else if (IS_OCULUS_LOADED) { - LOGGER.info("Oculus detected."); - INTERNAL_HANDLER = new Oculus(); + if (IS_IRIS_LOADED) { + FlwLibLink.INSTANCE.getLogger().debug("Iris detected."); + INTERNAL_HANDLER = irisHandler; + } else if (IS_OPTIFINE_INSTALLED) { + FlwLibLink.INSTANCE.getLogger().debug("OptiFine detected."); + INTERNAL_HANDLER = new OptifineHandler(); } else { - LOGGER.info("No shaders mod detected."); + FlwLibLink.INSTANCE.getLogger().debug("No shaders mod detected."); INTERNAL_HANDLER = new InternalHandler() {}; } } @@ -43,8 +40,8 @@ public final class ShadersModHandler { private ShadersModHandler() { } - public static boolean isOculusLoaded() { - return IS_OCULUS_LOADED; + public static boolean isIrisLoaded() { + return IS_IRIS_LOADED; } public static boolean isOptifineInstalled() { @@ -63,37 +60,23 @@ public static boolean isRenderingShadowPass() { public static void init() { } - private interface InternalHandler { + @ApiStatus.Internal + public interface InternalHandler { default boolean isShaderPackInUse() { return false; - }; + } default boolean isRenderingShadowPass() { return false; - }; - } - - // simple, lovely api calls - private static class Oculus implements InternalHandler { - @Override - public boolean isShaderPackInUse() { - return IrisApi.getInstance() - .isShaderPackInUse(); - } - - @Override - public boolean isRenderingShadowPass() { - return IrisApi.getInstance() - .isRenderingShadowPass(); } } // evil reflection - private static class Optifine implements InternalHandler { + private static class OptifineHandler implements InternalHandler { private final BooleanSupplier shadersEnabledSupplier; private final BooleanSupplier shadowPassSupplier; - Optifine() { + private OptifineHandler() { shadersEnabledSupplier = createShadersEnabledSupplier(); shadowPassSupplier = createShadowPassSupplier(); } @@ -116,11 +99,11 @@ private static BooleanSupplier createShadersEnabledSupplier() { return () -> { try { return field.getBoolean(null); - } catch (IllegalAccessException ignored) { + } catch (IllegalAccessException e) { return false; } }; - } catch (Exception ignored) { + } catch (Exception e) { return () -> false; } } @@ -133,11 +116,11 @@ private static BooleanSupplier createShadowPassSupplier() { return () -> { try { return field.getBoolean(null); - } catch (IllegalAccessException ignored) { + } catch (IllegalAccessException e) { return false; } }; - } catch (Exception ignored) { + } catch (Exception e) { return () -> false; } } diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/StringUtil.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/StringUtil.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/util/StringUtil.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/StringUtil.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/util/Unit.java b/common/src/lib/java/com/jozufozu/flywheel/lib/util/Unit.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/util/Unit.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/util/Unit.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/vertex/AbstractVertexView.java b/common/src/lib/java/com/jozufozu/flywheel/lib/vertex/AbstractVertexView.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/vertex/AbstractVertexView.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/vertex/AbstractVertexView.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/vertex/EmptyVertexList.java b/common/src/lib/java/com/jozufozu/flywheel/lib/vertex/EmptyVertexList.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/vertex/EmptyVertexList.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/vertex/EmptyVertexList.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/vertex/FullVertexView.java b/common/src/lib/java/com/jozufozu/flywheel/lib/vertex/FullVertexView.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/vertex/FullVertexView.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/vertex/FullVertexView.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/vertex/NoOverlayVertexView.java b/common/src/lib/java/com/jozufozu/flywheel/lib/vertex/NoOverlayVertexView.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/vertex/NoOverlayVertexView.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/vertex/NoOverlayVertexView.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/vertex/PosTexNormalVertexView.java b/common/src/lib/java/com/jozufozu/flywheel/lib/vertex/PosTexNormalVertexView.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/vertex/PosTexNormalVertexView.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/vertex/PosTexNormalVertexView.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/vertex/PosVertexView.java b/common/src/lib/java/com/jozufozu/flywheel/lib/vertex/PosVertexView.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/vertex/PosVertexView.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/vertex/PosVertexView.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/AbstractBlockEntityVisual.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/AbstractBlockEntityVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/AbstractBlockEntityVisual.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/AbstractBlockEntityVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/AbstractEntityVisual.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/AbstractEntityVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/AbstractEntityVisual.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/AbstractEntityVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/AbstractVisual.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/AbstractVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/AbstractVisual.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/AbstractVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/EntityComponent.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/EntityComponent.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/EntityComponent.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/EntityComponent.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/EntityVisibilityTester.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/EntityVisibilityTester.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/EntityVisibilityTester.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/EntityVisibilityTester.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/InstanceRecycler.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/InstanceRecycler.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/InstanceRecycler.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/InstanceRecycler.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleBlockEntityVisualizer.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleBlockEntityVisualizer.java similarity index 98% rename from src/main/java/com/jozufozu/flywheel/lib/visual/SimpleBlockEntityVisualizer.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleBlockEntityVisualizer.java index 49f2e4d5e..f32a814d5 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleBlockEntityVisualizer.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleBlockEntityVisualizer.java @@ -3,6 +3,8 @@ import java.util.Objects; import java.util.function.Predicate; +import org.jetbrains.annotations.Nullable; + import com.jozufozu.flywheel.api.visual.BlockEntityVisual; import com.jozufozu.flywheel.api.visualization.BlockEntityVisualizer; import com.jozufozu.flywheel.api.visualization.VisualizationContext; @@ -54,7 +56,9 @@ public interface Factory { */ public static class Builder { protected BlockEntityType type; + @Nullable protected Factory visualFactory; + @Nullable protected Predicate skipVanillaRender; public Builder(BlockEntityType type) { diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleDynamicVisual.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleDynamicVisual.java similarity index 84% rename from src/main/java/com/jozufozu/flywheel/lib/visual/SimpleDynamicVisual.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleDynamicVisual.java index 9e3220c44..8f0b76dc1 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleDynamicVisual.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleDynamicVisual.java @@ -4,7 +4,6 @@ import com.jozufozu.flywheel.api.instance.Instancer; import com.jozufozu.flywheel.api.task.Plan; import com.jozufozu.flywheel.api.visual.DynamicVisual; -import com.jozufozu.flywheel.api.visual.TickableVisual; import com.jozufozu.flywheel.lib.task.RunnablePlan; public interface SimpleDynamicVisual extends DynamicVisual { @@ -14,7 +13,7 @@ public interface SimpleDynamicVisual extends DynamicVisual { * The implementation is free to parallelize calls to this method. * You must ensure proper synchronization if you need to mutate anything outside this visual. *
- * This method and {@link TickableVisual#tick} will never be called simultaneously. + * This method and {@link SimpleTickableVisual#tick} will never be called simultaneously. *
* {@link Instancer}/{@link Instance} creation/acquisition is safe here. */ diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisual.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisual.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisualizer.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisualizer.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisualizer.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisualizer.java index 0cedc825d..220e43e7c 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisualizer.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleEntityVisualizer.java @@ -3,6 +3,8 @@ import java.util.Objects; import java.util.function.Predicate; +import org.jetbrains.annotations.Nullable; + import com.jozufozu.flywheel.api.visual.EntityVisual; import com.jozufozu.flywheel.api.visualization.EntityVisualizer; import com.jozufozu.flywheel.api.visualization.VisualizationContext; @@ -54,7 +56,9 @@ public interface Factory { */ public static class Builder { protected EntityType type; + @Nullable protected Factory visualFactory; + @Nullable protected Predicate skipVanillaRender; public Builder(EntityType type) { diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleTickableVisual.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleTickableVisual.java similarity index 84% rename from src/main/java/com/jozufozu/flywheel/lib/visual/SimpleTickableVisual.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleTickableVisual.java index a59881bdd..ac9a2d658 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/visual/SimpleTickableVisual.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SimpleTickableVisual.java @@ -3,7 +3,6 @@ import com.jozufozu.flywheel.api.instance.Instance; import com.jozufozu.flywheel.api.instance.Instancer; import com.jozufozu.flywheel.api.task.Plan; -import com.jozufozu.flywheel.api.visual.DynamicVisual; import com.jozufozu.flywheel.api.visual.TickableVisual; import com.jozufozu.flywheel.lib.task.RunnablePlan; @@ -15,7 +14,7 @@ public interface SimpleTickableVisual extends TickableVisual { * The implementation is free to parallelize calls to this method. * You must ensure proper synchronization if you need to mutate anything outside this visual. *
- * This method and {@link DynamicVisual#beginFrame} will never be called simultaneously. + * This method and {@link SimpleDynamicVisual#beginFrame} will never be called simultaneously. *
* {@link Instancer}/{@link Instance} creation/acquisition is safe here. */ diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/SmartRecycler.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/SmartRecycler.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/SmartRecycler.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/SmartRecycler.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/component/FireComponent.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/FireComponent.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/lib/visual/component/FireComponent.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/FireComponent.java index 9a11224dc..8c0f3bf0d 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/visual/component/FireComponent.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/FireComponent.java @@ -63,7 +63,7 @@ private TransformedInstance createInstance(Model model) { /** * Update the fire instances. You'd typically call this in your visual's - * {@link com.jozufozu.flywheel.api.visual.DynamicVisual#beginFrame(DynamicVisual.Context) beginFrame} method. + * {@link com.jozufozu.flywheel.lib.visual.SimpleDynamicVisual#beginFrame(DynamicVisual.Context) beginFrame} method. * * @param context The frame context. */ diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/component/HitboxComponent.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/HitboxComponent.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/lib/visual/component/HitboxComponent.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/HitboxComponent.java diff --git a/src/main/java/com/jozufozu/flywheel/lib/visual/component/ShadowComponent.java b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/ShadowComponent.java similarity index 98% rename from src/main/java/com/jozufozu/flywheel/lib/visual/component/ShadowComponent.java rename to common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/ShadowComponent.java index 305cd1b34..45d3526ca 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/visual/component/ShadowComponent.java +++ b/common/src/lib/java/com/jozufozu/flywheel/lib/visual/component/ShadowComponent.java @@ -108,7 +108,7 @@ public ShadowComponent strength(float strength) { /** * Update the shadow instances. You'd typically call this in your visual's - * {@link com.jozufozu.flywheel.api.visual.DynamicVisual#beginFrame(DynamicVisual.Context) beginFrame} method. + * {@link com.jozufozu.flywheel.lib.visual.SimpleDynamicVisual#beginFrame(DynamicVisual.Context) beginFrame} method. * * @param context The frame context. */ diff --git a/src/main/resources/assets/flywheel/flywheel/cutout/epsilon.glsl b/common/src/lib/resources/assets/flywheel/flywheel/cutout/epsilon.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/cutout/epsilon.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/cutout/epsilon.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/cutout/half.glsl b/common/src/lib/resources/assets/flywheel/flywheel/cutout/half.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/cutout/half.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/cutout/half.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/cutout/off.glsl b/common/src/lib/resources/assets/flywheel/flywheel/cutout/off.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/cutout/off.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/cutout/off.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/cutout/one_tenth.glsl b/common/src/lib/resources/assets/flywheel/flywheel/cutout/one_tenth.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/cutout/one_tenth.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/cutout/one_tenth.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/fog/linear.glsl b/common/src/lib/resources/assets/flywheel/flywheel/fog/linear.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/fog/linear.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/fog/linear.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/fog/linear_fade.glsl b/common/src/lib/resources/assets/flywheel/flywheel/fog/linear_fade.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/fog/linear_fade.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/fog/linear_fade.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/fog/none.glsl b/common/src/lib/resources/assets/flywheel/flywheel/fog/none.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/fog/none.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/fog/none.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/instance/cull/oriented.glsl b/common/src/lib/resources/assets/flywheel/flywheel/instance/cull/oriented.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/instance/cull/oriented.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/instance/cull/oriented.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/instance/cull/shadow.glsl b/common/src/lib/resources/assets/flywheel/flywheel/instance/cull/shadow.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/instance/cull/shadow.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/instance/cull/shadow.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/instance/cull/transformed.glsl b/common/src/lib/resources/assets/flywheel/flywheel/instance/cull/transformed.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/instance/cull/transformed.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/instance/cull/transformed.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/instance/oriented.vert b/common/src/lib/resources/assets/flywheel/flywheel/instance/oriented.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/instance/oriented.vert rename to common/src/lib/resources/assets/flywheel/flywheel/instance/oriented.vert diff --git a/src/main/resources/assets/flywheel/flywheel/instance/shadow.vert b/common/src/lib/resources/assets/flywheel/flywheel/instance/shadow.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/instance/shadow.vert rename to common/src/lib/resources/assets/flywheel/flywheel/instance/shadow.vert diff --git a/src/main/resources/assets/flywheel/flywheel/instance/transformed.vert b/common/src/lib/resources/assets/flywheel/flywheel/instance/transformed.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/instance/transformed.vert rename to common/src/lib/resources/assets/flywheel/flywheel/instance/transformed.vert diff --git a/src/main/resources/assets/flywheel/flywheel/material/default.frag b/common/src/lib/resources/assets/flywheel/flywheel/material/default.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/material/default.frag rename to common/src/lib/resources/assets/flywheel/flywheel/material/default.frag diff --git a/src/main/resources/assets/flywheel/flywheel/material/default.vert b/common/src/lib/resources/assets/flywheel/flywheel/material/default.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/material/default.vert rename to common/src/lib/resources/assets/flywheel/flywheel/material/default.vert diff --git a/src/main/resources/assets/flywheel/flywheel/material/lines.frag b/common/src/lib/resources/assets/flywheel/flywheel/material/lines.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/material/lines.frag rename to common/src/lib/resources/assets/flywheel/flywheel/material/lines.frag diff --git a/src/main/resources/assets/flywheel/flywheel/material/lines.vert b/common/src/lib/resources/assets/flywheel/flywheel/material/lines.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/material/lines.vert rename to common/src/lib/resources/assets/flywheel/flywheel/material/lines.vert diff --git a/src/main/resources/assets/flywheel/flywheel/material/wireframe.frag b/common/src/lib/resources/assets/flywheel/flywheel/material/wireframe.frag similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/material/wireframe.frag rename to common/src/lib/resources/assets/flywheel/flywheel/material/wireframe.frag diff --git a/src/main/resources/assets/flywheel/flywheel/material/wireframe.vert b/common/src/lib/resources/assets/flywheel/flywheel/material/wireframe.vert similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/material/wireframe.vert rename to common/src/lib/resources/assets/flywheel/flywheel/material/wireframe.vert diff --git a/src/main/resources/assets/flywheel/flywheel/util/color.glsl b/common/src/lib/resources/assets/flywheel/flywheel/util/color.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/util/color.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/util/color.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/util/matrix.glsl b/common/src/lib/resources/assets/flywheel/flywheel/util/matrix.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/util/matrix.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/util/matrix.glsl diff --git a/src/main/resources/assets/flywheel/flywheel/util/quaternion.glsl b/common/src/lib/resources/assets/flywheel/flywheel/util/quaternion.glsl similarity index 100% rename from src/main/resources/assets/flywheel/flywheel/util/quaternion.glsl rename to common/src/lib/resources/assets/flywheel/flywheel/util/quaternion.glsl diff --git a/src/main/java/com/jozufozu/flywheel/config/BackendArgument.java b/common/src/main/java/com/jozufozu/flywheel/impl/BackendArgument.java similarity index 98% rename from src/main/java/com/jozufozu/flywheel/config/BackendArgument.java rename to common/src/main/java/com/jozufozu/flywheel/impl/BackendArgument.java index 5f340ad5d..bbc2ff860 100644 --- a/src/main/java/com/jozufozu/flywheel/config/BackendArgument.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/BackendArgument.java @@ -1,4 +1,4 @@ -package com.jozufozu.flywheel.config; +package com.jozufozu.flywheel.impl; import java.util.Collection; import java.util.List; diff --git a/src/main/java/com/jozufozu/flywheel/impl/BackendManagerImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/BackendManagerImpl.java similarity index 65% rename from src/main/java/com/jozufozu/flywheel/impl/BackendManagerImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/BackendManagerImpl.java index 302959cbf..de7dbed89 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/BackendManagerImpl.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/BackendManagerImpl.java @@ -1,24 +1,17 @@ package com.jozufozu.flywheel.impl; -import org.slf4j.Logger; +import org.jetbrains.annotations.Nullable; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import com.jozufozu.flywheel.api.backend.Backend; -import com.jozufozu.flywheel.api.event.EndClientResourceReloadEvent; -import com.jozufozu.flywheel.api.event.ReloadLevelRendererEvent; import com.jozufozu.flywheel.backend.Backends; -import com.jozufozu.flywheel.config.FlwConfig; import com.jozufozu.flywheel.impl.visualization.VisualizationManagerImpl; import com.jozufozu.flywheel.lib.backend.SimpleBackend; -import com.mojang.logging.LogUtils; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.fml.CrashReportCallables; public final class BackendManagerImpl { - private static final Logger LOGGER = LogUtils.getLogger(); - public static final Backend OFF_BACKEND = SimpleBackend.builder() .engineFactory(level -> { throw new UnsupportedOperationException("Cannot create engine when backend is off."); @@ -48,11 +41,11 @@ private static Backend findDefaultBackend() { } private static void chooseBackend() { - var preferred = FlwConfig.get().getBackend(); + var preferred = FlwConfig.INSTANCE.backend(); var actual = preferred.findFallback(); if (preferred != actual) { - LOGGER.warn("Flywheel backend fell back from '{}' to '{}'", Backend.REGISTRY.getIdOrThrow(preferred), Backend.REGISTRY.getIdOrThrow(actual)); + FlwImpl.LOGGER.warn("Flywheel backend fell back from '{}' to '{}'", Backend.REGISTRY.getIdOrThrow(preferred), Backend.REGISTRY.getIdOrThrow(actual)); } backend = actual; @@ -67,12 +60,10 @@ public static String getBackendString() { } public static void init() { - CrashReportCallables.registerCrashCallable("Flywheel Backend", BackendManagerImpl::getBackendString); } - public static void onEndClientResourceReload(EndClientResourceReloadEvent event) { - if (event.error() - .isPresent()) { + public static void onEndClientResourceReload(boolean didError) { + if (didError) { return; } @@ -80,10 +71,9 @@ public static void onEndClientResourceReload(EndClientResourceReloadEvent event) VisualizationManagerImpl.resetAll(); } - public static void onReloadLevelRenderer(ReloadLevelRendererEvent event) { + public static void onReloadLevelRenderer(@Nullable ClientLevel level) { chooseBackend(); - ClientLevel level = event.level(); if (level != null) { VisualizationManagerImpl.reset(level); } diff --git a/common/src/main/java/com/jozufozu/flywheel/impl/DebugModeArgument.java b/common/src/main/java/com/jozufozu/flywheel/impl/DebugModeArgument.java new file mode 100644 index 000000000..d76b9af1e --- /dev/null +++ b/common/src/main/java/com/jozufozu/flywheel/impl/DebugModeArgument.java @@ -0,0 +1,15 @@ +package com.jozufozu.flywheel.impl; + +import com.jozufozu.flywheel.backend.engine.uniform.DebugMode; + +import net.minecraft.commands.arguments.StringRepresentableArgument; +import net.minecraft.commands.synchronization.SingletonArgumentInfo; + +public class DebugModeArgument extends StringRepresentableArgument { + public static final DebugModeArgument INSTANCE = new DebugModeArgument(); + public static final SingletonArgumentInfo INFO = SingletonArgumentInfo.contextFree(() -> INSTANCE); + + public DebugModeArgument() { + super(DebugMode.CODEC, DebugMode::values); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/impl/InternalFlywheelImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/FlwApiLinkImpl.java similarity index 88% rename from src/main/java/com/jozufozu/flywheel/impl/InternalFlywheelImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/FlwApiLinkImpl.java index c32738e52..877135322 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/InternalFlywheelImpl.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/FlwApiLinkImpl.java @@ -3,7 +3,7 @@ import org.jetbrains.annotations.Nullable; import com.jozufozu.flywheel.api.backend.Backend; -import com.jozufozu.flywheel.api.internal.InternalFlywheelApi; +import com.jozufozu.flywheel.api.internal.FlwApiLink; import com.jozufozu.flywheel.api.layout.LayoutBuilder; import com.jozufozu.flywheel.api.registry.IdRegistry; import com.jozufozu.flywheel.api.registry.Registry; @@ -11,15 +11,12 @@ import com.jozufozu.flywheel.api.visualization.BlockEntityVisualizer; import com.jozufozu.flywheel.api.visualization.EntityVisualizer; import com.jozufozu.flywheel.api.visualization.VisualizationManager; -import com.jozufozu.flywheel.impl.extension.PoseStackExtension; import com.jozufozu.flywheel.impl.layout.LayoutBuilderImpl; import com.jozufozu.flywheel.impl.registry.IdRegistryImpl; import com.jozufozu.flywheel.impl.registry.RegistryImpl; import com.jozufozu.flywheel.impl.vertex.VertexViewProviderRegistryImpl; import com.jozufozu.flywheel.impl.visualization.VisualizationManagerImpl; import com.jozufozu.flywheel.impl.visualization.VisualizerRegistryImpl; -import com.jozufozu.flywheel.lib.transform.PoseTransformStack; -import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.world.entity.Entity; @@ -28,7 +25,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; -public final class InternalFlywheelImpl implements InternalFlywheelApi { +public class FlwApiLinkImpl implements FlwApiLink { @Override public Registry createRegistry() { return new RegistryImpl<>(); @@ -111,9 +108,4 @@ public void setVisualizer(BlockEntityType type, Block public void setVisualizer(EntityType type, EntityVisualizer visualizer) { VisualizerRegistryImpl.setVisualizer(type, visualizer); } - - @Override - public PoseTransformStack getPoseTransformStackOf(PoseStack stack) { - return ((PoseStackExtension) stack).flywheel$transformStack(); - } } diff --git a/common/src/main/java/com/jozufozu/flywheel/impl/FlwConfig.java b/common/src/main/java/com/jozufozu/flywheel/impl/FlwConfig.java new file mode 100644 index 000000000..35e167d94 --- /dev/null +++ b/common/src/main/java/com/jozufozu/flywheel/impl/FlwConfig.java @@ -0,0 +1,13 @@ +package com.jozufozu.flywheel.impl; + +import com.jozufozu.flywheel.api.backend.Backend; + +public interface FlwConfig { + FlwConfig INSTANCE = FlwImplXplat.INSTANCE.getConfig(); + + Backend backend(); + + boolean limitUpdates(); + + int workerThreads(); +} diff --git a/common/src/main/java/com/jozufozu/flywheel/impl/FlwDebugInfo.java b/common/src/main/java/com/jozufozu/flywheel/impl/FlwDebugInfo.java new file mode 100644 index 000000000..6150146b1 --- /dev/null +++ b/common/src/main/java/com/jozufozu/flywheel/impl/FlwDebugInfo.java @@ -0,0 +1,37 @@ +package com.jozufozu.flywheel.impl; + +import java.util.List; + +import com.jozufozu.flywheel.api.visualization.VisualizationManager; +import com.jozufozu.flywheel.lib.memory.FlwMemoryTracker; +import com.jozufozu.flywheel.lib.util.StringUtil; + +import net.minecraft.client.Minecraft; +import net.minecraft.core.Vec3i; + +public final class FlwDebugInfo { + private FlwDebugInfo() { + } + + public static void addDebugInfo(Minecraft minecraft, List systemInfo) { + if (minecraft.showOnlyReducedInfo()) { + return; + } + + systemInfo.add(""); + systemInfo.add("Flywheel: " + FlwImplXplat.INSTANCE.getVersionStr()); + systemInfo.add("Backend: " + BackendManagerImpl.getBackendString()); + systemInfo.add("Update limiting: " + (FlwConfig.INSTANCE.limitUpdates() ? "on" : "off")); + + VisualizationManager manager = VisualizationManager.get(minecraft.level); + if (manager != null) { + systemInfo.add("B: " + manager.getBlockEntities().getVisualCount() + + ", E: " + manager.getEntities().getVisualCount() + + ", F: " + manager.getEffects().getVisualCount()); + Vec3i renderOrigin = manager.getRenderOrigin(); + systemInfo.add("Origin: " + renderOrigin.getX() + ", " + renderOrigin.getY() + ", " + renderOrigin.getZ()); + } + + systemInfo.add("Memory Usage: CPU: " + StringUtil.formatBytes(FlwMemoryTracker.getCPUMemory()) + ", GPU: " + StringUtil.formatBytes(FlwMemoryTracker.getGPUMemory())); + } +} diff --git a/common/src/main/java/com/jozufozu/flywheel/impl/FlwImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/FlwImpl.java new file mode 100644 index 000000000..53df9d4e1 --- /dev/null +++ b/common/src/main/java/com/jozufozu/flywheel/impl/FlwImpl.java @@ -0,0 +1,46 @@ +package com.jozufozu.flywheel.impl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jozufozu.flywheel.api.Flywheel; +import com.jozufozu.flywheel.backend.FlwBackend; +import com.jozufozu.flywheel.impl.registry.IdRegistryImpl; +import com.jozufozu.flywheel.impl.registry.RegistryImpl; +import com.jozufozu.flywheel.lib.instance.InstanceTypes; +import com.jozufozu.flywheel.lib.material.CutoutShaders; +import com.jozufozu.flywheel.lib.material.FogShaders; +import com.jozufozu.flywheel.lib.material.StandardMaterialShaders; +import com.jozufozu.flywheel.lib.util.ShadersModHandler; +import com.jozufozu.flywheel.vanilla.VanillaVisuals; + +public final class FlwImpl { + public static final Logger LOGGER = LoggerFactory.getLogger(Flywheel.ID); + public static final Logger CONFIG_LOGGER = LoggerFactory.getLogger(Flywheel.ID + "/config"); + + private FlwImpl() { + } + + public static void init() { + // impl + BackendManagerImpl.init(); + + // lib + ShadersModHandler.init(); + InstanceTypes.init(); + CutoutShaders.init(); + FogShaders.init(); + StandardMaterialShaders.init(); + + // backend + FlwBackend.init(); + + // vanilla + VanillaVisuals.init(); + } + + public static void freezeRegistries() { + RegistryImpl.freezeAll(); + IdRegistryImpl.freezeAll(); + } +} diff --git a/common/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplat.java b/common/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplat.java new file mode 100644 index 000000000..198b821ab --- /dev/null +++ b/common/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplat.java @@ -0,0 +1,23 @@ +package com.jozufozu.flywheel.impl; + +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.api.event.RenderContext; +import com.jozufozu.flywheel.api.event.RenderStage; +import com.jozufozu.flywheel.api.internal.DependencyInjection; + +import net.minecraft.client.multiplayer.ClientLevel; + +public interface FlwImplXplat { + FlwImplXplat INSTANCE = DependencyInjection.load(FlwImplXplat.class, "com.jozufozu.flywheel.impl.FlwImplXplatImpl"); + + void dispatchBeginFrameEvent(RenderContext context); + + void dispatchReloadLevelRendererEvent(@Nullable ClientLevel level); + + void dispatchRenderStageEvent(RenderContext context, RenderStage stage); + + String getVersionStr(); + + FlwConfig getConfig(); +} diff --git a/common/src/main/java/com/jozufozu/flywheel/impl/FlwLibLinkImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/FlwLibLinkImpl.java new file mode 100644 index 000000000..f49536065 --- /dev/null +++ b/common/src/main/java/com/jozufozu/flywheel/impl/FlwLibLinkImpl.java @@ -0,0 +1,20 @@ +package com.jozufozu.flywheel.impl; + +import org.slf4j.Logger; + +import com.jozufozu.flywheel.impl.extension.PoseStackExtension; +import com.jozufozu.flywheel.lib.internal.FlwLibLink; +import com.jozufozu.flywheel.lib.transform.PoseTransformStack; +import com.mojang.blaze3d.vertex.PoseStack; + +public class FlwLibLinkImpl implements FlwLibLink { + @Override + public Logger getLogger() { + return FlwImpl.LOGGER; + } + + @Override + public PoseTransformStack getPoseTransformStackOf(PoseStack stack) { + return ((PoseStackExtension) stack).flywheel$transformStack(); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/impl/event/RenderContextImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/event/RenderContextImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/event/RenderContextImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/event/RenderContextImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/extension/BlockEntityTypeExtension.java b/common/src/main/java/com/jozufozu/flywheel/impl/extension/BlockEntityTypeExtension.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/extension/BlockEntityTypeExtension.java rename to common/src/main/java/com/jozufozu/flywheel/impl/extension/BlockEntityTypeExtension.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/extension/EntityTypeExtension.java b/common/src/main/java/com/jozufozu/flywheel/impl/extension/EntityTypeExtension.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/extension/EntityTypeExtension.java rename to common/src/main/java/com/jozufozu/flywheel/impl/extension/EntityTypeExtension.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/extension/LevelExtension.java b/common/src/main/java/com/jozufozu/flywheel/impl/extension/LevelExtension.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/extension/LevelExtension.java rename to common/src/main/java/com/jozufozu/flywheel/impl/extension/LevelExtension.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/extension/PoseStackExtension.java b/common/src/main/java/com/jozufozu/flywheel/impl/extension/PoseStackExtension.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/extension/PoseStackExtension.java rename to common/src/main/java/com/jozufozu/flywheel/impl/extension/PoseStackExtension.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/extension/VertexFormatExtension.java b/common/src/main/java/com/jozufozu/flywheel/impl/extension/VertexFormatExtension.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/extension/VertexFormatExtension.java rename to common/src/main/java/com/jozufozu/flywheel/impl/extension/VertexFormatExtension.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/layout/ArrayElementTypeImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/layout/ArrayElementTypeImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/layout/ArrayElementTypeImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/layout/ArrayElementTypeImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutBuilderImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutBuilderImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/layout/LayoutBuilderImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutBuilderImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/layout/LayoutImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/layout/LayoutImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/layout/MatrixElementTypeImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/layout/MatrixElementTypeImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/layout/MatrixElementTypeImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/layout/MatrixElementTypeImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/layout/ScalarElementTypeImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/layout/ScalarElementTypeImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/layout/ScalarElementTypeImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/layout/ScalarElementTypeImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/layout/VectorElementTypeImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/layout/VectorElementTypeImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/layout/VectorElementTypeImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/layout/VectorElementTypeImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/BlockEntityTypeMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/BlockEntityTypeMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/BlockEntityTypeMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/BlockEntityTypeMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientChunkCacheMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientChunkCacheMixin.java similarity index 76% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/ClientChunkCacheMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientChunkCacheMixin.java index 4cf130204..30532a337 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientChunkCacheMixin.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientChunkCacheMixin.java @@ -15,17 +15,17 @@ import net.minecraft.world.level.LightLayer; @Mixin(ClientChunkCache.class) -public class ClientChunkCacheMixin { +abstract class ClientChunkCacheMixin { @Shadow @Final ClientLevel level; - @Inject(at = @At("HEAD"), method = "onLightUpdate") - private void flywheel$onLightUpdate(LightLayer pType, SectionPos pPos, CallbackInfo ci) { + @Inject(method = "onLightUpdate", at = @At("HEAD")) + private void flywheel$onLightUpdate(LightLayer layer, SectionPos pos, CallbackInfo ci) { var manager = VisualizationManagerImpl.get(level); if (manager != null) { - manager.enqueueLightUpdateSection(pPos.asLong()); + manager.enqueueLightUpdateSection(pos.asLong()); } } } diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientLevelMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientLevelMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/ClientLevelMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/ClientLevelMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/EntityTypeMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/EntityTypeMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/EntityTypeMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/EntityTypeMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/LevelMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelRendererMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelRendererMixin.java similarity index 84% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/LevelRendererMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelRendererMixin.java index 05c7af4f7..d9afd8992 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelRendererMixin.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/LevelRendererMixin.java @@ -11,13 +11,12 @@ import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At.Shift; +import org.spongepowered.asm.mixin.injection.Group; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import com.jozufozu.flywheel.api.event.BeginFrameEvent; -import com.jozufozu.flywheel.api.event.ReloadLevelRendererEvent; import com.jozufozu.flywheel.api.event.RenderStage; -import com.jozufozu.flywheel.api.event.RenderStageEvent; +import com.jozufozu.flywheel.impl.FlwImplXplat; import com.jozufozu.flywheel.impl.event.RenderContextImpl; import com.jozufozu.flywheel.impl.visualization.VisualizationManagerImpl; import com.mojang.blaze3d.vertex.PoseStack; @@ -30,11 +29,11 @@ import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.RenderBuffers; import net.minecraft.server.level.BlockDestructionProgress; -import net.minecraftforge.common.MinecraftForge; @Mixin(value = LevelRenderer.class, priority = 1001) // Higher priority to go after Sodium abstract class LevelRendererMixin { @Shadow + @Nullable private ClientLevel level; @Shadow @@ -54,7 +53,7 @@ abstract class LevelRendererMixin { private void flywheel$beginRender(PoseStack poseStack, float partialTick, long finishNanoTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f projectionMatrix, CallbackInfo ci) { flywheel$renderContext = RenderContextImpl.create((LevelRenderer) (Object) this, level, renderBuffers, poseStack, projectionMatrix, camera, partialTick); - MinecraftForge.EVENT_BUS.post(new BeginFrameEvent(flywheel$renderContext)); + FlwImplXplat.INSTANCE.dispatchBeginFrameEvent(flywheel$renderContext); } @Inject(method = "renderLevel", at = @At("RETURN")) @@ -64,7 +63,7 @@ abstract class LevelRendererMixin { @Inject(method = "allChanged", at = @At("RETURN")) private void flywheel$refresh(CallbackInfo ci) { - MinecraftForge.EVENT_BUS.post(new ReloadLevelRendererEvent(level)); + FlwImplXplat.INSTANCE.dispatchReloadLevelRendererEvent(level); } @Inject(method = "renderLevel", at = @At(value = "INVOKE_STRING", target = "Lnet/minecraft/util/profiling/ProfilerFiller;popPush(Ljava/lang/String;)V", args = "ldc=destroyProgress")) @@ -84,7 +83,7 @@ abstract class LevelRendererMixin { @Unique private void flywheel$dispatch(RenderStage stage) { if (flywheel$renderContext != null) { - MinecraftForge.EVENT_BUS.post(new RenderStageEvent(flywheel$renderContext, stage)); + FlwImplXplat.INSTANCE.dispatchRenderStageEvent(flywheel$renderContext, stage); } } @@ -108,8 +107,15 @@ abstract class LevelRendererMixin { flywheel$dispatch(RenderStage.AFTER_TRANSLUCENT_TERRAIN); } + @Group(name = "onStage$afterParticles", min = 2, max = 2) + @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V", shift = Shift.AFTER)) + private void flywheel$onStage$afterParticles$fabric(CallbackInfo ci) { + flywheel$dispatch(RenderStage.AFTER_PARTICLES); + } + + @Group(name = "onStage$afterParticles") @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;FLnet/minecraft/client/renderer/culling/Frustum;)V", shift = Shift.AFTER)) - private void flywheel$onStage$afterParticles(CallbackInfo ci) { + private void flywheel$onStage$afterParticles$forge(CallbackInfo ci) { flywheel$dispatch(RenderStage.AFTER_PARTICLES); } diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/PoseStackMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/PoseStackMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/PoseStackMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/PoseStackMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/VertexFormatMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/VertexFormatMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/VertexFormatMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/VertexFormatMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixFabulousDepthMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixFabulousDepthMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixFabulousDepthMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixFabulousDepthMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixNormalScalingMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixNormalScalingMixin.java similarity index 97% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixNormalScalingMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixNormalScalingMixin.java index b94f596c2..36abaff18 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixNormalScalingMixin.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/fix/FixNormalScalingMixin.java @@ -17,7 +17,7 @@ abstract class FixNormalScalingMixin { * applied, which negates the matrix again, resulting in the matrix being the * same as in the beginning. */ - @Inject(method = "scale(FFF)V", at = @At(value = "INVOKE", target = "Lorg/joml/Matrix3f;scale(F)Lorg/joml/Matrix3f;", shift = Shift.AFTER), cancellable = true) + @Inject(method = "scale(FFF)V", at = @At(value = "INVOKE", target = "Lorg/joml/Matrix3f;scale(F)Lorg/joml/Matrix3f;", shift = Shift.AFTER, remap = false), cancellable = true) private void flywheel$returnAfterNegate(float x, float y, float z, CallbackInfo ci) { ci.cancel(); } diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/BlockEntityMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/BlockEntityMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/BlockEntityMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/BlockEntityMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelChunkMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelChunkMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelChunkMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelChunkMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelRendererMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelRendererMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelRendererMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/LevelRendererMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/RebuildTaskMixin.java b/common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/RebuildTaskMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/RebuildTaskMixin.java rename to common/src/main/java/com/jozufozu/flywheel/impl/mixin/visualmanage/RebuildTaskMixin.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/registry/IdRegistryImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/registry/IdRegistryImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/registry/IdRegistryImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/registry/IdRegistryImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/registry/RegistryImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/registry/RegistryImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/registry/RegistryImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/registry/RegistryImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/task/FlwTaskExecutor.java b/common/src/main/java/com/jozufozu/flywheel/impl/task/FlwTaskExecutor.java similarity index 94% rename from src/main/java/com/jozufozu/flywheel/impl/task/FlwTaskExecutor.java rename to common/src/main/java/com/jozufozu/flywheel/impl/task/FlwTaskExecutor.java index 0caa47fbd..470cb97e5 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/task/FlwTaskExecutor.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/task/FlwTaskExecutor.java @@ -4,7 +4,7 @@ import org.apache.commons.lang3.concurrent.ConcurrentUtils; import com.jozufozu.flywheel.api.task.TaskExecutor; -import com.jozufozu.flywheel.config.FlwConfig; +import com.jozufozu.flywheel.impl.FlwConfig; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.util.Mth; @@ -39,7 +39,7 @@ private static int getMaxThreadCount() { private static class Initializer extends AtomicSafeInitializer { @Override protected TaskExecutor initialize() { - int threadCount = FlwConfig.get() + int threadCount = FlwConfig.INSTANCE .workerThreads(); if (threadCount == 0) { diff --git a/src/main/java/com/jozufozu/flywheel/impl/task/ParallelTaskExecutor.java b/common/src/main/java/com/jozufozu/flywheel/impl/task/ParallelTaskExecutor.java similarity index 94% rename from src/main/java/com/jozufozu/flywheel/impl/task/ParallelTaskExecutor.java rename to common/src/main/java/com/jozufozu/flywheel/impl/task/ParallelTaskExecutor.java index d16efb030..eb1e38282 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/task/ParallelTaskExecutor.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/task/ParallelTaskExecutor.java @@ -9,19 +9,14 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BooleanSupplier; -import org.slf4j.Logger; - -import com.jozufozu.flywheel.Flywheel; import com.jozufozu.flywheel.api.task.TaskExecutor; -import com.mojang.logging.LogUtils; +import com.jozufozu.flywheel.impl.FlwImpl; import net.minecraft.util.Mth; // https://github.com/CaffeineMC/sodium-fabric/blob/5d364ed5ba63f9067fcf72a078ca310bff4db3e9/src/main/java/me/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuilder.java // https://stackoverflow.com/questions/29655531 public class ParallelTaskExecutor implements TaskExecutor { - private static final Logger LOGGER = LogUtils.getLogger(); - private final String name; private final int threadCount; @@ -70,7 +65,7 @@ public void startWorkers() { threads.add(thread); } - LOGGER.info("Started {} worker threads", threads.size()); + FlwImpl.LOGGER.info("Started {} worker threads", threads.size()); } public void stopWorkers() { @@ -82,7 +77,7 @@ public void stopWorkers() { throw new IllegalStateException("No threads are alive but the executor is in the RUNNING state"); } - LOGGER.info("Stopping worker threads"); + FlwImpl.LOGGER.info("Stopping worker threads"); // Notify all worker threads to wake up, where they will then terminate synchronized (taskNotifier) { @@ -233,7 +228,7 @@ private void processTask(Runnable task) { try { task.run(); } catch (Exception e) { - Flywheel.LOGGER.error("Error running task", e); + FlwImpl.LOGGER.error("Error running task", e); } finally { waitGroup.done(); } @@ -243,7 +238,7 @@ private void processMainThreadTask(Runnable task) { try { task.run(); } catch (Exception e) { - Flywheel.LOGGER.error("Error running main thread task", e); + FlwImpl.LOGGER.error("Error running main thread task", e); } } diff --git a/src/main/java/com/jozufozu/flywheel/impl/task/SerialTaskExecutor.java b/common/src/main/java/com/jozufozu/flywheel/impl/task/SerialTaskExecutor.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/task/SerialTaskExecutor.java rename to common/src/main/java/com/jozufozu/flywheel/impl/task/SerialTaskExecutor.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/task/ThreadGroupNotifier.java b/common/src/main/java/com/jozufozu/flywheel/impl/task/ThreadGroupNotifier.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/task/ThreadGroupNotifier.java rename to common/src/main/java/com/jozufozu/flywheel/impl/task/ThreadGroupNotifier.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/task/WaitGroup.java b/common/src/main/java/com/jozufozu/flywheel/impl/task/WaitGroup.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/task/WaitGroup.java rename to common/src/main/java/com/jozufozu/flywheel/impl/task/WaitGroup.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexFormatInfo.java b/common/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexFormatInfo.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexFormatInfo.java rename to common/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexFormatInfo.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexView.java b/common/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexView.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexView.java rename to common/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexView.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexViewProvider.java b/common/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexViewProvider.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexViewProvider.java rename to common/src/main/java/com/jozufozu/flywheel/impl/vertex/InferredVertexViewProvider.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/vertex/VertexViewProviderRegistryImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/vertex/VertexViewProviderRegistryImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/vertex/VertexViewProviderRegistryImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/vertex/VertexViewProviderRegistryImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visual/DynamicVisualContextImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/visual/DynamicVisualContextImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visual/DynamicVisualContextImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visual/DynamicVisualContextImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visual/TickableVisualContextImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/visual/TickableVisualContextImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visual/TickableVisualContextImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visual/TickableVisualContextImpl.java diff --git a/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationEventHandler.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationEventHandler.java new file mode 100644 index 000000000..15f1102de --- /dev/null +++ b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationEventHandler.java @@ -0,0 +1,67 @@ +package com.jozufozu.flywheel.impl.visualization; + +import com.jozufozu.flywheel.api.event.RenderContext; +import com.jozufozu.flywheel.api.event.RenderStage; +import com.jozufozu.flywheel.api.visualization.VisualizationManager; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; + +public final class VisualizationEventHandler { + private VisualizationEventHandler() { + } + + public static void onClientTick(Minecraft minecraft, Level level) { + // The game won't be paused in the tick event, but let's make sure there's a player. + if (minecraft.player == null) { + return; + } + + VisualizationManagerImpl manager = VisualizationManagerImpl.get(level); + if (manager == null) { + return; + } + + manager.tick(); + } + + public static void onBeginFrame(RenderContext context) { + ClientLevel level = context.level(); + VisualizationManagerImpl manager = VisualizationManagerImpl.get(level); + if (manager == null) { + return; + } + + manager.beginFrame(context); + } + + public static void onRenderStage(RenderContext context, RenderStage stage) { + ClientLevel level = context.level(); + VisualizationManagerImpl manager = VisualizationManagerImpl.get(level); + if (manager == null) { + return; + } + + manager.renderStage(context, stage); + } + + public static void onEntityJoinLevel(Level level, Entity entity) { + VisualizationManager manager = VisualizationManager.get(level); + if (manager == null) { + return; + } + + manager.getEntities().queueAdd(entity); + } + + public static void onEntityLeaveLevel(Level level, Entity entity) { + VisualizationManager manager = VisualizationManager.get(level); + if (manager == null) { + return; + } + + manager.getEntities().queueRemove(entity); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationHelper.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationHelper.java similarity index 94% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationHelper.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationHelper.java index 439d4dcd6..b9ede2802 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationHelper.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationHelper.java @@ -31,8 +31,8 @@ public static EntityVisualizer getVisualizer(T ent /** * Checks if the given block entity can be visualized. - * @param type The block entity to check. - * @param The block entity. + * @param blockEntity The block entity to check. + * @param The type of the block entity. * @return {@code true} if the block entity can be visualized. */ public static boolean canVisualize(T blockEntity) { @@ -41,8 +41,8 @@ public static boolean canVisualize(T blockEntity) { /** * Checks if the given entity can be visualized. - * @param type The entity to check. - * @param The entity. + * @param entity The entity to check. + * @param The type of the entity. * @return {@code true} if the entity can be visualized. */ public static boolean canVisualize(T entity) { diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationManagerImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationManagerImpl.java similarity index 96% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationManagerImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationManagerImpl.java index adc6ffc2e..300621739 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationManagerImpl.java +++ b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationManagerImpl.java @@ -24,7 +24,7 @@ import com.jozufozu.flywheel.api.visualization.VisualizationContext; import com.jozufozu.flywheel.api.visualization.VisualizationLevel; import com.jozufozu.flywheel.api.visualization.VisualizationManager; -import com.jozufozu.flywheel.config.FlwConfig; +import com.jozufozu.flywheel.impl.FlwConfig; import com.jozufozu.flywheel.impl.extension.LevelExtension; import com.jozufozu.flywheel.impl.task.FlwTaskExecutor; import com.jozufozu.flywheel.impl.visual.DynamicVisualContextImpl; @@ -133,7 +133,7 @@ private DynamicVisual.Context createVisualFrameContext(RenderContext ctx) { } protected DistanceUpdateLimiterImpl createUpdateLimiter() { - if (FlwConfig.get() + if (FlwConfig.INSTANCE .limitUpdates()) { return new BandedPrimeLimiter(); } else { @@ -210,10 +210,7 @@ public VisualManager getEffects() { } /** - * Tick the visuals after the game has ticked: - *

- * Call {@link TickableVisual#tick} on all visuals in this level. - *

+ * Begin execution of the tick plan. */ public void tick() { // Make sure we're done with any prior frame or tick to avoid racing. @@ -227,11 +224,7 @@ public void tick() { } /** - * Get ready to render a frame. - * - *

Check and update the render origin. - *
- * Call {@link DynamicVisual#beginFrame} on all visuals in this level.

+ * Begin execution of the frame plan. */ public void beginFrame(RenderContext context) { // Make sure we're done with the last tick. diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizerRegistryImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizerRegistryImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizerRegistryImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizerRegistryImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/BlockEntityStorage.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/BlockEntityStorage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/manager/BlockEntityStorage.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/BlockEntityStorage.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EffectStorage.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EffectStorage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EffectStorage.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EffectStorage.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EntityStorage.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EntityStorage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EntityStorage.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/EntityStorage.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/VisualManagerImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/VisualManagerImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/manager/VisualManagerImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/manager/VisualManagerImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/BandedPrimeLimiter.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/BandedPrimeLimiter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/BandedPrimeLimiter.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/BandedPrimeLimiter.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/DistanceUpdateLimiterImpl.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/DistanceUpdateLimiterImpl.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/DistanceUpdateLimiterImpl.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/DistanceUpdateLimiterImpl.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/NonLimiter.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/NonLimiter.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/NonLimiter.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/ratelimit/NonLimiter.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Action.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Action.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Action.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Action.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/LitVisualStorage.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/LitVisualStorage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/storage/LitVisualStorage.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/LitVisualStorage.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Storage.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Storage.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Storage.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Storage.java diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Transaction.java b/common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Transaction.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Transaction.java rename to common/src/main/java/com/jozufozu/flywheel/impl/visualization/storage/Transaction.java diff --git a/src/main/java/com/jozufozu/flywheel/vanilla/BellVisual.java b/common/src/main/java/com/jozufozu/flywheel/vanilla/BellVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/vanilla/BellVisual.java rename to common/src/main/java/com/jozufozu/flywheel/vanilla/BellVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/vanilla/ChestVisual.java b/common/src/main/java/com/jozufozu/flywheel/vanilla/ChestVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/vanilla/ChestVisual.java rename to common/src/main/java/com/jozufozu/flywheel/vanilla/ChestVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/vanilla/MinecartVisual.java b/common/src/main/java/com/jozufozu/flywheel/vanilla/MinecartVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/vanilla/MinecartVisual.java rename to common/src/main/java/com/jozufozu/flywheel/vanilla/MinecartVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/vanilla/ShulkerBoxVisual.java b/common/src/main/java/com/jozufozu/flywheel/vanilla/ShulkerBoxVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/vanilla/ShulkerBoxVisual.java rename to common/src/main/java/com/jozufozu/flywheel/vanilla/ShulkerBoxVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/vanilla/TntMinecartVisual.java b/common/src/main/java/com/jozufozu/flywheel/vanilla/TntMinecartVisual.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/vanilla/TntMinecartVisual.java rename to common/src/main/java/com/jozufozu/flywheel/vanilla/TntMinecartVisual.java diff --git a/src/main/java/com/jozufozu/flywheel/vanilla/VanillaVisuals.java b/common/src/main/java/com/jozufozu/flywheel/vanilla/VanillaVisuals.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/vanilla/VanillaVisuals.java rename to common/src/main/java/com/jozufozu/flywheel/vanilla/VanillaVisuals.java diff --git a/src/main/resources/assets/flywheel/lang/en_us.json b/common/src/main/resources/assets/flywheel/lang/en_us.json similarity index 100% rename from src/main/resources/assets/flywheel/lang/en_us.json rename to common/src/main/resources/assets/flywheel/lang/en_us.json diff --git a/src/main/resources/flywheel.impl.mixins.json b/common/src/main/resources/flywheel.impl.mixins.json similarity index 100% rename from src/main/resources/flywheel.impl.mixins.json rename to common/src/main/resources/flywheel.impl.mixins.json diff --git a/src/main/resources/logo.png b/common/src/main/resources/logo.png similarity index 100% rename from src/main/resources/logo.png rename to common/src/main/resources/logo.png diff --git a/src/test/java/com/jozufozu/flywheel/backend/glsl/MockShaderSources.java b/common/src/test/java/com/jozufozu/flywheel/backend/glsl/MockShaderSources.java similarity index 100% rename from src/test/java/com/jozufozu/flywheel/backend/glsl/MockShaderSources.java rename to common/src/test/java/com/jozufozu/flywheel/backend/glsl/MockShaderSources.java diff --git a/src/test/java/com/jozufozu/flywheel/backend/glsl/TestBase.java b/common/src/test/java/com/jozufozu/flywheel/backend/glsl/TestBase.java similarity index 97% rename from src/test/java/com/jozufozu/flywheel/backend/glsl/TestBase.java rename to common/src/test/java/com/jozufozu/flywheel/backend/glsl/TestBase.java index beebdad43..1d74bdebb 100644 --- a/src/test/java/com/jozufozu/flywheel/backend/glsl/TestBase.java +++ b/common/src/test/java/com/jozufozu/flywheel/backend/glsl/TestBase.java @@ -6,7 +6,7 @@ import java.util.List; -import com.jozufozu.flywheel.Flywheel; +import com.jozufozu.flywheel.api.Flywheel; import net.minecraft.resources.ResourceLocation; diff --git a/src/test/java/com/jozufozu/flywheel/backend/glsl/TestErrorMessages.java b/common/src/test/java/com/jozufozu/flywheel/backend/glsl/TestErrorMessages.java similarity index 100% rename from src/test/java/com/jozufozu/flywheel/backend/glsl/TestErrorMessages.java rename to common/src/test/java/com/jozufozu/flywheel/backend/glsl/TestErrorMessages.java diff --git a/src/test/java/com/jozufozu/flywheel/backend/glsl/TestShaderSourceLoading.java b/common/src/test/java/com/jozufozu/flywheel/backend/glsl/TestShaderSourceLoading.java similarity index 100% rename from src/test/java/com/jozufozu/flywheel/backend/glsl/TestShaderSourceLoading.java rename to common/src/test/java/com/jozufozu/flywheel/backend/glsl/TestShaderSourceLoading.java diff --git a/src/test/java/com/jozufozu/flywheel/impl/task/WaitGroupTest.java b/common/src/test/java/com/jozufozu/flywheel/impl/task/WaitGroupTest.java similarity index 100% rename from src/test/java/com/jozufozu/flywheel/impl/task/WaitGroupTest.java rename to common/src/test/java/com/jozufozu/flywheel/impl/task/WaitGroupTest.java diff --git a/src/test/java/com/jozufozu/flywheel/lib/task/PlanCompositionTest.java b/common/src/test/java/com/jozufozu/flywheel/lib/task/PlanCompositionTest.java similarity index 100% rename from src/test/java/com/jozufozu/flywheel/lib/task/PlanCompositionTest.java rename to common/src/test/java/com/jozufozu/flywheel/lib/task/PlanCompositionTest.java diff --git a/src/test/java/com/jozufozu/flywheel/lib/task/PlanExecutionTest.java b/common/src/test/java/com/jozufozu/flywheel/lib/task/PlanExecutionTest.java similarity index 100% rename from src/test/java/com/jozufozu/flywheel/lib/task/PlanExecutionTest.java rename to common/src/test/java/com/jozufozu/flywheel/lib/task/PlanExecutionTest.java diff --git a/src/test/java/com/jozufozu/flywheel/lib/util/TestAtomicBitset.java b/common/src/test/java/com/jozufozu/flywheel/lib/util/TestAtomicBitset.java similarity index 100% rename from src/test/java/com/jozufozu/flywheel/lib/util/TestAtomicBitset.java rename to common/src/test/java/com/jozufozu/flywheel/lib/util/TestAtomicBitset.java diff --git a/fabric/build.gradle.kts b/fabric/build.gradle.kts new file mode 100644 index 000000000..b2c53440d --- /dev/null +++ b/fabric/build.gradle.kts @@ -0,0 +1,74 @@ +plugins { + idea + java + `maven-publish` + id("dev.architectury.loom") + id("flywheel.subproject") + id("flywheel.platform") +} + +val api = sourceSets.create("api") +val lib = sourceSets.create("lib") +val backend = sourceSets.create("backend") +val main = sourceSets.getByName("main") + +transitiveSourceSets { + compileClasspath = main.compileClasspath + + sourceSet(api) { + rootCompile() + } + sourceSet(lib) { + rootCompile() + compile(api) + } + sourceSet(backend) { + rootCompile() + compile(api, lib) + } + sourceSet(main) { + implementation(api, lib, backend) + } + + createCompileConfigurations() +} + +platform { + commonProject = project(":common") + sources(api, lib, backend, main) + compileWithCommonSourceSets() + setupLoomMod() + setupLoomRuns() + setupFatJar() +} + +jarSets { + mainSet.publish(platform.modArtifactId) + create("api", api, lib).apply { + addToAssemble() + publish(platform.apiArtifactId) + + configureJar { + manifest { + attributes("Fabric-Loom-Remap" to "true") + } + } + } +} + +defaultPackageInfos { + sources(api, lib, backend, main) +} + +dependencies { + modImplementation("net.fabricmc:fabric-loader:${property("fabric_loader_version")}") + modApi("net.fabricmc.fabric-api:fabric-api:${property("fabric_api_version")}") + + modCompileOnly("maven.modrinth:sodium:${property("sodium_version")}") + modCompileOnly("maven.modrinth:iris:${property("iris_version")}") + + "forApi"(project(path = ":common", configuration = "commonApiOnly")) + "forLib"(project(path = ":common", configuration = "commonLib")) + "forBackend"(project(path = ":common", configuration = "commonBackend")) + "forMain"(project(path = ":common", configuration = "commonImpl")) +} diff --git a/fabric/gradle.properties b/fabric/gradle.properties new file mode 100644 index 000000000..6c5947614 --- /dev/null +++ b/fabric/gradle.properties @@ -0,0 +1 @@ +loom.platform = fabric diff --git a/fabric/src/api/java/com/jozufozu/flywheel/api/event/BeginFrameCallback.java b/fabric/src/api/java/com/jozufozu/flywheel/api/event/BeginFrameCallback.java new file mode 100644 index 000000000..47d16fd95 --- /dev/null +++ b/fabric/src/api/java/com/jozufozu/flywheel/api/event/BeginFrameCallback.java @@ -0,0 +1,15 @@ +package com.jozufozu.flywheel.api.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; + +@FunctionalInterface +public interface BeginFrameCallback { + Event EVENT = EventFactory.createArrayBacked(BeginFrameCallback.class, callbacks -> context -> { + for (BeginFrameCallback callback : callbacks) { + callback.onBeginFrame(context); + } + }); + + void onBeginFrame(RenderContext context); +} diff --git a/fabric/src/api/java/com/jozufozu/flywheel/api/event/EndClientResourceReloadCallback.java b/fabric/src/api/java/com/jozufozu/flywheel/api/event/EndClientResourceReloadCallback.java new file mode 100644 index 000000000..d6f1a8644 --- /dev/null +++ b/fabric/src/api/java/com/jozufozu/flywheel/api/event/EndClientResourceReloadCallback.java @@ -0,0 +1,21 @@ +package com.jozufozu.flywheel.api.event; + +import java.util.Optional; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.client.Minecraft; +import net.minecraft.server.packs.resources.ResourceManager; + +@FunctionalInterface +public interface EndClientResourceReloadCallback { + Event EVENT = EventFactory.createArrayBacked(EndClientResourceReloadCallback.class, + callbacks -> (minecraft, resourceManager, initialReload, error) -> { + for (EndClientResourceReloadCallback callback : callbacks) { + callback.onEndClientResourceReload(minecraft, resourceManager, initialReload, error); + } + }); + + void onEndClientResourceReload(Minecraft minecraft, ResourceManager resourceManager, boolean initialReload, + Optional error); +} diff --git a/fabric/src/api/java/com/jozufozu/flywheel/api/event/ReloadLevelRendererCallback.java b/fabric/src/api/java/com/jozufozu/flywheel/api/event/ReloadLevelRendererCallback.java new file mode 100644 index 000000000..a8b448c3d --- /dev/null +++ b/fabric/src/api/java/com/jozufozu/flywheel/api/event/ReloadLevelRendererCallback.java @@ -0,0 +1,19 @@ +package com.jozufozu.flywheel.api.event; + +import org.jetbrains.annotations.Nullable; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; +import net.minecraft.client.multiplayer.ClientLevel; + +@FunctionalInterface +public interface ReloadLevelRendererCallback { + Event EVENT = + EventFactory.createArrayBacked(ReloadLevelRendererCallback.class, callbacks -> level -> { + for (ReloadLevelRendererCallback callback : callbacks) { + callback.onReloadLevelRenderer(level); + } + }); + + void onReloadLevelRenderer(@Nullable ClientLevel level); +} diff --git a/fabric/src/api/java/com/jozufozu/flywheel/api/event/RenderStageCallback.java b/fabric/src/api/java/com/jozufozu/flywheel/api/event/RenderStageCallback.java new file mode 100644 index 000000000..64e8061ad --- /dev/null +++ b/fabric/src/api/java/com/jozufozu/flywheel/api/event/RenderStageCallback.java @@ -0,0 +1,16 @@ +package com.jozufozu.flywheel.api.event; + +import net.fabricmc.fabric.api.event.Event; +import net.fabricmc.fabric.api.event.EventFactory; + +@FunctionalInterface +public interface RenderStageCallback { + Event EVENT = + EventFactory.createArrayBacked(RenderStageCallback.class, callbacks -> (context, stage) -> { + for (RenderStageCallback callback : callbacks) { + callback.onRenderStage(context, stage); + } + }); + + void onRenderStage(RenderContext context, RenderStage stage); +} diff --git a/fabric/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplatImpl.java b/fabric/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplatImpl.java new file mode 100644 index 000000000..222c3c183 --- /dev/null +++ b/fabric/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplatImpl.java @@ -0,0 +1,12 @@ +package com.jozufozu.flywheel.backend; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.state.BlockState; + +public class FlwBackendXplatImpl implements FlwBackendXplat { + @Override + public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) { + return state.getLightEmission(); + } +} diff --git a/fabric/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwProgramsReloader.java b/fabric/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwProgramsReloader.java new file mode 100644 index 000000000..4d32525eb --- /dev/null +++ b/fabric/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwProgramsReloader.java @@ -0,0 +1,26 @@ +package com.jozufozu.flywheel.backend.compile; + +import com.jozufozu.flywheel.api.Flywheel; + +import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; + +public final class FlwProgramsReloader implements SimpleSynchronousResourceReloadListener { + public static final FlwProgramsReloader INSTANCE = new FlwProgramsReloader(); + + public static final ResourceLocation ID = Flywheel.rl("programs"); + + private FlwProgramsReloader() { + } + + @Override + public void onResourceManagerReload(ResourceManager manager) { + FlwPrograms.reload(manager); + } + + @Override + public ResourceLocation getFabricId() { + return ID; + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java new file mode 100644 index 000000000..a0eb2302d --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java @@ -0,0 +1,154 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.Iterator; + +import org.jetbrains.annotations.Nullable; + +import com.mojang.blaze3d.vertex.BufferBuilder.RenderedBuffer; +import com.mojang.blaze3d.vertex.PoseStack; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; +import net.minecraft.client.renderer.ItemBlockRenderTypes; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.client.renderer.block.ModelBlockRenderer; +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.RenderShape; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; + +final class BakedModelBufferer { + static final RenderType[] CHUNK_LAYERS = RenderType.chunkBufferLayers().toArray(RenderType[]::new); + static final int CHUNK_LAYER_AMOUNT = CHUNK_LAYERS.length; + + private static final ThreadLocal THREAD_LOCAL_OBJECTS = ThreadLocal.withInitial(ThreadLocalObjects::new); + + private BakedModelBufferer() { + } + + public static void bufferSingle(ModelBlockRenderer blockRenderer, BlockAndTintGetter level, BakedModel model, BlockState state, @Nullable PoseStack poseStack, ResultConsumer resultConsumer) { + ThreadLocalObjects objects = THREAD_LOCAL_OBJECTS.get(); + if (poseStack == null) { + poseStack = objects.identityPoseStack; + } + RandomSource random = objects.random; + MeshEmitter[] emitters = objects.emitters; + UniversalMeshEmitter universalEmitter = objects.universalEmitter; + + for (MeshEmitter emitter : emitters) { + emitter.prepare(resultConsumer); + } + + RenderType defaultLayer = ItemBlockRenderTypes.getChunkRenderType(state); + universalEmitter.prepare(defaultLayer); + model = universalEmitter.wrapModel(model); + + poseStack.pushPose(); + blockRenderer.tesselateBlock(level, model, state, BlockPos.ZERO, poseStack, universalEmitter, false, random, 42L, OverlayTexture.NO_OVERLAY); + poseStack.popPose(); + + universalEmitter.clear(); + + for (MeshEmitter emitter : emitters) { + emitter.end(); + } + } + + public static void bufferBlock(BlockRenderDispatcher renderDispatcher, BlockAndTintGetter level, BlockState state, @Nullable PoseStack poseStack, ResultConsumer resultConsumer) { + if (state.getRenderShape() != RenderShape.MODEL) { + return; + } + + bufferSingle(renderDispatcher.getModelRenderer(), level, renderDispatcher.getBlockModel(state), state, poseStack, resultConsumer); + } + + public static void bufferMultiBlock(BlockRenderDispatcher renderDispatcher, Iterator posIterator, BlockAndTintGetter level, @Nullable PoseStack poseStack, boolean renderFluids, ResultConsumer resultConsumer) { + ThreadLocalObjects objects = THREAD_LOCAL_OBJECTS.get(); + if (poseStack == null) { + poseStack = objects.identityPoseStack; + } + RandomSource random = objects.random; + MeshEmitter[] emitters = objects.emitters; + Reference2ReferenceMap emitterMap = objects.emitterMap; + UniversalMeshEmitter universalEmitter = objects.universalEmitter; + TransformingVertexConsumer transformingWrapper = objects.transformingWrapper; + + for (MeshEmitter emitter : emitters) { + emitter.prepare(resultConsumer); + } + + ModelBlockRenderer blockRenderer = renderDispatcher.getModelRenderer(); + ModelBlockRenderer.enableCaching(); + + while (posIterator.hasNext()) { + BlockPos pos = posIterator.next(); + BlockState state = level.getBlockState(pos); + + if (renderFluids) { + FluidState fluidState = state.getFluidState(); + + if (!fluidState.isEmpty()) { + RenderType renderType = ItemBlockRenderTypes.getRenderLayer(fluidState); + + transformingWrapper.prepare(emitterMap.get(renderType).getBuffer(true), poseStack); + + poseStack.pushPose(); + poseStack.translate(pos.getX() - (pos.getX() & 0xF), pos.getY() - (pos.getY() & 0xF), pos.getZ() - (pos.getZ() & 0xF)); + renderDispatcher.renderLiquid(pos, level, transformingWrapper, state, fluidState); + poseStack.popPose(); + } + } + + if (state.getRenderShape() == RenderShape.MODEL) { + long seed = state.getSeed(pos); + BakedModel model = renderDispatcher.getBlockModel(state); + + RenderType defaultLayer = ItemBlockRenderTypes.getChunkRenderType(state); + universalEmitter.prepare(defaultLayer); + model = universalEmitter.wrapModel(model); + + poseStack.pushPose(); + poseStack.translate(pos.getX(), pos.getY(), pos.getZ()); + blockRenderer.tesselateBlock(level, model, state, pos, poseStack, universalEmitter, true, random, seed, OverlayTexture.NO_OVERLAY); + poseStack.popPose(); + } + } + + ModelBlockRenderer.clearCache(); + transformingWrapper.clear(); + universalEmitter.clear(); + + for (MeshEmitter emitter : emitters) { + emitter.end(); + } + } + + public interface ResultConsumer { + void accept(RenderType renderType, boolean shaded, RenderedBuffer data); + } + + private static class ThreadLocalObjects { + public final PoseStack identityPoseStack = new PoseStack(); + public final RandomSource random = RandomSource.createNewThreadLocalInstance(); + + public final MeshEmitter[] emitters = new MeshEmitter[CHUNK_LAYER_AMOUNT]; + public final Reference2ReferenceMap emitterMap = new Reference2ReferenceOpenHashMap<>(); + public final UniversalMeshEmitter universalEmitter; + public final TransformingVertexConsumer transformingWrapper = new TransformingVertexConsumer(); + + { + for (int layerIndex = 0; layerIndex < CHUNK_LAYER_AMOUNT; layerIndex++) { + RenderType renderType = CHUNK_LAYERS[layerIndex]; + MeshEmitter emitter = new MeshEmitter(renderType); + emitters[layerIndex] = emitter; + emitterMap.put(renderType, emitter); + } + universalEmitter = new UniversalMeshEmitter(emitterMap); + } + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ChunkLayerSortedListBuilder.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ChunkLayerSortedListBuilder.java new file mode 100644 index 000000000..5978d7729 --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ChunkLayerSortedListBuilder.java @@ -0,0 +1,58 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.List; + +import com.google.common.collect.ImmutableList; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; +import net.minecraft.client.renderer.RenderType; + +class ChunkLayerSortedListBuilder { + private static final ThreadLocal> THREAD_LOCAL = ThreadLocal.withInitial(ChunkLayerSortedListBuilder::new); + + @SuppressWarnings("unchecked") + private final ObjectArrayList[] lists = new ObjectArrayList[BakedModelBufferer.CHUNK_LAYER_AMOUNT]; + private final Reference2ReferenceMap> map = new Reference2ReferenceOpenHashMap<>(); + + private ChunkLayerSortedListBuilder() { + for (int layerIndex = 0; layerIndex < BakedModelBufferer.CHUNK_LAYER_AMOUNT; layerIndex++) { + RenderType renderType = BakedModelBufferer.CHUNK_LAYERS[layerIndex]; + ObjectArrayList list = new ObjectArrayList<>(); + lists[layerIndex] = list; + map.put(renderType, list); + } + } + + @SuppressWarnings("unchecked") + public static ChunkLayerSortedListBuilder getThreadLocal() { + return (ChunkLayerSortedListBuilder) THREAD_LOCAL.get(); + } + + public void add(RenderType renderType, T obj) { + List list = map.get(renderType); + if (list == null) { + throw new IllegalArgumentException("RenderType '" + renderType + "' is not a chunk layer"); + } + list.add(obj); + } + + @SuppressWarnings("unchecked") + public ImmutableList build() { + int size = 0; + for (ObjectArrayList list : lists) { + size += list.size(); + } + + T[] array = (T[]) new Object[size]; + int destPos = 0; + for (ObjectArrayList list : lists) { + System.arraycopy(list.elements(), 0, array, destPos, list.size()); + destPos += list.size(); + list.clear(); + } + + return ImmutableList.copyOf(array); + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricBakedModelBuilder.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricBakedModelBuilder.java new file mode 100644 index 000000000..f853ac884 --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricBakedModelBuilder.java @@ -0,0 +1,76 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.function.BiFunction; + +import com.jozufozu.flywheel.api.material.Material; +import com.jozufozu.flywheel.api.model.Model; +import com.jozufozu.flywheel.api.vertex.VertexView; +import com.jozufozu.flywheel.lib.memory.MemoryBlock; +import com.jozufozu.flywheel.lib.model.ModelUtil; +import com.jozufozu.flywheel.lib.model.SimpleMesh; +import com.jozufozu.flywheel.lib.model.SimpleModel; +import com.jozufozu.flywheel.lib.vertex.NoOverlayVertexView; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; + +public final class FabricBakedModelBuilder extends BakedModelBuilder { + public FabricBakedModelBuilder(BakedModel bakedModel) { + super(bakedModel); + } + + @Override + public FabricBakedModelBuilder level(BlockAndTintGetter level) { + super.level(level); + return this; + } + + @Override + public FabricBakedModelBuilder blockState(BlockState blockState) { + super.blockState(blockState); + return this; + } + + @Override + public FabricBakedModelBuilder poseStack(PoseStack poseStack) { + super.poseStack(poseStack); + return this; + } + + @Override + public FabricBakedModelBuilder materialFunc(BiFunction materialFunc) { + super.materialFunc(materialFunc); + return this; + } + + @Override + public SimpleModel build() { + if (level == null) { + level = VirtualEmptyBlockGetter.INSTANCE; + } + if (blockState == null) { + blockState = Blocks.AIR.defaultBlockState(); + } + if (materialFunc == null) { + materialFunc = ModelUtil::getMaterial; + } + + var builder = ChunkLayerSortedListBuilder.getThreadLocal(); + + BakedModelBufferer.bufferSingle(ModelUtil.VANILLA_RENDERER.getModelRenderer(), level, bakedModel, blockState, poseStack, (renderType, shaded, data) -> { + Material material = materialFunc.apply(renderType, shaded); + if (material != null) { + VertexView vertexView = new NoOverlayVertexView(); + MemoryBlock meshData = ModelUtil.convertVanillaBuffer(data, vertexView); + var mesh = new SimpleMesh(vertexView, meshData, "source=BakedModelBuilder," + "bakedModel=" + bakedModel + ",renderType=" + renderType + ",shaded=" + shaded); + builder.add(renderType, new Model.ConfiguredMesh(material, mesh)); + } + }); + + return new SimpleModel(builder.build()); + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricBlockModelBuilder.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricBlockModelBuilder.java new file mode 100644 index 000000000..a64144135 --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricBlockModelBuilder.java @@ -0,0 +1,65 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.function.BiFunction; + +import com.jozufozu.flywheel.api.material.Material; +import com.jozufozu.flywheel.api.model.Model; +import com.jozufozu.flywheel.api.vertex.VertexView; +import com.jozufozu.flywheel.lib.memory.MemoryBlock; +import com.jozufozu.flywheel.lib.model.ModelUtil; +import com.jozufozu.flywheel.lib.model.SimpleMesh; +import com.jozufozu.flywheel.lib.model.SimpleModel; +import com.jozufozu.flywheel.lib.vertex.NoOverlayVertexView; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.renderer.RenderType; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; + +public final class FabricBlockModelBuilder extends BlockModelBuilder { + public FabricBlockModelBuilder(BlockState state) { + super(state); + } + + @Override + public FabricBlockModelBuilder level(BlockAndTintGetter level) { + super.level(level); + return this; + } + + @Override + public FabricBlockModelBuilder poseStack(PoseStack poseStack) { + super.poseStack(poseStack); + return this; + } + + @Override + public FabricBlockModelBuilder materialFunc(BiFunction materialFunc) { + super.materialFunc(materialFunc); + return this; + } + + @Override + public SimpleModel build() { + if (level == null) { + level = VirtualEmptyBlockGetter.INSTANCE; + } + if (materialFunc == null) { + materialFunc = ModelUtil::getMaterial; + } + + var builder = ChunkLayerSortedListBuilder.getThreadLocal(); + + BakedModelBufferer.bufferBlock(ModelUtil.VANILLA_RENDERER, level, state, poseStack, (renderType, shaded, data) -> { + Material material = materialFunc.apply(renderType, shaded); + if (material != null) { + VertexView vertexView = new NoOverlayVertexView(); + MemoryBlock meshData = ModelUtil.convertVanillaBuffer(data, vertexView); + var mesh = new SimpleMesh(vertexView, meshData, "source=BlockModelBuilder," + "blockState=" + state + ",renderType=" + renderType + ",shaded=" + shaded); + builder.add(renderType, new Model.ConfiguredMesh(material, mesh)); + } + }); + + return new SimpleModel(builder.build()); + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricMultiBlockModelBuilder.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricMultiBlockModelBuilder.java new file mode 100644 index 000000000..74a4f29f1 --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/FabricMultiBlockModelBuilder.java @@ -0,0 +1,62 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.function.BiFunction; + +import com.jozufozu.flywheel.api.material.Material; +import com.jozufozu.flywheel.api.model.Model; +import com.jozufozu.flywheel.api.vertex.VertexView; +import com.jozufozu.flywheel.lib.memory.MemoryBlock; +import com.jozufozu.flywheel.lib.model.ModelUtil; +import com.jozufozu.flywheel.lib.model.SimpleMesh; +import com.jozufozu.flywheel.lib.model.SimpleModel; +import com.jozufozu.flywheel.lib.vertex.NoOverlayVertexView; +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.renderer.RenderType; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; + +public final class FabricMultiBlockModelBuilder extends MultiBlockModelBuilder { + public FabricMultiBlockModelBuilder(BlockAndTintGetter level, Iterable positions) { + super(level, positions); + } + + @Override + public FabricMultiBlockModelBuilder poseStack(PoseStack poseStack) { + super.poseStack(poseStack); + return this; + } + + @Override + public FabricMultiBlockModelBuilder enableFluidRendering() { + super.enableFluidRendering(); + return this; + } + + @Override + public FabricMultiBlockModelBuilder materialFunc(BiFunction materialFunc) { + super.materialFunc(materialFunc); + return this; + } + + @Override + public SimpleModel build() { + if (materialFunc == null) { + materialFunc = ModelUtil::getMaterial; + } + + var builder = ChunkLayerSortedListBuilder.getThreadLocal(); + + BakedModelBufferer.bufferMultiBlock(ModelUtil.VANILLA_RENDERER, positions.iterator(), level, poseStack, renderFluids, (renderType, shaded, data) -> { + Material material = materialFunc.apply(renderType, shaded); + if (material != null) { + VertexView vertexView = new NoOverlayVertexView(); + MemoryBlock meshData = ModelUtil.convertVanillaBuffer(data, vertexView); + var mesh = new SimpleMesh(vertexView, meshData, "source=MultiBlockModelBuilder," + "renderType=" + renderType + ",shaded=" + shaded); + builder.add(renderType, new Model.ConfiguredMesh(material, mesh)); + } + }); + + return new SimpleModel(builder.build()); + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java new file mode 100644 index 000000000..c443807af --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java @@ -0,0 +1,57 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import org.jetbrains.annotations.UnknownNullability; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; + +import net.minecraft.client.renderer.RenderType; + +class MeshEmitter { + private final RenderType renderType; + private final BufferBuilder bufferBuilder; + + private BakedModelBufferer.@UnknownNullability ResultConsumer resultConsumer; + private boolean currentShade; + + MeshEmitter(RenderType renderType) { + this.renderType = renderType; + this.bufferBuilder = new BufferBuilder(renderType.bufferSize()); + } + + public void prepare(BakedModelBufferer.ResultConsumer resultConsumer) { + this.resultConsumer = resultConsumer; + } + + public void end() { + if (bufferBuilder.building()) { + emit(); + } + resultConsumer = null; + } + + public BufferBuilder getBuffer(boolean shade) { + prepareForGeometry(shade); + return bufferBuilder; + } + + void prepareForGeometry(boolean shade) { + if (!bufferBuilder.building()) { + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLOCK); + } else if (shade != currentShade) { + emit(); + } + + currentShade = shade; + } + + void emit() { + var renderedBuffer = bufferBuilder.endOrDiscardIfEmpty(); + + if (renderedBuffer != null) { + resultConsumer.accept(renderType, currentShade, renderedBuffer); + renderedBuffer.release(); + } + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModelEventHandler.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModelEventHandler.java new file mode 100644 index 000000000..a1d80cbd0 --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModelEventHandler.java @@ -0,0 +1,56 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.List; + +import org.jetbrains.annotations.ApiStatus; + +import com.jozufozu.flywheel.api.Flywheel; + +import net.fabricmc.fabric.api.resource.ResourceReloadListenerKeys; +import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.model.ModelManager; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; + +@ApiStatus.Internal +public final class PartialModelEventHandler { + private PartialModelEventHandler() { + } + + public static ResourceLocation[] onRegisterAdditional() { + PartialModel.tooLate = true; + return PartialModel.ALL.stream().map(PartialModel::getLocation).toArray(ResourceLocation[]::new); + } + + public static void onBakingCompleted(ModelManager manager) { + for (PartialModel partial : PartialModel.ALL) { + partial.set(manager.getModel(partial.getLocation())); + } + } + + public static final class ReloadListener implements SimpleSynchronousResourceReloadListener { + public static final ReloadListener INSTANCE = new ReloadListener(); + + public static final ResourceLocation ID = Flywheel.rl("partial_models"); + public static final List DEPENDENCIES = List.of(ResourceReloadListenerKeys.MODELS); + + private ReloadListener() { + } + + @Override + public void onResourceManagerReload(ResourceManager resourceManager) { + onBakingCompleted(Minecraft.getInstance().getModelManager()); + } + + @Override + public ResourceLocation getFabricId() { + return ID; + } + + @Override + public List getFabricDependencies() { + return DEPENDENCIES; + } + } +} diff --git a/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/UniversalMeshEmitter.java b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/UniversalMeshEmitter.java new file mode 100644 index 000000000..d56633513 --- /dev/null +++ b/fabric/src/lib/java/com/jozufozu/flywheel/lib/model/baked/UniversalMeshEmitter.java @@ -0,0 +1,146 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.function.Supplier; + +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.UnknownNullability; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; + +import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; +import net.fabricmc.fabric.api.renderer.v1.material.BlendMode; +import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; +import net.fabricmc.fabric.api.renderer.v1.model.ForwardingBakedModel; +import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; + +class UniversalMeshEmitter implements VertexConsumer { + private final Reference2ReferenceMap emitterMap; + private final WrapperModel wrapperModel = new WrapperModel(); + + @UnknownNullability + private RenderType defaultLayer; + @UnknownNullability + private BufferBuilder currentDelegate; + + UniversalMeshEmitter(Reference2ReferenceMap emitterMap) { + this.emitterMap = emitterMap; + } + + public void prepare(RenderType defaultLayer) { + this.defaultLayer = defaultLayer; + } + + public void clear() { + wrapperModel.setWrapped(null); + } + + public BakedModel wrapModel(BakedModel model) { + wrapperModel.setWrapped(model); + return wrapperModel; + } + + private void prepareForGeometry(RenderMaterial material) { + BlendMode blendMode = material.blendMode(); + RenderType layer = blendMode == BlendMode.DEFAULT ? defaultLayer : blendMode.blockRenderLayer; + boolean shade = !material.disableDiffuse(); + currentDelegate = emitterMap.get(layer).getBuffer(shade); + } + + @Override + public VertexConsumer vertex(double x, double y, double z) { + currentDelegate.vertex(x, y, z); + return this; + } + + @Override + public VertexConsumer color(int red, int green, int blue, int alpha) { + currentDelegate.color(red, green, blue, alpha); + return this; + } + + @Override + public VertexConsumer uv(float u, float v) { + currentDelegate.uv(u, v); + return this; + } + + @Override + public VertexConsumer overlayCoords(int u, int v) { + currentDelegate.overlayCoords(u, v); + return this; + } + + @Override + public VertexConsumer uv2(int u, int v) { + currentDelegate.uv2(u, v); + return this; + } + + @Override + public VertexConsumer normal(float x, float y, float z) { + currentDelegate.normal(x, y, z); + return this; + } + + @Override + public void endVertex() { + currentDelegate.endVertex(); + } + + @Override + public void defaultColor(int red, int green, int blue, int alpha) { + currentDelegate.defaultColor(red, green, blue, alpha); + } + + @Override + public void unsetDefaultColor() { + currentDelegate.unsetDefaultColor(); + } + + @Override + public void vertex(float x, float y, float z, float red, float green, float blue, float alpha, float u, float v, int overlay, int light, float normalX, float normalY, float normalZ) { + currentDelegate.vertex(x, y, z, red, green, blue, alpha, u, v, overlay, light, normalX, normalY, normalZ); + } + + @Override + public void putBulkData(PoseStack.Pose pose, BakedQuad quad, float red, float green, float blue, int light, int overlay) { + currentDelegate.putBulkData(pose, quad, red, green, blue, light, overlay); + } + + @Override + public void putBulkData(PoseStack.Pose pose, BakedQuad quad, float[] brightnesses, float red, float green, float blue, int[] lights, int overlay, boolean readExistingColor) { + currentDelegate.putBulkData(pose, quad, brightnesses, red, green, blue, lights, overlay, readExistingColor); + } + + private class WrapperModel extends ForwardingBakedModel { + private final RenderContext.QuadTransform quadTransform = quad -> { + UniversalMeshEmitter.this.prepareForGeometry(quad.material()); + return true; + }; + + public void setWrapped(@Nullable BakedModel wrapped) { + this.wrapped = wrapped; + } + + @Override + public boolean isVanillaAdapter() { + return false; + } + + @Override + public void emitBlockQuads(BlockAndTintGetter level, BlockState state, BlockPos pos, Supplier randomSupplier, RenderContext context) { + context.pushTransform(quadTransform); + super.emitBlockQuads(level, state, pos, randomSupplier, context); + context.popTransform(); + } + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/FabricFlwConfig.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/FabricFlwConfig.java new file mode 100644 index 000000000..e147424f1 --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/FabricFlwConfig.java @@ -0,0 +1,163 @@ +package com.jozufozu.flywheel.impl; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.nio.file.Path; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import com.jozufozu.flywheel.api.backend.Backend; +import com.jozufozu.flywheel.api.backend.BackendManager; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.ResourceLocationException; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.Mth; + +public class FabricFlwConfig implements FlwConfig { + public static final Path PATH = FabricLoader.getInstance() + .getConfigDir() + .resolve("flywheel.json"); + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + public static final boolean LIMIT_UPDATES_DEFAULT = true; + public static final int WORKER_THREADS_DEFAULT = -1; + public static final int WORKER_THREADS_MAX = Runtime.getRuntime() + .availableProcessors(); + + public static final FabricFlwConfig INSTANCE = new FabricFlwConfig(PATH.toFile()); + + private final File file; + + public Backend backend = BackendManager.getDefaultBackend(); + public boolean limitUpdates = LIMIT_UPDATES_DEFAULT; + public int workerThreads = WORKER_THREADS_DEFAULT; + + public FabricFlwConfig(File file) { + this.file = file; + } + + @Override + public Backend backend() { + return backend; + } + + @Override + public boolean limitUpdates() { + return limitUpdates; + } + + @Override + public int workerThreads() { + return workerThreads; + } + + public void load() { + if (file.exists()) { + try (FileReader reader = new FileReader(file)) { + fromJson(JsonParser.parseReader(reader)); + } catch (Exception e) { + FlwImpl.CONFIG_LOGGER.warn("Could not load config from file '{}'", file.getAbsolutePath(), e); + } + } + // In case we found an error in the config file, immediately save to fix it. + save(); + } + + public void save() { + try (FileWriter writer = new FileWriter(file)) { + GSON.toJson(toJson(), writer); + } catch (Exception e) { + FlwImpl.CONFIG_LOGGER.warn("Could not save config to file '{}'", file.getAbsolutePath(), e); + } + } + + public void fromJson(JsonElement json) { + if (!(json instanceof JsonObject object)) { + FlwImpl.CONFIG_LOGGER.warn("Config JSON must be an object"); + backend = BackendManager.getDefaultBackend(); + limitUpdates = LIMIT_UPDATES_DEFAULT; + workerThreads = WORKER_THREADS_DEFAULT; + return; + } + + readBackend(object); + readLimitUpdates(object); + readWorkerThreads(object); + } + + private void readBackend(JsonObject object) { + var backendJson = object.get("backend"); + String msg = null; + + if (backendJson instanceof JsonPrimitive primitive && primitive.isString()) { + var value = primitive.getAsString(); + try { + this.backend = Backend.REGISTRY.getOrThrow(new ResourceLocation(value)); + return; + } catch (ResourceLocationException e) { + msg = "'backend' value '" + value + "' is not a valid resource location"; + } catch (IllegalArgumentException e) { + msg = "Backend with ID '" + value + "' is not registered"; + } catch (Exception e) { + // Something else went wrong? This should be dead code. + msg = "'backend' value '" + value + "' is invalid"; + } + } else if (backendJson != null) { + msg = "'backend' value must be a string"; + } + + // Don't log an error if the field is missing. + if (msg != null) { + FlwImpl.CONFIG_LOGGER.warn(msg); + } + backend = BackendManager.getDefaultBackend(); + } + + private void readLimitUpdates(JsonObject object) { + var limitUpdatesJson = object.get("limitUpdates"); + + if (limitUpdatesJson instanceof JsonPrimitive primitive && primitive.isBoolean()) { + limitUpdates = primitive.getAsBoolean(); + return; + } else if (limitUpdatesJson != null) { + FlwImpl.CONFIG_LOGGER.warn("'limitUpdates' value must be a boolean"); + } + + limitUpdates = LIMIT_UPDATES_DEFAULT; + } + + private void readWorkerThreads(JsonObject object) { + var workerThreadsJson = object.get("workerThreads"); + + if (workerThreadsJson instanceof JsonPrimitive primitive && primitive.isNumber()) { + int value = primitive.getAsInt(); + int clamped = Mth.clamp(value, WORKER_THREADS_DEFAULT, WORKER_THREADS_MAX); + + if (clamped != value) { + FlwImpl.CONFIG_LOGGER.warn("'workerThreads' value of {} is out of range, clamping to {}", value, clamped); + } + + workerThreads = clamped; + return; + } else if (workerThreadsJson != null) { + FlwImpl.CONFIG_LOGGER.warn("'workerThreads' value must be an integer"); + } + + workerThreads = WORKER_THREADS_DEFAULT; + } + + public JsonObject toJson() { + JsonObject object = new JsonObject(); + object.addProperty("backend", Backend.REGISTRY.getIdOrThrow(backend).toString()); + object.addProperty("limitUpdates", limitUpdates); + object.addProperty("workerThreads", workerThreads); + return object; + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwCommands.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwCommands.java new file mode 100644 index 000000000..5e5f44dd2 --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwCommands.java @@ -0,0 +1,133 @@ +package com.jozufozu.flywheel.impl; + +import com.jozufozu.flywheel.api.backend.Backend; +import com.jozufozu.flywheel.api.backend.BackendManager; +import com.jozufozu.flywheel.backend.engine.uniform.DebugMode; +import com.jozufozu.flywheel.backend.engine.uniform.FrameUniforms; +import com.mojang.brigadier.Command; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; + +import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; +import net.minecraft.client.Minecraft; +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.commands.arguments.coordinates.BlockPosArgument; +import net.minecraft.commands.arguments.coordinates.Coordinates; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.Entity; + +public final class FlwCommands { + private FlwCommands() { + } + + public static void registerClientCommands(CommandDispatcher dispatcher, CommandBuildContext buildContext) { + LiteralArgumentBuilder command = ClientCommandManager.literal("flywheel"); + + command.then(ClientCommandManager.literal("backend") + .executes(context -> { + Backend backend = BackendManager.getBackend(); + String idStr = Backend.REGISTRY.getIdOrThrow(backend) + .toString(); + context.getSource().sendFeedback(Component.translatable("command.flywheel.backend.get", idStr)); + return Command.SINGLE_SUCCESS; + }) + .then(ClientCommandManager.argument("id", BackendArgument.INSTANCE) + .executes(context -> { + Backend requestedBackend = context.getArgument("id", Backend.class); + FabricFlwConfig.INSTANCE.backend = requestedBackend; + FabricFlwConfig.INSTANCE.save(); + + // Reload renderers so we can report the actual backend. + Minecraft.getInstance().levelRenderer.allChanged(); + + Backend actualBackend = BackendManager.getBackend(); + if (actualBackend != requestedBackend) { + String requestedIdStr = Backend.REGISTRY.getIdOrThrow(requestedBackend) + .toString(); + context.getSource().sendError(Component.translatable("command.flywheel.backend.set.unavailable", requestedIdStr)); + } + + String actualIdStr = Backend.REGISTRY.getIdOrThrow(actualBackend) + .toString(); + context.getSource().sendFeedback(Component.translatable("command.flywheel.backend.set", actualIdStr)); + return Command.SINGLE_SUCCESS; + }))); + + command.then(ClientCommandManager.literal("limitUpdates") + .executes(context -> { + if (FabricFlwConfig.INSTANCE.limitUpdates) { + context.getSource().sendFeedback(Component.translatable("command.flywheel.limit_updates.get.on")); + } else { + context.getSource().sendFeedback(Component.translatable("command.flywheel.limit_updates.get.off")); + } + return Command.SINGLE_SUCCESS; + }) + .then(ClientCommandManager.literal("on") + .executes(context -> { + FabricFlwConfig.INSTANCE.limitUpdates = true; + FabricFlwConfig.INSTANCE.save(); + context.getSource().sendFeedback(Component.translatable("command.flywheel.limit_updates.set.on")); + Minecraft.getInstance().levelRenderer.allChanged(); + return Command.SINGLE_SUCCESS; + })) + .then(ClientCommandManager.literal("off") + .executes(context -> { + FabricFlwConfig.INSTANCE.limitUpdates = false; + FabricFlwConfig.INSTANCE.save(); + context.getSource().sendFeedback(Component.translatable("command.flywheel.limit_updates.set.off")); + Minecraft.getInstance().levelRenderer.allChanged(); + return Command.SINGLE_SUCCESS; + }))); + + command.then(ClientCommandManager.literal("crumbling") + .then(ClientCommandManager.argument("pos", BlockPosArgument.blockPos()) + .then(ClientCommandManager.argument("stage", IntegerArgumentType.integer(0, 9)) + .executes(context -> { + Entity executor = context.getSource() + .getEntity(); + + if (executor == null) { + return 0; + } + + BlockPos pos = getBlockPos(context, "pos"); + int value = IntegerArgumentType.getInteger(context, "stage"); + + executor.level() + .destroyBlockProgress(executor.getId(), pos, value); + + return Command.SINGLE_SUCCESS; + })))); + + command.then(ClientCommandManager.literal("debug") + .then(ClientCommandManager.argument("mode", DebugModeArgument.INSTANCE) + .executes(context -> { + DebugMode mode = context.getArgument("mode", DebugMode.class); + FrameUniforms.debugMode(mode); + return Command.SINGLE_SUCCESS; + }))); + + command.then(ClientCommandManager.literal("frustum") + .then(ClientCommandManager.literal("capture") + .executes(context -> { + FrameUniforms.captureFrustum(); + return Command.SINGLE_SUCCESS; + })) + .then(ClientCommandManager.literal("unpause") + .executes(context -> { + FrameUniforms.unpauseFrustum(); + return Command.SINGLE_SUCCESS; + }))); + + dispatcher.register(command); + } + + // Client version of BlockPosArgument.getBlockPos + private static BlockPos getBlockPos(CommandContext context, String name) { + return context.getArgument(name, Coordinates.class).getBlockPos(context.getSource().getPlayer().createCommandSourceStack()); + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplatImpl.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplatImpl.java new file mode 100644 index 000000000..35de913ce --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplatImpl.java @@ -0,0 +1,38 @@ +package com.jozufozu.flywheel.impl; + +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.api.event.BeginFrameCallback; +import com.jozufozu.flywheel.api.event.ReloadLevelRendererCallback; +import com.jozufozu.flywheel.api.event.RenderContext; +import com.jozufozu.flywheel.api.event.RenderStage; +import com.jozufozu.flywheel.api.event.RenderStageCallback; + +import net.minecraft.client.multiplayer.ClientLevel; + +public class FlwImplXplatImpl implements FlwImplXplat { + @Override + public void dispatchBeginFrameEvent(RenderContext context) { + BeginFrameCallback.EVENT.invoker().onBeginFrame(context); + } + + @Override + public void dispatchReloadLevelRendererEvent(@Nullable ClientLevel level) { + ReloadLevelRendererCallback.EVENT.invoker().onReloadLevelRenderer(level); + } + + @Override + public void dispatchRenderStageEvent(RenderContext context, RenderStage stage) { + RenderStageCallback.EVENT.invoker().onRenderStage(context, stage); + } + + @Override + public String getVersionStr() { + return FlywheelFabric.version().getFriendlyString(); + } + + @Override + public FlwConfig getConfig() { + return FabricFlwConfig.INSTANCE; + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwLibXplatImpl.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwLibXplatImpl.java new file mode 100644 index 000000000..932a458ac --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlwLibXplatImpl.java @@ -0,0 +1,66 @@ +package com.jozufozu.flywheel.impl; + +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.lib.internal.FlwLibXplat; +import com.jozufozu.flywheel.lib.model.baked.BakedModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.BlockModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.FabricBakedModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.FabricBlockModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.FabricMultiBlockModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.MultiBlockModelBuilder; +import com.jozufozu.flywheel.lib.util.ShadersModHandler; + +import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.api.v0.IrisApi; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; + +public class FlwLibXplatImpl implements FlwLibXplat { + @Override + public BlockRenderDispatcher createVanillaBlockRenderDispatcher() { + return Minecraft.getInstance().getBlockRenderer(); + } + + @Override + public BakedModelBuilder createBakedModelBuilder(BakedModel bakedModel) { + return new FabricBakedModelBuilder(bakedModel); + } + + @Override + public BlockModelBuilder createBlockModelBuilder(BlockState state) { + return new FabricBlockModelBuilder(state); + } + + @Override + public MultiBlockModelBuilder createMultiBlockModelBuilder(BlockAndTintGetter level, Iterable positions) { + return new FabricMultiBlockModelBuilder(level, positions); + } + + @Override + @Nullable + public ShadersModHandler.InternalHandler createIrisHandler() { + if (!FabricLoader.getInstance() + .isModLoaded("iris")) { + return null; + } + + return new ShadersModHandler.InternalHandler() { + @Override + public boolean isShaderPackInUse() { + return IrisApi.getInstance() + .isShaderPackInUse(); + } + + @Override + public boolean isRenderingShadowPass() { + return IrisApi.getInstance() + .isRenderingShadowPass(); + } + }; + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/FlywheelFabric.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlywheelFabric.java new file mode 100644 index 000000000..68857a7e1 --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/FlywheelFabric.java @@ -0,0 +1,93 @@ +package com.jozufozu.flywheel.impl; + +import org.jetbrains.annotations.UnknownNullability; + +import com.jozufozu.flywheel.api.Flywheel; +import com.jozufozu.flywheel.api.event.BeginFrameCallback; +import com.jozufozu.flywheel.api.event.EndClientResourceReloadCallback; +import com.jozufozu.flywheel.api.event.ReloadLevelRendererCallback; +import com.jozufozu.flywheel.api.event.RenderStageCallback; +import com.jozufozu.flywheel.backend.compile.FlwProgramsReloader; +import com.jozufozu.flywheel.backend.engine.uniform.Uniforms; +import com.jozufozu.flywheel.impl.visualization.VisualizationEventHandler; +import com.jozufozu.flywheel.lib.model.ModelCache; +import com.jozufozu.flywheel.lib.model.ModelHolder; +import com.jozufozu.flywheel.lib.model.baked.PartialModelEventHandler; + +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientEntityEvents; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.fabric.api.client.model.loading.v1.ModelLoadingPlugin; +import net.fabricmc.fabric.api.command.v2.ArgumentTypeRegistry; +import net.fabricmc.fabric.api.resource.ResourceManagerHelper; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.fabricmc.loader.api.Version; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.server.packs.PackType; + +public final class FlywheelFabric implements ClientModInitializer { + @UnknownNullability + private static Version version; + + @Override + public void onInitializeClient() { + ModContainer modContainer = FabricLoader.getInstance().getModContainer(Flywheel.ID).orElseThrow(); + version = modContainer.getMetadata().getVersion(); + + setupImpl(); + setupLib(); + setupBackend(); + + FlwImpl.init(); + } + + private static void setupImpl() { + ReloadLevelRendererCallback.EVENT.register(BackendManagerImpl::onReloadLevelRenderer); + + // This Fabric event runs slightly later than the Forge event Flywheel uses, but it shouldn't make a difference. + ClientTickEvents.END_CLIENT_TICK.register(minecraft -> { + if (!minecraft.isPaused()) { + ClientLevel level = minecraft.level; + if (level != null) { + VisualizationEventHandler.onClientTick(minecraft, level); + } + } + }); + BeginFrameCallback.EVENT.register(VisualizationEventHandler::onBeginFrame); + RenderStageCallback.EVENT.register(VisualizationEventHandler::onRenderStage); + ClientEntityEvents.ENTITY_LOAD.register((entity, level) -> VisualizationEventHandler.onEntityJoinLevel(level, entity)); + ClientEntityEvents.ENTITY_UNLOAD.register((entity, level) -> VisualizationEventHandler.onEntityLeaveLevel(level, entity)); + + ClientCommandRegistrationCallback.EVENT.register(FlwCommands::registerClientCommands); + + EndClientResourceReloadCallback.EVENT.register((minecraft, resourceManager, initialReload, error) -> + BackendManagerImpl.onEndClientResourceReload(error.isPresent())); + + ArgumentTypeRegistry.registerArgumentType(Flywheel.rl("backend"), BackendArgument.class, BackendArgument.INFO); + ArgumentTypeRegistry.registerArgumentType(Flywheel.rl("debug_mode"), DebugModeArgument.class, DebugModeArgument.INFO); + } + + private static void setupLib() { + EndClientResourceReloadCallback.EVENT.register((minecraft, resourceManager, initialReload, error) -> + ModelCache.onEndClientResourceReload()); + EndClientResourceReloadCallback.EVENT.register((minecraft, resourceManager, initialReload, error) -> + ModelHolder.onEndClientResourceReload()); + + ModelLoadingPlugin.register(ctx -> { + ctx.addModels(PartialModelEventHandler.onRegisterAdditional()); + }); + ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(PartialModelEventHandler.ReloadListener.INSTANCE); + } + + private static void setupBackend() { + ReloadLevelRendererCallback.EVENT.register(level -> Uniforms.onReloadLevelRenderer()); + + ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(FlwProgramsReloader.INSTANCE); + } + + public static Version version() { + return version; + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java new file mode 100644 index 000000000..0fed00bf7 --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java @@ -0,0 +1,46 @@ +package com.jozufozu.flywheel.impl.mixin; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.jozufozu.flywheel.api.event.EndClientResourceReloadCallback; +import com.jozufozu.flywheel.impl.FabricFlwConfig; +import com.jozufozu.flywheel.impl.FlwImpl; + +import net.minecraft.client.Minecraft; +import net.minecraft.server.packs.resources.ReloadableResourceManager; + +@Mixin(Minecraft.class) +abstract class MinecraftMixin { + @Shadow + @Final + private ReloadableResourceManager resourceManager; + + @Inject(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/packs/resources/ReloadableResourceManager;createReload(Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;Ljava/util/concurrent/CompletableFuture;Ljava/util/List;)Lnet/minecraft/server/packs/resources/ReloadInstance;")) + private void flywheel$onBeginInitialResourceReload(CallbackInfo ci) { + FlwImpl.freezeRegistries(); + // Load the config after we freeze registries, + // so we can find third party backends. + FabricFlwConfig.INSTANCE.load(); + } + + @Inject(method = "method_24040", at = @At("HEAD")) + private void flywheel$onEndInitialResourceReload(Optional error, CallbackInfo ci) { + EndClientResourceReloadCallback.EVENT.invoker() + .onEndClientResourceReload((Minecraft) (Object) this, resourceManager, true, error); + } + + @Inject(method = "method_24228", at = @At("HEAD")) + private void flywheel$onEndManualResourceReload(boolean recovery, CompletableFuture future, + Optional error, CallbackInfo ci) { + EndClientResourceReloadCallback.EVENT.invoker() + .onEndClientResourceReload((Minecraft) (Object) this, resourceManager, false, error); + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/DebugScreenOverlayMixin.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/DebugScreenOverlayMixin.java new file mode 100644 index 000000000..0d9719aea --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/DebugScreenOverlayMixin.java @@ -0,0 +1,27 @@ +package com.jozufozu.flywheel.impl.mixin.fabric; + +import java.util.List; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import com.jozufozu.flywheel.impl.FlwDebugInfo; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.DebugScreenOverlay; + +@Mixin(DebugScreenOverlay.class) +abstract class DebugScreenOverlayMixin { + @Shadow + @Final + private Minecraft minecraft; + + @Inject(method = "getSystemInformation", at = @At("RETURN")) + private void flywheel$onGetSystemInformation(CallbackInfoReturnable> cir) { + FlwDebugInfo.addDebugInfo(minecraft, cir.getReturnValue()); + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/MinecraftMixin.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/MinecraftMixin.java new file mode 100644 index 000000000..f80623ea7 --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/MinecraftMixin.java @@ -0,0 +1,32 @@ +package com.jozufozu.flywheel.impl.mixin.fabric; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.jozufozu.flywheel.lib.util.LevelAttached; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; + +@Mixin(Minecraft.class) +abstract class MinecraftMixin { + @Shadow + public ClientLevel level; + + @Inject(method = "setLevel(Lnet/minecraft/client/multiplayer/ClientLevel;)V", at = @At("HEAD")) + private void flywheel$onSetLevel(CallbackInfo ci) { + if (level != null) { + LevelAttached.invalidateLevel(level); + } + } + + @Inject(method = "clearLevel(Lnet/minecraft/client/gui/screens/Screen;)V", at = @At("HEAD")) + private void flywheel$onClearLevel(CallbackInfo ci) { + if (level != null) { + LevelAttached.invalidateLevel(level); + } + } +} diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/SystemReportMixin.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/SystemReportMixin.java new file mode 100644 index 000000000..8a8178793 --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/fabric/SystemReportMixin.java @@ -0,0 +1,19 @@ +package com.jozufozu.flywheel.impl.mixin.fabric; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import com.jozufozu.flywheel.impl.BackendManagerImpl; + +import net.minecraft.SystemReport; + +@Mixin(value = SystemReport.class, priority = 1056) +abstract class SystemReportMixin { + @Inject(method = "", at = @At("RETURN")) + private void flywheel$onInit(CallbackInfo ci) { + SystemReport self = (SystemReport) (Object) this; + self.setDetail("Flywheel Backend", BackendManagerImpl::getBackendString); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/ChunkBuilderMeshingTaskMixin.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/ChunkBuilderMeshingTaskMixin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/ChunkBuilderMeshingTaskMixin.java rename to fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/ChunkBuilderMeshingTaskMixin.java diff --git a/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/SodiumMixinPlugin.java b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/SodiumMixinPlugin.java new file mode 100644 index 000000000..0673915cb --- /dev/null +++ b/fabric/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/SodiumMixinPlugin.java @@ -0,0 +1,48 @@ +package com.jozufozu.flywheel.impl.mixin.sodium; + +import java.util.List; +import java.util.Set; +import java.util.function.Supplier; + +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import com.google.common.base.Suppliers; + +import net.fabricmc.loader.api.FabricLoader; + +public class SodiumMixinPlugin implements IMixinConfigPlugin { + private static final Supplier IS_SODIUM_LOADED = Suppliers.memoize(() -> FabricLoader.getInstance().isModLoaded("sodium")); + + @Override + public void onLoad(String mixinPackage) { + } + + @Override + public String getRefMapperConfig() { + return null; + } + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + return IS_SODIUM_LOADED.get(); + } + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) { + } + + @Override + public List getMixins() { + return null; + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + } + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + } +} diff --git a/fabric/src/main/resources/fabric.mod.json b/fabric/src/main/resources/fabric.mod.json new file mode 100644 index 000000000..8e42e83ae --- /dev/null +++ b/fabric/src/main/resources/fabric.mod.json @@ -0,0 +1,37 @@ +{ + "schemaVersion": 1, + "id": "${mod_id}", + "version": "${mod_version}", + "name": "${mod_name}", + "description": "${mod_description}", + "authors": [ + "Jozufozu", + "PepperCode1" + ], + "contact": { + "homepage": "${mod_homepage}", + "sources": "${mod_sources}", + "issues": "${mod_issues}" + }, + "license": "${mod_license}", + "icon": "logo.png", + "environment": "client", + "entrypoints": { + "client": [ + "com.jozufozu.flywheel.impl.FlywheelFabric" + ] + }, + "mixins": [ + "flywheel.backend.mixins.json", + "flywheel.impl.mixins.json", + "flywheel.impl.sodium.mixins.json", + "flywheel.impl.fabric.mixins.json" + ], + "depends": { + "minecraft": "${minecraft_semver_version_range}", + "fabric-api": "${fabric_api_version_range}" + }, + "breaks": { + "sodium": "<0.5.0" + } +} diff --git a/fabric/src/main/resources/flywheel.impl.fabric.mixins.json b/fabric/src/main/resources/flywheel.impl.fabric.mixins.json new file mode 100644 index 000000000..6bcba4308 --- /dev/null +++ b/fabric/src/main/resources/flywheel.impl.fabric.mixins.json @@ -0,0 +1,15 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "com.jozufozu.flywheel.impl.mixin.fabric", + "compatibilityLevel": "JAVA_17", + "refmap": "flywheel.refmap.json", + "client": [ + "DebugScreenOverlayMixin", + "MinecraftMixin", + "SystemReportMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/src/main/resources/flywheel.impl.sodium.mixins.json b/fabric/src/main/resources/flywheel.impl.sodium.mixins.json similarity index 100% rename from src/main/resources/flywheel.impl.sodium.mixins.json rename to fabric/src/main/resources/flywheel.impl.sodium.mixins.json diff --git a/forge/build.gradle.kts b/forge/build.gradle.kts new file mode 100644 index 000000000..5f51cc55e --- /dev/null +++ b/forge/build.gradle.kts @@ -0,0 +1,88 @@ +plugins { + idea + java + `maven-publish` + id("dev.architectury.loom") + id("flywheel.subproject") + id("flywheel.platform") +} + +val api = sourceSets.create("api") +val lib = sourceSets.create("lib") +val backend = sourceSets.create("backend") +val main = sourceSets.getByName("main") + +transitiveSourceSets { + compileClasspath = main.compileClasspath + + sourceSet(api) { + rootCompile() + } + sourceSet(lib) { + rootCompile() + compile(api) + } + sourceSet(backend) { + rootCompile() + compile(api, lib) + } + sourceSet(main) { + compile(api, lib, backend) + } + + createCompileConfigurations() +} + +platform { + commonProject = project(":common") + sources(api, lib, backend, main) + compileWithCommonSourceSets() + setupLoomMod() + setupLoomRuns() + setupFatJar() +} + +jarSets { + mainSet.publish(platform.modArtifactId) + create("api", api, lib).apply { + addToAssemble() + publish(platform.apiArtifactId) + + configureJar { + manifest { + attributes("Fabric-Loom-Remap" to "true") + } + } + } +} + +defaultPackageInfos { + sources(api, lib, backend, main) +} + +loom { + forge { + mixinConfig("flywheel.backend.mixins.json") + mixinConfig("flywheel.impl.mixins.json") + mixinConfig("flywheel.impl.sodium.mixins.json") + } + + runs { + configureEach { + property("forge.logging.markers", "") + property("forge.logging.console.level", "debug") + } + } +} + +dependencies { + forge("net.minecraftforge:forge:${property("minecraft_version")}-${property("forge_version")}") + + modCompileOnly("maven.modrinth:embeddium:${property("embeddium_version")}") + modCompileOnly("maven.modrinth:oculus:${property("oculus_version")}") + + "forApi"(project(path = ":common", configuration = "commonApiOnly")) + "forLib"(project(path = ":common", configuration = "commonLib")) + "forBackend"(project(path = ":common", configuration = "commonBackend")) + "forMain"(project(path = ":common", configuration = "commonImpl")) +} diff --git a/forge/gradle.properties b/forge/gradle.properties new file mode 100644 index 000000000..a58ba1416 --- /dev/null +++ b/forge/gradle.properties @@ -0,0 +1 @@ +loom.platform = forge diff --git a/src/main/java/com/jozufozu/flywheel/api/event/BeginFrameEvent.java b/forge/src/api/java/com/jozufozu/flywheel/api/event/BeginFrameEvent.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/event/BeginFrameEvent.java rename to forge/src/api/java/com/jozufozu/flywheel/api/event/BeginFrameEvent.java diff --git a/src/main/java/com/jozufozu/flywheel/api/event/EndClientResourceReloadEvent.java b/forge/src/api/java/com/jozufozu/flywheel/api/event/EndClientResourceReloadEvent.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/event/EndClientResourceReloadEvent.java rename to forge/src/api/java/com/jozufozu/flywheel/api/event/EndClientResourceReloadEvent.java diff --git a/src/main/java/com/jozufozu/flywheel/api/event/ReloadLevelRendererEvent.java b/forge/src/api/java/com/jozufozu/flywheel/api/event/ReloadLevelRendererEvent.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/event/ReloadLevelRendererEvent.java rename to forge/src/api/java/com/jozufozu/flywheel/api/event/ReloadLevelRendererEvent.java diff --git a/src/main/java/com/jozufozu/flywheel/api/event/RenderStageEvent.java b/forge/src/api/java/com/jozufozu/flywheel/api/event/RenderStageEvent.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/api/event/RenderStageEvent.java rename to forge/src/api/java/com/jozufozu/flywheel/api/event/RenderStageEvent.java diff --git a/forge/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplatImpl.java b/forge/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplatImpl.java new file mode 100644 index 000000000..b010dfe1f --- /dev/null +++ b/forge/src/backend/java/com/jozufozu/flywheel/backend/FlwBackendXplatImpl.java @@ -0,0 +1,12 @@ +package com.jozufozu.flywheel.backend; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.state.BlockState; + +public class FlwBackendXplatImpl implements FlwBackendXplat { + @Override + public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) { + return state.getLightEmission(level, pos); + } +} diff --git a/forge/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwProgramsReloader.java b/forge/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwProgramsReloader.java new file mode 100644 index 000000000..475b2586b --- /dev/null +++ b/forge/src/backend/java/com/jozufozu/flywheel/backend/compile/FlwProgramsReloader.java @@ -0,0 +1,16 @@ +package com.jozufozu.flywheel.backend.compile; + +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.ResourceManagerReloadListener; + +public final class FlwProgramsReloader implements ResourceManagerReloadListener { + public static final FlwProgramsReloader INSTANCE = new FlwProgramsReloader(); + + private FlwProgramsReloader() { + } + + @Override + public void onResourceManagerReload(ResourceManager manager) { + FlwPrograms.reload(manager); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java similarity index 84% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java rename to forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java index dcfa860f7..d62de8009 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java +++ b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBufferer.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.Nullable; -import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferBuilder.RenderedBuffer; import com.mojang.blaze3d.vertex.PoseStack; @@ -25,8 +24,8 @@ import net.minecraftforge.client.model.data.ModelData; final class BakedModelBufferer { - private static final RenderType[] CHUNK_LAYERS = RenderType.chunkBufferLayers().toArray(RenderType[]::new); - private static final int CHUNK_LAYER_AMOUNT = CHUNK_LAYERS.length; + static final RenderType[] CHUNK_LAYERS = RenderType.chunkBufferLayers().toArray(RenderType[]::new); + static final int CHUNK_LAYER_AMOUNT = CHUNK_LAYERS.length; private static final ThreadLocal THREAD_LOCAL_OBJECTS = ThreadLocal.withInitial(ThreadLocalObjects::new); @@ -39,7 +38,7 @@ public static void bufferSingle(ModelBlockRenderer blockRenderer, BlockAndTintGe poseStack = objects.identityPoseStack; } RandomSource random = objects.random; - var consumers = objects.emitters; + MeshEmitter[] emitters = objects.emitters; modelData = model.getModelData(level, BlockPos.ZERO, state, modelData); random.setSeed(42L); @@ -47,15 +46,15 @@ public static void bufferSingle(ModelBlockRenderer blockRenderer, BlockAndTintGe for (RenderType renderType : renderTypes) { int layerIndex = renderType.getChunkLayerId(); - var consumer = consumers[layerIndex]; + MeshEmitter emitter = emitters[layerIndex]; - consumer.begin(resultConsumer); + emitter.prepare(resultConsumer); poseStack.pushPose(); - blockRenderer.tesselateBlock(level, model, state, BlockPos.ZERO, poseStack, consumer, false, random, 42L, OverlayTexture.NO_OVERLAY, modelData, renderType); + blockRenderer.tesselateBlock(level, model, state, BlockPos.ZERO, poseStack, emitter, false, random, 42L, OverlayTexture.NO_OVERLAY, modelData, renderType); poseStack.popPose(); - consumer.end(); + emitter.end(); } } @@ -73,12 +72,11 @@ public static void bufferMultiBlock(BlockRenderDispatcher renderDispatcher, Iter poseStack = objects.identityPoseStack; } RandomSource random = objects.random; + MeshEmitter[] emitters = objects.emitters; TransformingVertexConsumer transformingWrapper = objects.transformingWrapper; - var emitters = objects.emitters; - - for (var emitter : emitters) { - emitter.begin(resultConsumer); + for (MeshEmitter emitter : emitters) { + emitter.prepare(resultConsumer); } ModelBlockRenderer blockRenderer = renderDispatcher.getModelRenderer(); @@ -92,10 +90,10 @@ public static void bufferMultiBlock(BlockRenderDispatcher renderDispatcher, Iter FluidState fluidState = state.getFluidState(); if (!fluidState.isEmpty()) { - RenderType layer = ItemBlockRenderTypes.getRenderLayer(fluidState); - int layerIndex = layer.getChunkLayerId(); + RenderType renderType = ItemBlockRenderTypes.getRenderLayer(fluidState); + int layerIndex = renderType.getChunkLayerId(); - transformingWrapper.prepare(emitters[layerIndex], poseStack); + transformingWrapper.prepare(emitters[layerIndex].unwrap(true), poseStack); poseStack.pushPose(); poseStack.translate(pos.getX() - (pos.getX() & 0xF), pos.getY() - (pos.getY() & 0xF), pos.getZ() - (pos.getZ() & 0xF)); @@ -124,12 +122,11 @@ public static void bufferMultiBlock(BlockRenderDispatcher renderDispatcher, Iter } ModelBlockRenderer.clearCache(); + transformingWrapper.clear(); - for (var emitter : emitters) { + for (MeshEmitter emitter : emitters) { emitter.end(); } - - transformingWrapper.clear(); } public interface ResultConsumer { @@ -140,15 +137,13 @@ private static class ThreadLocalObjects { public final PoseStack identityPoseStack = new PoseStack(); public final RandomSource random = RandomSource.createNewThreadLocalInstance(); - public final TransformingVertexConsumer transformingWrapper = new TransformingVertexConsumer(); - public final MeshEmitter[] emitters = new MeshEmitter[CHUNK_LAYER_AMOUNT]; + public final TransformingVertexConsumer transformingWrapper = new TransformingVertexConsumer(); { for (int layerIndex = 0; layerIndex < CHUNK_LAYER_AMOUNT; layerIndex++) { - var renderType = CHUNK_LAYERS[layerIndex]; - var buffer = new BufferBuilder(renderType.bufferSize()); - emitters[layerIndex] = new MeshEmitter(buffer, renderType); + RenderType renderType = CHUNK_LAYERS[layerIndex]; + emitters[layerIndex] = new MeshEmitter(renderType); } } } diff --git a/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ChunkLayerSortedListBuilder.java b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ChunkLayerSortedListBuilder.java new file mode 100644 index 000000000..01890f7c7 --- /dev/null +++ b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ChunkLayerSortedListBuilder.java @@ -0,0 +1,54 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.List; + +import com.google.common.collect.ImmutableList; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.client.renderer.RenderType; + +class ChunkLayerSortedListBuilder { + private static final ThreadLocal> THREAD_LOCAL = ThreadLocal.withInitial(ChunkLayerSortedListBuilder::new); + + @SuppressWarnings("unchecked") + private final ObjectArrayList[] lists = new ObjectArrayList[BakedModelBufferer.CHUNK_LAYER_AMOUNT]; + + private ChunkLayerSortedListBuilder() { + for (int layerIndex = 0; layerIndex < BakedModelBufferer.CHUNK_LAYER_AMOUNT; layerIndex++) { + ObjectArrayList list = new ObjectArrayList<>(); + lists[layerIndex] = list; + } + } + + @SuppressWarnings("unchecked") + public static ChunkLayerSortedListBuilder getThreadLocal() { + return (ChunkLayerSortedListBuilder) THREAD_LOCAL.get(); + } + + public void add(RenderType renderType, T obj) { + int layerIndex = renderType.getChunkLayerId(); + if (layerIndex == -1) { + throw new IllegalArgumentException("RenderType '" + renderType + "' is not a chunk layer"); + } + List list = lists[layerIndex]; + list.add(obj); + } + + @SuppressWarnings("unchecked") + public ImmutableList build() { + int size = 0; + for (ObjectArrayList list : lists) { + size += list.size(); + } + + T[] array = (T[]) new Object[size]; + int destPos = 0; + for (ObjectArrayList list : lists) { + System.arraycopy(list.elements(), 0, array, destPos, list.size()); + destPos += list.size(); + list.clear(); + } + + return ImmutableList.copyOf(array); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBuilder.java b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeBakedModelBuilder.java similarity index 61% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBuilder.java rename to forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeBakedModelBuilder.java index 550c54cce..515def783 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/baked/BakedModelBuilder.java +++ b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeBakedModelBuilder.java @@ -4,7 +4,6 @@ import org.jetbrains.annotations.Nullable; -import com.google.common.collect.ImmutableList; import com.jozufozu.flywheel.api.material.Material; import com.jozufozu.flywheel.api.model.Model; import com.jozufozu.flywheel.api.vertex.VertexView; @@ -12,7 +11,6 @@ import com.jozufozu.flywheel.lib.model.ModelUtil; import com.jozufozu.flywheel.lib.model.SimpleMesh; import com.jozufozu.flywheel.lib.model.SimpleModel; -import com.jozufozu.flywheel.lib.model.baked.BakedModelBufferer.ResultConsumer; import com.jozufozu.flywheel.lib.vertex.NoOverlayVertexView; import com.mojang.blaze3d.vertex.PoseStack; @@ -23,48 +21,44 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; -public class BakedModelBuilder { - private final BakedModel bakedModel; - @Nullable - private BlockAndTintGetter level; - @Nullable - private BlockState blockState; - @Nullable - private PoseStack poseStack; +public final class ForgeBakedModelBuilder extends BakedModelBuilder { @Nullable private ModelData modelData; - @Nullable - private BiFunction materialFunc; - public BakedModelBuilder(BakedModel bakedModel) { - this.bakedModel = bakedModel; + public ForgeBakedModelBuilder(BakedModel bakedModel) { + super(bakedModel); } - public BakedModelBuilder level(BlockAndTintGetter level) { - this.level = level; + @Override + public ForgeBakedModelBuilder level(BlockAndTintGetter level) { + super.level(level); return this; } - public BakedModelBuilder blockState(BlockState blockState) { - this.blockState = blockState; + @Override + public ForgeBakedModelBuilder blockState(BlockState blockState) { + super.blockState(blockState); return this; } - public BakedModelBuilder poseStack(PoseStack poseStack) { - this.poseStack = poseStack; + @Override + public ForgeBakedModelBuilder poseStack(PoseStack poseStack) { + super.poseStack(poseStack); return this; } - public BakedModelBuilder modelData(ModelData modelData) { - this.modelData = modelData; + @Override + public ForgeBakedModelBuilder materialFunc(BiFunction materialFunc) { + super.materialFunc(materialFunc); return this; } - public BakedModelBuilder materialFunc(BiFunction materialFunc) { - this.materialFunc = materialFunc; + public ForgeBakedModelBuilder modelData(ModelData modelData) { + this.modelData = modelData; return this; } + @Override public SimpleModel build() { if (level == null) { level = VirtualEmptyBlockGetter.INSTANCE; @@ -72,26 +66,25 @@ public SimpleModel build() { if (blockState == null) { blockState = Blocks.AIR.defaultBlockState(); } - if (modelData == null) { - modelData = ModelData.EMPTY; - } if (materialFunc == null) { materialFunc = ModelUtil::getMaterial; } + if (modelData == null) { + modelData = ModelData.EMPTY; + } - var out = ImmutableList.builder(); + var builder = ChunkLayerSortedListBuilder.getThreadLocal(); - ResultConsumer resultConsumer = (renderType, shaded, data) -> { + BakedModelBufferer.bufferSingle(ModelUtil.VANILLA_RENDERER.getModelRenderer(), level, bakedModel, blockState, poseStack, modelData, (renderType, shaded, data) -> { Material material = materialFunc.apply(renderType, shaded); if (material != null) { VertexView vertexView = new NoOverlayVertexView(); MemoryBlock meshData = ModelUtil.convertVanillaBuffer(data, vertexView); var mesh = new SimpleMesh(vertexView, meshData, "source=BakedModelBuilder," + "bakedModel=" + bakedModel + ",renderType=" + renderType + ",shaded=" + shaded); - out.add(new Model.ConfiguredMesh(material, mesh)); + builder.add(renderType, new Model.ConfiguredMesh(material, mesh)); } - }; - BakedModelBufferer.bufferSingle(ModelUtil.VANILLA_RENDERER.getModelRenderer(), level, bakedModel, blockState, poseStack, modelData, resultConsumer); + }); - return new SimpleModel(out.build()); + return new SimpleModel(builder.build()); } } diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/BlockModelBuilder.java b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeBlockModelBuilder.java similarity index 60% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/BlockModelBuilder.java rename to forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeBlockModelBuilder.java index c0e16e7db..ad385e40c 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/baked/BlockModelBuilder.java +++ b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeBlockModelBuilder.java @@ -4,7 +4,6 @@ import org.jetbrains.annotations.Nullable; -import com.google.common.collect.ImmutableList; import com.jozufozu.flywheel.api.material.Material; import com.jozufozu.flywheel.api.model.Model; import com.jozufozu.flywheel.api.vertex.VertexView; @@ -12,7 +11,6 @@ import com.jozufozu.flywheel.lib.model.ModelUtil; import com.jozufozu.flywheel.lib.model.SimpleMesh; import com.jozufozu.flywheel.lib.model.SimpleModel; -import com.jozufozu.flywheel.lib.model.baked.BakedModelBufferer.ResultConsumer; import com.jozufozu.flywheel.lib.vertex.NoOverlayVertexView; import com.mojang.blaze3d.vertex.PoseStack; @@ -21,65 +19,61 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; -public class BlockModelBuilder { - private final BlockState state; - @Nullable - private BlockAndTintGetter level; - @Nullable - private PoseStack poseStack; +public final class ForgeBlockModelBuilder extends BlockModelBuilder { @Nullable private ModelData modelData; - @Nullable - private BiFunction materialFunc; - public BlockModelBuilder(BlockState state) { - this.state = state; + public ForgeBlockModelBuilder(BlockState state) { + super(state); } - public BlockModelBuilder level(BlockAndTintGetter level) { - this.level = level; + @Override + public ForgeBlockModelBuilder level(BlockAndTintGetter level) { + super.level(level); return this; } - public BlockModelBuilder poseStack(PoseStack poseStack) { - this.poseStack = poseStack; + @Override + public ForgeBlockModelBuilder poseStack(PoseStack poseStack) { + super.poseStack(poseStack); return this; } - public BlockModelBuilder modelData(ModelData modelData) { - this.modelData = modelData; + @Override + public ForgeBlockModelBuilder materialFunc(BiFunction materialFunc) { + super.materialFunc(materialFunc); return this; } - public BlockModelBuilder materialFunc(BiFunction materialFunc) { - this.materialFunc = materialFunc; + public ForgeBlockModelBuilder modelData(ModelData modelData) { + this.modelData = modelData; return this; } + @Override public SimpleModel build() { if (level == null) { level = VirtualEmptyBlockGetter.INSTANCE; } - if (modelData == null) { - modelData = ModelData.EMPTY; - } if (materialFunc == null) { materialFunc = ModelUtil::getMaterial; } + if (modelData == null) { + modelData = ModelData.EMPTY; + } - var out = ImmutableList.builder(); + var builder = ChunkLayerSortedListBuilder.getThreadLocal(); - ResultConsumer resultConsumer = (renderType, shaded, data) -> { + BakedModelBufferer.bufferBlock(ModelUtil.VANILLA_RENDERER, level, state, poseStack, modelData, (renderType, shaded, data) -> { Material material = materialFunc.apply(renderType, shaded); if (material != null) { VertexView vertexView = new NoOverlayVertexView(); MemoryBlock meshData = ModelUtil.convertVanillaBuffer(data, vertexView); var mesh = new SimpleMesh(vertexView, meshData, "source=BlockModelBuilder," + "blockState=" + state + ",renderType=" + renderType + ",shaded=" + shaded); - out.add(new Model.ConfiguredMesh(material, mesh)); + builder.add(renderType, new Model.ConfiguredMesh(material, mesh)); } - }; - BakedModelBufferer.bufferBlock(ModelUtil.VANILLA_RENDERER, level, state, poseStack, modelData, resultConsumer); + }); - return new SimpleModel(out.build()); + return new SimpleModel(builder.build()); } } diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/MultiBlockModelBuilder.java b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeMultiBlockModelBuilder.java similarity index 58% rename from src/main/java/com/jozufozu/flywheel/lib/model/baked/MultiBlockModelBuilder.java rename to forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeMultiBlockModelBuilder.java index f372d36ba..d84379598 100644 --- a/src/main/java/com/jozufozu/flywheel/lib/model/baked/MultiBlockModelBuilder.java +++ b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/ForgeMultiBlockModelBuilder.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.Nullable; -import com.google.common.collect.ImmutableList; import com.jozufozu.flywheel.api.material.Material; import com.jozufozu.flywheel.api.model.Model; import com.jozufozu.flywheel.api.vertex.VertexView; @@ -13,7 +12,6 @@ import com.jozufozu.flywheel.lib.model.ModelUtil; import com.jozufozu.flywheel.lib.model.SimpleMesh; import com.jozufozu.flywheel.lib.model.SimpleModel; -import com.jozufozu.flywheel.lib.model.baked.BakedModelBufferer.ResultConsumer; import com.jozufozu.flywheel.lib.vertex.NoOverlayVertexView; import com.mojang.blaze3d.vertex.PoseStack; @@ -22,63 +20,58 @@ import net.minecraft.world.level.BlockAndTintGetter; import net.minecraftforge.client.model.data.ModelData; -public class MultiBlockModelBuilder { - private final BlockAndTintGetter level; - private final Iterable positions; - @Nullable - private PoseStack poseStack; +public final class ForgeMultiBlockModelBuilder extends MultiBlockModelBuilder { @Nullable private Function modelDataLookup; - private boolean renderFluids = false; - @Nullable - private BiFunction materialFunc; - public MultiBlockModelBuilder(BlockAndTintGetter level, Iterable positions) { - this.level = level; - this.positions = positions; + public ForgeMultiBlockModelBuilder(BlockAndTintGetter level, Iterable positions) { + super(level, positions); } - public MultiBlockModelBuilder poseStack(PoseStack poseStack) { - this.poseStack = poseStack; + @Override + public ForgeMultiBlockModelBuilder poseStack(PoseStack poseStack) { + super.poseStack(poseStack); return this; } - public MultiBlockModelBuilder modelDataLookup(Function modelDataLookup) { - this.modelDataLookup = modelDataLookup; + @Override + public ForgeMultiBlockModelBuilder enableFluidRendering() { + super.enableFluidRendering(); return this; } - public MultiBlockModelBuilder enableFluidRendering() { - renderFluids = true; + @Override + public ForgeMultiBlockModelBuilder materialFunc(BiFunction materialFunc) { + super.materialFunc(materialFunc); return this; } - public MultiBlockModelBuilder materialFunc(BiFunction materialFunc) { - this.materialFunc = materialFunc; + public ForgeMultiBlockModelBuilder modelDataLookup(Function modelDataLookup) { + this.modelDataLookup = modelDataLookup; return this; } + @Override public SimpleModel build() { - if (modelDataLookup == null) { - modelDataLookup = pos -> ModelData.EMPTY; - } if (materialFunc == null) { materialFunc = ModelUtil::getMaterial; } + if (modelDataLookup == null) { + modelDataLookup = pos -> ModelData.EMPTY; + } - var out = ImmutableList.builder(); + var builder = ChunkLayerSortedListBuilder.getThreadLocal(); - ResultConsumer resultConsumer = (renderType, shaded, data) -> { + BakedModelBufferer.bufferMultiBlock(ModelUtil.VANILLA_RENDERER, positions.iterator(), level, poseStack, modelDataLookup, renderFluids, (renderType, shaded, data) -> { Material material = materialFunc.apply(renderType, shaded); if (material != null) { VertexView vertexView = new NoOverlayVertexView(); MemoryBlock meshData = ModelUtil.convertVanillaBuffer(data, vertexView); var mesh = new SimpleMesh(vertexView, meshData, "source=MultiBlockModelBuilder," + "renderType=" + renderType + ",shaded=" + shaded); - out.add(new Model.ConfiguredMesh(material, mesh)); + builder.add(renderType, new Model.ConfiguredMesh(material, mesh)); } - }; - BakedModelBufferer.bufferMultiBlock(ModelUtil.VANILLA_RENDERER, positions.iterator(), level, poseStack, modelDataLookup, renderFluids, resultConsumer); + }); - return new SimpleModel(out.build()); + return new SimpleModel(builder.build()); } } diff --git a/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java new file mode 100644 index 000000000..41e36bbdb --- /dev/null +++ b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java @@ -0,0 +1,133 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import org.jetbrains.annotations.UnknownNullability; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.blaze3d.vertex.VertexFormat; + +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; + +class MeshEmitter implements VertexConsumer { + private final RenderType renderType; + private final BufferBuilder bufferBuilder; + + private BakedModelBufferer.@UnknownNullability ResultConsumer resultConsumer; + private boolean currentShade; + + MeshEmitter(RenderType renderType) { + this.renderType = renderType; + this.bufferBuilder = new BufferBuilder(renderType.bufferSize()); + } + + public void prepare(BakedModelBufferer.ResultConsumer resultConsumer) { + this.resultConsumer = resultConsumer; + } + + public void end() { + if (bufferBuilder.building()) { + emit(); + } + resultConsumer = null; + } + + public BufferBuilder unwrap(boolean shade) { + prepareForGeometry(shade); + return bufferBuilder; + } + + private void prepareForGeometry(boolean shade) { + if (!bufferBuilder.building()) { + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLOCK); + } else if (shade != currentShade) { + emit(); + } + + currentShade = shade; + } + + private void prepareForGeometry(BakedQuad quad) { + prepareForGeometry(quad.isShade()); + } + + private void emit() { + var renderedBuffer = bufferBuilder.endOrDiscardIfEmpty(); + + if (renderedBuffer != null) { + resultConsumer.accept(renderType, currentShade, renderedBuffer); + renderedBuffer.release(); + } + } + + @Override + public void putBulkData(PoseStack.Pose pose, BakedQuad quad, float red, float green, float blue, int light, int overlay) { + prepareForGeometry(quad); + bufferBuilder.putBulkData(pose, quad, red, green, blue, light, overlay); + } + + @Override + public void putBulkData(PoseStack.Pose pose, BakedQuad quad, float red, float green, float blue, float alpha, int light, int overlay, boolean readExistingColor) { + prepareForGeometry(quad); + bufferBuilder.putBulkData(pose, quad, red, green, blue, alpha, light, overlay, readExistingColor); + } + + @Override + public void putBulkData(PoseStack.Pose pose, BakedQuad quad, float[] brightnesses, float red, float green, float blue, int[] lights, int overlay, boolean readExistingColor) { + prepareForGeometry(quad); + bufferBuilder.putBulkData(pose, quad, brightnesses, red, green, blue, lights, overlay, readExistingColor); + } + + @Override + public void putBulkData(PoseStack.Pose pose, BakedQuad quad, float[] brightnesses, float red, float green, float blue, float alpha, int[] lights, int overlay, boolean readExistingColor) { + prepareForGeometry(quad); + bufferBuilder.putBulkData(pose, quad, brightnesses, red, green, blue, alpha, lights, overlay, readExistingColor); + } + + @Override + public VertexConsumer vertex(double x, double y, double z) { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public VertexConsumer color(int red, int green, int blue, int alpha) { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public VertexConsumer uv(float u, float v) { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public VertexConsumer overlayCoords(int u, int v) { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public VertexConsumer uv2(int u, int v) { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public VertexConsumer normal(float x, float y, float z) { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public void endVertex() { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public void defaultColor(int red, int green, int blue, int alpha) { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } + + @Override + public void unsetDefaultColor() { + throw new UnsupportedOperationException("MeshEmitter only supports putBulkData!"); + } +} diff --git a/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModelEventHandler.java b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModelEventHandler.java new file mode 100644 index 000000000..9957b2f2c --- /dev/null +++ b/forge/src/lib/java/com/jozufozu/flywheel/lib/model/baked/PartialModelEventHandler.java @@ -0,0 +1,31 @@ +package com.jozufozu.flywheel.lib.model.baked; + +import java.util.Map; + +import org.jetbrains.annotations.ApiStatus; + +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.client.event.ModelEvent; + +@ApiStatus.Internal +public final class PartialModelEventHandler { + private PartialModelEventHandler() { + } + + public static void onRegisterAdditional(ModelEvent.RegisterAdditional event) { + for (PartialModel partial : PartialModel.ALL) { + event.register(partial.getLocation()); + } + + PartialModel.tooLate = true; + } + + public static void onBakingCompleted(ModelEvent.BakingCompleted event) { + Map models = event.getModels(); + + for (PartialModel partial : PartialModel.ALL) { + partial.set(models.get(partial.getLocation())); + } + } +} diff --git a/src/main/java/com/jozufozu/flywheel/config/FlwCommands.java b/forge/src/main/java/com/jozufozu/flywheel/impl/FlwCommands.java similarity index 69% rename from src/main/java/com/jozufozu/flywheel/config/FlwCommands.java rename to forge/src/main/java/com/jozufozu/flywheel/impl/FlwCommands.java index d355478fa..37795b40c 100644 --- a/src/main/java/com/jozufozu/flywheel/config/FlwCommands.java +++ b/forge/src/main/java/com/jozufozu/flywheel/impl/FlwCommands.java @@ -1,9 +1,8 @@ -package com.jozufozu.flywheel.config; - -import java.util.function.BiConsumer; +package com.jozufozu.flywheel.impl; import com.jozufozu.flywheel.api.backend.Backend; import com.jozufozu.flywheel.api.backend.BackendManager; +import com.jozufozu.flywheel.backend.engine.uniform.DebugMode; import com.jozufozu.flywheel.backend.engine.uniform.FrameUniforms; import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.IntegerArgumentType; @@ -17,19 +16,17 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.Entity; import net.minecraftforge.client.event.RegisterClientCommandsEvent; +import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; -import net.minecraftforge.server.command.EnumArgument; public final class FlwCommands { private FlwCommands() { } public static void registerClientCommands(RegisterClientCommandsEvent event) { - FlwConfig config = FlwConfig.get(); - LiteralArgumentBuilder command = Commands.literal("flywheel"); - ConfigValue backendValue = config.client.backend; + ConfigValue backendValue = ForgeFlwConfig.INSTANCE.client.backend; command.then(Commands.literal("backend") .executes(context -> { Backend backend = BackendManager.getBackend(); @@ -59,24 +56,30 @@ public static void registerClientCommands(RegisterClientCommandsEvent event) { return Command.SINGLE_SUCCESS; }))); - command.then(booleanValueCommand(Commands.literal("limitUpdates"), config.client.limitUpdates, - (source, bool) -> { - if (bool) { - sendMessage(source, Component.translatable("command.flywheel.limit_updates.get.on")); - } else { - sendMessage(source, Component.translatable("command.flywheel.limit_updates.get.off")); - } - }, - (source, bool) -> { - if (bool) { - sendMessage(source, Component.translatable("command.flywheel.limit_updates.set.on")); + BooleanValue limitUpdatesValue = ForgeFlwConfig.INSTANCE.client.limitUpdates; + command.then(Commands.literal("limitUpdates") + .executes(context -> { + if (limitUpdatesValue.get()) { + sendMessage(context.getSource(), Component.translatable("command.flywheel.limit_updates.get.on")); } else { - sendMessage(source, Component.translatable("command.flywheel.limit_updates.set.off")); + sendMessage(context.getSource(), Component.translatable("command.flywheel.limit_updates.get.off")); } - - Minecraft.getInstance().levelRenderer.allChanged(); - } - )); + return Command.SINGLE_SUCCESS; + }) + .then(Commands.literal("on") + .executes(context -> { + limitUpdatesValue.set(true); + sendMessage(context.getSource(), Component.translatable("command.flywheel.limit_updates.set.on")); + Minecraft.getInstance().levelRenderer.allChanged(); + return Command.SINGLE_SUCCESS; + })) + .then(Commands.literal("off") + .executes(context -> { + limitUpdatesValue.set(false); + sendMessage(context.getSource(), Component.translatable("command.flywheel.limit_updates.set.off")); + Minecraft.getInstance().levelRenderer.allChanged(); + return Command.SINGLE_SUCCESS; + }))); command.then(Commands.literal("crumbling") .then(Commands.argument("pos", BlockPosArgument.blockPos()) @@ -99,7 +102,7 @@ public static void registerClientCommands(RegisterClientCommandsEvent event) { })))); command.then(Commands.literal("debug") - .then(Commands.argument("mode", EnumArgument.enumArgument(DebugMode.class)) + .then(Commands.argument("mode", DebugModeArgument.INSTANCE) .executes(context -> { DebugMode mode = context.getArgument("mode", DebugMode.class); FrameUniforms.debugMode(mode); @@ -121,26 +124,6 @@ public static void registerClientCommands(RegisterClientCommandsEvent event) { event.getDispatcher().register(command); } - private static LiteralArgumentBuilder booleanValueCommand(LiteralArgumentBuilder builder, ConfigValue value, BiConsumer displayAction, BiConsumer setAction) { - return builder - .executes(context -> { - displayAction.accept(context.getSource(), value.get()); - return Command.SINGLE_SUCCESS; - }) - .then(Commands.literal("on") - .executes(context -> { - value.set(true); - setAction.accept(context.getSource(), value.get()); - return Command.SINGLE_SUCCESS; - })) - .then(Commands.literal("off") - .executes(context -> { - value.set(false); - setAction.accept(context.getSource(), value.get()); - return Command.SINGLE_SUCCESS; - })); - } - private static void sendMessage(CommandSourceStack source, Component message) { source.sendSuccess(() -> message, true); } diff --git a/forge/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplatImpl.java b/forge/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplatImpl.java new file mode 100644 index 000000000..1234a4a4a --- /dev/null +++ b/forge/src/main/java/com/jozufozu/flywheel/impl/FlwImplXplatImpl.java @@ -0,0 +1,39 @@ +package com.jozufozu.flywheel.impl; + +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.api.event.BeginFrameEvent; +import com.jozufozu.flywheel.api.event.ReloadLevelRendererEvent; +import com.jozufozu.flywheel.api.event.RenderContext; +import com.jozufozu.flywheel.api.event.RenderStage; +import com.jozufozu.flywheel.api.event.RenderStageEvent; + +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraftforge.common.MinecraftForge; + +public class FlwImplXplatImpl implements FlwImplXplat { + @Override + public void dispatchBeginFrameEvent(RenderContext context) { + MinecraftForge.EVENT_BUS.post(new BeginFrameEvent(context)); + } + + @Override + public void dispatchReloadLevelRendererEvent(@Nullable ClientLevel level) { + MinecraftForge.EVENT_BUS.post(new ReloadLevelRendererEvent(level)); + } + + @Override + public void dispatchRenderStageEvent(RenderContext context, RenderStage stage) { + MinecraftForge.EVENT_BUS.post(new RenderStageEvent(context, stage)); + } + + @Override + public String getVersionStr() { + return FlywheelForge.version().toString(); + } + + @Override + public FlwConfig getConfig() { + return ForgeFlwConfig.INSTANCE; + } +} diff --git a/forge/src/main/java/com/jozufozu/flywheel/impl/FlwLibXplatImpl.java b/forge/src/main/java/com/jozufozu/flywheel/impl/FlwLibXplatImpl.java new file mode 100644 index 000000000..ef50b33fc --- /dev/null +++ b/forge/src/main/java/com/jozufozu/flywheel/impl/FlwLibXplatImpl.java @@ -0,0 +1,82 @@ +package com.jozufozu.flywheel.impl; + +import java.lang.reflect.Field; + +import org.jetbrains.annotations.Nullable; + +import com.jozufozu.flywheel.lib.internal.FlwLibXplat; +import com.jozufozu.flywheel.lib.model.baked.BakedModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.BlockModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.ForgeBakedModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.ForgeBlockModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.ForgeMultiBlockModelBuilder; +import com.jozufozu.flywheel.lib.model.baked.MultiBlockModelBuilder; +import com.jozufozu.flywheel.lib.util.ShadersModHandler; + +import net.irisshaders.iris.api.v0.IrisApi; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.BlockRenderDispatcher; +import net.minecraft.client.renderer.block.ModelBlockRenderer; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockAndTintGetter; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.util.ObfuscationReflectionHelper; + +public class FlwLibXplatImpl implements FlwLibXplat { + @Override + public BlockRenderDispatcher createVanillaBlockRenderDispatcher() { + BlockRenderDispatcher defaultDispatcher = Minecraft.getInstance().getBlockRenderer(); + BlockRenderDispatcher dispatcher = new BlockRenderDispatcher(null, null, null); + try { + for (Field field : BlockRenderDispatcher.class.getDeclaredFields()) { + field.setAccessible(true); + field.set(dispatcher, field.get(defaultDispatcher)); + } + ObfuscationReflectionHelper.setPrivateValue(BlockRenderDispatcher.class, dispatcher, new ModelBlockRenderer(Minecraft.getInstance().getBlockColors()), "f_110900_"); + } catch (Exception e) { + FlwImpl.LOGGER.error("Failed to initialize vanilla BlockRenderDispatcher!", e); + return defaultDispatcher; + } + return dispatcher; + } + + @Override + public BakedModelBuilder createBakedModelBuilder(BakedModel bakedModel) { + return new ForgeBakedModelBuilder(bakedModel); + } + + @Override + public BlockModelBuilder createBlockModelBuilder(BlockState state) { + return new ForgeBlockModelBuilder(state); + } + + @Override + public MultiBlockModelBuilder createMultiBlockModelBuilder(BlockAndTintGetter level, Iterable positions) { + return new ForgeMultiBlockModelBuilder(level, positions); + } + + @Override + @Nullable + public ShadersModHandler.InternalHandler createIrisHandler() { + if (!ModList.get() + .isLoaded("oculus")) { + return null; + } + + return new ShadersModHandler.InternalHandler() { + @Override + public boolean isShaderPackInUse() { + return IrisApi.getInstance() + .isShaderPackInUse(); + } + + @Override + public boolean isRenderingShadowPass() { + return IrisApi.getInstance() + .isRenderingShadowPass(); + } + }; + } +} diff --git a/forge/src/main/java/com/jozufozu/flywheel/impl/FlywheelForge.java b/forge/src/main/java/com/jozufozu/flywheel/impl/FlywheelForge.java new file mode 100644 index 000000000..03c06b4ec --- /dev/null +++ b/forge/src/main/java/com/jozufozu/flywheel/impl/FlywheelForge.java @@ -0,0 +1,132 @@ +package com.jozufozu.flywheel.impl; + +import org.apache.maven.artifact.versioning.ArtifactVersion; +import org.jetbrains.annotations.UnknownNullability; + +import com.jozufozu.flywheel.api.Flywheel; +import com.jozufozu.flywheel.api.event.BeginFrameEvent; +import com.jozufozu.flywheel.api.event.EndClientResourceReloadEvent; +import com.jozufozu.flywheel.api.event.ReloadLevelRendererEvent; +import com.jozufozu.flywheel.api.event.RenderStageEvent; +import com.jozufozu.flywheel.backend.compile.FlwProgramsReloader; +import com.jozufozu.flywheel.backend.engine.uniform.Uniforms; +import com.jozufozu.flywheel.impl.visualization.VisualizationEventHandler; +import com.jozufozu.flywheel.lib.model.ModelCache; +import com.jozufozu.flywheel.lib.model.ModelHolder; +import com.jozufozu.flywheel.lib.model.baked.PartialModelEventHandler; +import com.jozufozu.flywheel.lib.util.LevelAttached; + +import net.minecraft.client.Minecraft; +import net.minecraft.commands.synchronization.ArgumentTypeInfos; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.CustomizeGuiOverlayEvent; +import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.entity.EntityJoinLevelEvent; +import net.minecraftforge.event.entity.EntityLeaveLevelEvent; +import net.minecraftforge.event.level.LevelEvent; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.CrashReportCallables; +import net.minecraftforge.fml.DistExecutor; +import net.minecraftforge.fml.LogicalSide; +import net.minecraftforge.fml.ModLoadingContext; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.registries.ForgeRegistries; +import net.minecraftforge.registries.RegisterEvent; + +@Mod(Flywheel.ID) +public final class FlywheelForge { + @UnknownNullability + private static ArtifactVersion version; + + public FlywheelForge() { + ModLoadingContext modLoadingContext = ModLoadingContext.get(); + + version = modLoadingContext + .getActiveContainer() + .getModInfo() + .getVersion(); + + IEventBus forgeEventBus = MinecraftForge.EVENT_BUS; + IEventBus modEventBus = FMLJavaModLoadingContext.get() + .getModEventBus(); + + ForgeFlwConfig.INSTANCE.registerSpecs(modLoadingContext); + + DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> FlywheelForge.clientInit(forgeEventBus, modEventBus)); + } + + private static void clientInit(IEventBus forgeEventBus, IEventBus modEventBus) { + registerImplEventListeners(forgeEventBus, modEventBus); + registerLibEventListeners(forgeEventBus, modEventBus); + registerBackendEventListeners(forgeEventBus, modEventBus); + + CrashReportCallables.registerCrashCallable("Flywheel Backend", BackendManagerImpl::getBackendString); + FlwImpl.init(); + } + + private static void registerImplEventListeners(IEventBus forgeEventBus, IEventBus modEventBus) { + forgeEventBus.addListener((ReloadLevelRendererEvent e) -> BackendManagerImpl.onReloadLevelRenderer(e.level())); + + forgeEventBus.addListener((TickEvent.LevelTickEvent e) -> { + // Make sure we don't tick on the server somehow. + if (e.phase == TickEvent.Phase.END && e.side == LogicalSide.CLIENT) { + VisualizationEventHandler.onClientTick(Minecraft.getInstance(), e.level); + } + }); + forgeEventBus.addListener((BeginFrameEvent e) -> VisualizationEventHandler.onBeginFrame(e.context())); + forgeEventBus.addListener((RenderStageEvent e) -> VisualizationEventHandler.onRenderStage(e.context(), e.stage())); + forgeEventBus.addListener((EntityJoinLevelEvent e) -> VisualizationEventHandler.onEntityJoinLevel(e.getLevel(), e.getEntity())); + forgeEventBus.addListener((EntityLeaveLevelEvent e) -> VisualizationEventHandler.onEntityLeaveLevel(e.getLevel(), e.getEntity())); + + forgeEventBus.addListener(FlwCommands::registerClientCommands); + + forgeEventBus.addListener((CustomizeGuiOverlayEvent.DebugText e) -> { + Minecraft minecraft = Minecraft.getInstance(); + + if (!minecraft.options.renderDebug) { + return; + } + + FlwDebugInfo.addDebugInfo(minecraft, e.getRight()); + }); + + modEventBus.addListener((EndClientResourceReloadEvent e) -> BackendManagerImpl.onEndClientResourceReload(e.error().isPresent())); + + modEventBus.addListener((FMLCommonSetupEvent e) -> { + ArgumentTypeInfos.registerByClass(BackendArgument.class, BackendArgument.INFO); + ArgumentTypeInfos.registerByClass(DebugModeArgument.class, DebugModeArgument.INFO); + }); + modEventBus.addListener((RegisterEvent e) -> { + if (e.getRegistryKey().equals(ForgeRegistries.Keys.COMMAND_ARGUMENT_TYPES)) { + e.register(ForgeRegistries.Keys.COMMAND_ARGUMENT_TYPES, Flywheel.rl("backend"), () -> BackendArgument.INFO); + e.register(ForgeRegistries.Keys.COMMAND_ARGUMENT_TYPES, Flywheel.rl("debug_mode"), () -> DebugModeArgument.INFO); + } + }); + } + + private static void registerLibEventListeners(IEventBus forgeEventBus, IEventBus modEventBus) { + forgeEventBus.addListener((LevelEvent.Unload e) -> LevelAttached.invalidateLevel(e.getLevel())); + + modEventBus.addListener((EndClientResourceReloadEvent e) -> ModelCache.onEndClientResourceReload()); + modEventBus.addListener((EndClientResourceReloadEvent e) -> ModelHolder.onEndClientResourceReload()); + + modEventBus.addListener(PartialModelEventHandler::onRegisterAdditional); + modEventBus.addListener(PartialModelEventHandler::onBakingCompleted); + } + + private static void registerBackendEventListeners(IEventBus forgeEventBus, IEventBus modEventBus) { + forgeEventBus.addListener((ReloadLevelRendererEvent e) -> Uniforms.onReloadLevelRenderer()); + + modEventBus.addListener((RegisterClientReloadListenersEvent e) -> { + e.registerReloadListener(FlwProgramsReloader.INSTANCE); + }); + } + + public static ArtifactVersion version() { + return version; + } +} diff --git a/src/main/java/com/jozufozu/flywheel/config/FlwConfig.java b/forge/src/main/java/com/jozufozu/flywheel/impl/ForgeFlwConfig.java similarity index 75% rename from src/main/java/com/jozufozu/flywheel/config/FlwConfig.java rename to forge/src/main/java/com/jozufozu/flywheel/impl/ForgeFlwConfig.java index 2fa01e342..fff51a309 100644 --- a/src/main/java/com/jozufozu/flywheel/config/FlwConfig.java +++ b/forge/src/main/java/com/jozufozu/flywheel/impl/ForgeFlwConfig.java @@ -1,39 +1,31 @@ -package com.jozufozu.flywheel.config; +package com.jozufozu.flywheel.impl; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; import com.jozufozu.flywheel.api.backend.Backend; import com.jozufozu.flywheel.api.backend.BackendManager; -import com.mojang.logging.LogUtils; import net.minecraft.ResourceLocationException; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; -import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.config.ModConfig; -public class FlwConfig { - private static final Logger LOGGER = LogUtils.getLogger(); - private static final FlwConfig INSTANCE = new FlwConfig(); +public class ForgeFlwConfig implements FlwConfig { + public static final ForgeFlwConfig INSTANCE = new ForgeFlwConfig(); public final ClientConfig client; private final ForgeConfigSpec clientSpec; - private FlwConfig() { + private ForgeFlwConfig() { Pair clientPair = new ForgeConfigSpec.Builder().configure(ClientConfig::new); this.client = clientPair.getLeft(); clientSpec = clientPair.getRight(); } - public static FlwConfig get() { - return INSTANCE; - } - - public Backend getBackend() { + @Override + public Backend backend() { Backend backend = parseBackend(client.backend.get()); if (backend == null) { backend = BackendManager.getDefaultBackend(); @@ -49,23 +41,25 @@ private static Backend parseBackend(String idStr) { try { backendId = new ResourceLocation(idStr); } catch (ResourceLocationException e) { - LOGGER.warn("Config contains invalid backend ID '" + idStr + "'!"); + FlwImpl.CONFIG_LOGGER.warn("'backend' value '{}' is not a valid resource location", idStr); return null; } Backend backend = Backend.REGISTRY.get(backendId); if (backend == null) { - LOGGER.warn("Config contains non-existent backend with ID '" + backendId + "'!"); + FlwImpl.CONFIG_LOGGER.warn("Backend with ID '{}' is not registered", backendId); return null; } return backend; } + @Override public boolean limitUpdates() { return client.limitUpdates.get(); } + @Override public int workerThreads() { return client.workerThreads.get(); } @@ -75,8 +69,8 @@ public void registerSpecs(ModLoadingContext context) { } public static class ClientConfig { - public final ConfigValue backend; - public final BooleanValue limitUpdates; + public final ForgeConfigSpec.ConfigValue backend; + public final ForgeConfigSpec.BooleanValue limitUpdates; public final ForgeConfigSpec.IntValue workerThreads; private ClientConfig(ForgeConfigSpec.Builder builder) { diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java b/forge/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java similarity index 70% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java rename to forge/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java index 38ad493bb..16874dbaf 100644 --- a/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java +++ b/forge/src/main/java/com/jozufozu/flywheel/impl/mixin/MinecraftMixin.java @@ -2,15 +2,18 @@ import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.jozufozu.flywheel.api.event.EndClientResourceReloadEvent; +import com.jozufozu.flywheel.impl.FlwImpl; import com.mojang.realmsclient.client.RealmsClient; import net.minecraft.client.Minecraft; @@ -25,6 +28,13 @@ abstract class MinecraftMixin { @Final private ReloadableResourceManager resourceManager; + // Inject at invoke cannot be used in constructors in vanilla Mixin, so use ModifyArg instead. + @ModifyArg(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/packs/resources/ReloadableResourceManager;createReload(Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;Ljava/util/concurrent/CompletableFuture;Ljava/util/List;)Lnet/minecraft/server/packs/resources/ReloadInstance;"), index = 0) + private Executor flywheel$onBeginInitialResourceReload(Executor arg0) { + FlwImpl.freezeRegistries(); + return arg0; + } + @Inject(method = "lambda$new$5", at = @At("HEAD")) private void flywheel$onEndInitialResourceReload(RealmsClient realmsClient, ReloadInstance reloadInstance, GameConfig gameConfig, Optional error, CallbackInfo ci) { ModLoader.get().postEvent(new EndClientResourceReloadEvent((Minecraft) (Object) this, resourceManager, true, error)); diff --git a/forge/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/ChunkBuilderMeshingTaskMixin.java b/forge/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/ChunkBuilderMeshingTaskMixin.java new file mode 100644 index 000000000..71e32d0cd --- /dev/null +++ b/forge/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/ChunkBuilderMeshingTaskMixin.java @@ -0,0 +1,23 @@ +package com.jozufozu.flywheel.impl.mixin.sodium; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +import com.jozufozu.flywheel.impl.visualization.VisualizationHelper; + +import me.jellysquid.mods.sodium.client.render.chunk.compile.tasks.ChunkBuilderMeshingTask; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.world.level.block.entity.BlockEntity; + +@Mixin(value = ChunkBuilderMeshingTask.class, remap = false) +abstract class ChunkBuilderMeshingTaskMixin { + @Redirect(method = "execute", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;getRenderer(Lnet/minecraft/world/level/block/entity/BlockEntity;)Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderer;", remap = true)) + private BlockEntityRenderer flywheel$redirectGetRenderer(BlockEntityRenderDispatcher dispatcher, BlockEntity blockEntity) { + if (VisualizationHelper.tryAddBlockEntity(blockEntity)) { + return null; + } + return dispatcher.getRenderer(blockEntity); + } +} diff --git a/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/SodiumMixinPlugin.java b/forge/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/SodiumMixinPlugin.java similarity index 100% rename from src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/SodiumMixinPlugin.java rename to forge/src/main/java/com/jozufozu/flywheel/impl/mixin/sodium/SodiumMixinPlugin.java diff --git a/forge/src/main/resources/META-INF/mods.toml b/forge/src/main/resources/META-INF/mods.toml new file mode 100644 index 000000000..2dc330582 --- /dev/null +++ b/forge/src/main/resources/META-INF/mods.toml @@ -0,0 +1,35 @@ +modLoader = "javafml" +# The loader version doesn't matter. Modify the Forge and/or Minecraft version ranges instead. +loaderVersion = "[0,)" +license = "${mod_license}" +issueTrackerURL = "${mod_issues}" + +[[mods]] +modId = "${mod_id}" +version = "${mod_version}" +displayName = "${mod_name}" +description = "${mod_description}" +logoFile = "logo.png" +authors = "Jozufozu, PepperCode1" +displayURL = "${mod_homepage}" +displayTest = "IGNORE_ALL_VERSION" + +[[dependencies.${mod_id}]] +modId = "minecraft" +mandatory = true +versionRange = "${minecraft_maven_version_range}" +side = "CLIENT" + +[[dependencies.${mod_id}]] +modId = "forge" +mandatory = true +versionRange = "${forge_version_range}" +side = "CLIENT" + +[[dependencies.${mod_id}]] +# This replicates a "breaks" dependency. +# There's a mixin crash with Rubidium <0.7.0. +modId = "rubidium" +mandatory = false +versionRange = "[0.7.0,)" +side = "CLIENT" diff --git a/forge/src/main/resources/flywheel.impl.sodium.mixins.json b/forge/src/main/resources/flywheel.impl.sodium.mixins.json new file mode 100644 index 000000000..c02f33509 --- /dev/null +++ b/forge/src/main/resources/flywheel.impl.sodium.mixins.json @@ -0,0 +1,14 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "com.jozufozu.flywheel.impl.mixin.sodium", + "compatibilityLevel": "JAVA_17", + "refmap": "flywheel.refmap.json", + "plugin": "com.jozufozu.flywheel.impl.mixin.sodium.SodiumMixinPlugin", + "client": [ + "ChunkBuilderMeshingTaskMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/forge/src/main/resources/pack.mcmeta b/forge/src/main/resources/pack.mcmeta new file mode 100644 index 000000000..ae03c9b7f --- /dev/null +++ b/forge/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "${mod_name} resources", + "pack_format": 15 + } +} diff --git a/gradle.properties b/gradle.properties index 878a41fce..3b9b3881f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,20 +1,39 @@ org.gradle.jvmargs = -Xmx3G org.gradle.daemon = false -# mod version info -mod_version = 1.0.0-alpha -artifact_minecraft_version = 1.20.1 -minecraft_version = 1.20.1 -forge_version = 47.2.19 -# Version ranges for the mods.toml -minecraft_version_range = [1.20.1,1.20.2) -forge_version_range = [47,) -loader_version_range = [47,) +# Mod metadata +mod_id = flywheel +mod_name = Flywheel +mod_version = 1.0.0-beta +mod_description = An overhauled entity and block entity rendering API. +mod_license = MIT +mod_sources = https://github.com/Jozufozu/Flywheel +mod_issues = https://github.com/Jozufozu/Flywheel/issues +mod_homepage = https://github.com/Jozufozu/Flywheel -# build dependency versions -forgegradle_version = [6.0.16,6.2) -mixingradle_version = 0.7.+ -mixin_version = 0.8.5 -librarian_version = 1.+ +# Mod dependency declarations +minecraft_semver_version_range = >=1.20.1 <1.20.2 +minecraft_maven_version_range = [1.20.1,1.20.2) +fabric_api_version_range = >=0.86.0 +forge_version_range = [47.0.0,) + +# General build dependency versions +java_version = 17 +arch_loom_version = 1.6-SNAPSHOT cursegradle_version = 1.4.0 parchment_version = 2023.09.03 + +# Minecraft build dependency versions +minecraft_version = 1.20.1 +forge_version = 47.2.19 +fabric_loader_version = 0.15.9 +fabric_api_version = 0.92.1+1.20.1 + +# Build dependency mod versions +sodium_version = mc1.20.1-0.5.8 +iris_version = 1.6.17+1.20.1 +embeddium_version = 0.3.9+mc1.20.1 +oculus_version = 1.20.1-1.6.15a + +# Publication info +artifact_minecraft_version = 1.20.1 diff --git a/gradle/package-infos.gradle b/gradle/package-infos.gradle deleted file mode 100644 index b6877b240..000000000 --- a/gradle/package-infos.gradle +++ /dev/null @@ -1,70 +0,0 @@ -// Adapted from https://github.com/FabricMC/fabric/blob/31787236d242247e0b6c4ae806b1cfaa7042a62c/gradle/package-info.gradle, which is licensed under Apache 2.0. - -import java.nio.file.Files - -setupGeneratePackageInfos(sourceSets.main) - -def setupGeneratePackageInfos(SourceSet sourceSet) { - // We have to capture the source set name for the lazy string literals, - // otherwise it'll just be whatever the last source set is in the list. - def sourceSetName = sourceSet.name - def taskName = sourceSet.getTaskName('generate', 'PackageInfos') - def task = tasks.register(taskName, GeneratePackageInfosTask) { - group = 'flywheel' - description = "Generates package-info files for $sourceSetName packages." - - // Only apply to default source directory since we also add the generated - // sources to the source set. - sourceRoot = file("src/$sourceSetName/java") - outputDir = file("src/$sourceSetName/generatedPackageInfos") - } - sourceSet.java.srcDir task - - def cleanTask = tasks.register(sourceSet.getTaskName('clean', 'PackageInfos'), Delete) { - group = 'flywheel' - delete file("src/$sourceSetName/generatedPackageInfos") - } - clean.dependsOn cleanTask -} - -class GeneratePackageInfosTask extends DefaultTask { - @SkipWhenEmpty - @InputDirectory - final DirectoryProperty sourceRoot = project.objects.directoryProperty() - - @OutputDirectory - final DirectoryProperty outputDir = project.objects.directoryProperty() - - @TaskAction - def run() { - def output = outputDir.get().asFile.toPath() - output.deleteDir() - def root = sourceRoot.get().asFile.toPath() - - root.eachDirRecurse { - def containsJava = Files.list(it).any { - Files.isRegularFile(it) && it.fileName.toString().endsWith('.java') - } - - if (containsJava && Files.notExists(it.resolve('package-info.java'))) { - def relativePath = root.relativize(it) - def target = output.resolve(relativePath) - Files.createDirectories(target) - - target.resolve('package-info.java').withWriter { - def packageName = relativePath.toString().replace(File.separator, '.') - it.write("""@ParametersAreNonnullByDefault - |@FieldsAreNonnullByDefault - |@MethodsReturnNonnullByDefault - |package $packageName; - | - |import javax.annotation.ParametersAreNonnullByDefault; - | - |import net.minecraft.FieldsAreNonnullByDefault; - |import net.minecraft.MethodsReturnNonnullByDefault; - |""".stripMargin()) - } - } - } - } -} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index c1962a79e..e6441136f 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 309b4e18d..e7646dead 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index aeb74cbb4..1aa94a426 100755 --- a/gradlew +++ b/gradlew @@ -83,7 +83,8 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -130,10 +131,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -198,11 +202,11 @@ fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 93e3f59f1..25da30dbd 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -43,11 +43,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail diff --git a/javadoc-options.txt b/javadoc-options.txt new file mode 100644 index 000000000..54fbbe259 --- /dev/null +++ b/javadoc-options.txt @@ -0,0 +1,2 @@ +-Xdoclint:none +-quiet diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 26eaa3d68..000000000 --- a/settings.gradle +++ /dev/null @@ -1,18 +0,0 @@ -pluginManagement { - repositories { - gradlePluginPortal() - mavenCentral() - maven { - name = 'MinecraftForge' - url = 'https://maven.minecraftforge.net/' - } - maven { url = 'https://repo.spongepowered.org/repository/maven-public' } - maven { url = 'https://maven.parchmentmc.org' } - } -} - -plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' -} - -rootProject.name = 'Flywheel-Forge' diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 000000000..cf8fd7a12 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,25 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + maven("https://maven.minecraftforge.net/") { + name = "MinecraftForge" + } + maven("https://maven.architectury.dev/") { + name = "Architectury" + } + maven("https://repo.spongepowered.org/repository/maven-public") + maven("https://maven.parchmentmc.org") + } + + plugins { + val arch_loom_version: String by settings + id("dev.architectury.loom") version arch_loom_version + } +} + +rootProject.name = "Flywheel" + +include("common") +include("fabric") +include("forge") diff --git a/src/main/java/com/jozufozu/flywheel/Flywheel.java b/src/main/java/com/jozufozu/flywheel/Flywheel.java deleted file mode 100644 index 290722f23..000000000 --- a/src/main/java/com/jozufozu/flywheel/Flywheel.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.jozufozu.flywheel; - -import java.util.ArrayList; - -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jozufozu.flywheel.api.event.EndClientResourceReloadEvent; -import com.jozufozu.flywheel.api.visualization.VisualizationManager; -import com.jozufozu.flywheel.backend.Backends; -import com.jozufozu.flywheel.backend.ShaderIndices; -import com.jozufozu.flywheel.backend.compile.FlwPrograms; -import com.jozufozu.flywheel.backend.engine.uniform.Uniforms; -import com.jozufozu.flywheel.config.BackendArgument; -import com.jozufozu.flywheel.config.FlwCommands; -import com.jozufozu.flywheel.config.FlwConfig; -import com.jozufozu.flywheel.impl.BackendManagerImpl; -import com.jozufozu.flywheel.impl.registry.IdRegistryImpl; -import com.jozufozu.flywheel.impl.registry.RegistryImpl; -import com.jozufozu.flywheel.impl.visualization.VisualizationEventHandler; -import com.jozufozu.flywheel.lib.instance.InstanceTypes; -import com.jozufozu.flywheel.lib.material.CutoutShaders; -import com.jozufozu.flywheel.lib.material.FogShaders; -import com.jozufozu.flywheel.lib.material.StandardMaterialShaders; -import com.jozufozu.flywheel.lib.memory.FlwMemoryTracker; -import com.jozufozu.flywheel.lib.model.ModelCache; -import com.jozufozu.flywheel.lib.model.ModelHolder; -import com.jozufozu.flywheel.lib.model.baked.PartialModel; -import com.jozufozu.flywheel.lib.util.LevelAttached; -import com.jozufozu.flywheel.lib.util.ShadersModHandler; -import com.jozufozu.flywheel.lib.util.StringUtil; -import com.jozufozu.flywheel.vanilla.VanillaVisuals; - -import net.minecraft.client.Minecraft; -import net.minecraft.commands.synchronization.ArgumentTypeInfos; -import net.minecraft.core.Vec3i; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.CustomizeGuiOverlayEvent; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.level.LevelEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.IExtensionPoint; -import net.minecraftforge.fml.ModLoadingContext; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegisterEvent; - -@Mod(Flywheel.ID) -public class Flywheel { - public static final String ID = "flywheel"; - public static final Logger LOGGER = LoggerFactory.getLogger(ID); - private static ArtifactVersion version; - - public Flywheel() { - ModLoadingContext modLoadingContext = ModLoadingContext.get(); - - version = modLoadingContext - .getActiveContainer() - .getModInfo() - .getVersion(); - - IEventBus forgeEventBus = MinecraftForge.EVENT_BUS; - IEventBus modEventBus = FMLJavaModLoadingContext.get() - .getModEventBus(); - modEventBus.addListener(Flywheel::onCommonSetup); - modEventBus.addListener(Flywheel::onRegister); - - FlwConfig.get().registerSpecs(modLoadingContext); - - modLoadingContext.registerExtensionPoint(IExtensionPoint.DisplayTest.class, () -> new IExtensionPoint.DisplayTest( - () -> "any", - (serverVersion, isNetwork) -> true - )); - - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> Flywheel.clientInit(forgeEventBus, modEventBus)); - } - - private static void clientInit(IEventBus forgeEventBus, IEventBus modEventBus) { - forgeEventBus.addListener(Flywheel::addDebugInfo); - - forgeEventBus.addListener(BackendManagerImpl::onReloadLevelRenderer); - - forgeEventBus.addListener(VisualizationEventHandler::onClientTick); - forgeEventBus.addListener(VisualizationEventHandler::onBeginFrame); - forgeEventBus.addListener(VisualizationEventHandler::onRenderStage); - forgeEventBus.addListener(VisualizationEventHandler::onEntityJoinLevel); - forgeEventBus.addListener(VisualizationEventHandler::onEntityLeaveLevel); - - forgeEventBus.addListener(FlwCommands::registerClientCommands); - - forgeEventBus.addListener(Uniforms::onReloadLevelRenderer); - - forgeEventBus.addListener((LevelEvent.Unload e) -> LevelAttached.onUnloadLevel(e)); - -// forgeEventBus.addListener(ExampleEffect::tick); -// forgeEventBus.addListener(ExampleEffect::onReload); - - modEventBus.addListener(Flywheel::registerClientReloadListeners); - modEventBus.addListener(Flywheel::onClientSetup); - modEventBus.addListener(Flywheel::onLoadComplete); - - modEventBus.addListener(BackendManagerImpl::onEndClientResourceReload); - - modEventBus.addListener((EndClientResourceReloadEvent e) -> ModelCache.onEndClientResourceReload(e)); - modEventBus.addListener(ModelHolder::onEndClientResourceReload); - - modEventBus.addListener(PartialModel::onModelRegistry); - modEventBus.addListener(PartialModel::onModelBake); - - BackendManagerImpl.init(); - - ShadersModHandler.init(); - - Backends.init(); - } - - private static void registerClientReloadListeners(RegisterClientReloadListenersEvent event) { - event.registerReloadListener(FlwPrograms.ResourceReloadListener.INSTANCE); - } - - private static void onClientSetup(FMLClientSetupEvent event) { - InstanceTypes.init(); - CutoutShaders.init(); - FogShaders.init(); - StandardMaterialShaders.init(); - - ShaderIndices.init(); - - VanillaVisuals.init(); - } - - private static void onLoadComplete(FMLLoadCompleteEvent event) { - RegistryImpl.freezeAll(); - IdRegistryImpl.freezeAll(); - } - - private static void onCommonSetup(FMLCommonSetupEvent event) { - ArgumentTypeInfos.registerByClass(BackendArgument.class, BackendArgument.INFO); - } - - private static void onRegister(RegisterEvent event) { - event.register(ForgeRegistries.Keys.COMMAND_ARGUMENT_TYPES, rl("backend"), () -> BackendArgument.INFO); - } - - private static void addDebugInfo(CustomizeGuiOverlayEvent.DebugText event) { - Minecraft mc = Minecraft.getInstance(); - - if (!mc.options.renderDebug) { - return; - } - - ArrayList info = event.getRight(); - info.add(""); - info.add("Flywheel: " + getVersion()); - info.add("Backend: " + BackendManagerImpl.getBackendString()); - info.add("Update limiting: " + (FlwConfig.get().limitUpdates() ? "on" : "off")); - - VisualizationManager manager = VisualizationManager.get(mc.level); - if (manager != null) { - info.add("B: " + manager.getBlockEntities().getVisualCount() - + ", E: " + manager.getEntities().getVisualCount() - + ", F: " + manager.getEffects().getVisualCount()); - Vec3i renderOrigin = manager.getRenderOrigin(); - info.add("Origin: " + renderOrigin.getX() + ", " + renderOrigin.getY() + ", " + renderOrigin.getZ()); - } - - info.add("Memory Usage: CPU: " + StringUtil.formatBytes(FlwMemoryTracker.getCPUMemory()) + ", GPU: " + StringUtil.formatBytes(FlwMemoryTracker.getGPUMemory())); - } - - public static ArtifactVersion getVersion() { - return version; - } - - public static ResourceLocation rl(String path) { - return new ResourceLocation(ID, path); - } -} diff --git a/src/main/java/com/jozufozu/flywheel/backend/mixin/GameRendererAccessor.java b/src/main/java/com/jozufozu/flywheel/backend/mixin/GameRendererAccessor.java deleted file mode 100644 index cf92578fb..000000000 --- a/src/main/java/com/jozufozu/flywheel/backend/mixin/GameRendererAccessor.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.jozufozu.flywheel.backend.mixin; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; -import org.spongepowered.asm.mixin.gen.Invoker; - -import net.minecraft.client.Camera; -import net.minecraft.client.renderer.GameRenderer; - -@Mixin(GameRenderer.class) -public interface GameRendererAccessor { - @Invoker("getFov") - double flywheel$getFov(Camera pActiveRenderInfo, float pPartialTicks, boolean pUseFOVSetting); - - @Accessor("zoom") - float flywheel$getZoom(); - - @Accessor("zoomX") - float flywheel$getZoomX(); - - @Accessor("zoomY") - float flywheel$getZoomY(); -} diff --git a/src/main/java/com/jozufozu/flywheel/backend/mixin/LightTextureAccessor.java b/src/main/java/com/jozufozu/flywheel/backend/mixin/LightTextureAccessor.java deleted file mode 100644 index edda4df14..000000000 --- a/src/main/java/com/jozufozu/flywheel/backend/mixin/LightTextureAccessor.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jozufozu.flywheel.backend.mixin; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.texture.DynamicTexture; - -@Mixin(LightTexture.class) -public interface LightTextureAccessor { - @Accessor("lightTexture") - DynamicTexture flywheel$texture(); -} diff --git a/src/main/java/com/jozufozu/flywheel/backend/mixin/OverlayTextureAccessor.java b/src/main/java/com/jozufozu/flywheel/backend/mixin/OverlayTextureAccessor.java deleted file mode 100644 index 0f5af0ca6..000000000 --- a/src/main/java/com/jozufozu/flywheel/backend/mixin/OverlayTextureAccessor.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.jozufozu.flywheel.backend.mixin; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.client.renderer.texture.OverlayTexture; - -@Mixin(OverlayTexture.class) -public interface OverlayTextureAccessor { - @Accessor("texture") - DynamicTexture flywheel$texture(); -} diff --git a/src/main/java/com/jozufozu/flywheel/config/DebugMode.java b/src/main/java/com/jozufozu/flywheel/config/DebugMode.java deleted file mode 100644 index d8cbdbf50..000000000 --- a/src/main/java/com/jozufozu/flywheel/config/DebugMode.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.jozufozu.flywheel.config; - -public enum DebugMode { - OFF, - NORMALS, - INSTANCE_ID, - LIGHT_LEVEL, - LIGHT_COLOR, - OVERLAY, - DIFFUSE, - LIGHT_VOLUME, -} diff --git a/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationEventHandler.java b/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationEventHandler.java deleted file mode 100644 index f7a74fee2..000000000 --- a/src/main/java/com/jozufozu/flywheel/impl/visualization/VisualizationEventHandler.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.jozufozu.flywheel.impl.visualization; - -import com.jozufozu.flywheel.api.event.BeginFrameEvent; -import com.jozufozu.flywheel.api.event.RenderStageEvent; -import com.jozufozu.flywheel.api.visualization.VisualizationManager; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.world.level.Level; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.event.entity.EntityJoinLevelEvent; -import net.minecraftforge.event.entity.EntityLeaveLevelEvent; -import net.minecraftforge.fml.LogicalSide; - -public final class VisualizationEventHandler { - private VisualizationEventHandler() { - } - - public static void onClientTick(TickEvent.LevelTickEvent event) { - // Make sure we don't tick on the server somehow. - if (event.phase != TickEvent.Phase.END || event.side != LogicalSide.CLIENT) { - return; - } - - // The game won't be paused in the tick event, but let's make sure there's a player. - if (Minecraft.getInstance().player == null) { - return; - } - - VisualizationManagerImpl manager = VisualizationManagerImpl.get(event.level); - if (manager == null) { - return; - } - - manager.tick(); - } - - public static void onBeginFrame(BeginFrameEvent event) { - ClientLevel level = event.context() - .level(); - VisualizationManagerImpl manager = VisualizationManagerImpl.get(level); - if (manager == null) { - return; - } - - manager.beginFrame(event.context()); - } - - public static void onRenderStage(RenderStageEvent event) { - ClientLevel level = event.context() - .level(); - VisualizationManagerImpl manager = VisualizationManagerImpl.get(level); - if (manager == null) { - return; - } - - manager.renderStage(event.context(), event.stage()); - } - - public static void onEntityJoinLevel(EntityJoinLevelEvent event) { - Level level = event.getLevel(); - VisualizationManager manager = VisualizationManager.get(level); - if (manager == null) { - return; - } - - manager.getEntities().queueAdd(event.getEntity()); - } - - public static void onEntityLeaveLevel(EntityLeaveLevelEvent event) { - Level level = event.getLevel(); - VisualizationManager manager = VisualizationManager.get(level); - if (manager == null) { - return; - } - - manager.getEntities().queueRemove(event.getEntity()); - } -} diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java b/src/main/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java deleted file mode 100644 index 8f00b36a2..000000000 --- a/src/main/java/com/jozufozu/flywheel/lib/model/baked/MeshEmitter.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.jozufozu.flywheel.lib.model.baked; - -import org.jetbrains.annotations.Nullable; - -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.blaze3d.vertex.VertexFormat; - -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; - -class MeshEmitter implements VertexConsumer { - private final BufferBuilder bufferBuilder; - private final RenderType renderType; - private boolean lastQuadWasShaded; - private boolean seenFirstQuad; - @Nullable - private BakedModelBufferer.ResultConsumer resultConsumer; - - MeshEmitter(BufferBuilder bufferBuilder, RenderType renderType) { - this.bufferBuilder = bufferBuilder; - this.renderType = renderType; - } - - public void begin(BakedModelBufferer.ResultConsumer resultConsumer) { - this.resultConsumer = resultConsumer; - - begin(); - } - - public void end() { - emit(); - seenFirstQuad = false; - resultConsumer = null; - } - - private void begin() { - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLOCK); - } - - private void emit() { - var renderedBuffer = bufferBuilder.endOrDiscardIfEmpty(); - - if (renderedBuffer != null) { - if (resultConsumer != null) { - resultConsumer.accept(renderType, lastQuadWasShaded, renderedBuffer); - } - renderedBuffer.release(); - } - } - - private void observeQuadAndEmitIfNecessary(BakedQuad quad) { - if (seenFirstQuad && lastQuadWasShaded != quad.isShade()) { - emit(); - begin(); - } - - seenFirstQuad = true; - lastQuadWasShaded = quad.isShade(); - } - - @Override - public void putBulkData(PoseStack.Pose poseEntry, BakedQuad quad, float[] colorMuls, float red, float green, float blue, int[] combinedLights, int combinedOverlay, boolean mulColor) { - observeQuadAndEmitIfNecessary(quad); - - bufferBuilder.putBulkData(poseEntry, quad, colorMuls, red, green, blue, combinedLights, combinedOverlay, mulColor); - } - - @Override - public void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] baseBrightness, float red, float green, float blue, float alpha, int[] lightmapCoords, int overlayCoords, boolean readExistingColor) { - observeQuadAndEmitIfNecessary(quad); - - bufferBuilder.putBulkData(matrixEntry, quad, baseBrightness, red, green, blue, alpha, lightmapCoords, overlayCoords, readExistingColor); - } - - @Override - public VertexConsumer vertex(double x, double y, double z) { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public VertexConsumer color(int red, int green, int blue, int alpha) { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public VertexConsumer uv(float u, float v) { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public VertexConsumer overlayCoords(int u, int v) { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public VertexConsumer uv2(int u, int v) { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public VertexConsumer normal(float x, float y, float z) { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public void endVertex() { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public void defaultColor(int red, int green, int blue, int alpha) { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } - - @Override - public void unsetDefaultColor() { - throw new UnsupportedOperationException("ShadeSeparatingVertexConsumer only supports putBulkData!"); - } -} diff --git a/src/main/java/com/jozufozu/flywheel/lib/model/baked/PartialModel.java b/src/main/java/com/jozufozu/flywheel/lib/model/baked/PartialModel.java deleted file mode 100644 index c8fc27a0c..000000000 --- a/src/main/java/com/jozufozu/flywheel/lib/model/baked/PartialModel.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.jozufozu.flywheel.lib.model.baked; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.client.event.ModelEvent; - -/** - * A helper class for loading and accessing json models. - *
- * Creating a PartialModel will make the associated modelLocation automatically load. - * PartialModels must be initialized in the mod class constructor. - *
- * Once {@link ModelEvent.RegisterAdditional} finishes, all PartialModels (with valid modelLocations) - * will have their bakedModel fields populated. - *
- * Attempting to create a PartialModel after {@link ModelEvent.RegisterAdditional} will cause an error. - */ -public class PartialModel { - private static final List ALL = new ArrayList<>(); - private static boolean tooLate = false; - - protected final ResourceLocation modelLocation; - protected BakedModel bakedModel; - - public PartialModel(ResourceLocation modelLocation) { - if (tooLate) { - throw new RuntimeException("PartialModel '" + modelLocation + "' loaded after ModelRegistryEvent"); - } - - this.modelLocation = modelLocation; - ALL.add(this); - } - - public static void onModelRegistry(ModelEvent.RegisterAdditional event) { - for (PartialModel partial : ALL) { - event.register(partial.getLocation()); - } - - tooLate = true; - } - - public static void onModelBake(ModelEvent.BakingCompleted event) { - var modelRegistry = event.getModels(); - for (PartialModel partial : ALL) { - partial.set(modelRegistry.get(partial.getLocation())); - } - } - - public String getName() { - return getLocation() - .toString(); - } - - protected void set(BakedModel bakedModel) { - this.bakedModel = bakedModel; - } - - public ResourceLocation getLocation() { - return modelLocation; - } - - public BakedModel get() { - return bakedModel; - } -} diff --git a/src/main/java/com/jozufozu/flywheel/vanilla/effect/ExampleEffect.java b/src/main/java/com/jozufozu/flywheel/vanilla/effect/ExampleEffect.java deleted file mode 100644 index fd6712536..000000000 --- a/src/main/java/com/jozufozu/flywheel/vanilla/effect/ExampleEffect.java +++ /dev/null @@ -1,292 +0,0 @@ -package com.jozufozu.flywheel.vanilla.effect; - -import java.util.ArrayList; -import java.util.List; - -import org.joml.Vector3f; - -import com.jozufozu.flywheel.api.event.ReloadLevelRendererEvent; -import com.jozufozu.flywheel.api.task.Plan; -import com.jozufozu.flywheel.api.visual.DynamicVisual; -import com.jozufozu.flywheel.api.visual.Effect; -import com.jozufozu.flywheel.api.visual.EffectVisual; -import com.jozufozu.flywheel.api.visual.TickableVisual; -import com.jozufozu.flywheel.api.visualization.VisualizationContext; -import com.jozufozu.flywheel.api.visualization.VisualizationManager; -import com.jozufozu.flywheel.lib.instance.InstanceTypes; -import com.jozufozu.flywheel.lib.instance.TransformedInstance; -import com.jozufozu.flywheel.lib.model.Models; -import com.jozufozu.flywheel.lib.task.ForEachPlan; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.core.Vec3i; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.phys.Vec3; -import net.minecraftforge.event.TickEvent; - -// http://www.kfish.org/boids/pseudocode.html -public class ExampleEffect implements Effect { - private static final List ALL_EFFECTS = new ArrayList<>(); - - private static final int VISUAL_COUNT = 500; - private static final float SPAWN_RADIUS = 8.0f; - private static final float LIMIT_RANGE = 10.0f; - private static final float SPEED_LIMIT = 0.1f; - private static final float RENDER_SCALE = 2 / 16f; - - private static final float SIGHT_RANGE = 5; - - private static final float COHERENCE = 1f / 60f; - private static final float SEPARATION = 0.05f; - private static final float ALIGNMENT = 1 / 20f; - private static final float TENDENCY = 1 / 1000f; - private static final float AVERSION = 1; - - private static final float GNAT_JITTER = 0.05f; - - private final Level level; - private final Vector3f targetPoint; - - public ExampleEffect(Level level, Vector3f targetPoint) { - this.level = level; - this.targetPoint = targetPoint; - } - - public static void tick(TickEvent.ClientTickEvent event) { - if (event.phase != TickEvent.Phase.START || Minecraft.getInstance().isPaused()) { - return; - } - - trySpawnNewEffect(); - } - - public static void onReloadLevelRenderer(ReloadLevelRendererEvent event) { - ALL_EFFECTS.clear(); - } - - private static void trySpawnNewEffect() { - Level level = Minecraft.getInstance().level; - Player player = Minecraft.getInstance().player; - - if (player == null || level == null) { - return; - } - - VisualizationManager manager = VisualizationManager.get(level); - if (manager == null) { - return; - } - - if (!ALL_EFFECTS.isEmpty() && level.random.nextFloat() > 0.005f) { - return; - } - - Vec3 playerPos = player.position(); - - var x = (float) (playerPos.x + Mth.nextFloat(level.random, -20, 20)); - var y = (float) (playerPos.y + Mth.nextFloat(level.random, 0, 5)); - var z = (float) (playerPos.z + Mth.nextFloat(level.random, -20, 20)); - - ExampleEffect effect = new ExampleEffect(level, new Vector3f(x, y, z)); - ALL_EFFECTS.add(effect); - manager.getEffects().queueAdd(effect); - } - - @Override - public EffectVisual visualize(VisualizationContext ctx) { - return new ExampleVisual(ctx); - } - - public class ExampleVisual implements EffectVisual, TickableVisual, DynamicVisual { - private final List effects; - private final List boids; - - public ExampleVisual(VisualizationContext ctx) { - this.effects = new ArrayList<>(VISUAL_COUNT); - this.boids = new ArrayList<>(VISUAL_COUNT); - - for (int i = 0; i < VISUAL_COUNT; i++) { - var x = targetPoint.x + Mth.nextFloat(level.random, -SPAWN_RADIUS, SPAWN_RADIUS); - var y = targetPoint.y + Mth.nextFloat(level.random, -SPAWN_RADIUS, SPAWN_RADIUS); - var z = targetPoint.z + Mth.nextFloat(level.random, -SPAWN_RADIUS, SPAWN_RADIUS); - - Boid boid = new Boid(x, y, z); - boids.add(boid); - effects.add(new BoidVisual(ctx, boid)); - } - } - - @Override - public Plan planTick() { - Plan beginTick = ForEachPlan.of(() -> boids, Boid::beginTick); - return beginTick.then(ForEachPlan.of(() -> effects, boid -> boid.self.tick(boids))); - } - - @Override - public Plan planFrame() { - return ForEachPlan.of(() -> effects, BoidVisual::beginFrame); - } - - @Override - public void init(float partialTick) { - } - - @Override - public void update(float partialTick) { - } - - @Override - public void delete() { - effects.forEach(BoidVisual::_delete); - } - } - - public static class Boid { - final Vector3f lastPosition; - final Vector3f position; - final Vector3f lastVelocity = new Vector3f(0); - final Vector3f velocity = new Vector3f(0); - - final Vector3f scratch = new Vector3f(0); - final Vector3f coherence = new Vector3f(0); - final Vector3f alignment = new Vector3f(0); - - public Boid(float x, float y, float z) { - lastPosition = new Vector3f(x, y, z); - position = new Vector3f(x, y, z); - } - - - private void beginTick() { - lastVelocity.set(velocity); - lastPosition.set(position); - } - - public void tick(List swarm) { - int seen = 0; - coherence.set(0); - alignment.set(0); - for (Boid boid : swarm) { - if (boid == this) { - continue; - } - - float distance = boid.lastPosition.distance(lastPosition); - - if (distance > SIGHT_RANGE) { - continue; - } - seen++; - - coherence(boid); - separation(boid); - alignment(boid); - } - - if (seen > 0) { - coherencePost(seen); - alignmentPost(seen); - } - //tend(ExampleEffect.this.targetPoint); - - avoidPlayer(); - - position.add(capSpeed(velocity)); - } - - private void avoidPlayer() { - var player = Minecraft.getInstance().player.position(); - scratch.set(player.x, player.y, player.z); - - float dsq = lastPosition.distanceSquared(scratch); - if (dsq > SIGHT_RANGE * SIGHT_RANGE) { - return; - } - - lastPosition.sub(scratch, scratch) - .mul(AVERSION / dsq); - - velocity.add(capSpeed(scratch)); - } - - private void coherence(Boid other) { - this.coherence.add(other.lastPosition); - } - - private void separation(Boid other) { - float dsq = lastPosition.distanceSquared(other.lastPosition); - var push = other.lastPosition.sub(lastPosition, this.scratch) - .mul(SEPARATION / dsq); - - this.velocity.sub(push); - } - - private void alignment(Boid boid) { - this.alignment.add(boid.lastVelocity); - } - - private void coherencePost(int seen) { - this.coherence.div(seen) - .sub(lastPosition) - .mul(COHERENCE); - this.velocity.add(capSpeed(this.coherence)); - } - - private void alignmentPost(int seen) { - this.alignment.div(seen) - .sub(lastVelocity) - .mul(ALIGNMENT); - - this.velocity.add(this.alignment); - } - - private void tend(Vector3f target) { - this.scratch.set(target) - .sub(lastPosition) - .mul(TENDENCY); - this.velocity.add(capSpeed(this.scratch)); - } - - private static Vector3f capSpeed(Vector3f vec) { - return vec.normalize(SPEED_LIMIT); - } - } - - public static class BoidVisual { - private final Boid self; - private final Vec3i renderOrigin; - - private final TransformedInstance instance; - - public BoidVisual(VisualizationContext ctx, Boid self) { - renderOrigin = ctx.renderOrigin(); - this.self = self; - - instance = ctx.instancerProvider() - .instancer(InstanceTypes.TRANSFORMED, Models.block(Blocks.SHROOMLIGHT.defaultBlockState())) - .createInstance(); - - instance.light(LightTexture.FULL_BRIGHT); - } - - public void _delete() { - instance.delete(); - } - - public void beginFrame(DynamicVisual.Context context) { - float partialTick = context.partialTick(); - var x = Mth.lerp(partialTick, self.lastPosition.x, self.position.x); - var y = Mth.lerp(partialTick, self.lastPosition.y, self.position.y); - var z = Mth.lerp(partialTick, self.lastPosition.z, self.position.z); - - instance.loadIdentity() - .translateBack(renderOrigin) - .translate(x, y, z) - .scale(RENDER_SCALE); - } - } -} diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml deleted file mode 100644 index 5d3bde9cc..000000000 --- a/src/main/resources/META-INF/mods.toml +++ /dev/null @@ -1,37 +0,0 @@ -modLoader = "javafml" -loaderVersion = "${loader_version_range}" -issueTrackerURL = "https://github.com/Jozufozu/Flywheel/issues" -license = "MIT" - -[[mods]] -modId = "flywheel" -version = "${mod_version}" -displayName = "Flywheel" -logoFile = "logo.png" -displayURL = "https://github.com/Jozufozu/Flywheel" -authors = "Jozufozu, PepperCode1" -description = ''' -A modern engine for modded minecraft.''' - -[[dependencies.flywheel]] -modId = "forge" -mandatory = true -versionRange = "${forge_version_range}" -ordering = "NONE" -side = "CLIENT" - -[[dependencies.flywheel]] -modId = "minecraft" -mandatory = true -versionRange = "${minecraft_version_range}" -ordering = "NONE" -side = "CLIENT" - -[[dependencies.flywheel]] -modId = "rubidium" -# This replicates a "breaks" dependency. -# There's a mixin crash with Rubidium <0.7.0. -mandatory = false -versionRange = "[0.7.0,)" -ordering = "NONE" -side = "CLIENT" diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta deleted file mode 100644 index 2f2b4f1e2..000000000 --- a/src/main/resources/pack.mcmeta +++ /dev/null @@ -1,6 +0,0 @@ -{ - "pack": { - "description": "Flywheel resources", - "pack_format": 15 - } -}