From 706e69884b645636c43fff00d0b9115e9016b6da Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 1 Sep 2026 17:45:21 -0400 Subject: [PATCH 01/20] vendor bitraster --- .../grondag/bitraster/AbstractRasterizer.java | 1535 +++++++++++++++++ .../java/grondag/bitraster/BoxOccluder.java | 1203 +++++++++++++ .../java/grondag/bitraster/Constants.java | 258 +++ .../main/java/grondag/bitraster/Indexer.java | 64 + .../src/main/java/grondag/bitraster/LICENSE | 201 +++ .../main/java/grondag/bitraster/Matrix4L.java | 383 ++++ .../java/grondag/bitraster/MicroTimer.java | 120 ++ .../grondag/bitraster/OrthoRasterizer.java | 48 + .../java/grondag/bitraster/PackedBox.java | 89 + .../bitraster/PerspectiveRasterizer.java | 755 ++++++++ .../src/main/java/grondag/bitraster/Util.java | 38 + 11 files changed, 4694 insertions(+) create mode 100644 common/src/main/java/grondag/bitraster/AbstractRasterizer.java create mode 100644 common/src/main/java/grondag/bitraster/BoxOccluder.java create mode 100644 common/src/main/java/grondag/bitraster/Constants.java create mode 100644 common/src/main/java/grondag/bitraster/Indexer.java create mode 100644 common/src/main/java/grondag/bitraster/LICENSE create mode 100644 common/src/main/java/grondag/bitraster/Matrix4L.java create mode 100644 common/src/main/java/grondag/bitraster/MicroTimer.java create mode 100644 common/src/main/java/grondag/bitraster/OrthoRasterizer.java create mode 100644 common/src/main/java/grondag/bitraster/PackedBox.java create mode 100644 common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java create mode 100644 common/src/main/java/grondag/bitraster/Util.java diff --git a/common/src/main/java/grondag/bitraster/AbstractRasterizer.java b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java new file mode 100644 index 000000000..e7b0bc818 --- /dev/null +++ b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java @@ -0,0 +1,1535 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +import static grondag.bitraster.Constants.BOUNDS_IN; +import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; +import static grondag.bitraster.Constants.EDGE_BOTTOM; +import static grondag.bitraster.Constants.EDGE_POINT; +import static grondag.bitraster.Constants.EDGE_TOP; +import static grondag.bitraster.Constants.EVENT_0123_FFFF; +import static grondag.bitraster.Constants.EVENT_0123_FFFL; +import static grondag.bitraster.Constants.EVENT_0123_FFFR; +import static grondag.bitraster.Constants.EVENT_0123_FFLF; +import static grondag.bitraster.Constants.EVENT_0123_FFLL; +import static grondag.bitraster.Constants.EVENT_0123_FFLR; +import static grondag.bitraster.Constants.EVENT_0123_FFRF; +import static grondag.bitraster.Constants.EVENT_0123_FFRL; +import static grondag.bitraster.Constants.EVENT_0123_FFRR; +import static grondag.bitraster.Constants.EVENT_0123_FLFF; +import static grondag.bitraster.Constants.EVENT_0123_FLFL; +import static grondag.bitraster.Constants.EVENT_0123_FLFR; +import static grondag.bitraster.Constants.EVENT_0123_FLLF; +import static grondag.bitraster.Constants.EVENT_0123_FLLL; +import static grondag.bitraster.Constants.EVENT_0123_FLLR; +import static grondag.bitraster.Constants.EVENT_0123_FLRF; +import static grondag.bitraster.Constants.EVENT_0123_FLRL; +import static grondag.bitraster.Constants.EVENT_0123_FLRR; +import static grondag.bitraster.Constants.EVENT_0123_FRFF; +import static grondag.bitraster.Constants.EVENT_0123_FRFL; +import static grondag.bitraster.Constants.EVENT_0123_FRFR; +import static grondag.bitraster.Constants.EVENT_0123_FRLF; +import static grondag.bitraster.Constants.EVENT_0123_FRLL; +import static grondag.bitraster.Constants.EVENT_0123_FRLR; +import static grondag.bitraster.Constants.EVENT_0123_FRRF; +import static grondag.bitraster.Constants.EVENT_0123_FRRL; +import static grondag.bitraster.Constants.EVENT_0123_FRRR; +import static grondag.bitraster.Constants.EVENT_0123_LFFF; +import static grondag.bitraster.Constants.EVENT_0123_LFFL; +import static grondag.bitraster.Constants.EVENT_0123_LFFR; +import static grondag.bitraster.Constants.EVENT_0123_LFLF; +import static grondag.bitraster.Constants.EVENT_0123_LFLL; +import static grondag.bitraster.Constants.EVENT_0123_LFLR; +import static grondag.bitraster.Constants.EVENT_0123_LFRF; +import static grondag.bitraster.Constants.EVENT_0123_LFRL; +import static grondag.bitraster.Constants.EVENT_0123_LFRR; +import static grondag.bitraster.Constants.EVENT_0123_LLFF; +import static grondag.bitraster.Constants.EVENT_0123_LLFL; +import static grondag.bitraster.Constants.EVENT_0123_LLFR; +import static grondag.bitraster.Constants.EVENT_0123_LLLF; +import static grondag.bitraster.Constants.EVENT_0123_LLLL; +import static grondag.bitraster.Constants.EVENT_0123_LLLR; +import static grondag.bitraster.Constants.EVENT_0123_LLRF; +import static grondag.bitraster.Constants.EVENT_0123_LLRL; +import static grondag.bitraster.Constants.EVENT_0123_LLRR; +import static grondag.bitraster.Constants.EVENT_0123_LRFF; +import static grondag.bitraster.Constants.EVENT_0123_LRFL; +import static grondag.bitraster.Constants.EVENT_0123_LRFR; +import static grondag.bitraster.Constants.EVENT_0123_LRLF; +import static grondag.bitraster.Constants.EVENT_0123_LRLL; +import static grondag.bitraster.Constants.EVENT_0123_LRLR; +import static grondag.bitraster.Constants.EVENT_0123_LRRF; +import static grondag.bitraster.Constants.EVENT_0123_LRRL; +import static grondag.bitraster.Constants.EVENT_0123_LRRR; +import static grondag.bitraster.Constants.EVENT_0123_RFFF; +import static grondag.bitraster.Constants.EVENT_0123_RFFL; +import static grondag.bitraster.Constants.EVENT_0123_RFFR; +import static grondag.bitraster.Constants.EVENT_0123_RFLF; +import static grondag.bitraster.Constants.EVENT_0123_RFLL; +import static grondag.bitraster.Constants.EVENT_0123_RFLR; +import static grondag.bitraster.Constants.EVENT_0123_RFRF; +import static grondag.bitraster.Constants.EVENT_0123_RFRL; +import static grondag.bitraster.Constants.EVENT_0123_RFRR; +import static grondag.bitraster.Constants.EVENT_0123_RLFF; +import static grondag.bitraster.Constants.EVENT_0123_RLFL; +import static grondag.bitraster.Constants.EVENT_0123_RLFR; +import static grondag.bitraster.Constants.EVENT_0123_RLLF; +import static grondag.bitraster.Constants.EVENT_0123_RLLL; +import static grondag.bitraster.Constants.EVENT_0123_RLLR; +import static grondag.bitraster.Constants.EVENT_0123_RLRF; +import static grondag.bitraster.Constants.EVENT_0123_RLRL; +import static grondag.bitraster.Constants.EVENT_0123_RLRR; +import static grondag.bitraster.Constants.EVENT_0123_RRFF; +import static grondag.bitraster.Constants.EVENT_0123_RRFL; +import static grondag.bitraster.Constants.EVENT_0123_RRFR; +import static grondag.bitraster.Constants.EVENT_0123_RRLF; +import static grondag.bitraster.Constants.EVENT_0123_RRLL; +import static grondag.bitraster.Constants.EVENT_0123_RRLR; +import static grondag.bitraster.Constants.EVENT_0123_RRRF; +import static grondag.bitraster.Constants.EVENT_0123_RRRL; +import static grondag.bitraster.Constants.EVENT_0123_RRRR; +import static grondag.bitraster.Constants.EVENT_DATA_LENGTH; +import static grondag.bitraster.Constants.EVENT_POSITION_MASK; +import static grondag.bitraster.Constants.IDX_AX0; +import static grondag.bitraster.Constants.IDX_AX1; +import static grondag.bitraster.Constants.IDX_AY0; +import static grondag.bitraster.Constants.IDX_AY1; +import static grondag.bitraster.Constants.IDX_BX0; +import static grondag.bitraster.Constants.IDX_BX1; +import static grondag.bitraster.Constants.IDX_BY0; +import static grondag.bitraster.Constants.IDX_BY1; +import static grondag.bitraster.Constants.IDX_CX0; +import static grondag.bitraster.Constants.IDX_CX1; +import static grondag.bitraster.Constants.IDX_CY0; +import static grondag.bitraster.Constants.IDX_CY1; +import static grondag.bitraster.Constants.IDX_DX0; +import static grondag.bitraster.Constants.IDX_DX1; +import static grondag.bitraster.Constants.IDX_DY0; +import static grondag.bitraster.Constants.IDX_DY1; +import static grondag.bitraster.Constants.MAX_PIXEL_Y; +import static grondag.bitraster.Constants.PIXEL_HEIGHT; +import static grondag.bitraster.Constants.PIXEL_WIDTH; +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.PV_PX; +import static grondag.bitraster.Constants.PV_PY; +import static grondag.bitraster.Constants.PV_W; +import static grondag.bitraster.Constants.PV_Z; +import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER; +import static grondag.bitraster.Constants.TILE_AXIS_MASK; +import static grondag.bitraster.Constants.TILE_AXIS_SHIFT; +import static grondag.bitraster.Constants.TILE_COUNT; +import static grondag.bitraster.Constants.TILE_HEIGHT_MASK; +import static grondag.bitraster.Constants.TILE_WIDTH; +import static grondag.bitraster.Constants.TILE_WIDTH_BITS; +import static grondag.bitraster.Constants.TILE_WIDTH_MASK; +import static grondag.bitraster.Constants.VERTEX_DATA_LENGTH; +import static grondag.bitraster.Indexer.tileIndexFromPixelXY; + +// Some elements are adapted from content found at +// https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/ +// by Fabian “ryg” Giesen. That content is in the public domain. +public abstract class AbstractRasterizer { + final Matrix4L mvpMatrix = new Matrix4L(); + final int[] vertexData = new int[VERTEX_DATA_LENGTH]; + final int[] eventData = new int[EVENT_DATA_LENGTH]; + final long[] tiles = new long[TILE_COUNT]; + final EventFiller[] EVENT_FILLERS = new EventFiller[0x1000]; + + /** Bounds of current triangle - pixel coordinates. */ + protected int minPixelX, minPixelY, maxPixelX, maxPixelY; + + /** Classifies each edge, holding results of {@link #edgePosition(int, int, int, int)}. */ + protected int pos0, pos1, pos2, pos3; + + protected int saveTileIndex; + /** Control iteration in populateEvents_ methods. */ + protected int eventY0, eventLimit; + + { + EVENT_FILLERS[EVENT_0123_RRRR] = () -> { + populateLeftEvents(); + populateRightEvents4(IDX_AX0, IDX_BX0, IDX_CX0, IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_LRRR] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents3(IDX_BX0, IDX_CX0, IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_FRRR] = () -> { + populateLeftEvents(); + populateRightEvents3(IDX_BX0, IDX_CX0, IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RLRR] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents3(IDX_AX0, IDX_CX0, IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_LLRR] = () -> { + populateLeftEvents2(IDX_AX0, IDX_BX0); + populateRightEvents2(IDX_CX0, IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_FLRR] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents2(IDX_CX0, IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RFRR] = () -> { + populateLeftEvents(); + populateRightEvents3(IDX_AX0, IDX_CX0, IDX_DX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_LFRR] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents2(IDX_CX0, IDX_DX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_FFRR] = () -> { + populateLeftEvents(); + populateRightEvents2(IDX_CX0, IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + + EVENT_FILLERS[EVENT_0123_RRLR] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents3(IDX_AX0, IDX_BX0, IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_LRLR] = () -> { + populateLeftEvents2(IDX_AX0, IDX_CX0); + populateRightEvents2(IDX_BX0, IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_FRLR] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents2(IDX_BX0, IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RLLR] = () -> { + populateLeftEvents2(IDX_BX0, IDX_CX0); + populateRightEvents2(IDX_AX0, IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_LLLR] = () -> { + populateLeftEvents3(IDX_AX0, IDX_BX0, IDX_CX0); + populateRightEvents(IDX_DX0); + }; + EVENT_FILLERS[EVENT_0123_FLLR] = () -> { + populateLeftEvents2(IDX_BX0, IDX_CX0); + populateRightEvents(IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RFLR] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents2(IDX_AX0, IDX_DX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_LFLR] = () -> { + populateLeftEvents2(IDX_AX0, IDX_CX0); + populateRightEvents(IDX_DX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_FFLR] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents(IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + + EVENT_FILLERS[EVENT_0123_LRFR] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents2(IDX_BX0, IDX_DX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_RRFR] = () -> { + populateLeftEvents(); + populateRightEvents3(IDX_AX0, IDX_BX0, IDX_DX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_FRFR] = () -> { + populateLeftEvents(); + populateRightEvents2(IDX_BX0, IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_RLFR] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents2(IDX_AX0, IDX_DX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_LLFR] = () -> { + populateLeftEvents2(IDX_AX0, IDX_BX0); + populateRightEvents(IDX_DX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_FLFR] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents(IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_RFFR] = () -> { + populateLeftEvents(); + populateRightEvents2(IDX_AX0, IDX_DX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_LFFR] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents(IDX_DX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_FFFR] = () -> { + populateLeftEvents(); + populateRightEvents(IDX_DX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + + EVENT_FILLERS[EVENT_0123_RRRL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents3(IDX_AX0, IDX_BX0, IDX_CX0); + }; + EVENT_FILLERS[EVENT_0123_LRRL] = () -> { + populateLeftEvents2(IDX_AX0, IDX_DX0); + populateRightEvents2(IDX_BX0, IDX_CX0); + }; + EVENT_FILLERS[EVENT_0123_FRRL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents2(IDX_BX0, IDX_CX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RLRL] = () -> { + populateLeftEvents2(IDX_BX0, IDX_DX0); + populateRightEvents2(IDX_AX0, IDX_CX0); + }; + EVENT_FILLERS[EVENT_0123_LLRL] = () -> { + populateLeftEvents3(IDX_AX0, IDX_BX0, IDX_DX0); + populateRightEvents(IDX_CX0); + }; + EVENT_FILLERS[EVENT_0123_FLRL] = () -> { + populateLeftEvents2(IDX_BX0, IDX_DX0); + populateRightEvents(IDX_CX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RFRL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents2(IDX_AX0, IDX_CX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_LFRL] = () -> { + populateLeftEvents2(IDX_AX0, IDX_DX0); + populateRightEvents(IDX_CX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_FFRL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents(IDX_CX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_RRLL] = () -> { + populateLeftEvents2(IDX_CX0, IDX_DX0); + populateRightEvents2(IDX_AX0, IDX_BX0); + }; + EVENT_FILLERS[EVENT_0123_LRLL] = () -> { + populateLeftEvents3(IDX_AX0, IDX_CX0, IDX_DX0); + populateRightEvents(IDX_BX0); + }; + EVENT_FILLERS[EVENT_0123_FRLL] = () -> { + populateLeftEvents2(IDX_CX0, IDX_DX0); + populateRightEvents(IDX_BX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RLLL] = () -> { + populateLeftEvents3(IDX_BX0, IDX_CX0, IDX_DX0); + populateRightEvents(IDX_AX0); + }; + EVENT_FILLERS[EVENT_0123_LLLL] = () -> { + populateLeftEvents4(IDX_AX0, IDX_BX0, IDX_CX0, IDX_DX0); + populateRightEvents(); + }; + EVENT_FILLERS[EVENT_0123_FLLL] = () -> { + populateLeftEvents3(IDX_BX0, IDX_CX0, IDX_DX0); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + }; + EVENT_FILLERS[EVENT_0123_RFLL] = () -> { + populateLeftEvents2(IDX_CX0, IDX_DX0); + populateRightEvents(IDX_AX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_LFLL] = () -> { + populateLeftEvents3(IDX_AX0, IDX_CX0, IDX_DX0); + populateRightEvents(); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_FFLL] = () -> { + populateLeftEvents2(IDX_CX0, IDX_DX0); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + }; + EVENT_FILLERS[EVENT_0123_LRFL] = () -> { + populateLeftEvents2(IDX_AX0, IDX_DX0); + populateRightEvents(IDX_BX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_RRFL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents2(IDX_AX0, IDX_BX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_FRFL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents(IDX_BX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_RLFL] = () -> { + populateLeftEvents2(IDX_BX0, IDX_DX0); + populateRightEvents(IDX_AX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_LLFL] = () -> { + populateLeftEvents3(IDX_AX0, IDX_BX0, IDX_DX0); + populateRightEvents(); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_FLFL] = () -> { + populateLeftEvents2(IDX_BX0, IDX_DX0); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_RFFL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents(IDX_AX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_LFFL] = () -> { + populateLeftEvents2(IDX_AX0, IDX_DX0); + populateRightEvents(); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_FFFL] = () -> { + populateLeftEvents(IDX_DX0); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + }; + EVENT_FILLERS[EVENT_0123_RRRF] = () -> { + populateLeftEvents(); + populateRightEvents3(IDX_AX0, IDX_BX0, IDX_CX0); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LRRF] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents2(IDX_BX0, IDX_CX0); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FRRF] = () -> { + populateLeftEvents(); + populateRightEvents2(IDX_BX0, IDX_CX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RLRF] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents2(IDX_AX0, IDX_CX0); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LLRF] = () -> { + populateLeftEvents2(IDX_AX0, IDX_BX0); + populateRightEvents(IDX_CX0); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FLRF] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents(IDX_CX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RFRF] = () -> { + populateLeftEvents(); + populateRightEvents2(IDX_AX0, IDX_CX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LFRF] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents(IDX_CX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FFRF] = () -> { + populateLeftEvents(); + populateRightEvents(IDX_CX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RRLF] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents2(IDX_AX0, IDX_BX0); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LRLF] = () -> { + populateLeftEvents2(IDX_AX0, IDX_CX0); + populateRightEvents(IDX_BX0); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FRLF] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents(IDX_BX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RLLF] = () -> { + populateLeftEvents2(IDX_BX0, IDX_CX0); + populateRightEvents(IDX_AX0); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LLLF] = () -> { + populateLeftEvents3(IDX_AX0, IDX_BX0, IDX_CX0); + populateRightEvents(); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FLLF] = () -> { + populateLeftEvents2(IDX_BX0, IDX_CX0); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RFLF] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents(IDX_AX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LFLF] = () -> { + populateLeftEvents2(IDX_AX0, IDX_CX0); + populateRightEvents(); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FFLF] = () -> { + populateLeftEvents(IDX_CX0); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LRFF] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents(IDX_BX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RRFF] = () -> { + populateLeftEvents(); + populateRightEvents2(IDX_AX0, IDX_BX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FRFF] = () -> { + populateLeftEvents(); + populateRightEvents(IDX_BX0); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RLFF] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents(IDX_AX0); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LLFF] = () -> { + populateLeftEvents2(IDX_AX0, IDX_BX0); + populateRightEvents(); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FLFF] = () -> { + populateLeftEvents(IDX_BX0); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_RFFF] = () -> { + populateLeftEvents(); + populateRightEvents(IDX_AX0); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_LFFF] = () -> { + populateLeftEvents(IDX_AX0); + populateRightEvents(); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + EVENT_FILLERS[EVENT_0123_FFFF] = () -> { + // fill it + populateLeftEvents(); + populateRightEvents(); + populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos3, vertexData[IDX_DY0]); + }; + } + + final void copyFrom(AbstractRasterizer source) { + mvpMatrix.copyFrom(source.mvpMatrix); + System.arraycopy(source.vertexData, 0, vertexData, 0, VERTEX_DATA_LENGTH); + System.arraycopy(source.eventData, 0, eventData, 0, EVENT_DATA_LENGTH); + System.arraycopy(source.tiles, 0, tiles, 0, TILE_COUNT); + } + + final void drawQuad(int v0, int v1, int v2, int v3) { + if (prepareBounds(v0, v1, v2, v3) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { + return; + } + + // Don't draw single points + if (minPixelX == maxPixelX && minPixelY == maxPixelY) { + return; + } + + drawQuad(); + } + + final boolean isQuadPartiallyClear(int v0, int v1, int v2, int v3) { + if (prepareBounds(v0, v1, v2, v3) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { + return false; + } + + final int px = minPixelX; + final int py = minPixelY; + + if (px == maxPixelX && py == maxPixelY) { + return px >= 0 && py >= 0 && px < PIXEL_WIDTH && py < PIXEL_HEIGHT && isPixelClear(px, py); + } else { + return isQuadPartiallyClear(); + } + } + + final boolean isQuadPartiallyClear() { + final int minTileX = minPixelX >> TILE_AXIS_SHIFT; + final int maxTileX = maxPixelX >> TILE_AXIS_SHIFT; + final int maxTileY = (maxPixelY >> TILE_AXIS_SHIFT) << TILE_WIDTH_BITS; + final long[] tiles = this.tiles; + + int tileIndex = tileIndexFromPixelXY(minPixelX, minPixelY); + int xLimit = maxTileX; + int xInc = 1; + + while (true) { + final long word = tiles[tileIndex]; + + if (word != -1L && (~word & computeTileCoverage(tileIndex)) != 0) { + return true; + } + + if ((tileIndex & TILE_WIDTH_MASK) == xLimit) { + if ((tileIndex & TILE_HEIGHT_MASK) == maxTileY) { + return false; + } else { + // move up + tileIndex += TILE_WIDTH; + // flip x order + xLimit = xLimit == maxTileX ? minTileX : maxTileX; + xInc = -xInc; + } + } else { + // move left or right + tileIndex += xInc; + } + } + } + + final boolean isQuadPartiallyOccluded(int v0, int v1, int v2, int v3) { + if (prepareBounds(v0, v1, v2, v3) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { + return false; + } + + final int px = minPixelX; + final int py = minPixelY; + + if (px == maxPixelX && py == maxPixelY) { + return px >= 0 && py >= 0 && px < PIXEL_WIDTH && py < PIXEL_HEIGHT && isPixelSet(px, py); + } else { + return isQuadPartiallyOccluded(); + } + } + + final boolean isQuadPartiallyOccluded() { + final int minTileX = minPixelX >> TILE_AXIS_SHIFT; + final int maxTileX = maxPixelX >> TILE_AXIS_SHIFT; + final int maxTileY = (maxPixelY >> TILE_AXIS_SHIFT) << TILE_WIDTH_BITS; + final long[] tiles = this.tiles; + + int tileIndex = tileIndexFromPixelXY(minPixelX, minPixelY); + int xLimit = maxTileX; + int xInc = 1; + + while (true) { + final long word = tiles[tileIndex]; + + if (word != 0 && (word & computeTileCoverage(tileIndex)) != 0) { + return true; + } + + if ((tileIndex & TILE_WIDTH_MASK) == xLimit) { + if ((tileIndex & TILE_HEIGHT_MASK) == maxTileY) { + return false; + } else { + // move up + tileIndex += TILE_WIDTH; + // flip x order + xLimit = xLimit == maxTileX ? minTileX : maxTileX; + xInc = -xInc; + } + } else { + // move left or right + tileIndex += xInc; + } + } + } + + final void drawQuad() { + final int minTileX = minPixelX >> TILE_AXIS_SHIFT; + final int maxTileX = maxPixelX >> TILE_AXIS_SHIFT; + final int maxTileY = (maxPixelY >> TILE_AXIS_SHIFT) << TILE_WIDTH_BITS; + final long[] tiles = this.tiles; + + int tileIndex = tileIndexFromPixelXY(minPixelX, minPixelY); + int xLimit = maxTileX; + int xInc = 1; + + while (true) { + long word = tiles[tileIndex]; + + // nothing to do if fully occluded + if (word != -1L) { + word |= computeTileCoverage(tileIndex); + tiles[tileIndex] = word; + } + + if ((tileIndex & TILE_WIDTH_MASK) == xLimit) { + if ((tileIndex & TILE_HEIGHT_MASK) == maxTileY) { + return; + } else { + // move up + tileIndex += TILE_WIDTH; + // flip x order + xLimit = xLimit == maxTileX ? minTileX : maxTileX; + xInc = -xInc; + } + } else { + // move left or right + tileIndex += xInc; + } + } + } + + abstract int prepareBounds(int v0, int v1, int v2, int v3); + + private void populateFlatEvents(int position, int y0In) { + final int[] eventData = this.eventData; + + if (position == EDGE_TOP) { + final int py = ((y0In + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) + 1; + + if (py == MAX_PIXEL_Y) return; + + final int y1 = (maxPixelY & TILE_AXIS_MASK) + 7; + final int start = py < 0 ? 0 : (py << 1); + final int limit = y1 << 1; + + assert limit < EVENT_DATA_LENGTH; + + for (int y = start; y <= limit; ) { + eventData[y++] = PIXEL_WIDTH; + eventData[y++] = -1; + } + } else if (position == EDGE_BOTTOM) { + final int py = (y0In >> PRECISION_BITS); + + if (py == 0) return; + + final int y0 = minPixelY & TILE_AXIS_MASK; + final int start = y0 << 1; + final int limit = py > MAX_PIXEL_Y ? (MAX_PIXEL_Y << 1) : (py << 1); + + assert limit < EVENT_DATA_LENGTH; + + for (int y = start; y < limit; ) { + eventData[y++] = PIXEL_WIDTH; + eventData[y++] = -1; + } + } else { + assert position == EDGE_POINT; + } + } + + /** + * Puts left edge at screen boundary. + */ + private void populateLeftEvents() { + final int[] eventData = this.eventData; + final int y0 = eventY0; + final int limit = eventLimit; + + for (int y = y0 << 1; y <= limit; y += 2) { + eventData[y] = 0; + } + } + + private void populateLeftEvents(int a) { + final int[] vertexData = this.vertexData; + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + final int limit = eventLimit; + final long dx = ax1 - ax0; + + if (dx == 0) { + final int x = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + + for (int y = (y0 << 1); y <= limit; y += 2) { + eventData[y] = x; + } + } else { + final long n = (dx << 16) / (ay1 - ay0); + final long nStep = n << PRECISION_BITS; + long x = ((long) ax0 << 16) - n * ay0 + nStep * y0 + 0x100000L; + + for (int y = (y0 << 1); y <= limit; y += 2) { + eventData[y] = (int) (x >> 20); + x += nStep; + } + } + } + + private void populateRightEvents() { + final int[] eventData = this.eventData; + final int y0 = eventY0; + // difference from left: is high index in pairs + final int limit = eventLimit + 1; + + // difference from left: is high index in pairs + for (int y = (y0 << 1) + 1; y <= limit; y += 2) { + eventData[y] = PIXEL_WIDTH; + } + } + + private void populateRightEvents(int a) { + final int[] vertexData = this.vertexData; + + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + // difference from left: is high index in pairs + final int limit = eventLimit + 1; + final int dx = ax1 - ax0; + + if (dx == 0) { + final int x = (ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + + // difference from left: is high index in pairs + for (int y = (y0 << 1) + 1; y <= limit; y += 2) { + eventData[y] = x; + } + } else { + final long n = (((long) dx) << 16) / (ay1 - ay0); + final long nStep = n << PRECISION_BITS; + // difference from left: rounding looses tie + long x = ((long) ax0 << 16) - n * ay0 + nStep * y0 + 0x7FFFFL; + + // difference from left: is high index in pairs + for (int y = (y0 << 1) + 1; y <= limit; y += 2) { + eventData[y] = (int) (x >> 20); + x += nStep; + } + } + } + + private void populateLeftEvents2(int a, int b) { + final int[] vertexData = this.vertexData; + + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int bx0 = vertexData[b]; + final int by0 = vertexData[b + 1]; + final int bx1 = vertexData[b + 2]; + final int by1 = vertexData[b + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + final int limit = eventLimit; + + final long aStep, bStep; + long ax, bx; + + if (ax0 == ax1) { + ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + aStep = 0; + } else { + final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); + aStep = an << PRECISION_BITS; + ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x100000L; + } + + if (bx0 == bx1) { + bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + bStep = 0; + } else { + final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); + bStep = bn << PRECISION_BITS; + bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x100000L; + } + + for (int y = (y0 << 1); y <= limit; y += 2) { + eventData[y] = (int) ((ax > bx ? ax : bx) >> 20); + + ax += aStep; + bx += bStep; + } + } + + private void populateLeftEvents3(int a, int b, int c) { + final int[] vertexData = this.vertexData; + + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int bx0 = vertexData[b]; + final int by0 = vertexData[b + 1]; + final int bx1 = vertexData[b + 2]; + final int by1 = vertexData[b + 3]; + + final int cx0 = vertexData[c]; + final int cy0 = vertexData[c + 1]; + final int cx1 = vertexData[c + 2]; + final int cy1 = vertexData[c + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + final int limit = eventLimit; + + final long aStep, bStep, cStep; + long ax, bx, cx; + + if (ax0 == ax1) { + ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + aStep = 0; + } else { + final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); + aStep = an << PRECISION_BITS; + ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x100000L; + } + + if (bx0 == bx1) { + bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + bStep = 0; + } else { + final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); + bStep = bn << PRECISION_BITS; + bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x100000L; + } + + if (cx0 == cx1) { + cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + cStep = 0; + } else { + final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); + cStep = cn << PRECISION_BITS; + cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x100000L; + } + + for (int y = (y0 << 1); y <= limit; y += 2) { + final long i = ax > bx ? ax : bx; + eventData[y] = (int) ((cx > i ? cx : i) >> 20); + + ax += aStep; + bx += bStep; + cx += cStep; + } + } + + private void populateLeftEvents4(int a, int b, int c, int d) { + final int[] vertexData = this.vertexData; + + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int bx0 = vertexData[b]; + final int by0 = vertexData[b + 1]; + final int bx1 = vertexData[b + 2]; + final int by1 = vertexData[b + 3]; + + final int cx0 = vertexData[c]; + final int cy0 = vertexData[c + 1]; + final int cx1 = vertexData[c + 2]; + final int cy1 = vertexData[c + 3]; + + final int dx0 = vertexData[d]; + final int dy0 = vertexData[d + 1]; + final int dx1 = vertexData[d + 2]; + final int dy1 = vertexData[d + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + final int limit = eventLimit; + + final long aStep, bStep, cStep, dStep; + long ax, bx, cx, dx; + + if (ax0 == ax1) { + ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + aStep = 0; + } else { + final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); + aStep = an << PRECISION_BITS; + ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x100000L; + } + + if (bx0 == bx1) { + bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + bStep = 0; + } else { + final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); + bStep = bn << PRECISION_BITS; + bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x100000L; + } + + if (cx0 == cx1) { + cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + cStep = 0; + } else { + final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); + cStep = cn << PRECISION_BITS; + cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x100000L; + } + + if (dx0 == dx1) { + dx = ((dx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + dStep = 0; + } else { + final long dn = (((long) (dx1 - dx0)) << 16) / (dy1 - dy0); + dStep = dn << PRECISION_BITS; + dx = ((long) dx0 << 16) - dn * dy0 + dStep * y0 + 0x100000L; + } + + for (int y = (y0 << 1); y <= limit; y += 2) { + final long i = ax > bx ? ax : bx; + final long j = cx > dx ? cx : dx; + eventData[y] = (int) ((i > j ? i : j) >> 20); + + ax += aStep; + bx += bStep; + cx += cStep; + dx += dStep; + } + } + + private void populateRightEvents2(int a, int b) { + final int[] vertexData = this.vertexData; + + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int bx0 = vertexData[b]; + final int by0 = vertexData[b + 1]; + final int bx1 = vertexData[b + 2]; + final int by1 = vertexData[b + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + // difference from left: is high index in pairs + final int limit = eventLimit + 1; + + final long aStep, bStep; + long ax, bx; + + if (ax0 == ax1) { + ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + aStep = 0; + } else { + final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); + aStep = an << PRECISION_BITS; + // difference from left: rounding looses tie + ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x7FFFFL; + } + + if (bx0 == bx1) { + bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + bStep = 0; + } else { + final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); + bStep = bn << PRECISION_BITS; + // difference from left: rounding looses tie + bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x7FFFFL; + } + + // difference from left: is high index in pairs + for (int y = (y0 << 1) + 1; y <= limit; y += 2) { + // difference from left: lower value wins + eventData[y] = (int) ((ax < bx ? ax : bx) >> 20); + + ax += aStep; + bx += bStep; + } + } + + private void populateRightEvents3(int a, int b, int c) { + final int[] vertexData = this.vertexData; + + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int bx0 = vertexData[b]; + final int by0 = vertexData[b + 1]; + final int bx1 = vertexData[b + 2]; + final int by1 = vertexData[b + 3]; + + final int cx0 = vertexData[c]; + final int cy0 = vertexData[c + 1]; + final int cx1 = vertexData[c + 2]; + final int cy1 = vertexData[c + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + // difference from left: is high index in pairs + final int limit = eventLimit + 1; + + final long aStep, bStep, cStep; + long ax, bx, cx; + + if (ax0 == ax1) { + ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + aStep = 0; + } else { + final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); + aStep = an << PRECISION_BITS; + // difference from left: rounding looses tie + ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x7FFFFL; + } + + if (bx0 == bx1) { + bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + bStep = 0; + } else { + final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); + bStep = bn << PRECISION_BITS; + // difference from left: rounding looses tie + bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x7FFFFL; + } + + if (cx0 == cx1) { + cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + cStep = 0; + } else { + final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); + cStep = cn << PRECISION_BITS; + // difference from left: rounding looses tie + cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x7FFFFL; + } + + // difference from left: is high index in pairs + for (int y = (y0 << 1) + 1; y <= limit; y += 2) { + // difference from left: lower value wins + final long i = ax < bx ? ax : bx; + eventData[y] = (int) ((cx < i ? cx : i) >> 20); + + ax += aStep; + bx += bStep; + cx += cStep; + } + } + + private void populateRightEvents4(int a, int b, int c, int d) { + final int[] vertexData = this.vertexData; + + final int ax0 = vertexData[a]; + final int ay0 = vertexData[a + 1]; + final int ax1 = vertexData[a + 2]; + final int ay1 = vertexData[a + 3]; + + final int bx0 = vertexData[b]; + final int by0 = vertexData[b + 1]; + final int bx1 = vertexData[b + 2]; + final int by1 = vertexData[b + 3]; + + final int cx0 = vertexData[c]; + final int cy0 = vertexData[c + 1]; + final int cx1 = vertexData[c + 2]; + final int cy1 = vertexData[c + 3]; + + final int dx0 = vertexData[d]; + final int dy0 = vertexData[d + 1]; + final int dx1 = vertexData[d + 2]; + final int dy1 = vertexData[d + 3]; + + final int[] eventData = this.eventData; + final int y0 = eventY0; + // difference from left: is high index in pairs + final int limit = eventLimit + 1; + + final long aStep, bStep, cStep, dStep; + long ax, bx, cx, dx; + + if (ax0 == ax1) { + ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + aStep = 0; + } else { + final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); + aStep = an << PRECISION_BITS; + // difference from left: rounding looses tie + ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x7FFFFL; + } + + if (bx0 == bx1) { + bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + bStep = 0; + } else { + final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); + bStep = bn << PRECISION_BITS; + // difference from left: rounding looses tie + bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x7FFFFL; + } + + if (cx0 == cx1) { + cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + cStep = 0; + } else { + final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); + cStep = cn << PRECISION_BITS; + // difference from left: rounding looses tie + cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x7FFFFL; + } + + if (dx0 == dx1) { + dx = ((dx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + dStep = 0; + } else { + final long dn = (((long) (dx1 - dx0)) << 16) / (dy1 - dy0); + dStep = dn << PRECISION_BITS; + // difference from left: rounding looses tie + dx = ((long) dx0 << 16) - dn * dy0 + dStep * y0 + 0x7FFFFL; + } + + // difference from left: is high index in pairs + for (int y = (y0 << 1) + 1; y <= limit; y += 2) { + // difference from left: lower value wins + final long i = ax < bx ? ax : bx; + final long j = cx < dx ? cx : dx; + eventData[y] = (int) ((i < j ? i : j) >> 20); + + ax += aStep; + bx += bStep; + cx += cStep; + dx += dStep; + } + } + + abstract void setupVertex(int baseIndex, int x, int y, int z); + + int needsNearClip(final int baseIndex) { + final int[] data = vertexData; + final float w = Float.intBitsToFloat(data[baseIndex + PV_W]); + final float z = Float.intBitsToFloat(data[baseIndex + PV_Z]); + + if (w == 0) { + return 1; + } else if (w > 0) { + return (z > 0 && z <= w) ? 0 : 1; + } else { + // w < 0 + return (z < 0 && z >= w) ? 0 : 1; + } + } + + long computeTileCoverage(int tileIndex) { + final int[] data = eventData; + final int tileFirstX = (tileIndex & TILE_WIDTH_MASK) << TILE_AXIS_SHIFT; + final int tileLastX = tileFirstX + 7; + + // +1 to left shift because events are in pairs + final int baseEventIndex = (tileIndex >> TILE_WIDTH_BITS) << (TILE_AXIS_SHIFT + 1); + long mask = 0; + // shift left or right, > 7 means no coverage + int l, r; + + if ((l = data[baseEventIndex] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 1]) < 8) { + mask = (l < 0 ? 0xFFL : 0xFFL << l) & (r < 0 ? 0xFFL : 0xFFL >>> r); + } + + if ((l = data[baseEventIndex + 14] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 15]) < 8) { + mask |= ((l < 0 ? 0xFF00000000000000L : 0xFF00000000000000L << l) & (r < 0 ? 0xFF00000000000000L : 0xFF00000000000000L >>> r)); + } + + // Early exit when full coverage is detected + if (mask == 0xFF000000000000FFL) { + return -1L; + } + + if ((l = data[baseEventIndex + 2] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 3]) < 8) { + mask |= ((l < 0 ? 0xFF00L : 0xFF00L << l) & (r < 0 ? 0xFF00L : 0xFF00L >>> r)); + } + + if ((l = data[baseEventIndex + 4] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 5]) < 8) { + mask |= ((l < 0 ? 0xFF0000L : 0xFF0000L << l) & (r < 0 ? 0xFF0000L : 0xFF0000L >>> r)); + } + + if ((l = data[baseEventIndex + 6] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 7]) < 8) { + mask |= ((l < 0 ? 0xFF000000L : 0xFF000000L << l) & (r < 0 ? 0xFF000000L : 0xFF000000L >>> r)); + } + + if ((l = data[baseEventIndex + 8] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 9]) < 8) { + mask |= ((l < 0 ? 0xFF00000000L : 0xFF00000000L << l) & (r < 0 ? 0xFF00000000L : 0xFF00000000L >>> r)); + } + + if ((l = data[baseEventIndex + 10] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 11]) < 8) { + mask |= ((l < 0 ? 0xFF0000000000L : 0xFF0000000000L << l) & (r < 0 ? 0xFF0000000000L : 0xFF0000000000L >>> r)); + } + + if ((l = data[baseEventIndex + 12] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 13]) < 8) { + mask |= ((l < 0 ? 0xFF000000000000L : 0xFF000000000000L << l) & (r < 0 ? 0xFF000000000000L : 0xFF000000000000L >>> r)); + } + + //long bMask = computeTileCoverageB(tileIndex); + // + //if (bMask != mask) { + // System.out.println("Prior"); + // Util.printMask(mask); + // System.out.println("New"); + // Util.printMask(bMask); + // computeTileCoverageB(tileIndex); + //} + + return mask; + } + + public boolean isPixelClear(int x, int y) { + return (tiles[Indexer.tileIndexFromPixelXY(x, y)] & (1L << (Indexer.pixelIndex(x, y)))) == 0; + } + + public boolean isPixelSet(int x, int y) { + return (tiles[Indexer.tileIndexFromPixelXY(x, y)] & (1L << (Indexer.pixelIndex(x, y)))) != 0; + } + + void drawPixel(int x, int y) { + tiles[Indexer.tileIndexFromPixelXY(x, y)] |= (1L << (Indexer.pixelIndex(x, y))); + } + + @FunctionalInterface + interface EventFiller { + void apply(); + } + + /** + * Classifies the input segment, returning one of the EDGE_ constants. + */ + final int edgePosition(int x0In, int y0In, int x1In, int y1In) { + final int dy = y1In - y0In; + final int dx = x1In - x0In; + // signum of dx and dy, with shifted masks to derive the edge constant directly + // the edge constants are specifically formulated to allow this, inline, avoids any pointer chases + // sign of dy is inverted for historical reasons + return (1 << (((-dy >> 31) | (dy >>> 31)) + 1)) | (1 << (((dx >> 31) | (-dx >>> 31)) + 4)); + } + + final int prepareBoundsNoClip(int v0, int v1, int v2, int v3) { + final int[] data = vertexData; + int ax0, ay0, ax1, ay1; + int bx0, by0, bx1, by1; + int cx0, cy0, cx1, cy1; + int dx0, dy0, dx1, dy1; + int minY = 0, maxY = 0, minX = 0, maxX = 0; + + ax0 = data[v0 + PV_PX]; + ay0 = data[v0 + PV_PY]; + bx0 = data[v1 + PV_PX]; + by0 = data[v1 + PV_PY]; + cx0 = data[v2 + PV_PX]; + cy0 = data[v2 + PV_PY]; + dx0 = data[v3 + PV_PX]; + dy0 = data[v3 + PV_PY]; + + ax1 = bx0; + ay1 = by0; + bx1 = cx0; + by1 = cy0; + cx1 = dx0; + cy1 = dy0; + dx1 = ax0; + dy1 = ay0; + + minX = ax0; + maxX = ax0; + + if (bx0 < minX) { + minX = bx0; + } else if (bx0 > maxX) { + maxX = bx0; + } + + if (cx0 < minX) { + minX = cx0; + } else if (cx0 > maxX) { + maxX = cx0; + } + + if (dx0 < minX) { + minX = dx0; + } else if (dx0 > maxX) { + maxX = dx0; + } + + minY = ay0; + maxY = ay0; + + if (by0 < minY) { + minY = by0; + } else if (by0 > maxY) { + maxY = by0; + } + + if (cy0 < minY) { + minY = cy0; + } else if (cy0 > maxY) { + maxY = cy0; + } + + if (dy0 < minY) { + minY = dy0; + } else if (dy0 > maxY) { + maxY = dy0; + } + + if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (maxX <= 0 || minX >= PRECISE_WIDTH) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (minX < 0) { + minX = 0; + } + + if (maxX >= PRECISE_WIDTH_CLAMP) { + maxX = PRECISE_WIDTH_CLAMP; + + if (minX > PRECISE_WIDTH_CLAMP) { + minX = PRECISE_WIDTH_CLAMP; + } + } + + if (minY < 0) { + minY = 0; + } + + if (maxY >= PRECISE_HEIGHT_CLAMP) { + maxY = PRECISE_HEIGHT_CLAMP; + + if (minY > PRECISE_HEIGHT_CLAMP) { + minY = PRECISE_HEIGHT_CLAMP; + } + } + + final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + + final int position0 = edgePosition(ax0, ay0, ax1, ay1); + final int position1 = edgePosition(bx0, by0, bx1, by1); + final int position2 = edgePosition(cx0, cy0, cx1, cy1); + final int position3 = edgePosition(dx0, dy0, dx1, dy1); + + this.minPixelX = minPixelX; + this.minPixelY = minPixelY; + this.maxPixelX = maxPixelX; + this.maxPixelY = maxPixelY; + data[IDX_AX0] = ax0; + data[IDX_AY0] = ay0; + data[IDX_AX1] = ax1; + data[IDX_AY1] = ay1; + data[IDX_BX0] = bx0; + data[IDX_BY0] = by0; + data[IDX_BX1] = bx1; + data[IDX_BY1] = by1; + data[IDX_CX0] = cx0; + data[IDX_CY0] = cy0; + data[IDX_CX1] = cx1; + data[IDX_CY1] = cy1; + data[IDX_DX0] = dx0; + data[IDX_DY0] = dy0; + data[IDX_DX1] = dx1; + data[IDX_DY1] = dy1; + pos0 = position0; + pos1 = position1; + pos2 = position2; + pos3 = position3; + + final int eventKey = (position0 - 1) & EVENT_POSITION_MASK + | (((position1 - 1) & EVENT_POSITION_MASK) << 2) + | (((position2 - 1) & EVENT_POSITION_MASK) << 4) + | (((position3 - 1) & EVENT_POSITION_MASK) << 6); + + prepareEvents(eventKey); + return BOUNDS_IN; + } + + void prepareEvents(int eventKey) { + eventY0 = minPixelY & TILE_AXIS_MASK; + eventLimit = (((maxPixelY & TILE_AXIS_MASK) + 7) << 1); + EVENT_FILLERS[eventKey].apply(); + } +} diff --git a/common/src/main/java/grondag/bitraster/BoxOccluder.java b/common/src/main/java/grondag/bitraster/BoxOccluder.java new file mode 100644 index 000000000..d35f616fa --- /dev/null +++ b/common/src/main/java/grondag/bitraster/BoxOccluder.java @@ -0,0 +1,1203 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +import static grondag.bitraster.Constants.CAMERA_PRECISION_BITS; +import static grondag.bitraster.Constants.CAMERA_PRECISION_UNITY; +import static grondag.bitraster.Constants.DOWN; +import static grondag.bitraster.Constants.EAST; +import static grondag.bitraster.Constants.EMPTY_BITS; +import static grondag.bitraster.Constants.NORTH; +import static grondag.bitraster.Constants.SOUTH; +import static grondag.bitraster.Constants.TILE_COUNT; +import static grondag.bitraster.Constants.UP; +import static grondag.bitraster.Constants.V000; +import static grondag.bitraster.Constants.V001; +import static grondag.bitraster.Constants.V010; +import static grondag.bitraster.Constants.V011; +import static grondag.bitraster.Constants.V100; +import static grondag.bitraster.Constants.V101; +import static grondag.bitraster.Constants.V110; +import static grondag.bitraster.Constants.V111; +import static grondag.bitraster.Constants.WEST; + +import java.util.function.Consumer; + +public abstract class BoxOccluder { + /** How close face must be to trigger aggressive refresh of occlusion. */ + private static final int NEAR_RANGE = 8 << CAMERA_PRECISION_BITS; + + private final Matrix4L baseMvpMatrix = new Matrix4L(); + + protected final AbstractRasterizer raster; + private int occlusionVersion = 1; + protected final BoxTest[] partiallyClearTests = new BoxTest[128]; + protected final BoxTest[] partiallyOccludedTests = new BoxTest[128]; + protected final BoxDraw[] boxDraws = new BoxDraw[128]; + private long viewX; + private long viewY; + private long viewZ; + // Add these to region-relative box coordinates to get camera-relative coordinates + // They are in camera fixed precision. + protected int offsetX; + protected int offsetY; + protected int offsetZ; + private int occlusionRange; + private int regionSquaredChunkDist; + private int viewVersion = -1; + private int regionVersion = -1; + private volatile boolean forceRedraw = false; + private int maxSquaredChunkDistance; + private boolean hasNearOccluders = false; + private boolean drawNearOccluders = true; + + public BoxOccluder(AbstractRasterizer raster) { + this.raster = raster; + + partiallyClearTests[0] = (x0, y0, z0, x1, y1, z1) -> { + return false; + }; + + partiallyClearTests[UP] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V110, V010, V011, V111); + }; + + partiallyClearTests[DOWN] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + return raster.isQuadPartiallyClear(V000, V100, V101, V001); + }; + + partiallyClearTests[EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V101, V100, V110, V111); + }; + + partiallyClearTests[WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + return raster.isQuadPartiallyClear(V000, V001, V011, V010); + }; + + partiallyClearTests[NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyClear(V100, V000, V010, V110); + }; + + partiallyClearTests[SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V001, V101, V111, V011); + }; + + // NB: Split across two quads to give more evenly-sized test regions vs potentially one big and one very small + partiallyClearTests[UP | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V110, V010, V011, V111) + || raster.isQuadPartiallyClear(V101, V100, V110, V111); + }; + + partiallyClearTests[UP | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V110, V010, V011, V111) + || raster.isQuadPartiallyClear(V000, V001, V011, V010); + }; + + partiallyClearTests[UP | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V110, V010, V011, V111) + || raster.isQuadPartiallyClear(V100, V000, V010, V110); + }; + + partiallyClearTests[UP | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V110, V010, V011, V111) + || raster.isQuadPartiallyClear(V001, V101, V111, V011); + }; + + partiallyClearTests[DOWN | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V000, V100, V101, V001) + || raster.isQuadPartiallyClear(V101, V100, V110, V111); + }; + + partiallyClearTests[DOWN | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + return raster.isQuadPartiallyClear(V000, V100, V101, V001) + || raster.isQuadPartiallyClear(V000, V001, V011, V010); + }; + + partiallyClearTests[DOWN | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyClear(V000, V100, V101, V001) + || raster.isQuadPartiallyClear(V100, V000, V010, V110); + }; + + partiallyClearTests[DOWN | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V000, V100, V101, V001) + || raster.isQuadPartiallyClear(V001, V101, V111, V011); + }; + + partiallyClearTests[NORTH | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V100, V000, V010, V110) + || raster.isQuadPartiallyClear(V101, V100, V110, V111); + }; + + partiallyClearTests[NORTH | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyClear(V100, V000, V010, V110) + || raster.isQuadPartiallyClear(V000, V001, V011, V010); + }; + + partiallyClearTests[SOUTH | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V001, V101, V111, V011) + || raster.isQuadPartiallyClear(V101, V100, V110, V111); + }; + + partiallyClearTests[SOUTH | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V001, V101, V111, V011) + || raster.isQuadPartiallyClear(V000, V001, V011, V010); + }; + + // NB: When three faces are visible, omit nearest vertex and draw two quads instead of three. + + partiallyClearTests[UP | EAST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V011, V111, V101, V100) + || raster.isQuadPartiallyClear(V100, V000, V010, V011); + }; + + partiallyClearTests[UP | WEST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V111, V110, V100, V000) + || raster.isQuadPartiallyClear(V000, V001, V011, V111); + }; + + partiallyClearTests[UP | EAST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyClear(V010, V011, V001, V101) + || raster.isQuadPartiallyClear(V101, V100, V110, V010); + }; + + partiallyClearTests[UP | WEST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V110, V010, V000, V001) + || raster.isQuadPartiallyClear(V001, V101, V111, V110); + }; + + partiallyClearTests[DOWN | EAST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V001, V000, V010, V110) + || raster.isQuadPartiallyClear(V110, V111, V101, V001); + }; + + partiallyClearTests[DOWN | WEST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyClear(V101, V001, V011, V010) + || raster.isQuadPartiallyClear(V010, V110, V100, V101); + }; + + partiallyClearTests[DOWN | EAST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V000, V100, V110, V111) + || raster.isQuadPartiallyClear(V111, V011, V001, V000); + }; + + partiallyClearTests[DOWN | WEST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyClear(V100, V101, V111, V011) + || raster.isQuadPartiallyClear(V011, V010, V000, V100); + }; + + //// + + partiallyOccludedTests[0] = (x0, y0, z0, x1, y1, z1) -> { + return false; + }; + + partiallyOccludedTests[UP] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V110, V010, V011, V111); + }; + + partiallyOccludedTests[DOWN] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + return raster.isQuadPartiallyOccluded(V000, V100, V101, V001); + }; + + partiallyOccludedTests[EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V101, V100, V110, V111); + }; + + partiallyOccludedTests[WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + return raster.isQuadPartiallyOccluded(V000, V001, V011, V010); + }; + + partiallyOccludedTests[NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyOccluded(V100, V000, V010, V110); + }; + + partiallyOccludedTests[SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V001, V101, V111, V011); + }; + + // NB: Split across two quads to give more evenly-sized test regions vs potentially one big and one very small + partiallyOccludedTests[UP | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V110, V010, V011, V111) + || raster.isQuadPartiallyOccluded(V101, V100, V110, V111); + }; + + partiallyOccludedTests[UP | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V110, V010, V011, V111) + || raster.isQuadPartiallyOccluded(V000, V001, V011, V010); + }; + + partiallyOccludedTests[UP | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V110, V010, V011, V111) + || raster.isQuadPartiallyOccluded(V100, V000, V010, V110); + }; + + partiallyOccludedTests[UP | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V110, V010, V011, V111) + || raster.isQuadPartiallyOccluded(V001, V101, V111, V011); + }; + + partiallyOccludedTests[DOWN | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V000, V100, V101, V001) + || raster.isQuadPartiallyOccluded(V101, V100, V110, V111); + }; + + partiallyOccludedTests[DOWN | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + return raster.isQuadPartiallyOccluded(V000, V100, V101, V001) + || raster.isQuadPartiallyOccluded(V000, V001, V011, V010); + }; + + partiallyOccludedTests[DOWN | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyOccluded(V000, V100, V101, V001) + || raster.isQuadPartiallyOccluded(V100, V000, V010, V110); + }; + + partiallyOccludedTests[DOWN | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V000, V100, V101, V001) + || raster.isQuadPartiallyOccluded(V001, V101, V111, V011); + }; + + partiallyOccludedTests[NORTH | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V100, V000, V010, V110) + || raster.isQuadPartiallyOccluded(V101, V100, V110, V111); + }; + + partiallyOccludedTests[NORTH | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyOccluded(V100, V000, V010, V110) + || raster.isQuadPartiallyOccluded(V000, V001, V011, V010); + }; + + partiallyOccludedTests[SOUTH | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V001, V101, V111, V011) + || raster.isQuadPartiallyOccluded(V101, V100, V110, V111); + }; + + partiallyOccludedTests[SOUTH | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V001, V101, V111, V011) + || raster.isQuadPartiallyOccluded(V000, V001, V011, V010); + }; + + // NB: When three faces are visible, omit nearest vertex and draw two quads instead of three. + + partiallyOccludedTests[UP | EAST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V011, V111, V101, V100) + || raster.isQuadPartiallyOccluded(V100, V000, V010, V011); + }; + + partiallyOccludedTests[UP | WEST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V111, V110, V100, V000) + || raster.isQuadPartiallyOccluded(V000, V001, V011, V111); + }; + + partiallyOccludedTests[UP | EAST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyOccluded(V010, V011, V001, V101) + || raster.isQuadPartiallyOccluded(V101, V100, V110, V010); + }; + + partiallyOccludedTests[UP | WEST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V110, V010, V000, V001) + || raster.isQuadPartiallyOccluded(V001, V101, V111, V110); + }; + + partiallyOccludedTests[DOWN | EAST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V001, V000, V010, V110) + || raster.isQuadPartiallyOccluded(V110, V111, V101, V001); + }; + + partiallyOccludedTests[DOWN | WEST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + return raster.isQuadPartiallyOccluded(V101, V001, V011, V010) + || raster.isQuadPartiallyOccluded(V010, V110, V100, V101); + }; + + partiallyOccludedTests[DOWN | EAST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V000, V100, V110, V111) + || raster.isQuadPartiallyOccluded(V111, V011, V001, V000); + }; + + partiallyOccludedTests[DOWN | WEST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + return raster.isQuadPartiallyOccluded(V100, V101, V111, V011) + || raster.isQuadPartiallyOccluded(V011, V010, V000, V100); + }; + + //// + + boxDraws[0] = (x0, y0, z0, x1, y1, z1) -> { + // NOOP + }; + + boxDraws[UP] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V110, V010, V011, V111); + }; + + boxDraws[DOWN] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.drawQuad(V000, V100, V101, V001); + }; + + boxDraws[EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V101, V100, V110, V111); + }; + + boxDraws[WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.drawQuad(V000, V001, V011, V010); + }; + + boxDraws[NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.drawQuad(V100, V000, V010, V110); + }; + + boxDraws[SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V001, V101, V111, V011); + }; + + // NB: Split across two quads to give more evenly-sized test regions vs potentially one big and one very small + boxDraws[UP | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V110, V010, V011, V111); + raster.drawQuad(V101, V100, V110, V111); + }; + + boxDraws[UP | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V110, V010, V011, V111); + raster.drawQuad(V000, V001, V011, V010); + }; + + boxDraws[UP | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V110, V010, V011, V111); + raster.drawQuad(V100, V000, V010, V110); + }; + + boxDraws[UP | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V110, V010, V011, V111); + raster.drawQuad(V001, V101, V111, V011); + }; + + boxDraws[DOWN | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V000, V100, V101, V001); + raster.drawQuad(V101, V100, V110, V111); + }; + + boxDraws[DOWN | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.drawQuad(V000, V100, V101, V001); + raster.drawQuad(V000, V001, V011, V010); + }; + + boxDraws[DOWN | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.drawQuad(V000, V100, V101, V001); + raster.drawQuad(V100, V000, V010, V110); + }; + + boxDraws[DOWN | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V000, V100, V101, V001); + raster.drawQuad(V001, V101, V111, V011); + }; + + boxDraws[NORTH | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V100, V000, V010, V110); + raster.drawQuad(V101, V100, V110, V111); + }; + + boxDraws[NORTH | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.drawQuad(V100, V000, V010, V110); + raster.drawQuad(V000, V001, V011, V010); + }; + + boxDraws[SOUTH | EAST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V001, V101, V111, V011); + raster.drawQuad(V101, V100, V110, V111); + }; + + boxDraws[SOUTH | WEST] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V001, V101, V111, V011); + raster.drawQuad(V000, V001, V011, V010); + }; + + // NB: When three faces are visible, omit nearest vertex and draw two quads instead of three. + + boxDraws[UP | EAST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V011, V111, V101, V100); + raster.drawQuad(V100, V000, V010, V011); + }; + + boxDraws[UP | WEST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V111, V110, V100, V000); + raster.drawQuad(V000, V001, V011, V111); + }; + + boxDraws[UP | EAST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.drawQuad(V010, V011, V001, V101); + raster.drawQuad(V101, V100, V110, V010); + }; + + boxDraws[UP | WEST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V110, V010, V000, V001); + raster.drawQuad(V001, V101, V111, V110); + }; + + boxDraws[DOWN | EAST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V001, V000, V010, V110); + raster.drawQuad(V110, V111, V101, V001); + }; + + boxDraws[DOWN | WEST | NORTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V110, x1, y1, z0); + raster.drawQuad(V101, V001, V011, V010); + raster.drawQuad(V010, V110, V100, V101); + }; + + boxDraws[DOWN | EAST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V001, x0, y0, z1); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V110, x1, y1, z0); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V000, V100, V110, V111); + raster.drawQuad(V111, V011, V001, V000); + }; + + boxDraws[DOWN | WEST | SOUTH] = (x0, y0, z0, x1, y1, z1) -> { + raster.setupVertex(V000, x0, y0, z0); + raster.setupVertex(V010, x0, y1, z0); + raster.setupVertex(V011, x0, y1, z1); + raster.setupVertex(V100, x1, y0, z0); + raster.setupVertex(V101, x1, y0, z1); + raster.setupVertex(V111, x1, y1, z1); + raster.drawQuad(V100, V101, V111, V011); + raster.drawQuad(V011, V010, V000, V100); + }; + } + + @Override + public final String toString() { + return String.format("OcclusionVersion:%d viewX:%d viewY:%d viewZ:%d offsetX:%d offsetY:%d offsetZ:%d viewVersion:%d regionVersion:%d forceRedraw:%b matrix:%s", + occlusionVersion, viewX, viewY, viewZ, offsetX, offsetY, offsetZ, viewVersion, regionVersion, forceRedraw, raster.mvpMatrix.toString()); + } + + public void copyFrom(BoxOccluder source) { + baseMvpMatrix.copyFrom(source.baseMvpMatrix); + raster.copyFrom(source.raster); + viewX = source.viewX; + viewY = source.viewY; + viewZ = source.viewZ; + + offsetX = source.offsetX; + offsetY = source.offsetY; + offsetZ = source.offsetZ; + + occlusionRange = source.occlusionRange; + + viewVersion = source.viewVersion; + regionVersion = source.regionVersion; + occlusionVersion = source.occlusionVersion; + maxSquaredChunkDistance = source.maxSquaredChunkDistance; + + forceRedraw = source.forceRedraw; + } + + /** + * Incremented each time the occluder is cleared and redrawn. + * Previously tested regions can reuse test results if their version matches. + * However, they must still be drawn (if visible) if indicated by {@link #clearSceneIfNeeded(int, int)}. + */ + public final int occlusionVersion() { + return occlusionVersion; + } + + /** + * For perspective occluders, controls if near occluders are drawn. + * Has no effect on testing. Meant to reduce flickering and gaps + * when the camera is moving around nearby terrain. Defaults to true + * and setting persists until it is changed again. + */ + public void drawNearOccluders(boolean val) { + drawNearOccluders = val; + } + + /** + * Force update to new version. + */ + public final void invalidate() { + forceRedraw = true; + } + + public final void prepareRegion(int originX, int originY, int originZ, int occlusionRange, int squaredChunkDistance) { + this.occlusionRange = occlusionRange; + regionSquaredChunkDist = squaredChunkDistance; + + // PERF: could perhaps reuse CameraRelativeCenter values in BuildRenderRegion that are used by Frustum + offsetX = (int) ((originX << CAMERA_PRECISION_BITS) - viewX); + offsetY = (int) ((originY << CAMERA_PRECISION_BITS) - viewY); + offsetZ = (int) ((originZ << CAMERA_PRECISION_BITS) - viewZ); + + final Matrix4L mvpMatrix = raster.mvpMatrix; + mvpMatrix.copyFrom(baseMvpMatrix); + mvpMatrix.translate(offsetX, offsetY, offsetZ, CAMERA_PRECISION_BITS); + } + + /** + * Check if needs redrawn and prep for redraw if so. + * When false, regions should be drawn only if their occluder version is not current. + */ + public final boolean prepareScene(int viewVersion, double cameraX, double cameraY, double cameraZ, Consumer modelMatrixSetter, Consumer projectionMatrixSetter) { + if (this.viewVersion != viewVersion) { + final Matrix4L baseMvpMatrix = this.baseMvpMatrix; + final Matrix4L tempMatrix = raster.mvpMatrix; + + baseMvpMatrix.loadIdentity(); + + projectionMatrixSetter.accept(tempMatrix); + baseMvpMatrix.multiply(tempMatrix); + + modelMatrixSetter.accept(tempMatrix); + baseMvpMatrix.multiply(tempMatrix); + + viewX = Math.round(cameraX * CAMERA_PRECISION_UNITY); + viewY = Math.round(cameraY * CAMERA_PRECISION_UNITY); + viewZ = Math.round(cameraZ * CAMERA_PRECISION_UNITY); + } + + if (forceRedraw || this.viewVersion != viewVersion) { + this.viewVersion = viewVersion; + System.arraycopy(EMPTY_BITS, 0, raster.tiles, 0, TILE_COUNT); + forceRedraw = false; + hasNearOccluders = false; + maxSquaredChunkDistance = 0; + ++occlusionVersion; + return true; + } else { + return false; + } + } + + /** + * True if occlusion includes geometry within the near region. + * When true, simple movement distance test isn't sufficient for knowing if redraw is needed. + */ + public final boolean hasNearOccluders() { + return hasNearOccluders; + } + + //final MicroTimer timer = new MicroTimer("boxTests.apply", 500000); + + public abstract boolean isBoxVisible(int packedBox, int fuzz); + + /** + * Does not rely on winding order but instead the distance from + * plane with known facing to camera position. + * + *

Not suitable for orthographic perspective. + */ + protected final boolean isBoxVisibleFromPerspective(int packedBox, int fuzz) { + final int x0 = PackedBox.x0(packedBox) - fuzz; + final int y0 = PackedBox.y0(packedBox) - fuzz; + final int z0 = PackedBox.z0(packedBox) - fuzz; + final int x1 = PackedBox.x1(packedBox) + fuzz; + final int y1 = PackedBox.y1(packedBox) + fuzz; + final int z1 = PackedBox.z1(packedBox) + fuzz; + + final int offsetX = this.offsetX; + final int offsetY = this.offsetY; + final int offsetZ = this.offsetZ; + + int outcome = 0; + + // if camera below top face can't be seen + if (offsetY < -(y1 << CAMERA_PRECISION_BITS)) { + outcome |= UP; + } else if (offsetY > -(y0 << CAMERA_PRECISION_BITS)) { + outcome |= DOWN; + } + + if (offsetX < -(x1 << CAMERA_PRECISION_BITS)) { + outcome |= EAST; + } else if (offsetX > -(x0 << CAMERA_PRECISION_BITS)) { + outcome |= WEST; + } + + if (offsetZ < -(z1 << CAMERA_PRECISION_BITS)) { + outcome |= SOUTH; + } else if (offsetZ > -(z0 << CAMERA_PRECISION_BITS)) { + outcome |= NORTH; + } + + //timer.start(); + //final boolean result = partiallyClearTests[outcome].apply(x0, y0, z0, x1, y1, z1); + //timer.stop(false); + + //final int size = (raster.maxPixelY - raster.minPixelY) * (raster.maxPixelX - raster.minPixelX); + + // Small regions ~ 20% of elapsed time, generally fast + //timer.stop(size <= 576); + + // Very large regions are expensive but rare < 5% of elapsed time + //timer.stop(size > 500000); + + // Small to moderate are 80% of elapsed time, doesn't seem to be much variation in time + //timer.stop(size < 100000); + + //return result; + return partiallyClearTests[outcome].apply(x0, y0, z0, x1, y1, z1); + } + + public final boolean isEmptyRegionVisible(int originX, int originY, int originZ, int fuzz) { + prepareRegion(originX, originY, originZ, 0, 0); + return isBoxVisible(PackedBox.FULL_BOX, fuzz); + } + + /** + * Does not rely on winding order but instead the distance from + * plane with known facing to camera position. + */ + public abstract void occludeBox(int packedBox); + + /** + * Does not rely on winding order but instead the distance from + * plane with known facing to camera position. + * + *

Will not be suitable for orthographic projection. + */ + protected void occludeFromPerspective(int packedBox) { + final int x0 = PackedBox.x0(packedBox); + final int y0 = PackedBox.y0(packedBox); + final int z0 = PackedBox.z0(packedBox); + final int x1 = PackedBox.x1(packedBox); + final int y1 = PackedBox.y1(packedBox); + final int z1 = PackedBox.z1(packedBox); + + final int offsetX = this.offsetX; + final int offsetY = this.offsetY; + final int offsetZ = this.offsetZ; + + int outcome = 0; + + boolean hasNear = true; + + final int top = (y1 << CAMERA_PRECISION_BITS) + offsetY; + + // NB: entirely possible for neither top or bottom to be visible. + // This happens when camera is between them. + + if (top < 0) { + // camera above top face + outcome |= UP; + hasNear &= top > -NEAR_RANGE; + } else { + final int bottom = (y0 << CAMERA_PRECISION_BITS) + offsetY; + + if (bottom > 0) { + // camera below bottom face + outcome |= DOWN; + hasNear &= bottom < NEAR_RANGE; + } + } + + final int east = (x1 << CAMERA_PRECISION_BITS) + offsetX; + + if (east < 0) { + outcome |= EAST; + hasNear &= east > -NEAR_RANGE; + } else { + final int west = (x0 << CAMERA_PRECISION_BITS) + offsetX; + + if (west > 0) { + outcome |= WEST; + hasNear &= west < NEAR_RANGE; + } + } + + final int south = (z1 << CAMERA_PRECISION_BITS) + offsetZ; + + if (south < 0) { + outcome |= SOUTH; + hasNear &= south > -NEAR_RANGE; + } else { + final int north = (z0 << CAMERA_PRECISION_BITS) + offsetZ; + + if (north > 0) { + outcome |= NORTH; + hasNear &= north < NEAR_RANGE; + } + } + + if (hasNear) { + if (drawNearOccluders) { + hasNearOccluders |= hasNear; + } else { + return; + } + } + + //timer.start(); + boxDraws[outcome].apply(x0, y0, z0, x1, y1, z1); + //timer.stop(false); + } + + public final void occlude(int[] visData) { + final int occlusionRange = this.occlusionRange; + final int limit = visData.length; + + if (limit > 1) { + boolean updateDist = false; + + for (int i = 1; i < limit; i++) { + final int box = visData[i]; + + if (occlusionRange > PackedBox.range(box)) { + break; + } + + updateDist = true; + occludeBox(box); + } + + if (updateDist && maxSquaredChunkDistance < regionSquaredChunkDist) { + maxSquaredChunkDistance = regionSquaredChunkDist; + } + } + } + + @FunctionalInterface + protected interface BoxTest { + boolean apply(int x0, int y0, int z0, int x1, int y1, int z1); + } + + @FunctionalInterface + protected interface BoxDraw { + void apply(int x0, int y0, int z0, int x1, int y1, int z1); + } + + public final int maxSquaredChunkDistance() { + return maxSquaredChunkDistance; + } +} diff --git a/common/src/main/java/grondag/bitraster/Constants.java b/common/src/main/java/grondag/bitraster/Constants.java new file mode 100644 index 000000000..b7d01c645 --- /dev/null +++ b/common/src/main/java/grondag/bitraster/Constants.java @@ -0,0 +1,258 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +public class Constants { + public static final int UP = 1 << 1; + public static final int DOWN = 1 << 0; + public static final int EAST = 1 << 5; + public static final int WEST = 1 << 4; + public static final int NORTH = 1 << 2; + public static final int SOUTH = 1 << 3; + static final int TILE_AXIS_SHIFT = 3; + static final int TILE_AXIS_MASK = ~((1 << TILE_AXIS_SHIFT) - 1); + static final int TILE_PIXEL_DIAMETER = 1 << TILE_AXIS_SHIFT; + static final int TILE_PIXEL_INDEX_MASK = TILE_PIXEL_DIAMETER - 1; + static final int TILE_PIXEL_INVERSE_MASK = ~TILE_PIXEL_INDEX_MASK; + static final int PRECISION_BITS = 4; + static final int PRECISE_FRACTION_MASK = (1 << PRECISION_BITS) - 1; + static final int PRECISE_INTEGER_MASK = ~PRECISE_FRACTION_MASK; + static final int PRECISE_PIXEL_SIZE = 1 << PRECISION_BITS; + static final int PRECISE_PIXEL_CENTER = PRECISE_PIXEL_SIZE / 2; + static final int SCANT_PRECISE_PIXEL_CENTER = PRECISE_PIXEL_CENTER - 1; + static final int TILE_WIDTH_BITS = 8; + static final int TILE_WIDTH = 1 << TILE_WIDTH_BITS; + static final int TILE_WIDTH_MASK = TILE_WIDTH - 1; + public static final int PIXEL_WIDTH = TILE_WIDTH * TILE_PIXEL_DIAMETER; + static final int MAX_PIXEL_X = PIXEL_WIDTH - 1; + 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; + + /** + * clamp to this to ensure value + half pixel rounds down to last pixel. + */ + static final int PRECISE_WIDTH_CLAMP = PRECISE_WIDTH - PRECISE_PIXEL_CENTER; + static final int TILE_HEIGHT_BITS = 8; + 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; + 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_HALF = CAMERA_PRECISION_UNITY / 2; + static final int BOUNDS_IN = 0; + static final int BOUNDS_OUTSIDE_OR_TOO_SMALL = 1; + static final int B_NEGATIVE = 8; + static final int B_ZERO = 16; + static final int B_POSITIVE = 32; + static final int A_NEGATIVE = 1; + static final int A_ZERO = 2; + static final int A_POSITIVE = 4; + static final int EDGE_TOP = B_NEGATIVE | A_ZERO; + static final int EDGE_BOTTOM = B_POSITIVE | A_ZERO; + static final int EDGE_RIGHT = B_ZERO | A_NEGATIVE; + static final int EDGE_LEFT = B_ZERO | A_POSITIVE; + static final int EDGE_TOP_RIGHT = B_NEGATIVE | A_NEGATIVE; + static final int EDGE_TOP_LEFT = B_NEGATIVE | A_POSITIVE; + static final int EDGE_BOTTOM_RIGHT = B_POSITIVE | A_NEGATIVE; + static final int EDGE_BOTTOM_LEFT = B_POSITIVE | A_POSITIVE; + static final int EDGE_POINT = A_ZERO | B_ZERO; + // subtract 1 to fit in 2 bits + static final int EVENT_0_LEFT = A_POSITIVE - 1; + static final int EVENT_0_FLAT = A_ZERO - 1; + static final int EVENT_0_RIGHT = A_NEGATIVE - 1; + static final int EVENT_POSITION_MASK = 3; + static final int EVENT_1_LEFT = EVENT_0_LEFT << 2; + static final int EVENT_1_FLAT = EVENT_0_FLAT << 2; + static final int EVENT_1_RIGHT = EVENT_0_RIGHT << 2; + static final int EVENT_2_LEFT = EVENT_1_LEFT << 2; + static final int EVENT_2_FLAT = EVENT_1_FLAT << 2; + static final int EVENT_2_RIGHT = EVENT_1_RIGHT << 2; + static final int EVENT_3_LEFT = EVENT_2_LEFT << 2; + static final int EVENT_3_FLAT = EVENT_2_FLAT << 2; + static final int EVENT_3_RIGHT = EVENT_2_RIGHT << 2; + static final int EVENT_012_RRR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT; + static final int EVENT_012_LRR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT; + static final int EVENT_012_FRR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT; + static final int EVENT_012_RLR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT; + static final int EVENT_012_LLR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT; + static final int EVENT_012_FLR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT; + static final int EVENT_012_RFR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT; + static final int EVENT_012_LFR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT; + static final int EVENT_012_FFR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT; + static final int EVENT_012_RRL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT; + static final int EVENT_012_LRL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT; + static final int EVENT_012_FRL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT; + static final int EVENT_012_RLL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT; + static final int EVENT_012_LLL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT; + static final int EVENT_012_FLL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT; + static final int EVENT_012_RFL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT; + static final int EVENT_012_LFL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT; + static final int EVENT_012_FFL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT; + static final int EVENT_012_LRF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT; + static final int EVENT_012_RRF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT; + static final int EVENT_012_FRF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT; + + //// + static final int EVENT_012_RLF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT; + static final int EVENT_012_LLF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT; + static final int EVENT_012_FLF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT; + static final int EVENT_012_RFF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT; + static final int EVENT_012_LFF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT; + static final int EVENT_012_FFF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT; + static final int EVENT_0123_RRRR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_LRRR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_FRRR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_RLRR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_LLRR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_FLRR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_RFRR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_LFRR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_FFRR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_RIGHT; + static final int EVENT_0123_RRLR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_LRLR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_FRLR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_RLLR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_LLLR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_FLLR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_RFLR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_LFLR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_FFLR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_RIGHT; + static final int EVENT_0123_LRFR = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_RRFR = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_FRFR = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_RLFR = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_LLFR = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_FLFR = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_RFFR = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_LFFR = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_FFFR = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_RIGHT; + static final int EVENT_0123_RRRL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_LRRL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_FRRL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_RLRL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_LLRL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_FLRL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_RFRL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_LFRL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_FFRL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_LEFT; + static final int EVENT_0123_RRLL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_LRLL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_FRLL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_RLLL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_LLLL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_FLLL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_RFLL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_LFLL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_FFLL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_LEFT; + static final int EVENT_0123_LRFL = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_RRFL = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_FRFL = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_RLFL = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_LLFL = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_FLFL = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_RFFL = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_LFFL = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_FFFL = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_LEFT; + static final int EVENT_0123_RRRF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_LRRF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_FRRF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_RLRF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_LLRF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_FLRF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_RFRF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_LFRF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_FFRF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_RIGHT | EVENT_3_FLAT; + static final int EVENT_0123_RRLF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_LRLF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_FRLF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_RLLF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_LLLF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_FLLF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_RFLF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_LFLF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_FFLF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_LEFT | EVENT_3_FLAT; + static final int EVENT_0123_LRFF = EVENT_0_LEFT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_RRFF = EVENT_0_RIGHT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_FRFF = EVENT_0_FLAT | EVENT_1_RIGHT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_RLFF = EVENT_0_RIGHT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_LLFF = EVENT_0_LEFT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_FLFF = EVENT_0_FLAT | EVENT_1_LEFT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_RFFF = EVENT_0_RIGHT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_LFFF = EVENT_0_LEFT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_FLAT; + static final int EVENT_0123_FFFF = EVENT_0_FLAT | EVENT_1_FLAT | EVENT_2_FLAT | EVENT_3_FLAT; + + static final int PV_PX = 0; + static final int PV_PY = 1; + static final int PV_X = 2; + static final int PV_Y = 3; + static final int PV_Z = 4; + static final int PV_W = 5; + static final int PROJECTED_VERTEX_STRIDE = 6; + + static final int V000 = 0; + static final int V001 = V000 + PROJECTED_VERTEX_STRIDE; + static final int V010 = V001 + PROJECTED_VERTEX_STRIDE; + static final int V011 = V010 + PROJECTED_VERTEX_STRIDE; + static final int V100 = V011 + PROJECTED_VERTEX_STRIDE; + static final int V101 = V100 + PROJECTED_VERTEX_STRIDE; + static final int V110 = V101 + PROJECTED_VERTEX_STRIDE; + static final int V111 = V110 + PROJECTED_VERTEX_STRIDE; + static final int IDX_AX0 = V111 + PROJECTED_VERTEX_STRIDE; + static final int IDX_AY0 = IDX_AX0 + 1; + static final int IDX_AX1 = IDX_AY0 + 1; + static final int IDX_AY1 = IDX_AX1 + 1; + + static final int IDX_BX0 = IDX_AY1 + 1; + static final int IDX_BY0 = IDX_BX0 + 1; + static final int IDX_BX1 = IDX_BY0 + 1; + static final int IDX_BY1 = IDX_BX1 + 1; + + static final int IDX_CX0 = IDX_BY1 + 1; + static final int IDX_CY0 = IDX_CX0 + 1; + static final int IDX_CX1 = IDX_CY0 + 1; + static final int IDX_CY1 = IDX_CX1 + 1; + + static final int IDX_DX0 = IDX_CY1 + 1; + static final int IDX_DY0 = IDX_DX0 + 1; + static final int IDX_DX1 = IDX_DY0 + 1; + static final int IDX_DY1 = IDX_DX1 + 1; + + static final int VERTEX_DATA_LENGTH = IDX_DY1 + 1; + + static final int EVENT_DATA_LENGTH = PIXEL_HEIGHT * 2; +} diff --git a/common/src/main/java/grondag/bitraster/Indexer.java b/common/src/main/java/grondag/bitraster/Indexer.java new file mode 100644 index 000000000..86c6096f9 --- /dev/null +++ b/common/src/main/java/grondag/bitraster/Indexer.java @@ -0,0 +1,64 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +import static grondag.bitraster.Constants.TILE_AXIS_SHIFT; +import static grondag.bitraster.Constants.TILE_PIXEL_INDEX_MASK; +import static grondag.bitraster.Constants.TILE_WIDTH_BITS; + +abstract class Indexer { + private Indexer() { + } + + // only handle 0-7 values + static int mortonNumber(int x, int y) { + int z = (x & 0b001) | ((y & 0b001) << 1); + z |= ((x & 0b010) << 1) | ((y & 0b010) << 2); + 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) { + return ((y & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (x & TILE_PIXEL_INDEX_MASK); + } + + static boolean isPixelClear(long word, int x, int y) { + return (word & (1L << pixelIndex(x, y))) == 0; + } + + static long pixelMask(int x, int y) { + return 1L << pixelIndex(x, y); + } + + /** + * REQUIRES 0-7 inputs! + */ + static boolean testPixelInWordPreMasked(long word, int x, int y) { + return (word & (1L << ((y << TILE_AXIS_SHIFT) | x))) == 0; + } + + static long setPixelInWordPreMasked(long word, int x, int y) { + return word | (1L << ((y << TILE_AXIS_SHIFT) | x)); + } +} diff --git a/common/src/main/java/grondag/bitraster/LICENSE b/common/src/main/java/grondag/bitraster/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/common/src/main/java/grondag/bitraster/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/common/src/main/java/grondag/bitraster/Matrix4L.java b/common/src/main/java/grondag/bitraster/Matrix4L.java new file mode 100644 index 000000000..66a4021e6 --- /dev/null +++ b/common/src/main/java/grondag/bitraster/Matrix4L.java @@ -0,0 +1,383 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +public class Matrix4L { + public static final int MATRIX_PRECISION_BITS = 16; + public static final long MATRIX_PRECISION_UNITY = 1 << MATRIX_PRECISION_BITS; + public static final long MATRIX_PRECISION_HALF = MATRIX_PRECISION_UNITY / 2; + public static final float FLOAT_CONVERSION = 1f / MATRIX_PRECISION_UNITY; + + private long a00; + private long a01; + private long a02; + private long a03; + private long a10; + private long a11; + private long a12; + private long a13; + private long a20; + private long a21; + private long a22; + private long a23; + private long a30; + private long a31; + private long a32; + private long a33; + + @Override + public String toString() { + return String.format("[%d, %d, %d, %d], [%d, %d, %d, %d], [%d, %d, %d, %d], [%d, %d, %d, %d]", + a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33); + } + + public void set( + float a00, float a01, float a02, float a03, + float a10, float a11, float a12, float a13, + float a20, float a21, float a22, float a23, + float a30, float a31, float a32, float a33 + ) { + this.a00 = Math.round(a00 * MATRIX_PRECISION_UNITY); + this.a01 = Math.round(a01 * MATRIX_PRECISION_UNITY); + this.a02 = Math.round(a02 * MATRIX_PRECISION_UNITY); + this.a03 = Math.round(a03 * MATRIX_PRECISION_UNITY); + + this.a10 = Math.round(a10 * MATRIX_PRECISION_UNITY); + this.a11 = Math.round(a11 * MATRIX_PRECISION_UNITY); + this.a12 = Math.round(a12 * MATRIX_PRECISION_UNITY); + this.a13 = Math.round(a13 * MATRIX_PRECISION_UNITY); + + this.a20 = Math.round(a20 * MATRIX_PRECISION_UNITY); + this.a21 = Math.round(a21 * MATRIX_PRECISION_UNITY); + this.a22 = Math.round(a22 * MATRIX_PRECISION_UNITY); + this.a23 = Math.round(a23 * MATRIX_PRECISION_UNITY); + + this.a30 = Math.round(a30 * MATRIX_PRECISION_UNITY); + this.a31 = Math.round(a31 * MATRIX_PRECISION_UNITY); + this.a32 = Math.round(a32 * MATRIX_PRECISION_UNITY); + this.a33 = Math.round(a33 * MATRIX_PRECISION_UNITY); + } + + public void copyFrom(Matrix4L other) { + a00 = other.a00; + a01 = other.a01; + a02 = other.a02; + a03 = other.a03; + + a10 = other.a10; + a11 = other.a11; + a12 = other.a12; + a13 = other.a13; + + a20 = other.a20; + a21 = other.a21; + a22 = other.a22; + a23 = other.a23; + + a30 = other.a30; + a31 = other.a31; + a32 = other.a32; + a33 = other.a33; + } + + public boolean matches(Matrix4L other) { + return a00 == other.a00 + && a01 == other.a01 + && a02 == other.a02 + && a03 == other.a03 + + && a10 == other.a10 + && a11 == other.a11 + && a12 == other.a12 + && a13 == other.a13 + + && a20 == other.a20 + && a21 == other.a21 + && a22 == other.a22 + && a23 == other.a23 + + && a30 == other.a30 + && a31 == other.a31 + && a32 == other.a32 + && a33 == other.a33; + } + + public void loadIdentity() { + a00 = MATRIX_PRECISION_UNITY; + a01 = 0; + a02 = 0; + a03 = 0; + a10 = 0; + a11 = MATRIX_PRECISION_UNITY; + a12 = 0; + a13 = 0; + a20 = 0; + a21 = 0; + a22 = MATRIX_PRECISION_UNITY; + a23 = 0; + a30 = 0; + a31 = 0; + a32 = 0; + a33 = MATRIX_PRECISION_UNITY; + } + + public void multiply(Matrix4L other) { + final long f = a00 * other.a00 + a01 * other.a10 + a02 * other.a20 + a03 * other.a30; + final long g = a00 * other.a01 + a01 * other.a11 + a02 * other.a21 + a03 * other.a31; + final long h = a00 * other.a02 + a01 * other.a12 + a02 * other.a22 + a03 * other.a32; + final long i = a00 * other.a03 + a01 * other.a13 + a02 * other.a23 + a03 * other.a33; + final long j = a10 * other.a00 + a11 * other.a10 + a12 * other.a20 + a13 * other.a30; + final long k = a10 * other.a01 + a11 * other.a11 + a12 * other.a21 + a13 * other.a31; + final long l = a10 * other.a02 + a11 * other.a12 + a12 * other.a22 + a13 * other.a32; + final long m = a10 * other.a03 + a11 * other.a13 + a12 * other.a23 + a13 * other.a33; + final long n = a20 * other.a00 + a21 * other.a10 + a22 * other.a20 + a23 * other.a30; + final long o = a20 * other.a01 + a21 * other.a11 + a22 * other.a21 + a23 * other.a31; + final long p = a20 * other.a02 + a21 * other.a12 + a22 * other.a22 + a23 * other.a32; + final long q = a20 * other.a03 + a21 * other.a13 + a22 * other.a23 + a23 * other.a33; + final long r = a30 * other.a00 + a31 * other.a10 + a32 * other.a20 + a33 * other.a30; + final long s = a30 * other.a01 + a31 * other.a11 + a32 * other.a21 + a33 * other.a31; + final long t = a30 * other.a02 + a31 * other.a12 + a32 * other.a22 + a33 * other.a32; + final long u = a30 * other.a03 + a31 * other.a13 + a32 * other.a23 + a33 * other.a33; + a00 = ((f + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a01 = ((g + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a02 = ((h + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a03 = ((i + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a10 = ((j + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a11 = ((k + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a12 = ((l + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a13 = ((m + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a20 = ((n + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a21 = ((o + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a22 = ((p + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a23 = ((q + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a30 = ((r + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a31 = ((s + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a32 = ((t + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a33 = ((u + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + } + + public void translate(long x, long y, long z, int precision) { + final int shift = MATRIX_PRECISION_BITS - precision; + assert shift >= 0; + + final long t_a03 = x << shift; + final long t_a13 = y << shift; + final long t_a23 = z << shift; + + final long i = a00 * t_a03 + a01 * t_a13 + a02 * t_a23 + a03; + final long m = a10 * t_a03 + a11 * t_a13 + a12 * t_a23 + a13; + final long q = a20 * t_a03 + a21 * t_a13 + a22 * t_a23 + a23; + final long u = a30 * t_a03 + a31 * t_a13 + a32 * t_a23 + a33; + + a03 += ((i + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a13 += ((m + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a23 += ((q + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + a33 += ((u + MATRIX_PRECISION_HALF) >> MATRIX_PRECISION_BITS); + } + + public float a00f() { + return FLOAT_CONVERSION * a00; + } + + public float a01f() { + return FLOAT_CONVERSION * a01; + } + + public float a02f() { + return FLOAT_CONVERSION * a02; + } + + public float a03f() { + return FLOAT_CONVERSION * a03; + } + + public float a10f() { + return FLOAT_CONVERSION * a10; + } + + public float a11f() { + return FLOAT_CONVERSION * a11; + } + + public float a12f() { + return FLOAT_CONVERSION * a12; + } + + public float a13f() { + return FLOAT_CONVERSION * a13; + } + + public float a20f() { + return FLOAT_CONVERSION * a20; + } + + public float a21f() { + return FLOAT_CONVERSION * a21; + } + + public float a22f() { + return FLOAT_CONVERSION * a22; + } + + public float a23f() { + return FLOAT_CONVERSION * a23; + } + + public float a30f() { + return FLOAT_CONVERSION * a30; + } + + public float a31f() { + return FLOAT_CONVERSION * a31; + } + + public float a32f() { + return FLOAT_CONVERSION * a32; + } + + public float a33f() { + return FLOAT_CONVERSION * a33; + } + + public long a00() { + return a00; + } + + public long a01() { + return a01; + } + + public long a02() { + return a02; + } + + public long a03() { + return a03; + } + + public long a10() { + return a10; + } + + public long a11() { + return a11; + } + + public long a12() { + return a12; + } + + public long a13() { + return a13; + } + + public long a20() { + return a20; + } + + public long a21() { + return a21; + } + + public long a22() { + return a22; + } + + public long a23() { + return a23; + } + + public long a30() { + return a30; + } + + public long a31() { + return a31; + } + + public long a32() { + return a32; + } + + public long a33() { + return a33; + } + + /** + * Computes X component of transformed vector. Assumes input W is 1. + * Result has standard precision. + */ + public long transformVec4X(int x, int y, int z) { + return a00 * x + a01 * y + a02 * z + a03; + } + + /** + * Computes Y component of transformed vector. Assumes input W is 1. + * Result has standard precision. + */ + public long transformVec4Y(int x, int y, int z) { + return a10 * x + a11 * y + a12 * z + a13; + } + + /** + * Computes Z component of transformed vector. Assumes input W is 1. + * Result has standard precision. + */ + public long transformVec4Z(int x, int y, int z) { + return a20 * x + a21 * y + a22 * z + a23; + } + + /** + * Computes W component of transformed vector. Assumes input W is 1. + * Result has standard precision. + */ + public long transformVec4W(int x, int y, int z) { + return a30 * x + a31 * y + a32 * z + a33; + } + + /** + * Computes X component of transformed vector. + * Result has standard precision. + */ + public long transformVec4X(int x, int y, int z, int w) { + return a00 * x + a01 * y + a02 * z + a03 * w; + } + + /** + * Computes Y component of transformed vector. + * Result has standard precision. + */ + public long transformVec4Y(int x, int y, int z, int w) { + return a10 * x + a11 * y + a12 * z + a13 * w; + } + + /** + * Computes Z component of transformed vector. + * Result has standard precision. + */ + public long transformVec4Z(int x, int y, int z, int w) { + return a20 * x + a21 * y + a22 * z + a23 * w; + } + + /** + * Computes W component of transformed vector. + * Result has standard precision. + */ + public long transformVec4W(int x, int y, int z, int w) { + return a30 * x + a31 * y + a32 * z + a33 * w; + } +} diff --git a/common/src/main/java/grondag/bitraster/MicroTimer.java b/common/src/main/java/grondag/bitraster/MicroTimer.java new file mode 100644 index 000000000..8d38c352e --- /dev/null +++ b/common/src/main/java/grondag/bitraster/MicroTimer.java @@ -0,0 +1,120 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +/** + * For crude but simple microbenchmarks - for small scope, in-game situations + * where JMH would be more than I want. + */ +public class MicroTimer { + private final int sampleSize; + private final String label; + private int hits; + private long elapsed; + private long min; + private long max; + private long started; + + private int subsetHits; + private long subsetElapsed; + private long subsetMin; + private long subsetMax; + + public MicroTimer(String label, int sampleSize) { + this.label = label; + this.sampleSize = sampleSize; + } + + public int hits() { + return hits; + } + + public long elapsed() { + return elapsed; + } + + public void start() { + started = System.nanoTime(); + } + + /** + * Returns true if timer output stats this sample. For use if want to output + * supplementary information at same time. + */ + public boolean stop(boolean subset) { + final long t = System.nanoTime() - started; + elapsed += t; + + if (t < min) { + min = t; + } + + if (t > max) { + max = t; + } + + if (subset) { + ++subsetHits; + subsetElapsed += t; + + if (t < subsetMin) { + subsetMin = t; + } + + if (t > subsetMax) { + subsetMax = t; + } + } + + final long h = ++hits; + + if (h == sampleSize) { + reportAndClear(); + return true; + } else { + return false; + } + } + + public void reportAndClear() { + if (hits == 0) { + hits = 1; + } + + System.out.println(String.format("Avg %s duration = %,d ns, min = %d, max = %d, total duration = %,d, total runs = %,d", label, + elapsed / hits, min, max, elapsed / 1000000, hits)); + + if (subsetHits > 0) { + if (subsetElapsed == 0) { + subsetElapsed = 1; + } + + System.out.println(String.format("Subset avg duration = %,d ns, min = %d, max = %d, total duration = %,d, (%d) total runs = %,d", + subsetElapsed / subsetHits, subsetMin, subsetMax, subsetElapsed / 1000000, subsetElapsed * 100L / elapsed, subsetHits)); + + subsetHits = 0; + subsetElapsed = 0; + subsetMax = Long.MIN_VALUE; + subsetMin = Long.MAX_VALUE; + } + + hits = 0; + elapsed = 0; + max = Long.MIN_VALUE; + min = Long.MAX_VALUE; + } +} diff --git a/common/src/main/java/grondag/bitraster/OrthoRasterizer.java b/common/src/main/java/grondag/bitraster/OrthoRasterizer.java new file mode 100644 index 000000000..569daa5df --- /dev/null +++ b/common/src/main/java/grondag/bitraster/OrthoRasterizer.java @@ -0,0 +1,48 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +import static grondag.bitraster.Constants.HALF_PRECISE_HEIGHT; +import static grondag.bitraster.Constants.HALF_PRECISE_WIDTH; +import static grondag.bitraster.Constants.PV_PX; +import static grondag.bitraster.Constants.PV_PY; +import static grondag.bitraster.Constants.PV_X; +import static grondag.bitraster.Constants.PV_Y; + +public final class OrthoRasterizer extends AbstractRasterizer { + @Override + int prepareBounds(int v0, int v1, int v2, int v3) { + return prepareBoundsNoClip(v0, v1, v2, v3); + } + + @Override void setupVertex(final int baseIndex, final int x, final int y, final int z) { + final int[] data = vertexData; + final Matrix4L mvpMatrix = this.mvpMatrix; + + final float tx = mvpMatrix.transformVec4X(x, y, z) * Matrix4L.FLOAT_CONVERSION; + final float ty = mvpMatrix.transformVec4Y(x, y, z) * Matrix4L.FLOAT_CONVERSION; + + data[baseIndex + PV_X] = Float.floatToRawIntBits(tx); + data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty); + + final int px = Math.round(tx * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; + final int py = Math.round(ty * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; + + data[baseIndex + PV_PX] = px; + data[baseIndex + PV_PY] = py; + } +} diff --git a/common/src/main/java/grondag/bitraster/PackedBox.java b/common/src/main/java/grondag/bitraster/PackedBox.java new file mode 100644 index 000000000..eb5cbc58c --- /dev/null +++ b/common/src/main/java/grondag/bitraster/PackedBox.java @@ -0,0 +1,89 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +public abstract class PackedBox { + public static final int RANGE_NEAR = 0; + public static final int RANGE_MID = 1; + public static final int RANGE_FAR = 2; + public static final int RANGE_EXTREME = 3; + public static final int CHUNK_DIST_NEAR = 1; + public static final int CHUNK_DIST_MID = 2; + public static final int CHUNK_DIST_FAR = 8; + public static final int SQUARE_CHUNK_DIST_NEAR = CHUNK_DIST_NEAR * CHUNK_DIST_NEAR * 3; + public static final int SQUARE_CHUNK_DIST_MID = CHUNK_DIST_MID * CHUNK_DIST_MID * 3; + public static final int SQUARE_CHUNK_DIST_FAR = CHUNK_DIST_FAR * CHUNK_DIST_FAR * 3; + public static final int EMPTY_BOX = 0; + private static final int SHIFT_X0 = 0; + private static final int SHIFT_Y0 = SHIFT_X0 + 5; + private static final int SHIFT_Z0 = SHIFT_Y0 + 5; + private static final int SHIFT_X1 = SHIFT_Z0 + 5; + private static final int SHIFT_Y1 = SHIFT_X1 + 5; + private static final int SHIFT_Z1 = SHIFT_Y1 + 5; + private static final int SHIFT_RANGE = SHIFT_Z1 + 5; + public static final int FULL_BOX = pack(0, 0, 0, 16, 16, 16, RANGE_EXTREME); + + private PackedBox() { + } + + public static int rangeFromSquareChunkDist(int squareChunkDist) { + if (squareChunkDist <= SQUARE_CHUNK_DIST_MID) { + return squareChunkDist > SQUARE_CHUNK_DIST_NEAR ? RANGE_MID : RANGE_NEAR; + } else { + return squareChunkDist > SQUARE_CHUNK_DIST_FAR ? RANGE_EXTREME : RANGE_FAR; + } + } + + public static int pack(int x0, int y0, int z0, int x1, int y1, int z1, int range) { + return x0 | (y0 << SHIFT_Y0) | (z0 << SHIFT_Z0) + | ((x1) << SHIFT_X1) | ((y1) << SHIFT_Y1) | ((z1) << SHIFT_Z1) + | (range << SHIFT_RANGE); + } + + public static int range(int packed) { + return (packed >>> SHIFT_RANGE) & 3; + } + + public static int x0(int packed) { + return (packed & 31); + } + + public static int y0(int packed) { + return (packed >>> SHIFT_Y0) & 31; + } + + public static int z0(int packed) { + return (packed >>> SHIFT_Z0) & 31; + } + + public static int x1(int packed) { + return ((packed >>> SHIFT_X1) & 31); + } + + public static int y1(int packed) { + return ((packed >>> SHIFT_Y1) & 31); + } + + public static int z1(int packed) { + return ((packed >>> SHIFT_Z1) & 31); + } + + public static String toString(int packed) { + return "(" + x0(packed) + ", " + y0(packed) + ", " + z0(packed) + "), (" + + x1(packed) + ", " + y1(packed) + ", " + z1(packed) + ")"; + } +} diff --git a/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java b/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java new file mode 100644 index 000000000..5d839112b --- /dev/null +++ b/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java @@ -0,0 +1,755 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +import static grondag.bitraster.Constants.BOUNDS_IN; +import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; +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_AX1; +import static grondag.bitraster.Constants.IDX_AY0; +import static grondag.bitraster.Constants.IDX_AY1; +import static grondag.bitraster.Constants.IDX_BX0; +import static grondag.bitraster.Constants.IDX_BX1; +import static grondag.bitraster.Constants.IDX_BY0; +import static grondag.bitraster.Constants.IDX_BY1; +import static grondag.bitraster.Constants.IDX_CX0; +import static grondag.bitraster.Constants.IDX_CX1; +import static grondag.bitraster.Constants.IDX_CY0; +import static grondag.bitraster.Constants.IDX_CY1; +import static grondag.bitraster.Constants.IDX_DX0; +import static grondag.bitraster.Constants.IDX_DX1; +import static grondag.bitraster.Constants.IDX_DY0; +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.PV_PX; +import static grondag.bitraster.Constants.PV_PY; +import static grondag.bitraster.Constants.PV_W; +import static grondag.bitraster.Constants.PV_X; +import static grondag.bitraster.Constants.PV_Y; +import static grondag.bitraster.Constants.PV_Z; +import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER; + +public final class PerspectiveRasterizer extends AbstractRasterizer { + /** Holds results of {@link #clipNear(int, int)}. */ + private int clipX, clipY; + + @Override void setupVertex(final int baseIndex, final int x, final int y, final int z) { + final int[] data = vertexData; + final Matrix4L mvpMatrix = this.mvpMatrix; + + final float tx = mvpMatrix.transformVec4X(x, y, z) * Matrix4L.FLOAT_CONVERSION; + final float ty = mvpMatrix.transformVec4Y(x, y, z) * Matrix4L.FLOAT_CONVERSION; + final float w = mvpMatrix.transformVec4W(x, y, z) * Matrix4L.FLOAT_CONVERSION; + + data[baseIndex + PV_X] = Float.floatToRawIntBits(tx); + data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty); + data[baseIndex + PV_Z] = Float.floatToRawIntBits(mvpMatrix.transformVec4Z(x, y, z) * Matrix4L.FLOAT_CONVERSION); + data[baseIndex + PV_W] = Float.floatToRawIntBits(w); + + if (w != 0) { + final float iw = 1f / w; + final int px = Math.round(tx * iw * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; + final int py = Math.round(ty * iw * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; + + data[baseIndex + PV_PX] = px; + data[baseIndex + PV_PY] = py; + } + } + + private void clipNear(int internal, int external) { + final int[] data = vertexData; + + final float intX = Float.intBitsToFloat(data[internal + PV_X]); + final float intY = Float.intBitsToFloat(data[internal + PV_Y]); + final float intZ = Float.intBitsToFloat(data[internal + PV_Z]); + final float intW = Float.intBitsToFloat(data[internal + PV_W]); + + final float extX = Float.intBitsToFloat(data[external + PV_X]); + final float extY = Float.intBitsToFloat(data[external + PV_Y]); + final float extZ = Float.intBitsToFloat(data[external + PV_Z]); + final float extW = Float.intBitsToFloat(data[external + PV_W]); + + // intersection point is the projection plane, at which point Z == 1 + // and w will be 0 but projection division isn't needed, so force output to W = 1 + // see https://www.cs.usfca.edu/~cruse/math202s11/homocoords.pdf + + final float wt = intZ / -(extZ - intZ); + + // note again that projection division isn't needed + final float x = (intX + (extX - intX) * wt); + final float y = (intY + (extY - intY) * wt); + final float w = (intW + (extW - intW) * wt); + final float iw = 1f / w; + + clipX = Math.round(iw * x * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; + clipY = Math.round(iw * y * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; + } + + @Override + int prepareBounds(int v0, int v1, int v2, int v3) { + // puts bits in lexical order + final int split = needsNearClip(v3) | (needsNearClip(v2) << 1) | (needsNearClip(v1) << 2) | (needsNearClip(v0) << 3); + + switch (split) { + case 0b0000: + return prepareBounds0000(v0, v1, v2, v3); + + case 0b0001: + return prepareBounds0001(v0, v1, v2, v3); + + case 0b0010: + return prepareBounds0001(v3, v0, v1, v2); + + case 0b0100: + return prepareBounds0001(v2, v3, v0, v1); + + case 0b1000: + return prepareBounds0001(v1, v2, v3, v0); + + case 0b0011: + return prepareBounds0011(v0, v1, v2, v3); + + case 0b1001: + return prepareBounds0011(v1, v2, v3, v0); + + case 0b1100: + return prepareBounds0011(v2, v3, v0, v1); + + case 0b0110: + return prepareBounds0011(v3, v0, v1, v2); + + case 0b0111: + return prepareBounds0111(v0, v1, v2, v3); + + case 0b1011: + return prepareBounds0111(v1, v2, v3, v0); + + case 0b1101: + return prepareBounds0111(v2, v3, v0, v1); + + case 0b1110: + return prepareBounds0111(v3, v0, v1, v2); + + case 0b1111: + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + + default: + assert false : "Occlusion edge case"; + // NOOP + } + + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + private int prepareBounds0000(int v0, int v1, int v2, int v3) { + final int[] data = vertexData; + int ax0, ay0, ax1, ay1; + int bx0, by0, bx1, by1; + int cx0, cy0, cx1, cy1; + int dx0, dy0, dx1, dy1; + int minY = 0, maxY = 0, minX = 0, maxX = 0; + + ax0 = data[v0 + PV_PX]; + ay0 = data[v0 + PV_PY]; + bx0 = data[v1 + PV_PX]; + by0 = data[v1 + PV_PY]; + cx0 = data[v2 + PV_PX]; + cy0 = data[v2 + PV_PY]; + dx0 = data[v3 + PV_PX]; + dy0 = data[v3 + PV_PY]; + + ax1 = bx0; + ay1 = by0; + bx1 = cx0; + by1 = cy0; + cx1 = dx0; + cy1 = dy0; + dx1 = ax0; + dy1 = ay0; + + minX = ax0; + maxX = ax0; + + if (bx0 < minX) { + minX = bx0; + } else if (bx0 > maxX) { + maxX = bx0; + } + + if (cx0 < minX) { + minX = cx0; + } else if (cx0 > maxX) { + maxX = cx0; + } + + if (dx0 < minX) { + minX = dx0; + } else if (dx0 > maxX) { + maxX = dx0; + } + + minY = ay0; + maxY = ay0; + + if (by0 < minY) { + minY = by0; + } else if (by0 > maxY) { + maxY = by0; + } + + if (cy0 < minY) { + minY = cy0; + } else if (cy0 > maxY) { + maxY = cy0; + } + + if (dy0 < minY) { + minY = dy0; + } else if (dy0 > maxY) { + maxY = dy0; + } + + if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (maxX <= 0 || minX >= PRECISE_WIDTH) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (minX < 0) { + minX = 0; + } + + if (maxX >= PRECISE_WIDTH_CLAMP) { + maxX = PRECISE_WIDTH_CLAMP; + + if (minX > PRECISE_WIDTH_CLAMP) { + minX = PRECISE_WIDTH_CLAMP; + } + } + + if (minY < 0) { + minY = 0; + } + + if (maxY >= PRECISE_HEIGHT_CLAMP) { + maxY = PRECISE_HEIGHT_CLAMP; + + if (minY > PRECISE_HEIGHT_CLAMP) { + minY = PRECISE_HEIGHT_CLAMP; + } + } + + final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + + final int position0 = edgePosition(ax0, ay0, ax1, ay1); + final int position1 = edgePosition(bx0, by0, bx1, by1); + final int position2 = edgePosition(cx0, cy0, cx1, cy1); + final int position3 = edgePosition(dx0, dy0, dx1, dy1); + + this.minPixelX = minPixelX; + this.minPixelY = minPixelY; + this.maxPixelX = maxPixelX; + this.maxPixelY = maxPixelY; + data[IDX_AX0] = ax0; + data[IDX_AY0] = ay0; + data[IDX_AX1] = ax1; + data[IDX_AY1] = ay1; + data[IDX_BX0] = bx0; + data[IDX_BY0] = by0; + data[IDX_BX1] = bx1; + data[IDX_BY1] = by1; + data[IDX_CX0] = cx0; + data[IDX_CY0] = cy0; + data[IDX_CX1] = cx1; + data[IDX_CY1] = cy1; + data[IDX_DX0] = dx0; + data[IDX_DY0] = dy0; + data[IDX_DX1] = dx1; + data[IDX_DY1] = dy1; + pos0 = position0; + pos1 = position1; + pos2 = position2; + pos3 = position3; + + final int eventKey = (position0 - 1) & EVENT_POSITION_MASK + | (((position1 - 1) & EVENT_POSITION_MASK) << 2) + | (((position2 - 1) & EVENT_POSITION_MASK) << 4) + | (((position3 - 1) & EVENT_POSITION_MASK) << 6); + + prepareEvents(eventKey); + return BOUNDS_IN; + } + + private int prepareBounds0001(int v0, int v1, int v2, int ext3) { + final int[] data = vertexData; + int ax0, ay0, ax1, ay1; + int bx0, by0, bx1, by1; + int cx0, cy0, cx1, cy1; + int dx0, dy0, dx1, dy1; + int minY = 0, maxY = 0, minX = 0, maxX = 0; + + ax0 = data[v0 + PV_PX]; + ay0 = data[v0 + PV_PY]; + ax1 = data[v1 + PV_PX]; + ay1 = data[v1 + PV_PY]; + + bx0 = ax1; + by0 = ay1; + bx1 = data[v2 + PV_PX]; + by1 = data[v2 + PV_PY]; + + cx0 = bx1; + cy0 = by1; + clipNear(v2, ext3); + cx1 = clipX; + cy1 = clipY; + + clipNear(v0, ext3); + dx0 = clipX; + dy0 = clipY; + dx1 = ax0; + dy1 = ay0; + + minX = ax0; + maxX = ax0; + + // ax1 = bx0 and dx1 = ax0, so no need to test those + if (bx0 < minX) { + minX = bx0; + } else if (bx0 > maxX) { + maxX = bx0; + } + + if (cx0 < minX) { + minX = cx0; + } else if (cx0 > maxX) { + maxX = cx0; + } + + if (cx1 < minX) { + minX = cx1; + } else if (cx1 > maxX) { + maxX = cx1; + } + + if (dx0 < minX) { + minX = dx0; + } else if (dx0 > maxX) { + maxX = dx0; + } + + minY = ay0; + maxY = ay0; + + if (by0 < minY) { + minY = by0; + } else if (by0 > maxY) { + maxY = by0; + } + + if (cy0 < minY) { + minY = cy0; + } else if (cy0 > maxY) { + maxY = cy0; + } + + if (cy1 < minY) { + minY = cy1; + } else if (cy1 > maxY) { + maxY = cy1; + } + + if (dy0 < minY) { + minY = dy0; + } else if (dy0 > maxY) { + maxY = dy0; + } + + if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (maxX <= 0 || minX >= PRECISE_WIDTH) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (minX < 0) { + minX = 0; + } + + if (maxX >= PRECISE_WIDTH_CLAMP) { + maxX = PRECISE_WIDTH_CLAMP; + + if (minX > PRECISE_WIDTH_CLAMP) { + minX = PRECISE_WIDTH_CLAMP; + } + } + + if (minY < 0) { + minY = 0; + } + + if (maxY >= PRECISE_HEIGHT_CLAMP) { + maxY = PRECISE_HEIGHT_CLAMP; + + if (minY > PRECISE_HEIGHT_CLAMP) { + minY = PRECISE_HEIGHT_CLAMP; + } + } + + final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + + final int position0 = edgePosition(ax0, ay0, ax1, ay1); + final int position1 = edgePosition(bx0, by0, bx1, by1); + final int position2 = edgePosition(cx0, cy0, cx1, cy1); + final int position3 = edgePosition(dx0, dy0, dx1, dy1); + + this.minPixelX = minPixelX; + this.minPixelY = minPixelY; + this.maxPixelX = maxPixelX; + this.maxPixelY = maxPixelY; + data[IDX_AX0] = ax0; + data[IDX_AY0] = ay0; + data[IDX_AX1] = ax1; + data[IDX_AY1] = ay1; + data[IDX_BX0] = bx0; + data[IDX_BY0] = by0; + data[IDX_BX1] = bx1; + data[IDX_BY1] = by1; + data[IDX_CX0] = cx0; + data[IDX_CY0] = cy0; + data[IDX_CX1] = cx1; + data[IDX_CY1] = cy1; + data[IDX_DX0] = dx0; + data[IDX_DY0] = dy0; + data[IDX_DX1] = dx1; + data[IDX_DY1] = dy1; + pos0 = position0; + pos1 = position1; + pos2 = position2; + pos3 = position3; + + final int eventKey = (position0 - 1) & EVENT_POSITION_MASK + | (((position1 - 1) & EVENT_POSITION_MASK) << 2) + | (((position2 - 1) & EVENT_POSITION_MASK) << 4) + | (((position3 - 1) & EVENT_POSITION_MASK) << 6); + + prepareEvents(eventKey); + return BOUNDS_IN; + } + + private int prepareBounds0011(int v0, int v1, int ext2, int ext3) { + final int[] data = vertexData; + int ax0, ay0, ax1, ay1; + int bx0, by0, bx1, by1; + int cx0, cy0, cx1, cy1; + int dx0, dy0, dx1, dy1; + + int minY = 0, maxY = 0, minX = 0, maxX = 0; + + ax0 = data[v0 + PV_PX]; + ay0 = data[v0 + PV_PY]; + ax1 = data[v1 + PV_PX]; + ay1 = data[v1 + PV_PY]; + + bx0 = ax1; + by0 = ay1; + clipNear(v1, ext2); + bx1 = clipX; + by1 = clipY; + + // force line c to be a single, existing point - entire line is clipped and should not influence anything + cx0 = ax0; + cy0 = ay0; + cx1 = ax0; + cy1 = ay0; + + clipNear(v0, ext3); + dx0 = clipX; + dy0 = clipY; + dx1 = ax0; + dy1 = ay0; + + minX = ax0; + maxX = ax0; + + if (bx0 < minX) { + minX = bx0; + } else if (bx0 > maxX) { + maxX = bx0; + } + + if (bx1 < minX) { + minX = bx1; + } else if (bx1 > maxX) { + maxX = bx1; + } + + if (dx0 < minX) { + minX = dx0; + } else if (dx0 > maxX) { + maxX = dx0; + } + + minY = ay0; + maxY = ay0; + + if (by0 < minY) { + minY = by0; + } else if (by0 > maxY) { + maxY = by0; + } + + if (by1 < minY) { + minY = by1; + } else if (by1 > maxY) { + maxY = by1; + } + + if (dy0 < minY) { + minY = dy0; + } else if (dy0 > maxY) { + maxY = dy0; + } + + if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (maxX <= 0 || minX >= PRECISE_WIDTH) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (minX < 0) { + minX = 0; + } + + if (maxX >= PRECISE_WIDTH_CLAMP) { + maxX = PRECISE_WIDTH_CLAMP; + + if (minX > PRECISE_WIDTH_CLAMP) { + minX = PRECISE_WIDTH_CLAMP; + } + } + + if (minY < 0) { + minY = 0; + } + + if (maxY >= PRECISE_HEIGHT_CLAMP) { + maxY = PRECISE_HEIGHT_CLAMP; + + if (minY > PRECISE_HEIGHT_CLAMP) { + minY = PRECISE_HEIGHT_CLAMP; + } + } + + final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + + final int position0 = edgePosition(ax0, ay0, ax1, ay1); + final int position1 = edgePosition(bx0, by0, bx1, by1); + final int position2 = edgePosition(cx0, cy0, cx1, cy1); + final int position3 = edgePosition(dx0, dy0, dx1, dy1); + + this.minPixelX = minPixelX; + this.minPixelY = minPixelY; + this.maxPixelX = maxPixelX; + this.maxPixelY = maxPixelY; + data[IDX_AX0] = ax0; + data[IDX_AY0] = ay0; + data[IDX_AX1] = ax1; + data[IDX_AY1] = ay1; + data[IDX_BX0] = bx0; + data[IDX_BY0] = by0; + data[IDX_BX1] = bx1; + data[IDX_BY1] = by1; + data[IDX_CX0] = cx0; + data[IDX_CY0] = cy0; + data[IDX_CX1] = cx1; + data[IDX_CY1] = cy1; + data[IDX_DX0] = dx0; + data[IDX_DY0] = dy0; + data[IDX_DX1] = dx1; + data[IDX_DY1] = dy1; + pos0 = position0; + pos1 = position1; + pos2 = position2; + pos3 = position3; + + final int eventKey = (position0 - 1) & EVENT_POSITION_MASK + | (((position1 - 1) & EVENT_POSITION_MASK) << 2) + | (((position2 - 1) & EVENT_POSITION_MASK) << 4) + | (((position3 - 1) & EVENT_POSITION_MASK) << 6); + + prepareEvents(eventKey); + return BOUNDS_IN; + } + + private int prepareBounds0111(int v0, int ext1, int ext2, int ext3) { + final int[] data = vertexData; + int ax0, ay0, ax1, ay1; + int bx0, by0, bx1, by1; + int cx0, cy0, cx1, cy1; + int dx0, dy0, dx1, dy1; + int minY = 0, maxY = 0, minX = 0, maxX = 0; + + ax0 = data[v0 + PV_PX]; + ay0 = data[v0 + PV_PY]; + clipNear(v0, ext1); + ax1 = clipX; + ay1 = clipY; + + // force lines b & c to be a single, existing point - entire line is clipped and should not influence anything + bx0 = ax0; + by0 = ay0; + bx1 = ax0; + by1 = ay0; + cx0 = ax0; + cy0 = ay0; + cx1 = ax0; + cy1 = ay0; + + clipNear(v0, ext3); + dx0 = clipX; + dy0 = clipY; + dx1 = ax0; + dy1 = ay0; + + minX = ax0; + maxX = ax0; + + if (ax1 < minX) { + minX = ax1; + } else if (ax1 > maxX) { + maxX = ax1; + } + + if (dx0 < minX) { + minX = dx0; + } else if (dx0 > maxX) { + maxX = dx0; + } + + minY = ay0; + maxY = ay0; + + if (ay1 < minY) { + minY = ay1; + } else if (ay1 > maxY) { + maxY = ay1; + } + + if (dy0 < minY) { + minY = dy0; + } else if (dy0 > maxY) { + maxY = dy0; + } + + if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (maxX <= 0 || minX >= PRECISE_WIDTH) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (minX < 0) { + minX = 0; + } + + if (maxX >= PRECISE_WIDTH_CLAMP) { + maxX = PRECISE_WIDTH_CLAMP; + + if (minX > PRECISE_WIDTH_CLAMP) { + minX = PRECISE_WIDTH_CLAMP; + } + } + + if (minY < 0) { + minY = 0; + } + + if (maxY >= PRECISE_HEIGHT_CLAMP) { + maxY = PRECISE_HEIGHT_CLAMP; + + if (minY > PRECISE_HEIGHT_CLAMP) { + minY = PRECISE_HEIGHT_CLAMP; + } + } + + final int minPixelX = ((minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int minPixelY = ((minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelX = ((maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + final int maxPixelY = ((maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); + + final int position0 = edgePosition(ax0, ay0, ax1, ay1); + final int position1 = edgePosition(bx0, by0, bx1, by1); + final int position2 = edgePosition(cx0, cy0, cx1, cy1); + final int position3 = edgePosition(dx0, dy0, dx1, dy1); + + this.minPixelX = minPixelX; + this.minPixelY = minPixelY; + this.maxPixelX = maxPixelX; + this.maxPixelY = maxPixelY; + data[IDX_AX0] = ax0; + data[IDX_AY0] = ay0; + data[IDX_AX1] = ax1; + data[IDX_AY1] = ay1; + data[IDX_BX0] = bx0; + data[IDX_BY0] = by0; + data[IDX_BX1] = bx1; + data[IDX_BY1] = by1; + data[IDX_CX0] = cx0; + data[IDX_CY0] = cy0; + data[IDX_CX1] = cx1; + data[IDX_CY1] = cy1; + data[IDX_DX0] = dx0; + data[IDX_DY0] = dy0; + data[IDX_DX1] = dx1; + data[IDX_DY1] = dy1; + pos0 = position0; + pos1 = position1; + pos2 = position2; + pos3 = position3; + + final int eventKey = (position0 - 1) & EVENT_POSITION_MASK + | (((position1 - 1) & EVENT_POSITION_MASK) << 2) + | (((position2 - 1) & EVENT_POSITION_MASK) << 4) + | (((position3 - 1) & EVENT_POSITION_MASK) << 6); + + prepareEvents(eventKey); + return BOUNDS_IN; + } +} diff --git a/common/src/main/java/grondag/bitraster/Util.java b/common/src/main/java/grondag/bitraster/Util.java new file mode 100644 index 000000000..b044d6dbd --- /dev/null +++ b/common/src/main/java/grondag/bitraster/Util.java @@ -0,0 +1,38 @@ +/* + * Copyright 2019, 2020 grondag + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package grondag.bitraster; + +public class Util { + static void printMask(long mask) { + String s = "0000000000000000000000000000000000000000000000000000000000000000" + Long.toBinaryString(mask); + s = s.substring(s.length() - 64); + printSpaced(s.substring(0, 8)); + printSpaced(s.substring(8, 16)); + printSpaced(s.substring(16, 24)); + printSpaced(s.substring(24, 32)); + printSpaced(s.substring(32, 40)); + printSpaced(s.substring(40, 48)); + printSpaced(s.substring(48, 56)); + printSpaced(s.substring(56, 64)); + + System.out.println(); + } + + public static void printSpaced(String s) { + System.out.println(s.replace("0", "- ").replace("1", "X ")); + } +} -- 2.54.1 From 852bfb8d8dbe34c473528c21e1bd9f6b1dbdc011 Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 1 Sep 2026 21:15:34 -0400 Subject: [PATCH 02/20] port BoxFinder and add raster occlusion toggle --- .../embeddium/impl/gui/SodiumGameOptions.java | 2 + .../impl/gui/options/CommonOptionPages.java | 10 + .../render/chunk/occlusion/geometry/Area.java | 220 +++++++++++ .../chunk/occlusion/geometry/AreaFinder.java | 183 +++++++++ .../chunk/occlusion/geometry/BoxFinder.java | 354 ++++++++++++++++++ .../options/structure/StandardOptions.java | 1 + .../assets/celeritas/lang/en_US.lang | 2 + .../assets/embeddium/lang/en_us.json | 4 +- 8 files changed, 775 insertions(+), 1 deletion(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/Area.java create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/AreaFinder.java create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/gui/SodiumGameOptions.java b/common/src/main/java/org/embeddedt/embeddium/impl/gui/SodiumGameOptions.java index bbbf08224..d1cec6220 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/gui/SodiumGameOptions.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/gui/SodiumGameOptions.java @@ -76,6 +76,8 @@ public class SodiumGameOptions implements OptionStorage { public boolean useNoErrorGLContext = true; public AsyncOcclusionMode asyncOcclusionMode = AsyncOcclusionMode.ONLY_SHADOW; + + public boolean useRasterOcclusionCulling = false; } public static class AdvancedSettings { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/gui/options/CommonOptionPages.java b/common/src/main/java/org/embeddedt/embeddium/impl/gui/options/CommonOptionPages.java index e4bf12210..e04f9a01d 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/gui/options/CommonOptionPages.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/gui/options/CommonOptionPages.java @@ -157,6 +157,16 @@ public class CommonOptionPages { .setBinding((opts, value) -> opts.performance.useFasterClouds = value, opts -> opts.performance.useFasterClouds) .build()) //?} + .add(OptionImpl.createBuilder(boolean.class, sodiumOpts) + .setId(StandardOptions.Option.RASTER_OCCLUSION_CULLING.cast()) + .setName(TextComponent.translatable("celeritas.options.raster_occlusion_culling.name")) + .setTooltip(TextComponent.translatable("celeritas.options.raster_occlusion_culling.tooltip")) + .setControl(TickBoxControl::new) + .setImpact(OptionImpact.VARIES) + .setBinding((opts, value) -> opts.performance.useRasterOcclusionCulling = value, opts -> opts.performance.useRasterOcclusionCulling) + .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) + .build() + ) .build()); return new OptionPage(StandardOptions.Pages.PERFORMANCE, TextComponent.translatable("sodium.options.pages.performance"), List.copyOf(groups)); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/Area.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/Area.java new file mode 100644 index 000000000..6dc314ea6 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/Area.java @@ -0,0 +1,220 @@ +/* + * Ported from Canvas (https://github.com/vram-guild/canvas), Copyright 2019, 2020 grondag. + * Licensed under the GNU Lesser General Public License v3.0. + */ + +package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry; + +import it.unimi.dsi.fastutil.ints.AbstractIntComparator; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntArrays; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; + +public class Area { + public static final int AREA_COUNT; + public static final int SECTION_COUNT; + private static final int[] AREA_KEY_TO_INDEX = new int[0x10000]; + private static final int[] AREA_INDEX_TO_KEY; + private static final int[] SECTION_KEYS; + private static final int[] SECTION_INDEX; + private static final long[] AREA_BITS; + + static { + final IntOpenHashSet areas = new IntOpenHashSet(); + + areas.add(Area.areaKey(0, 0, 15, 15)); + + areas.add(Area.areaKey(1, 0, 15, 15)); + areas.add(Area.areaKey(0, 0, 14, 15)); + areas.add(Area.areaKey(0, 1, 15, 15)); + areas.add(Area.areaKey(0, 0, 15, 14)); + + for (int x0 = 0; x0 <= 15; x0++) { + for (int x1 = x0; x1 <= 15; x1++) { + for (int y0 = 0; y0 <= 15; y0++) { + for (int y1 = y0; y1 <= 15; y1++) { + areas.add(Area.areaKey(x0, y0, x1, y1)); + } + } + } + } + + AREA_COUNT = areas.size(); + AREA_INDEX_TO_KEY = new int[AREA_COUNT]; + AREA_BITS = new long[AREA_COUNT * 4]; + + int i = 0; + + for (final int k : areas) { + AREA_INDEX_TO_KEY[i++] = k; + } + + IntArrays.quickSort(AREA_INDEX_TO_KEY, new AbstractIntComparator() { + @Override + public int compare(int a, int b) { + final int result = Integer.compare(Area.size(b), Area.size(a)); + + // within same area size, prefer more compact rectangles + return result == 0 ? Integer.compare(Area.edgeCount(a), Area.edgeCount(b)) : result; + } + }); + + for (int j = 0; j < AREA_COUNT; j++) { + AREA_KEY_TO_INDEX[AREA_INDEX_TO_KEY[j]] = j; + } + + final IntArrayList sections = new IntArrayList(); + + for (int j = 0; j < AREA_COUNT; ++j) { + final int a = AREA_INDEX_TO_KEY[j]; + + if ((Area.x0(a) == 0 && Area.x1(a) == 15) || (Area.y0(a) == 0 && Area.y1(a) == 15)) { + sections.add(indexToKey(j)); + } + } + + SECTION_COUNT = sections.size(); + SECTION_KEYS = sections.toArray(new int[SECTION_COUNT]); + SECTION_INDEX = new int[SECTION_COUNT]; + + for (int k = 0; k < SECTION_COUNT; ++k) { + SECTION_INDEX[k] = keyToIndex(SECTION_KEYS[k]); + } + + final long[] xMasks = new long[256]; + final int[] yBits = new int[256]; + final long[] yMasks = new long[16]; + + for (int x0 = 0; x0 <= 15; ++x0) { + for (int x1 = x0; x1 <= 15; ++x1) { + final long template = (0xFFFF << x0) & (0xFFFF >> (15 - x1)); + xMasks[x0 | (x1 << 4)] = template | (template << 16) | (template << 32) | (template << 48); + } + } + + for (int y0 = 0; y0 <= 15; ++y0) { + for (int y1 = y0; y1 <= 15; ++y1) { + yBits[y0 | (y1 << 4)] = (0xFFFF << y0) & (0xFFFF >> (15 - y1)); + } + } + + yMasks[0b0000] = 0L; + yMasks[0b0001] = 0x000000000000FFFFL; + yMasks[0b0010] = 0x00000000FFFF0000L; + yMasks[0b0100] = 0x0000FFFF00000000L; + yMasks[0b1000] = 0xFFFF000000000000L; + yMasks[0b0011] = 0x00000000FFFFFFFFL; + yMasks[0b0110] = 0x0000FFFFFFFF0000L; + yMasks[0b1100] = 0xFFFFFFFF00000000L; + yMasks[0b0111] = 0x0000FFFFFFFFFFFFL; + yMasks[0b1110] = 0xFFFFFFFFFFFF0000L; + yMasks[0b1111] = 0xFFFFFFFFFFFFFFFFL; + + int j = 0; + + for (int areaIndex = 0; areaIndex < AREA_COUNT; ++areaIndex) { + final int areaKey = indexToKey(areaIndex); + AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (0 << 2)) & 0xF] & xMasks[areaKey & 0xFF]; + AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (1 << 2)) & 0xF] & xMasks[areaKey & 0xFF]; + AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (2 << 2)) & 0xF] & xMasks[areaKey & 0xFF]; + AREA_BITS[j++] = yMasks[(yBits[areaKey >> 8] >> (3 << 2)) & 0xF] & xMasks[areaKey & 0xFF]; + } + } + + public static int keyToIndex(int key) { + return AREA_KEY_TO_INDEX[key]; + } + + public static int indexToKey(int index) { + return AREA_INDEX_TO_KEY[index]; + } + + public static int sectionToAreaIndex(int sectionIndex) { + return SECTION_INDEX[sectionIndex]; + } + + public static boolean isIncludedBySample(long[] sample, int sampleStart, int areaIndex) { + areaIndex <<= 2; + + final long template = AREA_BITS[areaIndex]; + final long template1 = AREA_BITS[++areaIndex]; + final long template2 = AREA_BITS[++areaIndex]; + final long template3 = AREA_BITS[++areaIndex]; + + return (template & sample[sampleStart]) == template + && (template1 & sample[sampleStart + 1]) == template1 + && (template2 & sample[sampleStart + 2]) == template2 + && (template3 & sample[sampleStart + 3]) == template3; + } + + public static boolean intersectsWithSample(long[] sample, int sampleStart, int areaIndex) { + areaIndex <<= 2; + + return (AREA_BITS[areaIndex] & sample[sampleStart]) != 0 + || (AREA_BITS[++areaIndex] & sample[++sampleStart]) != 0 + || (AREA_BITS[++areaIndex] & sample[++sampleStart]) != 0 + || (AREA_BITS[++areaIndex] & sample[++sampleStart]) != 0; + } + + public static boolean isAdditive(long[] sample, int sampleStart, int areaIndex) { + areaIndex <<= 2; + + return (AREA_BITS[areaIndex] | sample[sampleStart]) != sample[sampleStart] + || (AREA_BITS[++areaIndex] | sample[++sampleStart]) != sample[sampleStart] + || (AREA_BITS[++areaIndex] | sample[++sampleStart]) != sample[sampleStart] + || (AREA_BITS[++areaIndex] | sample[++sampleStart]) != sample[sampleStart]; + } + + public static void clearBits(long[] targetBits, int startIndex, int areaIndex) { + areaIndex <<= 2; + + targetBits[startIndex] &= ~AREA_BITS[areaIndex]; + targetBits[++startIndex] &= ~AREA_BITS[++areaIndex]; + targetBits[++startIndex] &= ~AREA_BITS[++areaIndex]; + targetBits[++startIndex] &= ~AREA_BITS[++areaIndex]; + } + + public static long bitsFromIndex(int areaIndex, int y) { + return AREA_BITS[(areaIndex << 2) + y]; + } + + public static int areaKey(int x0, int y0, int x1, int y1) { + return x0 | (x1 << 4) | (y0 << 8) | (y1 << 12); + } + + public static int x0(int areaKey) { + return areaKey & 15; + } + + public static int y0(int areaKey) { + return (areaKey >> 8) & 15; + } + + public static int x1(int areaKey) { + return (areaKey >> 4) & 15; + } + + public static int y1(int areaKey) { + return (areaKey >> 12) & 15; + } + + public static int size(int areaKey) { + final int x0 = x0(areaKey); + final int y0 = y0(areaKey); + final int x1 = x1(areaKey); + final int y1 = y1(areaKey); + + return (x1 - x0 + 1) * (y1 - y0 + 1); + } + + public static int edgeCount(int areaKey) { + final int x0 = x0(areaKey); + final int y0 = y0(areaKey); + final int x1 = x1(areaKey); + final int y1 = y1(areaKey); + + final int x = x1 - x0 + 1; + final int y = y1 - y0 + 1; + return x + y; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/AreaFinder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/AreaFinder.java new file mode 100644 index 000000000..f5184966c --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/AreaFinder.java @@ -0,0 +1,183 @@ +/* + * Ported from Canvas (https://github.com/vram-guild/canvas), Copyright 2019, 2020 grondag. + * Licensed under the GNU Lesser General Public License v3.0. + */ + +package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry; + +import java.util.function.IntConsumer; + +public class AreaFinder { + final long[] bits = new long[4]; + + // based on approach described here: + // https://stackoverflow.com/a/7497967 + // https://stackoverflow.com/a/7773870 + // https://www.drdobbs.com/database/the-maximal-rectangle-problem/184410529 + public static int findLargest(long[] bitsIn) { + int bestX0 = 0; + int bestY0 = 0; + int bestX1 = -1; + int bestY1 = -1; + int bestArea = 0; + + // height of prior rows + // four bits per position, values 0-15 + long heights = 0; + + for (int y = 0; y < 16; ++y) { + final int rowBits = (int) ((bitsIn[y >> 2] >> ((y & 3) << 4)) & 0xFFFF); + + if (rowBits == 0) { + heights = 0; + continue; + } + + // track start of runs up to current height + long stackX15 = 0; // 0-15 + long stackH16 = 0; // 1-16 + int stackSize = 0; + + // height of first column is zero if closed, otherwise 1 + previous row first column height + int runHeight = (rowBits & 1) == 0 ? 0 : (1 + getVal15(heights, 0)); + int runStart = 0; + + // save height for use by next row, unless at top row + if (y != 15) heights = setVal15(heights, 0, runHeight); + + // NB: inclusive of 16. The height @ 16 will always be zero, closing off last column + for (int x = 1; x <= 16; ++x) { + // height here is 0 if closed, otherwise 1 + height of row below + final int h = (rowBits & (1 << x)) == 0 ? 0 : (1 + getVal15(heights, x)); + + // if higher than last start new run + if (h > runHeight) { + // push current run onto stack + if (runHeight != 0) { + stackX15 = setVal15(stackX15, stackSize, runStart); + stackH16 = setVal16(stackH16, stackSize, runHeight); + ++stackSize; + } + + // new run starts here + runStart = x; + runHeight = h; + } else { + // if reduction in height, close out current run and + // also runs on stack until revert to a sustainable run + // or the stack is empty + + while (h < runHeight) { + // check for largest area on current run + final int a = (x - runStart) * runHeight; + + if (a > bestArea) { + bestArea = a; + bestX0 = runStart; + bestX1 = x - 1; + bestY0 = y - runHeight + 1; + bestY1 = y; + } + + if (stackSize == 0) { + // if we have an empty stack but non-zero height, + // then run at current height effectively starts + // where the just-closed prior run started + runHeight = h; + // NB: no change to run start - continue from prior + } else { // stackSize > 0 + --stackSize; + final int stackStart = getVal15(stackX15, stackSize); + final int stackHeight = getVal16(stackH16, stackSize); + + if (stackHeight == h) { + // if stack run height is same as current, resume run, leave stack popped + runHeight = h; + runStart = stackStart; + } else if (stackHeight < h) { + // if stack run height is less new height, leave on the stack + ++stackSize; + // and new run starts from current position + runHeight = h; + // NB: no change to run start - continue from prior + } else { + // stack area is higher than new height + // leave stack popped and loop to close out area on the stack + runHeight = stackHeight; + runStart = stackStart; + } + } + } + } + + // track height of this column but don't overflow on last row/column + if (y != 15 && x < 16) heights = setVal15(heights, x, h); + } + } + + return Area.areaKey(bestX0, bestY0, bestX1, bestY1); + } + + private static int getVal16(long packed, int x) { + return 1 + getVal15(packed, x); + } + + private static long setVal16(long packed, int x, int val) { + return setVal15(packed, x, val - 1); + } + + private static int getVal15(long packed, int x) { + return (int) ((packed >>> (x << 2)) & 0xF); + } + + private static long setVal15(long packed, int x, int val) { + final int shift = x << 2; + final long mask = 0xFL << shift; + return (packed & ~mask) | (((long) val) << shift); + } + + public long[] bitsFromIndex(int areaIndex) { + final long[] result = bits; + + result[0] = Area.bitsFromIndex(areaIndex, 0); + result[1] = Area.bitsFromIndex(areaIndex, 1); + result[2] = Area.bitsFromIndex(areaIndex, 2); + result[3] = Area.bitsFromIndex(areaIndex, 3); + + return result; + } + + public void find(long[] bitsIn, int sourceIndex, IntConsumer areaIndexConsumer) { + final long[] bits = this.bits; + System.arraycopy(bitsIn, sourceIndex, bits, 0, 4); + + int bitCount = Long.bitCount(bits[0]) + Long.bitCount(bits[1]) + Long.bitCount(bits[2]) + Long.bitCount(bits[3]); + + while (bitCount > 0) { + final int key = findLargest(bits); + final int index = Area.keyToIndex(key); + areaIndexConsumer.accept(index); + Area.clearBits(bits, 0, index); + bitCount -= Area.size(key); + } + } + + public void findSections(long[] bitsIn, int sourceIndex, IntConsumer areaIndexConsumer) { + final long[] bits = this.bits; + System.arraycopy(bitsIn, sourceIndex, bits, 0, 4); + + final int bitCount = Long.bitCount(bits[0]) + Long.bitCount(bits[1]) + Long.bitCount(bits[2]) + Long.bitCount(bits[3]); + + if (bitCount == 0) { + return; + } + + for (int i = 0; i < Area.SECTION_COUNT; ++i) { + final int areaIndex = Area.sectionToAreaIndex(i); + + if (Area.isIncludedBySample(bits, 0, areaIndex)) { + areaIndexConsumer.accept(areaIndex); + } + } + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java new file mode 100644 index 000000000..4449d0493 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java @@ -0,0 +1,354 @@ +/* + * Adapted from Canvas (https://github.com/vram-guild/canvas), Copyright 2019, 2020 grondag. + * Licensed under the GNU Lesser General Public License v3.0. + */ + +package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry; + +import grondag.bitraster.PackedBox; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.longs.LongArrayList; + +import java.util.Arrays; +import java.util.function.IntConsumer; + +/** + * Decomposes a section's opaque voxels into disjoint occluder boxes. Input is 64 longs of occupancy + * for a 16x16x16 section. + * + *

Rectangles are found in the low two axes of the index and extended along the high one, so a + * caller with a different axis order permutes the resulting {@link PackedBox} instead of the input. + * + *

Boxes never cover a voxel the source left clear, but may leave some covered voxels out: two + * passes run and any residue is dropped. That costs culling, never correctness. + */ +public class BoxFinder { + /** One bit per voxel of a 16x16x16 section. */ + public static final int INTERIOR_CACHE_WORDS = 64; + + public static final int SLICE_WORD_COUNT = 4; + + public final IntArrayList boxes = new IntArrayList(); + public final AreaFinder areaFinder; + final long[] source = new long[INTERIOR_CACHE_WORDS]; + final long[] filled = new long[INTERIOR_CACHE_WORDS]; + /** + * Bits 0-15 indicate which slices contain the area with the same index of the value. + */ + final int[] areaSlices = new int[Area.AREA_COUNT]; + private final LongArrayList sortedBoxes = new LongArrayList(); + int mask; + private final IntConsumer markSliceConsumer = areaIndex -> areaSlices[areaIndex] |= mask; + private int voxelCount; + + public BoxFinder(AreaFinder areaFinder) { + this.areaFinder = areaFinder; + } + + public void findBoxes(long[] sourceBits, int sourceIndex) { + Arrays.fill(filled, 0L); + System.arraycopy(sourceBits, sourceIndex, source, 0, INTERIOR_CACHE_WORDS); + boxes.clear(); + + markSectionSlices(); + buildSortedSections(); + findSections(); + + clearSectionBits(); + + voxelCount = voxelCount(sourceBits, sourceIndex); + markBoxSlices(); + markBoxNeighborSlices(); + buildSortedBoxes(); + findDisjointBoxes(); + + if (voxelCount > 0) { + clearSectionBits(); + markBoxSlices(); + markBoxNeighborSlices(); + buildSortedBoxes(); + findDisjointBoxes(); + } + } + + private void buildSortedSections() { + final LongArrayList sortedBoxes = this.sortedBoxes; + sortedBoxes.clear(); + + final int[] areaSlices = this.areaSlices; + + if (areaSlices[0] != 0) { + // handle special case of full Z-plane + addBoxesFromSlice(Area.indexToKey(0), areaSlices[0]); + } + + for (int i = 1; i < Area.SECTION_COUNT; ++i) { + final int areaIndex = Area.sectionToAreaIndex(i); + final int slice = areaSlices[areaIndex]; + + if (slice == 0xFFFF) { + final int areaKey = Area.indexToKey(areaIndex); + final int dy = (Area.y1(areaKey) - Area.y0(areaKey) + 1); + final int dx = (Area.x1(areaKey) - Area.x0(areaKey) + 1); + final long vol = (dx * dy * 16); + sortedBoxes.add((vol << 34) | (areaIndex << 10) | (16 << 5) | 0); + } + } + + sortedBoxes.sort((a, b) -> Long.compare(b, a)); + } + + private void markBoxNeighborSlices() { + final int[] areaSlices = this.areaSlices; + + for (int areaIndex = 0; areaIndex < Area.AREA_COUNT; ++areaIndex) { + int slice = areaSlices[areaIndex]; + + if (slice != 0) { + if ((slice & 1) == 1 && (slice & 2) == 0) { + // special case first slice - can only transfer up + if (Area.isIncludedBySample(source, SLICE_WORD_COUNT, areaIndex)) { + slice |= 2; + } + } + + int mask = 2; + + for (int z = 1; z < 15; z++) { + if ((slice & mask) != 0) { + // transfer to lower slice if not already present + final int lowMask = (mask >> 1); + + if ((slice & lowMask) == 0) { + if (Area.isIncludedBySample(source, (z - 1) * SLICE_WORD_COUNT, areaIndex)) { + slice |= lowMask; + } + } + + // transfer to upper slice if not already present + final int highMask = (mask << 1); + + if ((slice & highMask) == 0) { + if (Area.isIncludedBySample(source, (z + 1) * SLICE_WORD_COUNT, areaIndex)) { + slice |= highMask; + } + } + } + + mask <<= 1; + } + + if ((slice & 0b1000000000000000) == 0b1000000000000000 && (slice & 0b0100000000000000) == 0) { + if (Area.isIncludedBySample(source, SLICE_WORD_COUNT * 14, areaIndex)) { + slice |= 0b0100000000000000; + } + } + + areaSlices[areaIndex] = slice; + } + } + } + + private void buildSortedBoxes() { + final LongArrayList sortedBoxes = this.sortedBoxes; + sortedBoxes.clear(); + + final int[] areaSlices = this.areaSlices; + + for (int areaIndex = 0; areaIndex < Area.AREA_COUNT; ++areaIndex) { + final int slice = areaSlices[areaIndex]; + + if (slice != 0) { + addBoxesFromSlice(Area.indexToKey(areaIndex), slice); + } + } + + sortedBoxes.sort((a, b) -> Long.compare(b, a)); + } + + private void addBoxesFromSlice(int areaKey, int slice) { + int z0 = -1; + int mask = 1; + final int x0 = Area.x0(areaKey); + final int y0 = Area.y0(areaKey); + final int x1 = Area.x1(areaKey); + final int y1 = Area.y1(areaKey); + final int areaIndex = Area.keyToIndex(areaKey); + + for (int z = 0; z < 16; z++) { + if ((slice & mask) == 0) { + // no bit, end run if started + if (z0 != -1) { + final int dz = (z - z0); + final int dy = (y1 - y0 + 1); + final int dx = (x1 - x0 + 1); + final long vol = dx * dy * dz; + sortedBoxes.add((vol << 34) | (areaIndex << 10) | (z << 5) | z0); + z0 = -1; + } + } else { + // bit set, start run if not started + if (z0 == -1) { + z0 = z; + } + } + + mask <<= 1; + } + + // handle case when run extends to last bit + if (z0 != -1) { + final int dz = (16 - z0); + final int dy = (y1 - y0 + 1); + final int dx = (x1 - x0 + 1); + final long vol = dx * dy * dz; + + sortedBoxes.add((vol << 34) | (areaIndex << 10) | (16 << 5) | z0); + } + } + + // PERF: still slow on relative basis to rest of chunk baking + private void markBoxSlices() { + final long[] sourceBits = source; + final AreaFinder areaFinder = this.areaFinder; + final int[] areaSlices = this.areaSlices; + Arrays.fill(areaSlices, 0); + mask = 1; + int sourceIndex = 0; + + for (int i = 0; i < 16; ++i) { + areaFinder.find(sourceBits, sourceIndex, markSliceConsumer); + sourceIndex += SLICE_WORD_COUNT; + mask <<= 1; + } + } + + private void markSectionSlices() { + final long[] sourceBits = source; + final AreaFinder areaFinder = this.areaFinder; + final int[] areaSlices = this.areaSlices; + Arrays.fill(areaSlices, 0); + mask = 1; + int sourceIndex = 0; + + for (int i = 0; i < 16; ++i) { + areaFinder.findSections(sourceBits, sourceIndex, markSliceConsumer); + sourceIndex += SLICE_WORD_COUNT; + mask <<= 1; + } + } + + private void findSections() { + final LongArrayList sortedBoxes = this.sortedBoxes; + final int limit = sortedBoxes.size(); + final IntArrayList boxes = this.boxes; + + for (int i = 0; i < limit; i++) { + final long box = sortedBoxes.getLong(i); + final int areaIndex = (int) (box >> 10) & 0xFFFFFF; + + final int z0 = (int) box & 31; + final int z1 = (int) (box >> 5) & 31; + + if (isAdditive(areaIndex, z0, z1)) { + fill(areaIndex, z0, z1); + final int areaKey = Area.indexToKey(areaIndex); + boxes.add(PackedBox.pack(Area.x0(areaKey), Area.y0(areaKey), z0, Area.x1(areaKey) + 1, Area.y1(areaKey) + 1, z1, PackedBox.RANGE_EXTREME)); + } + } + } + + private void findDisjointBoxes() { + final LongArrayList sortedBoxes = this.sortedBoxes; + final int limit = sortedBoxes.size(); + final IntArrayList boxes = this.boxes; + + for (int i = 0; i < limit; i++) { + final long box = sortedBoxes.getLong(i); + final int areaIndex = (int) (box >> 10) & 0xFFFFFF; + final int z0 = (int) box & 31; + final int z1 = (int) (box >> 5) & 31; + + if (!intersects(areaIndex, z0, z1)) { + fill(areaIndex, z0, z1); + final int vol = (int) (box >>> 34); + final int areaKey = Area.indexToKey(areaIndex); + boxes.add(PackedBox.pack(Area.x0(areaKey), Area.y0(areaKey), z0, Area.x1(areaKey) + 1, Area.y1(areaKey) + 1, z1, rangeFromVolume(vol))); + voxelCount -= vol; + + if (voxelCount == 0) { + break; + } + } + } + } + + private int rangeFromVolume(int maxArea) { + return maxArea <= 64 ? PackedBox.RANGE_NEAR : maxArea > 512 ? PackedBox.RANGE_FAR : PackedBox.RANGE_MID; + } + + private int voxelCount(long[] sourceBits, int sourceIndex) { + int result = 0; + final int limit = sourceIndex + INTERIOR_CACHE_WORDS; + + for (int i = sourceIndex; i < limit; ++i) { + final long bits = sourceBits[i]; + result += Long.bitCount(bits); + } + + return result; + } + + private void fill(int areaIndex, int z0, int z1) { + final long[] filled = this.filled; + int index = z0 * SLICE_WORD_COUNT; + final long[] bits = areaFinder.bitsFromIndex(areaIndex); + + for (int z = z0; z < z1; ++z) { + filled[index] |= bits[0]; + filled[index + 1] |= bits[1]; + filled[index + 2] |= bits[2]; + filled[index + 3] |= bits[3]; + index += SLICE_WORD_COUNT; + } + } + + private boolean intersects(int areaIndex, int z0, int z1) { + final long[] filled = this.filled; + int index = z0 * SLICE_WORD_COUNT; + + for (int z = z0; z < z1; ++z) { + if (Area.intersectsWithSample(filled, index, areaIndex)) { + return true; + } + + index += SLICE_WORD_COUNT; + } + + return false; + } + + private boolean isAdditive(int areaIndex, int z0, int z1) { + final long[] filled = this.filled; + int index = z0 * SLICE_WORD_COUNT; + + final long a0 = Area.bitsFromIndex(areaIndex, 0); + final long a1 = Area.bitsFromIndex(areaIndex, 1); + final long a2 = Area.bitsFromIndex(areaIndex, 2); + final long a3 = Area.bitsFromIndex(areaIndex, 3); + + for (int z = z0; z < z1; ++z) { + if (((~filled[index++] & a0) | (~filled[index++] & a1) | (~filled[index++] & a2) | (~filled[index++] & a3)) != 0) { + return true; + } + } + + return false; + } + + private void clearSectionBits() { + for (int i = 0; i < INTERIOR_CACHE_WORDS; ++i) { + source[i] &= ~filled[i]; + } + } +} diff --git a/common/src/main/java/org/taumc/celeritas/api/options/structure/StandardOptions.java b/common/src/main/java/org/taumc/celeritas/api/options/structure/StandardOptions.java index 319b08af4..cbe235da2 100644 --- a/common/src/main/java/org/taumc/celeritas/api/options/structure/StandardOptions.java +++ b/common/src/main/java/org/taumc/celeritas/api/options/structure/StandardOptions.java @@ -68,5 +68,6 @@ public final class StandardOptions { public static final OptionIdentifier USE_FASTER_CLOUDS = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "use_faster_clouds"); public static final OptionIdentifier ASYNC_GRAPH_SEARCH = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "async_graph_search"); public static final OptionIdentifier CHUNK_FADE_IN_DURATION = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "chunk_fade_in_duration"); + public static final OptionIdentifier RASTER_OCCLUSION_CULLING = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "raster_occlusion_culling"); } } diff --git a/forge122/src/main/resources/assets/celeritas/lang/en_US.lang b/forge122/src/main/resources/assets/celeritas/lang/en_US.lang index 823b53f1b..b7558d209 100644 --- a/forge122/src/main/resources/assets/celeritas/lang/en_US.lang +++ b/forge122/src/main/resources/assets/celeritas/lang/en_US.lang @@ -18,6 +18,8 @@ celeritas.options.async_graph_search.tooltip=Performs occlusion/frustum culling celeritas.options.chunk_fade_in_duration.name=Chunk Fade-In Duration celeritas.options.chunk_fade_in_duration.value=%s ms celeritas.options.chunk_fade_in_duration.tooltip=Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly. +celeritas.options.raster_occlusion_culling.name=Rasterized Occlusion Culling +celeritas.options.raster_occlusion_culling.tooltip=Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn, but costs extra CPU time each frame, so it helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks. sodium.option_impact.low=Low sodium.option_impact.medium=Medium sodium.option_impact.high=High diff --git a/modern/src/main/resources/assets/embeddium/lang/en_us.json b/modern/src/main/resources/assets/embeddium/lang/en_us.json index 70a9f136d..a200b8570 100644 --- a/modern/src/main/resources/assets/embeddium/lang/en_us.json +++ b/modern/src/main/resources/assets/embeddium/lang/en_us.json @@ -17,5 +17,7 @@ "celeritas.options.async_graph_search.tooltip": "Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively.", "celeritas.options.chunk_fade_in_duration.name": "Chunk Fade-In Duration", "celeritas.options.chunk_fade_in_duration.value": "%s ms", - "celeritas.options.chunk_fade_in_duration.tooltip": "Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly." + "celeritas.options.chunk_fade_in_duration.tooltip": "Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly.", + "celeritas.options.raster_occlusion_culling.name": "Rasterized Occlusion Culling", + "celeritas.options.raster_occlusion_culling.tooltip": "Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn, but costs extra CPU time each frame, so it helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks." } -- 2.54.1 From f20917afb5d4407aa4c226d0e1c198da7d72c99c Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 1 Sep 2026 21:36:03 -0400 Subject: [PATCH 03/20] add BoxFinder benchmark benches the cost on the build threads --- .../render/chunk/bench/voxel/VoxelSlice.java | 25 ++++ .../chunk/occlusion/bench/BoxFinderBench.java | 131 ++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/BoxFinderBench.java diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java index c96a32dce..63477187d 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java @@ -101,4 +101,29 @@ public final class VoxelSlice { return occluder.computeVisibilityEncoding(); } + + public long[] opacityBits() { + var bits = new long[64]; + + if (this.empty) { + return bits; + } + + byte[] blocks = this.blocks; + + for (int y = 0; y < 16; y++) { + for (int z = 0; z < 16; z++) { + int row = ((y + 1) * AREA) + ((z + 1) * SIZE) + 1; + + for (int x = 0; x < 16; x++) { + if (VoxelWorld.isOpaque(blocks[row + x])) { + int index = x | (z << 4) | (y << 8); + bits[index >> 6] |= 1L << (index & 63); + } + } + } + } + + return bits; + } } diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/BoxFinderBench.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/BoxFinderBench.java new file mode 100644 index 000000000..739bb0f3a --- /dev/null +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/BoxFinderBench.java @@ -0,0 +1,131 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench; + +import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.VoxelSlice; +import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.VoxelWorld; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.AreaFinder; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OperationsPerInvocation; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +/** + * Per-section cost of generating occluder boxes, which a real integration must pay on the chunk + * build thread. + * + *

{@link #visibilityFloodFill} is the yardstick, not a baseline to subtract: it is the per-section + * occlusion work meshing already does today and therefore a known-affordable cost. Read the result as + * a ratio against it. + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Fork(2) +@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +public class BoxFinderBench { + private static final int SECTION_SAMPLE = 512; + + @State(Scope.Benchmark) + public static class Sections { + @Param({ "SURFACE", "CAVES" }) + public WorldType world; + + public long[][] opacity; + public VoxelSlice[] slices; + + @Setup + public void setup() { + var voxelWorld = new VoxelWorld(this.world); + var sampledSlices = new ArrayList(SECTION_SAMPLE); + var sampledOpacity = new ArrayList(SECTION_SAMPLE); + + // Spiral out from the origin column so the sample spans terrain, caves and sky rather + // than whichever corner a raster scan happens to start in. + outer: + for (int radius = 0; radius < 64; radius++) { + for (int x = -radius; x <= radius; x++) { + for (int z = -radius; z <= radius; z++) { + if (Math.max(Math.abs(x), Math.abs(z)) != radius) { + continue; + } + + for (int y = SyntheticWorld.MIN_SECTION_Y; y < SyntheticWorld.MAX_SECTION_Y; y++) { + var slice = voxelWorld.slice(x, y, z); + + if (slice.isEmpty()) { + continue; + } + + long[] bits = slice.opacityBits(); + + // Sections with no opaque blocks produce no occluders and would be + // skipped in production. + if (isAllClear(bits)) { + continue; + } + + sampledSlices.add(slice); + sampledOpacity.add(bits); + + if (sampledOpacity.size() == SECTION_SAMPLE) { + break outer; + } + } + } + } + } + + if (sampledOpacity.size() < SECTION_SAMPLE) { + throw new IllegalStateException("only found " + sampledOpacity.size() + + " non-empty sections for world " + this.world); + } + + this.opacity = sampledOpacity.toArray(new long[0][]); + this.slices = sampledSlices.toArray(new VoxelSlice[0]); + } + + private static boolean isAllClear(long[] bits) { + for (long word : bits) { + if (word != 0) { + return false; + } + } + + return true; + } + } + + @State(Scope.Thread) + public static class Finder { + public final BoxFinder boxFinder = new BoxFinder(new AreaFinder()); + } + + @Benchmark + @OperationsPerInvocation(SECTION_SAMPLE) + public void findBoxes(Sections sections, Finder finder, Blackhole bh) { + for (long[] bits : sections.opacity) { + finder.boxFinder.findBoxes(bits, 0); + bh.consume(finder.boxFinder.boxes.size()); + } + } + + @Benchmark + @OperationsPerInvocation(SECTION_SAMPLE) + public void visibilityFloodFill(Sections sections, Blackhole bh) { + for (VoxelSlice slice : sections.slices) { + bh.consume(slice.computeVisibility()); + } + } +} -- 2.54.1 From aa377a21e353dc2b74e359eb3642f48f472b9a6c Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 1 Sep 2026 21:58:42 -0400 Subject: [PATCH 04/20] 1024px raster buffer and cull report baseline --- common/build.gradle | 10 +++ .../occlusion/bench/RasterCullReport.java | 68 +++++++++++++++++++ .../java/grondag/bitraster/Constants.java | 6 +- 3 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java diff --git a/common/build.gradle b/common/build.gradle index 110876f72..986aa4fbc 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -152,6 +152,16 @@ tasks.register('jmh', JavaExec) { } } +tasks.register('rasterCullReport', JavaExec) { + group = 'verification' + description = 'Reports visible section counts per world and camera placement.' + + classpath = sourceSets.jmh.runtimeClasspath + mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterCullReport' + + maxHeapSize = '1g' +} + publishing { publications { mavenJava(MavenPublication) { diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java new file mode 100644 index 000000000..cc13cefac --- /dev/null +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java @@ -0,0 +1,68 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion.bench; + +import org.embeddedt.embeddium.impl.render.chunk.RenderSection; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice; +import org.embeddedt.embeddium.impl.render.viewport.Viewport; + +public final class RasterCullReport { + private static final int RENDER_DISTANCE = 32; + private static final int YAW_STEPS = 8; + private static final WorldType[] WORLDS = { WorldType.SURFACE, WorldType.CAVES }; + + private RasterCullReport() { + } + + private record Placement(String name, double y, float pitch) { + } + + public static void main(String[] args) { + BenchPlatform.ensureInitialized(); + + System.out.printf("%-8s %-8s %10s %10s%n", "world", "camera", "visited", "visible"); + System.out.println("-".repeat(42)); + + for (WorldType world : WORLDS) { + var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true); + float searchDistance = syntheticWorld.getSearchDistance(); + int numRegions = BenchPlatform.regionManager().getRegionIdsLength(); + + var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false); + + for (RenderSection section : syntheticWorld.getConstructionOrder()) { + lattice.attach(section); + } + + int frame = 0; + + for (Placement placement : placements()) { + long visited = 0; + long visible = 0; + + for (int step = 0; step < YAW_STEPS; step++) { + Viewport viewport = Cameras.viewport(8.5, placement.y(), 8.5, + (360.0f / YAW_STEPS) * step, placement.pitch(), RENDER_DISTANCE); + + var visitor = new CountingVisitor(); + lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); + lattice.findVisible(visitor, viewport, searchDistance, numRegions, true, true, ++frame); + + visited += visitor.visited; + visible += visitor.visible; + } + + System.out.printf("%-8s %-8s %10d %10d%n", world, placement.name(), + visited / YAW_STEPS, visible / YAW_STEPS); + } + } + } + + private static Placement[] placements() { + double surfaceY = Cameras.surfaceCameraY(0, 0); + + return new Placement[] { + new Placement("surface", surfaceY, Cameras.DEFAULT_PITCH), + new Placement("treetop", surfaceY + 16.0, Cameras.DEFAULT_PITCH), + new Placement("high", 200.0, -45.0f), + }; + } +} diff --git a/common/src/main/java/grondag/bitraster/Constants.java b/common/src/main/java/grondag/bitraster/Constants.java index b7d01c645..551910d08 100644 --- a/common/src/main/java/grondag/bitraster/Constants.java +++ b/common/src/main/java/grondag/bitraster/Constants.java @@ -34,7 +34,8 @@ public class Constants { static final int PRECISE_PIXEL_SIZE = 1 << PRECISION_BITS; static final int PRECISE_PIXEL_CENTER = PRECISE_PIXEL_SIZE / 2; static final int SCANT_PRECISE_PIXEL_CENTER = PRECISE_PIXEL_CENTER - 1; - static final int TILE_WIDTH_BITS = 8; + // CELERITAS: 8 upstream; 7 gives a 1024px buffer, which matches 2048's culling to within 0.1% at ~1.7x the speed + static final int TILE_WIDTH_BITS = 7; static final int TILE_WIDTH = 1 << TILE_WIDTH_BITS; static final int TILE_WIDTH_MASK = TILE_WIDTH - 1; public static final int PIXEL_WIDTH = TILE_WIDTH * TILE_PIXEL_DIAMETER; @@ -48,7 +49,8 @@ public class Constants { * clamp to this to ensure value + half pixel rounds down to last pixel. */ static final int PRECISE_WIDTH_CLAMP = PRECISE_WIDTH - PRECISE_PIXEL_CENTER; - static final int TILE_HEIGHT_BITS = 8; + // 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; -- 2.54.1 From 9a662d757780980c8e29a2a74500741f1acf206f Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 1 Sep 2026 22:42:19 -0400 Subject: [PATCH 05/20] generate and store occluder boxes --- .../chunk/data/BuiltRenderSectionData.java | 9 ++- .../occlusion/SectionVisibilityBuilder.java | 19 ++++++ .../occlusion/geometry/OccluderBoxes.java | 62 +++++++++++++++++++ 3 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/OccluderBoxes.java diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltRenderSectionData.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltRenderSectionData.java index d1a75ad7c..f3fcdb1d2 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltRenderSectionData.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/data/BuiltRenderSectionData.java @@ -2,7 +2,9 @@ package org.embeddedt.embeddium.impl.render.chunk.data; import org.embeddedt.embeddium.impl.render.chunk.lists.RenderVisualsService; import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.Nullable; +import java.util.Arrays; import java.util.Objects; /** @@ -13,6 +15,8 @@ public class BuiltRenderSectionData { public boolean hasBlockGeometry; public long visibilityData; + public int @Nullable [] occluderBoxes; + public int getVisualBitmaskForSection() { return this.hasBlockGeometry ? (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY) : 0; } @@ -26,11 +30,12 @@ public class BuiltRenderSectionData { public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; BuiltRenderSectionData that = (BuiltRenderSectionData) o; - return hasBlockGeometry == that.hasBlockGeometry && visibilityData == that.visibilityData; + return hasBlockGeometry == that.hasBlockGeometry && visibilityData == that.visibilityData + && Arrays.equals(occluderBoxes, that.occluderBoxes); } @Override public int hashCode() { - return Objects.hash(hasBlockGeometry, visibilityData); + return (Objects.hash(hasBlockGeometry, visibilityData) * 31) + Arrays.hashCode(occluderBoxes); } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java index d9bed03dd..94d404121 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java @@ -2,7 +2,11 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import it.unimi.dsi.fastutil.ints.IntArrayList; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes; +import org.jetbrains.annotations.Nullable; +import java.util.Arrays; import java.util.BitSet; /** @@ -26,6 +30,8 @@ public class SectionVisibilityBuilder { private final BitSet blocks; + private boolean floodFilled; + private static int[] buildFloodfillIndices() { IntArrayList indicesList = new IntArrayList(TOTAL_BLOCKS - (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2)); for (int x = 0; x < SECTION_AXIS_SIZE; x++) { @@ -62,7 +68,20 @@ public class SectionVisibilityBuilder { this.blocks.set(getIndex(x & 15, y & 15, z & 15)); } + public int @Nullable [] computeOccluderBoxes() { + if (this.floodFilled) { + throw new IllegalStateException("opacity was consumed by computeVisibilityEncoding()"); + } + + if (this.blocks.isEmpty()) { + return null; + } + + return OccluderBoxes.from(Arrays.copyOf(this.blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS)); + } + private long computeWithFloodFill() { + this.floodFilled = true; long resultEncoding = 0; var blocks = this.blocks; BitSet escapedFaces = new BitSet(GraphDirection.COUNT); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/OccluderBoxes.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/OccluderBoxes.java new file mode 100644 index 000000000..9c71c1af2 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/OccluderBoxes.java @@ -0,0 +1,62 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry; + +import grondag.bitraster.PackedBox; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; + +public final class OccluderBoxes { + /** Below this a box costs a rasterizer draw for negligible screen coverage. */ + private static final int MIN_VOLUME = 8; + + /** {@link BoxFinder} is far too large to allocate per section; build threads are pooled */ + private static final ThreadLocal FINDER = ThreadLocal.withInitial(() -> new BoxFinder(new AreaFinder())); + + private OccluderBoxes() { + } + + public static int @Nullable [] from(long[] opacityBits) { + BoxFinder finder = FINDER.get(); + finder.findBoxes(opacityBits, 0); + + var found = finder.boxes; + int count = found.size(); + + if (count == 0) { + return null; + } + + int[] boxes = new int[count]; + int kept = 0; + + for (int range = PackedBox.RANGE_EXTREME; range >= PackedBox.RANGE_NEAR; range--) { + for (int i = 0; i < count; i++) { + int box = found.getInt(i); + + if (PackedBox.range(box) == range && volume(box) >= MIN_VOLUME) { + boxes[kept++] = toWorldAxes(box); + } + } + } + + if (kept == 0) { + return null; + } + + return kept == count ? boxes : Arrays.copyOf(boxes, kept); + } + + private static int toWorldAxes(int box) { + return PackedBox.pack( + PackedBox.x0(box), PackedBox.z0(box), PackedBox.y0(box), + PackedBox.x1(box), PackedBox.z1(box), PackedBox.y1(box), + PackedBox.range(box) + ); + } + + private static int volume(int box) { + return (PackedBox.x1(box) - PackedBox.x0(box)) + * (PackedBox.y1(box) - PackedBox.y0(box)) + * (PackedBox.z1(box) - PackedBox.z0(box)); + } +} -- 2.54.1 From c56653597f3d7a295f35f55f38d04ff467b80ecd Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 1 Sep 2026 23:18:55 -0400 Subject: [PATCH 06/20] wire up occluder box generation --- .../render/chunk/RenderSectionManager.java | 2 ++ .../chunk/occlusion/OccluderBoxBuilder.java | 30 +++++++++++++++++++ .../occlusion/SectionVisibilityBuilder.java | 13 ++------ .../terrain/VintageRenderSectionManager.java | 5 ++++ .../terrain/ArchaicRenderSectionManager.java | 8 ++++- .../compile/task/ChunkBuilderMeshingTask.java | 9 +++++- .../chunk/ModernRenderSectionManager.java | 8 ++++- .../tasks/ChunkBuilderMeshingTask.java | 15 +++++++++- 8 files changed, 76 insertions(+), 14 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index c56ca05db..0199c0ec4 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -347,6 +347,8 @@ public abstract class RenderSectionManager { protected abstract boolean useFogOcclusion(); + protected abstract boolean useRasterOcclusionCulling(); + private float getSearchDistance(@Nullable Matrix4fc projectionMatrix) { float distance; diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java new file mode 100644 index 000000000..6eeadc2cc --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java @@ -0,0 +1,30 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion; + +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.BitSet; + +// Separate from SectionVisibilityBuilder so a platform whose game already computes the visibility encoding +// can keep using that and supply opacity here instead of paying for a second flood fill it doesn't need +public final class OccluderBoxBuilder { + private final BitSet blocks = new BitSet(SectionVisibilityBuilder.TOTAL_BLOCKS); + + public void markOpaque(int x, int y, int z) { + this.blocks.set(SectionVisibilityBuilder.getIndex(x & 15, y & 15, z & 15)); + } + + public int @Nullable [] build() { + return boxesFrom(this.blocks); + } + + static int @Nullable [] boxesFrom(BitSet blocks) { + if (blocks.isEmpty()) { + return null; + } + + return OccluderBoxes.from(Arrays.copyOf(blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS)); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java index 94d404121..ec5ffc855 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java @@ -2,11 +2,8 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import it.unimi.dsi.fastutil.ints.IntArrayList; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes; import org.jetbrains.annotations.Nullable; -import java.util.Arrays; import java.util.BitSet; /** @@ -16,7 +13,7 @@ import java.util.BitSet; public class SectionVisibilityBuilder { private static final int SECTION_AXIS_SIZE = 16; private static final int SECTION_AXIS_MASK = SECTION_AXIS_SIZE - 1; - private static final int TOTAL_BLOCKS = SECTION_AXIS_SIZE * SECTION_AXIS_SIZE * SECTION_AXIS_SIZE; + static final int TOTAL_BLOCKS = SECTION_AXIS_SIZE * SECTION_AXIS_SIZE * SECTION_AXIS_SIZE; private static final int BLOCKS_ON_ONE_FACE = SECTION_AXIS_SIZE * SECTION_AXIS_SIZE; private static final int BITS_PER_AXIS = 4; private static final int X_SHIFT = 0; @@ -73,11 +70,7 @@ public class SectionVisibilityBuilder { throw new IllegalStateException("opacity was consumed by computeVisibilityEncoding()"); } - if (this.blocks.isEmpty()) { - return null; - } - - return OccluderBoxes.from(Arrays.copyOf(this.blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS)); + return OccluderBoxBuilder.boxesFrom(this.blocks); } private long computeWithFloodFill() { @@ -173,7 +166,7 @@ public class SectionVisibilityBuilder { } } - private static int getIndex(int x, int y, int z) { + static int getIndex(int x, int y, int z) { return (y << Y_SHIFT) | (z << Z_SHIFT) | (x << X_SHIFT); } } diff --git a/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/VintageRenderSectionManager.java b/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/VintageRenderSectionManager.java index 894bfa80e..ea5f1ed0d 100644 --- a/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/VintageRenderSectionManager.java +++ b/forge122/src/main/java/org/taumc/celeritas/impl/render/terrain/VintageRenderSectionManager.java @@ -57,6 +57,11 @@ public class VintageRenderSectionManager extends RenderSectionManager { return true; } + @Override + protected boolean useRasterOcclusionCulling() { + return false; + } + @Override protected boolean useFogOcclusion() { return CeleritasVintage.options().performance.useFogOcclusion; diff --git a/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/ArchaicRenderSectionManager.java b/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/ArchaicRenderSectionManager.java index 76d6b29bc..0ca5bf9e1 100644 --- a/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/ArchaicRenderSectionManager.java +++ b/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/ArchaicRenderSectionManager.java @@ -44,6 +44,11 @@ public class ArchaicRenderSectionManager extends RenderSectionManager { return true; } + @Override + protected boolean useRasterOcclusionCulling() { + return false; + } + @Override protected boolean useFogOcclusion() { return true; @@ -80,7 +85,8 @@ public class ArchaicRenderSectionManager extends RenderSectionManager { ChunkRenderContext context = new ChunkRenderContext(new SectionPos(render.getChunkX(), render.getChunkY(), render.getChunkZ())); - return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition); + return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition, + this.useRasterOcclusionCulling()); } @Override diff --git a/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java b/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java index bb4cb03d0..9c453e1e6 100644 --- a/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java +++ b/forge1710/src/main/java/org/taumc/celeritas/impl/render/terrain/compile/task/ChunkBuilderMeshingTask.java @@ -43,6 +43,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask private final int buildTime; private final Vector3d camera; private final ChunkRenderContext renderContext; + private final boolean rasterOcclusion; private static final MethodHandle RENDER_PASS_HANDLE; @@ -64,11 +65,13 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask } } - public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext context, int time, Vector3d camera) { + public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext context, int time, Vector3d camera, + boolean rasterOcclusion) { this.render = render; this.buildTime = time; this.camera = camera; this.renderContext = context; + this.rasterOcclusion = rasterOcclusion; } @Override @@ -163,6 +166,10 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask renderData.hasBlockGeometry = true; } + if (this.rasterOcclusion) { + renderData.occluderBoxes = occluder.computeOccluderBoxes(); + } + renderData.visibilityData = occluder.computeVisibilityEncoding(); return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime); diff --git a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/ModernRenderSectionManager.java b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/ModernRenderSectionManager.java index 77fb8f6d4..e9c3987b7 100644 --- a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/ModernRenderSectionManager.java +++ b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/ModernRenderSectionManager.java @@ -112,7 +112,8 @@ public class ModernRenderSectionManager extends RenderSectionManager { return null; } - return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition); + return new ChunkBuilderMeshingTask(render, context, frame, this.cameraPosition, + this.useRasterOcclusionCulling()); } @Override @@ -126,6 +127,11 @@ public class ModernRenderSectionManager extends RenderSectionManager { return new GenericSectionSpriteTicker<>(SpriteUtil::markSpriteActive); } + @Override + protected boolean useRasterOcclusionCulling() { + return Celeritas.options().performance.useRasterOcclusionCulling; + } + @Override protected boolean useFogOcclusion() { // TODO: does *every* shaderpack really disable fog? diff --git a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java index 246d190ab..019b3096c 100644 --- a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java +++ b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java @@ -21,6 +21,7 @@ import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask; import org.embeddedt.embeddium.impl.render.chunk.data.BuiltRenderSectionData; import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts; import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.OccluderBoxBuilder; import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.util.WorldUtil; @@ -66,13 +67,16 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask private final int buildTime; private final Vector3d camera; + private final boolean rasterOcclusion; - public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext renderContext, int time, Vector3d camera) { + public ChunkBuilderMeshingTask(RenderSection render, ChunkRenderContext renderContext, int time, Vector3d camera, + boolean rasterOcclusion) { this.render = render; this.renderContext = renderContext; this.buildTime = time; this.camera = camera; + this.rasterOcclusion = rasterOcclusion; } @Override @@ -80,6 +84,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask ModernChunkBuildContext buildContext = (ModernChunkBuildContext)jobContext; MinecraftBuiltRenderSectionData renderData = new MinecraftBuiltRenderSectionData<>(); VisGraph occluder = new VisGraph(); + OccluderBoxBuilder occluderBoxes = this.rasterOcclusion ? new OccluderBoxBuilder() : null; ChunkBuildBuffers buffers = buildContext.buffers; buffers.init(renderData, this.render.getSectionIndex()); @@ -224,6 +229,10 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask if (blockState.isSolidRender(/*? if <1.21.11 {*/ slice, blockPos /*?}*/)) { occluder.setOpaque(blockPos); + + if (occluderBoxes != null) { + occluderBoxes.markOpaque(x, y, z); + } } } } @@ -246,6 +255,10 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask encodeVisibilityData(occluder, renderData); + if (occluderBoxes != null) { + renderData.occluderBoxes = occluderBoxes.build(); + } + postSectionDataBuiltEvent(renderData); return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime); -- 2.54.1 From 3487525d9117808e6dcec3dcfedf5e37fefd8676 Mon Sep 17 00:00:00 2001 From: rdh Date: Tue, 1 Sep 2026 23:33:04 -0400 Subject: [PATCH 07/20] carry the view matrix on Viewport --- .../render/chunk/occlusion/bench/Cameras.java | 2 +- .../chunk/occlusion/RasterMatrices.java | 22 +++++++++++++++++++ .../impl/render/viewport/Viewport.java | 15 +++++++++++++ .../core/render/frustum/FrustumMixin.java | 6 ++++- 4 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java index d6d256f41..80985d511 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java @@ -33,7 +33,7 @@ public final class Cameras { .rotateX((float) Math.toRadians(pitchDegrees)) .rotateY((float) Math.toRadians(yawDegrees + 180.0f)); - return new Viewport(new SimpleFrustum(new FrustumIntersection(matrix)), new Vector3d(x, y, z)); + return new Viewport(new SimpleFrustum(new FrustumIntersection(matrix)), new Vector3d(x, y, z), matrix); } public static Viewport viewport(double x, double y, double z, int renderDistance) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java new file mode 100644 index 000000000..b3220b809 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java @@ -0,0 +1,22 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion; + +import grondag.bitraster.Matrix4L; +import org.joml.Matrix4fc; + +/** Bridges JOML matrices into bitraster's fixed-point ones. */ +public final class RasterMatrices { + private RasterMatrices() { + } + + /** + * {@link Matrix4L} indexes {@code a} while JOML indexes {@code m}, so this + * transposes. Feeding it straight through instead still produces plausible-looking output. + */ + public static void copy(Matrix4fc src, Matrix4L dst) { + dst.set( + src.m00(), src.m10(), src.m20(), src.m30(), + src.m01(), src.m11(), src.m21(), src.m31(), + src.m02(), src.m12(), src.m22(), src.m32(), + src.m03(), src.m13(), src.m23(), src.m33()); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java index 0c82c7c7e..1d0ef7ff1 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/viewport/Viewport.java @@ -2,6 +2,9 @@ package org.embeddedt.embeddium.impl.render.viewport; import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum; import org.embeddedt.embeddium.impl.util.PositionUtil; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.joml.Matrix4fc; import org.joml.RoundingMode; import org.joml.Vector3d; import org.joml.Vector3i; @@ -14,10 +17,18 @@ public final class Viewport { private final Vector3i chunkCoords; private final Vector3i blockCoords; + private final @Nullable Matrix4fc vpMatrix; + public Viewport(Frustum frustum, Vector3d position) { + this(frustum, position, null); + } + + public Viewport(Frustum frustum, Vector3d position, @Nullable Matrix4fc vpMatrix) { this.frustum = frustum; this.transform = new CameraTransform(position.x, position.y, position.z); + this.vpMatrix = vpMatrix == null ? null : new Matrix4f(vpMatrix); + this.chunkCoords = new Vector3i( PositionUtil.posToSectionCoord(position.x), PositionUtil.posToSectionCoord(position.y), @@ -62,6 +73,10 @@ public final class Viewport { return this.frustum.intersectAab(minX, minY, minZ, maxX, maxY, maxZ); } + public @Nullable Matrix4fc getVpMatrix() { + return this.vpMatrix; + } + public Frustum getFrustum() { return this.frustum; } diff --git a/modern/src/main/modern_java/org/embeddedt/embeddium/impl/mixin/core/render/frustum/FrustumMixin.java b/modern/src/main/modern_java/org/embeddedt/embeddium/impl/mixin/core/render/frustum/FrustumMixin.java index 3996835c3..996a045a8 100644 --- a/modern/src/main/modern_java/org/embeddedt/embeddium/impl/mixin/core/render/frustum/FrustumMixin.java +++ b/modern/src/main/modern_java/org/embeddedt/embeddium/impl/mixin/core/render/frustum/FrustumMixin.java @@ -56,7 +56,11 @@ public class FrustumMixin implements ViewportProvider { @Override public Viewport sodium$createViewport() { - return new Viewport(new SimpleFrustum(this.intersection), new Vector3d(this.camX, this.camY, this.camZ)); + //? if >=1.20 { + return new Viewport(new SimpleFrustum(this.intersection), new Vector3d(this.camX, this.camY, this.camZ), this.matrix); + //?} else { + /*return new Viewport(new SimpleFrustum(this.intersection), new Vector3d(this.camX, this.camY, this.camZ)); + *///?} } //? if <1.20 { -- 2.54.1 From 5ea0f09aef844b6f2393dfdc94f3239c8dbfa905 Mon Sep 17 00:00:00 2001 From: rdh Date: Wed, 2 Sep 2026 00:53:20 -0400 Subject: [PATCH 08/20] cull sections against the rasterized occlusion buffer --- .../chunk/multidraw/bench/MultiDrawBench.java | 2 +- .../occlusion/bench/RasterCullReport.java | 44 +++++--- .../chunk/occlusion/bench/SyntheticWorld.java | 49 ++++++--- .../render/chunk/RenderSectionManager.java | 2 +- .../impl/render/chunk/lists/SectionGraph.java | 4 +- .../chunk/occlusion/OcclusionCuller.java | 46 +++++++- .../chunk/occlusion/RasterOccluder.java | 101 ++++++++++++++++++ .../chunk/occlusion/SectionLattice.java | 10 +- 8 files changed, 226 insertions(+), 32 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java index 99093e05f..b17409b03 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java @@ -87,7 +87,7 @@ public class MultiDrawBench { BenchPlatform.ensureInitialized(); this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, SyntheticWorld.DEFAULT_SEED, - this.caveWidth, true, 0.0D, false); + this.caveWidth, true, 0.0D, false, false); this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false); diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java index cc13cefac..777245a59 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java @@ -18,40 +18,56 @@ public final class RasterCullReport { public static void main(String[] args) { BenchPlatform.ensureInitialized(); - System.out.printf("%-8s %-8s %10s %10s%n", "world", "camera", "visited", "visible"); - System.out.println("-".repeat(42)); + System.out.printf("%-8s %-8s %10s %10s %8s %10s%n", + "world", "camera", "baseline", "occluded", "delta", "backtrack"); + System.out.println("-".repeat(66)); for (WorldType world : WORLDS) { - var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true); + var syntheticWorld = new SyntheticWorld(world, RENDER_DISTANCE, true, true); float searchDistance = syntheticWorld.getSearchDistance(); int numRegions = BenchPlatform.regionManager().getRegionIdsLength(); - var lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false); + var baselineLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, + false, false); + var rasterLattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, + false, true); for (RenderSection section : syntheticWorld.getConstructionOrder()) { - lattice.attach(section); + baselineLattice.attach(section); + rasterLattice.attach(section); } int frame = 0; for (Placement placement : placements()) { - long visited = 0; - long visible = 0; + long baseline = 0; + long occluded = 0; + long backtracks = 0; for (int step = 0; step < YAW_STEPS; step++) { Viewport viewport = Cameras.viewport(8.5, placement.y(), 8.5, (360.0f / YAW_STEPS) * step, placement.pitch(), RENDER_DISTANCE); - var visitor = new CountingVisitor(); - lattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); - lattice.findVisible(visitor, viewport, searchDistance, numRegions, true, true, ++frame); + var without = new CountingVisitor(); + baselineLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); + baselineLattice.findVisible(without, viewport, searchDistance, numRegions, true, true, ++frame); - visited += visitor.visited; - visible += visitor.visible; + var with = new CountingVisitor(); + rasterLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); + rasterLattice.findVisible(with, viewport, searchDistance, numRegions, true, true, ++frame); + + baseline += without.visible; + occluded += with.visible; + backtracks += rasterLattice.rasterBacktrackCount(); } - System.out.printf("%-8s %-8s %10d %10d%n", world, placement.name(), - visited / YAW_STEPS, visible / YAW_STEPS); + long meanBaseline = baseline / YAW_STEPS; + long meanOccluded = occluded / YAW_STEPS; + double delta = meanBaseline == 0 ? 0.0 + : ((meanOccluded - meanBaseline) * 100.0) / meanBaseline; + + System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d%n", world, placement.name(), + meanBaseline, meanOccluded, delta, backtracks / YAW_STEPS); } } } diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java index 52167bda1..c01c25250 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java @@ -4,6 +4,7 @@ import it.unimi.dsi.fastutil.longs.Long2ReferenceMap; import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap; import org.embeddedt.embeddium.impl.render.chunk.ChunkUpdateType; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes; import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.VoxelWorld; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; @@ -43,20 +44,27 @@ public final class SyntheticWorld { private final int sectionCount; public SyntheticWorld(WorldType type, int renderDistance) { - this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, false, 0.0D, false); + this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, false, 0.0D, false, false); } public SyntheticWorld(WorldType type, int renderDistance, boolean scatteredAlloc) { - this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false); + this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false, false); + } + + public SyntheticWorld(WorldType type, int renderDistance, boolean scatteredAlloc, boolean occluderBoxes) { + this(type, renderDistance, DEFAULT_SEED, VoxelWorld.DEFAULT_CAVE_WIDTH, scatteredAlloc, 0.0D, false, + occluderBoxes); } /** * @param scatteredAlloc shuffled allocation order (models a long-lived session) * @param unloadedProbability fraction of sections absent from the box * @param allFlagged full visuals mask on every section (sensitivity knob, not realistic) + * @param occluderBoxes generate occluder boxes; far dearer per section than the visibility fill, + * and dead weight unless a report is measuring the rasterizer */ public SyntheticWorld(WorldType type, int renderDistance, long seed, double caveWidth, boolean scatteredAlloc, - double unloadedProbability, boolean allFlagged) { + double unloadedProbability, boolean allFlagged, boolean occluderBoxes) { this.type = type; this.renderDistance = renderDistance; this.seed = seed; @@ -102,7 +110,11 @@ public final class SyntheticWorld { // arithmetic moves off this thread — pass 2 still allocates every section itself, in order, because the // heap layout of those sections is exactly what scatteredAlloc exists to control and letting worker // threads allocate them into their own TLABs would quietly change what the benchmark measures. - long[] visibility = this.computeVisibility(radius, width); + int[][] boxes = occluderBoxes + ? new int[width * width * (MAX_SECTION_Y - MIN_SECTION_Y)][] + : null; + + long[] visibility = this.computeVisibility(radius, width, boxes); // Pass 2: allocate sections in the requested order. this.sections = new Long2ReferenceOpenHashMap<>(present, 0.75f); @@ -114,8 +126,14 @@ public final class SyntheticWorld { var section = new RenderSection(regionFor(regionManager, regions, x, y, z), x, y, z); - section.setInfo(new BenchSectionData(visibility[gridIndex(x, y, z, radius, width)], x, y, z, - allFlagged)); + var info = new BenchSectionData(visibility[gridIndex(x, y, z, radius, width)], x, y, z, + allFlagged); + + if (boxes != null) { + info.occluderBoxes = boxes[gridIndex(x, y, z, radius, width)]; + } + + section.setInfo(info); applyPendingUpdate(section, x, y, z); this.sections.put(packed, section); @@ -211,14 +229,14 @@ public final class SyntheticWorld { * {@code VoxelWorld}'s heightmap cache. Output does not depend on the striping: visibility is a pure * function of position. */ - private long[] computeVisibility(int radius, int width) { + private long[] computeVisibility(int radius, int width, int[][] occluderBoxes) { final int height = MAX_SECTION_Y - MIN_SECTION_Y; var visibility = new long[width * width * height]; int workers = Math.min(Runtime.getRuntime().availableProcessors(), width); if (workers <= 1) { - this.computeVisibilityStripe(this.voxelWorld, visibility, radius, width, 0, 1); + this.computeVisibilityStripe(this.voxelWorld, visibility, occluderBoxes, radius, width, 0, 1); return visibility; } @@ -231,7 +249,7 @@ public final class SyntheticWorld { // seed generate identical blocks. They are dropped with the threads, releasing those caches. threads[w] = new Thread(() -> this.computeVisibilityStripe( new VoxelWorld(this.type, this.seed, this.voxelWorld.getCaveWidth()), - visibility, radius, width, worker, workers), "bench-worldgen-" + worker); + visibility, occluderBoxes, radius, width, worker, workers), "bench-worldgen-" + worker); threads[w].start(); } @@ -249,8 +267,8 @@ public final class SyntheticWorld { } /** Runs the real visibility flood fill over every section in this worker's share of the columns. */ - private void computeVisibilityStripe(VoxelWorld world, long[] visibility, int radius, int width, - int worker, int workers) { + private void computeVisibilityStripe(VoxelWorld world, long[] visibility, int[][] occluderBoxes, + int radius, int width, int worker, int workers) { for (int xi = worker; xi < width; xi += workers) { int x = xi - radius; @@ -262,7 +280,14 @@ public final class SyntheticWorld { continue; } - visibility[gridIndex(x, y, z, radius, width)] = world.slice(x, y, z).computeVisibility(); + var slice = world.slice(x, y, z); + int index = gridIndex(x, y, z, radius, width); + + if (occluderBoxes != null) { + occluderBoxes[index] = OccluderBoxes.from(slice.opacityBits()); + } + + visibility[index] = slice.computeVisibility(); } } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java index 0199c0ec4..ff1d75f9f 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSectionManager.java @@ -139,7 +139,7 @@ public abstract class RenderSectionManager { this.minSection = minSection; this.maxSection = maxSection; AsyncOcclusionMode asyncMode = this.getAsyncOcclusionMode(); - this.sectionGraph = new SectionGraph(this.minSection, this.maxSection, asyncMode, hasShadowPass); + this.sectionGraph = new SectionGraph(this.minSection, this.maxSection, asyncMode, hasShadowPass, this.useRasterOcclusionCulling()); this.renderListManager = new RenderListManager(this.sectionGraph, false, asyncMode, this.createSectionTicker()); if (hasShadowPass) { this.shadowRenderListManager = new RenderListManager(this.sectionGraph, true, asyncMode, this.createSectionTicker()); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/SectionGraph.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/SectionGraph.java index 2839f098c..6c3d6c643 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/SectionGraph.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/lists/SectionGraph.java @@ -34,8 +34,8 @@ public final class SectionGraph { // runDeferredTasks() once every search has been joined. private final ArrayDeque updateTasks = new ArrayDeque<>(); - public SectionGraph(int minSectionY, int maxSectionY, AsyncOcclusionMode asyncMode, boolean hasShadowPass) { - this.lattice = new SectionLattice(minSectionY, maxSectionY, hasShadowPass); + public SectionGraph(int minSectionY, int maxSectionY, AsyncOcclusionMode asyncMode, boolean hasShadowPass, boolean rasterOcclusion) { + this.lattice = new SectionLattice(minSectionY, maxSectionY, hasShadowPass, rasterOcclusion); if (asyncMode != AsyncOcclusionMode.NONE) { this.executor = Executors.newSingleThreadExecutor(runnable -> { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java index 57554157d..b202f69de 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java @@ -3,10 +3,12 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion; import org.embeddedt.embeddium.impl.common.util.MathUtil; import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata; +import org.embeddedt.embeddium.impl.render.chunk.lists.RenderVisualsService; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum; +import org.jetbrains.annotations.Nullable; import org.joml.Vector3ic; import static org.embeddedt.embeddium.impl.common.util.MathUtil.nearestToZero; @@ -114,13 +116,17 @@ public class OcclusionCuller { private final RegionCullCache regionCullCache = new RegionCullCache(); + private final @Nullable RasterOccluder rasterOccluder; + private boolean rasterActive; + private boolean isCameraInUnloadedSection; private boolean isMultiRootSearch; - public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY) { + public OcclusionCuller(SectionLattice lattice, int minSectionY, int maxSectionY, boolean rasterOcclusion) { this.lattice = lattice; this.minSectionY = minSectionY; this.maxSectionY = maxSectionY; + this.rasterOccluder = rasterOcclusion ? new RasterOccluder() : null; } /** @@ -182,6 +188,12 @@ public class OcclusionCuller { allowFrustumClamping = false; } + this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null; + + if (this.rasterActive) { + this.rasterOccluder.prepareScene(frame, viewport); + } + this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame); if (recordVisible) { @@ -285,6 +297,10 @@ public class OcclusionCuller { visible = aperture != FastFrustumClamping.EMPTY; } + if (this.rasterActive && visible) { + visible = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, compactMeta); + } + int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ); visitor.visit(idx, regionId, sectionIndex, compactMeta, visible); @@ -335,6 +351,34 @@ public class OcclusionCuller { this.visibleCount = visibleCount; } + private boolean rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, int meta) { + int dx = chunkX - camX; + int dy = chunkY - camY; + int dz = chunkZ - camZ; + int squaredChunkDist = (dx * dx) + (dy * dy) + (dz * dz); + + var occluder = this.rasterOccluder; + + if (!occluder.isSectionVisible(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist)) { + return false; + } + + if ((PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0) { + var section = this.lattice.latticeSection[idx]; + var built = section != null ? section.getBuiltContext() : null; + + if (built != null && built.occluderBoxes != null) { + occluder.drawOccluders(built.occluderBoxes, squaredChunkDist); + } + } + + return true; + } + + public int rasterBacktrackCount() { + return this.rasterOccluder == null ? 0 : this.rasterOccluder.backtrackCount(); + } + // Visit each selected neighbour using both its linear array offset and // its packed-coordinate offset. The lattice border makes idx + delta safe. private void visitNeighbors(long[] visitState, long[] queue, int[] delta, int idx, int xyz, int outgoing, long frameStamp) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java new file mode 100644 index 000000000..ab3620451 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java @@ -0,0 +1,101 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion; + +import grondag.bitraster.BoxOccluder; +import grondag.bitraster.Matrix4L; +import grondag.bitraster.PackedBox; +import grondag.bitraster.PerspectiveRasterizer; +import org.embeddedt.embeddium.impl.render.viewport.Viewport; +import org.joml.Matrix4fc; + +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 */ + 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 maxDrawnSquaredDist; + private int backtrackCount; + + public RasterOccluder() { + super(new PerspectiveRasterizer()); + } + + @Override + public boolean isBoxVisible(int packedBox, int fuzz) { + return isBoxVisibleFromPerspective(packedBox, fuzz); + } + + @Override + public void occludeBox(int packedBox) { + occludeFromPerspective(packedBox); + } + + /** + * Clears the buffer for a new search. The matrix already carries rotation and projection but no + * camera translation, so it is supplied as the projection with an identity model matrix; + * {@link #prepareRegion} applies the camera-relative offset per section. + */ + public void prepareScene(int viewVersion, Viewport viewport) { + Matrix4fc vpMatrix = viewport.getVpMatrix(); + + if (vpMatrix == null) { + throw new IllegalStateException("viewport supplies no view matrix"); + } + + var transform = viewport.getTransform(); + + this.maxDrawnSquaredDist = 0; + this.backtrackCount = 0; + + invalidate(); + prepareScene(viewVersion, transform.x, transform.y, transform.z, + Matrix4L::loadIdentity, m -> RasterMatrices.copy(vpMatrix, m)); + } + + /** + * {@return whether any part of the section is unoccluded} + * + *

Must be called before {@link #drawOccluders}, or a section would occlude itself. + */ + public boolean isSectionVisible(int originX, int originY, int originZ, int squaredChunkDist) { + prepareRegion(originX, originY, originZ, + PackedBox.rangeFromSquareChunkDist(squaredChunkDist), squaredChunkDist); + + if (squaredChunkDist <= NEAR_SQUARED_CHUNK_DIST) { + return true; + } + + boolean visible = isBoxVisible(PackedBox.FULL_BOX, + squaredChunkDist >= FUZZ_SQUARED_CHUNK_DIST ? 1 : 0); + + if (!visible && squaredChunkDist < this.maxDrawnSquaredDist) { + this.backtrackCount++; + } + + return visible; + } + + public void drawOccluders(int[] boxes, int squaredChunkDist) { + int range = PackedBox.rangeFromSquareChunkDist(squaredChunkDist); + + for (int box : boxes) { + if (range > PackedBox.range(box)) { + break; + } + + occludeBox(box); + } + + if (squaredChunkDist > this.maxDrawnSquaredDist) { + this.maxDrawnSquaredDist = squaredChunkDist; + } + } + + // the buffer holds coverage only, with no depth, so it's correct only if sections are drawn + // front to back. our bfs visits in hop-count order, which approximates that but does not + // guarantee it, so this reports how often the approximation was wrong. + public int backtrackCount() { + return this.backtrackCount; + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index 6eb639b9d..0423a7954 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -192,11 +192,15 @@ public final class SectionLattice { * visit-state array */ public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass) { + this(minSectionY, maxSectionY, hasShadowPass, false); + } + + public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass, boolean rasterOcclusion) { this.minSectionY = minSectionY; this.maxSectionY = maxSectionY; this.baseY = minSectionY - 1; this.dimY = (maxSectionY - minSectionY) + 2; - this.culler = new OcclusionCuller(this, minSectionY, maxSectionY); + this.culler = new OcclusionCuller(this, minSectionY, maxSectionY, rasterOcclusion); this.shadowCuller = hasShadowPass ? new ShadowOcclusionCuller(this) : null; if (this.dimY > MAX_DIM) { @@ -459,6 +463,10 @@ public final class SectionLattice { return this.snapshot(this.visitState, this.mainSnapshotBuffers); } + public int rasterBacktrackCount() { + return this.culler.rasterBacktrackCount(); + } + /** * Run the shadow-pass search over the currently installed lattice cells, using the shadow visit-state array * so the main search's state is left intact. -- 2.54.1 From 74c6cf0ffd1be0ae998af2247bdba563ffd010af Mon Sep 17 00:00:00 2001 From: rdh Date: Wed, 2 Sep 2026 01:42:41 -0400 Subject: [PATCH 09/20] test sections against the bounds of what they draw a section holding one block was tested as though it filled its whole volume, so sparse sections were barely culled even though they contributed basically no coverage --- .../occlusion/bench/OcclusionCullerBench.java | 9 ++++- .../chunk/occlusion/bench/SyntheticWorld.java | 3 +- .../chunk/occlusion/OcclusionCuller.java | 38 +++++++++++-------- .../chunk/occlusion/RenderableBounds.java | 30 +++++++++++++++ .../occlusion/SectionVisibilityBuilder.java | 7 +++- .../tasks/ChunkBuilderMeshingTask.java | 4 ++ 6 files changed, 70 insertions(+), 21 deletions(-) create mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RenderableBounds.java diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java index 4f08eb912..fd5827ec5 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/OcclusionCullerBench.java @@ -45,6 +45,9 @@ public class OcclusionCullerBench { @Param({ "true" }) public boolean scatteredAlloc; + @Param({ "false" }) + public boolean rasterOcclusion; + public SyntheticWorld syntheticWorld; public SectionLattice lattice; @@ -62,12 +65,14 @@ public class OcclusionCullerBench { public void setup() { BenchPlatform.ensureInitialized(); - this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, this.scatteredAlloc); + this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, this.scatteredAlloc, + this.rasterOcclusion); this.searchDistance = this.syntheticWorld.getSearchDistance(); this.numRegions = BenchPlatform.regionManager().getRegionIdsLength(); - this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false); + this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, + this.rasterOcclusion); for (RenderSection section : this.syntheticWorld.getConstructionOrder()) { this.lattice.attach(section); diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java index c01c25250..86cb28542 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/SyntheticWorld.java @@ -4,7 +4,6 @@ import it.unimi.dsi.fastutil.longs.Long2ReferenceMap; import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap; import org.embeddedt.embeddium.impl.render.chunk.ChunkUpdateType; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes; import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.VoxelWorld; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager; @@ -284,7 +283,7 @@ public final class SyntheticWorld { int index = gridIndex(x, y, z, radius, width); if (occluderBoxes != null) { - occluderBoxes[index] = OccluderBoxes.from(slice.opacityBits()); + occluderBoxes[index] = slice.occlusionData(); } visibility[index] = slice.computeVisibility(); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java index b202f69de..ab6cdcafa 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java @@ -1,5 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion; +import grondag.bitraster.PackedBox; import org.embeddedt.embeddium.impl.common.util.MathUtil; import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; import org.embeddedt.embeddium.impl.render.chunk.PackedSectionMetadata; @@ -297,18 +298,22 @@ public class OcclusionCuller { visible = aperture != FastFrustumClamping.EMPTY; } + boolean traverse = visible; + if (this.rasterActive && visible) { - visible = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, compactMeta); + RasterOccluder.SectionVisibility result = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, compactMeta); + visible = result == RasterOccluder.SectionVisibility.VISIBLE; + traverse = result != RasterOccluder.SectionVisibility.HIDDEN; } int sectionIndex = LocalSectionIndex.pack(chunkX, chunkY, chunkZ); visitor.visit(idx, regionId, sectionIndex, compactMeta, visible); - if (!visible) { + if (!traverse) { continue; } - if (visibleCells != null) { + if (visible && visibleCells != null) { visibleCells[visibleCount++] = entry; } @@ -351,28 +356,29 @@ public class OcclusionCuller { this.visibleCount = visibleCount; } - private boolean rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, int meta) { + private RasterOccluder.SectionVisibility rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, int meta) { int dx = chunkX - camX; int dy = chunkY - camY; int dz = chunkZ - camZ; int squaredChunkDist = (dx * dx) + (dy * dy) + (dz * dz); + boolean hasGeometry = + (PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0; + + var section = this.lattice.latticeSection[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; + var occluder = this.rasterOccluder; + RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds); - if (!occluder.isSectionVisible(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist)) { - return false; + if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && data != null) { + occluder.occlude(data); } - if ((PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0) { - var section = this.lattice.latticeSection[idx]; - var built = section != null ? section.getBuiltContext() : null; - - if (built != null && built.occluderBoxes != null) { - occluder.drawOccluders(built.occluderBoxes, squaredChunkDist); - } - } - - return true; + return result; } public int rasterBacktrackCount() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RenderableBounds.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RenderableBounds.java new file mode 100644 index 000000000..5c9391d80 --- /dev/null +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RenderableBounds.java @@ -0,0 +1,30 @@ +package org.embeddedt.embeddium.impl.render.chunk.occlusion; + +import grondag.bitraster.PackedBox; + +final class RenderableBounds { + private int minX = 16, minY = 16, minZ = 16; + private int maxX = -1, maxY = -1, maxZ = -1; + + void mark(int x, int y, int z) { + if (x < this.minX) this.minX = x; + if (y < this.minY) this.minY = y; + if (z < this.minZ) this.minZ = z; + if (x > this.maxX) this.maxX = x; + if (y > this.maxY) this.maxY = y; + if (z > this.maxZ) this.maxZ = z; + } + + boolean isEmpty() { + return this.maxX < 0; + } + + int packed() { + if (isEmpty()) { + return PackedBox.FULL_BOX; + } + + return PackedBox.pack(this.minX, this.minY, this.minZ, + this.maxX + 1, this.maxY + 1, this.maxZ + 1, PackedBox.RANGE_EXTREME); + } +} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java index ec5ffc855..26c07ba9f 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java @@ -26,6 +26,7 @@ public class SectionVisibilityBuilder { private static final int[] INDICES_TO_INITIATE_FLOODFILL = buildFloodfillIndices(); private final BitSet blocks; + private final RenderableBounds renderableBounds = new RenderableBounds(); private boolean floodFilled; @@ -65,12 +66,16 @@ public class SectionVisibilityBuilder { this.blocks.set(getIndex(x & 15, y & 15, z & 15)); } + public void markRenderable(int x, int y, int z) { + this.renderableBounds.mark(x & 15, y & 15, z & 15); + } + public int @Nullable [] computeOccluderBoxes() { if (this.floodFilled) { throw new IllegalStateException("opacity was consumed by computeVisibilityEncoding()"); } - return OccluderBoxBuilder.boxesFrom(this.blocks); + return OccluderBoxBuilder.dataFrom(this.blocks, this.renderableBounds); } private long computeWithFloodFill() { diff --git a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java index 019b3096c..499dd35da 100644 --- a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java +++ b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java @@ -137,6 +137,10 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask blockPos.set(x, y, z); modelOffset.set(x & 15, y & 15, z & 15); + if (occluderBoxes != null) { + occluderBoxes.markRenderable(x, y, z); + } + //? if shaders && >=1.17 { if (voxelizingLight && blockState.getBlock() instanceof net.minecraft.world.level.block.LightBlock) { cache.getSpecialBlockRenderer().voxelizeLightBlock(blockPos, blockState, buffers); -- 2.54.1 From 33671a2f300fc7f01b4dec959ade67a0800f69ca Mon Sep 17 00:00:00 2001 From: rdh Date: Wed, 2 Sep 2026 14:58:45 -0400 Subject: [PATCH 10/20] oops this is why you dont mess with git history kids --- .../render/chunk/bench/voxel/VoxelSlice.java | 30 +++++++++++ .../chunk/occlusion/OccluderBoxBuilder.java | 30 +++++++++-- .../chunk/occlusion/RasterOccluder.java | 50 +++++++++---------- 3 files changed, 80 insertions(+), 30 deletions(-) diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java index 63477187d..76848ff8d 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java @@ -1,5 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.bench.voxel; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.OccluderBoxBuilder; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionVisibilityBuilder; import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; @@ -102,6 +103,35 @@ public final class VoxelSlice { return occluder.computeVisibilityEncoding(); } + public int[] occlusionData() { + if (this.empty) { + return null; + } + + var builder = new OccluderBoxBuilder(); + byte[] blocks = this.blocks; + + for (int y = 0; y < 16; y++) { + for (int z = 0; z < 16; z++) { + int row = ((y + 1) * AREA) + ((z + 1) * SIZE) + 1; + + for (int x = 0; x < 16; x++) { + int block = blocks[row + x]; + + if (VoxelWorld.isOpaque(block)) { + builder.markOpaque(x, y, z); + } + + if (VoxelWorld.isRenderable(block)) { + builder.markRenderable(x, y, z); + } + } + } + } + + return builder.build(); + } + public long[] opacityBits() { var bits = new long[64]; diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java index 6eeadc2cc..815956855 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java @@ -11,20 +11,40 @@ import java.util.BitSet; // can keep using that and supply opacity here instead of paying for a second flood fill it doesn't need public final class OccluderBoxBuilder { private final BitSet blocks = new BitSet(SectionVisibilityBuilder.TOTAL_BLOCKS); + private final RenderableBounds bounds = new RenderableBounds(); public void markOpaque(int x, int y, int z) { this.blocks.set(SectionVisibilityBuilder.getIndex(x & 15, y & 15, z & 15)); } - public int @Nullable [] build() { - return boxesFrom(this.blocks); + public void markRenderable(int x, int y, int z) { + this.bounds.mark(x & 15, y & 15, z & 15); } - static int @Nullable [] boxesFrom(BitSet blocks) { - if (blocks.isEmpty()) { + public int @Nullable [] build() { + return dataFrom(this.blocks, this.bounds); + } + + public static int bounds(int[] data) { + return data[0]; + } + + static int @Nullable [] dataFrom(BitSet blocks, RenderableBounds bounds) { + if (blocks.isEmpty() && bounds.isEmpty()) { return null; } - return OccluderBoxes.from(Arrays.copyOf(blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS)); + int[] boxes = blocks.isEmpty() ? null + : OccluderBoxes.from(Arrays.copyOf(blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS)); + + int count = boxes == null ? 0 : boxes.length; + int[] data = new int[count + 1]; + data[0] = bounds.packed(); + + if (boxes != null) { + System.arraycopy(boxes, 0, data, 1, count); + } + + return data; } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java index ab3620451..6f11e6324 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java @@ -14,9 +14,18 @@ public final class RasterOccluder extends BoxOccluder { /** 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 maxDrawnSquaredDist; private int backtrackCount; + public enum SectionVisibility { + /** nothing of the section is visible, and nothing behind it can be reached through it */ + HIDDEN, + /** the section draws nothing visible, but the space it occupies is not fully covered, so + * traversal must continue through it or geometry behind it would be lost */ + TRAVERSABLE, + /** the section is visible and can be used to occlude other sections */ + VISIBLE + } + public RasterOccluder() { super(new PerspectiveRasterizer()); } @@ -45,7 +54,6 @@ public final class RasterOccluder extends BoxOccluder { var transform = viewport.getTransform(); - this.maxDrawnSquaredDist = 0; this.backtrackCount = 0; invalidate(); @@ -54,42 +62,34 @@ public final class RasterOccluder extends BoxOccluder { } /** - * {@return whether any part of the section is unoccluded} - * - *

Must be called before {@link #drawOccluders}, or a section would occlude itself. + * 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. + * must run before occlude(), or a section would occlude itself. */ - public boolean isSectionVisible(int originX, int originY, int originZ, int squaredChunkDist) { + public SectionVisibility testSection(int originX, int originY, int originZ, int squaredChunkDist, int bounds) { prepareRegion(originX, originY, originZ, PackedBox.rangeFromSquareChunkDist(squaredChunkDist), squaredChunkDist); if (squaredChunkDist <= NEAR_SQUARED_CHUNK_DIST) { - return true; + return SectionVisibility.VISIBLE; } - boolean visible = isBoxVisible(PackedBox.FULL_BOX, - squaredChunkDist >= FUZZ_SQUARED_CHUNK_DIST ? 1 : 0); + int fuzz = squaredChunkDist >= FUZZ_SQUARED_CHUNK_DIST ? 1 : 0; - if (!visible && squaredChunkDist < this.maxDrawnSquaredDist) { + if (isBoxVisible(bounds, fuzz)) { + return SectionVisibility.VISIBLE; + } + + if (squaredChunkDist < maxSquaredChunkDistance()) { this.backtrackCount++; } - return visible; - } - - public void drawOccluders(int[] boxes, int squaredChunkDist) { - int range = PackedBox.rangeFromSquareChunkDist(squaredChunkDist); - - for (int box : boxes) { - if (range > PackedBox.range(box)) { - break; - } - - occludeBox(box); + // only worth asking when the bounds were tighter than the section itself + if (bounds != PackedBox.FULL_BOX && isBoxVisible(PackedBox.FULL_BOX, fuzz)) { + return SectionVisibility.TRAVERSABLE; } - if (squaredChunkDist > this.maxDrawnSquaredDist) { - this.maxDrawnSquaredDist = squaredChunkDist; - } + return SectionVisibility.HIDDEN; } // the buffer holds coverage only, with no depth, so it's correct only if sections are drawn -- 2.54.1 From f947f8f3ab687df40d835be547f2c89343aca3b9 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Thu, 3 Sep 2026 11:59:02 -0400 Subject: [PATCH 11/20] speed up raster occlusion culling ~4-8x and harden its accuracy Per-frame cost of the rasterized occlusion culler drops from 3.1ms to 1.4ms at render distance 32 and from 15.7ms to under 4ms at 64 (JMH rotatingCamera, SURFACE), against 0.5ms / 1.9ms for the culler with the raster off. Culled section counts are unchanged to within a few sections per frame. Rasterizer (grondag.bitraster): - Test polygons take a center-pixel fast path: the centre of a convex box projects inside its silhouette, so one clear pixel there proves visibility with a single transform. Resolves ~80% of section tests. - Boxes are drawn and tested as one convex silhouette polygon (4 or 6 vertices, derived from the existing per-face quad tables) instead of two or three overlapping quads. The quad path remains as the near-clip fallback. - Edge events are populated lazily per 8-row tile band instead of for the whole polygon up front, with the flat-edge filler clamped to the band. - Tests exit early on an untouched tile, and each band computes the range of tile columns fully inside the polygon so tests return and draws fill without computing coverage. - A one-bit-per-tile "fully covered" bitset lets scans skip covered runs 64 tiles at a time. - Vertex transforms use a float view-projection matrix plus a per-region offset instead of copying and translating a fixed-point matrix per section; box corners are built from one transformed corner and three axis deltas. - Edge slopes are computed once per polygon (double divide) rather than per band with a 64-bit integer divide, and only when a band actually needs them. - Test polygons are dilated by one pixel on every side so a visible strip thinner than the pixel pitch still reaches a sampled pixel centre. This replaces the distance-gated one-block world-space fuzz, whose margin was several pixels mid-range and under a pixel at the far end. - Buffer geometry is per instance and per axis. Each frame the width and height are chosen from the view-projection matrix's row lengths (the horizontal and vertical projection scales) so that a block at the search distance spans at least one pixel on each axis, with hysteresis so field-of-view animation cannot thrash it. Sizes range 512..2048 per axis. - Fix an off-by-one in the centre test where a screen coordinate just below 1.0 rounded to a pixel row equal to the buffer height. - Work counters for the stats report, gated behind a JIT-constant flag. Culler integration: - The lattice mirrors each cell's occluder box array so the raster test does not chase section and build-data pointers per visited cell. - The search distance is passed to the raster occluder for buffer sizing. Benchmarks: - RasterStatsReport (gradle rasterStats): per-frame counts of tests, draws and tiles by outcome, a test/occlude time split, and a camera-height scan. - RasterCullReport prints the chosen buffer size and accepts render distance and field of view via system properties, plus an FOV sweep mode. --- common/build.gradle | 9 + .../render/chunk/occlusion/bench/Cameras.java | 7 +- .../occlusion/bench/RasterCullReport.java | 57 +- .../occlusion/bench/RasterStatsReport.java | 102 ++ .../grondag/bitraster/AbstractRasterizer.java | 1476 ++++++++++------- .../java/grondag/bitraster/BoxOccluder.java | 107 +- .../java/grondag/bitraster/Constants.java | 56 +- .../main/java/grondag/bitraster/Indexer.java | 7 - .../grondag/bitraster/OrthoRasterizer.java | 58 +- .../bitraster/PerspectiveRasterizer.java | 170 +- .../chunk/occlusion/OcclusionCuller.java | 14 +- .../chunk/occlusion/RasterOccluder.java | 115 +- .../chunk/occlusion/SectionLattice.java | 23 + 13 files changed, 1473 insertions(+), 728 deletions(-) create mode 100644 common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java diff --git a/common/build.gradle b/common/build.gradle index 986aa4fbc..b72a5845d 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -239,3 +239,12 @@ def transformedAttr = Attribute.of("rfgDeobfuscatorTransformed", Boolean) 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() }) } +} diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java index 80985d511..420e146a8 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/Cameras.java @@ -28,8 +28,13 @@ public final class Cameras { } 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() - .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)) .rotateY((float) Math.toRadians(yawDegrees + 180.0f)); diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java index 777245a59..9ee12d257 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterCullReport.java @@ -5,7 +5,8 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionLattice; import org.embeddedt.embeddium.impl.render.viewport.Viewport; 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 WorldType[] WORLDS = { WorldType.SURFACE, WorldType.CAVES }; @@ -18,9 +19,14 @@ public final class RasterCullReport { public static void main(String[] args) { BenchPlatform.ensureInitialized(); - System.out.printf("%-8s %-8s %10s %10s %8s %10s%n", - "world", "camera", "baseline", "occluded", "delta", "backtrack"); - System.out.println("-".repeat(66)); + if (Boolean.getBoolean("report.fovscan")) { + fovScan(); + 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) { 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++) { 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(); baselineLattice.ensureWindowCovers(viewport.getChunkCoord(), searchDistance); @@ -66,12 +72,49 @@ public final class RasterCullReport { double delta = meanBaseline == 0 ? 0.0 : ((meanOccluded - meanBaseline) * 100.0) / meanBaseline; - System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d%n", world, placement.name(), - meanBaseline, meanOccluded, delta, backtracks / YAW_STEPS); + System.out.printf("%-8s %-8s %10d %10d %7.1f%% %10d %10s%n", world, placement.name(), + 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() { double surfaceY = Cameras.surfaceCameraY(0, 0); diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java new file mode 100644 index 000000000..0b285278e --- /dev/null +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java @@ -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; + } +} diff --git a/common/src/main/java/grondag/bitraster/AbstractRasterizer.java b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java index e7b0bc818..8f940f239 100644 --- a/common/src/main/java/grondag/bitraster/AbstractRasterizer.java +++ b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java @@ -16,6 +16,11 @@ package grondag.bitraster; +import java.util.Arrays; + +import static grondag.bitraster.Constants.MIN_SIZE_BITS; +import static grondag.bitraster.Constants.MAX_SIZE_BITS; +import static grondag.bitraster.Constants.PRECISE_PIXEL_CENTER; import static grondag.bitraster.Constants.BOUNDS_IN; import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; import static grondag.bitraster.Constants.EDGE_BOTTOM; @@ -102,7 +107,6 @@ import static grondag.bitraster.Constants.EVENT_0123_RRLR; import static grondag.bitraster.Constants.EVENT_0123_RRRF; import static grondag.bitraster.Constants.EVENT_0123_RRRL; import static grondag.bitraster.Constants.EVENT_0123_RRRR; -import static grondag.bitraster.Constants.EVENT_DATA_LENGTH; import static grondag.bitraster.Constants.EVENT_POSITION_MASK; import static grondag.bitraster.Constants.IDX_AX0; import static grondag.bitraster.Constants.IDX_AX1; @@ -120,13 +124,14 @@ import static grondag.bitraster.Constants.IDX_DX0; import static grondag.bitraster.Constants.IDX_DX1; import static grondag.bitraster.Constants.IDX_DY0; import static grondag.bitraster.Constants.IDX_DY1; -import static grondag.bitraster.Constants.MAX_PIXEL_Y; -import static grondag.bitraster.Constants.PIXEL_HEIGHT; -import static grondag.bitraster.Constants.PIXEL_WIDTH; -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.TEST_DILATION_PIXELS; +import static grondag.bitraster.Constants.EVENT_0_FLAT; +import static grondag.bitraster.Constants.EVENT_0_LEFT; +import static grondag.bitraster.Constants.TILE_PIXEL_INDEX_MASK; +import static grondag.bitraster.Constants.A_ZERO; +import static grondag.bitraster.Constants.A_POSITIVE; +import static grondag.bitraster.Constants.IDX_EX0; +import static grondag.bitraster.Constants.IDX_FX0; import static grondag.bitraster.Constants.PRECISION_BITS; import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PY; @@ -135,22 +140,32 @@ import static grondag.bitraster.Constants.PV_Z; import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER; import static grondag.bitraster.Constants.TILE_AXIS_MASK; import static grondag.bitraster.Constants.TILE_AXIS_SHIFT; -import static grondag.bitraster.Constants.TILE_COUNT; -import static grondag.bitraster.Constants.TILE_HEIGHT_MASK; -import static grondag.bitraster.Constants.TILE_WIDTH; -import static grondag.bitraster.Constants.TILE_WIDTH_BITS; -import static grondag.bitraster.Constants.TILE_WIDTH_MASK; import static grondag.bitraster.Constants.VERTEX_DATA_LENGTH; -import static grondag.bitraster.Indexer.tileIndexFromPixelXY; // Some elements are adapted from content found at // https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/ // by Fabian “ryg” Giesen. That content is in the public domain. public abstract class AbstractRasterizer { final Matrix4L mvpMatrix = new Matrix4L(); + + /** Float copy of the scene's view-projection matrix, without any per-region translation. */ + float m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33; + + /** Region origin relative to the camera, in blocks. Added to vertex positions before transformation. */ + float offsetX, offsetY, offsetZ; final int[] vertexData = new int[VERTEX_DATA_LENGTH]; - final int[] eventData = new int[EVENT_DATA_LENGTH]; - final long[] tiles = new long[TILE_COUNT]; + // CELERITAS: buffer geometry is per instance so each axis can follow render distance and field of view. + // The hot loops use only shifts and masks with these, which measured no slower than folded constants. + int widthBits, heightBits; + int tileWidthBits, tileWidthMask, tileCount; + int pixelWidth, pixelHeight, lastPixelX, lastPixelY, halfPixelWidth, halfPixelHeight; + int preciseWidth, preciseHeight, halfPreciseWidth, halfPreciseHeight, preciseWidthClamp, preciseHeightClamp; + + int[] eventData; + long[] tiles; + + /** One bit per tile, set once the tile is fully covered, so scans can skip covered runs 64 tiles at a time. */ + long[] fullBits; final EventFiller[] EVENT_FILLERS = new EventFiller[0x1000]; /** Bounds of current triangle - pixel coordinates. */ @@ -163,6 +178,39 @@ public abstract class AbstractRasterizer { /** Control iteration in populateEvents_ methods. */ protected int eventY0, eventLimit; + /** Edge classification of the current quad, selecting its {@link #EVENT_FILLERS} entry. */ + protected int eventKey; + + /** Inclusive range of tile columns fully covered by the quad on every row of the current band; empty when first > last. */ + protected int bandInnerFirst, bandInnerLast; + + /** Per-edge intercept at y = 0 and step per pixel row, 20-bit fixed point. See {@link #prepareEvents}. */ + protected boolean edgesReady; + protected final long[] edgeX0 = new long[6]; + protected final long[] edgeStep = new long[6]; + + /** Vertex-data slot of each edge of the current polygon, in order. */ + private static final int[] EDGE_SLOTS = { IDX_AX0, IDX_BX0, IDX_CX0, IDX_DX0, IDX_EX0, IDX_FX0 }; + + /** + * True when the current polygon was set up by {@link #preparePolygonNoClip} and its events come from the + * generic filler rather than the quad {@link #EVENT_FILLERS} table. + */ + protected boolean genericEvents; + + /** + * True while testing: the polygon is grown by one pixel on every side so a visible strip thinner than the + * pixel pitch, which pixel-centre sampling would miss, still reaches a sampled pixel. Drawing never dilates, + * or abutting occluders would double-cover and hide the seams between them. + */ + protected boolean dilate; + private final int[] leftEdges = new int[6]; + private final int[] rightEdges = new int[6]; + private final int[] flatPositions = new int[6]; + private final int[] flatSlots = new int[6]; + private int leftCount, rightCount, flatCount; + private final long[] leftX0 = new long[3], leftStep = new long[3], rightX0 = new long[3], rightStep = new long[3]; + { EVENT_FILLERS[EVENT_0123_RRRR] = () -> { populateLeftEvents(); @@ -175,7 +223,7 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FRRR] = () -> { populateLeftEvents(); populateRightEvents3(IDX_BX0, IDX_CX0, IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RLRR] = () -> { populateLeftEvents(IDX_BX0); @@ -188,23 +236,23 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FLRR] = () -> { populateLeftEvents(IDX_BX0); populateRightEvents2(IDX_CX0, IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RFRR] = () -> { populateLeftEvents(); populateRightEvents3(IDX_AX0, IDX_CX0, IDX_DX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_LFRR] = () -> { populateLeftEvents(IDX_AX0); populateRightEvents2(IDX_CX0, IDX_DX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_FFRR] = () -> { populateLeftEvents(); populateRightEvents2(IDX_CX0, IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_RRLR] = () -> { @@ -218,7 +266,7 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FRLR] = () -> { populateLeftEvents(IDX_CX0); populateRightEvents2(IDX_BX0, IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RLLR] = () -> { populateLeftEvents2(IDX_BX0, IDX_CX0); @@ -231,75 +279,75 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FLLR] = () -> { populateLeftEvents2(IDX_BX0, IDX_CX0); populateRightEvents(IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RFLR] = () -> { populateLeftEvents(IDX_CX0); populateRightEvents2(IDX_AX0, IDX_DX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_LFLR] = () -> { populateLeftEvents2(IDX_AX0, IDX_CX0); populateRightEvents(IDX_DX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_FFLR] = () -> { populateLeftEvents(IDX_CX0); populateRightEvents(IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_LRFR] = () -> { populateLeftEvents(IDX_AX0); populateRightEvents2(IDX_BX0, IDX_DX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RRFR] = () -> { populateLeftEvents(); populateRightEvents3(IDX_AX0, IDX_BX0, IDX_DX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_FRFR] = () -> { populateLeftEvents(); populateRightEvents2(IDX_BX0, IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RLFR] = () -> { populateLeftEvents(IDX_BX0); populateRightEvents2(IDX_AX0, IDX_DX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_LLFR] = () -> { populateLeftEvents2(IDX_AX0, IDX_BX0); populateRightEvents(IDX_DX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_FLFR] = () -> { populateLeftEvents(IDX_BX0); populateRightEvents(IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RFFR] = () -> { populateLeftEvents(); populateRightEvents2(IDX_AX0, IDX_DX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_LFFR] = () -> { populateLeftEvents(IDX_AX0); populateRightEvents(IDX_DX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_FFFR] = () -> { populateLeftEvents(); populateRightEvents(IDX_DX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RRRL] = () -> { @@ -313,7 +361,7 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FRRL] = () -> { populateLeftEvents(IDX_DX0); populateRightEvents2(IDX_BX0, IDX_CX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RLRL] = () -> { populateLeftEvents2(IDX_BX0, IDX_DX0); @@ -326,23 +374,23 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FLRL] = () -> { populateLeftEvents2(IDX_BX0, IDX_DX0); populateRightEvents(IDX_CX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RFRL] = () -> { populateLeftEvents(IDX_DX0); populateRightEvents2(IDX_AX0, IDX_CX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_LFRL] = () -> { populateLeftEvents2(IDX_AX0, IDX_DX0); populateRightEvents(IDX_CX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_FFRL] = () -> { populateLeftEvents(IDX_DX0); populateRightEvents(IDX_CX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_RRLL] = () -> { populateLeftEvents2(IDX_CX0, IDX_DX0); @@ -355,7 +403,7 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FRLL] = () -> { populateLeftEvents2(IDX_CX0, IDX_DX0); populateRightEvents(IDX_BX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RLLL] = () -> { populateLeftEvents3(IDX_BX0, IDX_CX0, IDX_DX0); @@ -368,251 +416,343 @@ public abstract class AbstractRasterizer { EVENT_FILLERS[EVENT_0123_FLLL] = () -> { populateLeftEvents3(IDX_BX0, IDX_CX0, IDX_DX0); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); + populateFlatEvents(pos0, IDX_AX0); }; EVENT_FILLERS[EVENT_0123_RFLL] = () -> { populateLeftEvents2(IDX_CX0, IDX_DX0); populateRightEvents(IDX_AX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_LFLL] = () -> { populateLeftEvents3(IDX_AX0, IDX_CX0, IDX_DX0); populateRightEvents(); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_FFLL] = () -> { populateLeftEvents2(IDX_CX0, IDX_DX0); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); }; EVENT_FILLERS[EVENT_0123_LRFL] = () -> { populateLeftEvents2(IDX_AX0, IDX_DX0); populateRightEvents(IDX_BX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RRFL] = () -> { populateLeftEvents(IDX_DX0); populateRightEvents2(IDX_AX0, IDX_BX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_FRFL] = () -> { populateLeftEvents(IDX_DX0); populateRightEvents(IDX_BX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RLFL] = () -> { populateLeftEvents2(IDX_BX0, IDX_DX0); populateRightEvents(IDX_AX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_LLFL] = () -> { populateLeftEvents3(IDX_AX0, IDX_BX0, IDX_DX0); populateRightEvents(); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_FLFL] = () -> { populateLeftEvents2(IDX_BX0, IDX_DX0); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RFFL] = () -> { populateLeftEvents(IDX_DX0); populateRightEvents(IDX_AX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_LFFL] = () -> { populateLeftEvents2(IDX_AX0, IDX_DX0); populateRightEvents(); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_FFFL] = () -> { populateLeftEvents(IDX_DX0); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); }; EVENT_FILLERS[EVENT_0123_RRRF] = () -> { populateLeftEvents(); populateRightEvents3(IDX_AX0, IDX_BX0, IDX_CX0); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LRRF] = () -> { populateLeftEvents(IDX_AX0); populateRightEvents2(IDX_BX0, IDX_CX0); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FRRF] = () -> { populateLeftEvents(); populateRightEvents2(IDX_BX0, IDX_CX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RLRF] = () -> { populateLeftEvents(IDX_BX0); populateRightEvents2(IDX_AX0, IDX_CX0); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LLRF] = () -> { populateLeftEvents2(IDX_AX0, IDX_BX0); populateRightEvents(IDX_CX0); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FLRF] = () -> { populateLeftEvents(IDX_BX0); populateRightEvents(IDX_CX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RFRF] = () -> { populateLeftEvents(); populateRightEvents2(IDX_AX0, IDX_CX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LFRF] = () -> { populateLeftEvents(IDX_AX0); populateRightEvents(IDX_CX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FFRF] = () -> { populateLeftEvents(); populateRightEvents(IDX_CX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RRLF] = () -> { populateLeftEvents(IDX_CX0); populateRightEvents2(IDX_AX0, IDX_BX0); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LRLF] = () -> { populateLeftEvents2(IDX_AX0, IDX_CX0); populateRightEvents(IDX_BX0); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FRLF] = () -> { populateLeftEvents(IDX_CX0); populateRightEvents(IDX_BX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RLLF] = () -> { populateLeftEvents2(IDX_BX0, IDX_CX0); populateRightEvents(IDX_AX0); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LLLF] = () -> { populateLeftEvents3(IDX_AX0, IDX_BX0, IDX_CX0); populateRightEvents(); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FLLF] = () -> { populateLeftEvents2(IDX_BX0, IDX_CX0); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RFLF] = () -> { populateLeftEvents(IDX_CX0); populateRightEvents(IDX_AX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LFLF] = () -> { populateLeftEvents2(IDX_AX0, IDX_CX0); populateRightEvents(); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FFLF] = () -> { populateLeftEvents(IDX_CX0); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LRFF] = () -> { populateLeftEvents(IDX_AX0); populateRightEvents(IDX_BX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RRFF] = () -> { populateLeftEvents(); populateRightEvents2(IDX_AX0, IDX_BX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FRFF] = () -> { populateLeftEvents(); populateRightEvents(IDX_BX0); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RLFF] = () -> { populateLeftEvents(IDX_BX0); populateRightEvents(IDX_AX0); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LLFF] = () -> { populateLeftEvents2(IDX_AX0, IDX_BX0); populateRightEvents(); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FLFF] = () -> { populateLeftEvents(IDX_BX0); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_RFFF] = () -> { populateLeftEvents(); populateRightEvents(IDX_AX0); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_LFFF] = () -> { populateLeftEvents(IDX_AX0); populateRightEvents(); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; EVENT_FILLERS[EVENT_0123_FFFF] = () -> { // fill it populateLeftEvents(); populateRightEvents(); - populateFlatEvents(pos0, vertexData[IDX_AY0]); - populateFlatEvents(pos1, vertexData[IDX_BY0]); - populateFlatEvents(pos2, vertexData[IDX_CY0]); - populateFlatEvents(pos3, vertexData[IDX_DY0]); + populateFlatEvents(pos0, IDX_AX0); + populateFlatEvents(pos1, IDX_BX0); + populateFlatEvents(pos2, IDX_CX0); + populateFlatEvents(pos3, IDX_DX0); }; } - final void copyFrom(AbstractRasterizer source) { - mvpMatrix.copyFrom(source.mvpMatrix); - System.arraycopy(source.vertexData, 0, vertexData, 0, VERTEX_DATA_LENGTH); - System.arraycopy(source.eventData, 0, eventData, 0, EVENT_DATA_LENGTH); - System.arraycopy(source.tiles, 0, tiles, 0, TILE_COUNT); + AbstractRasterizer(int widthBits, int heightBits) { + resize(widthBits, heightBits); } + /** {@return the buffer width as a power of two of tiles; pixels are eight times that} */ + public final int widthBits() { + return widthBits; + } + + /** {@return the buffer height as a power of two of tiles; pixels are eight times that} */ + public final int heightBits() { + return heightBits; + } + + /** + * Sets the buffer to {@code 8 << widthBits} by {@code 8 << heightBits} pixels, reallocating and clearing it + * if the size changed. Safe between frames only: the current polygon and scene contents are discarded. + */ + public final void resize(int widthBits, int heightBits) { + if (widthBits < MIN_SIZE_BITS || widthBits > MAX_SIZE_BITS || heightBits < MIN_SIZE_BITS || heightBits > MAX_SIZE_BITS) { + throw new IllegalArgumentException("unsupported buffer size bits " + widthBits + "x" + heightBits); + } + + if (this.widthBits == widthBits && this.heightBits == heightBits && tiles != null) { + return; + } + + this.widthBits = widthBits; + this.heightBits = heightBits; + tileWidthBits = widthBits; + tileWidthMask = (1 << widthBits) - 1; + tileCount = 1 << (widthBits + heightBits); + pixelWidth = 1 << (widthBits + TILE_AXIS_SHIFT); + pixelHeight = 1 << (heightBits + TILE_AXIS_SHIFT); + lastPixelX = pixelWidth - 1; + lastPixelY = pixelHeight - 1; + halfPixelWidth = pixelWidth >> 1; + halfPixelHeight = pixelHeight >> 1; + preciseWidth = pixelWidth << PRECISION_BITS; + preciseHeight = pixelHeight << PRECISION_BITS; + halfPreciseWidth = preciseWidth >> 1; + halfPreciseHeight = preciseHeight >> 1; + // clamp to this to ensure value + half pixel rounds down to last pixel + preciseWidthClamp = preciseWidth - PRECISE_PIXEL_CENTER; + preciseHeightClamp = preciseHeight - PRECISE_PIXEL_CENTER; + + eventData = new int[pixelHeight * 2]; + tiles = new long[tileCount]; + fullBits = new long[tileCount >> 6]; + } + + /** Marks every pixel clear. */ + final void clear() { + Arrays.fill(tiles, 0L); + Arrays.fill(fullBits, 0L); + } + + final int tileIndexFromPixelXY(int x, int y) { + return (x >>> TILE_AXIS_SHIFT) | ((y >>> TILE_AXIS_SHIFT) << tileWidthBits); + } + + /** Loads the scene matrix; regions are then positioned with {@link #setRegionOffset}. */ + final void setMatrix(Matrix4L m) { + mvpMatrix.copyFrom(m); + m00 = m.a00f(); m01 = m.a01f(); m02 = m.a02f(); m03 = m.a03f(); + m10 = m.a10f(); m11 = m.a11f(); m12 = m.a12f(); m13 = m.a13f(); + m20 = m.a20f(); m21 = m.a21f(); m22 = m.a22f(); m23 = m.a23f(); + m30 = m.a30f(); m31 = m.a31f(); m32 = m.a32f(); m33 = m.a33f(); + } + + /** @param x region origin relative to the camera, in {@link Constants#CAMERA_PRECISION_BITS} fixed point */ + final void setRegionOffset(int x, int y, int z) { + final float scale = 1f / Constants.CAMERA_PRECISION_UNITY; + offsetX = x * scale; + offsetY = y * scale; + offsetZ = z * scale; + } + + final void copyFrom(AbstractRasterizer source) { + resize(source.widthBits, source.heightBits); + setMatrix(source.mvpMatrix); + offsetX = source.offsetX; + offsetY = source.offsetY; + offsetZ = source.offsetZ; + System.arraycopy(source.vertexData, 0, vertexData, 0, VERTEX_DATA_LENGTH); + System.arraycopy(source.eventData, 0, eventData, 0, eventData.length); + System.arraycopy(source.tiles, 0, tiles, 0, tileCount); + System.arraycopy(source.fullBits, 0, fullBits, 0, tileCount >> 6); + } + + // CELERITAS: work counters for RasterStatsReport. STATS is a constant so the JIT drops the increments when off. + public static final boolean STATS = Boolean.getBoolean("bitraster.stats"); + public static long STAT_D_NOOP, STAT_D_RANGE0, STAT_D_RANGE1, STAT_D_RANGE2, STAT_D_RANGE3; + public static long STAT_T_EMPTY, STAT_T_INNER, STAT_T_COVER, STAT_T_HIDDEN, STAT_D_INNER, STAT_D_COVER; + public static long STAT_DRAW_QUADS, STAT_TEST_QUADS, STAT_TEST_TILES, STAT_EVENT_ROWS, STAT_DRAW_CALLS, STAT_TEST_CALLS; + final void drawQuad(int v0, int v1, int v2, int v3) { + if (STATS) STAT_DRAW_CALLS++; + dilate = false; if (prepareBounds(v0, v1, v2, v3) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { return; } + if (STATS) STAT_DRAW_QUADS++; // Don't draw single points if (minPixelX == maxPixelX && minPixelY == maxPixelY) { @@ -623,55 +763,90 @@ public abstract class AbstractRasterizer { } final boolean isQuadPartiallyClear(int v0, int v1, int v2, int v3) { + if (STATS) STAT_TEST_CALLS++; + dilate = true; if (prepareBounds(v0, v1, v2, v3) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { return false; } + if (STATS) STAT_TEST_QUADS++; - final int px = minPixelX; - final int py = minPixelY; + dilateBounds(); + return isQuadPartiallyClear(); + } - if (px == maxPixelX && py == maxPixelY) { - return px >= 0 && py >= 0 && px < PIXEL_WIDTH && py < PIXEL_HEIGHT && isPixelClear(px, py); - } else { - return isQuadPartiallyClear(); - } + /** Grows the pixel bounds of a test polygon by one on every side, within the screen. */ + private void dilateBounds() { + minPixelX = Math.max(0, minPixelX - TEST_DILATION_PIXELS); + minPixelY = Math.max(0, minPixelY - TEST_DILATION_PIXELS); + maxPixelX = Math.min(lastPixelX, maxPixelX + TEST_DILATION_PIXELS); + maxPixelY = Math.min(lastPixelY, maxPixelY + TEST_DILATION_PIXELS); } final boolean isQuadPartiallyClear() { final int minTileX = minPixelX >> TILE_AXIS_SHIFT; final int maxTileX = maxPixelX >> TILE_AXIS_SHIFT; - final int maxTileY = (maxPixelY >> TILE_AXIS_SHIFT) << TILE_WIDTH_BITS; + final int minTileY = minPixelY >> TILE_AXIS_SHIFT; + final int maxTileY = maxPixelY >> TILE_AXIS_SHIFT; final long[] tiles = this.tiles; + final long[] fullBits = this.fullBits; - int tileIndex = tileIndexFromPixelXY(minPixelX, minPixelY); - int xLimit = maxTileX; - int xInc = 1; + for (int tileY = minTileY; tileY <= maxTileY; tileY++) { + final int rowBase = tileY << tileWidthBits; + final int last = rowBase + maxTileX; + boolean populated = false; + int innerFirst = 0, innerLast = -1; - while (true) { - final long word = tiles[tileIndex]; + for (int tileIndex = rowBase + minTileX; tileIndex <= last; tileIndex++) { + // jump to the next tile that is not already fully covered + final long open = ~fullBits[tileIndex >> 6] >>> (tileIndex & 63); - if (word != -1L && (~word & computeTileCoverage(tileIndex)) != 0) { - return true; - } - - if ((tileIndex & TILE_WIDTH_MASK) == xLimit) { - if ((tileIndex & TILE_HEIGHT_MASK) == maxTileY) { - return false; - } else { - // move up - tileIndex += TILE_WIDTH; - // flip x order - xLimit = xLimit == maxTileX ? minTileX : maxTileX; - xInc = -xInc; + if (open == 0) { + tileIndex |= 63; + continue; + } + + tileIndex += Long.numberOfTrailingZeros(open); + + if (tileIndex > last) { + break; + } + + if (STATS) STAT_TEST_TILES++; + final long word = tiles[tileIndex]; + + // nothing drawn here yet; the quad's bounds reach this tile, so treat it as clear without + // rasterizing. slightly optimistic at silhouette corners, which only ever under-culls. + if (word == 0L) { + if (STATS) STAT_T_EMPTY++; + return true; + } + + if (!populated) { + populateBand(tileY); + populated = true; + innerFirst = rowBase + bandInnerFirst; + innerLast = rowBase + bandInnerLast; + } + + // interior tiles are fully covered by the quad, and this one is not fully drawn + if (tileIndex >= innerFirst && tileIndex <= innerLast) { + if (STATS) STAT_T_INNER++; + return true; + } + + if ((~word & computeTileCoverage(tileIndex)) != 0) { + if (STATS) STAT_T_COVER++; + return true; } - } else { - // move left or right - tileIndex += xInc; } } + + if (STATS) STAT_T_HIDDEN++; + return false; } final boolean isQuadPartiallyOccluded(int v0, int v1, int v2, int v3) { + dilate = false; if (prepareBounds(v0, v1, v2, v3) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { return false; } @@ -680,7 +855,7 @@ public abstract class AbstractRasterizer { final int py = minPixelY; if (px == maxPixelX && py == maxPixelY) { - return px >= 0 && py >= 0 && px < PIXEL_WIDTH && py < PIXEL_HEIGHT && isPixelSet(px, py); + return px >= 0 && py >= 0 && px < pixelWidth && py < pixelHeight && isPixelSet(px, py); } else { return isQuadPartiallyOccluded(); } @@ -689,113 +864,165 @@ public abstract class AbstractRasterizer { final boolean isQuadPartiallyOccluded() { final int minTileX = minPixelX >> TILE_AXIS_SHIFT; final int maxTileX = maxPixelX >> TILE_AXIS_SHIFT; - final int maxTileY = (maxPixelY >> TILE_AXIS_SHIFT) << TILE_WIDTH_BITS; + final int minTileY = minPixelY >> TILE_AXIS_SHIFT; + final int maxTileY = maxPixelY >> TILE_AXIS_SHIFT; final long[] tiles = this.tiles; - int tileIndex = tileIndexFromPixelXY(minPixelX, minPixelY); - int xLimit = maxTileX; - int xInc = 1; + for (int tileY = minTileY; tileY <= maxTileY; tileY++) { + final int rowBase = tileY << tileWidthBits; + boolean populated = false; - while (true) { - final long word = tiles[tileIndex]; + for (int tileX = minTileX; tileX <= maxTileX; tileX++) { + final int tileIndex = rowBase + tileX; + final long word = tiles[tileIndex]; - if (word != 0 && (word & computeTileCoverage(tileIndex)) != 0) { - return true; - } + if (word == 0L) { + continue; + } - if ((tileIndex & TILE_WIDTH_MASK) == xLimit) { - if ((tileIndex & TILE_HEIGHT_MASK) == maxTileY) { - return false; - } else { - // move up - tileIndex += TILE_WIDTH; - // flip x order - xLimit = xLimit == maxTileX ? minTileX : maxTileX; - xInc = -xInc; + if (!populated) { + populateBand(tileY); + populated = true; + } + + if ((word & computeTileCoverage(tileIndex)) != 0) { + return true; } - } else { - // move left or right - tileIndex += xInc; } } + + return false; } final void drawQuad() { final int minTileX = minPixelX >> TILE_AXIS_SHIFT; final int maxTileX = maxPixelX >> TILE_AXIS_SHIFT; - final int maxTileY = (maxPixelY >> TILE_AXIS_SHIFT) << TILE_WIDTH_BITS; + final int minTileY = minPixelY >> TILE_AXIS_SHIFT; + final int maxTileY = maxPixelY >> TILE_AXIS_SHIFT; final long[] tiles = this.tiles; + final long[] fullBits = this.fullBits; + for (int tileY = minTileY; tileY <= maxTileY; tileY++) { + final int rowBase = tileY << tileWidthBits; + final int last = rowBase + maxTileX; + boolean populated = false; + int innerFirst = 0, innerLast = -1; - int tileIndex = tileIndexFromPixelXY(minPixelX, minPixelY); - int xLimit = maxTileX; - int xInc = 1; + for (int tileIndex = rowBase + minTileX; tileIndex <= last; tileIndex++) { + // jump to the next tile that is not already fully covered + final int wordIndex = tileIndex >> 6; + final long open = ~fullBits[wordIndex] >>> (tileIndex & 63); - while (true) { - long word = tiles[tileIndex]; + if (open == 0) { + tileIndex |= 63; + continue; + } - // nothing to do if fully occluded - if (word != -1L) { - word |= computeTileCoverage(tileIndex); + tileIndex += Long.numberOfTrailingZeros(open); + + if (tileIndex > last) { + break; + } + + if (!populated) { + populateBand(tileY); + populated = true; + innerFirst = rowBase + bandInnerFirst; + innerLast = rowBase + bandInnerLast; + } + + final long word; + + if (tileIndex >= innerFirst && tileIndex <= innerLast) { + if (STATS) STAT_D_INNER++; + word = -1L; + } else { + if (STATS) STAT_D_COVER++; + word = tiles[tileIndex] | computeTileCoverage(tileIndex); + } + tiles[tileIndex] = word; - } - if ((tileIndex & TILE_WIDTH_MASK) == xLimit) { - if ((tileIndex & TILE_HEIGHT_MASK) == maxTileY) { - return; - } else { - // move up - tileIndex += TILE_WIDTH; - // flip x order - xLimit = xLimit == maxTileX ? minTileX : maxTileX; - xInc = -xInc; + if (word == -1L) { + fullBits[wordIndex] |= 1L << (tileIndex & 63); } - } else { - // move left or right - tileIndex += xInc; } } + + if (STATS && !edgesReady) STAT_D_NOOP++; } abstract int prepareBounds(int v0, int v1, int v2, int v3); - private void populateFlatEvents(int position, int y0In) { + /** + * Marks the rows beyond a flat edge as empty. Under {@link #dilate} the first such row instead takes the + * edge's span, since the sloped neighbours extrapolated past a flat edge would not cover it. + */ + private void populateFlatEvents(int position, int slot) { final int[] eventData = this.eventData; + final int[] data = this.vertexData; + final int y0In = data[slot + 1]; + final int bandFirst = eventY0; + final int bandLast = eventLimit >> 1; + final int grow = dilate ? TEST_DILATION_PIXELS : 0; if (position == EDGE_TOP) { - final int py = ((y0In + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) + 1; + final int edgeRow = (y0In + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + final int py = edgeRow + 1 + grow; - if (py == MAX_PIXEL_Y) return; + if (py > lastPixelY) return; - final int y1 = (maxPixelY & TILE_AXIS_MASK) + 7; - final int start = py < 0 ? 0 : (py << 1); - final int limit = y1 << 1; + final int start = (py < bandFirst ? bandFirst : py) << 1; + final int limit = bandLast << 1; - assert limit < EVENT_DATA_LENGTH; + assert limit < eventData.length; for (int y = start; y <= limit; ) { - eventData[y++] = PIXEL_WIDTH; + eventData[y++] = pixelWidth; eventData[y++] = -1; } + + for (int i = 1; i <= grow; i++) { + spanRow(edgeRow + i, slot, bandFirst, bandLast); + } } else if (position == EDGE_BOTTOM) { - final int py = (y0In >> PRECISION_BITS); + final int edgeRow = y0In >> PRECISION_BITS; + final int py = edgeRow - grow; - if (py == 0) return; + if (py <= 0) return; - final int y0 = minPixelY & TILE_AXIS_MASK; - final int start = y0 << 1; - final int limit = py > MAX_PIXEL_Y ? (MAX_PIXEL_Y << 1) : (py << 1); + final int start = bandFirst << 1; + final int end = py > bandLast + 1 ? bandLast + 1 : py; + final int limit = end > lastPixelY ? (lastPixelY << 1) : (end << 1); - assert limit < EVENT_DATA_LENGTH; + assert limit < eventData.length; for (int y = start; y < limit; ) { - eventData[y++] = PIXEL_WIDTH; + eventData[y++] = pixelWidth; eventData[y++] = -1; } + + for (int i = 1; i <= grow; i++) { + spanRow(edgeRow - i, slot, bandFirst, bandLast); + } } else { assert position == EDGE_POINT; } } + /** Gives one row the horizontal extent of a flat edge, if the row lies in the current band. */ + private void spanRow(int row, int slot, int bandFirst, int bandLast) { + if (row < bandFirst || row > bandLast || row < 0 || row > lastPixelY) { + return; + } + + final int[] data = this.vertexData; + final int xa = data[slot]; + final int xb = data[slot + 2]; + final int[] eventData = this.eventData; + eventData[row << 1] = ((xa < xb ? xa : xb) + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + eventData[(row << 1) + 1] = ((xa < xb ? xb : xa) + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + } + /** * Puts left edge at screen boundary. */ @@ -810,32 +1037,18 @@ public abstract class AbstractRasterizer { } private void populateLeftEvents(int a) { - final int[] vertexData = this.vertexData; - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; final int limit = eventLimit; - final long dx = ax1 - ax0; + final int ea = (a - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; - if (dx == 0) { - final int x = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS); - - for (int y = (y0 << 1); y <= limit; y += 2) { - eventData[y] = x; - } - } else { - final long n = (dx << 16) / (ay1 - ay0); - final long nStep = n << PRECISION_BITS; - long x = ((long) ax0 << 16) - n * ay0 + nStep * y0 + 0x100000L; - - for (int y = (y0 << 1); y <= limit; y += 2) { - eventData[y] = (int) (x >> 20); - x += nStep; - } + for (int y = (y0 << 1); y <= limit; y += 2) { + eventData[y] = (int) (ax >> 20); + ax += aStep; } } @@ -847,147 +1060,66 @@ public abstract class AbstractRasterizer { // difference from left: is high index in pairs for (int y = (y0 << 1) + 1; y <= limit; y += 2) { - eventData[y] = PIXEL_WIDTH; + eventData[y] = pixelWidth; } } private void populateRightEvents(int a) { - final int[] vertexData = this.vertexData; - - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; - // difference from left: is high index in pairs + // right events are the high index in each pair final int limit = eventLimit + 1; - final int dx = ax1 - ax0; + final int ea = (a - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; - if (dx == 0) { - final int x = (ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; - - // difference from left: is high index in pairs - for (int y = (y0 << 1) + 1; y <= limit; y += 2) { - eventData[y] = x; - } - } else { - final long n = (((long) dx) << 16) / (ay1 - ay0); - final long nStep = n << PRECISION_BITS; - // difference from left: rounding looses tie - long x = ((long) ax0 << 16) - n * ay0 + nStep * y0 + 0x7FFFFL; - - // difference from left: is high index in pairs - for (int y = (y0 << 1) + 1; y <= limit; y += 2) { - eventData[y] = (int) (x >> 20); - x += nStep; - } + for (int y = (y0 << 1) + 1; y <= limit; y += 2) { + eventData[y] = (int) (ax >> 20); + ax += aStep; } } private void populateLeftEvents2(int a, int b) { - final int[] vertexData = this.vertexData; - - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - - final int bx0 = vertexData[b]; - final int by0 = vertexData[b + 1]; - final int bx1 = vertexData[b + 2]; - final int by1 = vertexData[b + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; final int limit = eventLimit; - - final long aStep, bStep; - long ax, bx; - - if (ax0 == ax1) { - ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - aStep = 0; - } else { - final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); - aStep = an << PRECISION_BITS; - ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x100000L; - } - - if (bx0 == bx1) { - bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - bStep = 0; - } else { - final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); - bStep = bn << PRECISION_BITS; - bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x100000L; - } + final int ea = (a - IDX_AX0) >> 2; + final int eb = (b - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; + final long bStep = edgeStep[eb]; + long bx = edgeX0[eb] + bStep * y0; for (int y = (y0 << 1); y <= limit; y += 2) { eventData[y] = (int) ((ax > bx ? ax : bx) >> 20); - ax += aStep; bx += bStep; } } private void populateLeftEvents3(int a, int b, int c) { - final int[] vertexData = this.vertexData; - - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - - final int bx0 = vertexData[b]; - final int by0 = vertexData[b + 1]; - final int bx1 = vertexData[b + 2]; - final int by1 = vertexData[b + 3]; - - final int cx0 = vertexData[c]; - final int cy0 = vertexData[c + 1]; - final int cx1 = vertexData[c + 2]; - final int cy1 = vertexData[c + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; final int limit = eventLimit; - - final long aStep, bStep, cStep; - long ax, bx, cx; - - if (ax0 == ax1) { - ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - aStep = 0; - } else { - final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); - aStep = an << PRECISION_BITS; - ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x100000L; - } - - if (bx0 == bx1) { - bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - bStep = 0; - } else { - final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); - bStep = bn << PRECISION_BITS; - bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x100000L; - } - - if (cx0 == cx1) { - cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - cStep = 0; - } else { - final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); - cStep = cn << PRECISION_BITS; - cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x100000L; - } + final int ea = (a - IDX_AX0) >> 2; + final int eb = (b - IDX_AX0) >> 2; + final int ec = (c - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; + final long bStep = edgeStep[eb]; + long bx = edgeX0[eb] + bStep * y0; + final long cStep = edgeStep[ec]; + long cx = edgeX0[ec] + cStep * y0; for (int y = (y0 << 1); y <= limit; y += 2) { final long i = ax > bx ? ax : bx; eventData[y] = (int) ((cx > i ? cx : i) >> 20); - ax += aStep; bx += bStep; cx += cStep; @@ -995,76 +1127,28 @@ public abstract class AbstractRasterizer { } private void populateLeftEvents4(int a, int b, int c, int d) { - final int[] vertexData = this.vertexData; - - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - - final int bx0 = vertexData[b]; - final int by0 = vertexData[b + 1]; - final int bx1 = vertexData[b + 2]; - final int by1 = vertexData[b + 3]; - - final int cx0 = vertexData[c]; - final int cy0 = vertexData[c + 1]; - final int cx1 = vertexData[c + 2]; - final int cy1 = vertexData[c + 3]; - - final int dx0 = vertexData[d]; - final int dy0 = vertexData[d + 1]; - final int dx1 = vertexData[d + 2]; - final int dy1 = vertexData[d + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; final int limit = eventLimit; - - final long aStep, bStep, cStep, dStep; - long ax, bx, cx, dx; - - if (ax0 == ax1) { - ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - aStep = 0; - } else { - final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); - aStep = an << PRECISION_BITS; - ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x100000L; - } - - if (bx0 == bx1) { - bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - bStep = 0; - } else { - final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); - bStep = bn << PRECISION_BITS; - bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x100000L; - } - - if (cx0 == cx1) { - cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - cStep = 0; - } else { - final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); - cStep = cn << PRECISION_BITS; - cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x100000L; - } - - if (dx0 == dx1) { - dx = ((dx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - dStep = 0; - } else { - final long dn = (((long) (dx1 - dx0)) << 16) / (dy1 - dy0); - dStep = dn << PRECISION_BITS; - dx = ((long) dx0 << 16) - dn * dy0 + dStep * y0 + 0x100000L; - } + final int ea = (a - IDX_AX0) >> 2; + final int eb = (b - IDX_AX0) >> 2; + final int ec = (c - IDX_AX0) >> 2; + final int ed = (d - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; + final long bStep = edgeStep[eb]; + long bx = edgeX0[eb] + bStep * y0; + final long cStep = edgeStep[ec]; + long cx = edgeX0[ec] + cStep * y0; + final long dStep = edgeStep[ed]; + long dx = edgeX0[ed] + dStep * y0; for (int y = (y0 << 1); y <= limit; y += 2) { final long i = ax > bx ? ax : bx; final long j = cx > dx ? cx : dx; eventData[y] = (int) ((i > j ? i : j) >> 20); - ax += aStep; bx += bStep; cx += cStep; @@ -1073,118 +1157,46 @@ public abstract class AbstractRasterizer { } private void populateRightEvents2(int a, int b) { - final int[] vertexData = this.vertexData; - - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - - final int bx0 = vertexData[b]; - final int by0 = vertexData[b + 1]; - final int bx1 = vertexData[b + 2]; - final int by1 = vertexData[b + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; - // difference from left: is high index in pairs + // right events are the high index in each pair final int limit = eventLimit + 1; + final int ea = (a - IDX_AX0) >> 2; + final int eb = (b - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; + final long bStep = edgeStep[eb]; + long bx = edgeX0[eb] + bStep * y0; - final long aStep, bStep; - long ax, bx; - - if (ax0 == ax1) { - ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - aStep = 0; - } else { - final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); - aStep = an << PRECISION_BITS; - // difference from left: rounding looses tie - ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x7FFFFL; - } - - if (bx0 == bx1) { - bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - bStep = 0; - } else { - final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); - bStep = bn << PRECISION_BITS; - // difference from left: rounding looses tie - bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x7FFFFL; - } - - // difference from left: is high index in pairs for (int y = (y0 << 1) + 1; y <= limit; y += 2) { - // difference from left: lower value wins eventData[y] = (int) ((ax < bx ? ax : bx) >> 20); - ax += aStep; bx += bStep; } } private void populateRightEvents3(int a, int b, int c) { - final int[] vertexData = this.vertexData; - - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - - final int bx0 = vertexData[b]; - final int by0 = vertexData[b + 1]; - final int bx1 = vertexData[b + 2]; - final int by1 = vertexData[b + 3]; - - final int cx0 = vertexData[c]; - final int cy0 = vertexData[c + 1]; - final int cx1 = vertexData[c + 2]; - final int cy1 = vertexData[c + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; - // difference from left: is high index in pairs + // right events are the high index in each pair final int limit = eventLimit + 1; + final int ea = (a - IDX_AX0) >> 2; + final int eb = (b - IDX_AX0) >> 2; + final int ec = (c - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; + final long bStep = edgeStep[eb]; + long bx = edgeX0[eb] + bStep * y0; + final long cStep = edgeStep[ec]; + long cx = edgeX0[ec] + cStep * y0; - final long aStep, bStep, cStep; - long ax, bx, cx; - - if (ax0 == ax1) { - ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - aStep = 0; - } else { - final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); - aStep = an << PRECISION_BITS; - // difference from left: rounding looses tie - ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x7FFFFL; - } - - if (bx0 == bx1) { - bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - bStep = 0; - } else { - final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); - bStep = bn << PRECISION_BITS; - // difference from left: rounding looses tie - bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x7FFFFL; - } - - if (cx0 == cx1) { - cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - cStep = 0; - } else { - final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); - cStep = cn << PRECISION_BITS; - // difference from left: rounding looses tie - cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x7FFFFL; - } - - // difference from left: is high index in pairs for (int y = (y0 << 1) + 1; y <= limit; y += 2) { - // difference from left: lower value wins final long i = ax < bx ? ax : bx; eventData[y] = (int) ((cx < i ? cx : i) >> 20); - ax += aStep; bx += bStep; cx += cStep; @@ -1192,83 +1204,29 @@ public abstract class AbstractRasterizer { } private void populateRightEvents4(int a, int b, int c, int d) { - final int[] vertexData = this.vertexData; - - final int ax0 = vertexData[a]; - final int ay0 = vertexData[a + 1]; - final int ax1 = vertexData[a + 2]; - final int ay1 = vertexData[a + 3]; - - final int bx0 = vertexData[b]; - final int by0 = vertexData[b + 1]; - final int bx1 = vertexData[b + 2]; - final int by1 = vertexData[b + 3]; - - final int cx0 = vertexData[c]; - final int cy0 = vertexData[c + 1]; - final int cx1 = vertexData[c + 2]; - final int cy1 = vertexData[c + 3]; - - final int dx0 = vertexData[d]; - final int dy0 = vertexData[d + 1]; - final int dx1 = vertexData[d + 2]; - final int dy1 = vertexData[d + 3]; - + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; final int[] eventData = this.eventData; final int y0 = eventY0; - // difference from left: is high index in pairs + // right events are the high index in each pair final int limit = eventLimit + 1; + final int ea = (a - IDX_AX0) >> 2; + final int eb = (b - IDX_AX0) >> 2; + final int ec = (c - IDX_AX0) >> 2; + final int ed = (d - IDX_AX0) >> 2; + final long aStep = edgeStep[ea]; + long ax = edgeX0[ea] + aStep * y0; + final long bStep = edgeStep[eb]; + long bx = edgeX0[eb] + bStep * y0; + final long cStep = edgeStep[ec]; + long cx = edgeX0[ec] + cStep * y0; + final long dStep = edgeStep[ed]; + long dx = edgeX0[ed] + dStep * y0; - final long aStep, bStep, cStep, dStep; - long ax, bx, cx, dx; - - if (ax0 == ax1) { - ax = ((ax0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - aStep = 0; - } else { - final long an = (((long) (ax1 - ax0)) << 16) / (ay1 - ay0); - aStep = an << PRECISION_BITS; - // difference from left: rounding looses tie - ax = ((long) ax0 << 16) - an * ay0 + aStep * y0 + 0x7FFFFL; - } - - if (bx0 == bx1) { - bx = ((bx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - bStep = 0; - } else { - final long bn = (((long) (bx1 - bx0)) << 16) / (by1 - by0); - bStep = bn << PRECISION_BITS; - // difference from left: rounding looses tie - bx = ((long) bx0 << 16) - bn * by0 + bStep * y0 + 0x7FFFFL; - } - - if (cx0 == cx1) { - cx = ((cx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - cStep = 0; - } else { - final long cn = (((long) (cx1 - cx0)) << 16) / (cy1 - cy0); - cStep = cn << PRECISION_BITS; - // difference from left: rounding looses tie - cx = ((long) cx0 << 16) - cn * cy0 + cStep * y0 + 0x7FFFFL; - } - - if (dx0 == dx1) { - dx = ((dx0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - dStep = 0; - } else { - final long dn = (((long) (dx1 - dx0)) << 16) / (dy1 - dy0); - dStep = dn << PRECISION_BITS; - // difference from left: rounding looses tie - dx = ((long) dx0 << 16) - dn * dy0 + dStep * y0 + 0x7FFFFL; - } - - // difference from left: is high index in pairs for (int y = (y0 << 1) + 1; y <= limit; y += 2) { - // difference from left: lower value wins final long i = ax < bx ? ax : bx; final long j = cx < dx ? cx : dx; eventData[y] = (int) ((i < j ? i : j) >> 20); - ax += aStep; bx += bStep; cx += cStep; @@ -1278,6 +1236,74 @@ public abstract class AbstractRasterizer { abstract void setupVertex(int baseIndex, int x, int y, int z); + /** + * True if the pixel under the given region-relative point is known to be clear. False when the point is + * covered, off screen, or too close to the camera to project, so callers must fall back to a full test. + */ + abstract boolean isPointClear(float x, float y, float z); + + /** + * Projects the listed corners of a region-relative box. Corner slots are laid out as V, so the + * slot index selects which extent each axis takes. Returns false if any listed corner needs near clipping. + */ + abstract boolean setupBoxVertices(int[] corners, int x0, int y0, int z0, int x1, int y1, int z1); + + /** Scratch clip-space coordinates of a box's eight corners, indexed by corner in slot order. */ + protected final float[] cornerX = new float[8], cornerY = new float[8], cornerZ = new float[8], cornerW = new float[8]; + + /** Fills the corner scratch arrays from one transformed corner and the three axis deltas. */ + final void transformBoxCorners(int x0, int y0, int z0, int x1, int y1, int z1) { + final float fx = x0 + offsetX; + final float fy = y0 + offsetY; + final float fz = z0 + offsetZ; + final float ex = x1 - x0; + final float ey = y1 - y0; + final float ez = z1 - z0; + + final float[] cx = cornerX, cy = cornerY, cz = cornerZ, cw = cornerW; + + // V000 + final float bx = m00 * fx + m01 * fy + m02 * fz + m03; + final float by = m10 * fx + m11 * fy + m12 * fz + m13; + final float bz = m20 * fx + m21 * fy + m22 * fz + m23; + final float bw = m30 * fx + m31 * fy + m32 * fz + m33; + + final float dxx = m00 * ex, dxy = m10 * ex, dxz = m20 * ex, dxw = m30 * ex; + final float dyx = m01 * ey, dyy = m11 * ey, dyz = m21 * ey, dyw = m31 * ey; + final float dzx = m02 * ez, dzy = m12 * ez, dzz = m22 * ez, dzw = m32 * ez; + + cx[0] = bx; cy[0] = by; cz[0] = bz; cw[0] = bw; + cx[1] = bx + dzx; cy[1] = by + dzy; cz[1] = bz + dzz; cw[1] = bw + dzw; + cx[2] = bx + dyx; cy[2] = by + dyy; cz[2] = bz + dyz; cw[2] = bw + dyw; + cx[3] = cx[2] + dzx; cy[3] = cy[2] + dzy; cz[3] = cz[2] + dzz; cw[3] = cw[2] + dzw; + cx[4] = bx + dxx; cy[4] = by + dxy; cz[4] = bz + dxz; cw[4] = bw + dxw; + cx[5] = cx[4] + dzx; cy[5] = cy[4] + dzy; cz[5] = cz[4] + dzz; cw[5] = cw[4] + dzw; + cx[6] = cx[4] + dyx; cy[6] = cy[4] + dyy; cz[6] = cz[4] + dyz; cw[6] = cw[4] + dyw; + cx[7] = cx[6] + dzx; cy[7] = cy[6] + dzy; cz[7] = cz[6] + dzz; cw[7] = cw[6] + dzw; + } + + /** Shared tail of {@link #isPointClear}: normalized device position to pixel to tile bit. */ + final boolean isProjectedPointClear(float tx, float ty, float iw) { + final float sx = tx * iw; + final float sy = ty * iw; + + // NaN fails these too; the integer checks below catch the float rounding of (s + 1) up to exactly 2 + if (!(sx >= -1f && sx < 1f && sy >= -1f && sy < 1f)) { + return false; + } + + final int px = (int) ((sx + 1f) * halfPixelWidth); + final int py = (int) ((sy + 1f) * halfPixelHeight); + + if (px >= pixelWidth || py >= pixelHeight) { + return false; + } + + final int tileIndex = (px >> TILE_AXIS_SHIFT) | ((py >> TILE_AXIS_SHIFT) << tileWidthBits); + + return (tiles[tileIndex] & (1L << (((py & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (px & TILE_PIXEL_INDEX_MASK)))) == 0; + } + int needsNearClip(final int baseIndex) { final int[] data = vertexData; final float w = Float.intBitsToFloat(data[baseIndex + PV_W]); @@ -1295,11 +1321,11 @@ public abstract class AbstractRasterizer { long computeTileCoverage(int tileIndex) { final int[] data = eventData; - final int tileFirstX = (tileIndex & TILE_WIDTH_MASK) << TILE_AXIS_SHIFT; + final int tileFirstX = (tileIndex & tileWidthMask) << TILE_AXIS_SHIFT; final int tileLastX = tileFirstX + 7; // +1 to left shift because events are in pairs - final int baseEventIndex = (tileIndex >> TILE_WIDTH_BITS) << (TILE_AXIS_SHIFT + 1); + final int baseEventIndex = (tileIndex >> tileWidthBits) << (TILE_AXIS_SHIFT + 1); long mask = 0; // shift left or right, > 7 means no coverage int l, r; @@ -1355,15 +1381,15 @@ public abstract class AbstractRasterizer { } public boolean isPixelClear(int x, int y) { - return (tiles[Indexer.tileIndexFromPixelXY(x, y)] & (1L << (Indexer.pixelIndex(x, y)))) == 0; + return (tiles[tileIndexFromPixelXY(x, y)] & (1L << (Indexer.pixelIndex(x, y)))) == 0; } public boolean isPixelSet(int x, int y) { - return (tiles[Indexer.tileIndexFromPixelXY(x, y)] & (1L << (Indexer.pixelIndex(x, y)))) != 0; + return (tiles[tileIndexFromPixelXY(x, y)] & (1L << (Indexer.pixelIndex(x, y)))) != 0; } void drawPixel(int x, int y) { - tiles[Indexer.tileIndexFromPixelXY(x, y)] |= (1L << (Indexer.pixelIndex(x, y))); + tiles[tileIndexFromPixelXY(x, y)] |= (1L << (Indexer.pixelIndex(x, y))); } @FunctionalInterface @@ -1451,11 +1477,11 @@ public abstract class AbstractRasterizer { maxY = dy0; } - if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + if (maxY <= 0 || minY >= preciseHeight) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } - if (maxX <= 0 || minX >= PRECISE_WIDTH) { + if (maxX <= 0 || minX >= preciseWidth) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } @@ -1463,11 +1489,11 @@ public abstract class AbstractRasterizer { minX = 0; } - if (maxX >= PRECISE_WIDTH_CLAMP) { - maxX = PRECISE_WIDTH_CLAMP; + if (maxX >= preciseWidthClamp) { + maxX = preciseWidthClamp; - if (minX > PRECISE_WIDTH_CLAMP) { - minX = PRECISE_WIDTH_CLAMP; + if (minX > preciseWidthClamp) { + minX = preciseWidthClamp; } } @@ -1475,11 +1501,11 @@ public abstract class AbstractRasterizer { minY = 0; } - if (maxY >= PRECISE_HEIGHT_CLAMP) { - maxY = PRECISE_HEIGHT_CLAMP; + if (maxY >= preciseHeightClamp) { + maxY = preciseHeightClamp; - if (minY > PRECISE_HEIGHT_CLAMP) { - minY = PRECISE_HEIGHT_CLAMP; + if (minY > preciseHeightClamp) { + minY = preciseHeightClamp; } } @@ -1528,8 +1554,276 @@ public abstract class AbstractRasterizer { } void prepareEvents(int eventKey) { - eventY0 = minPixelY & TILE_AXIS_MASK; - eventLimit = (((maxPixelY & TILE_AXIS_MASK) + 7) << 1); - EVENT_FILLERS[eventKey].apply(); + this.eventKey = eventKey; + this.edgesReady = false; + this.genericEvents = false; + } + + /** Prepares an unclipped convex polygon of 3..6 projected vertices with consistent winding. */ + final int preparePolygonNoClip(int[] vertices, int count) { + final int[] data = vertexData; + + int minX = data[vertices[0] + PV_PX]; + int maxX = minX; + int minY = data[vertices[0] + PV_PY]; + int maxY = minY; + + for (int i = 1; i < count; i++) { + final int x = data[vertices[i] + PV_PX]; + final int y = data[vertices[i] + PV_PY]; + if (x < minX) minX = x; else if (x > maxX) maxX = x; + if (y < minY) minY = y; else if (y > maxY) maxY = y; + } + + if (maxY <= 0 || minY >= preciseHeight || maxX <= 0 || minX >= preciseWidth) { + return BOUNDS_OUTSIDE_OR_TOO_SMALL; + } + + if (minX < 0) minX = 0; + + if (maxX >= preciseWidthClamp) { + maxX = preciseWidthClamp; + if (minX > preciseWidthClamp) minX = preciseWidthClamp; + } + + if (minY < 0) minY = 0; + + if (maxY >= preciseHeightClamp) { + maxY = preciseHeightClamp; + if (minY > preciseHeightClamp) minY = preciseHeightClamp; + } + + minPixelX = (minX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + minPixelY = (minY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + maxPixelX = (maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + maxPixelY = (maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + + int leftCount = 0, rightCount = 0, flatCount = 0; + int x0 = data[vertices[0] + PV_PX]; + int y0 = data[vertices[0] + PV_PY]; + + for (int e = 0; e < count; e++) { + final int next = vertices[e + 1 == count ? 0 : e + 1]; + final int x1 = data[next + PV_PX]; + final int y1 = data[next + PV_PY]; + final int slot = EDGE_SLOTS[e]; + data[slot] = x0; + data[slot + 1] = y0; + data[slot + 2] = x1; + data[slot + 3] = y1; + + final int position = edgePosition(x0, y0, x1, y1); + + if ((position & A_ZERO) != 0) { + flatPositions[flatCount] = position; + flatSlots[flatCount++] = slot; + } else if ((position & A_POSITIVE) != 0) { + leftEdges[leftCount++] = e; + } else { + rightEdges[rightCount++] = e; + } + + x0 = x1; + y0 = y1; + } + + this.leftCount = leftCount; + this.rightCount = rightCount; + this.flatCount = flatCount; + this.genericEvents = true; + this.edgesReady = false; + return BOUNDS_IN; + } + + final void drawPolygon(int[] vertices, int count) { + if (STATS) STAT_DRAW_CALLS++; + dilate = false; + + if (preparePolygonNoClip(vertices, count) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { + return; + } + + if (STATS) STAT_DRAW_QUADS++; + + // Don't draw single points + if (minPixelX == maxPixelX && minPixelY == maxPixelY) { + return; + } + + drawQuad(); + } + + final boolean isPolygonPartiallyClear(int[] vertices, int count) { + if (STATS) STAT_TEST_CALLS++; + dilate = true; + + if (preparePolygonNoClip(vertices, count) == BOUNDS_OUTSIDE_OR_TOO_SMALL) { + return false; + } + + if (STATS) STAT_TEST_QUADS++; + + dilateBounds(); + return isQuadPartiallyClear(); + } + + /** 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() { + final int eventKey = this.eventKey; + final int[] data = vertexData; + final long[] edgeX0 = this.edgeX0; + final long[] edgeStep = this.edgeStep; + + for (int e = 0; e < 4; e++) { + final int role = (eventKey >> (e << 1)) & EVENT_POSITION_MASK; + + if (role == EVENT_0_FLAT) { + continue; + } + + final int i = IDX_AX0 + (e << 2); + final int x0 = data[i]; + final int y0 = data[i + 1]; + final int dx = data[i + 2] - x0; + + if (dx == 0) { + edgeStep[e] = 0; + edgeX0[e] = (long) ((x0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + } else { + // 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)); + edgeStep[e] = n << PRECISION_BITS; + // left edges round up; right edges lose the tie + edgeX0[e] = ((long) x0 << 16) - n * y0 + (role == EVENT_0_LEFT ? 0x100000L : 0x7FFFFL); + } + } + } + + private void prepareEdgesGeneric() { + // a convex hexagon has at most three edges per side; unused slots never win the max/min + for (int i = 0; i < 3; i++) { + if (i < leftCount) { + prepareEdge(leftEdges[i], 0x100000L, leftX0, leftStep, i); + } else { + leftX0[i] = Long.MIN_VALUE; + leftStep[i] = 0; + } + + if (i < rightCount) { + prepareEdge(rightEdges[i], 0x7FFFFL, rightX0, rightStep, i); + } else { + rightX0[i] = Long.MAX_VALUE; + rightStep[i] = 0; + } + } + } + + private void prepareEdge(int e, long rounding, long[] x0Out, long[] stepOut, int slotOut) { + final int[] data = vertexData; + final int i = EDGE_SLOTS[e]; + final int x0 = data[i]; + final int y0 = data[i + 1]; + final int dx = data[i + 2] - x0; + + if (dx == 0) { + stepOut[slotOut] = 0; + x0Out[slotOut] = (long) ((x0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + } else { + final long n = (long) ((double) (((long) dx) << 16) / (data[i + 3] - y0)); + stepOut[slotOut] = n << PRECISION_BITS; + x0Out[slotOut] = ((long) x0 << 16) - n * y0 + rounding; + } + } + + /** Band filler for polygons set up by {@link #preparePolygonNoClip}. */ + private void populateBandGeneric(int y0) { + final int[] eventData = this.eventData; + final long[] leftX0 = this.leftX0; + final long[] leftStep = this.leftStep; + final long[] rightX0 = this.rightX0; + final long[] rightStep = this.rightStep; + + final long la = leftStep[0], lb = leftStep[1], lc = leftStep[2]; + final long ra = rightStep[0], rb = rightStep[1], rc = rightStep[2]; + long lax = leftX0[0] + la * y0, lbx = leftX0[1] + lb * y0, lcx = leftX0[2] + lc * y0; + long rax = rightX0[0] + ra * y0, rbx = rightX0[1] + rb * y0, rcx = rightX0[2] + rc * y0; + final boolean noLeft = leftCount == 0; + final boolean noRight = rightCount == 0; + + for (int y = y0 << 1, limit = (y0 + 7) << 1; y <= limit; y += 2) { + final long l = lax > lbx ? lax : lbx; + final long left = lcx > l ? lcx : l; + final long r = rax < rbx ? rax : rbx; + final long right = rcx < r ? rcx : r; + + eventData[y] = noLeft ? 0 : (int) (left >> 20); + eventData[y + 1] = noRight ? pixelWidth : (int) (right >> 20); + + lax += la; + lbx += lb; + lcx += lc; + rax += ra; + rbx += rb; + rcx += rc; + } + + for (int i = 0; i < flatCount; i++) { + populateFlatEvents(flatPositions[i], flatSlots[i]); + } + } + + final void populateBand(int tileY) { + final boolean generic = this.genericEvents; + + if (!edgesReady) { + if (generic) { + prepareEdgesGeneric(); + } else { + prepareEdges(); + } + + edgesReady = true; + } + + final int y0 = tileY << TILE_AXIS_SHIFT; + eventY0 = y0; + eventLimit = (y0 + 7) << 1; + if (STATS) STAT_EVENT_ROWS += 8; + + if (generic) { + populateBandGeneric(y0); + } else { + EVENT_FILLERS[eventKey].apply(); + } + + if (dilate) { + final int[] events = eventData; + + for (int y = y0 << 1, limit = (y0 + 7) << 1; y <= limit; y += 2) { + final int l = events[y]; + final int r = events[y + 1]; + + if (l <= r) { + events[y] = l - TEST_DILATION_PIXELS; + events[y + 1] = r + TEST_DILATION_PIXELS; + } + } + } + + // tiles between the widest left event and the narrowest right event are covered on every row + final int[] data = eventData; + final int base = y0 << 1; + int maxLeft = data[base]; + int minRight = data[base + 1]; + + for (int i = base + 2; i < base + 16; i += 2) { + final int l = data[i]; + final int r = data[i + 1]; + if (l > maxLeft) maxLeft = l; + if (r < minRight) minRight = r; + } + + bandInnerFirst = (maxLeft + 7) >> TILE_AXIS_SHIFT; + bandInnerLast = (minRight - 7) >> TILE_AXIS_SHIFT; } } diff --git a/common/src/main/java/grondag/bitraster/BoxOccluder.java b/common/src/main/java/grondag/bitraster/BoxOccluder.java index d35f616fa..bb5d2f61d 100644 --- a/common/src/main/java/grondag/bitraster/BoxOccluder.java +++ b/common/src/main/java/grondag/bitraster/BoxOccluder.java @@ -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.DOWN; import static grondag.bitraster.Constants.EAST; -import static grondag.bitraster.Constants.EMPTY_BITS; 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.TILE_COUNT; import static grondag.bitraster.Constants.UP; import static grondag.bitraster.Constants.V000; import static grondag.bitraster.Constants.V001; @@ -65,6 +64,43 @@ public abstract class BoxOccluder { private boolean hasNearOccluders = false; 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) { this.raster = raster; @@ -944,6 +980,28 @@ public abstract class BoxOccluder { 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. */ @@ -960,9 +1018,7 @@ public abstract class BoxOccluder { offsetY = (int) ((originY << CAMERA_PRECISION_BITS) - viewY); offsetZ = (int) ((originZ << CAMERA_PRECISION_BITS) - viewZ); - final Matrix4L mvpMatrix = raster.mvpMatrix; - mvpMatrix.copyFrom(baseMvpMatrix); - mvpMatrix.translate(offsetX, offsetY, offsetZ, CAMERA_PRECISION_BITS); + raster.setRegionOffset(offsetX, offsetY, offsetZ); } /** @@ -985,11 +1041,13 @@ public abstract class BoxOccluder { viewX = Math.round(cameraX * CAMERA_PRECISION_UNITY); viewY = Math.round(cameraY * CAMERA_PRECISION_UNITY); viewZ = Math.round(cameraZ * CAMERA_PRECISION_UNITY); + + raster.setMatrix(baseMvpMatrix); } if (forceRedraw || this.viewVersion != viewVersion) { this.viewVersion = viewVersion; - System.arraycopy(EMPTY_BITS, 0, raster.tiles, 0, TILE_COUNT); + raster.clear(); forceRedraw = false; hasNearOccluders = false; 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 //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); } + /** + * 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) { prepareRegion(originX, originY, originZ, 0, 0); return isBoxVisible(PackedBox.FULL_BOX, fuzz); @@ -1158,9 +1232,14 @@ public abstract class BoxOccluder { } } - //timer.start(); - boxDraws[outcome].apply(x0, y0, z0, x1, y1, z1); - //timer.stop(false); + final int[] silhouette = SILHOUETTES[outcome]; + + 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) { @@ -1178,6 +1257,14 @@ public abstract class BoxOccluder { } 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); } diff --git a/common/src/main/java/grondag/bitraster/Constants.java b/common/src/main/java/grondag/bitraster/Constants.java index 551910d08..282544a93 100644 --- a/common/src/main/java/grondag/bitraster/Constants.java +++ b/common/src/main/java/grondag/bitraster/Constants.java @@ -34,44 +34,17 @@ public class Constants { static final int PRECISE_PIXEL_SIZE = 1 << PRECISION_BITS; static final int PRECISE_PIXEL_CENTER = PRECISE_PIXEL_SIZE / 2; 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 - static final int TILE_WIDTH_BITS = 7; - static final int TILE_WIDTH = 1 << TILE_WIDTH_BITS; - static final int TILE_WIDTH_MASK = TILE_WIDTH - 1; - public static final int PIXEL_WIDTH = TILE_WIDTH * TILE_PIXEL_DIAMETER; - static final int MAX_PIXEL_X = PIXEL_WIDTH - 1; - 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: the buffer size is chosen per rasterizer and per axis (see AbstractRasterizer.resize); upstream + // fixed it at 2048px square. + /** Occlusion buffer size along one axis in tiles, as a power of two: 6 = 512 px, 7 = 1024 px, 8 = 2048 px. */ + public static final int MIN_SIZE_BITS = 6; + public static final int DEFAULT_SIZE_BITS = 7; + public static final int MAX_SIZE_BITS = 8; - /** - * clamp to this to ensure value + half pixel rounds down to last pixel. - */ - 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; + // CELERITAS: pixels added on every side of a tested polygon so that a visible strip narrower than the 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; - /** - * 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; static final int CAMERA_PRECISION_UNITY = 1 << CAMERA_PRECISION_BITS; 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_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; } diff --git a/common/src/main/java/grondag/bitraster/Indexer.java b/common/src/main/java/grondag/bitraster/Indexer.java index 86c6096f9..bc2eac92e 100644 --- a/common/src/main/java/grondag/bitraster/Indexer.java +++ b/common/src/main/java/grondag/bitraster/Indexer.java @@ -18,7 +18,6 @@ package grondag.bitraster; import static grondag.bitraster.Constants.TILE_AXIS_SHIFT; import static grondag.bitraster.Constants.TILE_PIXEL_INDEX_MASK; -import static grondag.bitraster.Constants.TILE_WIDTH_BITS; abstract class Indexer { private Indexer() { @@ -31,13 +30,7 @@ abstract class Indexer { 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) { return ((y & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (x & TILE_PIXEL_INDEX_MASK); diff --git a/common/src/main/java/grondag/bitraster/OrthoRasterizer.java b/common/src/main/java/grondag/bitraster/OrthoRasterizer.java index 569daa5df..f50959e7f 100644 --- a/common/src/main/java/grondag/bitraster/OrthoRasterizer.java +++ b/common/src/main/java/grondag/bitraster/OrthoRasterizer.java @@ -16,31 +16,75 @@ package grondag.bitraster; -import static grondag.bitraster.Constants.HALF_PRECISE_HEIGHT; -import static grondag.bitraster.Constants.HALF_PRECISE_WIDTH; +import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE; +import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS; import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PY; import static grondag.bitraster.Constants.PV_X; import static grondag.bitraster.Constants.PV_Y; 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 int prepareBounds(int v0, int v1, int v2, int 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) { final int[] data = vertexData; - final Matrix4L mvpMatrix = this.mvpMatrix; - final float tx = mvpMatrix.transformVec4X(x, y, z) * Matrix4L.FLOAT_CONVERSION; - final float ty = mvpMatrix.transformVec4Y(x, y, z) * Matrix4L.FLOAT_CONVERSION; + 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; data[baseIndex + PV_X] = Float.floatToRawIntBits(tx); data[baseIndex + PV_Y] = Float.floatToRawIntBits(ty); - final int px = Math.round(tx * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; - final int py = Math.round(ty * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; + final int px = Math.round(tx * halfPreciseWidth) + halfPreciseWidth; + final int py = Math.round(ty * halfPreciseHeight) + halfPreciseHeight; data[baseIndex + PV_PX] = px; data[baseIndex + PV_PY] = py; diff --git a/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java b/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java index 5d839112b..fba162c35 100644 --- a/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java +++ b/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java @@ -16,11 +16,10 @@ package grondag.bitraster; +import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS; import static grondag.bitraster.Constants.BOUNDS_IN; import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; 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_AX1; 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_DY0; 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.PROJECTED_VERTEX_STRIDE; import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PY; 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; 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)}. */ private int clipX, clipY; @Override void setupVertex(final int baseIndex, final int x, final int y, final int z) { final int[] data = vertexData; - final Matrix4L mvpMatrix = this.mvpMatrix; - final float tx = mvpMatrix.transformVec4X(x, y, z) * Matrix4L.FLOAT_CONVERSION; - final float ty = mvpMatrix.transformVec4Y(x, y, z) * Matrix4L.FLOAT_CONVERSION; - final float w = mvpMatrix.transformVec4W(x, y, z) * Matrix4L.FLOAT_CONVERSION; + 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; + 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_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); if (w != 0) { final float iw = 1f / w; - final int px = Math.round(tx * iw * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; - final int py = Math.round(ty * iw * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; + final int px = Math.round(tx * iw * halfPreciseWidth) + halfPreciseWidth; + final int py = Math.round(ty * iw * halfPreciseHeight) + halfPreciseHeight; data[baseIndex + PV_PX] = px; 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) { final int[] data = vertexData; @@ -102,8 +162,8 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { final float w = (intW + (extW - intW) * wt); final float iw = 1f / w; - clipX = Math.round(iw * x * HALF_PRECISE_WIDTH) + HALF_PRECISE_WIDTH; - clipY = Math.round(iw * y * HALF_PRECISE_HEIGHT) + HALF_PRECISE_HEIGHT; + clipX = Math.round(iw * x * halfPreciseWidth) + halfPreciseWidth; + clipY = Math.round(iw * y * halfPreciseHeight) + halfPreciseHeight; } @Override @@ -230,11 +290,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { maxY = dy0; } - if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + if (maxY <= 0 || minY >= preciseHeight) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } - if (maxX <= 0 || minX >= PRECISE_WIDTH) { + if (maxX <= 0 || minX >= preciseWidth) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } @@ -242,11 +302,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minX = 0; } - if (maxX >= PRECISE_WIDTH_CLAMP) { - maxX = PRECISE_WIDTH_CLAMP; + if (maxX >= preciseWidthClamp) { + maxX = preciseWidthClamp; - if (minX > PRECISE_WIDTH_CLAMP) { - minX = PRECISE_WIDTH_CLAMP; + if (minX > preciseWidthClamp) { + minX = preciseWidthClamp; } } @@ -254,11 +314,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minY = 0; } - if (maxY >= PRECISE_HEIGHT_CLAMP) { - maxY = PRECISE_HEIGHT_CLAMP; + if (maxY >= preciseHeightClamp) { + maxY = preciseHeightClamp; - if (minY > PRECISE_HEIGHT_CLAMP) { - minY = PRECISE_HEIGHT_CLAMP; + if (minY > preciseHeightClamp) { + minY = preciseHeightClamp; } } @@ -391,11 +451,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { maxY = dy0; } - if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + if (maxY <= 0 || minY >= preciseHeight) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } - if (maxX <= 0 || minX >= PRECISE_WIDTH) { + if (maxX <= 0 || minX >= preciseWidth) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } @@ -403,11 +463,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minX = 0; } - if (maxX >= PRECISE_WIDTH_CLAMP) { - maxX = PRECISE_WIDTH_CLAMP; + if (maxX >= preciseWidthClamp) { + maxX = preciseWidthClamp; - if (minX > PRECISE_WIDTH_CLAMP) { - minX = PRECISE_WIDTH_CLAMP; + if (minX > preciseWidthClamp) { + minX = preciseWidthClamp; } } @@ -415,11 +475,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minY = 0; } - if (maxY >= PRECISE_HEIGHT_CLAMP) { - maxY = PRECISE_HEIGHT_CLAMP; + if (maxY >= preciseHeightClamp) { + maxY = preciseHeightClamp; - if (minY > PRECISE_HEIGHT_CLAMP) { - minY = PRECISE_HEIGHT_CLAMP; + if (minY > preciseHeightClamp) { + minY = preciseHeightClamp; } } @@ -541,11 +601,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { maxY = dy0; } - if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + if (maxY <= 0 || minY >= preciseHeight) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } - if (maxX <= 0 || minX >= PRECISE_WIDTH) { + if (maxX <= 0 || minX >= preciseWidth) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } @@ -553,11 +613,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minX = 0; } - if (maxX >= PRECISE_WIDTH_CLAMP) { - maxX = PRECISE_WIDTH_CLAMP; + if (maxX >= preciseWidthClamp) { + maxX = preciseWidthClamp; - if (minX > PRECISE_WIDTH_CLAMP) { - minX = PRECISE_WIDTH_CLAMP; + if (minX > preciseWidthClamp) { + minX = preciseWidthClamp; } } @@ -565,11 +625,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minY = 0; } - if (maxY >= PRECISE_HEIGHT_CLAMP) { - maxY = PRECISE_HEIGHT_CLAMP; + if (maxY >= preciseHeightClamp) { + maxY = preciseHeightClamp; - if (minY > PRECISE_HEIGHT_CLAMP) { - minY = PRECISE_HEIGHT_CLAMP; + if (minY > preciseHeightClamp) { + minY = preciseHeightClamp; } } @@ -677,11 +737,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { maxY = dy0; } - if (maxY <= 0 || minY >= PRECISE_HEIGHT) { + if (maxY <= 0 || minY >= preciseHeight) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } - if (maxX <= 0 || minX >= PRECISE_WIDTH) { + if (maxX <= 0 || minX >= preciseWidth) { return BOUNDS_OUTSIDE_OR_TOO_SMALL; } @@ -689,11 +749,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minX = 0; } - if (maxX >= PRECISE_WIDTH_CLAMP) { - maxX = PRECISE_WIDTH_CLAMP; + if (maxX >= preciseWidthClamp) { + maxX = preciseWidthClamp; - if (minX > PRECISE_WIDTH_CLAMP) { - minX = PRECISE_WIDTH_CLAMP; + if (minX > preciseWidthClamp) { + minX = preciseWidthClamp; } } @@ -701,11 +761,11 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { minY = 0; } - if (maxY >= PRECISE_HEIGHT_CLAMP) { - maxY = PRECISE_HEIGHT_CLAMP; + if (maxY >= preciseHeightClamp) { + maxY = preciseHeightClamp; - if (minY > PRECISE_HEIGHT_CLAMP) { - minY = PRECISE_HEIGHT_CLAMP; + if (minY > preciseHeightClamp) { + minY = preciseHeightClamp; } } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java index ab6cdcafa..163fd4a14 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java @@ -192,7 +192,7 @@ public class OcclusionCuller { this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null; if (this.rasterActive) { - this.rasterOccluder.prepareScene(frame, viewport); + this.rasterOccluder.prepareScene(frame, viewport, searchDistance); } this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame); @@ -365,9 +365,7 @@ public class OcclusionCuller { boolean hasGeometry = (PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0; - var section = this.lattice.latticeSection[idx]; - var built = section != null ? section.getBuiltContext() : null; - int[] data = built != null ? built.occluderBoxes : null; + int[] data = this.lattice.occluderData[idx]; 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); if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && data != null) { - occluder.occlude(data); + occluder.occludeSection(data); } 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() { return this.rasterOccluder == null ? 0 : this.rasterOccluder.backtrackCount(); } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java index 6f11e6324..ec65940fc 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java @@ -1,6 +1,8 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion; +import grondag.bitraster.AbstractRasterizer; import grondag.bitraster.BoxOccluder; +import grondag.bitraster.Constants; import grondag.bitraster.Matrix4L; import grondag.bitraster.PackedBox; 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 */ 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; + /** 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 { /** nothing of the section is visible, and nothing behind it can be reached through it */ 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; * {@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(); if (vpMatrix == null) { @@ -56,17 +59,111 @@ public final class RasterOccluder extends BoxOccluder { this.backtrackCount = 0; + chooseBufferSize(vpMatrix, searchDistance); invalidate(); prepareScene(viewVersion, transform.x, transform.y, transform.z, 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. + * + *

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 * may still have unoccluded empty space, so a second test decides whether traversal continues. * must run before occlude(), or a section would occlude itself. */ 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, PackedBox.rangeFromSquareChunkDist(squaredChunkDist), squaredChunkDist); @@ -74,9 +171,13 @@ public final class RasterOccluder extends BoxOccluder { 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; } @@ -85,7 +186,7 @@ public final class RasterOccluder extends BoxOccluder { } // 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; } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index 0423a7954..8c9f08dfe 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -137,6 +137,12 @@ public final class SectionLattice { long[] shadowVisitState; long[] sectionMeta; 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; // 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]; this.sectionMeta[idx] = packedMetadata; + this.occluderData[idx] = occluderDataOf(this.latticeSection[idx]); return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; } @@ -463,6 +470,10 @@ public final class SectionLattice { return this.snapshot(this.visitState, this.mainSnapshotBuffers); } + public String rasterBufferSize() { + return this.culler.rasterBufferSize(); + } + public int rasterBacktrackCount() { return this.culler.rasterBacktrackCount(); } @@ -535,6 +546,7 @@ public final class SectionLattice { this.sectionMeta = new long[slots]; this.regionOfCell = new int[slots]; this.latticeSection = new RenderSection[slots]; + this.occluderData = new int[slots][]; // Existing coordinates are no longer valid after resizing; the next // 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.regionOfCell, -1); Arrays.fill(this.latticeSection, null); + Arrays.fill(this.occluderData, null); this.baseX = newBaseX; this.baseZ = newBaseZ; @@ -632,6 +645,7 @@ public final class SectionLattice { System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len); System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, 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.regionOfCell, srcOff, this.regionOfCell, 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.regionOfCell[idx] = -1; this.latticeSection[idx] = null; + this.occluderData[idx] = null; RenderSection section = this.sections.get( 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 // 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) { if (this.visitState == null) { return; @@ -815,6 +836,7 @@ public final class SectionLattice { this.latticeSection[idx] = section; this.regionOfCell[idx] = section.getRegion().getId(); this.sectionMeta[idx] = section.getPackedMetadata(); + this.occluderData[idx] = occluderDataOf(section); this.installedCount++; } @@ -834,6 +856,7 @@ public final class SectionLattice { this.sectionMeta[idx] = VisibilityEncoding.NULL; this.regionOfCell[idx] = -1; this.latticeSection[idx] = null; + this.occluderData[idx] = null; this.installedCount--; } } -- 2.54.1 From 254659b5ecf30e0d9ebb07688ed4052f7ba6746b Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Thu, 3 Sep 2026 13:44:41 -0400 Subject: [PATCH 12/20] cut raster occlusion overhead by a third at 32 chunks and over half at 64 Per-frame cost of the rasterized culler (JMH rotatingCamera, SURFACE, two forks) drops from 1.42ms to 1.09ms at render distance 32 and from 4.62ms to 3.09ms at 64, against 0.48ms / 1.86ms with the raster off. Culled section counts match the previous commit within a few sections per placement at 32 and within 0.4% at 64; CAVES is unchanged. Culler integration: - Whole regions are settled at once where possible. The rasterizer keeps a coarse map of 64px cells that have been drawn into, with a version that changes when a cell is first touched. Each region's screen rectangle is projected once per scene; while its cells are untouched, an air section in it is visible with one compare, since its centre pixel must be clear. A region straddling a screen edge keeps the clip-space position of its first section centre, from which any section centre's on-screen check is a few multiplies with no divide. Resolves 4.6k of 11k tests at 32 and 30k of 51k at 64. Exactly equivalent to the centre test it replaces. - The lattice's metadata word carries a "has occluder data" bit and the bounds word is mirrored densely, so air sections skip the pointer load and terrain sections skip a second dependent cache miss. Rasterizer (grondag.bitraster): - Buffer axes are any multiple of eight tiles, not powers of two: rows are addressed by multiplication, so the buffer at 32 chunks is 1280x832 instead of 2048x1024 and at 64 it is 2048x1472 instead of 2048x2048. Hysteresis is one 64px step, so a wavering field of view neither grows nor shrinks it. - Projected silhouette vertices are sampled before any polygon setup; a clear pixel under one proves visibility. Cuts polygon tests from 2.4k to 750 per frame at 32. - Edges are prepared lazily and as left/right chains walked per band, with only the edge active on each row evaluated. This handles any chain length, where the previous max-of-three silently dropped a fourth edge produced by the rounding of a nearly flat one, and drops edges that contain no row centre instead of extrapolating them. - Band population is a single pass that derives row spans from the polygon's row range, replacing the flat-event, dilation and range passes. - Draws bulk-fill runs of interior tiles and clip each band's scan to the polygon's actual extent; tile coverage is computed without branches. - A small polygon whose bounding rectangle is fully covered at the pixel level is hidden before any edge setup; catches 29% of hidden tests at 64. - Vertex setup no longer stores clip-space coordinates the unclipped path never reads, and rounds through the floor intrinsic. - Region offsets no longer overflow int beyond 524k blocks. Measured and left alone: halving the pixels-per-block requirement gains only 8% at 32 and nothing at 64 now that per-polygon setup rather than tile work dominates, so the buffer size policy stands; skipping the near-camera box draws gains 3-5% but visibly weakens cave culling. The report tasks accept -Dreport.renderDistance and the stats report counts region skips, vertex hits and rectangle-hidden tests. --- common/build.gradle | 3 + .../occlusion/bench/RasterStatsReport.java | 14 +- .../grondag/bitraster/AbstractRasterizer.java | 795 +++++++++++++----- .../java/grondag/bitraster/BoxOccluder.java | 55 +- .../java/grondag/bitraster/Constants.java | 13 +- .../grondag/bitraster/OrthoRasterizer.java | 8 +- .../bitraster/PerspectiveRasterizer.java | 46 +- .../render/chunk/PackedSectionMetadata.java | 1 + .../chunk/occlusion/OcclusionCuller.java | 38 +- .../chunk/occlusion/RasterOccluder.java | 155 +++- .../chunk/occlusion/SectionLattice.java | 39 +- 11 files changed, 861 insertions(+), 306 deletions(-) diff --git a/common/build.gradle b/common/build.gradle index b72a5845d..2ea6fe8a0 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -160,6 +160,8 @@ tasks.register('rasterCullReport', JavaExec) { mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterCullReport' maxHeapSize = '1g' + // e.g. ./gradlew :common:rasterCullReport -Dreport.renderDistance=64 + systemProperties System.getProperties().findAll { it.key.toString().startsWith('report.') } } publishing { @@ -246,5 +248,6 @@ tasks.register('rasterStats', JavaExec) { mainClass = 'org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.RasterStatsReport' maxHeapSize = '1g' jvmArgs '-Dbitraster.stats=true' + systemProperties System.getProperties().findAll { it.key.toString().startsWith('report.') } doFirst { if (project.hasProperty('statargs')) args(project.property('statargs').toString().split('\\s+').findAll { !it.isEmpty() }) } } diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java index 0b285278e..b2d231bb3 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/RasterStatsReport.java @@ -12,7 +12,7 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport; * {@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 RENDER_DISTANCE = Integer.getInteger("report.renderDistance", 32); private static final int YAW_STEPS = 8; private static final int WARM = 150; @@ -71,8 +71,8 @@ public final class RasterStatsReport { 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("sections tested=%d occluded=%d regionSkip=%d vertexHit=%d%n", RasterOccluder.STAT_SECTIONS / n, + RasterOccluder.STAT_OCCLUDED_SECTIONS / n, RasterOccluder.STAT_REGION_SKIP / n, AbstractRasterizer.STAT_T_VERTEX / 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, @@ -84,16 +84,16 @@ public final class RasterStatsReport { } 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", + System.out.printf("centerHit=%d near=%d fullbox tests=%d fullbox visible=%d | test: empty=%d inner=%d cover=%d hidden=%d boxHidden=%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_T_EMPTY / n, AbstractRasterizer.STAT_T_INNER / n, AbstractRasterizer.STAT_T_COVER / n, AbstractRasterizer.STAT_T_HIDDEN / n, AbstractRasterizer.STAT_T_BOX_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; + RasterOccluder.STAT_CENTER_HIT = RasterOccluder.STAT_NEAR = RasterOccluder.STAT_AIR_TESTS = RasterOccluder.STAT_AIR_VISIBLE = RasterOccluder.STAT_REGION_SKIP = AbstractRasterizer.STAT_T_VERTEX = 0; + AbstractRasterizer.STAT_T_EMPTY = AbstractRasterizer.STAT_T_INNER = AbstractRasterizer.STAT_T_COVER = AbstractRasterizer.STAT_T_HIDDEN = AbstractRasterizer.STAT_T_BOX_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; diff --git a/common/src/main/java/grondag/bitraster/AbstractRasterizer.java b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java index 8f940f239..f543c157a 100644 --- a/common/src/main/java/grondag/bitraster/AbstractRasterizer.java +++ b/common/src/main/java/grondag/bitraster/AbstractRasterizer.java @@ -18,8 +18,8 @@ package grondag.bitraster; import java.util.Arrays; -import static grondag.bitraster.Constants.MIN_SIZE_BITS; -import static grondag.bitraster.Constants.MAX_SIZE_BITS; +import static grondag.bitraster.Constants.MIN_SIZE_TILES; +import static grondag.bitraster.Constants.MAX_SIZE_TILES; import static grondag.bitraster.Constants.PRECISE_PIXEL_CENTER; import static grondag.bitraster.Constants.BOUNDS_IN; import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; @@ -130,8 +130,6 @@ import static grondag.bitraster.Constants.EVENT_0_LEFT; import static grondag.bitraster.Constants.TILE_PIXEL_INDEX_MASK; import static grondag.bitraster.Constants.A_ZERO; import static grondag.bitraster.Constants.A_POSITIVE; -import static grondag.bitraster.Constants.IDX_EX0; -import static grondag.bitraster.Constants.IDX_FX0; import static grondag.bitraster.Constants.PRECISION_BITS; import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PY; @@ -155,9 +153,9 @@ public abstract class AbstractRasterizer { float offsetX, offsetY, offsetZ; final int[] vertexData = new int[VERTEX_DATA_LENGTH]; // CELERITAS: buffer geometry is per instance so each axis can follow render distance and field of view. - // The hot loops use only shifts and masks with these, which measured no slower than folded constants. - int widthBits, heightBits; - int tileWidthBits, tileWidthMask, tileCount; + // Widths need not be powers of two: rows are addressed by multiplication, which measured no slower than + // the shifts and masks it replaced, and it lets an axis be sized to its requirement instead of double it. + int tileWidth, tileHeight, tileCount; int pixelWidth, pixelHeight, lastPixelX, lastPixelY, halfPixelWidth, halfPixelHeight; int preciseWidth, preciseHeight, halfPreciseWidth, halfPreciseHeight, preciseWidthClamp, preciseHeightClamp; @@ -166,6 +164,14 @@ public abstract class AbstractRasterizer { /** One bit per tile, set once the tile is fully covered, so scans can skip covered runs 64 tiles at a time. */ long[] fullBits; + + /** + * One bit per cell of 8x8 tiles in each cell row, set once anything is drawn in the cell. A box whose + * tiles lie in untouched cells alone cannot be occluded, and {@link #touchedVersion} changes whenever a + * cell is first touched, so a caller can cache that verdict and revalidate it with one compare. + */ + int[] touchedCellRows; + int touchedVersion; final EventFiller[] EVENT_FILLERS = new EventFiller[0x1000]; /** Bounds of current triangle - pixel coordinates. */ @@ -184,13 +190,15 @@ public abstract class AbstractRasterizer { /** Inclusive range of tile columns fully covered by the quad on every row of the current band; empty when first > last. */ protected int bandInnerFirst, bandInnerLast; + /** Tile columns of the widest row of the current band; tiles outside them are untouched by the polygon. */ + protected int bandOuterFirst, bandOuterLast; + /** Per-edge intercept at y = 0 and step per pixel row, 20-bit fixed point. See {@link #prepareEvents}. */ protected boolean edgesReady; protected final long[] edgeX0 = new long[6]; protected final long[] edgeStep = new long[6]; /** Vertex-data slot of each edge of the current polygon, in order. */ - private static final int[] EDGE_SLOTS = { IDX_AX0, IDX_BX0, IDX_CX0, IDX_DX0, IDX_EX0, IDX_FX0 }; /** * True when the current polygon was set up by {@link #preparePolygonNoClip} and its events come from the @@ -198,18 +206,27 @@ public abstract class AbstractRasterizer { */ protected boolean genericEvents; + /** Vertices of the polygon set up by {@link #preparePolygonNoClip}, whose edges are classified on demand. */ + private int[] polyVertices; + private int polyCount; + + /** First and last pixel rows whose centres lie within the current polygon's vertical extent. */ + private int polyMinRow, polyMaxRow; + /** * True while testing: the polygon is grown by one pixel on every side so a visible strip thinner than the * pixel pitch, which pixel-centre sampling would miss, still reaches a sampled pixel. Drawing never dilates, * or abutting occluders would double-cover and hide the seams between them. */ protected boolean dilate; - private final int[] leftEdges = new int[6]; - private final int[] rightEdges = new int[6]; - private final int[] flatPositions = new int[6]; - private final int[] flatSlots = new int[6]; - private int leftCount, rightCount, flatCount; - private final long[] leftX0 = new long[3], leftStep = new long[3], rightX0 = new long[3], rightStep = new long[3]; + /** + * The current polygon's left and right edge chains in ascending row order: intercept at row zero and step + * per row in 20-bit fixed point, and the last pixel row on which the edge is the one that bounds the span. + */ + private int leftCount, rightCount; + private final long[] leftX0 = new long[6], leftStep = new long[6], rightX0 = new long[6], rightStep = new long[6]; + private final int[] leftEnd = new int[6], rightEnd = new int[6]; + private final int[] chainEdges = new int[6]; { EVENT_FILLERS[EVENT_0123_RRRR] = () -> { @@ -650,40 +667,38 @@ public abstract class AbstractRasterizer { }; } - AbstractRasterizer(int widthBits, int heightBits) { - resize(widthBits, heightBits); + AbstractRasterizer(int tileWidth, int tileHeight) { + resize(tileWidth, tileHeight); } - /** {@return the buffer width as a power of two of tiles; pixels are eight times that} */ - public final int widthBits() { - return widthBits; + /** {@return the buffer width in tiles; pixels are eight times that} */ + public final int tileWidth() { + return tileWidth; } - /** {@return the buffer height as a power of two of tiles; pixels are eight times that} */ - public final int heightBits() { - return heightBits; + /** {@return the buffer height in tiles; pixels are eight times that} */ + public final int tileHeight() { + return tileHeight; } /** - * Sets the buffer to {@code 8 << widthBits} by {@code 8 << heightBits} pixels, reallocating and clearing it + * Sets the buffer to {@code 8 * tileWidth} by {@code 8 * tileHeight} pixels, reallocating and clearing it * if the size changed. Safe between frames only: the current polygon and scene contents are discarded. */ - public final void resize(int widthBits, int heightBits) { - if (widthBits < MIN_SIZE_BITS || widthBits > MAX_SIZE_BITS || heightBits < MIN_SIZE_BITS || heightBits > MAX_SIZE_BITS) { - throw new IllegalArgumentException("unsupported buffer size bits " + widthBits + "x" + heightBits); + public final void resize(int tileWidth, int tileHeight) { + if (tileWidth < MIN_SIZE_TILES || tileWidth > MAX_SIZE_TILES || tileHeight < MIN_SIZE_TILES || tileHeight > MAX_SIZE_TILES) { + throw new IllegalArgumentException("unsupported buffer size in tiles " + tileWidth + "x" + tileHeight); } - if (this.widthBits == widthBits && this.heightBits == heightBits && tiles != null) { + if (this.tileWidth == tileWidth && this.tileHeight == tileHeight && tiles != null) { return; } - this.widthBits = widthBits; - this.heightBits = heightBits; - tileWidthBits = widthBits; - tileWidthMask = (1 << widthBits) - 1; - tileCount = 1 << (widthBits + heightBits); - pixelWidth = 1 << (widthBits + TILE_AXIS_SHIFT); - pixelHeight = 1 << (heightBits + TILE_AXIS_SHIFT); + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + tileCount = tileWidth * tileHeight; + pixelWidth = tileWidth << TILE_AXIS_SHIFT; + pixelHeight = tileHeight << TILE_AXIS_SHIFT; lastPixelX = pixelWidth - 1; lastPixelY = pixelHeight - 1; halfPixelWidth = pixelWidth >> 1; @@ -698,17 +713,130 @@ public abstract class AbstractRasterizer { eventData = new int[pixelHeight * 2]; tiles = new long[tileCount]; - fullBits = new long[tileCount >> 6]; + fullBits = new long[(tileCount + 63) >> 6]; + touchedCellRows = new int[(tileHeight + CELL_TILE_MASK) >> CELL_TILE_SHIFT]; } /** Marks every pixel clear. */ final void clear() { Arrays.fill(tiles, 0L); Arrays.fill(fullBits, 0L); + Arrays.fill(touchedCellRows, 0); + touchedVersion++; + } + + /** Cells of the touched map are this many tiles square; 256 tiles across fit one int of cell bits. */ + static final int CELL_TILE_SHIFT = 3; + static final int CELL_TILE_MASK = (1 << CELL_TILE_SHIFT) - 1; + + /** Bits of the cells spanning tile columns {@code first..last} inclusive. */ + private static int cellMask(int first, int last) { + return (-1 >>> (31 - (last >> CELL_TILE_SHIFT))) & (-1 << (first >> CELL_TILE_SHIFT)); + } + + /** Records that the tiles {@code first..last} of tile row {@code tileY} may have been drawn into. */ + private void markTouched(int tileY, int first, int last) { + final int[] rows = touchedCellRows; + final int cellY = tileY >> CELL_TILE_SHIFT; + final int mask = cellMask(first, last); + final int row = rows[cellY]; + + if ((row & mask) != mask) { + rows[cellY] = row | mask; + touchedVersion++; + } + } + + /** Changes whenever a cell of the touched map is first drawn into; see {@link #isTileBoxUntouched}. */ + public final int touchedVersion() { + return touchedVersion; + } + + /** True if nothing has been drawn in any cell overlapping the given inclusive tile bounds. */ + public final boolean isTileBoxUntouched(int packedTileBounds) { + final int[] rows = touchedCellRows; + final int mask = cellMask(packedTileBounds & 0xFF, (packedTileBounds >>> 16) & 0xFF); + final int lastCellY = ((packedTileBounds >>> 24) & 0xFF) >> CELL_TILE_SHIFT; + + for (int cellY = ((packedTileBounds >>> 8) & 0xFF) >> CELL_TILE_SHIFT; cellY <= lastCellY; cellY++) { + if ((rows[cellY] & mask) != 0) { + return false; + } + } + + return true; + } + + /** Result of {@link #boxTileBounds} for a box that reaches the near plane or lies wholly off screen. */ + public static final long NO_TILE_BOUNDS = -1L; + + /** Set in a {@link #boxTileBounds} result when every point of the box projects on screen. */ + public static final long TILE_BOUNDS_ON_SCREEN = 1L << 32; + + /** + * Inclusive tile bounds of the screen rectangle around a camera-relative box, packed as x0, y0, x1, y1 in + * successive bytes of the low word, grown by a pixel and clamped to the screen. This rectangle contains the + * projection of every point in the box, so every polygon a box inside it is tested with. The result carries + * {@link #TILE_BOUNDS_ON_SCREEN} when no clamping was needed, so that a box inside it is on screen too. + * {@link #NO_TILE_BOUNDS} if any corner is behind the near plane or the whole box is off screen. + */ + final long boxTileBounds(float fx, float fy, float fz, float ex, float ey, float ez) { + final float bx = m00 * fx + m01 * fy + m02 * fz + m03; + final float by = m10 * fx + m11 * fy + m12 * fz + m13; + final float bz = m20 * fx + m21 * fy + m22 * fz + m23; + final float bw = m30 * fx + m31 * fy + m32 * fz + m33; + + final float dxx = m00 * ex, dxy = m10 * ex, dxz = m20 * ex, dxw = m30 * ex; + final float dyx = m01 * ey, dyy = m11 * ey, dyz = m21 * ey, dyw = m31 * ey; + final float dzx = m02 * ez, dzy = m12 * ez, dzz = m22 * ez, dzw = m32 * ez; + + float minX = Float.POSITIVE_INFINITY, maxX = Float.NEGATIVE_INFINITY; + float minY = Float.POSITIVE_INFINITY, maxY = Float.NEGATIVE_INFINITY; + + for (int corner = 0; corner < 8; corner++) { + float x = bx, y = by, z = bz, w = bw; + + if ((corner & 4) != 0) { x += dxx; y += dxy; z += dxz; w += dxw; } + if ((corner & 2) != 0) { x += dyx; y += dyy; z += dyz; w += dyw; } + if ((corner & 1) != 0) { x += dzx; y += dzy; z += dzz; w += dzw; } + + // same acceptance as needsNearClip + if (!(w > 0 && z > 0 && z <= w)) { + return NO_TILE_BOUNDS; + } + + final float iw = 1f / w; + final float sx = x * iw; + final float sy = y * iw; + if (sx < minX) minX = sx; + if (sx > maxX) maxX = sx; + if (sy < minY) minY = sy; + if (sy > maxY) maxY = sy; + } + + // same acceptance as isProjectedPointClear, so that every point of the box passes it + final long onScreen = (minX >= -1f && maxX < 1f && minY >= -1f && maxY < 1f) ? TILE_BOUNDS_ON_SCREEN : 0L; + + // to pixels, with a pixel of margin over the rounding of the polygon path and the test dilation + final float px0 = (minX + 1f) * halfPixelWidth - 1f; + final float px1 = (maxX + 1f) * halfPixelWidth + 1f; + final float py0 = (minY + 1f) * halfPixelHeight - 1f; + final float py1 = (maxY + 1f) * halfPixelHeight + 1f; + + if (!(px1 >= 0f && py1 >= 0f && px0 <= lastPixelX && py0 <= lastPixelY)) { + return NO_TILE_BOUNDS; + } + + final int tx0 = Math.max(0, (int) px0) >> TILE_AXIS_SHIFT; + final int ty0 = Math.max(0, (int) py0) >> TILE_AXIS_SHIFT; + final int tx1 = Math.min(lastPixelX, (int) px1) >> TILE_AXIS_SHIFT; + final int ty1 = Math.min(lastPixelY, (int) py1) >> TILE_AXIS_SHIFT; + + return onScreen | (tx0 | (ty0 << 8) | (tx1 << 16) | (ty1 << 24)); } final int tileIndexFromPixelXY(int x, int y) { - return (x >>> TILE_AXIS_SHIFT) | ((y >>> TILE_AXIS_SHIFT) << tileWidthBits); + return (x >>> TILE_AXIS_SHIFT) + ((y >>> TILE_AXIS_SHIFT) * tileWidth); } /** Loads the scene matrix; regions are then positioned with {@link #setRegionOffset}. */ @@ -718,6 +846,37 @@ public abstract class AbstractRasterizer { m10 = m.a10f(); m11 = m.a11f(); m12 = m.a12f(); m13 = m.a13f(); m20 = m.a20f(); m21 = m.a21f(); m22 = m.a22f(); m23 = m.a23f(); m30 = m.a30f(); m31 = m.a31f(); m32 = m.a32f(); m33 = m.a33f(); + + final float[] step = sectionStep; + step[0] = 16f * m00; step[1] = 16f * m10; step[2] = 16f * m30; + step[3] = 16f * m01; step[4] = 16f * m11; step[5] = 16f * m31; + step[6] = 16f * m02; step[7] = 16f * m12; step[8] = 16f * m32; + } + + /** + * Clip-space change in x, y and w per section along each world axis, as three triples. Clip space is + * affine in world space, so a section centre is a base point plus whole steps, and whether it lies on + * screen is a comparison of x and y against w with no divide. + */ + final float[] sectionStep = new float[9]; + + /** Writes the clip-space x, y and w of a camera-relative point. */ + final void clipPoint(float fx, float fy, float fz, float[] out, int offset) { + out[offset] = m00 * fx + m01 * fy + m02 * fz + m03; + out[offset + 1] = m10 * fx + m11 * fy + m12 * fz + m13; + out[offset + 2] = m30 * fx + m31 * fy + m32 * fz + m33; + } + + /** + * True if the section centre {@code i, j, k} sections from the given clip-space base point is on screen + * by the same acceptance as {@link #isProjectedPointClear}. The base must be in front of the near plane. + */ + final boolean isSectionCenterOnScreen(float[] base, int offset, int i, int j, int k) { + final float[] step = sectionStep; + final float x = base[offset] + i * step[0] + j * step[3] + k * step[6]; + final float y = base[offset + 1] + i * step[1] + j * step[4] + k * step[7]; + final float w = base[offset + 2] + i * step[2] + j * step[5] + k * step[8]; + return w > 0 && x >= -w && x < w && y >= -w && y < w; } /** @param x region origin relative to the camera, in {@link Constants#CAMERA_PRECISION_BITS} fixed point */ @@ -729,7 +888,7 @@ public abstract class AbstractRasterizer { } final void copyFrom(AbstractRasterizer source) { - resize(source.widthBits, source.heightBits); + resize(source.tileWidth, source.tileHeight); setMatrix(source.mvpMatrix); offsetX = source.offsetX; offsetY = source.offsetY; @@ -737,13 +896,13 @@ public abstract class AbstractRasterizer { System.arraycopy(source.vertexData, 0, vertexData, 0, VERTEX_DATA_LENGTH); System.arraycopy(source.eventData, 0, eventData, 0, eventData.length); System.arraycopy(source.tiles, 0, tiles, 0, tileCount); - System.arraycopy(source.fullBits, 0, fullBits, 0, tileCount >> 6); + System.arraycopy(source.fullBits, 0, fullBits, 0, fullBits.length); } // CELERITAS: work counters for RasterStatsReport. STATS is a constant so the JIT drops the increments when off. public static final boolean STATS = Boolean.getBoolean("bitraster.stats"); public static long STAT_D_NOOP, STAT_D_RANGE0, STAT_D_RANGE1, STAT_D_RANGE2, STAT_D_RANGE3; - public static long STAT_T_EMPTY, STAT_T_INNER, STAT_T_COVER, STAT_T_HIDDEN, STAT_D_INNER, STAT_D_COVER; + public static long STAT_T_EMPTY, STAT_T_INNER, STAT_T_COVER, STAT_T_HIDDEN, STAT_T_VERTEX, STAT_T_BOX_HIDDEN, STAT_D_INNER, STAT_D_COVER; public static long STAT_DRAW_QUADS, STAT_TEST_QUADS, STAT_TEST_TILES, STAT_EVENT_ROWS, STAT_DRAW_CALLS, STAT_TEST_CALLS; final void drawQuad(int v0, int v1, int v2, int v3) { @@ -791,10 +950,10 @@ public abstract class AbstractRasterizer { final long[] fullBits = this.fullBits; for (int tileY = minTileY; tileY <= maxTileY; tileY++) { - final int rowBase = tileY << tileWidthBits; + final int rowBase = tileY * tileWidth; final int last = rowBase + maxTileX; boolean populated = false; - int innerFirst = 0, innerLast = -1; + int innerFirst = 0, innerLast = -1, outerFirst = 0, outerLast = -1; for (int tileIndex = rowBase + minTileX; tileIndex <= last; tileIndex++) { // jump to the next tile that is not already fully covered @@ -826,6 +985,8 @@ public abstract class AbstractRasterizer { populated = true; innerFirst = rowBase + bandInnerFirst; innerLast = rowBase + bandInnerLast; + outerFirst = rowBase + bandOuterFirst; + outerLast = rowBase + bandOuterLast; } // interior tiles are fully covered by the quad, and this one is not fully drawn @@ -834,7 +995,15 @@ public abstract class AbstractRasterizer { return true; } - if ((~word & computeTileCoverage(tileIndex)) != 0) { + // outside the band's widest row the polygon covers nothing + if (tileIndex < outerFirst) { + tileIndex = outerFirst - 1; + continue; + } else if (tileIndex > outerLast) { + break; + } + + if ((~word & computeTileCoverage(tileIndex - rowBase)) != 0) { if (STATS) STAT_T_COVER++; return true; } @@ -869,7 +1038,7 @@ public abstract class AbstractRasterizer { final long[] tiles = this.tiles; for (int tileY = minTileY; tileY <= maxTileY; tileY++) { - final int rowBase = tileY << tileWidthBits; + final int rowBase = tileY * tileWidth; boolean populated = false; for (int tileX = minTileX; tileX <= maxTileX; tileX++) { @@ -885,7 +1054,7 @@ public abstract class AbstractRasterizer { populated = true; } - if ((word & computeTileCoverage(tileIndex)) != 0) { + if ((word & computeTileCoverage(tileIndex - rowBase)) != 0) { return true; } } @@ -902,10 +1071,10 @@ public abstract class AbstractRasterizer { final long[] tiles = this.tiles; final long[] fullBits = this.fullBits; for (int tileY = minTileY; tileY <= maxTileY; tileY++) { - final int rowBase = tileY << tileWidthBits; + final int rowBase = tileY * tileWidth; final int last = rowBase + maxTileX; boolean populated = false; - int innerFirst = 0, innerLast = -1; + int innerFirst = 0, innerLast = -1, outerFirst = 0, outerLast = -1; for (int tileIndex = rowBase + minTileX; tileIndex <= last; tileIndex++) { // jump to the next tile that is not already fully covered @@ -927,19 +1096,38 @@ public abstract class AbstractRasterizer { populateBand(tileY); populated = true; innerFirst = rowBase + bandInnerFirst; - innerLast = rowBase + bandInnerLast; + innerLast = Math.min(last, rowBase + bandInnerLast); + outerFirst = rowBase + bandOuterFirst; + outerLast = Math.min(last, rowBase + bandOuterLast); + + final int firstDrawn = Math.max(tileIndex, outerFirst) - rowBase; + final int lastDrawn = outerLast - rowBase; + + if (firstDrawn <= lastDrawn) { + markTouched(tileY, firstDrawn, lastDrawn); + } } - final long word; + // outside the band's widest row the polygon covers nothing + if (tileIndex < outerFirst) { + tileIndex = outerFirst - 1; + continue; + } else if (tileIndex > outerLast) { + break; + } if (tileIndex >= innerFirst && tileIndex <= innerLast) { - if (STATS) STAT_D_INNER++; - word = -1L; - } else { - if (STATS) STAT_D_COVER++; - word = tiles[tileIndex] | computeTileCoverage(tileIndex); + // every tile through the end of the interior run is covered on all rows; filling the ones + // already full again is harmless and cheaper than testing them one by one + if (STATS) STAT_D_INNER += innerLast - tileIndex + 1; + Arrays.fill(tiles, tileIndex, innerLast + 1, -1L); + markFull(fullBits, tileIndex, innerLast); + tileIndex = innerLast; + continue; } + if (STATS) STAT_D_COVER++; + final long word = tiles[tileIndex] | computeTileCoverage(tileIndex - rowBase); tiles[tileIndex] = word; if (word == -1L) { @@ -951,6 +1139,26 @@ public abstract class AbstractRasterizer { if (STATS && !edgesReady) STAT_D_NOOP++; } + /** Sets the full bits of tiles {@code from} through {@code to} inclusive. */ + private static void markFull(long[] fullBits, int from, int to) { + final int firstWord = from >> 6; + final int lastWord = to >> 6; + final long head = -1L << (from & 63); + final long tail = -1L >>> (63 - (to & 63)); + + if (firstWord == lastWord) { + fullBits[firstWord] |= head & tail; + } else { + fullBits[firstWord] |= head; + + for (int w = firstWord + 1; w < lastWord; w++) { + fullBits[w] = -1L; + } + + fullBits[lastWord] |= tail; + } + } + abstract int prepareBounds(int v0, int v1, int v2, int v3); /** @@ -1282,6 +1490,14 @@ public abstract class AbstractRasterizer { cx[7] = cx[6] + dzx; cy[7] = cy[6] + dzy; cz[7] = cz[6] + dzz; cw[7] = cw[6] + dzw; } + /** + * {@link Math#round(float)} exactly, via the floor intrinsic: the double sum is exact, so the tie and the + * 0.49999997f cases come out the same, without the library call the JIT may otherwise emit. + */ + static int roundToInt(float v) { + return (int) Math.floor(v + 0.5); + } + /** Shared tail of {@link #isPointClear}: normalized device position to pixel to tile bit. */ final boolean isProjectedPointClear(float tx, float ty, float iw) { final float sx = tx * iw; @@ -1299,7 +1515,7 @@ public abstract class AbstractRasterizer { return false; } - final int tileIndex = (px >> TILE_AXIS_SHIFT) | ((py >> TILE_AXIS_SHIFT) << tileWidthBits); + final int tileIndex = (px >> TILE_AXIS_SHIFT) + ((py >> TILE_AXIS_SHIFT) * tileWidth); return (tiles[tileIndex] & (1L << (((py & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (px & TILE_PIXEL_INDEX_MASK)))) == 0; } @@ -1319,65 +1535,35 @@ public abstract class AbstractRasterizer { } } - long computeTileCoverage(int tileIndex) { + /** + * Coverage of the tile in the given column of the band last passed to {@link #populateBand}. Each row's + * bits are the row's span clipped to the tile: shifts clamped to eight give an empty byte when the span + * misses the tile on that side, so no row needs a branch and the eight rows overlap in the pipeline. + */ + long computeTileCoverage(int tileX) { final int[] data = eventData; - final int tileFirstX = (tileIndex & tileWidthMask) << TILE_AXIS_SHIFT; + final int tileFirstX = tileX << TILE_AXIS_SHIFT; final int tileLastX = tileFirstX + 7; - // +1 to left shift because events are in pairs - final int baseEventIndex = (tileIndex >> tileWidthBits) << (TILE_AXIS_SHIFT + 1); - long mask = 0; - // shift left or right, > 7 means no coverage - int l, r; + // events are in pairs, so the band's first row is at twice its pixel row + final int b = eventY0 << 1; - if ((l = data[baseEventIndex] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 1]) < 8) { - mask = (l < 0 ? 0xFFL : 0xFFL << l) & (r < 0 ? 0xFFL : 0xFFL >>> r); - } + return rowCoverage(data[b], data[b + 1], tileFirstX, tileLastX) + | rowCoverage(data[b + 2], data[b + 3], tileFirstX, tileLastX) << 8 + | rowCoverage(data[b + 4], data[b + 5], tileFirstX, tileLastX) << 16 + | rowCoverage(data[b + 6], data[b + 7], tileFirstX, tileLastX) << 24 + | rowCoverage(data[b + 8], data[b + 9], tileFirstX, tileLastX) << 32 + | rowCoverage(data[b + 10], data[b + 11], tileFirstX, tileLastX) << 40 + | rowCoverage(data[b + 12], data[b + 13], tileFirstX, tileLastX) << 48 + | rowCoverage(data[b + 14], data[b + 15], tileFirstX, tileLastX) << 56; + } - if ((l = data[baseEventIndex + 14] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 15]) < 8) { - mask |= ((l < 0 ? 0xFF00000000000000L : 0xFF00000000000000L << l) & (r < 0 ? 0xFF00000000000000L : 0xFF00000000000000L >>> r)); - } - - // Early exit when full coverage is detected - if (mask == 0xFF000000000000FFL) { - return -1L; - } - - if ((l = data[baseEventIndex + 2] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 3]) < 8) { - mask |= ((l < 0 ? 0xFF00L : 0xFF00L << l) & (r < 0 ? 0xFF00L : 0xFF00L >>> r)); - } - - if ((l = data[baseEventIndex + 4] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 5]) < 8) { - mask |= ((l < 0 ? 0xFF0000L : 0xFF0000L << l) & (r < 0 ? 0xFF0000L : 0xFF0000L >>> r)); - } - - if ((l = data[baseEventIndex + 6] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 7]) < 8) { - mask |= ((l < 0 ? 0xFF000000L : 0xFF000000L << l) & (r < 0 ? 0xFF000000L : 0xFF000000L >>> r)); - } - - if ((l = data[baseEventIndex + 8] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 9]) < 8) { - mask |= ((l < 0 ? 0xFF00000000L : 0xFF00000000L << l) & (r < 0 ? 0xFF00000000L : 0xFF00000000L >>> r)); - } - - if ((l = data[baseEventIndex + 10] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 11]) < 8) { - mask |= ((l < 0 ? 0xFF0000000000L : 0xFF0000000000L << l) & (r < 0 ? 0xFF0000000000L : 0xFF0000000000L >>> r)); - } - - if ((l = data[baseEventIndex + 12] - tileFirstX) < 8 && (r = tileLastX - data[baseEventIndex + 13]) < 8) { - mask |= ((l < 0 ? 0xFF000000000000L : 0xFF000000000000L << l) & (r < 0 ? 0xFF000000000000L : 0xFF000000000000L >>> r)); - } - - //long bMask = computeTileCoverageB(tileIndex); - // - //if (bMask != mask) { - // System.out.println("Prior"); - // Util.printMask(mask); - // System.out.println("New"); - // Util.printMask(bMask); - // computeTileCoverageB(tileIndex); - //} - - return mask; + /** Bits of one tile row covered by the span {@code left..right} inclusive, in the low byte. */ + private static long rowCoverage(int left, int right, int tileFirstX, int tileLastX) { + // pixels cut off the left and right of the tile, clamped to 0..8; 8 empties the byte + final int l = Math.min(Math.max(left - tileFirstX, 0), 8); + final int r = Math.min(Math.max(tileLastX - right, 0), 8); + return (0xFFL << l) & (0xFFL >>> r); } public boolean isPixelClear(int x, int y) { @@ -1559,7 +1745,11 @@ public abstract class AbstractRasterizer { this.genericEvents = false; } - /** Prepares an unclipped convex polygon of 3..6 projected vertices with consistent winding. */ + /** + * Prepares an unclipped convex polygon of 3..6 projected vertices with consistent winding. Only the pixel + * bounds are computed here; the edges are prepared by {@link #prepareEdgesGeneric} the first time a + * band needs them, which a test that finds an untouched tile or a draw onto fully covered tiles never does. + */ final int preparePolygonNoClip(int[] vertices, int count) { final int[] data = vertexData; @@ -1598,38 +1788,13 @@ public abstract class AbstractRasterizer { maxPixelX = (maxX + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; maxPixelY = (maxY + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; - int leftCount = 0, rightCount = 0, flatCount = 0; - int x0 = data[vertices[0] + PV_PX]; - int y0 = data[vertices[0] + PV_PY]; + // rows whose centres fall inside [minY, maxY]; the bounds above may overshoot by a row, which is fine + // for a scan range but not for deciding which rows the polygon actually spans + polyMinRow = minPixelY; + polyMaxRow = (maxY - PRECISE_PIXEL_CENTER) >> PRECISION_BITS; - for (int e = 0; e < count; e++) { - final int next = vertices[e + 1 == count ? 0 : e + 1]; - final int x1 = data[next + PV_PX]; - final int y1 = data[next + PV_PY]; - final int slot = EDGE_SLOTS[e]; - data[slot] = x0; - data[slot + 1] = y0; - data[slot + 2] = x1; - data[slot + 3] = y1; - - final int position = edgePosition(x0, y0, x1, y1); - - if ((position & A_ZERO) != 0) { - flatPositions[flatCount] = position; - flatSlots[flatCount++] = slot; - } else if ((position & A_POSITIVE) != 0) { - leftEdges[leftCount++] = e; - } else { - rightEdges[rightCount++] = e; - } - - x0 = x1; - y0 = y1; - } - - this.leftCount = leftCount; - this.rightCount = rightCount; - this.flatCount = flatCount; + this.polyVertices = vertices; + this.polyCount = count; this.genericEvents = true; this.edgesReady = false; return BOUNDS_IN; @@ -1653,6 +1818,39 @@ public abstract class AbstractRasterizer { drawQuad(); } + /** + * True if the pixel under any on-screen vertex of a projected polygon is clear. A sufficient test only: + * that pixel's centre is within half a pixel of the polygon, which the test dilation reaches except across + * a nearly flat edge, so this can call a polygon visible that the full test would not, never the reverse. + * Costs a few loads and no setup, and settles most sections whose centre is covered but that show at a + * corner, as sections cut by the horizon do. + */ + final boolean isAnyVertexPixelClear(int[] vertices, int count) { + final int[] data = vertexData; + final long[] tiles = this.tiles; + final int lastPixelX = this.lastPixelX; + final int lastPixelY = this.lastPixelY; + + for (int i = 0; i < count; i++) { + final int v = vertices[i]; + final int px = data[v + PV_PX] >> PRECISION_BITS; + final int py = data[v + PV_PY] >> PRECISION_BITS; + + if (px < 0 || py < 0 || px > lastPixelX || py > lastPixelY) { + continue; + } + + final int tileIndex = (px >> TILE_AXIS_SHIFT) + ((py >> TILE_AXIS_SHIFT) * tileWidth); + + if ((tiles[tileIndex] & (1L << (((py & TILE_PIXEL_INDEX_MASK) << TILE_AXIS_SHIFT) | (px & TILE_PIXEL_INDEX_MASK)))) == 0) { + if (STATS) STAT_T_VERTEX++; + return true; + } + } + + return false; + } + final boolean isPolygonPartiallyClear(int[] vertices, int count) { if (STATS) STAT_TEST_CALLS++; dilate = true; @@ -1664,9 +1862,57 @@ public abstract class AbstractRasterizer { if (STATS) STAT_TEST_QUADS++; dilateBounds(); + + if (isSmallPixelBoxCovered()) { + if (STATS) STAT_T_BOX_HIDDEN++; + return false; + } + return isQuadPartiallyClear(); } + /** Bounding rectangles of at most this many tiles are checked for full coverage before any edge setup. */ + private static final int COVERED_BOX_MAX_TILES = 16; + + /** + * True if every pixel of the current polygon's bounding rectangle is covered, which hides the polygon + * without preparing its edges. Only tried on small rectangles: a far section's is a few tiles, and + * those are the tests that end hidden, while a near section's would cost more than it could save. + */ + private boolean isSmallPixelBoxCovered() { + final int minTileX = minPixelX >> TILE_AXIS_SHIFT; + final int maxTileX = maxPixelX >> TILE_AXIS_SHIFT; + final int minTileY = minPixelY >> TILE_AXIS_SHIFT; + final int maxTileY = maxPixelY >> TILE_AXIS_SHIFT; + + if ((maxTileX - minTileX + 1) * (maxTileY - minTileY + 1) > COVERED_BOX_MAX_TILES) { + return false; + } + + final long[] tiles = this.tiles; + final int tileWidth = this.tileWidth; + + for (int tileY = minTileY; tileY <= maxTileY; tileY++) { + // rows of this tile inside the rectangle, as a mask of whole tile rows + final int r0 = tileY == minTileY ? minPixelY & TILE_PIXEL_INDEX_MASK : 0; + final int r1 = tileY == maxTileY ? maxPixelY & TILE_PIXEL_INDEX_MASK : 7; + final long rowsMask = (-1L << (r0 << TILE_AXIS_SHIFT)) & (-1L >>> ((7 - r1) << TILE_AXIS_SHIFT)); + final int rowBase = tileY * tileWidth; + + for (int tileX = minTileX; tileX <= maxTileX; tileX++) { + final int c0 = tileX == minTileX ? minPixelX & TILE_PIXEL_INDEX_MASK : 0; + final int c1 = tileX == maxTileX ? maxPixelX & TILE_PIXEL_INDEX_MASK : 7; + final long mask = (((0xFFL << c0) & (0xFFL >>> (7 - c1))) * 0x0101010101010101L) & rowsMask; + + if ((tiles[rowBase + tileX] & mask) != mask) { + return false; + } + } + } + + return true; + } + /** 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() { final int eventKey = this.eventKey; @@ -1699,76 +1945,195 @@ public abstract class AbstractRasterizer { } } + /** + * Builds the current polygon's left and right edge chains. With consistent winding an edge's vertical run + * tells its side, and each side's edges run monotonically in y, so each chain is collected in polygon order + * from wherever it starts and then read in ascending row order. An edge bounds the span only on the rows + * whose centres lie within its vertical extent; a nearly flat edge that contains no row centre is dropped, + * and the neighbouring edges are never evaluated outside their own extent. Deferred until a band needs + * it, which a test that finds an untouched tile or a draw onto fully covered tiles never does. + */ private void prepareEdgesGeneric() { - // a convex hexagon has at most three edges per side; unused slots never win the max/min - for (int i = 0; i < 3; i++) { - if (i < leftCount) { - prepareEdge(leftEdges[i], 0x100000L, leftX0, leftStep, i); - } else { - leftX0[i] = Long.MIN_VALUE; - leftStep[i] = 0; - } - - if (i < rightCount) { - prepareEdge(rightEdges[i], 0x7FFFFL, rightX0, rightStep, i); - } else { - rightX0[i] = Long.MAX_VALUE; - rightStep[i] = 0; - } - } - } - - private void prepareEdge(int e, long rounding, long[] x0Out, long[] stepOut, int slotOut) { final int[] data = vertexData; - final int i = EDGE_SLOTS[e]; - final int x0 = data[i]; - final int y0 = data[i + 1]; - final int dx = data[i + 2] - x0; + final int[] vertices = this.polyVertices; + final int count = this.polyCount; - if (dx == 0) { - stepOut[slotOut] = 0; - x0Out[slotOut] = (long) ((x0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; - } else { - final long n = (long) ((double) (((long) dx) << 16) / (data[i + 3] - y0)); - stepOut[slotOut] = n << PRECISION_BITS; - x0Out[slotOut] = ((long) x0 << 16) - n * y0 + rounding; + // which edges descend in polygon order; the rest ascend or are flat + int descending = 0; + int y0 = data[vertices[0] + PV_PY]; + + for (int e = 0; e < count; e++) { + final int y1 = data[vertices[e + 1 == count ? 0 : e + 1] + PV_PY]; + + if (y1 < y0) { + descending |= 1 << e; + } else if (y1 == y0) { + // flat edges belong to neither chain; they only ever join two sloped edges + descending |= 1 << (e + 8); + } + + y0 = y1; } + + final int flat = descending >>> 8; + final int all = (1 << count) - 1; + descending &= all; + leftCount = prepareChain(descending, true, leftX0, leftStep, leftEnd); + rightCount = prepareChain(all & ~descending & ~flat, false, rightX0, rightStep, rightEnd); } - /** Band filler for polygons set up by {@link #preparePolygonNoClip}. */ + /** + * Emits the edges in {@code members}, which form one contiguous run around the polygon, in ascending row + * order. Left chains descend in polygon order, so they are read backwards. + */ + private int prepareChain(int members, boolean left, long[] x0Out, long[] stepOut, int[] endOut) { + final int[] data = vertexData; + final int[] vertices = this.polyVertices; + final int count = this.polyCount; + final int[] chain = this.chainEdges; + + if (members == 0) { + return 0; + } + + // the run starts at a member whose predecessor is not one; a run of every edge is impossible + final int predecessors = ((members << 1) | (members >>> (count - 1))) & ((1 << count) - 1); + int start = Integer.numberOfTrailingZeros(members & ~predecessors); + int chained = 0; + + for (int e = start; (members & (1 << e)) != 0; ) { + chain[chained++] = e; + + if (++e == count) { + e = 0; + } + } + + int emitted = 0; + + for (int i = 0; i < chained; i++) { + final int e = chain[left ? chained - 1 - i : i]; + final int v0 = vertices[e]; + final int v1 = vertices[e + 1 == count ? 0 : e + 1]; + final int ex0 = data[v0 + PV_PX], ey0 = data[v0 + PV_PY]; + final int ex1 = data[v1 + PV_PX], ey1 = data[v1 + PV_PY]; + final int yLow = Math.min(ey0, ey1), yHigh = Math.max(ey0, ey1); + + // rows whose centres lie within the edge; a nearly flat edge may hold none + final int rowLow = (yLow + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + final int rowHigh = (yHigh - PRECISE_PIXEL_CENTER) >> PRECISION_BITS; + + if (rowLow > rowHigh) { + continue; + } + + final int dx = ex1 - ex0; + + if (dx == 0) { + stepOut[emitted] = 0; + x0Out[emitted] = (long) ((ex0 + SCANT_PRECISE_PIXEL_CENTER) >> PRECISION_BITS) << 20; + } else { + // exact for these magnitudes and far cheaper than a 64-bit integer divide + final long n = (long) ((double) (((long) dx) << 16) / (ey1 - ey0)); + stepOut[emitted] = n << PRECISION_BITS; + // left edges round up; right edges lose the tie + x0Out[emitted] = ((long) ex0 << 16) - n * ey0 + (left ? 0x100000L : 0x7FFFFL); + } + + endOut[emitted++] = rowHigh; + } + + return emitted; + } + + /** + * Band filler for polygons set up by {@link #preparePolygonNoClip}. Rows outside the polygon's vertical + * extent are empty; every other row's span runs from the left chain's edge for that row to the right + * chain's. Under {@link #dilate} the rows just past either end take the end row's span, grown like every + * row by the dilation. The band's interior and extent tile ranges are gathered in the same pass. + */ private void populateBandGeneric(int y0) { final int[] eventData = this.eventData; final long[] leftX0 = this.leftX0; final long[] leftStep = this.leftStep; + final int[] leftEnd = this.leftEnd; final long[] rightX0 = this.rightX0; final long[] rightStep = this.rightStep; + final int[] rightEnd = this.rightEnd; + final int lastLeft = leftCount - 1; + final int lastRight = rightCount - 1; + final int grow = dilate ? TEST_DILATION_PIXELS : 0; + final int rowMin = polyMinRow; + final int rowMax = polyMaxRow; + final int firstRow = rowMin - grow; + final int lastRow = rowMax + grow; + final int emptyLeft = pixelWidth; + final int screenRight = lastPixelX; - final long la = leftStep[0], lb = leftStep[1], lc = leftStep[2]; - final long ra = rightStep[0], rb = rightStep[1], rc = rightStep[2]; - long lax = leftX0[0] + la * y0, lbx = leftX0[1] + lb * y0, lcx = leftX0[2] + lc * y0; - long rax = rightX0[0] + ra * y0, rbx = rightX0[1] + rb * y0, rcx = rightX0[2] + rc * y0; - final boolean noLeft = leftCount == 0; - final boolean noRight = rightCount == 0; + // the chains ascend, as do the rows, so the active edge only ever moves forward + final int firstActive = y0 < rowMin ? rowMin : (y0 > rowMax ? rowMax : y0); + int li = 0, ri = 0; + while (li < lastLeft && firstActive > leftEnd[li]) li++; + while (ri < lastRight && firstActive > rightEnd[ri]) ri++; + long lx0 = lastLeft < 0 ? 0 : leftX0[li], ls = lastLeft < 0 ? 0 : leftStep[li]; + long rx0 = lastRight < 0 ? 0 : rightX0[ri], rs = lastRight < 0 ? 0 : rightStep[ri]; + int lEnd = li < lastLeft ? leftEnd[li] : Integer.MAX_VALUE; + int rEnd = ri < lastRight ? rightEnd[ri] : Integer.MAX_VALUE; - for (int y = y0 << 1, limit = (y0 + 7) << 1; y <= limit; y += 2) { - final long l = lax > lbx ? lax : lbx; - final long left = lcx > l ? lcx : l; - final long r = rax < rbx ? rax : rbx; - final long right = rcx < r ? rcx : r; + int maxLeft = Integer.MIN_VALUE, minRight = Integer.MAX_VALUE; + int minLeft = Integer.MAX_VALUE, maxRight = Integer.MIN_VALUE; - eventData[y] = noLeft ? 0 : (int) (left >> 20); - eventData[y + 1] = noRight ? pixelWidth : (int) (right >> 20); + for (int y = y0, i = y0 << 1, end = y0 + 8; y < end; y++, i += 2) { + int l, r; - lax += la; - lbx += lb; - lcx += lc; - rax += ra; - rbx += rb; - rcx += rc; + if (y < firstRow || y > lastRow) { + l = emptyLeft; + r = -1; + } else { + final int ey = y < rowMin ? rowMin : (y > rowMax ? rowMax : y); + + if (ey > lEnd) { + li++; + lx0 = leftX0[li]; + ls = leftStep[li]; + lEnd = li < lastLeft ? leftEnd[li] : Integer.MAX_VALUE; + } + + if (ey > rEnd) { + ri++; + rx0 = rightX0[ri]; + rs = rightStep[ri]; + rEnd = ri < lastRight ? rightEnd[ri] : Integer.MAX_VALUE; + } + + l = (lastLeft < 0 ? 0 : (int) ((lx0 + ls * ey) >> 20)) - grow; + r = (lastRight < 0 ? screenRight : (int) ((rx0 + rs * ey) >> 20)) + grow; + + if (l < minLeft) minLeft = l; + if (r > maxRight) maxRight = r; + } + + eventData[i] = l; + eventData[i + 1] = r; + if (l > maxLeft) maxLeft = l; + if (r < minRight) minRight = r; } - for (int i = 0; i < flatCount; i++) { - populateFlatEvents(flatPositions[i], flatSlots[i]); + setBandRanges(maxLeft, minRight, minLeft, maxRight); + } + + /** Derives the band's interior and extent tile columns from its narrowest and widest row spans. */ + private void setBandRanges(int maxLeft, int minRight, int minLeft, int maxRight) { + bandInnerFirst = (maxLeft + 7) >> TILE_AXIS_SHIFT; + bandInnerLast = (minRight - 7) >> TILE_AXIS_SHIFT; + + if (minLeft <= maxRight) { + bandOuterFirst = Math.max(minLeft, 0) >> TILE_AXIS_SHIFT; + bandOuterLast = Math.min(maxRight, lastPixelX) >> TILE_AXIS_SHIFT; + } else { + // an empty band: its extent starts past the row's last tile and ends before its first + bandOuterFirst = tileWidth; + bandOuterLast = -1; } } @@ -1792,38 +2157,36 @@ public abstract class AbstractRasterizer { if (generic) { populateBandGeneric(y0); - } else { - EVENT_FILLERS[eventKey].apply(); + return; } - if (dilate) { - final int[] events = eventData; + EVENT_FILLERS[eventKey].apply(); - for (int y = y0 << 1, limit = (y0 + 7) << 1; y <= limit; y += 2) { - final int l = events[y]; - final int r = events[y + 1]; - - if (l <= r) { - events[y] = l - TEST_DILATION_PIXELS; - events[y + 1] = r + TEST_DILATION_PIXELS; - } - } - } - - // tiles between the widest left event and the narrowest right event are covered on every row + // one pass over the rows dilates test polygons and finds the band's narrowest and widest spans: tiles + // between the widest left event and the narrowest right event are covered on every row, and tiles + // outside the narrowest left and widest right events on none final int[] data = eventData; - final int base = y0 << 1; - int maxLeft = data[base]; - int minRight = data[base + 1]; + final int grow = dilate ? TEST_DILATION_PIXELS : 0; + int maxLeft = Integer.MIN_VALUE, minRight = Integer.MAX_VALUE; + int minLeft = Integer.MAX_VALUE, maxRight = Integer.MIN_VALUE; + + for (int i = y0 << 1, limit = i + 16; i < limit; i += 2) { + int l = data[i]; + int r = data[i + 1]; + + if (l <= r) { + l -= grow; + r += grow; + data[i] = l; + data[i + 1] = r; + if (l < minLeft) minLeft = l; + if (r > maxRight) maxRight = r; + } - for (int i = base + 2; i < base + 16; i += 2) { - final int l = data[i]; - final int r = data[i + 1]; if (l > maxLeft) maxLeft = l; if (r < minRight) minRight = r; } - bandInnerFirst = (maxLeft + 7) >> TILE_AXIS_SHIFT; - bandInnerLast = (minRight - 7) >> TILE_AXIS_SHIFT; + setBandRanges(maxLeft, minRight, minLeft, maxRight); } } diff --git a/common/src/main/java/grondag/bitraster/BoxOccluder.java b/common/src/main/java/grondag/bitraster/BoxOccluder.java index bb5d2f61d..245b3066e 100644 --- a/common/src/main/java/grondag/bitraster/BoxOccluder.java +++ b/common/src/main/java/grondag/bitraster/BoxOccluder.java @@ -992,12 +992,12 @@ public abstract class BoxOccluder { /** * 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 + * @param tileWidth tiles across, see {@link Constants#DEFAULT_SIZE_TILES} + * @param tileHeight tiles down, likewise */ - public final void resizeBuffer(int widthBits, int heightBits) { - if (widthBits != raster.widthBits() || heightBits != raster.heightBits()) { - raster.resize(widthBits, heightBits); + public final void resizeBuffer(int tileWidth, int tileHeight) { + if (tileWidth != raster.tileWidth() || tileHeight != raster.tileHeight()) { + raster.resize(tileWidth, tileHeight); forceRedraw = true; } } @@ -1014,13 +1014,49 @@ public abstract class BoxOccluder { regionSquaredChunkDist = squaredChunkDistance; // PERF: could perhaps reuse CameraRelativeCenter values in BuildRenderRegion that are used by Frustum - offsetX = (int) ((originX << CAMERA_PRECISION_BITS) - viewX); - offsetY = (int) ((originY << CAMERA_PRECISION_BITS) - viewY); - offsetZ = (int) ((originZ << CAMERA_PRECISION_BITS) - viewZ); + offsetX = (int) (((long) originX << CAMERA_PRECISION_BITS) - viewX); + offsetY = (int) (((long) originY << CAMERA_PRECISION_BITS) - viewY); + offsetZ = (int) (((long) originZ << CAMERA_PRECISION_BITS) - viewZ); raster.setRegionOffset(offsetX, offsetY, offsetZ); } + /** + * Screen tile bounds of a world-space box for the current scene, as {@link AbstractRasterizer#boxTileBounds} + * packs them. Does not disturb the region prepared by {@link #prepareRegion}. + */ + public final long boxTileBounds(int originX, int originY, int originZ, int sizeX, int sizeY, int sizeZ) { + final float scale = 1f / CAMERA_PRECISION_UNITY; + final float fx = (int) (((long) originX << CAMERA_PRECISION_BITS) - viewX) * scale; + final float fy = (int) (((long) originY << CAMERA_PRECISION_BITS) - viewY) * scale; + final float fz = (int) (((long) originZ << CAMERA_PRECISION_BITS) - viewZ) * scale; + return raster.boxTileBounds(fx, fy, fz, sizeX, sizeY, sizeZ); + } + + /** Writes the clip-space x, y and w of a world-space point for the current scene; see {@link AbstractRasterizer#clipPoint}. */ + public final void clipPoint(int x, int y, int z, float[] out, int offset) { + final float scale = 1f / CAMERA_PRECISION_UNITY; + final float fx = (int) (((long) x << CAMERA_PRECISION_BITS) - viewX) * scale; + final float fy = (int) (((long) y << CAMERA_PRECISION_BITS) - viewY) * scale; + final float fz = (int) (((long) z << CAMERA_PRECISION_BITS) - viewZ) * scale; + raster.clipPoint(fx, fy, fz, out, offset); + } + + /** See {@link AbstractRasterizer#isSectionCenterOnScreen}. */ + public final boolean isSectionCenterOnScreen(float[] base, int offset, int i, int j, int k) { + return raster.isSectionCenterOnScreen(base, offset, i, j, k); + } + + /** See {@link AbstractRasterizer#touchedVersion}. */ + public final int touchedVersion() { + return raster.touchedVersion(); + } + + /** See {@link AbstractRasterizer#isTileBoxUntouched}. */ + public final boolean isTileBoxUntouched(int packedTileBounds) { + return raster.isTileBoxUntouched(packedTileBounds); + } + /** * Check if needs redrawn and prep for redraw if so. * When false, regions should be drawn only if their occluder version is not current. @@ -1127,7 +1163,8 @@ public abstract class BoxOccluder { final int[] silhouette = SILHOUETTES[outcome]; if (silhouette != null && raster.setupBoxVertices(silhouette, x0, y0, z0, x1, y1, z1)) { - return raster.isPolygonPartiallyClear(silhouette, silhouette.length); + return raster.isAnyVertexPixelClear(silhouette, silhouette.length) + || raster.isPolygonPartiallyClear(silhouette, silhouette.length); } return partiallyClearTests[outcome].apply(x0, y0, z0, x1, y1, z1); diff --git a/common/src/main/java/grondag/bitraster/Constants.java b/common/src/main/java/grondag/bitraster/Constants.java index 282544a93..06f72bae5 100644 --- a/common/src/main/java/grondag/bitraster/Constants.java +++ b/common/src/main/java/grondag/bitraster/Constants.java @@ -23,7 +23,7 @@ public class Constants { public static final int WEST = 1 << 4; public static final int NORTH = 1 << 2; public static final int SOUTH = 1 << 3; - static final int TILE_AXIS_SHIFT = 3; + public static final int TILE_AXIS_SHIFT = 3; static final int TILE_AXIS_MASK = ~((1 << TILE_AXIS_SHIFT) - 1); static final int TILE_PIXEL_DIAMETER = 1 << TILE_AXIS_SHIFT; static final int TILE_PIXEL_INDEX_MASK = TILE_PIXEL_DIAMETER - 1; @@ -36,10 +36,13 @@ public class Constants { static final int SCANT_PRECISE_PIXEL_CENTER = PRECISE_PIXEL_CENTER - 1; // CELERITAS: the buffer size is chosen per rasterizer and per axis (see AbstractRasterizer.resize); upstream // fixed it at 2048px square. - /** Occlusion buffer size along one axis in tiles, as a power of two: 6 = 512 px, 7 = 1024 px, 8 = 2048 px. */ - public static final int MIN_SIZE_BITS = 6; - public static final int DEFAULT_SIZE_BITS = 7; - public static final int MAX_SIZE_BITS = 8; + /** + * Occlusion buffer size along one axis in tiles of eight pixels. Any width in range is allowed, not just + * powers of two, so an axis can be sized to what the search distance needs without rounding up to double it. + */ + public static final int MIN_SIZE_TILES = 64; + public static final int DEFAULT_SIZE_TILES = 128; + public static final int MAX_SIZE_TILES = 256; // CELERITAS: pixels added on every side of a tested polygon so that a visible strip narrower than the pixel // pitch still reaches a sampled pixel centre. One pixel covers centre sampling exactly; occluders are never grown. diff --git a/common/src/main/java/grondag/bitraster/OrthoRasterizer.java b/common/src/main/java/grondag/bitraster/OrthoRasterizer.java index f50959e7f..14cc0b3b6 100644 --- a/common/src/main/java/grondag/bitraster/OrthoRasterizer.java +++ b/common/src/main/java/grondag/bitraster/OrthoRasterizer.java @@ -17,7 +17,7 @@ package grondag.bitraster; import static grondag.bitraster.Constants.PROJECTED_VERTEX_STRIDE; -import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS; +import static grondag.bitraster.Constants.DEFAULT_SIZE_TILES; import static grondag.bitraster.Constants.PV_PX; import static grondag.bitraster.Constants.PV_PY; import static grondag.bitraster.Constants.PV_X; @@ -25,11 +25,11 @@ import static grondag.bitraster.Constants.PV_Y; public final class OrthoRasterizer extends AbstractRasterizer { public OrthoRasterizer() { - this(DEFAULT_SIZE_BITS, DEFAULT_SIZE_BITS); + this(DEFAULT_SIZE_TILES, DEFAULT_SIZE_TILES); } - public OrthoRasterizer(int widthBits, int heightBits) { - super(widthBits, heightBits); + public OrthoRasterizer(int tileWidth, int tileHeight) { + super(tileWidth, tileHeight); } @Override diff --git a/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java b/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java index fba162c35..095559d5a 100644 --- a/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java +++ b/common/src/main/java/grondag/bitraster/PerspectiveRasterizer.java @@ -16,7 +16,7 @@ package grondag.bitraster; -import static grondag.bitraster.Constants.DEFAULT_SIZE_BITS; +import static grondag.bitraster.Constants.DEFAULT_SIZE_TILES; import static grondag.bitraster.Constants.BOUNDS_IN; import static grondag.bitraster.Constants.BOUNDS_OUTSIDE_OR_TOO_SMALL; import static grondag.bitraster.Constants.EVENT_POSITION_MASK; @@ -48,11 +48,11 @@ import static grondag.bitraster.Constants.SCANT_PRECISE_PIXEL_CENTER; public final class PerspectiveRasterizer extends AbstractRasterizer { public PerspectiveRasterizer() { - this(DEFAULT_SIZE_BITS, DEFAULT_SIZE_BITS); + this(DEFAULT_SIZE_TILES, DEFAULT_SIZE_TILES); } - public PerspectiveRasterizer(int widthBits, int heightBits) { - super(widthBits, heightBits); + public PerspectiveRasterizer(int tileWidth, int tileHeight) { + super(tileWidth, tileHeight); } /** Holds results of {@link #clipNear(int, int)}. */ @@ -77,8 +77,8 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { if (w != 0) { final float iw = 1f / w; - final int px = Math.round(tx * iw * halfPreciseWidth) + halfPreciseWidth; - final int py = Math.round(ty * iw * halfPreciseHeight) + halfPreciseHeight; + final int px = roundToInt(tx * iw * halfPreciseWidth) + halfPreciseWidth; + final int py = roundToInt(ty * iw * halfPreciseHeight) + halfPreciseHeight; data[baseIndex + PV_PX] = px; data[baseIndex + PV_PY] = py; @@ -90,32 +90,28 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { transformBoxCorners(x0, y0, z0, x1, y1, z1); final int[] data = vertexData; - final float[] cx = cornerX, cy = cornerY, cz = cornerZ, cw = cornerW; - boolean unclipped = true; + final float[] cx = cornerX, cy = cornerY, cw = cornerW, cz = cornerZ; + final int halfPreciseWidth = this.halfPreciseWidth; + final int halfPreciseHeight = this.halfPreciseHeight; + // only the projected position is stored: the clip-space coordinates are needed by the near-clip + // fallback alone, and that path recomputes every vertex it uses through setupVertex 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); + final float tz = cz[corner]; // 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; + if (!(w > 0 && tz > 0 && tz <= w)) { + return false; } + + final float iw = 1f / w; + data[baseIndex + PV_PX] = roundToInt(cx[corner] * iw * halfPreciseWidth) + halfPreciseWidth; + data[baseIndex + PV_PY] = roundToInt(cy[corner] * iw * halfPreciseHeight) + halfPreciseHeight; } - return unclipped; + return true; } @Override @@ -162,8 +158,8 @@ public final class PerspectiveRasterizer extends AbstractRasterizer { final float w = (intW + (extW - intW) * wt); final float iw = 1f / w; - clipX = Math.round(iw * x * halfPreciseWidth) + halfPreciseWidth; - clipY = Math.round(iw * y * halfPreciseHeight) + halfPreciseHeight; + clipX = roundToInt(iw * x * halfPreciseWidth) + halfPreciseWidth; + clipY = roundToInt(iw * y * halfPreciseHeight) + halfPreciseHeight; } @Override diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java index 620d71fa2..ca7c18e62 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java @@ -68,6 +68,7 @@ public final class PackedSectionMetadata { private static final long PENDING_UPDATE_MASK = 0b111L; // Bit 52: a build cancellation token is currently attached. + // Bit 53 is reserved for SectionLattice.OCCLUDER_DATA_FLAG on the lattice's copy of the word. private static final int BUILD_IN_FLIGHT_BIT = 52; private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT; diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java index 163fd4a14..e39acbf74 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java @@ -1,5 +1,6 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion; +import grondag.bitraster.AbstractRasterizer; import grondag.bitraster.PackedBox; import org.embeddedt.embeddium.impl.common.util.MathUtil; import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex; @@ -192,7 +193,7 @@ public class OcclusionCuller { this.rasterActive = this.rasterOccluder != null && useOcclusionCulling && viewport.getVpMatrix() != null; if (this.rasterActive) { - this.rasterOccluder.prepareScene(frame, viewport, searchDistance); + this.rasterOccluder.prepareScene(frame, viewport, searchDistance, numRegions); } this.process(visitor, viewport, searchDistance, useOcclusionCulling, allowFrustumClamping, frame); @@ -263,10 +264,10 @@ public class OcclusionCuller { int regionId = regionOfCell[idx]; long sm = sectionMeta[idx]; int compactMeta = PackedSectionMetadata.toCompactMeta(sm); - int classification = cache.classify(regionId, - regionOrigin(chunkX, RenderRegion.REGION_WIDTH_SH, RenderRegion.REGION_BLOCK_WIDTH), - regionOrigin(chunkY, RenderRegion.REGION_HEIGHT_SH, RenderRegion.REGION_BLOCK_HEIGHT), - regionOrigin(chunkZ, RenderRegion.REGION_LENGTH_SH, RenderRegion.REGION_BLOCK_LENGTH)); + int regionX = regionOrigin(chunkX, RenderRegion.REGION_WIDTH_SH, RenderRegion.REGION_BLOCK_WIDTH); + int regionY = regionOrigin(chunkY, RenderRegion.REGION_HEIGHT_SH, RenderRegion.REGION_BLOCK_HEIGHT); + int regionZ = regionOrigin(chunkZ, RenderRegion.REGION_LENGTH_SH, RenderRegion.REGION_BLOCK_LENGTH); + int classification = cache.classify(regionId, regionX, regionY, regionZ); // Fully-inside regions need no per-section tests and outside regions // are not traversed. Sections in a partial region are checked @@ -301,7 +302,8 @@ public class OcclusionCuller { boolean traverse = visible; if (this.rasterActive && visible) { - RasterOccluder.SectionVisibility result = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, compactMeta); + RasterOccluder.SectionVisibility result = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, + compactMeta, (sm & SectionLattice.OCCLUDER_DATA_FLAG) != 0, regionId, regionX, regionY, regionZ); visible = result == RasterOccluder.SectionVisibility.VISIBLE; traverse = result != RasterOccluder.SectionVisibility.HIDDEN; } @@ -356,7 +358,19 @@ public class OcclusionCuller { this.visibleCount = visibleCount; } - private RasterOccluder.SectionVisibility rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, int meta) { + private RasterOccluder.SectionVisibility rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, + int meta, boolean hasOccluderData, + int regionId, int regionX, int regionY, int regionZ) { + var occluder = this.rasterOccluder; + + // A section with nothing to draw is visible wherever nothing has been drawn. One with geometry is + // tested against the bounds of what it draws, which may lie off screen even though the section is + // in the frustum, and that cull is worth keeping; such sections are rare above the horizon anyway. + if (!hasOccluderData && occluder.isSectionUntouched(regionId, regionX, regionY, regionZ, chunkX, chunkY, chunkZ)) { + if (AbstractRasterizer.STATS) RasterOccluder.STAT_REGION_SKIP++; + return RasterOccluder.SectionVisibility.VISIBLE; + } + int dx = chunkX - camX; int dy = chunkY - camY; int dz = chunkZ - camZ; @@ -365,15 +379,13 @@ public class OcclusionCuller { boolean hasGeometry = (PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0; - int[] data = this.lattice.occluderData[idx]; + // the flag spares the many sections without data the loads below, which rarely hit cache + int bounds = hasOccluderData ? this.lattice.occluderBounds[idx] : PackedBox.FULL_BOX; - int bounds = data != null ? OccluderBoxBuilder.bounds(data) : PackedBox.FULL_BOX; - - var occluder = this.rasterOccluder; RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds); - if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && data != null) { - occluder.occludeSection(data); + if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && hasOccluderData) { + occluder.occludeSection(this.lattice.occluderData[idx]); } return result; diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java index ec65940fc..7becbb62a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java @@ -6,17 +6,48 @@ import grondag.bitraster.Constants; import grondag.bitraster.Matrix4L; import grondag.bitraster.PackedBox; import grondag.bitraster.PerspectiveRasterizer; +import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.viewport.Viewport; import org.joml.Matrix4fc; +import java.util.Arrays; + 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 */ public static final int NEAR_SQUARED_CHUNK_DIST = 3; private int backtrackCount; + /** + * Per-region screen bounds for the current scene, so that sections of a region whose screen area has + * had nothing drawn in it yet are visible without a test of their own. Most of the sections a surface + * camera reaches are sky, and nothing ever gets drawn above the horizon, so this resolves most of them. + * + *

{@code regionScene} stamps the scene the bounds were computed for. {@code regionVersion} holds the + * touched-map version at which the bounds were last found untouched, or {@link #REGION_TOUCHED} once they + * were not: drawing only ever adds coverage, so that verdict is final for the scene. A region that is not + * wholly on screen keeps the clip-space position of its first section centre in {@code regionClip}, from + * which any section centre's on-screen test is a few multiplies. + */ + private int[] regionScene = new int[0]; + private int[] regionTiles = new int[0]; + private int[] regionVersion = new int[0]; + private byte[] regionState = new byte[0]; + private float[] regionClip = new float[0]; + private int scene; + + /** {@code regionVersion} values that never match a touched-map version. */ + private static final int REGION_TOUCHED = -1, REGION_UNVERIFIED = -2; + + /** The region reaches the near plane or lies wholly off screen; its sections are all tested. */ + private static final byte REGION_NO_BOUNDS = 0; + /** The region straddles a screen edge; each section centre is checked against the screen. */ + private static final byte REGION_PARTLY_ON_SCREEN = 1; + /** Every point of the region is on screen. */ + private static final byte REGION_ON_SCREEN = 2; + /** 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_CENTER_HIT, STAT_AIR_TESTS, STAT_AIR_VISIBLE, STAT_NEAR, STAT_REGION_SKIP; public static long STAT_TEST_NANOS, STAT_OCCLUDE_NANOS, STAT_SECTIONS, STAT_OCCLUDED_SECTIONS; public enum SectionVisibility { @@ -48,7 +79,7 @@ public final class RasterOccluder extends BoxOccluder { * camera translation, so it is supplied as the projection with an identity model matrix; * {@link #prepareRegion} applies the camera-relative offset per section. */ - public void prepareScene(int viewVersion, Viewport viewport, float searchDistance) { + public void prepareScene(int viewVersion, Viewport viewport, float searchDistance, int numRegions) { Matrix4fc vpMatrix = viewport.getVpMatrix(); if (vpMatrix == null) { @@ -58,6 +89,16 @@ public final class RasterOccluder extends BoxOccluder { var transform = viewport.getTransform(); this.backtrackCount = 0; + this.scene++; + + if (this.regionScene.length < numRegions) { + int capacity = Math.max(numRegions, this.regionScene.length * 2); + this.regionScene = Arrays.copyOf(this.regionScene, capacity); + this.regionTiles = Arrays.copyOf(this.regionTiles, capacity); + this.regionVersion = Arrays.copyOf(this.regionVersion, capacity); + this.regionState = Arrays.copyOf(this.regionState, capacity); + this.regionClip = Arrays.copyOf(this.regionClip, capacity * 3); + } chooseBufferSize(vpMatrix, searchDistance); invalidate(); @@ -74,8 +115,9 @@ public final class RasterOccluder extends BoxOccluder { * 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. * - *

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. + *

Sizes are not limited to powers of two, so each axis holds close to what it needs rather than up to + * double it. An axis only grows when the current buffer falls short and only shrinks when it is more + * than a step above what is needed, 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 @@ -92,35 +134,102 @@ public final class RasterOccluder extends BoxOccluder { 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); + // pixels per block at distance d along an axis is size * scale / (2d) + float required = 2.0f * searchDistance * PIXELS_PER_BLOCK; + int widthTiles = chooseAxisTiles(bufferWidth() >> Constants.TILE_AXIS_SHIFT, required / scaleX); + int heightTiles = chooseAxisTiles(bufferHeight() >> Constants.TILE_AXIS_SHIFT, required / scaleY); + resizeBuffer(widthTiles, heightTiles); } - private static int chooseAxisBits(int currentPixels, float requiredPixels) { - int current = Integer.numberOfTrailingZeros(currentPixels) - 3; + /** + * Grows an axis to the smallest step that meets its requirement, and shrinks it only to one step above + * the requirement, so the two thresholds never meet: a requirement wavering about a step boundary neither + * grows nor shrinks the axis, and a sweeping field of view resizes at most once per step. + */ + private static int chooseAxisTiles(int currentTiles, float requiredPixels) { + int required = tilesFor(requiredPixels); - if (requiredPixels > currentPixels) { - int bits = current; + if (required > currentTiles) { + return required; + } - while (bits < Constants.MAX_SIZE_BITS && (8 << bits) < requiredPixels) { - bits++; + int shrunk = Math.min(Constants.MAX_SIZE_TILES, required + SIZE_STEP_TILES); + + return shrunk < currentTiles ? shrunk : currentTiles; + } + + /** Tiles needed to hold the given pixels, rounded up to {@link #SIZE_STEP_TILES} and clamped to the buffer limits. */ + private static int tilesFor(float pixels) { + int tiles = ((int) Math.ceil(pixels / (8 * SIZE_STEP_TILES))) * SIZE_STEP_TILES; + + return Math.max(Constants.MIN_SIZE_TILES, Math.min(Constants.MAX_SIZE_TILES, tiles)); + } + + /** Axis sizes are multiples of this many tiles (64 pixels). */ + private static final int SIZE_STEP_TILES = 8; + + /** + * Pixels a block at the search distance must span along each axis. Halving this measured within a few + * percent of the same frame time and culled within a few sections of the same count on the synthetic + * worlds, so the buffer is not sized for speed: this is what keeps a one-block gap between occluders + * from closing under pixel-centre sampling. + */ + private static final float PIXELS_PER_BLOCK = 1.0f; + + /** + * True if nothing has been drawn where the region projects and the given section's centre is on screen, + * in which case the section is visible: its centre pixel lies inside the region's screen rectangle, and + * an untouched pixel on screen is exactly what the centre test looks for. Costs one compare per section + * once the region's bounds are known, plus a few multiplies when the region is not wholly on screen, and + * a re-check of a handful of cell rows whenever something new has been drawn since. + */ + public boolean isSectionUntouched(int regionId, int originX, int originY, int originZ, int chunkX, int chunkY, int chunkZ) { + final int[] regionVersion = this.regionVersion; + + if (this.regionScene[regionId] != this.scene) { + this.regionScene[regionId] = this.scene; + long bounds = boxTileBounds(originX, originY, originZ, + RenderRegion.REGION_BLOCK_WIDTH, RenderRegion.REGION_BLOCK_HEIGHT, RenderRegion.REGION_BLOCK_LENGTH); + this.regionTiles[regionId] = (int) bounds; + regionVersion[regionId] = REGION_UNVERIFIED; + + if (bounds == AbstractRasterizer.NO_TILE_BOUNDS) { + this.regionState[regionId] = REGION_NO_BOUNDS; + } else if ((bounds & AbstractRasterizer.TILE_BOUNDS_ON_SCREEN) != 0) { + this.regionState[regionId] = REGION_ON_SCREEN; + } else { + this.regionState[regionId] = REGION_PARTLY_ON_SCREEN; + clipPoint(originX + 8, originY + 8, originZ + 8, this.regionClip, regionId * 3); + } + } + + final byte state = this.regionState[regionId]; + + if (state == REGION_NO_BOUNDS) { + return false; + } + + final int version = regionVersion[regionId]; + final int current = touchedVersion(); + + if (version != current) { + if (version == REGION_TOUCHED) { + return false; } - return bits; + if (!isTileBoxUntouched(this.regionTiles[regionId])) { + regionVersion[regionId] = REGION_TOUCHED; + return false; + } + + regionVersion[regionId] = current; } - if (current > Constants.MIN_SIZE_BITS && requiredPixels * SHRINK_MARGIN <= (currentPixels >> 1)) { - return current - 1; - } - - return current; + return state == REGION_ON_SCREEN + || isSectionCenterOnScreen(this.regionClip, regionId * 3, + chunkX - (originX >> 4), chunkY - (originY >> 4), chunkZ - (originZ >> 4)); } - /** 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 * may still have unoccluded empty space, so a second test decides whether traversal continues. diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index 8c9f08dfe..288dca994 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -143,6 +143,19 @@ public final class SectionLattice { * does not chase section and build-data pointers for every cell it visits. Null when absent. */ int[][] occluderData; + + /** + * The packed bounds word of each cell's occluder data, mirrored densely so the raster test reads one + * array instead of chasing the pointer above into a second cache line; only a draw needs the boxes. + */ + int[] occluderBounds; + + /** + * Set in a cell's {@link #sectionMeta} word when it has occluder data, so the raster test can skip the + * pointer load for the many cells, most of them sky, that have none. Bit 53 is outside every field of + * {@link PackedSectionMetadata}, and every reader masks the fields it wants. + */ + static final long OCCLUDER_DATA_FLAG = 1L << 53; RenderSection[] latticeSection; // Queue entries ((packedLocalXYZ << 32) | latticeIndex) of the cells the last main search reported visible, in @@ -277,8 +290,10 @@ public final class SectionLattice { } long previous = this.sectionMeta[idx]; - this.sectionMeta[idx] = packedMetadata; - this.occluderData[idx] = occluderDataOf(this.latticeSection[idx]); + int[] data = occluderDataOf(this.latticeSection[idx]); + this.sectionMeta[idx] = withOccluderFlag(packedMetadata, data); + this.occluderData[idx] = data; + this.occluderBounds[idx] = boundsOf(data); return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; } @@ -547,6 +562,7 @@ public final class SectionLattice { this.regionOfCell = new int[slots]; this.latticeSection = new RenderSection[slots]; this.occluderData = new int[slots][]; + this.occluderBounds = new int[slots]; // Existing coordinates are no longer valid after resizing; the next // ensureWindowCovers must rebase and reinstall every attached section. @@ -566,6 +582,7 @@ public final class SectionLattice { Arrays.fill(this.regionOfCell, -1); Arrays.fill(this.latticeSection, null); Arrays.fill(this.occluderData, null); + Arrays.fill(this.occluderBounds, 0); this.baseX = newBaseX; this.baseZ = newBaseZ; @@ -646,6 +663,7 @@ public final class SectionLattice { System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len); System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, len); + System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, len); } /** @@ -680,6 +698,7 @@ public final class SectionLattice { System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen); System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, runLen); + System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, runLen); } } @@ -766,6 +785,7 @@ public final class SectionLattice { this.regionOfCell[idx] = -1; this.latticeSection[idx] = null; this.occluderData[idx] = null; + this.occluderBounds[idx] = 0; RenderSection section = this.sections.get( PositionUtil.packSection(worldX, this.baseY + ly, worldZ)); @@ -818,6 +838,14 @@ public final class SectionLattice { return built != null ? built.occluderBoxes : null; } + private static int boundsOf(int @Nullable [] occluderData) { + return occluderData != null ? OccluderBoxBuilder.bounds(occluderData) : 0; + } + + private static long withOccluderFlag(long packedMetadata, int @Nullable [] occluderData) { + return occluderData != null ? packedMetadata | OCCLUDER_DATA_FLAG : packedMetadata; + } + private void install(RenderSection section) { if (this.visitState == null) { return; @@ -835,8 +863,10 @@ public final class SectionLattice { } this.latticeSection[idx] = section; this.regionOfCell[idx] = section.getRegion().getId(); - this.sectionMeta[idx] = section.getPackedMetadata(); - this.occluderData[idx] = occluderDataOf(section); + int[] data = occluderDataOf(section); + this.sectionMeta[idx] = withOccluderFlag(section.getPackedMetadata(), data); + this.occluderData[idx] = data; + this.occluderBounds[idx] = boundsOf(data); this.installedCount++; } @@ -857,6 +887,7 @@ public final class SectionLattice { this.regionOfCell[idx] = -1; this.latticeSection[idx] = null; this.occluderData[idx] = null; + this.occluderBounds[idx] = 0; this.installedCount--; } } -- 2.54.1 From 2545927343f830bb6ce420c42079f4e4c0c37dca Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 20:07:07 -0400 Subject: [PATCH 13/20] Define occluder data flag properly --- .../render/chunk/PackedSectionMetadata.java | 28 +++++++++++++++---- .../impl/render/chunk/RenderSection.java | 5 ++-- .../chunk/occlusion/OcclusionCuller.java | 2 +- .../chunk/occlusion/SectionLattice.java | 19 ++++--------- 4 files changed, 31 insertions(+), 23 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java index ca7c18e62..405517817 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java @@ -15,10 +15,10 @@ import org.jetbrains.annotations.Nullable; * *

Bit layout: *

- * 63                 53 52 51       49 48      46 45                0
- * +--------------------+--+-----------+----------+-------------------+
- * |       spare        |IF| pending   | visuals  | visibility graph  |
- * +--------------------+--+-----------+----------+-------------------+
+ * 63                 54 53 52 51       49 48      46 45                0
+ * +--------------------+--+--+-----------+----------+-------------------+
+ * |       spare        |OD|IF| pending   | visuals  | visibility graph  |
+ * +--------------------+--+--+-----------+----------+-------------------+
  * 
*
    *
  • Bits {@code 0..45}: {@link VisibilityEncoding} entries. Entry @@ -30,7 +30,8 @@ import org.jetbrains.annotations.Nullable; *
  • Bits {@code 49..51}: pending update type; zero means none, otherwise * {@code ChunkUpdateType.ordinal() + 1}.
  • *
  • Bit {@code 52}: a build is in flight.
  • - *
  • Bits {@code 53..63}: reserved.
  • + *
  • Bit {@code 53}: the section's built data has occluder boxes.
  • + *
  • Bits {@code 54..63}: reserved.
  • *
* *

The visibility graph uses only bits {@code 0..45}, but @@ -68,10 +69,13 @@ public final class PackedSectionMetadata { private static final long PENDING_UPDATE_MASK = 0b111L; // Bit 52: a build cancellation token is currently attached. - // Bit 53 is reserved for SectionLattice.OCCLUDER_DATA_FLAG on the lattice's copy of the word. private static final int BUILD_IN_FLIGHT_BIT = 52; private static final long BUILD_IN_FLIGHT_FLAG = 1L << BUILD_IN_FLIGHT_BIT; + // Bit 53: the section's built data has occluder boxes. + private static final int HAS_OCCLUDER_DATA_BIT = 53; + private static final long HAS_OCCLUDER_DATA_FLAG = 1L << HAS_OCCLUDER_DATA_BIT; + /** Returns only the visibility graph field. */ public static long getVisibilityData(long packed) { return packed & VISIBILITY_MASK; @@ -126,6 +130,18 @@ public final class PackedSectionMetadata { return (packed & BUILD_IN_FLIGHT_FLAG) != 0; } + /** Returns whether the section's built data has occluder boxes. */ + public static boolean hasOccluderData(long packed) { + return (packed & HAS_OCCLUDER_DATA_FLAG) != 0; + } + + /** + * Replaces the has-occluder-data flag and preserves every other field. + */ + public static long withHasOccluderData(long packed, boolean hasOccluderData) { + return hasOccluderData ? (packed | HAS_OCCLUDER_DATA_FLAG) : (packed & ~HAS_OCCLUDER_DATA_FLAG); + } + /* * Compact collector metadata: includes only the info the VisibleChunkCollector cares about. * diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java index 95afcf0f1..4aa1ae8f7 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/RenderSection.java @@ -143,9 +143,10 @@ public class RenderSection extends AbstractSection { public void updateCachedContextDataFlags() { int flags = this.contextData != null ? this.contextData.getVisualBitmaskForSection() : 0; long visibilityData = this.contextData != null ? this.contextData.visibilityData : VisibilityEncoding.NULL; + boolean hasOccluderData = this.contextData != null && this.contextData.occluderBoxes != null; - this.writeMetadata(PackedSectionMetadata.withVisibilityData( - PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData)); + this.writeMetadata(PackedSectionMetadata.withHasOccluderData(PackedSectionMetadata.withVisibilityData( + PackedSectionMetadata.withVisualsFlags(this.packedMetadata, flags), visibilityData), hasOccluderData)); } // The sole writer of packedMetadata: stores the new word and notifies the mirror. diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java index e39acbf74..d3da266db 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java @@ -303,7 +303,7 @@ public class OcclusionCuller { if (this.rasterActive && visible) { RasterOccluder.SectionVisibility result = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, - compactMeta, (sm & SectionLattice.OCCLUDER_DATA_FLAG) != 0, regionId, regionX, regionY, regionZ); + compactMeta, PackedSectionMetadata.hasOccluderData(sm), regionId, regionX, regionY, regionZ); visible = result == RasterOccluder.SectionVisibility.VISIBLE; traverse = result != RasterOccluder.SectionVisibility.HIDDEN; } diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index 288dca994..8bf42b3d7 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -150,12 +150,6 @@ public final class SectionLattice { */ int[] occluderBounds; - /** - * Set in a cell's {@link #sectionMeta} word when it has occluder data, so the raster test can skip the - * pointer load for the many cells, most of them sky, that have none. Bit 53 is outside every field of - * {@link PackedSectionMetadata}, and every reader masks the fields it wants. - */ - static final long OCCLUDER_DATA_FLAG = 1L << 53; RenderSection[] latticeSection; // Queue entries ((packedLocalXYZ << 32) | latticeIndex) of the cells the last main search reported visible, in @@ -290,8 +284,8 @@ public final class SectionLattice { } long previous = this.sectionMeta[idx]; - int[] data = occluderDataOf(this.latticeSection[idx]); - this.sectionMeta[idx] = withOccluderFlag(packedMetadata, data); + this.sectionMeta[idx] = packedMetadata; + int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(this.latticeSection[idx]) : null; this.occluderData[idx] = data; this.occluderBounds[idx] = boundsOf(data); @@ -842,10 +836,6 @@ public final class SectionLattice { return occluderData != null ? OccluderBoxBuilder.bounds(occluderData) : 0; } - private static long withOccluderFlag(long packedMetadata, int @Nullable [] occluderData) { - return occluderData != null ? packedMetadata | OCCLUDER_DATA_FLAG : packedMetadata; - } - private void install(RenderSection section) { if (this.visitState == null) { return; @@ -863,8 +853,9 @@ public final class SectionLattice { } this.latticeSection[idx] = section; this.regionOfCell[idx] = section.getRegion().getId(); - int[] data = occluderDataOf(section); - this.sectionMeta[idx] = withOccluderFlag(section.getPackedMetadata(), data); + long packedMetadata = section.getPackedMetadata(); + this.sectionMeta[idx] = packedMetadata; + int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(section) : null; this.occluderData[idx] = data; this.occluderBounds[idx] = boundsOf(data); this.installedCount++; -- 2.54.1 From 26784eb0e87de0efa8b05728102cd0ed39805476 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 20:19:42 -0400 Subject: [PATCH 14/20] Refactor visibility builder logic --- .../render/chunk/bench/voxel/VoxelSlice.java | 9 ++-- .../chunk/occlusion/OccluderBoxBuilder.java | 50 ------------------- .../chunk/occlusion/SectionLattice.java | 2 +- .../occlusion/SectionVisibilityBuilder.java | 49 ++++++++++++------ .../tasks/ChunkBuilderMeshingTask.java | 32 ++++-------- .../chunk/occlusion/ModernGraphDirection.java | 22 -------- 6 files changed, 49 insertions(+), 115 deletions(-) delete mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java delete mode 100644 modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/occlusion/ModernGraphDirection.java diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java index 76848ff8d..24a1b271a 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/bench/voxel/VoxelSlice.java @@ -1,6 +1,5 @@ package org.embeddedt.embeddium.impl.render.chunk.bench.voxel; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.OccluderBoxBuilder; import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionVisibilityBuilder; import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; @@ -108,7 +107,7 @@ public final class VoxelSlice { return null; } - var builder = new OccluderBoxBuilder(); + var occluder = new SectionVisibilityBuilder(); byte[] blocks = this.blocks; for (int y = 0; y < 16; y++) { @@ -119,17 +118,17 @@ public final class VoxelSlice { int block = blocks[row + x]; if (VoxelWorld.isOpaque(block)) { - builder.markOpaque(x, y, z); + occluder.markOpaque(x, y, z); } if (VoxelWorld.isRenderable(block)) { - builder.markRenderable(x, y, z); + occluder.markRenderable(x, y, z); } } } } - return builder.build(); + return occluder.computeOccluderBoxes(); } public long[] opacityBits() { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java deleted file mode 100644 index 815956855..000000000 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OccluderBoxBuilder.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.embeddedt.embeddium.impl.render.chunk.occlusion; - -import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes; -import org.jetbrains.annotations.Nullable; - -import java.util.Arrays; -import java.util.BitSet; - -// Separate from SectionVisibilityBuilder so a platform whose game already computes the visibility encoding -// can keep using that and supply opacity here instead of paying for a second flood fill it doesn't need -public final class OccluderBoxBuilder { - private final BitSet blocks = new BitSet(SectionVisibilityBuilder.TOTAL_BLOCKS); - private final RenderableBounds bounds = new RenderableBounds(); - - public void markOpaque(int x, int y, int z) { - this.blocks.set(SectionVisibilityBuilder.getIndex(x & 15, y & 15, z & 15)); - } - - public void markRenderable(int x, int y, int z) { - this.bounds.mark(x & 15, y & 15, z & 15); - } - - public int @Nullable [] build() { - return dataFrom(this.blocks, this.bounds); - } - - public static int bounds(int[] data) { - return data[0]; - } - - static int @Nullable [] dataFrom(BitSet blocks, RenderableBounds bounds) { - if (blocks.isEmpty() && bounds.isEmpty()) { - return null; - } - - int[] boxes = blocks.isEmpty() ? null - : OccluderBoxes.from(Arrays.copyOf(blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS)); - - int count = boxes == null ? 0 : boxes.length; - int[] data = new int[count + 1]; - data[0] = bounds.packed(); - - if (boxes != null) { - System.arraycopy(boxes, 0, data, 1, count); - } - - return data; - } -} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index 8bf42b3d7..d515c6542 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -833,7 +833,7 @@ public final class SectionLattice { } private static int boundsOf(int @Nullable [] occluderData) { - return occluderData != null ? OccluderBoxBuilder.bounds(occluderData) : 0; + return occluderData != null ? SectionVisibilityBuilder.bounds(occluderData) : 0; } private void install(RenderSection section) { diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java index 26c07ba9f..c314be17a 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionVisibilityBuilder.java @@ -2,8 +2,11 @@ package org.embeddedt.embeddium.impl.render.chunk.occlusion; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import it.unimi.dsi.fastutil.ints.IntArrayList; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.BoxFinder; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.geometry.OccluderBoxes; import org.jetbrains.annotations.Nullable; +import java.util.Arrays; import java.util.BitSet; /** @@ -28,8 +31,6 @@ public class SectionVisibilityBuilder { private final BitSet blocks; private final RenderableBounds renderableBounds = new RenderableBounds(); - private boolean floodFilled; - private static int[] buildFloodfillIndices() { IntArrayList indicesList = new IntArrayList(TOTAL_BLOCKS - (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2) * (SECTION_AXIS_SIZE - 2)); for (int x = 0; x < SECTION_AXIS_SIZE; x++) { @@ -71,24 +72,45 @@ public class SectionVisibilityBuilder { } public int @Nullable [] computeOccluderBoxes() { - if (this.floodFilled) { - throw new IllegalStateException("opacity was consumed by computeVisibilityEncoding()"); + return dataFrom(this.blocks, this.renderableBounds); + } + + static int bounds(int[] data) { + return data[0]; + } + + private static int @Nullable [] dataFrom(BitSet blocks, RenderableBounds bounds) { + if (blocks.isEmpty() && bounds.isEmpty()) { + return null; } - return OccluderBoxBuilder.dataFrom(this.blocks, this.renderableBounds); + int[] boxes = blocks.isEmpty() ? null + : OccluderBoxes.from(Arrays.copyOf(blocks.toLongArray(), BoxFinder.INTERIOR_CACHE_WORDS)); + + int count = boxes == null ? 0 : boxes.length; + int[] data = new int[count + 1]; + data[0] = bounds.packed(); + + if (boxes != null) { + System.arraycopy(boxes, 0, data, 1, count); + } + + return data; } private long computeWithFloodFill() { - this.floodFilled = true; long resultEncoding = 0; - var blocks = this.blocks; + // The fill marks cells as visited by setting their bit, which would corrupt the opacity data other + // callers (computeOccluderBoxes()) still need. Clone it into scratch space instead of mutating + // this.blocks in place; opaque cells start pre-marked since the fill must not pass through them. + BitSet visited = (BitSet) this.blocks.clone(); BitSet escapedFaces = new BitSet(GraphDirection.COUNT); IntArrayFIFOQueue queue = new IntArrayFIFOQueue(); for (int i : INDICES_TO_INITIATE_FLOODFILL) { - if (!blocks.get(i)) { + if (!visited.get(i)) { escapedFaces.clear(); queue.clear(); - this.exploreFrom(escapedFaces, queue, i); + exploreFrom(visited, escapedFaces, queue, i); for (int dir = escapedFaces.nextSetBit(0); dir >= 0; dir = escapedFaces.nextSetBit(dir+1)) { for (int dir2 = escapedFaces.nextSetBit(0); dir2 >= 0; dir2 = escapedFaces.nextSetBit(dir2+1)) { resultEncoding |= 1L << VisibilityEncoding.bit(dir, dir2); @@ -99,20 +121,19 @@ public class SectionVisibilityBuilder { return resultEncoding; } - private void exploreFrom(BitSet escapedFaces, IntArrayFIFOQueue queue, int startIndex) { + private static void exploreFrom(BitSet visited, BitSet escapedFaces, IntArrayFIFOQueue queue, int startIndex) { queue.enqueue(startIndex); - var blocks = this.blocks; // Mark the start location as handled - blocks.set(startIndex, true); + visited.set(startIndex, true); while (!queue.isEmpty()) { int idx = queue.dequeueInt(); for (int dir = 0; dir < GraphDirection.COUNT; dir++) { int neighborIdx = getNeighborIndex(idx, dir); if (neighborIdx >= 0) { // We can move within the section in that direction - if (!blocks.get(neighborIdx)) { + if (!visited.get(neighborIdx)) { // Mark this location as handled - blocks.set(neighborIdx, true); + visited.set(neighborIdx, true); queue.enqueue(neighborIdx); } } else { diff --git a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java index 499dd35da..6e9879a41 100644 --- a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java +++ b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/compile/tasks/ChunkBuilderMeshingTask.java @@ -11,18 +11,15 @@ import net.minecraft.world.level.block.AirBlock; import org.embeddedt.embeddium.api.render.chunk.SectionInfoBuilder; import org.embeddedt.embeddium.api.render.texture.SpriteUtil; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.ModernChunkBuildContext; -import org.embeddedt.embeddium.impl.modern.render.chunk.occlusion.ModernGraphDirection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.compile.*; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderCache; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderContext; import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.GeometryCategory; import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask; -import org.embeddedt.embeddium.impl.render.chunk.data.BuiltRenderSectionData; import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts; import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.OccluderBoxBuilder; -import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; +import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionVisibilityBuilder; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.util.WorldUtil; import org.embeddedt.embeddium.impl.util.task.CancellationToken; @@ -33,7 +30,6 @@ import net.minecraft.CrashReportCategory; import net.minecraft.ReportedException; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; -import net.minecraft.client.renderer.chunk.VisGraph; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; @@ -83,8 +79,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask public ChunkBuildOutput execute(ChunkBuildContext jobContext, CancellationToken cancellationToken) { ModernChunkBuildContext buildContext = (ModernChunkBuildContext)jobContext; MinecraftBuiltRenderSectionData renderData = new MinecraftBuiltRenderSectionData<>(); - VisGraph occluder = new VisGraph(); - OccluderBoxBuilder occluderBoxes = this.rasterOcclusion ? new OccluderBoxBuilder() : null; + SectionVisibilityBuilder occluder = new SectionVisibilityBuilder(); ChunkBuildBuffers buffers = buildContext.buffers; buffers.init(renderData, this.render.getSectionIndex()); @@ -137,8 +132,8 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask blockPos.set(x, y, z); modelOffset.set(x & 15, y & 15, z & 15); - if (occluderBoxes != null) { - occluderBoxes.markRenderable(x, y, z); + if (this.rasterOcclusion) { + occluder.markRenderable(x, y, z); } //? if shaders && >=1.17 { @@ -232,11 +227,7 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask } if (blockState.isSolidRender(/*? if <1.21.11 {*/ slice, blockPos /*?}*/)) { - occluder.setOpaque(blockPos); - - if (occluderBoxes != null) { - occluderBoxes.markOpaque(x, y, z); - } + occluder.markOpaque(x, y, z); } } } @@ -257,22 +248,17 @@ public class ChunkBuilderMeshingTask extends ChunkBuilderTask renderData.hasBlockGeometry = true; } - encodeVisibilityData(occluder, renderData); - - if (occluderBoxes != null) { - renderData.occluderBoxes = occluderBoxes.build(); + if (this.rasterOcclusion) { + renderData.occluderBoxes = occluder.computeOccluderBoxes(); } + renderData.visibilityData = occluder.computeVisibilityEncoding(); + postSectionDataBuiltEvent(renderData); return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime); } - private static void encodeVisibilityData(VisGraph occluder, BuiltRenderSectionData renderData) { - var data = occluder.resolve(); - renderData.visibilityData = VisibilityEncoding.encode((from, to) -> data.visibilityBetween(ModernGraphDirection.toEnum(from), ModernGraphDirection.toEnum(to))); - } - private static void postSectionDataBuiltEvent(MinecraftBuiltRenderSectionData renderData) { ChunkDataBuiltEvent.BUS.post(new ChunkDataBuiltEvent(new SectionInfoBuilder() { @Override diff --git a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/occlusion/ModernGraphDirection.java b/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/occlusion/ModernGraphDirection.java deleted file mode 100644 index dc09050a3..000000000 --- a/modern/src/main/java/org/embeddedt/embeddium/impl/modern/render/chunk/occlusion/ModernGraphDirection.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.embeddedt.embeddium.impl.modern.render.chunk.occlusion; - -import net.minecraft.core.Direction; - -import static org.embeddedt.embeddium.impl.render.chunk.occlusion.GraphDirection.*; - -public class ModernGraphDirection { - private static final Direction[] ENUMS; - - static { - ENUMS = new Direction[COUNT]; - ENUMS[DOWN] = Direction.DOWN; - ENUMS[UP] = Direction.UP; - ENUMS[NORTH] = Direction.NORTH; - ENUMS[SOUTH] = Direction.SOUTH; - ENUMS[WEST] = Direction.WEST; - ENUMS[EAST] = Direction.EAST; - } - public static Direction toEnum(int direction) { - return ENUMS[direction]; - } -} -- 2.54.1 From bd657ebc03b145ac9b5937068643c7a74fd9996c Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 21:37:19 -0400 Subject: [PATCH 15/20] Hoist some loads for consistency --- .../impl/render/chunk/occlusion/OcclusionCuller.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java index d3da266db..e46ec55d4 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/OcclusionCuller.java @@ -226,6 +226,8 @@ public class OcclusionCuller { final long[] queue = this.queue; final long[] apertures = this.apertures; final long[] visibleCells = this.visibleCells; + final int[] occluderBounds = this.lattice.occluderBounds; + final int[][] occluderData = this.lattice.occluderData; int visibleCount = this.visibleCount; final int baseX = this.lattice.baseX, baseY = this.lattice.baseY, baseZ = this.lattice.baseZ; @@ -302,7 +304,8 @@ public class OcclusionCuller { boolean traverse = visible; if (this.rasterActive && visible) { - RasterOccluder.SectionVisibility result = this.rasterTest(idx, chunkX, chunkY, chunkZ, camX, camY, camZ, + RasterOccluder.SectionVisibility result = this.rasterTest(occluderBounds, occluderData, + idx, chunkX, chunkY, chunkZ, camX, camY, camZ, compactMeta, PackedSectionMetadata.hasOccluderData(sm), regionId, regionX, regionY, regionZ); visible = result == RasterOccluder.SectionVisibility.VISIBLE; traverse = result != RasterOccluder.SectionVisibility.HIDDEN; @@ -358,7 +361,8 @@ public class OcclusionCuller { this.visibleCount = visibleCount; } - private RasterOccluder.SectionVisibility rasterTest(int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, + private RasterOccluder.SectionVisibility rasterTest(int[] occluderBounds, int[][] occluderData, + int idx, int chunkX, int chunkY, int chunkZ, int camX, int camY, int camZ, int meta, boolean hasOccluderData, int regionId, int regionX, int regionY, int regionZ) { var occluder = this.rasterOccluder; @@ -380,12 +384,12 @@ public class OcclusionCuller { (PackedSectionMetadata.getCompactVisualsFlags(meta) & (1 << RenderVisualsService.HAS_BLOCK_GEOMETRY)) != 0; // the flag spares the many sections without data the loads below, which rarely hit cache - int bounds = hasOccluderData ? this.lattice.occluderBounds[idx] : PackedBox.FULL_BOX; + int bounds = hasOccluderData ? occluderBounds[idx] : PackedBox.FULL_BOX; RasterOccluder.SectionVisibility result = occluder.testSection(chunkX << 4, chunkY << 4, chunkZ << 4, squaredChunkDist, bounds); if (result == RasterOccluder.SectionVisibility.VISIBLE && hasGeometry && hasOccluderData) { - occluder.occludeSection(this.lattice.occluderData[idx]); + occluder.occludeSection(occluderData[idx]); } return result; -- 2.54.1 From 344e3c549cd5d6129325d674f8f344b492140b60 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 21:40:07 -0400 Subject: [PATCH 16/20] Remove single-use RasterMatrices class --- .../chunk/occlusion/RasterMatrices.java | 22 ------------------- .../chunk/occlusion/RasterOccluder.java | 14 +++++++++++- 2 files changed, 13 insertions(+), 23 deletions(-) delete mode 100644 common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java deleted file mode 100644 index b3220b809..000000000 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterMatrices.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.embeddedt.embeddium.impl.render.chunk.occlusion; - -import grondag.bitraster.Matrix4L; -import org.joml.Matrix4fc; - -/** Bridges JOML matrices into bitraster's fixed-point ones. */ -public final class RasterMatrices { - private RasterMatrices() { - } - - /** - * {@link Matrix4L} indexes {@code a} while JOML indexes {@code m}, so this - * transposes. Feeding it straight through instead still produces plausible-looking output. - */ - public static void copy(Matrix4fc src, Matrix4L dst) { - dst.set( - src.m00(), src.m10(), src.m20(), src.m30(), - src.m01(), src.m11(), src.m21(), src.m31(), - src.m02(), src.m12(), src.m22(), src.m32(), - src.m03(), src.m13(), src.m23(), src.m33()); - } -} diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java index 7becbb62a..84a50edd8 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/RasterOccluder.java @@ -103,7 +103,19 @@ public final class RasterOccluder extends BoxOccluder { chooseBufferSize(vpMatrix, searchDistance); invalidate(); prepareScene(viewVersion, transform.x, transform.y, transform.z, - Matrix4L::loadIdentity, m -> RasterMatrices.copy(vpMatrix, m)); + Matrix4L::loadIdentity, m -> copyMatrix(vpMatrix, m)); + } + + /** + * {@link Matrix4L} indexes {@code a} while JOML indexes {@code m}, so this + * transposes. Feeding it straight through instead still produces plausible-looking output. + */ + private static void copyMatrix(Matrix4fc src, Matrix4L dst) { + dst.set( + src.m00(), src.m10(), src.m20(), src.m30(), + src.m01(), src.m11(), src.m21(), src.m31(), + src.m02(), src.m12(), src.m22(), src.m32(), + src.m03(), src.m13(), src.m23(), src.m33()); } /** -- 2.54.1 From b69525d7d9b80d2b7f3c151d513e08de7849df87 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 21:47:17 -0400 Subject: [PATCH 17/20] Clean up lattice and only store raster occlusion arrays when enabled --- .../chunk/multidraw/bench/MultiDrawBench.java | 2 +- .../bench/ShadowOcclusionCullerBench.java | 2 +- .../chunk/occlusion/SectionLattice.java | 72 ++++++++++--------- 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java index b17409b03..a59f5b62a 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/multidraw/bench/MultiDrawBench.java @@ -89,7 +89,7 @@ public class MultiDrawBench { this.syntheticWorld = new SyntheticWorld(this.world, this.renderDistance, SyntheticWorld.DEFAULT_SEED, this.caveWidth, true, 0.0D, false, false); - this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false); + this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, false, false); for (RenderSection section : this.syntheticWorld.getConstructionOrder()) { this.lattice.attach(section); diff --git a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/ShadowOcclusionCullerBench.java b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/ShadowOcclusionCullerBench.java index bf7909641..3936c3573 100644 --- a/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/ShadowOcclusionCullerBench.java +++ b/common/src/jmh/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/bench/ShadowOcclusionCullerBench.java @@ -89,7 +89,7 @@ public class ShadowOcclusionCullerBench { this.numRegions = BenchPlatform.regionManager().getRegionIdsLength(); // hasShadowPass: allocates the second visit-state array the shadow search stamps. - this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, true); + this.lattice = new SectionLattice(SyntheticWorld.MIN_SECTION_Y, SyntheticWorld.MAX_SECTION_Y, true, false); for (RenderSection section : syntheticWorld.getConstructionOrder()) { this.lattice.attach(section); diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index d515c6542..6963d7339 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -115,6 +115,8 @@ public final class SectionLattice { // Non-null only when the lattice serves a shadow pass as well. @Nullable private final ShadowOcclusionCuller shadowCuller; + // Whether the raster occluder is in use; gates maintenance of occluderData/occluderBounds, which only it reads. + private final boolean rasterOcclusion; private final int minSectionY, maxSectionY; @@ -138,17 +140,9 @@ public final class SectionLattice { long[] sectionMeta; 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; + int[] @Nullable [] occluderData; - /** - * The packed bounds word of each cell's occluder data, mirrored densely so the raster test reads one - * array instead of chasing the pointer above into a second cache line; only a draw needs the boxes. - */ - int[] occluderBounds; + int @Nullable [] occluderBounds; RenderSection[] latticeSection; @@ -204,10 +198,6 @@ public final class SectionLattice { * @param hasShadowPass whether the lattice must also support {@link #findShadowVisible}, which costs a second * visit-state array */ - public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass) { - this(minSectionY, maxSectionY, hasShadowPass, false); - } - public SectionLattice(int minSectionY, int maxSectionY, boolean hasShadowPass, boolean rasterOcclusion) { this.minSectionY = minSectionY; this.maxSectionY = maxSectionY; @@ -215,6 +205,7 @@ public final class SectionLattice { this.dimY = (maxSectionY - minSectionY) + 2; this.culler = new OcclusionCuller(this, minSectionY, maxSectionY, rasterOcclusion); this.shadowCuller = hasShadowPass ? new ShadowOcclusionCuller(this) : null; + this.rasterOcclusion = rasterOcclusion; if (this.dimY > MAX_DIM) { throw new IllegalStateException("World height " + this.dimY + " exceeds occlusion lattice limit " + MAX_DIM); @@ -285,9 +276,12 @@ public final class SectionLattice { long previous = this.sectionMeta[idx]; this.sectionMeta[idx] = packedMetadata; - int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(this.latticeSection[idx]) : null; - this.occluderData[idx] = data; - this.occluderBounds[idx] = boundsOf(data); + + if (this.rasterOcclusion) { + int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(this.latticeSection[idx]) : null; + this.occluderData[idx] = data; + this.occluderBounds[idx] = boundsOf(data); + } return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; } @@ -555,8 +549,8 @@ public final class SectionLattice { this.sectionMeta = new long[slots]; this.regionOfCell = new int[slots]; this.latticeSection = new RenderSection[slots]; - this.occluderData = new int[slots][]; - this.occluderBounds = new int[slots]; + this.occluderData = this.rasterOcclusion ? new int[slots][] : null; + this.occluderBounds = this.rasterOcclusion ? new int[slots] : null; // Existing coordinates are no longer valid after resizing; the next // ensureWindowCovers must rebase and reinstall every attached section. @@ -575,8 +569,10 @@ public final class SectionLattice { Arrays.fill(this.sectionMeta, VisibilityEncoding.NULL); Arrays.fill(this.regionOfCell, -1); Arrays.fill(this.latticeSection, null); - Arrays.fill(this.occluderData, null); - Arrays.fill(this.occluderBounds, 0); + if (this.rasterOcclusion) { + Arrays.fill(this.occluderData, null); + Arrays.fill(this.occluderBounds, 0); + } this.baseX = newBaseX; this.baseZ = newBaseZ; @@ -656,8 +652,10 @@ public final class SectionLattice { System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, len); System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, len); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, len); - System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, len); - System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, len); + if (this.rasterOcclusion) { + System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, len); + System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, len); + } } /** @@ -691,8 +689,10 @@ public final class SectionLattice { System.arraycopy(this.sectionMeta, srcOff, this.sectionMeta, destOff, runLen); System.arraycopy(this.regionOfCell, srcOff, this.regionOfCell, destOff, runLen); System.arraycopy(this.latticeSection, srcOff, this.latticeSection, destOff, runLen); - System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, runLen); - System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, runLen); + if (this.rasterOcclusion) { + System.arraycopy(this.occluderData, srcOff, this.occluderData, destOff, runLen); + System.arraycopy(this.occluderBounds, srcOff, this.occluderBounds, destOff, runLen); + } } } @@ -778,8 +778,10 @@ public final class SectionLattice { this.sectionMeta[idx] = VisibilityEncoding.NULL; this.regionOfCell[idx] = -1; this.latticeSection[idx] = null; - this.occluderData[idx] = null; - this.occluderBounds[idx] = 0; + if (this.rasterOcclusion) { + this.occluderData[idx] = null; + this.occluderBounds[idx] = 0; + } RenderSection section = this.sections.get( PositionUtil.packSection(worldX, this.baseY + ly, worldZ)); @@ -855,9 +857,13 @@ public final class SectionLattice { this.regionOfCell[idx] = section.getRegion().getId(); long packedMetadata = section.getPackedMetadata(); this.sectionMeta[idx] = packedMetadata; - int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(section) : null; - this.occluderData[idx] = data; - this.occluderBounds[idx] = boundsOf(data); + + if (this.rasterOcclusion) { + int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(section) : null; + this.occluderData[idx] = data; + this.occluderBounds[idx] = boundsOf(data); + } + this.installedCount++; } @@ -877,8 +883,10 @@ public final class SectionLattice { this.sectionMeta[idx] = VisibilityEncoding.NULL; this.regionOfCell[idx] = -1; this.latticeSection[idx] = null; - this.occluderData[idx] = null; - this.occluderBounds[idx] = 0; + if (this.rasterOcclusion) { + this.occluderData[idx] = null; + this.occluderBounds[idx] = 0; + } this.installedCount--; } } -- 2.54.1 From 6bf9fb66e51058936b9a83ce21a01514e43f75d3 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 22:12:10 -0400 Subject: [PATCH 18/20] Implement missing raster culling override on ornithe --- .../impl/render/terrain/PrimitiveRenderSectionManager.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/PrimitiveRenderSectionManager.java b/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/PrimitiveRenderSectionManager.java index 64d08dd03..6821d0a7d 100644 --- a/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/PrimitiveRenderSectionManager.java +++ b/ornithe/src/main/java/org/taumc/celeritas/impl/render/terrain/PrimitiveRenderSectionManager.java @@ -59,6 +59,11 @@ public class PrimitiveRenderSectionManager extends RenderSectionManager { return true; } + @Override + protected boolean useRasterOcclusionCulling() { + return false; + } + @Override protected boolean useFogOcclusion() { return true; -- 2.54.1 From 1ffa1c2079269def63b7f060d958e34387268482 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 22:12:10 -0400 Subject: [PATCH 19/20] Count remaining voxels after clearing section bits --- .../impl/render/chunk/occlusion/geometry/BoxFinder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java index 4449d0493..b93bbe002 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/geometry/BoxFinder.java @@ -56,7 +56,7 @@ public class BoxFinder { clearSectionBits(); - voxelCount = voxelCount(sourceBits, sourceIndex); + voxelCount = voxelCount(source, 0); markBoxSlices(); markBoxNeighborSlices(); buildSortedBoxes(); -- 2.54.1 From bb8c95dbd2b9037f3ab1b3bd59e19d6b6a55443b Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Fri, 4 Sep 2026 22:12:10 -0400 Subject: [PATCH 20/20] Re-search when a rebuild changes occluder boxes --- .../impl/render/chunk/PackedSectionMetadata.java | 12 ++++++------ .../impl/render/chunk/occlusion/SectionLattice.java | 7 ++++++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java index 405517817..aa96a8b11 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/PackedSectionMetadata.java @@ -58,12 +58,6 @@ public final class PackedSectionMetadata { private static final int VISUALS_FLAGS_SHIFT = 46; private static final long VISUALS_FLAGS_MASK = 0b111L; - /** - * Fields whose changes can alter the result of a visibility search or its - * render-list output: visibility graph data and visual-presence flags. - */ - public static final long GRAPH_INPUT_MASK = VISIBILITY_MASK | (VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT); - // Bits 49..51: 0 means no pending update; otherwise ordinal + 1. private static final int PENDING_UPDATE_SHIFT = 49; private static final long PENDING_UPDATE_MASK = 0b111L; @@ -76,6 +70,12 @@ public final class PackedSectionMetadata { private static final int HAS_OCCLUDER_DATA_BIT = 53; private static final long HAS_OCCLUDER_DATA_FLAG = 1L << HAS_OCCLUDER_DATA_BIT; + /** + * Fields whose changes can alter the result of a visibility search or its + * render-list output: visibility graph data and visual-presence flags. + */ + public static final long GRAPH_INPUT_MASK = VISIBILITY_MASK | (VISUALS_FLAGS_MASK << VISUALS_FLAGS_SHIFT); + /** Returns only the visibility graph field. */ public static long getVisibilityData(long packed) { return packed & VISIBILITY_MASK; diff --git a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java index 6963d7339..6e3b66646 100644 --- a/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java +++ b/common/src/main/java/org/embeddedt/embeddium/impl/render/chunk/occlusion/SectionLattice.java @@ -277,13 +277,18 @@ public final class SectionLattice { long previous = this.sectionMeta[idx]; this.sectionMeta[idx] = packedMetadata; + boolean occluderChanged = false; + if (this.rasterOcclusion) { int[] data = PackedSectionMetadata.hasOccluderData(packedMetadata) ? occluderDataOf(this.latticeSection[idx]) : null; + // A rebuild allocates a fresh array, so identity is enough to detect + // new boxes even when the packed metadata is otherwise unchanged. + occluderChanged = this.occluderData[idx] != data; this.occluderData[idx] = data; this.occluderBounds[idx] = boundsOf(data); } - return ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; + return occluderChanged || ((previous ^ packedMetadata) & PackedSectionMetadata.GRAPH_INPUT_MASK) != 0; } /** -- 2.54.1