OpenTTD Source 15.0-beta2
opengl.cpp
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "../stdafx.h"
11
12/* Define to disable buffer syncing. Will increase max fast forward FPS but produces artifacts. Mainly useful for performance testing. */
13// #define NO_GL_BUFFER_SYNC
14/* Define to allow software rendering backends. */
15// #define GL_ALLOW_SOFTWARE_RENDERER
16
17#if defined(_WIN32)
18# include <windows.h>
19#endif
20
21#define GL_GLEXT_PROTOTYPES
22#if defined(__APPLE__)
23# define GL_SILENCE_DEPRECATION
24# include <OpenGL/gl3.h>
25#else
26# include <GL/gl.h>
27#endif
28#include "../3rdparty/opengl/glext.h"
29
30#include "opengl.h"
31#include "../core/geometry_func.hpp"
32#include "../core/math_func.hpp"
33#include "../gfx_func.h"
34#include "../debug.h"
35#include "../blitter/factory.hpp"
36#include "../zoom_func.h"
37
38#include "../table/opengl_shader.h"
39#include "../table/sprites.h"
40
41
42#include "../safeguards.h"
43
44
45/* Define function pointers of all OpenGL functions that we load dynamically. */
46
47#define GL(function) static decltype(&function) _ ## function
48
49GL(glGetString);
50GL(glGetIntegerv);
51GL(glGetError);
52GL(glDebugMessageControl);
53GL(glDebugMessageCallback);
54
55GL(glDisable);
56GL(glEnable);
57GL(glViewport);
58GL(glClear);
59GL(glClearColor);
60GL(glBlendFunc);
61GL(glDrawArrays);
62
63GL(glTexImage1D);
64GL(glTexImage2D);
65GL(glTexParameteri);
66GL(glTexSubImage1D);
67GL(glTexSubImage2D);
68GL(glBindTexture);
69GL(glDeleteTextures);
70GL(glGenTextures);
71GL(glPixelStorei);
72
73GL(glActiveTexture);
74
75GL(glGenBuffers);
76GL(glDeleteBuffers);
77GL(glBindBuffer);
78GL(glBufferData);
79GL(glBufferSubData);
80GL(glMapBuffer);
81GL(glUnmapBuffer);
82GL(glClearBufferSubData);
83
84GL(glBufferStorage);
85GL(glMapBufferRange);
86GL(glClientWaitSync);
87GL(glFenceSync);
88GL(glDeleteSync);
89
90GL(glGenVertexArrays);
91GL(glDeleteVertexArrays);
92GL(glBindVertexArray);
93
94GL(glCreateProgram);
95GL(glDeleteProgram);
96GL(glLinkProgram);
97GL(glUseProgram);
98GL(glGetProgramiv);
99GL(glGetProgramInfoLog);
100GL(glCreateShader);
101GL(glDeleteShader);
102GL(glShaderSource);
103GL(glCompileShader);
104GL(glAttachShader);
105GL(glGetShaderiv);
106GL(glGetShaderInfoLog);
107GL(glGetUniformLocation);
108GL(glUniform1i);
109GL(glUniform1f);
110GL(glUniform2f);
111GL(glUniform4f);
112
113GL(glGetAttribLocation);
114GL(glEnableVertexAttribArray);
115GL(glDisableVertexAttribArray);
116GL(glVertexAttribPointer);
117GL(glBindFragDataLocation);
118
119#undef GL
120
121
124 float x, y;
125 float u, v;
126};
127
129static const int MAX_CACHED_CURSORS = 48;
130
131/* static */ OpenGLBackend *OpenGLBackend::instance = nullptr;
132
133GetOGLProcAddressProc GetOGLProcAddress;
134
142const char *FindStringInExtensionList(const char *string, const char *substring)
143{
144 while (true) {
145 /* Is the extension string present at all? */
146 const char *pos = strstr(string, substring);
147 if (pos == nullptr) break;
148
149 /* Is this a real match, i.e. are the chars before and after the matched string
150 * indeed spaces (or the start or end of the string, respectively)? */
151 const char *end = pos + strlen(substring);
152 if ((pos == string || pos[-1] == ' ') && (*end == ' ' || *end == '\0')) return pos;
153
154 /* False hit, try again for the remaining string. */
155 string = end;
156 }
157
158 return nullptr;
159}
160
166static bool IsOpenGLExtensionSupported(const char *extension)
167{
168 static PFNGLGETSTRINGIPROC glGetStringi = nullptr;
169 static bool glGetStringi_loaded = false;
170
171 /* Starting with OpenGL 3.0 the preferred API to get the extensions
172 * has changed. Try to load the required function once. */
173 if (!glGetStringi_loaded) {
174 if (IsOpenGLVersionAtLeast(3, 0)) glGetStringi = (PFNGLGETSTRINGIPROC)GetOGLProcAddress("glGetStringi");
175 glGetStringi_loaded = true;
176 }
177
178 if (glGetStringi != nullptr) {
179 /* New style: Each supported extension can be queried and compared independently. */
180 GLint num_exts;
181 _glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts);
182
183 for (GLint i = 0; i < num_exts; i++) {
184 const char *entry = (const char *)glGetStringi(GL_EXTENSIONS, i);
185 if (strcmp(entry, extension) == 0) return true;
186 }
187 } else {
188 /* Old style: A single, space-delimited string for all extensions. */
189 return FindStringInExtensionList((const char *)_glGetString(GL_EXTENSIONS), extension) != nullptr;
190 }
191
192 return false;
193}
194
195static uint8_t _gl_major_ver = 0;
196static uint8_t _gl_minor_ver = 0;
197
205bool IsOpenGLVersionAtLeast(uint8_t major, uint8_t minor)
206{
207 return (_gl_major_ver > major) || (_gl_major_ver == major && _gl_minor_ver >= minor);
208}
209
217template <typename F>
218static bool BindGLProc(F &f, const char *name)
219{
220 f = reinterpret_cast<F>(GetOGLProcAddress(name));
221 return f != nullptr;
222}
223
225static bool BindBasicInfoProcs()
226{
227 if (!BindGLProc(_glGetString, "glGetString")) return false;
228 if (!BindGLProc(_glGetIntegerv, "glGetIntegerv")) return false;
229 if (!BindGLProc(_glGetError, "glGetError")) return false;
230
231 return true;
232}
233
235static bool BindBasicOpenGLProcs()
236{
237 if (!BindGLProc(_glDisable, "glDisable")) return false;
238 if (!BindGLProc(_glEnable, "glEnable")) return false;
239 if (!BindGLProc(_glViewport, "glViewport")) return false;
240 if (!BindGLProc(_glTexImage1D, "glTexImage1D")) return false;
241 if (!BindGLProc(_glTexImage2D, "glTexImage2D")) return false;
242 if (!BindGLProc(_glTexParameteri, "glTexParameteri")) return false;
243 if (!BindGLProc(_glTexSubImage1D, "glTexSubImage1D")) return false;
244 if (!BindGLProc(_glTexSubImage2D, "glTexSubImage2D")) return false;
245 if (!BindGLProc(_glBindTexture, "glBindTexture")) return false;
246 if (!BindGLProc(_glDeleteTextures, "glDeleteTextures")) return false;
247 if (!BindGLProc(_glGenTextures, "glGenTextures")) return false;
248 if (!BindGLProc(_glPixelStorei, "glPixelStorei")) return false;
249 if (!BindGLProc(_glClear, "glClear")) return false;
250 if (!BindGLProc(_glClearColor, "glClearColor")) return false;
251 if (!BindGLProc(_glBlendFunc, "glBlendFunc")) return false;
252 if (!BindGLProc(_glDrawArrays, "glDrawArrays")) return false;
253
254 return true;
255}
256
258static bool BindTextureExtensions()
259{
260 if (IsOpenGLVersionAtLeast(1, 3)) {
261 if (!BindGLProc(_glActiveTexture, "glActiveTexture")) return false;
262 } else {
263 if (!BindGLProc(_glActiveTexture, "glActiveTextureARB")) return false;
264 }
265
266 return true;
267}
268
270static bool BindVBOExtension()
271{
272 if (IsOpenGLVersionAtLeast(1, 5)) {
273 if (!BindGLProc(_glGenBuffers, "glGenBuffers")) return false;
274 if (!BindGLProc(_glDeleteBuffers, "glDeleteBuffers")) return false;
275 if (!BindGLProc(_glBindBuffer, "glBindBuffer")) return false;
276 if (!BindGLProc(_glBufferData, "glBufferData")) return false;
277 if (!BindGLProc(_glBufferSubData, "glBufferSubData")) return false;
278 if (!BindGLProc(_glMapBuffer, "glMapBuffer")) return false;
279 if (!BindGLProc(_glUnmapBuffer, "glUnmapBuffer")) return false;
280 } else {
281 if (!BindGLProc(_glGenBuffers, "glGenBuffersARB")) return false;
282 if (!BindGLProc(_glDeleteBuffers, "glDeleteBuffersARB")) return false;
283 if (!BindGLProc(_glBindBuffer, "glBindBufferARB")) return false;
284 if (!BindGLProc(_glBufferData, "glBufferDataARB")) return false;
285 if (!BindGLProc(_glBufferSubData, "glBufferSubDataARB")) return false;
286 if (!BindGLProc(_glMapBuffer, "glMapBufferARB")) return false;
287 if (!BindGLProc(_glUnmapBuffer, "glUnmapBufferARB")) return false;
288 }
289
290 if (IsOpenGLVersionAtLeast(4, 3) || IsOpenGLExtensionSupported("GL_ARB_clear_buffer_object")) {
291 BindGLProc(_glClearBufferSubData, "glClearBufferSubData");
292 } else {
293 _glClearBufferSubData = nullptr;
294 }
295
296 return true;
297}
298
300static bool BindVBAExtension()
301{
302 /* The APPLE and ARB variants have different semantics (that don't matter for us).
303 * Successfully getting pointers to one variant doesn't mean it is supported for
304 * the current context. Always check the extension strings as well. */
305 if (IsOpenGLVersionAtLeast(3, 0) || IsOpenGLExtensionSupported("GL_ARB_vertex_array_object")) {
306 if (!BindGLProc(_glGenVertexArrays, "glGenVertexArrays")) return false;
307 if (!BindGLProc(_glDeleteVertexArrays, "glDeleteVertexArrays")) return false;
308 if (!BindGLProc(_glBindVertexArray, "glBindVertexArray")) return false;
309 } else if (IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object")) {
310 if (!BindGLProc(_glGenVertexArrays, "glGenVertexArraysAPPLE")) return false;
311 if (!BindGLProc(_glDeleteVertexArrays, "glDeleteVertexArraysAPPLE")) return false;
312 if (!BindGLProc(_glBindVertexArray, "glBindVertexArrayAPPLE")) return false;
313 }
314
315 return true;
316}
317
319static bool BindShaderExtensions()
320{
321 if (IsOpenGLVersionAtLeast(2, 0)) {
322 if (!BindGLProc(_glCreateProgram, "glCreateProgram")) return false;
323 if (!BindGLProc(_glDeleteProgram, "glDeleteProgram")) return false;
324 if (!BindGLProc(_glLinkProgram, "glLinkProgram")) return false;
325 if (!BindGLProc(_glUseProgram, "glUseProgram")) return false;
326 if (!BindGLProc(_glGetProgramiv, "glGetProgramiv")) return false;
327 if (!BindGLProc(_glGetProgramInfoLog, "glGetProgramInfoLog")) return false;
328 if (!BindGLProc(_glCreateShader, "glCreateShader")) return false;
329 if (!BindGLProc(_glDeleteShader, "glDeleteShader")) return false;
330 if (!BindGLProc(_glShaderSource, "glShaderSource")) return false;
331 if (!BindGLProc(_glCompileShader, "glCompileShader")) return false;
332 if (!BindGLProc(_glAttachShader, "glAttachShader")) return false;
333 if (!BindGLProc(_glGetShaderiv, "glGetShaderiv")) return false;
334 if (!BindGLProc(_glGetShaderInfoLog, "glGetShaderInfoLog")) return false;
335 if (!BindGLProc(_glGetUniformLocation, "glGetUniformLocation")) return false;
336 if (!BindGLProc(_glUniform1i, "glUniform1i")) return false;
337 if (!BindGLProc(_glUniform1f, "glUniform1f")) return false;
338 if (!BindGLProc(_glUniform2f, "glUniform2f")) return false;
339 if (!BindGLProc(_glUniform4f, "glUniform4f")) return false;
340
341 if (!BindGLProc(_glGetAttribLocation, "glGetAttribLocation")) return false;
342 if (!BindGLProc(_glEnableVertexAttribArray, "glEnableVertexAttribArray")) return false;
343 if (!BindGLProc(_glDisableVertexAttribArray, "glDisableVertexAttribArray")) return false;
344 if (!BindGLProc(_glVertexAttribPointer, "glVertexAttribPointer")) return false;
345 } else {
346 /* In the ARB extension programs and shaders are in the same object space. */
347 if (!BindGLProc(_glCreateProgram, "glCreateProgramObjectARB")) return false;
348 if (!BindGLProc(_glDeleteProgram, "glDeleteObjectARB")) return false;
349 if (!BindGLProc(_glLinkProgram, "glLinkProgramARB")) return false;
350 if (!BindGLProc(_glUseProgram, "glUseProgramObjectARB")) return false;
351 if (!BindGLProc(_glGetProgramiv, "glGetObjectParameterivARB")) return false;
352 if (!BindGLProc(_glGetProgramInfoLog, "glGetInfoLogARB")) return false;
353 if (!BindGLProc(_glCreateShader, "glCreateShaderObjectARB")) return false;
354 if (!BindGLProc(_glDeleteShader, "glDeleteObjectARB")) return false;
355 if (!BindGLProc(_glShaderSource, "glShaderSourceARB")) return false;
356 if (!BindGLProc(_glCompileShader, "glCompileShaderARB")) return false;
357 if (!BindGLProc(_glAttachShader, "glAttachObjectARB")) return false;
358 if (!BindGLProc(_glGetShaderiv, "glGetObjectParameterivARB")) return false;
359 if (!BindGLProc(_glGetShaderInfoLog, "glGetInfoLogARB")) return false;
360 if (!BindGLProc(_glGetUniformLocation, "glGetUniformLocationARB")) return false;
361 if (!BindGLProc(_glUniform1i, "glUniform1iARB")) return false;
362 if (!BindGLProc(_glUniform1f, "glUniform1fARB")) return false;
363 if (!BindGLProc(_glUniform2f, "glUniform2fARB")) return false;
364 if (!BindGLProc(_glUniform4f, "glUniform4fARB")) return false;
365
366 if (!BindGLProc(_glGetAttribLocation, "glGetAttribLocationARB")) return false;
367 if (!BindGLProc(_glEnableVertexAttribArray, "glEnableVertexAttribArrayARB")) return false;
368 if (!BindGLProc(_glDisableVertexAttribArray, "glDisableVertexAttribArrayARB")) return false;
369 if (!BindGLProc(_glVertexAttribPointer, "glVertexAttribPointerARB")) return false;
370 }
371
372 /* Bind functions only needed when using GLSL 1.50 shaders. */
373 if (IsOpenGLVersionAtLeast(3, 0)) {
374 BindGLProc(_glBindFragDataLocation, "glBindFragDataLocation");
375 } else if (IsOpenGLExtensionSupported("GL_EXT_gpu_shader4")) {
376 BindGLProc(_glBindFragDataLocation, "glBindFragDataLocationEXT");
377 } else {
378 _glBindFragDataLocation = nullptr;
379 }
380
381 return true;
382}
383
385static bool BindPersistentBufferExtensions()
386{
387 /* Optional functions for persistent buffer mapping. */
388 if (IsOpenGLVersionAtLeast(3, 0)) {
389 if (!BindGLProc(_glMapBufferRange, "glMapBufferRange")) return false;
390 }
391 if (IsOpenGLVersionAtLeast(4, 4) || IsOpenGLExtensionSupported("GL_ARB_buffer_storage")) {
392 if (!BindGLProc(_glBufferStorage, "glBufferStorage")) return false;
393 }
394#ifndef NO_GL_BUFFER_SYNC
395 if (IsOpenGLVersionAtLeast(3, 2) || IsOpenGLExtensionSupported("GL_ARB_sync")) {
396 if (!BindGLProc(_glClientWaitSync, "glClientWaitSync")) return false;
397 if (!BindGLProc(_glFenceSync, "glFenceSync")) return false;
398 if (!BindGLProc(_glDeleteSync, "glDeleteSync")) return false;
399 }
400#endif
401
402 return true;
403}
404
406void APIENTRY DebugOutputCallback([[maybe_unused]] GLenum source, GLenum type, [[maybe_unused]] GLuint id, GLenum severity, [[maybe_unused]] GLsizei length, const GLchar *message, [[maybe_unused]] const void *userParam)
407{
408 /* Make severity human readable. */
409 const char *severity_str = "";
410 switch (severity) {
411 case GL_DEBUG_SEVERITY_HIGH: severity_str = "high"; break;
412 case GL_DEBUG_SEVERITY_MEDIUM: severity_str = "medium"; break;
413 case GL_DEBUG_SEVERITY_LOW: severity_str = "low"; break;
414 }
415
416 /* Make type human readable.*/
417 const char *type_str = "Other";
418 switch (type) {
419 case GL_DEBUG_TYPE_ERROR: type_str = "Error"; break;
420 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: type_str = "Deprecated"; break;
421 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: type_str = "Undefined behaviour"; break;
422 case GL_DEBUG_TYPE_PERFORMANCE: type_str = "Performance"; break;
423 case GL_DEBUG_TYPE_PORTABILITY: type_str = "Portability"; break;
424 }
425
426 Debug(driver, 6, "OpenGL: {} ({}) - {}", type_str, severity_str, message);
427}
428
430void SetupDebugOutput()
431{
432#ifndef NO_DEBUG_MESSAGES
433 if (_debug_driver_level < 6) return;
434
435 if (IsOpenGLVersionAtLeast(4, 3)) {
436 BindGLProc(_glDebugMessageControl, "glDebugMessageControl");
437 BindGLProc(_glDebugMessageCallback, "glDebugMessageCallback");
438 } else if (IsOpenGLExtensionSupported("GL_ARB_debug_output")) {
439 BindGLProc(_glDebugMessageControl, "glDebugMessageControlARB");
440 BindGLProc(_glDebugMessageCallback, "glDebugMessageCallbackARB");
441 }
442
443 if (_glDebugMessageControl != nullptr && _glDebugMessageCallback != nullptr) {
444 /* Enable debug output. As synchronous debug output costs performance, we only enable it with a high debug level. */
445 _glEnable(GL_DEBUG_OUTPUT);
446 if (_debug_driver_level >= 8) _glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
447
448 _glDebugMessageCallback(&DebugOutputCallback, nullptr);
449 /* Enable all messages on highest debug level.*/
450 _glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, _debug_driver_level >= 9 ? GL_TRUE : GL_FALSE);
451 /* Get debug messages for errors and undefined/deprecated behaviour. */
452 _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
453 _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
454 _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
455 }
456#endif
457}
458
465/* static */ std::optional<std::string_view> OpenGLBackend::Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
466{
468
469 GetOGLProcAddress = get_proc;
470
472 return OpenGLBackend::instance->Init(screen_res);
473}
474
478/* static */ void OpenGLBackend::Destroy()
479{
481 OpenGLBackend::instance = nullptr;
482}
483
487OpenGLBackend::OpenGLBackend() : cursor_cache(MAX_CACHED_CURSORS)
488{
489}
490
495{
496 if (_glDeleteProgram != nullptr) {
497 _glDeleteProgram(this->remap_program);
498 _glDeleteProgram(this->vid_program);
499 _glDeleteProgram(this->pal_program);
500 _glDeleteProgram(this->sprite_program);
501 }
502 if (_glDeleteVertexArrays != nullptr) _glDeleteVertexArrays(1, &this->vao_quad);
503 if (_glDeleteBuffers != nullptr) {
504 _glDeleteBuffers(1, &this->vbo_quad);
505 _glDeleteBuffers(1, &this->vid_pbo);
506 _glDeleteBuffers(1, &this->anim_pbo);
507 }
508 if (_glDeleteTextures != nullptr) {
511
512 _glDeleteTextures(1, &this->vid_texture);
513 _glDeleteTextures(1, &this->anim_texture);
514 _glDeleteTextures(1, &this->pal_texture);
515 }
516}
517
523std::optional<std::string_view> OpenGLBackend::Init(const Dimension &screen_res)
524{
525 if (!BindBasicInfoProcs()) return "OpenGL not supported";
526
527 /* Always query the supported OpenGL version as the current context might have changed. */
528 const char *ver = (const char *)_glGetString(GL_VERSION);
529 const char *vend = (const char *)_glGetString(GL_VENDOR);
530 const char *renderer = (const char *)_glGetString(GL_RENDERER);
531
532 if (ver == nullptr || vend == nullptr || renderer == nullptr) return "OpenGL not supported";
533
534 Debug(driver, 1, "OpenGL driver: {} - {} ({})", vend, renderer, ver);
535
536#ifndef GL_ALLOW_SOFTWARE_RENDERER
537 /* Don't use MESA software rendering backends as they are slower than
538 * just using a non-OpenGL video driver. */
539 if (strncmp(renderer, "llvmpipe", 8) == 0 || strncmp(renderer, "softpipe", 8) == 0) return "Software renderer detected, not using OpenGL";
540#endif
541
542 const char *minor = strchr(ver, '.');
543 _gl_major_ver = atoi(ver);
544 _gl_minor_ver = minor != nullptr ? atoi(minor + 1) : 0;
545
546#ifdef _WIN32
547 /* Old drivers on Windows (especially if made by Intel) seem to be
548 * unstable, so cull the oldest stuff here. */
549 if (!IsOpenGLVersionAtLeast(3, 2)) return "Need at least OpenGL version 3.2 on Windows";
550#endif
551
552 if (!BindBasicOpenGLProcs()) return "Failed to bind basic OpenGL functions.";
553
554 SetupDebugOutput();
555
556 /* OpenGL 1.3 is the absolute minimum. */
557 if (!IsOpenGLVersionAtLeast(1, 3)) return "OpenGL version >= 1.3 required";
558 /* Check for non-power-of-two texture support. */
559 if (!IsOpenGLVersionAtLeast(2, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_non_power_of_two")) return "Non-power-of-two textures not supported";
560 /* Check for single element texture formats. */
561 if (!IsOpenGLVersionAtLeast(3, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_rg")) return "Single element texture formats not supported";
562 if (!BindTextureExtensions()) return "Failed to bind texture extension functions";
563 /* Check for vertex buffer objects. */
564 if (!IsOpenGLVersionAtLeast(1, 5) && !IsOpenGLExtensionSupported("ARB_vertex_buffer_object")) return "Vertex buffer objects not supported";
565 if (!BindVBOExtension()) return "Failed to bind VBO extension functions";
566 /* Check for pixel buffer objects. */
567 if (!IsOpenGLVersionAtLeast(2, 1) && !IsOpenGLExtensionSupported("GL_ARB_pixel_buffer_object")) return "Pixel buffer objects not supported";
568 /* Check for vertex array objects. */
569 if (!IsOpenGLVersionAtLeast(3, 0) && (!IsOpenGLExtensionSupported("GL_ARB_vertex_array_object") || !IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object"))) return "Vertex array objects not supported";
570 if (!BindVBAExtension()) return "Failed to bind VBA extension functions";
571 /* Check for shader objects. */
572 if (!IsOpenGLVersionAtLeast(2, 0) && (!IsOpenGLExtensionSupported("GL_ARB_shader_objects") || !IsOpenGLExtensionSupported("GL_ARB_fragment_shader") || !IsOpenGLExtensionSupported("GL_ARB_vertex_shader"))) return "No shader support";
573 if (!BindShaderExtensions()) return "Failed to bind shader extension functions";
574 if (IsOpenGLVersionAtLeast(3, 2) && _glBindFragDataLocation == nullptr) return "OpenGL claims to support version 3.2 but doesn't have glBindFragDataLocation";
575
576 this->persistent_mapping_supported = IsOpenGLVersionAtLeast(3, 0) && (IsOpenGLVersionAtLeast(4, 4) || IsOpenGLExtensionSupported("GL_ARB_buffer_storage"));
577#ifndef NO_GL_BUFFER_SYNC
578 this->persistent_mapping_supported = this->persistent_mapping_supported && (IsOpenGLVersionAtLeast(3, 2) || IsOpenGLExtensionSupported("GL_ARB_sync"));
579#endif
580
581 if (this->persistent_mapping_supported && !BindPersistentBufferExtensions()) {
582 Debug(driver, 1, "OpenGL claims to support persistent buffer mapping but doesn't export all functions, not using persistent mapping.");
583 this->persistent_mapping_supported = false;
584 }
585 if (this->persistent_mapping_supported) Debug(driver, 3, "OpenGL: Using persistent buffer mapping");
586
587 /* Check maximum texture size against screen resolution. */
588 GLint max_tex_size = 0;
589 _glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
590 if (std::max(screen_res.width, screen_res.height) > (uint)max_tex_size) return "Max supported texture size is too small";
591
592 /* Check available texture units. */
593 GLint max_tex_units = 0;
594 _glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_tex_units);
595 if (max_tex_units < 4) return "Not enough simultaneous textures supported";
596
597 Debug(driver, 2, "OpenGL shading language version: {}, texture units = {}", (const char *)_glGetString(GL_SHADING_LANGUAGE_VERSION), (int)max_tex_units);
598
599 if (!this->InitShaders()) return "Failed to initialize shaders";
600
601 /* Setup video buffer texture. */
602 _glGenTextures(1, &this->vid_texture);
603 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
604 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
605 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
606 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
607 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
608 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
609 _glBindTexture(GL_TEXTURE_2D, 0);
610 if (_glGetError() != GL_NO_ERROR) return "Can't generate video buffer texture";
611
612 /* Setup video buffer texture. */
613 _glGenTextures(1, &this->anim_texture);
614 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
615 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
616 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
617 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
618 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
619 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
620 _glBindTexture(GL_TEXTURE_2D, 0);
621 if (_glGetError() != GL_NO_ERROR) return "Can't generate animation buffer texture";
622
623 /* Setup palette texture. */
624 _glGenTextures(1, &this->pal_texture);
625 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
626 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
627 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
628 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
629 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
630 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
631 _glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA8, 256, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
632 _glBindTexture(GL_TEXTURE_1D, 0);
633 if (_glGetError() != GL_NO_ERROR) return "Can't generate palette lookup texture";
634
635 /* Bind uniforms in rendering shader program. */
636 GLint tex_location = _glGetUniformLocation(this->vid_program, "colour_tex");
637 GLint palette_location = _glGetUniformLocation(this->vid_program, "palette");
638 GLint sprite_location = _glGetUniformLocation(this->vid_program, "sprite");
639 GLint screen_location = _glGetUniformLocation(this->vid_program, "screen");
640 _glUseProgram(this->vid_program);
641 _glUniform1i(tex_location, 0); // Texture unit 0.
642 _glUniform1i(palette_location, 1); // Texture unit 1.
643 /* Values that result in no transform. */
644 _glUniform4f(sprite_location, 0.0f, 0.0f, 1.0f, 1.0f);
645 _glUniform2f(screen_location, 1.0f, 1.0f);
646
647 /* Bind uniforms in palette rendering shader program. */
648 tex_location = _glGetUniformLocation(this->pal_program, "colour_tex");
649 palette_location = _glGetUniformLocation(this->pal_program, "palette");
650 sprite_location = _glGetUniformLocation(this->pal_program, "sprite");
651 screen_location = _glGetUniformLocation(this->pal_program, "screen");
652 _glUseProgram(this->pal_program);
653 _glUniform1i(tex_location, 0); // Texture unit 0.
654 _glUniform1i(palette_location, 1); // Texture unit 1.
655 _glUniform4f(sprite_location, 0.0f, 0.0f, 1.0f, 1.0f);
656 _glUniform2f(screen_location, 1.0f, 1.0f);
657
658 /* Bind uniforms in remap shader program. */
659 tex_location = _glGetUniformLocation(this->remap_program, "colour_tex");
660 palette_location = _glGetUniformLocation(this->remap_program, "palette");
661 GLint remap_location = _glGetUniformLocation(this->remap_program, "remap_tex");
662 this->remap_sprite_loc = _glGetUniformLocation(this->remap_program, "sprite");
663 this->remap_screen_loc = _glGetUniformLocation(this->remap_program, "screen");
664 this->remap_zoom_loc = _glGetUniformLocation(this->remap_program, "zoom");
665 this->remap_rgb_loc = _glGetUniformLocation(this->remap_program, "rgb");
666 _glUseProgram(this->remap_program);
667 _glUniform1i(tex_location, 0); // Texture unit 0.
668 _glUniform1i(palette_location, 1); // Texture unit 1.
669 _glUniform1i(remap_location, 2); // Texture unit 2.
670
671 /* Bind uniforms in sprite shader program. */
672 tex_location = _glGetUniformLocation(this->sprite_program, "colour_tex");
673 palette_location = _glGetUniformLocation(this->sprite_program, "palette");
674 remap_location = _glGetUniformLocation(this->sprite_program, "remap_tex");
675 GLint pal_location = _glGetUniformLocation(this->sprite_program, "pal");
676 this->sprite_sprite_loc = _glGetUniformLocation(this->sprite_program, "sprite");
677 this->sprite_screen_loc = _glGetUniformLocation(this->sprite_program, "screen");
678 this->sprite_zoom_loc = _glGetUniformLocation(this->sprite_program, "zoom");
679 this->sprite_rgb_loc = _glGetUniformLocation(this->sprite_program, "rgb");
680 this->sprite_crash_loc = _glGetUniformLocation(this->sprite_program, "crash");
681 _glUseProgram(this->sprite_program);
682 _glUniform1i(tex_location, 0); // Texture unit 0.
683 _glUniform1i(palette_location, 1); // Texture unit 1.
684 _glUniform1i(remap_location, 2); // Texture unit 2.
685 _glUniform1i(pal_location, 3); // Texture unit 3.
686 (void)_glGetError(); // Clear errors.
687
688 /* Create pixel buffer object as video buffer storage. */
689 _glGenBuffers(1, &this->vid_pbo);
690 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
691 _glGenBuffers(1, &this->anim_pbo);
692 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
693 if (_glGetError() != GL_NO_ERROR) return "Can't allocate pixel buffer for video buffer";
694
695 /* Prime vertex buffer with a full-screen quad and store
696 * the corresponding state in a vertex array object. */
697 static const Simple2DVertex vert_array[] = {
698 // x y u v
699 { 1.f, -1.f, 1.f, 1.f },
700 { 1.f, 1.f, 1.f, 0.f },
701 { -1.f, -1.f, 0.f, 1.f },
702 { -1.f, 1.f, 0.f, 0.f },
703 };
704
705 /* Create VAO. */
706 _glGenVertexArrays(1, &this->vao_quad);
707 _glBindVertexArray(this->vao_quad);
708
709 /* Create and fill VBO. */
710 _glGenBuffers(1, &this->vbo_quad);
711 _glBindBuffer(GL_ARRAY_BUFFER, this->vbo_quad);
712 _glBufferData(GL_ARRAY_BUFFER, sizeof(vert_array), vert_array, GL_STATIC_DRAW);
713 if (_glGetError() != GL_NO_ERROR) return "Can't generate VBO for fullscreen quad";
714
715 /* Set vertex state. */
716 GLint loc_position = _glGetAttribLocation(this->vid_program, "position");
717 GLint colour_position = _glGetAttribLocation(this->vid_program, "colour_uv");
718 _glEnableVertexAttribArray(loc_position);
719 _glEnableVertexAttribArray(colour_position);
720 _glVertexAttribPointer(loc_position, 2, GL_FLOAT, GL_FALSE, sizeof(Simple2DVertex), (GLvoid *)offsetof(Simple2DVertex, x));
721 _glVertexAttribPointer(colour_position, 2, GL_FLOAT, GL_FALSE, sizeof(Simple2DVertex), (GLvoid *)offsetof(Simple2DVertex, u));
722 _glBindVertexArray(0);
723
724 /* Create resources for sprite rendering. */
725 if (!OpenGLSprite::Create()) return "Failed to create sprite rendering resources";
726
727 this->PrepareContext();
728 (void)_glGetError(); // Clear errors.
729
730 return std::nullopt;
731}
732
733void OpenGLBackend::PrepareContext()
734{
735 _glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
736 _glDisable(GL_DEPTH_TEST);
737 /* Enable alpha blending using the src alpha factor. */
738 _glEnable(GL_BLEND);
739 _glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
740}
741
742std::string OpenGLBackend::GetDriverName()
743{
744 std::string res{};
745 /* Skipping GL_VENDOR as it tends to be "obvious" from the renderer and version data, and just makes the string pointlessly longer */
746 res += reinterpret_cast<const char *>(_glGetString(GL_RENDERER));
747 res += ", ";
748 res += reinterpret_cast<const char *>(_glGetString(GL_VERSION));
749 return res;
750}
751
757static bool VerifyShader(GLuint shader)
758{
759 static ReusableBuffer<char> log_buf;
760
761 GLint result = GL_FALSE;
762 _glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
763
764 /* Output log if there is one. */
765 GLint log_len = 0;
766 _glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
767 if (log_len > 0) {
768 _glGetShaderInfoLog(shader, log_len, nullptr, log_buf.Allocate(log_len));
769 Debug(driver, result != GL_TRUE ? 0 : 2, "{}", log_buf.GetBuffer()); // Always print on failure.
770 }
771
772 return result == GL_TRUE;
773}
774
780static bool VerifyProgram(GLuint program)
781{
782 static ReusableBuffer<char> log_buf;
783
784 GLint result = GL_FALSE;
785 _glGetProgramiv(program, GL_LINK_STATUS, &result);
786
787 /* Output log if there is one. */
788 GLint log_len = 0;
789 _glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_len);
790 if (log_len > 0) {
791 _glGetProgramInfoLog(program, log_len, nullptr, log_buf.Allocate(log_len));
792 Debug(driver, result != GL_TRUE ? 0 : 2, "{}", log_buf.GetBuffer()); // Always print on failure.
793 }
794
795 return result == GL_TRUE;
796}
797
803{
804 const char *ver = (const char *)_glGetString(GL_SHADING_LANGUAGE_VERSION);
805 if (ver == nullptr) return false;
806
807 int glsl_major = ver[0] - '0';
808 int glsl_minor = ver[2] - '0';
809
810 bool glsl_150 = (IsOpenGLVersionAtLeast(3, 2) || glsl_major > 1 || (glsl_major == 1 && glsl_minor >= 5)) && _glBindFragDataLocation != nullptr;
811
812 /* Create vertex shader. */
813 GLuint vert_shader = _glCreateShader(GL_VERTEX_SHADER);
814 _glShaderSource(vert_shader, glsl_150 ? lengthof(_vertex_shader_sprite_150) : lengthof(_vertex_shader_sprite), glsl_150 ? _vertex_shader_sprite_150 : _vertex_shader_sprite, nullptr);
815 _glCompileShader(vert_shader);
816 if (!VerifyShader(vert_shader)) return false;
817
818 /* Create fragment shader for plain RGBA. */
819 GLuint frag_shader_rgb = _glCreateShader(GL_FRAGMENT_SHADER);
820 _glShaderSource(frag_shader_rgb, glsl_150 ? lengthof(_frag_shader_direct_150) : lengthof(_frag_shader_direct), glsl_150 ? _frag_shader_direct_150 : _frag_shader_direct, nullptr);
821 _glCompileShader(frag_shader_rgb);
822 if (!VerifyShader(frag_shader_rgb)) return false;
823
824 /* Create fragment shader for paletted only. */
825 GLuint frag_shader_pal = _glCreateShader(GL_FRAGMENT_SHADER);
826 _glShaderSource(frag_shader_pal, glsl_150 ? lengthof(_frag_shader_palette_150) : lengthof(_frag_shader_palette), glsl_150 ? _frag_shader_palette_150 : _frag_shader_palette, nullptr);
827 _glCompileShader(frag_shader_pal);
828 if (!VerifyShader(frag_shader_pal)) return false;
829
830 /* Sprite remap fragment shader. */
831 GLuint remap_shader = _glCreateShader(GL_FRAGMENT_SHADER);
833 _glCompileShader(remap_shader);
834 if (!VerifyShader(remap_shader)) return false;
835
836 /* Sprite fragment shader. */
837 GLuint sprite_shader = _glCreateShader(GL_FRAGMENT_SHADER);
839 _glCompileShader(sprite_shader);
840 if (!VerifyShader(sprite_shader)) return false;
841
842 /* Link shaders to program. */
843 this->vid_program = _glCreateProgram();
844 _glAttachShader(this->vid_program, vert_shader);
845 _glAttachShader(this->vid_program, frag_shader_rgb);
846
847 this->pal_program = _glCreateProgram();
848 _glAttachShader(this->pal_program, vert_shader);
849 _glAttachShader(this->pal_program, frag_shader_pal);
850
851 this->remap_program = _glCreateProgram();
852 _glAttachShader(this->remap_program, vert_shader);
853 _glAttachShader(this->remap_program, remap_shader);
854
855 this->sprite_program = _glCreateProgram();
856 _glAttachShader(this->sprite_program, vert_shader);
857 _glAttachShader(this->sprite_program, sprite_shader);
858
859 if (glsl_150) {
860 /* Bind fragment shader outputs. */
861 _glBindFragDataLocation(this->vid_program, 0, "colour");
862 _glBindFragDataLocation(this->pal_program, 0, "colour");
863 _glBindFragDataLocation(this->remap_program, 0, "colour");
864 _glBindFragDataLocation(this->sprite_program, 0, "colour");
865 }
866
867 _glLinkProgram(this->vid_program);
868 if (!VerifyProgram(this->vid_program)) return false;
869
870 _glLinkProgram(this->pal_program);
871 if (!VerifyProgram(this->pal_program)) return false;
872
873 _glLinkProgram(this->remap_program);
874 if (!VerifyProgram(this->remap_program)) return false;
875
876 _glLinkProgram(this->sprite_program);
877 if (!VerifyProgram(this->sprite_program)) return false;
878
879 _glDeleteShader(vert_shader);
880 _glDeleteShader(frag_shader_rgb);
881 _glDeleteShader(frag_shader_pal);
882 _glDeleteShader(remap_shader);
883 _glDeleteShader(sprite_shader);
884
885 return true;
886}
887
894template <class T>
895static void ClearPixelBuffer(size_t len, T data)
896{
897 T *buf = reinterpret_cast<T *>(_glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE));
898 for (size_t i = 0; i < len; i++) {
899 *buf++ = data;
900 }
901 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
902}
903
911bool OpenGLBackend::Resize(int w, int h, bool force)
912{
913 if (!force && _screen.width == w && _screen.height == h) return false;
914
916 int pitch = Align(w, 4);
917 size_t line_pixel_count = static_cast<size_t>(pitch) * h;
918
919 _glViewport(0, 0, w, h);
920
921 _glPixelStorei(GL_UNPACK_ROW_LENGTH, pitch);
922
923 this->vid_buffer = nullptr;
925 _glDeleteBuffers(1, &this->vid_pbo);
926 _glGenBuffers(1, &this->vid_pbo);
927 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
928 _glBufferStorage(GL_PIXEL_UNPACK_BUFFER, line_pixel_count * bpp / 8, nullptr, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT | GL_CLIENT_STORAGE_BIT);
929 } else {
930 /* Re-allocate video buffer texture and backing store. */
931 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
932 _glBufferData(GL_PIXEL_UNPACK_BUFFER, line_pixel_count * bpp / 8, nullptr, GL_DYNAMIC_DRAW);
933 }
934
935 if (bpp == 32) {
936 /* Initialize backing store alpha to opaque for 32bpp modes. */
937 Colour black(0, 0, 0);
938 if (_glClearBufferSubData != nullptr) {
939 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_RGBA8, 0, line_pixel_count * bpp / 8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, &black.data);
940 } else {
941 ClearPixelBuffer<uint32_t>(line_pixel_count, black.data);
942 }
943 } else if (bpp == 8) {
944 if (_glClearBufferSubData != nullptr) {
945 uint8_t b = 0;
946 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_R8, 0, line_pixel_count, GL_RED, GL_UNSIGNED_BYTE, &b);
947 } else {
948 ClearPixelBuffer<uint8_t>(line_pixel_count, 0);
949 }
950 }
951
952 _glActiveTexture(GL_TEXTURE0);
953 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
954 if (bpp == 8) {
955 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
956 } else {
957 _glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
958 }
959 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
960
961 /* Does this blitter need a separate animation buffer? */
962 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
963 this->anim_buffer = nullptr;
965 _glDeleteBuffers(1, &this->anim_pbo);
966 _glGenBuffers(1, &this->anim_pbo);
967 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
968 _glBufferStorage(GL_PIXEL_UNPACK_BUFFER, line_pixel_count, nullptr, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT | GL_CLIENT_STORAGE_BIT);
969 } else {
970 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
971 _glBufferData(GL_PIXEL_UNPACK_BUFFER, line_pixel_count, nullptr, GL_DYNAMIC_DRAW);
972 }
973
974 /* Initialize buffer as 0 == no remap. */
975 if (_glClearBufferSubData != nullptr) {
976 uint8_t b = 0;
977 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_R8, 0, line_pixel_count, GL_RED, GL_UNSIGNED_BYTE, &b);
978 } else {
979 ClearPixelBuffer<uint8_t>(line_pixel_count, 0);
980 }
981
982 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
983 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
984 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
985 } else {
986 if (this->anim_buffer != nullptr) {
987 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
988 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
989 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
990 this->anim_buffer = nullptr;
991 }
992
993 /* Allocate dummy texture that always reads as 0 == no remap. */
994 uint dummy = 0;
995 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
996 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
997 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, &dummy);
998 }
999
1000 _glBindTexture(GL_TEXTURE_2D, 0);
1001
1002 /* Set new viewport. */
1003 _screen.height = h;
1004 _screen.width = w;
1005 _screen.pitch = pitch;
1006 _screen.dst_ptr = nullptr;
1007
1008 /* Update screen size in remap shader program. */
1009 _glUseProgram(this->remap_program);
1010 _glUniform2f(this->remap_screen_loc, (float)_screen.width, (float)_screen.height);
1011
1012 _glClear(GL_COLOR_BUFFER_BIT);
1013
1014 return true;
1015}
1016
1023void OpenGLBackend::UpdatePalette(const Colour *pal, uint first, uint length)
1024{
1025 assert(first + length <= 256);
1026
1027 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1028 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1029 _glActiveTexture(GL_TEXTURE1);
1030 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1031 _glTexSubImage1D(GL_TEXTURE_1D, 0, first, length, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pal + first);
1032}
1033
1038{
1039 _glClear(GL_COLOR_BUFFER_BIT);
1040
1041 _glDisable(GL_BLEND);
1042
1043 /* Blit video buffer to screen. */
1044 _glActiveTexture(GL_TEXTURE0);
1045 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
1046 _glActiveTexture(GL_TEXTURE1);
1047 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1048 /* Is the blitter relying on a separate animation buffer? */
1049 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
1050 _glActiveTexture(GL_TEXTURE2);
1051 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1052 _glUseProgram(this->remap_program);
1053 _glUniform4f(this->remap_sprite_loc, 0.0f, 0.0f, 1.0f, 1.0f);
1054 _glUniform2f(this->remap_screen_loc, 1.0f, 1.0f);
1055 _glUniform1f(this->remap_zoom_loc, 0);
1056 _glUniform1i(this->remap_rgb_loc, 1);
1057 } else {
1058 _glUseProgram(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8 ? this->pal_program : this->vid_program);
1059 }
1060 _glBindVertexArray(this->vao_quad);
1061 _glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1062
1063 _glEnable(GL_BLEND);
1064}
1065
1070{
1071 if (!this->cursor_in_window) return;
1072
1073 /* Draw cursor on screen */
1074 _cur_dpi = &_screen;
1075 for (const auto &cs : this->cursor_sprites) {
1076 /* Sprites are cached by PopulateCursorCache(). */
1077 if (this->cursor_cache.Contains(cs.image.sprite)) {
1078 OpenGLSprite *spr = this->cursor_cache.Get(cs.image.sprite);
1079
1080 this->RenderOglSprite(spr, cs.image.pal,
1081 this->cursor_pos.x + cs.pos.x + UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI),
1082 this->cursor_pos.y + cs.pos.y + UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI),
1083 ZOOM_LVL_GUI);
1084 }
1085 }
1086}
1087
1089public:
1091 SpriteID sprite;
1092
1093 OpenGLSpriteAllocator(LRUCache<SpriteID, OpenGLSprite> &lru, SpriteID sprite) : lru(lru), sprite(sprite) {}
1094protected:
1095 void *AllocatePtr(size_t) override { NOT_REACHED(); }
1096};
1097
1098void OpenGLBackend::PopulateCursorCache()
1099{
1100 if (this->clear_cursor_cache) {
1101 /* We have a pending cursor cache clear to do first. */
1102 this->clear_cursor_cache = false;
1103 this->last_sprite_pal = (PaletteID)-1;
1104
1106 }
1107
1108 this->cursor_pos = _cursor.pos;
1109 this->cursor_in_window = _cursor.in_window;
1110
1111 this->cursor_sprites.clear();
1112 for (const auto &sc : _cursor.sprites) {
1113 this->cursor_sprites.emplace_back(sc);
1114
1115 if (!this->cursor_cache.Contains(sc.image.sprite)) {
1116 OpenGLSpriteAllocator allocator(this->cursor_cache, sc.image.sprite);
1117 GetRawSprite(sc.image.sprite, SpriteType::Normal, &allocator, this);
1118 }
1119 }
1120}
1121
1129
1134{
1135 /* If the game loop is threaded, this function might be called
1136 * from the game thread. As we can call OpenGL functions only
1137 * on the main thread, just set a flag that is handled the next
1138 * time we prepare the cursor cache for drawing. */
1139 this->clear_cursor_cache = true;
1140}
1141
1147{
1148#ifndef NO_GL_BUFFER_SYNC
1149 if (this->sync_vid_mapping != nullptr) _glClientWaitSync(this->sync_vid_mapping, GL_SYNC_FLUSH_COMMANDS_BIT, 100000000); // 100ms timeout.
1150#endif
1151
1152 if (!this->persistent_mapping_supported) {
1153 assert(this->vid_buffer == nullptr);
1154 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1155 this->vid_buffer = _glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE);
1156 } else if (this->vid_buffer == nullptr) {
1157 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1158 this->vid_buffer = _glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, static_cast<GLsizeiptr>(_screen.pitch) * _screen.height * BlitterFactory::GetCurrentBlitter()->GetScreenDepth() / 8, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
1159 }
1160
1161 return this->vid_buffer;
1162}
1163
1169{
1170 if (this->anim_pbo == 0) return nullptr;
1171
1172#ifndef NO_GL_BUFFER_SYNC
1173 if (this->sync_anim_mapping != nullptr) _glClientWaitSync(this->sync_anim_mapping, GL_SYNC_FLUSH_COMMANDS_BIT, 100000000); // 100ms timeout.
1174#endif
1175
1176 if (!this->persistent_mapping_supported) {
1177 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1178 this->anim_buffer = _glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE);
1179 } else if (this->anim_buffer == nullptr) {
1180 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1181 this->anim_buffer = _glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, static_cast<GLsizeiptr>(_screen.pitch) * _screen.height, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
1182 }
1183
1184 return (uint8_t *)this->anim_buffer;
1185}
1186
1192{
1193 assert(this->vid_pbo != 0);
1194
1195 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1196 if (!this->persistent_mapping_supported) {
1197 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1198 this->vid_buffer = nullptr;
1199 }
1200
1201#ifndef NO_GL_BUFFER_SYNC
1202 if (this->persistent_mapping_supported) {
1203 _glDeleteSync(this->sync_vid_mapping);
1204 this->sync_vid_mapping = nullptr;
1205 }
1206#endif
1207
1208 /* Update changed rect of the video buffer texture. */
1209 if (!IsEmptyRect(update_rect)) {
1210 _glActiveTexture(GL_TEXTURE0);
1211 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
1212 _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch);
1213 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8) {
1214 _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid*)(size_t)(update_rect.top * _screen.pitch + update_rect.left));
1215 } else {
1216 _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, (GLvoid*)(size_t)(update_rect.top * _screen.pitch * 4 + update_rect.left * 4));
1217 }
1218
1219#ifndef NO_GL_BUFFER_SYNC
1220 if (this->persistent_mapping_supported) this->sync_vid_mapping = _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
1221#endif
1222 }
1223}
1224
1230{
1231 if (this->anim_pbo == 0) return;
1232
1233 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1234 if (!this->persistent_mapping_supported) {
1235 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1236 this->anim_buffer = nullptr;
1237 }
1238
1239#ifndef NO_GL_BUFFER_SYNC
1240 if (this->persistent_mapping_supported) {
1241 _glDeleteSync(this->sync_anim_mapping);
1242 this->sync_anim_mapping = nullptr;
1243 }
1244#endif
1245
1246 /* Update changed rect of the video buffer texture. */
1247 if (update_rect.left != update_rect.right) {
1248 _glActiveTexture(GL_TEXTURE0);
1249 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1250 _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch);
1251 _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid *)(size_t)(update_rect.top * _screen.pitch + update_rect.left));
1252
1253#ifndef NO_GL_BUFFER_SYNC
1254 if (this->persistent_mapping_supported) this->sync_anim_mapping = _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
1255#endif
1256 }
1257}
1258
1260{
1261 /* This encoding is only called for mouse cursors. We don't need real sprites but OpenGLSprites to show as cursor. These need to be put in the LRU cache. */
1262 OpenGLSpriteAllocator &gl_allocator = static_cast<OpenGLSpriteAllocator&>(allocator);
1263 gl_allocator.lru.Insert(gl_allocator.sprite, std::make_unique<OpenGLSprite>(sprite));
1264
1265 return nullptr;
1266}
1267
1275void OpenGLBackend::RenderOglSprite(OpenGLSprite *gl_sprite, PaletteID pal, int x, int y, ZoomLevel zoom)
1276{
1277 /* Set textures. */
1278 bool rgb = gl_sprite->BindTextures();
1279 _glActiveTexture(GL_TEXTURE0 + 1);
1280 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1281
1282 /* Set palette remap. */
1283 _glActiveTexture(GL_TEXTURE0 + 3);
1284 if (pal != PAL_NONE) {
1285 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_tex);
1286 if (pal != this->last_sprite_pal) {
1287 /* Different remap palette in use, update texture. */
1288 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, OpenGLSprite::pal_pbo);
1289 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1290
1291 _glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, 256, GetNonSprite(GB(pal, 0, PALETTE_WIDTH), SpriteType::Recolour) + 1);
1292 _glTexSubImage1D(GL_TEXTURE_1D, 0, 0, 256, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1293
1294 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1295
1296 this->last_sprite_pal = pal;
1297 }
1298 } else {
1299 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_identity);
1300 }
1301
1302 /* Set up shader program. */
1303 Dimension dim = gl_sprite->GetSize(zoom);
1304 _glUseProgram(this->sprite_program);
1305 _glUniform4f(this->sprite_sprite_loc, (float)x, (float)y, (float)dim.width, (float)dim.height);
1306 _glUniform1f(this->sprite_zoom_loc, (float)zoom);
1307 _glUniform2f(this->sprite_screen_loc, (float)_screen.width, (float)_screen.height);
1308 _glUniform1i(this->sprite_rgb_loc, rgb ? 1 : 0);
1309 _glUniform1i(this->sprite_crash_loc, pal == PALETTE_CRASH ? 1 : 0);
1310
1311 _glBindVertexArray(this->vao_quad);
1312 _glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1313}
1314
1315
1316/* static */ std::array<GLuint, OpenGLSprite::NUM_TEX> OpenGLSprite::dummy_tex{};
1317/* static */ GLuint OpenGLSprite::pal_identity = 0;
1318/* static */ GLuint OpenGLSprite::pal_tex = 0;
1319/* static */ GLuint OpenGLSprite::pal_pbo = 0;
1320
1325/* static */ bool OpenGLSprite::Create()
1326{
1327 _glGenTextures(NUM_TEX, OpenGLSprite::dummy_tex.data());
1328
1329 for (int t = TEX_RGBA; t < NUM_TEX; t++) {
1330 _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[t]);
1331
1332 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
1333 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1334 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
1335 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1336 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1337 }
1338
1339 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1340 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1341
1342 /* Load dummy RGBA texture. */
1343 const Colour rgb_pixel(0, 0, 0);
1344 _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[TEX_RGBA]);
1345 _glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, &rgb_pixel);
1346
1347 /* Load dummy remap texture. */
1348 const uint pal = 0;
1349 _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[TEX_REMAP]);
1350 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, &pal);
1351
1352 /* Create palette remap textures. */
1353 std::array<uint8_t, 256> identity_pal;
1354 std::iota(std::begin(identity_pal), std::end(identity_pal), 0);
1355
1356 /* Permanent texture for identity remap. */
1357 _glGenTextures(1, &OpenGLSprite::pal_identity);
1358 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_identity);
1359 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1360 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1361 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
1362 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1363 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1364 _glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, 256, 0, GL_RED, GL_UNSIGNED_BYTE, identity_pal.data());
1365
1366 /* Dynamically updated texture for remaps. */
1367 _glGenTextures(1, &OpenGLSprite::pal_tex);
1368 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_tex);
1369 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1370 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1371 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
1372 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1373 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1374 _glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, 256, 0, GL_RED, GL_UNSIGNED_BYTE, identity_pal.data());
1375
1376 /* Pixel buffer for remap updates. */
1377 _glGenBuffers(1, &OpenGLSprite::pal_pbo);
1378 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, OpenGLSprite::pal_pbo);
1379 _glBufferData(GL_PIXEL_UNPACK_BUFFER, 256, identity_pal.data(), GL_DYNAMIC_DRAW);
1380 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1381
1382 return _glGetError() == GL_NO_ERROR;
1383}
1384
1386/* static */ void OpenGLSprite::Destroy()
1387{
1388 _glDeleteTextures(NUM_TEX, OpenGLSprite::dummy_tex.data());
1389 _glDeleteTextures(1, &OpenGLSprite::pal_identity);
1390 _glDeleteTextures(1, &OpenGLSprite::pal_tex);
1391 if (_glDeleteBuffers != nullptr) _glDeleteBuffers(1, &OpenGLSprite::pal_pbo);
1392}
1393
1399 dim(sprite[ZOOM_LVL_MIN].width, sprite[ZOOM_LVL_MIN].height), x_offs(sprite[ZOOM_LVL_MIN].x_offs), y_offs(sprite[ZOOM_LVL_MIN].y_offs)
1400{
1401 int levels = sprite[ZOOM_LVL_MIN].type == SpriteType::Font ? 1 : ZOOM_LVL_END;
1402 assert(levels > 0);
1403 (void)_glGetError();
1404
1405 this->tex = {};
1406 _glActiveTexture(GL_TEXTURE0);
1407 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1408
1409 for (int t = TEX_RGBA; t < NUM_TEX; t++) {
1410 /* Sprite component present? */
1411 if (t == TEX_RGBA && sprite[ZOOM_LVL_MIN].colours == SpriteComponent::Palette) continue;
1412 if (t == TEX_REMAP && !sprite[ZOOM_LVL_MIN].colours.Test(SpriteComponent::Palette)) continue;
1413
1414 /* Allocate texture. */
1415 _glGenTextures(1, &this->tex[t]);
1416 _glBindTexture(GL_TEXTURE_2D, this->tex[t]);
1417
1418 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
1419 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1420 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, levels - 1);
1421 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1422 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1423
1424 /* Set size. */
1425 for (int i = 0, w = this->dim.width, h = this->dim.height; i < levels; i++, w /= 2, h /= 2) {
1426 assert(w * h != 0);
1427 if (t == TEX_REMAP) {
1428 _glTexImage2D(GL_TEXTURE_2D, i, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1429 } else {
1430 _glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
1431 }
1432 }
1433 }
1434
1435 /* Upload texture data. */
1436 for (int i = 0; i < (sprite[ZOOM_LVL_MIN].type == SpriteType::Font ? 1 : ZOOM_LVL_END); i++) {
1437 this->Update(sprite[i].width, sprite[i].height, i, sprite[i].data);
1438 }
1439
1440 assert(_glGetError() == GL_NO_ERROR);
1441}
1442
1443OpenGLSprite::~OpenGLSprite()
1444{
1445 _glDeleteTextures(NUM_TEX, this->tex.data());
1446}
1447
1455void OpenGLSprite::Update(uint width, uint height, uint level, const SpriteLoader::CommonPixel * data)
1456{
1457 static ReusableBuffer<Colour> buf_rgba;
1458 static ReusableBuffer<uint8_t> buf_pal;
1459
1460 _glActiveTexture(GL_TEXTURE0);
1461 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1462 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1463
1464 if (this->tex[TEX_RGBA] != 0) {
1465 /* Unpack pixel data */
1466 size_t size = static_cast<size_t>(width) * height;
1467 Colour *rgba = buf_rgba.Allocate(size);
1468 for (size_t i = 0; i < size; i++) {
1469 rgba[i].r = data[i].r;
1470 rgba[i].g = data[i].g;
1471 rgba[i].b = data[i].b;
1472 rgba[i].a = data[i].a;
1473 }
1474
1475 _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_RGBA]);
1476 _glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, rgba);
1477 }
1478
1479 if (this->tex[TEX_REMAP] != 0) {
1480 /* Unpack and align pixel data. */
1481 size_t pitch = Align(width, 4);
1482
1483 uint8_t *pal = buf_pal.Allocate(pitch * height);
1484 const SpriteLoader::CommonPixel *row = data;
1485 for (uint y = 0; y < height; y++, pal += pitch, row += width) {
1486 for (uint x = 0; x < width; x++) {
1487 pal[x] = row[x].m;
1488 }
1489 }
1490
1491 _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_REMAP]);
1492 _glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, buf_pal.GetBuffer());
1493 }
1494
1495 assert(_glGetError() == GL_NO_ERROR);
1496}
1497
1504{
1505 Dimension sd = { (uint)UnScaleByZoomLower(this->dim.width, level), (uint)UnScaleByZoomLower(this->dim.height, level) };
1506 return sd;
1507}
1508
1514{
1515 _glActiveTexture(GL_TEXTURE0);
1516 _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_RGBA] != 0 ? this->tex[TEX_RGBA] : OpenGLSprite::dummy_tex[TEX_RGBA]);
1517 _glActiveTexture(GL_TEXTURE0 + 2);
1518 _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_REMAP] != 0 ? this->tex[TEX_REMAP] : OpenGLSprite::dummy_tex[TEX_REMAP]);
1519
1520 return this->tex[TEX_RGBA] != 0;
1521}
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:136
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
Size limited cache with a least recently used eviction strategy.
Definition lrucache.hpp:22
Tdata * Get(const Tkey key)
Get an item from the cache.
Definition lrucache.hpp:88
bool Contains(const Tkey key)
Test if a key is already contained in the cache.
Definition lrucache.hpp:44
void Insert(const Tkey key, std::unique_ptr< Tdata > &&item)
Insert a new data item with a specified key.
Definition lrucache.hpp:54
void Clear()
Clear the cache.
Definition lrucache.hpp:76
Platform-independent back-end class for OpenGL video drivers.
Definition opengl.h:27
GLint sprite_rgb_loc
Uniform location for RGB mode flag.
Definition opengl.h:58
void * anim_buffer
Pointer to the mapped animation buffer.
Definition opengl.h:44
GLuint remap_program
Shader program for blending and rendering a RGBA + remap texture.
Definition opengl.h:48
bool cursor_in_window
Cursor inside this window.
Definition opengl.h:66
void Paint()
Render video buffer to the screen.
Definition opengl.cpp:1037
GLuint pal_program
Shader program for rendering a paletted video buffer.
Definition opengl.h:39
void RenderOglSprite(OpenGLSprite *gl_sprite, PaletteID pal, int x, int y, ZoomLevel zoom)
Render a sprite to the back buffer.
Definition opengl.cpp:1275
std::vector< CursorSprite > cursor_sprites
Sprites comprising cursor.
Definition opengl.h:67
GLint remap_screen_loc
Uniform location for screen size.
Definition opengl.h:50
static OpenGLBackend * instance
Singleton instance pointer.
Definition opengl.h:29
uint8_t * GetAnimBuffer()
Get a pointer to the memory for the separate animation buffer.
Definition opengl.cpp:1168
void * GetVideoBuffer()
Get a pointer to the memory for the video driver to draw to.
Definition opengl.cpp:1146
bool persistent_mapping_supported
Persistent pixel buffer mapping supported.
Definition opengl.h:31
GLuint vid_texture
Texture handle for the video buffer texture.
Definition opengl.h:37
GLuint vao_quad
Vertex array object storing the rendering state for the fullscreen quad.
Definition opengl.h:40
GLint sprite_zoom_loc
Uniform location for sprite zoom.
Definition opengl.h:57
GLint remap_zoom_loc
Uniform location for sprite zoom.
Definition opengl.h:51
bool Resize(int w, int h, bool force=false)
Change the size of the drawing window and allocate matching resources.
Definition opengl.cpp:911
OpenGLBackend()
Construct OpenGL back-end class.
Definition opengl.cpp:487
static std::optional< std::string_view > Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
Create and initialize the singleton back-end class.
Definition opengl.cpp:465
void * vid_buffer
Pointer to the mapped video buffer.
Definition opengl.h:35
Sprite * Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override
Convert a sprite from the loader to our own format.
Definition opengl.cpp:1259
void UpdatePalette(const Colour *pal, uint first, uint length)
Update the stored palette.
Definition opengl.cpp:1023
GLuint anim_texture
Texture handle for the animation buffer texture.
Definition opengl.h:46
void InternalClearCursorCache()
Clear all cached cursor sprites.
Definition opengl.cpp:1125
GLuint sprite_program
Shader program for blending and rendering a sprite to the video buffer.
Definition opengl.h:54
void ReleaseAnimBuffer(const Rect &update_rect)
Update animation buffer texture after the animation buffer was filled.
Definition opengl.cpp:1229
GLuint vid_pbo
Pixel buffer object storing the memory used for the video driver to draw to.
Definition opengl.h:36
GLsync sync_anim_mapping
Sync object for the persistently mapped animation buffer.
Definition opengl.h:33
~OpenGLBackend()
Free allocated resources.
Definition opengl.cpp:494
GLuint vbo_quad
Vertex buffer with a fullscreen quad.
Definition opengl.h:41
bool clear_cursor_cache
A clear of the cursor cache is pending.
Definition opengl.h:63
GLint remap_rgb_loc
Uniform location for RGB mode flag.
Definition opengl.h:52
void ClearCursorCache()
Queue a request for cursor cache clear.
Definition opengl.cpp:1133
GLuint vid_program
Shader program for rendering a RGBA video buffer.
Definition opengl.h:38
GLuint pal_texture
Palette lookup texture.
Definition opengl.h:42
GLint remap_sprite_loc
Uniform location for sprite parameters.
Definition opengl.h:49
bool InitShaders()
Create all needed shader programs.
Definition opengl.cpp:802
void DrawMouseCursor()
Draw mouse cursor on screen.
Definition opengl.cpp:1069
LRUCache< SpriteID, OpenGLSprite > cursor_cache
Cache of encoded cursor sprites.
Definition opengl.h:61
Point cursor_pos
Cursor position.
Definition opengl.h:65
GLint sprite_crash_loc
Uniform location for crash remap mode flag.
Definition opengl.h:59
void ReleaseVideoBuffer(const Rect &update_rect)
Update video buffer texture after the video buffer was filled.
Definition opengl.cpp:1191
GLint sprite_sprite_loc
Uniform location for sprite parameters.
Definition opengl.h:55
PaletteID last_sprite_pal
Last uploaded remap palette.
Definition opengl.h:62
GLuint anim_pbo
Pixel buffer object storing the memory used for the animation buffer.
Definition opengl.h:45
GLsync sync_vid_mapping
Sync object for the persistently mapped video buffer.
Definition opengl.h:32
std::optional< std::string_view > Init(const Dimension &screen_res)
Check for the needed OpenGL functionality and allocate all resources.
Definition opengl.cpp:523
static void Destroy()
Free resources and destroy singleton back-end class.
Definition opengl.cpp:478
GLint sprite_screen_loc
Uniform location for screen size.
Definition opengl.h:56
void * AllocatePtr(size_t) override
Allocate memory for a sprite.
Definition opengl.cpp:1095
Class that encapsulates a RGBA texture together with a paletted remap texture.
Definition opengl.h:114
std::array< GLuint, NUM_TEX > tex
The texture objects.
Definition opengl.h:124
OpenGLSprite(const SpriteLoader::SpriteCollection &sprite)
Create an OpenGL sprite with a palette remap part.
Definition opengl.cpp:1398
bool BindTextures()
Bind textures for rendering this sprite.
Definition opengl.cpp:1513
@ TEX_RGBA
RGBA texture part.
Definition opengl.h:118
@ TEX_REMAP
Remap texture part.
Definition opengl.h:119
Dimension GetSize(ZoomLevel level) const
Query the sprite size at a certain zoom level.
Definition opengl.cpp:1503
static bool Create()
Create all common resources for sprite rendering.
Definition opengl.cpp:1325
static GLuint pal_pbo
Pixel buffer object for remap upload.
Definition opengl.h:132
static GLuint pal_identity
Identity texture mapping.
Definition opengl.h:130
static GLuint pal_tex
Texture for palette remap.
Definition opengl.h:131
int16_t y_offs
Number of pixels to shift the sprite downwards.
Definition opengl.h:126
static std::array< GLuint, NUM_TEX > dummy_tex
1x1 dummy textures to substitute for unused sprite components.
Definition opengl.h:1316
int16_t x_offs
Number of pixels to shift the sprite to the right.
Definition opengl.h:125
void Update(uint width, uint height, uint level, const SpriteLoader::CommonPixel *data)
Update a single mip-map level with new pixel data.
Definition opengl.cpp:1455
static void Destroy()
Free all common resources for sprite rendering.
Definition opengl.cpp:1386
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
const T * GetBuffer() const
Get the currently allocated buffer.
T * Allocate(size_t count)
Get buffer of at least count times T.
Interface for something that can allocate memory for a sprite.
std::array< Sprite, ZOOM_LVL_END > SpriteCollection
Type defining a collection of sprites, one for each zoom level.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Recolour
Recolour sprite.
@ Font
A sprite used for fonts.
@ Normal
The most basic (normal) sprite.
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
OpenGL video driver support.
bool IsOpenGLVersionAtLeast(uint8_t major, uint8_t minor)
Check if the current OpenGL version is equal or higher than a given one.
Definition opengl.cpp:205
static const char * _vertex_shader_sprite[]
Vertex shader that positions a sprite on screen.
static const char * _frag_shader_palette_150[]
GLSL 1.50 fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
static const char * _frag_shader_direct[]
Fragment shader that reads the fragment colour from a 32bpp texture.
static const char * _frag_shader_rgb_mask_blend[]
Fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
static const char * _frag_shader_palette[]
Fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
static const char * _frag_shader_rgb_mask_blend_150[]
GLSL 1.50 fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
static const char * _frag_shader_direct_150[]
GLSL 1.50 fragment shader that reads the fragment colour from a 32bpp texture.
static const char * _frag_shader_sprite_blend_150[]
GLSL 1.50 fragment shader that performs a palette lookup to read the colour from a sprite texture.
static const char * _frag_shader_sprite_blend[]
Fragment shader that performs a palette lookup to read the colour from a sprite texture.
static const char * _vertex_shader_sprite_150[]
GLSL 1.50 vertex shader that positions a sprite on screen.
void * GetRawSprite(SpriteID sprite, SpriteType type, SpriteAllocator *allocator, SpriteEncoder *encoder)
Reads a sprite (from disk or sprite cache).
@ Palette
Sprite has palette data.
static constexpr uint8_t PALETTE_WIDTH
number of bits of the sprite containing the recolour palette
Definition sprites.h:1538
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1609
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
Point pos
logical mouse position
Definition gfx_type.h:126
bool in_window
mouse inside this window, determines drawing logic
Definition gfx_type.h:148
Dimensions (a width and height) of a rectangle in 2D.
Specification of a rectangle with absolute coordinates of all edges.
A simple 2D vertex with just position and texture.
Definition opengl.cpp:123
Definition of a common pixel in OpenTTD's realm.
uint8_t m
Remap-channel.
uint8_t b
Blue-channel.
uint8_t r
Red-channel.
uint8_t g
Green-channel.
uint8_t a
Alpha-channel.
Data structure describing a sprite.
Definition spritecache.h:17
int UnScaleByZoomLower(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_MIN)
Definition zoom_func.h:67
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_MIN) When shifting right,...
Definition zoom_func.h:34
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:16
@ ZOOM_LVL_END
End for iteration.
Definition zoom_type.h:25
@ ZOOM_LVL_MIN
Minimum zoom level.
Definition zoom_type.h:41