GlDevice .java

com.mojang.renderpearl.backend.opengl.GlDevice (class, 384 lines): members: USE_GL_ARB_shader_draw_parameters, USE_GL_ARB_vertex_attrib_binding, debugLog.

com.mojang.renderpearl.backend.openglclass384 linesclient13.8 KB

Implements

API Surface (19)

GlHeuristics heuristics()
GlDebugLabel debugLabels()
GpuSurfaceBackend createSurface(final long windowHandle, final BooleanSupplier isIconified)
CommandEncoderBackend createCommandEncoder()
GpuSampler createSampler(final AddressMode addressModeU, final AddressMode addressModeV, final FilterMode minFilter, final FilterMode magFilter, final int maxAnisotropy, final OptionalDouble maxLod)
GpuTexture createTexture(@Nullable String label, final @GpuTexture.Usage int usage, final GpuFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels)
GpuTextureView createTextureView(final GpuTexture texture, final int baseMipLevel, final int mipLevels)
GpuBuffer createBuffer(final @Nullable Supplier<String> label, final @GpuBuffer.Usage int usage, final long size)
GpuBuffer createBuffer(final @Nullable Supplier<String> label, final @GpuBuffer.Usage int usage, final ByteBuffer data)
List<String> getLastDebugMessages()
boolean isDebuggingEnabled()
void close()
DirectStateAccess directStateAccess()
BackendRenderPipeline.Pending compilePipeline(final BackendRenderPipeline.CreateInfo createInfo)
BufferStorage getBufferStorage()
FrameBufferCache frameBufferCache()
GpuQueryPool createTimestampQueryPool(final int size)
long getTimestampCalibrationOffset()
DeviceInfo getDeviceInfo()

Fields & Constants (36)

LOGGER
USE_GL_ARB_vertex_attrib_binding
USE_GL_KHR_debug
USE_GL_EXT_debug_label
USE_GL_ARB_debug_output
USE_GL_ARB_direct_state_access
USE_GL_ARB_buffer_storage
USE_GL_ARB_base_instance
USE_GL_ARB_draw_indirect
USE_GL_ARB_multi_draw_indirect
USE_GL_ARB_shader_draw_parameters
initialWindowHandle
glContext
heuristics
encoder
debugLog
debugLabels
directStateAccess
frameBufferCache
vertexArraySource
bufferStorage
deviceInfo
recompiler
shaderCompilerRequiresSacrifice
currentWindow

…and 11 more (see full source).

String literals (15)

"Failed to create window for OpenGL context: "
"<no error>"
"Failed to create OpenGL context: "
"Failed to create OpenGL 3.3 context, got OpenGL "
"GL_EXT_texture_filter_anisotropic"
"GL_ARB_clip_control"
"GL_ARB_shader_draw_parameters"
"GL_ARB_draw_indirect"
"GL_ARB_multi_draw_indirect"
"GL_ARB_base_instance"
"Could not allocate texture of "
" for "
"OpenGL error "
" format cannot be used to create textures"
"Could not allocate buffer of "

Full Source

GlDevice.java384 lines · Minecraft 26.3 · verbatim
1
package com.mojang.renderpearl.backend.opengl;
2
3
import com.mojang.logging.LogUtils;
4
import com.mojang.renderpearl.api.GpuFormat;
5
import com.mojang.renderpearl.api.buffers.GpuBuffer;
6
import com.mojang.renderpearl.api.commands.GpuQueryPool;
7
import com.mojang.renderpearl.api.device.BackendCreationException;
8
import com.mojang.renderpearl.api.device.DeviceInfo;
9
import com.mojang.renderpearl.api.device.GpuDebugOptions;
10
import com.mojang.renderpearl.api.device.GpuOutOfMemoryException;
11
import com.mojang.renderpearl.api.textures.AddressMode;
12
import com.mojang.renderpearl.api.textures.FilterMode;
13
import com.mojang.renderpearl.api.textures.GpuSampler;
14
import com.mojang.renderpearl.api.textures.GpuTexture;
15
import com.mojang.renderpearl.api.textures.GpuTextureView;
16
import com.mojang.renderpearl.backend.api.BackendRenderPipeline;
17
import com.mojang.renderpearl.backend.api.CommandEncoderBackend;
18
import com.mojang.renderpearl.backend.api.GpuDeviceBackend;
19
import com.mojang.renderpearl.backend.api.GpuSurfaceBackend;
20
import com.mojang.renderpearl.backend.api.BackendRenderPipeline.CreateInfo.Shader;
21
import java.nio.ByteBuffer;
22
import java.nio.IntBuffer;
23
import java.util.Collections;
24
import java.util.HashSet;
25
import java.util.List;
26
import java.util.Map;
27
import java.util.Objects;
28
import java.util.OptionalDouble;
29
import java.util.Set;
30
import java.util.function.BiFunction;
31
import java.util.function.BooleanSupplier;
32
import java.util.function.Supplier;
33
import net.fabricmc.api.EnvType;
34
import net.fabricmc.api.Environment;
35
import net.minecraft.util.Mth;
36
import org.jspecify.annotations.Nullable;
37
import org.lwjgl.opengl.ARBClipControl;
38
import org.lwjgl.opengl.GL;
39
import org.lwjgl.opengl.GL33C;
40
import org.lwjgl.opengl.GLCapabilities;
41
import org.lwjgl.sdl.SDLError;
42
import org.lwjgl.sdl.SDLVideo;
43
import org.lwjgl.system.MemoryStack;
44
import org.slf4j.Logger;
45
46
@Environment(EnvType.CLIENT)
47
class GlDevice implements GpuDeviceBackend {
48
	private static final Logger LOGGER = LogUtils.getLogger();
49
	protected static boolean USE_GL_ARB_vertex_attrib_binding = true;
50
	protected static boolean USE_GL_KHR_debug = true;
51
	protected static boolean USE_GL_EXT_debug_label = true;
52
	protected static boolean USE_GL_ARB_debug_output = true;
53
	protected static boolean USE_GL_ARB_direct_state_access = true;
54
	protected static boolean USE_GL_ARB_buffer_storage = true;
55
	protected static boolean USE_GL_ARB_base_instance = true;
56
	protected static boolean USE_GL_ARB_draw_indirect = true;
57
	protected static boolean USE_GL_ARB_multi_draw_indirect = true;
58
	protected static boolean USE_GL_ARB_shader_draw_parameters = true;
59
	private final long initialWindowHandle;
60
	private final long glContext;
61
	private final GlHeuristics heuristics;
62
	private final GlCommandEncoder encoder;
63
	private final @Nullable GlDebug debugLog;
64
	private final GlDebugLabel debugLabels;
65
	private final DirectStateAccess directStateAccess;
66
	private final FrameBufferCache frameBufferCache = new FrameBufferCache();
67
	private final BiFunction<GlProgram, BackendRenderPipeline.CreateInfo, VertexArray> vertexArraySource;
68
	private final BufferStorage bufferStorage;
69
	private final DeviceInfo deviceInfo;
70
	private final GlPipelineRecompiler recompiler;
71
	private boolean shaderCompilerRequiresSacrifice = true;
72
	private long currentWindow = 0L;
73
74
	public GlDevice(final GlBackend backend, final GpuDebugOptions debugOptions) throws BackendCreationException {
75
		this.initialWindowHandle = backend.createWindow("Minecraft - RenderPearl OpenGL Hidden Utility Window", 320, 480, 2147614728L);
76
		if (this.initialWindowHandle == 0L) {
77
			throw new BackendCreationException(
78
				"Failed to create window for OpenGL context: " + Objects.requireNonNullElse(SDLError.SDL_GetError(), "<no error>"),
79
				BackendCreationException.Reason.OPENGL_MISSING
80
			);
81
		}
82
83
		long glContext = SDLVideo.SDL_GL_CreateContext(this.initialWindowHandle);
84
		if (glContext == 0L) {
85
			SDLVideo.SDL_DestroyWindow(this.initialWindowHandle);
86
			throw new BackendCreationException(
87
				"Failed to create OpenGL context: " + Objects.requireNonNullElse(SDLError.SDL_GetError(), "<no error>"), BackendCreationException.Reason.OPENGL_MISSING
88
			);
89
		}
90
91
		this.glContext = glContext;
92
		this.makeCurrent(this.initialWindowHandle);
93
94
		try (MemoryStack stack = MemoryStack.stackPush()) {
95
			IntBuffer majorVersion = stack.callocInt(1);
96
			IntBuffer minorVersion = stack.callocInt(1);
97
			SDLVideo.SDL_GL_GetAttribute(17, majorVersion);
98
			SDLVideo.SDL_GL_GetAttribute(18, minorVersion);
99
			if (majorVersion.get(0) < 3 || majorVersion.get(0) == 3 && minorVersion.get(0) < 3) {
100
				throw new BackendCreationException(
101
					"Failed to create OpenGL 3.3 context, got OpenGL " + majorVersion.get(0) + "." + minorVersion.get(0), BackendCreationException.Reason.OPENGL_MISSING
102
				);
103
			}
104
105
			long secondWindow = backend.createWindow("Minecraft - RenderPearl OpenGL Hidden Test Window", 320, 480, 2147614728L);
106
			if (secondWindow == 0L) {
107
				throw new BackendCreationException(
108
					"Failed to create window for OpenGL after creating context: " + Objects.requireNonNullElse(SDLError.SDL_GetError(), "<no error>"),
109
					BackendCreationException.Reason.OPENGL_MISSING
110
				);
111
			}
112
113
			SDLVideo.SDL_DestroyWindow(secondWindow);
114
			GLCapabilities capabilities = GL.createCapabilities();
115
			Set<String> enabledExtensions = new HashSet<>();
116
			int maxSupportedAnisotropy;
117
			if (capabilities.GL_EXT_texture_filter_anisotropic) {
118
				maxSupportedAnisotropy = Mth.floor(GL33C.glGetFloat(34047));
119
				enabledExtensions.add("GL_EXT_texture_filter_anisotropic");
120
			} else {
121
				maxSupportedAnisotropy = 1;
122
			}
123
124
			this.heuristics = new GlHeuristics(GlStateManager._getString(7937), GlStateManager._getString(7936));
125
			this.debugLog = GlDebug.enableDebugCallback(debugOptions.logLevel(), debugOptions.synchronousLogs(), enabledExtensions);
126
			this.debugLabels = GlDebugLabel.create(capabilities, debugOptions.useLabels(), enabledExtensions);
127
			this.bufferStorage = BufferStorage.create(capabilities, enabledExtensions, this.heuristics.couldBeIntelGen7() || this.heuristics.isNvidia());
128
			this.directStateAccess = DirectStateAccess.create(capabilities, enabledExtensions, this.heuristics);
129
			this.vertexArraySource = VertexArray.createSource(capabilities, enabledExtensions);
130
			GL33C.glEnable(34895);
131
			GL33C.glEnable(34370);
132
			if (capabilities.GL_ARB_clip_control) {
133
				ARBClipControl.glClipControl(36001, 37727);
134
				enabledExtensions.add("GL_ARB_clip_control");
135
			}
136
137
			if (capabilities.GL_ARB_shader_draw_parameters && USE_GL_ARB_shader_draw_parameters) {
138
				enabledExtensions.add("GL_ARB_shader_draw_parameters");
139
			}
140
141
			if (capabilities.GL_ARB_draw_indirect && USE_GL_ARB_draw_indirect) {
142
				enabledExtensions.add("GL_ARB_draw_indirect");
143
				if (capabilities.GL_ARB_multi_draw_indirect && USE_GL_ARB_multi_draw_indirect) {
144
					enabledExtensions.add("GL_ARB_multi_draw_indirect");
145
				}
146
			}
147
148
			if (capabilities.GL_ARB_base_instance && USE_GL_ARB_base_instance) {
149
				enabledExtensions.add("GL_ARB_base_instance");
150
			}
151
152
			this.deviceInfo = this.heuristics.createDeviceInfo(capabilities, maxSupportedAnisotropy, enabledExtensions);
153
			this.encoder = new GlCommandEncoder(this);
154
			this.recompiler = new GlPipelineRecompiler(this.debugLabels, this.deviceInfo.features().shaderDrawParameters());
155
		} catch (Throwable throwable) {
156
			SDLVideo.SDL_GL_DestroyContext(glContext);
157
			SDLVideo.SDL_DestroyWindow(this.initialWindowHandle);
158
			throw throwable;
159
		}
160
	}
161
162
	public GlHeuristics heuristics() {
163
		return this.heuristics;
164
	}
165
166
	public GlDebugLabel debugLabels() {
167
		return this.debugLabels;
168
	}
169
170
	@Override
171
	public GpuSurfaceBackend createSurface(final long windowHandle, final BooleanSupplier isIconified) {
172
		return new GlSurface(this, windowHandle, isIconified);
173
	}
174
175
	@Override
176
	public CommandEncoderBackend createCommandEncoder() {
177
		return this.encoder;
178
	}
179
180
	@Override
181
	public GpuSampler createSampler(
182
		final AddressMode addressModeU,
183
		final AddressMode addressModeV,
184
		final FilterMode minFilter,
185
		final FilterMode magFilter,
186
		final int maxAnisotropy,
187
		final OptionalDouble maxLod
188
	) {
189
		return new GlSampler(addressModeU, addressModeV, minFilter, magFilter, maxAnisotropy, maxLod);
190
	}
191
192
	@Override
193
	public GpuTexture createTexture(
194
		@Nullable String label,
195
		final @GpuTexture.Usage int usage,
196
		final GpuFormat format,
197
		final int width,
198
		final int height,
199
		final int depthOrLayers,
200
		final int mipLevels
201
	) {
202
		GlStateManager.clearGlErrors();
203
		int id = GlStateManager._genTexture();
204
		if (label == null) {
205
			label = String.valueOf(id);
206
		}
207
208
		boolean isCubemap = (usage & 16) != 0;
209
		int target;
210
		if (isCubemap) {
211
			GL33C.glBindTexture(34067, id);
212
			target = 34067;
213
		} else {
214
			GlStateManager._bindTexture(id);
215
			target = 3553;
216
		}
217
218
		GlStateManager._texParameter(target, 33085, mipLevels - 1);
219
		GlStateManager._texParameter(target, 33082, 0);
220
		GlStateManager._texParameter(target, 33083, mipLevels - 1);
221
		if (format.hasDepthAspect()) {
222
			GlStateManager._texParameter(target, 34892, 0);
223
		}
224
225
		int glInternalID = GlConst.toGlInternalId(format);
226
		int glExternalID = GlConst.toGlExternalId(format);
227
		int glType = GlConst.toGlType(format);
228
		if (glInternalID != 0 && glExternalID != 0 && glType != 0) {
229
			if (isCubemap) {
230
				for (int cubeTarget : GlConst.CUBEMAP_TARGETS) {
231
					for (int i = 0; i < mipLevels; i++) {
232
						GlStateManager._texImage2D(cubeTarget, i, glInternalID, width >> i, height >> i, 0, glExternalID, glType, null);
233
					}
234
				}
235
			} else {
236
				for (int i = 0; i < mipLevels; i++) {
237
					GlStateManager._texImage2D(target, i, glInternalID, width >> i, height >> i, 0, glExternalID, glType, null);
238
				}
239
			}
240
241
			int error = GlStateManager._getError();
242
			if (error == 1285) {
243
				throw new GpuOutOfMemoryException("Could not allocate texture of " + width + "x" + height + " for " + label);
244
			}
245
246
			if (error != 0) {
247
				throw new IllegalStateException("OpenGL error " + error);
248
			}
249
250
			GlTexture texture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, id, this.frameBufferCache);
251
			this.debugLabels.applyLabel(texture);
252
			return texture;
253
		} else {
254
			throw new IllegalArgumentException(format + " format cannot be used to create textures");
255
		}
256
	}
257
258
	@Override
259
	public GpuTextureView createTextureView(final GpuTexture texture, final int baseMipLevel, final int mipLevels) {
260
		return new GlTextureView((GlTexture)texture, baseMipLevel, mipLevels, this.frameBufferCache);
261
	}
262
263
	@Override
264
	public GpuBuffer createBuffer(final @Nullable Supplier<String> label, final @GpuBuffer.Usage int usage, final long size) {
265
		GlStateManager.clearGlErrors();
266
		GlBuffer buffer = this.bufferStorage.createBuffer(this.heuristics, this.directStateAccess, usage, size);
267
		int error = GlStateManager._getError();
268
		if (error == 1285) {
269
			throw new GpuOutOfMemoryException("Could not allocate buffer of " + size + " for " + label);
270
		}
271
272
		if (error != 0) {
273
			throw new IllegalStateException("OpenGL error " + error);
274
		}
275
276
		this.debugLabels.applyLabel(buffer, label);
277
		return buffer;
278
	}
279
280
	@Override
281
	public GpuBuffer createBuffer(final @Nullable Supplier<String> label, final @GpuBuffer.Usage int usage, final ByteBuffer data) {
282
		GlStateManager.clearGlErrors();
283
		long size = data.remaining();
284
		GlBuffer buffer = this.bufferStorage.createBuffer(this.heuristics, this.directStateAccess, usage, data);
285
		int error = GlStateManager._getError();
286
		if (error == 1285) {
287
			throw new GpuOutOfMemoryException("Could not allocate buffer of " + size + " for " + label);
288
		}
289
290
		if (error != 0) {
291
			throw new IllegalStateException("OpenGL error " + error);
292
		}
293
294
		this.debugLabels.applyLabel(buffer, label);
295
		return buffer;
296
	}
297
298
	@Override
299
	public List<String> getLastDebugMessages() {
300
		return this.debugLog == null ? Collections.emptyList() : this.debugLog.getLastOpenGlDebugMessages();
301
	}
302
303
	@Override
304
	public boolean isDebuggingEnabled() {
305
		return this.debugLog != null;
306
	}
307
308
	private void sacrificeShaderToOpenGlAndAmd() {
309
		if (this.shaderCompilerRequiresSacrifice) {
310
			this.shaderCompilerRequiresSacrifice = false;
311
			String glRenderer = GlStateManager._getString(7937);
312
			if (glRenderer.contains("AMD")) {
313
				int shader = GlStateManager.glCreateShader(35633);
314
				int program = GlStateManager.glCreateProgram();
315
				GlStateManager.glAttachShader(program, shader);
316
				GlStateManager.glDeleteShader(shader);
317
				GlStateManager.glDeleteProgram(program);
318
			}
319
		}
320
	}
321
322
	void markAmdShaderCompilerAngry() {
323
		this.shaderCompilerRequiresSacrifice = true;
324
	}
325
326
	@Override
327
	public void close() {
328
		this.encoder.close();
329
		SDLVideo.SDL_GL_DestroyContext(this.glContext);
330
		SDLVideo.SDL_DestroyWindow(this.initialWindowHandle);
331
	}
332
333
	public DirectStateAccess directStateAccess() {
334
		return this.directStateAccess;
335
	}
336
337
	@Override
338
	public BackendRenderPipeline.Pending compilePipeline(final BackendRenderPipeline.CreateInfo createInfo) {
339
		Map<Shader, String> decompiledShaders = this.recompiler.decompileShaders(createInfo);
340
		return decompiledShaders == null ? BackendRenderPipeline.Pending.NULL : () -> {
341
			this.sacrificeShaderToOpenGlAndAmd();
342
			GlProgram glProgram = this.recompiler.compileProgram(createInfo, decompiledShaders);
343
			if (glProgram == null) {
344
				return null;
345
			}
346
347
			VertexArray vertexArray = this.vertexArraySource.apply(glProgram, createInfo);
348
			return new GlRenderPipeline(this, createInfo, glProgram, vertexArray);
349
		};
350
	}
351
352
	public BufferStorage getBufferStorage() {
353
		return this.bufferStorage;
354
	}
355
356
	public FrameBufferCache frameBufferCache() {
357
		return this.frameBufferCache;
358
	}
359
360
	@Override
361
	public GpuQueryPool createTimestampQueryPool(final int size) {
362
		return new GlQueryPool(size);
363
	}
364
365
	@Override
366
	public long getTimestampCalibrationOffset() {
367
		long deviceTime = GL33C.glGetInteger64(36392);
368
		long hostTime = System.nanoTime();
369
		return hostTime - deviceTime;
370
	}
371
372
	@Override
373
	public DeviceInfo getDeviceInfo() {
374
		return this.deviceInfo;
375
	}
376
377
	void makeCurrent(final long windowHandle) {
378
		if (windowHandle != this.currentWindow) {
379
			this.currentWindow = windowHandle;
380
			SDLVideo.SDL_GL_MakeCurrent(windowHandle, this.glContext);
381
		}
382
	}
383
}
384

Decompiled Minecraft 26.3 source of GlDevice (com/mojang/renderpearl/backend/opengl/GlDevice.java) with Mojang official mappings, stored verbatim on the site.