Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
# render-webgl2
|
||||
|
||||
- Only the game's render API (`com.mojang.renderpearl`), `incari.client.render`, TeaVM JSO and the
|
||||
JDK (`BoundaryTest`). JavaScript goes in `WebGl.java` only.
|
||||
- Code here runs under TeaVM: no reflection, no blocking waits. The hot paths (`WebGl2RenderPass`,
|
||||
`GlState`, `Bindings`) don't allocate per draw.
|
||||
- Pure logic (formats, layouts, the manifest) stays free of JSO calls so it's tested on a JVM.
|
||||
- Renderer changes need a human reviewer (`.github/CODEOWNERS`).
|
||||
- A WebGL extension is feature-detected with a fallback, and the fallback is written down (ADR 0012).
|
||||
- Test: `./gradlew :render-webgl2:check`, then `./gradlew :app-web:browserCheck`. A change to what's
|
||||
drawn also needs `./gradlew :app-web:screenshotDiff` (local machine: a display and a GPU) to pass.
|
||||
@@ -0,0 +1,52 @@
|
||||
# render-webgl2: the WebGL2 graphics backend
|
||||
|
||||
Mojang's `GpuDeviceBackend` API over WebGL2, under the game's own frontend device, which validates
|
||||
every call first (ADR 0007). Every vanilla pipeline runs (ADR 0012). The browser build installs
|
||||
`WebGl2Backend` with the canvas and the shaders `tools/shaders` translated.
|
||||
|
||||
## Code map
|
||||
|
||||
| Where | What |
|
||||
| --- | --- |
|
||||
| `WebGl2Backend` | Makes the WebGL2 context and the frontend device |
|
||||
| `WebGl2Device` | Buffers, textures, samplers, surface, encoder; reported limits; draw counts and GPU time for the profiler |
|
||||
| `PipelineCompiler`, `WebGl2Pipeline` | Pipelines from translated shaders, linked on first use |
|
||||
| `WebGl2CommandEncoder`, `WebGl2RenderPass` | Commands, run as recorded. Terrain's indirect draws become a few `multiDrawElementsWEBGL` calls (ADR 0022) |
|
||||
| `QuadIndices`, `DrawRows`, `DrawIdRewrite` | Shared quad indices; per-draw data read by `gl_DrawID` |
|
||||
| `TexelBufferTexture` | A texel buffer emulated as a 2D texture |
|
||||
| `shaders` | The translated-shader manifest format, shared with `tools/shaders` |
|
||||
| `WebGl`, `Staging` | Every JavaScript snippet; how bytes reach WebGL |
|
||||
|
||||
## Invariants
|
||||
|
||||
- **The game's copy of a buffer is the truth.** WebGL2 can't map buffers, so writes are uploaded.
|
||||
- **Bytes reach WebGL through linear memory.** The game's memory is viewed in place; anything else
|
||||
is copied into one staging buffer first.
|
||||
- **Depth runs 0 to 1 where the browser allows** (EXT_clip_control), as on the desktop.
|
||||
- **Extensions are detected, each with a fallback:** clip control, float blending, anisotropy,
|
||||
polygon mode (wireframe).
|
||||
- **State is cached.** `GlState` and `Bindings` skip calls that change nothing; on a Chromebook
|
||||
call overhead, not the GPU, limits the draw rate.
|
||||
- **Uploads bind on the last texture unit**, so draw bindings stay cached.
|
||||
- **Only terrain draws indirectly, one instance per draw.** The multi-draw path relies on it.
|
||||
- **Depends only on the game's render API, `incari.client.render` and TeaVM JSO** (`BoundaryTest`).
|
||||
- **A lost context isn't rebuilt.** The game keeps no copies of what it put on the GPU. `WebGl`
|
||||
cancels `webglcontextlost`, shows a "reload the page" box, and tells platform-web through the
|
||||
canvas's event sink, which reports the window minimized (no drawing, 10 frames a second, the world
|
||||
saved). The surface reports the loss to the game once, not every frame.
|
||||
|
||||
## Debugging
|
||||
|
||||
- `window.__incariWebGl` (updated each frame): frames, draws, skipped draws.
|
||||
- `browserCheck`'s `init:` step runs a script before the page loads, to wrap WebGL calls.
|
||||
- The profiler overlay (F9 or `?overlay`): draw calls, terrain sections, GPU time.
|
||||
- `?multidraw=off` draws terrain a section at a time.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :render-webgl2:check
|
||||
./gradlew :app-web:screenshotDiff # against the desktop (needs GPU and display)
|
||||
./gradlew :app-web:browserCheck -Pbrowser.query=shaders=eager # link every program at start
|
||||
./gradlew :app-web:benchmark # docs/benchmark.md
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
plugins {
|
||||
`java-library`
|
||||
}
|
||||
|
||||
// The WebGL2 graphics backend: Mojang's GpuDevice API over WebGL2, for the browser build.
|
||||
// Only the shaders package runs on a normal JVM too (tools/shaders writes the manifest it reads).
|
||||
|
||||
dependencies {
|
||||
// The game's render API (com.mojang.renderpearl) and the Incari hooks its patches call.
|
||||
api(project(":client"))
|
||||
|
||||
// TeaVM's JavaScript interop: WebGL2 and the typed arrays that carry data to it.
|
||||
compileOnly(libs.teavm.jso)
|
||||
compileOnly(libs.teavm.jso.apis)
|
||||
compileOnly(libs.teavm.interop)
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testImplementation(libs.archunit)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// Game classes loaded by tests write logs/ into the working directory; keep that in build/.
|
||||
val runDir = layout.buildDirectory.dir("test-run").get().asFile
|
||||
workingDir = runDir
|
||||
doFirst { runDir.mkdirs() }
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* What's bound where across draws: uniform buffer ranges by binding point, textures and samplers by
|
||||
* unit, vertex attribute divisors and which attribute arrays are on. Binding points and units are
|
||||
* the pipelines' uniform indices, so consecutive draws of the GUI mostly rebind nothing. Hot path:
|
||||
* no allocation.
|
||||
*
|
||||
* <p>Texture uploads bind on a unit of their own ({@link WebGl2Device#bindTextureForUpdate}), so
|
||||
* they never disturb what's cached here.
|
||||
*/
|
||||
final class Bindings {
|
||||
|
||||
private final WebGL2RenderingContext gl;
|
||||
private final @Nullable Object[] uniformBuffers;
|
||||
private final long[] uniformOffsets;
|
||||
private final long[] uniformLengths;
|
||||
private final @Nullable Object[] textures;
|
||||
private final @Nullable Object[] samplers;
|
||||
private final int[] divisors;
|
||||
private int enabledAttributes;
|
||||
|
||||
Bindings(WebGL2RenderingContext gl, int slots, int attributes) {
|
||||
this.gl = gl;
|
||||
uniformBuffers = new Object[slots];
|
||||
uniformOffsets = new long[slots];
|
||||
uniformLengths = new long[slots];
|
||||
textures = new Object[slots];
|
||||
samplers = new Object[slots];
|
||||
divisors = new int[attributes];
|
||||
}
|
||||
|
||||
/** Records a uniform buffer range at {@code point}; true if it differs from what's bound. */
|
||||
boolean uniformBuffer(int point, WebGl2Buffer buffer, long offset, long length) {
|
||||
if (uniformBuffers[point] == buffer && uniformOffsets[point] == offset && uniformLengths[point] == length) {
|
||||
return false;
|
||||
}
|
||||
uniformBuffers[point] = buffer;
|
||||
uniformOffsets[point] = offset;
|
||||
uniformLengths[point] = length;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Records a texture and sampler on {@code unit}; true if either differs from what's bound. */
|
||||
boolean texture(int unit, WebGl2Texture texture, WebGl2Sampler sampler) {
|
||||
if (textures[unit] == texture && samplers[unit] == sampler) {
|
||||
return false;
|
||||
}
|
||||
textures[unit] = texture;
|
||||
samplers[unit] = sampler;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a texel buffer's texture on {@code unit}, with no sampler object (the texture's own
|
||||
* nearest filtering applies); true if that isn't what's bound.
|
||||
*/
|
||||
boolean texelBuffer(int unit, TexelBufferTexture texture) {
|
||||
if (textures[unit] == texture && samplers[unit] == null) {
|
||||
return false;
|
||||
}
|
||||
textures[unit] = texture;
|
||||
samplers[unit] = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
void divisor(int location, int divisor) {
|
||||
if (divisors[location] != divisor) {
|
||||
gl.vertexAttribDivisor(location, divisor);
|
||||
divisors[location] = divisor;
|
||||
}
|
||||
}
|
||||
|
||||
/** Turns on exactly the attribute arrays in {@code mask} (bit {@code i} is location {@code i}). */
|
||||
void enableAttributes(int mask) {
|
||||
int changed = mask ^ enabledAttributes;
|
||||
for (int location = 0; changed != 0; location++, changed >>>= 1) {
|
||||
if ((changed & 1) != 0) {
|
||||
if ((mask & (1 << location)) != 0) {
|
||||
gl.enableVertexAttribArray(location);
|
||||
} else {
|
||||
gl.disableVertexAttribArray(location);
|
||||
}
|
||||
}
|
||||
}
|
||||
enabledAttributes = mask;
|
||||
}
|
||||
|
||||
/** Forgets the texture on {@code unit}; something else was bound there. */
|
||||
void forgetTexture(int unit) {
|
||||
if (unit < textures.length) {
|
||||
textures[unit] = null;
|
||||
samplers[unit] = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
||||
|
||||
/**
|
||||
* Which buffers keep the game's copy of their contents (ADR 0025). Every buffer used to (ADR
|
||||
* 0007): the game's copy is what writes, maps and copies go through first. A large buffer that is
|
||||
* only drawn from keeps none: a vertex buffer of a megabyte or more that is never mapped and serves
|
||||
* nothing the CPU reads (the terrain's vertex heaps, whose copies cost as much linear memory as the
|
||||
* heaps take on the GPU). Small vertex buffers keep theirs: among them the per-instance rows the
|
||||
* render pass reads, and their copies cost nothing worth saving.
|
||||
*/
|
||||
final class BufferCopies {
|
||||
|
||||
/** Below this a buffer keeps its copy whatever its usage. */
|
||||
static final long LARGE = 1 << 20;
|
||||
|
||||
/** Usages that read the game's copy. */
|
||||
private static final int CPU_USAGES = GpuBuffer.USAGE_MAP_READ
|
||||
| GpuBuffer.USAGE_MAP_WRITE
|
||||
| GpuBuffer.USAGE_INDEX
|
||||
| GpuBuffer.USAGE_UNIFORM
|
||||
| GpuBuffer.USAGE_UNIFORM_TEXEL_BUFFER
|
||||
| GpuBuffer.USAGE_INDIRECT_PARAMETERS;
|
||||
|
||||
/** Every buffer keeps a copy, as before ADR 0025, when the page asks ({@code ?copies=all}), to compare. */
|
||||
static volatile boolean keepAll;
|
||||
|
||||
private BufferCopies() {}
|
||||
|
||||
/** Whether a buffer of {@code usage} and {@code size} keeps the game's copy from the start. */
|
||||
static boolean keepsCopy(@GpuBuffer.Usage int usage, long size) {
|
||||
return keepAll || size < LARGE || (usage & GpuBuffer.USAGE_VERTEX) == 0 || (usage & CPU_USAGES) != 0;
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Rewrites a terrain vertex shader to read Incari's compact terrain vertex (ADR 0023) instead
|
||||
* of the game's block vertex. The compact vertex is 16 bytes where the game's is 28: position and
|
||||
* light in four unsigned shorts ({@link #POSITION_LIGHT}: x, y and z in 1/2048ths of a block from
|
||||
* -8, then block light in the low byte and sky light in the high one), the color as the game has
|
||||
* it, and the texture coordinates in two unsigned shorts ({@link #UV}, 1/32768ths of the atlas).
|
||||
* The shader's own {@code Position}, {@code UV0} and {@code UV2} inputs become macros that decode
|
||||
* them, so the rest of it reads exactly what it read before.
|
||||
*
|
||||
* <p>Pure text over SPIRV-Cross's output (one input declaration per line), tested without a browser.
|
||||
*/
|
||||
final class CompactTerrainRewrite {
|
||||
|
||||
/** The compact format's position-and-light element, as its vertex format names it. */
|
||||
static final String POSITION_LIGHT = "IncariPositionLight";
|
||||
|
||||
/** The compact format's texture coordinates element. */
|
||||
static final String UV = "IncariUv";
|
||||
|
||||
private CompactTerrainRewrite() {}
|
||||
|
||||
/**
|
||||
* {@code stage} reading the compact vertex.
|
||||
*
|
||||
* @throws IllegalArgumentException if the shader doesn't declare the game's terrain inputs
|
||||
*/
|
||||
static TranslatedStage rewrite(TranslatedStage stage) {
|
||||
String glsl = stage.glsl();
|
||||
int positionLocation = location(stage, "Position");
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"vec3",
|
||||
"Position",
|
||||
"layout(location = " + positionLocation + ") in uvec4 " + POSITION_LIGHT + ";\n"
|
||||
+ "#define Position (vec3(" + POSITION_LIGHT + ".xyz) * (1.0 / 2048.0) - vec3(8.0))");
|
||||
// A variant that doesn't sample the atlas or the light map (the translucency passes' alpha
|
||||
// only) has no UV0 or UV2 input: the translation drops what the shader never reads.
|
||||
if (has(stage, "UV0")) {
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"vec2",
|
||||
"UV0",
|
||||
"layout(location = " + location(stage, "UV0") + ") in uvec2 " + UV + ";\n" + "#define UV0 (vec2("
|
||||
+ UV + ") * (1.0 / 32768.0))");
|
||||
}
|
||||
if (has(stage, "UV2")) {
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"ivec2",
|
||||
"UV2",
|
||||
"#define UV2 ivec2(int(" + POSITION_LIGHT + ".w & 255u), int(" + POSITION_LIGHT + ".w >> 8u))");
|
||||
}
|
||||
List<TranslatedStage.Attribute> attributes = new ArrayList<>();
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
switch (attribute.name()) {
|
||||
case "Position" ->
|
||||
attributes.add(new TranslatedStage.Attribute(POSITION_LIGHT, positionLocation, true));
|
||||
case "UV0" -> attributes.add(new TranslatedStage.Attribute(UV, attribute.location(), true));
|
||||
case "UV2" -> {}
|
||||
default -> attributes.add(attribute);
|
||||
}
|
||||
}
|
||||
return new TranslatedStage(
|
||||
stage.key(),
|
||||
stage.sourceHash(),
|
||||
glsl,
|
||||
attributes,
|
||||
stage.uniformBlocks(),
|
||||
stage.samplers(),
|
||||
stage.unsupported());
|
||||
}
|
||||
|
||||
private static boolean has(TranslatedStage stage, String name) {
|
||||
return stage.attributes().stream()
|
||||
.anyMatch(attribute -> attribute.name().equals(name));
|
||||
}
|
||||
|
||||
private static int location(TranslatedStage stage, String name) {
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
if (attribute.name().equals(name)) {
|
||||
return attribute.location();
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("No " + name + " input");
|
||||
}
|
||||
|
||||
private static String replaceDeclaration(String glsl, String type, String name, String replacement) {
|
||||
Matcher declaration = Pattern.compile("layout\\(location = \\d+\\) in (?:(?:highp|mediump|lowp) )?"
|
||||
+ Pattern.quote(type) + " " + Pattern.quote(name) + ";")
|
||||
.matcher(glsl);
|
||||
if (!declaration.find()) {
|
||||
throw new IllegalArgumentException("No " + type + " " + name + " input declaration");
|
||||
}
|
||||
return declaration.replaceFirst(Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Rewrites a vertex shader's per-instance inputs to read a row of a uniform block by
|
||||
* {@code gl_DrawID} instead (ADR 0022). That's what lets one {@code WEBGL_multi_draw} call
|
||||
* draw many terrain sections: the game's multi-draw terrain pipelines read each section's position
|
||||
* and fade from per-instance attributes, picked by an indirect draw's first instance, which WebGL2
|
||||
* has no way to offset within a multi-draw. The backend copies each draw's instance data into row
|
||||
* {@code i} of {@link #BLOCK} for sub-draw {@code i} instead.
|
||||
*
|
||||
* <p>Pure text over SPIRV-Cross's output, whose shape is fixed (one input declaration per line,
|
||||
* {@code layout(location = N) in type name;}), so it's tested without a browser.
|
||||
*/
|
||||
final class DrawIdRewrite {
|
||||
|
||||
/** The uniform block holding one row per sub-draw. */
|
||||
static final String BLOCK = "IncariDrawRows";
|
||||
|
||||
/** Rows in the block: 1024 rows of 16 bytes is WebGL2's smallest allowed maximum block size. */
|
||||
static final int ROWS = 1024;
|
||||
|
||||
/** Bytes per row: one {@code ivec4}. */
|
||||
static final int ROW_BYTES = 16;
|
||||
|
||||
/**
|
||||
* One per-instance input.
|
||||
*
|
||||
* @param word where its first component is in the row, in 32-bit words
|
||||
* @param kind how its words read: as {@link Kind#INT}, {@link Kind#UINT} or {@link Kind#FLOAT}
|
||||
*/
|
||||
record Input(String name, int word, Kind kind) {}
|
||||
|
||||
/** How an input's 32-bit words are read. */
|
||||
enum Kind {
|
||||
INT,
|
||||
UINT,
|
||||
FLOAT
|
||||
}
|
||||
|
||||
private static final Pattern VERSION = Pattern.compile("(?m)^#version 300 es\\n");
|
||||
|
||||
private DrawIdRewrite() {}
|
||||
|
||||
/**
|
||||
* {@code glsl} with each input in {@code inputs} read from the row of the current sub-draw.
|
||||
*
|
||||
* @throws IllegalArgumentException if an input isn't declared as expected, or doesn't fit in a row
|
||||
*/
|
||||
static String rewrite(String glsl, List<Input> inputs) {
|
||||
Matcher version = VERSION.matcher(glsl);
|
||||
if (!version.find()) {
|
||||
throw new IllegalArgumentException("Not GLSL ES 3.00");
|
||||
}
|
||||
String result = glsl;
|
||||
for (Input input : inputs) {
|
||||
Matcher declaration = Pattern.compile("layout\\(location = \\d+\\) in (?:(?:highp|mediump|lowp) )?(\\w+) "
|
||||
+ Pattern.quote(input.name()) + ";")
|
||||
.matcher(result);
|
||||
if (!declaration.find()) {
|
||||
throw new IllegalArgumentException("No input declaration of " + input.name());
|
||||
}
|
||||
String type = declaration.group(1);
|
||||
int components = components(type);
|
||||
if (input.word() < 0 || input.word() + components > 4) {
|
||||
throw new IllegalArgumentException(input.name() + " doesn't fit in a row");
|
||||
}
|
||||
String words = "incari_draw_rows[gl_DrawID]." + "xyzw".substring(input.word(), input.word() + components);
|
||||
String value =
|
||||
switch (input.kind()) {
|
||||
case INT -> words;
|
||||
case UINT -> (components == 1 ? "uint" : "uvec" + components) + "(" + words + ")";
|
||||
case FLOAT -> "intBitsToFloat(" + words + ")";
|
||||
};
|
||||
result = declaration.replaceFirst(
|
||||
Matcher.quoteReplacement("#define " + input.name() + " (" + type + "(" + value + "))"));
|
||||
}
|
||||
// The extension and the block go straight after the version line, before anything reads them.
|
||||
String header = "#extension GL_ANGLE_multi_draw : require\n" + "layout(std140) uniform " + BLOCK
|
||||
+ "\n{\n highp ivec4 incari_draw_rows[" + ROWS + "];\n};\n";
|
||||
Matcher again = VERSION.matcher(result);
|
||||
if (!again.find()) {
|
||||
throw new IllegalStateException("Lost the version line");
|
||||
}
|
||||
return result.substring(0, again.end()) + header + result.substring(again.end());
|
||||
}
|
||||
|
||||
/** Components of a scalar or vector type SPIRV-Cross declares an input as. */
|
||||
static int components(String type) {
|
||||
return switch (type) {
|
||||
case "int", "uint", "float" -> 1;
|
||||
case "ivec2", "uvec2", "vec2" -> 2;
|
||||
case "ivec3", "uvec3", "vec3" -> 3;
|
||||
case "ivec4", "uvec4", "vec4" -> 4;
|
||||
default -> throw new IllegalArgumentException("Can't read a " + type + " from a row");
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DYNAMIC_DRAW;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNIFORM_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNSIGNED_INT;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.JSObject;
|
||||
import org.teavm.jso.typedarrays.Int8Array;
|
||||
import org.teavm.jso.webgl.WebGLBuffer;
|
||||
|
||||
/**
|
||||
* The rows the multi-draw pipelines read by {@code gl_DrawID} ({@link DrawIdRewrite}): one
|
||||
* per sub-draw, holding what the game meant as that draw's per-instance data. Rows are filled here
|
||||
* and uploaded to a ring of uniform buffer space, one batch per draw call, which is then bound as
|
||||
* the {@link DrawIdRewrite#BLOCK} block from the batch's first row, so row {@code i} is sub-draw
|
||||
* {@code i}.
|
||||
*
|
||||
* <p>A batch always binds a whole block's worth (WebGL checks the bound range against the block's
|
||||
* size), so the ring has a block of slack past its end. Hot path: no allocation.
|
||||
*/
|
||||
final class DrawRows {
|
||||
|
||||
/** Batches of rows the ring holds before it starts over; a frame's terrain needs a few dozen. */
|
||||
private static final int RING_BYTES = 256 * 1024;
|
||||
|
||||
private static final int BLOCK_BYTES = DrawIdRewrite.ROWS * DrawIdRewrite.ROW_BYTES;
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final WebGLBuffer ring;
|
||||
private final int binding;
|
||||
private final int alignment;
|
||||
private final ByteBuffer rows = ByteBuffer.allocateDirect(BLOCK_BYTES).order(ByteOrder.LITTLE_ENDIAN);
|
||||
/** Each sub-draw's index count and byte offset, for {@code multiDrawElementsWEBGL}. */
|
||||
private final ByteBuffer counts =
|
||||
ByteBuffer.allocateDirect(4 * DrawIdRewrite.ROWS).order(ByteOrder.LITTLE_ENDIAN);
|
||||
|
||||
private final ByteBuffer offsets =
|
||||
ByteBuffer.allocateDirect(4 * DrawIdRewrite.ROWS).order(ByteOrder.LITTLE_ENDIAN);
|
||||
private int count;
|
||||
private int next;
|
||||
/** Kept views of the buffers above (hot path: none made per call), remade when detached. */
|
||||
private @Nullable Int8Array rowsView;
|
||||
|
||||
private @Nullable JSObject intViews;
|
||||
|
||||
/**
|
||||
* @param binding the uniform buffer binding point the block is bound at, which no pipeline's
|
||||
* own uniforms use
|
||||
* @param alignment {@code UNIFORM_BUFFER_OFFSET_ALIGNMENT}
|
||||
*/
|
||||
DrawRows(WebGl2Device device, int binding, int alignment) {
|
||||
this.device = device;
|
||||
this.binding = binding;
|
||||
this.alignment = Math.max(4, alignment);
|
||||
this.ring = device.gl().createBuffer();
|
||||
device.gl().bindBuffer(UNIFORM_BUFFER, ring);
|
||||
device.gl().bufferData(UNIFORM_BUFFER, RING_BYTES + BLOCK_BYTES, DYNAMIC_DRAW);
|
||||
}
|
||||
|
||||
/** The binding point the rows block is bound at. */
|
||||
int binding() {
|
||||
return binding;
|
||||
}
|
||||
|
||||
/** Starts a batch. */
|
||||
void clear() {
|
||||
count = 0;
|
||||
}
|
||||
|
||||
/** Rows in the batch. */
|
||||
int count() {
|
||||
return count;
|
||||
}
|
||||
|
||||
boolean full() {
|
||||
return count == DrawIdRewrite.ROWS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a sub-draw: its row, {@code length} bytes (at most a row) of {@code source} from
|
||||
* {@code offset}, the rest zero; and, for a multi-draw, its index count and the byte offset of
|
||||
* its first index.
|
||||
*/
|
||||
void add(ByteBuffer source, int offset, int length, int indexCount, int indexByteOffset) {
|
||||
int row = count * DrawIdRewrite.ROW_BYTES;
|
||||
for (int i = 0; i < DrawIdRewrite.ROW_BYTES; i += 4) {
|
||||
rows.putInt(row + i, i + 4 <= length ? source.getInt(offset + i) : 0);
|
||||
}
|
||||
counts.putInt(count * 4, indexCount);
|
||||
offsets.putInt(count * 4, indexByteOffset);
|
||||
count++;
|
||||
}
|
||||
|
||||
/** Draws the batch's sub-draws in one multi-draw, reading 32-bit indices from the bound element buffer. */
|
||||
void multiDraw(JSObject extension, int mode) {
|
||||
JSObject views = intViews;
|
||||
if (views == null || !WebGl.multiDrawElements(extension, mode, views, UNSIGNED_INT, count)) {
|
||||
views = WebGl.intViews(Int8Array.fromJavaBuffer(counts), Int8Array.fromJavaBuffer(offsets));
|
||||
intViews = views;
|
||||
WebGl.multiDrawElements(extension, mode, views, UNSIGNED_INT, count);
|
||||
}
|
||||
}
|
||||
|
||||
/** Uploads the batch and binds it as the block, its first row first. */
|
||||
void upload() {
|
||||
int bytes = count * DrawIdRewrite.ROW_BYTES;
|
||||
if (next + bytes > RING_BYTES) {
|
||||
// Rows overwritten now were read by draws already issued; WebGL keeps those draws'
|
||||
// results as they were.
|
||||
next = 0;
|
||||
}
|
||||
device.gl().bindBuffer(UNIFORM_BUFFER, ring);
|
||||
Int8Array view = rowsView;
|
||||
if (view == null || !WebGl.bufferSubData(device.gl(), UNIFORM_BUFFER, next, view, bytes)) {
|
||||
view = Int8Array.fromJavaBuffer(rows);
|
||||
rowsView = view;
|
||||
WebGl.bufferSubData(device.gl(), UNIFORM_BUFFER, next, view, bytes);
|
||||
}
|
||||
device.gl().bindBufferRange(UNIFORM_BUFFER, binding, ring, next, BLOCK_BYTES);
|
||||
next += (bytes + alignment - 1) / alignment * alignment;
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Rewrites the game's entity vertex shader to draw a model instanced (ADR 0024): the vertices
|
||||
* are the model's cubes once, in each part's own space, and every instance places them with its
|
||||
* own part matrices. A vertex says which part it belongs to ({@link #PART}); an instance says where
|
||||
* its rows start in {@link #BLOCK} ({@link #FIRST_ROW}), three rows (a 3×4 matrix) per part. The
|
||||
* shader's own {@code Position} and {@code Normal} inputs become the part's transform of the local
|
||||
* position and normal, so the rest of it reads exactly what it read before; the color, overlay and
|
||||
* light it reads as they are, per instance instead of per vertex.
|
||||
*
|
||||
* <p>The normal goes through the inverse transpose of the part's matrix and is normalized, which is
|
||||
* what the game's pose stack does to a normal (it keeps that matrix alongside the pose).
|
||||
*
|
||||
* <p>Pure text over SPIRV-Cross's output (one input declaration per line), tested without a browser.
|
||||
*/
|
||||
final class EntityInstanceRewrite {
|
||||
|
||||
/** The shader define that marks an instanced copy of an entity pipeline; no shader reads it. */
|
||||
static final String FLAG = "INCARI_INSTANCED";
|
||||
|
||||
/** The uniform block of part matrices: three rows per part, all of an instance's in a run. */
|
||||
static final String BLOCK = "IncariParts";
|
||||
|
||||
/** Rows in the block: 1024 rows of 16 bytes is WebGL2's smallest allowed maximum block size. */
|
||||
static final int ROWS = 1024;
|
||||
|
||||
/** The per-vertex input naming the vertex's part. */
|
||||
static final String PART = "IncariPart";
|
||||
|
||||
/** The per-instance input: where the instance's rows start. */
|
||||
static final String FIRST_ROW = "IncariFirstRow";
|
||||
|
||||
/** What {@code Position} reads now: the vertex in its part's space. */
|
||||
static final String LOCAL_POSITION = "IncariLocalPosition";
|
||||
|
||||
/** What {@code Normal} reads now: the face's normal in its part's space. */
|
||||
static final String LOCAL_NORMAL = "IncariLocalNormal";
|
||||
|
||||
private static final Pattern VERSION = Pattern.compile("(?m)^#version 300 es\\n");
|
||||
|
||||
private EntityInstanceRewrite() {}
|
||||
|
||||
/**
|
||||
* {@code stage} drawing instances.
|
||||
*
|
||||
* @throws IllegalArgumentException if the shader doesn't declare a {@code vec3 Position} input
|
||||
*/
|
||||
static TranslatedStage rewrite(TranslatedStage stage) {
|
||||
Matcher version = VERSION.matcher(stage.glsl());
|
||||
if (!version.find()) {
|
||||
throw new IllegalArgumentException("Not GLSL ES 3.00");
|
||||
}
|
||||
int nextLocation = 0;
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
nextLocation = Math.max(nextLocation, attribute.location() + 1);
|
||||
}
|
||||
int partLocation = nextLocation;
|
||||
int firstRowLocation = nextLocation + 1;
|
||||
// Declared first, so both replacements below can read them wherever their inputs were.
|
||||
String prelude = "layout(location = " + partLocation + ") in uint " + PART + ";\n"
|
||||
+ "layout(location = " + firstRowLocation + ") in uint " + FIRST_ROW + ";\n"
|
||||
+ "layout(std140) uniform " + BLOCK + "\n{\n vec4 incari_part_rows[" + ROWS + "];\n} incari_ubo_"
|
||||
+ BLOCK + ";\n"
|
||||
+ "uint incari_part_row()\n{\n return " + FIRST_ROW + " + " + PART + " * 3u;\n}\n";
|
||||
String glsl = version.replaceFirst(Matcher.quoteReplacement(version.group() + prelude));
|
||||
|
||||
int positionLocation = location(stage, "Position");
|
||||
String rows = "incari_ubo_" + BLOCK + ".incari_part_rows";
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"vec3",
|
||||
"Position",
|
||||
"layout(location = " + positionLocation + ") in vec3 " + LOCAL_POSITION + ";\n"
|
||||
+ "vec3 incari_part_position()\n{\n uint row = incari_part_row();\n"
|
||||
+ " vec4 local = vec4(" + LOCAL_POSITION + ", 1.0);\n"
|
||||
+ " return vec3(dot(" + rows + "[row], local), dot(" + rows + "[row + 1u], local), dot("
|
||||
+ rows + "[row + 2u], local));\n}\n"
|
||||
+ "#define Position incari_part_position()");
|
||||
boolean hasNormal = has(stage, "Normal");
|
||||
if (hasNormal) {
|
||||
// mat3 takes columns: the rows as columns are the transpose, whose inverse is the
|
||||
// inverse transpose of the part's matrix.
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"vec3",
|
||||
"Normal",
|
||||
"layout(location = " + location(stage, "Normal") + ") in vec3 " + LOCAL_NORMAL + ";\n"
|
||||
+ "vec3 incari_part_normal()\n{\n uint row = incari_part_row();\n"
|
||||
+ " mat3 transposed = mat3(" + rows + "[row].xyz, " + rows + "[row + 1u].xyz, " + rows
|
||||
+ "[row + 2u].xyz);\n"
|
||||
+ " return normalize(inverse(transposed) * " + LOCAL_NORMAL + ");\n}\n"
|
||||
+ "#define Normal incari_part_normal()");
|
||||
}
|
||||
List<TranslatedStage.Attribute> attributes = new ArrayList<>();
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
switch (attribute.name()) {
|
||||
case "Position" ->
|
||||
attributes.add(new TranslatedStage.Attribute(LOCAL_POSITION, attribute.location(), false));
|
||||
case "Normal" ->
|
||||
attributes.add(new TranslatedStage.Attribute(LOCAL_NORMAL, attribute.location(), false));
|
||||
default -> attributes.add(attribute);
|
||||
}
|
||||
}
|
||||
attributes.add(new TranslatedStage.Attribute(PART, partLocation, true));
|
||||
attributes.add(new TranslatedStage.Attribute(FIRST_ROW, firstRowLocation, true));
|
||||
List<String> blocks = new ArrayList<>(stage.uniformBlocks());
|
||||
blocks.add(BLOCK);
|
||||
return new TranslatedStage(
|
||||
stage.key(), stage.sourceHash(), glsl, attributes, blocks, stage.samplers(), stage.unsupported());
|
||||
}
|
||||
|
||||
private static boolean has(TranslatedStage stage, String name) {
|
||||
return stage.attributes().stream()
|
||||
.anyMatch(attribute -> attribute.name().equals(name));
|
||||
}
|
||||
|
||||
private static int location(TranslatedStage stage, String name) {
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
if (attribute.name().equals(name)) {
|
||||
return attribute.location();
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("No " + name + " input");
|
||||
}
|
||||
|
||||
private static String replaceDeclaration(String glsl, String type, String name, String replacement) {
|
||||
Matcher declaration = Pattern.compile("layout\\(location = \\d+\\) in (?:(?:highp|mediump|lowp) )?"
|
||||
+ Pattern.quote(type) + " " + Pattern.quote(name) + ";")
|
||||
.matcher(glsl);
|
||||
if (!declaration.find()) {
|
||||
throw new IllegalArgumentException("No " + type + " " + name + " input declaration");
|
||||
}
|
||||
return declaration.replaceFirst(Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.COLOR_ATTACHMENT0;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DRAW_FRAMEBUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.FRAMEBUFFER_COMPLETE;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.NONE;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLFramebuffer;
|
||||
|
||||
/**
|
||||
* Framebuffer objects by the textures and levels attached to them. The game names its render
|
||||
* targets per pass, and WebGL needs a framebuffer object for each combination; making one per pass
|
||||
* would allocate and validate every frame, so they're kept until one of their textures closes.
|
||||
*/
|
||||
final class Framebuffers {
|
||||
|
||||
/** One attachment: a texture's mip level. Textures compare by identity. */
|
||||
record Attachment(WebGl2Texture texture, int level) {
|
||||
static @Nullable Attachment of(@Nullable WebGl2TextureView view) {
|
||||
return view == null ? null : new Attachment(view.glTexture(), view.baseMipLevel());
|
||||
}
|
||||
}
|
||||
|
||||
private record Key(
|
||||
List<@Nullable Attachment> colors, @Nullable Attachment depth) {}
|
||||
|
||||
/**
|
||||
* A framebuffer object, and whether its draw buffers are set. They're the framebuffer's own
|
||||
* state and follow from its attachments, so they're set once, the first time it's bound to
|
||||
* draw into: setting them on every bind was 3% of the fly-through on the floor stand-in.
|
||||
*/
|
||||
private static final class Entry {
|
||||
final WebGLFramebuffer framebuffer;
|
||||
boolean drawBuffersSet;
|
||||
|
||||
Entry(WebGLFramebuffer framebuffer) {
|
||||
this.framebuffer = framebuffer;
|
||||
}
|
||||
}
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final Map<Key, Entry> framebuffers = new HashMap<>();
|
||||
|
||||
Framebuffers(WebGl2Device device) {
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds the framebuffer with these attachments to {@code target} (draw or read), making it the
|
||||
* first time. For a draw framebuffer, every color attachment is also a draw buffer.
|
||||
*/
|
||||
void bind(int target, List<@Nullable Attachment> colors, @Nullable Attachment depth) {
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
Key key = new Key(colors, depth);
|
||||
Entry entry = framebuffers.get(key);
|
||||
if (entry == null) {
|
||||
WebGLFramebuffer framebuffer = gl.createFramebuffer();
|
||||
gl.bindFramebuffer(target, framebuffer);
|
||||
for (int i = 0; i < colors.size(); i++) {
|
||||
Attachment color = colors.get(i);
|
||||
if (color != null) {
|
||||
gl.framebufferTexture2D(
|
||||
target,
|
||||
COLOR_ATTACHMENT0 + i,
|
||||
color.texture().imageTarget(0),
|
||||
color.texture().handle(),
|
||||
color.level());
|
||||
}
|
||||
}
|
||||
if (depth != null) {
|
||||
gl.framebufferTexture2D(
|
||||
target,
|
||||
GlFormats.attachment(depth.texture().getFormat()),
|
||||
depth.texture().imageTarget(0),
|
||||
depth.texture().handle(),
|
||||
depth.level());
|
||||
}
|
||||
int status = gl.checkFramebufferStatus(target);
|
||||
if (status != FRAMEBUFFER_COMPLETE) {
|
||||
WebGl.error("[Incari] Framebuffer for " + describe(key) + " is incomplete (status 0x"
|
||||
+ Integer.toHexString(status) + ")");
|
||||
}
|
||||
entry = new Entry(framebuffer);
|
||||
framebuffers.put(key, entry);
|
||||
} else {
|
||||
gl.bindFramebuffer(target, entry.framebuffer);
|
||||
}
|
||||
if (target == DRAW_FRAMEBUFFER && !entry.drawBuffersSet) {
|
||||
entry.drawBuffersSet = true;
|
||||
int[] drawBuffers = new int[colors.size()];
|
||||
for (int i = 0; i < drawBuffers.length; i++) {
|
||||
drawBuffers[i] = colors.get(i) != null ? COLOR_ATTACHMENT0 + i : NONE;
|
||||
}
|
||||
gl.drawBuffers(drawBuffers);
|
||||
}
|
||||
}
|
||||
|
||||
/** Binds a framebuffer with one attachment, to read from or clear. */
|
||||
void bindSingle(int target, WebGl2Texture texture, int level) {
|
||||
Attachment attachment = new Attachment(texture, level);
|
||||
if (texture.getFormat().hasColorAspect()) {
|
||||
List<@Nullable Attachment> colors = new ArrayList<>(1);
|
||||
colors.add(attachment);
|
||||
bind(target, colors, null);
|
||||
} else {
|
||||
bind(target, List.of(), attachment);
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes every framebuffer {@code texture} is attached to; it's closing. */
|
||||
void forget(WebGl2Texture texture) {
|
||||
Iterator<Map.Entry<Key, Entry>> entries = framebuffers.entrySet().iterator();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<Key, Entry> entry = entries.next();
|
||||
if (uses(entry.getKey(), texture)) {
|
||||
device.gl().deleteFramebuffer(entry.getValue().framebuffer);
|
||||
entries.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean uses(Key key, WebGl2Texture texture) {
|
||||
Attachment depth = key.depth();
|
||||
if (depth != null && depth.texture() == texture) {
|
||||
return true;
|
||||
}
|
||||
for (Attachment color : key.colors()) {
|
||||
if (color != null && color.texture() == texture) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String describe(Key key) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (Attachment color : key.colors()) {
|
||||
text.append(
|
||||
color == null
|
||||
? "(none)"
|
||||
: color.texture().getLabel() + " "
|
||||
+ color.texture().getFormat())
|
||||
.append(", ");
|
||||
}
|
||||
Attachment depth = key.depth();
|
||||
text.append("depth ")
|
||||
.append(
|
||||
depth == null
|
||||
? "(none)"
|
||||
: depth.texture().getLabel() + " "
|
||||
+ depth.texture().getFormat());
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.*;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import com.mojang.renderpearl.api.pipeline.BlendFactor;
|
||||
import com.mojang.renderpearl.api.pipeline.BlendOp;
|
||||
import com.mojang.renderpearl.api.pipeline.CompareOp;
|
||||
import com.mojang.renderpearl.api.pipeline.IndexType;
|
||||
import com.mojang.renderpearl.api.pipeline.PrimitiveTopology;
|
||||
import com.mojang.renderpearl.api.textures.AddressMode;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The game's formats and states in WebGL2's terms. Pure mapping, no GL calls, so it runs (and is
|
||||
* tested) on a normal JVM too: the WebGL constants are compile-time constants.
|
||||
*/
|
||||
final class GlFormats {
|
||||
|
||||
/** How a texture format is stored ({@code texStorage2D}) and uploaded ({@code texSubImage2D}). */
|
||||
record TextureFormat(int internalFormat, int format, int type) {}
|
||||
|
||||
/** WebGL2's {@code RGBA8}, which TeaVM's binding leaves out. */
|
||||
private static final int RGBA8 = 0x8058;
|
||||
|
||||
/** How a vertex attribute is read ({@code vertexAttrib[I]Pointer}). */
|
||||
record AttributeFormat(int size, int type, boolean normalized) {}
|
||||
|
||||
private GlFormats() {}
|
||||
|
||||
/**
|
||||
* The texture format, or null where WebGL2 has none: 16-bit normalized formats need an
|
||||
* extension (EXT_texture_norm16) Chromebooks rarely have, and a stencil-only texture doesn't
|
||||
* exist in WebGL.
|
||||
*/
|
||||
static @Nullable TextureFormat texture(GpuFormat format) {
|
||||
return switch (format) {
|
||||
case R8_UNORM -> new TextureFormat(R8, RED, UNSIGNED_BYTE);
|
||||
case R8_SNORM -> new TextureFormat(R8_SNORM, RED, BYTE);
|
||||
case RG8_UNORM -> new TextureFormat(RG8, RG, UNSIGNED_BYTE);
|
||||
case RG8_SNORM -> new TextureFormat(RG8_SNORM, RG, BYTE);
|
||||
case RGB8_UNORM -> new TextureFormat(RGB8, RGB, UNSIGNED_BYTE);
|
||||
case RGB8_SNORM -> new TextureFormat(RGB8_SNORM, RGB, BYTE);
|
||||
case RGBA8_UNORM -> new TextureFormat(RGBA8, RGBA, UNSIGNED_BYTE);
|
||||
case RGBA8_SNORM -> new TextureFormat(RGBA8_SNORM, RGBA, BYTE);
|
||||
case R8_UINT -> new TextureFormat(R8UI, RED_INTEGER, UNSIGNED_BYTE);
|
||||
case R8_SINT -> new TextureFormat(R8I, RED_INTEGER, BYTE);
|
||||
case RG8_UINT -> new TextureFormat(RG8UI, RG_INTEGER, UNSIGNED_BYTE);
|
||||
case RG8_SINT -> new TextureFormat(RG8I, RG_INTEGER, BYTE);
|
||||
case RGB8_UINT -> new TextureFormat(RGB8UI, RGB_INTEGER, UNSIGNED_BYTE);
|
||||
case RGB8_SINT -> new TextureFormat(RGB8I, RGB_INTEGER, BYTE);
|
||||
case RGBA8_UINT -> new TextureFormat(RGBA8UI, RGBA_INTEGER, UNSIGNED_BYTE);
|
||||
case RGBA8_SINT -> new TextureFormat(RGBA8I, RGBA_INTEGER, BYTE);
|
||||
case R16_UINT -> new TextureFormat(R16UI, RED_INTEGER, UNSIGNED_SHORT);
|
||||
case R16_SINT -> new TextureFormat(R16I, RED_INTEGER, SHORT);
|
||||
case RG16_UINT -> new TextureFormat(RG16UI, RG_INTEGER, UNSIGNED_SHORT);
|
||||
case RG16_SINT -> new TextureFormat(RG16I, RG_INTEGER, SHORT);
|
||||
case RGB16_UINT -> new TextureFormat(RGB16UI, RGB_INTEGER, UNSIGNED_SHORT);
|
||||
case RGB16_SINT -> new TextureFormat(RGB16I, RGB_INTEGER, SHORT);
|
||||
case RGBA16_UINT -> new TextureFormat(RGBA16UI, RGBA_INTEGER, UNSIGNED_SHORT);
|
||||
case RGBA16_SINT -> new TextureFormat(RGBA16I, RGBA_INTEGER, SHORT);
|
||||
case R32_UINT -> new TextureFormat(R32UI, RED_INTEGER, UNSIGNED_INT);
|
||||
case R32_SINT -> new TextureFormat(R32I, RED_INTEGER, INT);
|
||||
case RG32_UINT -> new TextureFormat(RG32UI, RG_INTEGER, UNSIGNED_INT);
|
||||
case RG32_SINT -> new TextureFormat(RG32I, RG_INTEGER, INT);
|
||||
case RGB32_UINT -> new TextureFormat(RGB32UI, RGB_INTEGER, UNSIGNED_INT);
|
||||
case RGB32_SINT -> new TextureFormat(RGB32I, RGB_INTEGER, INT);
|
||||
case RGBA32_UINT -> new TextureFormat(RGBA32UI, RGBA_INTEGER, UNSIGNED_INT);
|
||||
case RGBA32_SINT -> new TextureFormat(RGBA32I, RGBA_INTEGER, INT);
|
||||
case R16_FLOAT -> new TextureFormat(R16F, RED, HALF_FLOAT);
|
||||
case RG16_FLOAT -> new TextureFormat(RG16F, RG, HALF_FLOAT);
|
||||
case RGB16_FLOAT -> new TextureFormat(RGB16F, RGB, HALF_FLOAT);
|
||||
case RGBA16_FLOAT -> new TextureFormat(RGBA16F, RGBA, HALF_FLOAT);
|
||||
case R32_FLOAT -> new TextureFormat(R32F, RED, FLOAT);
|
||||
case RG32_FLOAT -> new TextureFormat(RG32F, RG, FLOAT);
|
||||
case RGB32_FLOAT -> new TextureFormat(RGB32F, RGB, FLOAT);
|
||||
case RGBA32_FLOAT -> new TextureFormat(RGBA32F, RGBA, FLOAT);
|
||||
case RGB10A2_UNORM -> new TextureFormat(RGB10_A2, RGBA, UNSIGNED_INT_2_10_10_10_REV);
|
||||
case RGB10A2_UINT -> new TextureFormat(RGB10_A2UI, RGBA_INTEGER, UNSIGNED_INT_2_10_10_10_REV);
|
||||
case RG11B10_FLOAT -> new TextureFormat(R11F_G11F_B10F, RGB, UNSIGNED_INT_10F_11F_11F_REV);
|
||||
case D16_UNORM -> new TextureFormat(DEPTH_COMPONENT16, DEPTH_COMPONENT, UNSIGNED_SHORT);
|
||||
case D32_FLOAT -> new TextureFormat(DEPTH_COMPONENT32F, DEPTH_COMPONENT, FLOAT);
|
||||
case D24_UNORM_S8_UINT -> new TextureFormat(DEPTH24_STENCIL8, DEPTH_STENCIL, UNSIGNED_INT_24_8);
|
||||
case D32_FLOAT_S8_UINT ->
|
||||
new TextureFormat(DEPTH32F_STENCIL8, DEPTH_STENCIL, FLOAT_32_UNSIGNED_INT_24_8_REV);
|
||||
case R16_UNORM,
|
||||
R16_SNORM,
|
||||
RG16_UNORM,
|
||||
RG16_SNORM,
|
||||
RGB16_UNORM,
|
||||
RGB16_SNORM,
|
||||
RGBA16_UNORM,
|
||||
RGBA16_SNORM,
|
||||
S8_UINT -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The storage for a render target of {@code format} on a device that can't blend into 32-bit
|
||||
* floats: the 16-bit float format with as many channels (uploads and read-backs keep their
|
||||
* 32-bit data; WebGL converts). Any other format is returned as it is.
|
||||
*/
|
||||
static TextureFormat withoutFloatBlending(TextureFormat format) {
|
||||
int half =
|
||||
switch (format.internalFormat()) {
|
||||
case R32F -> R16F;
|
||||
case RG32F -> RG16F;
|
||||
case RGB32F -> RGB16F;
|
||||
case RGBA32F -> RGBA16F;
|
||||
default -> 0;
|
||||
};
|
||||
return half == 0 ? format : new TextureFormat(half, format.format(), format.type());
|
||||
}
|
||||
|
||||
/** The framebuffer attachment point a texture of this format goes to. */
|
||||
static int attachment(GpuFormat format) {
|
||||
if (format.hasDepthAspect()) {
|
||||
return format.hasStencilAspect() ? DEPTH_STENCIL_ATTACHMENT : DEPTH_ATTACHMENT;
|
||||
}
|
||||
return COLOR_ATTACHMENT0;
|
||||
}
|
||||
|
||||
/** The vertex attribute layout of a vertex format element. */
|
||||
static AttributeFormat attribute(GpuFormat format) {
|
||||
int type =
|
||||
switch (format.componentType()) {
|
||||
case UNORM_8, UINT_8 -> UNSIGNED_BYTE;
|
||||
case SNORM_8, SINT_8 -> BYTE;
|
||||
case UNORM_16, UINT_16 -> UNSIGNED_SHORT;
|
||||
case SNORM_16, SINT_16 -> SHORT;
|
||||
case UINT_32 -> UNSIGNED_INT;
|
||||
case SINT_32 -> INT;
|
||||
case FLOAT_16 -> HALF_FLOAT;
|
||||
case FLOAT_32 -> FLOAT;
|
||||
case OPAQUE_8, OPAQUE_16, OPAQUE_32, OPAQUE_64 ->
|
||||
throw new IllegalArgumentException(format + " can't be a vertex attribute");
|
||||
};
|
||||
boolean normalized =
|
||||
switch (format.componentType()) {
|
||||
case UNORM_8, SNORM_8, UNORM_16, SNORM_16 -> true;
|
||||
default -> false;
|
||||
};
|
||||
return new AttributeFormat(format.componentCount(), type, normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* The draw mode. The game draws {@code LINES} and {@code QUADS} as triangles: its line shaders
|
||||
* widen each segment into a quad, and quads come with an index buffer that splits them.
|
||||
*/
|
||||
static int drawMode(PrimitiveTopology topology) {
|
||||
return switch (topology) {
|
||||
case LINES, TRIANGLES, QUADS -> TRIANGLES;
|
||||
case DEBUG_LINES -> LINES;
|
||||
case DEBUG_LINE_STRIP -> LINE_STRIP;
|
||||
case POINTS -> POINTS;
|
||||
case TRIANGLE_STRIP -> TRIANGLE_STRIP;
|
||||
case TRIANGLE_FAN -> TRIANGLE_FAN;
|
||||
};
|
||||
}
|
||||
|
||||
static int indexType(IndexType type) {
|
||||
return switch (type) {
|
||||
case SHORT -> UNSIGNED_SHORT;
|
||||
case INT -> UNSIGNED_INT;
|
||||
};
|
||||
}
|
||||
|
||||
static int compareOp(CompareOp op) {
|
||||
return switch (op) {
|
||||
case ALWAYS_PASS -> ALWAYS;
|
||||
case LESS_THAN -> LESS;
|
||||
case LESS_THAN_OR_EQUAL -> LEQUAL;
|
||||
case EQUAL -> EQUAL;
|
||||
case NOT_EQUAL -> NOTEQUAL;
|
||||
case GREATER_THAN_OR_EQUAL -> GEQUAL;
|
||||
case GREATER_THAN -> GREATER;
|
||||
case NEVER_PASS -> NEVER;
|
||||
};
|
||||
}
|
||||
|
||||
static int blendFactor(BlendFactor factor) {
|
||||
return switch (factor) {
|
||||
case CONSTANT_ALPHA -> CONSTANT_ALPHA;
|
||||
case CONSTANT_COLOR -> CONSTANT_COLOR;
|
||||
case DST_ALPHA -> DST_ALPHA;
|
||||
case DST_COLOR -> DST_COLOR;
|
||||
case ONE -> ONE;
|
||||
case ONE_MINUS_CONSTANT_ALPHA -> ONE_MINUS_CONSTANT_ALPHA;
|
||||
case ONE_MINUS_CONSTANT_COLOR -> ONE_MINUS_CONSTANT_COLOR;
|
||||
case ONE_MINUS_DST_ALPHA -> ONE_MINUS_DST_ALPHA;
|
||||
case ONE_MINUS_DST_COLOR -> ONE_MINUS_DST_COLOR;
|
||||
case ONE_MINUS_SRC_ALPHA -> ONE_MINUS_SRC_ALPHA;
|
||||
case ONE_MINUS_SRC_COLOR -> ONE_MINUS_SRC_COLOR;
|
||||
case SRC_ALPHA -> SRC_ALPHA;
|
||||
case SRC_ALPHA_SATURATE -> SRC_ALPHA_SATURATE;
|
||||
case SRC_COLOR -> SRC_COLOR;
|
||||
case ZERO -> ZERO;
|
||||
};
|
||||
}
|
||||
|
||||
static int blendOp(BlendOp op) {
|
||||
return switch (op) {
|
||||
case ADD -> FUNC_ADD;
|
||||
case SUBTRACT -> FUNC_SUBTRACT;
|
||||
case REVERSE_SUBTRACT -> FUNC_REVERSE_SUBTRACT;
|
||||
case MIN -> MIN;
|
||||
case MAX -> MAX;
|
||||
};
|
||||
}
|
||||
|
||||
static int wrap(AddressMode mode) {
|
||||
return switch (mode) {
|
||||
case REPEAT -> REPEAT;
|
||||
case CLAMP_TO_EDGE -> CLAMP_TO_EDGE;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.BLEND;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.CULL_FACE;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DEPTH_TEST;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.POLYGON_OFFSET_FILL;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.BlendFunction;
|
||||
import com.mojang.renderpearl.api.pipeline.DepthStencilState;
|
||||
import java.util.Objects;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.JSObject;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLProgram;
|
||||
|
||||
/**
|
||||
* WebGL's fixed-function state as last set, so a draw only changes what differs from the one
|
||||
* before. Every WebGL call crosses from WebAssembly into JavaScript and is checked by the browser;
|
||||
* on a Chromebook that overhead, not the GPU, is what limits the draw rate. Hot path: no
|
||||
* allocation.
|
||||
*/
|
||||
final class GlState {
|
||||
|
||||
private final WebGL2RenderingContext gl;
|
||||
/** Who owns the current program: JavaScript handles don't compare reliably across the boundary. */
|
||||
private @Nullable WebGl2Pipeline programOwner;
|
||||
|
||||
private int colorMask = -1;
|
||||
private int depthMask = -1;
|
||||
private int depthTest = -1;
|
||||
private int depthFunc = -1;
|
||||
private int cull = -1;
|
||||
private int blend = -1;
|
||||
private @Nullable BlendFunction blendFunction;
|
||||
private float offsetFactor = Float.NaN;
|
||||
private float offsetUnits = Float.NaN;
|
||||
private final @Nullable JSObject polygonModeExtension;
|
||||
private boolean lines;
|
||||
|
||||
GlState(WebGL2RenderingContext gl, @Nullable JSObject polygonModeExtension) {
|
||||
this.gl = gl;
|
||||
this.polygonModeExtension = polygonModeExtension;
|
||||
}
|
||||
|
||||
/** Outlines or filled triangles; only a device with WEBGL_polygon_mode compiles wireframe pipelines. */
|
||||
void polygonLines(boolean outline) {
|
||||
JSObject extension = polygonModeExtension;
|
||||
if (outline != lines && extension != null) {
|
||||
WebGl.polygonMode(extension, outline);
|
||||
lines = outline;
|
||||
}
|
||||
}
|
||||
|
||||
void program(WebGl2Pipeline owner, WebGLProgram next) {
|
||||
if (owner != programOwner) {
|
||||
gl.useProgram(next);
|
||||
programOwner = owner;
|
||||
}
|
||||
}
|
||||
|
||||
/** Forgets the current program; one was deleted or used behind this cache's back. */
|
||||
void forgetProgram() {
|
||||
programOwner = null;
|
||||
}
|
||||
|
||||
void colorMask(int mask) {
|
||||
if (mask != colorMask) {
|
||||
gl.colorMask((mask & 1) != 0, (mask & 2) != 0, (mask & 4) != 0, (mask & 8) != 0);
|
||||
colorMask = mask;
|
||||
}
|
||||
}
|
||||
|
||||
void depthMask(boolean write) {
|
||||
int value = write ? 1 : 0;
|
||||
if (value != depthMask) {
|
||||
gl.depthMask(write);
|
||||
depthMask = value;
|
||||
}
|
||||
}
|
||||
|
||||
/** Depth testing and writing as the pipeline asks; a pipeline without depth state does neither. */
|
||||
void depth(@Nullable DepthStencilState state) {
|
||||
if (state == null) {
|
||||
toggle(DEPTH_TEST, false);
|
||||
depthMask(false);
|
||||
polygonOffset(0, 0);
|
||||
return;
|
||||
}
|
||||
toggle(DEPTH_TEST, true);
|
||||
int function = GlFormats.compareOp(state.depthTest());
|
||||
if (function != depthFunc) {
|
||||
gl.depthFunc(function);
|
||||
depthFunc = function;
|
||||
}
|
||||
depthMask(state.writeDepth());
|
||||
polygonOffset(state.depthBiasScaleFactor(), state.depthBiasConstant());
|
||||
}
|
||||
|
||||
void cull(boolean enabled) {
|
||||
int value = enabled ? 1 : 0;
|
||||
if (value != cull) {
|
||||
if (enabled) {
|
||||
gl.enable(CULL_FACE);
|
||||
} else {
|
||||
gl.disable(CULL_FACE);
|
||||
}
|
||||
cull = value;
|
||||
}
|
||||
}
|
||||
|
||||
void blend(@Nullable BlendFunction function) {
|
||||
if (function == null) {
|
||||
if (blend != 0) {
|
||||
gl.disable(BLEND);
|
||||
blend = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (blend != 1) {
|
||||
gl.enable(BLEND);
|
||||
blend = 1;
|
||||
}
|
||||
if (!Objects.equals(function, blendFunction)) {
|
||||
gl.blendFuncSeparate(
|
||||
GlFormats.blendFactor(function.color().sourceFactor()),
|
||||
GlFormats.blendFactor(function.color().destFactor()),
|
||||
GlFormats.blendFactor(function.alpha().sourceFactor()),
|
||||
GlFormats.blendFactor(function.alpha().destFactor()));
|
||||
gl.blendEquationSeparate(
|
||||
GlFormats.blendOp(function.color().op()),
|
||||
GlFormats.blendOp(function.alpha().op()));
|
||||
blendFunction = function;
|
||||
}
|
||||
}
|
||||
|
||||
private void polygonOffset(float factor, float units) {
|
||||
boolean enabled = factor != 0 || units != 0;
|
||||
if (factor == offsetFactor && units == offsetUnits) {
|
||||
return;
|
||||
}
|
||||
toggle(POLYGON_OFFSET_FILL, enabled);
|
||||
if (enabled) {
|
||||
gl.polygonOffset(factor, units);
|
||||
}
|
||||
offsetFactor = factor;
|
||||
offsetUnits = units;
|
||||
}
|
||||
|
||||
private void toggle(int capability, boolean enabled) {
|
||||
if (capability == DEPTH_TEST) {
|
||||
int value = enabled ? 1 : 0;
|
||||
if (value == depthTest) {
|
||||
return;
|
||||
}
|
||||
depthTest = value;
|
||||
}
|
||||
if (enabled) {
|
||||
gl.enable(capability);
|
||||
} else {
|
||||
gl.disable(capability);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.JSObject;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* The page's {@code ?gpucensus} (development only, ADR 0031): the GPU's time for each draw call,
|
||||
* summed by pipeline and logged as milliseconds a frame every {@link #FRAMES} frames, so a frame's
|
||||
* GPU time can be told apart by what drew it. Each draw is timed with a query of its own
|
||||
* (EXT_disjoint_timer_query_webgl2); WebGL has only one time query open at once, so the frame's own
|
||||
* timer ({@link GpuTimer}) stands aside meanwhile. Timing every draw adds a little to each, so the
|
||||
* shares matter more than the sum.
|
||||
*
|
||||
* <p>Render thread only.
|
||||
*/
|
||||
final class GpuCensus {
|
||||
|
||||
private static final int FRAMES = 600;
|
||||
/** Queries in flight at most: a draw past these isn't timed. */
|
||||
private static final int MAX_PENDING = 4096;
|
||||
|
||||
private final WebGL2RenderingContext gl;
|
||||
private final boolean available;
|
||||
private final ArrayDeque<JSObject> free = new ArrayDeque<>();
|
||||
private final ArrayDeque<JSObject> pending = new ArrayDeque<>();
|
||||
private final ArrayDeque<String> pendingPipelines = new ArrayDeque<>();
|
||||
private final Map<String, double[]> nanos = new TreeMap<>();
|
||||
private @Nullable JSObject open;
|
||||
private int frames;
|
||||
|
||||
GpuCensus(WebGL2RenderingContext gl) {
|
||||
this.gl = gl;
|
||||
this.available = WebGl.extension(gl, "EXT_disjoint_timer_query_webgl2") != null;
|
||||
}
|
||||
|
||||
/** Before a draw's call: starts timing it. */
|
||||
void begin() {
|
||||
if (!available || open != null || pending.size() >= MAX_PENDING) {
|
||||
return;
|
||||
}
|
||||
JSObject query = free.poll();
|
||||
if (query == null) {
|
||||
query = WebGl.createQuery(gl);
|
||||
}
|
||||
WebGl.beginTimer(gl, query);
|
||||
open = query;
|
||||
}
|
||||
|
||||
/** After a draw's call: its time goes to {@code pipeline} once the GPU gives it. */
|
||||
void end(String pipeline) {
|
||||
JSObject query = open;
|
||||
if (query == null) {
|
||||
return;
|
||||
}
|
||||
WebGl.endTimer(gl);
|
||||
open = null;
|
||||
pending.add(query);
|
||||
pendingPipelines.add(pipeline);
|
||||
}
|
||||
|
||||
/** Once a frame: takes the finished results, oldest first, and logs every {@value #FRAMES} frames. */
|
||||
void frameEnded() {
|
||||
while (true) {
|
||||
JSObject query = pending.peek();
|
||||
if (query == null) {
|
||||
break;
|
||||
}
|
||||
double result = WebGl.timerResult(gl, query);
|
||||
if (result == -1) {
|
||||
break;
|
||||
}
|
||||
pending.poll();
|
||||
String pipeline = pendingPipelines.poll();
|
||||
free.add(query);
|
||||
if (result >= 0 && pipeline != null) {
|
||||
nanos.computeIfAbsent(pipeline, name -> new double[1])[0] += result;
|
||||
}
|
||||
}
|
||||
if (++frames == FRAMES) {
|
||||
StringBuilder line = new StringBuilder("[Incari] GPU ms a frame by pipeline over ")
|
||||
.append(FRAMES)
|
||||
.append(" frames:");
|
||||
nanos.entrySet().stream()
|
||||
.sorted((a, b) -> Double.compare(b.getValue()[0], a.getValue()[0]))
|
||||
.forEach(entry -> line.append(String.format(
|
||||
Locale.ROOT, " %s=%.3f", entry.getKey(), entry.getValue()[0] / 1e6 / FRAMES)));
|
||||
WebGl.info(line.toString());
|
||||
nanos.clear();
|
||||
frames = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.JSObject;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* Times each frame's GPU work with EXT_disjoint_timer_query_webgl2, where the browser has
|
||||
* it: a query opens at the frame's first command and closes after its blit to the canvas, and its
|
||||
* answer is read when the GPU gives it, a frame or two later. Not opening the query until the first
|
||||
* command keeps the time the GPU sits idle between frames (the page waiting for vsync) out of it.
|
||||
*
|
||||
* <p>A few queries are kept in flight; a frame that finds them all still pending isn't timed.
|
||||
*/
|
||||
final class GpuTimer {
|
||||
|
||||
private static final int QUERIES = 4;
|
||||
|
||||
private final WebGL2RenderingContext gl;
|
||||
private final JSObject @Nullable [] queries;
|
||||
private final boolean[] pending = new boolean[QUERIES];
|
||||
/** The order the pending queries were issued in, oldest first, as indices into {@link #queries}. */
|
||||
private final int[] order = new int[QUERIES];
|
||||
|
||||
private int pendingCount;
|
||||
private int open = -1;
|
||||
private double lastMillis = Double.NaN;
|
||||
|
||||
GpuTimer(WebGL2RenderingContext gl) {
|
||||
this.gl = gl;
|
||||
if (WebGl.extension(gl, "EXT_disjoint_timer_query_webgl2") == null) {
|
||||
queries = null;
|
||||
return;
|
||||
}
|
||||
queries = new JSObject[QUERIES];
|
||||
for (int i = 0; i < QUERIES; i++) {
|
||||
queries[i] = WebGl.createQuery(gl);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether this browser can time the GPU. */
|
||||
boolean available() {
|
||||
return queries != null;
|
||||
}
|
||||
|
||||
/** The GPU's time for the latest frame timed, in milliseconds; NaN if none has been. */
|
||||
double lastMillis() {
|
||||
return lastMillis;
|
||||
}
|
||||
|
||||
/** Called before each command that may reach the GPU: opens the frame's query if it isn't. */
|
||||
void frameWork() {
|
||||
JSObject[] all = queries;
|
||||
// Under ?gpucensus each draw has the one time query WebGL allows open at once.
|
||||
if (all == null || open >= 0 || pendingCount == QUERIES || WebGl2Device.timeDraws) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < QUERIES; i++) {
|
||||
if (!pending[i]) {
|
||||
open = i;
|
||||
WebGl.beginTimer(gl, all[i]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Called once a frame, after its blit: closes its query and reads any that have finished. */
|
||||
void frameEnded() {
|
||||
JSObject[] all = queries;
|
||||
if (all == null) {
|
||||
return;
|
||||
}
|
||||
if (open >= 0) {
|
||||
WebGl.endTimer(gl);
|
||||
pending[open] = true;
|
||||
order[pendingCount++] = open;
|
||||
open = -1;
|
||||
}
|
||||
// Oldest first: results come in the order the queries were issued.
|
||||
while (pendingCount > 0) {
|
||||
int oldest = order[0];
|
||||
double nanos = WebGl.timerResult(gl, all[oldest]);
|
||||
if (nanos == -1) {
|
||||
break;
|
||||
}
|
||||
if (nanos >= 0) {
|
||||
lastMillis = nanos / 1_000_000.0;
|
||||
}
|
||||
pending[oldest] = false;
|
||||
System.arraycopy(order, 1, order, 0, --pendingCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Rewrites the game's particle vertex shader to draw particles instanced (ADR 0032): each instance
|
||||
* is one particle as the game keeps it ({@code QuadParticleRenderState}'s twelve floats and two ints
|
||||
* a particle), and the four vertices of its quad are worked out here, from {@code gl_VertexID}
|
||||
* (the quad index buffer's 0 to 3), as the game works them out on the CPU: the corner of the unit
|
||||
* square turned by the particle's rotation (JOML's quaternion rotation, its normalization included),
|
||||
* scaled, moved to the particle; its texture coordinates the corner's of the sprite's. The shader's
|
||||
* own {@code Position}, {@code UV0} and {@code Color} inputs read those, so the rest of it is
|
||||
* unchanged; {@code UV2} (the light) is read per instance as it was per vertex.
|
||||
*
|
||||
* <p>The color arrives as the game's packed int (ARGB) as it lies in memory, so its bytes are blue,
|
||||
* green, red, alpha, and the shader turns them round. The light's two halves are its two shorts, as a
|
||||
* vertex holds them.
|
||||
*
|
||||
* <p>Pure text over SPIRV-Cross's output (one input declaration per line), tested without a browser.
|
||||
*/
|
||||
final class ParticleInstanceRewrite {
|
||||
|
||||
/** The shader define that marks an instanced copy of a particle pipeline; no shader reads it. */
|
||||
static final String FLAG = "INCARI_PARTICLES_INSTANCED";
|
||||
|
||||
/** Per instance: the particle's position. */
|
||||
static final String CENTER = "IncariCenter";
|
||||
|
||||
/** Per instance: its rotation, a quaternion (x, y, z, w). */
|
||||
static final String ROTATION = "IncariRotation";
|
||||
|
||||
/** Per instance: its scale. */
|
||||
static final String SCALE = "IncariScale";
|
||||
|
||||
/** Per instance: its sprite's texture coordinates, u0, u1, v0, v1. */
|
||||
static final String UVS = "IncariUvs";
|
||||
|
||||
/** Per instance: its color, the game's ARGB int as bytes. */
|
||||
static final String COLOR = "IncariColor";
|
||||
|
||||
private static final Pattern VERSION = Pattern.compile("(?m)^#version 300 es\\n");
|
||||
|
||||
private ParticleInstanceRewrite() {}
|
||||
|
||||
/**
|
||||
* {@code stage} drawing instances.
|
||||
*
|
||||
* @throws IllegalArgumentException if the shader doesn't declare the particle inputs
|
||||
*/
|
||||
static TranslatedStage rewrite(TranslatedStage stage) {
|
||||
Matcher version = VERSION.matcher(stage.glsl());
|
||||
if (!version.find()) {
|
||||
throw new IllegalArgumentException("Not GLSL ES 3.00");
|
||||
}
|
||||
int next = 0;
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
next = Math.max(next, attribute.location() + 1);
|
||||
}
|
||||
int rotation = next;
|
||||
int scale = next + 1;
|
||||
int uvs = next + 2;
|
||||
String glsl = stage.glsl();
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"vec3",
|
||||
"Position",
|
||||
"layout(location = " + location(stage, "Position") + ") in vec3 " + CENTER + ";\n"
|
||||
+ "layout(location = " + rotation + ") in vec4 " + ROTATION + ";\n"
|
||||
+ "layout(location = " + scale + ") in float " + SCALE + ";\n"
|
||||
+ "layout(location = " + uvs + ") in vec4 " + UVS + ";\n"
|
||||
+ "vec3 incari_particle_position()\n{\n"
|
||||
+ " int corner = gl_VertexID & 3;\n"
|
||||
+ " float cx = corner < 2 ? 1.0 : -1.0;\n"
|
||||
+ " float cy = (corner == 1 || corner == 2) ? 1.0 : -1.0;\n"
|
||||
// JOML's Vector3f.rotate(Quaternionfc), with z = 0.
|
||||
+ " vec4 q = " + ROTATION + ";\n"
|
||||
+ " float xx = q.x * q.x, yy = q.y * q.y, zz = q.z * q.z, ww = q.w * q.w;\n"
|
||||
+ " float xy = q.x * q.y, xz = q.x * q.z, yz = q.y * q.z;\n"
|
||||
+ " float xw = q.x * q.w, zw = q.z * q.w, yw = q.y * q.w;\n"
|
||||
+ " float k = 1.0 / (xx + yy + zz + ww);\n"
|
||||
+ " vec3 turned = vec3(\n"
|
||||
+ " (xx - yy - zz + ww) * k * cx + (2.0 * (xy - zw) * k) * cy,\n"
|
||||
+ " (2.0 * (xy + zw) * k) * cx + (yy - xx - zz + ww) * k * cy,\n"
|
||||
+ " (2.0 * (xz - yw) * k) * cx + (2.0 * (yz + xw) * k) * cy);\n"
|
||||
+ " return turned * " + SCALE + " + " + CENTER + ";\n}\n"
|
||||
+ "#define Position incari_particle_position()");
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"vec2",
|
||||
"UV0",
|
||||
"vec2 incari_particle_uv()\n{\n"
|
||||
+ " int corner = gl_VertexID & 3;\n"
|
||||
+ " return vec2(corner < 2 ? " + UVS + ".y : " + UVS + ".x, (corner == 1 || corner == 2) ? "
|
||||
+ UVS + ".z : " + UVS + ".w);\n}\n"
|
||||
+ "#define UV0 incari_particle_uv()");
|
||||
glsl = replaceDeclaration(
|
||||
glsl,
|
||||
"vec4",
|
||||
"Color",
|
||||
"layout(location = " + location(stage, "Color") + ") in vec4 " + COLOR + ";\n" + "#define Color ("
|
||||
+ COLOR + ".zyxw)");
|
||||
List<TranslatedStage.Attribute> attributes = new ArrayList<>();
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
switch (attribute.name()) {
|
||||
case "Position" -> attributes.add(new TranslatedStage.Attribute(CENTER, attribute.location(), false));
|
||||
case "Color" -> attributes.add(new TranslatedStage.Attribute(COLOR, attribute.location(), false));
|
||||
case "UV0" -> {
|
||||
// Worked out from the corner: no input any more.
|
||||
}
|
||||
default -> attributes.add(attribute);
|
||||
}
|
||||
}
|
||||
attributes.add(new TranslatedStage.Attribute(ROTATION, rotation, false));
|
||||
attributes.add(new TranslatedStage.Attribute(SCALE, scale, false));
|
||||
attributes.add(new TranslatedStage.Attribute(UVS, uvs, false));
|
||||
return new TranslatedStage(
|
||||
stage.key(),
|
||||
stage.sourceHash(),
|
||||
glsl,
|
||||
attributes,
|
||||
stage.uniformBlocks(),
|
||||
stage.samplers(),
|
||||
stage.unsupported());
|
||||
}
|
||||
|
||||
private static int location(TranslatedStage stage, String name) {
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
if (attribute.name().equals(name)) {
|
||||
return attribute.location();
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("No " + name + " input");
|
||||
}
|
||||
|
||||
private static String replaceDeclaration(String glsl, String type, String name, String replacement) {
|
||||
Matcher declaration = Pattern.compile("layout\\(location = \\d+\\) in (?:(?:highp|mediump|lowp) )?"
|
||||
+ Pattern.quote(type) + " " + Pattern.quote(name) + ";")
|
||||
.matcher(glsl);
|
||||
if (!declaration.find()) {
|
||||
throw new IllegalArgumentException("No " + type + " " + name + " input declaration");
|
||||
}
|
||||
return declaration.replaceFirst(Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Uniform buffers written since the last draw, uploaded together before the next one (ADR 0027).
|
||||
*
|
||||
* <p>The game writes most uniforms by mapping a block of a ring buffer, writing it and closing the
|
||||
* view: its dynamic transforms take one such block per draw. Closing a view used to upload its
|
||||
* bytes at once, a {@code bufferSubData} per block, each a call from WebAssembly into JavaScript
|
||||
* that the browser checks and copies into its command buffer. The writes follow each other in the
|
||||
* ring, so a buffer instead notes the range written ({@link WebGl2Buffer#deferUpload}) and the
|
||||
* render pass uploads that whole range in one call when it next draws ({@link #flush}).
|
||||
*
|
||||
* <p>Nothing else needs the bytes before a draw: the game's copy, which this leaves current, is
|
||||
* what the CPU side reads (texel buffers, copies, read-backs), and a uniform buffer always keeps
|
||||
* one ({@link BufferCopies}). Hot path: no allocation once the list has grown.
|
||||
*/
|
||||
final class PendingUploads {
|
||||
|
||||
/** Defer at all; the page's {@code ?uniforms=each} uploads each write on its own, to compare. */
|
||||
static volatile boolean enabled = true;
|
||||
|
||||
private final List<WebGl2Buffer> buffers = new ArrayList<>();
|
||||
|
||||
/** {@code buffer} has a range to upload; called once until the next {@link #flush}. */
|
||||
void add(WebGl2Buffer buffer) {
|
||||
buffers.add(buffer);
|
||||
}
|
||||
|
||||
/** Uploads every pending range: before a draw reads the buffers. */
|
||||
void flush() {
|
||||
if (buffers.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < buffers.size(); i++) {
|
||||
buffers.get(i).flushUpload();
|
||||
}
|
||||
buffers.clear();
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.BindGroupLayout;
|
||||
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
|
||||
import com.mojang.renderpearl.api.pipeline.PolygonMode;
|
||||
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderSource;
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import com.mojang.renderpearl.api.vertex.VertexFormat;
|
||||
import com.mojang.renderpearl.frontend.FrontendRenderPipeline;
|
||||
import incari.render.webgl2.shaders.ShaderManifest;
|
||||
import incari.render.webgl2.shaders.ShaderStageKey;
|
||||
import incari.render.webgl2.shaders.SourceHash;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntArrayMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Turns the game's pipeline descriptions into WebGL2 pipelines, from the shaders the build
|
||||
* translated ({@link ShaderManifest}) rather than by compiling GLSL at run time as the game's
|
||||
* other backends do. The frontend's render passes only take its own pipeline type, so the result
|
||||
* is wrapped in one, with the uniform indices it binds by.
|
||||
*
|
||||
* <p>A pipeline WebGL2 can't run yet still compiles: to a pipeline that skips its draws. The game
|
||||
* refuses to load at all if a required pipeline fails, and the title screen doesn't need clouds.
|
||||
*/
|
||||
final class PipelineCompiler {
|
||||
|
||||
/** The define of the game's terrain pipelines for indirect multi-draws. */
|
||||
private static final String MULTIDRAW_TERRAIN = "MULTIDRAW_TERRAIN";
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final ShaderManifest manifest;
|
||||
private final boolean eager;
|
||||
private final Set<String> warnedSources = new HashSet<>();
|
||||
|
||||
PipelineCompiler(WebGl2Device device, ShaderManifest manifest, boolean eager) {
|
||||
this.device = device;
|
||||
this.manifest = manifest;
|
||||
this.eager = eager;
|
||||
}
|
||||
|
||||
CompletableFuture<CompiledRenderPipeline.Pending> compile(RenderPipeline pipeline, ShaderSource source) {
|
||||
WebGl2Pipeline backend = backendPipeline(pipeline, source);
|
||||
if (eager || instanced(pipeline)) {
|
||||
backend.link();
|
||||
}
|
||||
if (instanced(pipeline) && backend.failed()) {
|
||||
// Incari's own copy: no pipeline at all, so the game's model renderer sees it
|
||||
// can't draw instanced and draws those models its own way, instead of skipping them.
|
||||
backend.close();
|
||||
return CompletableFuture.completedFuture(CompiledRenderPipeline.Pending.NULL);
|
||||
}
|
||||
List<BindGroupLayout.UniformDescription> uniforms =
|
||||
BindGroupLayout.flattenUniforms(pipeline.getBindGroupLayouts());
|
||||
Object2IntMap<String> indices = new Object2IntArrayMap<>(uniforms.size());
|
||||
for (int i = 0; i < uniforms.size(); i++) {
|
||||
indices.put(uniforms.get(i).name(), i);
|
||||
}
|
||||
CompiledRenderPipeline compiled = new FrontendRenderPipeline(
|
||||
pipeline.getLocation().toString(),
|
||||
backend,
|
||||
pipeline.getVertexFormatBindings(),
|
||||
Object2IntMaps.unmodifiable(indices),
|
||||
uniforms,
|
||||
pipeline.getColorTargetStates(),
|
||||
pipeline.wantsDepthTexture(),
|
||||
pipeline.pushConstantSize());
|
||||
return CompletableFuture.completedFuture(() -> compiled);
|
||||
}
|
||||
|
||||
private WebGl2Pipeline backendPipeline(RenderPipeline pipeline, ShaderSource source) {
|
||||
if (pipeline.getPolygonMode() == PolygonMode.WIREFRAME && !device.hasPolygonMode()) {
|
||||
return WebGl2Pipeline.unsupported(
|
||||
device, pipeline, "wireframe (this browser has no WEBGL_polygon_mode, a debug view)");
|
||||
}
|
||||
TranslatedStage vertex = stage(pipeline, ShaderType.VERTEX, source);
|
||||
TranslatedStage fragment = stage(pipeline, ShaderType.FRAGMENT, source);
|
||||
if (vertex == null || fragment == null) {
|
||||
return WebGl2Pipeline.unsupported(
|
||||
device,
|
||||
pipeline,
|
||||
"its shaders aren't in shaders.json (the build translates only the vanilla pipelines)");
|
||||
}
|
||||
String unsupported = vertex.unsupported() != null ? vertex.unsupported() : fragment.unsupported();
|
||||
if (unsupported != null) {
|
||||
return WebGl2Pipeline.unsupported(device, pipeline, unsupported);
|
||||
}
|
||||
if (instancedParticles(pipeline)) {
|
||||
// An instanced copy of a particle pipeline (ADR 0032): each particle's quad worked out per instance.
|
||||
try {
|
||||
vertex = ParticleInstanceRewrite.rewrite(vertex);
|
||||
} catch (IllegalArgumentException e) {
|
||||
WebGl.error("[Incari] " + pipeline.getLocation() + " can't draw instanced: " + e.getMessage());
|
||||
return WebGl2Pipeline.unsupported(device, pipeline, "instanced particles: " + e.getMessage());
|
||||
}
|
||||
} else if (instanced(pipeline)) {
|
||||
// An instanced copy of an entity pipeline: the model's parts placed per instance.
|
||||
try {
|
||||
vertex = EntityInstanceRewrite.rewrite(vertex);
|
||||
} catch (IllegalArgumentException e) {
|
||||
WebGl.error("[Incari] " + pipeline.getLocation() + " can't draw instanced: " + e.getMessage());
|
||||
return WebGl2Pipeline.unsupported(device, pipeline, "instanced models: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
if (readsCompactTerrain(pipeline)) {
|
||||
// Incari's compact terrain vertex: the shader decodes it into the inputs it had.
|
||||
try {
|
||||
vertex = CompactTerrainRewrite.rewrite(vertex);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return WebGl2Pipeline.unsupported(device, pipeline, "compact terrain vertices: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
List<VertexLayout.Binding> layout =
|
||||
VertexLayout.of(pipeline.getVertexFormatBindings(), vertex.attributes());
|
||||
// The game's multi-draw terrain pipelines, the only ones with per-instance data: their
|
||||
// draws are indirect, and each section's instance data is read by gl_DrawID.
|
||||
VertexLayout.DrawRowLayout rows =
|
||||
device.multiDraw() && pipeline.getShaderDefines().flags().contains(MULTIDRAW_TERRAIN)
|
||||
? VertexLayout.drawRows(layout, vertex.attributes())
|
||||
: null;
|
||||
if (rows != null) {
|
||||
try {
|
||||
return WebGl2Pipeline.withDrawRows(
|
||||
device,
|
||||
pipeline,
|
||||
vertex,
|
||||
fragment,
|
||||
rows,
|
||||
DrawIdRewrite.rewrite(vertex.glsl(), rows.inputs()));
|
||||
} catch (IllegalArgumentException e) {
|
||||
WebGl.warn("[Incari] " + pipeline.getLocation() + " draws without multi-draw: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
return WebGl2Pipeline.of(device, pipeline, vertex, fragment, layout);
|
||||
} catch (VertexLayout.MismatchException e) {
|
||||
return WebGl2Pipeline.unsupported(
|
||||
device, pipeline, e.getMessage() == null ? "vertex layout" : e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the pipeline is one of Incari's instanced copies (an entity's or a particle's). */
|
||||
private static boolean instanced(RenderPipeline pipeline) {
|
||||
Set<String> flags = pipeline.getShaderDefines().flags();
|
||||
return flags.contains(EntityInstanceRewrite.FLAG) || flags.contains(ParticleInstanceRewrite.FLAG);
|
||||
}
|
||||
|
||||
private static boolean instancedParticles(RenderPipeline pipeline) {
|
||||
return pipeline.getShaderDefines().flags().contains(ParticleInstanceRewrite.FLAG);
|
||||
}
|
||||
|
||||
/**
|
||||
* The defines the build translated the pipeline's shaders with: its own, less the flag of an
|
||||
* instanced copy, which is the copied pipeline's shaders rewritten here.
|
||||
*/
|
||||
private static ShaderDefines translatedDefines(RenderPipeline pipeline) {
|
||||
ShaderDefines defines = pipeline.getShaderDefines();
|
||||
if (!instanced(pipeline)) {
|
||||
return defines;
|
||||
}
|
||||
Set<String> flags = new HashSet<>(defines.flags());
|
||||
flags.remove(EntityInstanceRewrite.FLAG);
|
||||
flags.remove(ParticleInstanceRewrite.FLAG);
|
||||
return new ShaderDefines(defines.values(), flags);
|
||||
}
|
||||
|
||||
/** Whether the pipeline's vertices are Incari's compact terrain vertices (its first binding says). */
|
||||
private static boolean readsCompactTerrain(RenderPipeline pipeline) {
|
||||
List<@Nullable VertexFormat> formats = pipeline.getVertexFormatBindings();
|
||||
VertexFormat first = formats.isEmpty() ? null : formats.getFirst();
|
||||
return first != null && first.contains(CompactTerrainRewrite.POSITION_LIGHT);
|
||||
}
|
||||
|
||||
private @Nullable TranslatedStage stage(RenderPipeline pipeline, ShaderType type, ShaderSource source) {
|
||||
Identifier id = pipeline.getShaders().get(type);
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
ShaderStageKey key = ShaderStageKey.of(type, id, translatedDefines(pipeline));
|
||||
TranslatedStage stage = null;
|
||||
if (device.depthZeroToOne()) {
|
||||
// The game compiles its shaders for a 0-to-1 depth range when the device has one; the
|
||||
// build translated a second variant of the stages that define changes.
|
||||
stage = manifest.stage(key.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE));
|
||||
}
|
||||
if (stage == null) {
|
||||
stage = manifest.stage(key);
|
||||
}
|
||||
if (stage != null) {
|
||||
String text = source.getShader(id, type);
|
||||
if (text != null && !SourceHash.of(text).equals(stage.sourceHash()) && warnedSources.add(id + " " + type)) {
|
||||
// Translating shaders in the page needs a GLSL compiler there; until then packs
|
||||
// can't change shaders, and the vanilla translation keeps the game drawing.
|
||||
WebGl.warn("[Incari] A resource pack changed " + type.getName() + " shader " + id
|
||||
+ "; the browser build still uses the vanilla one");
|
||||
}
|
||||
}
|
||||
return stage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.webgl.WebGLBuffer;
|
||||
|
||||
/**
|
||||
* The backend's own index buffer of sequential quads (0 1 2 2 3 0, 4 5 6 6 7 4, ...), 32-bit, as
|
||||
* long as the largest vertex heap drawn from needs (ADR 0022). WebGL2 has no base vertex, so
|
||||
* where the game draws a terrain section from vertex {@code v} of a shared buffer with the start
|
||||
* of its own quad index buffer, this buffer is read from quad {@code v / 4} instead: the indices
|
||||
* there already count from {@code v}. That makes every section of a heap drawable by one
|
||||
* multi-draw.
|
||||
*
|
||||
* <p>Grows by doubling, so it's re-uploaded a handful of times as the world loads; each index
|
||||
* costs 4 bytes of GPU memory, 6 per quad of the largest heap.
|
||||
*/
|
||||
final class QuadIndices {
|
||||
|
||||
/** Enough for 16384 quads before the first growth. */
|
||||
private static final int MIN_INDICES = 6 * 16384;
|
||||
|
||||
private final WebGl2Device device;
|
||||
private @Nullable WebGLBuffer buffer;
|
||||
private int indices;
|
||||
|
||||
QuadIndices(WebGl2Device device) {
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
/** Binds the buffer as the element array, grown to hold at least {@code needed} indices. */
|
||||
void bind(long needed) {
|
||||
if (needed > Integer.MAX_VALUE / 4) {
|
||||
throw new IllegalArgumentException("A quad index buffer of " + needed + " indices is too large");
|
||||
}
|
||||
WebGLBuffer current = buffer;
|
||||
if (current == null || needed > indices) {
|
||||
int size = Math.max(MIN_INDICES, indices);
|
||||
while (size < needed) {
|
||||
size = (int) Math.min((long) size * 2, Integer.MAX_VALUE / 4 / 6 * 6);
|
||||
}
|
||||
if (current == null) {
|
||||
current = device.gl().createBuffer();
|
||||
buffer = current;
|
||||
}
|
||||
device.gl().bindBuffer(ELEMENT_ARRAY_BUFFER, current);
|
||||
WebGl.uploadQuadIndices(device.gl(), size);
|
||||
indices = size;
|
||||
return;
|
||||
}
|
||||
device.gl().bindBuffer(ELEMENT_ARRAY_BUFFER, current);
|
||||
}
|
||||
|
||||
/** Indices the buffer holds, for tests and the log. */
|
||||
int size() {
|
||||
return indices;
|
||||
}
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.STATIC_DRAW;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import org.teavm.jso.typedarrays.Int8Array;
|
||||
import org.teavm.jso.webgl.WebGLBuffer;
|
||||
|
||||
/**
|
||||
* Indices with their draw's base vertex already added (ADR 0022), for draws with index buffers of
|
||||
* their own, which the backend's sequential quads can't replace. The game sorts each translucent
|
||||
* section's quads back to front into indices counted from the section's first vertex; WebGL2 has
|
||||
* no base vertex, so each section would be its own draw. Rebased, a heap's translucent sections
|
||||
* are one multi-draw, still in the game's order.
|
||||
*
|
||||
* <p>The copies live in one element buffer (the arena) and are kept from frame to frame: a
|
||||
* section's copy is reused until the game writes that part of its index heap again (a new sort,
|
||||
* {@link WebGl2Buffer#unchangedSince}), so a frame copies only the sections re-sorted since the last.
|
||||
* A re-sorted section has as many indices as before, so its new copy takes the old one's place
|
||||
* (ADR 0027); only a section new to the arena, or one whose size or base vertex changed, is
|
||||
* appended. When the arena fills, it starts over and everything is copied again.
|
||||
*
|
||||
* <p>Hot path: nothing allocates once the arena, the staging buffer and the caches have grown.
|
||||
*/
|
||||
final class RebasedIndices {
|
||||
|
||||
private static final int MIN_INDICES = 1 << 18;
|
||||
|
||||
/** A copy: where it is in the arena, and what it was copied from. */
|
||||
static final class Copy {
|
||||
int epoch;
|
||||
int offset;
|
||||
int count;
|
||||
int baseVertex;
|
||||
int indexSize;
|
||||
int version;
|
||||
}
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final WebGLBuffer arena;
|
||||
/** Counts the arena's restarts: a copy from an earlier one is gone. */
|
||||
private int epoch;
|
||||
|
||||
private int capacity;
|
||||
private int used;
|
||||
/** Where this batch's new copies start in the arena; they're staged until {@link #upload}. */
|
||||
private int stagedFrom;
|
||||
|
||||
private ByteBuffer staging = ByteBuffer.allocateDirect(256 * 1024).order(ByteOrder.LITTLE_ENDIAN);
|
||||
/** A kept view of the staging buffer (hot path: none made per upload), remade when detached or replaced. */
|
||||
private @Nullable Int8Array stagingView;
|
||||
|
||||
/** Copies rewritten in place this batch, staged one after another (see {@link #rewrite}). */
|
||||
private ByteBuffer rewrites = ByteBuffer.allocateDirect(64 * 1024).order(ByteOrder.LITTLE_ENDIAN);
|
||||
|
||||
private @Nullable Int8Array rewritesView;
|
||||
/** Per rewrite: where it goes in the arena, where it is in {@link #rewrites}, and its count (indices). */
|
||||
private int[] rewriteRanges = new int[3 * 64];
|
||||
|
||||
private int rewriteCount;
|
||||
private int rewriteUsed;
|
||||
|
||||
RebasedIndices(WebGl2Device device) {
|
||||
this.device = device;
|
||||
this.arena = device.gl().createBuffer();
|
||||
resize(MIN_INDICES);
|
||||
}
|
||||
|
||||
/** Starts a batch that will need at most {@code indices} new indices. */
|
||||
void begin(long indices) {
|
||||
if (used + indices > capacity) {
|
||||
// Start over: every copy is made again, in a larger arena if one batch needs it.
|
||||
epoch++;
|
||||
used = 0;
|
||||
if (indices > capacity) {
|
||||
long size = capacity;
|
||||
while (size < indices) {
|
||||
size *= 2;
|
||||
}
|
||||
resize((int) Math.min(size, Integer.MAX_VALUE / 4));
|
||||
}
|
||||
}
|
||||
stagedFrom = used;
|
||||
}
|
||||
|
||||
/**
|
||||
* The byte offset in the arena of {@code indexCount} indices of {@code indexSize} bytes from
|
||||
* index {@code firstIndex} of {@code source}, each plus {@code baseVertex}: a kept copy if it's
|
||||
* still good, else a new one.
|
||||
*/
|
||||
int offsetOf(WebGl2Buffer source, int indexSize, int firstIndex, int indexCount, int baseVertex) {
|
||||
Int2ObjectOpenHashMap<Copy> kept = source.rebasedCopies();
|
||||
Copy copy = kept.get(firstIndex);
|
||||
if (copy != null
|
||||
&& copy.epoch == epoch
|
||||
&& copy.count == indexCount
|
||||
&& copy.baseVertex == baseVertex
|
||||
&& copy.indexSize == indexSize
|
||||
&& source.unchangedSince(firstIndex * indexSize, indexCount * indexSize, copy.version)) {
|
||||
return copy.offset * 4;
|
||||
}
|
||||
if (copy != null
|
||||
&& copy.epoch == epoch
|
||||
&& copy.count == indexCount
|
||||
&& copy.baseVertex == baseVertex
|
||||
&& copy.indexSize == indexSize) {
|
||||
// Re-sorted: the same indices in a new order, written over the old copy.
|
||||
copy.version = source.version();
|
||||
rewrite(source.memory(), indexSize, firstIndex, indexCount, baseVertex, copy.offset);
|
||||
return copy.offset * 4;
|
||||
}
|
||||
if (copy == null) {
|
||||
copy = new Copy();
|
||||
kept.put(firstIndex, copy);
|
||||
}
|
||||
copy.epoch = epoch;
|
||||
copy.offset = used;
|
||||
copy.count = indexCount;
|
||||
copy.baseVertex = baseVertex;
|
||||
copy.indexSize = indexSize;
|
||||
copy.version = source.version();
|
||||
stage(source.memory(), indexSize, firstIndex, indexCount, baseVertex);
|
||||
return copy.offset * 4;
|
||||
}
|
||||
|
||||
/** Uploads this batch's new copies and binds the arena as the element array buffer. */
|
||||
void upload() {
|
||||
device.gl().bindBuffer(ELEMENT_ARRAY_BUFFER, arena);
|
||||
int bytes = (used - stagedFrom) * 4;
|
||||
if (bytes > 0) {
|
||||
Int8Array view = stagingView;
|
||||
if (view == null || !WebGl.bufferSubData(device.gl(), ELEMENT_ARRAY_BUFFER, stagedFrom * 4, view, bytes)) {
|
||||
view = Int8Array.fromJavaBuffer(staging);
|
||||
stagingView = view;
|
||||
WebGl.bufferSubData(device.gl(), ELEMENT_ARRAY_BUFFER, stagedFrom * 4, view, bytes);
|
||||
}
|
||||
}
|
||||
stagedFrom = used;
|
||||
for (int i = 0; i < rewriteCount; i++) {
|
||||
int at = rewriteRanges[i * 3] * 4;
|
||||
int from = rewriteRanges[i * 3 + 1] * 4;
|
||||
int length = rewriteRanges[i * 3 + 2] * 4;
|
||||
Int8Array view = rewritesView;
|
||||
if (view == null || !WebGl.bufferSubDataFrom(device.gl(), ELEMENT_ARRAY_BUFFER, at, view, from, length)) {
|
||||
view = Int8Array.fromJavaBuffer(rewrites);
|
||||
rewritesView = view;
|
||||
WebGl.bufferSubDataFrom(device.gl(), ELEMENT_ARRAY_BUFFER, at, view, from, length);
|
||||
}
|
||||
}
|
||||
rewriteCount = 0;
|
||||
rewriteUsed = 0;
|
||||
}
|
||||
|
||||
/** Stages {@code indexCount} rebased indices to go over the copy at arena index {@code at} on {@link #upload}. */
|
||||
private void rewrite(ByteBuffer source, int indexSize, int firstIndex, int indexCount, int baseVertex, int at) {
|
||||
if ((long) (rewriteUsed + indexCount) * 4 > rewrites.capacity()) {
|
||||
int size = rewrites.capacity();
|
||||
while (size < (rewriteUsed + indexCount) * 4) {
|
||||
size *= 2;
|
||||
}
|
||||
ByteBuffer grown = ByteBuffer.allocateDirect(size).order(ByteOrder.LITTLE_ENDIAN);
|
||||
grown.put(0, rewrites, 0, rewriteUsed * 4);
|
||||
rewrites = grown;
|
||||
rewritesView = null;
|
||||
}
|
||||
if (rewriteCount * 3 + 3 > rewriteRanges.length) {
|
||||
rewriteRanges = Arrays.copyOf(rewriteRanges, rewriteRanges.length * 2);
|
||||
}
|
||||
rewriteRanges[rewriteCount * 3] = at;
|
||||
rewriteRanges[rewriteCount * 3 + 1] = rewriteUsed;
|
||||
rewriteRanges[rewriteCount * 3 + 2] = indexCount;
|
||||
rewriteCount++;
|
||||
copyRebased(source, indexSize, firstIndex, indexCount, baseVertex, rewrites, rewriteUsed);
|
||||
rewriteUsed += indexCount;
|
||||
}
|
||||
|
||||
private void stage(ByteBuffer source, int indexSize, int firstIndex, int indexCount, int baseVertex) {
|
||||
int at = used - stagedFrom;
|
||||
ensureStaging(at + indexCount);
|
||||
copyRebased(source, indexSize, firstIndex, indexCount, baseVertex, staging, at);
|
||||
used += indexCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the indices from {@code firstIndex}, each plus {@code baseVertex}, as 32-bit ints from
|
||||
* index {@code at} of {@code target}. Hot (every re-sorted translucent section's indices, each
|
||||
* frame the camera moves): straight loads and stores in linear memory, the ranges checked once
|
||||
* rather than at every index as the buffers' own accessors check them.
|
||||
*/
|
||||
private static void copyRebased(
|
||||
ByteBuffer source,
|
||||
int indexSize,
|
||||
int firstIndex,
|
||||
int indexCount,
|
||||
int baseVertex,
|
||||
ByteBuffer target,
|
||||
int at) {
|
||||
Objects.checkFromIndexSize(firstIndex * indexSize, indexCount * indexSize, source.capacity());
|
||||
Objects.checkFromIndexSize(at * 4, indexCount * 4, target.capacity());
|
||||
long from = MemoryUtil.memAddress(source) - source.position() + (long) firstIndex * indexSize;
|
||||
long to = MemoryUtil.memAddress(target) - target.position() + (long) at * 4;
|
||||
if (indexSize == 2) {
|
||||
for (int i = 0; i < indexCount; i++) {
|
||||
MemoryUtil.memPutInt(
|
||||
to + i * 4L, Short.toUnsignedInt(MemoryUtil.memGetShort(from + i * 2L)) + baseVertex);
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i < indexCount; i++) {
|
||||
MemoryUtil.memPutInt(to + i * 4L, MemoryUtil.memGetInt(from + i * 4L) + baseVertex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void resize(int indices) {
|
||||
capacity = indices;
|
||||
device.gl().bindBuffer(ELEMENT_ARRAY_BUFFER, arena);
|
||||
device.gl().bufferData(ELEMENT_ARRAY_BUFFER, indices * 4, STATIC_DRAW);
|
||||
}
|
||||
|
||||
private void ensureStaging(int indices) {
|
||||
if ((long) indices * 4 <= staging.capacity()) {
|
||||
return;
|
||||
}
|
||||
int size = staging.capacity();
|
||||
while (size < indices * 4) {
|
||||
size *= 2;
|
||||
}
|
||||
ByteBuffer grown = ByteBuffer.allocateDirect(size).order(ByteOrder.LITTLE_ENDIAN);
|
||||
grown.put(0, staging, 0, (used - stagedFrom) * 4);
|
||||
staging = grown;
|
||||
stagingView = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import org.teavm.jso.JSObject;
|
||||
import org.teavm.jso.typedarrays.ArrayBufferView;
|
||||
import org.teavm.jso.typedarrays.Int8Array;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* Carries bytes from the game to WebGL. Under WebAssembly GC a Java {@code byte[]} lives in the GC
|
||||
* heap, where JavaScript can't see it; only a direct buffer, which TeaVM keeps in the module's
|
||||
* linear memory, can be read by WebGL. The game's off-heap memory is in linear memory (ADR 0008),
|
||||
* so its buffers are read where they are; anything else (a heap buffer, or pixels not on
|
||||
* their element size) is copied into one direct buffer and read there.
|
||||
*
|
||||
* <p>Uploads read through views of the whole linear memory, kept from one upload to the next, with
|
||||
* the source's address as WebGL2's source offset (ADR 0027). Making a view per upload made a
|
||||
* JavaScript object per upload, which TeaVM's interop wraps and keeps in a weak map; thousands of
|
||||
* those a frame made major garbage collections pause for tens of milliseconds walking the map.
|
||||
* Hot path: no allocation, Java or JavaScript, once the copy buffer has grown to the largest copy.
|
||||
*/
|
||||
final class Staging {
|
||||
|
||||
private ByteBuffer direct = ByteBuffer.allocateDirect(64 * 1024).order(ByteOrder.LITTLE_ENDIAN);
|
||||
|
||||
/** {@link WebGl#memoryViews}: made on first use, and again when growing the memory detaches them. */
|
||||
private @Nullable JSObject memoryViews;
|
||||
|
||||
/**
|
||||
* Uploads {@code length} bytes of {@code source} from {@code offset} to the buffer bound at
|
||||
* {@code target}, at {@code destination}.
|
||||
*/
|
||||
void bufferSubData(
|
||||
WebGL2RenderingContext gl, int target, int destination, ByteBuffer source, int offset, int length) {
|
||||
int address = address(source, offset, length);
|
||||
if (!WebGl.bufferSubDataAt(gl, target, destination, views(false), address, length)) {
|
||||
WebGl.bufferSubDataAt(gl, target, destination, views(true), address, length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code texSubImage2D} with {@code length} bytes of {@code source} from {@code offset} as its
|
||||
* pixels, of pixel {@code type}. The unpack parameters apply from there, as they would to a
|
||||
* typed array starting at that byte.
|
||||
*/
|
||||
void texSubImage2D(
|
||||
WebGL2RenderingContext gl,
|
||||
int target,
|
||||
int level,
|
||||
int x,
|
||||
int y,
|
||||
int width,
|
||||
int height,
|
||||
int format,
|
||||
int type,
|
||||
ByteBuffer source,
|
||||
int offset,
|
||||
int length) {
|
||||
int address = address(source, offset, length);
|
||||
int done = WebGl.texSubImage2DAt(gl, target, level, x, y, width, height, format, type, views(false), address);
|
||||
if (done == 0) {
|
||||
done = WebGl.texSubImage2DAt(gl, target, level, x, y, width, height, format, type, views(true), address);
|
||||
}
|
||||
if (done == 2) {
|
||||
// Not on the element size: copied to the start of the copy buffer, which is.
|
||||
int aligned = copyToDirect(source, offset, length);
|
||||
if (WebGl.texSubImage2DAt(gl, target, level, x, y, width, height, format, type, views(false), aligned)
|
||||
== 0) {
|
||||
WebGl.texSubImage2DAt(gl, target, level, x, y, width, height, format, type, views(true), aligned);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A view to read pixels of {@code type} into ({@code readPixels}); copy them out with
|
||||
* {@link #readBack} before the next call. Rare (screenshots, map exports): a view per call.
|
||||
*/
|
||||
ArrayBufferView scratch(int length, int type) {
|
||||
ensureCapacity(length);
|
||||
return WebGl.typed(Int8Array.fromJavaBuffer(direct.slice(0, length)), type);
|
||||
}
|
||||
|
||||
/** Copies what {@link #scratch} received into {@code target} at {@code offset}. */
|
||||
void readBack(ByteBuffer target, int offset, int length) {
|
||||
target.put(offset, direct, 0, length);
|
||||
}
|
||||
|
||||
/** The linear-memory address of {@code source}'s byte {@code offset}; a heap buffer is copied first. */
|
||||
private int address(ByteBuffer source, int offset, int length) {
|
||||
if (!source.isDirect()) {
|
||||
return copyToDirect(source, offset, length);
|
||||
}
|
||||
return Math.toIntExact(MemoryUtil.memAddress(source) - source.position() + offset);
|
||||
}
|
||||
|
||||
/** Copies the bytes into the start of the copy buffer; its address. */
|
||||
private int copyToDirect(ByteBuffer source, int offset, int length) {
|
||||
ensureCapacity(length);
|
||||
if (source.hasArray()) {
|
||||
direct.put(0, source.array(), source.arrayOffset() + offset, length);
|
||||
} else {
|
||||
direct.put(0, source, offset, length);
|
||||
}
|
||||
return Math.toIntExact(MemoryUtil.memAddress(direct) - direct.position());
|
||||
}
|
||||
|
||||
private JSObject views(boolean remake) {
|
||||
JSObject views = memoryViews;
|
||||
if (views == null || remake) {
|
||||
// Any view of linear memory leads to its buffer; the copy buffer's is at hand.
|
||||
views = WebGl.memoryViews(Int8Array.fromJavaBuffer(direct));
|
||||
memoryViews = views;
|
||||
}
|
||||
return views;
|
||||
}
|
||||
|
||||
private void ensureCapacity(int length) {
|
||||
if (direct.capacity() < length) {
|
||||
int grown = Math.max(length, direct.capacity() * 2);
|
||||
direct = ByteBuffer.allocateDirect(grown).order(ByteOrder.LITTLE_ENDIAN);
|
||||
}
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.NEAREST;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_2D;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_MAG_FILTER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_MIN_FILTER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNPACK_ROW_LENGTH;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import incari.render.webgl2.shaders.TexelBuffers;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLTexture;
|
||||
|
||||
/**
|
||||
* A texel buffer emulated as a 2D texture (WebGL2 has no texel buffers): the buffer's elements
|
||||
* row by row, {@link TexelBuffers#WIDTH} to a row, which is how the build rewrote the shaders'
|
||||
* {@code texelFetch} calls. The copy is refreshed from the buffer's own memory when the buffer has
|
||||
* changed since, so a buffer the game rewrites now and then (the clouds' faces, rebuilt when the
|
||||
* camera crosses a cloud cell) costs one upload per change, not one per draw.
|
||||
*/
|
||||
final class TexelBufferTexture {
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final WebGLTexture handle;
|
||||
private final GpuFormat format;
|
||||
private final GlFormats.TextureFormat glFormat;
|
||||
private final int elements;
|
||||
private int version = -1;
|
||||
|
||||
TexelBufferTexture(WebGl2Device device, GpuFormat format, long bufferSize) {
|
||||
GlFormats.TextureFormat texture = GlFormats.texture(format);
|
||||
if (texture == null) {
|
||||
throw new UnsupportedOperationException("WebGL2 has no " + format + " textures for a texel buffer");
|
||||
}
|
||||
this.device = device;
|
||||
this.format = format;
|
||||
this.glFormat = texture;
|
||||
this.elements = Math.toIntExact(bufferSize / format.blockSize());
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
handle = gl.createTexture();
|
||||
device.bindTextureForUpdate(TEXTURE_2D, handle);
|
||||
gl.texStorage2D(TEXTURE_2D, 1, texture.internalFormat(), TexelBuffers.WIDTH, TexelBuffers.rows(elements));
|
||||
// Integer textures can only be sampled with nearest filtering; texelFetch ignores it anyway.
|
||||
gl.texParameteri(TEXTURE_2D, TEXTURE_MIN_FILTER, NEAREST);
|
||||
gl.texParameteri(TEXTURE_2D, TEXTURE_MAG_FILTER, NEAREST);
|
||||
}
|
||||
|
||||
GpuFormat format() {
|
||||
return format;
|
||||
}
|
||||
|
||||
WebGLTexture handle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
/** Copies {@code buffer} in if it has changed since the last copy. */
|
||||
void refresh(WebGl2Buffer buffer) {
|
||||
if (buffer.version() == version) {
|
||||
return;
|
||||
}
|
||||
version = buffer.version();
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
device.bindTextureForUpdate(TEXTURE_2D, handle);
|
||||
int blockSize = format.blockSize();
|
||||
int fullRows = elements / TexelBuffers.WIDTH;
|
||||
gl.pixelStorei(UNPACK_ROW_LENGTH, 0);
|
||||
if (fullRows > 0) {
|
||||
device.staging()
|
||||
.texSubImage2D(
|
||||
gl,
|
||||
TEXTURE_2D,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
TexelBuffers.WIDTH,
|
||||
fullRows,
|
||||
glFormat.format(),
|
||||
glFormat.type(),
|
||||
buffer.memory(),
|
||||
0,
|
||||
fullRows * TexelBuffers.WIDTH * blockSize);
|
||||
}
|
||||
int rest = elements - fullRows * TexelBuffers.WIDTH;
|
||||
if (rest > 0) {
|
||||
device.staging()
|
||||
.texSubImage2D(
|
||||
gl,
|
||||
TEXTURE_2D,
|
||||
0,
|
||||
0,
|
||||
fullRows,
|
||||
rest,
|
||||
1,
|
||||
glFormat.format(),
|
||||
glFormat.type(),
|
||||
buffer.memory(),
|
||||
fullRows * TexelBuffers.WIDTH * blockSize,
|
||||
rest * blockSize);
|
||||
}
|
||||
}
|
||||
|
||||
void close() {
|
||||
device.gl().deleteTexture(handle);
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import com.mojang.renderpearl.api.vertex.VertexFormat;
|
||||
import com.mojang.renderpearl.api.vertex.VertexFormatElement;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* Where each vertex shader input reads from: which vertex buffer slot, at what offset and stride,
|
||||
* in what format. Inputs match the vertex format's elements by name, as the game's own pipeline
|
||||
* builder matches them; an element the shader doesn't read is skipped. Pure logic, tested on a JVM.
|
||||
*/
|
||||
final class VertexLayout {
|
||||
|
||||
/**
|
||||
* One attribute.
|
||||
*
|
||||
* @param divisor 0 to advance per vertex, otherwise per that many instances
|
||||
* @param integer whether the shader reads it as an integer ({@code vertexAttribIPointer})
|
||||
*/
|
||||
record Binding(
|
||||
int slot,
|
||||
int location,
|
||||
int offset,
|
||||
int stride,
|
||||
int divisor,
|
||||
GlFormats.AttributeFormat format,
|
||||
boolean integer) {}
|
||||
|
||||
/** Thrown when the shader reads an input no vertex format element provides. */
|
||||
static final class MismatchException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
MismatchException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A pipeline's per-instance inputs read as rows by {@code gl_DrawID} instead of as attributes
|
||||
* ({@link DrawIdRewrite}).
|
||||
*
|
||||
* @param slot the vertex buffer slot the instance data comes from
|
||||
* @param stride bytes per instance, at most a row
|
||||
* @param inputs the inputs, where each is in a row
|
||||
* @param attributes the bindings still read as attributes (the per-vertex ones)
|
||||
*/
|
||||
record DrawRowLayout(int slot, int stride, List<DrawIdRewrite.Input> inputs, List<Binding> attributes) {}
|
||||
|
||||
private VertexLayout() {}
|
||||
|
||||
/**
|
||||
* How {@code bindings}' per-instance inputs fit in a row, or null if there are none or they
|
||||
* don't: they must all come from one slot, in 32-bit components, within a row's 16 bytes.
|
||||
*/
|
||||
static @Nullable DrawRowLayout drawRows(List<Binding> bindings, List<TranslatedStage.Attribute> inputs) {
|
||||
Map<Integer, String> names = new HashMap<>();
|
||||
for (TranslatedStage.Attribute input : inputs) {
|
||||
names.put(input.location(), input.name());
|
||||
}
|
||||
int slot = -1;
|
||||
int stride = 0;
|
||||
List<DrawIdRewrite.Input> rows = new ArrayList<>();
|
||||
List<Binding> attributes = new ArrayList<>();
|
||||
for (Binding binding : bindings) {
|
||||
if (binding.divisor() == 0) {
|
||||
attributes.add(binding);
|
||||
continue;
|
||||
}
|
||||
GlFormats.AttributeFormat format = binding.format();
|
||||
DrawIdRewrite.Kind kind = format.normalized()
|
||||
? null
|
||||
: switch (format.type()) {
|
||||
case WebGL2RenderingContext.INT -> binding.integer() ? DrawIdRewrite.Kind.INT : null;
|
||||
case WebGL2RenderingContext.UNSIGNED_INT -> binding.integer() ? DrawIdRewrite.Kind.UINT : null;
|
||||
case WebGL2RenderingContext.FLOAT -> binding.integer() ? null : DrawIdRewrite.Kind.FLOAT;
|
||||
default -> null;
|
||||
};
|
||||
String name = names.get(binding.location());
|
||||
if (kind == null
|
||||
|| name == null
|
||||
|| (slot >= 0 && binding.slot() != slot)
|
||||
|| binding.stride() > DrawIdRewrite.ROW_BYTES
|
||||
|| binding.offset() % 4 != 0
|
||||
|| binding.offset() + 4 * format.size() > DrawIdRewrite.ROW_BYTES) {
|
||||
return null;
|
||||
}
|
||||
slot = binding.slot();
|
||||
stride = binding.stride();
|
||||
rows.add(new DrawIdRewrite.Input(name, binding.offset() / 4, kind));
|
||||
}
|
||||
return rows.isEmpty() ? null : new DrawRowLayout(slot, stride, List.copyOf(rows), List.copyOf(attributes));
|
||||
}
|
||||
|
||||
static List<Binding> of(List<@Nullable VertexFormat> formats, List<TranslatedStage.Attribute> inputs)
|
||||
throws MismatchException {
|
||||
Map<String, TranslatedStage.Attribute> byName = new HashMap<>();
|
||||
for (TranslatedStage.Attribute input : inputs) {
|
||||
byName.put(input.name(), input);
|
||||
}
|
||||
Map<Integer, TranslatedStage.Attribute> covered = new HashMap<>();
|
||||
List<Binding> bindings = new ArrayList<>();
|
||||
for (int slot = 0; slot < formats.size(); slot++) {
|
||||
VertexFormat format = formats.get(slot);
|
||||
if (format == null) {
|
||||
continue;
|
||||
}
|
||||
String previousName = null;
|
||||
int previousLocation = 0;
|
||||
for (VertexFormatElement element : format.getElements()) {
|
||||
TranslatedStage.Attribute input = byName.get(element.name());
|
||||
if (input == null) {
|
||||
continue;
|
||||
}
|
||||
// An element repeating the previous one's name fills the next location of the same
|
||||
// input (a matrix, or an array of vectors), as in the game's pipeline builder.
|
||||
int location = element.name().equals(previousName) ? previousLocation + 1 : input.location();
|
||||
bindings.add(new Binding(
|
||||
slot,
|
||||
location,
|
||||
element.offset(),
|
||||
format.getVertexSize(),
|
||||
format.getStepRate(),
|
||||
GlFormats.attribute(element.format()),
|
||||
input.integer()));
|
||||
covered.put(location, input);
|
||||
previousName = element.name();
|
||||
previousLocation = location;
|
||||
}
|
||||
}
|
||||
for (TranslatedStage.Attribute input : inputs) {
|
||||
if (!covered.containsKey(input.location())) {
|
||||
throw new MismatchException("vertex input " + input.name() + " has no matching vertex format element");
|
||||
}
|
||||
}
|
||||
return bindings;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.JSBody;
|
||||
import org.teavm.jso.JSObject;
|
||||
import org.teavm.jso.typedarrays.ArrayBufferView;
|
||||
import org.teavm.jso.typedarrays.Int8Array;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLProgram;
|
||||
|
||||
/**
|
||||
* Every JavaScript snippet the WebGL2 backend runs, in one file so the page surface is easy to
|
||||
* audit (like {@code platform-web}'s {@code Dom}). Everything else uses TeaVM's typed
|
||||
* {@link WebGL2RenderingContext}.
|
||||
*/
|
||||
final class WebGl {
|
||||
|
||||
/** EXT_texture_filter_anisotropic's enums. */
|
||||
static final int TEXTURE_MAX_ANISOTROPY = 0x84FE;
|
||||
|
||||
static final int MAX_TEXTURE_MAX_ANISOTROPY = 0x84FF;
|
||||
|
||||
/** WEBGL_debug_renderer_info's enums. */
|
||||
static final int UNMASKED_VENDOR = 0x9245;
|
||||
|
||||
static final int UNMASKED_RENDERER = 0x9246;
|
||||
|
||||
private WebGl() {}
|
||||
|
||||
@JSBody(script = "return typeof WebGL2RenderingContext !== 'undefined';")
|
||||
static native boolean isSupported();
|
||||
|
||||
/**
|
||||
* The canvas's WebGL2 context, or null if the browser won't make one. The game draws into its
|
||||
* own framebuffers and blits to the canvas once a frame, so the canvas gets no depth, stencil,
|
||||
* alpha or antialiasing (each costs memory and a resolve on low-end GPUs).
|
||||
*/
|
||||
@JSBody(
|
||||
params = "canvasId",
|
||||
script = "var canvas = document.getElementById(canvasId);"
|
||||
+ "if (!canvas || !canvas.getContext) return null;"
|
||||
+ "var gl = canvas.getContext('webgl2', { alpha: false, depth: false, stencil: false,"
|
||||
+ " antialias: false, premultipliedAlpha: false, preserveDrawingBuffer: false,"
|
||||
+ " powerPreference: 'high-performance' }) || null;"
|
||||
+ "if (gl && !canvas.__incariGlWatched) { canvas.__incariGlWatched = true;"
|
||||
// Cancelled, so the browser may give the context back. What was on the GPU
|
||||
// (textures, meshes, shaders) isn't: the game keeps no copies to upload again,
|
||||
// so the page must be reloaded. The platform's event queue hears of it through
|
||||
// the canvas's sink (platform-web's Dom.listen) and reports the window
|
||||
// minimized: the game stops drawing and, minimized, saves its singleplayer world.
|
||||
+ " canvas.addEventListener('webglcontextlost', function(e) { e.preventDefault();"
|
||||
+ " console.error('[Incari] The WebGL context was lost; the page must be reloaded');"
|
||||
+ " var sink = canvas.__incariSink; if (sink) sink('graphics', '', '', 1, 0, 0, 0, 0, 0);"
|
||||
+ " if (document.pointerLockElement && document.exitPointerLock) document.exitPointerLock();"
|
||||
+ " if (document.fullscreenElement && document.exitFullscreen) {"
|
||||
+ " var p = document.exitFullscreen(); if (p && p.catch) p.catch(function() {}); }"
|
||||
+ " if (document.getElementById('incari-graphics-lost')) return;"
|
||||
+ " var box = document.createElement('div'); box.id = 'incari-graphics-lost';"
|
||||
+ " box.setAttribute('role', 'alert');"
|
||||
+ " box.style.cssText = 'position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);"
|
||||
+ "max-width:min(420px,90vw);padding:16px 20px;border-radius:8px;background:rgba(0,0,0,0.85);"
|
||||
+ "color:#eee;font:15px/1.4 system-ui,sans-serif;text-align:center;z-index:2147483647';"
|
||||
+ " var text = document.createElement('p'); text.style.margin = '0 0 12px';"
|
||||
+ " text.textContent = 'The graphics stopped working (the browser reset them). "
|
||||
+ "Singleplayer worlds are being saved. Reload the page to keep playing.';"
|
||||
+ " var button = document.createElement('button'); button.textContent = 'Reload';"
|
||||
+ " button.style.cssText = 'font:inherit;padding:6px 18px;cursor:pointer';"
|
||||
+ " button.addEventListener('click', function() { location.reload(); });"
|
||||
+ " box.appendChild(text); box.appendChild(button); document.body.appendChild(box); });"
|
||||
+ " canvas.addEventListener('webglcontextrestored', function() {"
|
||||
+ " console.warn('[Incari] The WebGL context came back, empty; reload the page to draw again'); }); }"
|
||||
+ "return gl;")
|
||||
static native @Nullable WebGL2RenderingContext context(String canvasId);
|
||||
|
||||
/** Turns an extension on; false if the browser doesn't have it. */
|
||||
@JSBody(
|
||||
params = {"gl", "name"},
|
||||
script = "return !!gl.getExtension(name);")
|
||||
static native boolean enableExtension(WebGL2RenderingContext gl, String name);
|
||||
|
||||
/**
|
||||
* Makes clip space's depth run from 0 to 1, as the game's desktop backends set it up
|
||||
* ({@code glClipControl}), with EXT_clip_control; false if the browser doesn't have it.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"gl"},
|
||||
script = "var e = gl.getExtension('EXT_clip_control'); if (!e) return false;"
|
||||
+ " e.clipControlEXT(e.LOWER_LEFT_EXT, e.ZERO_TO_ONE_EXT); return true;")
|
||||
static native boolean clipControlZeroToOne(WebGL2RenderingContext gl);
|
||||
|
||||
/** WEBGL_polygon_mode, for the game's wireframe debug view, or null where the browser lacks it. */
|
||||
@JSBody(
|
||||
params = {"gl"},
|
||||
script = "return gl.getExtension('WEBGL_polygon_mode');")
|
||||
static native @Nullable JSObject polygonModeExtension(WebGL2RenderingContext gl);
|
||||
|
||||
/** Draws triangles as their outlines ({@code line}) or filled, through WEBGL_polygon_mode. */
|
||||
@JSBody(
|
||||
params = {"extension", "line"},
|
||||
script = "extension.polygonModeWEBGL(0x0408, line ? 0x1B01 : 0x1B02);")
|
||||
static native void polygonMode(JSObject extension, boolean line);
|
||||
|
||||
@JSBody(
|
||||
params = {"gl"},
|
||||
script = "return gl.getSupportedExtensions() || [];")
|
||||
static native JSObject supportedExtensions(WebGL2RenderingContext gl);
|
||||
|
||||
@JSBody(
|
||||
params = {"list"},
|
||||
script = "return list.length;")
|
||||
static native int length(JSObject list);
|
||||
|
||||
@JSBody(
|
||||
params = {"list", "index"},
|
||||
script = "return String(list[index]);")
|
||||
static native String stringAt(JSObject list, int index);
|
||||
|
||||
/** A linked program's uniform block's size in bytes ({@code UNIFORM_BLOCK_DATA_SIZE}). */
|
||||
@JSBody(
|
||||
params = {"gl", "program", "block"},
|
||||
script = "return gl.getActiveUniformBlockParameter(program, block, 0x8A40) | 0;")
|
||||
static native int uniformBlockDataSize(WebGL2RenderingContext gl, WebGLProgram program, int block);
|
||||
|
||||
/** A string parameter, or "" where the browser hides it (the unmasked renderer, for one). */
|
||||
@JSBody(
|
||||
params = {"gl", "name"},
|
||||
script = "var v = gl.getParameter(name); return v == null ? '' : String(v);")
|
||||
static native String stringParameter(WebGL2RenderingContext gl, int name);
|
||||
|
||||
/** A numeric parameter, or 0 where the browser has none. */
|
||||
@JSBody(
|
||||
params = {"gl", "name"},
|
||||
script = "var v = gl.getParameter(name); return typeof v === 'number' ? v : 0;")
|
||||
static native double numberParameter(WebGL2RenderingContext gl, int name);
|
||||
|
||||
@JSBody(
|
||||
params = {"gl"},
|
||||
script = "return gl.isContextLost();")
|
||||
static native boolean isContextLost(WebGL2RenderingContext gl);
|
||||
|
||||
/**
|
||||
* The same bytes as the typed array a pixel {@code type} needs: WebGL refuses texture uploads
|
||||
* and read-backs through any other kind (an {@code Int8Array} for {@code UNSIGNED_BYTE} pixels
|
||||
* is an error). {@code view} must start on the element size, which staging views do.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"view", "type"},
|
||||
script = "var C = type === 0x1401 ? Uint8Array : type === 0x1400 ? Int8Array"
|
||||
+ " : (type === 0x1403 || type === 0x140B) ? Uint16Array : type === 0x1402 ? Int16Array"
|
||||
+ " : type === 0x1404 ? Int32Array : type === 0x1406 ? Float32Array : Uint32Array;"
|
||||
+ "return new C(view.buffer, view.byteOffset, view.byteLength / C.BYTES_PER_ELEMENT);")
|
||||
static native ArrayBufferView typed(ArrayBufferView view, int type);
|
||||
|
||||
/** {@link #typed}, or null if {@code view} doesn't start on the element size. */
|
||||
@JSBody(
|
||||
params = {"view", "type"},
|
||||
script = "var C = type === 0x1401 ? Uint8Array : type === 0x1400 ? Int8Array"
|
||||
+ " : (type === 0x1403 || type === 0x140B) ? Uint16Array : type === 0x1402 ? Int16Array"
|
||||
+ " : type === 0x1404 ? Int32Array : type === 0x1406 ? Float32Array : Uint32Array;"
|
||||
+ "if (view.byteOffset % C.BYTES_PER_ELEMENT !== 0) return null;"
|
||||
+ "return new C(view.buffer, view.byteOffset, view.byteLength / C.BYTES_PER_ELEMENT);")
|
||||
static native @Nullable ArrayBufferView typedIfAligned(ArrayBufferView view, int type);
|
||||
|
||||
/**
|
||||
* Publishes the device's counters as {@code window.__incariWebGl}, for tools and the console to
|
||||
* read ({@code BrowserCheck}'s {@code eval:} step): frames, draws and skipped draws so far,
|
||||
* and the last blit's source and canvas sizes. Once a frame, so it costs one call.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"frames", "draws", "skipped", "width", "height", "canvasWidth", "canvasHeight"},
|
||||
script = "window.__incariWebGl = { frames: frames, draws: draws, skipped: skipped,"
|
||||
+ " blit: width + 'x' + height + ' -> ' + canvasWidth + 'x' + canvasHeight };")
|
||||
static native void publishStats(
|
||||
int frames, int draws, int skipped, int width, int height, int canvasWidth, int canvasHeight);
|
||||
|
||||
/** An extension's object, or null where the browser doesn't have it. */
|
||||
@JSBody(
|
||||
params = {"gl", "name"},
|
||||
script = "return gl.getExtension(name) || null;")
|
||||
static native @Nullable JSObject extension(WebGL2RenderingContext gl, String name);
|
||||
|
||||
// --- GPU timing (EXT_disjoint_timer_query_webgl2) ---------------------------------
|
||||
|
||||
@JSBody(params = "gl", script = "return gl.createQuery();")
|
||||
static native JSObject createQuery(WebGL2RenderingContext gl);
|
||||
|
||||
/** Starts timing the GPU's work into {@code query} (TIME_ELAPSED_EXT). */
|
||||
@JSBody(
|
||||
params = {"gl", "query"},
|
||||
script = "gl.beginQuery(0x88BF, query);")
|
||||
static native void beginTimer(WebGL2RenderingContext gl, JSObject query);
|
||||
|
||||
@JSBody(params = "gl", script = "gl.endQuery(0x88BF);")
|
||||
static native void endTimer(WebGL2RenderingContext gl);
|
||||
|
||||
/**
|
||||
* A finished timer's result in nanoseconds; -1 if it isn't ready yet, -2 if the GPU was
|
||||
* disjoint meanwhile (the result is meaningless: a power change, a context switch).
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"gl", "query"},
|
||||
script = "if (!gl.getQueryParameter(query, 0x8867)) return -1;"
|
||||
+ "if (gl.getParameter(0x8FBB)) return -2;"
|
||||
+ "return gl.getQueryParameter(query, 0x8866);")
|
||||
static native double timerResult(WebGL2RenderingContext gl, JSObject query);
|
||||
|
||||
// --- Multi-draw (WEBGL_multi_draw) --------------------------------------------------
|
||||
|
||||
/**
|
||||
* Views of two buffers of little-endian ints in linear memory, kept for
|
||||
* {@link #multiDrawElements}: made once, not per call (a hot path), and made again only when
|
||||
* growing the module's memory detaches them.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"counts", "offsets"},
|
||||
script = "return { counts: new Int32Array(counts.buffer, counts.byteOffset, counts.byteLength >> 2),"
|
||||
+ " offsets: new Int32Array(offsets.buffer, offsets.byteOffset, offsets.byteLength >> 2) };")
|
||||
static native JSObject intViews(Int8Array counts, Int8Array offsets);
|
||||
|
||||
/**
|
||||
* Draws {@code count} index ranges in one call: each sub-draw's index count and byte offset
|
||||
* from {@code views} ({@link #intViews}). The shader tells sub-draws apart by
|
||||
* {@code gl_DrawID}. False, drawing nothing, if the views were detached (make them again).
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"extension", "mode", "views", "type", "count"},
|
||||
script =
|
||||
"if (views.counts.length === 0) return false;"
|
||||
+ "extension.multiDrawElementsWEBGL(mode, views.counts, 0, type, views.offsets, 0, count); return true;")
|
||||
static native boolean multiDrawElements(JSObject extension, int mode, JSObject views, int type, int count);
|
||||
|
||||
/**
|
||||
* Uploads the first {@code bytes} of {@code view} (a kept view of a buffer in linear memory)
|
||||
* to {@code target} at {@code offset}. False, uploading nothing, if the view was detached.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"gl", "target", "offset", "view", "bytes"},
|
||||
script = "if (view.length === 0 && bytes > 0) return false;"
|
||||
+ "gl.bufferSubData(target, offset, view, 0, bytes); return true;")
|
||||
static native boolean bufferSubData(WebGL2RenderingContext gl, int target, int offset, Int8Array view, int bytes);
|
||||
|
||||
// --- Uploads straight from linear memory (ADR 0027) --------------------------------------
|
||||
|
||||
/**
|
||||
* Views of the whole linear memory {@code view} is in, one per element type WebGL uploads read,
|
||||
* remade only when memory growth detaches them. Every JavaScript object handed to Java is kept
|
||||
* in the runtime's weak map, so a view per upload put thousands of entries there for each major
|
||||
* collection to walk in its pause.
|
||||
*/
|
||||
@JSBody(
|
||||
params = "view",
|
||||
script = "var b = view.buffer; return { buffer: b, i8: new Int8Array(b), u8: new Uint8Array(b),"
|
||||
+ " i16: new Int16Array(b), u16: new Uint16Array(b), i32: new Int32Array(b),"
|
||||
+ " u32: new Uint32Array(b), f32: new Float32Array(b) };")
|
||||
static native JSObject memoryViews(Int8Array view);
|
||||
|
||||
/**
|
||||
* Uploads {@code bytes} from {@code address} of linear memory to {@code target} at
|
||||
* {@code offset}, through {@code views} ({@link #memoryViews}). False, uploading nothing, if
|
||||
* growing the memory detached them.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"gl", "target", "offset", "views", "address", "bytes"},
|
||||
script = "if (views.buffer.byteLength === 0) return false;"
|
||||
+ "gl.bufferSubData(target, offset, views.i8, address, bytes); return true;")
|
||||
static native boolean bufferSubDataAt(
|
||||
WebGL2RenderingContext gl, int target, int offset, JSObject views, int address, int bytes);
|
||||
|
||||
/**
|
||||
* {@code texSubImage2D} with the pixels from {@code address} of linear memory, read through the
|
||||
* view {@code type} needs (as {@link #typed} picks it). 1 when uploaded; 0, uploading nothing,
|
||||
* if growing the memory detached the views; 2 if {@code address} isn't on the element size,
|
||||
* which a typed array's offset must be.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"gl", "target", "level", "x", "y", "width", "height", "format", "type", "views", "address"},
|
||||
script = "if (views.buffer.byteLength === 0) return 0;"
|
||||
+ "var v = type === 0x1401 ? views.u8 : type === 0x1400 ? views.i8"
|
||||
+ " : (type === 0x1403 || type === 0x140B) ? views.u16 : type === 0x1402 ? views.i16"
|
||||
+ " : type === 0x1404 ? views.i32 : type === 0x1406 ? views.f32 : views.u32;"
|
||||
+ "if (address % v.BYTES_PER_ELEMENT !== 0) return 2;"
|
||||
+ "gl.texSubImage2D(target, level, x, y, width, height, format, type, v,"
|
||||
+ " address / v.BYTES_PER_ELEMENT); return 1;")
|
||||
static native int texSubImage2DAt(
|
||||
WebGL2RenderingContext gl,
|
||||
int target,
|
||||
int level,
|
||||
int x,
|
||||
int y,
|
||||
int width,
|
||||
int height,
|
||||
int format,
|
||||
int type,
|
||||
JSObject views,
|
||||
int address);
|
||||
|
||||
/**
|
||||
* Uploads {@code bytes} of {@code view} (a kept view of a buffer in linear memory) from byte
|
||||
* {@code from} to {@code target} at {@code offset}. False, uploading nothing, if the view was detached.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"gl", "target", "offset", "view", "from", "bytes"},
|
||||
script = "if (view.length === 0 && bytes > 0) return false;"
|
||||
+ "gl.bufferSubData(target, offset, view, from, bytes); return true;")
|
||||
static native boolean bufferSubDataFrom(
|
||||
WebGL2RenderingContext gl, int target, int offset, Int8Array view, int from, int bytes);
|
||||
|
||||
/**
|
||||
* Uploads {@code indices} 32-bit indices of sequential quads (0 1 2 2 3 0, then 4 5 6 6 7 4,
|
||||
* and on) into the bound element array buffer, sized to hold exactly those.
|
||||
*/
|
||||
@JSBody(
|
||||
params = {"gl", "indices"},
|
||||
script = "var data = new Uint32Array(indices);"
|
||||
+ "for (var i = 0, v = 0; i + 6 <= indices; i += 6, v += 4) {"
|
||||
+ " data[i] = v; data[i + 1] = v + 1; data[i + 2] = v + 2;"
|
||||
+ " data[i + 3] = v + 2; data[i + 4] = v + 3; data[i + 5] = v; }"
|
||||
+ "gl.bufferData(0x8893, data, 0x88E4);")
|
||||
static native void uploadQuadIndices(WebGL2RenderingContext gl, int indices);
|
||||
|
||||
@JSBody(params = "message", script = "console.warn(message);")
|
||||
static native void warn(String message);
|
||||
|
||||
@JSBody(params = "message", script = "console.info(message);")
|
||||
static native void info(String message);
|
||||
|
||||
@JSBody(params = "message", script = "console.error(message);")
|
||||
static native void error(String message);
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import com.mojang.renderpearl.api.device.BackendCreationException;
|
||||
import com.mojang.renderpearl.api.device.GpuBackend;
|
||||
import com.mojang.renderpearl.api.device.GpuDebugOptions;
|
||||
import com.mojang.renderpearl.api.device.GpuDevice;
|
||||
import com.mojang.renderpearl.frontend.FrontendGpuDevice;
|
||||
import incari.render.webgl2.shaders.ShaderManifest;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* The browser's graphics backend: a WebGL2 context on the page's canvas, under the game's own
|
||||
* frontend device. The browser build's entry point installs it with the canvas the platform made
|
||||
* and the shaders the build translated.
|
||||
*/
|
||||
public final class WebGl2Backend implements GpuBackend {
|
||||
|
||||
private final String canvasId;
|
||||
private final ShaderManifest shaders;
|
||||
private final boolean eagerShaders;
|
||||
private final boolean multiDraw;
|
||||
|
||||
/**
|
||||
* Whether every buffer keeps the game's copy of its contents, as before ADR 0025, instead
|
||||
* of large vertex-only buffers keeping none: the page's {@code ?copies=all}, to compare.
|
||||
*/
|
||||
public static void keepAllCopies(boolean all) {
|
||||
BufferCopies.keepAll = all;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether each write to a uniform buffer is uploaded when its view closes, as before ADR 0027,
|
||||
* instead of each buffer's writes together before the next draw: the page's {@code ?uniforms=each},
|
||||
* to compare.
|
||||
*/
|
||||
public static void uploadEachUniformWrite(boolean each) {
|
||||
PendingUploads.enabled = !each;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether draws from the game's sequential quad indices move the vertex attributes to their
|
||||
* base vertex, as before ADR 0027, instead of reading the backend's own quad indices from
|
||||
* there: the page's {@code ?rebase=off}, to compare.
|
||||
*/
|
||||
public static void movePointersForQuadDraws(boolean move) {
|
||||
WebGl2Device.rebaseQuadDraws = !move;
|
||||
}
|
||||
|
||||
/** The page's {@code ?drawcensus}: logs each pipeline's draws a frame every 600 frames. */
|
||||
public static void countDrawsByPipeline(boolean on) {
|
||||
WebGl2Device.census = on;
|
||||
}
|
||||
|
||||
/** The page's {@code ?gpucensus}: logs each pipeline's GPU time a frame every 600 frames. */
|
||||
public static void timeDrawsByPipeline(boolean on) {
|
||||
WebGl2Device.timeDraws = on;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param canvasId the page's canvas, which the platform owns and sizes
|
||||
* @param shaders the translated shaders ({@code shaders.json})
|
||||
* @param eagerShaders link every program when the game compiles its pipelines, instead of on
|
||||
* first use: slower to start, but every shader is checked by the browser's compiler at once
|
||||
* @param multiDraw draw terrain with WEBGL_multi_draw where the browser has it; off only
|
||||
* to compare against the draw per section
|
||||
*/
|
||||
public WebGl2Backend(String canvasId, ShaderManifest shaders, boolean eagerShaders, boolean multiDraw) {
|
||||
this.canvasId = canvasId;
|
||||
this.shaders = shaders;
|
||||
this.eagerShaders = eagerShaders;
|
||||
this.multiDraw = multiDraw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "WebGL2";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadLibrary() throws BackendCreationException {
|
||||
if (!WebGl.isSupported()) {
|
||||
throw new BackendCreationException(
|
||||
"This browser has no WebGL2", BackendCreationException.Reason.OPENGL_MISSING);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unloadLibrary() {}
|
||||
|
||||
/** The canvas is the window; the handle only has to be non-zero. */
|
||||
@Override
|
||||
public long createWindow(@Nullable String title, int width, int height, long flags) {
|
||||
return 1L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuDevice createDevice(GpuDebugOptions debugOptions) throws BackendCreationException {
|
||||
WebGL2RenderingContext gl = WebGl.context(canvasId);
|
||||
if (gl == null) {
|
||||
throw new BackendCreationException(
|
||||
"The browser didn't make a WebGL2 context (is hardware acceleration off?)",
|
||||
BackendCreationException.Reason.OPENGL_MISSING);
|
||||
}
|
||||
return new FrontendGpuDevice(new WebGl2Device(gl, shaders, eagerShaders, multiDraw));
|
||||
}
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.COPY_READ_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.COPY_WRITE_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DYNAMIC_DRAW;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.STATIC_DRAW;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
||||
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
|
||||
import com.mojang.renderpearl.backend.common.BaseGpuBuffer;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import org.teavm.jso.typedarrays.Int8Array;
|
||||
import org.teavm.jso.webgl.WebGLBuffer;
|
||||
|
||||
/**
|
||||
* A buffer as two copies: the game's (LWJGL {@code MemoryUtil} memory, since the game copies into
|
||||
* mapped memory natively by address) and WebGL's. WebGL2 can't map buffers, so the game's copy is
|
||||
* the truth: all data (writes, mapped writes, copies, texture read-backs) lands there first and is
|
||||
* then uploaded.
|
||||
*
|
||||
* <p>WebGL forbids an index buffer from ever being bound as anything else, so a buffer with
|
||||
* {@link GpuBuffer#USAGE_INDEX} is uploaded through the index target and every other buffer
|
||||
* through {@code COPY_WRITE_BUFFER}. These get no WebGL buffer:
|
||||
*
|
||||
* <ul>
|
||||
* <li>read-back targets, which the GPU never reads;
|
||||
* <li>texel buffers: WebGL2 has none, so the device reads them through a texture copied from the
|
||||
* game's copy ({@link TexelBufferTexture});
|
||||
* <li>indirect command buffers: WebGL2 has no indirect draws, so the render pass reads the game's
|
||||
* copy.
|
||||
* </ul>
|
||||
*
|
||||
* <p>Large draw-only buffers keep no game copy ({@link BufferCopies}): the terrain's vertex heaps,
|
||||
* filled only by copies from the staging buffer that go straight to WebGL. Their copies would cost
|
||||
* as much linear memory as the heaps take on the GPU (128 MB a layer). If anything asks for their
|
||||
* contents, they're read back from WebGL once and kept.
|
||||
*/
|
||||
final class WebGl2Buffer extends BaseGpuBuffer {
|
||||
|
||||
/** More than any driver pads a uniform block by: up to a vec4 of std140 rounding, and then some. */
|
||||
private static final int UNIFORM_SLACK = 256;
|
||||
|
||||
private static final int GPU_USAGES = GpuBuffer.USAGE_VERTEX | GpuBuffer.USAGE_INDEX | GpuBuffer.USAGE_UNIFORM;
|
||||
|
||||
/** Pages of {@link #pageVersions}: 4 KiB. */
|
||||
private static final int PAGE_SHIFT = 12;
|
||||
|
||||
/** The game's sequential quad indices repeat these six, four vertices further each time. */
|
||||
private static final int[] QUAD = {0, 1, 2, 2, 3, 0};
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final @Nullable WebGLBuffer handle;
|
||||
private final int uploadTarget;
|
||||
private final long glSize;
|
||||
/** The game's copy; null for a buffer only drawn from until something asks for its contents. */
|
||||
private @Nullable ByteBuffer memory;
|
||||
|
||||
private @Nullable TexelBufferTexture texelTexture;
|
||||
/** Counts changes to the contents, so copies of them (a texel buffer's texture) know when they're stale. */
|
||||
private int version;
|
||||
/** The {@link #version} {@link #quadSequenceOf} last looked at, and what it found. */
|
||||
private int quadCheckedVersion = -1;
|
||||
|
||||
private int quadCheckedSize;
|
||||
private boolean quadSequence;
|
||||
/**
|
||||
* For index buffers: the {@link #version} each 4 KiB page was last written at, so a copy of a
|
||||
* range (rebased indices, {@link RebasedIndices}) knows whether it's stale. Made on first write.
|
||||
*/
|
||||
private int @Nullable [] pageVersions;
|
||||
/** Copies of this index buffer's ranges with their base vertex added, by first index; made on first use. */
|
||||
private @Nullable Int2ObjectOpenHashMap<RebasedIndices.Copy> rebasedCopies;
|
||||
|
||||
/** The range written but not yet sent to WebGL ({@link #deferUpload}); none while {@code dirtyTo} is 0. */
|
||||
private int dirtyFrom = Integer.MAX_VALUE;
|
||||
|
||||
private int dirtyTo;
|
||||
|
||||
private boolean closed;
|
||||
|
||||
WebGl2Buffer(WebGl2Device device, @GpuBuffer.Usage int usage, long size) {
|
||||
super(usage, size);
|
||||
this.device = device;
|
||||
this.memory = BufferCopies.keepsCopy(usage, size)
|
||||
? MemoryUtil.memCalloc(Math.toIntExact(size)).order(ByteOrder.nativeOrder())
|
||||
: null;
|
||||
this.uploadTarget = (usage & GpuBuffer.USAGE_INDEX) != 0 ? ELEMENT_ARRAY_BUFFER : COPY_WRITE_BUFFER;
|
||||
// A uniform buffer gets some slack past its end, so a range can be bound at the size a
|
||||
// driver rounds a block up to even at the buffer's end (see WebGl2Pipeline#blockSize).
|
||||
this.glSize = (usage & GpuBuffer.USAGE_UNIFORM) != 0 ? size + UNIFORM_SLACK : size;
|
||||
if ((usage & GPU_USAGES) != 0) {
|
||||
handle = device.gl().createBuffer();
|
||||
device.gl().bindBuffer(uploadTarget, handle);
|
||||
// Written from the CPU often (MAP_WRITE) or once: the only hint WebGL acts on.
|
||||
int hint = (usage & GpuBuffer.USAGE_MAP_WRITE) != 0 ? DYNAMIC_DRAW : STATIC_DRAW;
|
||||
device.gl().bufferData(uploadTarget, Math.toIntExact(glSize), hint);
|
||||
} else {
|
||||
handle = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The WebGL buffer; only buffers with a GPU usage have one. */
|
||||
WebGLBuffer handle() {
|
||||
WebGLBuffer current = handle;
|
||||
if (current == null || closed) {
|
||||
throw new IllegalStateException(
|
||||
"Buffer (usage " + usage() + ") has no WebGL buffer" + (closed ? "; it's closed" : ""));
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/** The WebGL buffer's size: the buffer's, plus some slack for a uniform buffer. */
|
||||
long glSize() {
|
||||
return glSize;
|
||||
}
|
||||
|
||||
/** Whether the game's copy is here: else the contents are only in WebGL. */
|
||||
boolean hasCopy() {
|
||||
return memory != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The game's copy of the contents. A buffer that kept none reads its contents back from WebGL
|
||||
* now (a wait for the GPU) and keeps them from then on.
|
||||
*/
|
||||
ByteBuffer memory() {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("Buffer is closed");
|
||||
}
|
||||
ByteBuffer current = memory;
|
||||
if (current == null) {
|
||||
WebGl.warn("[Incari] Reading back a vertex buffer that kept no copy (usage " + usage() + ", " + size()
|
||||
+ " bytes): it keeps one from now on");
|
||||
current = MemoryUtil.memCalloc(Math.toIntExact(size())).order(ByteOrder.nativeOrder());
|
||||
if (handle != null) {
|
||||
device.gl().bindBuffer(COPY_READ_BUFFER, handle);
|
||||
device.gl().getBufferSubData(COPY_READ_BUFFER, 0, Int8Array.fromJavaBuffer(current));
|
||||
}
|
||||
memory = current;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBufferSlice.MappedView map(long offset, long length, boolean read, boolean write) {
|
||||
int start = Math.toIntExact(offset);
|
||||
int count = Math.toIntExact(length);
|
||||
ByteBuffer view = memory().slice(start, count).order(ByteOrder.nativeOrder());
|
||||
// Written bytes reach WebGL when the view is closed, as unmapping flushes them on a desktop
|
||||
// GPU; a uniform buffer's, before the next draw, with whatever else was written meanwhile.
|
||||
Runnable onClose;
|
||||
if (!write) {
|
||||
onClose = () -> {};
|
||||
} else if ((usage() & GpuBuffer.USAGE_UNIFORM) != 0 && PendingUploads.enabled) {
|
||||
onClose = () -> deferUpload(start, count);
|
||||
} else {
|
||||
onClose = () -> upload(start, count);
|
||||
}
|
||||
return new GpuBufferSlice.MappedView(slice(offset, length), view, onClose);
|
||||
}
|
||||
|
||||
/** Copies {@code data}'s remaining bytes in at {@code offset}, and on to WebGL. */
|
||||
void write(int offset, ByteBuffer data) {
|
||||
int length = data.remaining();
|
||||
ByteBuffer current = memory;
|
||||
if (current == null) {
|
||||
uploadFrom(offset, data, data.position(), length);
|
||||
return;
|
||||
}
|
||||
current.put(offset, data, data.position(), length);
|
||||
upload(offset, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies {@code length} bytes of {@code source} from {@code sourceOffset} in at
|
||||
* {@code offset}: into the game's copy and on to WebGL, or, for a buffer without one, to WebGL
|
||||
* alone.
|
||||
*/
|
||||
void copyFrom(int offset, WebGl2Buffer source, int sourceOffset, int length) {
|
||||
ByteBuffer current = memory;
|
||||
if (current != null) {
|
||||
current.put(offset, source.memory(), sourceOffset, length);
|
||||
upload(offset, length);
|
||||
} else if (source.hasCopy()) {
|
||||
uploadFrom(offset, source.memory(), sourceOffset, length);
|
||||
} else {
|
||||
// Both only in WebGL: copied there. Neither is an index buffer, which WebGL keeps apart.
|
||||
version++;
|
||||
if (handle != null && !closed && length > 0) {
|
||||
device.gl().bindBuffer(COPY_READ_BUFFER, source.handle());
|
||||
device.gl().bindBuffer(COPY_WRITE_BUFFER, handle);
|
||||
device.gl().copyBufferSubData(COPY_READ_BUFFER, COPY_WRITE_BUFFER, sourceOffset, offset, length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends {@code length} bytes of {@code data} from {@code from} to WebGL at {@code offset}: a buffer without a copy. */
|
||||
private void uploadFrom(int offset, ByteBuffer data, int from, int length) {
|
||||
version++;
|
||||
if (handle == null || closed || length == 0) {
|
||||
return;
|
||||
}
|
||||
device.gl().bindBuffer(uploadTarget, handle);
|
||||
device.staging().bufferSubData(device.gl(), uploadTarget, offset, data, from, length);
|
||||
}
|
||||
|
||||
/** How many times the contents have changed. */
|
||||
int version() {
|
||||
return version;
|
||||
}
|
||||
|
||||
/**
|
||||
* This buffer as a texel buffer of {@code format}: a texture holding its current contents, made
|
||||
* on first use and refreshed when the contents have changed.
|
||||
*/
|
||||
TexelBufferTexture texelTexture(GpuFormat format) {
|
||||
TexelBufferTexture texture = texelTexture;
|
||||
if (texture == null || texture.format() != format) {
|
||||
if (texture != null) {
|
||||
texture.close();
|
||||
}
|
||||
texture = new TexelBufferTexture(device, format, size());
|
||||
texelTexture = texture;
|
||||
}
|
||||
texture.refresh(this);
|
||||
return texture;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the contents, read as indices of {@code indexSize} bytes, are the game's sequential
|
||||
* quads from vertex 0 on (its shared quad index buffer). Looked at once per change of the
|
||||
* contents.
|
||||
*/
|
||||
boolean quadSequenceOf(int indexSize) {
|
||||
if (quadCheckedVersion == version && quadCheckedSize == indexSize) {
|
||||
return quadSequence;
|
||||
}
|
||||
quadCheckedVersion = version;
|
||||
quadCheckedSize = indexSize;
|
||||
ByteBuffer contents = memory();
|
||||
int indices = (int) (size() / indexSize) / 6 * 6;
|
||||
boolean matches = indices > 0;
|
||||
for (int i = 0; matches && i < indices; i++) {
|
||||
int value = indexSize == 2
|
||||
? Short.toUnsignedInt(contents.getShort(i * 2))
|
||||
: indexSize == 4 ? contents.getInt(i * 4) : -1;
|
||||
matches = value == i / 6 * 4 + QUAD[i % 6];
|
||||
}
|
||||
quadSequence = matches;
|
||||
return matches;
|
||||
}
|
||||
|
||||
/** The copies {@link RebasedIndices} keeps of this buffer's ranges. */
|
||||
Int2ObjectOpenHashMap<RebasedIndices.Copy> rebasedCopies() {
|
||||
Int2ObjectOpenHashMap<RebasedIndices.Copy> copies = rebasedCopies;
|
||||
if (copies == null) {
|
||||
copies = new Int2ObjectOpenHashMap<>();
|
||||
rebasedCopies = copies;
|
||||
}
|
||||
return copies;
|
||||
}
|
||||
|
||||
/** Whether bytes {@code offset} to {@code offset + length} are unchanged since {@code sinceVersion}. */
|
||||
boolean unchangedSince(int offset, int length, int sinceVersion) {
|
||||
int[] pages = pageVersions;
|
||||
if (pages == null) {
|
||||
return true;
|
||||
}
|
||||
int last = Math.min(pages.length - 1, (offset + Math.max(length, 1) - 1) >> PAGE_SHIFT);
|
||||
for (int page = offset >> PAGE_SHIFT; page <= last; page++) {
|
||||
if (pages[page] > sinceVersion) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notes that bytes {@code offset} to {@code offset + length} of the game's copy changed, to be
|
||||
* sent to WebGL before the next draw with any other range written meanwhile ({@link PendingUploads}).
|
||||
*/
|
||||
private void deferUpload(int offset, int length) {
|
||||
if (length == 0) {
|
||||
return;
|
||||
}
|
||||
version++;
|
||||
if (dirtyTo == 0) {
|
||||
device.pendingUploads().add(this);
|
||||
}
|
||||
dirtyFrom = Math.min(dirtyFrom, offset);
|
||||
dirtyTo = Math.max(dirtyTo, offset + length);
|
||||
}
|
||||
|
||||
/** Sends the range {@link #deferUpload} noted, as one upload. */
|
||||
void flushUpload() {
|
||||
int from = dirtyFrom;
|
||||
int to = dirtyTo;
|
||||
dirtyFrom = Integer.MAX_VALUE;
|
||||
dirtyTo = 0;
|
||||
if (to > from) {
|
||||
upload(from, to - from);
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends a range of the game's copy to WebGL. */
|
||||
void upload(int offset, int length) {
|
||||
version++;
|
||||
if ((usage() & GpuBuffer.USAGE_INDEX) != 0 && length > 0) {
|
||||
int[] pages = pageVersions;
|
||||
if (pages == null) {
|
||||
pages = new int[(int) ((size() >> PAGE_SHIFT) + 1)];
|
||||
pageVersions = pages;
|
||||
}
|
||||
int last = Math.min(pages.length - 1, (offset + length - 1) >> PAGE_SHIFT);
|
||||
for (int page = offset >> PAGE_SHIFT; page <= last; page++) {
|
||||
pages[page] = version;
|
||||
}
|
||||
}
|
||||
if (handle == null || closed || length == 0) {
|
||||
return;
|
||||
}
|
||||
device.gl().bindBuffer(uploadTarget, handle);
|
||||
device.staging().bufferSubData(device.gl(), uploadTarget, offset, memory(), offset, length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
if (handle != null) {
|
||||
device.gl().deleteBuffer(handle);
|
||||
}
|
||||
TexelBufferTexture texture = texelTexture;
|
||||
if (texture != null) {
|
||||
texture.close();
|
||||
texelTexture = null;
|
||||
}
|
||||
if (memory != null) {
|
||||
MemoryUtil.memFree(memory);
|
||||
memory = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.COLOR;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.COLOR_BUFFER_BIT;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DEPTH;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DEPTH_BUFFER_BIT;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DRAW_FRAMEBUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.NEAREST;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.PACK_ALIGNMENT;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.READ_FRAMEBUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.SCISSOR_TEST;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNPACK_ALIGNMENT;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNPACK_ROW_LENGTH;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNPACK_SKIP_PIXELS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNPACK_SKIP_ROWS;
|
||||
|
||||
import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
||||
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
|
||||
import com.mojang.renderpearl.api.buffers.TransientMemory;
|
||||
import com.mojang.renderpearl.api.commands.GpuFence;
|
||||
import com.mojang.renderpearl.api.commands.GpuQueryPool;
|
||||
import com.mojang.renderpearl.api.commands.RenderPassDescriptor;
|
||||
import com.mojang.renderpearl.api.textures.GpuTexture;
|
||||
import com.mojang.renderpearl.backend.api.CommandEncoderBackend;
|
||||
import com.mojang.renderpearl.backend.api.RenderPassBackend;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import org.joml.Vector4fc;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* Commands run as they're recorded: WebGL is an immediate API with one queue, so there's nothing
|
||||
* to batch until submit, which only recycles the frame's transient memory. The game's frontend
|
||||
* checks every argument before it gets here.
|
||||
*
|
||||
* <p>Copies that read from the GPU ({@code copyTextureToBuffer}) block on {@code readPixels}. The
|
||||
* game uses them for screenshots and map exports, not every frame; making them asynchronous
|
||||
* (pixel pack buffers and a fence) is left for later.
|
||||
*/
|
||||
final class WebGl2CommandEncoder implements CommandEncoderBackend {
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final WebGl2TransientMemory transientMemory;
|
||||
private final float[] clearColor = new float[4];
|
||||
private final float[] clearDepth = new float[1];
|
||||
|
||||
WebGl2CommandEncoder(WebGl2Device device) {
|
||||
this.device = device;
|
||||
this.transientMemory = new WebGl2TransientMemory(device);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void submit() {
|
||||
transientMemory.release();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransientMemory transientMemory() {
|
||||
return transientMemory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderPassBackend createRenderPass(RenderPassDescriptor descriptor) {
|
||||
device.gpuTimer().frameWork();
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
List<RenderPassDescriptor.@Nullable Attachment<Optional<Vector4fc>>> colors = descriptor.colorAttachments();
|
||||
List<Framebuffers.@Nullable Attachment> colorAttachments = new ArrayList<>(colors.size());
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
for (RenderPassDescriptor.Attachment<Optional<Vector4fc>> color : colors) {
|
||||
WebGl2TextureView view = color == null ? null : (WebGl2TextureView) color.textureView();
|
||||
colorAttachments.add(Framebuffers.Attachment.of(view));
|
||||
if (view != null) {
|
||||
width = view.getWidth(0);
|
||||
height = view.getHeight(0);
|
||||
}
|
||||
}
|
||||
RenderPassDescriptor.Attachment<OptionalDouble> depth = descriptor.depthAttachment();
|
||||
WebGl2TextureView depthView = depth == null ? null : (WebGl2TextureView) depth.textureView();
|
||||
if (depthView != null && width == 0) {
|
||||
width = depthView.getWidth(0);
|
||||
height = depthView.getHeight(0);
|
||||
}
|
||||
device.framebuffers().bind(DRAW_FRAMEBUFFER, colorAttachments, Framebuffers.Attachment.of(depthView));
|
||||
|
||||
// Clears and draws are limited to the render area; the viewport covers the whole target.
|
||||
var area = descriptor.renderArea();
|
||||
gl.enable(SCISSOR_TEST);
|
||||
gl.scissor(area.x(), area.y(), area.width(), area.height());
|
||||
for (int i = 0; i < colors.size(); i++) {
|
||||
RenderPassDescriptor.Attachment<Optional<Vector4fc>> color = colors.get(i);
|
||||
if (color != null && color.clearValue().isPresent()) {
|
||||
device.state().colorMask(15);
|
||||
gl.clearBufferfv(COLOR, i, rgba(color.clearValue().get()));
|
||||
}
|
||||
}
|
||||
if (depth != null && depth.clearValue().isPresent()) {
|
||||
device.state().depthMask(true);
|
||||
gl.clearBufferfv(DEPTH, 0, depth((float) depth.clearValue().getAsDouble()));
|
||||
}
|
||||
gl.viewport(0, 0, width, height);
|
||||
return new WebGl2RenderPass(device, area);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void submitRenderPass() {
|
||||
// Nothing to end: the pass's commands ran as they came.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearColorTexture(GpuTexture colorTexture, Vector4fc color) {
|
||||
device.gpuTimer().frameWork();
|
||||
WebGl2Texture texture = (WebGl2Texture) colorTexture;
|
||||
for (int level = 0; level < texture.getMipLevels(); level++) {
|
||||
device.framebuffers().bindSingle(DRAW_FRAMEBUFFER, texture, level);
|
||||
prepareFullClear(true, false);
|
||||
device.gl().clearBufferfv(COLOR, 0, rgba(color));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearColorAndDepthTextures(
|
||||
GpuTexture colorTexture, Vector4fc color, GpuTexture depthTexture, double clearDepth) {
|
||||
clearColorTexture(colorTexture, color);
|
||||
clearDepthTexture(depthTexture, clearDepth);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearColorAndDepthTextures(
|
||||
GpuTexture colorTexture,
|
||||
Vector4fc color,
|
||||
GpuTexture depthTexture,
|
||||
double clearDepth,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int regionWidth,
|
||||
int regionHeight,
|
||||
int mipLevel) {
|
||||
device.gpuTimer().frameWork();
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
List<Framebuffers.@Nullable Attachment> colors = new ArrayList<>(1);
|
||||
colors.add(new Framebuffers.Attachment((WebGl2Texture) colorTexture, mipLevel));
|
||||
device.framebuffers()
|
||||
.bind(DRAW_FRAMEBUFFER, colors, new Framebuffers.Attachment((WebGl2Texture) depthTexture, mipLevel));
|
||||
device.state().colorMask(15);
|
||||
device.state().depthMask(true);
|
||||
gl.enable(SCISSOR_TEST);
|
||||
gl.scissor(regionX, regionY, regionWidth, regionHeight);
|
||||
gl.clearBufferfv(COLOR, 0, rgba(color));
|
||||
gl.clearBufferfv(DEPTH, 0, depth((float) clearDepth));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDepthTexture(GpuTexture depthTexture, double clearDepth) {
|
||||
device.gpuTimer().frameWork();
|
||||
WebGl2Texture texture = (WebGl2Texture) depthTexture;
|
||||
for (int level = 0; level < texture.getMipLevels(); level++) {
|
||||
device.framebuffers().bindSingle(DRAW_FRAMEBUFFER, texture, level);
|
||||
prepareFullClear(false, true);
|
||||
device.gl().clearBufferfv(DEPTH, 0, depth((float) clearDepth));
|
||||
}
|
||||
}
|
||||
|
||||
private void prepareFullClear(boolean color, boolean depth) {
|
||||
device.gl().disable(SCISSOR_TEST);
|
||||
if (color) {
|
||||
device.state().colorMask(15);
|
||||
}
|
||||
if (depth) {
|
||||
device.state().depthMask(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToBuffer(GpuBufferSlice destination, ByteBuffer data) {
|
||||
((WebGl2Buffer) destination.buffer()).write(Math.toIntExact(destination.offset()), data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copyToBuffer(GpuBufferSlice source, GpuBufferSlice target) {
|
||||
// The game's copy of a buffer that keeps one is current: the copy happens there and is
|
||||
// uploaded (or uploaded straight from it, into a buffer that keeps none).
|
||||
WebGl2Buffer from = (WebGl2Buffer) source.buffer();
|
||||
WebGl2Buffer to = (WebGl2Buffer) target.buffer();
|
||||
to.copyFrom(
|
||||
Math.toIntExact(target.offset()),
|
||||
from,
|
||||
Math.toIntExact(source.offset()),
|
||||
Math.toIntExact(source.length()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToTexture(
|
||||
GpuTexture destination,
|
||||
ByteBuffer source,
|
||||
int mipLevel,
|
||||
int depthOrLayer,
|
||||
int destX,
|
||||
int destY,
|
||||
int width,
|
||||
int height) {
|
||||
WebGl2Texture texture = (WebGl2Texture) destination;
|
||||
GlFormats.TextureFormat format = texture.glFormat();
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
device.bindTextureForUpdate(texture.target(), texture.handle());
|
||||
int length = width * height * destination.getFormat().blockSize();
|
||||
setUnpack(1, 0, 0, 0);
|
||||
device.staging()
|
||||
.texSubImage2D(
|
||||
gl,
|
||||
texture.imageTarget(depthOrLayer),
|
||||
mipLevel,
|
||||
destX,
|
||||
destY,
|
||||
width,
|
||||
height,
|
||||
format.format(),
|
||||
format.type(),
|
||||
source,
|
||||
source.position(),
|
||||
length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copyBufferToTexture(
|
||||
GpuBufferSlice source,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
GpuTexture destination,
|
||||
int destinationX,
|
||||
int destinationY,
|
||||
int copyWidth,
|
||||
int copyHeight,
|
||||
int mipLevel,
|
||||
int arrayLayer) {
|
||||
WebGl2Texture texture = (WebGl2Texture) destination;
|
||||
GlFormats.TextureFormat format = texture.glFormat();
|
||||
WebGl2Buffer buffer = (WebGl2Buffer) source.buffer();
|
||||
int blockSize = destination.getFormat().blockSize();
|
||||
// Only the rows the copy reads, from its first row; the unpack skips pick the rectangle out.
|
||||
int firstByte = Math.toIntExact(source.offset()) + sourceY * sourceWidth * blockSize;
|
||||
int length = (copyHeight - 1) * sourceWidth * blockSize + (sourceX + copyWidth) * blockSize;
|
||||
device.bindTextureForUpdate(texture.target(), texture.handle());
|
||||
setUnpack(1, sourceWidth, sourceX, 0);
|
||||
device.staging()
|
||||
.texSubImage2D(
|
||||
device.gl(),
|
||||
texture.imageTarget(arrayLayer),
|
||||
mipLevel,
|
||||
destinationX,
|
||||
destinationY,
|
||||
copyWidth,
|
||||
copyHeight,
|
||||
format.format(),
|
||||
format.type(),
|
||||
buffer.memory(),
|
||||
firstByte,
|
||||
length);
|
||||
setUnpack(1, 0, 0, 0);
|
||||
}
|
||||
|
||||
private void setUnpack(int alignment, int rowLength, int skipPixels, int skipRows) {
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
gl.pixelStorei(UNPACK_ALIGNMENT, alignment);
|
||||
gl.pixelStorei(UNPACK_ROW_LENGTH, rowLength);
|
||||
gl.pixelStorei(UNPACK_SKIP_PIXELS, skipPixels);
|
||||
gl.pixelStorei(UNPACK_SKIP_ROWS, skipRows);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copyTextureToBuffer(
|
||||
GpuTexture source, GpuBuffer destination, long offset, Runnable callback, int mipLevel) {
|
||||
copyTextureToBuffer(
|
||||
source,
|
||||
destination,
|
||||
offset,
|
||||
callback,
|
||||
mipLevel,
|
||||
0,
|
||||
0,
|
||||
source.getWidth(mipLevel),
|
||||
source.getHeight(mipLevel));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copyTextureToBuffer(
|
||||
GpuTexture source,
|
||||
GpuBuffer destination,
|
||||
long offset,
|
||||
Runnable callback,
|
||||
int mipLevel,
|
||||
int x,
|
||||
int y,
|
||||
int width,
|
||||
int height) {
|
||||
WebGl2Texture texture = (WebGl2Texture) source;
|
||||
GlFormats.TextureFormat format = texture.glFormat();
|
||||
WebGl2Buffer buffer = (WebGl2Buffer) destination;
|
||||
int length = width * height * source.getFormat().blockSize();
|
||||
device.framebuffers().bindSingle(READ_FRAMEBUFFER, texture, mipLevel);
|
||||
device.gl().pixelStorei(PACK_ALIGNMENT, 1);
|
||||
device.gl()
|
||||
.readPixels(
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
format.format(),
|
||||
format.type(),
|
||||
device.staging().scratch(length, format.type()));
|
||||
device.staging().readBack(buffer.memory(), Math.toIntExact(offset), length);
|
||||
buffer.upload(Math.toIntExact(offset), length);
|
||||
// readPixels waited for the GPU, so the data is there now.
|
||||
callback.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copyTextureToTexture(
|
||||
GpuTexture source,
|
||||
GpuTexture destination,
|
||||
int mipLevel,
|
||||
int destX,
|
||||
int destY,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int width,
|
||||
int height) {
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
device.framebuffers().bindSingle(READ_FRAMEBUFFER, (WebGl2Texture) source, mipLevel);
|
||||
device.framebuffers().bindSingle(DRAW_FRAMEBUFFER, (WebGl2Texture) destination, mipLevel);
|
||||
gl.disable(SCISSOR_TEST);
|
||||
int mask = source.getFormat().hasColorAspect() ? COLOR_BUFFER_BIT : DEPTH_BUFFER_BIT;
|
||||
gl.blitFramebuffer(
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourceX + width,
|
||||
sourceY + height,
|
||||
destX,
|
||||
destY,
|
||||
destX + width,
|
||||
destY + height,
|
||||
mask,
|
||||
NEAREST);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuFence createFence() {
|
||||
// Every command has run by the time the game could wait: see readPixels above.
|
||||
return new GpuFence() {
|
||||
@Override
|
||||
public void close() {}
|
||||
|
||||
@Override
|
||||
public boolean awaitCompletion(long timeoutNS) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTimestamp(GpuQueryPool pool, int index) {
|
||||
// WebGL2's timer queries (EXT_disjoint_timer_query_webgl2) are off in most browsers.
|
||||
}
|
||||
|
||||
private float[] depth(float value) {
|
||||
clearDepth[0] = value;
|
||||
return clearDepth;
|
||||
}
|
||||
|
||||
private float[] rgba(Vector4fc color) {
|
||||
clearColor[0] = color.x();
|
||||
clearColor[1] = color.y();
|
||||
clearColor[2] = color.z();
|
||||
clearColor[3] = color.w();
|
||||
return clearColor;
|
||||
}
|
||||
}
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.MAX_COLOR_ATTACHMENTS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.MAX_COMBINED_TEXTURE_IMAGE_UNITS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.MAX_DRAW_BUFFERS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.MAX_TEXTURE_SIZE;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.MAX_UNIFORM_BUFFER_BINDINGS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.MAX_VERTEX_ATTRIBS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.RENDERER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.SHADING_LANGUAGE_VERSION;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE0;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNIFORM_BUFFER_OFFSET_ALIGNMENT;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNPACK_ALIGNMENT;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.VENDOR;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.VERSION;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
||||
import com.mojang.renderpearl.api.commands.GpuQueryPool;
|
||||
import com.mojang.renderpearl.api.device.DeviceFeatures;
|
||||
import com.mojang.renderpearl.api.device.DeviceInfo;
|
||||
import com.mojang.renderpearl.api.device.DeviceLimits;
|
||||
import com.mojang.renderpearl.api.device.DeviceType;
|
||||
import com.mojang.renderpearl.api.device.HintsAndWorkarounds;
|
||||
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
|
||||
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderSource;
|
||||
import com.mojang.renderpearl.api.textures.AddressMode;
|
||||
import com.mojang.renderpearl.api.textures.FilterMode;
|
||||
import com.mojang.renderpearl.api.textures.GpuSampler;
|
||||
import com.mojang.renderpearl.api.textures.GpuTexture;
|
||||
import com.mojang.renderpearl.api.textures.GpuTextureView;
|
||||
import com.mojang.renderpearl.backend.api.BackendRenderPipeline;
|
||||
import com.mojang.renderpearl.backend.api.CommandEncoderBackend;
|
||||
import com.mojang.renderpearl.backend.api.GpuDeviceBackend;
|
||||
import com.mojang.renderpearl.backend.api.GpuSurfaceBackend;
|
||||
import incari.client.render.GpuFrameStats;
|
||||
import incari.client.render.PipelineCompilingBackend;
|
||||
import incari.render.webgl2.shaders.ShaderManifest;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Supplier;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.JSObject;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLTexture;
|
||||
|
||||
/**
|
||||
* Mojang's {@code GpuDevice} backend API over WebGL2, under the game's own frontend
|
||||
* ({@code FrontendGpuDevice}), which validates every call before it gets here.
|
||||
*
|
||||
* <p>What it tells the game: depth from 0 to 1 where the browser has EXT_clip_control (else -1 to
|
||||
* 1, as OpenGL without clip control), and no persistent mapping. Where the browser has
|
||||
* WEBGL_multi_draw it also claims indirect multi-draws and a base instance, which is what makes the
|
||||
* game draw terrain through its multi-draw path: the render pass carries each indirect draw out as
|
||||
* a few {@code multiDrawElementsWEBGL} calls, one per vertex heap (ADR 0022). Without it the
|
||||
* game takes its plain path, a draw per section. Pipelines come from
|
||||
* the build's translated shaders ({@link PipelineCompiler}), not from shaderc.
|
||||
*
|
||||
* <p>It counts each frame's draw calls, and times the GPU's work where the browser can
|
||||
* ({@link GpuTimer}), for the profiler.
|
||||
*
|
||||
* <p>Runs on the page's only thread; no call blocks except the read-backs noted in
|
||||
* {@link WebGl2CommandEncoder}.
|
||||
*/
|
||||
final class WebGl2Device implements GpuDeviceBackend, PipelineCompilingBackend, GpuFrameStats {
|
||||
|
||||
/** The memory the game may plan to allocate; it sizes large textures from this. Chromebooks share 4 GB. */
|
||||
private static final long MAX_ALLOCATION = 512L * 1024 * 1024;
|
||||
|
||||
/** Sub-draws the game may put in one indirect draw; the render pass splits them as it needs. */
|
||||
private static final int MAX_INDIRECT_DRAWS = 1 << 16;
|
||||
|
||||
private final WebGL2RenderingContext gl;
|
||||
private final Staging staging = new Staging();
|
||||
private final PendingUploads pendingUploads = new PendingUploads();
|
||||
private final Framebuffers framebuffers = new Framebuffers(this);
|
||||
private final GlState state;
|
||||
private final Bindings bindings;
|
||||
private final PipelineCompiler pipelines;
|
||||
private final DeviceInfo info;
|
||||
private final boolean anisotropy;
|
||||
private final boolean floatBlend;
|
||||
private final boolean zeroToOne;
|
||||
private final boolean polygonMode;
|
||||
private final @Nullable JSObject multiDraw;
|
||||
private final GpuTimer gpuTimer;
|
||||
private final GpuCensus gpuCensus;
|
||||
private final @Nullable QuadIndices quadIndices;
|
||||
private final @Nullable DrawRows drawRows;
|
||||
private final @Nullable RebasedIndices rebasedIndices;
|
||||
/** Counters for {@link WebGl#publishStats}. */
|
||||
int frames;
|
||||
|
||||
int draws;
|
||||
int skippedDraws;
|
||||
|
||||
/** This frame's draw calls, terrain's among them, and the terrain sections they drew. */
|
||||
int frameDraws;
|
||||
|
||||
int frameTerrainDraws;
|
||||
int frameTerrainSections;
|
||||
private int lastDraws;
|
||||
private int lastTerrainDraws;
|
||||
private int lastTerrainSections;
|
||||
|
||||
/** The texture unit uploads bind on: the last one, which no pipeline's uniform index reaches. */
|
||||
private final int updateUnit;
|
||||
|
||||
/**
|
||||
* @param allowMultiDraw whether to draw terrain with WEBGL_multi_draw where the browser has it
|
||||
* (the page's {@code ?multidraw=off} turns it off, to compare)
|
||||
*/
|
||||
WebGl2Device(WebGL2RenderingContext gl, ShaderManifest manifest, boolean eagerShaders, boolean allowMultiDraw) {
|
||||
this.gl = gl;
|
||||
JSObject polygonMode = WebGl.polygonModeExtension(gl);
|
||||
this.polygonMode = polygonMode != null;
|
||||
this.state = new GlState(gl, polygonMode);
|
||||
int units = gl.getParameteri(MAX_COMBINED_TEXTURE_IMAGE_UNITS);
|
||||
int uniformBindings = gl.getParameteri(MAX_UNIFORM_BUFFER_BINDINGS);
|
||||
this.updateUnit = units - 1;
|
||||
// The last uniform buffer binding point is the multi-draw rows' (DrawRows); the pipelines'
|
||||
// uniforms use the ones below it.
|
||||
this.bindings =
|
||||
new Bindings(gl, Math.min(units - 1, uniformBindings - 1), gl.getParameteri(MAX_VERTEX_ATTRIBS));
|
||||
this.gpuTimer = new GpuTimer(gl);
|
||||
this.gpuCensus = new GpuCensus(gl);
|
||||
this.multiDraw = allowMultiDraw ? WebGl.extension(gl, "WEBGL_multi_draw") : null;
|
||||
if (multiDraw != null) {
|
||||
this.quadIndices = new QuadIndices(this);
|
||||
this.drawRows = new DrawRows(this, uniformBindings - 1, gl.getParameteri(UNIFORM_BUFFER_OFFSET_ALIGNMENT));
|
||||
this.rebasedIndices = new RebasedIndices(this);
|
||||
} else {
|
||||
this.quadIndices = null;
|
||||
this.drawRows = null;
|
||||
this.rebasedIndices = null;
|
||||
}
|
||||
this.pipelines = new PipelineCompiler(this, manifest, eagerShaders);
|
||||
// Rendering to float targets (the game's HDR and translucency buffers) is an extension in
|
||||
// WebGL2; so is anisotropic filtering.
|
||||
WebGl.enableExtension(gl, "EXT_color_buffer_float");
|
||||
WebGl.enableExtension(gl, "EXT_color_buffer_half_float");
|
||||
this.floatBlend = WebGl.enableExtension(gl, "EXT_float_blend");
|
||||
WebGl.enableExtension(gl, "OES_texture_float_linear");
|
||||
this.anisotropy = WebGl.enableExtension(gl, "EXT_texture_filter_anisotropic");
|
||||
// Reversed-Z as on the desktop: the game puts the near plane at depth 1 and the far one at
|
||||
// 0, which only pays off in precision where depth runs 0 to 1. Without the extension the
|
||||
// game builds its projection for -1 to 1 instead, as for any OpenGL without clip control.
|
||||
this.zeroToOne = WebGl.clipControlZeroToOne(gl);
|
||||
WebGl.enableExtension(gl, "WEBGL_debug_renderer_info");
|
||||
// The game packs its uploads tightly.
|
||||
gl.pixelStorei(UNPACK_ALIGNMENT, 1);
|
||||
// One vertex array for everything: attributes are re-pointed per pipeline, not per object.
|
||||
gl.bindVertexArray(gl.createVertexArray());
|
||||
this.info = describe();
|
||||
GpuFrameStats.install(this);
|
||||
}
|
||||
|
||||
private DeviceInfo describe() {
|
||||
String renderer = WebGl.stringParameter(gl, WebGl.UNMASKED_RENDERER);
|
||||
String vendor = WebGl.stringParameter(gl, WebGl.UNMASKED_VENDOR);
|
||||
Set<String> extensions = new HashSet<>();
|
||||
JSObject supported = WebGl.supportedExtensions(gl);
|
||||
for (int i = 0; i < WebGl.length(supported); i++) {
|
||||
extensions.add(WebGl.stringAt(supported, i));
|
||||
}
|
||||
int maxAnisotropy =
|
||||
anisotropy ? Math.max(1, (int) WebGl.numberParameter(gl, WebGl.MAX_TEXTURE_MAX_ANISOTROPY)) : 1;
|
||||
return new DeviceInfo(
|
||||
renderer.isEmpty() ? WebGl.stringParameter(gl, RENDERER) : renderer,
|
||||
vendor.isEmpty() ? WebGl.stringParameter(gl, VENDOR) : vendor,
|
||||
WebGl.stringParameter(gl, VERSION) + ", " + WebGl.stringParameter(gl, SHADING_LANGUAGE_VERSION),
|
||||
zeroToOne,
|
||||
"WebGL2",
|
||||
1.0F,
|
||||
new DeviceLimits(
|
||||
maxAnisotropy,
|
||||
gl.getParameteri(UNIFORM_BUFFER_OFFSET_ALIGNMENT),
|
||||
gl.getParameteri(MAX_TEXTURE_SIZE),
|
||||
MAX_ALLOCATION,
|
||||
0,
|
||||
Math.min(gl.getParameteri(MAX_COLOR_ATTACHMENTS), gl.getParameteri(MAX_DRAW_BUFFERS)),
|
||||
multiDraw != null ? MAX_INDIRECT_DRAWS : 0),
|
||||
// Indirect draws and a base instance are emulated (WebGl2RenderPass), so they're
|
||||
// only claimed where the terrain they're for can be multi-drawn.
|
||||
multiDraw != null
|
||||
? new DeviceFeatures(false, false, false, false, true, true, true, false)
|
||||
: new DeviceFeatures(false, false, false, false, false, false, false, false),
|
||||
Set.copyOf(extensions),
|
||||
new HintsAndWorkarounds(false, false, false, false),
|
||||
DeviceType.OTHER);
|
||||
}
|
||||
|
||||
WebGL2RenderingContext gl() {
|
||||
return gl;
|
||||
}
|
||||
|
||||
Staging staging() {
|
||||
return staging;
|
||||
}
|
||||
|
||||
/** Uniform buffers written since the last draw (ADR 0027). */
|
||||
PendingUploads pendingUploads() {
|
||||
return pendingUploads;
|
||||
}
|
||||
|
||||
Framebuffers framebuffers() {
|
||||
return framebuffers;
|
||||
}
|
||||
|
||||
GlState state() {
|
||||
return state;
|
||||
}
|
||||
|
||||
Bindings bindings() {
|
||||
return bindings;
|
||||
}
|
||||
|
||||
boolean hasAnisotropy() {
|
||||
return anisotropy;
|
||||
}
|
||||
|
||||
/** Whether depth runs from 0 to 1 (EXT_clip_control), as the game's desktop backends set it. */
|
||||
boolean depthZeroToOne() {
|
||||
return zeroToOne;
|
||||
}
|
||||
|
||||
/** Whether wireframe pipelines can draw (WEBGL_polygon_mode). */
|
||||
boolean hasPolygonMode() {
|
||||
return polygonMode;
|
||||
}
|
||||
|
||||
/** Whether terrain is multi-drawn (WEBGL_multi_draw). */
|
||||
boolean multiDraw() {
|
||||
return multiDraw != null;
|
||||
}
|
||||
|
||||
/** WEBGL_multi_draw's object; only where {@link #multiDraw()}. */
|
||||
JSObject multiDrawExtension() {
|
||||
JSObject extension = multiDraw;
|
||||
if (extension == null) {
|
||||
throw new IllegalStateException("No WEBGL_multi_draw");
|
||||
}
|
||||
return extension;
|
||||
}
|
||||
|
||||
/** The multi-draw rows; only where {@link #multiDraw()}. */
|
||||
DrawRows drawRows() {
|
||||
DrawRows rows = drawRows;
|
||||
if (rows == null) {
|
||||
throw new IllegalStateException("No WEBGL_multi_draw");
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Rebase quad-indexed draws onto {@link QuadIndices}; the page's {@code ?rebase=off} doesn't, to compare. */
|
||||
static volatile boolean rebaseQuadDraws = true;
|
||||
|
||||
/** The page's {@code ?drawcensus}: draws per pipeline logged every {@link #CENSUS_FRAMES} frames. */
|
||||
static volatile boolean census;
|
||||
|
||||
/** The page's {@code ?gpucensus}: each draw's GPU time, by pipeline ({@link GpuCensus}). */
|
||||
static volatile boolean timeDraws;
|
||||
|
||||
private static final int CENSUS_FRAMES = 600;
|
||||
private final java.util.Map<String, Integer> censusDraws = new java.util.TreeMap<>();
|
||||
private int censusFrames;
|
||||
|
||||
/** Logs the census: each pipeline's draws a frame, most first (development only). */
|
||||
private void logCensus() {
|
||||
StringBuilder line = new StringBuilder("[Incari] Draws a frame by pipeline over ")
|
||||
.append(censusFrames)
|
||||
.append(" frames:");
|
||||
censusDraws.entrySet().stream()
|
||||
.sorted(java.util.Map.Entry.<String, Integer>comparingByValue().reversed())
|
||||
.forEach(entry -> line.append(String.format(
|
||||
java.util.Locale.ROOT, " %s=%.2f", entry.getKey(), entry.getValue() / (double) censusFrames)));
|
||||
WebGl.info(line.toString());
|
||||
censusDraws.clear();
|
||||
censusFrames = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a draw from the game's sequential quad indices is drawn from the backend's own
|
||||
* instead, leaving the vertex attributes in place (ADR 0027): where the device has them.
|
||||
*/
|
||||
boolean rebasesQuadDraws() {
|
||||
return rebaseQuadDraws && quadIndices != null;
|
||||
}
|
||||
|
||||
/** The sequential quad indices multi-draws read; only where {@link #multiDraw()}. */
|
||||
QuadIndices quadIndices() {
|
||||
QuadIndices indices = quadIndices;
|
||||
if (indices == null) {
|
||||
throw new IllegalStateException("No WEBGL_multi_draw");
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
|
||||
/** The streamed rebased indices multi-draws of sections with their own indices read; only where {@link #multiDraw()}. */
|
||||
RebasedIndices rebasedIndices() {
|
||||
RebasedIndices indices = rebasedIndices;
|
||||
if (indices == null) {
|
||||
throw new IllegalStateException("No WEBGL_multi_draw");
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
|
||||
GpuTimer gpuTimer() {
|
||||
return gpuTimer;
|
||||
}
|
||||
|
||||
/** Before a draw's call: times it, under {@code ?gpucensus}. */
|
||||
void drawStarting() {
|
||||
if (timeDraws) {
|
||||
gpuCensus.begin();
|
||||
}
|
||||
}
|
||||
|
||||
/** After a draw's call by {@code pipeline}. */
|
||||
void drawIssued(WebGl2Pipeline pipeline) {
|
||||
if (timeDraws) {
|
||||
gpuCensus.end(pipeline.name());
|
||||
}
|
||||
}
|
||||
|
||||
/** Counts a draw call; {@code sections} is how many terrain sections it drew, if it drew terrain. */
|
||||
void countDraw(WebGl2Pipeline pipeline, int sections) {
|
||||
draws++;
|
||||
frameDraws++;
|
||||
if (census) {
|
||||
censusDraws.merge(pipeline.name(), 1, Integer::sum);
|
||||
}
|
||||
if (pipeline.terrain()) {
|
||||
frameTerrainDraws++;
|
||||
frameTerrainSections += sections;
|
||||
}
|
||||
}
|
||||
|
||||
/** Called once a frame, after the blit to the canvas: the frame's counts become the last frame's. */
|
||||
void frameEnded() {
|
||||
gpuTimer.frameEnded();
|
||||
if (timeDraws) {
|
||||
gpuCensus.frameEnded();
|
||||
}
|
||||
if (census && ++censusFrames == CENSUS_FRAMES) {
|
||||
logCensus();
|
||||
}
|
||||
lastDraws = frameDraws;
|
||||
lastTerrainDraws = frameTerrainDraws;
|
||||
lastTerrainSections = frameTerrainSections;
|
||||
frameDraws = 0;
|
||||
frameTerrainDraws = 0;
|
||||
frameTerrainSections = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double gpuMillis() {
|
||||
return gpuTimer.lastMillis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int drawCalls() {
|
||||
return lastDraws;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int terrainDrawCalls() {
|
||||
return lastTerrainDraws;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int terrainSections() {
|
||||
return lastTerrainSections;
|
||||
}
|
||||
|
||||
/** Binds a texture to change it, on a unit of its own so the draw bindings stay as they are. */
|
||||
void bindTextureForUpdate(int target, WebGLTexture texture) {
|
||||
gl.activeTexture(TEXTURE0 + updateUnit);
|
||||
gl.bindTexture(target, texture);
|
||||
}
|
||||
|
||||
/** Called after something outside the state caches changed WebGL's bindings. */
|
||||
void invalidateBindings() {
|
||||
// The surface blit only touches framebuffers and the scissor, which every pass sets anew.
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuSurfaceBackend createSurface(long windowHandle, BooleanSupplier isIconified) {
|
||||
return new WebGl2Surface(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommandEncoderBackend createCommandEncoder() {
|
||||
return new WebGl2CommandEncoder(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuSampler createSampler(
|
||||
AddressMode addressModeU,
|
||||
AddressMode addressModeV,
|
||||
FilterMode minFilter,
|
||||
FilterMode magFilter,
|
||||
int maxAnisotropy,
|
||||
OptionalDouble maxLod) {
|
||||
return new WebGl2Sampler(this, addressModeU, addressModeV, minFilter, magFilter, maxAnisotropy, maxLod);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuTexture createTexture(
|
||||
@Nullable String label,
|
||||
@GpuTexture.Usage int usage,
|
||||
GpuFormat format,
|
||||
int width,
|
||||
int height,
|
||||
int depthOrLayers,
|
||||
int mipLevels) {
|
||||
GlFormats.TextureFormat glFormat = GlFormats.texture(format);
|
||||
if (glFormat == null) {
|
||||
throw new UnsupportedOperationException("WebGL2 has no " + format + " textures (" + label + ")");
|
||||
}
|
||||
if (!floatBlend && (usage & GpuTexture.USAGE_RENDER_ATTACHMENT) != 0) {
|
||||
// Blending into 32-bit float targets needs EXT_float_blend, which some mobile GPUs
|
||||
// lack; the game blends into one (the transparency passes' depth bounds, MAX), so it
|
||||
// gets 16-bit floats there instead, like the passes' other targets.
|
||||
glFormat = GlFormats.withoutFloatBlending(glFormat);
|
||||
}
|
||||
return new WebGl2Texture(
|
||||
this, usage, label == null ? "" : label, format, glFormat, width, height, depthOrLayers, mipLevels);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuTextureView createTextureView(GpuTexture texture, int baseMipLevel, int mipLevels) {
|
||||
return new WebGl2TextureView((WebGl2Texture) texture, baseMipLevel, mipLevels);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBuffer createBuffer(@Nullable Supplier<String> label, @GpuBuffer.Usage int usage, long size) {
|
||||
return new WebGl2Buffer(this, usage, size);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBuffer createBuffer(@Nullable Supplier<String> label, @GpuBuffer.Usage int usage, ByteBuffer data) {
|
||||
WebGl2Buffer buffer = new WebGl2Buffer(this, usage, data.remaining());
|
||||
buffer.write(0, data);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getLastDebugMessages() {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebuggingEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Never called: the frontend hands pipelines to {@link #compilePipeline(RenderPipeline, ShaderSource, Executor)}. */
|
||||
@Override
|
||||
public BackendRenderPipeline.Pending compilePipeline(BackendRenderPipeline.CreateInfo pipelineCreateInfo) {
|
||||
throw new UnsupportedOperationException("WebGL2 pipelines are compiled from the build's translated shaders");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<CompiledRenderPipeline.Pending> compilePipeline(
|
||||
RenderPipeline pipeline, ShaderSource shaderSource, Executor executor) {
|
||||
return pipelines.compile(pipeline, shaderSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {}
|
||||
|
||||
@Override
|
||||
public GpuQueryPool createTimestampQueryPool(int size) {
|
||||
return new GpuQueryPool() {
|
||||
@Override
|
||||
public int size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalLong getValue(int index) {
|
||||
return OptionalLong.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalLong[] getValues(int index, int count) {
|
||||
OptionalLong[] values = new OptionalLong[count];
|
||||
java.util.Arrays.fill(values, OptionalLong.empty());
|
||||
return values;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getTimestampCalibrationOffset() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceInfo getDeviceInfo() {
|
||||
return info;
|
||||
}
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.COMPILE_STATUS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.FRAGMENT_SHADER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.INVALID_INDEX;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.LINK_STATUS;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.VERTEX_SHADER;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.BindGroupLayout;
|
||||
import com.mojang.renderpearl.api.pipeline.BlendFunction;
|
||||
import com.mojang.renderpearl.api.pipeline.ColorTargetState;
|
||||
import com.mojang.renderpearl.api.pipeline.DepthStencilState;
|
||||
import com.mojang.renderpearl.api.pipeline.PolygonMode;
|
||||
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
||||
import com.mojang.renderpearl.api.pipeline.UniformType;
|
||||
import com.mojang.renderpearl.backend.api.BackendRenderPipeline;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLProgram;
|
||||
import org.teavm.jso.webgl.WebGLShader;
|
||||
import org.teavm.jso.webgl.WebGLUniformLocation;
|
||||
|
||||
/**
|
||||
* A pipeline: its translated program plus the fixed-function state the game describes with it.
|
||||
*
|
||||
* <p>The program is linked on first use, not when the game compiles its pipelines at startup: the
|
||||
* game compiles every pipeline it has (over two hundred) before the title screen, and on a
|
||||
* Chromebook each WebGL link costs milliseconds of the page's only thread. A pipeline WebGL2 can't
|
||||
* run, or whose program fails to link, draws nothing and says why once.
|
||||
*
|
||||
* <p>Uniform {@code i} of the pipeline (the frontend's index) is uniform block binding point
|
||||
* {@code i} or texture unit {@code i}, fixed when the program links.
|
||||
*
|
||||
* <p>A pipeline with {@link #drawRows() draw rows} reads its per-instance inputs from a uniform
|
||||
* block by {@code gl_DrawID} instead of from attributes ({@link DrawIdRewrite}): the game's
|
||||
* multi-draw terrain pipelines, where the device has {@code WEBGL_multi_draw}.
|
||||
*/
|
||||
final class WebGl2Pipeline implements BackendRenderPipeline {
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final String name;
|
||||
private final @Nullable TranslatedStage vertex;
|
||||
private final @Nullable TranslatedStage fragment;
|
||||
private final List<BindGroupLayout.UniformDescription> uniforms;
|
||||
/**
|
||||
* Each uniform block's size as the linked program reports it, by uniform index (0 for
|
||||
* anything else). A driver may round a block up past the game's std140 size (Mesa's
|
||||
* radeonsi does, under ANGLE's OpenGL backend), and WebGL refuses to draw from a bound range
|
||||
* smaller than that.
|
||||
*/
|
||||
private final int[] blockSizes;
|
||||
|
||||
private final List<VertexLayout.Binding> attributes;
|
||||
private final VertexLayout.@Nullable DrawRowLayout drawRows;
|
||||
private final @Nullable String vertexGlsl;
|
||||
private final boolean terrain;
|
||||
private final int drawMode;
|
||||
private final boolean cull;
|
||||
private final boolean wireframe;
|
||||
private final @Nullable DepthStencilState depthState;
|
||||
private final @Nullable BlendFunction blend;
|
||||
private final int colorMask;
|
||||
private @Nullable String problem;
|
||||
private @Nullable WebGLProgram program;
|
||||
private boolean reported;
|
||||
private boolean closed;
|
||||
|
||||
private WebGl2Pipeline(
|
||||
WebGl2Device device,
|
||||
RenderPipeline pipeline,
|
||||
@Nullable TranslatedStage vertex,
|
||||
@Nullable TranslatedStage fragment,
|
||||
List<VertexLayout.Binding> attributes,
|
||||
VertexLayout.@Nullable DrawRowLayout drawRows,
|
||||
@Nullable String vertexGlsl,
|
||||
@Nullable String problem) {
|
||||
this.device = device;
|
||||
this.name = pipeline.getLocation().toString();
|
||||
this.vertex = vertex;
|
||||
this.fragment = fragment;
|
||||
this.uniforms = BindGroupLayout.flattenUniforms(pipeline.getBindGroupLayouts());
|
||||
this.blockSizes = new int[uniforms.size()];
|
||||
this.drawRows = drawRows;
|
||||
this.attributes = drawRows != null ? drawRows.attributes() : List.copyOf(attributes);
|
||||
this.vertexGlsl = vertexGlsl;
|
||||
// The profiler counts terrain's draws apart from the rest.
|
||||
this.terrain = pipeline.getLocation().getPath().contains("terrain");
|
||||
this.drawMode = GlFormats.drawMode(pipeline.getPrimitiveTopology());
|
||||
this.cull = pipeline.isCull();
|
||||
this.wireframe = pipeline.getPolygonMode() == PolygonMode.WIREFRAME;
|
||||
this.depthState = pipeline.getDepthStencilState();
|
||||
// WebGL2 has one blend state and one color mask for all attachments (per-attachment ones need
|
||||
// OES_draw_buffers_indexed); the game's blend is the same on every target by construction.
|
||||
BlendFunction firstBlend = null;
|
||||
int mask = ColorTargetState.WRITE_ALL;
|
||||
for (ColorTargetState target : pipeline.getColorTargetStates()) {
|
||||
if (target != null) {
|
||||
if (firstBlend == null && target.blendFunction().isPresent()) {
|
||||
firstBlend = target.blendFunction().get();
|
||||
}
|
||||
mask = target.writeMask();
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.blend = firstBlend;
|
||||
this.colorMask = mask;
|
||||
this.problem = problem;
|
||||
}
|
||||
|
||||
static WebGl2Pipeline of(
|
||||
WebGl2Device device,
|
||||
RenderPipeline pipeline,
|
||||
TranslatedStage vertex,
|
||||
TranslatedStage fragment,
|
||||
List<VertexLayout.Binding> attributes) {
|
||||
return new WebGl2Pipeline(device, pipeline, vertex, fragment, attributes, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* A pipeline whose per-instance inputs are read as draw rows ({@link DrawIdRewrite}), with
|
||||
* {@code vertexGlsl} the rewritten vertex shader.
|
||||
*/
|
||||
static WebGl2Pipeline withDrawRows(
|
||||
WebGl2Device device,
|
||||
RenderPipeline pipeline,
|
||||
TranslatedStage vertex,
|
||||
TranslatedStage fragment,
|
||||
VertexLayout.DrawRowLayout drawRows,
|
||||
String vertexGlsl) {
|
||||
return new WebGl2Pipeline(
|
||||
device, pipeline, vertex, fragment, drawRows.attributes(), drawRows, vertexGlsl, null);
|
||||
}
|
||||
|
||||
/** A pipeline that draws nothing, because {@code reason}. */
|
||||
static WebGl2Pipeline unsupported(WebGl2Device device, RenderPipeline pipeline, String reason) {
|
||||
return new WebGl2Pipeline(device, pipeline, null, null, List.of(), null, null, reason);
|
||||
}
|
||||
|
||||
String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
List<VertexLayout.Binding> attributes() {
|
||||
return attributes;
|
||||
}
|
||||
|
||||
/** Where the per-instance inputs come from if they're read as draw rows; null if they aren't. */
|
||||
VertexLayout.@Nullable DrawRowLayout drawRows() {
|
||||
return drawRows;
|
||||
}
|
||||
|
||||
/** Whether it can't draw: unsupported, or its program didn't compile or link. */
|
||||
boolean failed() {
|
||||
return problem != null;
|
||||
}
|
||||
|
||||
/** Whether this draws terrain. */
|
||||
boolean terrain() {
|
||||
return terrain;
|
||||
}
|
||||
|
||||
/** The size the program needs bound for uniform block {@code index}, or 0. */
|
||||
int blockSize(int index) {
|
||||
return blockSizes[index];
|
||||
}
|
||||
|
||||
List<BindGroupLayout.UniformDescription> uniforms() {
|
||||
return uniforms;
|
||||
}
|
||||
|
||||
int drawMode() {
|
||||
return drawMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes this the current program with its state, linking it first if it hasn't been; false if
|
||||
* it can't draw (the draw is then skipped).
|
||||
*/
|
||||
boolean use() {
|
||||
if (closed) {
|
||||
return false;
|
||||
}
|
||||
WebGLProgram linked = link();
|
||||
if (linked == null) {
|
||||
if (!reported) {
|
||||
reported = true;
|
||||
WebGl.warn("[Incari] Skipping draws of " + name + ": " + problem);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
GlState state = device.state();
|
||||
state.program(this, linked);
|
||||
state.cull(cull);
|
||||
state.polygonLines(wireframe);
|
||||
state.depth(depthState);
|
||||
state.blend(blend);
|
||||
state.colorMask(colorMask);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Links the program if it hasn't been; null if the pipeline can't be drawn. */
|
||||
@Nullable
|
||||
WebGLProgram link() {
|
||||
if (program != null || problem != null) {
|
||||
return program;
|
||||
}
|
||||
TranslatedStage vertexStage = vertex;
|
||||
TranslatedStage fragmentStage = fragment;
|
||||
if (vertexStage == null || fragmentStage == null) {
|
||||
problem = "no shaders";
|
||||
return null;
|
||||
}
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
WebGLShader vertexShader =
|
||||
compile(VERTEX_SHADER, vertexStage, vertexGlsl != null ? vertexGlsl : vertexStage.glsl());
|
||||
WebGLShader fragmentShader = compile(FRAGMENT_SHADER, fragmentStage, fragmentStage.glsl());
|
||||
if (vertexShader == null || fragmentShader == null) {
|
||||
return null;
|
||||
}
|
||||
WebGLProgram linked = gl.createProgram();
|
||||
gl.attachShader(linked, vertexShader);
|
||||
gl.attachShader(linked, fragmentShader);
|
||||
gl.linkProgram(linked);
|
||||
// The program keeps what it needs; the shader objects only hold memory.
|
||||
gl.deleteShader(vertexShader);
|
||||
gl.deleteShader(fragmentShader);
|
||||
if (!gl.getProgramParameterb(linked, LINK_STATUS)) {
|
||||
problem = "program doesn't link: " + gl.getProgramInfoLog(linked);
|
||||
WebGl.error("[Incari] " + name + ": " + problem);
|
||||
gl.deleteProgram(linked);
|
||||
return null;
|
||||
}
|
||||
device.state().program(this, linked);
|
||||
if (drawRows != null) {
|
||||
int block = gl.getUniformBlockIndex(linked, DrawIdRewrite.BLOCK);
|
||||
if (block != INVALID_INDEX) {
|
||||
gl.uniformBlockBinding(linked, block, device.drawRows().binding());
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < uniforms.size(); i++) {
|
||||
BindGroupLayout.UniformDescription uniform = uniforms.get(i);
|
||||
if (uniform.type() == UniformType.UNIFORM_BUFFER) {
|
||||
int block = gl.getUniformBlockIndex(linked, uniform.name());
|
||||
if (block != INVALID_INDEX) {
|
||||
gl.uniformBlockBinding(linked, block, i);
|
||||
blockSizes[i] = WebGl.uniformBlockDataSize(gl, linked, block);
|
||||
}
|
||||
} else if (uniform.type() == UniformType.COMBINED_IMAGE_SAMPLER
|
||||
|| uniform.type() == UniformType.TEXEL_BUFFER) {
|
||||
// A texel buffer is a texture here (TexelBufferTexture), on its unit like a sampler.
|
||||
WebGLUniformLocation location = gl.getUniformLocation(linked, uniform.name());
|
||||
if (location != null) {
|
||||
gl.uniform1i(location, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
program = linked;
|
||||
return linked;
|
||||
}
|
||||
|
||||
private @Nullable WebGLShader compile(int type, TranslatedStage stage, String glsl) {
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
WebGLShader shader = gl.createShader(type);
|
||||
gl.shaderSource(shader, glsl);
|
||||
gl.compileShader(shader);
|
||||
if (!gl.getShaderParameterb(shader, COMPILE_STATUS)) {
|
||||
problem = stage.key() + " doesn't compile: " + gl.getShaderInfoLog(shader);
|
||||
WebGl.error("[Incari] " + name + ": " + problem);
|
||||
gl.deleteShader(shader);
|
||||
return null;
|
||||
}
|
||||
return shader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
closed = true;
|
||||
WebGLProgram linked = program;
|
||||
if (linked != null) {
|
||||
device.state().forgetProgram();
|
||||
device.gl().deleteProgram(linked);
|
||||
program = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+547
@@ -0,0 +1,547 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.ARRAY_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE0;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_2D;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNIFORM_BUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.UNSIGNED_INT;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
||||
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
|
||||
import com.mojang.renderpearl.api.commands.GpuQueryPool;
|
||||
import com.mojang.renderpearl.api.commands.RenderPass;
|
||||
import com.mojang.renderpearl.api.pipeline.BindGroupLayout;
|
||||
import com.mojang.renderpearl.api.pipeline.IndexType;
|
||||
import com.mojang.renderpearl.api.pipeline.UniformType;
|
||||
import com.mojang.renderpearl.backend.api.BackendRenderPipeline;
|
||||
import com.mojang.renderpearl.backend.api.RenderPassBackend;
|
||||
import com.mojang.renderpearl.util.TextureViewAndSampler;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* Draws in one render pass. State is applied when a draw needs it, and only what changed: the
|
||||
* frontend tells this pass about every uniform and buffer as the game sets them, often more than
|
||||
* once between draws.
|
||||
*
|
||||
* <p>WebGL2 can't offset the vertex index of an indexed draw ({@code baseVertex}) or the instance
|
||||
* of an instanced one ({@code firstInstance}), so the vertex attributes are pointed that many
|
||||
* vertices, or instances, further into their buffers instead. Indirect draws, which only terrain
|
||||
* makes, are read from the game's copy of their commands and multi-drawn
|
||||
* ({@link #drawIndexedIndirect}).
|
||||
*/
|
||||
final class WebGl2RenderPass implements RenderPassBackend {
|
||||
|
||||
private static final int MAX_UNIFORMS = 32;
|
||||
|
||||
/** An indirect command: index count, instance count, first index, base vertex, first instance. */
|
||||
private static final int COMMAND_BYTES = 20;
|
||||
|
||||
/** A row of zeros, for a draw-row pipeline drawn without its instance data bound. */
|
||||
private static final ByteBuffer ZERO_ROW = ByteBuffer.allocate(DrawIdRewrite.ROW_BYTES);
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final RenderPass.RenderArea area;
|
||||
private @Nullable WebGl2Pipeline pipeline;
|
||||
private final @Nullable GpuBufferSlice[] vertexBuffers = new GpuBufferSlice[RenderPass.MAX_VERTEX_BUFFERS];
|
||||
private @Nullable WebGl2Buffer indexBuffer;
|
||||
private int indexType;
|
||||
private int indexSize;
|
||||
private final @Nullable Object[] uniforms = new Object[MAX_UNIFORMS];
|
||||
private boolean uniformsDirty = true;
|
||||
private boolean attributesDirty = true;
|
||||
private int attributesBaseVertex;
|
||||
private int attributesBaseInstance;
|
||||
private boolean warned;
|
||||
|
||||
WebGl2RenderPass(WebGl2Device device, RenderPass.RenderArea area) {
|
||||
this.device = device;
|
||||
this.area = area;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pushDebugGroup(Supplier<String> label) {}
|
||||
|
||||
@Override
|
||||
public void popDebugGroup() {}
|
||||
|
||||
@Override
|
||||
public void setPipeline(BackendRenderPipeline next) {
|
||||
WebGl2Pipeline glPipeline = (WebGl2Pipeline) next;
|
||||
if (glPipeline != pipeline) {
|
||||
pipeline = glPipeline;
|
||||
uniformsDirty = true;
|
||||
attributesDirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUniform(int index, @Nullable Object value) {
|
||||
if (index >= MAX_UNIFORMS) {
|
||||
throw new IllegalArgumentException("Pipeline uniform " + index + " is beyond WebGL2's " + MAX_UNIFORMS);
|
||||
}
|
||||
uniforms[index] = value;
|
||||
uniformsDirty = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pushConstants(ByteBuffer value) {
|
||||
// No pipeline WebGL2 can run has push constants: the shader tool marks those unsupported.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableScissor(int x, int y, int width, int height) {
|
||||
device.gl().scissor(x, y, width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disableScissor() {
|
||||
device.gl().scissor(area.x(), area.y(), area.width(), area.height());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("ReferenceEquality") // the same buffer object, not an equal one
|
||||
public void setVertexBuffer(int slot, @Nullable GpuBufferSlice vertexBuffer) {
|
||||
GpuBufferSlice previous = vertexBuffers[slot];
|
||||
vertexBuffers[slot] = vertexBuffer;
|
||||
// The game sets the frame's staged vertex buffer again for every draw; the attributes only
|
||||
// need pointing again when the buffer or the slice's start changes (ADR 0027).
|
||||
if (previous == null
|
||||
|| vertexBuffer == null
|
||||
|| previous.buffer() != vertexBuffer.buffer()
|
||||
|| previous.offset() != vertexBuffer.offset()) {
|
||||
attributesDirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setIndexBuffer(GpuBuffer buffer, IndexType type) {
|
||||
indexBuffer = (WebGl2Buffer) buffer;
|
||||
indexType = GlFormats.indexType(type);
|
||||
indexSize = type.bytes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) {
|
||||
WebGl2Buffer indices = indexBuffer;
|
||||
WebGl2Pipeline current = currentPipeline();
|
||||
// A draw-row pipeline reads no per-instance attributes: its first instance picks a row.
|
||||
boolean rows = current.drawRows() != null;
|
||||
if (indices == null || instanceCount == 0) {
|
||||
return;
|
||||
}
|
||||
if (!rows && device.rebasesQuadDraws() && indices.quadSequenceOf(indexSize)) {
|
||||
drawQuads(current, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
|
||||
return;
|
||||
}
|
||||
if (!prepare(vertexOffset, rows ? 0 : firstInstance)) {
|
||||
return;
|
||||
}
|
||||
if (rows && !singleRow(current, firstInstance, instanceCount)) {
|
||||
return;
|
||||
}
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
gl.bindBuffer(ELEMENT_ARRAY_BUFFER, indices.handle());
|
||||
int mode = current.drawMode();
|
||||
device.drawStarting();
|
||||
if (instanceCount == 1) {
|
||||
gl.drawElements(mode, indexCount, indexType, firstIndex * indexSize);
|
||||
} else {
|
||||
gl.drawElementsInstanced(mode, indexCount, indexType, firstIndex * indexSize, instanceCount);
|
||||
}
|
||||
device.drawIssued(current);
|
||||
device.countDraw(current, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) {
|
||||
WebGl2Pipeline current = currentPipeline();
|
||||
boolean rows = current.drawRows() != null;
|
||||
if (instanceCount == 0 || !prepare(0, rows ? 0 : firstInstance)) {
|
||||
return;
|
||||
}
|
||||
if (rows && !singleRow(current, firstInstance, instanceCount)) {
|
||||
return;
|
||||
}
|
||||
int mode = current.drawMode();
|
||||
device.drawStarting();
|
||||
if (instanceCount == 1) {
|
||||
device.gl().drawArrays(mode, firstVertex, vertexCount);
|
||||
} else {
|
||||
device.gl().drawArraysInstanced(mode, firstVertex, vertexCount, instanceCount);
|
||||
}
|
||||
device.drawIssued(current);
|
||||
device.countDraw(current, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws from the game's sequential quad indices with the backend's own ({@link QuadIndices}),
|
||||
* read from quad {@code vertexOffset / 4} on: the indices there already count from that
|
||||
* vertex, so the vertex attributes stay put (ADR 0027). Every staged draw (the GUI, entities,
|
||||
* text, particles) comes from one shared vertex buffer at its own base vertex, and re-pointing
|
||||
* the attributes costs a buffer bind and a call per attribute. Only a base vertex that isn't a
|
||||
* multiple of four moves them, by the remainder.
|
||||
*/
|
||||
private void drawQuads(
|
||||
WebGl2Pipeline current,
|
||||
int indexCount,
|
||||
int instanceCount,
|
||||
int firstIndex,
|
||||
int vertexOffset,
|
||||
int firstInstance) {
|
||||
int remainder = vertexOffset & 3;
|
||||
long first = firstIndex + (long) (vertexOffset - remainder) / 4 * 6;
|
||||
if (!prepare(remainder, firstInstance)) {
|
||||
return;
|
||||
}
|
||||
device.quadIndices().bind(first + indexCount);
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
int offset = Math.toIntExact(first * 4);
|
||||
device.drawStarting();
|
||||
if (instanceCount == 1) {
|
||||
gl.drawElements(current.drawMode(), indexCount, UNSIGNED_INT, offset);
|
||||
} else {
|
||||
gl.drawElementsInstanced(current.drawMode(), indexCount, UNSIGNED_INT, offset, instanceCount);
|
||||
}
|
||||
device.drawIssued(current);
|
||||
device.countDraw(current, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* An indirect draw, as the game's terrain makes them (ADR 0022): {@code drawCount}
|
||||
* commands of five ints (index count, instance count, first index, base vertex, first
|
||||
* instance), read from the game's copy since WebGL2 can't read them from a buffer. Where the
|
||||
* pipeline reads its instance data as draw rows, they're multi-drawn: sequential quads with the
|
||||
* backend's own ({@link #multiDrawQuads}), own indices rebased ({@link #multiDrawRebased}).
|
||||
* Otherwise each is drawn alone.
|
||||
*/
|
||||
@Override
|
||||
public void drawIndexedIndirect(GpuBufferSlice commands, int drawCount) {
|
||||
WebGl2Buffer indices = indexBuffer;
|
||||
if (indices == null) {
|
||||
return;
|
||||
}
|
||||
ByteBuffer memory = ((WebGl2Buffer) commands.buffer()).memory();
|
||||
int base = Math.toIntExact(commands.offset());
|
||||
WebGl2Pipeline current = currentPipeline();
|
||||
if (current.drawRows() != null && indices.quadSequenceOf(indexSize)) {
|
||||
multiDrawQuads(current, memory, base, drawCount);
|
||||
return;
|
||||
}
|
||||
if (current.drawRows() != null) {
|
||||
multiDrawRebased(current, indices, memory, base, drawCount);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < drawCount; i++) {
|
||||
int command = base + i * COMMAND_BYTES;
|
||||
drawIndexed(
|
||||
memory.getInt(command),
|
||||
memory.getInt(command + 4),
|
||||
memory.getInt(command + 8),
|
||||
memory.getInt(command + 12),
|
||||
memory.getInt(command + 16));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws indirect commands over the game's sequential quad indices with the backend's own
|
||||
* ({@link QuadIndices}), whose indices already count from each command's base vertex, so the
|
||||
* commands differ only in where their indices start and can share a multi-draw. A base vertex
|
||||
* that isn't a multiple of four can't be reached that way; those commands are drawn by a
|
||||
* multi-draw of their own, with the vertex attributes moved by the remainder. So a heap's
|
||||
* commands take at most four calls (more past {@link DrawIdRewrite#ROWS} sub-draws).
|
||||
*/
|
||||
private void multiDrawQuads(WebGl2Pipeline current, ByteBuffer memory, int base, int drawCount) {
|
||||
DrawRows rows = device.drawRows();
|
||||
for (int remainder = 0; remainder < 4; remainder++) {
|
||||
rows.clear();
|
||||
long needed = 0;
|
||||
for (int i = 0; i < drawCount; i++) {
|
||||
int command = base + i * COMMAND_BYTES;
|
||||
int baseVertex = memory.getInt(command + 12);
|
||||
int instances = memory.getInt(command + 4);
|
||||
if ((baseVertex & 3) != remainder || instances == 0) {
|
||||
continue;
|
||||
}
|
||||
int indexCount = memory.getInt(command);
|
||||
long first = memory.getInt(command + 8) + (long) (baseVertex - remainder) / 4 * 6;
|
||||
if (instances != 1 || first * 4 > Integer.MAX_VALUE) {
|
||||
warnOnce("an indirect draw of " + instances + " instances from index " + first);
|
||||
continue;
|
||||
}
|
||||
addRow(current, rows, memory.getInt(command + 16), indexCount, (int) first * 4);
|
||||
needed = Math.max(needed, first + indexCount);
|
||||
if (rows.full()) {
|
||||
flushQuads(current, rows, remainder, needed);
|
||||
rows.clear();
|
||||
needed = 0;
|
||||
}
|
||||
}
|
||||
if (rows.count() > 0) {
|
||||
flushQuads(current, rows, remainder, needed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws indirect commands whose indices are their own (translucent sections, sorted back to
|
||||
* front) with the indices copied, each plus its command's base vertex, and kept until the game
|
||||
* sorts that section again ({@link RebasedIndices}), so they share multi-draws, in the
|
||||
* commands' order.
|
||||
*/
|
||||
private void multiDrawRebased(
|
||||
WebGl2Pipeline current, WebGl2Buffer indices, ByteBuffer memory, int base, int drawCount) {
|
||||
DrawRows rows = device.drawRows();
|
||||
RebasedIndices rebased = device.rebasedIndices();
|
||||
long total = 0;
|
||||
for (int i = 0; i < drawCount; i++) {
|
||||
total += memory.getInt(base + i * COMMAND_BYTES);
|
||||
}
|
||||
// Room for every command's copy: a batch's offsets must all stay in the same arena.
|
||||
rebased.begin(total);
|
||||
rows.clear();
|
||||
for (int i = 0; i < drawCount; i++) {
|
||||
int command = base + i * COMMAND_BYTES;
|
||||
int instances = memory.getInt(command + 4);
|
||||
if (instances == 0) {
|
||||
continue;
|
||||
}
|
||||
if (instances != 1) {
|
||||
warnOnce("an indirect draw of " + instances + " instances");
|
||||
continue;
|
||||
}
|
||||
int indexCount = memory.getInt(command);
|
||||
int offset = rebased.offsetOf(
|
||||
indices, indexSize, memory.getInt(command + 8), indexCount, memory.getInt(command + 12));
|
||||
addRow(current, rows, memory.getInt(command + 16), indexCount, offset);
|
||||
if (rows.full()) {
|
||||
flushRebased(current, rows, rebased);
|
||||
rows.clear();
|
||||
}
|
||||
}
|
||||
if (rows.count() > 0) {
|
||||
flushRebased(current, rows, rebased);
|
||||
}
|
||||
}
|
||||
|
||||
private void flushRebased(WebGl2Pipeline current, DrawRows rows, RebasedIndices rebased) {
|
||||
if (!prepare(0, 0)) {
|
||||
return;
|
||||
}
|
||||
rebased.upload();
|
||||
rows.upload();
|
||||
device.drawStarting();
|
||||
rows.multiDraw(device.multiDrawExtension(), current.drawMode());
|
||||
device.drawIssued(current);
|
||||
device.countDraw(current, rows.count());
|
||||
}
|
||||
|
||||
private void flushQuads(WebGl2Pipeline current, DrawRows rows, int baseVertex, long indices) {
|
||||
if (!prepare(baseVertex, 0)) {
|
||||
return;
|
||||
}
|
||||
device.quadIndices().bind(indices);
|
||||
rows.upload();
|
||||
device.drawStarting();
|
||||
rows.multiDraw(device.multiDrawExtension(), current.drawMode());
|
||||
device.drawIssued(current);
|
||||
device.countDraw(current, rows.count());
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds one draw row, for a single draw with a draw-row pipeline; false (and the draw skipped)
|
||||
* for several instances, which one row can't describe.
|
||||
*/
|
||||
private boolean singleRow(WebGl2Pipeline current, int firstInstance, int instanceCount) {
|
||||
if (instanceCount != 1) {
|
||||
warnOnce("a draw of " + instanceCount + " instances");
|
||||
return false;
|
||||
}
|
||||
DrawRows rows = device.drawRows();
|
||||
rows.clear();
|
||||
addRow(current, rows, firstInstance, 0, 0);
|
||||
rows.upload();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Adds the row of instance {@code instance} of the draw-row slot's vertex buffer. */
|
||||
private void addRow(WebGl2Pipeline current, DrawRows rows, int instance, int indexCount, int indexByteOffset) {
|
||||
VertexLayout.DrawRowLayout layout = current.drawRows();
|
||||
GpuBufferSlice slice = layout == null ? null : vertexBuffers[layout.slot()];
|
||||
if (layout == null || slice == null) {
|
||||
rows.add(ZERO_ROW, 0, 0, indexCount, indexByteOffset);
|
||||
return;
|
||||
}
|
||||
int offset = Math.toIntExact(slice.offset() + (long) instance * layout.stride());
|
||||
rows.add(((WebGl2Buffer) slice.buffer()).memory(), offset, layout.stride(), indexCount, indexByteOffset);
|
||||
}
|
||||
|
||||
private void warnOnce(String what) {
|
||||
if (!warned) {
|
||||
warned = true;
|
||||
WebGl.warn("[Incari] Skipping draws of " + currentPipeline().name() + ": " + what
|
||||
+ ", but its instance data is read per draw");
|
||||
}
|
||||
}
|
||||
|
||||
// The device reports no direct multi-draws, so the frontend never calls these.
|
||||
|
||||
@Override
|
||||
public void multiDrawIndexed(IntBuffer drawParameters, int instanceCount, int firstInstance, int drawCount) {
|
||||
throw new UnsupportedOperationException("WebGL2 has no multi-draw");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void multiDrawIndexed(
|
||||
PointerBuffer firstIndexOffsets, IntBuffer indexCounts, IntBuffer vertexOffsets, int drawCount) {
|
||||
throw new UnsupportedOperationException("WebGL2 has no multi-draw");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void multiDraw(IntBuffer drawParameters, int instanceCount, int firstInstance, int drawCount) {
|
||||
throw new UnsupportedOperationException("WebGL2 has no multi-draw");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void multiDraw(IntBuffer firstVertices, IntBuffer vertexCounts, int drawCount) {
|
||||
throw new UnsupportedOperationException("WebGL2 has no multi-draw");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawIndirect(GpuBufferSlice commands, int drawCount) {
|
||||
// Only terrain draws indirectly, and always with indices.
|
||||
throw new UnsupportedOperationException("WebGL2 has no indirect draws without indices");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTimestamp(GpuQueryPool pool, int index) {}
|
||||
|
||||
private WebGl2Pipeline currentPipeline() {
|
||||
WebGl2Pipeline current = pipeline;
|
||||
if (current == null) {
|
||||
throw new IllegalStateException("No pipeline bound");
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies what the next draw needs, with per-vertex attributes from vertex {@code baseVertex}
|
||||
* and per-instance ones from instance {@code baseInstance}; false if it can't be drawn (the
|
||||
* pipeline can't run here).
|
||||
*/
|
||||
private boolean prepare(int baseVertex, int baseInstance) {
|
||||
// Uniforms written since the last draw reach WebGL now, in one upload per buffer (ADR 0027).
|
||||
device.pendingUploads().flush();
|
||||
WebGl2Pipeline current = currentPipeline();
|
||||
if (!current.use()) {
|
||||
device.skippedDraws++;
|
||||
return false;
|
||||
}
|
||||
if (uniformsDirty) {
|
||||
bindUniforms(current);
|
||||
uniformsDirty = false;
|
||||
}
|
||||
if (attributesDirty || baseVertex != attributesBaseVertex || baseInstance != attributesBaseInstance) {
|
||||
bindAttributes(current, baseVertex, baseInstance);
|
||||
attributesDirty = false;
|
||||
attributesBaseVertex = baseVertex;
|
||||
attributesBaseInstance = baseInstance;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void bindUniforms(WebGl2Pipeline current) {
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
List<BindGroupLayout.UniformDescription> descriptions = current.uniforms();
|
||||
for (int i = 0; i < descriptions.size() && i < MAX_UNIFORMS; i++) {
|
||||
Object value = uniforms[i];
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
UniformType type = descriptions.get(i).type();
|
||||
if (type == UniformType.UNIFORM_BUFFER && value instanceof GpuBufferSlice slice) {
|
||||
WebGl2Buffer buffer = (WebGl2Buffer) slice.buffer();
|
||||
// Bind at least what the program says the block takes, where the buffer has it: the
|
||||
// bytes past the game's slice are never read, but WebGL checks the range's size.
|
||||
long length =
|
||||
Math.max(slice.length(), Math.min(current.blockSize(i), buffer.glSize() - slice.offset()));
|
||||
if (device.bindings().uniformBuffer(i, buffer, slice.offset(), length)) {
|
||||
gl.bindBufferRange(
|
||||
UNIFORM_BUFFER,
|
||||
i,
|
||||
buffer.handle(),
|
||||
Math.toIntExact(slice.offset()),
|
||||
Math.toIntExact(length));
|
||||
}
|
||||
} else if (type == UniformType.TEXEL_BUFFER && value instanceof GpuBufferSlice slice) {
|
||||
// The frontend only takes whole buffers as texel buffers.
|
||||
GpuFormat format = descriptions.get(i).gpuFormat();
|
||||
if (format == null) {
|
||||
continue;
|
||||
}
|
||||
TexelBufferTexture texture = ((WebGl2Buffer) slice.buffer()).texelTexture(format);
|
||||
if (device.bindings().texelBuffer(i, texture)) {
|
||||
gl.activeTexture(TEXTURE0 + i);
|
||||
gl.bindTexture(TEXTURE_2D, texture.handle());
|
||||
gl.bindSampler(i, null);
|
||||
}
|
||||
} else if (type == UniformType.COMBINED_IMAGE_SAMPLER && value instanceof TextureViewAndSampler pair) {
|
||||
WebGl2TextureView view = (WebGl2TextureView) pair.view();
|
||||
WebGl2Texture texture = view.glTexture();
|
||||
WebGl2Sampler sampler = (WebGl2Sampler) pair.sampler();
|
||||
boolean rebind = device.bindings().texture(i, texture, sampler);
|
||||
boolean levels = texture.needsLevels(view.baseMipLevel(), view.mipLevels());
|
||||
if (rebind || levels) {
|
||||
gl.activeTexture(TEXTURE0 + i);
|
||||
}
|
||||
if (rebind) {
|
||||
gl.bindTexture(texture.target(), texture.handle());
|
||||
gl.bindSampler(i, sampler.handle());
|
||||
}
|
||||
if (levels) {
|
||||
texture.restrictLevels(view.baseMipLevel(), view.mipLevels());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void bindAttributes(WebGl2Pipeline current, int baseVertex, int baseInstance) {
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
int enabled = 0;
|
||||
for (VertexLayout.Binding binding : current.attributes()) {
|
||||
GpuBufferSlice slice = vertexBuffers[binding.slot()];
|
||||
if (slice == null) {
|
||||
continue;
|
||||
}
|
||||
WebGl2Buffer buffer = (WebGl2Buffer) slice.buffer();
|
||||
gl.bindBuffer(ARRAY_BUFFER, buffer.handle());
|
||||
// Per-instance data moves with the first instance instead of the base vertex.
|
||||
long first = binding.divisor() == 0
|
||||
? (long) baseVertex * binding.stride()
|
||||
: (long) baseInstance / binding.divisor() * binding.stride();
|
||||
int offset = Math.toIntExact(slice.offset() + binding.offset() + first);
|
||||
GlFormats.AttributeFormat format = binding.format();
|
||||
if (binding.integer()) {
|
||||
gl.vertexAttribIPointer(binding.location(), format.size(), format.type(), binding.stride(), offset);
|
||||
} else {
|
||||
gl.vertexAttribPointer(
|
||||
binding.location(),
|
||||
format.size(),
|
||||
format.type(),
|
||||
format.normalized(),
|
||||
binding.stride(),
|
||||
offset);
|
||||
}
|
||||
device.bindings().divisor(binding.location(), binding.divisor());
|
||||
enabled |= 1 << binding.location();
|
||||
}
|
||||
device.bindings().enableAttributes(enabled);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.LINEAR;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.LINEAR_MIPMAP_LINEAR;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.NEAREST;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.NEAREST_MIPMAP_LINEAR;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_MAG_FILTER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_MAX_LOD;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_MIN_FILTER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_WRAP_S;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_WRAP_T;
|
||||
|
||||
import com.mojang.renderpearl.api.textures.AddressMode;
|
||||
import com.mojang.renderpearl.api.textures.FilterMode;
|
||||
import com.mojang.renderpearl.api.textures.GpuSampler;
|
||||
import java.util.OptionalDouble;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLSampler;
|
||||
|
||||
/**
|
||||
* A WebGL2 sampler object. Minification always blends between mip levels, as on the game's other
|
||||
* backends: a texture without mips has one level, and a view limits the levels, so the blend only
|
||||
* does anything where there are levels to blend.
|
||||
*/
|
||||
final class WebGl2Sampler implements GpuSampler {
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final WebGLSampler handle;
|
||||
private final AddressMode addressModeU;
|
||||
private final AddressMode addressModeV;
|
||||
private final FilterMode minFilter;
|
||||
private final FilterMode magFilter;
|
||||
private final int maxAnisotropy;
|
||||
private final OptionalDouble maxLod;
|
||||
private boolean closed;
|
||||
|
||||
WebGl2Sampler(
|
||||
WebGl2Device device,
|
||||
AddressMode addressModeU,
|
||||
AddressMode addressModeV,
|
||||
FilterMode minFilter,
|
||||
FilterMode magFilter,
|
||||
int maxAnisotropy,
|
||||
OptionalDouble maxLod) {
|
||||
this.device = device;
|
||||
this.addressModeU = addressModeU;
|
||||
this.addressModeV = addressModeV;
|
||||
this.minFilter = minFilter;
|
||||
this.magFilter = magFilter;
|
||||
this.maxAnisotropy = maxAnisotropy;
|
||||
this.maxLod = maxLod;
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
handle = gl.createSampler();
|
||||
gl.samplerParameteri(handle, TEXTURE_WRAP_S, GlFormats.wrap(addressModeU));
|
||||
gl.samplerParameteri(handle, TEXTURE_WRAP_T, GlFormats.wrap(addressModeV));
|
||||
gl.samplerParameteri(
|
||||
handle,
|
||||
TEXTURE_MIN_FILTER,
|
||||
minFilter == FilterMode.LINEAR ? LINEAR_MIPMAP_LINEAR : NEAREST_MIPMAP_LINEAR);
|
||||
gl.samplerParameteri(handle, TEXTURE_MAG_FILTER, magFilter == FilterMode.LINEAR ? LINEAR : NEAREST);
|
||||
if (maxLod.isPresent()) {
|
||||
gl.samplerParameterf(handle, TEXTURE_MAX_LOD, (float) maxLod.getAsDouble());
|
||||
}
|
||||
if (maxAnisotropy > 1 && device.hasAnisotropy()) {
|
||||
gl.samplerParameterf(handle, WebGl.TEXTURE_MAX_ANISOTROPY, maxAnisotropy);
|
||||
}
|
||||
}
|
||||
|
||||
WebGLSampler handle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AddressMode getAddressModeU() {
|
||||
return addressModeU;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AddressMode getAddressModeV() {
|
||||
return addressModeV;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FilterMode getMinFilter() {
|
||||
return minFilter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FilterMode getMagFilter() {
|
||||
return magFilter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxAnisotropy() {
|
||||
return maxAnisotropy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble getMaxLod() {
|
||||
return maxLod;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
closed = true;
|
||||
device.gl().deleteSampler(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.COLOR_BUFFER_BIT;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.DRAW_FRAMEBUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.LINEAR;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.NEAREST;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.READ_FRAMEBUFFER;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.SCISSOR_TEST;
|
||||
|
||||
import com.mojang.renderpearl.api.device.GpuSurface;
|
||||
import com.mojang.renderpearl.api.device.SurfaceException;
|
||||
import com.mojang.renderpearl.api.textures.GpuTextureView;
|
||||
import com.mojang.renderpearl.backend.api.CommandEncoderBackend;
|
||||
import com.mojang.renderpearl.backend.api.GpuSurfaceBackend;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
|
||||
/**
|
||||
* The canvas. The game renders into its own target and blits it here once a frame; the browser
|
||||
* shows the canvas when the frame's JavaScript task ends (the game yields to the page every
|
||||
* frame), so presenting does nothing. The canvas's size belongs to the platform
|
||||
* ({@code platform-web}'s window), which keeps it at the CSS size times the pixel ratio.
|
||||
*/
|
||||
final class WebGl2Surface implements GpuSurfaceBackend {
|
||||
|
||||
private final WebGl2Device device;
|
||||
private GpuSurface.Configuration configuration = new GpuSurface.Configuration(1, 1, GpuSurface.PresentMode.FIFO);
|
||||
/** The lost context was reported to the game ({@link #acquireNextTexture}). */
|
||||
private boolean lostReported;
|
||||
|
||||
WebGl2Surface(WebGl2Device device) {
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(GpuSurface.Configuration config) {
|
||||
configuration = config;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSuboptimal() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void acquireNextTexture() throws SurfaceException {
|
||||
if (!lostReported && WebGl.isContextLost(device.gl())) {
|
||||
// The GPU process crashed or the tab was starved. Said once: the game logs every
|
||||
// failure, and the context never comes back with the game's resources on it. The
|
||||
// platform reports the window minimized from the next frame, which stops the game
|
||||
// asking; until then, and after, drawing into a lost context does nothing.
|
||||
lostReported = true;
|
||||
throw new SurfaceException("The WebGL context was lost; the page must be reloaded");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void blitFromTexture(CommandEncoderBackend commandEncoder, GpuTextureView textureView) {
|
||||
WebGl2TextureView view = (WebGl2TextureView) textureView;
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
device.framebuffers().bindSingle(READ_FRAMEBUFFER, view.glTexture(), view.baseMipLevel());
|
||||
gl.bindFramebuffer(DRAW_FRAMEBUFFER, null);
|
||||
gl.disable(SCISSOR_TEST);
|
||||
device.state().colorMask(15);
|
||||
int width = view.getWidth(0);
|
||||
int height = view.getHeight(0);
|
||||
int targetWidth = configuration.width();
|
||||
int targetHeight = configuration.height();
|
||||
boolean sameSize = width == targetWidth && height == targetHeight;
|
||||
gl.blitFramebuffer(
|
||||
0, 0, width, height, 0, 0, targetWidth, targetHeight, COLOR_BUFFER_BIT, sameSize ? NEAREST : LINEAR);
|
||||
device.invalidateBindings();
|
||||
device.frames++;
|
||||
device.frameEnded();
|
||||
WebGl.publishStats(device.frames, device.draws, device.skippedDraws, width, height, targetWidth, targetHeight);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void present() {}
|
||||
|
||||
/** Only FIFO: the browser shows frames on its own vsync, whatever the game asks. */
|
||||
@Override
|
||||
public Collection<GpuSurface.PresentMode> supportedPresentModes() {
|
||||
return List.of(GpuSurface.PresentMode.FIFO);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_2D;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_BASE_LEVEL;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_CUBE_MAP;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X;
|
||||
import static org.teavm.jso.webgl.WebGL2RenderingContext.TEXTURE_MAX_LEVEL;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import com.mojang.renderpearl.api.textures.GpuTexture;
|
||||
import com.mojang.renderpearl.backend.common.BaseGpuTexture;
|
||||
import org.teavm.jso.webgl.WebGL2RenderingContext;
|
||||
import org.teavm.jso.webgl.WebGLTexture;
|
||||
|
||||
/**
|
||||
* A texture with immutable storage ({@code texStorage2D}): every mip level exists from the start,
|
||||
* so the texture is always complete, whatever gets uploaded when. A cubemap-compatible texture is
|
||||
* a WebGL cube map with its six faces as the game's six layers.
|
||||
*/
|
||||
final class WebGl2Texture extends BaseGpuTexture {
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final WebGLTexture handle;
|
||||
private final int target;
|
||||
private final GlFormats.TextureFormat glFormat;
|
||||
private int baseLevel;
|
||||
private int maxLevel;
|
||||
private boolean closed;
|
||||
|
||||
WebGl2Texture(
|
||||
WebGl2Device device,
|
||||
@GpuTexture.Usage int usage,
|
||||
String label,
|
||||
GpuFormat format,
|
||||
GlFormats.TextureFormat glFormat,
|
||||
int width,
|
||||
int height,
|
||||
int depthOrLayers,
|
||||
int mipLevels) {
|
||||
super(usage, label, format, width, height, depthOrLayers, mipLevels);
|
||||
this.device = device;
|
||||
this.glFormat = glFormat;
|
||||
this.target = (usage & GpuTexture.USAGE_CUBEMAP_COMPATIBLE) != 0 ? TEXTURE_CUBE_MAP : TEXTURE_2D;
|
||||
WebGL2RenderingContext gl = device.gl();
|
||||
handle = gl.createTexture();
|
||||
device.bindTextureForUpdate(target, handle);
|
||||
gl.texStorage2D(target, mipLevels, glFormat.internalFormat(), width, height);
|
||||
baseLevel = 0;
|
||||
maxLevel = mipLevels - 1;
|
||||
gl.texParameteri(target, TEXTURE_BASE_LEVEL, baseLevel);
|
||||
gl.texParameteri(target, TEXTURE_MAX_LEVEL, maxLevel);
|
||||
}
|
||||
|
||||
WebGLTexture handle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
int target() {
|
||||
return target;
|
||||
}
|
||||
|
||||
GlFormats.TextureFormat glFormat() {
|
||||
return glFormat;
|
||||
}
|
||||
|
||||
/** The 2D image target of one layer: the texture itself, or one face of a cube map. */
|
||||
int imageTarget(int layer) {
|
||||
return target == TEXTURE_CUBE_MAP ? TEXTURE_CUBE_MAP_POSITIVE_X + layer : TEXTURE_2D;
|
||||
}
|
||||
|
||||
/** Whether sampling through a view of these levels needs {@link #restrictLevels}. */
|
||||
boolean needsLevels(int base, int count) {
|
||||
return base != baseLevel || base + count - 1 != maxLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits sampling to a view's mip levels. WebGL2 has no texture views, so the range is texture
|
||||
* state, set when a view is bound for sampling; the texture must be bound on the active unit.
|
||||
*/
|
||||
void restrictLevels(int base, int count) {
|
||||
int max = base + count - 1;
|
||||
if (base != baseLevel) {
|
||||
device.gl().texParameteri(target, TEXTURE_BASE_LEVEL, base);
|
||||
baseLevel = base;
|
||||
}
|
||||
if (max != maxLevel) {
|
||||
device.gl().texParameteri(target, TEXTURE_MAX_LEVEL, max);
|
||||
maxLevel = max;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!closed) {
|
||||
closed = true;
|
||||
device.framebuffers().forget(this);
|
||||
device.gl().deleteTexture(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import com.mojang.renderpearl.backend.common.BaseGpuTextureView;
|
||||
|
||||
/**
|
||||
* A range of a texture's mip levels. WebGL2 has no view objects: sampling through a view limits the
|
||||
* texture's levels when it's bound, and rendering to one attaches its base level.
|
||||
*/
|
||||
final class WebGl2TextureView extends BaseGpuTextureView {
|
||||
|
||||
private boolean closed;
|
||||
|
||||
WebGl2TextureView(WebGl2Texture texture, int baseMipLevel, int mipLevels) {
|
||||
super(texture, baseMipLevel, mipLevels);
|
||||
}
|
||||
|
||||
WebGl2Texture glTexture() {
|
||||
return (WebGl2Texture) texture();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return closed || texture().isClosed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
||||
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
|
||||
import com.mojang.renderpearl.api.buffers.TransientMemory;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
/**
|
||||
* Memory that lives until the frame's commands are submitted: uniforms, streamed vertices, staging.
|
||||
* GPU memory is carved from blocks, one pool per usage (WebGL won't let an index buffer be anything
|
||||
* else, and uniform offsets have their own alignment), and the blocks are reused every frame, so a
|
||||
* steady frame allocates no WebGL buffers. WebGL runs commands in order, so reusing a block after
|
||||
* submit can't overwrite data a draw still needs.
|
||||
*/
|
||||
final class WebGl2TransientMemory implements TransientMemory {
|
||||
|
||||
/** Big enough for a frame's GUI and uniforms in one block; bigger requests get their own. */
|
||||
private static final int BLOCK_SIZE = 1 << 20;
|
||||
|
||||
private final WebGl2Device device;
|
||||
private final Map<Integer, List<Block>> pools = new HashMap<>();
|
||||
private final List<ByteBuffer> cpu = new ArrayList<>();
|
||||
|
||||
WebGl2TransientMemory(WebGl2Device device) {
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
/** Frees this frame's CPU memory and rewinds every block; the encoder calls it on submit. */
|
||||
void release() {
|
||||
for (ByteBuffer buffer : cpu) {
|
||||
MemoryUtil.memFree(buffer);
|
||||
}
|
||||
cpu.clear();
|
||||
for (List<Block> blocks : pools.values()) {
|
||||
for (Block block : blocks) {
|
||||
block.used = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuffer allocateCpu(long size, long alignment, long minimumAllocation, long elementSize) {
|
||||
ByteBuffer buffer = MemoryUtil.memCalloc(Math.toIntExact(size)).order(ByteOrder.nativeOrder());
|
||||
cpu.add(buffer);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBufferSlice.MappedView allocateStaging(
|
||||
long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) {
|
||||
return allocate(size, alignment, usage).map(true, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBufferSlice allocateGpu(
|
||||
long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) {
|
||||
return allocate(size, alignment, usage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBufferSlice.MappedView allocateGpuMapped(
|
||||
long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) {
|
||||
return allocate(size, alignment, usage).map(true, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBufferSlice uploadStaging(
|
||||
List<ByteBuffer> data,
|
||||
long alignment,
|
||||
@GpuBuffer.Usage int usage,
|
||||
long minimumAllocation,
|
||||
long elementSize) {
|
||||
return upload(data, alignment, usage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GpuBufferSlice uploadGpu(
|
||||
List<ByteBuffer> data,
|
||||
long alignment,
|
||||
@GpuBuffer.Usage int usage,
|
||||
long minimumAllocation,
|
||||
long elementSize) {
|
||||
return upload(data, alignment, usage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<GpuBufferSlice> multiUploadStaging(List<ByteBuffer> data, long alignment, @GpuBuffer.Usage int usage) {
|
||||
return multiUpload(data, alignment, usage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<GpuBufferSlice> multiUploadGpu(List<ByteBuffer> data, long alignment, @GpuBuffer.Usage int usage) {
|
||||
return multiUpload(data, alignment, usage);
|
||||
}
|
||||
|
||||
private GpuBufferSlice upload(List<ByteBuffer> data, long alignment, @GpuBuffer.Usage int usage) {
|
||||
long size = 0;
|
||||
for (ByteBuffer part : data) {
|
||||
size += part.remaining();
|
||||
}
|
||||
GpuBufferSlice slice = allocate(size, alignment, usage);
|
||||
WebGl2Buffer buffer = (WebGl2Buffer) slice.buffer();
|
||||
ByteBuffer memory = buffer.memory();
|
||||
int offset = Math.toIntExact(slice.offset());
|
||||
for (ByteBuffer part : data) {
|
||||
memory.put(offset, part, part.position(), part.remaining());
|
||||
offset += part.remaining();
|
||||
}
|
||||
buffer.upload(Math.toIntExact(slice.offset()), Math.toIntExact(size));
|
||||
return slice;
|
||||
}
|
||||
|
||||
private List<GpuBufferSlice> multiUpload(List<ByteBuffer> data, long alignment, @GpuBuffer.Usage int usage) {
|
||||
List<GpuBufferSlice> slices = new ArrayList<>(data.size());
|
||||
for (ByteBuffer part : data) {
|
||||
slices.add(upload(List.of(part), alignment, usage));
|
||||
}
|
||||
return slices;
|
||||
}
|
||||
|
||||
private GpuBufferSlice allocate(long size, long alignment, @GpuBuffer.Usage int usage) {
|
||||
// Every transient buffer can be written from the CPU, whatever else it's for.
|
||||
int blockUsage = usage | GpuBuffer.USAGE_MAP_WRITE | GpuBuffer.USAGE_COPY_DST;
|
||||
List<Block> blocks = pools.computeIfAbsent(blockUsage, u -> new ArrayList<>());
|
||||
long align = Math.max(1, alignment);
|
||||
for (Block block : blocks) {
|
||||
long start = (block.used + align - 1) / align * align;
|
||||
if (start + size <= block.buffer.size()) {
|
||||
block.used = start + size;
|
||||
return block.buffer.slice(start, size);
|
||||
}
|
||||
}
|
||||
Block block = new Block(new WebGl2Buffer(device, blockUsage, Math.max(BLOCK_SIZE, size)));
|
||||
blocks.add(block);
|
||||
block.used = size;
|
||||
return block.buffer.slice(0, size);
|
||||
}
|
||||
|
||||
private static final class Block {
|
||||
final WebGl2Buffer buffer;
|
||||
long used;
|
||||
|
||||
Block(WebGl2Buffer buffer) {
|
||||
this.buffer = buffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* The WebGL2 graphics backend: the game's {@code GpuDevice} backend API over WebGL2, for
|
||||
* the browser build. {@link incari.render.webgl2.WebGl2Backend} is the entry point.
|
||||
*/
|
||||
@NullMarked
|
||||
package incari.render.webgl2;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package incari.render.webgl2.shaders;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Every shader stage the game can ask for, translated when the browser build is made
|
||||
* ({@code tools/shaders}) and fetched by the page as {@code shaders.json}. It holds translated
|
||||
* Mojang shaders, so like every build output it is never committed or published.
|
||||
*
|
||||
* <p>Read and written as Gson trees, not through Gson's reflective binding, which the browser build
|
||||
* doesn't support.
|
||||
*/
|
||||
public final class ShaderManifest {
|
||||
|
||||
/** Bumped when the layout changes, so a stale file fails clearly instead of half-working. */
|
||||
public static final int FORMAT = 1;
|
||||
|
||||
private final String minecraftVersion;
|
||||
private final Map<String, TranslatedStage> stages;
|
||||
|
||||
public ShaderManifest(String minecraftVersion, Collection<TranslatedStage> stages) {
|
||||
this.minecraftVersion = minecraftVersion;
|
||||
// Sorted, so the file is the same from one build to the next.
|
||||
Map<String, TranslatedStage> byKey = new TreeMap<>();
|
||||
for (TranslatedStage stage : stages) {
|
||||
byKey.put(stage.key(), stage);
|
||||
}
|
||||
this.stages = byKey;
|
||||
}
|
||||
|
||||
public String minecraftVersion() {
|
||||
return minecraftVersion;
|
||||
}
|
||||
|
||||
public @Nullable TranslatedStage stage(ShaderStageKey key) {
|
||||
return stages.get(key.asString());
|
||||
}
|
||||
|
||||
public Collection<TranslatedStage> stages() {
|
||||
return stages.values();
|
||||
}
|
||||
|
||||
public String toJson() {
|
||||
JsonObject root = new JsonObject();
|
||||
root.addProperty("format", FORMAT);
|
||||
root.addProperty("minecraft", minecraftVersion);
|
||||
JsonObject all = new JsonObject();
|
||||
for (TranslatedStage stage : stages.values()) {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("sourceHash", stage.sourceHash());
|
||||
String unsupported = stage.unsupported();
|
||||
if (unsupported != null) {
|
||||
json.addProperty("unsupported", unsupported);
|
||||
} else {
|
||||
json.addProperty("glsl", stage.glsl());
|
||||
JsonArray attributes = new JsonArray();
|
||||
for (TranslatedStage.Attribute attribute : stage.attributes()) {
|
||||
JsonObject entry = new JsonObject();
|
||||
entry.addProperty("name", attribute.name());
|
||||
entry.addProperty("location", attribute.location());
|
||||
entry.addProperty("integer", attribute.integer());
|
||||
attributes.add(entry);
|
||||
}
|
||||
json.add("attributes", attributes);
|
||||
json.add("uniformBlocks", strings(stage.uniformBlocks()));
|
||||
json.add("samplers", strings(stage.samplers()));
|
||||
}
|
||||
all.add(stage.key(), json);
|
||||
}
|
||||
root.add("stages", all);
|
||||
return root.toString();
|
||||
}
|
||||
|
||||
public static ShaderManifest parse(String text) {
|
||||
JsonObject root = JsonParser.parseString(text).getAsJsonObject();
|
||||
int format = root.get("format").getAsInt();
|
||||
if (format != FORMAT) {
|
||||
throw new IllegalArgumentException(
|
||||
"shaders.json is format " + format + ", this build reads format " + FORMAT + "; rebuild it");
|
||||
}
|
||||
List<TranslatedStage> stages = new ArrayList<>();
|
||||
for (Map.Entry<String, JsonElement> entry :
|
||||
root.getAsJsonObject("stages").entrySet()) {
|
||||
JsonObject json = entry.getValue().getAsJsonObject();
|
||||
String sourceHash = json.get("sourceHash").getAsString();
|
||||
JsonElement unsupported = json.get("unsupported");
|
||||
if (unsupported != null) {
|
||||
stages.add(TranslatedStage.unsupported(entry.getKey(), sourceHash, unsupported.getAsString()));
|
||||
continue;
|
||||
}
|
||||
List<TranslatedStage.Attribute> attributes = new ArrayList<>();
|
||||
for (JsonElement element : json.getAsJsonArray("attributes")) {
|
||||
JsonObject attribute = element.getAsJsonObject();
|
||||
attributes.add(new TranslatedStage.Attribute(
|
||||
attribute.get("name").getAsString(),
|
||||
attribute.get("location").getAsInt(),
|
||||
attribute.get("integer").getAsBoolean()));
|
||||
}
|
||||
stages.add(new TranslatedStage(
|
||||
entry.getKey(),
|
||||
sourceHash,
|
||||
json.get("glsl").getAsString(),
|
||||
attributes,
|
||||
strings(json.getAsJsonArray("uniformBlocks")),
|
||||
strings(json.getAsJsonArray("samplers")),
|
||||
null));
|
||||
}
|
||||
return new ShaderManifest(root.get("minecraft").getAsString(), stages);
|
||||
}
|
||||
|
||||
private static JsonArray strings(List<String> values) {
|
||||
JsonArray array = new JsonArray();
|
||||
values.forEach(array::add);
|
||||
return array;
|
||||
}
|
||||
|
||||
private static List<String> strings(JsonArray array) {
|
||||
List<String> values = new ArrayList<>(array.size());
|
||||
for (JsonElement element : array) {
|
||||
values.add(element.getAsString());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package incari.render.webgl2.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Names one translated shader stage: which source file, which stage, compiled with which defines.
|
||||
* Two pipelines that share all three share the stage. The build tool files each translation under
|
||||
* this key and the browser looks it up the same way, so both sides must produce the same string;
|
||||
* that's why the defines are sorted rather than kept in the game's map order.
|
||||
*/
|
||||
public record ShaderStageKey(ShaderType type, Identifier id, String defines) {
|
||||
|
||||
public static ShaderStageKey of(ShaderType type, Identifier id, ShaderDefines defines) {
|
||||
return new ShaderStageKey(type, id, canonicalDefines(defines));
|
||||
}
|
||||
|
||||
/** {@code KEY=value} pairs sorted by key, then bare flags sorted, joined by {@code ;}. */
|
||||
static String canonicalDefines(ShaderDefines defines) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
defines.values().entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.forEach(entry -> parts.add(entry.getKey() + "=" + entry.getValue()));
|
||||
defines.flags().stream().sorted().forEach(parts::add);
|
||||
return String.join(";", parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* The define the game's shader compiler adds when the device's depth range is 0 to 1 (clip
|
||||
* control); the build translates a second variant of each stage whose source reads it.
|
||||
*/
|
||||
public static final String DEPTH_IS_ZERO_TO_ONE = "RENDERPEARL_DEPTH_IS_ZERO_TO_ONE";
|
||||
|
||||
/** The same stage compiled with one more bare define (a flag), in canonical order. */
|
||||
public ShaderStageKey withFlag(String flag) {
|
||||
List<String> values = new ArrayList<>();
|
||||
List<String> flags = new ArrayList<>();
|
||||
if (!defines.isEmpty()) {
|
||||
for (String part : defines.split(";", -1)) {
|
||||
(part.contains("=") ? values : flags).add(part);
|
||||
}
|
||||
}
|
||||
if (!flags.contains(flag)) {
|
||||
flags.add(flag);
|
||||
}
|
||||
flags.sort(null);
|
||||
values.addAll(flags);
|
||||
return new ShaderStageKey(type, id, String.join(";", values));
|
||||
}
|
||||
|
||||
/** The manifest's key: {@code "<stage> <id> <defines>"}. */
|
||||
public String asString() {
|
||||
return type.getName() + " " + id + " " + defines;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return asString();
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package incari.render.webgl2.shaders;
|
||||
|
||||
/**
|
||||
* A fingerprint of a shader's source text, so the browser can tell when the source it was asked to
|
||||
* compile isn't the one the build translated (a resource pack replaced it). FNV-1a over the UTF-16
|
||||
* code units: trivial to compute the same way in the build tool and under TeaVM, and collisions
|
||||
* only matter between vanilla and a pack's edit of the same file.
|
||||
*/
|
||||
public final class SourceHash {
|
||||
|
||||
private static final long OFFSET_BASIS = 0xcbf29ce484222325L;
|
||||
private static final long PRIME = 0x100000001b3L;
|
||||
|
||||
private SourceHash() {}
|
||||
|
||||
public static String of(String source) {
|
||||
long hash = OFFSET_BASIS;
|
||||
for (int i = 0; i < source.length(); i++) {
|
||||
hash ^= source.charAt(i);
|
||||
hash *= PRIME;
|
||||
}
|
||||
String hex = Long.toHexString(hash);
|
||||
return "0".repeat(16 - hex.length()) + hex;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package incari.render.webgl2.shaders;
|
||||
|
||||
/**
|
||||
* How texel buffers are emulated (WebGL2 has none): a texel buffer uniform becomes a 2D texture
|
||||
* {@link #WIDTH} texels wide, element {@code i} at ({@code i % WIDTH}, {@code i / WIDTH}). The
|
||||
* build rewrites each {@code texelFetch} to that coordinate, and the device copies the buffer into
|
||||
* such a texture; both read the width from here. 2048 is the smallest {@code MAX_TEXTURE_SIZE}
|
||||
* WebGL2 allows, so the layout works on every device, and a power of two keeps the shader's
|
||||
* arithmetic to a mask and a shift.
|
||||
*/
|
||||
public final class TexelBuffers {
|
||||
|
||||
public static final int WIDTH_SHIFT = 11;
|
||||
public static final int WIDTH = 1 << WIDTH_SHIFT;
|
||||
|
||||
private TexelBuffers() {}
|
||||
|
||||
/** The rows a buffer of {@code elements} texels takes. */
|
||||
public static int rows(int elements) {
|
||||
return Math.max(1, (elements + WIDTH - 1) >> WIDTH_SHIFT);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package incari.render.webgl2.shaders;
|
||||
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* One shader stage as the build translated it: GLSL ES 3.00 for WebGL2, plus what the device needs
|
||||
* to wire it up without reflecting on the source at run time (WebGL has no SPIR-V to reflect on).
|
||||
*
|
||||
* @param key the stage's {@link ShaderStageKey#asString() key}
|
||||
* @param sourceHash {@link SourceHash} of the vanilla source the translation came from
|
||||
* @param glsl the GLSL ES 3.00 source, or empty if the stage is unsupported
|
||||
* @param attributes vertex shader inputs by name, as the game's vertex formats name their elements
|
||||
* @param uniformBlocks the uniform blocks' names, which are the pipeline's uniform names
|
||||
* @param samplers the sampler uniforms' names, which are the pipeline's uniform names
|
||||
* @param unsupported why WebGL2 can't run this stage yet (for example a texel buffer), or null
|
||||
*/
|
||||
public record TranslatedStage(
|
||||
String key,
|
||||
String sourceHash,
|
||||
String glsl,
|
||||
List<Attribute> attributes,
|
||||
List<String> uniformBlocks,
|
||||
List<String> samplers,
|
||||
@Nullable String unsupported) {
|
||||
|
||||
public TranslatedStage {
|
||||
attributes = List.copyOf(attributes);
|
||||
uniformBlocks = List.copyOf(uniformBlocks);
|
||||
samplers = List.copyOf(samplers);
|
||||
}
|
||||
|
||||
public static TranslatedStage unsupported(String key, String sourceHash, String reason) {
|
||||
return new TranslatedStage(key, sourceHash, "", List.of(), List.of(), List.of(), reason);
|
||||
}
|
||||
|
||||
public boolean isSupported() {
|
||||
return unsupported == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A vertex shader input.
|
||||
*
|
||||
* @param integer whether the shader reads it as an integer ({@code int}, {@code uvec4}...), which
|
||||
* decides between {@code vertexAttribIPointer} and {@code vertexAttribPointer}
|
||||
*/
|
||||
public record Attribute(String name, int location, boolean integer) {}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* The shader manifest: the game's shaders translated to GLSL ES 3.00 when the browser build is
|
||||
* made, keyed the same way by the build tool and the device.
|
||||
*/
|
||||
@NullMarked
|
||||
package incari.render.webgl2.shaders;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
|
||||
import com.tngtech.archunit.core.importer.ImportOption;
|
||||
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||
import com.tngtech.archunit.junit.ArchTest;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
|
||||
/**
|
||||
* The WebGL2 backend talks to the game only through its render API and the Incari hook for it, and
|
||||
* to the page only through TeaVM's JavaScript interop. LWJGL appears in two places the render API
|
||||
* forces on it: {@code MemoryUtil} for mapped memory the game takes addresses of, and
|
||||
* {@code PointerBuffer} in a multi-draw signature it never implements.
|
||||
*/
|
||||
@AnalyzeClasses(packages = "incari.render.webgl2", importOptions = ImportOption.DoNotIncludeTests.class)
|
||||
class BoundaryTest {
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule onlyTheRenderApiAndJso = classes()
|
||||
.should()
|
||||
.onlyDependOnClassesThat()
|
||||
.resideInAnyPackage(
|
||||
"java..",
|
||||
"org.jspecify..",
|
||||
"org.teavm.jso..",
|
||||
"com.mojang.renderpearl.api..",
|
||||
"com.mojang.renderpearl.backend.api..",
|
||||
"com.mojang.renderpearl.backend.common..",
|
||||
"com.mojang.renderpearl.frontend",
|
||||
"com.mojang.renderpearl.util..",
|
||||
"net.minecraft.resources..",
|
||||
"net.minecraft.client.renderer",
|
||||
"com.google.gson..",
|
||||
"it.unimi.dsi.fastutil..",
|
||||
"org.joml..",
|
||||
"org.lwjgl",
|
||||
"org.lwjgl.system",
|
||||
"incari.client.render..",
|
||||
"incari.render.webgl2..")
|
||||
.allowEmptyShould(true);
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule lwjglOnlyWhereTheApiForcesIt = classes()
|
||||
.should()
|
||||
.onlyDependOnClassesThat()
|
||||
.resideOutsideOfPackages("org.lwjgl.opengl..", "org.lwjgl.sdl..", "org.lwjgl.util..", "org.lwjgl.vulkan..")
|
||||
.allowEmptyShould(true);
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Which buffers keep the game's copy of their contents. */
|
||||
class BufferCopyTest {
|
||||
|
||||
private static final int HEAP = GpuBuffer.USAGE_VERTEX | GpuBuffer.USAGE_COPY_DST | GpuBuffer.USAGE_COPY_SRC;
|
||||
|
||||
@Test
|
||||
void theTerrainsVertexHeapsKeepNone() {
|
||||
assertThat(BufferCopies.keepsCopy(HEAP, 32 << 20)).isFalse();
|
||||
assertThat(BufferCopies.keepsCopy(HEAP, 128 << 20)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void smallVertexBuffersKeepTheirs() {
|
||||
// Per-instance rows the render pass reads.
|
||||
assertThat(BufferCopies.keepsCopy(GpuBuffer.USAGE_VERTEX | GpuBuffer.USAGE_COPY_DST, 8192))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void buffersTheCpuReadsKeepTheirs() {
|
||||
int large = 32 << 20;
|
||||
assertThat(BufferCopies.keepsCopy(HEAP | GpuBuffer.USAGE_MAP_WRITE, large))
|
||||
.isTrue();
|
||||
assertThat(BufferCopies.keepsCopy(HEAP | GpuBuffer.USAGE_MAP_READ, large))
|
||||
.isTrue();
|
||||
// The index heaps: translucent sections' indices are rebased from the copy.
|
||||
assertThat(BufferCopies.keepsCopy(
|
||||
GpuBuffer.USAGE_INDEX | GpuBuffer.USAGE_COPY_DST | GpuBuffer.USAGE_COPY_SRC, large))
|
||||
.isTrue();
|
||||
assertThat(BufferCopies.keepsCopy(GpuBuffer.USAGE_UNIFORM, large)).isTrue();
|
||||
assertThat(BufferCopies.keepsCopy(GpuBuffer.USAGE_COPY_SRC | GpuBuffer.USAGE_MAP_WRITE, large))
|
||||
.isTrue();
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CompactTerrainRewriteTest {
|
||||
|
||||
// The inputs as SPIRV-Cross declares them in the terrain vertex shader.
|
||||
private static final String TERRAIN = """
|
||||
#version 300 es
|
||||
layout(location = 0) in vec3 Position;
|
||||
out float incari_io_0;
|
||||
layout(location = 1) in vec4 Color;
|
||||
layout(location = 3) in ivec2 UV2;
|
||||
out vec2 incari_io_3;
|
||||
layout(location = 2) in vec2 UV0;
|
||||
|
||||
void main()
|
||||
{
|
||||
vec3 pos = Position;
|
||||
ivec2 param_2 = UV2;
|
||||
incari_io_3 = UV0;
|
||||
}
|
||||
""";
|
||||
|
||||
private static TranslatedStage stage(String glsl) {
|
||||
return new TranslatedStage(
|
||||
"vertex minecraft:core/terrain ",
|
||||
"0",
|
||||
glsl,
|
||||
List.of(
|
||||
new TranslatedStage.Attribute("Position", 0, false),
|
||||
new TranslatedStage.Attribute("Color", 1, false),
|
||||
new TranslatedStage.Attribute("UV2", 3, true),
|
||||
new TranslatedStage.Attribute("UV0", 2, false)),
|
||||
List.of("Globals"),
|
||||
List.of("Sampler2"),
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theGamesInputsDecodeTheCompactVertex() {
|
||||
TranslatedStage rewritten = CompactTerrainRewrite.rewrite(stage(TERRAIN));
|
||||
|
||||
assertThat(rewritten.glsl())
|
||||
.contains("layout(location = 0) in uvec4 IncariPositionLight;")
|
||||
.contains("#define Position (vec3(IncariPositionLight.xyz) * (1.0 / 2048.0) - vec3(8.0))")
|
||||
.contains("layout(location = 2) in uvec2 IncariUv;")
|
||||
.contains("#define UV0 (vec2(IncariUv) * (1.0 / 32768.0))")
|
||||
.contains("#define UV2 ivec2(int(IncariPositionLight.w & 255u), int(IncariPositionLight.w >> 8u))")
|
||||
.contains("layout(location = 1) in vec4 Color;")
|
||||
.doesNotContain("in vec3 Position;")
|
||||
.doesNotContain("in ivec2 UV2;")
|
||||
// The body reads the same names as before.
|
||||
.contains("vec3 pos = Position;");
|
||||
assertThat(rewritten.attributes())
|
||||
.containsExactly(
|
||||
new TranslatedStage.Attribute("IncariPositionLight", 0, true),
|
||||
new TranslatedStage.Attribute("Color", 1, false),
|
||||
new TranslatedStage.Attribute("IncariUv", 2, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShaderWithoutTheTerrainInputsIsRefused() {
|
||||
assertThatThrownBy(() -> CompactTerrainRewrite.rewrite(stage("#version 300 es\nvoid main() {}\n")))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DrawIdRewriteTest {
|
||||
|
||||
// The shape SPIRV-Cross gives the multi-draw terrain vertex shader.
|
||||
private static final String TERRAIN = """
|
||||
#version 300 es
|
||||
|
||||
layout(std140) uniform Projection
|
||||
{
|
||||
mat4 ProjMat;
|
||||
} incari_ubo_Projection;
|
||||
|
||||
layout(location = 0) in vec3 Position;
|
||||
layout(location = 4) in ivec3 ChunkPosition;
|
||||
out float incari_io_0;
|
||||
layout(location = 5) in float ChunkVisibility;
|
||||
|
||||
void main()
|
||||
{
|
||||
vec3 pos = Position + vec3(ChunkPosition);
|
||||
incari_io_0 = ChunkVisibility;
|
||||
}
|
||||
""";
|
||||
|
||||
@Test
|
||||
void instanceInputsReadTheSubDrawsRow() {
|
||||
String rewritten = DrawIdRewrite.rewrite(
|
||||
TERRAIN,
|
||||
List.of(
|
||||
new DrawIdRewrite.Input("ChunkPosition", 0, DrawIdRewrite.Kind.INT),
|
||||
new DrawIdRewrite.Input("ChunkVisibility", 3, DrawIdRewrite.Kind.FLOAT)));
|
||||
|
||||
assertThat(rewritten)
|
||||
.startsWith("""
|
||||
#version 300 es
|
||||
#extension GL_ANGLE_multi_draw : require
|
||||
layout(std140) uniform IncariDrawRows
|
||||
{
|
||||
highp ivec4 incari_draw_rows[1024];
|
||||
};
|
||||
""")
|
||||
.contains("#define ChunkPosition (ivec3(incari_draw_rows[gl_DrawID].xyz))")
|
||||
.contains("#define ChunkVisibility (float(intBitsToFloat(incari_draw_rows[gl_DrawID].w)))")
|
||||
.contains("layout(location = 0) in vec3 Position;")
|
||||
.doesNotContain("in ivec3 ChunkPosition")
|
||||
.doesNotContain("in float ChunkVisibility");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsignedInputsConvert() {
|
||||
String glsl = "#version 300 es\nlayout(location = 2) in highp uvec2 Pair;\nvoid main() {}\n";
|
||||
|
||||
String rewritten =
|
||||
DrawIdRewrite.rewrite(glsl, List.of(new DrawIdRewrite.Input("Pair", 1, DrawIdRewrite.Kind.UINT)));
|
||||
|
||||
assertThat(rewritten).contains("#define Pair (uvec2(uvec2(incari_draw_rows[gl_DrawID].yz)))");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesWhatDoesntFitOrIsntThere() {
|
||||
assertThatThrownBy(() -> DrawIdRewrite.rewrite(
|
||||
TERRAIN, List.of(new DrawIdRewrite.Input("ChunkPosition", 2, DrawIdRewrite.Kind.INT))))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> DrawIdRewrite.rewrite(
|
||||
TERRAIN, List.of(new DrawIdRewrite.Input("Missing", 0, DrawIdRewrite.Kind.INT))))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class EntityInstanceRewriteTest {
|
||||
|
||||
// The inputs as SPIRV-Cross declares them in the entity vertex shader, Normal after Position.
|
||||
private static final String ENTITY = """
|
||||
#version 300 es
|
||||
|
||||
layout(std140) uniform DynamicTransforms
|
||||
{
|
||||
mat4 ModelViewMat;
|
||||
} incari_ubo_DynamicTransforms;
|
||||
|
||||
layout(location = 0) in vec3 Position;
|
||||
out float incari_io_0;
|
||||
layout(location = 5) in vec3 Normal;
|
||||
layout(location = 1) in vec4 Color;
|
||||
layout(location = 4) in ivec2 UV2;
|
||||
layout(location = 2) in vec2 UV0;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = incari_ubo_DynamicTransforms.ModelViewMat * vec4(Position, 1.0);
|
||||
vec3 param_4 = Normal;
|
||||
}
|
||||
""";
|
||||
|
||||
private static TranslatedStage stage(String glsl, boolean normal) {
|
||||
List<TranslatedStage.Attribute> attributes = normal
|
||||
? List.of(
|
||||
new TranslatedStage.Attribute("Position", 0, false),
|
||||
new TranslatedStage.Attribute("Normal", 5, false),
|
||||
new TranslatedStage.Attribute("Color", 1, false),
|
||||
new TranslatedStage.Attribute("UV2", 4, true),
|
||||
new TranslatedStage.Attribute("UV0", 2, false))
|
||||
: List.of(
|
||||
new TranslatedStage.Attribute("Position", 0, false),
|
||||
new TranslatedStage.Attribute("Color", 1, false));
|
||||
return new TranslatedStage(
|
||||
"vertex minecraft:core/entity ",
|
||||
"0",
|
||||
glsl,
|
||||
attributes,
|
||||
List.of("DynamicTransforms"),
|
||||
List.of("Sampler2"),
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void positionAndNormalComeFromThePartsRows() {
|
||||
TranslatedStage rewritten = EntityInstanceRewrite.rewrite(stage(ENTITY, true));
|
||||
|
||||
assertThat(rewritten.glsl())
|
||||
.startsWith("""
|
||||
#version 300 es
|
||||
layout(location = 6) in uint IncariPart;
|
||||
layout(location = 7) in uint IncariFirstRow;
|
||||
""")
|
||||
.contains("uniform IncariParts")
|
||||
.contains("layout(location = 0) in vec3 IncariLocalPosition;")
|
||||
.contains("#define Position incari_part_position()")
|
||||
.contains("layout(location = 5) in vec3 IncariLocalNormal;")
|
||||
.contains("#define Normal incari_part_normal()")
|
||||
.doesNotContain("in vec3 Position;")
|
||||
.doesNotContain("in vec3 Normal;")
|
||||
// The rest of the shader reads what it read before.
|
||||
.contains("vec4(Position, 1.0)")
|
||||
.contains("vec3 param_4 = Normal;");
|
||||
assertThat(rewritten.attributes())
|
||||
.extracting(TranslatedStage.Attribute::name)
|
||||
.containsExactly(
|
||||
"IncariLocalPosition",
|
||||
"IncariLocalNormal",
|
||||
"Color",
|
||||
"UV2",
|
||||
"UV0",
|
||||
"IncariPart",
|
||||
"IncariFirstRow");
|
||||
assertThat(rewritten.attributes())
|
||||
.filteredOn(attribute -> attribute.name().startsWith("IncariPart")
|
||||
|| attribute.name().equals("IncariFirstRow"))
|
||||
.allMatch(TranslatedStage.Attribute::integer);
|
||||
assertThat(rewritten.uniformBlocks()).containsExactly("DynamicTransforms", "IncariParts");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShaderWithoutNormalsOnlyPlacesPositions() {
|
||||
String glsl = """
|
||||
#version 300 es
|
||||
layout(location = 0) in vec3 Position;
|
||||
layout(location = 1) in vec4 Color;
|
||||
void main() { gl_Position = vec4(Position, 1.0); }
|
||||
""";
|
||||
TranslatedStage rewritten = EntityInstanceRewrite.rewrite(stage(glsl, false));
|
||||
|
||||
assertThat(rewritten.glsl()).contains("in uint IncariPart;").doesNotContain("incari_part_normal");
|
||||
assertThat(rewritten.attributes())
|
||||
.extracting(TranslatedStage.Attribute::location)
|
||||
.containsExactly(0, 1, 2, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShaderWithoutPositionIsRefused() {
|
||||
String glsl = "#version 300 es\nlayout(location = 1) in vec4 Color;\nvoid main() {}\n";
|
||||
TranslatedStage stage = new TranslatedStage(
|
||||
"vertex minecraft:core/other ",
|
||||
"0",
|
||||
glsl,
|
||||
List.of(new TranslatedStage.Attribute("Color", 1, false)),
|
||||
List.of(),
|
||||
List.of(),
|
||||
null);
|
||||
|
||||
assertThatThrownBy(() -> EntityInstanceRewrite.rewrite(stage)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import com.mojang.renderpearl.api.pipeline.CompareOp;
|
||||
import com.mojang.renderpearl.api.pipeline.PrimitiveTopology;
|
||||
import java.util.EnumSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class GlFormatsTest {
|
||||
|
||||
// WebGL2 enum values, from the WebGL 2.0 specification.
|
||||
private static final int RGBA8 = 0x8058;
|
||||
private static final int RGBA = 0x1908;
|
||||
private static final int UNSIGNED_BYTE = 0x1401;
|
||||
private static final int DEPTH_COMPONENT32F = 0x8CAC;
|
||||
private static final int DEPTH_ATTACHMENT = 0x8D00;
|
||||
private static final int DEPTH_STENCIL_ATTACHMENT = 0x821A;
|
||||
private static final int COLOR_ATTACHMENT0 = 0x8CE0;
|
||||
private static final int TRIANGLES = 0x0004;
|
||||
private static final int LINES = 0x0001;
|
||||
private static final int GEQUAL = 0x0206;
|
||||
private static final int FLOAT = 0x1406;
|
||||
|
||||
@Test
|
||||
void theGamesCommonTargetsExist() {
|
||||
assertThat(GlFormats.texture(GpuFormat.RGBA8_UNORM))
|
||||
.isEqualTo(new GlFormats.TextureFormat(RGBA8, RGBA, UNSIGNED_BYTE));
|
||||
assertThat(GlFormats.texture(GpuFormat.D32_FLOAT))
|
||||
.extracting(GlFormats.TextureFormat::internalFormat)
|
||||
.isEqualTo(DEPTH_COMPONENT32F);
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutFloatBlendingTargetsAreHalfFloats() {
|
||||
int rgba32f = 0x8814;
|
||||
int rgba16f = 0x881A;
|
||||
GlFormats.TextureFormat full = GlFormats.texture(GpuFormat.RGBA32_FLOAT);
|
||||
assertThat(full).isNotNull();
|
||||
assertThat(GlFormats.withoutFloatBlending(full))
|
||||
.isEqualTo(new GlFormats.TextureFormat(rgba16f, RGBA, FLOAT))
|
||||
.isNotEqualTo(full);
|
||||
assertThat(full.internalFormat()).isEqualTo(rgba32f);
|
||||
GlFormats.TextureFormat bytes = GlFormats.texture(GpuFormat.RGBA8_UNORM);
|
||||
assertThat(bytes).isNotNull();
|
||||
assertThat(GlFormats.withoutFloatBlending(bytes)).isSameAs(bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyExtensionFormatsAreMissing() {
|
||||
EnumSet<GpuFormat> missing = EnumSet.noneOf(GpuFormat.class);
|
||||
for (GpuFormat format : GpuFormat.values()) {
|
||||
if (GlFormats.texture(format) == null) {
|
||||
missing.add(format);
|
||||
}
|
||||
}
|
||||
// 16-bit normalized formats need EXT_texture_norm16; WebGL has no stencil-only textures.
|
||||
assertThat(missing)
|
||||
.containsExactlyInAnyOrder(
|
||||
GpuFormat.R16_UNORM,
|
||||
GpuFormat.R16_SNORM,
|
||||
GpuFormat.RG16_UNORM,
|
||||
GpuFormat.RG16_SNORM,
|
||||
GpuFormat.RGB16_UNORM,
|
||||
GpuFormat.RGB16_SNORM,
|
||||
GpuFormat.RGBA16_UNORM,
|
||||
GpuFormat.RGBA16_SNORM,
|
||||
GpuFormat.S8_UINT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachmentFollowsTheAspects() {
|
||||
assertThat(GlFormats.attachment(GpuFormat.RGBA8_UNORM)).isEqualTo(COLOR_ATTACHMENT0);
|
||||
assertThat(GlFormats.attachment(GpuFormat.D32_FLOAT)).isEqualTo(DEPTH_ATTACHMENT);
|
||||
assertThat(GlFormats.attachment(GpuFormat.D24_UNORM_S8_UINT)).isEqualTo(DEPTH_STENCIL_ATTACHMENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributesKeepTheirNormalization() {
|
||||
assertThat(GlFormats.attribute(GpuFormat.RGBA8_UNORM))
|
||||
.isEqualTo(new GlFormats.AttributeFormat(4, UNSIGNED_BYTE, true));
|
||||
assertThat(GlFormats.attribute(GpuFormat.RGB32_FLOAT))
|
||||
.isEqualTo(new GlFormats.AttributeFormat(3, FLOAT, false));
|
||||
assertThat(GlFormats.attribute(GpuFormat.RG16_SINT).normalized()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void linesAndQuadsDrawAsTriangles() {
|
||||
// The game widens lines into quads in its shaders, and splits quads with an index buffer.
|
||||
assertThat(GlFormats.drawMode(PrimitiveTopology.LINES)).isEqualTo(TRIANGLES);
|
||||
assertThat(GlFormats.drawMode(PrimitiveTopology.QUADS)).isEqualTo(TRIANGLES);
|
||||
assertThat(GlFormats.drawMode(PrimitiveTopology.DEBUG_LINES)).isEqualTo(LINES);
|
||||
}
|
||||
|
||||
@Test
|
||||
void depthComparesAsTheGameWritesThem() {
|
||||
assertThat(GlFormats.compareOp(CompareOp.GREATER_THAN_OR_EQUAL)).isEqualTo(GEQUAL);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ParticleInstanceRewriteTest {
|
||||
|
||||
// The inputs as SPIRV-Cross declares them in the particle vertex shader.
|
||||
private static final String PARTICLE = """
|
||||
#version 300 es
|
||||
|
||||
layout(location = 0) in vec3 Position;
|
||||
out float incari_io_0;
|
||||
layout(location = 1) in vec2 UV0;
|
||||
out vec4 incari_io_3;
|
||||
layout(location = 2) in vec4 Color;
|
||||
layout(location = 3) in ivec2 UV2;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = vec4(Position, 1.0);
|
||||
incari_io_0 = UV0.x;
|
||||
incari_io_3 = Color * float(UV2.x);
|
||||
}
|
||||
""";
|
||||
|
||||
private static TranslatedStage stage(String glsl) {
|
||||
return new TranslatedStage(
|
||||
"vertex minecraft:core/particle ",
|
||||
"0",
|
||||
glsl,
|
||||
List.of(
|
||||
new TranslatedStage.Attribute("Position", 0, false),
|
||||
new TranslatedStage.Attribute("UV0", 1, false),
|
||||
new TranslatedStage.Attribute("Color", 2, false),
|
||||
new TranslatedStage.Attribute("UV2", 3, true)),
|
||||
List.of(),
|
||||
List.of("Sampler2"),
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theQuadIsWorkedOutFromTheInstance() {
|
||||
TranslatedStage rewritten = ParticleInstanceRewrite.rewrite(stage(PARTICLE));
|
||||
|
||||
assertThat(rewritten.glsl())
|
||||
.contains("layout(location = 0) in vec3 IncariCenter;")
|
||||
.contains("layout(location = 4) in vec4 IncariRotation;")
|
||||
.contains("layout(location = 5) in float IncariScale;")
|
||||
.contains("layout(location = 6) in vec4 IncariUvs;")
|
||||
.contains("layout(location = 2) in vec4 IncariColor;")
|
||||
.contains("#define Position incari_particle_position()")
|
||||
.contains("#define UV0 incari_particle_uv()")
|
||||
.contains("#define Color (IncariColor.zyxw)")
|
||||
.contains("gl_VertexID & 3")
|
||||
.doesNotContain("in vec3 Position;")
|
||||
.doesNotContain("in vec2 UV0;")
|
||||
.contains("layout(location = 3) in ivec2 UV2;");
|
||||
assertThat(rewritten.attributes())
|
||||
.containsExactly(
|
||||
new TranslatedStage.Attribute("IncariCenter", 0, false),
|
||||
new TranslatedStage.Attribute("IncariColor", 2, false),
|
||||
new TranslatedStage.Attribute("UV2", 3, true),
|
||||
new TranslatedStage.Attribute("IncariRotation", 4, false),
|
||||
new TranslatedStage.Attribute("IncariScale", 5, false),
|
||||
new TranslatedStage.Attribute("IncariUvs", 6, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherShaderIsRefused() {
|
||||
String noUv = PARTICLE.replace("layout(location = 1) in vec2 UV0;\n", "");
|
||||
assertThatThrownBy(() -> ParticleInstanceRewrite.rewrite(stage(noUv)))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("UV0");
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import incari.platform.api.Platform;
|
||||
import incari.platform.api.Platforms;
|
||||
import incari.platform.api.threads.PlatformThreads;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* Enough of a platform for game classes to load in tests: building a {@code VertexFormat} runs
|
||||
* {@code Mth}'s static initializer, which reaches {@code Util}'s, which asks the platform how many
|
||||
* background threads to make. Anything else the game asks for fails the test loudly.
|
||||
*/
|
||||
final class TestPlatform {
|
||||
|
||||
private TestPlatform() {}
|
||||
|
||||
static void install() {
|
||||
if (Platforms.isInstalled()) {
|
||||
return;
|
||||
}
|
||||
PlatformThreads inline = suggested -> 0;
|
||||
Platforms.install((Platform) Proxy.newProxyInstance(
|
||||
Platform.class.getClassLoader(),
|
||||
new Class<?>[] {Platform.class},
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "threads" -> inline;
|
||||
case "description" -> "render-webgl2 tests";
|
||||
case "nanoTime" -> System.nanoTime();
|
||||
case "toString" -> "TestPlatform";
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
}));
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package incari.render.webgl2;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.mojang.renderpearl.api.GpuFormat;
|
||||
import com.mojang.renderpearl.api.vertex.VertexFormat;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class VertexLayoutTest {
|
||||
|
||||
private static final VertexFormat POSITION_COLOR;
|
||||
|
||||
static {
|
||||
TestPlatform.install();
|
||||
POSITION_COLOR = VertexFormat.builder(0)
|
||||
.addAttribute("Position", GpuFormat.RGB32_FLOAT)
|
||||
.addAttribute("Color", GpuFormat.RGBA8_UNORM)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMatrixFillsConsecutiveLocations() throws Exception {
|
||||
VertexFormat instance = VertexFormat.builder(1)
|
||||
.addAttribute("Transform", GpuFormat.RGBA32_FLOAT, 4)
|
||||
.build();
|
||||
|
||||
List<VertexLayout.Binding> bindings = VertexLayout.of(List.of(instance), List.of(attribute("Transform", 4)));
|
||||
|
||||
assertThat(bindings).extracting(VertexLayout.Binding::location).containsExactly(4, 5, 6, 7);
|
||||
assertThat(bindings).extracting(VertexLayout.Binding::offset).containsExactly(0, 16, 32, 48);
|
||||
assertThat(bindings).extracting(VertexLayout.Binding::divisor).containsOnly(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inputsMatchElementsByName() throws Exception {
|
||||
List<VertexLayout.Binding> bindings = VertexLayout.of(
|
||||
Arrays.asList(POSITION_COLOR, null), List.of(attribute("Color", 1), attribute("Position", 0)));
|
||||
|
||||
assertThat(bindings)
|
||||
.containsExactly(
|
||||
new VertexLayout.Binding(0, 0, 0, 16, 0, GlFormats.attribute(GpuFormat.RGB32_FLOAT), false),
|
||||
new VertexLayout.Binding(0, 1, 12, 16, 0, GlFormats.attribute(GpuFormat.RGBA8_UNORM), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void elementsTheShaderDoesntReadAreSkipped() throws Exception {
|
||||
assertThat(VertexLayout.of(List.of(POSITION_COLOR), List.of(attribute("Position", 0))))
|
||||
.extracting(VertexLayout.Binding::location)
|
||||
.containsExactly(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInputWithoutAnElementIsAnError() {
|
||||
assertThatThrownBy(() -> VertexLayout.of(List.of(POSITION_COLOR), List.of(attribute("UV0", 2))))
|
||||
.isInstanceOf(VertexLayout.MismatchException.class)
|
||||
.hasMessageContaining("UV0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void terrainsInstanceDataFitsARow() throws Exception {
|
||||
// The game's CHUNK_DATA_INSTANCED, read by its multi-draw terrain pipelines.
|
||||
VertexFormat chunkData = VertexFormat.builder(1)
|
||||
.addAttribute("ChunkPosition", GpuFormat.RGB32_SINT)
|
||||
.addAttribute("ChunkVisibility", GpuFormat.R32_FLOAT)
|
||||
.build();
|
||||
List<TranslatedStage.Attribute> inputs = List.of(
|
||||
attribute("Position", 0),
|
||||
new TranslatedStage.Attribute("ChunkPosition", 4, true),
|
||||
attribute("ChunkVisibility", 5));
|
||||
List<VertexLayout.Binding> bindings = VertexLayout.of(Arrays.asList(POSITION_COLOR, chunkData), inputs);
|
||||
|
||||
VertexLayout.DrawRowLayout rows = VertexLayout.drawRows(bindings, inputs);
|
||||
|
||||
assertThat(rows).isNotNull();
|
||||
assertThat(rows.slot()).isEqualTo(1);
|
||||
assertThat(rows.stride()).isEqualTo(16);
|
||||
assertThat(rows.inputs())
|
||||
.containsExactly(
|
||||
new DrawIdRewrite.Input("ChunkPosition", 0, DrawIdRewrite.Kind.INT),
|
||||
new DrawIdRewrite.Input("ChunkVisibility", 3, DrawIdRewrite.Kind.FLOAT));
|
||||
assertThat(rows.attributes()).extracting(VertexLayout.Binding::location).containsExactly(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noRowsWithoutInstanceDataOrWhenItDoesntFit() throws Exception {
|
||||
List<TranslatedStage.Attribute> position = List.of(attribute("Position", 0));
|
||||
assertThat(VertexLayout.drawRows(VertexLayout.of(List.of(POSITION_COLOR), position), position))
|
||||
.isNull();
|
||||
|
||||
VertexFormat matrix = VertexFormat.builder(1)
|
||||
.addAttribute("Transform", GpuFormat.RGBA32_FLOAT, 4)
|
||||
.build();
|
||||
List<TranslatedStage.Attribute> transform = List.of(attribute("Transform", 4));
|
||||
assertThat(VertexLayout.drawRows(VertexLayout.of(List.of(matrix), transform), transform))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
private static TranslatedStage.Attribute attribute(String name, int location) {
|
||||
return new TranslatedStage.Attribute(name, location, false);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package incari.render.webgl2.shaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ShaderManifestTest {
|
||||
|
||||
@Test
|
||||
void keysDontDependOnTheOrderDefinesWereAddedIn() {
|
||||
ShaderDefines one = new ShaderDefines(Map.of("B", "2", "A", "1"), Set.of("Y", "X"));
|
||||
ShaderDefines other = ShaderDefines.builder()
|
||||
.define("X")
|
||||
.define("A", "1")
|
||||
.define("Y")
|
||||
.define("B", "2")
|
||||
.build();
|
||||
Identifier id = Identifier.withDefaultNamespace("core/terrain");
|
||||
|
||||
ShaderStageKey key = ShaderStageKey.of(ShaderType.FRAGMENT, id, one);
|
||||
|
||||
assertThat(key).isEqualTo(ShaderStageKey.of(ShaderType.FRAGMENT, id, other));
|
||||
assertThat(key.asString()).isEqualTo("fragment minecraft:core/terrain A=1;B=2;X;Y");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFlagJoinsTheDefinesInCanonicalOrder() {
|
||||
Identifier id = Identifier.withDefaultNamespace("core/terrain");
|
||||
ShaderDefines defines = new ShaderDefines(Map.of("A", "1"), Set.of("X", "Z"));
|
||||
ShaderDefines withFlag = new ShaderDefines(Map.of("A", "1"), Set.of("X", "Z", "Y"));
|
||||
|
||||
assertThat(ShaderStageKey.of(ShaderType.VERTEX, id, defines).withFlag("Y"))
|
||||
.isEqualTo(ShaderStageKey.of(ShaderType.VERTEX, id, withFlag));
|
||||
assertThat(ShaderStageKey.of(ShaderType.VERTEX, id, ShaderDefines.EMPTY)
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString())
|
||||
.isEqualTo("vertex minecraft:core/terrain RENDERPEARL_DEPTH_IS_ZERO_TO_ONE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesDifferByTypeAndDefines() {
|
||||
Identifier id = Identifier.withDefaultNamespace("core/gui");
|
||||
assertThat(ShaderStageKey.of(ShaderType.VERTEX, id, ShaderDefines.EMPTY).asString())
|
||||
.isEqualTo("vertex minecraft:core/gui ")
|
||||
.isNotEqualTo(ShaderStageKey.of(ShaderType.FRAGMENT, id, ShaderDefines.EMPTY)
|
||||
.asString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sourceHashIsStableAndSensitive() {
|
||||
assertThat(SourceHash.of("")).isEqualTo("cbf29ce484222325");
|
||||
assertThat(SourceHash.of("void main() {}")).hasSize(16).isEqualTo(SourceHash.of("void main() {}"));
|
||||
assertThat(SourceHash.of("void main() {}")).isNotEqualTo(SourceHash.of("void main(){}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roundTripsThroughJson() {
|
||||
TranslatedStage vertex = new TranslatedStage(
|
||||
"vertex minecraft:core/gui ",
|
||||
SourceHash.of("source"),
|
||||
"#version 300 es\nvoid main() {}\n",
|
||||
List.of(
|
||||
new TranslatedStage.Attribute("Position", 0, false),
|
||||
new TranslatedStage.Attribute("Id", 3, true)),
|
||||
List.of("Projection", "DynamicTransforms"),
|
||||
List.of("Sampler0"),
|
||||
null);
|
||||
TranslatedStage clouds =
|
||||
TranslatedStage.unsupported("vertex minecraft:core/clouds ", "0123456789abcdef", "texel buffer");
|
||||
|
||||
ShaderManifest parsed = ShaderManifest.parse(new ShaderManifest("26.3", List.of(vertex, clouds)).toJson());
|
||||
|
||||
assertThat(parsed.minecraftVersion()).isEqualTo("26.3");
|
||||
assertThat(parsed.stages()).containsExactlyInAnyOrder(vertex, clouds);
|
||||
assertThat(parsed.stage(ShaderStageKey.of(
|
||||
ShaderType.VERTEX, Identifier.withDefaultNamespace("core/clouds"), ShaderDefines.EMPTY)))
|
||||
.isEqualTo(clouds)
|
||||
.satisfies(stage -> assertThat(stage.isSupported()).isFalse());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAnotherFormat() {
|
||||
assertThatThrownBy(() -> ShaderManifest.parse("{\"format\":0,\"minecraft\":\"26.3\",\"stages\":{}}"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("rebuild");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user