Compare commits

..
Author SHA1 Message Date
Darren Eberly 29072ee3f8 Ambient Occlusion Fixes (#575)
* Disable broken optimizations for Sodium AO

* Use Sodium AO by default for standard block rendering
2024-07-30 22:31:27 -04:00
Rad ff8315270b Update pl_PL.lang (#564)
* Update pl_PL.lang

* Update pl_PL.lang (NotFine)
2024-07-30 16:37:55 +00:00
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
84 changed files with 2647 additions and 925 deletions

No files matched your search

+5
View File
@@ -31,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
+4 -4
View File
@@ -30,14 +30,14 @@
* 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.3.0+
* Neodymium - Untested, but unlikely to be compatible. (Chunk Meshing is definitely incompatible, other features might work depending on config)
* Neodymium - Untested, but unlikely to be compatible. (Chunk Meshing is definitely incompatible, other features might work depending on config)
# Credits
* ShadersMod
+5
View File
@@ -56,6 +56,9 @@ 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.3.2:dev")
@@ -78,6 +81,8 @@ dependencies {
compileOnly("com.github.GTNewHorizons:TinkersConstruct:1.12.0-GTNH:dev")
compileOnly("com.github.GTNewHorizons:Natura:2.6.1:dev")
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 }
+1 -1
View File
@@ -16,5 +16,5 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.23'
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.24'
}
@@ -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;
@@ -26,6 +26,8 @@ public class ModStatus {
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");
@@ -38,6 +40,8 @@ public class ModStatus {
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")
@@ -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];
@@ -72,6 +72,10 @@ public class AngelicaConfig {
@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)
@@ -77,7 +77,7 @@ 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
@@ -148,13 +148,11 @@ 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
@@ -178,6 +176,8 @@ public class Feature {
// 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(
@@ -11,7 +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;
@@ -94,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);
@@ -126,6 +124,14 @@ public class GLStateManager {
@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);
@@ -280,6 +286,7 @@ public class GLStateManager {
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();
@@ -303,6 +310,7 @@ public class GLStateManager {
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();
@@ -329,6 +337,7 @@ public class GLStateManager {
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();
@@ -356,6 +365,7 @@ public class GLStateManager {
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();
@@ -402,6 +412,8 @@ 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);
@@ -426,6 +438,32 @@ 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) {
if (shouldBypassCache()) {
GL11.glGetLight(light, pname, params);
@@ -444,8 +482,8 @@ public class GLStateManager {
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);
}
GL11.glGetLight(light, pname, params);
}
public static void glGetFloat(int pname, FloatBuffer params) {
@@ -964,6 +1002,42 @@ public class GLStateManager {
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();
}
@@ -1215,10 +1289,6 @@ public class GLStateManager {
}
}
public static Matrix4f getModelviewMatrix() {
return modelViewMatrix;
}
public static void glLoadIdentity() {
GL11.glLoadIdentity();
getMatrixStack().identity();
@@ -1489,6 +1559,115 @@ public class GLStateManager {
};
}
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) {
@@ -1548,20 +1727,44 @@ public class GLStateManager {
}
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) {
@@ -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,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);
}
}
@@ -66,10 +66,10 @@ public class LightState implements ISettableState<LightState> {
this.quadraticAttenuation = quadraticAttenuation;
this.position = position;
this.position.mul(GLStateManager.getModelviewMatrix());
this.position.mul(GLStateManager.getModelViewMatrix());
this.spotDirection = spotDirection;
GLStateManager.getModelviewMatrix().get3x3(matrix3f);
GLStateManager.getModelViewMatrix().get3x3(matrix3f);
this.spotDirection.mul(matrix3f);
}
@@ -129,14 +129,14 @@ public class LightState implements ISettableState<LightState> {
// 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());
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());
this.position.mul(GLStateManager.getModelViewMatrix());
GL11.glLight(this.light, GL11.GL_POSITION, newBuffer);
}
@@ -144,7 +144,7 @@ public class LightState implements ISettableState<LightState> {
// 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);
GLStateManager.getModelViewMatrix().get3x3(matrix3f);
this.spotDirection.set(newBuffer);
this.spotDirection.mul(matrix3f);
GL11.glLight(this.light, GL11.GL_SPOT_DIRECTION, newBuffer);
@@ -152,7 +152,7 @@ public class LightState implements ISettableState<LightState> {
public void setSpotDirection(IntBuffer newBuffer) {
vector3i.set(newBuffer);
GLStateManager.getModelviewMatrix().get3x3(matrix3f);
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);
@@ -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); }
}
@@ -6,6 +6,7 @@ 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;
@@ -21,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;
@@ -33,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;
@@ -61,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();
@@ -82,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()) {
@@ -120,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);
@@ -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;
}
}
}
@@ -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);
}
@@ -533,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")),
;
@@ -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);
}
}
@@ -1,13 +1,7 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@@ -15,10 +9,6 @@ import org.spongepowered.asm.mixin.injection.Redirect;
public abstract class MixinRenderBlocks {
@Redirect(method = "renderStandardBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;isAmbientOcclusionEnabled()Z"))
private boolean checkAOEnabled() {
if(AngelicaConfig.enableIris && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()) {
return false; // force Sodium pipeline
}
return Minecraft.isAmbientOcclusionEnabled();
return false;
}
}
@@ -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);
}
@@ -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;
@@ -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,10 +140,14 @@ 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")
@@ -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();
}
}
}
@@ -3,6 +3,7 @@ package me.jellysquid.mods.sodium.client.model.light.smooth;
import com.google.common.math.DoubleMath;
import com.gtnewhorizons.angelica.compat.mojang.BlockPosImpl;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.model.light.LightPipeline;
import me.jellysquid.mods.sodium.client.model.light.data.LightDataAccess;
import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData;
@@ -40,6 +41,8 @@ import net.minecraftforge.common.util.ForgeDirection;
*/
public class SmoothLightPipeline implements LightPipeline {
public static final double TOLERANCE = 1.0E-5F;
public static final boolean useSmoothLightingOptimizations = false;
/**
* The cache which light data will be accessed from.
*/
@@ -80,14 +83,18 @@ public class SmoothLightPipeline implements LightPipeline {
// map the corner values onto this quad's vertices. This covers most situations during rendering and provides
// a modest speed-up.
// To match vanilla behavior, also treat the face as aligned if it is parallel and the block state is a full cube
if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && LightDataAccess.unpackFC(this.lightCache.get(pos)))) {
if ((flags & ModelQuadFlags.IS_PARTIAL) == 0) {
this.applyAlignedFullFace(neighborInfo, pos, face, out);
if (useSmoothLightingOptimizations) {
if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && LightDataAccess.unpackFC(this.lightCache.get(pos)))) {
if ((flags & ModelQuadFlags.IS_PARTIAL) == 0) {
this.applyAlignedFullFace(neighborInfo, pos, face, out);
} else {
this.applyAlignedPartialFace(neighborInfo, quad, pos, face, out);
}
} else if ((flags & ModelQuadFlags.IS_PARALLEL) != 0) {
this.applyParallelFace(neighborInfo, quad, pos, face, out);
} else {
this.applyAlignedPartialFace(neighborInfo, quad, pos, face, out);
this.applyNonParallelFace(neighborInfo, quad, pos, face, out);
}
} else if ((flags & ModelQuadFlags.IS_PARALLEL) != 0) {
this.applyParallelFace(neighborInfo, quad, pos, face, out);
} else {
this.applyNonParallelFace(neighborInfo, quad, pos, face, out);
}
@@ -77,6 +77,12 @@ public class ModelQuad implements ModelQuadViewMutable {
this.colorIdx = index;
}
/**
* Doesn't do anything useful, but I'm not sure if it has to.
*/
@Override
public void setCullFace(ForgeDirection f) {}
@Override
public int getLight(int idx) {
return this.data[vertexOffset(idx) + LIGHT_INDEX];
@@ -93,13 +99,21 @@ public class ModelQuad implements ModelQuadViewMutable {
}
/**
* Doesn't do anything useful, but I'm not sure if it has to anyways.
* Doesn't do anything useful, but I'm not sure if it has to.
*/
@Override
public ForgeDirection getLightFace() {
return ForgeDirection.UP;
}
/**
* Doesn't do anything useful, but I'm not sure if it has to.
*/
@Override
public ForgeDirection getCullFace() {
return ForgeDirection.UNKNOWN;
}
@Override
public float getX(int idx) {
return Float.intBitsToFloat(this.data[vertexOffset(idx) + POSITION_INDEX]);
@@ -1,5 +1,6 @@
package me.jellysquid.mods.sodium.client.model.quad;
import com.gtnewhorizons.angelica.models.NdQuadBuilder;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFlags;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraftforge.common.util.ForgeDirection;
@@ -60,6 +61,14 @@ public interface ModelQuadView {
*/
int getColorIndex();
/**
* 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)
*/
ForgeDirection getCullFace();
/**
* This is the face used for vanilla lighting calculations and will be the block face
* to which the quad is most closely aligned. Always the same as cull face for quads
@@ -2,6 +2,7 @@ package me.jellysquid.mods.sodium.client.model.quad;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFlags;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Provides a mutable view to a model quad.
@@ -27,6 +28,16 @@ public interface ModelQuadViewMutable extends ModelQuadView {
*/
void setColor(int idx, int color);
/**
* Convenience: set vertex color for all vertices at once.
*/
default void setColors(int abgr) {
this.setColor(0, abgr);
this.setColor(1, abgr);
this.setColor(2, abgr);
this.setColor(3, abgr);
}
/**
* Sets the texture x-coordinate of the vertex at index {@param idx} to the value {@param u}
*/
@@ -61,4 +72,18 @@ public interface ModelQuadViewMutable extends ModelQuadView {
* Sets the color index used by this quad
*/
void setColorIndex(int index);
/**
* 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>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()}.
*/
void setCullFace(ForgeDirection dir);
}
@@ -10,7 +10,6 @@ import net.minecraftforge.common.util.ForgeDirection;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
import java.util.Locale;
/**
@@ -19,8 +18,8 @@ import java.util.Locale;
public class Quad implements QuadView {
// Adapted from Neodymium
public static final int INTS_PER_VERTEX = 8;
public static final int QUAD_STRIDE = INTS_PER_VERTEX * 4;
public static final int VERTEX_STRIDE = 8;
public static final int QUAD_STRIDE = VERTEX_STRIDE * 4;
public static final int X_INDEX = 0;
public static final int Y_INDEX = 1;
public static final int Z_INDEX = 2;
@@ -33,10 +32,10 @@ public class Quad implements QuadView {
private final static int DEFAULT_LIGHTMAP = 15 << 20 | 15 << 4;
private final static int DEFAULT_COLOR = 0xFFFFFFFF;
private final int[] data = new int[QUAD_STRIDE];
protected final int[] data = new int[QUAD_STRIDE];
@Getter
private boolean deleted;
private boolean deleted = false;
private final Vector3f vectorA = new Vector3f(), vectorB = new Vector3f(), vectorC = new Vector3f();
@@ -54,44 +53,49 @@ public class Quad implements QuadView {
return this.face != ForgeDirection.UNKNOWN ? this.face : ForgeDirection.UP;
}
@Override
public ForgeDirection getCullFace() {
return this.face;
}
@Override
public float getX(int idx) {
return Float.intBitsToFloat(this.data[idx * INTS_PER_VERTEX + X_INDEX]);
return Float.intBitsToFloat(this.data[idx * VERTEX_STRIDE + X_INDEX]);
}
@Override
public float getY(int idx) {
return Float.intBitsToFloat(this.data[idx * INTS_PER_VERTEX + Y_INDEX]);
return Float.intBitsToFloat(this.data[idx * VERTEX_STRIDE + Y_INDEX]);
}
@Override
public float getZ(int idx) {
return Float.intBitsToFloat(this.data[idx * INTS_PER_VERTEX + Z_INDEX]);
return Float.intBitsToFloat(this.data[idx * VERTEX_STRIDE + Z_INDEX]);
}
@Override
public float getTexU(int idx) {
return Float.intBitsToFloat(this.data[idx * INTS_PER_VERTEX + U_INDEX]);
return Float.intBitsToFloat(this.data[idx * VERTEX_STRIDE + U_INDEX]);
}
@Override
public float getTexV(int idx) {
return Float.intBitsToFloat(this.data[idx * INTS_PER_VERTEX + V_INDEX]);
return Float.intBitsToFloat(this.data[idx * VERTEX_STRIDE + V_INDEX]);
}
@Override
public int getColor(int idx) {
return this.data[idx * INTS_PER_VERTEX + COLOR_INDEX];
return this.data[idx * VERTEX_STRIDE + COLOR_INDEX];
}
@Override
public int getLight(int idx) {
return this.data[idx * INTS_PER_VERTEX + LIGHTMAP_INDEX];
return this.data[idx * VERTEX_STRIDE + LIGHTMAP_INDEX];
}
@Override
public int getNormal(int idx) {
return this.data[idx * INTS_PER_VERTEX + NORMAL_INDEX];
return this.data[idx * VERTEX_STRIDE + NORMAL_INDEX];
}
@Override
@@ -109,44 +113,50 @@ public class Quad implements QuadView {
return this.sprite;
}
@Override
public void setCullFace(ForgeDirection face) {
this.face = face;
}
@Override
public void setX(int idx, float x) {
this.data[idx * INTS_PER_VERTEX + X_INDEX] = Float.floatToRawIntBits(x);
this.data[idx * VERTEX_STRIDE + X_INDEX] = Float.floatToRawIntBits(x);
}
@Override
public void setY(int idx, float y) {
this.data[idx * INTS_PER_VERTEX + Y_INDEX] = Float.floatToRawIntBits(y);
this.data[idx * VERTEX_STRIDE + Y_INDEX] = Float.floatToRawIntBits(y);
}
@Override
public void setZ(int idx, float z) {
this.data[idx * INTS_PER_VERTEX + Z_INDEX] = Float.floatToRawIntBits(z);
this.data[idx * VERTEX_STRIDE + Z_INDEX] = Float.floatToRawIntBits(z);
}
@Override
public void setTexU(int idx, float u) {
this.data[idx * INTS_PER_VERTEX + U_INDEX] = Float.floatToRawIntBits(u);
this.data[idx * VERTEX_STRIDE + U_INDEX] = Float.floatToRawIntBits(u);
}
@Override
public void setTexV(int idx, float v) {
this.data[idx * INTS_PER_VERTEX + V_INDEX] = Float.floatToRawIntBits(v);
this.data[idx * VERTEX_STRIDE + V_INDEX] = Float.floatToRawIntBits(v);
}
@Override
public void setColor(int idx, int c) {
this.data[idx * INTS_PER_VERTEX + COLOR_INDEX] = c;
this.data[idx * VERTEX_STRIDE + COLOR_INDEX] = c;
}
@Override
public void setLight(int idx, int l) {
this.data[idx * INTS_PER_VERTEX + LIGHTMAP_INDEX] = l;
this.data[idx * VERTEX_STRIDE + LIGHTMAP_INDEX] = l;
}
@Override
public void setNormal(int idx, int n) {
this.data[idx * INTS_PER_VERTEX + NORMAL_INDEX] = n;
this.data[idx * VERTEX_STRIDE + NORMAL_INDEX] = n;
}
@Override
@@ -165,7 +175,7 @@ public class Quad implements QuadView {
}
@Override
public int[] getRawVertexes() {
public int[] getRawData() {
return this.data;
}
@@ -173,14 +183,14 @@ public class Quad implements QuadView {
* Convenience: access x, y, z by index 0-2.
*/
private float posByIndex(int vertexIndex, int coordinateIndex) {
return Float.intBitsToFloat(this.data[vertexIndex * INTS_PER_VERTEX + coordinateIndex]);
return Float.intBitsToFloat(this.data[vertexIndex * VERTEX_STRIDE + coordinateIndex]);
}
/**
* Convenience: access x, y, z by index 0-2.
*/
private void setPosByIndex(int vertexIndex, int coordinateIndex, float val) {
this.data[vertexIndex * INTS_PER_VERTEX + coordinateIndex] = Float.floatToRawIntBits(val);
this.data[vertexIndex * VERTEX_STRIDE + coordinateIndex] = Float.floatToRawIntBits(val);
}
/**
@@ -193,13 +203,6 @@ public class Quad implements QuadView {
this.setPosByIndex(3, idx, this.posByIndex(3, idx) + offset);
}
private void clearColors() {
this.setColor(0, DEFAULT_COLOR);
this.setColor(1, DEFAULT_COLOR);
this.setColor(2, DEFAULT_COLOR);
this.setColor(3, DEFAULT_COLOR);
}
private void clearNormals() {
this.setNormal(0, 0);
this.setNormal(1, 0);
@@ -237,10 +240,23 @@ public class Quad implements QuadView {
this.vectorA.cross(this.vectorB, this.vectorC);
}
@Override
public void copyFrom(QuadView quad) {
protected void quadrangulate() {
this.setX(3, this.getX(2));
this.setY(3, this.getY(2));
this.setZ(3, this.getZ(2));
System.arraycopy(quad.getRawVertexes(), 0, this.data, 0, QUAD_STRIDE);
this.setTexU(3, this.getTexU(2));
this.setTexV(3, this.getTexV(2));
this.setLight(3, this.getLight(2));
this.setColor(3, this.getColor(2));
this.setNormal(3, this.getNormal(2));
}
@Override
public QuadView copyFrom(QuadView quad) {
System.arraycopy(quad.getRawData(), 0, this.data, 0, QUAD_STRIDE);
this.deleted = quad.isDeleted();
this.shade = quad.isShade();
@@ -248,21 +264,8 @@ public class Quad implements QuadView {
this.colorIndex = quad.getColorIndex();
this.cachedFlags = quad.getFlags();
this.sprite = quad.rubidium$getSprite();
}
/**
* Unlike setState, setRaw assumes your quad is valid and does not compute normals, clear color/normal/lightmap
* values, or quadrangulate. Basically the same as copyFrom but without an input quad.
*/
public void setRaw(int[] data, boolean shade, @Nullable ForgeDirection face, int colorIndex, int flags) {
System.arraycopy(data, 0, this.data, 0, QUAD_STRIDE);
this.deleted = false;
this.shade = shade;
this.face = face;
this.colorIndex = colorIndex;
this.cachedFlags = flags;
return this;
}
private void read(int[] rawBuffer, int offset, float offsetX, float offsetY, float offsetZ, int drawMode, BlockRenderer.Flags flags) {
@@ -272,27 +275,14 @@ public class Quad implements QuadView {
if (offsetY != 0) this.offsetPos(1, offsetY);
if (offsetZ != 0) this.offsetPos(2, offsetZ);
if (!flags.hasColor) this.clearColors();
if (!flags.hasColor) this.setColors(DEFAULT_COLOR);
if (!flags.hasNormals) this.clearNormals();
if (!flags.hasBrightness) this.clearLight();
// sus
this.shade = flags.hasBrightness;
if (drawMode == GL11.GL_TRIANGLES) {
// Quadrangulate!
this.setX(3, this.getX(2));
this.setY(3, this.getY(2));
this.setZ(3, this.getZ(2));
this.setTexU(3, this.getTexU(2));
this.setTexV(3, this.getTexV(2));
this.setLight(3, this.getLight(2));
this.setColor(3, this.getColor(2));
this.setNormal(3, this.getNormal(2));
}
if (drawMode == GL11.GL_TRIANGLES) this.quadrangulate();
}
@Override
@@ -32,7 +32,6 @@ import me.jellysquid.mods.sodium.client.render.chunk.lists.ChunkRenderListIterat
import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass;
import me.jellysquid.mods.sodium.client.util.math.FrustumExtended;
import me.jellysquid.mods.sodium.client.world.ChunkStatusListener;
import me.jellysquid.mods.sodium.common.util.DirectionUtil;
import me.jellysquid.mods.sodium.common.util.IdTable;
import me.jellysquid.mods.sodium.common.util.collections.FutureDequeDrain;
import net.coderbot.iris.shadows.ShadowRenderingState;
@@ -459,7 +458,7 @@ public class ChunkRenderManager<T extends ChunkGraphicsState> implements ChunkSt
}
private void connectNeighborColumns(ChunkRenderColumn<T> column) {
for (ForgeDirection dir : DirectionUtil.ALL_DIRECTIONS) {
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
ChunkRenderColumn<T> adj = this.getAdjacentColumn(column, dir);
if (adj != null) {
@@ -471,7 +470,7 @@ public class ChunkRenderManager<T extends ChunkGraphicsState> implements ChunkSt
}
private void disconnectNeighborColumns(ChunkRenderColumn<T> column) {
for (ForgeDirection dir : DirectionUtil.ALL_DIRECTIONS) {
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
ChunkRenderColumn<T> adj = column.getAdjacentColumn(dir);
if (adj != null) {
@@ -9,11 +9,10 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import me.jellysquid.mods.sodium.client.render.chunk.cull.ChunkCuller;
import me.jellysquid.mods.sodium.client.util.math.FrustumExtended;
import me.jellysquid.mods.sodium.common.util.DirectionUtil;
import net.minecraft.block.Block;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraft.util.MathHelper;
import java.util.ArrayList;
import java.util.Comparator;
@@ -47,7 +46,7 @@ public class ChunkGraphCuller implements ChunkCuller {
ChunkGraphNode node = queue.getNode(i);
short cullData = node.computeQueuePop();
for (ForgeDirection dir : DirectionUtil.ALL_DIRECTIONS) {
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
if (useOcclusionCulling && (cullData & (1 << dir.ordinal())) == 0) {
continue;
}
@@ -148,7 +147,7 @@ public class ChunkGraphCuller implements ChunkCuller {
}
private void connectNeighborNodes(ChunkGraphNode node) {
for (ForgeDirection dir : DirectionUtil.ALL_DIRECTIONS) {
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
ChunkGraphNode adj = this.findAdjacentNode(node, dir);
if (adj != null) {
@@ -160,7 +159,7 @@ public class ChunkGraphCuller implements ChunkCuller {
}
private void disconnectNeighborNodes(ChunkGraphNode node) {
for (ForgeDirection dir : DirectionUtil.ALL_DIRECTIONS) {
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
ChunkGraphNode adj = node.getConnectedNode(dir);
if (adj != null) {
@@ -4,14 +4,13 @@ import com.gtnewhorizons.angelica.compat.mojang.BlockPosImpl;
import com.gtnewhorizons.angelica.compat.mojang.ChunkOcclusionData;
import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData;
import me.jellysquid.mods.sodium.client.util.math.FrustumExtended;
import me.jellysquid.mods.sodium.common.util.DirectionUtil;
import net.minecraftforge.common.util.ForgeDirection;
public class ChunkGraphNode {
private static final long DEFAULT_VISIBILITY_DATA = calculateVisibilityData(ChunkRenderData.EMPTY.getOcclusionData());
private static final float FRUSTUM_EPSILON = 1.0f /* block model margin */ + 0.125f /* epsilon */;
private final ChunkGraphNode[] nodes = new ChunkGraphNode[DirectionUtil.ALL_DIRECTIONS.length];
private final ChunkGraphNode[] nodes = new ChunkGraphNode[ForgeDirection.VALID_DIRECTIONS.length];
private final int id;
private final int chunkX, chunkY, chunkZ;
@@ -65,8 +64,8 @@ public class ChunkGraphNode {
private static long calculateVisibilityData(ChunkOcclusionData occlusionData) {
long visibilityData = 0;
for (ForgeDirection from : DirectionUtil.ALL_DIRECTIONS) {
for (ForgeDirection to : DirectionUtil.ALL_DIRECTIONS) {
for (ForgeDirection from : ForgeDirection.VALID_DIRECTIONS) {
for (ForgeDirection to : ForgeDirection.VALID_DIRECTIONS) {
if (occlusionData == null || occlusionData.isVisibleThrough(from, to)) {
visibilityData |= (1L << ((from.ordinal() << 3) + to.ordinal()));
}
@@ -4,14 +4,16 @@ import com.gtnewhorizons.angelica.api.QuadProvider;
import com.gtnewhorizons.angelica.api.QuadView;
import com.gtnewhorizons.angelica.client.renderer.CapturingTessellator;
import com.gtnewhorizons.angelica.compat.mojang.BlockPosImpl;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.TessellatorManager;
import com.gtnewhorizons.angelica.mixins.interfaces.ModeledBlock;
import com.gtnewhorizons.angelica.utils.ObjectPooler;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.model.light.LightMode;
import me.jellysquid.mods.sodium.client.model.light.LightPipeline;
import me.jellysquid.mods.sodium.client.model.light.LightPipelineProvider;
import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData;
import me.jellysquid.mods.sodium.client.model.quad.Quad;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadOrientation;
import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuffers;
@@ -21,6 +23,7 @@ import me.jellysquid.mods.sodium.client.render.occlusion.BlockOcclusionCache;
import me.jellysquid.mods.sodium.client.util.ModelQuadUtil;
import me.jellysquid.mods.sodium.client.util.color.ColorABGR;
import me.jellysquid.mods.sodium.client.util.rand.XoRoShiRoRandom;
import me.jellysquid.mods.sodium.common.util.DirectionUtil;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
@@ -62,24 +65,25 @@ public class BlockRenderer {
this.useSeparateAo = AngelicaConfig.enableIris && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo();
boolean rendered = false;
final QuadProvider model = ((ModeledBlock) block).getModel();
if (block instanceof QuadProvider qBlock) {
if (model != null) {
final int color = qBlock.getColor(world, pos, block, meta, random);
final int color = model.getColor(world, pos, block, meta, random);
for (ForgeDirection dir : ForgeDirection.values()) {
for (ForgeDirection dir : DirectionUtil.ALL_DIRECTIONS) {
this.random.setSeed(seed);
List<QuadView> quads;
if (!cull || this.occlusionCache.shouldDrawSide(block, meta, world, pos, dir)) {
quads = qBlock.getQuads(world, pos, block, meta, dir, random, color, this.quadPool::getInstance);
quads = model.getQuads(world, pos, block, meta, dir, random, color, this.quadPool::getInstance);
if (quads.isEmpty()) continue;
this.renderQuadList(pos, lighter, buffers, quads, ModelQuadFacing.fromDirection(dir), true);
rendered = true;
if (qBlock.isDynamic())
if (model.isDynamic())
for (QuadView q : quads) this.quadPool.releaseInstance(q);
}
}
@@ -98,7 +102,7 @@ public class BlockRenderer {
for (ModelQuadFacing facing : ModelQuadFacing.VALUES) {
this.random.setSeed(seed);
this.renderQuadList(pos, lighter, buffers, quads, facing, false);
this.renderQuadList(pos, lighter, buffers, quads, facing, block.getRenderType() == 0);
}
if (!quads.isEmpty()) rendered = true;
@@ -45,6 +45,7 @@ public class FluidRenderer {
private final QuadLightData quadLightData = new QuadLightData();
private boolean useSeparateAo;
private final int[] quadColors = new int[4];
private final int[] biomeColors = new int[4];
private final TextureAtlasSprite missingTex = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:missing");
public FluidRenderer(LightPipelineProvider lpp) {
@@ -359,16 +360,13 @@ public class FluidRenderer {
QuadLightData light = this.quadLightData;
lighter.calculate(quad, pos, light, null, dir, false);
int[] biomeColors = null;
if (colorized) {
biomeColors = new int[4];
int color = slice.getBlock(pos.x,pos.y,pos.z).colorMultiplier(slice,pos.x,pos.y,pos.z);
Arrays.fill(biomeColors,ColorARGB.toABGR(color));
Arrays.fill(this.biomeColors, ColorARGB.toABGR(color));
}
for (int i = 0; i < 4; i++) {
int color = biomeColors != null ? biomeColors[i] : 0xFFFFFFFF;
int color = colorized ? biomeColors[i] : 0xFFFFFFFF;
final float ao = light.br[i] * brightness;
if (useSeparateAo) {
color &= 0x00FFFFFF;
@@ -1,6 +1,5 @@
package me.jellysquid.mods.sodium.client.util;
import me.jellysquid.mods.sodium.common.util.DirectionUtil;
import net.minecraftforge.common.util.ForgeDirection;
/**
@@ -30,11 +29,11 @@ public class ModelQuadUtil {
public static final int VERTEX_SIZE_BYTES = VERTEX_SIZE * 4;
// Cached array of normals for every facing to avoid expensive computation
static final int[] NORMALS = new int[DirectionUtil.ALL_DIRECTIONS.length];
static final int[] NORMALS = new int[ForgeDirection.VALID_DIRECTIONS.length];
static {
for (int i = 0; i < NORMALS.length; i++) {
final ForgeDirection dir = DirectionUtil.ALL_DIRECTIONS[i];
final ForgeDirection dir = ForgeDirection.VALID_DIRECTIONS[i];
NORMALS[i] = Norm3b.pack(dir.offsetX, dir.offsetY, dir.offsetZ);
}
}
@@ -1,6 +1,8 @@
package me.jellysquid.mods.sodium.common.util;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing;
import net.minecraftforge.common.util.ForgeDirection;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector3i;
@@ -9,9 +11,8 @@ import org.joml.Vector3i;
* be cloned every time.
*/
public class DirectionUtil {
public static final ForgeDirection[] ALL_DIRECTIONS = ForgeDirection.VALID_DIRECTIONS;
public static final ForgeDirection[] ALL_DIRECTIONS = ForgeDirection.values();
public static final int DIRECTION_COUNT = ALL_DIRECTIONS.length;
// Provides the same order as enumerating ForgeDirection and checking the axis of each value
public static final ForgeDirection[] HORIZONTAL_DIRECTIONS = new ForgeDirection[] { ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.WEST, ForgeDirection.EAST };
@@ -33,4 +34,11 @@ public class DirectionUtil {
// UNKNOWN
new Vector3i(0, 0, 0)
};
public static ForgeDirection rotateDir(ForgeDirection in, Matrix4f rotMat) {
final Vector3f v = new Vector3f(in.offsetX, in.offsetY, in.offsetZ);
v.mulPosition(rotMat);
return ModelQuadFacing.toDirection(ModelQuadFacing.fromVector(v));
}
}
@@ -1,3 +1,5 @@
public net.minecraft.block.Block func_149641_N()Ljava/lang/String; # getTextureName
public net.minecraft.client.renderer.EntityRenderer func_78476_b(FI)V # void renderHand(float, int)
public net.minecraft.client.renderer.RenderGlobal field_72765_l # worldRenderers
@@ -0,0 +1,134 @@
options.button.shader=Shadery...
options.chunks=%s chunków
options.entityShadows=Cienie bytów
sodium.option_impact.low=Niski
sodium.option_impact.medium=Średni
sodium.option_impact.high=Wysoki
sodium.option_impact.extreme=Ekstremalny
sodium.option_impact.varies=Różny
sodium.options.pages.quality=Jakość
sodium.options.pages.performance=Wydajność
sodium.options.pages.advanced=Zaawansowane
sodium.options.view_distance.tooltip=Zasięg renderowania kontroluje, jak daleko otoczenie będzie renderowane. Krótszy dystans oznacza, że mniej otoczenia będzie renderowane, zwiększając klatki na sekundę.
sodium.options.simulation_distance.tooltip=Zasięg symulacji kontroluje jak daleko otoczenie i byty będą wczytywane i symulowane. Krótsze dystansy mogą zmniejszyć obciążenie wewnętrznego serwera i poprawić klatki na sekundę.
sodium.options.brightness.tooltip=Kontroluje jasność (gammę) gry.
sodium.options.clouds.name=Chmury
sodium.options.clouds.tooltip=Kontroluje, czy chmury będą lub nie będą widoczne.
sodium.options.gui_scale.tooltip=Ustawia maksymalne skalowanie użyte dla interfejsu użytkownika. Jeśli opcja "auto" jest użyta, wtedy największa skala interfejsu zawsze będzie użyta.
sodium.options.fullscreen.tooltip=Jeśli włączone, gra będzie wyświetlana w trybie pełnoekranowym (Jeśli opcja jest wspierana).
sodium.options.v_sync.tooltip=Jeśli włączone, klatki na sekundę będą synchronizowane z częstotliwością odświeżania monitora, co zapewni płynniejsze wrażenia kosztem gorszego opóźnienia wejścia. To ustawienie może zmniejszyć wydajność, jeśli twój sprzęt jest zbyt słaby.
sodium.options.fps_limit.tooltip=Ogranicza maksymalną liczbę klatek na sekundę. Ta opcja może pomóc zmniejszyć zużycie baterii i obciążenie systemu, gdy robisz wiele rzeczy naraz. Jeśli VSync jest włączony, limit klatek będzie zignorowany, jeśli jest mniejszy od częstotliwości odświeżania twojego monitora.
sodium.options.view_bobbing.tooltip=Jeśli włączone, pole widzenia gracza będzie się bujać i podskakiwać. Gracze, którzy posiadają chorobę lokomocyjną lub tym podobne mogą mieć korzyści z wyłączenia tej opcji.
sodium.options.attack_indicator.tooltip=Kontroluje, gdzie ikona ataku jest wyświetlana na ekranie.
sodium.options.autosave_indicator.tooltip=Jeśli włączone, ikona zapisywania będzie pokazana, gdy gra zapisuje świat na dysku.
sodium.options.graphics_quality.tooltip=Domyślna jakość grafiki kontroluje kilka starych opcji i jest potrzebna do kompatybilności modów. Jeśli opcje poniżej są ustawione na "Domyślna", wtedy użyją one tej opcji.
sodium.options.clouds_quality.tooltip=Kontroluje jakość renderowania chmur na niebie.
sodium.options.weather_quality.tooltip=Kontroluje jakość efektów deszczu i śniegu.
sodium.options.leaves_quality.name=Jakość liści
sodium.options.leaves_quality.tooltip=Kontroluje jakość liści.
sodium.options.grass_quality.name=Jakość trawy
sodium.options.grass_quality.tooltip=Kontroluje jakość stron bloków trawy.
sodium.options.particle_quality.name=Jakość cząstek
sodium.options.particle_quality.tooltip=Kontroluje maksymalną ilość cząstek, które mogą być widoczne na ekranie w tym samym czasie.
sodium.options.smooth_lighting.tooltip=Kontroluje, czy bloki będą gładko oświetlone i cieniowane. Ta opcja może troszkę podwyższyć ilość czasu, jaką zajmuje załadowanie lub zaktualizowanie chunku, lecz nie ma wpływu na klatki na sekundę.This slightly increases the amount of time needed to re-build a chunk, but doesn't affect frame rates.
sodium.options.biome_blend.value=%s blok(ów)
sodium.options.biome_blend.tooltip=Kontroluje zasięg, w którym biomy będą próbkowane dla kolorowania bloków. Wyższe wartoście znacznie zwiększy czas ładowania chunków, w zamian za znikome poprawki w jakości.
sodium.options.entity_distance.tooltip=Kontroluje, jak daleko od gracza będą renderowane byty. Wyższe wartości zwiększają zasięg renderowania, kosztem klatek na sekundę.
sodium.options.entity_shadows.tooltip=Jeśli włączone, podstawowe cienie będą renderowane pod mobami i innymi bytami.
sodium.options.vignette.name=Winieta
sodium.options.vignette.tooltip=Jeśli włączone, efekt winiety będzie renderowany na widoku gracza. To raczej nie wpłynie na klatki na sekundę, chyba że jesteś ograniczany przez szybkość wypełniania.
sodium.options.mipmap_levels.tooltip=Kontroluje ilość mipmap, które będą użyte do tekstur modeli bloków. Wyższe wartości skutkują lepszym renderowaniem bloków w oddali, lecz mogą spowodować pogorszenie wydajności przy dużej ilości animowanych tekstur.
sodium.options.use_chunk_multidraw.name=Chunk Multi-Draw
sodium.options.use_chunk_multidraw.tooltip=Multi-draw pozwala na renderowanie wielu chunków przy mniejszej liczbie wywołań rysowania, znacznie zmniejszając obciążenie CPU przy renderowaniu świata, jednocześnie potencjalnie pozwalając na bardziej efektywne użycie GPU. Ta optymalizacja może powodować problemy z niektórymi sterownikami graficznymi, więc powinieneś spróbować ją wyłączyć, jeśli napotykasz błędy.
sodium.options.use_vertex_objects.name=Obiekty układu wierzchołków
sodium.options.use_vertex_objects.tooltip=Pomaga poprawić wydajność poprzez przenoszenie informacji o tym, jak dane wierzchołków powinny być renderowane do sterownika, pozwalając na lepszą optymalizację dla wielokrotnego renderowania tych samych obiektów. Generalnie, nie ma potrzebyy wyłączania tego, chyba że używasz niekompatybilnych modów.
sodium.options.use_block_face_culling.name=Chowanie ścian bloków
sodium.options.use_block_face_culling.tooltip=Jeśli włączone, tylko ściany bloków, które odwrócone są w stronę kamery, będą renderowane. To może wyeliminować dużą liczbę ścian bloków wcześnie w procesie renderowania, oszczędzając przepustowość pamięci i czas na GPU. Niektóre paczki zasobów mogą mieć problem z tą opcją, możesz wtedy spróbować ją wyłączyć jeśli widzisz dziury w blokach.
sodium.options.use_compact_vertex_format.name=Kompaktowy format wierzchołków
sodium.options.use_compact_vertex_format.tooltip=Jeśli włączone, bardziej kompaktowy format wierzchołków będzie użyty do renderowania chunków. To może znacznie zmniejszyć zużycie pamięci grafiki i wymagań przepustowości, szczególnie dla zintegrowanych układów graficznych, ale może powodować z-fighting z niektórymi paczkami zasobów przez to jak zmniejsza precyzję pozycji i atrybutuów współrzędnych tekstur.
sodium.options.use_fog_occlusion.name=Okluzja mgły
sodium.options.use_fog_occlusion.tooltip=Jeśli włączone, chunki, które uważane są za w pełni ukryte przez mgłę, nie będą renderowane, zwiększając wydajność. Efekt poprawy może być większy, gdy efekt mgły jest cięższy (np. pod wodą), ale może skutkować w niechcianych artefaktach graficznych pomiędzy niebem a mgłą w niektórych przypadkach.
sodium.options.use_entity_culling.name=Chowanie bytów
sodium.options.use_entity_culling.tooltip=Jeśli włączone, byty, które nie są w żadnym widocznym chunku, będą zignorowane podczas renderowaniu.To może zwiększyć wydajność, pomijając renderowanie bytów znajdujących się pod ziemią lub za ścianami.
sodium.options.use_particle_culling.name=Chowanie cząstek
sodium.options.use_particle_culling.tooltip=Jeśli włączone, tylko cząstki, które uważane są za widoczne, będą renderowane. To może skutkować znaczną poprawą klatek na sekundę, gdy wiele cząstek jest w polu widzenia.
sodium.options.animate_only_visible_textures.name=Animuj tylko widoczne tekstury
sodium.options.animate_only_visible_textures.tooltip=Jeśli włączone, tylko animowane tekstury, które uważane są za widoczne, będą aktualizowane. To może pomóc z wydajnością na niektórych systemach, szczególnie z cięższymi paczkami zasobów. Jeśli zauważyłeś, że niektóre tekstury nie są animowane, spróbuj wyłączyć tę opcję. If enabled, only animated textures determined to be visible will be updated.
sodium.options.translucency_sorting.name=Sortowanie przezroczystości
sodium.options.translucency_sorting.tooltip=Jeśli włączone, przezroczyste bloki będą sortowane poprawnie od tyłu do przodu aby zapewnić lepsze renderowanie, szczególnie jeśli wiele przezroczystych bloków jest widocznych i ułożonych na sobie. Jest to trochę kosztowna operacja.
sodium.options.cpu_render_ahead_limit.name=Limit renderowania klatek z wyprzedzeniem przez CPU
sodium.options.cpu_render_ahead_limit.tooltip=Określa maksymalną liczbę klatek na które CPU może czekać, aby zostały wyrenderowane przez GPU. Bardzo niskie lub wysokie wartości mogą powodować niestabilność klatek.
sodium.options.cpu_render_ahead_limit.value=%s klat(ki/ek)
sodium.options.allow_direct_memory_access.name=Zezwól na bezpośredni dostęp do pamięci
sodium.options.allow_direct_memory_access.tooltip=Jeśli włączone, niektóre krytyczne ścieżki kodu będą miały pozwolenie na użycie bezpośredniego dostępu do pamięci dla wydajności. To często znacznie zmniejsza obciążenie CPU do renderowania chunków i bytów, lecz może utrudnić diagnozę błędów i awarii. Powinieneś to wyłączyć tylko wtedy, jeśli zostałeś o to zapytany lub wiesz co robisz.
sodium.options.ignore_driver_blacklist.name=Ignoruj czarną listę sterowników
sodium.options.ignore_driver_blacklist.tooltip=Jeśli włączone, znane problemy z kompatybilnością z twoim systemem/sterownikiem będą zignorowane, pozwalając na włączenie opcji, które mogą powodować problemy z grą. Nie powinieneś dotykać tej opcji, chyba że dokładnie wiesz co robisz. Po zmienieniu tej opcji, musisz zapisać, zamknąć, a potem ponownie otworzyć ekran ustawień.
sodium.options.enable_memory_tracing.name=Włącz śledzenie pamięci
sodium.options.enable_memory_tracing.tooltip=Funkcja debugowania. Jeśli włączone, śledzona pamięć będzie zbierana wraz z alokacją pamięci w celu ulepszenia informacji diagnostycznych, gdy wycieki pamięci są wykryte.
sodium.options.performance_impact_string=Wpływ na wydajność: %s
sodium.options.use_persistent_mapping.name=Trwałe mapowanie
sodium.options.use_persistent_mapping.tooltip=Jeśli włączone, niewielka ilość pamięci będzie trwale mapowana aby przyspieszyć aktualizacje chunków i renderowanie bytów.\n\nWymaga OpenGL 4.4 lub ARB_buffer_storage.
sodium.options.chunk_memory_allocator.name=Alokator pamięci chunków
sodium.options.chunk_memory_allocator.tooltip=Wybiera alokator pamięci, który będzie użyty do renderowania chunków.\n- ASYNC: Najszybsza opcja, działa dobrze z większością nowoczesnych sterowników graficznych.\n- SWAP: Opcja awaryjna dla starszych sterowników graficznych. Może znacznie zwiększyć użycie pamięci.
sodium.options.chunk_memory_allocator.async=Async
sodium.options.chunk_memory_allocator.swap=Swap
sodium.options.chunk_update_threads.name=Wątki aktualizacji chunków
sodium.options.chunk_update_threads.tooltip=Określa liczbę wątków użytych do budowania chunków. Używanie większej liczby wątków może przyspieszyć wczytywanie chunków i ich aktualizowanie, ale może negatywnie wpłynąć na klatki.
sodium.options.always_defer_chunk_updates.name=Zawsze opóźniaj aktualizacje chunków
sodium.options.always_defer_chunk_updates.tooltip=Jeśli włączone, renderowanie nigdy nie będzie czekać aż aktualizacje chunków się zakończą, nawet gdy są one ważne. To może znacznie poprawić wydajność klatek w niektórych przypadkach, ale może skutkować widocznym opóźnieniem na świecie.
sodium.options.use_no_error_context.name=Brak kontekstu błędu
sodium.options.use_no_error_context.tooltip=Jeśli włączone, kontekst OpenGL zostanie stworzony z wyłączonym sprawdzaniem błędów. To może minimalnie zwiększyć wydajność, ale również zwiększa ryzyko awarii gry zamiast radzenia sobie z błędami OpenGL. Powinieneś wyłączyć tą opcję, jeśli napotykasz nagłe i niewyjaśnione awarie.
sodium.options.use_gl_state_cache.name=Pamięć podręczna stanu GL
sodium.options.use_gl_state_cache.tooltip=Jeśli włączone, pamięć podręczna stanu OpenGL będzie użyta aby zmniejszyć ilość niepotrzebnych zmian stanu. To może zwiększyć wydajność, ale może też spowodować problemy z modami. Nie utrzymuje się po ponownym uruchomieniu gry.
sodium.options.threads.value=%s wątek(ów)
sodium.options.default=Domyślne
sodium.options.buttons.undo=Cofnij
sodium.options.buttons.apply=Zastosuj
sodium.options.buttons.donate=Kup kawę dla JellySquid!
options.dynamic_fov=Dynamiczne pole widzenia
options.dynamic_fov.tooltip=Jeśli włączone, pole widzenia gry będzie zmieniać się na podstawie szybkości gracza.
options.framerate=%s FPS
iris.shaders.toggled=Przełączono shadery na %s!
iris.shaders.disabled=Shadery wyłączone!
options.iris.apply=Zastosuj
options.iris.refresh=Odśwież
options.iris.openShaderPackFolder=Otwórz folder paczek shaderów...
options.iris.shaderPackSettings=Ustawnienia paczki shaderów...
options.iris.shaderPackList=Lista paczek shaderów...
options.iris.refreshShaderPacks=Odśwież paczki shaderów
options.iris.shaderPackSelection=Paczki shaderów...
options.iris.shaderPackSelection.title=Paczki shaderów
options.iris.shaderPackSelection.addedPack=Dodano paczkę shaderów "%s"
options.iris.shaderPackSelection.addedPacks=Dodano %s paczki shaderów
options.iris.shaderPackSelection.failedAdd=Pliki nie były prawidłowymi paczkami shaderów
options.iris.shaderPackSelection.failedAddSingle="%s" nie jest prawidłową paczką shaderów
options.iris.shaderPackSelection.copyError=Nie można było dodać paczki shaderów "%s"
options.iris.shaderPackSelection.copyErrorAlreadyExists="%s" już istnieje w twoim folderze Shader Packs!
options.iris.shaderPackOptions.tooManyFiles=Nie można zaimportować wielu plików ustawień shadera!
options.iris.shaderPackOptions.failedImport=Nie udało się zaimportować plik ustawień shadera "%s"
options.iris.shaderPackOptions.importedSettings=Zaimportowano ustawienia shadera z "%s"
options.iris.shaders.disabled=Shadery: Wyłączone
options.iris.shaders.enabled=Shadery: Włączone
options.iris.shaders.nonePresent=Shadery: Brak paczek shaderów
options.iris.back=Powrót
options.iris.reset=Resetuj
options.iris.reset.tooltip=Zresetować WSZYSTKIE opcje i zastosować?
options.iris.reset.tooltip.holdShift=Przytrzymaj SHIFT i kliknij aby zresetować
options.iris.importSettings.tooltip=Importuj ustawienia z pliku
options.iris.exportSettings.tooltip=Eksportuj zastosowane ustawienia do pliku
options.iris.mustDisableFullscreen=Proszę najpierw wyłączyć tryb pełnoekranowy!
options.iris.setToDefault=Ustawić opcję na domyślną wartość?
options.iris.profile=Profil
options.iris.profile.custom=Niestandardowy
options.iris.shadowDistance=Maksymalny zasięg cieni
options.iris.shadowDistance.enabled=Pozwala zmienić maksymalny zasięg renderowania cieni. Teren i byty poza tym dystansem nie będą rzucać cieni. Zmniejszenie zasięgu renderowania cieni może znacznie zwiększyć wydajność.
options.iris.shadowDistance.disabled=Twoja obecna paczka shaderów ustawiła już zasięg renderowania cieni; nie możesz go zmienić.
options.iris.gui.hide=Ukryj GUI
options.iris.gui.show=Pokaż GUI
options.dynamic_lights=Dynamiczne światła
options.dynamic_lights.tooltip=Włącza dynamiczne światła. Tryby: OFF. - wyłączone, FASTEST - opóźnienie 500ms, FAST - opóźnienie 250ms, FANCY - brak opóźnienia. Wyłączone, jeśli shadery są w użyciu.
pack.iris.select.title=Wybierz
pack.iris.configure.title=Konfiguruj
label.iris.true=Wł.
label.iris.false=Wył.
@@ -0,0 +1,134 @@
options.button.shader=Шейдеры...
options.chunks=%s чанков
options.entityShadows=Тени сущностей
sodium.option_impact.low=Низкий
sodium.option_impact.medium=Средний
sodium.option_impact.high=Высокий
sodium.option_impact.extreme=Экстремальный
sodium.option_impact.varies=Варьируется
sodium.options.pages.quality=Качество
sodium.options.pages.performance=Производительность
sodium.options.pages.advanced=Расширенные
sodium.options.view_distance.tooltip=Дистанция рендеринга контролирует, насколько далеко будет отрисовываться местность. Короткие дистанции означают, что будет отрисовываться меньше местности, что улучшает частоту кадров.
sodium.options.simulation_distance.tooltip=Дистанция симуляции контролирует, насколько далеко будут загружаться и обрабатываться местность и сущности. Короткие дистанции могут снизить нагрузку на внутренний сервер и улучшить частоту кадров.
sodium.options.brightness.tooltip=Контролирует яркость (гамма) игры.
sodium.options.clouds.name=Облака
sodium.options.clouds.tooltip=Контролирует, будут ли видны облака.
sodium.options.gui_scale.tooltip=Устанавливает максимальный коэффициент масштабирования, который будет использоваться для пользовательского интерфейса. Если используется 'авто', то всегда будет использоваться наибольший коэффициент масштабирования.
sodium.options.fullscreen.tooltip=Если включено, игра будет отображаться в полноэкранном режиме (если поддерживается).
sodium.options.v_sync.tooltip=Если включено, частота кадров игры будет синхронизирована с частотой обновления монитора, что в целом обеспечивает более плавное восприятие за счет увеличения общей задержки ввода. Эта настройка может снизить производительность, если ваша система слишком медленная.
sodium.options.fps_limit.tooltip=Ограничивает максимальное количество кадров в секунду. Это может помочь снизить потребление батареи и общую нагрузку на систему при многозадачности. Если включен V-Sync, этот параметр будет игнорироваться, если он ниже частоты обновления вашего дисплея.
sodium.options.view_bobbing.tooltip=Если включено, вид игрока будет качаться и прыгать при движении. Игроки, испытывающие укачивание при игре, могут выиграть от отключения этого.
sodium.options.attack_indicator.tooltip=Контролирует, где на экране отображается индикатор атаки.
sodium.options.autosave_indicator.tooltip=Если включено, индикатор будет показан, когда игра сохраняет мир на диск.
sodium.options.graphics_quality.tooltip=Качество графики по умолчанию контролирует некоторые устаревшие параметры и необходимо для совместимости с модами. Если параметры ниже оставлены по умолчанию, они будут использовать эту настройку.
sodium.options.clouds_quality.tooltip=Контролирует качество отрисовываемых облаков в небе.
sodium.options.weather_quality.tooltip=Контролирует качество эффектов дождя и снега.
sodium.options.leaves_quality.name=Качество Листьев
sodium.options.leaves_quality.tooltip=Контролирует качество листьев.
sodium.options.grass_quality.name=Качество Травы
sodium.options.grass_quality.tooltip=Контролирует качество боковых сторон блока травы.
sodium.options.particle_quality.name=Качество Частиц
sodium.options.particle_quality.tooltip=Контролирует максимальное количество частиц, которые могут быть на экране в любой момент времени.
sodium.options.smooth_lighting.tooltip=Контролирует, будут ли блоки плавно освещены и затенены. Это немного увеличивает время, необходимое для перестройки чанка, но не влияет на частоту кадров.
sodium.options.biome_blend.value=%s блок(ов)
sodium.options.biome_blend.tooltip=Контролирует диапазон, в котором будут отбираться биомы для окрашивания блоков. Более высокие значения значительно увеличивают время, необходимое для построения чанков, при уменьшении улучшений качества.
sodium.options.entity_distance.tooltip=Контролирует, насколько далеко сущности могут отображаться от игрока. Более высокие значения увеличивают дистанцию рендеринга за счет частоты кадров.
sodium.options.entity_shadows.tooltip=Если включено, под мобами и другими сущностями будут отрисовываться базовые тени.
sodium.options.vignette.name=Виньетка
sodium.options.vignette.tooltip=Если включено, на вид игрока будет наложен эффект виньетки. Это вряд ли повлияет на частоту кадров, если вы не ограничены заполнением.
sodium.options.mipmap_levels.tooltip=Контролирует количество мип-карт, которые будут использоваться для текстур моделей блоков. Более высокие значения обеспечивают лучшую отрисовку блоков на расстоянии, но могут негативно повлиять на производительность при наличии многих анимированных текстур.
sodium.options.use_chunk_multidraw.name=Мульти-Рисование Чанков
sodium.options.use_chunk_multidraw.tooltip=Мульти-рисование позволяет отрисовывать несколько чанков с меньшим количеством вызовов рисования, значительно снижая нагрузку на CPU при рендеринге мира, а также потенциально позволяя более эффективное использование GPU. Эта оптимизация может вызвать проблемы с некоторыми графическими драйверами, поэтому вы должны попробовать отключить ее, если у вас возникают сбои.
sodium.options.use_vertex_objects.name=Объекты Вершин
sodium.options.use_vertex_objects.tooltip=Помогает улучшить производительность, перемещая информацию о том, как должны отображаться вершинные данные, в драйвер, позволяя ему лучше оптимизировать повторное отображение одних и тех же объектов. Обычно нет причин отключать это, если вы не используете несовместимые моды.
sodium.options.use_block_face_culling.name=Отсечение Лиц Блока
sodium.options.use_block_face_culling.tooltip=Если включено, для отрисовки будут представлены только те стороны блоков, которые обращены к камере. Это может устранить большое количество граней блоков на очень ранней стадии процесса отрисовки, экономя пропускную способность памяти и время на GPU. Некоторые ресурс-паки могут иметь проблемы с этой опцией, поэтому попробуйте отключить ее, если вы видите дыры в блоках.
sodium.options.use_compact_vertex_format.name=Компактный Формат Вершин
sodium.options.use_compact_vertex_format.tooltip=Если включено, для отрисовки чанков будет использоваться более компактный формат вершин. Это может значительно снизить использование памяти графики и требования к пропускной способности, особенно для интегрированных графических карт, но может вызвать борьбу за z с некоторыми ресурс-паками из-за того, как это уменьшает точность атрибутов положения и текстурных координат.
sodium.options.use_fog_occlusion.name=Окклюзия Тумана
sodium.options.use_fog_occlusion.tooltip=Если включено, чанки, которые определены как полностью скрытые эффектами тумана, не будут отрисовываться, что помогает улучшить производительность. Улучшение может быть более заметным, когда эффекты тумана более тяжелые (например, под водой), но это может вызвать нежелательные визуальные артефакты между небом и туманом в некоторых сценариях.
sodium.options.use_entity_culling.name=Отсечение Сущностей
sodium.options.use_entity_culling.tooltip=Если включено, сущности, которые определены как не находящиеся в любых видимых чанках, будут пропущены во время отрисовки. Это может помочь улучшить производительность, избегая отрисовки сущностей, расположенных под землей или за стенами.
sodium.options.use_particle_culling.name=Отсечение Частиц
sodium.options.use_particle_culling.tooltip=Если включено, будут отрисовываться только те частицы, которые определены как видимые. Это может значительно улучшить частоту кадров, когда рядом находится много частиц.
sodium.options.animate_only_visible_textures.name=Анимировать Только Видимые Текстуры
sodium.options.animate_only_visible_textures.tooltip=Если включено, будут обновляться только анимированные текстуры, определенные как видимые. Это может значительно увеличить частоту кадров на некотором оборудовании, особенно с более тяжелыми ресурс-паками. Если у вас возникают проблемы с некоторыми текстурами, которые не анимируются, попробуйте отключить эту опцию.
sodium.options.translucency_sorting.name=Сортировка Прозрачности
sodium.options.translucency_sorting.tooltip=Если включено, прозрачные блоки будут правильно отсортированы сзади вперед для обеспечения лучшей отрисовки, особенно когда в поле зрения находится несколько прозрачных блоков и они слоены. Это немного дорогостоящая операция.
sodium.options.cpu_render_ahead_limit.name=Предел Предварительной Отрисовки CPU
sodium.options.cpu_render_ahead_limit.tooltip=Определяет максимальное количество кадров, которые CPU может ожидать завершения отрисовки на GPU. Очень низкие или высокие значения могут создать нестабильность частоты кадров.
sodium.options.cpu_render_ahead_limit.value=%s кадр(ов)
sodium.options.allow_direct_memory_access.name=Разрешить Прямой Доступ к Памяти
sodium.options.allow_direct_memory_access.tooltip=Если включено, некоторые критически важные коды будут иметь право использовать прямой доступ к памяти для повышения производительности. Это часто значительно снижает нагрузку на CPU при отрисовке чанков и сущностей, но может затруднить диагностику некоторых ошибок и сбоев. Вы должны отключить это, только если вам это попросили или вы иначе знаете, что делаете.
sodium.options.ignore_driver_blacklist.name=Игнорировать Черный Список Драйверов
sodium.options.ignore_driver_blacklist.tooltip=Если включено, будут игнорироваться известные несовместимости с вашей конфигурацией оборудования/драйвера, что позволит вам включить опции, которые могут вызвать проблемы с вашей игрой. Вы, как правило, не должны трогать эту опцию, если вы точно не знаете, что делаете. После изменения этой опции, вы должны сохранить, закрыть, а затем снова открыть экран настроек.
sodium.options.enable_memory_tracing.name=Включить Трассировку Памяти
sodium.options.enable_memory_tracing.tooltip=Функция отладки. Если включено, трассировки стека будут собираться наряду с выделениями памяти, чтобы помочь улучшить диагностическую информацию при обнаружении утечек памяти.
sodium.options.performance_impact_string=Влияние на Производительность: %s
sodium.options.use_persistent_mapping.name=Постоянное Отображение
sodium.options.use_persistent_mapping.tooltip=Если включено, небольшое количество памяти будет постоянно отображено для ускорения обновлений чанков и отрисовки сущностей.\n\nТребуется OpenGL 4.4 или ARB_buffer_storage.
sodium.options.chunk_memory_allocator.name=Аллокатор Памяти Чанка
sodium.options.chunk_memory_allocator.tooltip=Выбирает аллокатор памяти, который будет использоваться для отрисовки чанков.\n- ASYNC: Самый быстрый вариант, хорошо работает с большинством современных графических драйверов.\n- SWAP: Резервный вариант для старых графических драйверов. Может значительно увеличить использование памяти.
sodium.options.chunk_memory_allocator.async=Асинхронный
sodium.options.chunk_memory_allocator.swap=Обмен
sodium.options.chunk_update_threads.name=Потоки Обновления Чанков
sodium.options.chunk_update_threads.tooltip=Определяет количество потоков, которые будут использоваться для построения чанков. Использование большего количества потоков может ускорить загрузку чанков и скорость обновления, но может негативно влиять на время кадра.
sodium.options.always_defer_chunk_updates.name=Всегда Откладывать Обновления Чанков
sodium.options.always_defer_chunk_updates.tooltip=Если включено, отрисовка никогда не будет ждать завершения обновлений чанков, даже если они важны. Это может значительно улучшить частоту кадров в некоторых сценариях, но это может создать значительную визуальную задержку в мире.
sodium.options.use_no_error_context.name=Без Контекста Ошибок
sodium.options.use_no_error_context.tooltip=Если включено, контекст OpenGL будет создан с отключенной проверкой ошибок. Это может немного улучшить производительность, но также увеличивает риск того, что игра будет вылетать, а не грациозно обрабатывать ошибки OpenGL. Вы должны отключить эту опцию, если у вас возникают внезапные необъяснимые сбои.
sodium.options.use_gl_state_cache.name=Кэш Состояния GL
sodium.options.use_gl_state_cache.tooltip=Если включено, будет использоваться кэш состояния OpenGL, чтобы уменьшить количество избыточных изменений состояния. Это может улучшить производительность, но также может вызвать проблемы с некоторыми модами. Не сохраняется при перезапуске игры.
sodium.options.threads.value=%s поток(ов)
sodium.options.default=По умолчанию
sodium.options.buttons.undo=Отменить
sodium.options.buttons.apply=Применить
sodium.options.buttons.donate=Купить кофе для JellySquid!
options.dynamic_fov=Динамическое FOV
options.dynamic_fov.tooltip=Если включено, поле зрения игры будет меняться в зависимости от скорости игрока.
options.framerate=%s FPS
iris.shaders.toggled=Переключены шейдеры на %s!
iris.shaders.disabled=Шейдеры отключены!
options.iris.apply=Применить
options.iris.refresh=Обновить
options.iris.openShaderPackFolder=Открыть папку с пакетами шейдеров...
options.iris.shaderPackSettings=Настройки пакета шейдеров...
options.iris.shaderPackList=Список пакетов шейдеров...
options.iris.refreshShaderPacks=Обновить пакеты шейдеров
options.iris.shaderPackSelection=Пакеты шейдеров...
options.iris.shaderPackSelection.title=Пакеты шейдеров
options.iris.shaderPackSelection.addedPack=Добавлен пакет шейдеров "%s"
options.iris.shaderPackSelection.addedPacks=Добавлено %s пакетов шейдеров
options.iris.shaderPackSelection.failedAdd=Файлы не были действительными пакетами шейдеров
options.iris.shaderPackSelection.failedAddSingle="%s" не является действительным пакетом шейдеров
options.iris.shaderPackSelection.copyError=Не удалось добавить пакет шейдеров "%s"
options.iris.shaderPackSelection.copyErrorAlreadyExists="%s" уже находится в вашей папке с пакетами шейдеров!
options.iris.shaderPackOptions.tooManyFiles=Невозможно импортировать несколько файлов настроек шейдеров!
options.iris.shaderPackOptions.failedImport=Не удалось импортировать файл настроек шейдеров "%s"
options.iris.shaderPackOptions.importedSettings=Импортированы настройки шейдеров из "%s"
options.iris.shaders.disabled=Шейдеры: Отключены
options.iris.shaders.enabled=Шейдеры: Включены
options.iris.shaders.nonePresent=Шейдеры: Пакеты отсутствуют
options.iris.back=Назад
options.iris.reset=Сброс
options.iris.reset.tooltip=Сбросить ВСЕ настройки и применить?
options.iris.reset.tooltip.holdShift=Удерживайте SHIFT и нажмите, чтобы сбросить
options.iris.importSettings.tooltip=Импортировать настройки из файла
options.iris.exportSettings.tooltip=Экспортировать примененные настройки в файл
options.iris.mustDisableFullscreen=Пожалуйста, сначала отключите полноэкранный режим!
options.iris.setToDefault=Установить параметр по умолчанию?
options.iris.profile=Профиль
options.iris.profile.custom=Пользовательский
options.iris.shadowDistance=Максимальное расстояние тени
options.iris.shadowDistance.enabled=Позволяет вам изменить максимальное расстояние для теней. Местность и сущности за этим расстоянием не будут отбрасывать тени. Уменьшение расстояния тени может значительно увеличить производительность.
options.iris.shadowDistance.disabled=Ваш текущий пакет шейдеров уже установил расстояние рендеринга для теней; вы не можете его изменить.
options.iris.gui.hide=Скрыть GUI
options.iris.gui.show=Показать GUI
options.dynamic_lights=Динамическое освещение
options.dynamic_lights.tooltip=Включает динамическое освещение. Режимы: OFF - выключено, FASTEST - задержка 500 мс, FAST - задержка 250 мс, FANCY - без задержки. Отключено, если используются шейдеры.
pack.iris.select.title=Выбрать
pack.iris.configure.title=Настроить
label.iris.true=Вкл
label.iris.false=Выкл
@@ -1,35 +0,0 @@
{
"gui_light": "side",
"display": {
"gui": {
"rotation": [ 30, 225, 0 ],
"translation": [ 0, 0, 0],
"scale":[ 0.625, 0.625, 0.625 ]
},
"ground": {
"rotation": [ 0, 0, 0 ],
"translation": [ 0, 3, 0],
"scale":[ 0.25, 0.25, 0.25 ]
},
"fixed": {
"rotation": [ 0, 0, 0 ],
"translation": [ 0, 0, 0],
"scale":[ 0.5, 0.5, 0.5 ]
},
"thirdperson_righthand": {
"rotation": [ 75, 45, 0 ],
"translation": [ 0, 2.5, 0],
"scale": [ 0.375, 0.375, 0.375 ]
},
"firstperson_righthand": {
"rotation": [ 0, 45, 0 ],
"translation": [ 0, 0, 0 ],
"scale": [ 0.40, 0.40, 0.40 ]
},
"firstperson_lefthand": {
"rotation": [ 0, 225, 0 ],
"translation": [ 0, 0, 0 ],
"scale": [ 0.40, 0.40, 0.40 ]
}
}
}
@@ -1,16 +0,0 @@
{
"parent": "blocks/block",
"elements": [
{ "from": [ 0, 0, 0 ],
"to": [ 16, 16, 16 ],
"faces": {
"down": { "texture": "#down", "cullface": "down" },
"up": { "texture": "#up", "cullface": "up" },
"north": { "texture": "#north", "cullface": "north" },
"south": { "texture": "#south", "cullface": "south" },
"west": { "texture": "#west", "cullface": "west" },
"east": { "texture": "#east", "cullface": "east" }
}
}
]
}
@@ -1,12 +0,0 @@
{
"parent": "blocks/cube",
"textures": {
"particle": "#all",
"down": "#all",
"up": "#all",
"north": "#all",
"east": "#all",
"south": "#all",
"west": "#all"
}
}
@@ -1,55 +0,0 @@
{
"parent": "blocks/block",
"display": {
"firstperson_righthand": {
"rotation": [ 0, 135, 0 ],
"translation": [ 0, 0, 0 ],
"scale": [ 0.4, 0.4, 0.4 ]
}
},
"textures": {
"particle": "lectern_sides",
"bottom": "oak_planks",
"base": "lectern_base",
"front": "lectern_front",
"sides": "lectern_sides",
"top": "lectern_top"
},
"elements": [
{
"from": [ 0, 0, 0 ],
"to": [ 16, 2, 16 ],
"faces": {
"north": { "uv": [ 0, 14, 16, 16 ], "texture": "#base", "cullface": "north" },
"east": { "uv": [ 0, 6, 16, 8 ], "texture": "#base", "cullface": "east" },
"south": { "uv": [ 0, 6, 16, 8 ], "texture": "#base", "cullface": "south" },
"west": { "uv": [ 0, 6, 16, 8 ], "texture": "#base", "cullface": "west" },
"up": { "uv": [ 0, 0, 16, 16 ], "rotation": 180, "texture": "#base" },
"down": { "uv": [ 0, 0, 16, 16 ], "texture": "#bottom", "cullface": "down" }
}
},
{
"from": [4, 2, 4],
"to": [12, 15, 12],
"faces": {
"north": { "uv": [ 0, 0, 8, 13 ], "texture": "#front" },
"east": { "uv": [ 2, 16, 15, 8 ], "rotation": 90, "texture": "#sides" },
"south": { "uv": [ 8, 3, 16, 16 ], "texture": "#front" },
"west": { "uv": [ 2, 8, 15, 16 ], "rotation": 90, "texture": "#sides" }
}
},
{
"from": [ 0.01, 12, 3 ],
"to": [ 15.99, 16, 16 ],
"rotation": { "angle": -22.5, "axis": "x", "origin": [ 8, 8, 8 ] },
"faces": {
"north": { "uv": [ 0, 0, 16, 4 ], "texture": "#sides" },
"east": { "uv": [ 0, 4, 13, 8 ], "texture": "#sides" },
"south": { "uv": [ 0, 4, 16, 8 ], "texture": "#sides" },
"west": { "uv": [ 0, 4, 13, 8 ], "texture": "#sides" },
"up": { "uv": [ 0, 1, 16, 14 ], "rotation": 180, "texture": "#top" },
"down": { "uv": [ 0, 0, 16, 13 ], "texture": "#bottom" }
}
}
]
}
@@ -1,6 +0,0 @@
{
"parent": "blocks/cube_all",
"textures": {
"all": "stone"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 269 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 312 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 268 B

@@ -1,67 +1,43 @@
options.button.detail=Detale...
options.button.other=Inne...
options.button.particle=Cząsteczki...
options.button.particle=Cząstki...
options.button.sky=Atmosfera...
options.chunks=%s chunków
options.framerate=%s FPS
options.graphics.shelledfancy=Hybrydowe dokładne
options.graphics.shelledfast=Hybrydowe szybkie
options.graphics.smart=Inteligentne
options.graphics.ultra=Ultra
options.off=Wył.
options.on=Wł.
options.cloud_height=Wysokość chmur
options.cloud_scale=Skala chmur
options.gui_background=Tło
options.gui_background.-1=Domyślne
options.gui_background.0=Piasek
options.gui_background.1=Grzybnia
options.gui_background.2=Kamienne cegły
options.gui_background.3=Zamszone kamienne cegły
options.gui_background.4=Dębowe deski
options.gui_background.5=Brzozowe deski
options.downfall_distance=Efekty pogody
options.downfall_distance.-1=Domyślne
options.downfall_distance.0=Szybkie
options.downfall_distance.1=Dokładne
options.downfall_distance.2=Ultra
options.downfall_distance.3=Wył.
options.dynamic_fov=Dynamiczne pole widzenia
options.dynamic_fov.tooltip=Jeśli włączone, pole widzenia gry będzie zmieniać się na podstawie szybkości gracza.
options.fog_near_distance=Odległość mgły
options.mode_cloud_translucency=Przezroczystość chmur
options.mode_cloud_translucency.-1=Domyślna
options.mode_cloud_translucency.0=Zawsze
options.mode_cloud_translucency.1=Nigdy
options.mode_clouds=Chmury
options.mode_clouds.-1=Domyślne
options.mode_clouds.0=Dokładne
options.mode_clouds.1=Szybkie
options.mode_clouds.2=Wył.
options.mode_dropped_items=Wyrzucone przedmioty
options.mode_dropped_items.-1=Domyślne
options.mode_dropped_items.0=Dokładne
options.mode_dropped_items.1=Szybkie
options.mode_dropped_items=Upuszczone przedmioty
options.mode_glint_inv=Efekt zaklęć w GUI
options.mode_glint_world=Efekt zaklęć w świecie
options.mode_glint_world=Efekt zaklęć na świecie
options.mode_gui_background=Tła menu
options.mode_leaves=Liście
options.mode_leaves.-1=Domyślne
options.mode_leaves.0=Dokładne
options.mode_leaves.1=Szybkie
options.mode_leaves.2=Inteligentne
options.mode_leaves.3=Hybrydowe dokładne
options.mode_leaves.4=Hybrydowe szybkie
options.mode_light_flicker=Migotanie światła
options.mode_shadows=Cienie bytów
options.mode_shadows.-1=Domyślne
options.mode_shadows.0=Wł.
options.mode_shadows.1=Wył.
options.mode_sky=Niebo
options.mode_sun_moon=Słońce i księżyc
options.mode_stars=Gwiazdy
options.mode_water=Woda
options.mode_water.-1=Domyślna
options.mode_water.0=Dokładna
options.mode_water.1=Szybka
options.mode_vignette=Winieta
options.mode_vignette.-1=Domyślna
options.mode_vignette.0=Wł.
options.mode_vignette.1=Wył.
options.particles_enc_table=Cząsteczki zaklęć
options.particles_void=Cząsteczki próżni
options.particles_enc_table=Cząstki zaklęć
options.particles_void=Cząstki próżni
options.render_distance_clouds=Odległość renderowania chmur
options.title.detail=Ustawienia detali
options.title.other=Inne ustawienia
options.title.particle=Ustawienia cząsteczek
options.title.particle=Ustawienia cząstek
options.title.sky=Ustawienia atmosfery
options.title.video=Ustawienia graficzne
options.total_stars=Gęstość gwiazd
options.void_fog=Mgła próżni
@@ -0,0 +1,43 @@
options.button.detail=Детали...
options.button.other=Другое...
options.button.particle=Частицы...
options.button.sky=Атмосфера...
options.chunks=%s чанков
options.framerate=%s FPS
options.graphics.shelledfancy=Гибридный Красивый
options.graphics.shelledfast=Гибридный Быстрый
options.graphics.smart=Умный
options.graphics.ultra=Ультра
options.off=Выкл
options.on=Вкл
options.cloud_height=Высота Облаков
options.cloud_scale=Масштаб Облаков
options.gui_background=Фон
options.downfall_distance=Эффекты Погоды
options.dynamic_fov=Динамическое FOV
options.dynamic_fov.tooltip=Если включено, поле зрения игры будет меняться в зависимости от скорости игрока.
options.fog_near_distance=Расстояние до Ближнего Тумана
options.mode_cloud_translucency=Прозрачность Облаков
options.mode_clouds=Облака
options.mode_dropped_items=Выброшенные Предметы
options.mode_glint_inv=GUI Эффекты Зачарования
options.mode_glint_world=Мировые Эффекты Зачарования
options.mode_gui_background=Фоны Меню
options.mode_leaves=Листва
options.mode_light_flicker=Мерцание Света
options.mode_shadows=Тени Сущностей
options.mode_sky=Небо
options.mode_sun_moon=Солнце & Луна
options.mode_stars=Звезды
options.mode_water=Вода
options.mode_vignette=Виньетка
options.particles_enc_table=Частицы Зачарования
options.particles_void=Частицы Пустоты
options.render_distance_clouds=Расстояние Рендеринга Облаков
options.title.detail=Настройки Деталей
options.title.other=Другие Настройки
options.title.particle=Настройки Частиц
options.title.sky=Настройки Атмосферы
options.title.video=Видео Настройки
options.total_stars=Плотность Звезд
options.void_fog=Туман Пустоты
@@ -1,9 +1,12 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.joml.Vector3f;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -11,6 +14,7 @@ import java.nio.FloatBuffer;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyLightState;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyMaterialState;
@ExtendWith(AngelicaExtension.class)
public class GLSM_Lighting_UnitTest {
@@ -153,6 +157,156 @@ public class GLSM_Lighting_UnitTest {
GLStateManager.glPopAttrib();
}
@Test
void testLightModel() {
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "GL_LIGHT_MODEL_AMBIENT initial state");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, f4b);
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "GL_LIGHT_MODEL_AMBIENT changed state");
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F});
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SINGLE_COLOR);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModeli(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SEPARATE_SPECULAR_COLOR);
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SEPARATE_SPECULAR_COLOR);
GLStateManager.glPopAttrib();
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SINGLE_COLOR);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModelf(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, 0.8F);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModeli(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModelf(GL11.GL_LIGHT_MODEL_TWO_SIDE, 0.8F);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glLightModeli(GL11.GL_LIGHT_MODEL_TWO_SIDE, 1);
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, true);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false);
}
@Test
void testColorMaterial() {
verifyState(GL11.GL_COLOR_MATERIAL, false);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT | GL11.GL_CURRENT_BIT);
GLStateManager.glColor4f(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glColorMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT);
GLStateManager.glEnable(GL11.GL_COLOR_MATERIAL);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glDisable(GL11.GL_COLOR_MATERIAL);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyState(GL11.GL_COLOR_MATERIAL, false);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_COLOR_MATERIAL, false);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT_AND_BACK);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT_AND_DIFFUSE);
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glColorMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT_AND_DIFFUSE);
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT_AND_DIFFUSE);
GLStateManager.glColorMaterial(GL11.GL_FRONT, GL11.GL_SPECULAR);
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_SPECULAR);
GLStateManager.glColorMaterial(GL11.GL_BACK, GL11.GL_DIFFUSE);
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_BACK);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_DIFFUSE);
GLStateManager.glPopAttrib();
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT_AND_BACK);
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT_AND_DIFFUSE);
}
@Test
void testMaterial() {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT, f4b);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT, f4b);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT_AND_DIFFUSE, f4b);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_DIFFUSE, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_DIFFUSE, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_AMBIENT, new float[]{0.2F, 0.2F, 0.2F, 1.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_DIFFUSE, new float[]{0.8F, 0.8F, 0.8F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_SPECULAR, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_BACK, GL11.GL_SPECULAR, f4b);
verifyMaterialState(GL11.GL_BACK, GL11.GL_SPECULAR, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_BACK, GL11.GL_SPECULAR, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
verifyMaterialState(GL11.GL_BACK, GL11.GL_EMISSION, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.2F);
GLStateManager.glMaterial(GL11.GL_BACK, GL11.GL_EMISSION, f4b);
verifyMaterialState(GL11.GL_BACK, GL11.GL_EMISSION, new float[]{0.8F, 0.6F, 0.4F, 0.2F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_BACK, GL11.GL_EMISSION, new float[]{0.0F, 0.0F, 0.0F, 1.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_SHININESS, new float[]{0.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
GLStateManager.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS, 5.5F);
verifyMaterialState(GL11.GL_FRONT, GL11.GL_SHININESS, new float[]{5.5F}, "");
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_SHININESS, new float[]{0.0F}, "");
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.0F, 1.0F, 1.0F}, "");
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.0F);
GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, f4b);
if (GLStateManager.isNVIDIA()) {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.8F, 0.4F, 0.6F}, "");
} else {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.8F, 0.6F, 0.4F}, "");
}
GLStateManager.glPopAttrib();
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.0F, 1.0F, 1.0F}, "");
}
static void newf4b(float x, float y, float z, float w) {
f4b.clear();
f4b.put(x).put(y).put(z).put(w);
@@ -269,6 +269,16 @@ class GLSM_PushPop_UnitTest {
});
GLStateManager.glPopAttrib();
//glEnable(GL_COLOR_MATERIAL) changes the material color state when it is triggered. We need to reset that
//here to not mess up the default state for other tests. We're not resetting with glPush/PopAttrib because
//we're specifically trying to test GL_ENABLE_BIT here.
FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(16);
floatBuffer.put(0.2F).put(0.2F).put(0.2F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT, floatBuffer);
floatBuffer.put(0.8F).put(0.8F).put(0.8F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_DIFFUSE, floatBuffer);
bits.forEach(bit -> verifyState(bit.glEnum(), bit.initial(), bit.name() + " Reset State"));
}
@@ -337,8 +347,8 @@ class GLSM_PushPop_UnitTest {
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT, "Color Material Face");
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT, "Color Material Parameter");
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, 1f, "Light Model Local Viewer");
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, 1f, "Light Model Two Side");
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, true, "Light Model Local Viewer");
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, true, "Light Model Two Side");
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, FLOAT_ARRAY_4_POINT_5, "Light Model Ambient");
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SEPARATE_SPECULAR_COLOR, "Light Model Color Control");
verifyLightState(GL11.GL_LIGHT0, GL11.GL_AMBIENT, FLOAT_ARRAY_4_POINT_5, "Light Ambient");
@@ -361,8 +371,8 @@ class GLSM_PushPop_UnitTest {
GLStateManager.glPopAttrib();
verifyState(GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_FRONT_AND_BACK, "Color Material Face - Reset");
verifyState(GL11.GL_COLOR_MATERIAL_PARAMETER, GL11.GL_AMBIENT_AND_DIFFUSE, "Color Material Parameter - Reset");
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, 0f, "Light Model Local Viewer - Reset");
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, 0f, "Light Model Two Side - Reset");
verifyState(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, false, "Light Model Local Viewer - Reset");
verifyState(GL11.GL_LIGHT_MODEL_TWO_SIDE, false, "Light Model Two Side - Reset");
verifyState(GL11.GL_LIGHT_MODEL_AMBIENT, FLOAT_ARRAY_MODEL_AMBIENT_DEFAULT, "Light Model Ambient - Reset");
verifyState(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, GL12.GL_SINGLE_COLOR, "Light Model Color Control - Reset");
verifyLightState(GL11.GL_LIGHT0, GL11.GL_AMBIENT, FLOAT_ARRAY_4_0001, "Light Ambient - Reset");
@@ -124,4 +124,13 @@ public class GLSMUtil {
() -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i)
));
}
public static void verifyMaterialState(int face, int pname, float[] expected, String message) {
GL11.glGetMaterial(face, pname, (FloatBuffer) glFloatBuffer.clear());
GLStateManager.glGetMaterial(face, pname, (FloatBuffer) glsmFloatBuffer.clear());
IntStream.range (0, expected.length).forEach(i -> assertAll(message,
() -> assertEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i),
() -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i)
));
}
}