Compare commits

..
Author SHA1 Message Date
Jason Mitchell 3d97977050 Maybe fix holo inventory again - v2 - final.xlsx (#1413) 2026-02-22 20:37:08 -08:00
Eclipse-Sol 5f41c60bc2 Remove force blend as commit 0325a96b fixed this properly. (#1409) 2026-02-22 11:35:35 -08:00
Jason Mitchell 0325a96bc2 Add unknown blend state and BufferBlendOverride handling from modern Iris (#1408) 2026-02-21 15:27:22 -08:00
Caedis ad123d0bd5 Now with 200% more screen shake (#1402) 2026-02-18 09:20:47 -05:00
Caedis 4b89997985 Add slider for hurt screen shake intensity (#1401) 2026-02-18 04:23:57 +01:00
Death Fuel f5c9fa3301 slightly less stupid glyph size loading (#1390) 2026-02-15 18:49:44 -08:00
Death Fuel d6a6d3b525 Less logging + small refactor (#1379)
* less logging

* refactor

* missed a spot

* consistency
2026-02-15 18:48:51 -08:00
Ruling-0 f079bed977 TESRs Translucency Sorting (#1384)
* Iterate blocks in region towards the camera

* Sort translucent TESRs when translucency sorting is enabled
2026-02-15 18:48:05 -08:00
Caedis c9ec40e94b use mc.renderViewEntity instead of mc.thePlayer in shader shadow rendering (#1392) 2026-02-15 18:47:19 -08:00
embeddedt 8380f3853d Detect quads rendered by vanilla AO pipeline and only recalculate lighting for those (#1391)
* Detect quads rendered by vanilla AO pipeline and only recalculate lighting for those

* Handle oldLighting correctly
2026-02-15 18:46:58 -08:00
Yan Huang 534ae6b05c Remove support for NotEnoughIds-Legacy and update BetterCrashes dependency version, as the old files have been removed from the GTNH source. (#1388) 2026-02-15 09:35:09 -08:00
Jason Mitchell 68d523d3df Sign Culling (#1386) 2026-02-14 04:09:00 -08:00
Jason Mitchell 2f22a7b3ad Swap vanilla clipping helper with joml (#1385) 2026-02-13 14:29:31 -08:00
Jason Mitchell 7b79b90dd6 Fix crash without speedupAnimations enabled (#1377) 2026-02-09 12:00:36 -08:00
Jason Mitchell 417f23f826 Add runtime toggle for HUD Caching, and disable by default (for now at least) (#1374) 2026-02-07 14:44:49 -08:00
TeterosandTeteros ca3c46c873 Add PFAA Geologica cobble/bricks to the BlockCrackFix Whitelist (#1370)
Co-authored-by: Teteros <[email protected]>
2026-02-06 11:36:41 -08:00
Jason Mitchell 82fa9ade2b Add new emitter modes (#1368)
* Indirect
* Individual
2026-02-05 20:58:10 -08:00
Jason Mitchell aaab8fd0bc Thread safe biome cache & VAO Redirection (#1367)
* Thread safe biome cache

* VAO Redirection
* Delegate GLSM VAO calls to UniversalVAO
* Redirect usages of UniversalVAO & LWJGLService VAO functions to GLSM
* Avoid infinite recursion
2026-02-05 13:56:44 -08:00
Jason Mitchell bd56ccc4b8 Totally not experimental 2026-02-04 22:42:03 -08:00
sisyphussy e17f60308d Display List Refactor (#1360) 2026-02-04 10:39:20 -08:00
Kotmatross 1dd98978ad [Hotfix] Fix NTM:Space mixin targets for X5593_H261 (#1356) 2026-02-02 10:02:36 -08:00
Jason Mitchell dae986eb0b Fix crash with clearBufferSubData (#1355) 2026-02-01 12:41:53 -08:00
Jason Mitchell 5fdf84edd0 Camera and Menu Tweaks (#1354) 2026-02-01 12:14:32 -08:00
Jason Mitchell b19d023c11 Bump gtnhgradle 2026-02-01 09:26:19 -08:00
Jason Mitchell 41eafbd151 GLSL Downgrading (#1348) 2026-01-31 13:23:02 -08:00
sisyphussy dd970b4c6a Fix nested display lists rendering twice (#1349)
* Fix nested display lists rendering twice

* cleanup
2026-01-31 05:45:48 -08:00
Eclipse-Sol f79ad7f22a Fix arrows inheriting item material IDs (#1347) 2026-01-30 18:35:04 -08:00
Jason Mitchell 6947ffa3e2 Add IS_IRIS define as an option. 2026-01-30 18:10:27 -08:00
Jason Mitchell 969d2c3710 Backports tessellation shader support, safe zone shadow culling, and shader pack rendering directives. 2026-01-30 18:10:27 -08:00
Jason Mitchell c5988d29c3 Fix camera position and nether portal 3rd party rendering 2026-01-30 18:10:27 -08:00
Jason Mitchell dc68c2c265 Fix end portal w/ Shaders 2026-01-30 18:10:27 -08:00
Jason Mitchell 51533a81ec Misc Shaderpack loading fixes (#1343) 2026-01-30 14:53:41 -08:00
Eclipse-Sol 90eabb5d40 Add hardcoded entities and player_cape (#1327) 2026-01-30 14:53:26 -08:00
sisyphussyandJason Mitchell 74843cb1f9 Glc redirects (#1340)
Co-authored-by: Jason Mitchell <[email protected]>
2026-01-30 14:50:54 -08:00
Death Fuel 5e0344a529 remove unnecessary resource refresh (#1342) 2026-01-30 14:40:51 -08:00
Jason Mitchell 3cdd934987 First pass at setup/begin pass support (#1335) 2026-01-29 07:53:04 -08:00
Léa Gris 9d90ff137c fix(render): adapt hodgepodge fixBottomFaceUV (#1334) 2026-01-28 10:55:53 -08:00
Jason Mitchell bee9541797 Shadow Compute Shaders (#1333) 2026-01-28 00:03:04 -08:00
Jason Mitchell b75a5d8f7d Ya that won't work (#1332) 2026-01-27 15:32:42 -08:00
Jason Mitchell 8d3ab41c53 Use entity position instead of camera pos (#1330) 2026-01-26 22:19:54 -08:00
Jason Mitchell 48d032e654 Tweaks (#1329) 2026-01-26 21:08:09 -08:00
sisyphussy 1968914582 Fix hud flickering (#1325) 2026-01-26 10:19:49 -08:00
Guus Waals a70bd76ff3 Fix deadlock in CTMUtils (#1189) 2026-01-26 10:08:32 -08:00
mist475 db919b5f37 add biomeDictionary and lotr compat to BiomeUniforms (#1324) 2026-01-26 09:58:08 -08:00
MalTeeez cde47ea423 Add option to disable f3 additions (#1308) 2026-01-26 09:56:11 -08:00
Jason Mitchell 5ef6cb11c0 Don't double check infinite bounds (#1321) 2026-01-25 21:13:14 -08:00
Eclipse-Sol b7015bf10e Adds "name_tag" feature (#1318) 2026-01-25 20:00:49 -08:00
Jason Mitchell 46602ab921 Chunk Thread Saftey (#1320) 2026-01-25 19:58:33 -08:00
Jason Mitchell 63e9fa0df1 Dynamic Lights Improvements (#1319) 2026-01-25 19:07:11 -08:00
Eclipse-Sol dcea970a77 Various Shader Fixes (#1315) 2026-01-25 16:56:54 -08:00
Jason Mitchell b29240d6da Use the proper blockAccess on the main thread (#1317) 2026-01-25 16:55:45 -08:00
Jason Mitchell 9d5a02ed21 Optimize TileEntities (#1314) 2026-01-25 10:54:45 -08:00
Jason Mitchell b454483aae Add a nvidia workarounds from celeritas (#1286) 2026-01-24 18:52:52 -08:00
Jason Mitchell 72b13543c6 AABB Caching (#1309) 2026-01-24 18:52:22 -08:00
Jason Mitchell 36d98fcb22 Fix currentRenderedItemId for ItemBlocks (#1307) 2026-01-24 12:43:03 -08:00
Jason Mitchell 44c5b9617a Lighting fixes (#1306) 2026-01-24 12:23:59 -08:00
Kotmatross f3f1677db8 [Shaders] Fix NTM:Space sunset not rendering {2.0 regression} (#1275) 2026-01-24 19:47:30 +00:00
Jason Mitchell d396b611ad Buffer fixes (#1304) 2026-01-24 11:30:05 -08:00
Jason Mitchell 08f4c0f9db Make feature flag defines available in shader.properties preprocessing (#1303) 2026-01-24 10:10:13 -08:00
Eclipse-Sol 50b0d22dc2 Fix entity material handling. (#1298) 2026-01-23 20:24:27 -08:00
Jason Mitchell 7fed54264e No more OpenGLHelper (#1297) 2026-01-23 19:48:52 -08:00
embeddedt be87401be6 Improve behavior of Celeritas-based lighting pipeline 2026-01-23 19:37:57 -08:00
Jason Mitchell 94254006df Properly cleanup (#1294) 2026-01-23 18:19:46 -08:00
Jason Mitchell f79774df65 Respect shader render layer overrides (#1293) 2026-01-23 16:43:01 -08:00
Eclipse-Sol 2f2fc22df3 Add support for dimension.properties (#1283) 2026-01-22 19:17:16 -08:00
Jason Mitchell 26300bbb1b Celeritas Smooth Lighting is now default and working. UseSeparateAO, Emissives, and oldLighting=false now work. 2026-01-22 16:32:15 -08:00
Jason Mitchell 88e4d2fd6c Use Separate AO & SmoothLightPipeline 2026-01-22 16:32:15 -08:00
Jason Mitchell bb52476d27 Custom images, textures, SSBO, and ShaderPack/ShaderProperties backports 2026-01-22 16:32:15 -08:00
Jason Mitchell 6d60477b93 Actually allocate the (minimal) display lists so we stop clobbering the hand renderer on shader reload (#1278) 2026-01-19 13:05:27 -08:00
Jason MitchellandEclipse-Sol 362724610c Add Various Features (#1209) (#1277)
Co-authored-by: Eclipse-Sol <[email protected]>
2026-01-19 13:03:56 -08:00
Jason Mitchell ea4a3cdf0b Fix a race condition (#1273) 2026-01-16 16:46:36 -08:00
Jason Mitchell 65959268d0 Support glCallLists (#1265) 2026-01-13 10:41:09 -08:00
Jason Mitchell 58d820cd7e Fix OSX F3 crash
Fixes #1256
2026-01-13 09:37:28 -08:00
Death Fuel 685d68bd9c Improve glyph replacement logic (#1247) 2026-01-12 15:17:20 -08:00
Jason MitchellandCaedis ad63d2d62c Dynamic light improvements (#1255)
Co-authored-by: Caedis <[email protected]>
2026-01-10 23:50:32 -08:00
Jason Mitchell d2730ccca8 Better video settings search (#1254) 2026-01-10 21:25:03 -08:00
Jason Mitchell e9257b8739 Fixes (#1251) 2026-01-10 15:20:19 -08:00
Jason Mitchell 3984225faa Better OSX J8 Support (#1248) 2026-01-09 12:58:42 -08:00
Jason Mitchell 52db6b56d6 Fix GLSL 120 support (#1243) 2026-01-08 21:34:40 -08:00
Jason Mitchell 34bfe513f1 Maybe less deadlock-y (#1241) 2026-01-08 20:53:32 -08:00
Jason Mitchell 42d7ed58aa 2.0.0 Alpha1 Fixes (#1240) 2026-01-08 19:26:56 -08:00
Jason Mitchell 9a4f0f9b99 Adapt some Beddium features & add FPS Cap info 2026-01-07 13:22:16 -08:00
Jason Mitchell be90a01725 Angelica 2.0
* GLStateManagerService & RenderSystemService
* Wire up Celeritas
* Iris working
* Dynamic lights working
* Goodbye Sodium 0.2
* Add Multi-Threading for check meshing again
2026-01-07 13:22:16 -08:00
Jason Mitchell e5e8250d44 JVMDG 2026-01-07 13:22:16 -08:00
Wilhelm Schuster 062a03ffc2 Add more menu backgrounds (#1225) 2026-01-07 12:46:33 -08:00
Jason Mitchell 9f5afaaec3 Better Splash support (#1220) 2026-01-05 10:24:12 -08:00
Death Fuel b05f17a477 Disable custom fonts with GraphicsEnvironment.isHeadless() (#1218)
* disable custom fonts with GraphicsEnvironment.isHeadless()
2026-01-04 10:19:17 -08:00
Death Fuel 57caf08212 remove a horizontal shift (#1216) 2026-01-03 13:34:23 -08:00
Jason Mitchell 085ec79c21 Set defaults once per TE pass instead of once per TE (#1213) 2026-01-03 12:46:40 -08:00
Wilhelm Schuster 38641268ae Random menu backgrounds (#1217) 2026-01-03 12:01:48 -08:00
Jason Mitchell fe8e723638 Update 000-report-bug.yml 2025-12-31 22:35:40 -08:00
Jason Mitchell 16debfd518 Move EntityID shader mixin to shaders, and optimize (#1208) 2025-12-29 18:23:48 -08:00
Jason Mitchell 8cfc3e1f4a Why were these bypassing GLSM? (#1207) 2025-12-28 22:42:39 -05:00
Eclipse-Sol 2c808fae43 Update entity.properties formatting (#1197)
* Update entity.properties formatting

1.7.10 doesn't have namespaces like modern does, this code updates this so that Angelica can handle names such as XPOrb or Creeper.

* Allows shaders to target Lightning Bolts

Lightning bolts within 1.7.10 are not registered, this allows shader devs to target the lightning bolt like it does in modern.

* Additional fixes

* Adds back getEntityId as a fallback
2025-12-27 09:04:37 -08:00
Eclipse-Sol 1649c3c0c6 Adds entity_flame ID to Angelic (#1202) 2025-12-26 13:05:08 -08:00
Jason Mitchell b84286ba3b Nvidia test fix (#1201)
confirmed working in #meta-dev (nvidia/windows 11)
2025-12-25 13:36:19 -08:00
Jason Mitchell ee6c79802a Display List Overhaul (#1200) 2025-12-24 20:30:48 -08:00
Jason Mitchell d3366ad31a Update Buildscript (#1199) 2025-12-23 19:56:48 -08:00
Jason Mitchell 92b6dcc010 Texture cache fixes (#1198) 2025-12-23 17:38:52 -08:00
Jason Mitchell 89132f3ef9 Parallel shader transformation and use Transformer instead of Utils (#1191) 2025-12-23 09:11:32 -08:00
Eclipse-Sol f0d45b0d62 Fix metadata parsing by removing space in split (#1196) 2025-12-23 01:53:31 +00:00
Jason Mitchell 173d986a5b Add a test for the server side texture cache fix (#1194) 2025-12-21 12:14:53 -08:00
mist475 473a690054 fix #1190: remove remap = false from GuiIngameForge (#1192) 2025-12-21 10:34:01 -08:00
sisyphussy 2515b3520f Always delete texture parameter cache (#1193) 2025-12-21 10:33:44 -08:00
glowredman a32f9ca244 Only catch Exceptions not Errors (#1186) 2025-12-21 14:14:50 +01:00
Jason Mitchell 941fc88484 Shader boot fix + more DSA (#1184) 2025-12-16 16:54:50 -08:00
Creeper-banner 4106dd3865 Fix broken text rendering after certain characters (#1178)
* Font render fix

* re-fix

* Update fix for consistency
2025-12-14 07:10:12 -08:00
Jason Mitchell 61f6aa19a8 glDrawBuffers Support 2025-12-09 18:46:47 -08:00
Jason Mitchell 77875f7f91 Stop recording normals... we're already baking them into a VBO 2025-12-08 15:28:07 -08:00
Jason Mitchell 241c32def1 Add some transformer exclusions 2025-12-08 14:57:27 -08:00
sisyphussy a8107f97e8 Add VAO's (#1126) 2025-12-07 16:51:32 -08:00
Death FuelandJason Mitchell 8bec433699 GT5 custom glyph handling and visual fixes (#1148)
Co-authored-by: Jason Mitchell <[email protected]>
2025-12-06 09:48:03 -08:00
Kotmatross 2d39fb2397 [BCF] Fix z-fighting on GT ores 2: here we go again edition (#1161) 2025-12-06 08:17:26 -08:00
656 changed files with 22193 additions and 23183 deletions

No files matched your search

@@ -39,6 +39,7 @@ body:
- Java 19
- Java 20
- Java 21
- Java 25
- Other (Please Specify)
validations:
required: true
+1
View File
@@ -36,3 +36,4 @@ addon.local.gradle
addon.local.gradle.kts
addon.late.local.gradle
addon.late.local.gradle.kts
local/
+6 -4
View File
@@ -9,13 +9,13 @@
## **Beta Quality - Here there be Dragons**
* Shaders - Beta
* Complementary & BSL mostly function, but have some bugs
* Sildurs, Seus, and any other shader probably doesn't work
* Complementary + Euphoria Patches is the primary compatibility target
* Sildurs, Seus, and any other shaders might work
# Required Dependencies
* [UniMixins](https://github.com/LegacyModdingMC/UniMixins/releases) >= 0.1.23
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.8.21
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.9.0
* NOTE: Some mods are not required, but a specific version is required if present - see: `Permanent Incompatibilities` below.
# Known (temporary) Incompatibilities
@@ -38,7 +38,7 @@
* [Amazing Trophies 1.2.1 and below](https://github.com/GTNewHorizons/Amazing-Trophies/releases) - Use 1.2.2+
* [LWJGL3ify 1.5.4 and below](https://github.com/GTNewHorizons/lwjgl3ify/releases/) - Use the latest version available, 1.5.7+
* [ArchaicFix 0.6.2 and below](https://www.curseforge.com/minecraft/mc-mods/archaicfix/files/all?page=1&pageSize=20) - Use 0.7.0 or above
* [Hodgepodge 2.4.3 and below](https://github.com/GTNewHorizons/Hodgepodge/releases) - Use 0.4.5 or above
* [Hodgepodge 2.4.3 and below](https://github.com/GTNewHorizons/Hodgepodge/releases) - Use 2.4.5 or above
* CodeChicken[Core](https://github.com/GTNewHorizons/CodeChickenCore/releases)/[Lib](https://github.com/GTNewHorizons/CodeChickenLib/releases) <1.2.0 - Threading issues, use 1.3.0+
* Neodymium - Untested, but unlikely to be compatible. (Chunk Meshing is definitely incompatible, other features might work depending on config)
* SmoothFont - Equivalent functionality added
@@ -83,3 +83,5 @@
* Code from both glsl-transformation-lib and Monocle taken under their respective LGPL 3.0 licenses
* FalseTweaks
* FalsePattern for [FalseTweaks](https://github.com/falsepattern/falsetweaks) - Item Rendering Optimizations taken from FalseTweaks under the LGPL 3.0 license
* Beddium
* Venn and Falsepattern for [Beddium](https://github.com/vfx-dev/Beddium) - MinimapRenderer, SafeChunkTracker, and some debug commands adapted under the LGPL 3.0 License
+14 -7
View File
@@ -5,11 +5,8 @@ plugins {
minecraft {
extraRunJvmArguments.add("-Dangelica.enableTestBlocks=true")
extraRunJvmArguments.add("-Dangelica.dumpClass=true")
/* extraRunJvmArguments.addAll(
"-Dlegacy.debugClassLoading=true",
"-Dlegacy.debugClassLoadingFiner=true",
"-Dlegacy.debugClassLoadingSave=true")*/
// extraRunJvmArguments.addAll("-Dlegacy.debugClassLoadingSave=true")
// extraRunJvmArguments.addAll("-Drfb.dumpLoadedClasses=true", "-Drfb.dumpLoadedClassesPerTransformer=true")
//extraRunJvmArguments.add("-Dangelica.redirectorLogspam=true")
}
@@ -32,9 +29,10 @@ tasks.test {
}
tasks.processResources {
inputs.property("version", project.version.toString())
val projectVersion = project.version.toString()
inputs.property("version", projectVersion)
filesMatching("META-INF/rfb-plugin/*") {
expand("version" to project.version.toString())
expand("version" to projectVersion)
}
}
@@ -44,3 +42,12 @@ tasks.register<Copy>("copyDependencies") {
from(configurations.default)
into("testDependencies")
}
val embedOnly: Configuration by configurations
tasks.shadowJar {
from(embedOnly.map(::zipTree))
relocate("com.mitchej123", "com.mitchej123")
relocate("org.embeddedt", "org.embeddedt")
}
+40 -16
View File
@@ -46,26 +46,44 @@ configurations {
// Can be enabled for testing if desired
// runtimeClasspath.extendsFrom(transformedMod)
// testRuntimeClasspath.extendsFrom(transformedMod)
// Embed in JAR without relocation (compile only, shadowed into JAR)
embedOnly
embedOnly.canBeConsumed = false
embedOnly.canBeResolved = true
compileClasspath.extendsFrom(embedOnly)
testCompileClasspath.extendsFrom(embedOnly)
}
// Exclude self-reference from all configurations - prevents transitive Angelica deps from resolving against this project
configurations.all {
exclude group: "com.github.GTNewHorizons", module: "Angelica"
}
dependencies {
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.14")
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.14:dev")
compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.0.7") { transitive = false }
compileOnly("org.projectlombok:lombok:1.18.34") { transitive = false }
annotationProcessor("org.projectlombok:lombok:1.18.34")
compileOnly("org.projectlombok:lombok:1.18.42") { transitive = false }
annotationProcessor("org.projectlombok:lombok:1.18.42")
// Iris Shaders
compileOnly('org.jetbrains:annotations:26.0.2')
api("com.github.GTNewHorizons:GTNHLib:0.8.21:dev")
api("com.github.GTNewHorizons:GTNHLib:0.9.10:dev")
shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-4.g6b42bca") {
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-26.g5ee7d96-GTNH") {
exclude module: "antlr4" // we only want to shadow the runtime module
}
shadowImplementation("org.antlr:antlr4-runtime:4.13.2")
compileOnly "org.apache.ant:ant:1.8.2"
// Celeritas (transitive=false: deps provided by GTNHLib/runtime)
embedOnly("org.embeddedt.celeritas:celeritas-common:2.5.2-GTNH") { transitive = false }
embedOnly("org.embeddedt.celeritas:celeritas-lwjgl2-service:2.5.2-GTNH") { transitive = false }
// Because who doesn't want NEI
devOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.8.35-GTNH:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:CodeChickenCore:1.4.7:dev')
@@ -90,16 +108,16 @@ dependencies {
compileOnly("curse.maven:minefactory-reloaded-66672:2277486")
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev") // Mixin Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds-Legacy:1.4.7:dev") // ASM Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev")
compileOnly(rfg.deobf("curse.maven:ntm-space-1121235:6974420"))
compileOnly(rfg.deobf("maven.modrinth:ntmspace:X5593_H261"))
compileOnly(rfg.deobf("curse.maven:campfirebackport-387444:4611675"))
compileOnly(rfg.deobf("curse.maven:xaeros-minimap-263420:5060684"))
compileOnly(rfg.deobf("curse.maven:security-craft-64760:2818228"))
compileOnly(rfg.deobf("curse.maven:et-futurum-requiem-441392:5873837"))
runtimeOnlyNonPublishable(rfg.deobf("CoreTweaks:CoreTweaks:0.3.3.2"))
// runtimeOnlyNonPublishable("com.github.GTNewHorizons:CoreTweaks:0.3.3.6-GTNH")
// For testing alternative splash screens, can be sourced from https://github.com/MalTeeez/ModernSplash/releases
//runtimeOnly(rfg.deobf(files("dependencies/modernsplash-1.7.10-1.2.2-dev.jar")))
@@ -107,14 +125,20 @@ dependencies {
transformedMod("net.industrial-craft:industrialcraft-2:2.2.828-experimental:dev")
// Better Crashes
compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.0-GTNH:dev")
compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.1-GTNH:dev")
// Tests
testImplementation(platform('org.junit:junit-bom:5.11.4'))
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation("org.mockito:mockito-core:3.+")
testImplementation("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209")
testAnnotationProcessor("com.github.bsideup.jabel:jabel-javac-plugin:1.0.1")
afterEvaluate {
dependencies {
testImplementation(platform('org.junit:junit-bom:5.14.1'))
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation("org.mockito:mockito-core:3.+")
testImplementation("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209")
testImplementation('org.junit.platform:junit-platform-engine')
testImplementation('org.junit.platform:junit-platform-reporting')
testImplementation('org.junit.platform:junit-platform-launcher')
}
}
compileOnly("mega:fluidlogged-mc1.7.10:0.1.2")
}
+32 -13
View File
@@ -39,9 +39,33 @@ remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/co
# `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE.
developmentEnvironmentUserName = Developer
# Enables using modern Java syntax (up to version 17) via Jabel, while still targeting JVM 8.
# See https://github.com/bsideup/jabel for details on how this works.
enableModernJavaSyntax = true
# Enables modern Java syntax support. Valid values:
# - false: No modern syntax, Java 8 only
# - jabel: Jabel syntax-only support, compiles to J8 bytecode
# - jvmDowngrader: Full modern Java via JVM Downgrader (syntax + stdlib APIs)
# - modern: Native modern Java bytecode, no downgrading
enableModernJavaSyntax = jvmDowngrader
# If set, ignores the above setting and compiles with the given toolchain. This may cause unexpected issues,
# and should *not* be used in most situations. -1 disables this.
# forceToolchainVersion = -1
# Target JVM version for JVM Downgrader bytecode downgrading.
# Only used when enableModernJavaSyntax = jvmDowngrader
# downgradeTargetVersion = 8
# Comma-separated list of Java versions for multi-release jar support (JVM Downgrader only).
# Classes will be available in META-INF/versions/N/ for each version N in this list.
# Default: "21,25" (J25+ gets native classes, J21-24 gets partial downgrade, J8-20 gets full downgrade).
jvmDowngraderMultiReleaseVersions = 17, 21, 25
# Specifies how JVM Downgrader API stubs are provided. Options:
# - shade: Shade minimized stubs into the jar
# - gtnhlib: GTNHLib provides stubs at runtime (adds version constraint)
# - external: Another dependency provides stubs (no constraint, no warning)
# - (empty): Warning reminding you to configure stubs
# Note: 'shade' option requires you to verify license compliance, see: https://github.com/unimined/JvmDowngrader/blob/main/LICENSE.md
jvmDowngraderStubsProvider = gtnhlib
# Enables injecting missing generics into the decompiled source code for a better coding experience.
# Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types.
@@ -55,22 +79,13 @@ generateGradleTokenClass = com.gtnewhorizons.angelica.Tags
# Name of the token containing the project's current version to generate/replace.
gradleTokenVersion = VERSION
# [DEPRECATED] Mod ID replacement token.
gradleTokenModId =
# [DEPRECATED] Mod name replacement token.
gradleTokenModName =
# [DEPRECATED] Mod Group replacement token.
gradleTokenGroupName =
# [DEPRECATED]
# Multiple source files can be defined here by providing a comma-separated list: Class1.java,Class2.java,Class3.java
# public static final String VERSION = "GRADLETOKEN_VERSION";
# The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's
# version in @Mod([...], version = VERSION, [...]).
# Leave these properties empty to skip individual token replacements.
replaceGradleTokenInFile =
# replaceGradleTokenInFile =
# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise, you can
# leave this property empty.
@@ -209,3 +224,7 @@ disableSpotless = true
# This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
org.gradle.configuration-cache = true
org.gradle.jvmargs = -Xmx2g
org.gradle.parallel = true
+12
View File
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/e1118b4c7c2858d28154d086dbff010e/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/59a9771cad43219260d9aac9a8ec4d6a/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c5ee947fbfb70bc347d8d531e3a578c4/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/5ee463876563a46fff651cce1bc53a4c/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/832229f0f6f0be60ed817c5a5e5848eb/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/b96cb7670c095245220e7d01d5927b58/redirect
toolchainVersion=25
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+2 -5
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -114,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -172,7 +171,6 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -212,8 +210,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
Vendored
+1 -2
View File
@@ -70,11 +70,10 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
-17
View File
@@ -15,23 +15,6 @@ repositories {
includeGroup 'mega'
}
}
exclusiveContent {
forRepository {
ivy {
name = 'CoreTweaks releases'
url = 'https://github.com/makamys/CoreTweaks/releases/download/'
patternLayout {
artifact '[revision]/[module]-1.7.10-[revision]+nomixin(-[classifier])(.[ext])'
}
metadataSources {
artifact()
}
}
}
filter {
includeGroup('CoreTweaks')
}
}
maven {
name = 'taumc'
url = 'https://maven.taumc.org/releases'
+3 -3
View File
@@ -2,8 +2,8 @@ pluginManagement {
repositories {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "https://nexus.gtnewhorizons.com/repository/public/"
name = "GTNH Maven"
url = uri("https://nexus.gtnewhorizons.com/repository/public/")
mavenContent {
includeGroup("com.gtnewhorizons")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
@@ -16,5 +16,5 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.48'
id("com.gtnewhorizons.gtnhsettingsconvention") version("2.0.19")
}
@@ -9,10 +9,14 @@ import java.util.List;
import java.util.Set;
@LateMixin
@SuppressWarnings("unused")
public class AngelicaLateMixins implements ILateMixinLoader {
@Override
public String getMixinConfig() {
int v = Runtime.version().feature();
if (v >= 21) return "mixins.angelica.late.j21.json";
if (v >= 17) return "mixins.angelica.late.j17.json";
return "mixins.angelica.late.json";
}
@@ -1,9 +1,8 @@
package com.gtnewhorizons.angelica;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.config.ConfigMigrator;
import com.gtnewhorizons.angelica.proxy.CommonProxy;
import com.gtnewhorizons.angelica.utils.AnimationMode;
import com.gtnewhorizons.angelica.utils.ManagedEnum;
@@ -12,6 +11,11 @@ import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
@Mod(
modid = MOD_ID,
@@ -29,6 +33,16 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent;
guiFactory = "com.gtnewhorizons.angelica.config.AngelicaGuiConfigFactory")
public class AngelicaMod {
public static final String MOD_ID = "angelica";
public static final Logger LOGGER = LogManager.getLogger("Angelica");
private static SodiumGameOptions CONFIG;
public static SodiumGameOptions options() {
if (CONFIG == null) {
CONFIG = SodiumGameOptions.load(ConfigMigrator.handleConfigMigration("angelica-options.json"));
}
return CONFIG;
}
@SidedProxy(clientSide = "com.gtnewhorizons.angelica.proxy.ClientProxy", serverSide = "com.gtnewhorizons.angelica.proxy.CommonProxy")
public static CommonProxy proxy;
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.api;
import com.gtnewhorizons.angelica.mixins.interfaces.IPatchedTextureAtlasSprite;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import com.gtnewhorizons.angelica.rendering.celeritas.SpriteExtension;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.IIcon;
@@ -20,8 +20,8 @@ public class TextureServices {
@SuppressWarnings("unused")
public static void updateTextureAnimation(IIcon icon) {
if(icon instanceof IPatchedTextureAtlasSprite patchedSprite) {
patchedSprite.markNeedsAnimationUpdate();
if (icon instanceof SpriteExtension ext) {
ext.celeritas$markActive();
}
}
}
@@ -1,10 +1,10 @@
package com.gtnewhorizons.angelica.client.font;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
import cpw.mods.fml.client.SplashProgress;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
@@ -75,11 +75,9 @@ public class BatchingFontRenderer {
}
}
public BatchingFontRenderer(FontRenderer underlying, int[] charWidth, byte[] glyphWidth,
int[] colorCode, ResourceLocation locationFontTexture) {
public BatchingFontRenderer(FontRenderer underlying, int[] charWidth, int[] colorCode, ResourceLocation locationFontTexture) {
this.underlying = underlying;
this.charWidth = charWidth;
this.glyphWidth = glyphWidth;
this.colorCode = colorCode;
this.locationFontTexture = locationFontTexture;
@@ -92,7 +90,6 @@ public class BatchingFontRenderer {
FontProviderMC.get(this.isSGA).charWidth = this.charWidth;
FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture;
FontProviderUnicode.get().glyphWidth = this.glyphWidth;
//noinspection deprecation
fontShaderId = FontAAShader.getProgram().getProgramId();
@@ -380,11 +377,11 @@ public class BatchingFontRenderer {
}
public float getGlyphScaleX() {
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect));
}
public float getGlyphScaleY() {
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect));
}
public float getGlyphSpacing() {
@@ -431,13 +428,13 @@ public class BatchingFontRenderer {
boolean curStrikethrough = false;
boolean curUnderline = false;
final float glyphScaleY = getGlyphScaleY();
final float heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY / 2);
final float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY;
float glyphScaleY = getGlyphScaleY();
float heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY / 2);
final float underlineY = heightNorth + (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY;
float underlineStartX = 0.0f;
float underlineEndX = 0.0f;
final float strikethroughY = heightNorth + ((float) (underlying.FONT_HEIGHT / 2) - 1.0f) * glyphScaleY;
float strikethroughStartX = 0.0f;
float strikethroughEndX = 0.0f;
@@ -507,12 +504,28 @@ public class BatchingFontRenderer {
continue;
}
if (FontConfig.enableCustomFont && FontConfig.enableGlyphReplacements) {
String chrReplacement = GlyphReplacements.customGlyphs.get(String.valueOf(chr));
if (chrReplacement != null) {
char replacement = chrReplacement.charAt(0);
boolean isReplacementCharAvailable =
FontProviderCustom.getPrimary().isGlyphAvailable(replacement)
|| FontProviderCustom.getFallback().isGlyphAvailable(replacement);
if (isReplacementCharAvailable) {
chr = replacement;
}
}
}
if (curRandom) {
chr = FontProviderMC.get(this.isSGA).getRandomReplacement(chr);
}
FontProvider fontProvider = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, unicodeFlag);
heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY * fontProvider.getYScaleMultiplier() / 2);
float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY * fontProvider.getYScaleMultiplier();
// Check ASCII space, NBSP, NNBSP
if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') {
curX += 4 * this.getWhitespaceScale();
@@ -17,4 +17,5 @@ public interface FontProvider {
float getVSize(char chr);
float getShadowOffset();
ResourceLocation getTexture(char chr);
float getYScaleMultiplier();
}
@@ -1,6 +1,5 @@
package com.gtnewhorizons.angelica.client.font;
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
import com.gtnewhorizons.angelica.config.FontConfig;
import lombok.Setter;
import lombok.Value;
@@ -40,19 +39,13 @@ public final class FontProviderCustom implements FontProvider {
private FontProviderCustom(byte id) {
this.id = id;
Font[] availableFonts = FontStrategist.getAvailableFonts();
if (availableFonts.length == 0) {
LOGGER.fatal("There seem to be no fonts available on this system! Disabling custom font and throwing an exception in an attempt to restore the session.");
FontConfig.enableCustomFont = false;
ConfigurationManager.save(FontConfig.class);
throw new RuntimeException();
}
String myFontName = switch (this.id) {
case 0 -> FontConfig.customFontNamePrimary;
case 1 -> FontConfig.customFontNameFallback;
default -> null;
};
if (Objects.equals(myFontName, "(none)")) {
font = null;
this.font = null;
return;
}
int fontPos = -1;
@@ -64,10 +57,10 @@ public final class FontProviderCustom implements FontProvider {
}
if (fontPos == -1) {
LOGGER.info("Could not find previously set font \"{}\". ", myFontName);
font = null;
this.font = null;
return;
}
font = availableFonts[fontPos].deriveFont(currentFontQuality);
this.font = availableFonts[fontPos].deriveFont(this.currentFontQuality);
}
private static class InstLoader {
static final FontProviderCustom instance0 = new FontProviderCustom((byte)0);
@@ -77,8 +70,8 @@ public final class FontProviderCustom implements FontProvider {
public static FontProviderCustom getFallback() { return InstLoader.instance1; }
public void reloadFont(int fontID) {
currentFontQuality = FontConfig.customFontQuality;
font = FontStrategist.getAvailableFonts()[fontID].deriveFont(currentFontQuality);
this.currentFontQuality = FontConfig.customFontQuality;
this.font = FontStrategist.getAvailableFonts()[fontID].deriveFont(this.currentFontQuality);
File[] files = new File(getFontDir()).listFiles();
if (files != null) {
@@ -100,7 +93,7 @@ public final class FontProviderCustom implements FontProvider {
}
}
fontAtlases = new FontAtlas[ATLAS_COUNT];
this.fontAtlases = new FontAtlas[ATLAS_COUNT];
}
private String getFontDir() {
@@ -140,50 +133,44 @@ public final class FontProviderCustom implements FontProvider {
}
void construct(Font font) {
float separator = currentFontQuality / 3f;
int atlasChars = 0;
for (int i = 0; i < ATLAS_SIZE; i++) {
final char ch = (char) (i + ATLAS_SIZE * this.id);
if (font.canDisplay(ch)) { atlasChars++; }
}
if (atlasChars == 0) { return; }
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
g2d.dispose();
int width = 0;
int actualChars = 0;
for (int i = 0; i < ATLAS_SIZE; i++) {
final char ch = (char)(i + ATLAS_SIZE * this.id);
if (font.canDisplay(ch)) {
width += (int) (separator + fm.charWidth(ch));
actualChars++;
}
}
if (actualChars == 0) {
return;
}
final int atlasTilesX = (int) Math.ceil(Math.sqrt(actualChars) * 1.5f);
final int atlasTilesY = (int) Math.ceil((double) actualChars / atlasTilesX);
LOGGER.info("constructing custom font atlas (ID {}) of nominal size {} chars, actual: {}, {} rows by {} columns",
this.id, ATLAS_SIZE, actualChars, atlasTilesX, atlasTilesY);
width = 0;
actualChars = 0;
final int atlasTilesX = (int) Math.ceil(Math.sqrt(atlasChars) * 1.5f);
final int atlasTilesY = (int) Math.ceil((double) atlasChars / atlasTilesX);
final float charSeparator = currentFontQuality / 3f;
int rowWidth = 0;
int maxRowWidth = 0;
atlasChars = 0;
for (int i = 0; i < ATLAS_SIZE; i++) {
if (actualChars % atlasTilesX == 0) {
maxRowWidth = Math.max(maxRowWidth, width);
width = 0;
if (atlasChars % atlasTilesX == 0) {
maxRowWidth = Math.max(maxRowWidth, rowWidth);
rowWidth = 0;
}
final char ch = (char)(i + ATLAS_SIZE * this.id);
if (font.canDisplay(ch)) {
width += (int) (separator + fm.charWidth(ch));
actualChars++;
rowWidth += (int) (charSeparator + fm.charWidth(ch));
atlasChars++;
}
}
maxRowWidth = Math.max(maxRowWidth, width);
maxRowWidth = Math.max(maxRowWidth, rowWidth);
final int lineHeight = fm.getHeight();
final float desc = fm.getDescent();
final int imageWidth = (int) (maxRowWidth + separator);
final int imageHeight = (int) ((separator + lineHeight) * atlasTilesY + separator);
final int imageWidth = (int) (maxRowWidth + charSeparator);
final int imageHeight = (int) ((charSeparator + lineHeight) * atlasTilesY + charSeparator);
image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
g2d = image.createGraphics();
@@ -198,35 +185,34 @@ public final class FontProviderCustom implements FontProvider {
fm = g2d.getFontMetrics();
int tileX = 0, tileY = 0; // position in atlas tiles
int imgX = (int) separator; // position in pixels
int imgX = (int) charSeparator; // position in pixels
for (int i = 0; i < ATLAS_SIZE; i++) {
final char ch = (char)(i + ATLAS_SIZE * this.id);
final char ch = (char) (i + ATLAS_SIZE * this.id);
if (!font.canDisplay(ch)) { continue; }
if (tileX >= atlasTilesX) {
tileX = 0;
imgX = (int) separator;
imgX = (int) charSeparator;
tileY++;
}
final int charWidth = fm.charWidth(ch);
final float charAspectRatio = (float) charWidth / lineHeight;
final float inset = currentFontQuality / 16;
g2d.drawString(Character.toString(ch), imgX, (lineHeight + separator) * (tileY + 1) - desc);
g2d.drawString(Character.toString(ch), imgX, (lineHeight + charSeparator) * (tileY + 1) - desc);
final float uStart = (float) (imgX - inset * charAspectRatio) / imageWidth;
final float vStart = ((lineHeight + separator) * (tileY + 1) - lineHeight - inset) / imageHeight;
final float vStart = ((lineHeight + charSeparator) * (tileY + 1) - lineHeight - inset) / imageHeight;
final float xAdvance = charAspectRatio * 8 * charWidth / (charWidth + 2 * inset * charAspectRatio);
final float glyphW = charAspectRatio * 8 + 1;
final float uSz = (float) (charWidth + 2 * inset * charAspectRatio) / imageWidth;
final float vSz = (float) (lineHeight + 2 * inset) / imageHeight;
glyphData[i] = new GlyphData(uStart, vStart, xAdvance, glyphW, uSz, vSz);
imgX += (int) (charWidth + separator);
this.glyphData[i] = new GlyphData(uStart, vStart, xAdvance, glyphW, uSz, vSz);
imgX += (int) (charWidth + charSeparator);
tileX++;
}
g2d.dispose();
try {
LOGGER.info("writing custom font atlas texture ({}x{} px) to {}", imageWidth, imageHeight, getAtlasFullPath(this.id));
Files.createDirectories(Paths.get(getFontDir()));
ImageIO.write(image, "png", new File(getAtlasFullPath(this.id)));
} catch (IOException e) {
@@ -238,18 +224,18 @@ public final class FontProviderCustom implements FontProvider {
private FontAtlas getAtlas(char chr) {
int id = chr / ATLAS_SIZE;
FontAtlas fa = fontAtlases[id];
FontAtlas fa = this.fontAtlases[id];
if (fa == null) {
fa = new FontAtlas(id);
fa.construct(font);
fa.construct(this.font);
this.fontAtlases[id] = fa;
}
fontAtlases[id] = fa;
return fa;
}
@Override
public boolean isGlyphAvailable(char chr) {
if (font == null) { return false; }
if (this.font == null) { return false; }
return (getAtlas(chr).glyphData[chr % ATLAS_SIZE] != null);
}
@@ -270,12 +256,12 @@ public final class FontProviderCustom implements FontProvider {
@Override
public float getXAdvance(char chr) {
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].xAdvance;
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].xAdvance * FontConfig.customFontScale;
}
@Override
public float getGlyphW(char chr) {
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].glyphW;
return getAtlas(chr).glyphData[chr % ATLAS_SIZE].glyphW * FontConfig.customFontScale;
}
@Override
@@ -297,4 +283,9 @@ public final class FontProviderCustom implements FontProvider {
public ResourceLocation getTexture(char chr) {
return getAtlas(chr).texture;
}
@Override
public float getYScaleMultiplier() {
return FontConfig.customFontScale;
}
}
@@ -103,4 +103,9 @@ public final class FontProviderMC implements FontProvider {
public ResourceLocation getTexture(char chr) {
return locationFontTexture;
}
@Override
public float getYScaleMultiplier() {
return 1;
}
}
@@ -1,16 +1,31 @@
package com.gtnewhorizons.angelica.client.font;
import com.gtnewhorizons.angelica.config.FontConfig;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import java.io.IOException;
import java.io.InputStream;
public final class FontProviderUnicode implements FontProvider {
private FontProviderUnicode() {}
private FontProviderUnicode() {
try {
InputStream inputstream = Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation("font/glyph_sizes.bin")).getInputStream();
//noinspection ResultOfMethodCallIgnored
inputstream.read(this.glyphWidth);
}
catch (IOException ioexception) {
throw new RuntimeException(ioexception);
}
}
private static class InstLoader { static final FontProviderUnicode instance = new FontProviderUnicode(); }
public static FontProviderUnicode get() { return FontProviderUnicode.InstLoader.instance; }
private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256];
public byte[] glyphWidth;
private final byte[] glyphWidth = new byte[65536];
private ResourceLocation getUnicodePageLocation(int page) {
final ResourceLocation lookup = unicodePageLocations[page];
@@ -37,7 +52,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getUStart(char chr) {
final float startColumnF = (float)(this.glyphWidth[chr] >>> 4);
final float startColumnF = (float)((this.glyphWidth[chr] >>> 4) & 15);
return ((float) (chr % 16 * 16) + startColumnF + 0.21f) / 256.0f;
}
@@ -48,7 +63,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getXAdvance(char chr) {
final int startColumn = this.glyphWidth[chr] >>> 4;
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
@@ -57,7 +72,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getGlyphW(char chr) {
final int startColumn = this.glyphWidth[chr] >>> 4;
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
@@ -67,7 +82,7 @@ public final class FontProviderUnicode implements FontProvider {
@Override
public float getUSize(char chr) {
final int startColumn = this.glyphWidth[chr] >>> 4;
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
@@ -90,4 +105,9 @@ public final class FontProviderUnicode implements FontProvider {
final int uniPage = chr / 256;
return getUnicodePageLocation(uniPage);
}
@Override
public float getYScaleMultiplier() {
return 1;
}
}
@@ -25,37 +25,42 @@ public class FontStrategist {
@Getter
private static final Font[] availableFonts;
public static final Logger LOGGER = LogManager.getLogger("Angelica");
public static boolean customFontInUse;
static {
// get available fonts without duplicates (250 copies of dialog.plain need not apply)
Font[] availableFontsDirty = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
HashMap<String, Font> fontSet = new HashMap<>();
HashMultiset<String> duplicates = HashMultiset.create(); // for debugging
if (GraphicsEnvironment.isHeadless()) {
LOGGER.warn("GraphicsEnvironment.isHeadless() returned true! Custom fonts will be unavailable. This is likely a MacOS issue.");
availableFonts = new Font[0];
} else {
// get available fonts without duplicates (250 copies of dialog.plain need not apply)
Font[] availableFontsDirty = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
HashMap<String, Font> fontSet = new HashMap<>();
HashMultiset<String> duplicates = HashMultiset.create(); // for debugging
for (Font font : availableFontsDirty) {
String fontName = font.getFontName();
if (fontSet.containsKey(fontName)) {
duplicates.add(fontName);
} else {
fontSet.put(fontName, font);
}
}
if (!duplicates.isEmpty()) {
StringBuilder sb = new StringBuilder(duplicates.size() + " duplicate font(s) found in the list reported by Java: ");
for (Iterator<String> iter = duplicates.stream().distinct().iterator(); iter.hasNext(); ) {
String dupe = iter.next();
sb.append(duplicates.count(dupe)).append("x ").append(dupe);
if (iter.hasNext()) {
sb.append(", ");
for (Font font : availableFontsDirty) {
String fontName = font.getFontName();
if (fontSet.containsKey(fontName)) {
duplicates.add(fontName);
} else {
fontSet.put(fontName, font);
}
}
sb.append(". Some fonts may be missing from the font selection menu.");
LOGGER.warn(sb.toString());
}
availableFonts = fontSet.values().stream().sorted(Comparator.comparing(Font::getFontName)).toArray(Font[]::new);
if (!duplicates.isEmpty()) {
StringBuilder sb = new StringBuilder(duplicates.size() + " duplicate font(s) found in the list reported by Java: ");
for (Iterator<String> iter = duplicates.stream().distinct().iterator(); iter.hasNext(); ) {
String dupe = iter.next();
sb.append(duplicates.count(dupe)).append("x ").append(dupe);
if (iter.hasNext()) {
sb.append(", ");
}
}
sb.append(". Some fonts may be missing from the font selection menu.");
LOGGER.warn(sb.toString());
}
availableFonts = fontSet.values().stream().sorted(Comparator.comparing(Font::getFontName)).toArray(Font[]::new);
LOGGER.info("Got {} fonts from GraphicsEnvironment ({} after deduplication)", availableFontsDirty.length, availableFonts.length);
}
// create and add the resource pack that provides fonts
HashMap<String, File> packMap = new HashMap<>();
@@ -67,22 +72,6 @@ public class FontStrategist {
DefaultResourcePack fontResourcePack = new DefaultResourcePack(packMap);
List defaultResourcePacks = ((ResourceAccessor) Minecraft.getMinecraft()).angelica$getDefaultResourcePacks();
defaultResourcePacks.add(fontResourcePack);
Minecraft.getMinecraft().refreshResources();
// determine if a custom font is in use based on config values
boolean primaryFontFound = false;
boolean fallbackFontFound = false;
for (Font availableFont : availableFonts) {
if (Objects.equals(FontConfig.customFontNamePrimary, availableFont.getFontName())) {
primaryFontFound = true;
break;
}
if (Objects.equals(FontConfig.customFontNameFallback, availableFont.getFontName())) {
fallbackFontFound = true;
break;
}
}
customFontInUse = (FontConfig.enableCustomFont && (primaryFontFound || fallbackFontFound));
}
/**
@@ -112,20 +101,14 @@ public class FontStrategist {
public static void reloadCustomFontProviders() {
FontProviderCustom.getPrimary().setFont(null);
FontProviderCustom.getFallback().setFont(null);
boolean primaryFontFound = false;
boolean fallbackFontFound = false;
for (int i = 0; i < availableFonts.length; i++) {
if (Objects.equals(FontConfig.customFontNamePrimary, availableFonts[i].getFontName())) {
FontProviderCustom.getPrimary().reloadFont(i);
primaryFontFound = true;
}
if (Objects.equals(FontConfig.customFontNameFallback, availableFonts[i].getFontName())) {
FontProviderCustom.getFallback().reloadFont(i);
fallbackFontFound = true;
}
if (primaryFontFound && fallbackFontFound) { break; }
}
customFontInUse = (FontConfig.enableCustomFont && (primaryFontFound || fallbackFontFound));
}
public static boolean isSplashFontRendererActive(FontRenderer fontRenderer) {
@@ -0,0 +1,105 @@
package com.gtnewhorizons.angelica.client.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfigStorage;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityTypeEntry;
import jss.notfine.core.Settings;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionGroup;
import me.jellysquid.mods.sodium.client.gui.options.OptionImpl;
import me.jellysquid.mods.sodium.client.gui.options.OptionImpact;
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.gui.options.control.TickBoxControl;
import net.minecraft.client.resources.I18n;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class DynamicLightsOptionPages {
public static OptionPage dynamicLights() {
if (!DynamicLights.configEnabled) {
return null;
}
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS.option)
.add(Settings.DYNAMIC_LIGHTS_SHADER_FORCE.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS_FRUSTUM_CULLING.option)
.add(Settings.DYNAMIC_LIGHTS_ADAPTIVE_TICKING.option)
.add(Settings.DYNAMIC_LIGHTS_CULL_TIMEOUT.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS_SLOW_DIST.option)
.add(Settings.DYNAMIC_LIGHTS_SLOWER_DIST.option)
.add(Settings.DYNAMIC_LIGHTS_BACKGROUND_DIST.option)
.build());
// Entity type toggles - grouped by mod ID
List<EntityTypeEntry> allEntities = EntityLightConfig.getAllEntityTypes();
Map<String, List<EntityTypeEntry>> byMod = new LinkedHashMap<>();
for (EntityTypeEntry entry : allEntities) {
byMod.computeIfAbsent(entry.getModId(), _ -> new ArrayList<>()).add(entry);
}
// Create a group for each mod's entities
for (Map.Entry<String, List<EntityTypeEntry>> modEntry : byMod.entrySet()) {
String modId = modEntry.getKey();
List<EntityTypeEntry> entities = modEntry.getValue();
OptionGroup.Builder groupBuilder = OptionGroup.createBuilder();
for (EntityTypeEntry entity : entities) {
Option<Boolean> option = createEntityOption(entity);
if (option != null) {
groupBuilder.add(option);
}
}
// Only add group if it has options
OptionGroup group = groupBuilder.build();
if (!group.getOptions().isEmpty()) {
groups.add(group);
}
}
return new OptionPage(I18n.format("options.dynamiclights.page"), ImmutableList.copyOf(groups));
}
private static Option<Boolean> createEntityOption(EntityTypeEntry entry) {
final String className = entry.getClassName();
// Resolve class once during option creation, not on every get/set
Class<?> resolvedClass;
try {
resolvedClass = Class.forName(className);
} catch (ClassNotFoundException e) {
// Class not loaded, skip this option
return null;
}
final Class<?> entityClass = resolvedClass;
return OptionImpl.createBuilder(Boolean.class, EntityLightConfigStorage.INSTANCE)
.setName(entry.getDisplayName() + " (" + entry.getModId() + ")")
.setTooltip(I18n.format("options.dynamiclights.entity.tooltip", entry.getDisplayName()))
.setControl(TickBoxControl::new)
.setBinding(
(_, value) -> EntityLightConfig.setEntityTypeEnabled(entityClass, value),
storage -> EntityLightConfig.isEntityTypeEnabled(entityClass)
)
.setImpact(OptionImpact.LOW)
.build();
}
}
@@ -29,6 +29,7 @@ public class FontConfigScreen extends GuiScreen {
private final String searchPrompt;
private final String testAreaPrompt;
private List<String> testAreaInfo;
private List<String> noFontsWarning;
private String currentPrimaryFontName;
private String currentFallbackFontName;
private FontList fontList;
@@ -56,6 +57,7 @@ public class FontConfigScreen extends GuiScreen {
SliderClone.Option optGlyphSpacing = new SliderClone.Option(-2f, 2f, 0.05f);
SliderClone.Option optFontAAMode = new SliderClone.Option(0, 2, 1);
SliderClone.Option optFontAAStrength = new SliderClone.Option(1, 24, 1);
SliderClone.Option optCustomFontScale = new SliderClone.Option(0.1f, 3, 0.05f);
public FontConfigScreen(GuiScreen parent) {
this.title = I18n.format("options.angelica.fontconfig.title");
@@ -214,6 +216,16 @@ public class FontConfigScreen extends GuiScreen {
.formatString("%.0f")
.build()
);
sliders.add(new SliderClone.SliderCloneBuilder()
.width(sliderWidth)
.height(sliderHeight)
.option(optCustomFontScale)
.initialValue(FontConfig.customFontScale)
.setter(value -> FontConfig.customFontScale = value)
.langKey("options.angelica.fontconfig.custom_font_scale")
.formatString("x%3.2f")
.build()
);
final int halfWidth = this.width / 2;
final int sliderSpacing = 4;
@@ -279,7 +291,6 @@ public class FontConfigScreen extends GuiScreen {
currentFallbackFontName = null;
selectedPrimaryFontListPos = -1;
selectedFallbackFontListPos = -1;
FontStrategist.customFontInUse = false;
super.buttonList.clear();
this.initButtons();
}
@@ -322,9 +333,22 @@ public class FontConfigScreen extends GuiScreen {
@Override
public void drawScreen(int mouseX, int mouseY, float delta) {
drawBackground(0);
fontList.drawScreen(mouseX, mouseY, delta);
searchBox.drawTextBox();
// I bet you thought this was drawn inside the search box, not on top of it.
this.fontList.drawScreen(mouseX, mouseY, delta);
if (availableFonts.length == 0) {
if (this.noFontsWarning == null) {
this.noFontsWarning = this.fontRendererObj.listFormattedStringToWidth(
I18n.format("options.angelica.fontconfig.no_fonts_warning"), this.width / 2
);
}
int y = 80;
for (String s : this.noFontsWarning) {
drawCenteredString(this.fontRendererObj, s, this.width / 3, y, 0xFFFFFF);
y += this.fontRendererObj.FONT_HEIGHT;
}
}
this.searchBox.drawTextBox();
if (!this.searchBox.isFocused() && this.searchBox.getText().isEmpty()) {
this.drawCenteredString(this.fontRendererObj, this.searchPrompt,
this.searchBox.xPosition + this.fontRendererObj.getStringWidth(this.searchPrompt) / 2 + 4,
@@ -0,0 +1,94 @@
package com.gtnewhorizons.angelica.commands;
// Debug commands adapted from Beddium by Ven and FalsePattern
import com.gtnewhorizons.angelica.debug.ChunkDebugMinimap;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasDebugScreenHandler;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AngelicaCommand extends CommandBase {
private static final List<String> SUBCOMMANDS = Arrays.asList("wireframe", "fog", "minimap", "help");
@Override
public String getCommandName() {
return "angelica";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "/angelica <wireframe|fog|minimap|help>";
}
@Override
public int getRequiredPermissionLevel() {
return 0; // Available to all players (client-side only)
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args) {
if (args.length == 1) {
return getListOfStringsMatchingLastWord(args, SUBCOMMANDS.toArray(new String[0]));
}
return new ArrayList<>();
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length == 0) {
sendHelp(sender);
return;
}
switch (args[0].toLowerCase()) {
case "wireframe" -> handleWireframe(sender);
case "fog" -> handleFog(sender);
case "minimap" -> handleMinimap(sender);
default -> sendHelp(sender);
}
}
private void handleWireframe(ICommandSender sender) {
CeleritasWorldRenderer.DEBUG_WIREFRAME_MODE = !CeleritasWorldRenderer.DEBUG_WIREFRAME_MODE;
final String state = CeleritasWorldRenderer.DEBUG_WIREFRAME_MODE ? "ON" : "OFF";
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Wireframe mode: " + state));
}
private void handleFog(ICommandSender sender) {
CeleritasDebugScreenHandler.showFogDebug = !CeleritasDebugScreenHandler.showFogDebug;
final String f3State = CeleritasDebugScreenHandler.showFogDebug ? "ON" : "OFF";
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Fog debug (F3): " + f3State));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " " + CeleritasDebugScreenHandler.getFogDebugString()));
}
private void handleMinimap(ICommandSender sender) {
ChunkDebugMinimap.toggle();
final String state = ChunkDebugMinimap.isEnabled() ? "ON" : "OFF";
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Chunk debug minimap: " + state));
}
private void sendHelp(ICommandSender sender) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] Debug Commands:"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica wireframe" + EnumChatFormatting.WHITE + " - Toggle wireframe rendering"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica fog" + EnumChatFormatting.WHITE + " - Toggle fog debug on F3"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica minimap" + EnumChatFormatting.WHITE + " - Toggle chunk debug overlay"));
}
@Override
public int compareTo(Object o) {
if (o instanceof ICommand cmd) {
return this.getCommandName().compareTo(cmd.getCommandName());
}
return 0;
}
}
@@ -0,0 +1,55 @@
package com.gtnewhorizons.angelica.compat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.ARBDebugOutput;
import org.lwjgl.opengl.GL11;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
/**
* Checks for known problematic driver configurations and applies workarounds. Adapted from Embeddium/Sodium's LateDriverScanner.
*
* <p>The NVIDIA workaround can be disabled via: {@code -Dangelica.disableNvidiaWorkaround=true}
*/
public class DriverCompatabilityCheck {
private static final Logger LOGGER = LogManager.getLogger("Angelica");
private static final boolean DISABLE_NVIDIA_WORKAROUND = Boolean.getBoolean("angelica.disableNvidiaWorkaround");
/**
* Should be called after GL context is created and GLStateManager is initialized.
*/
public static void checkDriverCompatibility() {
final String vendor = GL11.glGetString(GL11.GL_VENDOR);
final String renderer = GL11.glGetString(GL11.GL_RENDERER);
final String version = GL11.glGetString(GL11.GL_VERSION);
LOGGER.info("OpenGL Vendor: {}", vendor);
LOGGER.info("OpenGL Renderer: {}", renderer);
LOGGER.info("OpenGL Version: {}", version);
if (vendor != null && vendor.contains("NVIDIA")) {
if (DISABLE_NVIDIA_WORKAROUND) {
LOGGER.info("NVIDIA workaround disabled via -Dangelica.disableNvidiaWorkaround=true");
} else {
applyNvidiaWorkaround();
}
}
}
/**
* https://github.com/godotengine/godot/issues/33969#issuecomment-917846774
* Attempt to force the driver to disable its submission thread by enabling synchronous debug output.
* This usually suppresses bad behavior from NVIDIA's "Threaded Optimizations" feature.
*/
private static void applyNvidiaWorkaround() {
if (!GLStateManager.capabilities.GL_ARB_debug_output) {
LOGGER.warn("Cannot apply NVIDIA workaround: ARB_debug_output not available");
return;
}
LOGGER.info("Enabling workaround for NVIDIA threaded optimizations");
GL11.glEnable(ARBDebugOutput.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
}
}
@@ -6,7 +6,6 @@ import com.gtnewhorizons.neid.mixins.interfaces.IExtendedBlockStorageMixin;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.NibbleArray;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import ru.fewizz.idextender.Hooks;
public class ExtendedBlockStorageExt extends ExtendedBlockStorage {
public boolean hasSky;
@@ -39,12 +38,6 @@ public class ExtendedBlockStorageExt extends ExtendedBlockStorage {
System.arraycopy(((IExtendedBlockStorageMixin)(Object)storage).getBlock16BMetaArray(), 0, block16BMetaArray, 0, block16BMetaArray.length);
}
}
else if (ModStatus.isOldNEIDLoaded){
final short[] blockLSBArray = Hooks.get(this);
System.arraycopy(Hooks.get(storage), 0, blockLSBArray, 0, blockLSBArray.length);
// getBlockMSBArray is nuked in asm version
arrayLen = blockLSBArray.length;
}
else {
final byte[] blockLSBArray = this.getBlockLSBArray();
System.arraycopy(storage.getBlockLSBArray(), 0, blockLSBArray, 0, blockLSBArray.length);
@@ -12,15 +12,8 @@ public class ModStatus {
public static final Logger LOGGER = LogManager.getLogger("ModCompat");
public static BackhandReflectionCompat backhandCompat;
/**
* Mixin Version
*/
public static boolean isNEIDLoaded;
/**
* ASM Version
*/
public static boolean isOldNEIDLoaded;
public static boolean isBetterCrashesLoaded;
public static boolean isNEIDLoaded;
public static boolean isNEIDMetadataExtended;
public static boolean isLotrLoaded;
public static boolean isChunkAPILoaded;
@@ -42,7 +35,6 @@ public class ModStatus {
isBetterCrashesLoaded = Loader.isModLoaded("bettercrashes");
isNEIDLoaded = Loader.isModLoaded("neid");
isOldNEIDLoaded = Loader.isModLoaded("notenoughIDs");
isLotrLoaded = Loader.isModLoaded("lotr");
isChunkAPILoaded = Loader.isModLoaded("chunkapi");
isEIDBiomeLoaded = Loader.isModLoaded("endlessids_biome");
@@ -55,8 +55,10 @@ public class BackhandReflectionCompat {
if (isLoaded && renderOffhandReturn != null) {
try {
renderOffhandReturn.invokeExact(partialTicks);
} catch (Throwable e) {
LOGGER.error("Failed to invoke Backhand renderOffhandReturn", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -66,8 +68,10 @@ public class BackhandReflectionCompat {
if (isLoaded && getOffhandItem != null) {
try {
return (ItemStack) getOffhandItem.invokeExact(player);
} catch (Throwable e) {
LOGGER.error("Failed to invoke Backhand getOffhandItem", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -27,7 +27,7 @@ public class BetterCrashesCompat implements StateManager.IResettable {
@Override
public void resetState() {
LOGGER.info("Reloading SodiumRenderer");
((IRenderGlobalExt) Minecraft.getMinecraft().renderGlobal).reload();
((IRenderGlobalExt) Minecraft.getMinecraft().renderGlobal).angelica$reload();
LOGGER.info("Resetting GLStateManager");
GLStateManager.reset();
}
@@ -75,8 +75,10 @@ public class HoloInventoryReflectionCompat {
} else {
renderEventMethod.invokeExact(event);
}
} catch (Throwable e) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -85,8 +87,10 @@ public class HoloInventoryReflectionCompat {
if (!isLoaded) return;
try {
angelicaOverrideSetter.invokeExact(value);
} catch (Throwable e) {
LOGGER.error("Failed to set HoloInventory angelicaOverride", e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
LOGGER.error("Failed to invoke HoloInventory renderEvent", t);
isLoaded = false;
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.compat.iris;
import com.gtnewhorizons.angelica.compat.ModStatus;
import net.coderbot.iris.parsing.BiomeCategories;
import net.minecraft.world.biome.BiomeGenBase;
@@ -8,7 +9,7 @@ import java.util.Map;
/**
* Detects and categorizes biomes from popular modded biome mods using cached class checks.
* Currently supports: BiomesOPlenty (BOP), Realistic World Gen (RWG)
* Currently supports: BiomesOPlenty (BOP), Realistic World Gen (RWG), lotr (b36.15)
*/
public class ModdedBiomeDetector {
private static boolean initialized = false;
@@ -23,12 +24,15 @@ public class ModdedBiomeDetector {
// LinkedHashMap maintains insertion order for deterministic behavior
private static final Map<Class<?>, BiomeCategories> rwgClassMap = new LinkedHashMap<>();
private static Class<?> lotrBiomeClass = null;
private static synchronized void initialize() {
if (initialized) return;
initialized = true;
initializeBOP();
initializeRWG();
initializeLOTR();
}
private static void initializeBOP() {
@@ -59,6 +63,16 @@ public class ModdedBiomeDetector {
tryAddRWGClass("rwg.biomes.base.BaseBiomeSnowForest", BiomeCategories.TAIGA); // Snow forests are taiga
}
private static void initializeLOTR() {
if (ModStatus.isLotrLoaded) {
try {
lotrBiomeClass = Class.forName("lotr.common.world.biome.LOTRBiome");
} catch (ClassNotFoundException ignored) {
// lotr not installed
}
}
}
private static void tryAddRWGClass(String className, BiomeCategories category) {
try {
final Class<?> clazz = Class.forName(className);
@@ -91,12 +105,64 @@ public class ModdedBiomeDetector {
// fall through to name/property-based detection
// Realistic World Gen detection
for (Map.Entry<Class<?>, BiomeCategories> entry : rwgClassMap.entrySet()) {
if (entry.getKey().isInstance(biome)) {
return entry.getValue();
if (biome.getBiomeClass().getName().contains("rwg.biomes")) {
for (Map.Entry<Class<?>, BiomeCategories> entry : rwgClassMap.entrySet()) {
if (entry.getKey().isInstance(biome)) {
return entry.getValue();
}
}
}
// lotr
if (lotrBiomeClass!= null && lotrBiomeClass.isInstance(biome)) {
return detectLOTRBiome(biome);
}
return null;
}
private static BiomeCategories detectLOTRBiome(BiomeGenBase biome) {
return switch (biome.biomeName) {
case "river", "farHaradJungleLake", "lake" -> BiomeCategories.RIVER;
case "rohan", "rivendell", "rhunIsland", "rhunLandHills", "rhunLandSteppe", "rhunLand", "andrast",
"blackrootVale", "lamedon", "imlothMelui", "towerHills", "dorwinion", "dale", "shireMoors", "wold",
"anduinVale", "rhun", "lebennin", "pertorogwaith", "breeland", "island", "pinnathGelin",
"minhiriath", "pelennor", "adornland", "nanCurunir", "ithilienWasteland", "fangornClearing",
"barrowDowns", "dorEnErnilHills", "dorEnErnil", "nurn", "wilderland", "eastBight", "lindon",
"eregion", "enedwaith", "meneltarma", "anduinHills", "eriador", "angle", "loneLandsHills",
"loneLands", "pelargir", "rohanUrukHighlands", "celebrant", "gondor", "shire", "nurnen", "farHarad" ->
BiomeCategories.PLAINS;
case "mistyMountains", "windMountains", "farHaradVolcano", "redMountains", "haradMountains",
"angmarMountains", "blueMountains", "greyMountains", "whiteMountains", "mordorMountains" ->
BiomeCategories.MOUNTAIN;
case "shireWoodlands", "rhunIslandForest", "rhunRedForest", "pukel", "lossarnach", "gulfHaradForest",
"nearHaradFertileForest", "dolGuldur", "rhunForest", "tauredainClearing", "umbarForest",
"farHaradForest", "chetwood", "woodlandRealmHills", "mirkwoodNorth", "whiteDowns", "ithilienHills",
"gondorWoodlands", "rohanWoodlands", "fangornWasteland", "mirkwoodMountains", "lindonWoodlands",
"lothlorienEdge", "erynVorn", "oldForest", "fangorn", "dunland", "ithilien", "mirkwoodCorrupted",
"woodlandRealm", "trollshaws", "lothlorien", "farHaradKanuka" -> BiomeCategories.FOREST;
case "mordor", "lastDesert", "harnedor", "easternDesolation", "morgulVale", "gorgoroth", "udun",
"nearHaradRedDesert", "nearHaradSemiDesert", "lostladen",
"nearHaradHills", "nearHarad", "nanUngol", "dagorlad", "brownLands" -> BiomeCategories.DESERT;
case "ironHills", "rivendellHills", "windMountainsFoothills", "lamedonHills", "redMountainsFoothills",
"tolfalas", "dorwinionHills", "whiteMountainsFoothills", "blueMountainsFoothills",
"greyMountainsFoothills", "mistyMountainsFoothills", "erebor", "angmar", "eriadorDowns",
"ettenmoors", "emynMuil" -> BiomeCategories.EXTREME_HILLS;
case "deadMarshes", "shireMarshes", "farHaradMangrove", "farHaradSwamp", "swanfleet", "nindalf",
"longMarshes", "entwashMouth", "nurnMarshes", "gladdenFields", "midgewater", "anduinMouth" ->
BiomeCategories.SWAMP;
case "harondor", "nearHaradOasis", "nearHaradRiverbank", "farHaradBushlandHills", "farHaradBushland",
"gulfHarad", "nearHaradFertile", "umbarHills", "umbar", "farHaradAridHills", "farHaradArid" ->
BiomeCategories.SAVANNA;
case "ocean" -> BiomeCategories.OCEAN;
case "forodwaith", "forodwaithGlacier", "tundra", "forodwaithMountains" -> BiomeCategories.ICY;
case "lindonCoast", "beachWhite", "farHaradCoast", "forodwaithCoast", "beachGravel", "beach" ->
BiomeCategories.BEACH;
case "coldfells", "wilderlandNorth", "taiga" -> BiomeCategories.TAIGA;
case "farHaradJungle", "halfTrollForest", "farHaradJungleMountains",
"farHaradCloudForest", "farHaradJungleEdge" -> BiomeCategories.JUNGLE;
case "utumno" -> BiomeCategories.NONE;
default -> null;
};
}
}
@@ -19,6 +19,7 @@ public class Camera {
public static final Camera INSTANCE = new Camera();
private final Vector3d pos = new Vector3d();
private final Vector3d entityPos = new Vector3d();
private final BlockPos blockPos = new BlockPos();
private final Vector3f offset = new Vector3f();
private final Matrix4f inverseModelView = new Matrix4f();
@@ -42,12 +43,14 @@ public class Camera {
this.partialTicks = partialTicks;
this.entity = entity;
// Entity position (interpolated, at feet level)
// Entity position (interpolated, at eye level)
final double entityX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks;
final double entityY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks;
final double entityZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks;
final double eyeHeight = entity.getEyeHeight();
entityPos.set(entityX, entityY + eyeHeight, entityZ);
thirdPerson = Minecraft.getMinecraft().gameSettings.thirdPersonView > 0;
final double camX, camY, camZ;
@@ -34,10 +34,17 @@ public class MatrixStack {
public void pop() {
this.matrixStack.removeLast();
}
public boolean clear() {
public boolean isEmpty() {
return this.matrixStack.size() == 1;
}
public void reset() {
while (this.matrixStack.size() > 1) {
this.matrixStack.removeLast();
}
loadIdentity();
}
public void translate(double d, double e, double f) {
final Entry lv = (Entry)this.matrixStack.getLast();
lv.model.translate((float)d, (float)e, (float)f);
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.compat.toremove;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
@@ -147,7 +147,7 @@ public abstract class RenderPhase {
FOG = new Fog("fog", () -> {
// Unclear what this should do
// BackgroundRenderer.setFogBlack(), also levelFogColor()
SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color");
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
GLStateManager.enableFog();
}, GLStateManager::disableFog);
BLACK_FOG = new Fog("black_fog", () -> {
@@ -156,7 +156,7 @@ public abstract class RenderPhase {
}, () -> {
// Unclear what this should do
// BackgroundRenderer.setFogBlack(), also levelFogColor()
SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color");
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
GLStateManager.disableFog();
});
MAIN_TARGET = new Target("main_target", () -> {
@@ -164,7 +164,7 @@ public abstract class RenderPhase {
});
OUTLINE_TARGET = new Target("outline_target", () -> {
// TODO: Sodium
SodiumClientMod.LOGGER.debug("NOT enabling the entity outline framebuffer");
AngelicaMod.LOGGER.debug("NOT enabling the entity outline framebuffer");
//MinecraftClient.getInstance().worldRenderer.getEntityOutlinesFramebuffer().beginWrite(false);
}, () -> {
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
@@ -172,7 +172,7 @@ public abstract class RenderPhase {
TRANSLUCENT_TARGET = new Target("translucent_target", () -> {
if (Minecraft.isFancyGraphicsEnabled()) {
// TODO: Sodium
SodiumClientMod.LOGGER.debug("NOT enabling the translucent framebuffer");
AngelicaMod.LOGGER.debug("NOT enabling the translucent framebuffer");
// MinecraftClient.getInstance().worldRenderer.getTranslucentFramebuffer().beginWrite(false);
}
@@ -345,7 +345,7 @@ public abstract class RenderPhase {
super("lightmap", () -> {
if (lightmap) {
// TODO: Sodium - LightmapTextureManager
SodiumClientMod.LOGGER.debug("Lightmap - enable (not implemented)");
AngelicaMod.LOGGER.debug("Lightmap - enable (not implemented)");
// throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().enable();
@@ -354,7 +354,7 @@ public abstract class RenderPhase {
}, () -> {
if (lightmap) {
// TODO: Sodium - LightmapTextureManager
SodiumClientMod.LOGGER.debug("Lightmap - disable (not implemented)");
AngelicaMod.LOGGER.debug("Lightmap - disable (not implemented)");
// throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().disable();
}
@@ -4,10 +4,21 @@ import com.gtnewhorizon.gtnhlib.config.Config;
@Config(modid = "angelica", filename = "angelica-modules")
public class AngelicaConfig {
@Config.Comment("Enable Sodium rendering")
@Config.Comment("Enable Celeritas terrain rendering")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableSodium;
public static boolean enableCeleritas;
@Config.Comment("Enable multi-threaded chunk building for improved performance [Requires Celeritas]")
@Config.DefaultBoolean(true)
@Config.RequiresWorldRestart
public static boolean enableThreadedChunkBuilding;
@Config.Comment("Number of chunk builder threads. 0 = auto-detect, -1 = use single-threaded fallback")
@Config.DefaultInt(0)
@Config.RangeInt(min = -1, max = 16)
@Config.RequiresWorldRestart
public static int chunkBuilderThreadCount;
@Config.Comment("Enable NotFine Options")
@Config.DefaultBoolean(false)
@@ -17,11 +28,6 @@ public class AngelicaConfig {
@Config.DefaultBoolean(true)
public static boolean enableReesesSodiumOptions;
@Config.Comment("Enable Sodium fluid rendering [Experimental]")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
public static boolean enableSodiumFluidRendering;
@Config.Comment("Inject BakedModel rendering into some vanilla blocks")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
@@ -32,7 +38,7 @@ public class AngelicaConfig {
@Config.Ignore()
public static boolean enableTestBlocks;
@Config.Comment("Enable Iris Shaders [Requires Sodium]")
@Config.Comment("Enable Iris Shaders [Requires Celeritas]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableIris;
@@ -47,6 +53,11 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean enableVBOClouds;
@Config.Comment("Uses cached attributes for VBO rendering, resulting in less CPU overhead. Disable if you notice any graphical issues.")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableVAO;
@Config.Comment("Enable NotFine features")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
@@ -77,12 +88,16 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean enableHudCachingEventTransformer;
@Config.Comment("Enable HUD Caching at runtime. Requires enableHudCaching to be on at startup. [Experimental]")
@Config.DefaultBoolean(false)
public static boolean hudCachingActive;
@Config.Comment("The amount of frames to wait before updating the HUD elements. [Experimental]")
@Config.DefaultInt(20)
@Config.RangeInt(min = 1, max = 60)
public static int hudCachingFPS = 20;
@Config.Comment("Batch drawScreen fonts [Experimental]")
@Config.Comment("Batch drawScreen fonts")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableFontRenderer;
@@ -189,19 +204,35 @@ public class AngelicaConfig {
"net.minecraft.block.BlockStairs"
})
public static String[] blockCrackFixBlacklist;
@Config.Comment({"Block classes that have render pass other than 0 but still need to be manipulated.",
"Add a block class here if you see flickering (z-fighting) with fixBlockCrack enabled"
})
@Config.DefaultStringList({
"gregtech.common.blocks.BlockOres",
"gregtech.common.blocks.GTBlockOre",
"shukaro.artifice.block.world.BlockOre",
"bartworks.system.material.BWMetaGeneratedOres",
"gtPlusPlus.core.block.base.BlockBaseOre",
"org.pfaa.geologica.block.BrokenGeoBlock",
"org.pfaa.geologica.block.BrickGeoBlock",
})
public static String[] blockCrackFixRenderPassWhitelist_;
public static String[] blockCrackFixRenderPassWhitelist__;
@Config.Comment("Register HardcodedCustomUniforms in Iris Shaders. May help with compatibility in certain shader packs")
@Config.DefaultBoolean(false)
public static boolean enableHardcodedCustomUniforms;
@Config.Comment("Define IS_IRIS in shader macros.")
@Config.DefaultBoolean(true)
public static boolean defineIsIris;
@Config.Comment("Renders chunks before neighbors are ready. Improves loading at render distance edges, useful for low render distance servers.")
@Config.DefaultBoolean(false)
public static boolean useVanillaChunkTracking;
@Config.Comment("Disables additional F3 information added by Angelica.")
@Config.DefaultBoolean(false)
public static boolean disableF3Additions;
}
@@ -65,4 +65,16 @@ public class FontConfig {
@Config.DefaultInt(7)
@Config.RangeInt(min = 1, max = 24)
public static int fontAAStrength;
@Config.Comment("Custom font scale multiplier, for bugfixes.")
@Config.DefaultFloat(1.5F)
@Config.RangeFloat(min = 0.1F, max = 3F)
public static float customFontScale;
@Config.Comment({"Mods can provide Angelica with a mapping of special characters to either get replaced with " +
"different characters or rendered using the default Unicode font. Setting this to false disables the " +
"replacement, which is useful in cases where custom fonts have direct support for these special characters. ",
"See for additional details: https://github.com/GTNewHorizons/Angelica/issues/1239#issuecomment-3729877936"})
@Config.DefaultBoolean(true)
public static boolean enableGlyphReplacements;
}
@@ -0,0 +1,158 @@
/*
* Adapated from: Beddium for usage in Angelica
*
* Copyright (C) 2025 Ven, FalsePattern
* All Rights Reserved
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gtnewhorizons.angelica.debug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.rendering.celeritas.AngelicaRenderSectionManager;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import lombok.Getter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.world.chunk.EmptyChunk;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
/**
* Debug overlay that renders a minimap showing chunk loading and rendering state. Toggle via /angelica minimap
*/
public class ChunkDebugMinimap {
private static final ChunkDebugMinimap INSTANCE = new ChunkDebugMinimap();
@Getter
private static volatile boolean enabled = false;
private static final int RANGE = 32; // Chunks in each direction from player
public static synchronized void toggle() {
if (enabled) disable();
else enable();
}
public static synchronized void enable() {
if (enabled) return;
enabled = true;
MinecraftForge.EVENT_BUS.register(INSTANCE);
}
public static synchronized void disable() {
if (!enabled) return;
enabled = false;
MinecraftForge.EVENT_BUS.unregister(INSTANCE);
}
@SubscribeEvent
public void onRenderOverlay(RenderGameOverlayEvent.Text event) {
final Minecraft mc = Minecraft.getMinecraft();
if (mc.theWorld == null || mc.thePlayer == null) return;
final CeleritasWorldRenderer renderer;
try {
renderer = CeleritasWorldRenderer.getInstance();
} catch (IllegalStateException e) {
return; // Renderer not initialized
}
final AngelicaRenderSectionManager manager = renderer.getRenderSectionManager();
if (manager == null) return;
final float partialTicks = event.partialTicks;
final double pX = mc.thePlayer.prevPosX + (mc.thePlayer.posX - mc.thePlayer.prevPosX) * partialTicks;
final double pZ = mc.thePlayer.prevPosZ + (mc.thePlayer.posZ - mc.thePlayer.prevPosZ) * partialTicks;
final int playerChunkX = ((int) Math.floor(pX)) >> 4;
final int playerChunkZ = ((int) Math.floor(pZ)) >> 4;
// Save GL state
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GLStateManager.glPushMatrix();
// Setup rendering
GLStateManager.glScaled(2, 2, 1);
GLStateManager.glTranslated(32, 32, 0);
GLStateManager.disableLighting();
GLStateManager.disableTexture();
GLStateManager.disableDepthTest();
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.glBegin(GL11.GL_QUADS);
final ChunkProviderClient chunkProvider = (ChunkProviderClient) mc.theWorld.getChunkProvider();
for (int x = playerChunkX - RANGE; x < playerChunkX + RANGE; x++) {
for (int z = playerChunkZ - RANGE; z < playerChunkZ + RANGE; z++) {
drawChunk(x, z, playerChunkX, playerChunkZ, manager, chunkProvider);
}
}
GL11.glEnd();
// Restore GL state
GLStateManager.enableLighting();
GLStateManager.enableDepthTest();
GLStateManager.disableBlend();
GLStateManager.glPopMatrix();
GLStateManager.glPopAttrib();
}
private void drawChunk(int chunkX, int chunkZ, int playerChunkX, int playerChunkZ, AngelicaRenderSectionManager manager, ChunkProviderClient chunkProvider) {
boolean initialized = false;
float r = 0, g = 0, b = 0;
// Check all 16 sections in the chunk column
for (int y = 0; y < 16; y++) {
if (manager.isSectionBuilt(chunkX, y, chunkZ) && !manager.isSectionVisuallyEmpty(chunkX, y, chunkZ)) {
initialized = true;
g = 1; // Green = built
if (manager.isSectionVisible(chunkX, y, chunkZ)) {
b = 1; // Cyan = visible
break;
}
}
}
if (!initialized) {
// Check if chunk is loaded
final var chunk = chunkProvider.provideChunk(chunkX, chunkZ);
if (chunk instanceof EmptyChunk) {
r = 1; // Red = unloaded
} else {
b = 1; // Blue = loaded but not built
}
}
GL11.glColor4f(r, g, b, 0.8f);
final int xStart = chunkX - playerChunkX;
final int zStart = chunkZ - playerChunkZ;
final int xEnd = xStart + 1;
final int zEnd = zStart + 1;
GLStateManager.glVertex3d(xStart, zStart, 0);
GLStateManager.glVertex3d(xStart, zEnd, 0);
GLStateManager.glVertex3d(xEnd, zEnd, 0);
GLStateManager.glVertex3d(xEnd, zStart, 0);
}
}
@@ -19,7 +19,7 @@ import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glEnableClientState;
import static org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER;
import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW;
import static org.lwjgl.opengl.GL15.glBindBuffer;
import static com.gtnewhorizons.angelica.glsm.GLStateManager.glBindBuffer;
import static org.lwjgl.opengl.GL15.glBufferData;
import static org.lwjgl.opengl.GL15.glGenBuffers;
import static org.lwjgl.opengl.GL20.glDisableVertexAttribArray;
@@ -0,0 +1,70 @@
package com.gtnewhorizons.angelica.dynamiclights;
import org.jetbrains.annotations.NotNull;
/**
* Calculates the appropriate tick mode for a dynamic light source based on distance from camera and position relative to camera direction.
*/
public final class AdaptiveTickCalculator {
// Distance thresholds in blocks (configurable via settings)
private static int slowDistance = 32; // ~2 chunks
private static int slowerDistance = 64; // ~4 chunks
private static int backgroundDistance = 128; // ~8 chunks
// Squared thresholds for efficient distance comparison
private static int slowDistanceSq = slowDistance * slowDistance;
private static int slowerDistanceSq = slowerDistance * slowerDistance;
private static int backgroundDistanceSq = backgroundDistance * backgroundDistance;
private AdaptiveTickCalculator() {}
/**
* Calculate the appropriate tick mode for a light source.
*/
public static AdaptiveTickMode calculate(@NotNull IDynamicLightSource source, double cameraX, double cameraY, double cameraZ, double lookDirX, double lookDirZ) {
double dx = source.angelica$getDynamicLightX() - cameraX;
double dy = source.angelica$getDynamicLightY() - cameraY;
double dz = source.angelica$getDynamicLightZ() - cameraZ;
double distSq = dx * dx + dy * dy + dz * dz;
// Check if behind camera (dot product of direction to source with look direction)
// Only use X and Z for horizontal check (more stable as player looks up/down)
double dot = dx * lookDirX + dz * lookDirZ;
boolean behindCamera = dot < 0;
// Behind camera always gets BACKGROUND mode
if (behindCamera) {
return AdaptiveTickMode.BACKGROUND;
}
// Distance-based mode selection
if (distSq > backgroundDistanceSq) {
return AdaptiveTickMode.BACKGROUND;
}
if (distSq > slowerDistanceSq) {
return AdaptiveTickMode.SLOWER;
}
if (distSq > slowDistanceSq) {
return AdaptiveTickMode.SLOW;
}
return AdaptiveTickMode.REAL_TIME;
}
public static void setSlowDistance(int distance) {
slowDistance = distance;
slowDistanceSq = distance * distance;
}
public static void setSlowerDistance(int distance) {
slowerDistance = distance;
slowerDistanceSq = distance * distance;
}
public static void setBackgroundDistance(int distance) {
backgroundDistance = distance;
backgroundDistanceSq = distance * distance;
}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.dynamiclights;
/**
* Defines tick modes for adaptive dynamic light updates. Distant or off-screen light sources update less frequently to save CPU.
*/
public enum AdaptiveTickMode {
/** Updates every tick - for nearby, visible light sources */
REAL_TIME(1),
/** Updates every 5 ticks - for light sources at moderate distance */
SLOW(5),
/** Updates every 10 ticks - for light sources at far distance */
SLOWER(10),
/** Updates every 20 ticks - for light sources behind the camera or very far */
BACKGROUND(20);
private final int delay;
AdaptiveTickMode(int delay) {
this.delay = delay;
}
public int getDelay() {
return delay;
}
public boolean shouldTickThisFrame(int worldTick, int sourceHash) {
if (delay <= 1) {
return true;
}
return (worldTick % delay) == Math.abs(sourceHash % delay);
}
}
@@ -0,0 +1,152 @@
package com.gtnewhorizons.angelica.dynamiclights;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongIterator;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Manages deferred chunk rebuilds for dynamic lights with optional frustum culling. Instead of scheduling chunk rebuilds immediately
* when light sources move, this tracks pending rebuilds and only schedules visible chunks.
*/
public class ChunkRebuildManager {
/** Maps packed chunk position to ticks waiting */
private final Long2IntOpenHashMap pendingRebuilds = new Long2IntOpenHashMap();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
/** Maximum ticks a pending rebuild can wait before being forced through */
private static int maxTicksWaiting = 100;
/** Reusable lists for processVisible - only used from render thread */
private final LongArrayList candidates = new LongArrayList();
private final LongArrayList toRebuild = new LongArrayList();
private final LongArrayList toIncrement = new LongArrayList();
public static void setMaxTicksWaiting(int ticks) {
maxTicksWaiting = Math.max(20, Math.min(ticks, 600)); // Clamp 1-30 seconds (20-600 ticks)
}
public void requestRebuild(int x, int y, int z) {
final long packed = CoordinatePacker.pack(x, y, z);
lock.writeLock().lock();
try {
// Reset wait counter if already pending, otherwise add new entry
pendingRebuilds.put(packed, 0);
} finally {
lock.writeLock().unlock();
}
}
public void processVisible(Viewport viewport, @NotNull IDynamicLightWorldRenderer renderer) {
candidates.clear();
toRebuild.clear();
toIncrement.clear();
// Phase 1: Collect all pending chunks with read lock (fast)
lock.readLock().lock();
try {
if (pendingRebuilds.isEmpty()) {
return;
}
// Collect candidates that might need processing
final var iterator = pendingRebuilds.long2IntEntrySet().fastIterator();
while (iterator.hasNext()) {
final var entry = iterator.next();
final long packed = entry.getLongKey();
final int ticksWaiting = entry.getIntValue();
// Force process if no viewport or waited too long
if (viewport == null || ticksWaiting >= maxTicksWaiting) {
toRebuild.add(packed);
} else {
candidates.add(packed);
}
}
} finally {
lock.readLock().unlock();
}
// Phase 2: Check visibility
for (int i = 0; i < candidates.size(); i++) {
long packed = candidates.getLong(i);
int x = CoordinatePacker.unpackX(packed);
int y = CoordinatePacker.unpackY(packed);
int z = CoordinatePacker.unpackZ(packed);
if (isChunkVisible(viewport, x, y, z)) {
toRebuild.add(packed);
} else {
toIncrement.add(packed);
}
}
// Phase 3: Update map with write lock (brief)
if (!toRebuild.isEmpty() || !toIncrement.isEmpty()) {
lock.writeLock().lock();
try {
// Remove chunks we're going to rebuild
LongIterator rebuildIter = toRebuild.iterator();
while (rebuildIter.hasNext()) {
pendingRebuilds.remove(rebuildIter.nextLong());
}
LongIterator incIter = toIncrement.iterator();
while (incIter.hasNext()) {
long packed = incIter.nextLong();
int current = pendingRebuilds.get(packed);
if (pendingRebuilds.containsKey(packed)) {
pendingRebuilds.put(packed, current + 1);
}
}
} finally {
lock.writeLock().unlock();
}
}
// Phase 4: Schedule rebuilds outside of lock
for (int i = 0; i < toRebuild.size(); i++) {
final long packed = toRebuild.getLong(i);
renderer.scheduleRebuildForChunk(
CoordinatePacker.unpackX(packed),
CoordinatePacker.unpackY(packed),
CoordinatePacker.unpackZ(packed),
false
);
}
}
private boolean isChunkVisible(Viewport viewport, int chunkX, int chunkY, int chunkZ) {
// Convert chunk section coords to block coords
int blockX = chunkX << 4;
int blockY = chunkY << 4;
int blockZ = chunkZ << 4;
// Check if the 16x16x16 chunk section box is visible
return viewport.isBoxVisible(
blockX, blockY, blockZ,
blockX + 16, blockY + 16, blockZ + 16
);
}
public void clear() {
lock.writeLock().lock();
try {
pendingRebuilds.clear();
} finally {
lock.writeLock().unlock();
}
}
public int getPendingCount() {
lock.readLock().lock();
try {
return pendingRebuilds.size();
} finally {
lock.readLock().unlock();
}
}
}
@@ -8,9 +8,10 @@ import com.gtnewhorizons.angelica.api.IDynamicLightProducer;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.battlegear2.Battlegear2Compat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.PrimedEntityAccessor;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import mods.battlegear2.api.core.IBattlePlayer;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.block.Block;
@@ -22,20 +23,28 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
public class DynamicLights {
private static DynamicLights instance;
private static IDynamicLightWorldRenderer activeRenderer;
public static DynamicLightsMode Mode = DynamicLightsMode.OFF;
public static boolean ShaderForce = false;
public static boolean FrustumCullingEnabled = true;
public static boolean AdaptiveTickingEnabled = true;
public static final boolean configEnabled = AngelicaConfig.enableDynamicLights;
@@ -43,6 +52,8 @@ public class DynamicLights {
private static final double MAX_RADIUS_SQUARED = MAX_RADIUS * MAX_RADIUS;
private final Set<IDynamicLightSource> dynamicLightSources = new ObjectOpenHashSet<>();
private final ReentrantReadWriteLock lightSourcesLock = new ReentrantReadWriteLock();
private volatile int lightSourceCount = 0;
private final ChunkRebuildManager chunkRebuildManager = new ChunkRebuildManager();
private long lastUpdate = System.currentTimeMillis();
private int lastUpdateCount = 0;
@@ -60,12 +71,24 @@ public class DynamicLights {
(ShaderForce || !IrisApi.getInstance().isShaderPackInUse());
}
public boolean hasLightSources() {
return lightSourceCount > 0;
}
public static IDynamicLightWorldRenderer getActiveRenderer() {
return activeRenderer;
}
public static void setActiveRenderer(IDynamicLightWorldRenderer renderer) {
activeRenderer = renderer;
}
/**
* Updates all light sources.
*
* @param renderer the renderer
*/
public void updateAll(@NotNull SodiumWorldRenderer renderer) {
public void updateAll(@NotNull IDynamicLightWorldRenderer renderer) {
if (!isEnabled())
return;
@@ -74,8 +97,43 @@ public class DynamicLights {
this.lastUpdate = now;
this.lastUpdateCount = 0;
// Get camera info for adaptive ticking
double cameraX = 0, cameraY = 0, cameraZ = 0;
double lookDirX = 0, lookDirZ = 1;
int worldTick = 0;
if (AdaptiveTickingEnabled) {
Minecraft mc = Minecraft.getMinecraft();
if (mc.theWorld != null && mc.renderViewEntity != null) {
cameraX = mc.renderViewEntity.posX;
cameraY = mc.renderViewEntity.posY + mc.renderViewEntity.getEyeHeight();
cameraZ = mc.renderViewEntity.posZ;
worldTick = (int) (mc.theWorld.getTotalWorldTime() & 0x7FFFFFFF);
// Calculate look direction from yaw (normalized horizontal direction)
float yaw = mc.renderViewEntity.rotationYaw;
double yawRad = Math.toRadians(yaw);
lookDirX = -Math.sin(yawRad);
lookDirZ = Math.cos(yawRad);
}
}
this.lightSourcesLock.readLock().lock();
for (var lightSource : this.dynamicLightSources) {
// Entity type filter
if (!EntityLightConfig.isEntityTypeEnabled(lightSource)) {
continue;
}
// Adaptive ticking filter
if (AdaptiveTickingEnabled) {
AdaptiveTickMode mode = AdaptiveTickCalculator.calculate(
lightSource, cameraX, cameraY, cameraZ, lookDirX, lookDirZ);
if (!mode.shouldTickThisFrame(worldTick, lightSource.hashCode())) {
continue;
}
}
if (lightSource.angelica$updateDynamicLight(renderer))
this.lastUpdateCount++;
}
@@ -89,7 +147,9 @@ public class DynamicLights {
public void addLightSource(IDynamicLightSource lightSource) {
this.lightSourcesLock.writeLock().lock();
this.dynamicLightSources.add(lightSource);
if (this.dynamicLightSources.add(lightSource)) {
this.lightSourceCount = this.dynamicLightSources.size();
}
this.lightSourcesLock.writeLock().unlock();
}
@@ -107,8 +167,9 @@ public class DynamicLights {
it = dynamicLightSources.next();
if (it.equals(lightSource)) {
dynamicLightSources.remove();
if (SodiumWorldRenderer.getInstance() != null)
lightSource.angelica$scheduleTrackedChunksRebuild(SodiumWorldRenderer.getInstance());
this.lightSourceCount = this.dynamicLightSources.size();
if (activeRenderer != null)
lightSource.angelica$scheduleTrackedChunksRebuild(activeRenderer);
break;
}
}
@@ -130,10 +191,11 @@ public class DynamicLights {
it = dynamicLightSources.next();
if (filter.test(it)) {
dynamicLightSources.remove();
if (SodiumWorldRenderer.getInstance() != null) {
this.lightSourceCount = this.dynamicLightSources.size();
if (activeRenderer != null) {
if (it.angelica$getLuminance() > 0)
it.angelica$resetDynamicLight();
it.angelica$scheduleTrackedChunksRebuild(SodiumWorldRenderer.getInstance());
it.angelica$scheduleTrackedChunksRebuild(activeRenderer);
}
break;
}
@@ -153,12 +215,13 @@ public class DynamicLights {
while (dynamicLightSources.hasNext()) {
it = dynamicLightSources.next();
dynamicLightSources.remove();
if (SodiumWorldRenderer.getInstance() != null) {
if (activeRenderer != null) {
if (it.angelica$getLuminance() > 0)
it.angelica$resetDynamicLight();
it.angelica$scheduleTrackedChunksRebuild(SodiumWorldRenderer.getInstance());
it.angelica$scheduleTrackedChunksRebuild(activeRenderer);
}
}
this.lightSourceCount = 0;
this.lightSourcesLock.writeLock().unlock();
}
@@ -203,6 +266,20 @@ public class DynamicLights {
return MathHelper.clamp_double(result, 0, 15);
}
/**
* Gets dynamic light level at an exact world position (for smooth per-vertex lighting).
*/
public double getDynamicLightLevel(double x, double y, double z) {
double result = 0;
this.lightSourcesLock.readLock().lock();
for (var lightSource : this.dynamicLightSources) {
result = maxDynamicLightLevelExact(x, y, z, lightSource, result);
}
this.lightSourcesLock.readLock().unlock();
return MathHelper.clamp_double(result, 0, 15);
}
public double getDynamicLightLevel(@NotNull BlockPos pos) {
return this.getDynamicLightLevel(pos.getX(), pos.getY(), pos.getZ());
}
@@ -229,6 +306,29 @@ public class DynamicLights {
return currentLightLevel;
}
/**
* Calculates dynamic light level at an exact position (no block center offset).
* Used for smooth per-vertex lighting.
*/
public static double maxDynamicLightLevelExact(double x, double y, double z, @NotNull IDynamicLightSource lightSource, double currentLightLevel) {
int luminance = lightSource.angelica$getLuminance();
if (luminance > 0) {
double dx = x - lightSource.angelica$getDynamicLightX();
double dy = y - lightSource.angelica$getDynamicLightY();
double dz = z - lightSource.angelica$getDynamicLightZ();
double distanceSquared = dx * dx + dy * dy + dz * dz;
if (distanceSquared <= MAX_RADIUS_SQUARED) {
double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS;
double lightLevel = multiplier * (double) luminance;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
}
}
return currentLightLevel;
}
/**
* Returns the dynamic light level generated by the light source at the specified position.
*
@@ -245,6 +345,51 @@ public class DynamicLights {
return this.getLightmapWithDynamicLight(this.getDynamicLightLevel(x, y, z), lightmap);
}
public List<IDynamicLightSource> getSourcesForChunk(int chunkMinX, int chunkMinY, int chunkMinZ) {
// Chunk center
final double centerX = chunkMinX + 8.0;
final double centerY = chunkMinY + 8.0;
final double centerZ = chunkMinZ + 8.0;
// Max distance from chunk center to any corner is sqrt(3) * 8 ≈ 13.86
// Add MAX_RADIUS to get the search radius (13.86 + 7.75)^2 ≈ 467
final double searchRadiusSq = 470.0; // Slightly padded for safety
List<IDynamicLightSource> result = null;
this.lightSourcesLock.readLock().lock();
try {
for (IDynamicLightSource source : this.dynamicLightSources) {
double dx = source.angelica$getDynamicLightX() - centerX;
double dy = source.angelica$getDynamicLightY() - centerY;
double dz = source.angelica$getDynamicLightZ() - centerZ;
double distSq = dx * dx + dy * dy + dz * dz;
if (distSq <= searchRadiusSq) {
if (result == null) {
result = new ArrayList<>();
}
result.add(source);
}
}
} finally {
this.lightSourcesLock.readLock().unlock();
}
return result != null ? result : Collections.emptyList();
}
public double getDynamicLightLevelFromSources(double x, double y, double z, List<IDynamicLightSource> sources) {
if (sources == null || sources.isEmpty()) {
return 0;
}
double result = 0;
for (int i = 0, size = sources.size(); i < size; i++) {
result = maxDynamicLightLevelExact(x, y, z, sources.get(i), result);
}
return MathHelper.clamp_double(result, 0, 15);
}
/**
* Returns the lightmap with combined light levels.
*
@@ -275,7 +420,7 @@ public class DynamicLights {
* @param renderer the renderer
* @param chunkPos the chunk position
*/
public static void scheduleChunkRebuild(@NotNull SodiumWorldRenderer renderer, @NotNull IBlockPos chunkPos) {
public static void scheduleChunkRebuild(@NotNull IDynamicLightWorldRenderer renderer, @NotNull IBlockPos chunkPos) {
scheduleChunkRebuild(renderer, chunkPos.getX(), chunkPos.getY(), chunkPos.getZ());
}
@@ -285,14 +430,37 @@ public class DynamicLights {
* @param renderer the renderer
* @param chunkPos the packed chunk position
*/
public static void scheduleChunkRebuild(@NotNull SodiumWorldRenderer renderer, long chunkPos) {
public static void scheduleChunkRebuild(@NotNull IDynamicLightWorldRenderer renderer, long chunkPos) {
scheduleChunkRebuild(renderer, CoordinatePacker.unpackX(chunkPos), CoordinatePacker.unpackY(chunkPos), CoordinatePacker.unpackZ(chunkPos));
}
public static void scheduleChunkRebuild(@NotNull SodiumWorldRenderer renderer, int x, int y, int z) {
public static void scheduleChunkRebuild(@NotNull IDynamicLightWorldRenderer renderer, int x, int y, int z) {
if (FrustumCullingEnabled && instance != null) {
instance.chunkRebuildManager.requestRebuild(x, y, z);
} else {
renderer.scheduleRebuildForChunk(x, y, z, false);
}
}
public static void scheduleChunkRebuildForRemoval(@NotNull IDynamicLightWorldRenderer renderer, int x, int y, int z) {
renderer.scheduleRebuildForChunk(x, y, z, false);
}
public static void scheduleChunkRebuildForRemoval(@NotNull IDynamicLightWorldRenderer renderer, long chunkPos) {
scheduleChunkRebuildForRemoval(renderer, CoordinatePacker.unpackX(chunkPos), CoordinatePacker.unpackY(chunkPos), CoordinatePacker.unpackZ(chunkPos));
}
public void processChunkRebuilds(@Nullable Viewport viewport) {
if (activeRenderer == null) {
return;
}
chunkRebuildManager.processVisible(viewport, activeRenderer);
}
public ChunkRebuildManager getChunkRebuildManager() {
return chunkRebuildManager;
}
/**
* Updates the tracked chunk sets.
*
@@ -333,10 +501,7 @@ public class DynamicLights {
* @param submergedInWater {@code true} if the stack is submerged in water, else {@code false}
* @return the luminance of the item
*/
public static int getLuminanceFromItemStack(@NotNull ItemStack stack, boolean submergedInWater) {
// TODO only have certain items not glow in water?
if (submergedInWater) return 0;
public static int getLuminanceFromItemStack(@NotNull ItemStack stack) {
Item item = stack.getItem();
if (item instanceof ItemBlock itemBlock) {
Block block = itemBlock.field_150939_a;
@@ -354,49 +519,53 @@ public class DynamicLights {
public static int getLuminanceFromEntity(@NotNull Entity entity) {
if (entity.fire > 0) return 15;
if (entity.isBurning()) return 15;
boolean inWater = entity.isInsideOfMaterial(Material.water);
// TODO only have certain items not glow in water?
if (inWater) return 0;
if (entity instanceof EntityItem item) {
return getLuminanceFromItemStack(item.getEntityItem(), item.isInsideOfMaterial(Material.water));
return getLuminanceFromItemStack(item.getEntityItem());
}
int luminance = 0;
if (entity instanceof EntityLivingBase living) {
int luminance = 0;
boolean inWater = living.isInsideOfMaterial(Material.water);
// check equipment + hand for light (should work for all entities)
ItemStack itemStack;
for (int i = 0; i < 5; i++) {
if ((itemStack = living.getEquipmentInSlot(i)) != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(itemStack, inWater));
luminance = Math.max(luminance, getLuminanceFromItemStack(itemStack));
}
}
if (ModStatus.isBattlegearLoaded &&
living instanceof EntityPlayer player &&
player instanceof IBattlePlayer battlePlayer &&
battlePlayer.battlegear2$isBattlemode()
) {
ItemStack offhand = Battlegear2Compat.getBattlegear2Offhand(player);
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand, inWater));
if (living instanceof EntityPlayer player) {
if (ModStatus.isBattlegearLoaded &&
player instanceof IBattlePlayer battlePlayer &&
battlePlayer.battlegear2$isBattlemode()
) {
ItemStack offhand = Battlegear2Compat.getBattlegear2Offhand(player);
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand));
}
}
}
else if (ModStatus.isBackhandLoaded && living instanceof EntityPlayer player){
ItemStack offhand = ModStatus.backhandCompat.getOffhandItem(player);
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand, inWater));
else if (ModStatus.isBackhandLoaded){
ItemStack offhand = ModStatus.backhandCompat.getOffhandItem(player);
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand));
}
}
}
if (ModStatus.isBaublesLoaded && living instanceof EntityPlayer player){
var playerBaubles = PlayerHandler.getPlayerBaubles(player);
if (playerBaubles != null){
for (int i = 0; i < playerBaubles.getSizeInventory(); i++){
var stack = playerBaubles.getStackInSlot(i);
if (stack != null){
luminance = Math.max(luminance, getLuminanceFromItemStack(stack, inWater));
if (ModStatus.isBaublesLoaded){
var playerBaubles = PlayerHandler.getPlayerBaubles(player);
if (playerBaubles != null){
for (int i = 0; i < playerBaubles.getSizeInventory(); i++){
var stack = playerBaubles.getStackInSlot(i);
if (stack != null){
luminance = Math.max(luminance, getLuminanceFromItemStack(stack));
}
}
}
}
@@ -406,7 +575,10 @@ public class DynamicLights {
}
// TODO: Creepers? TNT? Dusts?
if (entity instanceof PrimedEntityAccessor primedEntity) {
luminance = Math.max(luminance, primedEntity.angelica$getLuminance());
}
return 0;
return luminance;
}
}
@@ -1,6 +1,5 @@
package com.gtnewhorizons.angelica.dynamiclights;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
@@ -27,11 +26,13 @@ public interface IDynamicLightSource {
double angelica$getDynamicLightZ();
/**
* Returns the dynamic light source world.
* Returns the dynamic light source world renderer.
*
* @return the world instance
* @return the world renderer instance
*/
SodiumWorldRenderer angelica$getDynamicLightWorld();
default IDynamicLightWorldRenderer angelica$getDynamicLightWorld() {
return DynamicLights.getActiveRenderer();
}
/**
* Returns whether the dynamic light is enabled or not.
@@ -72,8 +73,9 @@ public interface IDynamicLightSource {
* Executed at each tick.
*/
void angelica$dynamicLightTick();
default void angelica$updateLights() {}
boolean angelica$updateDynamicLight(@NotNull SodiumWorldRenderer renderer);
boolean angelica$updateDynamicLight(@NotNull IDynamicLightWorldRenderer renderer);
void angelica$scheduleTrackedChunksRebuild(@NotNull SodiumWorldRenderer renderer);
void angelica$scheduleTrackedChunksRebuild(@NotNull IDynamicLightWorldRenderer renderer);
}
@@ -0,0 +1,17 @@
package com.gtnewhorizons.angelica.dynamiclights;
/**
* Common interface for world renderers that support dynamic lights chunk rebuilds.
* Implemented by CeleritasWorldRenderer.
*/
public interface IDynamicLightWorldRenderer {
/**
* Schedules a chunk rebuild for the render section at the given chunk coordinates.
*/
void scheduleRebuildForChunk(int x, int y, int z, boolean important);
/**
* Returns whether this renderer is currently active (has a world loaded).
*/
boolean isActive();
}
@@ -0,0 +1,187 @@
package com.gtnewhorizons.angelica.dynamiclights.config;
import com.gtnewhorizon.gtnhlib.concurrent.cas.CasMap;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightSource;
import cpw.mods.fml.common.registry.EntityRegistry;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public final class EntityLightConfig {
private static final Logger LOGGER = LogManager.getLogger("Angelica/DynamicLights");
private static final Set<String> disabledClassNames = ConcurrentHashMap.newKeySet();
private static final CasMap<Class<?>, Boolean> enabledCache = new CasMap<>();
private static File configFile;
private static boolean initialized = false;
private EntityLightConfig() {}
public static void init(@NotNull File configDir) {
if (initialized) return;
configFile = new File(configDir, "angelica-dynamiclights-entities.txt");
load();
initialized = true;
}
public static boolean isEntityTypeEnabled(@NotNull IDynamicLightSource source) {
if (!initialized) return true;
return isEntityTypeEnabled(source.getClass());
}
public static boolean isEntityTypeEnabled(@NotNull Class<?> entityClass) {
if (!initialized) return true;
Boolean cached = enabledCache.get(entityClass);
if (cached != null) {
return cached;
}
final boolean enabled = !disabledClassNames.contains(entityClass.getName());
Boolean existing = enabledCache.putIfAbsent(entityClass, enabled);
return existing != null ? existing : enabled;
}
public static void setEntityTypeEnabled(@NotNull Class<?> entityClass, boolean enabled) {
enabledCache.put(entityClass, enabled);
final String className = entityClass.getName();
if (enabled) {
disabledClassNames.remove(className);
} else {
disabledClassNames.add(className);
}
}
@SuppressWarnings("unchecked")
public static List<EntityTypeEntry> getAllEntityTypes() {
List<EntityTypeEntry> entries = new ArrayList<>();
Set<String> seenClasses = new HashSet<>();
Map<String, Class<? extends Entity>> stringToClass = EntityList.stringToClassMapping;
for (Map.Entry<String, Class<? extends Entity>> entry : stringToClass.entrySet()) {
String entityId = entry.getKey();
Class<?> entityClass = entry.getValue();
String className = entityClass.getName();
if (seenClasses.contains(className)) continue;
seenClasses.add(className);
String modId = getModIdForEntity(entityClass, entityId);
String displayName = getDisplayName(entityId, entityClass);
boolean enabled = !disabledClassNames.contains(className);
entries.add(new EntityTypeEntry(displayName, className, modId, enabled));
}
// Sort by mod ID, then by display name
entries.sort((a, b) -> {
int modCompare = a.getModId().compareToIgnoreCase(b.getModId());
if (modCompare != 0) return modCompare;
return a.getDisplayName().compareToIgnoreCase(b.getDisplayName());
});
return entries;
}
@SuppressWarnings("unchecked")
private static String getModIdForEntity(Class<?> entityClass, String entityId) {
// Check EntityRegistry for mod entity entries
if (Entity.class.isAssignableFrom(entityClass)) {
EntityRegistry.EntityRegistration registration = EntityRegistry.instance()
.lookupModSpawn((Class<? extends Entity>) entityClass, false);
if (registration != null && registration.getContainer() != null) {
return registration.getContainer().getModId();
}
}
// Check if it's a vanilla entity (no dot in entity ID)
if (!entityId.contains(".")) {
return "minecraft";
}
// Extract mod ID from entity ID (format: modid.EntityName)
int dotIndex = entityId.indexOf('.');
if (dotIndex > 0) {
return entityId.substring(0, dotIndex);
}
return "unknown";
}
private static String getDisplayName(String entityId, Class<?> entityClass) {
// Use the simple class name, removing package
String simpleName = entityClass.getSimpleName();
if (simpleName.isEmpty()) {
// Anonymous class, use entity ID
return entityId;
}
return simpleName;
}
public static void load() {
if (configFile == null || !configFile.exists()) return;
disabledClassNames.clear();
enabledCache.clear();
try (BufferedReader reader = new BufferedReader(new FileReader(configFile))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) continue;
// Lines are entity class names that are DISABLED
disabledClassNames.add(line);
}
LOGGER.info("Loaded {} disabled entity types from config", disabledClassNames.size());
} catch (IOException e) {
LOGGER.warn("Failed to load entity light config: {}", e.getMessage());
}
}
public static void save() {
if (configFile == null) return;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(configFile))) {
writer.write("# Angelica Dynamic Lights - Disabled Entity Types");
writer.newLine();
writer.write("# Each line is a fully qualified class name of an entity type that is DISABLED.");
writer.newLine();
writer.write("# Remove a line to re-enable dynamic lighting for that entity type.");
writer.newLine();
writer.newLine();
List<String> sorted = new ArrayList<>(disabledClassNames);
Collections.sort(sorted);
for (String className : sorted) {
writer.write(className);
writer.newLine();
}
LOGGER.info("Saved {} disabled entity types to config", disabledClassNames.size());
} catch (IOException e) {
LOGGER.warn("Failed to save entity light config: {}", e.getMessage());
}
}
}
@@ -0,0 +1,20 @@
package com.gtnewhorizons.angelica.dynamiclights.config;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
public class EntityLightConfigStorage implements OptionStorage<EntityLightConfigStorage> {
public static final EntityLightConfigStorage INSTANCE = new EntityLightConfigStorage();
private EntityLightConfigStorage() {}
@Override
public EntityLightConfigStorage getData() {
return this;
}
@Override
public void save() {
EntityLightConfig.save();
}
}
@@ -0,0 +1,42 @@
package com.gtnewhorizons.angelica.dynamiclights.config;
import org.jetbrains.annotations.NotNull;
public class EntityTypeEntry {
private final String displayName;
private final String className;
private final String modId;
private boolean enabled;
public EntityTypeEntry(@NotNull String displayName, @NotNull String className, @NotNull String modId, boolean enabled) {
this.displayName = displayName;
this.className = className;
this.modId = modId;
this.enabled = enabled;
}
public String getDisplayName() {
return displayName;
}
public String getClassName() {
return className;
}
public String getModId() {
return modId;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return displayName + " (" + modId + ") [" + (enabled ? "ON" : "OFF") + "]";
}
}
@@ -0,0 +1,52 @@
package com.gtnewhorizons.angelica.glsm;
import org.embeddedt.embeddium.impl.render.chunk.fog.FogService;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
public class AngelicaFogService implements FogService {
private final float[] fogColorArray = new float[4];
@Override
public float getFogEnd() {
return GLStateManager.getFogState().getEnd();
}
@Override
public float getFogStart() {
return GLStateManager.getFogState().getStart();
}
@Override
public float getFogDensity() {
return GLStateManager.getFogState().getDensity();
}
@Override
public int getFogShapeIndex() {
return 0; // 1.7.10 only has one fog shape
}
@Override
public float getFogCutoff() {
return getFogEnd();
}
@Override
public float[] getFogColor() {
final var fogState = GLStateManager.getFogState();
final var color = fogState.getFogColor();
fogColorArray[0] = (float) color.x;
fogColorArray[1] = (float) color.y;
fogColorArray[2] = (float) color.z;
fogColorArray[3] = fogState.getFogAlpha();
return fogColorArray;
}
@Override
public ChunkFogMode getFogMode() {
if (!GLStateManager.getFogMode().isEnabled()) {
return ChunkFogMode.NONE;
}
return ChunkFogMode.fromGLMode(GLStateManager.getFogState().getFogMode());
}
}
@@ -0,0 +1,370 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.opengl.UniversalVAO;
import com.mitchej123.glsm.GLStateManagerService;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import java.nio.IntBuffer;
public class AngelicaGLStateManagerService implements GLStateManagerService {
private IntBuffer intArrayBuffer = BufferUtils.createIntBuffer(16);
private IntBuffer getIntArrayBuffer(int size) {
if (intArrayBuffer.capacity() < size) {
intArrayBuffer = BufferUtils.createIntBuffer(size);
}
intArrayBuffer.clear();
return intArrayBuffer;
}
@Override
public int getPriority() {
return 100;
}
// ===================== QUERY OPERATIONS =====================
@Override
public int glGetInteger(int pname) {
return GLStateManager.glGetInteger(pname);
}
@Override
public String glGetString(int pname) {
return GL11.glGetString(pname);
}
// ===================== FRAMEBUFFER OPERATIONS =====================
@Override
public int glGenFramebuffers() {
return GL30.glGenFramebuffers();
}
@Override
public void glDeleteFramebuffers(int framebuffer) {
GL30.glDeleteFramebuffers(framebuffer);
}
@Override
public void glBindFramebuffer(int target, int framebuffer) {
GL30.glBindFramebuffer(target, framebuffer);
}
@Override
public int glCheckFramebufferStatus(int target) {
return GL30.glCheckFramebufferStatus(target);
}
@Override
public void glFramebufferTexture2D(int target, int attachment, int textarget, int texture, int level) {
GL30.glFramebufferTexture2D(target, attachment, textarget, texture, level);
}
// ===================== SHADER OPERATIONS =====================
@Override
public int glCreateShader(int type) {
return GL20.glCreateShader(type);
}
@Override
public void glCompileShader(int shader) {
GL20.glCompileShader(shader);
}
@Override
public int glGetShaderi(int shader, int pname) {
return GL20.glGetShaderi(shader, pname);
}
@Override
public String glGetShaderInfoLog(int shader, int maxLength) {
return GL20.glGetShaderInfoLog(shader, maxLength);
}
@Override
public void glDeleteShader(int shader) {
GL20.glDeleteShader(shader);
}
@Override
public int glCreateProgram() {
return GL20.glCreateProgram();
}
@Override
public void glAttachShader(int program, int shader) {
GL20.glAttachShader(program, shader);
}
@Override
public void glLinkProgram(int program) {
GL20.glLinkProgram(program);
}
@Override
public int glGetProgrami(int program, int pname) {
return GL20.glGetProgrami(program, pname);
}
@Override
public void glUseProgram(int program) {
GLStateManager.glUseProgram(program);
}
@Override
public void glDeleteProgram(int program) {
GL20.glDeleteProgram(program);
}
// ===================== UNIFORM/ATTRIBUTE OPERATIONS =====================
@Override
public int glGetUniformLocation(int program, CharSequence name) {
return GL20.glGetUniformLocation(program, name);
}
@Override
public void glUniform1i(int location, int value) {
GL20.glUniform1i(location, value);
}
@Override
public int glGetAttribLocation(int program, CharSequence name) {
return GL20.glGetAttribLocation(program, name);
}
@Override
public void glBindAttribLocation(int program, int index, CharSequence name) {
GL20.glBindAttribLocation(program, index, name);
}
// ===================== VAO OPERATIONS =====================
@Override
public int glGenVertexArrays() {
return UniversalVAO.genVertexArrays();
}
@Override
public void glBindVertexArray(int array) {
GLStateManager.glBindVertexArray(array);
}
@Override
public void glDeleteVertexArrays(int array) {
UniversalVAO.deleteVertexArrays(array);
}
// ===================== BUFFER OPERATIONS =====================
@Override
public int glGenBuffers() {
return GL15.glGenBuffers();
}
@Override
public void glBindBuffer(int target, int buffer) {
GLStateManager.glBindBuffer(target, buffer);
}
@Override
public void glDeleteBuffers(int buffer) {
GL15.glDeleteBuffers(buffer);
}
// ===================== TEXTURE OPERATIONS =====================
@Override
public int glGenTextures() {
return GL11.glGenTextures();
}
@Override
public void glGenTextures(int[] textures) {
IntBuffer buffer = getIntArrayBuffer(textures.length);
GL11.glGenTextures(buffer);
buffer.get(textures);
}
@Override
public void glDeleteTextures(int texture) {
GLStateManager.glDeleteTextures(texture);
}
@Override
public void glDeleteTextures(int[] textures) {
IntBuffer buffer = getIntArrayBuffer(textures.length);
buffer.put(textures);
buffer.flip();
GLStateManager.glDeleteTextures(buffer);
}
@Override
public void glActiveTexture(int texture) {
GLStateManager.glActiveTexture(texture);
}
@Override
public int glGetTexLevelParameteri(int target, int level, int pname) {
return GLStateManager.glGetTexLevelParameteri(target, level, pname);
}
@Override
public int glGetTexLevelParameter(int target, int level, int pname) {
return GLStateManager.glGetTexLevelParameteri(target, level, pname);
}
@Override
public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) {
GL11.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
}
@Override
public void glPixelStorei(int pname, int param) {
GLStateManager.glPixelStorei(pname, param);
}
// ===================== STATE OPERATIONS =====================
@Override
public void enableCullFace() {
GLStateManager.enableCull();
}
@Override
public void disableCullFace() {
GLStateManager.disableCull();
}
@Override
public void enableBlend() {
GLStateManager.enableBlend();
}
@Override
public void disableBlend() {
GLStateManager.disableBlend();
}
@Override
public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
GLStateManager.tryBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void enableDepthTest() {
GLStateManager.enableDepthTest();
}
@Override
public void disableDepthTest() {
GLStateManager.disableDepthTest();
}
@Override
public void glDepthFunc(int func) {
GLStateManager.glDepthFunc(func);
}
@Override
public void glDepthMask(boolean flag) {
GLStateManager.glDepthMask(flag);
}
@Override
public void glViewport(int x, int y, int width, int height) {
GLStateManager.glViewport(x, y, width, height);
}
@Override
public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) {
GLStateManager.glColorMask(red, green, blue, alpha);
}
@Override
public void glClearColor(float red, float green, float blue, float alpha) {
GLStateManager.glClearColor(red, green, blue, alpha);
}
@Override
public void glClear(int mask) {
GLStateManager.glClear(mask);
}
// ===================== MOJANG ADDITIONS =====================
@Override
public void clear(int mask, boolean checkError) {
GLStateManager.glClear(mask);
}
@Override
public void bindTexture(int texture) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
@Override
public int getActiveTexture() {
return GLStateManager.getActiveTextureUnit() + GL13.GL_TEXTURE0;
}
@Override
public int getActiveTextureAccessor() {
return GLStateManager.getActiveTextureUnit();
}
@Override
public int getBoundTexture(int internalUnit) {
return GLStateManager.getBoundTextureForServerState(internalUnit);
}
@Override
public int getActiveBoundTexture() {
return GLStateManager.getBoundTextureForServerState();
}
@Override
public int getViewportWidth() {
return GLStateManager.getViewportState().width;
}
@Override
public int getViewportHeight() {
return GLStateManager.getViewportState().height;
}
@Override
public boolean getDepthStateMask() {
return GLStateManager.getDepthState().isEnabled();
}
@Override
public boolean isBlendEnabled() {
return GLStateManager.getBlendMode().isEnabled();
}
@Override
public void setBoundTexture(int unit, int texture) {
int currentUnit = GLStateManager.getActiveTextureUnit();
if (currentUnit != unit) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + unit);
}
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
if (currentUnit != unit) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + currentUnit);
}
}
@Override
public int getTextureBinding(int unit) {
return GLStateManager.getBoundTextureForServerState(unit);
}
}
@@ -0,0 +1,244 @@
package com.gtnewhorizons.angelica.glsm;
import com.mitchej123.glsm.RenderSystemService;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import java.nio.FloatBuffer;
public class AngelicaRenderSystemService implements RenderSystemService {
// Shader state (Mojang-specific, tracked here)
private final int[] shaderTextures = new int[16];
private final float[] shaderColor = {1f, 1f, 1f, 1f};
private final float[] shaderFogColor = {0f, 0f, 0f, 1f};
private float shaderFogStart = 0f;
private float shaderFogEnd = 0f;
private int fogShape = 0;
private float shaderLineWidth = 1f;
private final Matrix4f projectionMatrix = new Matrix4f();
private final FloatBuffer projectionMatrixBuffer = BufferUtils.createFloatBuffer(16);
@Override
public int getPriority() {
return 100;
}
// ===================== TEXTURE OPERATIONS =====================
@Override
public void glActiveTexture(int texture) {
GLStateManager.glActiveTexture(texture);
}
@Override
public void bindTexture(int texture) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
// ===================== STATE OPERATIONS =====================
@Override
public void enableCullFace() {
GLStateManager.enableCull();
}
@Override
public void disableCullFace() {
GLStateManager.disableCull();
}
@Override
public void enableBlend() {
GLStateManager.enableBlend();
}
@Override
public void disableBlend() {
GLStateManager.disableBlend();
}
@Override
public void defaultBlendFunc() {
GLStateManager.defaultBlendFunc();
}
@Override
public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
GLStateManager.tryBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void setUnknownBlendState() {
// No-op: Angelica tracks blend state accurately
}
@Override
public void enableDepthTest() {
GLStateManager.enableDepthTest();
}
@Override
public void disableDepthTest() {
GLStateManager.disableDepthTest();
}
@Override
public void depthFunc(int depthFunc) {
GLStateManager.glDepthFunc(depthFunc);
}
@Override
public void depthMask(boolean flag) {
GLStateManager.glDepthMask(flag);
}
@Override
public void glViewport(int x, int y, int width, int height) {
GLStateManager.glViewport(x, y, width, height);
}
@Override
public void glClearColor(float red, float green, float blue, float alpha) {
GLStateManager.glClearColor(red, green, blue, alpha);
}
@Override
public void clear(int mask, boolean checkError) {
GLStateManager.glClear(mask);
}
// ===================== UNIFORM OPERATIONS =====================
@Override
public void glUniform1i(int location, int value) {
GL20.glUniform1i(location, value);
}
@Override
public void glUniformMatrix3(int location, boolean transpose, FloatBuffer value) {
GL20.glUniformMatrix3(location, transpose, value);
}
@Override
public void glUniformMatrix4(int location, boolean transpose, FloatBuffer value) {
GL20.glUniformMatrix4(location, transpose, value);
}
// ===================== THREAD ASSERTIONS =====================
@Override
public void assertOnRenderThread() {
// No-op: 1.7.10 is single-threaded for rendering
}
@Override
public void assertOnRenderThreadOrInit() {
// No-op: 1.7.10 is single-threaded for rendering
}
// ===================== SHADER STATE =====================
@Override
public void setShaderTexture(int shaderTexture, int textureId) {
if (shaderTexture >= 0 && shaderTexture < 16) {
shaderTextures[shaderTexture] = textureId;
}
}
@Override
public int getShaderTexture(int shaderTexture) {
return (shaderTexture >= 0 && shaderTexture < 16) ? shaderTextures[shaderTexture] : 0;
}
@Override
public void setShaderColor(float red, float green, float blue, float alpha) {
shaderColor[0] = red;
shaderColor[1] = green;
shaderColor[2] = blue;
shaderColor[3] = alpha;
}
@Override
public float[] getShaderColor() {
return shaderColor.clone();
}
@Override
public void setShaderLineWidth(float lineWidth) {
shaderLineWidth = lineWidth;
}
@Override
public float getShaderLineWidth() {
return shaderLineWidth;
}
// ===================== FOG STATE =====================
@Override
public void setShaderFogColor(float red, float green, float blue, float alpha) {
shaderFogColor[0] = red;
shaderFogColor[1] = green;
shaderFogColor[2] = blue;
shaderFogColor[3] = alpha;
}
@Override
public float[] getShaderFogColor() {
return shaderFogColor.clone();
}
@Override
public void setShaderFogStart(float start) {
shaderFogStart = start;
}
@Override
public float getShaderFogStart() {
return shaderFogStart;
}
@Override
public void setShaderFogEnd(float end) {
shaderFogEnd = end;
}
@Override
public float getShaderFogEnd() {
return shaderFogEnd;
}
@Override
public void setFogShape(int shape) {
fogShape = shape;
}
@Override
public int getFogShape() {
return fogShape;
}
// ===================== PROJECTION MATRIX =====================
@Override
public Matrix4f getProjectionMatrix() {
return new Matrix4f(projectionMatrix);
}
@Override
public void setProjectionMatrixOrth(Matrix4f m) {
projectionMatrix.set(m);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
projectionMatrix.get(projectionMatrixBuffer);
projectionMatrixBuffer.rewind();
GLStateManager.glLoadMatrix(projectionMatrixBuffer);
}
@Override
public void setProjectionMatrixOrigin(Matrix4f m) {
setProjectionMatrixOrth(m);
}
}
@@ -1,18 +1,10 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor.BufferTransformOptimizer;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* Builds final command buffers from raw command buffers and compiled VBO data.
@@ -27,179 +19,49 @@ public final class CommandBufferBuilder {
* Accumulates MODELVIEW transforms and emits MultMatrix at barriers (draws, CallList).
* Uses mergedRanges where consecutive same-transform draws are combined.
*/
public static void buildOptimizedFromRawBuffer(
public static void buildFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
final CompiledLineBuffer compiledLineBuffer,
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
VertexBuffer[] ownedVbos,
int glListId,
List<AccumulatedDraw> accumulatedDraws,
CommandBuffer finalBuffer) {
// Build VBO index map for efficient lookup (no boxing)
final Object2IntMap<VertexBuffer> vboIndexMap = new Object2IntOpenHashMap<>();
vboIndexMap.defaultReturnValue(-1);
for (int i = 0; i < ownedVbos.length; i++) {
vboIndexMap.put(ownedVbos[i], i);
}
// Collect all merged draw ranges sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Buffer optimizer state
final BufferTransformOptimizer opt = new BufferTransformOptimizer();
rawBuffer.resetRead();
int cmdIndex = 0;
int rangeIndex = 0;
AccumulatedDraw draw;
while (rawBuffer.hasRemaining()) {
// Emit draw ranges at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) {
emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap);
}
// Read and process the command
final int opcode = rawBuffer.readInt();
CommandBufferProcessor.processCommandForOptimization(opcode, rawBuffer, opt, finalBuffer);
cmdIndex++;
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap);
}
// Emit residual transform if not identity
if (!opt.isIdentity()) {
opt.emitPendingTransform(finalBuffer);
}
}
/**
* Build commands without transform collapsing.
* Copies state commands directly (no transform optimization), but still uses
* merged draw ranges (draws already collapsed by format + transform in VBO compilation).
*/
public static void buildUnoptimizedFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
VertexBuffer[] ownedVbos,
CommandBuffer finalBuffer) {
// Build VBO index map for efficient lookup (no boxing)
final Object2IntMap<VertexBuffer> vboIndexMap = new Object2IntOpenHashMap<>();
vboIndexMap.defaultReturnValue(-1);
for (int i = 0; i < ownedVbos.length; i++) {
vboIndexMap.put(ownedVbos[i], i);
}
// Collect all merged draw ranges sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
rawBuffer.resetRead();
int cmdIndex = 0;
int rangeIndex = 0;
while (rawBuffer.hasRemaining()) {
// Emit draw ranges at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) {
final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++);
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
}
}
// Copy the command directly
CommandBufferProcessor.copyCommand(rawBuffer, finalBuffer);
// Emit draw ranges at this command position
while (rangeIndex < accumulatedDraws.size() && (draw = accumulatedDraws.get(rangeIndex)).commandIndex == cmdIndex) {
emitDrawRangeToBuffer(draw, finalBuffer, rangeIndex);
rangeIndex++;
}
cmdIndex++;
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++);
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
}
while (rangeIndex < accumulatedDraws.size()) {
emitDrawRangeToBuffer(accumulatedDraws.get(rangeIndex), finalBuffer, rangeIndex);
rangeIndex++;
}
}
/**
* Collect all draw ranges from compiled buffers, sorted by command index.
*/
static List<DrawRangeWithBuffer> collectDrawRanges(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
final List<DrawRangeWithBuffer> allRanges = new ArrayList<>();
// Add quad ranges
final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]);
for (int b = 0; b < quadBufferArray.length; b++) {
final CompiledFormatBuffer compiledBuffer = quadBufferArray[b];
final DrawRange[] ranges = compiledBuffer.mergedRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledBuffer.vbo(), compiledBuffer.flags().hasBrightness));
}
}
// Add immediate mode line ranges
if (compiledLineBuffer != null) {
final DrawRange[] ranges = compiledLineBuffer.mergedRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), false));
}
}
// Add tessellator primitive ranges (lines and triangles) - grouped by format
if (compiledPrimitiveBuffers != null && !compiledPrimitiveBuffers.isEmpty()) {
final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]);
for (int p = 0; p < primBufferArray.length; p++) {
final CompiledPrimitiveBuffers primBuffers = primBufferArray[p];
final boolean hasBrightness = primBuffers.flags().hasBrightness;
// Tessellator lines
if (primBuffers.hasLines()) {
final DrawRange[] ranges = primBuffers.lineMergedRanges();
final VertexBuffer vbo = primBuffers.lineVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, hasBrightness));
}
}
// Tessellator triangles
if (primBuffers.hasTriangles()) {
final DrawRange[] ranges = primBuffers.triangleMergedRanges();
final VertexBuffer vbo = primBuffers.triangleVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, hasBrightness));
}
}
}
}
allRanges.sort(Comparator.comparingInt(r -> r.range().commandIndex()));
return allRanges;
}
/**
* Emit a draw range to the output buffer, with transform if needed.
*/
private static void emitDrawRangeToBuffer(
DrawRangeWithBuffer drb,
BufferTransformOptimizer opt,
AccumulatedDraw draw,
CommandBuffer out,
Object2IntMap<VertexBuffer> vboIndexMap) {
// Emit transform to reach the draw's expected transform
opt.emitTransformTo(out, drb.range().transform());
int vboIdx) {
if (draw.restoreData != null) {
out.writeDrawRangeRestore(vboIdx, draw.restoreData);
return;
}
// Write the draw range command
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
out.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
}
out.writeDrawRange(vboIdx);
}
}
@@ -1,23 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* A compiled VBO with its associated draw ranges.
* All ranges reference vertices within this single VBO.
* <p>
* Contains two range arrays:
* <ul>
* <li><b>mergedRanges</b>: For optimized path - consecutive same-transform draws merged</li>
* <li><b>perDrawRanges</b>: For unoptimized path - 1:1 with original draws</li>
* </ul>
*/
@Desugar
public record CompiledFormatBuffer(
VertexBuffer vbo,
CapturingTessellator.Flags flags,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
) {}
@@ -1,21 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* A compiled VBO containing all line geometry with associated draw ranges.
* All ranges reference vertices within this single VBO.
* <p>
* Contains two range arrays:
* <ul>
* <li><b>mergedRanges</b>: For optimized path - consecutive same-transform draws merged</li>
* <li><b>perDrawRanges</b>: For unoptimized path - 1:1 with original draws</li>
* </ul>
*/
@Desugar
record CompiledLineBuffer(
VertexBuffer vbo,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
) {}
@@ -1,31 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* Compiled VBOs containing tessellator primitives (lines and triangles) for a single vertex format.
* Separate VBOs are used for lines (GL_LINES) and triangles (GL_TRIANGLES) since they have different draw modes.
* <p>
* Contains range arrays for both optimized (merged) and unoptimized (per-draw) paths.
* Similar to CompiledFormatBuffer but handles primitives instead of quads.
*/
@Desugar
record CompiledPrimitiveBuffers(
CapturingTessellator.Flags flags,
VertexBuffer lineVbo,
DrawRange[] lineMergedRanges,
DrawRange[] linePerDrawRanges,
VertexBuffer triangleVbo,
DrawRange[] triangleMergedRanges,
DrawRange[] trianglePerDrawRanges
) {
public boolean hasLines() {
return lineVbo != null;
}
public boolean hasTriangles() {
return triangleVbo != null;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,11 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import org.joml.Matrix4f;
/**
* Represents a vertex range within a shared VBO, along with its transform.
* Used during format-based batching to track where each draw's vertices are stored.
*/
@Desugar
record DrawRange(int startVertex, int vertexCount, Matrix4f transform, int commandIndex) {}
@@ -1,12 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* Helper record pairing a DrawRange with its VBO and brightness flag.
* Used for sorting ranges by command index while retaining VBO reference.
* Works for both quad ranges (from CompiledFormatBuffer) and line ranges (from CompiledLineBuffer).
*/
@Desugar
record DrawRangeWithBuffer(DrawRange range, VertexBuffer vbo, boolean hasBrightness) {}
@@ -1,96 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import org.joml.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates geometry for a single vertex format during display list compilation.
* All draws with the same format are collected here, then compiled into a single VBO.
* <p>
* Tracks two types of ranges:
* <ul>
* <li><b>mergedRanges</b>: Consecutive same-transform draws merged for optimized path</li>
* <li><b>perDrawRanges</b>: One range per input draw for unoptimized path (1:1 with addDraw calls)</li>
* </ul>
*/
class FormatBuffer {
final CapturingTessellator.Flags flags;
final List<ModelQuadViewMutable> allQuads = new ArrayList<>();
// Merged ranges for optimized path (consecutive same-transform draws combined)
final List<DrawRange> mergedRanges = new ArrayList<>();
// Per-draw ranges for unoptimized path (1:1 with input draws)
final List<DrawRange> perDrawRanges = new ArrayList<>();
int currentVertexOffset = 0;
// Track the current range being built for merging consecutive same-transform draws
private int pendingStartVertex = -1;
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
FormatBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
}
/**
* Add a draw to this format buffer.
* Tracks both merged (for optimized) and per-draw (for unoptimized) ranges.
*/
void addDraw(AccumulatedDraw draw) {
int vertexCount = draw.quads.size() * 4; // 4 vertices per quad
// Always track per-draw range for unoptimized path
perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path
if (pendingTransform != null && pendingTransform.equals(draw.transform)) {
// Extend the pending range
pendingVertexCount += vertexCount;
} else {
// Flush pending range if any
flushPendingRange();
// Start new pending range
pendingStartVertex = currentVertexOffset;
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
}
allQuads.addAll(draw.quads);
currentVertexOffset += vertexCount;
}
private void flushPendingRange() {
if (pendingTransform != null) {
mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex));
pendingTransform = null;
}
}
/**
* Compile all accumulated quads into a single VBO.
* @return The compiled buffer with VBO and both range types
*/
CompiledFormatBuffer finish() {
// Flush any remaining pending range
flushPendingRange();
VertexBuffer vbo = DisplayListManager.compileQuads(allQuads, flags);
return new CompiledFormatBuffer(
vbo,
flags,
mergedRanges.toArray(new DrawRange[0]),
perDrawRanges.toArray(new DrawRange[0])
);
}
}
@@ -19,9 +19,6 @@ import org.lwjgl.opengl.GL43;
import org.lwjgl.opengl.KHRDebug;
import org.lwjgl.opengl.KHRDebugCallback;
import java.io.PrintStream;
import java.util.function.Consumer;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import static org.lwjgl.opengl.ARBDebugOutput.glDebugMessageCallbackARB;
@@ -35,20 +32,9 @@ public final class GLDebug {
LOGGER.warn("setupDebugMessageCallback called from non-main thread!");
return 0;
}
return setupDebugMessageCallback(System.err);
return setupDebugMessageCallbackImpl();
}
private static void trace(Consumer<String> output) {
/*
* We can not just use a fixed stacktrace element offset, because some methods
* are intercepted and some are not. So, check the package name.
*/
StackTraceElement[] elems = filterStackTrace(new Throwable(), 4).getStackTrace();
for (StackTraceElement ste : elems) {
output.accept(ste.toString());
}
}
public static Throwable filterStackTrace(Throwable throwable, int offset) {
StackTraceElement[] elems = throwable.getStackTrace();
StackTraceElement[] filtered = new StackTraceElement[elems.length];
@@ -66,36 +52,48 @@ public final class GLDebug {
return throwable;
}
public static void printTrace(PrintStream stream) {
trace(new Consumer<String>() {
boolean first = true;
private static String buildStackTrace() {
StackTraceElement[] elems = filterStackTrace(new Throwable(), 4).getStackTrace();
StringBuilder sb = new StringBuilder();
for (StackTraceElement elem : elems) {
sb.append("\n\t").append(elem.toString());
}
return sb.toString();
}
public void accept(String str) {
if (first) {
printDetail(stream, "Stacktrace", str);
first = false;
} else {
printDetailLine(stream, "Stacktrace", str);
}
}
});
private static void logDebugMessage(int id, String source, String type, String severity, String message) {
String fullMessage = String.format("[GL] %s %s (0x%X) from %s: %s%s", severity, type, id, source, message, buildStackTrace());
if ("HIGH".equals(severity)) {
LOGGER.error(fullMessage);
} else if ("MEDIUM".equals(severity)) {
LOGGER.warn(fullMessage);
} else {
LOGGER.info(fullMessage);
}
}
private static void logDebugMessageAMD(int id, String category, String severity, String message) {
String fullMessage = String.format("[GL] %s %s (0x%X): %s%s", severity, category, id, message, buildStackTrace());
if ("HIGH".equals(severity)) {
LOGGER.error(fullMessage);
} else if ("MEDIUM".equals(severity)) {
LOGGER.warn(fullMessage);
} else {
LOGGER.info(fullMessage);
}
}
/**
* Sets up debug callbacks
* @return 0 for failure, 1 for success, 2 for restart required.
*/
public static int setupDebugMessageCallback(PrintStream stream) {
private static int setupDebugMessageCallbackImpl() {
if (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_KHR_debug) {
LOGGER.info("[GL] Using OpenGL 4.3 for error logging.");
KHRDebugCallback proc = new KHRDebugCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] OpenGL debug message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Source", getDebugSource(source));
printDetail(stream, "Type", getDebugType(type));
printDetail(stream, "Severity", getDebugSeverity(severity));
printDetail(stream, "Message", message);
printTrace(stream);
final KHRDebugCallback proc = new KHRDebugCallback((source, type, id, severity, message) -> {
logDebugMessage(id, getDebugSource(source), getDebugType(type), getDebugSeverity(severity), message);
});
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
@@ -103,6 +101,9 @@ public final class GLDebug {
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_NOTIFICATION, null, false);
GL43.glDebugMessageCallback(proc);
// Enable synchronous debug output so errors are reported immediately with accurate stack traces
GL11.glEnable(GL43.GL_DEBUG_OUTPUT_SYNCHRONOUS);
if ((GL11.glGetInteger(GL30.GL_CONTEXT_FLAGS) & GL43.GL_CONTEXT_FLAG_DEBUG_BIT) == 0) {
LOGGER.warn("[GL] Warning: A non-debug context may not produce any debug output.");
GL11.glEnable(GL43.GL_DEBUG_OUTPUT);
@@ -111,30 +112,22 @@ public final class GLDebug {
return 1;
} else if (GLStateManager.capabilities.GL_ARB_debug_output) {
LOGGER.info("[GL] Using ARB_debug_output for error logging.");
ARBDebugOutputCallback proc = new ARBDebugOutputCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] ARB_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Source", getSourceARB(source));
printDetail(stream, "Type", getTypeARB(type));
printDetail(stream, "Severity", getSeverityARB(severity));
printDetail(stream, "Message", message);
printTrace(stream);
final ARBDebugOutputCallback proc = new ARBDebugOutputCallback((source, type, id, severity, message) -> {
logDebugMessage(id, getSourceARB(source), getTypeARB(type), getSeverityARB(severity), message);
});
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_LOW, null, false);
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_NOTIFICATION, null, false);
ARBDebugOutput.glDebugMessageCallbackARB(proc);
// Enable synchronous debug output so errors are reported immediately with accurate stack traces
GL11.glEnable(ARBDebugOutput.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
return 1;
} else if (GLStateManager.capabilities.GL_AMD_debug_output) {
LOGGER.info("[GL] Using AMD_debug_output for error logging.");
AMDDebugOutputCallback proc = new AMDDebugOutputCallback((id, category, severity, message) -> {
stream.println("[LWJGL] AMD_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Category", getCategoryAMD(category));
printDetail(stream, "Severity", getSeverityAMD(severity));
printDetail(stream, "Message", message);
printTrace(stream);
final AMDDebugOutputCallback proc = new AMDDebugOutputCallback((id, category, severity, message) -> {
logDebugMessageAMD(id, getCategoryAMD(category), getSeverityAMD(severity), message);
});
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
@@ -170,17 +163,6 @@ public final class GLDebug {
}
}
private static void printDetail(PrintStream stream, String type, String message) {
stream.printf("\t%s: %s\n", type, message);
}
private static void printDetailLine(PrintStream stream, String type, String message) {
stream.append(" ");
for (int i = 0; i < type.length(); i++) {
stream.append(" ");
}
stream.append(message).append("\n");
}
private static String getDebugSource(int source) {
return switch (source) {
@@ -571,6 +553,57 @@ public final class GLDebug {
};
}
public static String getFramebufferStatusName(int status) {
return switch (status) {
case GL30.GL_FRAMEBUFFER_COMPLETE -> "COMPLETE";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT -> "INCOMPLETE_ATTACHMENT";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT -> "INCOMPLETE_MISSING_ATTACHMENT";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER -> "INCOMPLETE_DRAW_BUFFER";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER -> "INCOMPLETE_READ_BUFFER";
case GL30.GL_FRAMEBUFFER_UNSUPPORTED -> "UNSUPPORTED";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE -> "INCOMPLETE_MULTISAMPLE";
case 0 -> "NO_FRAMEBUFFER_BOUND";
default -> String.format("UNKNOWN(0x%X)", status);
};
}
public static String getInternalFormatName(int format) {
return switch (format) {
// Basic
case GL11.GL_RGBA -> "RGBA";
case GL11.GL_RGB -> "RGB";
// 8-bit normalized
case GL30.GL_R8 -> "R8";
case GL30.GL_RG8 -> "RG8";
case GL11.GL_RGB8 -> "RGB8";
case GL11.GL_RGBA8 -> "RGBA8";
// 8-bit signed normalized
case 0x8F94 -> "R8_SNORM";
case 0x8F95 -> "RG8_SNORM";
case 0x8F96 -> "RGB8_SNORM";
case 0x8F97 -> "RGBA8_SNORM";
// 16-bit normalized
case GL30.GL_R16 -> "R16";
case GL30.GL_RG16 -> "RG16";
case GL11.GL_RGB16 -> "RGB16";
case GL11.GL_RGBA16 -> "RGBA16";
// 16-bit float
case GL30.GL_R16F -> "R16F";
case GL30.GL_RG16F -> "RG16F";
case GL30.GL_RGB16F -> "RGB16F";
case GL30.GL_RGBA16F -> "RGBA16F";
// 32-bit float
case GL30.GL_R32F -> "R32F";
case GL30.GL_RG32F -> "RG32F";
case GL30.GL_RGB32F -> "RGB32F";
case GL30.GL_RGBA32F -> "RGBA32F";
// Packed
case GL30.GL_R11F_G11F_B10F -> "R11F_G11F_B10F";
case GL11.GL_RGB10_A2 -> "RGB10_A2";
default -> String.format("0x%X", format);
};
}
private static DebugState debugState;
private interface DebugState {
File diff suppressed because it is too large. Load diff
@@ -1,125 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates line geometry during display list compilation.
* All line draws are collected here, then compiled into a single VBO.
* <p>
* Lines all use the same format (POSITION_COLOR), so no format-based grouping needed.
* <p>
* Tracks two types of ranges:
* <ul>
* <li><b>mergedRanges</b>: Consecutive same-transform draws merged for optimized path</li>
* <li><b>perDrawRanges</b>: One range per input draw for unoptimized path (1:1 with addDraw calls)</li>
* </ul>
*/
class LineBuffer {
final List<ImmediateModeRecorder.LineVertex> allVertices = new ArrayList<>();
// Merged ranges for optimized path (consecutive same-transform draws combined)
final List<DrawRange> mergedRanges = new ArrayList<>();
// Per-draw ranges for unoptimized path (1:1 with input draws)
final List<DrawRange> perDrawRanges = new ArrayList<>();
int currentVertexOffset = 0;
// Track the current range being built for merging consecutive same-transform draws
private int pendingStartVertex = -1;
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
/**
* Add a line draw to this buffer.
* Tracks both merged (for optimized) and per-draw (for unoptimized) ranges.
*/
void addDraw(AccumulatedLineDraw draw) {
int vertexCount = draw.lines.size(); // Each LineVertex is one vertex, lines come in pairs
// Always track per-draw range for unoptimized path
perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path
if (pendingTransform != null && pendingTransform.equals(draw.transform)) {
// Extend the pending range
pendingVertexCount += vertexCount;
} else {
// Flush pending range if any
flushPendingRange();
// Start new pending range
pendingStartVertex = currentVertexOffset;
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
}
allVertices.addAll(draw.lines);
currentVertexOffset += vertexCount;
}
private void flushPendingRange() {
if (pendingTransform != null) {
mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex));
pendingTransform = null;
}
}
/**
* Compile all accumulated line vertices into a single VBO.
* @return The compiled buffer with VBO and both range types, or null if empty
*/
CompiledLineBuffer finish() {
if (allVertices.isEmpty()) {
return null;
}
// Flush any remaining pending range
flushPendingRange();
VertexBuffer vbo = compileLinesToVBO(allVertices);
return new CompiledLineBuffer(
vbo,
mergedRanges.toArray(new DrawRange[0]),
perDrawRanges.toArray(new DrawRange[0])
);
}
/**
* Compile line vertices into a VertexBuffer (VAO or VBO).
* Lines use POSITION_COLOR format (x, y, z, color).
*/
private static VertexBuffer compileLinesToVBO(List<ImmediateModeRecorder.LineVertex> lines) {
final VertexFormat format = DefaultVertexFormat.POSITION_COLOR;
final VertexBuffer vao = VAOManager.createVAO(format, GL11.GL_LINES);
// POSITION_COLOR format: 3 floats (12 bytes) + 4 bytes color = 16 bytes per vertex
final int vertexSize = format.getVertexSize();
final ByteBuffer buffer = org.lwjgl.BufferUtils.createByteBuffer(vertexSize * lines.size());
for (ImmediateModeRecorder.LineVertex v : lines) {
buffer.putFloat(v.x);
buffer.putFloat(v.y);
buffer.putFloat(v.z);
buffer.putInt(v.color);
}
buffer.flip();
vao.upload(buffer);
return vao;
}
}
@@ -1,12 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
/**
* Result of building an optimized display list.
* Contains both the commands and the shared VBOs that need lifecycle management.
*/
@Desugar
record OptimizedListResult(DisplayListCommand[] commands, VertexBuffer[] ownedVbos) {}
@@ -4,20 +4,32 @@ import com.gtnewhorizons.angelica.glsm.dsa.DSAARB;
import com.gtnewhorizons.angelica.glsm.dsa.DSAAccess;
import com.gtnewhorizons.angelica.glsm.dsa.DSACore;
import com.gtnewhorizons.angelica.glsm.dsa.DSAUnsupported;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Vector3i;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBBufferStorage;
import org.lwjgl.opengl.ARBClearBufferObject;
import org.lwjgl.opengl.ARBClearTexture;
import org.lwjgl.opengl.ARBShaderImageLoadStore;
import org.lwjgl.opengl.ARBShaderStorageBufferObject;
import org.lwjgl.opengl.EXTShaderImageLoadStore;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL33;
import org.lwjgl.opengl.GL40;
import org.lwjgl.opengl.GL42;
import org.lwjgl.opengl.GL43;
import org.lwjgl.opengl.GL44;
import org.lwjgl.opengl.NVXGpuMemoryInfo;
import net.coderbot.iris.gl.shader.StandardMacros;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
@@ -31,6 +43,19 @@ public class RenderSystem {
private static final Logger LOGGER = LogManager.getLogger("RenderSystem");
private static DSAAccess dsaState;
private static boolean supportsCompute;
private static boolean supportsImageLoadStore;
private static boolean supportsSSBO;
private static boolean supportsBufferStorage;
private static boolean supportsClearTexture;
private static boolean supportsTesselation;
private static boolean supportsSamplerObjects;
private static int maxImageUnits;
private static int maxSSBOBindings;
private static int maxGlslVersion;
private static boolean supportsGpuShader4;
// Sampler object state tracking (null if unsupported)
private static int[] samplers;
private RenderSystem() {}
@@ -54,6 +79,51 @@ public class RenderSystem {
}
supportsCompute = supportsCompute();
supportsTesselation = GLStateManager.capabilities.GL_ARB_tessellation_shader || GLStateManager.capabilities.OpenGL40;
supportsImageLoadStore = GLStateManager.capabilities.OpenGL42 || GLStateManager.capabilities.GL_ARB_shader_image_load_store || GLStateManager.capabilities.GL_EXT_shader_image_load_store;
supportsSSBO = GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_shader_storage_buffer_object;
supportsBufferStorage = GLStateManager.capabilities.OpenGL44 || GLStateManager.capabilities.GL_ARB_buffer_storage;
supportsClearTexture = GLStateManager.capabilities.OpenGL44 || GLStateManager.capabilities.GL_ARB_clear_texture;
// Cache maximum image units
if (supportsImageLoadStore) {
if (GLStateManager.capabilities.OpenGL42) {
maxImageUnits = GL11.glGetInteger(GL42.GL_MAX_IMAGE_UNITS);
} else if (GLStateManager.capabilities.GL_ARB_shader_image_load_store) {
maxImageUnits = GL11.glGetInteger(ARBShaderImageLoadStore.GL_MAX_IMAGE_UNITS);
} else {
maxImageUnits = GL11.glGetInteger(EXTShaderImageLoadStore.GL_MAX_IMAGE_UNITS_EXT);
}
} else {
maxImageUnits = 0;
}
// Cache maximum SSBO bindings
if (supportsSSBO) {
if (GLStateManager.capabilities.OpenGL43) {
maxSSBOBindings = GL11.glGetInteger(GL43.GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS);
} else {
maxSSBOBindings = GL11.glGetInteger(ARBShaderStorageBufferObject.GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS);
}
} else {
maxSSBOBindings = 0;
}
// Check for sampler objects support (GL 3.3+ or ARB extension)
supportsSamplerObjects = GLStateManager.capabilities.OpenGL33
|| GLStateManager.capabilities.GL_ARB_sampler_objects;
if (supportsSamplerObjects) {
samplers = new int[GL11.glGetInteger(GL20.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS)];
}
maxGlslVersion = Integer.parseInt(StandardMacros.getGlVersion(GL20.GL_SHADING_LANGUAGE_VERSION));
supportsGpuShader4 = GLStateManager.capabilities.GL_EXT_gpu_shader4;
LOGGER.info("Max GLSL version: {}, GPU Shader4: {}", maxGlslVersion, supportsGpuShader4);
LOGGER.info("Image Load/Store: {}, Max Image Units: {}", supportsImageLoadStore, maxImageUnits);
LOGGER.info("SSBO: {}, Max SSBO Bindings: {}", supportsSSBO, maxSSBOBindings);
LOGGER.info("Buffer Storage: {}, Clear Texture: {}, Sampler Objects: {}", supportsBufferStorage, supportsClearTexture, supportsSamplerObjects);
}
public static void generateMipmaps(int texture, int mipmapTarget) {
@@ -65,8 +135,11 @@ public class RenderSystem {
}
public static void texImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLStateManager.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
GLStateManager.glBindTexture(target, texture);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
if (target == GL11.GL_TEXTURE_2D && level == 0) {
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
}
public static void uniformMatrix4fv(int location, boolean transpose, FloatBuffer matrix) {
@@ -74,7 +147,7 @@ public class RenderSystem {
}
public static void copyTexImage2D(int target, int level, int internalFormat, int x, int y, int width, int height, int border) {
GL11.glCopyTexImage2D(target, level, internalFormat, x, y, width, height, border);
GLStateManager.glCopyTexImage2D(target, level, internalFormat, x, y, width, height, border);
}
public static void uniform1f(int location, float v0) {
@@ -147,6 +220,17 @@ public class RenderSystem {
dsaState.textureSubImage2D(texture, target, level, xoffset, yoffset, width, height, format, type, pixels);
}
public static void texImage1D(int texture, int target, int level, int internalformat, int width, int border, int format, int type, ByteBuffer pixels) {
GL11.glBindTexture(target, texture);
GL11.glTexImage1D(target, level, internalformat, width, border, format, type, pixels);
}
public static void texImage3D(int texture, int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, ByteBuffer pixels) {
GL11.glBindTexture(target, texture);
GL12.glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels);
}
public static String getProgramInfoLog(int program) {
return GL20.glGetProgramInfoLog(program, GL20.glGetProgrami(program, GL20.GL_INFO_LOG_LENGTH));
}
@@ -195,6 +279,10 @@ public class RenderSystem {
return dsaState.getTexParameteri(texture, target, pname);
}
public static int getTexLevelParameteri(int texture, int level, int pname) {
return dsaState.getTexLevelParameteri(texture, level, pname);
}
public static void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) {
if (GLStateManager.capabilities.OpenGL42) {
GL42.glBindImageTexture(unit, texture, level, layered, layer, access, format);
@@ -204,13 +292,27 @@ public class RenderSystem {
}
public static int getMaxImageUnits() {
if (GLStateManager.capabilities.OpenGL42) {
return GL11.glGetInteger(GL42.GL_MAX_IMAGE_UNITS);
} else if (GLStateManager.capabilities.GL_EXT_shader_image_load_store) {
return GL11.glGetInteger(EXTShaderImageLoadStore.GL_MAX_IMAGE_UNITS_EXT);
} else {
return 0;
}
return maxImageUnits;
}
public static boolean supportsImageLoadStore() {
return supportsImageLoadStore;
}
public static boolean supportsSSBO() {
return supportsSSBO;
}
public static boolean supportsBufferStorage() {
return supportsBufferStorage;
}
public static boolean supportsClearTexture() {
return supportsClearTexture;
}
public static int getMaxSSBOBindings() {
return maxSSBOBindings;
}
public static void getProgramiv(int program, int value, IntBuffer storage) {
@@ -225,6 +327,14 @@ public class RenderSystem {
GL43.glDispatchCompute(workGroups.x, workGroups.y, workGroups.z);
}
public static void dispatchComputeIndirect(long offset) {
GL43.glDispatchComputeIndirect(offset);
}
public static void bindBuffer(int target, int buffer) {
GLStateManager.glBindBuffer(target, buffer);
}
public static void memoryBarrier(int barriers) {
if (supportsCompute) {
GL42.glMemoryBarrier(barriers);
@@ -237,10 +347,12 @@ public class RenderSystem {
public static void disableBufferBlend(int buffer) {
GL30.glDisablei(GL11.GL_BLEND, buffer);
GLStateManager.getBlendMode().setUnknownState();
}
public static void enableBufferBlend(int buffer) {
GL30.glEnablei(GL11.GL_BLEND, buffer);
GLStateManager.getBlendMode().setUnknownState();
}
public static void blendFuncSeparatei(int buffer, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
@@ -251,19 +363,23 @@ public class RenderSystem {
dsaState.bindTextureToUnit(unit, texture);
}
public static void bindTextureToUnit(int target, int unit, int texture) {
dsaState.bindTextureToUnit(target, unit, texture);
}
public static final FloatBuffer PROJECTION_MATRIX_BUFFER = BufferUtils.createFloatBuffer(16);
public static void setupProjectionMatrix(Matrix4f matrix) {
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glPushMatrix();
matrix.get(0, PROJECTION_MATRIX_BUFFER);
GL11.glLoadMatrix(PROJECTION_MATRIX_BUFFER);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadMatrix(PROJECTION_MATRIX_BUFFER);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
public static void restoreProjectionMatrix() {
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glPopMatrix();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
}
public static void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2, int bufferChoice, int filter) {
@@ -286,4 +402,122 @@ public class RenderSystem {
return false;
}
}
public static int createBuffers() {
return GL15.glGenBuffers();
}
public static void bindBufferBase(int target, int index, int buffer) {
GL30.glBindBufferBase(target, index, buffer);
}
public static void bufferStorage(int target, long size, int flags) {
if (GLStateManager.capabilities.OpenGL44) {
GL44.glBufferStorage(target, size, flags);
} else if (GLStateManager.capabilities.GL_ARB_buffer_storage) {
ARBBufferStorage.glBufferStorage(target, size, flags);
} else {
// Fallback: use mutable storage
GL15.glBufferData(target, size, GL15.GL_DYNAMIC_DRAW);
}
}
public static void clearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, int[] data) {
final ByteBuffer buf = BufferUtils.createByteBuffer(data.length * 4);
buf.asIntBuffer().put(data);
if (GLStateManager.capabilities.OpenGL43) {
GL43.glClearBufferSubData(target, internalFormat, offset, size, format, type, buf);
} else if (GLStateManager.capabilities.GL_ARB_clear_buffer_object) {
ARBClearBufferObject.glClearBufferSubData(target, internalFormat, offset, size, format, type, buf);
}
}
public static void deleteBuffers(int buffer) {
GL15.glDeleteBuffers(buffer);
}
public static long getVRAM() {
if (GLStateManager.capabilities.GL_NVX_gpu_memory_info) {
return GL11.glGetInteger(NVXGpuMemoryInfo.GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX) * 1024L;
} else {
// Default to 4GB if we can't query VRAM
return 4294967296L;
}
}
public static void clearTexImage(int texture, int target, int level, int format, int type) {
if (GLStateManager.capabilities.OpenGL44) {
GL44.glClearTexImage(texture, level, format, type, (ByteBuffer) null);
} else {
ARBClearTexture.glClearTexImage(texture, level, format, type, (ByteBuffer) null);
}
}
public static void textureStorage1D(int texture, int target, int levels, int internalFormat, int width) {
dsaState.textureStorage1D(texture, target, levels, internalFormat, width);
}
public static void textureStorage2D(int texture, int target, int levels, int internalFormat, int width, int height) {
dsaState.textureStorage2D(texture, target, levels, internalFormat, width, height);
}
public static void textureStorage3D(int texture, int target, int levels, int internalFormat, int width, int height, int depth) {
dsaState.textureStorage3D(texture, target, levels, internalFormat, width, height, depth);
}
public static int getMaxGlslVersion() {
return maxGlslVersion;
}
public static boolean supportsGpuShader4() {
return supportsGpuShader4;
}
public static boolean supportsSnormFormats() {
return GLStateManager.capabilities.OpenGL31;
}
public static boolean supportsPackedFloatRenderable() {
return GLStateManager.capabilities.OpenGL30 && maxGlslVersion >= 130;
}
public static boolean supportsTesselation() {
return supportsTesselation;
}
public static boolean supportsSamplerObjects() {
return supportsSamplerObjects;
}
public static int genSampler() {
if (!supportsSamplerObjects) return 0;
return GL33.glGenSamplers();
}
public static void destroySampler(int sampler) {
if (!supportsSamplerObjects || sampler == 0) return;
GL33.glDeleteSamplers(sampler);
}
public static void samplerParameteri(int sampler, int pname, int param) {
if (!supportsSamplerObjects || sampler == 0) return;
GL33.glSamplerParameteri(sampler, pname, param);
}
public static void bindSamplerToUnit(int unit, int sampler) {
if (!supportsSamplerObjects) return;
if (samplers[unit] == sampler) return;
GL33.glBindSampler(unit, sampler);
samplers[unit] = sampler;
}
public static void unbindAllSamplers() {
if (!supportsSamplerObjects) return;
for (int i = 0; i < samplers.length; i++) {
if (samplers[i] != 0) {
GL33.glBindSampler(i, 0);
samplers[i] = 0;
}
}
}
}
@@ -1,228 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates tessellator primitives (lines, triangles) for a single vertex format during display list compilation.
* Similar to FormatBuffer but handles ModelPrimitiveView instances instead of quads.
* <p>
* Unlike LineBuffer which handles ImmediateModeRecorder.LineVertex (fixed 16-byte: pos+color),
* this handles ModelLine/ModelTriangle from the tessellator with format-optimized vertex size.
* <p>
* Primitives are separated by draw mode (GL_LINES, GL_TRIANGLES) into separate VBOs.
*/
class TessellatorPrimitiveBuffer {
final CapturingTessellator.Flags flags;
// Accumulated primitives separated by type
final List<ModelLine> allLines = new ArrayList<>();
final List<ModelTriangle> allTriangles = new ArrayList<>();
// Ranges for lines
final List<DrawRange> lineMergedRanges = new ArrayList<>();
final List<DrawRange> linePerDrawRanges = new ArrayList<>();
int currentLineVertexOffset = 0;
private int pendingLineStartVertex = -1;
private int pendingLineVertexCount = 0;
private Matrix4f pendingLineTransform = null;
private int pendingLineCommandIndex = -1;
// Ranges for triangles
final List<DrawRange> triangleMergedRanges = new ArrayList<>();
final List<DrawRange> trianglePerDrawRanges = new ArrayList<>();
int currentTriangleVertexOffset = 0;
private int pendingTriangleStartVertex = -1;
private int pendingTriangleVertexCount = 0;
private Matrix4f pendingTriangleTransform = null;
private int pendingTriangleCommandIndex = -1;
TessellatorPrimitiveBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
}
/**
* Add a primitive draw to this buffer.
* Separates lines and triangles, tracking ranges for both merged and per-draw paths.
*/
void addDraw(AccumulatedPrimitiveDraw draw) {
final List<ModelPrimitiveView> primitives = draw.primitives;
final int size = primitives.size();
// Single pass: count and collect primitives by type
int lineCount = 0;
int triangleCount = 0;
for (int i = 0; i < size; i++) {
final ModelPrimitiveView prim = primitives.get(i);
if (prim instanceof ModelLine ml) {
allLines.add(ml);
lineCount++;
} else if (prim instanceof ModelTriangle mt) {
allTriangles.add(mt);
triangleCount++;
}
}
// Process lines
if (lineCount > 0) {
final int lineVertexCount = lineCount * 2; // 2 vertices per line
linePerDrawRanges.add(new DrawRange(currentLineVertexOffset, lineVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path
if (pendingLineTransform != null && pendingLineTransform.equals(draw.transform)) {
pendingLineVertexCount += lineVertexCount;
} else {
flushPendingLineRange();
pendingLineStartVertex = currentLineVertexOffset;
pendingLineVertexCount = lineVertexCount;
pendingLineTransform = new Matrix4f(draw.transform);
pendingLineCommandIndex = draw.commandIndex;
}
currentLineVertexOffset += lineVertexCount;
}
// Process triangles
if (triangleCount > 0) {
final int triangleVertexCount = triangleCount * 3; // 3 vertices per triangle
trianglePerDrawRanges.add(new DrawRange(currentTriangleVertexOffset, triangleVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path
if (pendingTriangleTransform != null && pendingTriangleTransform.equals(draw.transform)) {
pendingTriangleVertexCount += triangleVertexCount;
} else {
flushPendingTriangleRange();
pendingTriangleStartVertex = currentTriangleVertexOffset;
pendingTriangleVertexCount = triangleVertexCount;
pendingTriangleTransform = new Matrix4f(draw.transform);
pendingTriangleCommandIndex = draw.commandIndex;
}
currentTriangleVertexOffset += triangleVertexCount;
}
}
private void flushPendingLineRange() {
if (pendingLineTransform != null) {
lineMergedRanges.add(new DrawRange(pendingLineStartVertex, pendingLineVertexCount, pendingLineTransform, pendingLineCommandIndex));
pendingLineTransform = null;
}
}
private void flushPendingTriangleRange() {
if (pendingTriangleTransform != null) {
triangleMergedRanges.add(new DrawRange(pendingTriangleStartVertex, pendingTriangleVertexCount, pendingTriangleTransform, pendingTriangleCommandIndex));
pendingTriangleTransform = null;
}
}
/**
* Compile all accumulated primitives into VBOs using optimal vertex format.
* @return The compiled buffers with separate VBOs for lines and triangles, or null if empty
*/
CompiledPrimitiveBuffers finish() {
flushPendingLineRange();
flushPendingTriangleRange();
if (allLines.isEmpty() && allTriangles.isEmpty()) {
return null;
}
// Use optimal format based on flags (same logic as quads)
final VertexFormat format = DisplayListManager.selectOptimalFormat(flags);
final VertexBuffer lineVbo = allLines.isEmpty() ? null : compileLinesToVBO(format);
final VertexBuffer triangleVbo = allTriangles.isEmpty() ? null : compileTrianglesToVBO(format);
return new CompiledPrimitiveBuffers(
flags,
lineVbo,
lineMergedRanges.toArray(new DrawRange[0]),
linePerDrawRanges.toArray(new DrawRange[0]),
triangleVbo,
triangleMergedRanges.toArray(new DrawRange[0]),
trianglePerDrawRanges.toArray(new DrawRange[0])
);
}
private VertexBuffer compileLinesToVBO(VertexFormat format) {
final int vertexSize = format.getVertexSize();
final int size = allLines.size();
final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 2);
for (int i = 0; i < size; i++) {
writePrimitiveToBuffer(allLines.get(i), buffer);
}
buffer.flip();
final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_LINES);
vbo.upload(buffer);
return vbo;
}
private VertexBuffer compileTrianglesToVBO(VertexFormat format) {
final int vertexSize = format.getVertexSize();
final int size = allTriangles.size();
final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 3);
for (int i = 0; i < size; i++) {
writePrimitiveToBuffer(allTriangles.get(i), buffer);
}
buffer.flip();
final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_TRIANGLES);
vbo.upload(buffer);
return vbo;
}
/**
* Write a primitive's vertices to the buffer using the format specified by flags.
* Only writes attributes that are present in the format.
*/
private void writePrimitiveToBuffer(ModelPrimitiveView prim, ByteBuffer buffer) {
final int vertexCount = prim.getVertexCount();
final boolean hasTexture = flags.hasTexture;
final boolean hasBrightness = flags.hasBrightness;
final boolean hasColor = flags.hasColor;
final boolean hasNormals = flags.hasNormals;
for (int i = 0; i < vertexCount; i++) {
// Position (always present) - 12 bytes
buffer.putFloat(prim.getX(i));
buffer.putFloat(prim.getY(i));
buffer.putFloat(prim.getZ(i));
// Color (4 bytes, ABGR) - if present
if (hasColor) {
buffer.putInt(prim.getColor(i));
}
// Texture (2 floats = 8 bytes) - if present
if (hasTexture) {
buffer.putFloat(prim.getTexU(i));
buffer.putFloat(prim.getTexV(i));
}
// Light/Brightness (4 bytes, packed) - if present
if (hasBrightness) {
buffer.putInt(prim.getLight(i));
}
// Normal (4 bytes, packed) - if present
if (hasNormals) {
buffer.putInt(prim.getForgeNormal(i));
}
}
}
}
@@ -5,14 +5,13 @@ import com.gtnewhorizons.angelica.glsm.recording.commands.MultMatrixCmd;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
/**
* Helper class for tracking and collapsing MODELVIEW transforms during optimization.
* Helper class for tracking and collapsing matrix transforms during optimization.
* Implements the transform accumulation and emission strategy:
* <ul>
* <li>accumulated: total relative transform (what GL matrix should be)</li>
@@ -100,11 +99,11 @@ class TransformOptimizer {
// But for simplicity, if lastEmitted is identity, just emit target
if (DisplayListManager.isIdentity(lastEmitted)) {
// Simple case: just emit target
output.add(MultMatrixCmd.create(target, GL11.GL_MODELVIEW));
output.add(MultMatrixCmd.create(target));
} else {
// Need to emit delta: inv(lastEmitted) * target
final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target);
output.add(MultMatrixCmd.create(delta, GL11.GL_MODELVIEW));
output.add(MultMatrixCmd.create(delta));
}
lastEmitted.set(target);
}
@@ -126,7 +125,7 @@ class TransformOptimizer {
/**
* Check if the GL matrix is at an absolute value and clear the flag.
* Used by LoadIdentityCmd to determine if it needs to emit.
* Used to determine if LoadIdentity needs to emit.
* @return true if LoadMatrix was called and not yet reset by LoadIdentity
*/
boolean checkAndClearAbsoluteMatrix() {
@@ -0,0 +1,11 @@
package com.gtnewhorizons.angelica.glsm.compat;
/**
* Simple holder for fog color values captured from vanilla rendering.
* Used by terrain renderers to access fog state.
*/
public class FogHelper {
public static float red;
public static float green;
public static float blue;
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.glsm.debug;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray;
import net.minecraft.client.Minecraft;
@@ -23,7 +24,9 @@ import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
// Adapted from https://github.com/makamys/CoreTweaks/blob/master/src/main/java/makamys/coretweaks/util/OpenGLDebugging.java;
@@ -34,6 +37,7 @@ public class OpenGLDebugging {
public static final Logger LOGGER = LogManager.getLogger("gldumper");
private static final Consumer<String> LINE_LOGGER = LOGGER::debug;
private static final Set<String> seenErrors = new HashSet<>();
public static final String GL_IS_ENABLED = "glIsEnabled()";
public static final String GL_GET_BOOLEANV = "glGetBooleanv()";
public static final String GL_GET_INTEGERV = "glGetIntegerv()";
@@ -455,49 +459,195 @@ public class OpenGLDebugging {
}
public static String getGLSMErrorLog() {
StringBuilder error = new StringBuilder();
return getGLSMErrorLog(null, false, false);
}
// Re-entrancy guard - getGLSMErrorLog calls glActiveTexture which could trigger checkGLSMOnce
private static boolean inCheck = false;
/**
* Enhanced GLSM error logging with context, stack trace, and first-occurrence filtering.
*
* @param context Optional context string to include in error messages (e.g., "During rendering")
* @param logStacktrace If true, includes the current stack trace in the error output
* @param onlyFirstOccurrence If true, only logs each unique error once
* @return Error log string if mismatches found, null otherwise
*/
public static String getGLSMErrorLog(String context, boolean logStacktrace, boolean onlyFirstOccurrence) {
if (inCheck) return null;
if (!GLStateManager.isCachingEnabled() || GLStateManager.isRecordingDisplayList()) {
return null;
}
inCheck = true;
try {
String group = "checkGLSM" + (context == null ? "" : " " + context);
GLDebug.pushGroup(group);
final StringBuilder error = new StringBuilder();
boolean mismatch = false;
if (context != null && !context.isEmpty()) {
error.append("[").append(context).append("] ");
}
for (int i = 0; i < instance.propertyList.length; ++i) {
final GLproperty gLProperty = instance.propertyList[i];
if (gLProperty.fetchCommand.equals(GL_GET_FLOATV) && gLProperty.name.endsWith("_MATRIX")) {
final Matrix4f cached = gLProperty.getAsMatrix4f(true);
final Matrix4f uncached = gLProperty.getAsMatrix4f(false);
// Some precision issues due to RAD vs degrees, and translated (vs f)
if (!cached.equals(uncached, 0.001f)) {
LOGGER.error("GLSM mismatch: " + gLProperty.name + "\ncached:\n" + cached + "uncached:\n" + uncached);
mismatch = true;
// Skip comparison if either matrix is degenerate (contains NaN/Infinity) these represent invalid GL state from bad parameters, not cache bugs
if (isMatrixDegenerate(cached) || isMatrixDegenerate(uncached)) continue;
if (!matricesEquivalent(cached, uncached, 0.001f)) {
final String errorKey = "MATRIX:" + gLProperty.name;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
final String errorMsg = "GLSM mismatch: " + gLProperty.name + "\ncached:\n" + cached + "uncached:\n" + uncached;
LOGGER.error(errorMsg);
error.append(errorMsg).append('\n');
mismatch = true;
}
}
} else {
final String cached = gLProperty.getAsString(true);
final String uncached = gLProperty.getAsString(false);
if (!cached.equals(uncached)) {
error.append("GLSM mismatch: " + gLProperty.name + " cached: " + cached + " uncached: " + uncached);
error.append('\n');
final String errorKey = "PROPERTY:" + gLProperty.name + ":" + cached + ":" + uncached;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: ").append(gLProperty.name).append(" cached: ").append(cached).append(" uncached: ").append(uncached);
error.append('\n');
mismatch = true;
}
}
}
}
final TextureUnitArray textureUnits = GLStateManager.getTextures();
final int currentActiveTexture = GLStateManager.getActiveTextureUnit();
// Check GL_ACTIVE_TEXTURE
final int glActiveUnit = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE) - GL13.GL_TEXTURE0;
if (glActiveUnit != currentActiveTexture) {
final String errorKey = "ACTIVE_TEXTURE:" + currentActiveTexture + ":" + glActiveUnit;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: GL_ACTIVE_TEXTURE cached: ").append(currentActiveTexture)
.append(" uncached: ").append(glActiveUnit).append('\n');
mismatch = true;
}
}
// Check per-unit texture state
for (int i = 0; i < textureUnits.textureMatricies.length; i++) {
GL13.glActiveTexture(GL13.GL_TEXTURE0 + i);
// Check GL_TEXTURE_2D enabled
final boolean cachedEnabled = textureUnits.getTextureUnitStates(i).isEnabled();
final boolean uncachedEnabled = GL11.glIsEnabled(GL11.GL_TEXTURE_2D);
if (cachedEnabled != uncachedEnabled) {
final String errorKey = "TEXTURE_2D:" + i + ":" + cachedEnabled + ":" + uncachedEnabled;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: GL_TEXTURE_2D cached: ").append(cachedEnabled)
.append(" uncached: ").append(uncachedEnabled)
.append(", texture unit: GL_TEXTURE").append(i).append('\n');
mismatch = true;
}
}
// Check GL_TEXTURE_BINDING_2D
final int cachedBinding = textureUnits.getTextureUnitBindings(i).getBinding();
final int uncachedBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
if (cachedBinding != uncachedBinding) {
final String errorKey = "TEXTURE_BINDING_2D:" + i + ":" + cachedBinding + ":" + uncachedBinding;
if (!onlyFirstOccurrence || seenErrors.add(errorKey)) {
error.append("GLSM mismatch: GL_TEXTURE_BINDING_2D cached: ").append(cachedBinding)
.append(" uncached: ").append(uncachedBinding)
.append(", texture unit: GL_TEXTURE").append(i).append('\n');
mismatch = true;
}
}
}
final TextureUnitArray textureUnits = GLStateManager.getTextures();
int currentActiveTexture = GLStateManager.getActiveTextureUnit();
for (int i = 0; i < textureUnits.textureMatricies.length; i++) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i);
final boolean cached = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean uncached = GL11.glIsEnabled(GL11.GL_TEXTURE_2D);
if (cached != uncached) {
error.append("GLSM mismatch: " + "GL_TEXTURE_2D" + " cached: " + cached + " uncached: " + uncached + ", texture unit: GL_TEXTURE" + i);
error.append('\n');
mismatch = true;
GL13.glActiveTexture(GL13.GL_TEXTURE0 + currentActiveTexture);
// Add stack trace if requested
if (mismatch && logStacktrace) {
error.append("\nStack trace:\n");
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (int i = 2; i < stackTrace.length; i++) {
error.append(" at ").append(stackTrace[i].toString()).append('\n');
}
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + currentActiveTexture);
if (!mismatch) {
return null;
GLDebug.popGroup();
return mismatch ? error.toString() : null;
} finally {
inCheck = false;
}
return error.toString();
}
public static boolean checkGLSMOnce(String context) {
final String output = getGLSMErrorLog(context, true, true);
if (output != null) {
// Only log on actual mismatch
LOGGER.error("[{}] MISMATCH thread={}\n{}", context, Thread.currentThread().getName(), output);
return false;
}
return true;
}
/**
* Check if a matrix contains any non-finite values (NaN or Infinity).
* Such matrices represent invalid/degenerate GL state (e.g., zero near/far in projection).
*/
private static boolean isMatrixDegenerate(Matrix4f matrix) {
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
if (!Float.isFinite(matrix.get(col, row))) {
return true;
}
}
}
return false;
}
/**
* Compare two matrices with tolerance for NaN/Infinity.
* Treats NaN == NaN and Infinity == Infinity as equal (both are degenerate states).
* For finite values, uses epsilon comparison.
*/
private static boolean matricesEquivalent(Matrix4f a, Matrix4f b, float epsilon) {
// Compare all 16 elements
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
final float aVal = a.get(col, row);
final float bVal = b.get(col, row);
// If both are non-finite (NaN or Infinity), consider them equal
if (!Float.isFinite(aVal) && !Float.isFinite(bVal)) {
// Both non-finite: check if both NaN or both same Infinity
if (Float.isNaN(aVal) && Float.isNaN(bVal)) continue;
if (Float.isInfinite(aVal) && Float.isInfinite(bVal)) {
// Check same sign of infinity
if ((aVal > 0) == (bVal > 0)) continue;
}
return false; // Different non-finite values
}
// If one is finite and other is not, they differ
if (Float.isFinite(aVal) != Float.isFinite(bVal)) {
return false;
}
// Both finite: use epsilon comparison
if (Math.abs(aVal - bVal) > epsilon) {
return false;
}
}
}
return true;
}
public static void checkGLSM() {
String output = getGLSMErrorLog();
final String output = getGLSMErrorLog();
if (output == null) {
LOGGER.info("GLSM state matches!");
@@ -507,7 +657,7 @@ public class OpenGLDebugging {
}
public static void copyTexture(ResourceLocation resource, File output) {
Object object = Minecraft.getMinecraft().renderEngine.mapTextureObjects.get(resource);
final Object object = Minecraft.getMinecraft().renderEngine.mapTextureObjects.get(resource);
if (object != null) {
copyTexture(((ITextureObject) object).getGlTextureId(), output);
@@ -72,6 +72,11 @@ public class DSAARB extends DSAUnsupported {
return GLStateManager.getTexParameterOrDefault(texture, pname, () -> ARBDirectStateAccess.glGetTextureParameteri(texture, pname));
}
@Override
public int getTexLevelParameteri(int texture, int level, int pname) {
return ARBDirectStateAccess.glGetTextureLevelParameteri(texture, level, pname);
}
@Override
public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) {
ARBDirectStateAccess.glCopyTextureSubImage2D(destTexture, i, i1, i2, i3, i4, width, height);
@@ -79,7 +84,7 @@ public class DSAARB extends DSAUnsupported {
@Override
public void bindTextureToUnit(int unit, int texture) {
if(GLStateManager.getBoundTexture(unit) == texture) return;
if(GLStateManager.getBoundTextureForServerState(unit) == texture) return;
if (texture == 0) {
super.bindTextureToUnit(unit, texture);
@@ -89,6 +94,11 @@ public class DSAARB extends DSAUnsupported {
}
}
@Override
public void bindTextureToUnit(int target, int unit, int texture) {
bindTextureToUnit(unit, texture);
}
@Override
public int bufferStorage(int target, FloatBuffer data, int usage) {
final int buffer = GL45.glCreateBuffers();
@@ -116,4 +126,19 @@ public class DSAARB extends DSAUnsupported {
public int createTexture(int target) {
return ARBDirectStateAccess.glCreateTextures(target);
}
@Override
public void textureStorage1D(int texture, int target, int levels, int internalFormat, int width) {
ARBDirectStateAccess.glTextureStorage1D(texture, levels, internalFormat, width);
}
@Override
public void textureStorage2D(int texture, int target, int levels, int internalFormat, int width, int height) {
ARBDirectStateAccess.glTextureStorage2D(texture, levels, internalFormat, width, height);
}
@Override
public void textureStorage3D(int texture, int target, int levels, int internalFormat, int width, int height, int depth) {
ARBDirectStateAccess.glTextureStorage3D(texture, levels, internalFormat, width, height, depth);
}
}
@@ -23,9 +23,12 @@ public interface DSAAccess {
int getTexParameteri(int texture, int target, int pname);
int getTexLevelParameteri(int texture, int level, int pname);
void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height);
void bindTextureToUnit(int unit, int texture);
void bindTextureToUnit(int target, int unit, int texture);
int bufferStorage(int target, FloatBuffer data, int usage);
@@ -35,4 +38,9 @@ public interface DSAAccess {
int createFramebuffer();
int createTexture(int target);
// Texture storage methods for custom images
void textureStorage1D(int texture, int target, int levels, int internalFormat, int width);
void textureStorage2D(int texture, int target, int levels, int internalFormat, int width, int height);
void textureStorage3D(int texture, int target, int levels, int internalFormat, int width, int height, int depth);
}
@@ -2,12 +2,14 @@ package com.gtnewhorizons.angelica.glsm.dsa;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.minecraft.client.renderer.OpenGlHelper;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL31;
import org.lwjgl.opengl.GL42;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
@@ -24,7 +26,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) {
// Get what cache thinks is bound - we'll restore to this to keep cache/GL in sync
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
GL11.glBindTexture(target, cachedBinding); // Restore to cache value
@@ -32,7 +34,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) {
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
GL11.glBindTexture(target, cachedBinding);
@@ -40,7 +42,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) {
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
GL11.glBindTexture(target, cachedBinding);
@@ -48,7 +50,7 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) {
final int cachedBinding = GLStateManager.getBoundTexture();
final int cachedBinding = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(target, texture);
GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
GL11.glBindTexture(target, cachedBinding);
@@ -74,13 +76,13 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void readBuffer(int framebuffer, int buffer) {
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, framebuffer);
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer);
GL11.glReadBuffer(buffer);
}
@Override
public void drawBuffers(int framebuffer, IntBuffer buffers) {
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, framebuffer);
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer);
GL20.glDrawBuffers(buffers);
}
@@ -90,9 +92,18 @@ public class DSAUnsupported implements DSAAccess {
return GLStateManager.glGetTexParameteri(target, pname);
}
@Override
public int getTexLevelParameteri(int texture, int level, int pname) {
final int previous = GLStateManager.getBoundTextureForServerState();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture);
final int result = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, pname);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, previous);
return result;
}
@Override
public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) {
final int previous = GLStateManager.getBoundTexture();
final int previous = GLStateManager.getBoundTextureForServerState();
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, destTexture);
GL11.glCopyTexSubImage2D(target, i, i1, i2, i3, i4, width, height);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous);
@@ -104,12 +115,18 @@ public class DSAUnsupported implements DSAAccess {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
@Override
public void bindTextureToUnit(int target, int unit, int texture) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + unit);
GLStateManager.glBindTexture(target, texture);
}
@Override
public int bufferStorage(int target, FloatBuffer data, int usage) {
final int buffer = GL15.glGenBuffers();
GL15.glBindBuffer(target, buffer);
GLStateManager.glBindBuffer(target, buffer);
RenderSystem.bufferData(target, data, usage);
GL15.glBindBuffer(target, 0);
GLStateManager.glBindBuffer(target, 0);
return buffer;
}
@@ -117,21 +134,21 @@ public class DSAUnsupported implements DSAAccess {
@Override
public void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2,
int bufferChoice, int filter) {
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, source);
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_DRAW_FRAMEBUFFER, dest);
GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, source);
GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, dest);
GL30.glBlitFramebuffer(offsetX, offsetY, width, height, offsetX2, offsetY2, width2, height2, bufferChoice, filter);
}
@Override
public void framebufferTexture2D(int fb, int fbtarget, int attachment, int target, int texture, int levels) {
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(fbtarget, fb);
GLStateManager.glBindFramebuffer(fbtarget, fb);
GL30.glFramebufferTexture2D(fbtarget, attachment, target, texture, levels);
}
@Override
public int createFramebuffer() {
final int framebuffer = OpenGlHelper.func_153165_e/*glGenFramebuffers*/();
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, framebuffer);
final int framebuffer = GLStateManager.glGenFramebuffers();
GLStateManager.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer);
return framebuffer;
}
@@ -141,4 +158,28 @@ public class DSAUnsupported implements DSAAccess {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
return texture;
}
@Override
public void textureStorage1D(int texture, int target, int levels, int internalFormat, int width) {
final int previous = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_1D);
GL11.glBindTexture(target, texture);
GL42.glTexStorage1D(target, levels, internalFormat, width);
GL11.glBindTexture(target, previous);
}
@Override
public void textureStorage2D(int texture, int target, int levels, int internalFormat, int width, int height) {
final int previous = (target == GL11.GL_TEXTURE_2D) ? GLStateManager.getBoundTextureForServerState() : GL11.glGetInteger(GL31.GL_TEXTURE_BINDING_RECTANGLE);
GL11.glBindTexture(target, texture);
GL42.glTexStorage2D(target, levels, internalFormat, width, height);
GL11.glBindTexture(target, previous);
}
@Override
public void textureStorage3D(int texture, int target, int levels, int internalFormat, int width, int height, int depth) {
final int previous = GL11.glGetInteger(GL12.GL_TEXTURE_BINDING_3D);
GL11.glBindTexture(target, texture);
GL42.glTexStorage3D(target, levels, internalFormat, width, height, depth);
GL11.glBindTexture(target, previous);
}
}
@@ -1,10 +1,10 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import org.joml.Matrix4f;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
@@ -12,24 +12,53 @@ import java.util.List;
* Matrix-as-Data Architecture: Stores untransformed vertices + captured matrix.
* The matrix will be applied at runtime, not baked into vertices.
*/
public class AccumulatedDraw {
public final List<ModelQuadViewMutable> quads;
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final class AccumulatedDraw {
public final VertexFormat format;
public final List<ByteBuffer> drawBuffers;
public final int drawMode;
public final int commandIndex; // Position in command list for state tracking
public final int stateGeneration; // Position in command list for state tracking
public RestoreData restoreData;
public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
// Deep copy quads - pooled quads are reused after callback
this.quads = ModelQuadUtil.deepCopyQuads(quads);
this.transform = new Matrix4f(transform); // Snapshot for runtime application
this.flags = flags;
public AccumulatedDraw(DirectTessellator tessellator, int commandIndex, int stateGeneration, boolean copyLast) {
this.format = tessellator.getVertexFormat();
this.drawMode = tessellator.drawMode;
this.drawBuffers = new ArrayList<>();
this.drawBuffers.add(tessellator.allocateBufferCopy());
this.commandIndex = commandIndex;
this.stateGeneration = stateGeneration;
if (copyLast) {
this.restoreData = new RestoreData(tessellator);
}
}
@Override
public String toString() {
return String.format("AccumulatedDraw[quads=%d, cmdIdx=%d, flags=C%dT%dL%dN%d]",
quads.size(), commandIndex, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0);
public void mergeDraw(DirectTessellator tessellator, boolean copyLast) {
this.drawBuffers.add(tessellator.allocateBufferCopy());
if (copyLast) {
this.restoreData = new RestoreData(tessellator);
}
}
/**
* Holds last vertex attribute values for GL state restoration after VBO draw.
* Used to sync GLSM cache with actual GL state after VBO rendering.
*/
public static final class RestoreData {
public final int lastColor;
public final int lastNormal;
public final float lastTexCoordU;
public final float lastTexCoordV;
public final int flags;
public RestoreData(DirectTessellator tessellator) {
this.lastColor = tessellator.getPackedColor();
this.lastNormal = tessellator.getPackedNormal();
this.lastTexCoordU = (float) tessellator.getLastTextureU();
this.lastTexCoordV = (float) tessellator.getLastTextureV();
this.flags = tessellator.getVertexFormat().getVertexFlags();
}
}
}
@@ -1,33 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import org.joml.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an accumulated line draw call during display list compilation.
* Similar to AccumulatedDraw but for line primitives.
* Stores untransformed line vertices + captured matrix.
*/
public class AccumulatedLineDraw {
public final List<ImmediateModeRecorder.LineVertex> lines;
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex; // Position in command list for state tracking
public AccumulatedLineDraw(List<ImmediateModeRecorder.LineVertex> lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
// Copy lines - the source list may be cleared
this.lines = new ArrayList<>(lines);
this.transform = new Matrix4f(transform); // Snapshot for runtime application
this.flags = flags;
this.commandIndex = commandIndex;
}
@Override
public String toString() {
return String.format("AccumulatedLineDraw[lines=%d, cmdIdx=%d, flags=C%dT%dL%dN%d]",
lines.size() / 2, commandIndex, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0);
}
}
@@ -1,58 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import org.joml.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an accumulated primitive draw call during display list compilation.
* Stores primitives (lines, triangles) from tessellator callback with their transform.
* <p>
* Unlike AccumulatedLineDraw which stores ImmediateModeRecorder.LineVertex (16-byte: pos+color),
* this stores ModelPrimitiveView (32-byte: pos+color+tex+light+normal) from the tessellator.
*/
public class AccumulatedPrimitiveDraw {
public final List<ModelPrimitiveView> primitives;
public final Matrix4f transform;
public final CapturingTessellator.Flags flags;
public final int commandIndex;
public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) {
// Deep copy primitives - pooled primitives are reused after callback
this.primitives = deepCopyPrimitives(primitives);
this.transform = new Matrix4f(transform);
this.flags = flags;
this.commandIndex = commandIndex;
}
/**
* Creates deep copies of all primitives in the list.
* Required because CapturingTessellator pools and reuses primitive objects.
*/
private static List<ModelPrimitiveView> deepCopyPrimitives(List<ModelPrimitiveView> source) {
final int size = source.size();
final List<ModelPrimitiveView> copies = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
final ModelPrimitiveView prim = source.get(i);
if (prim instanceof ModelLine ml) {
copies.add(new ModelLine().copyFrom(ml));
} else if (prim instanceof ModelTriangle mt) {
copies.add(new ModelTriangle().copyFrom(mt));
}
}
return copies;
}
@Override
public String toString() {
return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, mode=%d, flags=C%dT%dL%dN%d]",
primitives.size(), commandIndex, flags.drawMode,
flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0,
flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0);
}
}
@@ -5,6 +5,7 @@ import org.joml.Matrix4f;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
@@ -35,6 +36,11 @@ public final class CommandBuffer {
writePointer += 4;
}
private void writeLong(long value) {
memPutLong(writePointer, value);
writePointer += 8;
}
private void writeFloat(float value) {
memPutFloat(writePointer, value);
writePointer += 4;
@@ -136,22 +142,19 @@ public final class CommandBuffer {
writeInt(0); // unused padding
}
public void writeLoadIdentity(int matrixMode) {
ensureCapacity(8);
public void writeLoadIdentity() {
ensureCapacity(4);
writeInt(GLCommand.LOAD_IDENTITY);
writeInt(matrixMode);
}
public void writePushMatrix(int matrixMode) {
ensureCapacity(8);
public void writePushMatrix() {
ensureCapacity(4);
writeInt(GLCommand.PUSH_MATRIX);
writeInt(matrixMode);
}
public void writePopMatrix(int matrixMode) {
ensureCapacity(8);
public void writePopMatrix() {
ensureCapacity(4);
writeInt(GLCommand.POP_MATRIX);
writeInt(matrixMode);
}
public void writeStencilMask(int mask) {
@@ -317,14 +320,6 @@ public final class CommandBuffer {
writeFloat(units);
}
public void writeNormal(float x, float y, float z) {
ensureCapacity(16);
writeInt(GLCommand.NORMAL);
writeFloat(x);
writeFloat(y);
writeFloat(z);
}
public void writeColor(float r, float g, float b, float a) {
ensureCapacity(20);
writeInt(GLCommand.COLOR);
@@ -422,29 +417,26 @@ public final class CommandBuffer {
// === Double commands ===
public void writeTranslate(int matrixMode, double x, double y, double z) {
ensureCapacity(32);
public void writeTranslate(double x, double y, double z) {
ensureCapacity(28);
writeInt(GLCommand.TRANSLATE);
writeInt(matrixMode);
writeDouble(x);
writeDouble(y);
writeDouble(z);
}
public void writeRotate(int matrixMode, double angle, double x, double y, double z) {
ensureCapacity(40);
public void writeRotate(double angle, double x, double y, double z) {
ensureCapacity(36);
writeInt(GLCommand.ROTATE);
writeInt(matrixMode);
writeDouble(angle);
writeDouble(x);
writeDouble(y);
writeDouble(z);
}
public void writeScale(int matrixMode, double x, double y, double z) {
ensureCapacity(32);
public void writeScale(double x, double y, double z) {
ensureCapacity(28);
writeInt(GLCommand.SCALE);
writeInt(matrixMode);
writeDouble(x);
writeDouble(y);
writeDouble(z);
@@ -474,17 +466,15 @@ public final class CommandBuffer {
// === Matrix commands ===
public void writeMultMatrix(int matrixMode, Matrix4f matrix) {
ensureCapacity(72);
public void writeMultMatrix(Matrix4f matrix) {
ensureCapacity(68);
writeInt(GLCommand.MULT_MATRIX);
writeInt(matrixMode);
writeMatrix4f(matrix);
}
public void writeLoadMatrix(int matrixMode, Matrix4f matrix) {
ensureCapacity(72);
public void writeLoadMatrix(Matrix4f matrix) {
ensureCapacity(68);
writeInt(GLCommand.LOAD_MATRIX);
writeInt(matrixMode);
writeMatrix4f(matrix);
}
@@ -557,13 +547,32 @@ public final class CommandBuffer {
// === Draw commands ===
public void writeDrawRange(int vboIndex, int startVertex, int vertexCount, boolean hasBrightness) {
ensureCapacity(20);
public void writeDrawRange(int vboIndex) {
ensureCapacity(8);
writeInt(GLCommand.DRAW_RANGE);
writeInt(vboIndex);
writeInt(startVertex);
writeInt(vertexCount);
writeInt(hasBrightness ? 1 : 0);
}
/**
* Write a DRAW_RANGE_RESTORE command that draws a VBO range and restores GL current state after.
* Used for immediate mode VBOs to restore GL_CURRENT_COLOR, GL_CURRENT_NORMAL, GL_CURRENT_TEXTURE_COORDS.
*
* @param vboIndex Index into ownedVbos array
*/
public void writeDrawRangeRestore(
int vboIndex, AccumulatedDraw.RestoreData restoreData
) {
ensureCapacity(28);
writeInt(GLCommand.DRAW_RANGE_RESTORE);
writeInt(vboIndex);
writeInt(restoreData.flags);
// Last color (4 bytes)
writeInt(restoreData.lastColor);
// Last normal (4 bytes)
writeInt(restoreData.lastNormal);
// Last texcoord (2 floats = 8 bytes)
writeFloat(restoreData.lastTexCoordU);
writeFloat(restoreData.lastTexCoordV);
}
public void writeCallList(int listId) {
@@ -572,6 +581,68 @@ public final class CommandBuffer {
writeInt(listId);
}
public void writeDrawArrays(int mode, int start, int count) {
ensureCapacity(16);
writeInt(GLCommand.DRAW_ARRAYS);
writeInt(mode);
writeInt(start);
writeInt(count);
}
public void writeDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
ensureCapacity(24);
writeInt(GLCommand.DRAW_ELEMENTS);
writeInt(mode);
writeInt(indices_count);
writeInt(type);
writeLong(indices_buffer_offset);
}
public void writeBindVBO(int vbo) {
ensureCapacity(8);
writeInt(GLCommand.BIND_VBO);
writeInt(vbo);
}
public void writeBindVAO(int vao) {
ensureCapacity(8);
writeInt(GLCommand.BIND_VAO);
writeInt(vao);
}
public void writeDrawBuffer(int mode) {
ensureCapacity(8);
writeInt(GLCommand.DRAW_BUFFER);
writeInt(mode);
}
private static final int MAX_DRAW_BUFFERS = 8;
// cmd (4) + count (4) + buffers (4 * MAX_DRAW_BUFFERS)
private static final int DRAW_BUFFERS_SIZE = 4 + 4 + 4 * MAX_DRAW_BUFFERS;
public void writeDrawBuffers(int count, int buffer) {
ensureCapacity(DRAW_BUFFERS_SIZE);
writeInt(GLCommand.DRAW_BUFFERS);
writeInt(count);
writeInt(buffer);
for (int i = 1; i < MAX_DRAW_BUFFERS; i++) {
writeInt(0);
}
}
public void writeDrawBuffers(int count, IntBuffer bufs) {
ensureCapacity(DRAW_BUFFERS_SIZE);
writeInt(GLCommand.DRAW_BUFFERS);
writeInt(count);
final int pos = bufs.position();
for (int i = 0; i < count && i < MAX_DRAW_BUFFERS; i++) {
writeInt(bufs.get(pos + i));
}
for (int i = count; i < MAX_DRAW_BUFFERS; i++) {
writeInt(0);
}
}
// === Complex object reference ===
public void writeComplexRef(DisplayListCommand cmd) {
@@ -609,6 +680,12 @@ public final class CommandBuffer {
return value;
}
public long readLong() {
final long value = memGetLong(readPointer);
readPointer += 8;
return value;
}
/**
* Read a float from the current position.
*/
@@ -1,13 +1,17 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.opengl.UniversalVAO;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
@@ -21,6 +25,9 @@ public final class CommandBufferExecutor {
private static final FloatBuffer MATRIX_BUFFER = BufferUtils.createFloatBuffer(16);
// Static reusable buffer for fog/light/material params
private static final FloatBuffer PARAMS_BUFFER = BufferUtils.createFloatBuffer(4);
// Static reusable buffer for draw buffers
private static final int MAX_DRAW_BUFFERS = 8;
private static final IntBuffer DRAW_BUFFERS_BUFFER = BufferUtils.createIntBuffer(MAX_DRAW_BUFFERS);
/**
* Execute all commands in the buffer.
@@ -29,7 +36,7 @@ public final class CommandBufferExecutor {
* @param complexObjects Array of complex objects (TexImage2DCmd, etc.)
* @param ownedVbos Array of VBOs owned by the display list (indexed by DrawRange commands)
*/
public static void execute(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos) {
public static void execute(ByteBuffer buffer, Object[] complexObjects, DisplayListVBO ownedVbos) {
long ptr = memAddress(buffer);
final long end = ptr + buffer.limit();
@@ -92,28 +99,13 @@ public final class CommandBufferExecutor {
ptr += 4; // Skip unused padding
}
case GLCommand.LOAD_IDENTITY -> {
final int mode = memGetInt(ptr);
ptr += 4;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.PUSH_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glPushMatrix();
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.POP_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glPopMatrix();
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.STENCIL_MASK -> {
GLStateManager.glStencilMask(memGetInt(ptr));
@@ -256,13 +248,6 @@ public final class CommandBufferExecutor {
ptr += 8;
GLStateManager.glPolygonOffset(factor, units);
}
case GLCommand.NORMAL -> {
final float x = memGetFloat(ptr);
final float y = memGetFloat(ptr + 4);
final float z = memGetFloat(ptr + 8);
ptr += 12;
GLStateManager.glNormal3f(x, y, z);
}
case GLCommand.COLOR -> {
final float r = memGetFloat(ptr);
final float g = memGetFloat(ptr + 4);
@@ -349,38 +334,26 @@ public final class CommandBufferExecutor {
// === Double commands ===
case GLCommand.TRANSLATE -> {
final int mode = memGetInt(ptr);
final double x = memGetDouble(ptr + 4);
final double y = memGetDouble(ptr + 12);
final double z = memGetDouble(ptr + 20);
ptr += 28;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
final double x = memGetDouble(ptr);
final double y = memGetDouble(ptr + 8);
final double z = memGetDouble(ptr + 16);
ptr += 24;
GLStateManager.glTranslated(x, y, z);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.ROTATE -> {
final int mode = memGetInt(ptr);
final double angle = memGetDouble(ptr + 4);
final double x = memGetDouble(ptr + 12);
final double y = memGetDouble(ptr + 20);
final double z = memGetDouble(ptr + 28);
ptr += 36;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
final double angle = memGetDouble(ptr);
final double x = memGetDouble(ptr + 8);
final double y = memGetDouble(ptr + 16);
final double z = memGetDouble(ptr + 24);
ptr += 32;
GLStateManager.glRotated(angle, x, y, z);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.SCALE -> {
final int mode = memGetInt(ptr);
final double x = memGetDouble(ptr + 4);
final double y = memGetDouble(ptr + 12);
final double z = memGetDouble(ptr + 20);
ptr += 28;
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
final double x = memGetDouble(ptr);
final double y = memGetDouble(ptr + 8);
final double z = memGetDouble(ptr + 16);
ptr += 24;
GLStateManager.glScaled(x, y, z);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.ORTHO -> {
final double left = memGetDouble(ptr);
@@ -405,32 +378,23 @@ public final class CommandBufferExecutor {
// === Matrix commands ===
case GLCommand.MULT_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
// Mode-agnostic: just multiply current matrix
MATRIX_BUFFER.clear();
for (int i = 0; i < 16; i++) {
MATRIX_BUFFER.put(memGetFloat(ptr));
ptr += 4;
}
MATRIX_BUFFER.flip();
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glMultMatrix(MATRIX_BUFFER);
GLStateManager.glMatrixMode(savedMode);
}
case GLCommand.LOAD_MATRIX -> {
final int mode = memGetInt(ptr);
ptr += 4;
MATRIX_BUFFER.clear();
for (int i = 0; i < 16; i++) {
MATRIX_BUFFER.put(memGetFloat(ptr));
ptr += 4;
}
MATRIX_BUFFER.flip();
final int savedMode = GLStateManager.getMatrixMode().getMode();
GLStateManager.glMatrixMode(mode);
GLStateManager.glLoadMatrix(MATRIX_BUFFER);
GLStateManager.glMatrixMode(savedMode);
}
// === Buffer commands ===
@@ -488,20 +452,76 @@ public final class CommandBufferExecutor {
// === Draw commands ===
case GLCommand.DRAW_RANGE -> {
final int vboIndex = memGetInt(ptr);
final int start = memGetInt(ptr + 4);
final int count = memGetInt(ptr + 8);
final boolean hasBrightness = memGetInt(ptr + 12) != 0;
ptr += 16;
final VertexBuffer vbo = ownedVbos[vboIndex];
vbo.setupState();
vbo.draw(start, count);
vbo.cleanupState();
ptr += 4;
ownedVbos.render(vboIndex);
}
case GLCommand.DRAW_RANGE_RESTORE -> {
// Draw VBO range then restore GL current state from last vertex attributes
final int vboIndex = memGetInt(ptr);
final int flags = memGetInt(ptr + 4);
// Draw the VBO
ownedVbos.render(vboIndex);
// Restore attributes based on flags
if ((flags & VertexFlags.COLOR_BIT) != 0) {
final int color = memGetInt(ptr + 8);
byte a = (byte) ((color >> 24) & 0xFF);
byte r = (byte) ((color >> 16) & 0xFF);
byte g = (byte) ((color >> 8) & 0xFF);
byte b = (byte) ((color & 0xFF));
GLStateManager.glColor4ub(r, g, b, a);
}
if ((flags & VertexFlags.NORMAL_BIT) != 0) {
final int normal = memGetInt(ptr + 12);
float nx = (byte)(normal) / 127.0f;
float ny = (byte)(normal >> 8) / 127.0f;
float nz = (byte)(normal >> 16) / 127.0f;
GLStateManager.glNormal3f(nx, ny, nz);
}
if ((flags & VertexFlags.TEXTURE_BIT) != 0) {
final float s = memGetFloat(ptr + 16);
final float t = memGetFloat(ptr + 20);
GLStateManager.glTexCoord2f(s, t);
}
ptr += 24; // Skip full command size (28 - 4 for cmd already read)
}
case GLCommand.CALL_LIST -> {
final int listId = memGetInt(ptr);
ptr += 4;
DisplayListManager.glCallList(listId);
}
case GLCommand.DRAW_BUFFER -> {
GLStateManager.glDrawBuffer(memGetInt(ptr));
ptr += 4;
}
case GLCommand.DRAW_BUFFERS -> {
final int count = memGetInt(ptr);
ptr += 4;
DRAW_BUFFERS_BUFFER.clear();
for (int i = 0; i < count; i++) {
DRAW_BUFFERS_BUFFER.put(memGetInt(ptr + i * 4));
}
DRAW_BUFFERS_BUFFER.flip();
ptr += 4 * MAX_DRAW_BUFFERS;
GLStateManager.glDrawBuffers(DRAW_BUFFERS_BUFFER);
}
case GLCommand.DRAW_ARRAYS -> {
GLStateManager.glDrawArrays(memGetInt(ptr), memGetInt(ptr + 4), memGetInt(ptr + 8));
ptr += 12;
}
case GLCommand.DRAW_ELEMENTS -> {
GLStateManager.glDrawElements(memGetInt(ptr), memGetInt(ptr + 4), memGetInt(ptr + 8), memGetLong(ptr + 12));
ptr += 20;
}
case GLCommand.BIND_VBO -> {
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, memGetInt(ptr));
ptr += 4;
}
case GLCommand.BIND_VAO -> {
UniversalVAO.bindVertexArray(memGetInt(ptr));
ptr += 4;
}
// === Complex object reference ===
case GLCommand.COMPLEX_REF -> {
@@ -17,112 +17,6 @@ public final class CommandBufferProcessor {
private CommandBufferProcessor() {}
public static void processCommandForOptimization(int opcode, CommandBuffer raw, BufferTransformOptimizer opt, CommandBuffer out) {
switch (opcode) {
// === MODELVIEW matrix commands - accumulate instead of copying ===
case GLCommand.TRANSLATE -> {
final int mode = raw.readInt();
final double x = raw.readDouble();
final double y = raw.readDouble();
final double z = raw.readDouble();
if (mode == GL11.GL_MODELVIEW) {
opt.translate(x, y, z);
} else {
out.writeTranslate(mode, x, y, z);
}
}
case GLCommand.ROTATE -> {
final int mode = raw.readInt();
final double angle = raw.readDouble();
final double x = raw.readDouble();
final double y = raw.readDouble();
final double z = raw.readDouble();
if (mode == GL11.GL_MODELVIEW) {
opt.rotate(angle, x, y, z);
} else {
out.writeRotate(mode, angle, x, y, z);
}
}
case GLCommand.SCALE -> {
final int mode = raw.readInt();
final double x = raw.readDouble();
final double y = raw.readDouble();
final double z = raw.readDouble();
if (mode == GL11.GL_MODELVIEW) {
opt.scale(x, y, z);
} else {
out.writeScale(mode, x, y, z);
}
}
case GLCommand.MULT_MATRIX -> {
final int mode = raw.readInt();
raw.readMatrix4f(tempMatrix);
if (mode == GL11.GL_MODELVIEW) {
opt.multMatrix(tempMatrix);
} else {
out.writeMultMatrix(mode, tempMatrix);
}
}
case GLCommand.LOAD_IDENTITY -> {
final int mode = raw.readInt();
if (mode == GL11.GL_MODELVIEW) {
if (opt.checkAndClearAbsoluteMatrix()) {
out.writeLoadIdentity(mode);
}
opt.loadIdentity();
} else {
out.writeLoadIdentity(mode);
}
}
case GLCommand.LOAD_MATRIX -> {
final int mode = raw.readInt();
raw.readMatrix4f(tempMatrix);
if (mode == GL11.GL_MODELVIEW) {
opt.emitPendingTransform(out);
out.writeLoadMatrix(mode, tempMatrix);
opt.loadIdentity();
opt.markAbsoluteMatrix();
} else {
out.writeLoadMatrix(mode, tempMatrix);
}
}
// === Stack operations - update optimizer state and copy ===
case GLCommand.PUSH_MATRIX -> {
final int mode = raw.readInt();
if (mode == GL11.GL_MODELVIEW) {
opt.emitPendingTransform(out);
opt.push();
}
out.writePushMatrix(mode);
}
case GLCommand.POP_MATRIX -> {
final int mode = raw.readInt();
if (mode == GL11.GL_MODELVIEW) {
opt.pop();
}
out.writePopMatrix(mode);
}
// === Barriers - emit pending transform before copying ===
case GLCommand.CALL_LIST -> {
final int listId = raw.readInt();
opt.emitPendingTransform(out);
out.writeCallList(listId);
}
case GLCommand.PUSH_ATTRIB -> {
final int mask = raw.readInt();
if ((mask & GL11.GL_TRANSFORM_BIT) != 0) {
opt.emitPendingTransform(out);
}
out.writePushAttrib(mask);
}
// === All other commands - just copy ===
default -> copyCommandData(opcode, raw, out);
}
}
/**
* Copy a complete command (opcode already read) from raw to final buffer.
*/
@@ -150,9 +44,9 @@ public final class CommandBufferProcessor {
case GLCommand.USE_PROGRAM -> out.writeUseProgram(raw.readInt());
case GLCommand.PUSH_ATTRIB -> out.writePushAttrib(raw.readInt());
case GLCommand.POP_ATTRIB -> { raw.readInt(); out.writePopAttrib(); }
case GLCommand.LOAD_IDENTITY -> out.writeLoadIdentity(raw.readInt());
case GLCommand.PUSH_MATRIX -> out.writePushMatrix(raw.readInt());
case GLCommand.POP_MATRIX -> out.writePopMatrix(raw.readInt());
case GLCommand.LOAD_IDENTITY -> out.writeLoadIdentity();
case GLCommand.PUSH_MATRIX -> out.writePushMatrix();
case GLCommand.POP_MATRIX -> out.writePopMatrix();
case GLCommand.STENCIL_MASK -> out.writeStencilMask(raw.readInt());
case GLCommand.DEPTH_MASK -> out.writeDepthMask(raw.readInt() != 0);
case GLCommand.FRONT_FACE -> out.writeFrontFace(raw.readInt());
@@ -182,7 +76,6 @@ public final class CommandBufferProcessor {
case GLCommand.POINT_SIZE -> out.writePointSize(raw.readFloat());
case GLCommand.LINE_WIDTH -> out.writeLineWidth(raw.readFloat());
case GLCommand.POLYGON_OFFSET -> out.writePolygonOffset(raw.readFloat(), raw.readFloat());
case GLCommand.NORMAL -> out.writeNormal(raw.readFloat(), raw.readFloat(), raw.readFloat());
case GLCommand.COLOR -> out.writeColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat());
case GLCommand.CLEAR_COLOR -> out.writeClearColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat());
@@ -203,15 +96,15 @@ public final class CommandBufferProcessor {
case GLCommand.TEX_PARAMETERF -> out.writeTexParameterf(raw.readInt(), raw.readInt(), raw.readFloat());
// Double commands
case GLCommand.TRANSLATE -> out.writeTranslate(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.ROTATE -> out.writeRotate(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.SCALE -> out.writeScale(raw.readInt(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.TRANSLATE -> out.writeTranslate(raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.ROTATE -> out.writeRotate(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.SCALE -> out.writeScale(raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.ORTHO -> out.writeOrtho(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
case GLCommand.FRUSTUM -> out.writeFrustum(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble());
// Matrix commands
case GLCommand.MULT_MATRIX -> { int mode = raw.readInt(); out.writeMultMatrix(mode, raw.readMatrix4f(tempMatrix)); }
case GLCommand.LOAD_MATRIX -> { int mode = raw.readInt(); out.writeLoadMatrix(mode, raw.readMatrix4f(tempMatrix)); }
case GLCommand.MULT_MATRIX -> { out.writeMultMatrix(raw.readMatrix4f(tempMatrix)); }
case GLCommand.LOAD_MATRIX -> { out.writeLoadMatrix(raw.readMatrix4f(tempMatrix)); }
// FloatBuffer commands (inline 4 floats max)
case GLCommand.FOG -> {
@@ -250,8 +143,12 @@ public final class CommandBufferProcessor {
}
// Draw/call commands
case GLCommand.DRAW_RANGE -> out.writeDrawRange(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt() != 0);
case GLCommand.DRAW_RANGE -> out.writeDrawRange(raw.readInt());
case GLCommand.CALL_LIST -> out.writeCallList(raw.readInt());
case GLCommand.DRAW_ARRAYS -> out.writeDrawArrays(raw.readInt(), raw.readInt(), raw.readInt());
case GLCommand.DRAW_ELEMENTS -> out.writeDrawElements(raw.readInt(), raw.readInt(), raw.readInt(), raw.readLong());
case GLCommand.BIND_VBO -> out.writeBindVBO(raw.readInt());
case GLCommand.BIND_VAO -> out.writeBindVAO(raw.readInt());
// Complex object reference - transfer the object to output buffer
case GLCommand.COMPLEX_REF -> {
@@ -263,88 +160,4 @@ public final class CommandBufferProcessor {
default -> LOGGER.warn("[CommandBufferProcessor] Unknown opcode in buffer copy: {}", opcode);
}
}
/**
* Lightweight transform optimizer for buffer-to-buffer processing.
* Tracks accumulated MODELVIEW transform and emits MultMatrix commands when needed.
*/
public static class BufferTransformOptimizer {
private final Matrix4f accumulated = new Matrix4f();
private final Matrix4f lastEmitted = new Matrix4f();
private final Deque<Matrix4f> stack = new ArrayDeque<>();
private boolean absoluteMatrixFlag = false;
public BufferTransformOptimizer() {
accumulated.identity();
lastEmitted.identity();
}
public void translate(double x, double y, double z) {
accumulated.translate((float) x, (float) y, (float) z);
}
public void rotate(double angle, double x, double y, double z) {
accumulated.rotate((float) Math.toRadians(angle), (float) x, (float) y, (float) z);
}
public void scale(double x, double y, double z) {
accumulated.scale((float) x, (float) y, (float) z);
}
public void multMatrix(Matrix4f m) {
accumulated.mul(m);
}
public void loadIdentity() {
accumulated.identity();
}
public void push() {
stack.push(new Matrix4f(accumulated));
}
public void pop() {
if (!stack.isEmpty()) {
accumulated.set(stack.pop());
lastEmitted.set(accumulated);
} else {
accumulated.identity();
lastEmitted.identity();
}
}
public boolean isIdentity() {
return DisplayListManager.isIdentity(accumulated);
}
public void markAbsoluteMatrix() {
absoluteMatrixFlag = true;
}
public boolean checkAndClearAbsoluteMatrix() {
final boolean was = absoluteMatrixFlag;
absoluteMatrixFlag = false;
return was;
}
public void emitPendingTransform(CommandBuffer out) {
if (!accumulated.equals(lastEmitted)) {
emitTransformTo(out, accumulated);
}
}
public void emitTransformTo(CommandBuffer out, Matrix4f target) {
if (target.equals(lastEmitted)) {
return;
}
if (DisplayListManager.isIdentity(lastEmitted)) {
out.writeMultMatrix(GL11.GL_MODELVIEW, target);
} else {
final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target);
out.writeMultMatrix(GL11.GL_MODELVIEW, delta);
}
lastEmitted.set(target);
}
}
}
@@ -4,11 +4,12 @@ import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import org.joml.Matrix4f;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
/**
* Records GL commands to a CommandBuffer during display list compilation.
*/
public class CommandRecorder {
public final class CommandRecorder {
private final CommandBuffer buffer;
private int commandCount;
@@ -131,43 +132,28 @@ public class CommandRecorder {
commandCount++;
}
public void recordLoadIdentity(int matrixMode) {
buffer.writeLoadIdentity(matrixMode);
public void recordLoadIdentity() {
buffer.writeLoadIdentity();
commandCount++;
}
public void recordPushMatrix(int matrixMode) {
buffer.writePushMatrix(matrixMode);
public void recordPushMatrix() {
buffer.writePushMatrix();
commandCount++;
}
public void recordPopMatrix(int matrixMode) {
buffer.writePopMatrix(matrixMode);
public void recordPopMatrix() {
buffer.writePopMatrix();
commandCount++;
}
public void recordTranslate(int matrixMode, double x, double y, double z) {
buffer.writeTranslate(matrixMode, x, y, z);
public void recordMultMatrix(Matrix4f matrix) {
buffer.writeMultMatrix(matrix);
commandCount++;
}
public void recordRotate(int matrixMode, double angle, double x, double y, double z) {
buffer.writeRotate(matrixMode, angle, x, y, z);
commandCount++;
}
public void recordScale(int matrixMode, double x, double y, double z) {
buffer.writeScale(matrixMode, x, y, z);
commandCount++;
}
public void recordMultMatrix(int matrixMode, Matrix4f matrix) {
buffer.writeMultMatrix(matrixMode, matrix);
commandCount++;
}
public void recordLoadMatrix(int matrixMode, Matrix4f matrix) {
buffer.writeLoadMatrix(matrixMode, matrix);
public void recordLoadMatrix(Matrix4f matrix) {
buffer.writeLoadMatrix(matrix);
commandCount++;
}
@@ -186,11 +172,6 @@ public class CommandRecorder {
commandCount++;
}
public void recordNormal(float nx, float ny, float nz) {
buffer.writeNormal(nx, ny, nz);
commandCount++;
}
public void recordPointSize(float size) {
buffer.writePointSize(size);
commandCount++;
@@ -341,6 +322,41 @@ public class CommandRecorder {
commandCount++;
}
public void recordDrawBuffer(int mode) {
buffer.writeDrawBuffer(mode);
commandCount++;
}
public void recordDrawBuffers(int count, int buf) {
buffer.writeDrawBuffers(count, buf);
commandCount++;
}
public void recordDrawBuffers(int count, IntBuffer bufs) {
buffer.writeDrawBuffers(count, bufs);
commandCount++;
}
public void recordDrawArrays(int mode, int start, int count) {
buffer.writeDrawArrays(mode, start, count);
commandCount++;
}
public void recordDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
buffer.writeDrawElements(mode, indices_count, type, indices_buffer_offset);
commandCount++;
}
public void recordBindVBO(int vbo) {
buffer.writeBindVBO(vbo);
commandCount++;
}
public void recordBindVAO(int vao) {
buffer.writeBindVAO(vao);
commandCount++;
}
public void recordComplexCommand(DisplayListCommand cmd) {
buffer.writeComplexRef(cmd);
commandCount++;
@@ -1,6 +1,6 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
@@ -22,11 +22,17 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
* <p>The ownedVbos array contains VBOs that are referenced by DrawRange commands.
*/
public final class CompiledDisplayList {
/**
* Empty display list singleton. Per OpenGL spec, an empty list is still valid.
* This instance does nothing when rendered and is never deleted (shared singleton).
*/
public static final CompiledDisplayList EMPTY = new CompiledDisplayList(null, null, null);
private final ByteBuffer commandBuffer; // Off-heap command storage, must be freed
private final Object[] complexObjects; // Complex commands (TexImage2D, etc.)
private final VertexBuffer[] ownedVbos; // GPU resources referenced by index
private final DisplayListVBO ownedVbos; // GPU resources referenced by index
public CompiledDisplayList(ByteBuffer commandBuffer, Object[] complexObjects, VertexBuffer[] ownedVbos) {
public CompiledDisplayList(ByteBuffer commandBuffer, Object[] complexObjects, DisplayListVBO ownedVbos) {
this.commandBuffer = commandBuffer;
this.complexObjects = complexObjects;
this.ownedVbos = ownedVbos;
@@ -56,11 +62,7 @@ public final class CompiledDisplayList {
// Close VBOs
if (ownedVbos != null) {
for (VertexBuffer vbo : ownedVbos) {
if (vbo != null) {
vbo.close();
}
}
ownedVbos.delete();
}
// Free the command buffer (off-heap memory)
@@ -83,10 +85,7 @@ public final class CompiledDisplayList {
return complexObjects;
}
/**
* Get owned VBOs for inlining into another display list.
*/
public VertexBuffer[] getOwnedVbos() {
public DisplayListVBO getOwnedVbos() {
return ownedVbos;
}
@@ -97,16 +96,16 @@ public final class CompiledDisplayList {
* Used for testing to verify optimization results.
*/
public Int2IntMap getCommandCounts() {
Int2IntMap counts = new Int2IntOpenHashMap();
final Int2IntMap counts = new Int2IntOpenHashMap();
if (commandBuffer == null || commandBuffer.limit() == 0) {
return counts;
}
long ptr = memAddress(commandBuffer);
long end = ptr + commandBuffer.limit();
final long end = ptr + commandBuffer.limit();
while (ptr < end) {
int cmd = memGetInt(ptr);
final int cmd = memGetInt(ptr);
counts.mergeInt(cmd, 1, Integer::sum);
ptr += getCommandSize(cmd, ptr);
ptr += GLCommand.getCommandSize(cmd, ptr);
}
return counts;
}
@@ -116,71 +115,22 @@ public final class CompiledDisplayList {
* Used for testing to verify command ordering.
*/
public IntList getCommandOpcodes() {
IntList opcodes = new IntArrayList();
final IntList opcodes = new IntArrayList();
if (commandBuffer == null || commandBuffer.limit() == 0) {
return opcodes;
}
long ptr = memAddress(commandBuffer);
long end = ptr + commandBuffer.limit();
final long end = ptr + commandBuffer.limit();
while (ptr < end) {
int cmd = memGetInt(ptr);
final int cmd = memGetInt(ptr);
opcodes.add(cmd);
ptr += getCommandSize(cmd, ptr);
ptr += GLCommand.getCommandSize(cmd, ptr);
}
return opcodes;
}
/**
* Get size of a command in bytes (including the opcode).
*/
private static int getCommandSize(int cmd, long ptr) {
return switch (cmd) {
// Single int commands (8 bytes)
case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL,
GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP,
GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.LOAD_IDENTITY,
GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX, GLCommand.STENCIL_MASK,
GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH,
GLCommand.CALL_LIST, GLCommand.COMPLEX_REF -> 8;
// Two int commands (12 bytes)
case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL,
GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI,
GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF,
GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12;
// Three int commands (16 bytes)
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.NORMAL, GLCommand.LIGHTF, GLCommand.LIGHTI,
GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF -> 16;
// Four int commands (20 bytes)
case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK,
GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE,
GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR,
GLCommand.DRAW_RANGE -> 20;
// Double commands
case GLCommand.TRANSLATE, GLCommand.SCALE -> 32; // cmd + mode + 3 doubles
case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double
case GLCommand.ROTATE -> 40; // cmd + mode + 4 doubles
case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles
// Matrix commands (72 bytes)
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 72;
// Buffer commands (variable, read count)
case GLCommand.FOG, GLCommand.LIGHT_MODEL -> {
int count = memGetInt(ptr + 8); // pname at +4, count at +8
yield 12 + count * 4;
}
case GLCommand.LIGHT, GLCommand.MATERIAL -> {
int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12
yield 16 + count * 4;
}
default -> throw new IllegalStateException("Unknown command: " + cmd);
};
@Override
public String toString() {
return DisplayListManager.getCompiledDisplayListString(0, this, null);
}
}
@@ -0,0 +1,60 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import org.lwjgl.opengl.GL15;
/**
* A class that stores multiple vertex formats & their corresponding buffers.
*/
public final class DisplayListVBO {
private final SubVBO[] vbos;
DisplayListVBO(SubVBO[] vbos) {
this.vbos = vbos;
}
public void delete() {
for (SubVBO vbo : vbos) {
vbo.delete();
}
}
public SubVBO[] getVBOs() {
return vbos;
}
public void render(int index) {
vbos[index].render();
}
public static final class SubVBO {
private final IVertexArrayObject vao;
private final int drawMode;
private final int start;
private final int count;
public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count) {
this.vao = vao;
this.drawMode = drawMode;
this.start = start;
this.count = count;
}
public void delete() {
vao.delete();
}
public void render() {
vao.bind();
vao.draw(drawMode, start, count);
vao.unbind();
}
public IVertexArrayObject getVAO() {
return vao;
}
}
}
@@ -0,0 +1,127 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexedVAO;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
/**
* Compiles multiple ByteBuffers of the same Vertex format into a VBO. Any buffer added to the builder will be freed afterward.
*/
public final class DisplayListVBOBuilder {
// Removes the need for a HashMap. Since it's only an array of 16 values, this should be faster
private final List<FormatData>[] formats = new List[VertexFlags.BITSET_SIZE];
private int count;
public DisplayListVBOBuilder addDraw(VertexFormat format, int drawMode, List<ByteBuffer> buffers) {
List<FormatData> data = formats[format.getVertexFlags()];
if (data == null) {
data = new ArrayList<>();
formats[format.getVertexFlags()] = data;
}
data.add(new FormatData(buffers, drawMode, count));
count++;
return this;
}
public DisplayListVBOBuilder addDraws(List<AccumulatedDraw> draws) {
for (AccumulatedDraw draw : draws) {
addDraw(draw.format, draw.drawMode, draw.drawBuffers);
}
return this;
}
public DisplayListVBO build() {
final DisplayListVBO.SubVBO[] vbos = new DisplayListVBO.SubVBO[count];
final ArrayList<ByteBuffer> allBuffers = new ArrayList<>();
for (int i = 0; i < VertexFlags.BITSET_SIZE; i++) {
List<FormatData> formatData = formats[i];
if (formatData == null) continue;
final VertexFormat format = DefaultVertexFormat.ALL_FORMATS[i];
int start = 0;
final IVertexArrayObject vao = VAOManager.createStorageVAO(format, -1, 0); // drawMode will be ignored
final IVertexBuffer vbo = vao.getVBO();
for (FormatData data : formatData) {
int vertexCount;
final List<ByteBuffer> drawBuffers = data.buffers;
if (drawBuffers.size() == 1) {
final ByteBuffer buffer = drawBuffers.get(0);
allBuffers.add(buffer);
vertexCount = format.getVertexCount(buffer);
} else {
allBuffers.addAll(drawBuffers);
int size = 0;
for (ByteBuffer buffer : drawBuffers) {
size += buffer.remaining();
}
vertexCount = format.getVertexCount(size);
}
if (data.drawMode == GL11.GL_QUADS) {
IVertexArrayObject indexedVAO = new IndexedVAO(vbo, IndexBuffer.convertQuadsToTrigs(start, start + vertexCount));
vbos[data.drawIndex] = new DisplayListVBO.SubVBO(indexedVAO, GL11.GL_TRIANGLES, 0, vertexCount / 4 * 6);
} else {
vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount);
}
start += vertexCount;
}
ByteBuffer bigBuffer = mergeAndDelete(allBuffers);
vbo.allocate(bigBuffer, start);
memFree(bigBuffer);
allBuffers.clear();
}
return new DisplayListVBO(vbos);
}
private static ByteBuffer mergeAndDelete(List<ByteBuffer> buffers) {
if (buffers.size() == 1) {
return buffers.get(0);
}
int needed = 0;
for (ByteBuffer buffer : buffers) {
needed += buffer.remaining();
}
ByteBuffer out = memAlloc(needed);
long dst = memAddress0(out);
for (ByteBuffer buffer : buffers) {
final int len = buffer.limit();
final long address = memAddress0(buffer);
memCopy(address, dst, len);
dst += len;
nmemFree(address);
}
out.limit(needed);
return out;
}
private static final class FormatData {
private final List<ByteBuffer> buffers;
private final int drawMode;
private final int drawIndex;
public FormatData(List<ByteBuffer> buffers, int drawMode, int drawIndex) {
this.buffers = buffers;
this.drawMode = drawMode;
this.drawIndex = drawIndex;
}
}
}
@@ -1,5 +1,7 @@
package com.gtnewhorizons.angelica.glsm.recording;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
/**
* Command opcodes for ByteBuffer-based display list serialization.
* Each command has a fixed layout described in comments.
@@ -88,8 +90,24 @@ public final class GLCommand {
public static final int MATERIAL = 93; // [cmd:4][face:4][pname:4][count:4][params:16f] = 32 bytes
// === Draw commands ===
public static final int DRAW_RANGE = 100; // [cmd:4][vboIndex:4][start:4][count:4][hasBrightness:4] = 20 bytes
public static final int CALL_LIST = 101; // [cmd:4][listId:4] = 8 bytes
public static final int DRAW_RANGE = 100; // [cmd:4][vboIndex:4] = 8 bytes
public static final int DRAW_RANGE_RESTORE = 101; // [cmd:4][vboIndex:4][flags:4][color:4][normal:4][lastTexCoord:8f] = 28 bytes
public static final int CALL_LIST = 102; // [cmd:4][listId:4] = 8 bytes
public static final int DRAW_ARRAYS = 110; // [cmd:4][drawMode:4][start:4][count:4] = 20 bytes
public static final int DRAW_ELEMENTS = 111; // [cmd:4][mode:4][indices_count:4][type:4][indices_buffer_offset:8] = 28 bytes
public static final int DRAW_BUFFER = 112; // [cmd:4][mode:4] = 8 bytes
public static final int DRAW_BUFFERS = 113; // [cmd:4][count:4][bufs:4*8] = 40 bytes (up to 8 buffers)
/**
* Draw VBO range with attribute restoration after draw.
* Used for immediate mode VBOs to restore GL current state (color, normal, texcoord).
*/
// === Bind commands ===
public static final int BIND_VBO = 120;
public static final int BIND_VAO = 121;
// === Complex object reference ===
public static final int COMPLEX_REF = 255; // [cmd:4][index:4] = 8 bytes
@@ -136,7 +154,6 @@ public final class GLCommand {
case POINT_SIZE -> "POINT_SIZE";
case LINE_WIDTH -> "LINE_WIDTH";
case POLYGON_OFFSET -> "POLYGON_OFFSET";
case NORMAL -> "NORMAL";
case COLOR -> "COLOR";
case CLEAR_COLOR -> "CLEAR_COLOR";
case BLEND_COLOR -> "BLEND_COLOR";
@@ -162,8 +179,80 @@ public final class GLCommand {
case MATERIAL -> "MATERIAL";
case DRAW_RANGE -> "DRAW_RANGE";
case CALL_LIST -> "CALL_LIST";
case DRAW_BUFFER -> "DRAW_BUFFER";
case DRAW_BUFFERS -> "DRAW_BUFFERS";
case COMPLEX_REF -> "COMPLEX_REF";
case DRAW_RANGE_RESTORE -> "DRAW_RANGE_RESTORE";
case BIND_VAO -> "BIND_VAO";
case BIND_VBO -> "BIND_VBO";
default -> "UNKNOWN(" + opcode + ")";
};
}
/**
* Get size of a command in bytes (including the opcode).
*/
public static int getCommandSize(int cmd, long ptr) {
return switch (cmd) {
// Opcode-only commands (4 bytes)
case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4;
// Single int commands (8 bytes)
case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL,
GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP,
GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK,
GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH,
GLCommand.CALL_LIST, GLCommand.COMPLEX_REF, GLCommand.DRAW_RANGE, GLCommand.BIND_VBO,
GLCommand.BIND_VAO -> 8;
// Two int commands (12 bytes)
case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL,
GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI,
GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF,
GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12;
// Three int commands (16 bytes)
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.LIGHTF, GLCommand.LIGHTI,
GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF, GLCommand.DRAW_ARRAYS -> 16;
// Four int commands (20 bytes)
case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK,
GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE,
GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR -> 20;
case GLCommand.DRAW_ELEMENTS -> 24;
// DRAW_RANGE_RESTORE: 28 bytes
case GLCommand.DRAW_RANGE_RESTORE -> 28;
// DRAW_BUFFER: 8 bytes [cmd:4][mode:4]
case GLCommand.DRAW_BUFFER -> 8;
// DRAW_BUFFERS: 40 bytes [cmd:4][count:4][bufs:4*8]
case GLCommand.DRAW_BUFFERS -> 40;
// Double commands
case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles
case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double
case GLCommand.ROTATE -> 36; // cmd + 4 doubles
case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles
// Matrix commands
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats
// Buffer commands (variable, read count)
case GLCommand.FOG, GLCommand.LIGHT_MODEL -> {
final int count = memGetInt(ptr + 8); // pname at +4, count at +8
yield 12 + count * 4;
}
case GLCommand.LIGHT, GLCommand.MATERIAL -> {
final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12
yield 16 + count * 4;
}
default -> throw new IllegalStateException("Unknown command: " + cmd);
};
}
}
@@ -1,156 +1,58 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizons.angelica.glsm.states.ClientArrayState;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Records immediate mode GL calls (glBegin/glEnd/glVertex) during display list compilation.
* Converts immediate mode geometry to ModelQuad format for VBO compilation.
*
* <p>Tracks current immediate mode state:
* <ul>
* <li>TexCoord: Set by glTexCoord* calls</li>
* <li>Normal: Set by glNormal* calls</li>
* <li>Color: Read from GLStateManager.getColor() at vertex emission time</li>
* </ul>
*
* <p>Supported primitive types:
* <ul>
* <li>GL_QUADS: 4 vertices per quad (native support)</li>
* <li>GL_TRIANGLES: 3 vertices per triangle (converted to degenerate quad)</li>
* <li>GL_TRIANGLE_FAN: Fan of triangles (converted to individual quads)</li>
* <li>GL_TRIANGLE_STRIP: Strip of triangles (converted to individual quads)</li>
* <li>GL_QUAD_STRIP: Strip of quads (converted to individual quads)</li>
* <li>GL_POLYGON: Polygon (treated as triangle fan)</li>
* </ul>
*
* <p>Unsupported primitive types (logged warning, geometry discarded):
* <ul>
* <li>GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP: Line primitives</li>
* <li>GL_POINTS: Point primitives</li>
* </ul>
* Converts immediate mode geometry to ByteBuffer directly via {@link DirectTessellator}
* <p>
* Currently only used for display list compilation, should be perfectly usable outside of display lists too though.
*/
public class ImmediateModeRecorder {
private static final Logger LOGGER = LogManager.getLogger("ImmediateModeRecorder");
public final class ImmediateModeRecorder {
private static final DirectTessellator tessellator = new DirectTessellator(TessellatorManager.DEFAULT_BUFFER_SIZE);
// Accumulated quads from completed primitives
private final List<ModelQuadViewMutable> quads = new ArrayList<>();
private ImmediateModeRecorder() {
// Accumulated line vertices (pairs of vertices for GL_LINES)
private final List<LineVertex> lineVertices = new ArrayList<>();
// Current primitive state
private int currentPrimitiveType = -1;
private boolean inPrimitive = false;
// Vertices for current primitive (cleared on glEnd)
private final List<ImmediateVertex> currentVertices = new ArrayList<>();
// Current immediate mode state (set by glTexCoord*, glNormal*)
private float texCoordS = 0.0f;
private float texCoordT = 0.0f;
private float normalX = 0.0f;
private float normalY = 0.0f;
private float normalZ = 1.0f; // Default normal points +Z
// Track which attributes have been set (for flags)
private boolean hasTexCoord = false;
private boolean hasNormal = false;
private boolean hasColor = false;
/**
* Represents a single vertex captured during immediate mode.
*/
private static class ImmediateVertex {
float x, y, z; // Position
int color; // Packed ABGR color
float texU, texV; // Texture coordinates
int normal; // Packed normal
ImmediateVertex(float x, float y, float z, int color, float texU, float texV, int normal) {
this.x = x;
this.y = y;
this.z = z;
this.color = color;
this.texU = texU;
this.texV = texV;
this.normal = normal;
}
}
/**
* Represents a vertex for line primitives.
* Simpler than ImmediateVertex - just position and color.
*/
public static class LineVertex {
public final float x, y, z;
public final int color; // Packed ABGR color
public LineVertex(float x, float y, float z, int color) {
this.x = x;
this.y = y;
this.z = z;
this.color = color;
}
}
public ImmediateModeRecorder() {
// Recorder is ready to capture geometry
public static DirectTessellator getInternalTessellator() {
return tessellator;
}
/**
* Set the current texture coordinate.
* Called by GLStateManager.glTexCoord*.
*/
public void setTexCoord(float s, float t) {
this.texCoordS = s;
this.texCoordT = t;
this.hasTexCoord = true;
public static void setTexCoord(float s, float t) {
tessellator.setTextureUV(s, t);
}
/**
* Set the current normal vector.
* Called by GLStateManager.glNormal*.
*/
public void setNormal(float x, float y, float z) {
this.normalX = x;
this.normalY = y;
this.normalZ = z;
this.hasNormal = true;
}
/**
* Check if currently in a primitive (between glBegin and glEnd).
*/
public boolean isInPrimitive() {
return inPrimitive;
public static void setNormal(float x, float y, float z) {
tessellator.setNormal(x, y, z);
}
/**
* Start recording a new primitive.
*/
public void begin(int primitiveType) {
if (inPrimitive) {
throw new IllegalStateException("glBegin called while already in primitive");
}
this.currentPrimitiveType = primitiveType;
this.currentVertices.clear();
this.inPrimitive = true;
public static void begin(int primitiveType) {
tessellator.startDrawing(primitiveType);
}
/**
@@ -159,318 +61,27 @@ public class ImmediateModeRecorder {
*
* @return Result containing quads, lines, and flags, or null if no geometry was produced
*/
public Result end() {
if (!inPrimitive) {
public static DirectTessellator end() {
if (!tessellator.isDrawing) {
throw new IllegalStateException("glEnd called without glBegin");
}
// Convert this primitive's vertices to quads or lines
convertPrimitiveToQuads();
this.currentVertices.clear();
this.inPrimitive = false;
tessellator.isDrawing = false;
// Return geometry from this primitive immediately (don't accumulate)
if (quads.isEmpty() && lineVertices.isEmpty()) {
return null;
}
if (tessellator.isEmpty()) return null;
// Copy geometry and create flags
List<ModelQuadViewMutable> resultQuads = new ArrayList<>(quads);
List<LineVertex> resultLines = new ArrayList<>(lineVertices);
CapturingTessellator.Flags flags = new CapturingTessellator.Flags(
hasTexCoord, // hasTexture
false, // hasBrightness - immediate mode doesn't typically use lightmap
hasColor, // hasColor
hasNormal // hasNormals
);
// Clear for next primitive (but keep attribute tracking state)
quads.clear();
lineVertices.clear();
return new Result(resultQuads, resultLines, flags);
return tessellator;
}
/**
* Record a vertex with current attributes.
* Color is read from GLStateManager at call time.
*/
public void vertex(float x, float y, float z) {
if (!inPrimitive) {
public static void vertex(float x, float y, float z) {
if (!tessellator.isDrawing) {
throw new IllegalStateException("glVertex called outside glBegin/glEnd");
}
// Get current color from GLStateManager
int packedColor = packColor(
GLStateManager.getColor().getRed(),
GLStateManager.getColor().getGreen(),
GLStateManager.getColor().getBlue(),
GLStateManager.getColor().getAlpha()
);
if (packedColor != 0xFFFFFFFF) {
hasColor = true;
}
// Pack normal
int packedNormal = NormI8.pack(normalX, normalY, normalZ);
currentVertices.add(new ImmediateVertex(
x, y, z,
packedColor,
texCoordS, texCoordT,
packedNormal
));
}
/**
* Pack RGBA floats (0-1) into ABGR int format used by ModelQuad.
*/
private static int packColor(float r, float g, float b, float a) {
int ri = (int) (r * 255.0f) & 0xFF;
int gi = (int) (g * 255.0f) & 0xFF;
int bi = (int) (b * 255.0f) & 0xFF;
int ai = (int) (a * 255.0f) & 0xFF;
// ABGR format (little-endian: stored as RGBA bytes)
return (ai << 24) | (bi << 16) | (gi << 8) | ri;
}
/**
* Convert the current primitive vertices to quads.
* Handles different primitive types.
*/
private void convertPrimitiveToQuads() {
int vertexCount = currentVertices.size();
if (vertexCount == 0) {
return;
}
switch (currentPrimitiveType) {
case GL11.GL_QUADS -> convertQuads();
case GL11.GL_TRIANGLES -> convertTriangles();
case GL11.GL_TRIANGLE_FAN, GL11.GL_POLYGON -> convertTriangleFan();
case GL11.GL_TRIANGLE_STRIP -> convertTriangleStrip();
case GL11.GL_QUAD_STRIP -> convertQuadStrip();
case GL11.GL_LINES -> convertLines();
case GL11.GL_LINE_STRIP -> convertLineStripToLines();
case GL11.GL_LINE_LOOP -> convertLineLoopToLines();
case GL11.GL_POINTS -> {
LOGGER.warn("[ImmediateModeRecorder] Point primitives not supported, discarding {} vertices", vertexCount);
}
default -> {
LOGGER.warn("[ImmediateModeRecorder] Unknown primitive type {}, discarding {} vertices",
currentPrimitiveType, vertexCount);
}
}
}
/**
* Convert GL_QUADS vertices to ModelQuads (4 vertices per quad).
*/
private void convertQuads() {
int vertexCount = currentVertices.size();
int fullQuads = vertexCount / 4;
for (int i = 0; i < fullQuads; i++) {
int base = i * 4;
addQuad(
currentVertices.get(base),
currentVertices.get(base + 1),
currentVertices.get(base + 2),
currentVertices.get(base + 3)
);
}
int remaining = vertexCount % 4;
if (remaining > 0) {
LOGGER.warn("[ImmediateModeRecorder] GL_QUADS: Incomplete quad, discarding {} vertices", remaining);
}
}
/**
* Convert GL_TRIANGLES vertices to degenerate quads (3 vertices per triangle, duplicate last).
*/
private void convertTriangles() {
int vertexCount = currentVertices.size();
int fullTriangles = vertexCount / 3;
for (int i = 0; i < fullTriangles; i++) {
int base = i * 3;
ImmediateVertex v0 = currentVertices.get(base);
ImmediateVertex v1 = currentVertices.get(base + 1);
ImmediateVertex v2 = currentVertices.get(base + 2);
// Degenerate quad: duplicate third vertex
addQuad(v0, v1, v2, v2);
}
int remaining = vertexCount % 3;
if (remaining > 0) {
LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLES: Incomplete triangle, discarding {} vertices", remaining);
}
}
/**
* Convert GL_TRIANGLE_FAN vertices to triangles then to degenerate quads.
* First vertex is center, subsequent vertices form fan.
*/
private void convertTriangleFan() {
int vertexCount = currentVertices.size();
if (vertexCount < 3) {
LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_FAN: Need at least 3 vertices, got {}", vertexCount);
return;
}
ImmediateVertex center = currentVertices.get(0);
for (int i = 1; i < vertexCount - 1; i++) {
ImmediateVertex v1 = currentVertices.get(i);
ImmediateVertex v2 = currentVertices.get(i + 1);
// Triangle: center, v1, v2 -> degenerate quad
addQuad(center, v1, v2, v2);
}
}
/**
* Convert GL_TRIANGLE_STRIP vertices to triangles then to degenerate quads.
*/
private void convertTriangleStrip() {
int vertexCount = currentVertices.size();
if (vertexCount < 3) {
LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_STRIP: Need at least 3 vertices, got {}", vertexCount);
return;
}
for (int i = 0; i < vertexCount - 2; i++) {
ImmediateVertex v0, v1, v2;
if ((i & 1) == 0) {
// Even triangle: v[i], v[i+1], v[i+2]
v0 = currentVertices.get(i);
v1 = currentVertices.get(i + 1);
v2 = currentVertices.get(i + 2);
} else {
// Odd triangle: v[i+1], v[i], v[i+2] (reverse winding)
v0 = currentVertices.get(i + 1);
v1 = currentVertices.get(i);
v2 = currentVertices.get(i + 2);
}
addQuad(v0, v1, v2, v2);
}
}
/**
* Convert GL_QUAD_STRIP vertices to quads.
* Vertices come in pairs: (v0,v1), (v2,v3), (v4,v5)...
* Each quad uses 4 consecutive vertices in pattern: v[2i], v[2i+1], v[2i+3], v[2i+2]
*/
private void convertQuadStrip() {
int vertexCount = currentVertices.size();
if (vertexCount < 4) {
LOGGER.warn("[ImmediateModeRecorder] GL_QUAD_STRIP: Need at least 4 vertices, got {}", vertexCount);
return;
}
int numQuads = (vertexCount - 2) / 2;
for (int i = 0; i < numQuads; i++) {
int base = i * 2;
// Quad strip winding: v[0], v[1], v[3], v[2]
addQuad(
currentVertices.get(base),
currentVertices.get(base + 1),
currentVertices.get(base + 3),
currentVertices.get(base + 2)
);
}
}
/**
* Convert GL_LINES vertices to line segments (pairs of vertices).
*/
private void convertLines() {
int vertexCount = currentVertices.size();
int fullLines = vertexCount / 2;
for (int i = 0; i < fullLines; i++) {
int base = i * 2;
ImmediateVertex v0 = currentVertices.get(base);
ImmediateVertex v1 = currentVertices.get(base + 1);
lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color));
lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color));
}
int remaining = vertexCount % 2;
if (remaining > 0) {
LOGGER.warn("[ImmediateModeRecorder] GL_LINES: Incomplete line, discarding {} vertices", remaining);
}
}
/**
* Convert GL_LINE_STRIP to individual line segments.
* Vertices 0-1-2-3 become lines: 0-1, 1-2, 2-3
*/
private void convertLineStripToLines() {
int vertexCount = currentVertices.size();
if (vertexCount < 2) {
LOGGER.warn("[ImmediateModeRecorder] GL_LINE_STRIP: Need at least 2 vertices, got {}", vertexCount);
return;
}
for (int i = 0; i < vertexCount - 1; i++) {
ImmediateVertex v0 = currentVertices.get(i);
ImmediateVertex v1 = currentVertices.get(i + 1);
lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color));
lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color));
}
}
/**
* Convert GL_LINE_LOOP to individual line segments.
* Like LINE_STRIP but also closes the loop from last to first vertex.
*/
private void convertLineLoopToLines() {
int vertexCount = currentVertices.size();
if (vertexCount < 2) {
LOGGER.warn("[ImmediateModeRecorder] GL_LINE_LOOP: Need at least 2 vertices, got {}", vertexCount);
return;
}
// Convert as strip first
convertLineStripToLines();
// Close the loop: add last-to-first segment
ImmediateVertex vLast = currentVertices.get(vertexCount - 1);
ImmediateVertex vFirst = currentVertices.get(0);
lineVertices.add(new LineVertex(vLast.x, vLast.y, vLast.z, vLast.color));
lineVertices.add(new LineVertex(vFirst.x, vFirst.y, vFirst.z, vFirst.color));
}
/**
* Create a ModelQuad from 4 ImmediateVertex objects.
*/
private void addQuad(ImmediateVertex v0, ImmediateVertex v1, ImmediateVertex v2, ImmediateVertex v3) {
ModelQuad quad = new ModelQuad();
setVertex(quad, 0, v0);
setVertex(quad, 1, v1);
setVertex(quad, 2, v2);
setVertex(quad, 3, v3);
// Set light face based on computed normal
quad.setLightFace(ModelQuadUtil.findLightFace(quad.getComputedFaceNormal()));
quads.add(quad);
}
/**
* Set a single vertex in a ModelQuad.
*/
private void setVertex(ModelQuad quad, int idx, ImmediateVertex v) {
quad.setX(idx, v.x);
quad.setY(idx, v.y);
quad.setZ(idx, v.z);
quad.setColor(idx, v.color);
quad.setTexU(idx, v.texU);
quad.setTexV(idx, v.texV);
quad.setForgeNormal(idx, v.normal);
// Light defaults to full brightness (no lightmap for immediate mode typically)
quad.setLight(idx, ModelQuadUtil.DEFAULT_LIGHTMAP);
tessellator.addVertex(x, y, z);
}
/**
@@ -480,73 +91,16 @@ public class ImmediateModeRecorder {
* is returned from end() immediately. This method is kept for edge cases
* where primitives might fail to convert (e.g., incomplete quads).
*/
public boolean hasGeometry() {
return !quads.isEmpty() || !lineVertices.isEmpty();
public static boolean hasGeometry() {
return tessellator.vertexCount != 0;
}
/**
* Get any remaining accumulated geometry and clear the recorder.
*
* <p>Note: With immediate flush mode, this will typically return null as geometry
* is returned from end() immediately. This method is kept for cleanup and
* edge cases where geometry might remain (e.g., if end() was never called).
*
* @return Result containing remaining quads, lines, and flags, or null if no geometry
*/
public Result getQuadsAndClear() {
if (inPrimitive) {
throw new IllegalStateException("Cannot get geometry while in primitive (missing glEnd)");
}
if (quads.isEmpty() && lineVertices.isEmpty()) {
return null;
}
// Copy geometry and create flags
List<ModelQuadViewMutable> resultQuads = new ArrayList<>(quads);
List<LineVertex> resultLines = new ArrayList<>(lineVertices);
CapturingTessellator.Flags flags = new CapturingTessellator.Flags(
hasTexCoord, // hasTexture
false, // hasBrightness - immediate mode doesn't typically use lightmap
hasColor, // hasColor
hasNormal // hasNormals
);
// Clear state for reuse
quads.clear();
lineVertices.clear();
hasColor = false;
hasTexCoord = false;
hasNormal = false;
// Note: current texcoord/normal values are NOT reset - they persist per OpenGL spec
return new Result(resultQuads, resultLines, flags);
}
/**
* Result of immediate mode recording: quads, lines, and their attribute flags.
*/
@com.github.bsideup.jabel.Desugar
public record Result(List<ModelQuadViewMutable> quads, List<LineVertex> lines, CapturingTessellator.Flags flags) {}
/**
* Reset all state including current texcoord/normal.
* Called when starting a new display list.
*/
public void reset() {
quads.clear();
lineVertices.clear();
currentVertices.clear();
inPrimitive = false;
currentPrimitiveType = -1;
texCoordS = 0.0f;
texCoordT = 0.0f;
normalX = 0.0f;
normalY = 0.0f;
normalZ = 1.0f;
hasColor = false;
hasTexCoord = false;
hasNormal = false;
public static void reset() {
tessellator.reset();
}
/**
@@ -558,10 +112,10 @@ public class ImmediateModeRecorder {
* @param count Number of vertices
* @return Result containing converted geometry, or null if no geometry produced
*/
public Result processDrawArrays(int mode, int first, int count) {
final var cas = GLStateManager.getClientArrayState();
final var vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null;
final var colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null;
public static DirectTessellator processDrawArrays(int mode, int first, int count) {
final ClientArrayState cas = GLStateManager.getClientArrayState();
final Buffer vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null;
final Buffer colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null;
return convertClientArrays(
mode, first, count,
@@ -590,7 +144,7 @@ public class ImmediateModeRecorder {
* @param colorStride Stride in bytes (0 for tightly packed)
* @return Result containing converted geometry, or null if no geometry produced
*/
public Result convertClientArrays(
public static DirectTessellator convertClientArrays(
int mode, int first, int count,
java.nio.Buffer vertexPointer, int vertexType, int vertexSize, int vertexStride,
java.nio.Buffer colorPointer, int colorType, int colorSize, int colorStride
@@ -603,12 +157,10 @@ public class ImmediateModeRecorder {
// Determine color reader (hoisted out of loop)
final ColorReader colorReader;
final int colorEffectiveStride;
if (colorPointer == null) {
colorReader = null;
colorEffectiveStride = 0;
} else if (colorType == GL11.GL_FLOAT && colorPointer instanceof FloatBuffer fb) {
colorEffectiveStride = (colorStride == 0) ? colorSize * 4 : colorStride;
final int colorEffectiveStride = (colorStride == 0) ? colorSize * 4 : colorStride;
final int strideInFloats = colorEffectiveStride / 4;
colorReader = (idx) -> {
final int offset = idx * strideInFloats;
@@ -619,7 +171,7 @@ public class ImmediateModeRecorder {
GLStateManager.glColor4f(r, g, b, a);
};
} else if ((colorType == GL11.GL_UNSIGNED_BYTE || colorType == GL11.GL_BYTE) && colorPointer instanceof ByteBuffer bb) {
colorEffectiveStride = (colorStride == 0) ? colorSize : colorStride;
final int colorEffectiveStride = (colorStride == 0) ? colorSize : colorStride;
colorReader = (idx) -> {
final int offset = idx * colorEffectiveStride;
final float r = (bb.get(offset) & 0xFF) / 255.0f;
@@ -630,7 +182,6 @@ public class ImmediateModeRecorder {
};
} else {
// Unsupported color type - use white
colorEffectiveStride = 0;
colorReader = (idx) -> GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
@@ -696,6 +247,8 @@ public class ImmediateModeRecorder {
return end();
}
@FunctionalInterface
private interface ColorReader {
void read(int index);
@@ -1,19 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.recording.commands.DrawCommand;
import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat;
import java.nio.ByteBuffer;
import java.util.List;
/**
* Represents recorded geometry from a display list compilation.
* Contains the vertex data buffer and metadata about draw commands.
*/
@Desugar
public record RecordedGeometry(ByteBuffer buffer, BufferVertexFormat format, List<DrawCommand> drawCommands, int totalVertexCount) {
public int getByteSize() {
return buffer.remaining();
}
}
@@ -1,21 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import org.joml.Matrix4f;
/**
* Interface for matrix commands that can be accumulated during transform optimization.
* Implemented by TranslateCmd, RotateCmd, ScaleCmd, and MultMatrixCmd.
*/
public interface AccumulableMatrixCommand extends DisplayListCommand {
boolean isModelView();
void applyTo(Matrix4f matrix);
@Override
default boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
applyTo(ctx.getAccumulatedTransform());
return false; // Accumulated, don't emit
}
return true; // Non-MODELVIEW, emit as-is
}
}
@@ -1,61 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
/**
* Command: Call another display list (glCallList)
* Records a reference to another display list to be executed during playback.
* Per OpenGL spec: the referenced list is NOT executed during compilation,
* only the reference is recorded.
*
*/
@Desugar
public record CallListCmd(int listId) implements DisplayListCommand {
private static final Logger LOGGER = LogManager.getLogger("CallListCmd");
@Override
public void execute() {
final CompiledDisplayList compiled = GLStateManager.getDisplayList(listId);
if (compiled != null) {
GLDebug.pushGroup("CallList(" + listId + ")");
try {
compiled.render();
} finally {
GLDebug.popGroup();
}
} else {
// Fallback if list not found (shouldn't happen in normal operation)
LOGGER.warn("[CallListCmd] List {} not found in cache, using fallback glCallList", listId);
GLStateManager.glCallList(listId);
}
}
@Override
public void delete() {
// No resources to free - we just hold a reference
}
@Override
public boolean needsTransformSync() {
return true; // Nested list uses current GL matrix state
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
// Nested list needs current GL matrix state
ctx.emitPendingTransform();
return true; // Emit this command
}
@Override
public @NotNull String toString() {
return "CallList(" + listId + ")";
}
}
@@ -17,39 +17,4 @@ public interface DisplayListCommand {
default void delete() {
// Most commands don't hold resources
}
/**
* Returns true if this barrier command requires the MODELVIEW transform to be
* synchronized with the accumulated state before execution.
*
* <p>This should return true for commands where the GL matrix state matters,
* such as CallListCmd (nested lists use current GL state) or PushAttribCmd
* with GL_TRANSFORM_BIT (saves the current matrix).</p>
*
* <p>Commands like PushAttribCmd with only GL_COLOR_BUFFER_BIT don't need
* transform sync because they don't interact with the matrix stack.</p>
*
* @return true if transform must be synced to accumulated before this barrier
*/
default boolean needsTransformSync() {
return false;
}
/**
* Handle this command during display list optimization.
*
* <p>Commands override this to implement their optimization behavior:
* <ul>
* <li>Matrix transforms: accumulate into the optimizer, return false</li>
* <li>Push/Pop: update stack, return true to emit</li>
* <li>Barriers: emit pending transforms, return true to emit</li>
* <li>State changes: return true to emit</li>
* </ul>
*
* @param ctx The optimization context providing access to transform state
* @return true if this command should be added to output, false if handled internally
*/
default boolean handleOptimization(OptimizationContext ctx) {
return true;
}
}
@@ -1,14 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
/**
* Represents a single draw call within a compiled display list.
* Each DrawCommand corresponds to one glBegin/glEnd block.
*/
@Desugar
public record DrawCommand(
int firstVertex,
int vertexCount,
int primitiveType
) {}
@@ -1,42 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import org.jetbrains.annotations.NotNull;
/**
* Command: Draw a range of vertices from a shared VBO.
* <p>
* DrawRangeCmd references a shared VBO owned by CompiledDisplayList.ownedVbos.
* Multiple DrawRangeCmds can reference different ranges within the same VBO,
* enabling format-based batching where all draws with the same vertex format
* share a single VBO.
* <p>
* Transform is NOT stored here - handled by TransformOptimizer emitting
* MultMatrixCmd before this command during optimization.
*/
@Desugar
public record DrawRangeCmd(
VertexBuffer sharedVbo,
int startVertex,
int vertexCount,
boolean hasBrightness
) implements DisplayListCommand {
@Override
public void execute() {
sharedVbo.setupState();
sharedVbo.draw(startVertex, vertexCount);
sharedVbo.cleanupState();
}
@Override
public void delete() {
// No-op: VBO lifetime is managed by CompiledDisplayList.ownedVbos
}
@Override
public @NotNull String toString() {
return "DrawRange(start=" + startVertex + ", count=" + vertexCount + ", hasBrightness=" + hasBrightness + ")";
}
}
@@ -1,44 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glLoadIdentity()
* Replaces the current matrix with the identity matrix for the specified matrix mode.
*/
@Desugar
public record LoadIdentityCmd(int matrixMode) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glLoadIdentity();
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
// Check if we're at an absolute matrix (after LoadMatrix)
// If so, we must emit LoadIdentity to actually reset GL state
if (ctx.checkAndClearAbsoluteMatrix()) {
ctx.emit(this);
ctx.loadIdentity();
return false; // Already emitted
}
ctx.loadIdentity();
return false; // Accumulated, don't emit
}
return true; // Non-MODELVIEW, emit as-is
}
@Override
public @NotNull String toString() {
return String.format("LoadIdentity(%s)", GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,75 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
/**
* Command: glLoadMatrix(matrix)
* Replaces the current matrix with the specified matrix for the given matrix mode.
*
* <p>Unlike MultMatrixCmd which can be absorbed into the accumulated transform,
* LoadMatrixCmd must always be emitted because it sets an absolute value, not a relative one.
* After a LoadMatrix command, the accumulated transform is reset to identity since
* subsequent transforms are relative to the newly loaded matrix.</p>
*/
@Desugar
public record LoadMatrixCmd(Matrix4f matrix, int matrixMode, FloatBuffer buffer) implements DisplayListCommand {
/**
* Create a LoadMatrixCmd with pre-allocated buffer.
*/
public static LoadMatrixCmd create(Matrix4f matrix, int matrixMode) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
matrix.get(buffer);
buffer.rewind();
return new LoadMatrixCmd(new Matrix4f(matrix), matrixMode, buffer);
}
/**
* Create a LoadMatrixCmd from a FloatBuffer (copies the data).
*/
public static LoadMatrixCmd create(FloatBuffer src, int matrixMode) {
final Matrix4f matrix = new Matrix4f().set(src);
src.rewind();
return create(matrix, matrixMode);
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void execute() {
// Buffer already populated at construction, just rewind and use
buffer.rewind();
GLStateManager.glLoadMatrix(buffer);
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
// LoadMatrix sets an absolute value - emit any pending relative transform first
ctx.emitPendingTransform();
// Emit this command
ctx.emit(this);
// Reset accumulated to identity - subsequent transforms are relative to the loaded matrix
ctx.loadIdentity();
// Mark that GL is at an absolute value - LoadIdentity must emit to reset
ctx.markAbsoluteMatrix();
return false; // Already emitted
}
return true; // Non-MODELVIEW, emit as-is
}
@Override
public @NotNull String toString() {
return String.format("LoadMatrix(%s, %s)", GLDebug.getMatrixModeName(matrixMode), matrix);
}
}
@@ -5,40 +5,28 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
/**
* Command: glMultMatrix(matrix)
* Multiplies the specified matrix mode by the specified matrix.
* Multiplies the current matrix by the specified matrix.
*/
@Desugar
public record MultMatrixCmd(Matrix4f matrix, int matrixMode, FloatBuffer buffer) implements AccumulableMatrixCommand {
public record MultMatrixCmd(Matrix4f matrix, FloatBuffer buffer) implements DisplayListCommand {
/**
* Create a MultMatrixCmd with pre-allocated buffer.
*/
public static MultMatrixCmd create(Matrix4f matrix, int matrixMode) {
public static MultMatrixCmd create(Matrix4f matrix) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
matrix.get(buffer);
buffer.rewind();
return new MultMatrixCmd(new Matrix4f(matrix), matrixMode, buffer);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f target) {
target.mul(matrix);
return new MultMatrixCmd(new Matrix4f(matrix), buffer);
}
@Override
public void execute() {
// Buffer already populated at construction, just rewind and use
buffer.rewind();
GLStateManager.glMultMatrix(buffer);
}
@@ -1,42 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import org.joml.Matrix4f;
/**
* Context provided to commands during display list optimization.
* Allows commands to interact with the transform optimizer and draw batcher.
*/
public interface OptimizationContext {
/** Get the accumulated MODELVIEW transform matrix. */
Matrix4f getAccumulatedTransform();
/** Reset accumulated transform to identity. */
void loadIdentity();
/** Push current accumulated transform onto stack. */
void pushTransform();
/** Pop transform from stack, restoring previous accumulated value. */
void popTransform();
/** Emit a MultMatrix command if accumulated differs from last emitted. */
void emitPendingTransform();
/** Emit a MultMatrix command to reach the target transform. */
void emitTransformTo(Matrix4f target);
/** Add a command to the output list. */
void emit(DisplayListCommand cmd);
/**
* Mark that the GL matrix is at an absolute value (after LoadMatrix).
* Subsequent LoadIdentity commands must be emitted to reset to identity.
*/
void markAbsoluteMatrix();
/**
* Check if the GL matrix is at an absolute value and clear the flag.
* @return true if LoadMatrix was called and not yet reset by LoadIdentity
*/
boolean checkAndClearAbsoluteMatrix();
}
@@ -1,33 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
/**
* Command: glPopAttrib()
* Pops the server attribute stack.
*/
@Desugar
public record PopAttribCmd() implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPopAttrib();
}
@Override
public boolean needsTransformSync() {
return true;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
ctx.emitPendingTransform();
return true;
}
@Override
public @NotNull String toString() {
return "PopAttrib()";
}
}
@@ -1,36 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glPopMatrix()
* Pops the current matrix from the matrix stack for the specified matrix mode.
*/
@Desugar
public record PopMatrixCmd(int matrixMode) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPopMatrix();
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
ctx.popTransform();
}
return true; // Always emit Pop
}
@Override
public @NotNull String toString() {
return String.format("PopMatrix(%s)", GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,38 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glPushAttrib(mask)
* Pushes the server attribute stack.
*/
@Desugar
public record PushAttribCmd(int mask) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPushAttrib(mask);
}
@Override
public boolean needsTransformSync() {
// Only need transform sync if we're pushing transform state.
// GL_TRANSFORM_BIT includes the matrix mode and matrix stacks.
return (mask & GL11.GL_TRANSFORM_BIT) != 0;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (needsTransformSync()) {
ctx.emitPendingTransform();
}
return true;
}
@Override
public @NotNull String toString() {
return String.format("PushAttrib(0x%08X)", mask);
}
}
@@ -1,37 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
/**
* Command: glPushMatrix()
* Pushes the current matrix onto the matrix stack for the specified matrix mode.
*/
@Desugar
public record PushMatrixCmd(int matrixMode) implements DisplayListCommand {
@Override
public void execute() {
GLStateManager.glPushMatrix();
}
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public boolean handleOptimization(OptimizationContext ctx) {
if (isModelView()) {
ctx.emitPendingTransform();
ctx.pushTransform();
}
return true; // Always emit Push
}
@Override
public @NotNull String toString() {
return String.format("PushMatrix(%s)", GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,35 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
/**
* Command: glRotatef() or glRotated()
* Stores as doubles for precision.
*/
@Desugar
public record RotateCmd(double angle, double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand {
@Override
public void execute() {
GLStateManager.glRotated(angle, x, y, z);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f matrix) {
matrix.rotate((float) Math.toRadians(angle), (float) x, (float) y, (float) z);
}
@Override
public @NotNull String toString() {
return String.format("Rotate(%.2f deg, %.2f, %.2f, %.2f, %s)", angle, x, y, z, GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,35 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
/**
* Command: glScalef() or glScaled()
* Stores as doubles for precision.
*/
@Desugar
public record ScaleCmd(double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand {
@Override
public void execute() {
GLStateManager.glScaled(x, y, z);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f matrix) {
matrix.scale((float) x, (float) y, (float) z);
}
@Override
public @NotNull String toString() {
return String.format("Scale(%.2f, %.2f, %.2f, %s)", x, y, z, GLDebug.getMatrixModeName(matrixMode));
}
}
@@ -1,43 +0,0 @@
package com.gtnewhorizons.angelica.glsm.recording.commands;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.jetbrains.annotations.NotNull;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
/**
* Command: glTranslatef() or glTranslated()
* Stores as doubles for precision.
*/
@Desugar
public record TranslateCmd(double x, double y, double z, int matrixMode) implements AccumulableMatrixCommand {
@Override
public void execute() {
// Save current mode
final int savedMode = GLStateManager.getMatrixMode().getMode();
// Switch to the mode this was recorded with
GLStateManager.glMatrixMode(matrixMode);
GLStateManager.glTranslated(x, y, z);
// Restore mode
GLStateManager.glMatrixMode(savedMode);
}
@Override
public boolean isModelView() {
return matrixMode == GL11.GL_MODELVIEW;
}
@Override
public void applyTo(Matrix4f matrix) {
matrix.translate((float) x, (float) y, (float) z);
}
@Override
public @NotNull String toString() {
return String.format("Translate(%.2f, %.2f, %.2f, %s)", x, y, z, GLDebug.getMatrixModeName(matrixMode));
}
}
Loaded 100 of 656 files, more files were not shown because too many files have changed in this diff. Show more