Compare commits

...
Author SHA1 Message Date
Darren Eberly 54f276a460 More GLSM Lighting and Material work (#569)
* Initial glMaterial work
* Explicitly reset material state during enable bit test
2024-07-25 00:42:27 +00:00
Darren Eberly feef745722 Support for glColorMaterial and glLightModel in GLSM (#556)
* Support for glColorMaterial and glLightModel in GLSM

* Tests for light model

* Tests for glColorMaterial
2024-07-23 22:26:23 -07:00
ah-OOG-ahandJason Mitchell 88cb3faf47 Merge beta JSON loading API (#567)
* Remove ARR assets

* Refactor leaf mixins

* Refactor asset loading

Introduces a resource reload in POSTINIT, just before loading models

* Move lectern model to template

* Unlink test blocks and injected QuadProviders

Now they can be enabled or disabled separately

* Replace log renderer

* Fix JSON model culling

* Actually fix culling this time

* Update NdQuadBuilder.java

* Remove unused method

* Support tris

Hasn't been tested

* Pull QuadBuilder into an API

* Move Variant and Loader to API

* Glass QP and minor FluidRenderer improvement

* Rename Loader

* Move injected QuadProviders to a field

This way they don't get inherited

* Prioritize 7.10 textures over modern

* Use JSON models for vanilla logs

* Add a rewind method

This doesn't fix the problem, but it looks interesting, maybe it's closer?

* Fix texture loading

* Reenable rewinding

* FRAPI AO builds

Still useless tho

* Super broken, but maybe salvageable?

* Revert "Super broken, but maybe salvageable?"

This reverts commit ef4352f0d82f93039547bacdd38bddca65193743.

* Revert "FRAPI AO builds"

This reverts commit 7a4fd800831f973ea25c6a3c2b088afcf224770f.

* Cleanroom Mojang's rewinder

* Not-really-working-rewinding

* Mark JSON API as beta

* Ew, star imports

* Update gtnh gradle

* Update dependencies.gradle

* Update dependencies.gradle

---------

Co-authored-by: Jason Mitchell <[email protected]>
2024-07-23 19:17:59 -07:00
Caedis f477675ee9 HUD Caching Early Return (#562)
* Initial logic

* Cleanup

* change to 1 parameter + hashset

* handle methods that return a bool or int

* move some stuff around

* clean up

* update

* delete that

* update .gitignore

* Add null check

* update gitignore

* Simplify ASM injection

* Rework ASM logic

* switch to MixinClassWriter

* update

* change folder name

* cleanup hook
2024-07-21 10:05:58 -05:00
Rad 4294059fbe Create pl_PL.lang + minor README improvements (#560)
* Slight Readme.md improvements

* Create pl_PL.lang
2024-07-20 11:21:23 -07:00
Caedis e40c9f2441 Fix Thaumic Horizons Lens Selector (#561)
* Fix line endings

* Fix Lens Selector Rendering
2024-07-20 11:08:20 -07:00
Caedis 52e886adcc Fix Thaumcraft foci rendering (#559)
* remove redundent @Getter

* Fix slow thaumcraft rendering

* swap to @Getter

* Revert "swap to @Getter"

This reverts commit 92f216a0db.

* fix getter
2024-07-18 22:33:46 -07:00
Jason Mitchell f38fcd1d82 Update MixinCompatHackTweaker.java 2024-07-16 21:33:21 -07:00
Jason Mitchell fbebbd4049 Also disable Better FPS (#558) 2024-07-16 21:00:21 -07:00
cutiegin 03a0406199 Create ru_RU.lang (#552)
* russian translation
2024-07-15 10:05:43 -07:00
Jason Mitchell 1ef691ecc8 Beta Release - Shaders sneak preview (Don't submit issues yet)
Beta Release - Shaders sneak preview (Don't submit issues yet)
Latest set of shader fixes and other improvements
2024-07-14 23:24:03 -07:00
Jason Mitchell b242a13fd6 Update README.MD 2024-07-14 23:17:12 -07:00
2274bfabfd Beta (#461)
* Beta, maybe
* Fixes for entityColor uniform in Iris
* Handle Iris Texture input hook properly in GLSM
* Iris Entity Fixes
* Gbuffer progress
* Wire up BlockEntity gbuffer
* Move Entity gbuffer to a more appropriate place to avoid reentrancy
* Wire up ENTITY_EYES and BEACOM_BEAM
* Clean up unused RenderStateShard files
* This seems marginally more correct?
* Fix shadows from showing on sides of blocks
* Remove overlay
* yeet
* More gl debugging
* Grr, fix water textures
* Add missed enable checks
* Workaround for unset depth texture when using apitrace...
   Use a WrapOperation instead of an Inject with local capture - it wasn't working in dev w/ mixin debug set
* update bs
* Fix crosshair rendering with shaders
* more final
* Disable dynamic lights if shaders are in use
* No light when in water
* Add Void Particle Option + Mixin cleanup
* update bs
* less false

---------

Co-authored-by: Darren Eberly <[email protected]>
Co-authored-by: Caedis <[email protected]>
2024-07-14 23:09:03 -07:00
ev chang 7e4292bdba Add HUDCaching FPS (from PolyPatcher) 2024-07-12 10:49:07 -07:00
Darren Eberly f79e112700 More GLSM Lighting Fixes (#554) 2024-07-11 15:16:15 -04:00
Darren Eberly ba46feb20b GLSM Lighting (#553) 2024-07-11 11:10:04 -04:00
Jason Mitchell 33804c67da Use gtnhlib for coordinate packing/unpacking (#550) 2024-07-07 22:48:58 -07:00
Caedis 3c9353e143 Update dynamic lights from beta branch (#534)
* move dynamic lights lang to angelica

* No light when in water

* update bs

* add battlegear2 compat

Can't add backhand compat since it shares api package path with
battlegear2 (mods/battlegear2/api/core/BattlegearUtils)

* Add backhand 1.4.1+ support
2024-06-26 05:39:26 -07:00
JL2210 77eb3ad46a Fix NPE from MineFactory Reloaded during lag spikes (#522)
* Fix NPE from MineFactory Reloaded during lag spikes

This is an ARR mod and hence cannot be forked.
I decided to put the fix here rather than e.g. Hodgepodge as this is only an
issue with Angelica and seems to be due to its thread safety patches.

* Rewrite as injector

IDE go brr
2024-06-24 17:45:37 -07:00
FalsePattern 8a56ab8ca1 fixed crash with EndlessIDs when joining a multiplayer server 2024-06-09 21:24:26 +08:00
Dakotah fe065803aa THIS ADDS FEATURE REQUEST ISSUE TO GITHUB (#514)
* Add feature request template

* Add feature request template

* Add labels to feature request template automatically

* switch labels to enhancement
2024-05-30 16:30:09 -07:00
ah-OOG-ah f94268c384 Add null check to FluidRenderer (#513)
* Add null check to FluidRenderer

* Update FluidRenderer.java
2024-05-30 17:56:32 -04:00
jss2a98aj f7a8b0f3bf Cloud scaling, distance, and some fixes 2024-05-24 22:16:41 -07:00
embeddedt 8893cf2291 Mark chunk graph as dirty when FOV changes (#506) 2024-05-24 15:59:46 -04:00
Jason Mitchell adc575c5ab remaps 2024-05-23 20:00:21 -07:00
Jason Mitchell 35a056b73b Patches vanilla getFlowDirection to not crash with a ClassCastException if another mod implements their own fluid renderer and calls getFlowDirection when COFH ASM is loaded 2024-05-23 20:00:21 -07:00
jss2a98aj fbbb0ed4f2 Various cleanup (IJK -> XYZ etc) 2024-05-23 19:49:49 -07:00
jss2a98aj bc148ba09c Updated file overlooked in previous sync 2024-05-23 19:49:49 -07:00
jss2a98aj 1db3932af0 Roll ITileOverride into TileOverride 2024-05-23 19:49:49 -07:00
jss2a98aj 0fd4611a97 Refactor glass pane mixins to solve compat issues 2024-05-23 19:49:49 -07:00
jss2a98aj 27243991b7 Add near fog distance percentage slider
Initial commit by MellowArpeggiation and George Paton
FOG_NEAR to FOG_NEAR_DISTANCE, minimum of 1% by jss2a98aj
2024-05-23 19:49:49 -07:00
jss2a98aj 956eec0366 Face culling for the Enchantment Table 2024-05-23 19:49:49 -07:00
jss2a98aj 9b06c5a210 Add interpolated icon support (Roadhog360) 2024-05-23 19:49:49 -07:00
jss2a98aj 5511759b6d Fix door smooth lighting, cull sides against solid blocks 2024-05-23 19:49:49 -07:00
jss2a98aj fb5aa81e01 Sandstone connected textures 2024-05-23 19:49:49 -07:00
jss2a98aj 6592e13e02 Improve Bookshelf connected textures 2024-05-23 19:49:49 -07:00
Jason Mitchell 31174dc35a Update README.MD 2024-05-23 17:57:46 -07:00
Caedis f0bd9de081 Disable Dynamic Lights video option when module is disabled (#491) 2024-05-17 20:18:23 +00:00
Jason Mitchell 75617a5456 More null checks 2024-05-14 23:23:01 -07:00
Jason Mitchell e158faada0 Only set/access texture info cache from the main thread 2024-05-14 22:35:21 -07:00
Raven Szewczyk f684bc0a1b Fix RenderBlockFluid reading the block type from the world access multiple times (#482)
* Fix RenderBlockFluid reading the block type from the world access multiple times

* Fix compiler warnings
2024-05-13 18:04:58 +01:00
Jason Mitchell 3d56b1c2fc Make TextureInfoCache safer 2024-05-12 09:35:43 -07:00
Jason Mitchell 6e60f671b5 Neuter FML optifine detection/reporting 2024-05-11 10:33:45 -07:00
Caedis 323d2e726c Adjust dynamic lights in World#getLightBrightnessForSkyBlocks as well (#466)
This can be called when rendering is done on the main there as
WorldSlice is only used outside the main thread.
2024-05-06 08:50:25 -07:00
179 changed files with 5128 additions and 2385 deletions

No files matched your search

@@ -0,0 +1,33 @@
name: Feature Request
description: "Request a feature."
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: "Please use this form to request features. We ask you check if it was already requested though"
- type: input
id: discord
attributes:
label: Your GTNH Discord Username
description: Leave empty if you don't have one, but this will make it harder to contact you if we need additional info.
placeholder: "Example: Wumpus#1234"
- type: textarea
id: request
attributes:
label: Feature Request
description: "Relevant information, as well as relevant images"
placeholder: "Example: https://mclo.gs/ OR submit the file to github by dragging it to this textbox."
validations:
required: true
- type: checkboxes
id: final
attributes:
label: Final Checklist
description: Certify that you read things
options:
- label: "I have searched the issues and haven't found a similar issue."
required: true
- label: "I have read the known incompatibilities and this is not related to one of those."
required: true
- label: "This issue is not related to a feature that is disabed by default - Shaders, MCPF, etc. [They'll be enabled when they're ready for testing]"
required: true
+6
View File
@@ -1,6 +1,7 @@
.gradle
.settings
/.idea/
/.vs/
/.vscode/
/run/
/build/
@@ -30,3 +31,8 @@ src/main/resources/mixins.*([!.]).json
*.bat
*.DS_Store
!gradlew.bat
layout.json
addon.local.gradle
addon.local.gradle.kts
addon.late.local.gradle
addon.late.local.gradle.kts
+19 -12
View File
@@ -6,31 +6,38 @@
* Is it obtuse, or accute? -Caedis
* It's a cute angle -mitchej123
**Alpha Quality - Here there be Dragons**
## **Beta Quality - Here there be Dragons**
* Shaders sneak preview - Please don't report issues yet, but please do submit fixes
* Complementary & BSL mostly function, but have some bugs
* Sildurs, Seus, and any other shader probably doesn't work
# Required Dependencies
* [UniMixins](https://github.com/LegacyModdingMC/UniMixins/releases) >= 0.1.14
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.2.9
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.3.2
* NOTE: Some mods are not required, but a specific version is required if present - see: `Permanent Incompatibilities` below.
# Known (temporary) Incompatibilities
* Forge Relocation - Currently non Thread Safe; safe if not in use
* ProjectRed Frames - Currently non Thread Safe; safe if not in use
* EndlessIDs - Future compat planned
* FalseTweaks - Future compat planned
* SmoothFont - Future compat planned
* RPLE - Future compat planned
* ProjectRed Frames - Currently non Thread Safe; safe if not in use'
# Potential Incompatibilities
* EndlessIDs - Compat commits have been made, might work, might not - not fully tested
# Known Incompatibilities
* FalseTweaks - Not currently planned (Looking for volunteers) [Might work if you effectively disable most of the mod]
* SmoothFont - Not currently planned (Looking for volunteers)
* RPLE - Not currently planned (Looking for volunteers)
# Permanent Incompatibilities
* Optifine [Disabled, won't fix]
* Fastcraft [Disable, won't fix]
* BetterFPS [Won't fix]
* OptiFine [Disabled, won't fix]
* FastCraft [Disabled, won't fix]
* BetterFPS [Disabled, won't fix]
* LWJGL3ify 1.5.4 and below - Use the latest version available, 1.5.7+
* ArchaicFix 0.6.2 and below - Use 0.7.0 or above
* Hodgepodge 2.4.3 and below - [Use 2.4.4 or above](https://github.com/GTNewHorizons/Hodgepodge/releases)
* CodeChicken[Core](https://github.com/GTNewHorizons/CodeChickenCore/releases)/[Lib](https://github.com/GTNewHorizons/CodeChickenLib/releases) <1.2.0 - Threading issues, use 1.2.0+
* Neodymium - Untested, but unlikely to be compatible. (Chunk Meshing is definitely incompatible, other features might work depending on config)
* 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)
# Credits
* ShadersMod
+16 -3
View File
@@ -56,9 +56,12 @@ dependencies {
compileOnly("org.projectlombok:lombok:1.18.22") { transitive = false }
annotationProcessor("org.projectlombok:lombok:1.18.22")
// Use modern models+textures to inject QuadProviders
devOnlyNonPublishable('com.github.GTNewHorizons:TX-Loader:1.7.1:dev')
// Iris Shaders
compileOnly('org.jetbrains:annotations:24.0.1')
api("com.github.GTNewHorizons:GTNHLib:0.2.9:dev")
api("com.github.GTNewHorizons:GTNHLib:0.3.2:dev")
shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0
implementation("io.github.douira:glsl-transformer:1.0.0")
shadowImplementation("io.github.douira:glsl-transformer:1.0.0") { // glsl-transformer Noncommercial License 1.0.0
@@ -78,12 +81,22 @@ dependencies {
compileOnly("com.github.GTNewHorizons:TinkersConstruct:1.12.0-GTNH:dev")
compileOnly("com.github.GTNewHorizons:Natura:2.6.1:dev")
compileOnly("com.falsepattern:chunkapi-mc1.7.10:0.5.0:api") { transitive = false }
compileOnly("com.falsepattern:endlessids-mc1.7.10:1.5-beta0002:dev") { transitive = false }
compileOnly("com.github.GTNewHorizons:ThaumicHorizons:1.6.1:dev")
compileOnly("com.github.GTNewHorizons:Battlegear2:1.4.0:dev") { transitive = false }
compileOnly(rfg.deobf('maven.modrinth:backhand:1.4.1')) { transitive = false }
compileOnly("com.github.GTNewHorizons:Battlegear2:1.4.0:dev") { transitive = false }
compileOnly(rfg.deobf('maven.modrinth:backhand:1.4.1')) { transitive = false }
compileOnly("com.falsepattern:chunkapi-mc1.7.10:0.5.1:api") { transitive = false }
compileOnly("com.falsepattern:endlessids-mc1.7.10:1.5-beta0003:dev") { transitive = false }
compileOnly(rfg.deobf("curse.maven:extrautils-225561:2264383"))
compileOnly(rfg.deobf("curse.maven:dynamiclights-227874:2337326"))
compileOnly("curse.maven:minefactory-reloaded-66672:2277486")
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.0.3:dev") // Mixin Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds-Legacy:1.4.7:dev") // ASM Version
Binary file not shown.
+1 -1
View File
@@ -16,5 +16,5 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.21'
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.24'
}
@@ -15,7 +15,7 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent;
name = "Angelica",
version = Tags.VERSION,
dependencies = " before:lwjgl3ify@[1.5.3,);" + " after:hodgepodge@[2.4.4,);" + " after:CodeChickenCore@[1.2.0,);"
+ " after:archaicfix@[0.7.0,);" + " required-after:gtnhlib@[0.2.9,);",
+ " after:archaicfix@[0.7.0,);" + " required-after:gtnhlib@[0.3.2,);",
acceptedMinecraftVersions = "[1.7.10]",
acceptableRemoteVersions = "*",
guiFactory = "com.gtnewhorizons.angelica.config.AngelicaGuiConfigFactory")
@@ -1,24 +1,10 @@
package com.gtnewhorizons.angelica.api;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import com.gtnewhorizons.angelica.compat.mojang.BlockPosImpl;
import net.minecraft.util.MathHelper;
import net.minecraftforge.common.util.ForgeDirection;
import java.math.RoundingMode;
import static com.google.common.math.IntMath.log2;
public interface BlockPos {
int SIZE_BITS_X = 1 + log2(MathHelper.roundUpToPowerOfTwo(30000000), RoundingMode.UNNECESSARY);
int SIZE_BITS_Z = SIZE_BITS_X;
int SIZE_BITS_Y = 64 - SIZE_BITS_X - SIZE_BITS_Z;
long BITS_X = (1L << SIZE_BITS_X) - 1L;
long BITS_Y = (1L << SIZE_BITS_Y) - 1L;
long BITS_Z = (1L << SIZE_BITS_Z) - 1L;
int BIT_SHIFT_Z = SIZE_BITS_Y;
int BIT_SHIFT_X = SIZE_BITS_Y + SIZE_BITS_Z;
int getX();
int getY();
int getZ();
@@ -28,22 +14,6 @@ public interface BlockPos {
long asLong();
static long asLong(int x, int y, int z) {
long l = 0L;
l |= ((long) x & BITS_X) << BIT_SHIFT_X;
l |= ((long) y & BITS_Y) << 0;
l |= ((long) z & BITS_Z) << BIT_SHIFT_Z;
return l;
}
public static int unpackLongX(long packedPos) {
return (int)(packedPos << 64 - BIT_SHIFT_X - SIZE_BITS_X >> 64 - SIZE_BITS_X);
}
public static int unpackLongY(long packedPos) {
return (int)(packedPos << 64 - SIZE_BITS_Y >> 64 - SIZE_BITS_Y);
}
public static int unpackLongZ(long packedPos) {
return (int)(packedPos << 64 - BIT_SHIFT_Z - SIZE_BITS_Z >> 64 - SIZE_BITS_Z);
return CoordinatePacker.pack(x, y, z);
}
}
@@ -1,11 +1,17 @@
package com.gtnewhorizons.angelica.models.json;
package com.gtnewhorizons.angelica.api;
import com.google.common.annotations.Beta;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import com.gtnewhorizons.angelica.models.json.JsonModel;
import com.gtnewhorizons.angelica.utils.Callback;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -13,28 +19,35 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
/**
* Model loading should proceed as follows: <ul>
* <li>Models to load are registered in PREINIT.</li>
* <li>All registered models are recursively loaded in INIT.</li>
* <li>Models registered for baking are baked on the first tick of the game.</li>
* Model loading is as follows: <ul>
* <li>Models to load are registered in PREINIT or INIT. See {@link #registerModels(Callback, Collection)}.</li>
* <li>A resource rebuild is triggered, then registered models and their parents are recursively loaded in POSTINIT.
* </li>
* <li>Models registered for baking are baked on the first client tick.</li>
*</ul>
* <p>Alternatively, you can register blocks with blockstate variants in preinit, and the rest is handled by
* {@link Loader}.
* <p>As for icons, register them in {@link Block#registerBlockIcons}. Whatever gets them in the block texture atlas.
*/
public class Loader {
@Beta
public class ModelLoader {
static final Gson GSON = new GsonBuilder()
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(JsonModel.class, new JsonModel.Deserializer()).create();
private static final List<ResourceLocation> unloadedModels = new ObjectArrayList<>();
private static final Map<ResourceLocation, JsonModel> loadedModels = new Object2ObjectOpenHashMap<>();
private static final Map<Variant, JsonModel> modelsToBake = new Object2ObjectOpenHashMap<>();
private static final List<Callback> postBakeCallbacks = new ObjectArrayList<>();
/**
* Convenience method to register a baker callback, which will be run after JSON models are baked. Useful if
* you implemented your own non-JSON model that still needs baking.
*/
public static void registerBaker(Callback baker) {
postBakeCallbacks.add(baker);
}
/**
* Convenience method to register multiple variants. See {@link #registerModels(Callback, Collection)}.
*/
@@ -65,21 +78,20 @@ public class Loader {
if (l == null) continue;
if (loadedModels.containsKey(l)) continue;
final JsonModel model = loadJson(
"/assets/" + l.getResourceDomain() + "/models/" + l.getResourcePath() + ".json", JsonModel.class);
final JsonModel model = loadJson(l, JsonModel.class);
unloadedModels.addAll(model.getParents());
loadedModels.put(l, model);
}
}
private static <T> T loadJson(String path, Class<T> clazz) {
try (final InputStream is = Loader.class.getResourceAsStream(path)) {
private static <T> T loadJson(ResourceLocation path, Class<T> clazz) {
try {
final InputStream is = Minecraft.getMinecraft().getResourceManager().getResource(path).getInputStream();
return GSON.fromJson(new InputStreamReader(is), clazz);
} catch (IOException e) {
} catch (IOException | NullPointerException e) {
AngelicaTweaker.LOGGER.fatal("Could not find " + path);
AngelicaTweaker.LOGGER.fatal("Could not find " + path.getResourceDomain() + " " + path.getResourcePath());
throw new RuntimeException(e);
}
}
@@ -91,6 +103,7 @@ public class Loader {
final JsonModel dough = new JsonModel(loadedModels.get(l.getKey().getModel()));
// Resolve the parent chain
//noinspection SuspiciousMethodCalls
dough.resolveParents(loadedModels::get);
// Bake
@@ -103,7 +116,7 @@ public class Loader {
c.run();
}
public static JsonModel getModel(Variant loc) {
public static QuadProvider getModel(Variant loc) {
return modelsToBake.get(loc);
}
}
@@ -0,0 +1,233 @@
package com.gtnewhorizons.angelica.api;
import com.gtnewhorizons.angelica.models.NdQuadBuilder;
import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView;
import me.jellysquid.mods.sodium.client.model.quad.ModelQuadViewMutable;
import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Vector3f;
public interface QuadBuilder {
/**
* Causes texture to appear with no rotation.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
int BAKE_ROTATE_NONE = 0;
/**
* Causes texture to appear rotated 90 deg. clockwise relative to nominal face.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
int BAKE_ROTATE_90 = 1;
/**
* Causes texture to appear rotated 180 deg. relative to nominal face.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
int BAKE_ROTATE_180 = 2;
/**
* Causes texture to appear rotated 270 deg. clockwise relative to nominal face.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
int BAKE_ROTATE_270 = 3;
/**
* When enabled, texture coordinate are assigned based on vertex position.
* Any existing UV coordinates will be replaced.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*
* <p>UV lock always derives texture coordinates based on nominal face, even
* when the quad is not co-planar with that face, and the result is
* the same as if the quad were projected onto the nominal face, which
* is usually the desired result.
*/
int BAKE_LOCK_UV = 4;
/**
* When set, U texture coordinates for the given sprite are
* flipped as part of baking. Can be useful for some randomization
* and texture mapping scenarios. Results are different from what
* can be obtained via rotation and both can be applied.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
int BAKE_FLIP_U = 8;
/**
* Same as {@link #BAKE_FLIP_U} but for V coordinate.
*/
int BAKE_FLIP_V = 16;
/**
* UV coordinates by default are assumed to be 0-16 scale for consistency
* with conventional Minecraft model format. This is scaled to 0-1 during
* baking before interpolation. Model loaders that already have 0-1 coordinates
* can avoid wasteful multiplication/division by passing 0-1 coordinates directly.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
int BAKE_NORMALIZED = 32;
/**
* Tolerance for determining if the depth parameter to {@link #square(ForgeDirection, float, float, float, float, float)}
* is effectively zero - meaning the face is a cull face.
*/
float CULL_FACE_EPSILON = 0.00001f;
static QuadBuilder getBuilder() {
return new NdQuadBuilder();
}
/**
* Copies data to out, returns it, and resets builder for further use.
*/
QuadView build(QuadView out);
/**
* See {@link #build(QuadView)}. This also rotates the output by the given matrix.
*/
QuadView build(QuadView out, Matrix4f rotMat);
/**
* Tries to automatically set the culling and nominal face from the quad's geometry.
*/
void setCullFace();
/**
* Provides a hint to renderer about the facing of this quad. Not required,
* but if provided can shortcut some geometric analysis if the quad is parallel to a block face.
* Should be the expected value of {@link ModelQuadView#getLightFace()}. Value will be confirmed
* and if invalid the correct light face will be calculated.
*
* <p>Null by default, and set automatically by {@link ModelQuadViewMutable#setCullFace(ForgeDirection)}.
*
* <p>Models may also find this useful as the face for texture UV locking and rotation semantics.
*
* <p>Note: This value is not persisted independently when the quad is encoded.
* When reading encoded quads, this value will always be the same as {@link ModelQuadView#getLightFace()}.
*/
void nominalFace(@Nullable ForgeDirection face);
/**
* See {@link #nominalFace(ForgeDirection)}
*/
ForgeDirection nominalFace();
/**
* Sets the geometric vertex position for the given vertex,
* relative to block origin, (0,0,0). Minecraft rendering is designed
* for models that fit within a single block space and is recommended
* that coordinates remain in the 0-1 range, with multi-block meshes
* split into multiple per-block models.
*/
void pos(int vertexIndex, float x, float y, float z);
/**
* Convenience: set pos with a vector. See {@link #pos(int, float, float, float)}.
*/
void pos(int vertexIndex, Vector3f vec);
/**
* Gets the vertex position as a vector. This allocates a new vector, do not use in dynamic rendering!
*/
Vector3f pos(int vertexIndex);
/**
* Convenience: access x, y, z by index 0-2.
*/
float posByIndex(int vertexIndex, int coordinateIndex);
/**
* Convienence, gets the icon from the block atlas. See {@link #spriteBake(IIcon, int)}
*/
void spriteBake(String spriteName, int bakeFlags);
/**
* Assigns sprite atlas u,v coordinates to this quad for the given sprite.
* Can handle UV locking, rotation, interpolation, etc. Control this behavior
* by passing additive combinations of the BAKE_ flags defined in this interface.
*/
void spriteBake(IIcon sprite, int bakeFlags);
/**
* Helper method to assign vertex coordinates for a square aligned with the given face.
* Ensures that vertex order is consistent with vanilla convention. (Incorrect order can
* lead to bad AO lighting unless enhanced lighting logic is available/enabled.)
*
* <p>Square will be parallel to the given face and coplanar with the face (and culled if the
* face is occluded) if the depth parameter is approximately zero. See {@link #CULL_FACE_EPSILON}.
*
* <p>All coordinates should be normalized (0-1).
*
* <p>The directions for the faces assume you're looking at them. For top and bottom, they assume you're looking north.
*/
void square(ForgeDirection nominalFace, float left, float bottom, float right, float top, float depth);
int tag();
/**
* Encodes an integer tag with this quad that can later be retrieved via
* {@link #tag()}. Useful for models that want to perform conditional
* transformation or filtering on static meshes.
*/
void tag(int tag);
/**
* Set texture coordinates.
*/
void uv(int vertexIndex, float u, float v);
/**
* Modern Minecraft uses magic arrays to do this without breaking AO. This is the same thing, but without arrays.
*/
static Vector3f mapSideToVertex(Vector3f from, Vector3f to, int index, ForgeDirection side) {
return switch (side) {
case DOWN -> switch (index) {
case 0 -> new Vector3f(from.x, from.y, to.z);
case 1 -> new Vector3f(from.x, from.y, from.z);
case 2 -> new Vector3f(to.x, from.y, from.z);
case 3 -> new Vector3f(to.x, from.y, to.z);
default -> throw new RuntimeException("Too many indices!");
};
case UP -> switch (index) {
case 0 -> new Vector3f(from.x, to.y, from.z);
case 1 -> new Vector3f(from.x, to.y, to.z);
case 2 -> new Vector3f(to.x, to.y, to.z);
case 3 -> new Vector3f(to.x, to.y, from.z);
default -> throw new RuntimeException("Too many indices!");
};
case NORTH -> switch (index) {
case 0 -> new Vector3f(to.x, to.y, from.z);
case 1 -> new Vector3f(to.x, from.y, from.z);
case 2 -> new Vector3f(from.x, from.y, from.z);
case 3 -> new Vector3f(from.x, to.y, from.z);
default -> throw new RuntimeException("Too many indices!");
};
case SOUTH -> switch (index) {
case 0 -> new Vector3f(from.x, to.y, to.z);
case 1 -> new Vector3f(from.x, from.y, to.z);
case 2 -> new Vector3f(to.x, from.y, to.z);
case 3 -> new Vector3f(to.x, to.y, to.z);
default -> throw new RuntimeException("Too many indices!");
};
case WEST -> switch (index) {
case 0 -> new Vector3f(from.x, to.y, from.z);
case 1 -> new Vector3f(from.x, from.y, from.z);
case 2 -> new Vector3f(from.x, from.y, to.z);
case 3 -> new Vector3f(from.x, to.y, to.z);
default -> throw new RuntimeException("Too many indices!");
};
case EAST -> switch (index) {
case 0 -> new Vector3f(to.x, to.y, to.z);
case 1 -> new Vector3f(to.x, from.y, to.z);
case 2 -> new Vector3f(to.x, from.y, from.z);
case 3 -> new Vector3f(to.x, to.y, from.z);
default -> throw new RuntimeException("Too many indices!");
};
case UNKNOWN -> null;
};
}
}
@@ -15,12 +15,18 @@ public interface QuadProvider {
int B_MASK = 0xFF;
/**
* Returns the color packed as ABGR. If you want to vary colors within a block, just ignore the color passed into
* {@link #getQuads} and use whatever you want. You might want to override this to return a constant if you're
* extending a block with an expensive color call, like leaves.
* Called once per block and returns the color packed as ABGR. If you want to vary colors within a block, just
* ignore the color passed into {@link #getQuads} and use your own function, don't override this. But if you only
* want to change color once per block, like vanilla leaves, override this. The default vanilla adapter is
* {@link #getDefaultColor}
*/
default int getColor(IBlockAccess world, BlockPos pos, Block block, int meta, Random random) {
return -1;
}
static int getDefaultColor(IBlockAccess world, BlockPos pos, Block block) {
final int cin = block.colorMultiplier(world, pos.getX(), pos.getY(), pos.getZ());
return (0xFF << 24) | ((cin & B_MASK) << 16) | (cin & G_MASK) | ((cin & R_MASK) >>> 16);
}
@@ -1,19 +1,25 @@
package com.gtnewhorizons.angelica.api;
import me.jellysquid.mods.sodium.client.model.quad.ModelQuadViewMutable;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import me.jellysquid.mods.sodium.client.render.pipeline.BlockRenderer;
import net.minecraftforge.common.util.ForgeDirection;
import javax.annotation.Nullable;
public interface QuadView extends ModelQuadViewMutable {
/**
* Allocates a new quad - use sparingly, and not at all in render paths if you can help it. We don't need another
* Malice Doors.
*/
static QuadView allocate() {
return new Quad();
}
boolean isShade();
boolean isDeleted();
ForgeDirection getFace();
void copyFrom(QuadView src);
void setRaw(int[] data, boolean shade, @Nullable ForgeDirection face, int colorIndex, int flags);
int[] getRawVertexes();
QuadView copyFrom(QuadView src);
int[] getRawData();
/**
* Present for compatibility with the Tesselator, not recommended for general use.
@@ -1,11 +1,13 @@
package com.gtnewhorizons.angelica.models.json;
package com.gtnewhorizons.angelica.api;
import com.google.common.annotations.Beta;
import lombok.Getter;
import net.minecraft.util.ResourceLocation;
import org.joml.Matrix4f;
import static java.lang.Math.toRadians;
@Beta
public class Variant {
@Getter
@@ -21,9 +23,12 @@ public class Variant {
this.uvLock = uvLock;
}
Matrix4f getAffineMatrix() {
public Matrix4f getAffineMatrix() {
return new Matrix4f()
.translation(-.5f, -.5f, -.5f).rotateLocalY(x).rotateLocalX(y).translateLocal(.5f, .5f, .5f);
.translation(-.5f, -.5f, -.5f)
.rotateLocalY(x)
.rotateLocalX(y)
.translateLocal(.5f, .5f, .5f);
}
}
@@ -1,64 +1,34 @@
package com.gtnewhorizons.angelica.common;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.models.json.JsonModel;
import com.gtnewhorizons.angelica.models.json.Loader;
import com.gtnewhorizons.angelica.models.json.Variant;
import it.unimi.dsi.fastutil.objects.ObjectImmutableList;
import com.gtnewhorizons.angelica.mixins.interfaces.ModeledBlock;
import com.gtnewhorizons.angelica.utils.AssetLoader;
import lombok.Getter;
import lombok.Setter;
import me.jellysquid.mods.sodium.common.util.DirectionUtil;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import static com.gtnewhorizons.angelica.models.VanillaModels.LECTERN;
public class BlockTest extends Block implements QuadProvider {
public class BlockTest extends Block implements ModeledBlock {
public static final Variant[] modelId = {
new Variant(
new ResourceLocation("blocks/lectern"),
0,
0,
false
),
new Variant(
new ResourceLocation("blocks/lectern"),
180,
0,
false
),
new Variant(
new ResourceLocation("blocks/lectern"),
90,
0,
false
),
new Variant(
new ResourceLocation("blocks/lectern"),
270,
0,
false
),
};
private static final List<QuadView> EMPTY = ObjectImmutableList.of();
private static final JsonModel[] model = new JsonModel[4];
@Getter
@Setter
private QuadProvider model;
public BlockTest() {
super(Material.rock);
}
public static void loadModel() {
for (int i = 0; i < 4; ++i)
model[i] = Loader.getModel(modelId[i]);
this.setBlockTextureName("missingno");
this.setModel((world, pos, block, meta, dir, random, color, quadPool) -> {
if (meta < 2 || meta > 5) meta = 2;
return LECTERN.models[meta - 2].getQuads(world, pos, block, meta, dir, random, color, quadPool);
});
}
@Override
@@ -68,21 +38,9 @@ public class BlockTest extends Block implements QuadProvider {
@Override
public void registerBlockIcons(IIconRegister reg) {
reg.registerIcon("angelica:test_block");
reg.registerIcon("lectern_base");
reg.registerIcon("lectern_front");
reg.registerIcon("lectern_sides");
reg.registerIcon("lectern_top");
reg.registerIcon("oak_planks");
}
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
if (meta < 2 || meta > 5) meta = 2;
return (model[meta - 2] != null) ? model[meta - 2].getQuads(world, pos, block, meta, dir, random, color, quadPool) : EMPTY;
for (String s : AssetLoader.testTexs) {
reg.registerIcon(s);
}
}
/**
@@ -92,7 +50,7 @@ public class BlockTest extends Block implements QuadProvider {
public int onBlockPlaced(@NotNull World worldIn, int x, int y, int z, int side, float subX, float subY, float subZ, int meta) {
// Face NORTH if placed up or down
final ForgeDirection s = ForgeDirection.values()[side];
final ForgeDirection s = DirectionUtil.ALL_DIRECTIONS[side];
if (s == ForgeDirection.UP || s == ForgeDirection.DOWN)
return 2;
@@ -5,6 +5,7 @@ import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import net.dries007.holoInventory.HoloInventory;
import xonin.backhand.Backhand;
public class ModStatus {
/**
@@ -23,6 +24,10 @@ public class ModStatus {
public static boolean isEIDBiomeLoaded;
public static boolean isXaerosMinimapLoaded;
public static boolean isHoloInventoryLoaded;
public static boolean isBattlegearLoaded;
public static boolean isBackhandLoaded;
public static boolean isThaumcraftLoaded;
public static boolean isThaumicHorizonsLoaded;
public static void preInit(){
isBetterCrashesLoaded = Loader.isModLoaded("bettercrashes");
@@ -33,6 +38,10 @@ public class ModStatus {
isEIDBiomeLoaded = Loader.isModLoaded("endlessids_biome");
isXaerosMinimapLoaded = Loader.isModLoaded("XaeroMinimap");
isHoloInventoryLoaded = Loader.isModLoaded("holoinventory");
isBattlegearLoaded = Loader.isModLoaded("battlegear2");
isBackhandLoaded = Loader.isModLoaded("backhand");
isThaumcraftLoaded = Loader.isModLoaded("Thaumcraft");
isThaumicHorizonsLoaded = Loader.isModLoaded("ThaumicHorizons");
if (isHoloInventoryLoaded){
isHoloInventoryLoaded = new DefaultArtifactVersion("2.4.4-GTNH")
@@ -41,6 +50,13 @@ public class ModStatus {
) <= 0;
}
if (isBackhandLoaded){
isBackhandLoaded = new DefaultArtifactVersion("1.4.1")
.compareTo(
LoadControllerHelper.getOwningMod(Backhand.class).getProcessedVersion()
) <= 0;
}
isNEIDMetadataExtended = false;
if (isNEIDLoaded) {
@@ -0,0 +1,37 @@
package com.gtnewhorizons.angelica.compat.endlessids;
import com.falsepattern.endlessids.mixin.helpers.ChunkBiomeHook;
import lombok.val;
import net.minecraft.world.chunk.Chunk;
import static com.falsepattern.endlessids.constants.ExtendedConstants.biomeIDMask;
import static com.falsepattern.endlessids.constants.ExtendedConstants.biomeIDNull;
public class EndlessIDsCompat {
public static void sodium$populateBiomes(Chunk chunk) {
if (!(chunk instanceof ChunkBiomeHook hook))
return;
val biomes = hook.getBiomeShortArray();
if (biomes == null)
return;
val cX = chunk.xPosition << 4;
val cZ = chunk.zPosition << 4;
val manager = chunk.worldObj.getWorldChunkManager();
for(var z = 0; z < 16; z++) {
for(var x = 0; x < 16; x++) {
val idx = (z << 4) + x;
val biome = biomes[idx] & biomeIDMask;
if(biome == biomeIDNull) {
val generated = manager.getBiomeGenAt(cX + x, cZ + z);
if (generated == null)
continue;
biomes[idx] = (short)(generated.biomeID & biomeIDMask);
}
}
}
}
}
@@ -1,14 +1,11 @@
package com.gtnewhorizons.angelica.compat.mojang;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import com.gtnewhorizons.angelica.api.MutableBlockPos;
import net.minecraft.world.ChunkPosition;
import net.minecraftforge.common.util.ForgeDirection;
import org.joml.Vector3i;
import static com.gtnewhorizons.angelica.api.BlockPos.unpackLongX;
import static com.gtnewhorizons.angelica.api.BlockPos.unpackLongY;
import static com.gtnewhorizons.angelica.api.BlockPos.unpackLongZ;
// Should we keep this?
public class BlockPosImpl extends Vector3i implements MutableBlockPos {
@@ -54,7 +51,7 @@ public class BlockPosImpl extends Vector3i implements MutableBlockPos {
@Override
public long asLong() {
return BlockPos.asLong(this.x, this.y, this.z);
return CoordinatePacker.pack(this.x, this.y, this.z);
}
@Override
@@ -65,6 +62,7 @@ public class BlockPosImpl extends Vector3i implements MutableBlockPos {
@Override
public BlockPosImpl set(long packedPos) {
return set(unpackLongX(packedPos), unpackLongY(packedPos), unpackLongZ(packedPos));
CoordinatePacker.unpack(packedPos, this);
return this;
}
}
@@ -2,7 +2,6 @@ package com.gtnewhorizons.angelica.compat.mojang;
import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
import it.unimi.dsi.fastutil.ints.IntPriorityQueue;
import me.jellysquid.mods.sodium.common.util.DirectionUtil;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.BitSet;
@@ -17,7 +16,7 @@ public class ChunkOcclusionDataBuilder {
private static final int STEP_X = (int)Math.pow(16.0, 0.0);
private static final int STEP_Z = (int)Math.pow(16.0, 1.0);
private static final int STEP_Y = (int)Math.pow(16.0, 2.0);
private static final ForgeDirection[] DIRECTIONS = DirectionUtil.ALL_DIRECTIONS;
private static final ForgeDirection[] DIRECTIONS = ForgeDirection.VALID_DIRECTIONS;
private final BitSet closed = new BitSet(4096);
private static final int[] EDGE_POINTS = new int[1352];
@@ -1,21 +0,0 @@
package com.gtnewhorizons.angelica.compat.toremove;
import com.gtnewhorizons.angelica.compat.mojang.VertexFormat;
import lombok.Getter;
@Deprecated
public class DrawState {
@Getter
private final VertexFormat format;
@Getter
private final int vertexCount;
@Getter
private final int mode;
public DrawState(VertexFormat format, int vertexCount, int mode) {
this.format = format;
this.vertexCount = vertexCount;
this.mode = mode;
}
}
@@ -1,8 +0,0 @@
package com.gtnewhorizons.angelica.compat.toremove;
@Deprecated
public class OverlayTexture {
// This is definitely wrong
public static final int NO_OVERLAY = 0;
}
@@ -140,7 +140,6 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
private final RenderPhase.DepthTest depthTest;
private final RenderPhase.Cull cull;
private final RenderPhase.Lightmap lightmap;
private final RenderPhase.Overlay overlay;
private final RenderPhase.Fog fog;
private final RenderPhase.Layering layering;
private final RenderPhase.Target target;
@@ -150,7 +149,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
private final OutlineMode outlineMode;
private final ImmutableList<RenderPhase> phases;
private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Overlay overlay, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, RenderPhase.LineWidth lineWidth, OutlineMode outlineMode) {
private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, RenderPhase.LineWidth lineWidth, OutlineMode outlineMode) {
this.texture = texture;
this.transparency = transparency;
this.diffuseLighting = diffuseLighting;
@@ -159,7 +158,6 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
this.depthTest = depthTest;
this.cull = cull;
this.lightmap = lightmap;
this.overlay = overlay;
this.fog = fog;
this.layering = layering;
this.target = target;
@@ -167,7 +165,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
this.writeMaskState = writeMaskState;
this.lineWidth = lineWidth;
this.outlineMode = outlineMode;
this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.overlay, this.fog, this.layering, this.target, new RenderPhase[]{this.texturing, this.writeMaskState, this.lineWidth});
this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.lineWidth);
}
public boolean equals(Object object) {
@@ -202,7 +200,6 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
private RenderPhase.DepthTest depthTest;
private RenderPhase.Cull cull;
private RenderPhase.Lightmap lightmap;
private RenderPhase.Overlay overlay;
private RenderPhase.Fog fog;
private RenderPhase.Layering layering;
private RenderPhase.Target target;
@@ -219,7 +216,6 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
this.depthTest = RenderPhase.LEQUAL_DEPTH_TEST;
this.cull = RenderPhase.ENABLE_CULLING;
this.lightmap = RenderPhase.DISABLE_LIGHTMAP;
this.overlay = RenderPhase.DISABLE_OVERLAY_COLOR;
this.fog = RenderPhase.FOG;
this.layering = RenderPhase.NO_LAYERING;
this.target = RenderPhase.MAIN_TARGET;
@@ -263,11 +259,6 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
return this;
}
public Builder overlay(RenderPhase.Overlay overlay) {
this.overlay = overlay;
return this;
}
public Builder fog(RenderPhase.Fog fog) {
this.fog = fog;
return this;
@@ -288,7 +279,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
}
public MultiPhaseParameters build(OutlineMode outlineMode) {
return new MultiPhaseParameters(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.overlay, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.lineWidth, outlineMode);
return new MultiPhaseParameters(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.lineWidth, outlineMode);
}
}
}
@@ -69,8 +69,6 @@ public abstract class RenderPhase {
protected static final Texturing ENTITY_GLINT_TEXTURING;
protected static final Lightmap ENABLE_LIGHTMAP;
protected static final Lightmap DISABLE_LIGHTMAP;
protected static final Overlay ENABLE_OVERLAY_COLOR;
protected static final Overlay DISABLE_OVERLAY_COLOR;
protected static final DiffuseLighting ENABLE_DIFFUSE_LIGHTING;
protected static final DiffuseLighting DISABLE_DIFFUSE_LIGHTING;
protected static final Cull ENABLE_CULLING;
@@ -177,8 +175,6 @@ public abstract class RenderPhase {
});
ENABLE_LIGHTMAP = new Lightmap(true);
DISABLE_LIGHTMAP = new Lightmap(false);
ENABLE_OVERLAY_COLOR = new Overlay(true);
DISABLE_OVERLAY_COLOR = new Overlay(false);
ENABLE_DIFFUSE_LIGHTING = new DiffuseLighting(true);
DISABLE_DIFFUSE_LIGHTING = new DiffuseLighting(false);
ENABLE_CULLING = new Cull(true);
@@ -505,25 +501,6 @@ public abstract class RenderPhase {
}
public static class Overlay extends Toggleable {
public Overlay(boolean overlayColor) {
super("overlay", () -> {
if (overlayColor) {
throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getOverlayTexture().setupOverlayColor();
}
}, () -> {
if (overlayColor) {
throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getOverlayTexture().teardownOverlayColor();
}
}, overlayColor);
}
}
public static class Lightmap extends Toggleable {
public Lightmap(boolean lightmap) {
super("lightmap", () -> {
@@ -35,13 +35,11 @@ public class AngelicaConfig {
@Config.Comment("Enable Iris Shaders [Requires Sodium]")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
@Config.Ignore()
public static boolean enableIris;
@Config.Comment("Enable MCPatcherForge features, still in Alpha. Individual features are toggled in mcpatcher.json")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
@Config.Ignore()
public static boolean enableMCPatcherForgeFeatures;
@Config.Comment("Replace some vanilla render paths with more optimized versions. Disable if you encounter mixin conflicts.")
@@ -70,10 +68,19 @@ public class AngelicaConfig {
@Config.DefaultBoolean(true)
public static boolean showSplashMemoryBar;
@Config.Comment("Renders the HUD elements once per tick and reuses the pixels to improve performance. [Experimental]")
@Config.Comment("Renders the HUD elements once per 20 frames (by default) and reuses the pixels to improve performance. [Experimental]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableHudCaching;
@Config.Comment("Inject a conditional early return into all RenderGameOverlayEvent receivers; Requires enableHudCaching")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableHudCachingEventTransformer;
@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.DefaultBoolean(true)
@@ -81,7 +88,7 @@ public class AngelicaConfig {
public static boolean enableFontRenderer;
@Config.Comment("Enable Dynamic Lights")
@Config.DefaultBoolean(false)
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableDynamicLights;
@@ -110,6 +117,16 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean fixExtraUtilsSodiumCompat;
@Config.Comment("Fix thread-safety issues in MineFactory Reloaded")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixMineFactoryReloadedSodiumCompat;
@Config.Comment("Fix RenderBlockFluid reading the block type from the world access multiple times")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixFluidRendererCheckingBlockAgain;
@Config.Comment("Enable Debug Logging")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
@@ -1,15 +1,21 @@
package com.gtnewhorizons.angelica.dynamiclights;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.mojang.BlockPosImpl;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
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 mods.battlegear2.api.core.IInventoryPlayerBattle;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
@@ -18,8 +24,9 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xonin.backhand.api.core.BackhandUtils;
import xonin.backhand.api.core.IBackhandPlayer;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
@@ -42,7 +49,7 @@ public class DynamicLights {
}
public static boolean isEnabled() {
return Mode.isEnabled() && AngelicaConfig.enableDynamicLights;
return AngelicaConfig.enableDynamicLights && Mode.isEnabled() && !IrisApi.getInstance().isShaderPackInUse();
}
/**
@@ -271,7 +278,7 @@ public class DynamicLights {
* @param chunkPos the packed chunk position
*/
public static void scheduleChunkRebuild(@NotNull SodiumWorldRenderer renderer, long chunkPos) {
scheduleChunkRebuild(renderer, BlockPos.unpackLongX(chunkPos), BlockPos.unpackLongY(chunkPos), BlockPos.unpackLongZ(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) {
@@ -287,7 +294,7 @@ public class DynamicLights {
*/
public static void updateTrackedChunks(@NotNull BlockPosImpl chunkPos, @Nullable LongOpenHashSet old, @Nullable LongOpenHashSet newPos) {
if (old != null || newPos != null) {
long pos = chunkPos.asLong();
final long pos = chunkPos.asLong();
if (old != null)
old.remove(pos);
if (newPos != null)
@@ -319,6 +326,9 @@ public class DynamicLights {
* @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;
Item item = stack.getItem();
if (item instanceof ItemBlock itemBlock) {
Block block = itemBlock.field_150939_a;
@@ -337,15 +347,15 @@ public class DynamicLights {
if (entity.fire > 0) return 15;
if (entity instanceof EntityItem item) {
return getLuminanceFromItemStack(item.getEntityItem(), item.isInWater());
return getLuminanceFromItemStack(item.getEntityItem(), item.isInsideOfMaterial(Material.water));
}
if (entity instanceof EntityLivingBase living) {
int luminance = 0;
boolean inWater = living.isInWater();
boolean inWater = living.isInsideOfMaterial(Material.water);
// check equipment + hand for light
// 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) {
@@ -353,6 +363,23 @@ public class DynamicLights {
}
}
if (ModStatus.isBattlegearLoaded &&
living instanceof EntityPlayer player &&
player instanceof IBattlePlayer battlePlayer &&
battlePlayer.battlegear2$isBattlemode()
) {
ItemStack offhand = ((IInventoryPlayerBattle) player.inventory).battlegear2$getCurrentOffhandWeapon();
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand, inWater));
}
}
else if (ModStatus.isBackhandLoaded && living instanceof EntityPlayer player){
ItemStack offhand = BackhandUtils.getOffhandItem(player);
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand, inWater));
}
}
return luminance;
}
@@ -77,12 +77,19 @@ public class Feature {
// GL_AUTO_NORMAL flag
, GLStateManager.blendMode // GL_BLEND flag
// Enable bits for the user-definable clipping planes
// GL_COLOR_MATERIAL
, GLStateManager.colorMaterial // GL_COLOR_MATERIAL
, GLStateManager.cullState // GL_CULL_FACE flag
, GLStateManager.depthTest // GL_DEPTH_TEST flag
// GL_DITHER flag
, GLStateManager.fogMode // GL_FOG flag
// GL_LIGHTi where 0 <= i < GL_MAX_LIGHTS
, GLStateManager.lightStates[0] // GL_LIGHT0
, GLStateManager.lightStates[1] // GL_LIGHT1
, GLStateManager.lightStates[2] // GL_LIGHT2
, GLStateManager.lightStates[3] // GL_LIGHT3
, GLStateManager.lightStates[4] // GL_LIGHT4
, GLStateManager.lightStates[5] // GL_LIGHT5
, GLStateManager.lightStates[6] // GL_LIGHT6
, GLStateManager.lightStates[7] // GL_LIGHT7
, GLStateManager.lightingState // GL_LIGHTING flag
// GL_LINE_SMOOTH flag
// GL_LINE_STIPPLE flag
@@ -141,20 +148,36 @@ public class Feature {
// GL_TEXTURE_COMPRESSION_HINT setting
));
attribToFeatures.put(GL11.GL_LIGHTING_BIT, ImmutableSet.of(
// GL_COLOR_MATERIAL enable bit
// GL_COLOR_MATERIAL_FACE value
// Color material parameters that are tracking the current color
// Ambient scene color
// GL_LIGHT_MODEL_LOCAL_VIEWER value
// GL_LIGHT_MODEL_TWO_SIDE setting
GLStateManager.lightingState // GL_LIGHTING enable bit
GLStateManager.colorMaterial // GL_COLOR_MATERIAL enable bit
, GLStateManager.colorMaterialFace // GL_COLOR_MATERIAL_FACE value
, GLStateManager.colorMaterialParameter // Color material parameters that are tracking the current color
, GLStateManager.lightModel // Ambient scene color, GL_LIGHT_MODEL_LOCAL_VIEWER, GL_LIGHT_MODEL_TWO_SIDE
, GLStateManager.lightingState // GL_LIGHTING enable bit
// Enable bit for each light
, GLStateManager.lightStates[0] // GL_LIGHT0
, GLStateManager.lightStates[1] // GL_LIGHT1
, GLStateManager.lightStates[2] // GL_LIGHT2
, GLStateManager.lightStates[3] // GL_LIGHT3
, GLStateManager.lightStates[4] // GL_LIGHT4
, GLStateManager.lightStates[5] // GL_LIGHT5
, GLStateManager.lightStates[6] // GL_LIGHT6
, GLStateManager.lightStates[7] // GL_LIGHT7
// Ambient, diffuse, and specular intensity for each light
// Direction, position, exponent, and cutoff angle for each light
// Constant, linear, and quadratic attenuation factors for each light
, GLStateManager.lightDataStates[0]
, GLStateManager.lightDataStates[1]
, GLStateManager.lightDataStates[2]
, GLStateManager.lightDataStates[3]
, GLStateManager.lightDataStates[4]
, GLStateManager.lightDataStates[5]
, GLStateManager.lightDataStates[6]
, GLStateManager.lightDataStates[7]
// Ambient, diffuse, specular, and emissive color for each material
// Ambient, diffuse, and specular color indices for each material
// Specular exponent for each material
, GLStateManager.frontMaterial
, GLStateManager.backMaterial
, GLStateManager.shadeModelState // GL_SHADE_MODEL setting
));
attribToFeatures.put(GL11.GL_LINE_BIT, ImmutableSet.of(
@@ -271,17 +271,20 @@ public final class GLDebug {
private static DebugState debugState;
private interface DebugState {
private interface DebugState {
void nameObject(int id, int object, String name);
void pushGroup(String name);
void popGroup();
void debugMessage(String name);
}
String getObjectLabel(int glProgram, int program);
}
private static class KHRDebugState implements DebugState {
private static final int ID = 0;
private int depth = 0;
private static final int maxDepth = GL11.glGetInteger(KHRDebug.GL_MAX_DEBUG_GROUP_STACK_DEPTH);
private static final int maxNameLength = GL11.glGetInteger(KHRDebug.GL_MAX_LABEL_LENGTH);
@Override
public void nameObject(int id, int object, String name) {
@@ -310,6 +313,14 @@ public final class GLDebug {
public void debugMessage(String message) {
KHRDebug.glDebugMessageInsert(KHRDebug.GL_DEBUG_SOURCE_APPLICATION, KHRDebug.GL_DEBUG_TYPE_MARKER, ID, KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION, message);
}
@Override
public String getObjectLabel(int glProgram, int program) {
if(program == 0)
return "";
return KHRDebug.glGetObjectLabel(glProgram, program, maxNameLength);
}
}
private static class UnsupportedDebugState implements DebugState {
@@ -329,6 +340,11 @@ public final class GLDebug {
public void debugMessage(String name) {
}
@Override
public String getObjectLabel(int glProgram, int program) {
return "";
}
}
public static void initDebugState() {
@@ -359,4 +375,12 @@ public final class GLDebug {
debugState.debugMessage(message);
}
}
public static String getObjectLabel(int glProgram, int program) {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
return debugState.getObjectLabel(glProgram, program);
}
return "";
}
}
@@ -11,6 +11,9 @@ import com.gtnewhorizons.angelica.glsm.stacks.DepthStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.FogStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.IStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.IntegerStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.LightModelStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.LightStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.MaterialStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.MatrixModeStack;
import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack;
import com.gtnewhorizons.angelica.glsm.states.Color4;
@@ -58,7 +61,9 @@ import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.KHRDebug;
import java.lang.Math;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
@@ -91,13 +96,9 @@ public class GLStateManager {
// GLStateManager State Trackers
private static final IntStack attribs = new IntArrayList(MAX_ATTRIB_STACK_DEPTH);
protected static final IntegerStateStack activeTextureUnit = new IntegerStateStack();
protected static final IntegerStateStack shadeModelState = new IntegerStateStack();
protected static final IntegerStateStack activeTextureUnit = new IntegerStateStack(0);
protected static final IntegerStateStack shadeModelState = new IntegerStateStack(GL11.GL_SMOOTH);
static {
activeTextureUnit.setValue(0); // GL_TEXTURE0
shadeModelState.setValue(GL11.GL_SMOOTH);
}
@Getter protected static final TextureUnitArray textures = new TextureUnitArray();
@Getter protected static final BlendStateStack blendState = new BlendStateStack();
@Getter protected static final BooleanStateStack blendMode = new BooleanStateStack(GL11.GL_BLEND);
@@ -121,9 +122,27 @@ public class GLStateManager {
@Getter protected static final Matrix4fStack modelViewMatrix = new Matrix4fStack(MAX_MODELVIEW_STACK_DEPTH);
@Getter protected static final Matrix4fStack projectionMatrix = new Matrix4fStack(MAX_PROJECTION_STACK_DEPTH);
@Getter protected static final BooleanStateStack[] lightStates = new BooleanStateStack[8];
@Getter protected static final LightStateStack[] lightDataStates = new LightStateStack[8];
@Getter protected static final BooleanStateStack colorMaterial = new BooleanStateStack(GL11.GL_COLOR_MATERIAL);
@Getter protected static final IntegerStateStack colorMaterialFace = new IntegerStateStack(GL11.GL_FRONT_AND_BACK);
@Getter protected static final IntegerStateStack colorMaterialParameter = new IntegerStateStack(GL11.GL_AMBIENT_AND_DIFFUSE);
@Getter protected static final LightModelStateStack lightModel = new LightModelStateStack();
@Getter protected static final MaterialStateStack frontMaterial = new MaterialStateStack(GL11.GL_FRONT);
@Getter protected static final MaterialStateStack backMaterial = new MaterialStateStack(GL11.GL_BACK);
static {
for (int i = 0; i < lightStates.length; i ++) {
lightStates[i] = new BooleanStateStack(GL11.GL_LIGHT0 + i);
lightDataStates[i] = new LightStateStack(GL11.GL_LIGHT0 + i);
}
}
@Getter protected static final ViewPortStateStack viewportState = new ViewPortStateStack();
@Getter protected static int activeProgram = 0;
public static void reset() {
runningSplash = true;
while(!attribs.isEmpty()) {
@@ -236,6 +255,9 @@ public class GLStateManager {
}
public static boolean isMainThread() {
return Thread.currentThread() == MainThread;
}
public static void assertMainThread() {
if (Thread.currentThread() != CurrentThread && !runningSplash) {
@@ -256,6 +278,15 @@ public class GLStateManager {
case GL11.GL_DEPTH_TEST -> enableDepthTest();
case GL11.GL_FOG -> enableFog();
case GL11.GL_LIGHTING -> enableLighting();
case GL11.GL_LIGHT0 -> enableLight(0);
case GL11.GL_LIGHT1 -> enableLight(1);
case GL11.GL_LIGHT2 -> enableLight(2);
case GL11.GL_LIGHT3 -> enableLight(3);
case GL11.GL_LIGHT4 -> enableLight(4);
case GL11.GL_LIGHT5 -> enableLight(5);
case GL11.GL_LIGHT6 -> enableLight(6);
case GL11.GL_LIGHT7 -> enableLight(7);
case GL11.GL_COLOR_MATERIAL -> enableColorMaterial();
case GL11.GL_SCISSOR_TEST -> enableScissorTest();
case GL11.GL_TEXTURE_2D -> enableTexture();
case GL12.GL_RESCALE_NORMAL -> enableRescaleNormal();
@@ -271,6 +302,15 @@ public class GLStateManager {
case GL11.GL_DEPTH_TEST -> disableDepthTest();
case GL11.GL_FOG -> disableFog();
case GL11.GL_LIGHTING -> disableLighting();
case GL11.GL_LIGHT0 -> disableLight(0);
case GL11.GL_LIGHT1 -> disableLight(1);
case GL11.GL_LIGHT2 -> disableLight(2);
case GL11.GL_LIGHT3 -> disableLight(3);
case GL11.GL_LIGHT4 -> disableLight(4);
case GL11.GL_LIGHT5 -> disableLight(5);
case GL11.GL_LIGHT6 -> disableLight(6);
case GL11.GL_LIGHT7 -> disableLight(7);
case GL11.GL_COLOR_MATERIAL -> disableColorMaterial();
case GL11.GL_SCISSOR_TEST -> disableScissorTest();
case GL11.GL_TEXTURE_2D -> disableTexture();
case GL12.GL_RESCALE_NORMAL -> disableRescaleNormal();
@@ -289,6 +329,15 @@ public class GLStateManager {
case GL11.GL_DEPTH_TEST -> depthTest.isEnabled();
case GL11.GL_FOG -> fogMode.isEnabled();
case GL11.GL_LIGHTING -> lightingState.isEnabled();
case GL11.GL_LIGHT0 -> lightStates[0].isEnabled();
case GL11.GL_LIGHT1 -> lightStates[1].isEnabled();
case GL11.GL_LIGHT2 -> lightStates[2].isEnabled();
case GL11.GL_LIGHT3 -> lightStates[3].isEnabled();
case GL11.GL_LIGHT4 -> lightStates[4].isEnabled();
case GL11.GL_LIGHT5 -> lightStates[5].isEnabled();
case GL11.GL_LIGHT6 -> lightStates[6].isEnabled();
case GL11.GL_LIGHT7 -> lightStates[7].isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled();
@@ -308,6 +357,15 @@ public class GLStateManager {
case GL11.GL_DEPTH_WRITEMASK -> depthState.isEnabled();
case GL11.GL_FOG -> fogMode.isEnabled();
case GL11.GL_LIGHTING -> lightingState.isEnabled();
case GL11.GL_LIGHT0 -> lightStates[0].isEnabled();
case GL11.GL_LIGHT1 -> lightStates[1].isEnabled();
case GL11.GL_LIGHT2 -> lightStates[2].isEnabled();
case GL11.GL_LIGHT3 -> lightStates[3].isEnabled();
case GL11.GL_LIGHT4 -> lightStates[4].isEnabled();
case GL11.GL_LIGHT5 -> lightStates[5].isEnabled();
case GL11.GL_LIGHT6 -> lightStates[6].isEnabled();
case GL11.GL_LIGHT7 -> lightStates[7].isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled();
@@ -354,6 +412,9 @@ public class GLStateManager {
case GL14.GL_BLEND_DST_RGB -> blendState.getDstRgb();
case GL14.GL_BLEND_SRC_ALPHA -> blendState.getSrcAlpha();
case GL14.GL_BLEND_SRC_RGB -> blendState.getSrcRgb();
case GL11.GL_COLOR_MATERIAL_FACE -> colorMaterialFace.getValue();
case GL11.GL_COLOR_MATERIAL_PARAMETER -> colorMaterialParameter.getValue();
case GL20.GL_CURRENT_PROGRAM -> activeProgram;
default -> GL11.glGetInteger(pname);
};
@@ -377,8 +438,52 @@ public class GLStateManager {
}
}
public static void glGetMaterial(int face, int pname, FloatBuffer params) {
if (shouldBypassCache()) {
GL11.glGetMaterial(face, pname, params);
return;
}
MaterialStateStack state;
if (face == GL11.GL_FRONT) {
state = frontMaterial;
} else if (face == GL11.GL_BACK) {
state = backMaterial;
} else {
throw new RuntimeException("Invalid face parameter specified to glGetMaterial: " + face);
}
switch (pname) {
case GL11.GL_AMBIENT -> state.ambient.get(0, params);
case GL11.GL_DIFFUSE -> state.diffuse.get(0, params);
case GL11.GL_SPECULAR -> state.specular.get(0, params);
case GL11.GL_EMISSION -> state.emission.get(0, params);
case GL11.GL_SHININESS -> params.put(state.shininess);
case GL11.GL_COLOR_INDEXES -> state.colorIndexes.get(0, params);
default -> GL11.glGetMaterial(face, pname, params);
}
}
public static void glGetLight(int light, int pname, FloatBuffer params) {
GL11.glGetLight(light, pname, params);
if (shouldBypassCache()) {
GL11.glGetLight(light, pname, params);
return;
}
LightStateStack state = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_AMBIENT -> state.ambient.get(0, params);
case GL11.GL_DIFFUSE -> state.diffuse.get(0, params);
case GL11.GL_SPECULAR -> state.specular.get(0, params);
case GL11.GL_POSITION -> state.position.get(0, params);
case GL11.GL_SPOT_DIRECTION -> state.spotDirection.get(0, params);
case GL11.GL_SPOT_EXPONENT -> params.put(state.spotExponent);
case GL11.GL_SPOT_CUTOFF -> params.put(state.spotCutoff);
case GL11.GL_CONSTANT_ATTENUATION -> params.put(state.constantAttenuation);
case GL11.GL_LINEAR_ATTENUATION -> params.put(state.linearAttenuation);
case GL11.GL_QUADRATIC_ATTENUATION -> params.put(state.quadraticAttenuation);
default -> GL11.glGetLight(light, pname, params);
}
}
public static void glGetFloat(int pname, FloatBuffer params) {
@@ -592,6 +697,8 @@ public class GLStateManager {
return ((b - Byte.MIN_VALUE) & 0xFF) / 255.0F;
}
public static float i2f(int i) { return ((i - Integer.MIN_VALUE) & 0xFFFFFF) / 4294967295.0F; }
private static boolean changeColor(float red, float green, float blue, float alpha) {
// Helper function for glColor*
if (shouldBypassCache() || red != color.getRed() || green != color.getGreen() || blue != color.getBlue() || alpha != color.getAlpha()) {
@@ -780,9 +887,6 @@ public class GLStateManager {
} else if (textureUnit == IrisSamplers.LIGHTMAP_TEXTURE_UNIT) {
StateTracker.INSTANCE.lightmapSampler = true;
updatePipeline = true;
} else if (textureUnit == IrisSamplers.OVERLAY_TEXTURE_UNIT) {
StateTracker.INSTANCE.overlaySampler = true;
updatePipeline = true;
}
if (updatePipeline) {
@@ -803,9 +907,6 @@ public class GLStateManager {
} else if (textureUnit == IrisSamplers.LIGHTMAP_TEXTURE_UNIT) {
StateTracker.INSTANCE.lightmapSampler = false;
updatePipeline = true;
} else if (textureUnit == IrisSamplers.OVERLAY_TEXTURE_UNIT) {
StateTracker.INSTANCE.overlaySampler = false;
updatePipeline = true;
}
if (updatePipeline) {
@@ -897,10 +998,54 @@ public class GLStateManager {
lightingState.enable();
}
public static void enableLight(int light) {
lightStates[light].enable();
}
public static void enableColorMaterial() {
colorMaterial.enable();
float r = getColor().getRed();
float g = getColor().getGreen();
float b = getColor().getBlue();
float a = getColor().getAlpha();
if (colorMaterialFace.getValue() == GL11.GL_FRONT || colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) {
switch (colorMaterialParameter.getValue()) {
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
frontMaterial.ambient.set(r, g, b, a);
frontMaterial.diffuse.set(r, g, b, a);
}
case GL11.GL_AMBIENT -> frontMaterial.ambient.set(r, g, b, a);
case GL11.GL_DIFFUSE -> frontMaterial.diffuse.set(r, g, b, a);
case GL11.GL_SPECULAR -> frontMaterial.specular.set(r, g, b, a);
case GL11.GL_EMISSION -> frontMaterial.emission.set(r, g, b, a);
}
}
if (colorMaterialFace.getValue() == GL11.GL_BACK || colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) {
switch (colorMaterialParameter.getValue()) {
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
backMaterial.ambient.set(r, g, b, a);
backMaterial.diffuse.set(r, g, b, a);
}
case GL11.GL_AMBIENT -> backMaterial.ambient.set(r, g, b, a);
case GL11.GL_DIFFUSE -> backMaterial.diffuse.set(r, g, b, a);
case GL11.GL_SPECULAR -> backMaterial.specular.set(r, g, b, a);
case GL11.GL_EMISSION -> backMaterial.emission.set(r, g, b, a);
}
}
}
public static void disableColorMaterial() {
colorMaterial.disable();
}
public static void disableLighting() {
lightingState.disable();
}
public static void disableLight(int light) {
lightStates[light].disable();
}
public static void enableRescaleNormal() {
rescaleNormalState.enable();
}
@@ -1259,6 +1404,9 @@ public class GLStateManager {
return true;
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture);
if (info == null) {
return true;
}
switch (pname) {
case GL11.GL_TEXTURE_MIN_FILTER -> {
if(info.getMinFilter() == param && !shouldBypassCache()) return false;
@@ -1330,6 +1478,9 @@ public class GLStateManager {
return true;
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture);
if (info == null) {
return true;
}
switch (pname) {
case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> {
if(info.getMaxAnisotropy() == param && !shouldBypassCache()) return false;
@@ -1355,7 +1506,9 @@ public class GLStateManager {
public static int getTexParameterOrDefault(int texture, int pname, IntSupplier defaultSupplier) {
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture);
if (info == null) {
return defaultSupplier.getAsInt();
}
return switch (pname) {
case GL11.GL_TEXTURE_MIN_FILTER -> info.getMinFilter();
case GL11.GL_TEXTURE_MAG_FILTER -> info.getMagFilter();
@@ -1379,6 +1532,9 @@ public class GLStateManager {
return GL11.glGetTexParameterf(target, pname);
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTexture());
if(info == null) {
return GL11.glGetTexParameterf(target, pname);
}
return switch (pname) {
case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> info.getMaxAnisotropy();
@@ -1392,7 +1548,9 @@ public class GLStateManager {
return GL11.glGetTexLevelParameteri(target, level, pname);
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTexture());
if (info == null) {
return GL11.glGetTexLevelParameteri(target, level, pname);
}
return switch (pname) {
case GL11.GL_TEXTURE_WIDTH -> info.getWidth();
case GL11.GL_TEXTURE_HEIGHT -> info.getHeight();
@@ -1401,31 +1559,229 @@ public class GLStateManager {
};
}
public static void glLight(int light, int pname, FloatBuffer params) {
GL11.glLight(light, pname, params);
private static void glMaterialFront(int pname, FloatBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> frontMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> frontMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> frontMaterial.setSpecular(params);
case GL11.GL_EMISSION -> frontMaterial.setEmission(params);
case GL11.GL_SHININESS -> frontMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
frontMaterial.setAmbient(params);
frontMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> frontMaterial.setColorIndexes(params);
}
}
private static void glMaterialBack(int pname, FloatBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> backMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> backMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> backMaterial.setSpecular(params);
case GL11.GL_EMISSION -> backMaterial.setEmission(params);
case GL11.GL_SHININESS -> backMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
backMaterial.setAmbient(params);
backMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> backMaterial.setColorIndexes(params);
}
}
private static void glMaterialFront(int pname, IntBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> frontMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> frontMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> frontMaterial.setSpecular(params);
case GL11.GL_EMISSION -> frontMaterial.setEmission(params);
case GL11.GL_SHININESS -> frontMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
frontMaterial.setAmbient(params);
frontMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> frontMaterial.setColorIndexes(params);
}
}
private static void glMaterialBack(int pname, IntBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> backMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> backMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> backMaterial.setSpecular(params);
case GL11.GL_EMISSION -> backMaterial.setEmission(params);
case GL11.GL_SHININESS -> backMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
backMaterial.setAmbient(params);
backMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> backMaterial.setColorIndexes(params);
}
}
public static void glMaterial(int face, int pname, FloatBuffer params) {
if (face == GL11.GL_FRONT) {
glMaterialFront(pname, params);
} else if (face == GL11.GL_BACK) {
glMaterialBack(pname, params);
} else if (face == GL11.GL_FRONT_AND_BACK) {
glMaterialFront(pname, params);
glMaterialBack(pname, params);
} else {
throw new RuntimeException("Unsupported face value for glMaterial: " + face);
}
}
public static void glMaterial(int face, int pname, IntBuffer params) {
if (face == GL11.GL_FRONT) {
glMaterialFront(pname, params);
} else if (face == GL11.GL_BACK) {
glMaterialBack(pname, params);
} else if (face == GL11.GL_FRONT_AND_BACK) {
glMaterialFront(pname, params);
glMaterialBack(pname, params);
} else {
throw new RuntimeException("Unsupported face value for glMaterial: " + face);
}
}
public static void glMaterialf(int face, int pname, float val) {
if (pname != GL11.GL_SHININESS) {
// it is only valid to call glMaterialf for the GL_SHININESS parameter
return;
}
if (face == GL11.GL_FRONT) {
frontMaterial.setShininess(val);
} else if (face == GL11.GL_BACK) {
backMaterial.setShininess(val);
} else if (face == GL11.GL_FRONT_AND_BACK) {
frontMaterial.setShininess(val);
backMaterial.setShininess(val);
} else {
throw new RuntimeException("Unsupported face value for glMaterial: " + face);
}
}
public static void glMateriali(int face, int pname, int val) {
// This will end up no-opping if pname != GL_SHININESS, it is invalid to call this with another pname
glMaterialf(face, pname, (float) val);
}
public static void glLight(int light, int pname, FloatBuffer params) {
LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_AMBIENT -> lightState.setAmbient(params);
case GL11.GL_DIFFUSE -> lightState.setDiffuse(params);
case GL11.GL_SPECULAR -> lightState.setSpecular(params);
case GL11.GL_POSITION -> lightState.setPosition(params);
case GL11.GL_SPOT_DIRECTION -> lightState.setSpotDirection(params);
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(params);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(params);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(params);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(params);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params);
default -> GL11.glLight(light, pname, params);
}
}
public static void glLight(int light, int pname, IntBuffer params) {
GL11.glLight(light, pname, params);
LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_AMBIENT -> lightState.setAmbient(params);
case GL11.GL_DIFFUSE -> lightState.setDiffuse(params);
case GL11.GL_SPECULAR -> lightState.setSpecular(params);
case GL11.GL_POSITION -> lightState.setPosition(params);
case GL11.GL_SPOT_DIRECTION -> lightState.setSpotDirection(params);
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(params);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(params);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(params);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(params);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params);
default -> GL11.glLight(light, pname, params);
}
}
public static void glLightf(int light, int pname, float param) {
LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(param);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(param);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(param);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(param);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param);
default -> GL11.glLightf(light, pname, param);
}
}
public static void glLighti(int light, int pname, int param) {
LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(param);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(param);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(param);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(param);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param);
default -> GL11.glLighti(light, pname, param);
}
}
public static void glLightModel(int pname, FloatBuffer params) {
GL11.glLightModel(pname, params);
switch (pname) {
case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params);
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params);
default -> GL11.glLightModel(pname, params);
}
}
public static void glLightModel(int pname, IntBuffer params) {
GL11.glLightModel(pname, params);
switch (pname) {
case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params);
case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(params);
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params);
default -> GL11.glLightModel(pname, params);
}
}
public static void glLightModelf(int pname, float param) {
GL11.glLightModelf(pname, param);
switch (pname) {
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param);
default -> GL11.glLightModelf(pname, param);
}
}
public static void glLightModeli(int pname, int param) {
GL11.glLightModeli(pname, param);
switch (pname) {
case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(param);
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param);
default -> GL11.glLightModeli(pname, param);
}
}
public static void glColorMaterial(int face, int mode) {
GL11.glColorMaterial(face, mode);
if (shouldBypassCache() || (colorMaterialFace.getValue() != face || colorMaterialParameter.getValue() != mode)) {
colorMaterialFace.setValue(face);
colorMaterialParameter.setValue(mode);
GL11.glColorMaterial(face, mode);
}
}
public static void glDepthRange(double near, double far) {
GL11.glDepthRange(near, far);
}
public static void glUseProgram(int program) {
if(program != activeProgram || shouldBypassCache()) {
activeProgram = program;
if(AngelicaMod.lwjglDebug) {
final String programName = GLDebug.getObjectLabel(KHRDebug.GL_PROGRAM, program);
GLDebug.debugMessage("Activating Program - " + program + ":" + programName);
}
GL20.glUseProgram(program);
}
}
}
@@ -9,10 +9,12 @@ public class IntegerStateStack extends IntegerState implements IStateStack<Integ
protected int pointer;
public IntegerStateStack() {
public IntegerStateStack(int val) {
setValue(val);
stack = new IntegerState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
stack[i] = new IntegerState();
stack[i].setValue(val);
}
}
@@ -0,0 +1,39 @@
package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.LightModelState;
public class LightModelStateStack extends LightModelState implements IStateStack<LightModelStateStack> {
protected final LightModelState[] stack;
protected int pointer;
public LightModelStateStack() {
super();
stack = new LightModelState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
stack[i] = new LightModelState();
}
}
public LightModelStateStack push() {
if (pointer == stack.length) {
throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached");
}
stack[pointer++].set(this);
return this;
}
public LightModelStateStack pop() {
if (pointer == 0) {
throw new IllegalStateException("Stack underflow");
}
set(stack[--pointer]);
return this;
}
public boolean isEmpty() { return pointer == 0; }
}
@@ -0,0 +1,39 @@
package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.LightState;
public class LightStateStack extends LightState implements IStateStack<LightStateStack> {
protected final LightState[] stack;
protected int pointer;
public LightStateStack(int light) {
super(light);
stack = new LightState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
stack[i] = new LightState(light);
}
}
public LightStateStack push() {
if (pointer == stack.length) {
throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached");
}
stack[pointer++].set(this);
return this;
}
public LightStateStack pop() {
if (pointer == 0) {
throw new IllegalStateException("Stack underflow");
}
set(stack[--pointer]);
return this;
}
public boolean isEmpty() { return pointer == 0; }
}
@@ -0,0 +1,41 @@
package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.MaterialState;
public class MaterialStateStack extends MaterialState implements IStateStack<MaterialStateStack> {
protected final MaterialState[] stack;
protected int pointer;
public MaterialStateStack(int face) {
super(face);
stack = new MaterialState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
stack[i] = new MaterialState(face);
}
}
public MaterialStateStack push() {
if (pointer == stack.length) {
throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached");
}
stack[pointer++].set(this);
return this;
}
public MaterialStateStack pop() {
if (pointer == 0) {
throw new IllegalStateException("Stack underflow");
}
set(stack[--pointer]);
return this;
}
public boolean isEmpty() { return pointer == 0; }
}
@@ -0,0 +1,121 @@
package com.gtnewhorizons.angelica.glsm.states;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.joml.Vector4f;
import org.joml.Vector4i;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static com.gtnewhorizons.angelica.glsm.GLStateManager.i2f;
public class LightModelState implements ISettableState<LightModelState> {
private static final Vector4f vector4f = new Vector4f();
private static final Vector4i vector4i = new Vector4i();
public final Vector4f ambient;
public int colorControl;
public float localViewer;
public float twoSide;
public LightModelState() {
ambient = new Vector4f(0.2F, 0.2F, 0.2F, 1.0F);
colorControl = GL12.GL_SINGLE_COLOR;
localViewer = 0.0F;
twoSide = 0.0F;
}
public void setAmbient(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) {
this.ambient.set(vector4f);
GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, newBuffer);
}
}
public void setAmbient(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) {
this.ambient.set(vector4f);
GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, newBuffer);
}
}
public void setColorControl(int val) {
if (GLStateManager.shouldBypassCache() || this.colorControl != val) {
this.colorControl = val;
GL11.glLightModeli(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, val);
}
}
public void setColorControl(IntBuffer newBuffer) {
setColorControl(newBuffer.get());
}
public void setLocalViewer(float val) {
if (GLStateManager.shouldBypassCache() || Float.compare(this.localViewer, val) != 0) {
this.localViewer = val;
GL11.glLightModelf(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, val);
}
}
public void setLocalViewer(FloatBuffer newBuffer) {
setLocalViewer(newBuffer.get());
}
public void setLocalViewer(IntBuffer newBuffer) {
setLocalViewer((float) newBuffer.get());
}
public void setLocalViewer(int val) {
setLocalViewer((float) val);
}
public void setTwoSide(float val) {
if (GLStateManager.shouldBypassCache() || Float.compare(this.twoSide, val) != 0) {
this.twoSide = val;
GL11.glLightModelf(GL11.GL_LIGHT_MODEL_TWO_SIDE, val);
}
}
public void setTwoSide(FloatBuffer newBuffer) {
setTwoSide(newBuffer.get());
}
public void setTwoSide(IntBuffer newBuffer) {
setTwoSide((float) newBuffer.get());
}
public void setTwoSide(int val) {
setTwoSide((float) val);
}
@Override
public LightModelState set(LightModelState state) {
this.ambient.set(state.ambient);
this.colorControl = state.colorControl;
this.localViewer = state.localViewer;
this.twoSide = state.twoSide;
return this;
}
@Override
public boolean sameAs(Object state) {
if (this == state) return true;
if (!(state instanceof LightModelState lightModelState)) return false;
return this.ambient.equals(lightModelState.ambient)
&& this.colorControl == lightModelState.colorControl
&& Float.compare(lightModelState.localViewer, this.localViewer) == 0
&& Float.compare(lightModelState.twoSide, this.twoSide) == 0;
}
@Override
public LightModelState copy() {
return new LightModelState().set(this);
}
}
@@ -0,0 +1,291 @@
package com.gtnewhorizons.angelica.glsm.states;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.joml.Matrix3f;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.joml.Vector4f;
import org.joml.Vector4i;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static com.gtnewhorizons.angelica.glsm.GLStateManager.i2f;
public class LightState implements ISettableState<LightState> {
private static final Vector4i vector4i = new Vector4i();
private static final Vector4f vector4f = new Vector4f();
private static final Vector3i vector3i = new Vector3i();
private static final Vector3f vector3f = new Vector3f();
private static final Matrix3f matrix3f = new Matrix3f();
public int light;
public final Vector4f ambient;
public final Vector4f diffuse;
public final Vector4f specular;
public final Vector4f position;
public final Vector3f spotDirection;
public float spotExponent;
public float spotCutoff;
public float constantAttenuation;
public float linearAttenuation;
public float quadraticAttenuation;
public LightState(int light) {
this(
light,
new Vector4f(0F, 0F, 0F, 1F),
new Vector4f(0F, 0F, 0F, 1F),
new Vector4f(0F, 0F, 0F, 1F),
new Vector4f(0F, 0F, 1F, 0F),
new Vector3f(0F, 0F, -1F),
0F,
180F,
1.0F,
0.0F,
0.0F
);
if (light == GL11.GL_LIGHT0) {
this.diffuse.set(1F, 1F, 1F, 1F);
this.specular.set(1F, 1F, 1F, 1F);
}
}
public LightState(int light, Vector4f ambient, Vector4f diffuse, Vector4f specular, Vector4f position, Vector3f spotDirection, float spotExponent, float spotCutoff, float constantAttenuation, float linearAttenuation, float quadraticAttenuation) {
this.light = light;
this.ambient = ambient;
this.diffuse = diffuse;
this.specular = specular;
this.spotExponent = spotExponent;
this.spotCutoff = spotCutoff;
this.constantAttenuation = constantAttenuation;
this.linearAttenuation = linearAttenuation;
this.quadraticAttenuation = quadraticAttenuation;
this.position = position;
this.position.mul(GLStateManager.getModelViewMatrix());
this.spotDirection = spotDirection;
GLStateManager.getModelViewMatrix().get3x3(matrix3f);
this.spotDirection.mul(matrix3f);
}
public void setAmbient(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) {
this.ambient.set(vector4f);
GL11.glLight(this.light, GL11.GL_AMBIENT, newBuffer);
}
}
public void setAmbient(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) {
this.ambient.set(vector4f);
GL11.glLight(this.light, GL11.GL_AMBIENT, newBuffer);
}
}
public void setDiffuse(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) {
this.diffuse.set(vector4f);
GL11.glLight(this.light, GL11.GL_DIFFUSE, newBuffer);
}
}
public void setDiffuse(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) {
this.diffuse.set(vector4f);
GL11.glLight(this.light, GL11.GL_DIFFUSE, newBuffer);
}
}
public void setSpecular(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) {
this.specular.set(vector4f);
GL11.glLight(this.light, GL11.GL_SPECULAR, newBuffer);
}
}
public void setSpecular(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) {
this.specular.set(vector4f);
GL11.glLight(this.light, GL11.GL_SPECULAR, newBuffer);
}
}
public void setPosition(FloatBuffer newBuffer) {
// We are bypassing cache everytime for position, because the necessary components to enable tracking the cache
// are big and probably more than just bypassing. We would need to track the modelview matrix it was transformed
// with and the untransformed coordinates in addition to the final transformation.
this.position.set(newBuffer);
this.position.mul(GLStateManager.getModelViewMatrix());
GL11.glLight(this.light, GL11.GL_POSITION, newBuffer);
}
public void setPosition(IntBuffer newBuffer) {
vector4i.set(newBuffer);
this.position.set((float) vector4i.x, (float) vector4i.y, (float) vector4i.z, (float) vector4i.w);
this.position.mul(GLStateManager.getModelViewMatrix());
GL11.glLight(this.light, GL11.GL_POSITION, newBuffer);
}
public void setSpotDirection(FloatBuffer newBuffer) {
// We are bypassing cache everytime for spot direction, because the necessary components to enable tracking the cache
// are big and probably more than just bypassing. We would need to track the modelview matrix it was transformed
// with and the untransformed coordinates in addition to the final transformation.
GLStateManager.getModelViewMatrix().get3x3(matrix3f);
this.spotDirection.set(newBuffer);
this.spotDirection.mul(matrix3f);
GL11.glLight(this.light, GL11.GL_SPOT_DIRECTION, newBuffer);
}
public void setSpotDirection(IntBuffer newBuffer) {
vector3i.set(newBuffer);
GLStateManager.getModelViewMatrix().get3x3(matrix3f);
this.spotDirection.set((float) vector3i.x, (float) vector3i.y, (float) vector3i.z);
this.spotDirection.mul(matrix3f);
GL11.glLight(this.light, GL11.GL_SPOT_DIRECTION, newBuffer);
}
public void setSpotExponent(FloatBuffer newBuffer) {
setSpotExponent(newBuffer.get());
}
public void setSpotExponent(IntBuffer newBuffer) {
setSpotExponent((float) newBuffer.get());
}
public void setSpotExponent(int i) {
setSpotExponent((float) i);
}
public void setSpotExponent(float f) {
if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotExponent) != 0) {
this.spotExponent = f;
GL11.glLightf(this.light, GL11.GL_SPOT_EXPONENT, f);
}
}
public void setSpotCutoff(FloatBuffer newBuffer) {
setSpotCutoff(newBuffer.get());
}
public void setSpotCutoff(IntBuffer newBuffer) {
setSpotCutoff((float) newBuffer.get());
}
public void setSpotCutoff(int i) {
setSpotCutoff((float) i);
}
public void setSpotCutoff(float f) {
if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotCutoff) != 0) {
this.spotCutoff = f;
GL11.glLightf(this.light, GL11.GL_SPOT_CUTOFF, f);
}
}
public void setConstantAttenuation(FloatBuffer newBuffer) {
setConstantAttenuation(newBuffer.get());
}
public void setConstantAttenuation(IntBuffer newBuffer) {
setConstantAttenuation((float) newBuffer.get());
}
public void setConstantAttenuation(int i) {
setConstantAttenuation((float) i);
}
public void setConstantAttenuation(float f) {
if (GLStateManager.shouldBypassCache() || Float.compare(f, this.constantAttenuation) != 0) {
this.constantAttenuation = f;
GL11.glLightf(this.light, GL11.GL_CONSTANT_ATTENUATION, f);
}
}
public void setLinearAttenuation(FloatBuffer newBuffer) {
setLinearAttenuation(newBuffer.get());
}
public void setLinearAttenuation(IntBuffer newBuffer) {
setLinearAttenuation((float) newBuffer.get());
}
public void setLinearAttenuation(int i) {
setLinearAttenuation((float) i);
}
public void setLinearAttenuation(float f) {
if (GLStateManager.shouldBypassCache() || Float.compare(f, this.linearAttenuation) != 0) {
this.linearAttenuation = f;
GL11.glLightf(this.light, GL11.GL_LINEAR_ATTENUATION, f);
}
}
public void setQuadraticAttenuation(FloatBuffer newBuffer) {
setQuadraticAttenuation(newBuffer.get());
}
public void setQuadraticAttenuation(IntBuffer newBuffer) {
setQuadraticAttenuation((float) newBuffer.get());
}
public void setQuadraticAttenuation(int i) {
setQuadraticAttenuation((float) i);
}
public void setQuadraticAttenuation(float f) {
if (GLStateManager.shouldBypassCache() || Float.compare(f, this.quadraticAttenuation) != 0) {
this.quadraticAttenuation = f;
GL11.glLightf(this.light, GL11.GL_QUADRATIC_ATTENUATION, f);
}
}
@Override
public LightState set(LightState state) {
this.ambient.set(state.ambient);
this.diffuse.set(state.diffuse);
this.specular.set(state.specular);
this.position.set(state.position);
this.spotDirection.set(state.spotDirection);
this.spotExponent = state.spotExponent;
this.spotCutoff = state.spotCutoff;
this.constantAttenuation = state.constantAttenuation;
this.linearAttenuation = state.linearAttenuation;
this.quadraticAttenuation = state.quadraticAttenuation;
return this;
}
@Override
public boolean sameAs(Object state) {
if (this == state) return true;
if (!(state instanceof LightState lightState)) return false;
return this.ambient.equals(lightState.ambient)
&& this.diffuse.equals(lightState.diffuse)
&& this.specular.equals(lightState.specular)
&& this.position.equals(lightState.position)
&& this.spotDirection.equals(lightState.spotDirection)
&& Float.compare(this.spotCutoff, lightState.spotCutoff) == 0
&& Float.compare(this.spotExponent, lightState.spotExponent) == 0
&& Float.compare(this.linearAttenuation, lightState.linearAttenuation) == 0
&& Float.compare(this.constantAttenuation, lightState.constantAttenuation) == 0
&& Float.compare(this.quadraticAttenuation, lightState.quadraticAttenuation) == 0;
}
@Override
public LightState copy() { return new LightState(this.light).set(this); }
}
@@ -0,0 +1,174 @@
package com.gtnewhorizons.angelica.glsm.states;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.joml.Vector4f;
import org.joml.Vector4i;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static com.gtnewhorizons.angelica.glsm.GLStateManager.i2f;
public class MaterialState implements ISettableState<MaterialState> {
private static final Vector4f vector4f = new Vector4f();
private static final Vector4i vector4i = new Vector4i();
private static final Vector3f vector3f = new Vector3f();
private static final Vector3i vector3i = new Vector3i();
public int face;
public final Vector4f ambient;
public final Vector4f diffuse;
public final Vector4f specular;
public final Vector4f emission;
public float shininess;
public final Vector3f colorIndexes;
public MaterialState(int face) {
this.face = face;
ambient = new Vector4f(0.2F, 0.2F, 0.2F, 1.0F);
diffuse = new Vector4f(0.8F, 0.8F, 0.8F, 1.0F);
specular = new Vector4f(0.0F, 0.0F, 0.0F, 1.0F);
emission = new Vector4f(0.0F, 0.0F, 0.0F, 1.0F);
shininess = 0.0F;
colorIndexes = new Vector3f(0.0F, 1.0F, 1.0F);
}
public void setAmbient(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) {
this.ambient.set(vector4f);
GL11.glMaterial(face, GL11.GL_AMBIENT, newBuffer);
}
}
public void setAmbient(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) {
this.ambient.set(vector4f);
GL11.glMaterial(face, GL11.GL_AMBIENT, newBuffer);
}
}
public void setDiffuse(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) {
this.diffuse.set(vector4f);
GL11.glMaterial(face, GL11.GL_DIFFUSE, newBuffer);
}
}
public void setDiffuse(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) {
this.diffuse.set(vector4f);
GL11.glMaterial(face, GL11.GL_DIFFUSE, newBuffer);
}
}
public void setSpecular(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) {
this.specular.set(vector4f);
GL11.glMaterial(face, GL11.GL_SPECULAR, newBuffer);
}
}
public void setSpecular(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) {
this.specular.set(vector4f);
GL11.glMaterial(face, GL11.GL_SPECULAR, newBuffer);
}
}
public void setEmission(FloatBuffer newBuffer) {
vector4f.set(newBuffer);
if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) {
this.emission.set(vector4f);
GL11.glMaterial(face, GL11.GL_EMISSION, newBuffer);
}
}
public void setEmission(IntBuffer newBuffer) {
vector4i.set(newBuffer);
vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w));
if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) {
this.emission.set(vector4f);
GL11.glMaterial(face, GL11.GL_EMISSION, newBuffer);
}
}
public void setShininess(float val) {
if (GLStateManager.shouldBypassCache() || Float.compare(this.shininess, val) != 0) {
this.shininess = val;
GL11.glMaterialf(face, GL11.GL_SHININESS, val);
}
}
public void setShininess(FloatBuffer newBuffer) { setShininess(newBuffer.get()); }
public void setShininess(IntBuffer newBuffer) { setShininess((float) newBuffer.get());}
public void setShininess(int val) { setShininess((float) val);}
public void setColorIndexes(FloatBuffer newBuffer) {
// You are reading this correctly, nvidia drivers flip the y and z values in
// glMaterial specifically for GL_COLOR_INDEXES. Other drivers do not do this.
// This probably breaks things but who knows, GLSM is setup to track to what the
// driver is doing for it right now.
if (GLStateManager.isNVIDIA()) {
vector3f.set(newBuffer.get(0), newBuffer.get(2), newBuffer.get(1));
} else {
vector3f.set(newBuffer);
}
if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) {
this.colorIndexes.set(vector3f);
GL11.glMaterial(face, GL11.GL_COLOR_INDEXES, newBuffer);
}
}
public void setColorIndexes(IntBuffer newBuffer) {
vector3i.set(newBuffer.get(0), newBuffer.get(2), newBuffer.get(1));
vector3f.set((float) vector3i.x, (float) vector3i.y, (float) vector3i.z);
if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) {
this.colorIndexes.set(vector3f);
GL11.glMaterial(face, GL11.GL_COLOR_INDEXES, newBuffer);
}
}
@Override
public MaterialState set(MaterialState state) {
this.ambient.set(state.ambient);
this.diffuse.set(state.diffuse);
this.specular.set(state.specular);
this.emission.set(state.emission);
this.shininess = state.shininess;
this.colorIndexes.set(state.colorIndexes);
return this;
}
@Override
public boolean sameAs(Object state) {
if (this == state) return true;
if (!(state instanceof MaterialState materialState)) return false;
return this.ambient.equals(materialState.ambient)
&& this.diffuse.equals(materialState.diffuse)
&& this.specular.equals(materialState.specular)
&& this.emission.equals(materialState.emission)
&& Float.compare(materialState.shininess, this.shininess) == 0
&& this.colorIndexes.equals(materialState.colorIndexes);
}
@Override
public MaterialState copy() { return new MaterialState(this.face).set(this); }
}
@@ -21,20 +21,23 @@ public class TextureInfoCache {
}
public TextureInfo getInfo(int id) {
if(id < 0 || !GLStateManager.isMainThread()) return null;
return cache.computeIfAbsent(id, TextureInfo::new);
}
public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) {
if (level == 0) {
if (target == GL11.GL_TEXTURE_2D && level == 0) {
final TextureInfo info = getInfo(GLStateManager.getBoundTexture());
if(info == null) return;
info.internalFormat = internalformat;
info.width = width;
info.height = height;
}
}
public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, long pixels_buffer_offset) {
if (level == 0) {
if (target == GL11.GL_TEXTURE_2D && level == 0) {
final TextureInfo info = getInfo(GLStateManager.getBoundTexture());
if(info == null) return;
info.internalFormat = internalformat;
info.width = width;
info.height = height;
@@ -42,7 +45,7 @@ public class TextureInfoCache {
}
public void onDeleteTexture(int id) {
cache.remove(id);
if(id >= 0 && GLStateManager.isMainThread()) cache.remove(id);
}
}
@@ -4,7 +4,9 @@ import java.util.ArrayList;
import java.util.List;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching.RenderGameOverlayEventAccessor;
import com.kentington.thaumichorizons.common.ThaumicHorizons;
import cpw.mods.fml.common.eventhandler.EventPriority;
import net.dries007.holoInventory.client.Renderer;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
@@ -20,7 +22,6 @@ import com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching.GuiIngameForg
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiIngame;
@@ -32,6 +33,7 @@ import net.minecraft.client.settings.KeyBinding;
import net.minecraft.client.shader.Framebuffer;
import net.minecraft.util.ChatComponentText;
import net.minecraftforge.client.GuiIngameForge;
import thaumcraft.common.Thaumcraft;
import xaero.common.core.XaeroMinimapCore;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
@@ -43,6 +45,7 @@ public class HUDCaching {
private static final Minecraft mc = Minecraft.getMinecraft();
public static Framebuffer framebuffer;
private static boolean dirty = true;
private static long nextHudRefresh;
public static boolean renderingCacheOverride;
@@ -59,7 +62,8 @@ public class HUDCaching {
// Crosshairs need to be blended with the scene
public static boolean renderCrosshairsCaptured;
private static RenderGameOverlayEvent fakeHoloInventoryEvent = new RenderGameOverlayEvent.Pre(new RenderGameOverlayEvent(0, null, 0, 0), RenderGameOverlayEvent.ElementType.HELMET);
private final static RenderGameOverlayEvent fakeTextEvent = new RenderGameOverlayEvent.Text(new RenderGameOverlayEvent(0, null, 0, 0), null, null);
private final static RenderGameOverlayEvent fakePreEvent = new RenderGameOverlayEvent.Pre(new RenderGameOverlayEvent(0, null, 0, 0), RenderGameOverlayEvent.ElementType.HELMET);
public static final HUDCaching INSTANCE = new HUDCaching();
@@ -80,21 +84,6 @@ public class HUDCaching {
ClientRegistry.registerKeyBinding(toggle);
}
// @SubscribeEvent
// public void onFrame(RenderGameOverlayEvent.Post event) {
// if (event.type == RenderGameOverlayEvent.ElementType.TEXT) {
// final long currentTimeMillis = System.currentTimeMillis();
// updateTimeList.removeIf(time -> currentTimeMillis - time > 1000L);
// String text = EnumChatFormatting.GREEN + "HUD Fps : " + updateTimeList.size();
// mc.fontRenderer.drawStringWithShadow(
// text,
// event.resolution.getScaledWidth() / 4,
// event.resolution.getScaledHeight() / 4,
// 0xFFFFFF);
// updateTimeList.add(currentTimeMillis);
// }
// }
@SubscribeEvent
public void onKeypress(InputEvent.KeyInputEvent event) {
if (toggle != null && toggle.isPressed()) {
@@ -106,13 +95,6 @@ public class HUDCaching {
/* TODO END REMOVE DEBUG STUFF */
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.END) {
dirty = true;
}
}
// highest so it runs before the GLSM load event
@SubscribeEvent(priority = EventPriority.HIGH)
public void onJoinWorld(WorldEvent.Load event) {
@@ -125,7 +107,6 @@ public class HUDCaching {
@SuppressWarnings("unused")
public static void renderCachedHud(EntityRenderer renderer, GuiIngame ingame, float partialTicks, boolean hasScreen, int mouseX, int mouseY) {
if (ModStatus.isXaerosMinimapLoaded && ingame instanceof GuiIngameForge) {
// this used to be called by asming into renderGameOverlay, but we removed it
XaeroMinimapCore.beforeIngameGuiRender(partialTicks);
@@ -136,8 +117,13 @@ public class HUDCaching {
return;
}
if (System.currentTimeMillis() > nextHudRefresh) {
dirty = true;
}
if (dirty) {
dirty = false;
nextHudRefresh = System.currentTimeMillis() + (1000 / AngelicaConfig.hudCachingFPS);
resetFramebuffer(mc.displayWidth, mc.displayHeight);
framebuffer.bindFramebuffer(false);
renderingCacheOverride = true;
@@ -171,8 +157,8 @@ public class HUDCaching {
if (ModStatus.isHoloInventoryLoaded){
Renderer.INSTANCE.angelicaOverride = false;
// only settings the partial ticks as mouseX and mouseY are not used in renderEvent
((RenderGameOverlayEventAccessor) fakeHoloInventoryEvent).setPartialTicks(partialTicks);
Renderer.INSTANCE.renderEvent(fakeHoloInventoryEvent);
((RenderGameOverlayEventAccessor) fakePreEvent).setPartialTicks(partialTicks);
Renderer.INSTANCE.renderEvent(fakePreEvent);
}
}
if (renderPortalCapturedTicks > 0) {
@@ -181,7 +167,18 @@ public class HUDCaching {
if (renderCrosshairsCaptured) {
guiForge.callRenderCrosshairs(width, height);
}
if (ModStatus.isThaumcraftLoaded || ModStatus.isThaumicHorizonsLoaded){
((RenderGameOverlayEventAccessor) fakeTextEvent).setPartialTicks(partialTicks);
((RenderGameOverlayEventAccessor) fakeTextEvent).setResolution(resolution);
((RenderGameOverlayEventAccessor) fakeTextEvent).setMouseX(mouseX);
((RenderGameOverlayEventAccessor) fakeTextEvent).setMouseY(mouseY);
if (ModStatus.isThaumcraftLoaded){
Thaumcraft.instance.renderEventHandler.renderOverlay(fakeTextEvent);
}
if (ModStatus.isThaumicHorizonsLoaded){
ThaumicHorizons.instance.renderEventHandler.renderOverlay(fakeTextEvent);
}
}
} else {
if (renderHelmetCaptured)
{
@@ -252,4 +249,9 @@ public class HUDCaching {
}
}
public static class HUDCachingHooks {
public static boolean shouldReturnEarly(){
return renderingCacheOverride;
}
}
}
@@ -48,11 +48,6 @@ public class AngelicaTweaker implements IFMLLoadingPlugin, IEarlyMixinLoader {
}
ctx.updateLoggers();
// Too many bug reports because people refuse to read or just want to try it - so make these only able
// to be enabled by system properties for now.
AngelicaConfig.enableIris = Boolean.parseBoolean(System.getProperty("angelica.enableShaders", "false"));
AngelicaConfig.enableMCPatcherForgeFeatures = Boolean.parseBoolean(System.getProperty("angelica.enableMCPatcherForgeFeatures", "false"));
// Debug features
AngelicaConfig.enableTestBlocks = Boolean.parseBoolean(System.getProperty("angelica.enableTestBlocks", "false"));
@@ -17,14 +17,14 @@ import java.util.List;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
public class MixinCompatHackTweaker implements ITweaker {
public static final boolean DISABLE_OPTIFINE_AND_FASTCRAFT = true;
public static final boolean DISABLE_OPTIFINE_FASTCRAFT_BETTERFPS = true;
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
verifyDependencies();
if(DISABLE_OPTIFINE_AND_FASTCRAFT) {
LOGGER.info("Disabling Optifine and Fastcraft (if present)");
disableOptifineAndFastcraft();
if(DISABLE_OPTIFINE_FASTCRAFT_BETTERFPS) {
LOGGER.info("Disabling Optifine, Fastcraft, and BetterFPS (if present)");
disableOptifineFastcraftAndBetterFPS();
}
if (AngelicaConfig.enableHudCaching){
@@ -57,8 +57,8 @@ public class MixinCompatHackTweaker implements ITweaker {
}
}
private void disableOptifineAndFastcraft() {
// Remove Optifine and Fastcraft transformers & Mod Containers
private void disableOptifineFastcraftAndBetterFPS() {
// Remove Optifine, Fastcraft, and BetterFPS transformers & Mod Containers
try {
LaunchClassLoader lcl = Launch.classLoader;
Field xformersField = lcl.getClass().getDeclaredField("transformers");
@@ -67,7 +67,7 @@ public class MixinCompatHackTweaker implements ITweaker {
List<IClassTransformer> xformers = (List<IClassTransformer>) xformersField.get(lcl);
for (int idx = xformers.size() - 1; idx >= 0; idx--) {
final String name = xformers.get(idx).getClass().getName();
if (name.startsWith("optifine") || name.startsWith("fastcraft")) {
if (name.startsWith("optifine") || name.startsWith("fastcraft") || name.startsWith("me.guichaguri.betterfps")) {
LOGGER.info("Removing transformer " + name);
xformers.remove(idx);
}
@@ -28,6 +28,7 @@ public enum Mixins {
,"angelica.MixinEntityRenderer"
,"angelica.MixinMinecraft"
,"angelica.optimizations.MixinRendererLivingEntity"
,"angelica.MixinFMLClientHandler"
)
),
ANGELICA_VBO(
@@ -62,6 +63,12 @@ public enum Mixins {
)
),
ANGELICA_FIX_FLUID_RENDERER_CHECKING_BLOCK_AGAIN(
new Builder("Fix RenderBlockFluid reading the block type from the world access multiple times")
.setPhase(Phase.EARLY).addMixinClasses("angelica.bugfixes.MixinRenderBlockFluid").setSide(Side.BOTH)
.setApplyIf(() -> AngelicaConfig.fixFluidRendererCheckingBlockAgain)
.addTargetedMod(TargetedMod.VANILLA)),
// Not compatible with the lwjgl debug callbacks, so disable if that's enabled
ARCHAIC_SPLASH(new Builder("ArchaicFix Splash").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.showSplashMemoryBar && !AngelicaMod.lwjglDebug).addMixinClasses(
@@ -95,6 +102,7 @@ public enum Mixins {
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableSodium).addMixinClasses(
"sodium.MixinChunkProviderClient"
,"sodium.MixinBlock"
,"sodium.MixinBlockFluidBase"
,"sodium.AccessorBiomeColorEvent"
,"sodium.MixinBiomeGenBase"
,"sodium.MixinChunk"
@@ -132,13 +140,18 @@ public enum Mixins {
IRIS_RENDERING(new Builder("Iris Shaders").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableIris).addMixinClasses(
"shaders.MixinEntityRenderer"
,"shaders.MixinGuiIngameForge"
,"shaders.MixinFramebuffer"
,"shaders.MixinItem"
,"shaders.MixinLocale"
,"shaders.MixinOpenGlHelper"
,"shaders.MixinRender"
,"shaders.MixinRenderDragon"
,"shaders.MixinRenderEnderman"
,"shaders.MixinRendererLivingEntity"
,"shaders.MixinRenderGlobal"
,"shaders.MixinRenderManager"
,"shaders.MixinRenderSpider"
,"shaders.MixinTileEntityBeaconRenderer"
)
),
@@ -199,6 +212,11 @@ public enum Mixins {
"client.extrautils.MixinRenderBlockConnectedTexturesEthereal",
"client.extrautils.MixinIconConnectedTexture")),
MFR_THREAD_SAFETY(new Builder("Enable thread safety fixes for MineFactory Reloaded").setPhase(Phase.LATE)
.addTargetedMod(TargetedMod.MINEFACTORY_RELOADED).setSide(Side.CLIENT)
.setApplyIf(() -> AngelicaConfig.fixMineFactoryReloadedSodiumCompat)
.addMixinClasses("client.minefactoryreloaded.MixinRedNetCableRenderer")),
SPEEDUP_CAMPFIRE_BACKPORT_ANIMATIONS(new Builder("Add animation speedup support to Campfire Backport").setPhase(Phase.LATE)
.addTargetedMod(TargetedMod.CAMPFIRE_BACKPORT).setSide(Side.CLIENT)
.setApplyIf(() -> AngelicaConfig.speedupAnimations)
@@ -244,7 +262,9 @@ public enum Mixins {
"toggle.MixinEntityRenderer",
"toggle.MixinGuiIngame",
"toggle.MixinRender",
"toggle.MixinRenderItem"
"toggle.MixinRenderItem",
"interpolatedtexturemap.MixinTextureMap"
))
),
BETTER_FACE_CULLING(new Builder("Better face culling")
@@ -255,6 +275,7 @@ public enum Mixins {
"MixinBlock",
"MixinBlockCactus",
"MixinBlockCarpet",
"MixinBlockEnchantmentTable",
"MixinBlockFarmland",
"MixinBlockSlab",
"MixinBlockSnow",
@@ -512,16 +533,14 @@ public enum Mixins {
),
//End from NotFine
NOVIS_OCULIS(new Builder("Non-Tessellator Quad provider")
QPR(new Builder("Adds a QuadProvider field to blocks without populating it")
.setSide(Side.CLIENT)
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.injectQPRendering)
.setApplyIf(() -> true)
.addTargetedMod(TargetedMod.VANILLA)
.addMixinClasses(
"angelica.models.MixinBlockStone",
"angelica.models.MixinBlockAir",
"angelica.models.MixinBlockWorkbench",
"angelica.models.MixinBlockLeaves")),
"angelica.models.MixinBlock",
"angelica.models.MixinBlockOldLeaf")),
;
@@ -15,6 +15,7 @@ public enum TargetedMod {
, DYNAMIC_SURROUNDINGS_MIST("Dynamic Surroundings", "org.blockartistry.mod.DynSurround.mixinplugin.DynamicSurroundingsEarlyMixins", "dsurround")
, DYNAMIC_SURROUNDINGS_ORIGINAL("Dynamic Surroundings", "org.blockartistry.mod.DynSurround.asm.TransformLoader", "dsurround")
, EXTRAUTILS("ExtraUtilities", null, "ExtraUtilities")
, MINEFACTORY_RELOADED("MineFactory Reloaded", null, "MineFactoryReloaded")
, GTNHLIB("GTNHLib", "com.gtnewhorizon.gtnhlib.core.GTNHLibCore", "gtnhlib")
, IC2("IC2", "ic2.core.coremod.IC2core", "IC2")
, JABBA("JABBA", null, "JABBA")
@@ -7,6 +7,7 @@ import net.minecraft.entity.EntityLivingBase;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(EntityRenderer.class)
@@ -23,4 +24,9 @@ public abstract class MixinEntityRenderer {
);
}
@ModifyArg(method = "setupCameraTransform", at = @At(value = "INVOKE", target = "Lorg/lwjgl/util/glu/Project;gluPerspective(FFFF)V", ordinal = 0, remap = false), index = 0)
private float captureFov(float fov) {
RenderingState.INSTANCE.setFov(fov);
return fov;
}
}
@@ -0,0 +1,27 @@
package com.gtnewhorizons.angelica.mixins.early.angelica;
import cpw.mods.fml.client.FMLClientHandler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
@Mixin(value = FMLClientHandler.class, remap = false)
public class MixinFMLClientHandler {
/**
* @author mitchej123
* @reason Remove more traces of Optifine
*/
@Overwrite
private void detectOptifine() {
// Do nothing
}
/**
* @author mitchej123
* @reason Remove more traces of Optifine
*/
@Overwrite
public boolean hasOptifine() {
return false;
}
}
@@ -8,7 +8,7 @@ import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(GuiIngameForge.class)
@Mixin(value=GuiIngameForge.class, remap = false)
public class MixinGuiIngameForge {
@Redirect(method = "renderHUDText", at = @At(value = "FIELD", target = "Lnet/minecraft/world/biome/BiomeGenBase;biomeName:Ljava/lang/String;"))
private String getModNameWithBiome(BiomeGenBase biome) {
@@ -0,0 +1,24 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.bugfixes;
import com.gtnewhorizons.angelica.mixins.hooks.FluidHooks;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fluids.BlockFluidBase;
import net.minecraftforge.fluids.RenderBlockFluid;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import com.llamalad7.mixinextras.sugar.Local;
@Mixin(value = RenderBlockFluid.class, remap = false)
public class MixinRenderBlockFluid {
@Redirect(
method = "renderWorldBlock", at = @At(
value = "INVOKE",
target = "Lnet/minecraftforge/fluids/BlockFluidBase;getFlowDirection(Lnet/minecraft/world/IBlockAccess;III)D"))
double hodgepodge$directFlowDirectionCheck(IBlockAccess world, int x, int y, int z, @Local BlockFluidBase block) {
return FluidHooks.getFlowDirection(world, x, y, z, block);
}
}
@@ -1,6 +1,8 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.dynamiclights;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightSource;
import com.llamalad7.mixinextras.injector.ModifyReturnValue;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.world.World;
@@ -26,4 +28,12 @@ public abstract class MixinWorld {
}
}
@ModifyReturnValue(method = "getLightBrightnessForSkyBlocks", at = @At(value = "RETURN"))
private int angelica$dynamiclights_getLightBrightnessForSkyBlocks(int lightmap, int p_72802_1_, int p_72802_2_, int p_72802_3_, int p_72802_4_){
if (DynamicLights.isEnabled()){
return DynamicLights.get().getLightmapWithDynamicLight(p_72802_1_, p_72802_2_, p_72802_3_, lightmap);
}
return lightmap;
}
}
@@ -103,7 +103,7 @@ public abstract class MixinFontRenderer implements FontRendererAccessor {
@Shadow
protected abstract String bidiReorder(String p_147647_1_);
@Shadow
@Shadow(remap = false)
protected abstract void bindTexture(ResourceLocation location);
@Unique
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.event.terraingen.BiomeEvent;
import org.spongepowered.asm.mixin.Mixin;
@@ -9,4 +10,13 @@ import org.spongepowered.asm.mixin.gen.Accessor;
public interface RenderGameOverlayEventAccessor {
@Accessor(value = "partialTicks", remap = false)
void setPartialTicks(float value);
@Accessor(value = "resolution", remap = false)
void setResolution(ScaledResolution resolution);
@Accessor(value = "mouseX", remap = false)
void setMouseX(int mouseX);
@Accessor(value = "mouseY", remap = false)
void setMouseY(int mouseY);
}
@@ -0,0 +1,38 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.models;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.ModeledBlock;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static com.gtnewhorizons.angelica.models.VanillaModels.*;
@Mixin(Block.class)
public abstract class MixinBlock implements ModeledBlock {
@Getter
@Setter
private QuadProvider model = null;
@Inject(method = "registerBlocks", at = @At(value = "TAIL"))
private static void angelica$registerInjectedQP(CallbackInfo ci) {
if (!AngelicaConfig.injectQPRendering)
return;
((ModeledBlock) Blocks.stone).setModel(STONE);
((ModeledBlock) Blocks.glass).setModel(GLASS);
((ModeledBlock) Blocks.crafting_table).setModel(WORKBENCH);
((ModeledBlock) Blocks.leaves).setModel(OLD_LEAF);
((ModeledBlock) Blocks.leaves2).setModel(NEW_LEAF);
((ModeledBlock) Blocks.log).setModel(OLD_LOG);
((ModeledBlock) Blocks.log2).setModel(NEW_LOG);
}
}
@@ -1,28 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.models;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import it.unimi.dsi.fastutil.objects.ObjectImmutableList;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
@Mixin(BlockAir.class)
public abstract class MixinBlockAir implements QuadProvider {
@Unique
private static final List<QuadView> angelica$EMPTY = ObjectImmutableList.of();
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return angelica$EMPTY;
}
}
@@ -1,35 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.models;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.material.Material;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import org.spongepowered.asm.mixin.Mixin;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import static com.gtnewhorizons.angelica.models.CubeModel.INSTANCE;
@Mixin(BlockLeaves.class)
public abstract class MixinBlockLeaves extends Block implements QuadProvider {
@Override
public boolean isDynamic() {
return true;
}
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return INSTANCE.get().getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
private MixinBlockLeaves(Material materialIn) {
super(materialIn);
}
}
@@ -0,0 +1,20 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.models;
import com.gtnewhorizons.angelica.utils.AssetLoader;
import net.minecraft.block.BlockOldLeaf;
import net.minecraft.client.renderer.texture.IIconRegister;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(BlockOldLeaf.class)
public abstract class MixinBlockOldLeaf {
@Inject(method = "registerBlockIcons", at = @At(value = "TAIL"))
public void angelica$injectTextures(IIconRegister reg, CallbackInfo ci) {
for (String s : AssetLoader.injectTexs) {
reg.registerIcon(s);
}
}
}
@@ -1,24 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.models;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.models.VanillaModels;
import net.minecraft.block.Block;
import net.minecraft.block.BlockStone;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import org.spongepowered.asm.mixin.Mixin;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
@Mixin(BlockStone.class)
public abstract class MixinBlockStone implements QuadProvider {
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return VanillaModels.stoneModel.getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
}
@@ -1,24 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.models;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.models.CubeModel;
import net.minecraft.block.Block;
import net.minecraft.block.BlockWorkbench;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import org.spongepowered.asm.mixin.Mixin;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
@Mixin(BlockWorkbench.class)
public class MixinBlockWorkbench implements QuadProvider {
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return CubeModel.INSTANCE.get().getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
}
@@ -0,0 +1,50 @@
package com.gtnewhorizons.angelica.mixins.early.notfine.faceculling;
import jss.notfine.util.IFaceObstructionCheckHelper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockEnchantmentTable;
import net.minecraft.block.material.Material;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(value = BlockEnchantmentTable.class)
public abstract class MixinBlockEnchantmentTable extends Block implements IFaceObstructionCheckHelper {
/**
* @author jss2a98aj
* @reason More accurate face culling.
*/
public boolean shouldSideBeRendered(IBlockAccess worldIn, int x, int y, int z, int side) {
//If this is the top
if(side == 1) {
return true;
}
//Check if other block is solid
Block otherBlock = worldIn.getBlock(x, y, z);
if(otherBlock.isOpaqueCube()) {
return false;
}
//Check for IFaceObstructionCheckHelper
if(otherBlock instanceof IFaceObstructionCheckHelper target) {
return target.isFaceNonObstructing(worldIn, x, y, z, side, 0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F);
}
//Default
return true;
}
@Override
public boolean isFaceNonObstructing(IBlockAccess worldIn, int x, int y, int z, int side, double otherMinX, double otherMinY, double otherMinZ, double otherMaxX, double otherMaxY, double otherMaxZ) {
if(getRenderBlockPass() == 1) {
return true;
}
if(side <= 1) {
return side == 0;
}
return otherMaxY > 0.75F;
}
private MixinBlockEnchantmentTable(Material material) {
super(material);
}
}
@@ -17,7 +17,7 @@ public abstract class MixinRenderBlocks {
/**
* @author jss2a98aj
* @reason Culling a few more faces
* @reason Do not render fence arms unless actually required.
*/
@Overwrite
public boolean renderBlockFence(BlockFence fence, int x, int y, int z) {
@@ -69,6 +69,30 @@ public abstract class MixinRenderBlocks {
return true;
}
/**
* @author jss2a98aj
* @reason Cull faces against solid blocks, fix door smooth lighting
*/
@Overwrite
public boolean renderBlockDoor(Block block, int x, int y, int z) {
final int meta = blockAccess.getBlockMetadata(x, y, z);
if((meta & 8) != 0) {
if (blockAccess.getBlock(x, y - 1, z) != block) {
return false;
}
} else if (blockAccess.getBlock(x, y + 1, z) != block) {
return false;
}
if ((meta & 8) != 0) {
uvRotateTop = meta % 6;
}
boolean flag = renderStandardBlock(block, x, y, z);
uvRotateTop = 0;
return flag;
}
/**
* @author jss2a98aj
* @reason Fix modded wall detection
@@ -87,6 +111,7 @@ public abstract class MixinRenderBlocks {
@Shadow public IBlockAccess blockAccess;
@Shadow public boolean field_152631_f;
@Shadow public int uvRotateTop;
@Shadow public abstract void setRenderBounds(double minX, double minY, double minZ, double maxX, double maxY, double maxZ);
@Shadow public abstract boolean renderStandardBlock(Block blockType, int blockX, int blockY, int blockZ);
@@ -0,0 +1,51 @@
package com.gtnewhorizons.angelica.mixins.early.notfine.interpolatedtexturemap;
import com.google.gson.JsonObject;
import jss.notfine.render.InterpolatedIcon;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.client.renderer.texture.ITickableTextureObject;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.SimpleResource;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Map;
@Mixin(TextureMap.class)
public abstract class MixinTextureMap extends AbstractTexture implements ITickableTextureObject, IIconRegister {
@Shadow
@Final
private Map mapRegisteredSprites;
@Shadow
protected abstract ResourceLocation completeResourceLocation(ResourceLocation p_147634_1_, int p_147634_2_);
@Inject(method = "registerIcon", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;<init>(Ljava/lang/String;)V"), cancellable = true)
private void registerInterpolatedIcon(String textureName, CallbackInfoReturnable<IIcon> cir) {
try {
IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(completeResourceLocation(new ResourceLocation(textureName), 0));
if (resource instanceof SimpleResource) {
//This returns IMetadataSections, which seems to already remove unused mcmeta fields in 1.7.10
//I'm just running this to populate the mcmetaJson field more easily; this does it for us
if (resource.getMetadata("animation") != null) {
JsonObject mcmetaJson = ((SimpleResource) resource).mcmetaJson;
if (mcmetaJson.getAsJsonObject("animation").getAsJsonPrimitive("interpolate").getAsBoolean()) {
InterpolatedIcon interpolatedIcon = new InterpolatedIcon(textureName);
mapRegisteredSprites.put(textureName, interpolatedIcon);
cir.setReturnValue(interpolatedIcon);
}
}
}
} catch (Exception ignored) {/*Should quietly fail, no need to fail hard*/}
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.notfine.leaves;
import jss.notfine.util.IFaceObstructionCheckHelper;
import jss.notfine.util.ILeafBlock;
import jss.notfine.util.LeafRenderUtil;
import net.minecraft.block.Block;
@@ -9,13 +10,18 @@ import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(value = BlockLeavesBase.class)
public abstract class MixinBlockLeavesBase extends Block implements ILeafBlock {
public abstract class MixinBlockLeavesBase extends Block implements IFaceObstructionCheckHelper, ILeafBlock {
@Override
public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) {
return LeafRenderUtil.shouldSideBeRendered(world, x, y, z, side);
}
@Override()
public boolean isFaceNonObstructing(IBlockAccess world, int x, int y, int z, int side, double otherMinX, double otherMinY, double otherMinZ, double otherMaxX, double otherMaxY, double otherMaxZ) {
return LeafRenderUtil.isFaceNonObstructing(world, x, y, z);
}
private MixinBlockLeavesBase(Material material) {
super(material);
}
@@ -14,6 +14,8 @@ import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.lwjgl.opengl.GL11;
@Mixin(EntityRenderer.class)
abstract public class MixinEntityRenderer {
@@ -30,6 +32,10 @@ abstract public class MixinEntityRenderer {
return SettingsManager.waterDetail;
}
/**
* @author Caedis
* @reason Void fog toggle
*/
@WrapOperation(
method = "setupFog",
at = @At(
@@ -37,10 +43,23 @@ abstract public class MixinEntityRenderer {
target = "Lnet/minecraft/world/WorldProvider;getWorldHasVoidParticles()Z"
)
)
private boolean angelica$wrapVoidFog(WorldProvider provider, Operation<Boolean> original){
private boolean notFine$toggleVoidFog(WorldProvider provider, Operation<Boolean> original){
return ((boolean)Settings.VOID_FOG.option.getStore()) ? original.call(provider) : false;
}
@Redirect(
method = "setupFog",
at = @At(
value = "INVOKE",
target = "Lorg/lwjgl/opengl/GL11;glFogf(IF)V",
ordinal = 14,
remap = false
)
)
private void notFine$nearFogDistance(int mode, float value) {
GL11.glFogf(mode, farPlaneDistance * (int)Settings.FOG_NEAR_DISTANCE.option.getStore() * 0.01F - 1F);
}
@Redirect(
method = "updateRenderer()V",
at = @At(
@@ -48,7 +67,7 @@ abstract public class MixinEntityRenderer {
target = "Lnet/minecraft/client/renderer/EntityRenderer;updateTorchFlicker()V"
)
)
private void toggleTorchFlicker(EntityRenderer instance) {
private void notFine$toggleTorchFlicker(EntityRenderer instance) {
if((boolean)Settings.MODE_LIGHT_FLICKER.option.getStore()) {
updateTorchFlicker();
} else {
@@ -59,6 +78,10 @@ abstract public class MixinEntityRenderer {
@Shadow
abstract void updateTorchFlicker();
@Shadow private boolean lightmapUpdateNeeded;
@Shadow
private boolean lightmapUpdateNeeded;
@Shadow
private float farPlaneDistance;
}
@@ -17,7 +17,7 @@ public abstract class MixinGuiIngame {
target = "Lnet/minecraft/client/Minecraft;isFancyGraphicsEnabled()Z"
)
)
private boolean notFine$toggleVignette(float whyAndHowIsThisAFloat) {
private boolean notFine$toggleVignette() {
return SettingsManager.vignette;
}
@@ -71,6 +71,9 @@ public abstract class MixinFramebuffer implements IRenderTargetExt {
@Inject(method="createFramebuffer(II)V", at=@At(value="FIELD", target="Lnet/minecraft/client/shader/Framebuffer;useDepth:Z", shift=At.Shift.BEFORE, ordinal = 1))
private void iris$createDepthTexture(int width, int height, CallbackInfo ci) {
if(this.iris$useDepth) {
if(this.iris$depthTextureId == -1) {
this.iris$depthTextureId = GL11.glGenTextures();
}
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, this.iris$depthTextureId);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
@@ -0,0 +1,17 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import net.minecraftforge.client.GuiIngameForge;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(value = GuiIngameForge.class, remap = false)
public class MixinGuiIngameForge {
@Inject(method="renderCrosshairs", at= @At(value = "INVOKE", target = "Lnet/minecraftforge/client/GuiIngameForge;bind(Lnet/minecraft/util/ResourceLocation;)V", shift = At.Shift.AFTER))
private void renderCrosshairs(CallbackInfo ci) {
// Set the same state as vanilla so we don't break with textures that set a color value on transparent pixels for the crosshairs
GL11.glEnable(GL11.GL_ALPHA_TEST);
}
}
@@ -0,0 +1,18 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.renderer.entity.RenderDragon;
import net.minecraft.entity.boss.EntityDragon;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(RenderDragon.class)
public class MixinRenderDragon {
@Inject(method = "Lnet/minecraft/client/renderer/entity/RenderDragon;shouldRenderPass(Lnet/minecraft/entity/boss/EntityDragon;IF)I", at = @At(value="RETURN", ordinal = 1))
private void onShouldRenderPass(EntityDragon entity, int pass, float partialTicks, CallbackInfoReturnable<Integer> cir) {
GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.ENTITY_EYES);
}
}
@@ -0,0 +1,19 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.renderer.entity.RenderEnderman;
import net.minecraft.entity.monster.EntityEnderman;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(RenderEnderman.class)
public class MixinRenderEnderman {
@Inject(method = "Lnet/minecraft/client/renderer/entity/RenderEnderman;shouldRenderPass(Lnet/minecraft/entity/monster/EntityEnderman;IF)I", at = @At(value="RETURN", ordinal = 1))
private void onShouldRenderPass(EntityEnderman entity, int pass, float partialTicks, CallbackInfoReturnable<Integer> cir) {
GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.ENTITY_EYES);
}
}
@@ -1,30 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(RenderManager.class)
public class MixinRenderManager {
@Unique
private static final String DO_RENDER = "Lnet/minecraft/client/renderer/entity/Render;doRender(Lnet/minecraft/entity/Entity;DDDFF)V";
@Inject(method = "func_147939_a", at = @At(value = "INVOKE", target = DO_RENDER))
private void iris$onRenderEntityPre(Entity entity, double x, double y, double z, float yaw, float partialTicks, boolean rebuild, CallbackInfoReturnable<Boolean> cir) {
CapturedRenderingState.INSTANCE.setCurrentEntity(entity.getEntityId());
GbufferPrograms.beginEntities();
}
@Inject(method = "func_147939_a", at = @At(value = "INVOKE", target = DO_RENDER, shift = At.Shift.AFTER))
private void iris$onRenderEntityPost(Entity entity, double x, double y, double z, float yaw, float partialTicks, boolean rebuild, CallbackInfoReturnable<Boolean> cir) {
CapturedRenderingState.INSTANCE.setCurrentEntity(-1);
GbufferPrograms.endEntities();
}
}
@@ -0,0 +1,19 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.renderer.entity.RenderSpider;
import net.minecraft.entity.monster.EntitySpider;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(RenderSpider.class)
public class MixinRenderSpider {
@Inject(method = "Lnet/minecraft/client/renderer/entity/RenderSpider;shouldRenderPass(Lnet/minecraft/entity/monster/EntitySpider;IF)I", at = @At(value="RETURN", ordinal = 1))
private void onShouldRenderPass(EntitySpider entity, int pass, float partialTicks, CallbackInfoReturnable<Integer> cir) {
GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.ENTITY_EYES);
}
}
@@ -0,0 +1,38 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.renderer.entity.RendererLivingEntity;
import net.minecraft.entity.EntityLivingBase;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(RendererLivingEntity.class)
public class MixinRendererLivingEntity {
@WrapOperation(
method="doRender",
at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/entity/RendererLivingEntity;getColorMultiplier(Lnet/minecraft/entity/EntityLivingBase;FF)I")
)
private int iris$setEntityColor(RendererLivingEntity instance, EntityLivingBase elb, float f0, float f1, Operation<Integer> original) {
final int j = original.call(instance, elb, f0, f1);
final float a = (j >> 24 & 255) / 255.0F;
final float r = (j >> 16 & 255) / 255.0F;
final float g = (j >> 8 & 255) / 255.0F;
final float b = (j & 255) / 255.0F;
CapturedRenderingState.INSTANCE.setCurrentEntityColor(r, g, b, 1.0F - a);
return j;
}
@Inject(
method="Lnet/minecraft/client/renderer/entity/RendererLivingEntity;doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", at=@At(value="INVOKE",
target="Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V", shift=At.Shift.BEFORE)
)
private void iris$teardownSpecialRenderConditions(EntityLivingBase entity, double x, double y, double z, float entityYaw, float partialTicks, CallbackInfo ci) {
GbufferPrograms.teardownSpecialRenderCondition();
}
}
@@ -0,0 +1,26 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.renderer.tileentity.TileEntityBeaconRenderer;
import net.minecraft.tileentity.TileEntityBeacon;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(TileEntityBeaconRenderer.class)
public class MixinTileEntityBeaconRenderer {
@Inject(method="Lnet/minecraft/client/renderer/tileentity/TileEntityBeaconRenderer;renderTileEntityAt(Lnet/minecraft/tileentity/TileEntityBeacon;DDDF)V", at=@At("HEAD"))
private void onRenderTileEntityAt(TileEntityBeacon beacon, double x, double y, double z, float partialTicks, CallbackInfo ci) {
GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.BEACON_BEAM);
}
@Inject(method="Lnet/minecraft/client/renderer/tileentity/TileEntityBeaconRenderer;renderTileEntityAt(Lnet/minecraft/tileentity/TileEntityBeacon;DDDF)V", at=@At("RETURN"))
private void afterRenderTileEntityAt(TileEntityBeacon beacon, double x, double y, double z, float partialTicks, CallbackInfo ci) {
GbufferPrograms.teardownSpecialRenderCondition();
}
}
@@ -0,0 +1,24 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Local;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraftforge.fluids.BlockFluidBase;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(value = BlockFluidBase.class, remap = false)
public class MixinBlockFluidBase {
@WrapOperation(method = "getFlowDirection", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/material/Material;isLiquid()Z"), remap = true)
private static boolean isLiquid(Material instance, Operation<Boolean> original, @Local Block block) {
if (block instanceof BlockFluidBase) {
return original.call(instance);
} else {
return false;
}
}
}
@@ -5,6 +5,9 @@ import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.biome.WorldChunkManager;
import net.minecraft.world.chunk.Chunk;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.endlessids.EndlessIDsCompat;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@@ -29,14 +32,18 @@ public abstract class MixinChunk {
if(this.worldObj.isRemote && !Minecraft.getMinecraft().isSingleplayer()) {
// We are in multiplayer, the server might not have sent all biomes to the client.
// Populate them now while we're on the main thread.
WorldChunkManager manager = this.worldObj.getWorldChunkManager();
for(int z = 0; z < 16; z++) {
for(int x = 0; x < 16; x++) {
int idx = (z << 4) + x;
int biome = this.blockBiomeArray[idx] & 255;
if(biome == 255) {
BiomeGenBase generated = manager.getBiomeGenAt((this.xPosition << 4) + x, (this.zPosition << 4) + z);
this.blockBiomeArray[idx] = (byte)(generated.biomeID & 255);
if (ModStatus.isEIDBiomeLoaded) {
EndlessIDsCompat.sodium$populateBiomes((Chunk) (Object) this);
} else {
WorldChunkManager manager = this.worldObj.getWorldChunkManager();
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
int idx = (z << 4) + x;
int biome = this.blockBiomeArray[idx] & 255;
if (biome == 255) {
BiomeGenBase generated = manager.getBiomeGenAt((this.xPosition << 4) + x, (this.zPosition << 4) + z);
this.blockBiomeArray[idx] = (byte) (generated.biomeID & 255);
}
}
}
}
@@ -6,15 +6,19 @@ import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderGlobalExt;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.gl.device.RenderDevice;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass;
import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.HandRenderer;
import net.coderbot.iris.pipeline.ShadowRenderer;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.multiplayer.WorldClient;
@@ -23,10 +27,14 @@ import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.culling.Frustrum;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@@ -49,6 +57,8 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
@Shadow public int renderDistanceChunks;
@Shadow public WorldRenderer[] worldRenderers;
@Shadow public WorldRenderer[] sortedWorldRenderers;
@Shadow @Final private TextureManager renderEngine;
@Getter
@Unique private SodiumWorldRenderer renderer;
@@ -141,9 +151,10 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
pipeline = null;
} else {
pipeline = Iris.getPipelineManager().getPipelineNullable();
pipeline.setPhase(WorldRenderingPhase.TERRAIN_CUTOUT);
if(pass == 1) {
if(pass == 0) {
pipeline.setPhase(WorldRenderingPhase.TERRAIN_CUTOUT);
} else if(pass == 1) {
pipeline.setPhase(WorldRenderingPhase.TERRAIN_TRANSLUCENT);
final Camera camera = new Camera(mc.renderViewEntity, (float) partialTicks);
// iris$beginTranslucents
@@ -151,6 +162,7 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
HandRenderer.INSTANCE.renderSolid(null /*poseStack*/, (float) partialTicks, camera, mc.renderGlobal, pipeline);
mc.mcProfiler.endStartSection("iris_pre_translucent");
pipeline.beginTranslucents();
this.renderEngine.bindTexture(TextureMap.locationBlocksTexture);
}
}
// Handle view distance change
@@ -172,6 +184,7 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
try {
final MatrixStack matrixStack = new MatrixStack(ShadowRenderer.ACTIVE ? ShadowRenderer.MODELVIEW : RenderingState.INSTANCE.getModelViewMatrix());
mc.mcProfiler.endStartSection("draw_chunk_layer_" + pass);
this.renderer.drawChunkLayer(BlockRenderPass.VALUES[pass], matrixStack, x, y, z);
} finally {
RenderDevice.exitManagedCode();
@@ -285,6 +298,19 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
this.renderChunksDeep = 0;
}
@WrapOperation(method="renderEntities", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/entity/RenderManager;renderEntitySimple(Lnet/minecraft/entity/Entity;F)Z"))
private boolean angelica$renderEntitySimple(RenderManager instance, Entity entity, float partialTicks, Operation<Boolean> original) {
CapturedRenderingState.INSTANCE.setCurrentEntity(entity.getEntityId());
GbufferPrograms.beginEntities();
try {
return original.call(instance, entity, partialTicks);
} finally {
CapturedRenderingState.INSTANCE.setCurrentEntity(-1);
GbufferPrograms.endEntities();
}
}
@Inject(method="renderEntities", at=@At(value="INVOKE", target="Lnet/minecraft/client/renderer/RenderHelper;enableStandardItemLighting()V", shift = At.Shift.AFTER))
public void sodium$renderTileEntities(EntityLivingBase entity, ICamera camera, float partialTicks, CallbackInfo ci) {
this.renderer.renderTileEntities(entity, camera, partialTicks);
@@ -0,0 +1,19 @@
package com.gtnewhorizons.angelica.mixins.hooks;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fluids.BlockFluidBase;
public class FluidHooks {
/**
* {@link BlockFluidBase#getFluid()} that uses the given Block instead of fetching it from the world again
*/
public static double getFlowDirection(IBlockAccess world, int x, int y, int z, BlockFluidBase block) {
if (!block.getMaterial().isLiquid()) {
return -1000.0;
}
Vec3 vec = block.getFlowVector(world, x, y, z);
return vec.xCoord == 0.0D && vec.zCoord == 0.0D ? -1000.0D : Math.atan2(vec.zCoord, vec.xCoord) - Math.PI / 2D;
}
}
@@ -0,0 +1,9 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import com.gtnewhorizons.angelica.api.QuadProvider;
public interface ModeledBlock {
QuadProvider getModel();
void setModel(QuadProvider model);
}
@@ -14,20 +14,20 @@ import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.IIcon;
@Mixin(targets = "connor135246.campfirebackport.client.rendering.RenderBlockCampfire", remap = false)
@Mixin(value = connor135246.campfirebackport.client.rendering.RenderBlockCampfire.class, remap = false)
public class MixinRenderBlockCampfire {
@Inject(method = "renderFace", at = @At("HEAD"))
private static void angelica$beforeRenderFace(double x, double y, double z, Block block, RenderBlocks renderer, IIcon icon, int side, CallbackInfo ci) {
AnimationsRenderUtils.markBlockTextureForUpdate(icon, renderer.blockAccess);
((ITexturesCache)renderer).getRenderedTextures().add(icon);
}
@ModifyArgs(method = "renderFire", at = @At(value = "INVOKE", target = "Lconnor135246/campfirebackport/client/rendering/RenderBlockCampfire;drawCrossedSquaresTwoIcons(Lnet/minecraft/util/IIcon;Lnet/minecraft/util/IIcon;DDDF)V"))
private static void angelica$onDrawCrossedSquaresTwoIcons(Args args, double x, double y, double z, Block block, RenderBlocks renderer, boolean mix) {
IIcon icon1 = (IIcon)args.get(0);
AnimationsRenderUtils.markBlockTextureForUpdate(icon1, renderer.blockAccess);
((ITexturesCache)renderer).getRenderedTextures().add(icon1);
IIcon icon2 = (IIcon)args.get(1);
AnimationsRenderUtils.markBlockTextureForUpdate(icon2, renderer.blockAccess);
((ITexturesCache)renderer).getRenderedTextures().add(icon2);
@@ -0,0 +1,31 @@
package com.gtnewhorizons.angelica.mixins.late.client.minefactoryreloaded;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import powercrystals.minefactoryreloaded.render.block.RedNetCableRenderer;
import powercrystals.minefactoryreloaded.tile.rednet.TileEntityRedNetCable;
@Mixin(value = RedNetCableRenderer.class)
public abstract class MixinRedNetCableRenderer extends TileEntitySpecialRenderer {
/**
* @author JL2210
* @reason Thread safety compat (check result of getTileEntity for null)
*/
@Inject(method = "renderWorldBlock", at = @At(value = "FIELD", target = "Lpowercrystals/minefactoryreloaded/setup/MFRConfig;TESRCables*:Z"), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, remap = false)
public void angelica$checkNullBeforeAccess(IBlockAccess world, int x, int y, int z, Block block, int modelId,
RenderBlocks renderer, CallbackInfoReturnable<Boolean> cir, TileEntityRedNetCable _cable) {
if (_cable == null) {
cir.setReturnValue(false);
}
}
}
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.models;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadBuilder;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -14,19 +15,19 @@ import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
public class CubeModel implements QuadProvider {
public class DynamicCubeModel implements QuadProvider {
/*
* By the power of ~~theft~~ inspiration, this class is wayyy simpler.
* It's also a basic example of dynamic model building.
*/
public static final ThreadLocal<CubeModel> INSTANCE = ThreadLocal.withInitial(CubeModel::new);
public static final ThreadLocal<DynamicCubeModel> INSTANCE = ThreadLocal.withInitial(DynamicCubeModel::new);
private final NdQuadBuilder builder = new NdQuadBuilder();
private static final List<QuadView> EMPTY = ObjectImmutableList.of();
private final List<QuadView> ONE = new ObjectArrayList<>(1);
public CubeModel() {
public DynamicCubeModel() {
this.ONE.add(null);
}
@@ -44,9 +45,9 @@ public class CubeModel implements QuadProvider {
this.builder.square(dir, 0, 0, 1, 1, 0);
final IIcon tex = block.getIcon(dir.ordinal(), meta);
this.builder.spriteBake(tex, NdQuadBuilder.BAKE_LOCK_UV);
this.builder.spriteBake(tex, QuadBuilder.BAKE_LOCK_UV);
this.builder.color(color, color, color, color);
this.builder.setColors(color);
ONE.set(0, this.builder.build(quadPool.get()));
return ONE;
@@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.models;
import com.gtnewhorizons.angelica.compat.mojang.Axis;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import net.minecraftforge.common.util.ForgeDirection;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import static me.jellysquid.mods.sodium.client.util.MathUtil.fuzzy_eq;
@@ -34,10 +35,17 @@ public abstract class GeometryHelper {
*/
public static ForgeDirection lightFace(NdQuadBuilder quad) {
final Vector3f normal = quad.faceNormal;
return switch (GeometryHelper.longestAxis(normal)) {
case X -> normal.x() > 0 ? ForgeDirection.EAST : ForgeDirection.WEST;
case Y -> normal.y() > 0 ? ForgeDirection.UP : ForgeDirection.DOWN;
case Z -> normal.z() > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH;
return coerceVector(normal);
}
/**
* Returns the direction closest to the given vector.
*/
private static ForgeDirection coerceVector(Vector3f v) {
return switch (GeometryHelper.longestAxis(v)) {
case X -> v.x() > 0 ? ForgeDirection.EAST : ForgeDirection.WEST;
case Y -> v.y() > 0 ? ForgeDirection.UP : ForgeDirection.DOWN;
case Z -> v.z() > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH;
default -> ForgeDirection.UP; // handle WTF case
};
}
@@ -65,4 +73,18 @@ public abstract class GeometryHelper {
return Math.abs(normalZ) > longest
? Axis.Z : result;
}
/**
* Rotates the given direction by the matrix, and returns the closest direction to the output.
*/
public static ForgeDirection rotate(ForgeDirection d, Matrix4f rotMat) {
return rotate(d, rotMat, new Vector3f());
}
/**
* See {@link #rotate(ForgeDirection, Matrix4f)}. This overload allows you to pass a scratch vector instead.
*/
public static ForgeDirection rotate(ForgeDirection d, Matrix4f rotMat, Vector3f v) {
return coerceVector(v.set(d.offsetX, d.offsetY, d.offsetZ).mulPosition(rotMat));
}
}
@@ -1,9 +1,9 @@
package com.gtnewhorizons.angelica.models;
import com.gtnewhorizons.angelica.api.QuadBuilder;
import com.gtnewhorizons.angelica.api.QuadView;
import lombok.Setter;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFlags;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@@ -11,140 +11,75 @@ import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import java.util.Arrays;
public class NdQuadBuilder implements ModelQuadView {
import static com.gtnewhorizons.angelica.models.json.FaceRewindHelper.*;
/**
* Causes texture to appear with no rotation.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
public static final int BAKE_ROTATE_NONE = 0;
public class NdQuadBuilder extends Quad implements QuadBuilder {
/**
* Causes texture to appear rotated 90 deg. clockwise relative to nominal face.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
public static final int BAKE_ROTATE_90 = 1;
/**
* Causes texture to appear rotated 180 deg. relative to nominal face.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
public static final int BAKE_ROTATE_180 = 2;
/**
* Causes texture to appear rotated 270 deg. clockwise relative to nominal face.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
public static final int BAKE_ROTATE_270 = 3;
/**
* When enabled, texture coordinate are assigned based on vertex position.
* Any existing UV coordinates will be replaced.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*
* <p>UV lock always derives texture coordinates based on nominal face, even
* when the quad is not co-planar with that face, and the result is
* the same as if the quad were projected onto the nominal face, which
* is usually the desired result.
*/
public static final int BAKE_LOCK_UV = 4;
/**
* When set, U texture coordinates for the given sprite are
* flipped as part of baking. Can be useful for some randomization
* and texture mapping scenarios. Results are different from what
* can be obtained via rotation and both can be applied.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
public static final int BAKE_FLIP_U = 8;
/**
* Same as {@link #BAKE_FLIP_U} but for V coordinate.
*/
public static final int BAKE_FLIP_V = 16;
/**
* UV coordinates by default are assumed to be 0-16 scale for consistency
* with conventional Minecraft model format. This is scaled to 0-1 during
* baking before interpolation. Model loaders that already have 0-1 coordinates
* can avoid wasteful multiplication/division by passing 0-1 coordinates directly.
* Pass in bakeFlags parameter to {@link #spriteBake(IIcon, int)}.
*/
public static final int BAKE_NORMALIZED = 32;
/**
* Tolerance for determining if the depth parameter to {@link #square(ForgeDirection, float, float, float, float, float)}
* is effectively zero - meaning the face is a cull face.
*/
public static float CULL_FACE_EPSILON = 0.00001f;
private ForgeDirection cullFace = ForgeDirection.UNKNOWN;
private ForgeDirection nominalFace = ForgeDirection.UNKNOWN;
// Defaults to UP, but only because it can't be UNKNOWN or null
private ForgeDirection lightFace = ForgeDirection.UP;
// It's called a header, but because I'm lazy it's at the end
// The header is an int with flags -------- -------- -------- -GGGNNNN, then an int for the normal
private final int[] data = new int[Quad.QUAD_STRIDE];
private int geometryFlags = 0;
private boolean isGeometryInvalid = true;
private int tag = 0;
@Getter
private int colorIndex = -1;
final Vector3f faceNormal = new Vector3f();
public final Material mat = new Material();
@Setter
private int drawMode = GL11.GL_QUADS;
/**
* Dumps to {@param out} and returns it.
*/
@Override
public QuadView build(QuadView out) {
if (this.drawMode != GL11.GL_QUADS)
this.quadrangulate();
// FRAPI does this late, but we need to do it before baking to Nd quads
this.computeGeometry();
out.setRaw(this.data, this.hasShade(), this.cullFace(), this.colorIndex, this.geometryFlags);
out.copyFrom(this);
this.clear();
return out;
}
public void clear() {
/**
* See {@link #build(QuadView)}. This rotates the output by the given matrix.
*/
public QuadView build(QuadView out, Matrix4f rotMat) {
this.pos(0, this.pos(0).mulPosition(rotMat));
this.pos(1, this.pos(1).mulPosition(rotMat));
this.pos(2, this.pos(2).mulPosition(rotMat));
if (this.drawMode == GL11.GL_QUADS)
this.pos(3, this.pos(3).mulPosition(rotMat));
else
this.quadrangulate();
this.computeGeometry();
// Reset the cull face
this.setCullFace();
out.copyFrom(this);
this.clear();
return out;
}
private void clear() {
Arrays.fill(this.data, 0);
this.cullFace = ForgeDirection.UNKNOWN;
this.nominalFace = ForgeDirection.UNKNOWN;
this.setCullFace(ForgeDirection.UNKNOWN);
this.lightFace = ForgeDirection.UP;
this.geometryFlags = 0;
this.isGeometryInvalid = true;
this.tag(0);
this.colorIndex(-1);
this.setColorIndex(-1);
this.mat.reset();
}
/**
* Set vertex color in ARGB format (0xAARRGGBB).
*/
public void color(int vertexIndex, int color) {
data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.COLOR_INDEX] = color;
}
/**
* Convenience: set vertex color for all vertices at once.
*/
public void color(int c0, int c1, int c2, int c3) {
this.color(0, c0);
this.color(1, c1);
this.color(2, c2);
this.color(3, c3);
}
/**
* Value functions identically to {@link Quad#getColorIndex()} and is
* used by renderer / model builder in same way. Default value is -1.
*/
public void colorIndex(int colorIndex) {
this.colorIndex = colorIndex;
this.drawMode = GL11.GL_QUADS;
}
private void computeGeometry() {
@@ -161,38 +96,8 @@ public class NdQuadBuilder implements ModelQuadView {
}
}
/**
* If not {@link ForgeDirection#UNKNOWN}, quad should not be rendered in-world if the
* opposite face of a neighbor block occludes it.
*
* @see NdQuadBuilder#cullFace(ForgeDirection)
*/
public final ForgeDirection cullFace() {
return this.cullFace;
}
/**
* If not {@link ForgeDirection#UNKNOWN}, quad is coplanar with a block face which, if known, simplifies
* or shortcuts geometric analysis that might otherwise be needed.
* Set to {@link ForgeDirection#UNKNOWN} if quad is not coplanar or if this is not known.
* Also controls face culling during block rendering.
*
* <p>{@link ForgeDirection#UNKNOWN} by default.
*
* <p>When called with a non-{@link ForgeDirection#UNKNOWN} value, also sets {@link #nominalFace(ForgeDirection)}
* to the same value.
*
* <p>This is different from the value reported by {@link Quad#getLightFace()}. That value
* is computed based on face geometry and must be non-{@link ForgeDirection#UNKNOWN} in vanilla quads.
* That computed value is returned by {@link #getLightFace()}.
*/
public void cullFace(ForgeDirection dir) {
this.cullFace = dir;
this.nominalFace(dir);
}
private boolean hasShade() {
@Override
public boolean isShade() {
return this.mat.getDiffuse();
}
@@ -203,97 +108,145 @@ public class NdQuadBuilder implements ModelQuadView {
return this.lightFace;
}
/**
* Provides a hint to renderer about the facing of this quad. Not required,
* but if provided can shortcut some geometric analysis if the quad is parallel to a block face.
* Should be the expected value of {@link #getLightFace()}. Value will be confirmed
* and if invalid the correct light face will be calculated.
*
* <p>Null by default, and set automatically by {@link #cullFace(ForgeDirection)}.
*
* <p>Models may also find this useful as the face for texture UV locking and rotation semantics.
*
* <p>Note: This value is not persisted independently when the quad is encoded.
* When reading encoded quads, this value will always be the same as {@link #getLightFace()}.
*/
@Override
public void setCullFace(ForgeDirection dir) {
super.setCullFace(dir);
this.nominalFace(dir);
}
@Override
public void setCullFace() {
this.computeGeometry();
if ((this.geometryFlags & ModelQuadFlags.IS_ALIGNED) != 0)
this.setCullFace(this.lightFace);
else {
this.setCullFace(ForgeDirection.UNKNOWN);
this.nominalFace(this.lightFace);
}
}
@Override
public void nominalFace(@Nullable ForgeDirection face) {
nominalFace = face;
this.nominalFace = face;
}
/**
* See {@link #nominalFace(ForgeDirection)}
*/
@Override
public ForgeDirection nominalFace() {
return nominalFace;
return this.nominalFace;
}
/**
* Sets the geometric vertex position for the given vertex,
* relative to block origin, (0,0,0). Minecraft rendering is designed
* for models that fit within a single block space and is recommended
* that coordinates remain in the 0-1 range, with multi-block meshes
* split into multiple per-block models.
*/
@Override
public void pos(int vertexIndex, float x, float y, float z) {
data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.X_INDEX] = Float.floatToRawIntBits(x);
data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.Y_INDEX] = Float.floatToRawIntBits(y);
data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.Z_INDEX] = Float.floatToRawIntBits(z);
this.setX(vertexIndex, x);
this.setY(vertexIndex, y);
this.setZ(vertexIndex, z);
isGeometryInvalid = true;
}
@Override
public void pos(int vertexIndex, Vector3f vec) {
this.setX(vertexIndex, vec.x);
this.setY(vertexIndex, vec.y);
this.setZ(vertexIndex, vec.z);
isGeometryInvalid = true;
}
@Override
public Vector3f pos(int vertexIndex) {
return new Vector3f(
Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.X_INDEX]),
Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.Y_INDEX]),
Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.Z_INDEX])
this.getX(vertexIndex),
this.getY(vertexIndex),
this.getZ(vertexIndex)
);
}
/**
* Convenience: access x, y, z by index 0-2.
*/
float posByIndex(int vertexIndex, int coordinateIndex) {
return Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.X_INDEX + coordinateIndex]);
@Override
public float posByIndex(int vertexIndex, int coordinateIndex) {
return Float.intBitsToFloat(this.data[vertexIndex * Quad.VERTEX_STRIDE + Quad.X_INDEX + coordinateIndex]);
}
final int MIN_X = 0;
final int MIN_Y = 1;
final int MIN_Z = 2;
final int MAX_X = 3;
final int MAX_Y = 4;
final int MAX_Z = 5;
/**
* Convienence, gets the icon from the block atlas. See {@link #spriteBake(IIcon, int)}
* Rewinds the quad to the standard order. Works as long as four vertex positions have been assigned, and will
* not rewind any non-position data. Recommended to do immediately after vertex assignment, and to set/reset UVs,
* colors, etc. afterwards.
*
* PS: this should only be used on quads parallel to the block grid.
*
* TODO: this doesn't actually work
*/
public void rewind(float x, float y, float z, float X, float Y, float Z) {
boolean[] targets = switch (getLightFace()) {
case DOWN -> DOWN;
case UP -> UP;
case NORTH -> NORTH;
case SOUTH -> SOUTH;
case WEST -> WEST;
case EAST -> EAST;
case UNKNOWN -> throw new RuntimeException("Expected non-UNKNOWN face!");
};
final float ox = getX(0);
final float oy = getY(0);
final float oz = getZ(0);
// Reset the vertices, given the bounds
int iFirst = 0;
for (int i = 0; i < 4; ++i) {
final float px = targets[i * 3] ? X : x;
final float py = targets[i * 3 + 1] ? Y : y;
final float pz = targets[i * 3 + 2] ? Z : z;
pos(i, px, py, pz);
// Save the original first vertex
if (px == ox && py == oy && pz == oz)
iFirst = i;
}
// Shift the UVs - copy to a temp array, then copy back in the right order, wrapping appropriately
float[] uvs = {
getTexU(0),
getTexV(0),
getTexU(1),
getTexV(1),
getTexU(2),
getTexV(2),
getTexU(3),
getTexV(3)
};
for (int i = 0; i < 4; ++i) {
uv((i + iFirst) % 4, uvs[i * 2], uvs[i * 2 + 1]);
}
}
@Override
public void spriteBake(String spriteName, int bakeFlags) {
final IIcon icon = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(spriteName);
TexHelper.bakeSprite(this, icon, bakeFlags);
}
/**
* Assigns sprite atlas u,v coordinates to this quad for the given sprite.
* Can handle UV locking, rotation, interpolation, etc. Control this behavior
* by passing additive combinations of the BAKE_ flags defined in this interface.
*/
@Override
public void spriteBake(IIcon sprite, int bakeFlags) {
TexHelper.bakeSprite(this, sprite, bakeFlags);
}
/**
* Helper method to assign vertex coordinates for a square aligned with the given face.
* Ensures that vertex order is consistent with vanilla convention. (Incorrect order can
* lead to bad AO lighting unless enhanced lighting logic is available/enabled.)
*
* <p>Square will be parallel to the given face and coplanar with the face (and culled if the
* face is occluded) if the depth parameter is approximately zero. See {@link #CULL_FACE_EPSILON}.
*
* <p>All coordinates should be normalized (0-1).
*
* <p>The directions for the faces assume you're looking at them. For top and bottom, they assume you're looking north.
*/
@Override
public void square(ForgeDirection nominalFace, float left, float bottom, float right, float top, float depth) {
if (Math.abs(depth) < CULL_FACE_EPSILON) {
cullFace(nominalFace);
setCullFace(nominalFace);
depth = 0; // avoid any inconsistency for face quads
} else {
cullFace(ForgeDirection.UNKNOWN);
setCullFace(ForgeDirection.UNKNOWN);
}
nominalFace(nominalFace);
@@ -340,62 +293,16 @@ public class NdQuadBuilder implements ModelQuadView {
return this.tag;
}
/**
* Encodes an integer tag with this quad that can later be retrieved via
* {@link NdQuadBuilder#tag()}. Useful for models that want to perform conditional
* transformation or filtering on static meshes.
*/
@Override
public void tag(int tag) {
this.tag = tag;
}
/**
* Set texture coordinates.
*/
@Override
public void uv(int vertexIndex, float u, float v) {
data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.U_INDEX] = Float.floatToRawIntBits(u);
data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.V_INDEX] = Float.floatToRawIntBits(v);
}
@Override
public float getX(int vertexIndex) {
return Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.X_INDEX]);
}
@Override
public float getY(int vertexIndex) {
return Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.Y_INDEX]);
}
@Override
public float getZ(int vertexIndex) {
return Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.Z_INDEX]);
}
@Override
public float getTexU(int vertexIndex) {
return Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.U_INDEX]);
}
@Override
public float getTexV(int vertexIndex) {
return Float.intBitsToFloat(data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.V_INDEX]);
}
@Override
public int getColor(int vertexIndex) {
return this.data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.COLOR_INDEX];
}
@Override
public int getNormal(int vertexIndex) {
return this.data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.NORMAL_INDEX];
}
@Override
public int getLight(int vertexIndex) {
return this.data[vertexIndex * Quad.INTS_PER_VERTEX + Quad.LIGHTMAP_INDEX];
this.setTexU(vertexIndex, u);
this.setTexV(vertexIndex, v);
}
@Override
@@ -407,56 +314,4 @@ public class NdQuadBuilder implements ModelQuadView {
public TextureAtlasSprite rubidium$getSprite() {
return null;
}
/**
* Modern Minecraft uses magic arrays to do this without breaking AO. This is the same thing, but without arrays.
*/
public static Vector3f mapSideToVertex(Vector3f from, Vector3f to, int index, ForgeDirection side) {
return switch (side) {
case DOWN -> switch (index) {
case 0 -> new Vector3f(from.x, from.y, to.z);
case 1 -> new Vector3f(from.x, from.y, from.z);
case 2 -> new Vector3f(to.x, from.y, from.z);
case 3 -> new Vector3f(to.x, from.y, to.z);
default -> throw new RuntimeException("Too many indices!");
};
case UP -> switch (index) {
case 0 -> new Vector3f(from.x, to.y, from.z);
case 1 -> new Vector3f(from.x, to.y, to.z);
case 2 -> new Vector3f(to.x, to.y, to.z);
case 3 -> new Vector3f(to.x, to.y, from.z);
default -> throw new RuntimeException("Too many indices!");
};
case NORTH -> switch (index) {
case 0 -> new Vector3f(to.x, to.y, from.z);
case 1 -> new Vector3f(to.x, from.y, from.z);
case 2 -> new Vector3f(from.x, from.y, from.z);
case 3 -> new Vector3f(from.x, to.y, from.z);
default -> throw new RuntimeException("Too many indices!");
};
case SOUTH -> switch (index) {
case 0 -> new Vector3f(from.x, to.y, to.z);
case 1 -> new Vector3f(from.x, from.y, to.z);
case 2 -> new Vector3f(to.x, from.y, to.z);
case 3 -> new Vector3f(to.x, to.y, to.z);
default -> throw new RuntimeException("Too many indices!");
};
case WEST -> switch (index) {
case 0 -> new Vector3f(from.x, to.y, from.z);
case 1 -> new Vector3f(from.x, from.y, from.z);
case 2 -> new Vector3f(from.x, from.y, to.z);
case 3 -> new Vector3f(from.x, to.y, to.z);
default -> throw new RuntimeException("Too many indices!");
};
case EAST -> switch (index) {
case 0 -> new Vector3f(to.x, to.y, to.z);
case 1 -> new Vector3f(to.x, from.y, to.z);
case 2 -> new Vector3f(to.x, from.y, from.z);
case 3 -> new Vector3f(to.x, to.y, from.z);
default -> throw new RuntimeException("Too many indices!");
};
case UNKNOWN -> null;
};
}
}
@@ -1,6 +1,5 @@
package com.gtnewhorizons.angelica.models;
import net.minecraft.util.MathHelper;
import net.minecraftforge.common.util.ForgeDirection;
import org.jetbrains.annotations.NotNull;
import org.joml.Vector3f;
@@ -10,9 +9,6 @@ import static me.jellysquid.mods.sodium.common.util.DirectionUtil.STEP;
public class NormalHelper {
private static final float PACK = 127.0f;
private static final float UNPACK = 1.0f / PACK;
/**
* Computes the face normal of the given quad and saves it in the provided non-null vector.
* If {@link NdQuadBuilder#nominalFace()} is set will optimize by confirming quad is parallel to that
@@ -24,7 +20,7 @@ public class NormalHelper {
public static void computeFaceNormal(@NotNull Vector3f saveTo, NdQuadBuilder q) {
final ForgeDirection nominalFace = q.nominalFace();
if (nominalFace != null && GeometryHelper.isQuadParallelToFace(nominalFace, q)) {
if (nominalFace != ForgeDirection.UNKNOWN && GeometryHelper.isQuadParallelToFace(nominalFace, q)) {
Vector3i vec = STEP[nominalFace.ordinal()];
saveTo.set(vec.x, vec.y, vec.z);
return;
@@ -64,22 +60,4 @@ public class NormalHelper {
saveTo.set(normX, normY, normZ);
}
/**
* Like {@link #packNormal(float, float, float, float)}, but without a {@code w} value.
*/
public static int packNormal(float x, float y, float z) {
x = MathHelper.clamp_float(x, -1, 1);
y = MathHelper.clamp_float(y, -1, 1);
z = MathHelper.clamp_float(z, -1, 1);
return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16);
}
/**
* Like {@link #packNormal(Vector3f, float)}, but without a {@code w} value.
*/
public static int packNormal(Vector3f normal) {
return packNormal(normal.x, normal.y, normal.z);
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.models;
import com.gtnewhorizons.angelica.api.QuadBuilder;
import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
@@ -35,10 +36,10 @@ public class TexHelper {
* rotation, interpolation, etc. Textures must not be already baked.
*/
public static void bakeSprite(NdQuadBuilder quad, IIcon sprite, int bakeFlags) {
if (quad.nominalFace() != ForgeDirection.UNKNOWN && (NdQuadBuilder.BAKE_LOCK_UV & bakeFlags) != 0) {
if (quad.nominalFace() != ForgeDirection.UNKNOWN && (QuadBuilder.BAKE_LOCK_UV & bakeFlags) != 0) {
// Assigns normalized UV coordinates based on vertex positions
applyModifier(quad, UVLOCKERS[quad.nominalFace().ordinal()]);
} else if ((NdQuadBuilder.BAKE_NORMALIZED & bakeFlags) == 0) { // flag is NOT set, UVs are assumed to not be normalized yet as is the default, normalize through dividing by 16
} else if ((QuadBuilder.BAKE_NORMALIZED & bakeFlags) == 0) { // flag is NOT set, UVs are assumed to not be normalized yet as is the default, normalize through dividing by 16
// Scales from 0-16 to 0-1
applyModifier(quad, (q, i) -> q.uv(i, q.getTexU(i) * NORMALIZER, q.getTexV(i) * NORMALIZER));
}
@@ -51,12 +52,12 @@ public class TexHelper {
applyModifier(quad, ROTATIONS[rotation]);
}
if ((NdQuadBuilder.BAKE_FLIP_U & bakeFlags) != 0) {
if ((QuadBuilder.BAKE_FLIP_U & bakeFlags) != 0) {
// Inverts U coordinates. Assumes normalized (0-1) values.
applyModifier(quad, (q, i) -> q.uv(i, 1 - q.getTexU(i), q.getTexV(i)));
}
if ((NdQuadBuilder.BAKE_FLIP_V & bakeFlags) != 0) {
if ((QuadBuilder.BAKE_FLIP_V & bakeFlags) != 0) {
// Inverts V coordinates. Assumes normalized (0-1) values.
applyModifier(quad, (q, i) -> q.uv(i, q.getTexU(i), 1 - q.getTexV(i)));
}
@@ -1,22 +1,191 @@
package com.gtnewhorizons.angelica.models;
import com.gtnewhorizons.angelica.models.json.JsonModel;
import com.gtnewhorizons.angelica.models.json.Loader;
import com.gtnewhorizons.angelica.models.json.Variant;
import net.minecraft.util.ResourceLocation;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.ModelLoader;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.api.Variant;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.models.json.ModelLocation;
import com.gtnewhorizons.angelica.models.template.BlockColoredCube;
import com.gtnewhorizons.angelica.models.template.BlockStaticCube;
import com.gtnewhorizons.angelica.models.template.Column3Rot;
import com.gtnewhorizons.angelica.models.template.Model4Rot;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
public class VanillaModels {
public static final Variant stoneVariant = new Variant(
new ResourceLocation("blocks/stone"),
private static boolean init = false;
public static final BlockStaticCube STONE = new BlockStaticCube("stone");
public static final BlockStaticCube GLASS = new BlockStaticCube("glass");
public static BlockColoredCube OAK_LEAVES;
public static BlockColoredCube SPRUCE_LEAVES;
public static BlockColoredCube BIRCH_LEAVES;
public static BlockColoredCube JUNGLE_LEAVES;
public static QuadProvider OLD_LEAF = new QuadProvider() {
@Override
public int getColor(IBlockAccess world, BlockPos pos, Block block, int meta, Random random) {
return QuadProvider.getDefaultColor(world, pos, block);
}
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return (switch (meta % 4) {
case 0 -> OAK_LEAVES;
case 1 -> SPRUCE_LEAVES;
case 2 -> BIRCH_LEAVES;
case 3 -> JUNGLE_LEAVES;
default -> throw new IllegalStateException("Unexpected value: " + meta);
}).getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
};
public static BlockColoredCube ACACIA_LEAVES;
public static BlockColoredCube DARK_OAK_LEAVES;
public static QuadProvider NEW_LEAF = new QuadProvider() {
@Override
public int getColor(IBlockAccess world, BlockPos pos, Block block, int meta, Random random) {
return QuadProvider.getDefaultColor(world, pos, block);
}
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return (switch (meta % 2) {
case 0 -> ACACIA_LEAVES;
case 1 -> DARK_OAK_LEAVES;
default -> throw new IllegalStateException("Unexpected value: " + meta);
}).getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
};
public static Column3Rot OAK_LOG;
public static Column3Rot SPRUCE_LOG;
public static Column3Rot BIRCH_LOG;
public static Column3Rot JUNGLE_LOG;
public static BlockStaticCube OAK_WOOD;
public static BlockStaticCube BIRCH_WOOD;
public static BlockStaticCube SPRUCE_WOOD;
public static BlockStaticCube JUNGLE_WOOD;
public static QuadProvider OLD_LOG = new QuadProvider() {
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
if (meta > 11) {
return (switch (meta) {
case 12 -> OAK_WOOD;
case 13 -> SPRUCE_WOOD;
case 14 -> BIRCH_WOOD;
case 15 -> JUNGLE_WOOD;
default -> throw new IllegalStateException("Unexpected value: " + meta);
}).getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
Column3Rot ret = switch (meta % 4) {
case 0 -> OAK_LOG;
case 1 -> SPRUCE_LOG;
case 2 -> BIRCH_LOG;
case 3 -> JUNGLE_LOG;
default -> throw new IllegalStateException("Unexpected value: " + meta);
};
return (switch (meta / 4) {
case 0 -> ret.updown();
case 1 -> ret.eastwest();
case 2 -> ret.northsouth();
default -> throw new IllegalStateException("Unexpected value: " + meta);
}).getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
};
public static Column3Rot ACACIA_LOG;
public static Column3Rot DARK_OAK_LOG;
public static BlockStaticCube ACACIA_WOOD;
public static BlockStaticCube DARK_OAK_WOOD;
public static QuadProvider NEW_LOG = new QuadProvider() {
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
if (meta > 11) {
return (switch (meta) {
case 12 -> ACACIA_WOOD;
case 13 -> DARK_OAK_WOOD;
default -> throw new IllegalStateException("Unexpected value: " + meta);
}).getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
Column3Rot ret = switch (meta % 4) {
case 0 -> ACACIA_LOG;
case 1 -> DARK_OAK_LOG;
default -> throw new IllegalStateException("Unexpected value: " + meta);
};
return (switch (meta / 4) {
case 0 -> ret.updown();
case 1 -> ret.eastwest();
case 2 -> ret.northsouth();
default -> throw new IllegalStateException("Unexpected value: " + meta);
}).getQuads(world, pos, block, meta, dir, random, color, quadPool);
}
};
public static final Variant workbench = new Variant(
new ModelLocation("block/crafting_table"),
0,
0,
true
);
public static JsonModel stoneModel;
public static QuadProvider WORKBENCH;
public static Model4Rot LECTERN;
public static void init() {
if (init) {
throw new RuntimeException("Vanilla models were baked twice!");
}
if (AngelicaConfig.injectQPRendering) {
ACACIA_LEAVES = new BlockColoredCube("leaves_acacia");
BIRCH_LEAVES = new BlockColoredCube("leaves_birch");
DARK_OAK_LEAVES = new BlockColoredCube("leaves_big_oak");
JUNGLE_LEAVES = new BlockColoredCube("leaves_jungle");
OAK_LEAVES = new BlockColoredCube("leaves_oak");
SPRUCE_LEAVES = new BlockColoredCube("leaves_spruce");
ACACIA_LOG = new Column3Rot(new ModelLocation("block/acacia_log"));
BIRCH_LOG = new Column3Rot(new ModelLocation("block/birch_log"));
DARK_OAK_LOG = new Column3Rot(new ModelLocation("block/dark_oak_log"));
JUNGLE_LOG = new Column3Rot(new ModelLocation("block/jungle_log"));
OAK_LOG = new Column3Rot(new ModelLocation("block/oak_log"));
SPRUCE_LOG = new Column3Rot(new ModelLocation("block/spruce_log"));
ACACIA_WOOD = new BlockStaticCube("log_acacia");
BIRCH_WOOD = new BlockStaticCube("log_birch");
DARK_OAK_WOOD = new BlockStaticCube("log_big_oak");
JUNGLE_WOOD = new BlockStaticCube("log_jungle");
OAK_WOOD = new BlockStaticCube("log_oak");
SPRUCE_WOOD = new BlockStaticCube("log_spruce");
ModelLoader.registerModels(VanillaModels::loadModels,
workbench);
}
if (AngelicaConfig.enableTestBlocks)
LECTERN = new Model4Rot(new ModelLocation("block/lectern"));
init = true;
}
public static void loadModels() {
stoneModel = Loader.getModel(stoneVariant);
WORKBENCH = ModelLoader.getModel(workbench);
}
}
@@ -0,0 +1,18 @@
package com.gtnewhorizons.angelica.models.json;
/**
* Modern vanilla uses magic numbers to rewind quads, let's try that. NOTE: may or may not work with sheared quads, but
* probably not.
*/
public class FaceRewindHelper {
/**
* These constants map face sides to the characteristics of the vertexes. False is min, true is max, and the order
* is XYZ, repeating 4 times. So the first vertex of DOWN faces should have the minimum X and Y and the maximum Z.
*/
public static final boolean[] DOWN = { false, false, true, false, false, false, true, false, false, true, false, true };
public static final boolean[] UP = { false, true, false, false, true, true, true, true, true, true, true, false };
public static final boolean[] NORTH = { true, true, false, true, false, false, false, false, false, false, true, false };
public static final boolean[] SOUTH = { false, true, true, false, false, true, true, false, true, true, true, true };
public static final boolean[] WEST = { false, true, false, false, false, false, false, false, true, false, true, true };
public static final boolean[] EAST = { true, true, true, true, false, true, true, false, false, true, true, false };
}
@@ -7,10 +7,11 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadBuilder;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.api.Variant;
import com.gtnewhorizons.angelica.compat.mojang.Axis;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import com.gtnewhorizons.angelica.models.NdQuadBuilder;
import com.gtnewhorizons.angelica.utils.DirUtil;
import it.unimi.dsi.fastutil.Function;
@@ -18,6 +19,7 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectImmutableList;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockAccess;
@@ -35,6 +37,8 @@ import java.util.Random;
import java.util.function.Supplier;
import static com.gtnewhorizons.angelica.utils.JsonUtil.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static me.jellysquid.mods.sodium.common.util.DirectionUtil.ALL_DIRECTIONS;
public class JsonModel implements QuadProvider {
@@ -52,7 +56,7 @@ public class JsonModel implements QuadProvider {
private final Map<ForgeDirection, List<QuadView>> sidedQuadStore = new Object2ObjectOpenHashMap<>();
private static final List<QuadView> EMPTY = ObjectImmutableList.of();
JsonModel(@Nullable ResourceLocation parentId, boolean useAO, Map<ModelDisplay.Position, ModelDisplay> display, Map<String, String> textures, List<ModelElement> elements) {
public JsonModel(@Nullable ResourceLocation parentId, boolean useAO, Map<ModelDisplay.Position, ModelDisplay> display, Map<String, String> textures, List<ModelElement> elements) {
this.parentId = parentId;
this.useAO = useAO;
this.display = display;
@@ -63,7 +67,7 @@ public class JsonModel implements QuadProvider {
/**
* Makes a shallow copy of og. This allows you to bake the same model multiple times with various transformations.
*/
JsonModel(JsonModel og) {
public JsonModel(JsonModel og) {
this.parentId = og.parentId;
this.parent = og.parent;
@@ -76,7 +80,6 @@ public class JsonModel implements QuadProvider {
public void bake(Variant v) {
final Matrix4f vRot = v.getAffineMatrix();
final NdQuadBuilder builder = new NdQuadBuilder();
// Append faces from each element
@@ -91,28 +94,40 @@ public class JsonModel implements QuadProvider {
for (ModelElement.Face f : e.getFaces()) {
float x = Float.MAX_VALUE;
float y = Float.MAX_VALUE;
float z = Float.MAX_VALUE;
float X = Float.MIN_VALUE;
float Y = Float.MIN_VALUE;
float Z = Float.MIN_VALUE;
// Assign vertexes
for (int i = 0; i < 4; ++i) {
final Vector3f vert =
rot.transformPosition(NdQuadBuilder.mapSideToVertex(from, to, i, f.getName()));
vRot.transformPosition(vert);
QuadBuilder.mapSideToVertex(from, to, i, f.getName()).mulPosition(rot).mulPosition(vRot);
builder.pos(i, vert.x, vert.y, vert.z);
x = min(x, vert.x);
y = min(y, vert.y);
z = min(z, vert.z);
X = max(X, vert.x);
Y = max(Y, vert.y);
Z = max(Z, vert.z);
}
// Set culling and nominal faces
builder.cullFace(f.getCullFace());
builder.nominalFace(f.getName());
builder.setCullFace();
// Set bake flags
int flags = switch(f.getRotation()) {
case 90 -> NdQuadBuilder.BAKE_ROTATE_90;
case 180 -> NdQuadBuilder.BAKE_ROTATE_180;
case 270 -> NdQuadBuilder.BAKE_ROTATE_270;
default -> NdQuadBuilder.BAKE_ROTATE_NONE;
case 90 -> QuadBuilder.BAKE_ROTATE_90;
case 180 -> QuadBuilder.BAKE_ROTATE_180;
case 270 -> QuadBuilder.BAKE_ROTATE_270;
default -> QuadBuilder.BAKE_ROTATE_NONE;
};
// Set UV
// TODO: UV locking
final Vector4f uv = f.getUv();
if (uv != null) {
@@ -123,15 +138,14 @@ public class JsonModel implements QuadProvider {
} else {
// Not sure if this is correct, but it seems to fix things
flags |= NdQuadBuilder.BAKE_LOCK_UV;
flags |= QuadBuilder.BAKE_LOCK_UV;
}
// Set the sprite
builder.spriteBake(this.textures.get(f.getTexture()), flags);
// Set the tint index
final int tint = f.getTintIndex();
builder.color(tint, tint, tint, tint);
builder.setColors(f.getTintIndex());
// Set AO
builder.mat.setAO(this.useAO);
@@ -139,7 +153,7 @@ public class JsonModel implements QuadProvider {
// Bake and add it
final QuadView q = builder.build(new Quad());
this.allQuadStore.add(q);
this.sidedQuadStore.computeIfAbsent(f.getCullFace(),
this.sidedQuadStore.computeIfAbsent(q.getCullFace(),
o -> new ObjectArrayList<>()).add(q);
}
}
@@ -207,7 +221,7 @@ public class JsonModel implements QuadProvider {
}
}
static class Deserializer implements JsonDeserializer<JsonModel> {
public static class Deserializer implements JsonDeserializer<JsonModel> {
private Vector3f loadVec3(JsonObject in, String name) {
@@ -275,7 +289,15 @@ public class JsonModel implements QuadProvider {
// Trim leading octothorpes. They indicate a texture variable, but I don't actually care.
String s = e.getValue().getAsString();
if (s.startsWith("#")) s = s.substring(1);
if (s.startsWith("#")) {
s = s.substring(1);
} else if (s.startsWith("minecraft:")) {
// Because of how we fetch textures from the atlas, minecraft textures need to have their domain
// stripped
s = s.substring(10);
}
textures.put(e.getKey(), s);
}
}
@@ -352,7 +374,14 @@ public class JsonModel implements QuadProvider {
final JsonObject in = json.getAsJsonObject();
final String parent = loadStr(in, "parent", "");
final ResourceLocation parentId = (parent.isEmpty()) ? null : new ResourceLocation(parent);
ResourceLocation parentId = null;
if (!parent.isEmpty()) {
if (parent.contains(":")) {
parentId = new ModelLocation(parent.split(":")[0], parent.split(":")[1]);
} else {
parentId = new ModelLocation(parent);
}
}
final boolean useAO = loadBool(in, "ambientocclusion", true);
final Map<ModelDisplay.Position, ModelDisplay> display = loadDisplay(in);
@@ -21,7 +21,7 @@ public class ModelDisplay {
this.scale = scale;
}
enum Position {
public enum Position {
thirdperson_righthand,
thirdperson_lefthand,
firstperson_righthand,
@@ -0,0 +1,20 @@
package com.gtnewhorizons.angelica.models.json;
import net.minecraft.util.ResourceLocation;
public class ModelLocation extends ResourceLocation {
/**
* Create a model location in the minecraft domain.
*/
public ModelLocation(String path) {
super("models/" + path + ".json");
}
/**
* Create a model location in any domain
*/
public ModelLocation(String domain, String path) {
super(domain, "models/" + path + ".json");
}
}
@@ -0,0 +1,61 @@
package com.gtnewhorizons.angelica.models.template;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import it.unimi.dsi.fastutil.objects.ObjectImmutableList;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
/**
* While this class does not provide dynamic quads, they still need to be threadlocaled because the color of the quads
* are modified.
*/
public class BlockColoredCube extends BlockStaticCube {
private ThreadLocal<List<QuadView>[]> threadedStore;
public BlockColoredCube(String block) {
super(block);
}
@Override
protected void bake() {
super.bake();
// Kind of a mess, but it's required because I don't want to just store quads - that would require initializing
// a new List every time. This ain't efficient, but it only runs when a new thread is spun off.
this.threadedStore = ThreadLocal.withInitial(() -> {
final List<QuadView>[] ret = new List[7];
for (int i = 0; i < 6; ++i) {
ret[i] = this.store[i].stream().map(new Quad()::copyFrom)
.collect(ObjectImmutableList.toListWithExpectedSize(1));
}
ret[6] = ObjectImmutableList.of();
return ret;
});
}
@Override
public int getColor(IBlockAccess world, BlockPos pos, Block block, int meta, Random random) {
return QuadProvider.getDefaultColor(world, pos, block);
}
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
final List<QuadView> ret = this.threadedStore.get()[dir.ordinal()];
if (dir != ForgeDirection.UNKNOWN)
ret.get(0).setColors(color);
return ret;
}
}
@@ -0,0 +1,46 @@
package com.gtnewhorizons.angelica.models.template;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.QuadBuilder;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.models.NdQuadBuilder;
import com.gtnewhorizons.angelica.api.ModelLoader;
import it.unimi.dsi.fastutil.objects.ObjectImmutableList;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
public class BlockStaticCube implements QuadProvider {
private final String textureName;
protected final List<QuadView>[] store = new List[7];
public BlockStaticCube(String textureName) {
this.textureName = textureName;
ModelLoader.registerBaker(this::bake);
}
protected void bake() {
final NdQuadBuilder builder = new NdQuadBuilder();
for (ForgeDirection f : ForgeDirection.VALID_DIRECTIONS) {
builder.square(f, 0, 0, 1, 1, 0);
builder.spriteBake(this.textureName, QuadBuilder.BAKE_LOCK_UV);
builder.setColors(-1);
this.store[f.ordinal()] = ObjectImmutableList.of(builder.build(new Quad()));
}
this.store[6] = ObjectImmutableList.of();
}
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return store[dir.ordinal()];
}
}
@@ -0,0 +1,31 @@
package com.gtnewhorizons.angelica.models.template;
import com.gtnewhorizons.angelica.api.ModelLoader;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.Variant;
import net.minecraft.util.ResourceLocation;
/**
* Use this to create a full cube column rotatable in 3 directions - vertical, x, and z
*/
public class Column3Rot {
public final Variant[] variants = new Variant[3];
public final QuadProvider[] models = new QuadProvider[3];
public Column3Rot(ResourceLocation model) {
this.variants[0] = new Variant(model, 0, 0, false);
this.variants[1] = new Variant(model, 90, 90, false);
this.variants[2] = new Variant(model, 0, 90, false);
ModelLoader.registerModels(() -> {
for (int i = 0; i < 3; ++i)
this.models[i] = ModelLoader.getModel(this.variants[i]);
}, this.variants);
}
public QuadProvider updown() { return this.models[0]; }
public QuadProvider eastwest() { return this.models[1]; }
public QuadProvider northsouth() { return this.models[2]; }
}
@@ -0,0 +1,65 @@
package com.gtnewhorizons.angelica.models.template;
import com.gtnewhorizons.angelica.api.BlockPos;
import com.gtnewhorizons.angelica.api.ModelLoader;
import com.gtnewhorizons.angelica.api.QuadBuilder;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.models.NdQuadBuilder;
import it.unimi.dsi.fastutil.objects.ObjectImmutableList;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
import org.joml.Matrix4f;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
public class ColumnModel implements QuadProvider {
private final String topTex;
private final String sideTex;
protected final List<QuadView>[] store = new List[7];
private boolean rotate = false;
private Matrix4f rotMat;
public ColumnModel(String topTex, String sideTex, Matrix4f rotMat) {
this(topTex, sideTex);
this.rotate = true;
this.rotMat = rotMat;
}
public ColumnModel(String topTex, String sideTex) {
this.topTex = topTex;
this.sideTex = sideTex;
ModelLoader.registerBaker(this::bake);
}
protected void bake() {
final NdQuadBuilder builder = new NdQuadBuilder();
for (ForgeDirection f : ForgeDirection.VALID_DIRECTIONS) {
builder.square(f, 0, 0, 1, 1, 0);
final String tex = (f == ForgeDirection.UP || f == ForgeDirection.DOWN) ? this.topTex : this.sideTex;
builder.spriteBake(tex, QuadBuilder.BAKE_LOCK_UV);
builder.setColors(-1);
final List<QuadView> tmp = ObjectImmutableList.of(
(this.rotate) ? builder.build(new Quad(), this.rotMat) : builder.build(new Quad()));
this.store[tmp.get(0).getCullFace().ordinal()] = tmp;
}
this.store[6] = ObjectImmutableList.of();
}
@Override
public List<QuadView> getQuads(IBlockAccess world, BlockPos pos, Block block, int meta, ForgeDirection dir, Random random, int color, Supplier<QuadView> quadPool) {
return this.store[dir.ordinal()];
}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.models.template;
import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.ModelLoader;
import com.gtnewhorizons.angelica.api.Variant;
import net.minecraft.util.ResourceLocation;
/**
* Use this to create JSON model rotatable in 4 directions - NSWE
*/
public class Model4Rot {
public final QuadProvider[] models = new QuadProvider[4];
private final Variant[] modelIds;
public Model4Rot(ResourceLocation modelLoc) {
this.modelIds = new Variant[] {
new Variant(modelLoc, 0, 0, false),
new Variant(modelLoc, 180, 0, false),
new Variant(modelLoc, 90, 0, false),
new Variant(modelLoc, 270, 0, false)
};
ModelLoader.registerModels(() -> loadModels(this), this.modelIds);
}
public static void loadModels(Model4Rot model) {
for (int i = 0; i < 4; ++i)
model.models[i] = ModelLoader.getModel(model.modelIds[i]);
}
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.proxy;
import com.google.common.base.Objects;
import com.gtnewhorizons.angelica.common.BlockTest;
import com.gtnewhorizons.angelica.api.ModelLoader;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
@@ -10,9 +10,9 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.debug.OpenGLDebugging;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.models.VanillaModels;
import com.gtnewhorizons.angelica.models.json.Loader;
import com.gtnewhorizons.angelica.render.CloudRenderer;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.utils.AssetLoader;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
@@ -66,10 +66,7 @@ public class ClientProxy extends CommonProxy {
FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
if (AngelicaConfig.enableTestBlocks)
Loader.registerModels(BlockTest::loadModel, BlockTest.modelId);
if (AngelicaConfig.injectQPRendering)
Loader.registerModels(VanillaModels::loadModels, VanillaModels.stoneVariant);
AssetLoader.load();
}
@@ -120,7 +117,7 @@ public class ClientProxy extends CommonProxy {
glsmKeyBinding = new KeyBinding("Print GLSM Debug", Keyboard.KEY_NONE, "Angelica Keybinds");
ClientRegistry.registerKeyBinding(glsmKeyBinding);
Loader.loadModels();
VanillaModels.init();
if(ModStatus.isBetterCrashesLoaded) {
BetterCrashesCompat.init();
@@ -152,6 +149,9 @@ public class ClientProxy extends CommonProxy {
LOGGER.error("Could not replace LOTR handle render code with thread safe version");
}
}
Minecraft.getMinecraft().refreshResources();
ModelLoader.loadModels();
}
float lastIntegratedTickTime;
@@ -289,7 +289,7 @@ public class ClientProxy extends CommonProxy {
}
if (!baked) {
Loader.bakeModels();
ModelLoader.bakeModels();
baked = true;
}
}
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.proxy;
import com.gtnewhorizons.angelica.common.BlockTest;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.utils.AssetLoader;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
@@ -64,6 +64,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
private VertexBuffer vbo;
private int cloudMode = -1;
private int renderDistance = -1;
private int cloudElevation = -1;
private int scaleMult = -1;
private DynamicTexture COLOR_TEX = null;
@@ -82,9 +84,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
return instance;
}
private int getScale() {
return cloudMode == 2 ? 12 : 8;
return (cloudMode == 2 ? 12 : 8) * scaleMult;
}
private float ceilToScale(float value) {
@@ -139,11 +140,12 @@ public class CloudRenderer implements IResourceManagerReloadListener {
tessellator.pos(sectX0, 0, sectZ1).tex(u0, v1).color(bCol, bCol, bCol, ALPHA).endVertex();
if (fancy) {
final int height = HEIGHT * scaleMult;
// Top
tessellator.pos(sectX0, HEIGHT, sectZ0).tex(u0, v0).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX0, HEIGHT, sectZ1).tex(u0, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, HEIGHT, sectZ1).tex(u1, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, HEIGHT, sectZ0).tex(u1, v0).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX0, height, sectZ0).tex(u0, v0).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX0, height, sectZ1).tex(u0, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, height, sectZ1).tex(u1, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, height, sectZ0).tex(u1, v0).color(1, 1, 1, ALPHA).endVertex();
float slice;
float sliceCoord0;
@@ -157,8 +159,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
if (slice > -CULL_DIST) {
slice += INSET;
tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, HEIGHT, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, HEIGHT, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
slice -= INSET;
}
@@ -168,8 +170,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
if (slice <= CULL_DIST) {
slice -= INSET;
tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, HEIGHT, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, HEIGHT, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
slice += INSET;
}
@@ -183,8 +185,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
if (slice > -CULL_DIST) {
slice += INSET;
tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, HEIGHT, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, HEIGHT, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
slice -= INSET;
}
@@ -194,8 +196,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
if (slice <= CULL_DIST) {
slice -= INSET;
tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, HEIGHT, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, HEIGHT, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
slice += INSET;
}
@@ -238,21 +240,32 @@ public class CloudRenderer implements IResourceManagerReloadListener {
public void checkSettings() {
GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff)Settings.MODE_CLOUDS.option.getStore();
final int cloudQualitySetting = cloudGraphicsQuality == GraphicsQualityOff.FANCY
final int cloudQualitySetting = cloudGraphicsQuality == GraphicsQualityOff.FANCY
|| cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics ? 2 : 1;
boolean newEnabled = mc.gameSettings.shouldRenderClouds()
final boolean newEnabled = mc.gameSettings.shouldRenderClouds()
&& mc.theWorld != null
&& mc.theWorld.provider.isSurfaceWorld();
final int targetDistance = Math.max(mc.gameSettings.renderDistanceChunks, (int)Settings.RENDER_DISTANCE_CLOUDS.option.getStore());
final int cloudScaleMult = (int)Settings.CLOUD_SCALE.option.getStore();
if (isBuilt()
&& (!newEnabled
|| cloudQualitySetting != cloudMode
|| mc.gameSettings.renderDistanceChunks != renderDistance)) {
|| targetDistance != renderDistance
|| cloudScaleMult != scaleMult)) {
dispose();
}
cloudMode = cloudQualitySetting;
renderDistance = mc.gameSettings.renderDistanceChunks;
renderDistance = targetDistance;
scaleMult = cloudScaleMult;
cloudElevation = mc.theWorld == null ? 128 : (int)mc.theWorld.provider.getCloudHeight();
//Allows the setting to work with RFG and similar without hardcoding.
//The minimum height check is so stuff like Aether cloud height doesn't get messed up.
if(cloudElevation >= 96) {
cloudElevation = (int)Settings.CLOUD_HEIGHT.option.getStore();
}
if (newEnabled && !isBuilt()) {
build();
@@ -268,7 +281,7 @@ public class CloudRenderer implements IResourceManagerReloadListener {
double totalOffset = cloudTicks + partialTicks;
double x = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks + totalOffset * 0.03;
double y = mc.theWorld.provider.getCloudHeight() - (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks) + 0.33;
double y = cloudElevation - (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks) + 0.33;
double z = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks;
int scale = getScale();
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import lombok.Getter;
import lombok.Setter;
import org.joml.Matrix4f;
import org.joml.Vector3d;
import org.lwjgl.BufferUtils;
@@ -21,6 +22,9 @@ public class RenderingState {
private final Matrix4f projectionMatrix = new Matrix4f().identity();
@Getter
private final Matrix4f modelViewMatrix = new Matrix4f().identity();
@Getter
@Setter
private float fov;
public void setCameraPosition(double x, double y, double z) {
@@ -0,0 +1,112 @@
package com.gtnewhorizons.angelica.transform;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.io.FileUtils;
import org.spongepowered.asm.lib.ClassReader;
import org.spongepowered.asm.lib.ClassWriter;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.InsnNode;
import org.spongepowered.asm.lib.tree.JumpInsnNode;
import org.spongepowered.asm.lib.tree.LabelNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.transformers.MixinClassWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
public class HUDCachingTransformer implements IClassTransformer, Opcodes {
static final String HUDCaching = "com/gtnewhorizons/angelica/hudcaching/HUDCaching$HUDCachingHooks";
private static final boolean DUMP_CLASSES = Boolean.parseBoolean(System.getProperty("angelica.dumpClass", "false"));
static final Map<String, List<String>> ReturnEarlyMethods = ImmutableMap.of(
"thaumcraft.client.lib.RenderEventHandler", ImmutableList.of("renderOverlay"),
"com.kentington.thaumichorizons.client.lib.RenderEventHandler", ImmutableList.of("renderOverlay")
);
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
if (basicClass == null) return null;
if (ReturnEarlyMethods.containsKey(transformedName)) {
ClassReader cr = new ClassReader(basicClass);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
for (String targetMethod : ReturnEarlyMethods.get(transformedName)) {
for (MethodNode method : cn.methods) {
if (!method.name.equals(targetMethod)) continue;
InsnList list = new InsnList();
LabelNode exitLabel = new LabelNode();
AngelicaTweaker.LOGGER.info("Injecting HUDCaching Conditional Return: " + transformedName + "#" + method.name);
list.add(new MethodInsnNode(INVOKESTATIC, HUDCaching, "shouldReturnEarly", "()Z", false));
list.add(new JumpInsnNode(IFEQ, exitLabel));
if (method.desc.endsWith("Z") || method.desc.endsWith("I")) {
list.add(new InsnNode(ICONST_0));
list.add(new InsnNode(IRETURN));
} else if (method.desc.endsWith("V")) {
list.add(new InsnNode(RETURN));
} else {
AngelicaTweaker.LOGGER.warn("HUDCaching Conditional Return - Unknown return type: " + transformedName + "#" + method.name + ":" + method.desc);
return basicClass;
}
list.add(exitLabel);
method.instructions.insert(list);
}
}
MixinClassWriter cw = new MixinClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cn.accept(cw);
final byte[] bytes = cw.toByteArray();
saveTransformedClass(bytes, transformedName);
return bytes;
}
return basicClass;
}
private File outputDir = null;
private void saveTransformedClass(final byte[] data, final String transformedName) {
if (!DUMP_CLASSES) {
return;
}
if (outputDir == null) {
outputDir = new File(Launch.minecraftHome, "ASM_HUD_CACHING");
try {
FileUtils.deleteDirectory(outputDir);
} catch (IOException ignored) {}
if (!outputDir.exists()) {
//noinspection ResultOfMethodCallIgnored
outputDir.mkdirs();
}
}
final String fileName = transformedName.replace('.', File.separatorChar);
final File classFile = new File(outputDir, fileName + ".class");
final File outDir = classFile.getParentFile();
if (!outDir.exists()) {
//noinspection ResultOfMethodCallIgnored
outDir.mkdirs();
}
if (classFile.exists()) {
//noinspection ResultOfMethodCallIgnored
classFile.delete();
}
try (final OutputStream output = Files.newOutputStream(classFile.toPath())) {
output.write(data);
} catch (IOException e) {
AngelicaTweaker.LOGGER.error("Could not save transformed class (byte[]) " + transformedName, e);
}
}
}
@@ -140,11 +140,17 @@ public class RedirectorTransformer implements IClassTransformer {
.add("glGetFloat")
.add("glGetInteger")
.add("glGetLight")
.add("glGetMaterial")
.add("glGetTexLevelParameteri")
.add("glGetTexParameterf")
.add("glGetTexParameteri")
.add("glIsEnabled")
.add("glMaterial")
.add("glMaterialf")
.add("glMateriali")
.add("glLight")
.add("glLightf")
.add("glLighti")
.add("glLightModel")
.add("glLightModelf")
.add("glLightModeli")
@@ -202,6 +208,7 @@ public class RedirectorTransformer implements IClassTransformer {
);
methodRedirects.put(GL20, RedirectMap.newMap()
.add("glBlendEquationSeparate")
.add("glUseProgram")
);
methodRedirects.put(OpenGlHelper, RedirectMap.newMap()
.add("glBlendFunc", "tryBlendFuncSeparate")
@@ -13,7 +13,10 @@ public enum CompatASMTransformers {
EXTRA_UTILITIES_ISBRH("RenderBlockColor Transformer", () -> AngelicaConfig.fixExtraUtilsSodiumCompat, Side.CLIENT,
"com.gtnewhorizons.angelica.transform.compat.ExtraUtilsTransformer"
);
),
HUD_CACHING("HUDCaching Early Return Transformer", () -> AngelicaConfig.enableHudCaching && AngelicaConfig.enableHudCachingEventTransformer, Side.CLIENT,
"com.gtnewhorizons.angelica.transform.HUDCachingTransformer")
;
private final Supplier<Boolean> applyIf;
private final Side side;
@@ -0,0 +1,111 @@
package com.gtnewhorizons.angelica.utils;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import glowredman.txloader.Asset;
import glowredman.txloader.TXLoaderCore;
public class AssetLoader {
// Texture paths from modern, starting with "minecraft/textures/"
public static final String[] injectTexs = {
"block/stone",
"block/crafting_table_front",
"block/crafting_table_side",
"block/crafting_table_top",
"block/oak_planks",
"block/acacia_log_top",
"block/acacia_log",
"block/birch_log_top",
"block/birch_log",
"block/dark_oak_log_top",
"block/dark_oak_log",
"block/jungle_log_top",
"block/jungle_log",
"block/oak_log_top",
"block/oak_log",
"block/spruce_log_top",
"block/spruce_log"
};
// Any equivalents from 7.10, starting with "minecraft/"
// This can't be automatic because some of them are inconsistent
public static final String[] oldInjectTexs = {
"blocks/stone",
"blocks/crafting_table_front",
"blocks/crafting_table_side",
"blocks/crafting_table_top",
"blocks/planks_oak",
"blocks/log_acacia_top",
"blocks/log_acacia",
"blocks/log_birch_top",
"blocks/log_birch",
"blocks/log_big_oak_top",
"blocks/log_big_oak",
"blocks/log_jungle_top",
"blocks/log_jungle",
"blocks/log_oak_top",
"blocks/log_oak",
"blocks/log_spruce_top",
"blocks/log_spruce"
};
public static final String[] testTexs = {
"block/lectern_base",
"block/lectern_front",
"block/lectern_base",
"block/lectern_sides",
"block/lectern_top",
"block/oak_planks"
};
public static void load() {
if (AngelicaConfig.injectQPRendering || AngelicaConfig.enableTestBlocks) {
addModelAssets(
"block/block",
"block/cube",
"block/cube_all",
"block/cube_column"
);
}
// For textures, we first clone old assets to their locations in modern, then copy any modern textures we don't
// have equivalents for (only the lectern rn). Models are always downloaded, 7.10 doesn't have any.
if (AngelicaConfig.injectQPRendering) {
addModelAssets(
"block/stone",
"block/crafting_table",
"block/acacia_log",
"block/birch_log",
"block/dark_oak_log",
"block/jungle_log",
"block/oak_log",
"block/spruce_log");
addTexAssets(oldInjectTexs, injectTexs, "1.7.10");
}
if (AngelicaConfig.enableTestBlocks) {
addModelAssets("block/lectern");
addTexAssets(testTexs, testTexs, "1.20.4");
}
}
private static void addModelAssets(String... resourcePaths) {
for (String path : resourcePaths) {
TXLoaderCore.getAssetBuilder("minecraft/models/" + path + ".json")
.setVersion("1.20.4")
.setSource(Asset.Source.CLIENT)
.add();
}
}
private static void addTexAssets(String[] resourcePaths, String[] destPaths, String version) {
for (int i = 0; i < resourcePaths.length; ++i) {
TXLoaderCore.getAssetBuilder("minecraft/textures/" + resourcePaths[i] + ".png")
.setOverride("minecraft/textures/blocks/" + destPaths[i] + ".png")
.setVersion(version)
.setSource(Asset.Source.CLIENT)
.add();
}
}
}
@@ -358,8 +358,7 @@ public class ColorizeBlock {
return colorizeBlock(blockAccess, colorMap, x, y, z);
}
private static boolean colorizeBlock(IBlockAccess blockAccess, IColorMap colorMap, int x, int y,
int z) {
private static boolean colorizeBlock(IBlockAccess blockAccess, IColorMap colorMap, int x, int y, int z) {
if (colorMap == null) {
return false;
} else {
@@ -30,9 +30,7 @@ final class BlockOrientation extends RenderBlockState {
{ WEST_FACE, EAST_FACE, NORTH_FACE, SOUTH_FACE, TOP_FACE, BOTTOM_FACE, 2, -2, -2, -2, 0, 0 },
{ NORTH_FACE, SOUTH_FACE, TOP_FACE, BOTTOM_FACE, WEST_FACE, EAST_FACE, 0, 0, 0, 0, -2, -2 }, };
private int i;
private int j;
private int k;
private int x, y, z;
private int metadata;
private int altMetadata;
private int metadataBits;
@@ -46,29 +44,29 @@ final class BlockOrientation extends RenderBlockState {
@Override
public void clear() {
super.clear();
i = j = k = 0;
x = y = z = 0;
renderType = -1;
metadata = 0;
blockFace = textureFace = 0;
rotateUV = 0;
offsetsComputed = false;
haveOffsets = false;
di = dj = dk = 0;
dx = dy = dz = 0;
}
@Override
public int getI() {
return i;
public int getX() {
return x;
}
@Override
public int getJ() {
return j;
public int getY() {
return y;
}
@Override
public int getK() {
return k;
public int getZ() {
return z;
}
@Override
@@ -86,11 +84,6 @@ final class BlockOrientation extends RenderBlockState {
return textureFaceOrig;
}
@Override
public String getTextureFaceName() {
throw new UnsupportedOperationException("getTextureName");
}
@Override
public int getFaceForHV() {
return blockFace;
@@ -98,7 +91,7 @@ final class BlockOrientation extends RenderBlockState {
@Override
public boolean match(BlockStateMatcher matcher) {
return isInWorld() ? matcher.match(blockAccess, i, j, k) : matcher.match(block, metadata);
return isInWorld() ? matcher.match(blockAccess, x, y, z) : matcher.match(block, metadata);
}
@Override
@@ -113,32 +106,32 @@ final class BlockOrientation extends RenderBlockState {
}
offsetsComputed = true;
haveOffsets = false;
di = dj = dk = 0;
dx = dy = dz = 0;
switch (renderType) {
case 1 -> { // renderCrossedSquares
while (j + dj > 0 && block == blockAccess.getBlock(i, j + dj - 1, k)) {
dj--;
while (y + dy > 0 && block == blockAccess.getBlock(x, y + dy - 1, z)) {
dy--;
haveOffsets = true;
}
} // renderBlockDoor
case 7, 40 -> { // renderBlockDoublePlant
if ((metadata & 0x8) != 0 && block == blockAccess.getBlock(i, j - 1, k)) {
dj--;
if ((metadata & 0x8) != 0 && block == blockAccess.getBlock(x, y - 1, z)) {
dy--;
haveOffsets = true;
}
}
case 14 -> { // renderBlockBed
metadata = blockAccess.getBlockMetadata(i, j, k);
metadata = blockAccess.getBlockMetadata(x, y, z);
switch (metadata) {
case 0, 4 -> dk = 1; // head is one block south
case 1, 5 -> di = -1; // head is one block west
case 2, 6 -> dk = -1; // head is one block north
case 3, 7 -> di = 1; // head is one block east
case 0, 4 -> dz = 1; // head is one block south
case 1, 5 -> dx = -1; // head is one block west
case 2, 6 -> dz = -1; // head is one block north
case 3, 7 -> dx = 1; // head is one block east
default -> {
return false; // head itself, no offset
}
}
haveOffsets = block == blockAccess.getBlock(i + di, j, k + dk);
haveOffsets = block == blockAccess.getBlock(x + dx, y, z + dz);
}
default -> {
}
@@ -161,9 +154,9 @@ final class BlockOrientation extends RenderBlockState {
this.block = block;
this.blockAccess = blockAccess;
inWorld = true;
this.i = x;
this.j = y;
this.k = z;
this.x = x;
this.y = y;
this.z = z;
renderType = block.getRenderType();
metadata = altMetadata = blockAccess.getBlockMetadata(x, y, z);
offsetsComputed = false;
@@ -181,12 +174,12 @@ final class BlockOrientation extends RenderBlockState {
this.block = block;
blockAccess = null;
inWorld = false;
i = j = k = 0;
x = y = z = 0;
renderType = block.getRenderType();
blockFace = textureFace = textureFaceOrig = face;
this.metadata = metadata;
metadataBits = 1 << metadata;
di = dj = dk = 0;
dx = dy = dz = 0;
rotateUV = 0;
}
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more