clean up chunk build outputs and renderer resources after job failures #54

Merged
embeddedt merged 2 commits from rdh/celeritas:thingy into stonecutter 2026-11-24 09:02:00 -05:00
11 changed files with 520 additions and 36 deletions
Showing only changes of commit 384e028b53 - Show all commits

No files matched your search

@@ -1758,6 +1758,44 @@ public abstract class AbstractRasterizer {
return true; return true;
} }
/**
* Span end for an edge that is vertical on screen, at precise x. Span ends sample pixel centres: a left edge
* keeps the first pixel whose centre is at or right of it, {@code ceil(x - 0.5)}, and a right edge the last
* pixel whose centre is strictly left of it, one less. A centre on an edge shared by two polygons then goes to
* exactly one of them, so abutting occluders leave no seam. No polygon reaches a pixel whose centre is outside
* it either, which matters because the test dilation reaches only one pixel past what it tests: an occluder
* rounded outward can close a gap the test would otherwise find.
*/
private static int verticalEdgePixel(int x, boolean left) {
return left
? (x + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS
: (x - PRECISE_PIXEL_CENTER - 1) >> PRECISION_BITS;
}
/**
* Intercept at row zero of a sloped edge through precise {@code (x0, y0)} with 16.16 slope {@code n}, in 20-bit
* fixed point, so that adding {@code step} per row and truncating gives each row's span end under the rule in
* {@link #verticalEdgePixel}.
*
* <p>A shallow edge crosses many pixels within one row, so where in the row it is read matters. A drawn
* occluder reads it at the row centre, the height of the pixel centres it covers. A test reads it at the top
* or bottom of the row, whichever is farther out, so its span holds every pixel centre the polygon passes in
* that row. Reading the edge's line past the edge's own end is still conservative for a test, since the line
* of every edge of a convex polygon lies outside it.
*/
private long slopedEdgeIntercept(int x0, int y0, long n, long step, boolean left) {
// ceil(x - 0.5) is floor(x + 0.5 - ulp) on this grid; the right end is one less
final long bias = left ? 0x7FFFFL : -0x80001L;
if (!dilate) {
return ((long) x0 << 16) - n * (y0 - PRECISE_PIXEL_CENTER) + bias;
}
// stepping from this intercept reads each row's top; its bottom is one step further
final long farthest = left ? Math.min(0, step) : Math.max(0, step);
return ((long) x0 << 16) - n * y0 + farthest + bias;
}
/** Slope and intercept of each non-flat edge of the current quad, in 20-bit fixed point, so bands only step them. */ /** Slope and intercept of each non-flat edge of the current quad, in 20-bit fixed point, so bands only step them. */
private void prepareEdges() { private void prepareEdges() {
final int eventKey = this.eventKey; final int eventKey = this.eventKey;
@@ -1776,16 +1814,17 @@ public abstract class AbstractRasterizer {
final int x0 = data[i]; final int x0 = data[i];
final int y0 = data[i + 1]; final int y0 = data[i + 1];
final int dx = data[i + 2] - x0; final int dx = data[i + 2] - x0;
final boolean left = role == EVENT_0_LEFT;
if (dx == 0) { if (dx == 0) {
edgeStep[e] = 0; edgeStep[e] = 0;
edgeX0[e] = (long) ((x0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; edgeX0[e] = (long) verticalEdgePixel(x0, left) << 20;
} else { } else {
// exact for these magnitudes and far cheaper than a 64-bit integer divide // exact for these magnitudes and far cheaper than a 64-bit integer divide
final long n = (long) ((double) (((long) dx) << 16) / (data[i + 3] - y0)); final long n = (long) ((double) (((long) dx) << 16) / (data[i + 3] - y0));
edgeStep[e] = n << PRECISION_BITS; final long step = n << PRECISION_BITS;
// left edges round up; right edges lose the tie edgeStep[e] = step;
edgeX0[e] = ((long) x0 << 16) - n * y0 + (role == EVENT_0_LEFT ? 0x100000L : 0x7FFFFL); edgeX0[e] = slopedEdgeIntercept(x0, y0, n, step, left);
} }
} }
} }
@@ -1876,13 +1915,13 @@ public abstract class AbstractRasterizer {
if (dx == 0) { if (dx == 0) {
stepOut[emitted] = 0; stepOut[emitted] = 0;
x0Out[emitted] = (long) ((ex0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; x0Out[emitted] = (long) verticalEdgePixel(ex0, left) << 20;
} else { } else {
// exact for these magnitudes and far cheaper than a 64-bit integer divide // exact for these magnitudes and far cheaper than a 64-bit integer divide
final long n = (long) ((double) (((long) dx) << 16) / (ey1 - ey0)); final long n = (long) ((double) (((long) dx) << 16) / (ey1 - ey0));
stepOut[emitted] = n << PRECISION_BITS; final long step = n << PRECISION_BITS;
// left edges round up; right edges lose the tie stepOut[emitted] = step;
x0Out[emitted] = ((long) ex0 << 16) - n * ey0 + (left ? 0x100000L : 0x7FFFFL); x0Out[emitted] = slopedEdgeIntercept(ex0, ey0, n, step, left);
} }
endOut[emitted++] = rowHigh; endOut[emitted++] = rowHigh;
@@ -11,10 +11,16 @@ import org.joml.Matrix4fc;
* @param red the cloud color * @param red the cloud color
* @param range how far clouds are drawn, in blocks * @param range how far clouds are drawn, in blocks
* @param fogEnd the distance at which clouds have faded out completely * @param fogEnd the distance at which clouds have faded out completely
* @param textureSize how many blocks the clouds texture spans before repeating, which sets the cell size
* @param textureOffsetZ how far the clouds texture is shifted along Z, in blocks
*/ */
public record CloudFrame(Matrix4fc modelView, Matrix4fc projection, public record CloudFrame(Matrix4fc modelView, Matrix4fc projection,
double cameraX, double cameraY, double cameraZ, double cameraX, double cameraY, double cameraZ,
float cloudHeight, double ticks, float cloudHeight, double ticks,
float red, float green, float blue, float red, float green, float blue,
boolean fancy, float range, float fogEnd) { boolean fancy, float range, float fogEnd,
float textureSize, float textureOffsetZ) {
/** A 256 px texture makes 12 block cells, like vanilla's fancy clouds. */
public static final float DEFAULT_TEXTURE_SIZE = 3072.0f;
public static final float DEFAULT_TEXTURE_OFFSET_Z = 3.96f;
} }
@@ -64,8 +64,6 @@ public final class CloudRenderer {
// The largest offset that fits in the signed 12-bit cell position // The largest offset that fits in the signed 12-bit cell position
private static final int MAX_RADIUS = 2047; private static final int MAX_RADIUS = 2047;
// A 256 px clouds texture makes 12 block cells
private static final float TEXTURE_SIZE_IN_BLOCKS = 3072.0f;
private static final float CLOUD_THICKNESS = 4.0f; private static final float CLOUD_THICKNESS = 4.0f;
private static final float CLOUD_ALPHA = 0.8f; private static final float CLOUD_ALPHA = 0.8f;
private static final double BLOCKS_PER_TICK = 0.03; private static final double BLOCKS_PER_TICK = 0.03;
@@ -92,7 +90,7 @@ public final class CloudRenderer {
private final GlStateService glState; private final GlStateService glState;
private final CloudTexture texture; private final CloudTexture texture;
private final float cellSizeX, cellSizeZ; private float cellSizeX, cellSizeZ;
private final GlProgram<ShaderInterface> program; private final GlProgram<ShaderInterface> program;
private final GlMutableBuffer faceBuffer; private final GlMutableBuffer faceBuffer;
@@ -125,8 +123,6 @@ public final class CloudRenderer {
public CloudRenderer(CommandList commandList, GlStateService glState, CloudTexture texture) { public CloudRenderer(CommandList commandList, GlStateService glState, CloudTexture texture) {
this.glState = glState; this.glState = glState;
this.texture = texture; this.texture = texture;
this.cellSizeX = TEXTURE_SIZE_IN_BLOCKS / texture.width;
this.cellSizeZ = TEXTURE_SIZE_IN_BLOCKS / texture.height;
this.program = createProgram(); this.program = createProgram();
this.faceBuffer = commandList.createMutableBuffer(); this.faceBuffer = commandList.createMutableBuffer();
@@ -146,13 +142,17 @@ public final class CloudRenderer {
* @return whether there is anything to draw * @return whether there is anything to draw
*/ */
public boolean prepare(CommandList commandList, CloudFrame frame) { public boolean prepare(CommandList commandList, CloudFrame frame) {
double textureWidthBlocks = this.texture.width * this.cellSizeX; float textureSize = frame.textureSize();
double textureHeightBlocks = this.texture.height * this.cellSizeZ; float cellSizeX = textureSize / this.texture.width;
float cellSizeZ = textureSize / this.texture.height;
boolean cellSizeChanged = cellSizeX != this.cellSizeX || cellSizeZ != this.cellSizeZ;
this.cellSizeX = cellSizeX;
this.cellSizeZ = cellSizeZ;
double cloudX = frame.cameraX() + frame.ticks() * BLOCKS_PER_TICK; double cloudX = frame.cameraX() + frame.ticks() * BLOCKS_PER_TICK;
double cloudZ = frame.cameraZ() + 3.96; double cloudZ = frame.cameraZ() + frame.textureOffsetZ();
cloudX -= Math.floor(cloudX / textureWidthBlocks) * textureWidthBlocks; cloudX -= Math.floor(cloudX / textureSize) * textureSize;
cloudZ -= Math.floor(cloudZ / textureHeightBlocks) * textureHeightBlocks; cloudZ -= Math.floor(cloudZ / textureSize) * textureSize;
int cellX = (int) Math.floor(cloudX / this.cellSizeX); int cellX = (int) Math.floor(cloudX / this.cellSizeX);
int cellZ = (int) Math.floor(cloudZ / this.cellSizeZ); int cellZ = (int) Math.floor(cloudZ / this.cellSizeZ);
@@ -188,7 +188,7 @@ public final class CloudRenderer {
int fadeRadius = ((int) Math.ceil(frame.fogEnd() / cellSize) + 1 + 15) & ~15; int fadeRadius = ((int) Math.ceil(frame.fogEnd() / cellSize) + 1 + 15) & ~15;
int radius = Math.min(Math.min(maxRadius, fadeRadius), MAX_RADIUS); int radius = Math.min(Math.min(maxRadius, fadeRadius), MAX_RADIUS);
if (this.needsRebuild || cellX != this.prevCellX || cellZ != this.prevCellZ || radius != this.prevRadius if (this.needsRebuild || cellSizeChanged || cellX != this.prevCellX || cellZ != this.prevCellZ || radius != this.prevRadius
|| cameraPosition != this.prevCameraPosition || insideFaces != this.prevInsideFaces || cameraPosition != this.prevCameraPosition || insideFaces != this.prevInsideFaces
|| frame.fancy() != this.prevFancy) { || frame.fancy() != this.prevFancy) {
this.needsRebuild = false; this.needsRebuild = false;
@@ -0,0 +1,293 @@
package grondag.bitraster;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.RasterOccluder;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.SimpleFrustum;
import org.joml.FrustumIntersection;
import org.joml.Matrix4f;
import org.joml.Vector3d;
import org.joml.Vector4f;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Checks the rasterizer against the exact projected silhouettes of single boxes seen from random cameras.
*
* <p>Drawing and testing are held to pixel centres from opposite sides. A drawn occluder must set no pixel whose
* centre is outside its silhouette, since the test dilation only reaches one pixel past what it tests and any
* such pixel can close a visible gap between two occluders. A tested box must find any clear pixel whose centre
* is inside its silhouette, or a section showing through that pixel is culled.
*/
class OccluderCoverageTest {
/** Slack for the 1/16 pixel vertex snapping and float projection. */
private static final double TOLERANCE = 0.07;
private static final int TRIALS = 400;
/** A random box some distance in front of a random camera, with its projected silhouette in buffer pixels. */
private record Scene(Viewport viewport, int originX, int originY, int originZ, int box, double[][] hull,
float yaw, float pitch) {
RasterOccluder occluder() {
RasterOccluder occluder = new RasterOccluder();
occluder.prepareScene(1, viewport, 128.0f);
return occluder;
}
String describe() {
return String.format("yaw=%.1f pitch=%.1f box %s at %d,%d,%d", yaw, pitch, PackedBox.toString(box), originX, originY, originZ);
}
}
/** Returns null if the box is too close to the camera to project without near clipping. */
private static Scene randomScene(Random random, int trial, int[] lo, int[] hi) {
// every fourth view is level, so box edges that are vertical in the world stay vertical on screen
float yaw = random.nextFloat() * 360.0f;
float pitch = trial % 4 == 0 ? 0.0f : (random.nextFloat() - 0.5f) * 120.0f;
Matrix4f rotation = new Matrix4f().rotateX((float) Math.toRadians(pitch)).rotateY((float) Math.toRadians(yaw));
Matrix4f matrix = new Matrix4f().perspective((float) Math.toRadians(70.0), 16.0f / 9.0f, 0.05f, 512.0f).mul(rotation);
Vector3d camera = new Vector3d(random.nextDouble() * 16, random.nextDouble() * 16, random.nextDouble() * 16);
Viewport viewport = new Viewport(new SimpleFrustum(new FrustumIntersection(matrix)), camera, matrix);
// the section some distance straight ahead
Vector4f forward = new Matrix4f(rotation).invert().transform(new Vector4f(0, 0, -1, 0));
double distance = 24 + (random.nextDouble() * 80);
int originX = (int) Math.floor((camera.x + (forward.x * distance)) / 16) * 16;
int originY = (int) Math.floor((camera.y + (forward.y * distance)) / 16) * 16;
int originZ = (int) Math.floor((camera.z + (forward.z * distance)) / 16) * 16;
int box = PackedBox.pack(lo[0], lo[1], lo[2], hi[0], hi[1], hi[2], PackedBox.RANGE_EXTREME);
RasterOccluder sizing = new RasterOccluder();
sizing.prepareScene(1, viewport, 128.0f);
int width = sizing.bufferWidth(), height = sizing.bufferHeight();
double[][] corners = new double[8][];
for (int c = 0; c < 8; c++) {
Vector4f v = matrix.transform(new Vector4f(
(float) (originX + ((c & 1) != 0 ? hi[0] : lo[0]) - camera.x),
(float) (originY + ((c & 2) != 0 ? hi[1] : lo[1]) - camera.y),
(float) (originZ + ((c & 4) != 0 ? hi[2] : lo[2]) - camera.z), 1.0f));
if (v.w <= 0.1f) {
return null;
}
corners[c] = new double[] { ((v.x / v.w) + 1) * width / 2.0, ((v.y / v.w) + 1) * height / 2.0 };
}
return new Scene(viewport, originX, originY, originZ, box, convexHull(corners), yaw, pitch);
}
private static Scene randomScene(Random random, int trial) {
int[] lo = { random.nextInt(15), random.nextInt(15), random.nextInt(15) };
int[] hi = new int[3];
for (int a = 0; a < 3; a++) {
hi[a] = lo[a] + 1 + random.nextInt(16 - lo[a]);
}
return randomScene(random, trial, lo, hi);
}
@Test
void occludersCoverNoPixelCentreOutsideTheirSilhouette() {
Random random = new Random(1234);
long over = 0, pixels = 0;
double worst = 0;
String example = null;
for (int trial = 0; trial < TRIALS; trial++) {
Scene scene = randomScene(random, trial);
if (scene == null) {
continue;
}
RasterOccluder occluder = scene.occluder();
occluder.occludeSectionAt(scene.originX, scene.originY, scene.originZ, new int[] { scene.box, scene.box });
AbstractRasterizer raster = occluder.raster;
int[] bounds = pixelBounds(scene.hull, raster);
for (int y = bounds[1]; y <= bounds[3]; y++) {
for (int x = bounds[0]; x <= bounds[2]; x++) {
pixels++;
double outside = distanceOutside(scene.hull, x + 0.5, y + 0.5);
if (outside > TOLERANCE && raster.isPixelSet(x, y)) {
over++;
if (outside > worst) {
worst = outside;
example = String.format("%s pixel=(%d,%d) centre %.3f px outside", scene.describe(), x, y, outside);
}
}
}
}
}
assertEquals(0, over, over + " of " + pixels + " pixels set with their centre outside the silhouette; worst " + example);
}
/**
* Covers the whole buffer but one pixel whose centre is inside the box's silhouette; the box must be found
* visible through it. Pixels just inside the silhouette's edge are the ones a misplaced span end loses.
*/
@Test
void testedBoxesFindEveryClearPixelCentreInside() {
Random random = new Random(4321);
long missed = 0, checks = 0;
String example = null;
for (int trial = 0; trial < TRIALS; trial++) {
Scene scene = randomScene(random, trial);
if (scene == null) {
continue;
}
RasterOccluder occluder = scene.occluder();
AbstractRasterizer raster = occluder.raster;
int[] bounds = pixelBounds(scene.hull, raster);
for (int y = bounds[1]; y <= bounds[3]; y++) {
for (int x = bounds[0]; x <= bounds[2]; x++) {
double outside = distanceOutside(scene.hull, x + 0.5, y + 0.5);
// only centres just inside the edge, where a misplaced span end shows
if (outside > -TOLERANCE || outside < -1.0) {
continue;
}
checks++;
Arrays.fill(raster.tiles, -1L);
raster.tiles[raster.tileIndexFromPixelXY(x, y)] &= ~(1L << Indexer.pixelIndex(x, y));
occluder.prepareRegion(scene.originX, scene.originY, scene.originZ, PackedBox.RANGE_EXTREME, 64);
if (!occluder.isBoxVisible(scene.box, 0)) {
missed++;
if (example == null) {
example = String.format("%s pixel=(%d,%d) centre %.3f px inside", scene.describe(), x, y, -outside);
}
}
}
}
}
assertEquals(0, missed, missed + " of " + checks + " clear pixels inside a silhouette were not found; first " + example);
}
/**
* A box drawn as two abutting halves must cover every pixel centre inside the whole box: a centre on the shared
* edge has to land in one half or the other, or every seam between occluder boxes would leak.
*/
@Test
void abuttingOccludersLeaveNoSeam() {
Random random = new Random(5678);
long seams = 0, pixels = 0;
String example = null;
for (int trial = 0; trial < TRIALS; trial++) {
int[] lo = { random.nextInt(14), random.nextInt(14), random.nextInt(14) };
int[] hi = new int[3];
for (int a = 0; a < 3; a++) {
hi[a] = lo[a] + 2 + random.nextInt(15 - lo[a]);
}
Scene scene = randomScene(random, trial, lo, hi);
if (scene == null) {
continue;
}
int axis = random.nextInt(3);
int split = lo[axis] + 1 + random.nextInt(hi[axis] - lo[axis] - 1);
int[] firstHi = hi.clone(), secondLo = lo.clone();
firstHi[axis] = split;
secondLo[axis] = split;
int first = PackedBox.pack(lo[0], lo[1], lo[2], firstHi[0], firstHi[1], firstHi[2], PackedBox.RANGE_EXTREME);
int second = PackedBox.pack(secondLo[0], secondLo[1], secondLo[2], hi[0], hi[1], hi[2], PackedBox.RANGE_EXTREME);
RasterOccluder whole = scene.occluder();
whole.occludeSectionAt(scene.originX, scene.originY, scene.originZ, new int[] { scene.box, scene.box });
RasterOccluder halves = scene.occluder();
halves.occludeSectionAt(scene.originX, scene.originY, scene.originZ, new int[] { scene.box, first, second });
AbstractRasterizer wholeRaster = whole.raster, halvesRaster = halves.raster;
for (int y = 0; y < wholeRaster.pixelHeight; y++) {
for (int x = 0; x < wholeRaster.pixelWidth; x++) {
if (wholeRaster.isPixelSet(x, y)) {
pixels++;
// a centre within the tolerance of the outer silhouette is a near tie that the halves may
// round the other way, since splitting adds a snapped vertex on that outer edge
if (!halvesRaster.isPixelSet(x, y) && distanceOutside(scene.hull, x + 0.5, y + 0.5) < -TOLERANCE) {
seams++;
if (example == null) {
example = String.format("%s split axis %d at %d, pixel=(%d,%d)", scene.describe(), axis, split, x, y);
}
}
}
}
}
}
assertEquals(0, seams, seams + " of " + pixels + " pixels covered by a whole box are missed by its halves; first " + example);
}
/** Pixel rectangle {minX, minY, maxX, maxY} around a silhouette, with a two pixel margin, within the buffer. */
private static int[] pixelBounds(double[][] hull, AbstractRasterizer raster) {
double minX = Arrays.stream(hull).mapToDouble(p -> p[0]).min().orElseThrow();
double maxX = Arrays.stream(hull).mapToDouble(p -> p[0]).max().orElseThrow();
double minY = Arrays.stream(hull).mapToDouble(p -> p[1]).min().orElseThrow();
double maxY = Arrays.stream(hull).mapToDouble(p -> p[1]).max().orElseThrow();
return new int[] {
Math.max(0, (int) minX - 2), Math.max(0, (int) minY - 2),
Math.min(raster.pixelWidth - 1, (int) maxX + 2), Math.min(raster.pixelHeight - 1, (int) maxY + 2)
};
}
/** Distance in pixels from a point to a counter-clockwise convex polygon, positive outside and negative inside. */
private static double distanceOutside(double[][] hull, double px, double py) {
double worst = Double.NEGATIVE_INFINITY;
for (int i = 0; i < hull.length; i++) {
double[] a = hull[i], b = hull[(i + 1) % hull.length];
double ex = b[0] - a[0], ey = b[1] - a[1];
worst = Math.max(worst, -((ex * (py - a[1])) - (ey * (px - a[0]))) / Math.hypot(ex, ey));
}
return worst;
}
/** Andrew's monotone chain; counter-clockwise, without collinear points. */
private static double[][] convexHull(double[][] points) {
double[][] sorted = points.clone();
Arrays.sort(sorted, (p, q) -> p[0] != q[0] ? Double.compare(p[0], q[0]) : Double.compare(p[1], q[1]));
double[][] hull = new double[2 * sorted.length][];
int k = 0;
for (double[] p : sorted) {
while (k >= 2 && cross(hull[k - 2], hull[k - 1], p) <= 0) k--;
hull[k++] = p;
}
for (int i = sorted.length - 2, lower = k + 1; i >= 0; i--) {
while (k >= lower && cross(hull[k - 2], hull[k - 1], sorted[i]) <= 0) k--;
hull[k++] = sorted[i];
}
return Arrays.copyOf(hull, k - 1);
}
private static double cross(double[] o, double[] a, double[] b) {
return ((a[0] - o[0]) * (b[1] - o[1])) - ((a[1] - o[1]) * (b[0] - o[0]));
}
}
@@ -0,0 +1,124 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import grondag.bitraster.PackedBox;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.frustum.SimpleFrustum;
import org.joml.FrustumIntersection;
import org.joml.Matrix4f;
import org.joml.Vector3d;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A section seen only through a thin gap between two occluders at different depths, as where the edges of two
* walls nearly line up on screen.
*
* <p>The camera looks down +Z from {@code x = -e}. A near occluder fills world x in [-16, 0] at z in [32, 48],
* so its silhouette edge on the gap side is its front edge, at tangent {@code e / 32}. A far occluder fills x in
* [1, 16] at z in [64, 80], so its edge on the gap side is its back edge, at tangent {@code (1 + e) / 80}. The
* rays between the two edges pass both occluders and hit a wall section at z in [96, 112] that the occluders
* otherwise hide completely, so the wall is visible and a correct culler must not report it hidden. Moving the
* camera along x changes the gap width, which is {@code 1/80 - 3e/160}.
*/
class RasterOccluderSliverTest {
private static final float FOV_DEGREES = 70.0f;
private static final float ASPECT = 16.0f / 9.0f;
private static final float TEST_DISTANCE = 128.0f;
private static final int[] NEAR_OCCLUDER = section(PackedBox.pack(0, 0, 0, 16, 16, 16, PackedBox.RANGE_EXTREME));
private static final int[] FAR_OCCLUDER = section(PackedBox.pack(1, 0, 0, 16, 16, 16, PackedBox.RANGE_EXTREME));
private static int[] section(int box) {
// data[0] is the renderable bounds and the occluder boxes follow; see SectionVisibilityBuilder
return new int[] { box, box };
}
private static Viewport viewport(double cameraX) {
Matrix4f matrix = new Matrix4f()
.perspective((float) Math.toRadians(FOV_DEGREES), ASPECT, 0.05f, 512.0f)
.lookAlong(0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f);
return new Viewport(new SimpleFrustum(new FrustumIntersection(matrix)), new Vector3d(cameraX, 8.0, 0.0), matrix);
}
/** Width of the gap in tangent units, i.e. on a screen plane one block in front of the camera. */
private static double gapTangent(double e) {
return ((1.0 + e) / 80.0) - (e / 32.0);
}
/** Camera offset that opens a gap of the given width in tangent units. */
private static double offsetForGap(double gapTangent) {
return (1.0 / 80.0 - gapTangent) * 160.0 / 3.0;
}
/** Width of one buffer pixel in tangent units, for the buffer {@link RasterOccluder} sizes for this view. */
private static double pixelTangent() {
RasterOccluder occluder = new RasterOccluder();
occluder.prepareScene(1, viewport(0.0), TEST_DISTANCE);
double halfWidth = ASPECT * Math.tan(Math.toRadians(FOV_DEGREES / 2.0));
return 2.0 * halfWidth / occluder.bufferWidth();
}
private static RasterOccluder.SectionVisibility testWall(double e, boolean drawNear, boolean drawFar) {
Viewport viewport = viewport(-e);
RasterOccluder occluder = new RasterOccluder();
occluder.prepareScene(1, viewport, TEST_DISTANCE);
// both occluders are fewer hops from the camera than the wall, so the search draws them first
if (drawNear) {
occluder.occludeSectionAt(-16, 0, 32, NEAR_OCCLUDER);
}
if (drawFar) {
occluder.occludeSectionAt(0, 0, 64, FAR_OCCLUDER);
}
// camera is in chunk (-1, 0, 0) and the wall in chunk (0, 0, 6)
return occluder.testSection(0, 0, 96, 1 + 36, PackedBox.FULL_BOX);
}
/** The scene itself: with either occluder missing the wall is plainly visible. */
@Test
void wallVisibleWithoutBothOccluders() {
assertEquals(RasterOccluder.SectionVisibility.VISIBLE, testWall(0.6, false, false));
assertEquals(RasterOccluder.SectionVisibility.VISIBLE, testWall(0.6, true, false));
assertEquals(RasterOccluder.SectionVisibility.VISIBLE, testWall(0.6, false, true));
}
/** The scene itself: once the far occluder's edge passes behind the near one, the wall really is hidden. */
@Test
void wallHiddenWhenGapCloses() {
assertTrue(gapTangent(0.9) < 0);
assertEquals(RasterOccluder.SectionVisibility.HIDDEN, testWall(0.9, true, true));
}
/**
* A gap at least a buffer pixel wide always holds a pixel centre, so occluders drawn by pixel-centre sampling
* can never close it, wherever it falls. Narrower gaps can close when no centre falls inside them; that is a
* limit of centre sampling, not tested here.
*/
@Test
void gapOfOnePixelOrMoreStaysOpen() {
double pixel = pixelTangent();
int steps = 64;
List<String> culled = new ArrayList<>();
for (int i = 0; i < steps; i++) {
double pixels = 1.0 + ((double) i / (steps - 1));
double e = offsetForGap(pixels * pixel);
var result = testWall(e, true, true);
if (result != RasterOccluder.SectionVisibility.VISIBLE) {
culled.add(String.format("gap=%.3f px (e=%.4f) -> %s", pixels, e, result));
}
}
assertTrue(culled.isEmpty(), culled.size() + "/" + steps + " gaps of 1-2 buffer pixels culled a visible section:\n"
+ String.join("\n", culled));
}
}
@@ -32,6 +32,9 @@ public class VintageCloudRenderer {
// Vanilla's default cloud range since 1.21.6 // Vanilla's default cloud range since 1.21.6
private static final int CLOUD_RANGE_CHUNKS = 128; private static final int CLOUD_RANGE_CHUNKS = 128;
// Vanilla's fast clouds span 2048 blocks, making 8 block cells, and aren't shifted along Z like fancy clouds
private static final float FAST_TEXTURE_SIZE = 2048.0f;
// Where exponential fog has hidden everything, as exp(-x) < 1/255 // Where exponential fog has hidden everything, as exp(-x) < 1/255
private static final float EXP_FOG_OPAQUE_DEPTH = (float) Math.log(255.0); private static final float EXP_FOG_OPAQUE_DEPTH = (float) Math.log(255.0);
@@ -124,7 +127,9 @@ public class VintageCloudRenderer {
this.projectionMatrix.set(ActiveRenderInfoAccessor.getProjectionMatrix()); this.projectionMatrix.set(ActiveRenderInfoAccessor.getProjectionMatrix());
CloudFrame frame = new CloudFrame(this.modelViewMatrix, this.projectionMatrix, cameraX, cameraY, cameraZ, CloudFrame frame = new CloudFrame(this.modelViewMatrix, this.projectionMatrix, cameraX, cameraY, cameraZ,
world.provider.getCloudHeight(), ticks + partialTicks, red, green, blue, fancy, range, fogEnd); world.provider.getCloudHeight(), ticks + partialTicks, red, green, blue, fancy, range, fogEnd,
fancy ? CloudFrame.DEFAULT_TEXTURE_SIZE : FAST_TEXTURE_SIZE,
fancy ? CloudFrame.DEFAULT_TEXTURE_OFFSET_Z : 0.0f);
RenderDevice.enterManagedCode(); RenderDevice.enterManagedCode();
@@ -25,7 +25,11 @@ public class EntityShadowBatch {
private static final ResourceLocation SHADOW_TEXTURES = new ResourceLocation("textures/misc/shadow.png"); private static final ResourceLocation SHADOW_TEXTURES = new ResourceLocation("textures/misc/shadow.png");
private static final int NO_LIGHT = -1; private static final int NO_LIGHT = -1;
// A POSITION_TEX_COLOR vertex: 3 position floats, 2 texture floats, packed color
private static final int INTS_PER_VERTEX = 6;
private final BufferBuilder buffer = new BufferBuilder(0x4000); private final BufferBuilder buffer = new BufferBuilder(0x4000);
private final int[] quad = new int[4 * INTS_PER_VERTEX];
private final WorldVertexBufferUploader uploader = new WorldVertexBufferUploader(); private final WorldVertexBufferUploader uploader = new WorldVertexBufferUploader();
private final Long2IntOpenHashMap lightCache = new Long2IntOpenHashMap(); private final Long2IntOpenHashMap lightCache = new Long2IntOpenHashMap();
private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
@@ -131,13 +135,25 @@ public class EntityShadowBatch {
float u1 = (float)((x - x1) / 2.0D / (double)size + 0.5D); float u1 = (float)((x - x1) / 2.0D / (double)size + 0.5D);
float v0 = (float)((z - z0) / 2.0D / (double)size + 0.5D); float v0 = (float)((z - z0) / 2.0D / (double)size + 0.5D);
float v1 = (float)((z - z1) / 2.0D / (double)size + 0.5D); float v1 = (float)((z - z1) / 2.0D / (double)size + 0.5D);
float a = (float)alpha; // White with the shadow's alpha, rounded like BufferBuilder.color(float...)
int color = 0x00FFFFFF | ((int)((float)alpha * 255.0F) << 24);
BufferBuilder buffer = this.buffer; this.putVertex(0, x0, surfaceY, z0, u0, v0, color);
buffer.pos(x0, surfaceY, z0).tex(u0, v0).color(1.0F, 1.0F, 1.0F, a).endVertex(); this.putVertex(1, x0, surfaceY, z1, u0, v1, color);
buffer.pos(x0, surfaceY, z1).tex(u0, v1).color(1.0F, 1.0F, 1.0F, a).endVertex(); this.putVertex(2, x1, surfaceY, z1, u1, v1, color);
buffer.pos(x1, surfaceY, z1).tex(u1, v1).color(1.0F, 1.0F, 1.0F, a).endVertex(); this.putVertex(3, x1, surfaceY, z0, u1, v0, color);
buffer.pos(x1, surfaceY, z0).tex(u1, v0).color(1.0F, 1.0F, 1.0F, a).endVertex(); this.buffer.addVertexData(this.quad);
}
private void putVertex(int vertex, double x, double y, double z, float u, float v, int color) {
int[] quad = this.quad;
int i = vertex * INTS_PER_VERTEX;
quad[i] = Float.floatToRawIntBits((float)x);
quad[i + 1] = Float.floatToRawIntBits((float)y);
quad[i + 2] = Float.floatToRawIntBits((float)z);
quad[i + 3] = Float.floatToRawIntBits(u);
quad[i + 4] = Float.floatToRawIntBits(v);
quad[i + 5] = color;
} }
private int getLight(World world, BlockPos pos) { private int getLight(World world, BlockPos pos) {
@@ -145,17 +145,14 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Vin
return true; return true;
} }
// Ensure entities with outlines or nametags are always visible
if (entity.isGlowing() || entity.getAlwaysRenderNameTagForRender()) {
return true;
}
//? if <1.21.2 //? if <1.21.2
AxisAlignedBB box = entity.getRenderBoundingBox(); AxisAlignedBB box = entity.getRenderBoundingBox();
//? if >=1.21.2 //? if >=1.21.2
/*AABB box = renderer.getBoundingBoxForCulling(entity);*/ /*AABB box = renderer.getBoundingBoxForCulling(entity);*/
return this.isBoxVisible(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ); // Entities with outlines or nametags are always visible
return this.isBoxVisible(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ)
|| entity.isGlowing() || entity.getAlwaysRenderNameTagForRender();
} }
private ChunkVertexType chooseVertexType() { private ChunkVertexType chooseVertexType() {
@@ -13,6 +13,9 @@ public interface BlockColorsAccessor {
//? if forge && <1.17 { //? if forge && <1.17 {
/*@Accessor("field_186725_a") /*@Accessor("field_186725_a")
Map<net.minecraftforge.registries.IRegistryDelegate<Block>, net.minecraft.client.color.block.BlockColor> Map<net.minecraftforge.registries.IRegistryDelegate<Block>, net.minecraft.client.color.block.BlockColor>
*///?} else if forge && <1.19 {
/*@Accessor("blockColors")
Map<net.minecraftforge.registries.IRegistryDelegate<Block>, net.minecraft.client.color.block.BlockColor>
*///?} else if forge && <26.1 { *///?} else if forge && <26.1 {
@Accessor("blockColors") @Accessor("blockColors")
Map<net.minecraft.core.Holder.Reference<Block>, net.minecraft.client.color.block.BlockColor> Map<net.minecraft.core.Holder.Reference<Block>, net.minecraft.client.color.block.BlockColor>
@@ -33,8 +33,8 @@ public class ColorProviderRegistry {
//? if (forgelike && <26.1) || >=26.1 { //? if (forgelike && <26.1) || >=26.1 {
for (var entry : providers.entrySet()) { for (var entry : providers.entrySet()) {
var block = entry.getKey() var block = entry.getKey()
/*? if forge && >=1.17 && <26.1 {*/.value()/*?}*/ /*? if forge && >=1.19 && <26.1 {*/.value()/*?}*/
/*? if forge && <1.17 {*//*.get()*//*?}*/; /*? if forge && <1.19 {*//*.get()*//*?}*/;
if (!DefaultColorProviders.isVanillaProvider(entry.getValue())) { if (!DefaultColorProviders.isVanillaProvider(entry.getValue())) {
overridenBlocks.add(block); overridenBlocks.add(block);
} }
@@ -109,7 +109,8 @@ public class ModernCloudRenderer {
boolean fancy = Minecraft.getInstance().options.getCloudsType() == CloudStatus.FANCY; boolean fancy = Minecraft.getInstance().options.getCloudsType() == CloudStatus.FANCY;
CloudFrame frame = new CloudFrame(modelViewMatrix, projectionMatrix, cameraX, cameraY, cameraZ, cloudHeight, CloudFrame frame = new CloudFrame(modelViewMatrix, projectionMatrix, cameraX, cameraY, cameraZ, cloudHeight,
ticks + tickDelta, (float) color.x, (float) color.y, (float) color.z, fancy, range, fogEnd); ticks + tickDelta, (float) color.x, (float) color.y, (float) color.z, fancy, range, fogEnd,
CloudFrame.DEFAULT_TEXTURE_SIZE, CloudFrame.DEFAULT_TEXTURE_OFFSET_Z);
RenderDevice.enterManagedCode(); RenderDevice.enterManagedCode();