rasterized occlusion culling #38

Merged
embeddedt merged 20 commits from rdh/celeritas:raster into stonecutter 2026-09-04 22:15:05 -04:00
13 changed files with 1473 additions and 728 deletions
Showing only changes of commit f947f8f3ab - Show all commits

No files matched your search

+9
View File
@@ -239,3 +239,12 @@ def transformedAttr = Attribute.of("rfgDeobfuscatorTransformed", Boolean)
attribute(transformedAttr, true) attribute(transformedAttr, true)
} }
} }
tasks.register('rasterStats', JavaExec) {
group = 'verification'
classpath = sourceSets.jmh.runtimeClasspath
mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterStatsReport'
maxHeapSize = '1g'
jvmArgs '-Dbitraster.stats=true'
doFirst { if (project.hasProperty('statargs')) args(project.property('statargs').toString().split('\\s+').findAll { !it.isEmpty() }) }
}
@@ -28,8 +28,13 @@ public final class Cameras {
} }
public static Viewport viewport(double x, double y, double z, float yawDegrees, float pitchDegrees, int renderDistance) { public static Viewport viewport(double x, double y, double z, float yawDegrees, float pitchDegrees, int renderDistance) {
return viewport(x, y, z, yawDegrees, pitchDegrees, renderDistance, FOV_DEGREES);
}
public static Viewport viewport(double x, double y, double z, float yawDegrees, float pitchDegrees, int renderDistance,
float fovDegrees) {
Matrix4f matrix = new Matrix4f() Matrix4f matrix = new Matrix4f()
.perspective((float) Math.toRadians(FOV_DEGREES), ASPECT, NEAR_PLANE, farPlane(renderDistance)) .perspective((float) Math.toRadians(fovDegrees), ASPECT, NEAR_PLANE, farPlane(renderDistance))
.rotateX((float) Math.toRadians(pitchDegrees)) .rotateX((float) Math.toRadians(pitchDegrees))
.rotateY((float) Math.toRadians(yawDegrees + 180.0f)); .rotateY((float) Math.toRadians(yawDegrees + 180.0f));
@@ -5,7 +5,8 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.Viewport;
public final class RasterCullReport { public final class RasterCullReport {
private static final int RENDER_DISTANCE = 32; private static final int RENDER_DISTANCE = Integer.getInteger("report.renderDistance", 32);
private static final float FOV = Float.parseFloat(System.getProperty("report.fov", "70"));
private static final int YAW_STEPS = 8; private static final int YAW_STEPS = 8;
private static final WorldType[] WORLDS = { WorldType.SURFACE, WorldType.CAVES }; private static final WorldType[] WORLDS = { WorldType.SURFACE, WorldType.CAVES };
@@ -18,9 +19,14 @@ public final class RasterCullReport {
public static void main(String[] args) { public static void main(String[] args) {
BenchPlatform.ensureInitialized(); BenchPlatform.ensureInitialized();
System.out.printf("%-8s %-8s %10s %10s %8s %10s%n", if (Boolean.getBoolean("report.fovscan")) {
"world", "camera", "baseline", "occluded", "delta", "backtrack"); fovScan();
System.out.println("-".repeat(66)); return;
}
System.out.printf("%-8s %-8s %10s %10s %8s %10s %10s%n",
"world", "camera", "baseline", "occluded", "delta", "backtrack", "buffer");
System.out.println("-".repeat(80));
for (WorldType world : WORLDS) { for (WorldType world : WORLDS) {
var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true, true); var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true, true);
@@ -46,7 +52,7 @@ public final class RasterCullReport {
for (int step = 0; step < YAW_STEPS; step++) { for (int step = 0; step < YAW_STEPS; step++) {
Viewport viewport = Cameras.viewport(8.5, placement.y(), 8.5, Viewport viewport = Cameras.viewport(8.5, placement.y(), 8.5,
(360.0f / YAW_STEPS) * step, placement.pitch(), RENDER_DISTANCE); (360.0f / YAW_STEPS) * step, placement.pitch(), RENDER_DISTANCE, FOV);
var without = new CountingVisitor(); var without = new CountingVisitor();
baselineLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); baselineLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
@@ -66,12 +72,49 @@ public final class RasterCullReport {
double delta = meanBaseline == 0 ? 0.0 double delta = meanBaseline == 0 ? 0.0
: ((meanOccluded - meanBaseline) * 100.0) / meanBaseline; : ((meanOccluded - meanBaseline) * 100.0) / meanBaseline;
System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d%n", world, placement.name(), System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d %10s%n", world, placement.name(),
meanBaseline, meanOccluded, delta, backtracks / YAW_STEPS); meanBaseline, meanOccluded, delta, backtracks / YAW_STEPS, rasterLattice.rasterBufferSize());
} }
} }
} }
/** Sweeps the field of view up and back down and prints the buffer size chosen at each step. */
private static void fovScan() {
var world = new SyntheticWorld(WorldType.SURFACE, RENDER_DISTANCE, true, true);
float searchDistance = world.getSearchDistance();
int numRegions = BenchPlatform.regionManager().getRegionIdsLength();
var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, true);
for (RenderSection section : world.getConstructionOrder()) {
lattice.attach(section);
}
double y = Cameras.surfaceCameraY(0, 0);
int frame = 0;
var line = new StringBuilder("rd=" + RENDER_DISTANCE + " fov sweep 30..130..30:");
int[] fovs = new int[41];
for (int i = 0; i <= 20; i++) {
fovs[i] = 30 + (i * 5);
fovs[40 - i] = fovs[i];
}
for (int i = 0; i < fovs.length; i++) {
int fov = fovs[i];
Viewport viewport = Cameras.viewport(8.5, y, 8.5, Cameras.DEFAULT_YAW, Cameras.DEFAULT_PITCH, RENDER_DISTANCE, fov);
lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance);
lattice.findVisible(new CountingVisitor(), viewport, searchDistance, numRegions, true, true, ++frame);
line.append(' ').append(fov).append(':').append(lattice.rasterBufferSize());
if (i == 20) {
line.append(" |");
}
}
System.out.println(line);
}
private static Placement[] placements() { private static Placement[] placements() {
double surfaceY = Cameras.surfaceCameraY(0, 0); double surfaceY = Cameras.surfaceCameraY(0, 0);
@@ -0,0 +1,102 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench;
import grondag.bitraster.AbstractRasterizer;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.RasterOccluder;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
/**
* Per-frame rasterizer work counters and a test/occlude time split for one world, run with
* {@code -Dbitraster.stats=true} (the {@code rasterStats} Gradle task sets it). Args: world, and optionally
* {@code yscan lo hi} to print visible counts (raster/baseline) per yaw step as the camera height varies.
*/
public final class RasterStatsReport {
private static final int RENDER_DISTANCE = 32;
private static final int YAW_STEPS = 8;
private static final int WARM = 150;
public static void main(String[] args) {
BenchPlatform.ensureInitialized();
WorldType worldType = args.length > 0 ? WorldType.valueOf(args[0]) : WorldType.SURFACE;
var world = new SyntheticWorld(worldType, RENDER_DISTANCE, true, true);
float searchDistance = world.getSearchDistance();
int numRegions = BenchPlatform.regionManager().getRegionIdsLength();
var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, true);
for (RenderSection section : world.getConstructionOrder()) lattice.attach(section);
double y = Cameras.surfaceCameraY(0, 0);
if (args.length > 1 && args[1].equals("yscan")) {
var base = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, false);
for (RenderSection section : world.getConstructionOrder()) base.attach(section);
int f = 0;
double lo = args.length > 2 ? Double.parseDouble(args[2]) : -1.0, hi = args.length > 3 ? Double.parseDouble(args[3]) : 3.0;
for (double dy = lo; dy <= hi; dy += 0.125) {
StringBuilder sb = new StringBuilder(String.format("y=%7.3f ", y + dy));
for (int step = 0; step < YAW_STEPS; step++) {
Viewport v = Cameras.viewport(8.5, y + dy, 8.5, (360.0f / YAW_STEPS) * step, Cameras.DEFAULT_PITCH, RENDER_DISTANCE);
var a = new CountingVisitor(); var b = new CountingVisitor();
base.ensureWindowCovers(v.getChunkCoord(), searchDistance);
base.findVisible(a, v, searchDistance, numRegions, true, true, ++f);
lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance);
lattice.findVisible(b, v, searchDistance, numRegions, true, true, ++f);
sb.append(String.format("%5d/%5d ", b.visible, a.visible));
}
System.out.println(sb);
}
return;
}
Viewport[] ring = Cameras.yawRing(8.5, y, 8.5, YAW_STEPS, Cameras.DEFAULT_PITCH, RENDER_DISTANCE);
int frame = 0;
for (int w = 0; w < WARM; w++) {
for (Viewport v : ring) {
lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance);
lattice.findVisible(new CountingVisitor(), v, searchDistance, numRegions, true, true, ++frame);
}
}
reset();
long visible = 0;
long t0 = System.nanoTime();
for (Viewport v : ring) {
var c = new CountingVisitor();
lattice.ensureWindowCovers(v.getChunkCoord(), searchDistance);
lattice.findVisible(c, v, searchDistance, numRegions, true, true, ++frame);
visible += c.visible;
}
long total = System.nanoTime() - t0;
int n = YAW_STEPS;
System.out.printf("world=%s visible/frame=%d total=%.3fms test=%.3fms occlude=%.3fms%n", worldType, visible / n,
total / 1e6 / n, RasterOccluder.STAT_TEST_NANOS / 1e6 / n, RasterOccluder.STAT_OCCLUDE_NANOS / 1e6 / n);
System.out.printf("sections tested=%d occluded=%d%n", RasterOccluder.STAT_SECTIONS / n,
RasterOccluder.STAT_OCCLUDED_SECTIONS / n);
System.out.printf("draw calls=%d polygons=%d tiles=%d | test calls=%d polygons=%d tiles=%d | eventRows=%d%n",
AbstractRasterizer.STAT_DRAW_CALLS / n, AbstractRasterizer.STAT_DRAW_QUADS / n,
(AbstractRasterizer.STAT_D_INNER + AbstractRasterizer.STAT_D_COVER) / n,
AbstractRasterizer.STAT_TEST_CALLS / n, AbstractRasterizer.STAT_TEST_QUADS / n, AbstractRasterizer.STAT_TEST_TILES / n,
AbstractRasterizer.STAT_EVENT_ROWS / n);
printExtra(n);
System.out.printf("draw noop polygons=%d boxes drawn by range near/mid/far/extreme=%d/%d/%d/%d%n", AbstractRasterizer.STAT_D_NOOP / n,
AbstractRasterizer.STAT_D_RANGE0 / n, AbstractRasterizer.STAT_D_RANGE1 / n, AbstractRasterizer.STAT_D_RANGE2 / n, AbstractRasterizer.STAT_D_RANGE3 / n);
}
private static void printExtra(int n) {
System.out.printf("centerHit=%d near=%d fullbox tests=%d fullbox visible=%d | test: empty=%d inner=%d cover=%d hidden=%d | draw tiles: inner=%d cover=%d%n",
RasterOccluder.STAT_CENTER_HIT / n, RasterOccluder.STAT_NEAR / n, RasterOccluder.STAT_AIR_TESTS / n, RasterOccluder.STAT_AIR_VISIBLE / n,
AbstractRasterizer.STAT_T_EMPTY / n, AbstractRasterizer.STAT_T_INNER / n, AbstractRasterizer.STAT_T_COVER / n, AbstractRasterizer.STAT_T_HIDDEN / n,
AbstractRasterizer.STAT_D_INNER / n, AbstractRasterizer.STAT_D_COVER / n);
}
private static void reset() {
AbstractRasterizer.STAT_D_NOOP = AbstractRasterizer.STAT_D_RANGE0 = AbstractRasterizer.STAT_D_RANGE1 = AbstractRasterizer.STAT_D_RANGE2 = AbstractRasterizer.STAT_D_RANGE3 = 0;
RasterOccluder.STAT_CENTER_HIT = RasterOccluder.STAT_NEAR = RasterOccluder.STAT_AIR_TESTS = RasterOccluder.STAT_AIR_VISIBLE = 0;
AbstractRasterizer.STAT_T_EMPTY = AbstractRasterizer.STAT_T_INNER = AbstractRasterizer.STAT_T_COVER = AbstractRasterizer.STAT_T_HIDDEN = 0;
AbstractRasterizer.STAT_D_INNER = AbstractRasterizer.STAT_D_COVER = 0;
RasterOccluder.STAT_TEST_NANOS = RasterOccluder.STAT_OCCLUDE_NANOS = RasterOccluder.STAT_SECTIONS = RasterOccluder.STAT_OCCLUDED_SECTIONS = 0;
AbstractRasterizer.STAT_DRAW_CALLS = AbstractRasterizer.STAT_DRAW_QUADS = 0;
AbstractRasterizer.STAT_TEST_CALLS = AbstractRasterizer.STAT_TEST_QUADS = AbstractRasterizer.STAT_TEST_TILES = AbstractRasterizer.STAT_EVENT_ROWS = 0;
}
}
File diff suppressed because it is too large. Load diff
@@ -20,10 +20,9 @@ import static grondag.bitraster.Constants.CAMERA_PRECISION_BITS;
import static grondag.bitraster.Constants.CAMERA_PRECISION_UNITY; import static grondag.bitraster.Constants.CAMERA_PRECISION_UNITY;
import static grondag.bitraster.Constants.DOWN; import static grondag.bitraster.Constants.DOWN;
import static grondag.bitraster.Constants.EAST; import static grondag.bitraster.Constants.EAST;
import static grondag.bitraster.Constants.EMPTY_BITS;
import static grondag.bitraster.Constants.NORTH; import static grondag.bitraster.Constants.NORTH;
import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE;
import static grondag.bitraster.Constants.SOUTH; import static grondag.bitraster.Constants.SOUTH;
import static grondag.bitraster.Constants.TILE_COUNT;
import static grondag.bitraster.Constants.UP; import static grondag.bitraster.Constants.UP;
import static grondag.bitraster.Constants.V000; import static grondag.bitraster.Constants.V000;
import static grondag.bitraster.Constants.V001; import static grondag.bitraster.Constants.V001;
@@ -65,6 +64,43 @@ public abstract class BoxOccluder {
private boolean hasNearOccluders = false; private boolean hasNearOccluders = false;
private boolean drawNearOccluders = true; private boolean drawNearOccluders = true;
/**
* Outline of a box as seen from the camera side encoded by the face-visibility outcome: the union of the
* visible faces' quads with their shared edges removed, wound consistently with the quad tables below.
* Drawing or testing this one convex polygon replaces two or three overlapping quads. The quad tables
* remain as the fallback when a corner needs near-plane clipping.
*/
private static final int[][] SILHOUETTES = new int[64][];
static {
SILHOUETTES[UP] = new int[] { V110, V010, V011, V111 };
SILHOUETTES[DOWN] = new int[] { V000, V100, V101, V001 };
SILHOUETTES[EAST] = new int[] { V101, V100, V110, V111 };
SILHOUETTES[WEST] = new int[] { V000, V001, V011, V010 };
SILHOUETTES[NORTH] = new int[] { V100, V000, V010, V110 };
SILHOUETTES[SOUTH] = new int[] { V001, V101, V111, V011 };
SILHOUETTES[UP | EAST] = new int[] { V110, V010, V011, V111, V101, V100 };
SILHOUETTES[UP | WEST] = new int[] { V011, V111, V110, V010, V000, V001 };
SILHOUETTES[UP | NORTH] = new int[] { V010, V011, V111, V110, V100, V000 };
SILHOUETTES[UP | SOUTH] = new int[] { V111, V110, V010, V011, V001, V101 };
SILHOUETTES[DOWN | EAST] = new int[] { V101, V001, V000, V100, V110, V111 };
SILHOUETTES[DOWN | WEST] = new int[] { V000, V100, V101, V001, V011, V010 };
SILHOUETTES[DOWN | NORTH] = new int[] { V100, V101, V001, V000, V010, V110 };
SILHOUETTES[DOWN | SOUTH] = new int[] { V001, V000, V100, V101, V111, V011 };
SILHOUETTES[NORTH | EAST] = new int[] { V100, V000, V010, V110, V111, V101 };
SILHOUETTES[NORTH | WEST] = new int[] { V010, V110, V100, V000, V001, V011 };
SILHOUETTES[SOUTH | EAST] = new int[] { V111, V011, V001, V101, V100, V110 };
SILHOUETTES[SOUTH | WEST] = new int[] { V001, V101, V111, V011, V010, V000 };
SILHOUETTES[UP | EAST | NORTH] = new int[] { V011, V111, V101, V100, V000, V010 };
SILHOUETTES[UP | WEST | NORTH] = new int[] { V111, V110, V100, V000, V001, V011 };
SILHOUETTES[UP | EAST | SOUTH] = new int[] { V010, V011, V001, V101, V100, V110 };
SILHOUETTES[UP | WEST | SOUTH] = new int[] { V110, V010, V000, V001, V101, V111 };
SILHOUETTES[DOWN | EAST | NORTH] = new int[] { V001, V000, V010, V110, V111, V101 };
SILHOUETTES[DOWN | WEST | NORTH] = new int[] { V101, V001, V011, V010, V110, V100 };
SILHOUETTES[DOWN | EAST | SOUTH] = new int[] { V000, V100, V110, V111, V011, V001 };
SILHOUETTES[DOWN | WEST | SOUTH] = new int[] { V100, V101, V111, V011, V010, V000 };
}
public BoxOccluder(AbstractRasterizer raster) { public BoxOccluder(AbstractRasterizer raster) {
this.raster = raster; this.raster = raster;
@@ -944,6 +980,28 @@ public abstract class BoxOccluder {
drawNearOccluders = val; drawNearOccluders = val;
} }
/** Current buffer width in pixels. */
public final int bufferWidth() {
return raster.pixelWidth;
}
/** Current buffer height in pixels. */
public final int bufferHeight() {
return raster.pixelHeight;
}
/**
* Changes the buffer size; call before {@link #prepareScene} since the buffer is discarded.
* @param widthBits tiles across as a power of two, see {@link Constants#DEFAULT_SIZE_BITS}
* @param heightBits tiles down, likewise
*/
public final void resizeBuffer(int widthBits, int heightBits) {
if (widthBits != raster.widthBits() || heightBits != raster.heightBits()) {
raster.resize(widthBits, heightBits);
forceRedraw = true;
}
}
/** /**
* Force update to new version. * Force update to new version.
*/ */
@@ -960,9 +1018,7 @@ public abstract class BoxOccluder {
offsetY = (int) ((originY << CAMERA_PRECISION_BITS) - viewY); offsetY = (int) ((originY << CAMERA_PRECISION_BITS) - viewY);
offsetZ = (int) ((originZ << CAMERA_PRECISION_BITS) - viewZ); offsetZ = (int) ((originZ << CAMERA_PRECISION_BITS) - viewZ);
final Matrix4L mvpMatrix = raster.mvpMatrix; raster.setRegionOffset(offsetX, offsetY, offsetZ);
mvpMatrix.copyFrom(baseMvpMatrix);
mvpMatrix.translate(offsetX, offsetY, offsetZ, CAMERA_PRECISION_BITS);
} }
/** /**
@@ -985,11 +1041,13 @@ public abstract class BoxOccluder {
viewX = Math.round(cameraX * CAMERA_PRECISION_UNITY); viewX = Math.round(cameraX * CAMERA_PRECISION_UNITY);
viewY = Math.round(cameraY * CAMERA_PRECISION_UNITY); viewY = Math.round(cameraY * CAMERA_PRECISION_UNITY);
viewZ = Math.round(cameraZ * CAMERA_PRECISION_UNITY); viewZ = Math.round(cameraZ * CAMERA_PRECISION_UNITY);
raster.setMatrix(baseMvpMatrix);
} }
if (forceRedraw || this.viewVersion != viewVersion) { if (forceRedraw || this.viewVersion != viewVersion) {
this.viewVersion = viewVersion; this.viewVersion = viewVersion;
System.arraycopy(EMPTY_BITS, 0, raster.tiles, 0, TILE_COUNT); raster.clear();
forceRedraw = false; forceRedraw = false;
hasNearOccluders = false; hasNearOccluders = false;
maxSquaredChunkDistance = 0; maxSquaredChunkDistance = 0;
@@ -1066,10 +1124,26 @@ public abstract class BoxOccluder {
// Small to moderate are 80% of elapsed time, doesn't seem to be much variation in time // Small to moderate are 80% of elapsed time, doesn't seem to be much variation in time
//timer.stop(size < 100000); //timer.stop(size < 100000);
//return result; final int[] silhouette = SILHOUETTES[outcome];
if (silhouette != null && raster.setupBoxVertices(silhouette, x0, y0, z0, x1, y1, z1)) {
return raster.isPolygonPartiallyClear(silhouette, silhouette.length);
}
return partiallyClearTests[outcome].apply(x0, y0, z0, x1, y1, z1); return partiallyClearTests[outcome].apply(x0, y0, z0, x1, y1, z1);
} }
/**
* Cheap sufficient test: the centre of a convex box projects inside the box's silhouette, so a clear pixel
* there proves the box visible with one transform. False only means the full test is still needed.
*/
public final boolean isBoxCenterClear(int packedBox) {
final float cx = (PackedBox.x0(packedBox) + PackedBox.x1(packedBox)) * 0.5f;
final float cy = (PackedBox.y0(packedBox) + PackedBox.y1(packedBox)) * 0.5f;
final float cz = (PackedBox.z0(packedBox) + PackedBox.z1(packedBox)) * 0.5f;
return raster.isPointClear(cx, cy, cz);
}
public final boolean isEmptyRegionVisible(int originX, int originY, int originZ, int fuzz) { public final boolean isEmptyRegionVisible(int originX, int originY, int originZ, int fuzz) {
prepareRegion(originX, originY, originZ, 0, 0); prepareRegion(originX, originY, originZ, 0, 0);
return isBoxVisible(PackedBox.FULL_BOX, fuzz); return isBoxVisible(PackedBox.FULL_BOX, fuzz);
@@ -1158,9 +1232,14 @@ public abstract class BoxOccluder {
} }
} }
//timer.start(); final int[] silhouette = SILHOUETTES[outcome];
boxDraws[outcome].apply(x0, y0, z0, x1, y1, z1);
//timer.stop(false); if (silhouette != null && raster.setupBoxVertices(silhouette, x0, y0, z0, x1, y1, z1)) {
raster.drawPolygon(silhouette, silhouette.length);
} else {
// some vertex needs near clipping, which only the quad path handles
boxDraws[outcome].apply(x0, y0, z0, x1, y1, z1);
}
} }
public final void occlude(int[] visData) { public final void occlude(int[] visData) {
@@ -1178,6 +1257,14 @@ public abstract class BoxOccluder {
} }
updateDist = true; updateDist = true;
if (AbstractRasterizer.STATS) {
switch (PackedBox.range(box)) {
case PackedBox.RANGE_NEAR -> AbstractRasterizer.STAT_D_RANGE0++;
case PackedBox.RANGE_MID -> AbstractRasterizer.STAT_D_RANGE1++;
case PackedBox.RANGE_FAR -> AbstractRasterizer.STAT_D_RANGE2++;
default -> AbstractRasterizer.STAT_D_RANGE3++;
}
}
occludeBox(box); occludeBox(box);
} }
@@ -34,44 +34,17 @@ public class Constants {
static final int PRECISE_PIXEL_SIZE = 1 << PRECISION_BITS; static final int PRECISE_PIXEL_SIZE = 1 << PRECISION_BITS;
static final int PRECISE_PIXEL_CENTER = PRECISE_PIXEL_SIZE / 2; static final int PRECISE_PIXEL_CENTER = PRECISE_PIXEL_SIZE / 2;
static final int SCANT_PRECISE_PIXEL_CENTER = PRECISE_PIXEL_CENTER - 1; static final int SCANT_PRECISE_PIXEL_CENTER = PRECISE_PIXEL_CENTER - 1;
// CELERITAS: 8 upstream; 7 gives a 1024px buffer, which matches 2048's culling to within 0.1% at ~1.7x the speed // CELERITAS: the buffer size is chosen per rasterizer and per axis (see AbstractRasterizer.resize); upstream
static final int TILE_WIDTH_BITS = 7; // fixed it at 2048px square.
static final int TILE_WIDTH = 1 << TILE_WIDTH_BITS; /** Occlusion buffer size along one axis in tiles, as a power of two: 6 = 512 px, 7 = 1024 px, 8 = 2048 px. */
static final int TILE_WIDTH_MASK = TILE_WIDTH - 1; public static final int MIN_SIZE_BITS = 6;
public static final int PIXEL_WIDTH = TILE_WIDTH * TILE_PIXEL_DIAMETER; public static final int DEFAULT_SIZE_BITS = 7;
static final int MAX_PIXEL_X = PIXEL_WIDTH - 1; public static final int MAX_SIZE_BITS = 8;
static final int HALF_PIXEL_WIDTH = PIXEL_WIDTH / 2;
static final int PRECISE_WIDTH = PIXEL_WIDTH << PRECISION_BITS;
static final int PRECISE_WIDTH_MAX = PRECISE_WIDTH - 1;
static final int HALF_PRECISE_WIDTH = PRECISE_WIDTH / 2;
/** // CELERITAS: pixels added on every side of a tested polygon so that a visible strip narrower than the pixel
* clamp to this to ensure value + half pixel rounds down to last pixel. // pitch still reaches a sampled pixel centre. One pixel covers centre sampling exactly; occluders are never grown.
*/ static final int TEST_DILATION_PIXELS = 1;
static final int PRECISE_WIDTH_CLAMP = PRECISE_WIDTH - PRECISE_PIXEL_CENTER;
// CELERITAS: 8 upstream. See TILE_WIDTH_BITS
static final int TILE_HEIGHT_BITS = 7;
static final int TILE_HEIGHT = 1 << TILE_HEIGHT_BITS;
static final int TILE_HEIGHT_MASK = (TILE_HEIGHT - 1) << TILE_WIDTH_BITS;
public static final int PIXEL_HEIGHT = TILE_HEIGHT * TILE_PIXEL_DIAMETER;
static final int MAX_PIXEL_Y = PIXEL_HEIGHT - 1;
static final int HALF_PIXEL_HEIGHT = PIXEL_HEIGHT / 2;
static final int PRECISE_HEIGHT = PIXEL_HEIGHT << PRECISION_BITS;
static final int PRECISE_HEIGHT_MAX = PRECISE_HEIGHT - 1;
static final int PRECISE_CLIP_MAX = PRECISE_HEIGHT - PRECISE_PIXEL_CENTER;
static final int HALF_PRECISE_HEIGHT = PRECISE_HEIGHT / 2;
/**
* clamp to this to ensure value + half pixel rounds down to last pixel.
*/
static final int PRECISE_HEIGHT_CLAMP = PRECISE_HEIGHT - PRECISE_PIXEL_CENTER;
static final int GUARD_SIZE = 512 << PRECISION_BITS;
static final int GUARD_MAX = PRECISE_WIDTH + GUARD_SIZE;
static final int GUARD_MIN = -GUARD_SIZE;
static final int CLIP_RANGE = PRECISE_WIDTH + GUARD_SIZE * 2;
static final int CLIP_MASK = ~(CLIP_RANGE - 1);
static final int TILE_COUNT = TILE_WIDTH * TILE_HEIGHT;
static final long[] EMPTY_BITS = new long[TILE_COUNT];
public static final int CAMERA_PRECISION_BITS = 12; public static final int CAMERA_PRECISION_BITS = 12;
static final int CAMERA_PRECISION_UNITY = 1 << CAMERA_PRECISION_BITS; static final int CAMERA_PRECISION_UNITY = 1 << CAMERA_PRECISION_BITS;
static final int CAMERA_PRECISION_CHUNK_MAX = 18 * CAMERA_PRECISION_UNITY; static final int CAMERA_PRECISION_CHUNK_MAX = 18 * CAMERA_PRECISION_UNITY;
@@ -254,7 +227,14 @@ public class Constants {
static final int IDX_DX1 = IDX_DY0 + 1; static final int IDX_DX1 = IDX_DY0 + 1;
static final int IDX_DY1 = IDX_DX1 + 1; static final int IDX_DY1 = IDX_DX1 + 1;
static final int VERTEX_DATA_LENGTH = IDX_DY1 + 1; static final int IDX_EX0 = IDX_DY1 + 1;
static final int IDX_EY0 = IDX_EX0 + 1;
static final int IDX_EX1 = IDX_EY0 + 1;
static final int IDX_EY1 = IDX_EX1 + 1;
static final int IDX_FX0 = IDX_EY1 + 1;
static final int IDX_FY0 = IDX_FX0 + 1;
static final int IDX_FX1 = IDX_FY0 + 1;
static final int IDX_FY1 = IDX_FX1 + 1;
static final int VERTEX_DATA_LENGTH = IDX_FY1 + 1;
static final int EVENT_DATA_LENGTH = PIXEL_HEIGHT * 2;
} }
@@ -18,7 +18,6 @@ package grondag.bitraster;
import static grondag.bitraster.Constants.TILE_AXIS_SHIFT; import static grondag.bitraster.Constants.TILE_AXIS_SHIFT;
import static grondag.bitraster.Constants.TILE_PIXEL_INDEX_MASK; import static grondag.bitraster.Constants.TILE_PIXEL_INDEX_MASK;
import static grondag.bitraster.Constants.TILE_WIDTH_BITS;
abstract class Indexer { abstract class Indexer {
private Indexer() { private Indexer() {
@@ -31,13 +30,7 @@ abstract class Indexer {
return z | ((x & 0b100) << 2) | ((y & 0b100) << 3); return z | ((x & 0b100) << 2) | ((y & 0b100) << 3);
} }
private static int tileIndex(int tileX, int tileY) {
return tileX | (tileY << TILE_WIDTH_BITS);
}
static int tileIndexFromPixelXY(int x, int y) {
return tileIndex(x >>> TILE_AXIS_SHIFT, y >>> TILE_AXIS_SHIFT);
}
static int pixelIndex(int x, int y) { static int pixelIndex(int x, int y) {
return ((y & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (x & TILE_PIXEL_INDEX_MASK); return ((y & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (x & TILE_PIXEL_INDEX_MASK);
@@ -16,31 +16,75 @@
package grondag.bitraster; package grondag.bitraster;
import static grondag.bitraster.Constants.HALF_PRECISE_HEIGHT; import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE;
import static grondag.bitraster.Constants.HALF_PRECISE_WIDTH; import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS;
import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PX;
import static grondag.bitraster.Constants.PV_PY; import static grondag.bitraster.Constants.PV_PY;
import static grondag.bitraster.Constants.PV_X; import static grondag.bitraster.Constants.PV_X;
import static grondag.bitraster.Constants.PV_Y; import static grondag.bitraster.Constants.PV_Y;
public final class OrthoRasterizer extends AbstractRasterizer { public final class OrthoRasterizer extends AbstractRasterizer {
public OrthoRasterizer() {
this(DEFAULT_SIZE_BITS, DEFAULT_SIZE_BITS);
}
public OrthoRasterizer(int widthBits, int heightBits) {
super(widthBits, heightBits);
}
@Override @Override
int prepareBounds(int v0, int v1, int v2, int v3) { int prepareBounds(int v0, int v1, int v2, int v3) {
return prepareBoundsNoClip(v0, v1, v2, v3); return prepareBoundsNoClip(v0, v1, v2, v3);
} }
@Override
boolean setupBoxVertices(int[] corners, int x0, int y0, int z0, int x1, int y1, int z1) {
transformBoxCorners(x0, y0, z0, x1, y1, z1);
final int[] data = vertexData;
final float[] cx = cornerX, cy = cornerY;
for (int baseIndex : corners) {
final int corner = baseIndex / PROJECTED_VERTEX_STRIDE;
final float tx = cx[corner];
final float ty = cy[corner];
data[baseIndex + PV_X] = Float.floatToRawIntBits(tx);
data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty);
data[baseIndex + PV_PX] = Math.round(tx * halfPreciseWidth) + halfPreciseWidth;
data[baseIndex + PV_PY] = Math.round(ty * halfPreciseHeight) + halfPreciseHeight;
}
return true;
}
@Override
boolean isPointClear(float x, float y, float z) {
final float fx = x + offsetX;
final float fy = y + offsetY;
final float fz = z + offsetZ;
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
return isProjectedPointClear(tx, ty, 1f);
}
@Override void setupVertex(final int baseIndex, final int x, final int y, final int z) { @Override void setupVertex(final int baseIndex, final int x, final int y, final int z) {
final int[] data = vertexData; final int[] data = vertexData;
final Matrix4L mvpMatrix = this.mvpMatrix;
final float tx = mvpMatrix.transformVec4X(x, y, z) * Matrix4L.FLOAT_CONVERSION; final float fx = x + offsetX;
final float ty = mvpMatrix.transformVec4Y(x, y, z) * Matrix4L.FLOAT_CONVERSION; final float fy = y + offsetY;
final float fz = z + offsetZ;
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
data[baseIndex + PV_X] = Float.floatToRawIntBits(tx); data[baseIndex + PV_X] = Float.floatToRawIntBits(tx);
data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty); data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty);
final int px = Math.round(tx * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; final int px = Math.round(tx * halfPreciseWidth) + halfPreciseWidth;
final int py = Math.round(ty * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; final int py = Math.round(ty * halfPreciseHeight) + halfPreciseHeight;
data[baseIndex + PV_PX] = px; data[baseIndex + PV_PX] = px;
data[baseIndex + PV_PY] = py; data[baseIndex + PV_PY] = py;
@@ -16,11 +16,10 @@
package grondag.bitraster; package grondag.bitraster;
import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS;
import static grondag.bitraster.Constants.BOUNDS_IN; import static grondag.bitraster.Constants.BOUNDS_IN;
import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL;
import static grondag.bitraster.Constants.EVENT_POSITION_MASK; import static grondag.bitraster.Constants.EVENT_POSITION_MASK;
import static grondag.bitraster.Constants.HALF_PRECISE_HEIGHT;
import static grondag.bitraster.Constants.HALF_PRECISE_WIDTH;
import static grondag.bitraster.Constants.IDX_AX0; import static grondag.bitraster.Constants.IDX_AX0;
import static grondag.bitraster.Constants.IDX_AX1; import static grondag.bitraster.Constants.IDX_AX1;
import static grondag.bitraster.Constants.IDX_AY0; import static grondag.bitraster.Constants.IDX_AY0;
@@ -37,11 +36,8 @@ import static grondag.bitraster.Constants.IDX_DX0;
import static grondag.bitraster.Constants.IDX_DX1; import static grondag.bitraster.Constants.IDX_DX1;
import static grondag.bitraster.Constants.IDX_DY0; import static grondag.bitraster.Constants.IDX_DY0;
import static grondag.bitraster.Constants.IDX_DY1; import static grondag.bitraster.Constants.IDX_DY1;
import static grondag.bitraster.Constants.PRECISE_HEIGHT;
import static grondag.bitraster.Constants.PRECISE_HEIGHT_CLAMP;
import static grondag.bitraster.Constants.PRECISE_WIDTH;
import static grondag.bitraster.Constants.PRECISE_WIDTH_CLAMP;
import static grondag.bitraster.Constants.PRECISION_BITS; import static grondag.bitraster.Constants.PRECISION_BITS;
import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE;
import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PX;
import static grondag.bitraster.Constants.PV_PY; import static grondag.bitraster.Constants.PV_PY;
import static grondag.bitraster.Constants.PV_W; import static grondag.bitraster.Constants.PV_W;
@@ -51,32 +47,96 @@ import static grondag.bitraster.Constants.PV_Z;
import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER; import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER;
public final class PerspectiveRasterizer extends AbstractRasterizer { public final class PerspectiveRasterizer extends AbstractRasterizer {
public PerspectiveRasterizer() {
this(DEFAULT_SIZE_BITS, DEFAULT_SIZE_BITS);
}
public PerspectiveRasterizer(int widthBits, int heightBits) {
super(widthBits, heightBits);
}
/** Holds results of {@link #clipNear(int, int)}. */ /** Holds results of {@link #clipNear(int, int)}. */
private int clipX, clipY; private int clipX, clipY;
@Override void setupVertex(final int baseIndex, final int x, final int y, final int z) { @Override void setupVertex(final int baseIndex, final int x, final int y, final int z) {
final int[] data = vertexData; final int[] data = vertexData;
final Matrix4L mvpMatrix = this.mvpMatrix;
final float tx = mvpMatrix.transformVec4X(x, y, z) * Matrix4L.FLOAT_CONVERSION; final float fx = x + offsetX;
final float ty = mvpMatrix.transformVec4Y(x, y, z) * Matrix4L.FLOAT_CONVERSION; final float fy = y + offsetY;
final float w = mvpMatrix.transformVec4W(x, y, z) * Matrix4L.FLOAT_CONVERSION; final float fz = z + offsetZ;
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
final float tz = m20 * fx + m21 * fy + m22 * fz + m23;
final float w = m30 * fx + m31 * fy + m32 * fz + m33;
data[baseIndex + PV_X] = Float.floatToRawIntBits(tx); data[baseIndex + PV_X] = Float.floatToRawIntBits(tx);
data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty); data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty);
data[baseIndex + PV_Z] = Float.floatToRawIntBits(mvpMatrix.transformVec4Z(x, y, z) * Matrix4L.FLOAT_CONVERSION); data[baseIndex + PV_Z] = Float.floatToRawIntBits(tz);
data[baseIndex + PV_W] = Float.floatToRawIntBits(w); data[baseIndex + PV_W] = Float.floatToRawIntBits(w);
if (w != 0) { if (w != 0) {
final float iw = 1f / w; final float iw = 1f / w;
final int px = Math.round(tx * iw * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; final int px = Math.round(tx * iw * halfPreciseWidth) + halfPreciseWidth;
final int py = Math.round(ty * iw * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; final int py = Math.round(ty * iw * halfPreciseHeight) + halfPreciseHeight;
data[baseIndex + PV_PX] = px; data[baseIndex + PV_PX] = px;
data[baseIndex + PV_PY] = py; data[baseIndex + PV_PY] = py;
} }
} }
@Override
boolean setupBoxVertices(int[] corners, int x0, int y0, int z0, int x1, int y1, int z1) {
transformBoxCorners(x0, y0, z0, x1, y1, z1);
final int[] data = vertexData;
final float[] cx = cornerX, cy = cornerY, cz = cornerZ, cw = cornerW;
boolean unclipped = true;
for (int baseIndex : corners) {
final int corner = baseIndex / PROJECTED_VERTEX_STRIDE;
final float tx = cx[corner];
final float ty = cy[corner];
final float tz = cz[corner];
final float w = cw[corner];
data[baseIndex + PV_X] = Float.floatToRawIntBits(tx);
data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty);
data[baseIndex + PV_Z] = Float.floatToRawIntBits(tz);
data[baseIndex + PV_W] = Float.floatToRawIntBits(w);
// same acceptance as needsNearClip
if (w > 0 && tz > 0 && tz <= w) {
final float iw = 1f / w;
data[baseIndex + PV_PX] = Math.round(tx * iw * halfPreciseWidth) + halfPreciseWidth;
data[baseIndex + PV_PY] = Math.round(ty * iw * halfPreciseHeight) + halfPreciseHeight;
} else {
unclipped = false;
}
}
return unclipped;
}
@Override
boolean isPointClear(float x, float y, float z) {
final float fx = x + offsetX;
final float fy = y + offsetY;
final float fz = z + offsetZ;
final float w = m30 * fx + m31 * fy + m32 * fz + m33;
// behind the eye; callers only ask about points well past the near plane
if (w <= 0) {
return false;
}
final float tx = m00 * fx + m01 * fy + m02 * fz + m03;
final float ty = m10 * fx + m11 * fy + m12 * fz + m13;
return isProjectedPointClear(tx, ty, 1f / w);
}
private void clipNear(int internal, int external) { private void clipNear(int internal, int external) {
final int[] data = vertexData; final int[] data = vertexData;
@@ -102,8 +162,8 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
final float w = (intW + (extW - intW) * wt); final float w = (intW + (extW - intW) * wt);
final float iw = 1f / w; final float iw = 1f / w;
clipX = Math.round(iw * x * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; clipX = Math.round(iw * x * halfPreciseWidth) + halfPreciseWidth;
clipY = Math.round(iw * y * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; clipY = Math.round(iw * y * halfPreciseHeight) + halfPreciseHeight;
} }
@Override @Override
@@ -230,11 +290,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
maxY = dy0; maxY = dy0;
} }
if (maxY <= 0 || minY >= PRECISE_HEIGHT) { if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
if (maxX <= 0 || minX >= PRECISE_WIDTH) { if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
@@ -242,11 +302,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minX = 0; minX = 0;
} }
if (maxX >= PRECISE_WIDTH_CLAMP) { if (maxX >= preciseWidthClamp) {
maxX = PRECISE_WIDTH_CLAMP; maxX = preciseWidthClamp;
if (minX > PRECISE_WIDTH_CLAMP) { if (minX > preciseWidthClamp) {
minX = PRECISE_WIDTH_CLAMP; minX = preciseWidthClamp;
} }
} }
@@ -254,11 +314,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minY = 0; minY = 0;
} }
if (maxY >= PRECISE_HEIGHT_CLAMP) { if (maxY >= preciseHeightClamp) {
maxY = PRECISE_HEIGHT_CLAMP; maxY = preciseHeightClamp;
if (minY > PRECISE_HEIGHT_CLAMP) { if (minY > preciseHeightClamp) {
minY = PRECISE_HEIGHT_CLAMP; minY = preciseHeightClamp;
} }
} }
@@ -391,11 +451,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
maxY = dy0; maxY = dy0;
} }
if (maxY <= 0 || minY >= PRECISE_HEIGHT) { if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
if (maxX <= 0 || minX >= PRECISE_WIDTH) { if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
@@ -403,11 +463,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minX = 0; minX = 0;
} }
if (maxX >= PRECISE_WIDTH_CLAMP) { if (maxX >= preciseWidthClamp) {
maxX = PRECISE_WIDTH_CLAMP; maxX = preciseWidthClamp;
if (minX > PRECISE_WIDTH_CLAMP) { if (minX > preciseWidthClamp) {
minX = PRECISE_WIDTH_CLAMP; minX = preciseWidthClamp;
} }
} }
@@ -415,11 +475,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minY = 0; minY = 0;
} }
if (maxY >= PRECISE_HEIGHT_CLAMP) { if (maxY >= preciseHeightClamp) {
maxY = PRECISE_HEIGHT_CLAMP; maxY = preciseHeightClamp;
if (minY > PRECISE_HEIGHT_CLAMP) { if (minY > preciseHeightClamp) {
minY = PRECISE_HEIGHT_CLAMP; minY = preciseHeightClamp;
} }
} }
@@ -541,11 +601,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
maxY = dy0; maxY = dy0;
} }
if (maxY <= 0 || minY >= PRECISE_HEIGHT) { if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
if (maxX <= 0 || minX >= PRECISE_WIDTH) { if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
@@ -553,11 +613,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minX = 0; minX = 0;
} }
if (maxX >= PRECISE_WIDTH_CLAMP) { if (maxX >= preciseWidthClamp) {
maxX = PRECISE_WIDTH_CLAMP; maxX = preciseWidthClamp;
if (minX > PRECISE_WIDTH_CLAMP) { if (minX > preciseWidthClamp) {
minX = PRECISE_WIDTH_CLAMP; minX = preciseWidthClamp;
} }
} }
@@ -565,11 +625,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minY = 0; minY = 0;
} }
if (maxY >= PRECISE_HEIGHT_CLAMP) { if (maxY >= preciseHeightClamp) {
maxY = PRECISE_HEIGHT_CLAMP; maxY = preciseHeightClamp;
if (minY > PRECISE_HEIGHT_CLAMP) { if (minY > preciseHeightClamp) {
minY = PRECISE_HEIGHT_CLAMP; minY = preciseHeightClamp;
} }
} }
@@ -677,11 +737,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
maxY = dy0; maxY = dy0;
} }
if (maxY <= 0 || minY >= PRECISE_HEIGHT) { if (maxY <= 0 || minY >= preciseHeight) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
if (maxX <= 0 || minX >= PRECISE_WIDTH) { if (maxX <= 0 || minX >= preciseWidth) {
return BOUNDS_OUTSIDE_OR_TOO_SMALL; return BOUNDS_OUTSIDE_OR_TOO_SMALL;
} }
@@ -689,11 +749,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minX = 0; minX = 0;
} }
if (maxX >= PRECISE_WIDTH_CLAMP) { if (maxX >= preciseWidthClamp) {
maxX = PRECISE_WIDTH_CLAMP; maxX = preciseWidthClamp;
if (minX > PRECISE_WIDTH_CLAMP) { if (minX > preciseWidthClamp) {
minX = PRECISE_WIDTH_CLAMP; minX = preciseWidthClamp;
} }
} }
@@ -701,11 +761,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer {
minY = 0; minY = 0;
} }
if (maxY >= PRECISE_HEIGHT_CLAMP) { if (maxY >= preciseHeightClamp) {
maxY = PRECISE_HEIGHT_CLAMP; maxY = preciseHeightClamp;
if (minY > PRECISE_HEIGHT_CLAMP) { if (minY > preciseHeightClamp) {
minY = PRECISE_HEIGHT_CLAMP; minY = preciseHeightClamp;
} }
} }
@@ -192,7 +192,7 @@ public class OcclusionCuller {
this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null; this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null;
if (this.rasterActive) { if (this.rasterActive) {
this.rasterOccluder.prepareScene(frame, viewport); this.rasterOccluder.prepareScene(frame, viewport, searchDistance);
} }
this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame); this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame);
@@ -365,9 +365,7 @@ public class OcclusionCuller {
boolean hasGeometry = boolean hasGeometry =
(PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0; (PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0;
var section = this.lattice.latticeSection[idx]; int[] data = this.lattice.occluderData[idx];
var built = section != null ? section.getBuiltContext() : null;
int[] data = built != null ? built.occluderBoxes : null;
int bounds = data != null ? OccluderBoxBuilder.bounds(data) : PackedBox.FULL_BOX; int bounds = data != null ? OccluderBoxBuilder.bounds(data) : PackedBox.FULL_BOX;
@@ -375,12 +373,18 @@ public class OcclusionCuller {
RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds); RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds);
if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && data != null) { if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && data != null) {
occluder.occlude(data); occluder.occludeSection(data);
} }
return result; return result;
} }
/** Current raster buffer size as {@code width x height} in pixels, or null when the raster is off. */
public String rasterBufferSize() {
return this.rasterOccluder == null ? null
: this.rasterOccluder.bufferWidth() + "x" + this.rasterOccluder.bufferHeight();
}
public int rasterBacktrackCount() { public int rasterBacktrackCount() {
return this.rasterOccluder == null ? 0 : this.rasterOccluder.backtrackCount(); return this.rasterOccluder == null ? 0 : this.rasterOccluder.backtrackCount();
} }
@@ -1,6 +1,8 @@
package org.embeddedt.embeddium.impl.render.chunk.occlusion; package org.embeddedt.embeddium.impl.render.chunk.occlusion;
import grondag.bitraster.AbstractRasterizer;
import grondag.bitraster.BoxOccluder; import grondag.bitraster.BoxOccluder;
import grondag.bitraster.Constants;
import grondag.bitraster.Matrix4L; import grondag.bitraster.Matrix4L;
import grondag.bitraster.PackedBox; import grondag.bitraster.PackedBox;
import grondag.bitraster.PerspectiveRasterizer; import grondag.bitraster.PerspectiveRasterizer;
@@ -11,11 +13,12 @@ public final class RasterOccluder extends BoxOccluder {
/** Sections this close are drawn but never tested, since they're almost always visible and most costly to test */ /** Sections this close are drawn but never tested, since they're almost always visible and most costly to test */
public static final int NEAR_SQUARED_CHUNK_DIST = 3; public static final int NEAR_SQUARED_CHUNK_DIST = 3;
/** Beyond 7 chunks, expand tests by a block to absorb rasterization error. From canvas's trial and error. */
private static final int FUZZ_SQUARED_CHUNK_DIST = 7 * 7;
private int backtrackCount; private int backtrackCount;
/** Work counters for benchmarks; only maintained when {@link AbstractRasterizer#STATS} is set. */
public static long STAT_CENTER_HIT, STAT_AIR_TESTS, STAT_AIR_VISIBLE, STAT_NEAR;
public static long STAT_TEST_NANOS, STAT_OCCLUDE_NANOS, STAT_SECTIONS, STAT_OCCLUDED_SECTIONS;
public enum SectionVisibility { public enum SectionVisibility {
/** nothing of the section is visible, and nothing behind it can be reached through it */ /** nothing of the section is visible, and nothing behind it can be reached through it */
HIDDEN, HIDDEN,
@@ -45,7 +48,7 @@ public final class RasterOccluder extends BoxOccluder {
* camera translation, so it is supplied as the projection with an identity model matrix; * camera translation, so it is supplied as the projection with an identity model matrix;
* {@link #prepareRegion} applies the camera-relative offset per section. * {@link #prepareRegion} applies the camera-relative offset per section.
*/ */
public void prepareScene(int viewVersion, Viewport viewport) { public void prepareScene(int viewVersion, Viewport viewport, float searchDistance) {
Matrix4fc vpMatrix = viewport.getVpMatrix(); Matrix4fc vpMatrix = viewport.getVpMatrix();
if (vpMatrix == null) { if (vpMatrix == null) {
@@ -56,17 +59,111 @@ public final class RasterOccluder extends BoxOccluder {
this.backtrackCount = 0; this.backtrackCount = 0;
chooseBufferSize(vpMatrix, searchDistance);
invalidate(); invalidate();
prepareScene(viewVersion, transform.x, transform.y, transform.z, prepareScene(viewVersion, transform.x, transform.y, transform.z,
Matrix4L::loadIdentity, m -> RasterMatrices.copy(vpMatrix, m)); Matrix4L::loadIdentity, m -> RasterMatrices.copy(vpMatrix, m));
} }
/**
* Sizes each axis of the buffer so that a block at the search distance spans at least one pixel along it,
* which is what keeps a one-block gap between occluders from closing under pixel-centre sampling. The
* projection scale of an axis is the length of the matching row of the view-projection matrix: for a
* perspective matrix those rows are {@code (1/(aspect tan(fov/2)), 0, 0, 0)} and {@code (0, 1/tan(fov/2), 0, 0)},
* and the camera rotation they are multiplied by preserves length. Bobbing folded into the matrix adds a
* rotation and a translation, neither of which changes that. The axes differ by the aspect ratio, so a
* widescreen view needs a wider buffer than it is tall.
*
* <p>An axis only grows when the current buffer falls short and only shrinks when the next size down
* would still have a quarter margin, so field-of-view animation cannot thrash it.
*/
private void chooseBufferSize(Matrix4fc vp, float searchDistance) {
// orthographic or degenerate matrices have no perspective row; keep whatever we have
float perspectiveRow = (float) Math.sqrt((vp.m03() * vp.m03()) + (vp.m13() * vp.m13()) + (vp.m23() * vp.m23()));
if (!(perspectiveRow > 0.5f) || !(searchDistance > 0)) {
return;
}
float scaleX = (float) Math.sqrt((vp.m00() * vp.m00()) + (vp.m10() * vp.m10()) + (vp.m20() * vp.m20()));
float scaleY = (float) Math.sqrt((vp.m01() * vp.m01()) + (vp.m11() * vp.m11()) + (vp.m21() * vp.m21()));
if (!(scaleX > 0) || !(scaleY > 0)) {
return;
}
// pixels per block at distance d along an axis is size * scale / (2d); require at least one
int widthBits = chooseAxisBits(bufferWidth(), (2.0f * searchDistance) / scaleX);
int heightBits = chooseAxisBits(bufferHeight(), (2.0f * searchDistance) / scaleY);
resizeBuffer(widthBits, heightBits);
}
private static int chooseAxisBits(int currentPixels, float requiredPixels) {
int current = Integer.numberOfTrailingZeros(currentPixels) - 3;
if (requiredPixels > currentPixels) {
int bits = current;
while (bits < Constants.MAX_SIZE_BITS && (8 << bits) < requiredPixels) {
bits++;
}
return bits;
}
if (current > Constants.MIN_SIZE_BITS && requiredPixels * SHRINK_MARGIN <= (currentPixels >> 1)) {
return current - 1;
}
return current;
}
/** The next size down must satisfy the requirement with this much to spare before we shrink to it. */
private static final float SHRINK_MARGIN = 1.25f;
/** /**
* tests the tight bounds of what the section draws first. a section whose geometry is hidden * tests the tight bounds of what the section draws first. a section whose geometry is hidden
* may still have unoccluded empty space, so a second test decides whether traversal continues. * may still have unoccluded empty space, so a second test decides whether traversal continues.
* must run before occlude(), or a section would occlude itself. * must run before occlude(), or a section would occlude itself.
*/ */
public SectionVisibility testSection(int originX, int originY, int originZ, int squaredChunkDist, int bounds) { public SectionVisibility testSection(int originX, int originY, int originZ, int squaredChunkDist, int bounds) {
if (!AbstractRasterizer.STATS) {
return testSection0(originX, originY, originZ, squaredChunkDist, bounds);
}
long t0 = System.nanoTime();
try {
STAT_SECTIONS++;
var result = testSection0(originX, originY, originZ, squaredChunkDist, bounds);
if (squaredChunkDist <= NEAR_SQUARED_CHUNK_DIST) {
STAT_NEAR++;
} else if (bounds == PackedBox.FULL_BOX) {
STAT_AIR_TESTS++;
if (result == SectionVisibility.VISIBLE) STAT_AIR_VISIBLE++;
}
return result;
} finally {
STAT_TEST_NANOS += System.nanoTime() - t0;
}
}
/** Draws the section's occluder boxes for the region prepared by the last {@link #testSection}. */
public void occludeSection(int[] data) {
if (!AbstractRasterizer.STATS) {
occlude(data);
return;
}
long t0 = System.nanoTime();
STAT_OCCLUDED_SECTIONS++;
occlude(data);
STAT_OCCLUDE_NANOS += System.nanoTime() - t0;
}
private SectionVisibility testSection0(int originX, int originY, int originZ, int squaredChunkDist, int bounds) {
prepareRegion(originX, originY, originZ, prepareRegion(originX, originY, originZ,
PackedBox.rangeFromSquareChunkDist(squaredChunkDist), squaredChunkDist); PackedBox.rangeFromSquareChunkDist(squaredChunkDist), squaredChunkDist);
@@ -74,9 +171,13 @@ public final class RasterOccluder extends BoxOccluder {
return SectionVisibility.VISIBLE; return SectionVisibility.VISIBLE;
} }
int fuzz = squaredChunkDist >= FUZZ_SQUARED_CHUNK_DIST ? 1 : 0; if (isBoxCenterClear(bounds)) {
if (AbstractRasterizer.STATS) STAT_CENTER_HIT++;
return SectionVisibility.VISIBLE;
}
if (isBoxVisible(bounds, fuzz)) { // tests are dilated by a pixel inside the rasterizer, so no world-space fuzz is needed
if (isBoxVisible(bounds, 0)) {
return SectionVisibility.VISIBLE; return SectionVisibility.VISIBLE;
} }
@@ -85,7 +186,7 @@ public final class RasterOccluder extends BoxOccluder {
} }
// only worth asking when the bounds were tighter than the section itself // only worth asking when the bounds were tighter than the section itself
if (bounds != PackedBox.FULL_BOX && isBoxVisible(PackedBox.FULL_BOX, fuzz)) { if (bounds != PackedBox.FULL_BOX && (isBoxCenterClear(PackedBox.FULL_BOX) || isBoxVisible(PackedBox.FULL_BOX, 0))) {
return SectionVisibility.TRAVERSABLE; return SectionVisibility.TRAVERSABLE;
} }
@@ -137,6 +137,12 @@ public final class SectionLattice {
long[] shadowVisitState; long[] shadowVisitState;
long[] sectionMeta; long[] sectionMeta;
int[] regionOfCell; int[] regionOfCell;
/**
* Per-cell occluder data ({@code BuiltRenderSectionData.occluderBoxes}) mirrored here so the raster test
* does not chase section and build-data pointers for every cell it visits. Null when absent.
*/
int[][] occluderData;
RenderSection[] latticeSection; RenderSection[] latticeSection;
// Queue entries ((packedLocalXYZ << 32) | latticeIndex) of the cells the last main search reported visible, in // Queue entries ((packedLocalXYZ << 32) | latticeIndex) of the cells the last main search reported visible, in
@@ -272,6 +278,7 @@ public final class SectionLattice {
long previous = this.sectionMeta[idx]; long previous = this.sectionMeta[idx];
this.sectionMeta[idx] = packedMetadata; this.sectionMeta[idx] = packedMetadata;
this.occluderData[idx] = occluderDataOf(this.latticeSection[idx]);
return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0;
} }
@@ -463,6 +470,10 @@ public final class SectionLattice {
return this.snapshot(this.visitState, this.mainSnapshotBuffers); return this.snapshot(this.visitState, this.mainSnapshotBuffers);
} }
public String rasterBufferSize() {
return this.culler.rasterBufferSize();
}
public int rasterBacktrackCount() { public int rasterBacktrackCount() {
return this.culler.rasterBacktrackCount(); return this.culler.rasterBacktrackCount();
} }
@@ -535,6 +546,7 @@ public final class SectionLattice {
this.sectionMeta = new long[slots]; this.sectionMeta = new long[slots];
this.regionOfCell = new int[slots]; this.regionOfCell = new int[slots];
this.latticeSection = new RenderSection[slots]; this.latticeSection = new RenderSection[slots];
this.occluderData = new int[slots][];
// Existing coordinates are no longer valid after resizing; the next // Existing coordinates are no longer valid after resizing; the next
// ensureWindowCovers must rebase and reinstall every attached section. // ensureWindowCovers must rebase and reinstall every attached section.
@@ -553,6 +565,7 @@ public final class SectionLattice {
Arrays.fill(this.sectionMeta, VisibilityEncoding.NULL); Arrays.fill(this.sectionMeta, VisibilityEncoding.NULL);
Arrays.fill(this.regionOfCell, -1); Arrays.fill(this.regionOfCell, -1);
Arrays.fill(this.latticeSection, null); Arrays.fill(this.latticeSection, null);
Arrays.fill(this.occluderData, null);
this.baseX = newBaseX; this.baseX = newBaseX;
this.baseZ = newBaseZ; this.baseZ = newBaseZ;
@@ -632,6 +645,7 @@ public final class SectionLattice {
System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len); System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len);
System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len); System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len);
System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len);
System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, len);
} }
/** /**
@@ -665,6 +679,7 @@ public final class SectionLattice {
System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, runLen); System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, runLen);
System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen); System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen);
System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen);
System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, runLen);
} }
} }
@@ -750,6 +765,7 @@ public final class SectionLattice {
this.sectionMeta[idx] = VisibilityEncoding.NULL; this.sectionMeta[idx] = VisibilityEncoding.NULL;
this.regionOfCell[idx] = -1; this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null; this.latticeSection[idx] = null;
this.occluderData[idx] = null;
RenderSection section = this.sections.get( RenderSection section = this.sections.get(
PositionUtil.packSection(worldX, this.baseY + ly, worldZ)); PositionUtil.packSection(worldX, this.baseY + ly, worldZ));
@@ -797,6 +813,11 @@ public final class SectionLattice {
// Install only into the interior. An attached section outside the current // Install only into the interior. An attached section outside the current
// window remains in sections and is picked up by a later rebase. // window remains in sections and is picked up by a later rebase.
private static int @Nullable [] occluderDataOf(@Nullable RenderSection section) {
var built = section != null ? section.getBuiltContext() : null;
return built != null ? built.occluderBoxes : null;
}
private void install(RenderSection section) { private void install(RenderSection section) {
if (this.visitState == null) { if (this.visitState == null) {
return; return;
@@ -815,6 +836,7 @@ public final class SectionLattice {
this.latticeSection[idx] = section; this.latticeSection[idx] = section;
this.regionOfCell[idx] = section.getRegion().getId(); this.regionOfCell[idx] = section.getRegion().getId();
this.sectionMeta[idx] = section.getPackedMetadata(); this.sectionMeta[idx] = section.getPackedMetadata();
this.occluderData[idx] = occluderDataOf(section);
this.installedCount++; this.installedCount++;
} }
@@ -834,6 +856,7 @@ public final class SectionLattice {
this.sectionMeta[idx] = VisibilityEncoding.NULL; this.sectionMeta[idx] = VisibilityEncoding.NULL;
this.regionOfCell[idx] = -1; this.regionOfCell[idx] = -1;
this.latticeSection[idx] = null; this.latticeSection[idx] = null;
this.occluderData[idx] = null;
this.installedCount--; this.installedCount--;
} }
} }