OpenTTD Source 20261112-master-gbcbec5e63f
opengl.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
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"
32#include "../core/math_func.hpp"
33#include "../gfx_func.h"
34#include "../debug.h"
36#include "../spritecache.h"
37#include "../zoom_func.h"
39
41#include "../table/sprites.h"
42
43
44#include "../safeguards.h"
45
46
47/* Define function pointers of all OpenGL functions that we load dynamically. */
48
49#define GL(function) static decltype(&function) _ ## function
50
51GL(glGetString);
52GL(glGetIntegerv);
53GL(glGetError);
54GL(glDebugMessageControl);
55GL(glDebugMessageCallback);
56
57GL(glDisable);
58GL(glEnable);
59GL(glViewport);
60GL(glClear);
61GL(glClearColor);
62GL(glBlendFunc);
63GL(glDrawArrays);
64
65GL(glTexImage1D);
66GL(glTexImage2D);
67GL(glTexParameteri);
68GL(glTexSubImage1D);
69GL(glTexSubImage2D);
70GL(glBindTexture);
71GL(glDeleteTextures);
72GL(glGenTextures);
73GL(glPixelStorei);
74
75GL(glActiveTexture);
76
77GL(glGenBuffers);
78GL(glDeleteBuffers);
79GL(glBindBuffer);
80GL(glBufferData);
81GL(glBufferSubData);
82GL(glMapBuffer);
83GL(glUnmapBuffer);
84GL(glClearBufferSubData);
85
86GL(glBufferStorage);
87GL(glMapBufferRange);
88GL(glClientWaitSync);
89GL(glFenceSync);
90GL(glDeleteSync);
91
92GL(glGenVertexArrays);
93GL(glDeleteVertexArrays);
94GL(glBindVertexArray);
95
96GL(glCreateProgram);
97GL(glDeleteProgram);
98GL(glLinkProgram);
99GL(glUseProgram);
100GL(glGetProgramiv);
101GL(glGetProgramInfoLog);
102GL(glCreateShader);
103GL(glDeleteShader);
104GL(glShaderSource);
105GL(glCompileShader);
106GL(glAttachShader);
107GL(glGetShaderiv);
108GL(glGetShaderInfoLog);
109GL(glGetUniformLocation);
110GL(glUniform1i);
111GL(glUniform1f);
112GL(glUniform2f);
113GL(glUniform4f);
114
115GL(glGetAttribLocation);
116GL(glEnableVertexAttribArray);
117GL(glDisableVertexAttribArray);
118GL(glVertexAttribPointer);
119GL(glBindFragDataLocation);
120
121#undef GL
122
123
126 float x, y;
127 float u, v;
128};
129
131static const int MAX_CACHED_CURSORS = 48;
132
133/* static */ OpenGLBackend *OpenGLBackend::instance = nullptr;
134
135GetOGLProcAddressProc GetOGLProcAddress;
136
137static std::optional<std::string_view> GlGetString(GLenum name)
138{
139 auto str = reinterpret_cast<const char *>(_glGetString(name));
140 if (str == nullptr) return {};
141 return str;
142}
143
151bool HasStringInExtensionList(std::string_view string, std::string_view substring)
152{
153 StringConsumer consumer{string};
154 while (consumer.AnyBytesLeft()) {
155 if (substring == consumer.ReadUntil(" ", StringConsumer::SKIP_ALL_SEPARATORS)) return true;
156 }
157
158 return false;
159}
160
166static bool IsOpenGLExtensionSupported(std::string_view 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 = reinterpret_cast<const char *>(glGetStringi(GL_EXTENSIONS, i));
185 if (entry != nullptr && entry == extension) return true;
186 }
187 } else if (auto str = GlGetString(GL_EXTENSIONS); str.has_value()) {
188 /* Old style: A single, space-delimited string for all extensions. */
189 return HasStringInExtensionList(*str, extension);
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
229{
230 if (!BindGLProc(_glGetString, "glGetString")) return false;
231 if (!BindGLProc(_glGetIntegerv, "glGetIntegerv")) return false;
232 if (!BindGLProc(_glGetError, "glGetError")) return false;
233
234 return true;
235}
236
242{
243 if (!BindGLProc(_glDisable, "glDisable")) return false;
244 if (!BindGLProc(_glEnable, "glEnable")) return false;
245 if (!BindGLProc(_glViewport, "glViewport")) return false;
246 if (!BindGLProc(_glTexImage1D, "glTexImage1D")) return false;
247 if (!BindGLProc(_glTexImage2D, "glTexImage2D")) return false;
248 if (!BindGLProc(_glTexParameteri, "glTexParameteri")) return false;
249 if (!BindGLProc(_glTexSubImage1D, "glTexSubImage1D")) return false;
250 if (!BindGLProc(_glTexSubImage2D, "glTexSubImage2D")) return false;
251 if (!BindGLProc(_glBindTexture, "glBindTexture")) return false;
252 if (!BindGLProc(_glDeleteTextures, "glDeleteTextures")) return false;
253 if (!BindGLProc(_glGenTextures, "glGenTextures")) return false;
254 if (!BindGLProc(_glPixelStorei, "glPixelStorei")) return false;
255 if (!BindGLProc(_glClear, "glClear")) return false;
256 if (!BindGLProc(_glClearColor, "glClearColor")) return false;
257 if (!BindGLProc(_glBlendFunc, "glBlendFunc")) return false;
258 if (!BindGLProc(_glDrawArrays, "glDrawArrays")) return false;
259
260 return true;
261}
262
268{
269 if (IsOpenGLVersionAtLeast(1, 3)) {
270 if (!BindGLProc(_glActiveTexture, "glActiveTexture")) return false;
271 } else {
272 if (!BindGLProc(_glActiveTexture, "glActiveTextureARB")) return false;
273 }
274
275 return true;
276}
277
282static bool BindVBOExtension()
283{
284 if (IsOpenGLVersionAtLeast(1, 5)) {
285 if (!BindGLProc(_glGenBuffers, "glGenBuffers")) return false;
286 if (!BindGLProc(_glDeleteBuffers, "glDeleteBuffers")) return false;
287 if (!BindGLProc(_glBindBuffer, "glBindBuffer")) return false;
288 if (!BindGLProc(_glBufferData, "glBufferData")) return false;
289 if (!BindGLProc(_glBufferSubData, "glBufferSubData")) return false;
290 if (!BindGLProc(_glMapBuffer, "glMapBuffer")) return false;
291 if (!BindGLProc(_glUnmapBuffer, "glUnmapBuffer")) return false;
292 } else {
293 if (!BindGLProc(_glGenBuffers, "glGenBuffersARB")) return false;
294 if (!BindGLProc(_glDeleteBuffers, "glDeleteBuffersARB")) return false;
295 if (!BindGLProc(_glBindBuffer, "glBindBufferARB")) return false;
296 if (!BindGLProc(_glBufferData, "glBufferDataARB")) return false;
297 if (!BindGLProc(_glBufferSubData, "glBufferSubDataARB")) return false;
298 if (!BindGLProc(_glMapBuffer, "glMapBufferARB")) return false;
299 if (!BindGLProc(_glUnmapBuffer, "glUnmapBufferARB")) return false;
300 }
301
302 if (IsOpenGLVersionAtLeast(4, 3) || IsOpenGLExtensionSupported("GL_ARB_clear_buffer_object")) {
303 BindGLProc(_glClearBufferSubData, "glClearBufferSubData");
304 } else {
305 _glClearBufferSubData = nullptr;
306 }
307
308 return true;
309}
310
315static bool BindVBAExtension()
316{
317 /* The APPLE and ARB variants have different semantics (that don't matter for us).
318 * Successfully getting pointers to one variant doesn't mean it is supported for
319 * the current context. Always check the extension strings as well. */
320 if (IsOpenGLVersionAtLeast(3, 0) || IsOpenGLExtensionSupported("GL_ARB_vertex_array_object")) {
321 if (!BindGLProc(_glGenVertexArrays, "glGenVertexArrays")) return false;
322 if (!BindGLProc(_glDeleteVertexArrays, "glDeleteVertexArrays")) return false;
323 if (!BindGLProc(_glBindVertexArray, "glBindVertexArray")) return false;
324 } else if (IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object")) {
325 if (!BindGLProc(_glGenVertexArrays, "glGenVertexArraysAPPLE")) return false;
326 if (!BindGLProc(_glDeleteVertexArrays, "glDeleteVertexArraysAPPLE")) return false;
327 if (!BindGLProc(_glBindVertexArray, "glBindVertexArrayAPPLE")) return false;
328 }
329
330 return true;
331}
332
338{
339 if (IsOpenGLVersionAtLeast(2, 0)) {
340 if (!BindGLProc(_glCreateProgram, "glCreateProgram")) return false;
341 if (!BindGLProc(_glDeleteProgram, "glDeleteProgram")) return false;
342 if (!BindGLProc(_glLinkProgram, "glLinkProgram")) return false;
343 if (!BindGLProc(_glUseProgram, "glUseProgram")) return false;
344 if (!BindGLProc(_glGetProgramiv, "glGetProgramiv")) return false;
345 if (!BindGLProc(_glGetProgramInfoLog, "glGetProgramInfoLog")) return false;
346 if (!BindGLProc(_glCreateShader, "glCreateShader")) return false;
347 if (!BindGLProc(_glDeleteShader, "glDeleteShader")) return false;
348 if (!BindGLProc(_glShaderSource, "glShaderSource")) return false;
349 if (!BindGLProc(_glCompileShader, "glCompileShader")) return false;
350 if (!BindGLProc(_glAttachShader, "glAttachShader")) return false;
351 if (!BindGLProc(_glGetShaderiv, "glGetShaderiv")) return false;
352 if (!BindGLProc(_glGetShaderInfoLog, "glGetShaderInfoLog")) return false;
353 if (!BindGLProc(_glGetUniformLocation, "glGetUniformLocation")) return false;
354 if (!BindGLProc(_glUniform1i, "glUniform1i")) return false;
355 if (!BindGLProc(_glUniform1f, "glUniform1f")) return false;
356 if (!BindGLProc(_glUniform2f, "glUniform2f")) return false;
357 if (!BindGLProc(_glUniform4f, "glUniform4f")) return false;
358
359 if (!BindGLProc(_glGetAttribLocation, "glGetAttribLocation")) return false;
360 if (!BindGLProc(_glEnableVertexAttribArray, "glEnableVertexAttribArray")) return false;
361 if (!BindGLProc(_glDisableVertexAttribArray, "glDisableVertexAttribArray")) return false;
362 if (!BindGLProc(_glVertexAttribPointer, "glVertexAttribPointer")) return false;
363 } else {
364 /* In the ARB extension programs and shaders are in the same object space. */
365 if (!BindGLProc(_glCreateProgram, "glCreateProgramObjectARB")) return false;
366 if (!BindGLProc(_glDeleteProgram, "glDeleteObjectARB")) return false;
367 if (!BindGLProc(_glLinkProgram, "glLinkProgramARB")) return false;
368 if (!BindGLProc(_glUseProgram, "glUseProgramObjectARB")) return false;
369 if (!BindGLProc(_glGetProgramiv, "glGetObjectParameterivARB")) return false;
370 if (!BindGLProc(_glGetProgramInfoLog, "glGetInfoLogARB")) return false;
371 if (!BindGLProc(_glCreateShader, "glCreateShaderObjectARB")) return false;
372 if (!BindGLProc(_glDeleteShader, "glDeleteObjectARB")) return false;
373 if (!BindGLProc(_glShaderSource, "glShaderSourceARB")) return false;
374 if (!BindGLProc(_glCompileShader, "glCompileShaderARB")) return false;
375 if (!BindGLProc(_glAttachShader, "glAttachObjectARB")) return false;
376 if (!BindGLProc(_glGetShaderiv, "glGetObjectParameterivARB")) return false;
377 if (!BindGLProc(_glGetShaderInfoLog, "glGetInfoLogARB")) return false;
378 if (!BindGLProc(_glGetUniformLocation, "glGetUniformLocationARB")) return false;
379 if (!BindGLProc(_glUniform1i, "glUniform1iARB")) return false;
380 if (!BindGLProc(_glUniform1f, "glUniform1fARB")) return false;
381 if (!BindGLProc(_glUniform2f, "glUniform2fARB")) return false;
382 if (!BindGLProc(_glUniform4f, "glUniform4fARB")) return false;
383
384 if (!BindGLProc(_glGetAttribLocation, "glGetAttribLocationARB")) return false;
385 if (!BindGLProc(_glEnableVertexAttribArray, "glEnableVertexAttribArrayARB")) return false;
386 if (!BindGLProc(_glDisableVertexAttribArray, "glDisableVertexAttribArrayARB")) return false;
387 if (!BindGLProc(_glVertexAttribPointer, "glVertexAttribPointerARB")) return false;
388 }
389
390 /* Bind functions only needed when using GLSL 1.50 shaders. */
391 if (IsOpenGLVersionAtLeast(3, 0)) {
392 BindGLProc(_glBindFragDataLocation, "glBindFragDataLocation");
393 } else if (IsOpenGLExtensionSupported("GL_EXT_gpu_shader4")) {
394 BindGLProc(_glBindFragDataLocation, "glBindFragDataLocationEXT");
395 } else {
396 _glBindFragDataLocation = nullptr;
397 }
398
399 return true;
400}
401
407{
408 /* Optional functions for persistent buffer mapping. */
409 if (IsOpenGLVersionAtLeast(3, 0)) {
410 if (!BindGLProc(_glMapBufferRange, "glMapBufferRange")) return false;
411 }
412 if (IsOpenGLVersionAtLeast(4, 4) || IsOpenGLExtensionSupported("GL_ARB_buffer_storage")) {
413 if (!BindGLProc(_glBufferStorage, "glBufferStorage")) return false;
414 }
415#ifndef NO_GL_BUFFER_SYNC
416 if (IsOpenGLVersionAtLeast(3, 2) || IsOpenGLExtensionSupported("GL_ARB_sync")) {
417 if (!BindGLProc(_glClientWaitSync, "glClientWaitSync")) return false;
418 if (!BindGLProc(_glFenceSync, "glFenceSync")) return false;
419 if (!BindGLProc(_glDeleteSync, "glDeleteSync")) return false;
420 }
421#endif
422
423 return true;
424}
425
432void APIENTRY DebugOutputCallback(GLenum, GLenum type, GLuint, GLenum severity, GLsizei, const GLchar *message, const void *)
433{
434 /* Make severity human readable. */
435 std::string_view severity_str;
436 switch (severity) {
437 case GL_DEBUG_SEVERITY_HIGH: severity_str = "high"; break;
438 case GL_DEBUG_SEVERITY_MEDIUM: severity_str = "medium"; break;
439 case GL_DEBUG_SEVERITY_LOW: severity_str = "low"; break;
440 }
441
442 /* Make type human readable.*/
443 std::string_view type_str = "Other";
444 switch (type) {
445 case GL_DEBUG_TYPE_ERROR: type_str = "Error"; break;
446 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: type_str = "Deprecated"; break;
447 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: type_str = "Undefined behaviour"; break;
448 case GL_DEBUG_TYPE_PERFORMANCE: type_str = "Performance"; break;
449 case GL_DEBUG_TYPE_PORTABILITY: type_str = "Portability"; break;
450 }
451
452 Debug(Facility::Driver, Severity::Debug2, "OpenGL: {} ({}) - {}", type_str, severity_str, message);
453}
454
457{
458#ifndef NO_DEBUG_MESSAGES
460
461 if (IsOpenGLVersionAtLeast(4, 3)) {
462 BindGLProc(_glDebugMessageControl, "glDebugMessageControl");
463 BindGLProc(_glDebugMessageCallback, "glDebugMessageCallback");
464 } else if (IsOpenGLExtensionSupported("GL_ARB_debug_output")) {
465 BindGLProc(_glDebugMessageControl, "glDebugMessageControlARB");
466 BindGLProc(_glDebugMessageCallback, "glDebugMessageCallbackARB");
467 }
468
469 if (_glDebugMessageControl != nullptr && _glDebugMessageCallback != nullptr) {
470 /* Enable debug output. As synchronous debug output costs performance, we only enable it with a high debug level. */
471 _glEnable(GL_DEBUG_OUTPUT);
472 if (IsVisibleSeverity(Facility::Driver, Severity::Trace2)) _glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
473
474 _glDebugMessageCallback(&DebugOutputCallback, nullptr);
475 /* Enable all messages on highest debug level.*/
476 _glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, IsVisibleSeverity(Facility::Driver, Severity::Trace3) ? GL_TRUE : GL_FALSE);
477 /* Get debug messages for errors and undefined/deprecated behaviour. */
478 _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
479 _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
480 _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
481 }
482#endif
483}
484
491/* static */ std::optional<std::string_view> OpenGLBackend::Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
492{
494
495 GetOGLProcAddress = get_proc;
496
498 return OpenGLBackend::instance->Init(screen_res);
499}
500
504/* static */ void OpenGLBackend::Destroy()
505{
507 OpenGLBackend::instance = nullptr;
508}
509
516
521{
522 if (_glDeleteProgram != nullptr) {
523 _glDeleteProgram(this->remap_program);
524 _glDeleteProgram(this->vid_program);
525 _glDeleteProgram(this->pal_program);
526 _glDeleteProgram(this->sprite_program);
527 }
528 if (_glDeleteVertexArrays != nullptr) _glDeleteVertexArrays(1, &this->vao_quad);
529 if (_glDeleteBuffers != nullptr) {
530 _glDeleteBuffers(1, &this->vbo_quad);
531 _glDeleteBuffers(1, &this->vid_pbo);
532 _glDeleteBuffers(1, &this->anim_pbo);
533 }
534 if (_glDeleteTextures != nullptr) {
537
538 _glDeleteTextures(1, &this->vid_texture);
539 _glDeleteTextures(1, &this->anim_texture);
540 _glDeleteTextures(1, &this->pal_texture);
541 }
542}
543
544static std::tuple<uint8_t, uint8_t> DecodeVersion(std::string_view ver)
545{
546 StringConsumer consumer{ver};
547 int major = consumer.ReadIntegerBase<uint8_t>(10);
548 if (consumer.ReadIf(".")) return {major, consumer.ReadIntegerBase<uint8_t>(10)};
549 return {major, 0};
550}
551
557std::optional<std::string_view> OpenGLBackend::Init(const Dimension &screen_res)
558{
559 if (!BindBasicInfoProcs()) return "OpenGL not supported";
560
561 /* Always query the supported OpenGL version as the current context might have changed. */
562 auto ver = GlGetString(GL_VERSION);
563 auto vend = GlGetString(GL_VENDOR);
564 auto renderer = GlGetString(GL_RENDERER);
565
566 if (!ver.has_value() || !vend.has_value() || !renderer.has_value()) return "OpenGL not supported";
567
568 Debug(Facility::Driver, Severity::Error, "OpenGL driver: {} - {} ({})", *vend, *renderer, *ver);
569
570#ifndef GL_ALLOW_SOFTWARE_RENDERER
571 /* Don't use MESA software rendering backends as they are slower than
572 * just using a non-OpenGL video driver. */
573 if (renderer->starts_with("llvmpipe") || renderer->starts_with("softpipe")) return "Software renderer detected, not using OpenGL";
574#endif
575
576 std::tie(_gl_major_ver, _gl_minor_ver) = DecodeVersion(*ver);
577
578#ifdef _WIN32
579 /* Old drivers on Windows (especially if made by Intel) seem to be
580 * unstable, so cull the oldest stuff here. */
581 if (!IsOpenGLVersionAtLeast(3, 2)) return "Need at least OpenGL version 3.2 on Windows";
582#endif
583
584 if (!BindBasicOpenGLProcs()) return "Failed to bind basic OpenGL functions.";
585
587
588 /* OpenGL 1.3 is the absolute minimum. */
589 if (!IsOpenGLVersionAtLeast(1, 3)) return "OpenGL version >= 1.3 required";
590 /* Check for non-power-of-two texture support. */
591 if (!IsOpenGLVersionAtLeast(2, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_non_power_of_two")) return "Non-power-of-two textures not supported";
592 /* Check for single element texture formats. */
593 if (!IsOpenGLVersionAtLeast(3, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_rg")) return "Single element texture formats not supported";
594 if (!BindTextureExtensions()) return "Failed to bind texture extension functions";
595 /* Check for vertex buffer objects. */
596 if (!IsOpenGLVersionAtLeast(1, 5) && !IsOpenGLExtensionSupported("ARB_vertex_buffer_object")) return "Vertex buffer objects not supported";
597 if (!BindVBOExtension()) return "Failed to bind VBO extension functions";
598 /* Check for pixel buffer objects. */
599 if (!IsOpenGLVersionAtLeast(2, 1) && !IsOpenGLExtensionSupported("GL_ARB_pixel_buffer_object")) return "Pixel buffer objects not supported";
600 /* Check for vertex array objects. */
601 if (!IsOpenGLVersionAtLeast(3, 0) && (!IsOpenGLExtensionSupported("GL_ARB_vertex_array_object") || !IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object"))) return "Vertex array objects not supported";
602 if (!BindVBAExtension()) return "Failed to bind VBA extension functions";
603 /* Check for shader objects. */
604 if (!IsOpenGLVersionAtLeast(2, 0) && (!IsOpenGLExtensionSupported("GL_ARB_shader_objects") || !IsOpenGLExtensionSupported("GL_ARB_fragment_shader") || !IsOpenGLExtensionSupported("GL_ARB_vertex_shader"))) return "No shader support";
605 if (!BindShaderExtensions()) return "Failed to bind shader extension functions";
606 if (IsOpenGLVersionAtLeast(3, 2) && _glBindFragDataLocation == nullptr) return "OpenGL claims to support version 3.2 but doesn't have glBindFragDataLocation";
607
609#ifndef NO_GL_BUFFER_SYNC
611#endif
612
614 Debug(Facility::Driver, Severity::Error, "OpenGL claims to support persistent buffer mapping but doesn't export all functions, not using persistent mapping.");
615 this->persistent_mapping_supported = false;
616 }
617 if (this->persistent_mapping_supported) Debug(Facility::Driver, Severity::Notice, "OpenGL: Using persistent buffer mapping");
618
619 /* Check maximum texture size against screen resolution. */
620 GLint max_tex_size = 0;
621 _glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
622 if (std::max(screen_res.width, screen_res.height) > (uint)max_tex_size) return "Max supported texture size is too small";
623
624 /* Check available texture units. */
625 GLint max_tex_units = 0;
626 _glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_tex_units);
627 if (max_tex_units < 4) return "Not enough simultaneous textures supported";
628
629 Debug(Facility::Driver, Severity::Warning, "OpenGL shading language version: {}, texture units = {}", GlGetString(GL_SHADING_LANGUAGE_VERSION).value_or("Unknown version"), max_tex_units);
630
631 if (!this->InitShaders()) return "Failed to initialize shaders";
632
633 /* Setup video buffer texture. */
634 _glGenTextures(1, &this->vid_texture);
635 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
636 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
637 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
638 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
639 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
640 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
641 _glBindTexture(GL_TEXTURE_2D, 0);
642 if (_glGetError() != GL_NO_ERROR) return "Can't generate video buffer texture";
643
644 /* Setup video buffer texture. */
645 _glGenTextures(1, &this->anim_texture);
646 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
647 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
648 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
649 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
650 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
651 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
652 _glBindTexture(GL_TEXTURE_2D, 0);
653 if (_glGetError() != GL_NO_ERROR) return "Can't generate animation buffer texture";
654
655 /* Setup palette texture. */
656 _glGenTextures(1, &this->pal_texture);
657 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
658 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
659 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
660 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
661 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
662 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
663 _glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA8, 256, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
664 _glBindTexture(GL_TEXTURE_1D, 0);
665 if (_glGetError() != GL_NO_ERROR) return "Can't generate palette lookup texture";
666
667 /* Bind uniforms in rendering shader program. */
668 GLint tex_location = _glGetUniformLocation(this->vid_program, "colour_tex");
669 GLint palette_location = _glGetUniformLocation(this->vid_program, "palette");
670 GLint sprite_location = _glGetUniformLocation(this->vid_program, "sprite");
671 GLint screen_location = _glGetUniformLocation(this->vid_program, "screen");
672 _glUseProgram(this->vid_program);
673 _glUniform1i(tex_location, 0); // Texture unit 0.
674 _glUniform1i(palette_location, 1); // Texture unit 1.
675 /* Values that result in no transform. */
676 _glUniform4f(sprite_location, 0.0f, 0.0f, 1.0f, 1.0f);
677 _glUniform2f(screen_location, 1.0f, 1.0f);
678
679 /* Bind uniforms in palette rendering shader program. */
680 tex_location = _glGetUniformLocation(this->pal_program, "colour_tex");
681 palette_location = _glGetUniformLocation(this->pal_program, "palette");
682 sprite_location = _glGetUniformLocation(this->pal_program, "sprite");
683 screen_location = _glGetUniformLocation(this->pal_program, "screen");
684 _glUseProgram(this->pal_program);
685 _glUniform1i(tex_location, 0); // Texture unit 0.
686 _glUniform1i(palette_location, 1); // Texture unit 1.
687 _glUniform4f(sprite_location, 0.0f, 0.0f, 1.0f, 1.0f);
688 _glUniform2f(screen_location, 1.0f, 1.0f);
689
690 /* Bind uniforms in remap shader program. */
691 tex_location = _glGetUniformLocation(this->remap_program, "colour_tex");
692 palette_location = _glGetUniformLocation(this->remap_program, "palette");
693 GLint remap_location = _glGetUniformLocation(this->remap_program, "remap_tex");
694 this->remap_sprite_loc = _glGetUniformLocation(this->remap_program, "sprite");
695 this->remap_screen_loc = _glGetUniformLocation(this->remap_program, "screen");
696 this->remap_zoom_loc = _glGetUniformLocation(this->remap_program, "zoom");
697 this->remap_rgb_loc = _glGetUniformLocation(this->remap_program, "rgb");
698 _glUseProgram(this->remap_program);
699 _glUniform1i(tex_location, 0); // Texture unit 0.
700 _glUniform1i(palette_location, 1); // Texture unit 1.
701 _glUniform1i(remap_location, 2); // Texture unit 2.
702
703 /* Bind uniforms in sprite shader program. */
704 tex_location = _glGetUniformLocation(this->sprite_program, "colour_tex");
705 palette_location = _glGetUniformLocation(this->sprite_program, "palette");
706 remap_location = _glGetUniformLocation(this->sprite_program, "remap_tex");
707 GLint pal_location = _glGetUniformLocation(this->sprite_program, "pal");
708 this->sprite_sprite_loc = _glGetUniformLocation(this->sprite_program, "sprite");
709 this->sprite_screen_loc = _glGetUniformLocation(this->sprite_program, "screen");
710 this->sprite_zoom_loc = _glGetUniformLocation(this->sprite_program, "zoom");
711 this->sprite_rgb_loc = _glGetUniformLocation(this->sprite_program, "rgb");
712 this->sprite_crash_loc = _glGetUniformLocation(this->sprite_program, "crash");
713 _glUseProgram(this->sprite_program);
714 _glUniform1i(tex_location, 0); // Texture unit 0.
715 _glUniform1i(palette_location, 1); // Texture unit 1.
716 _glUniform1i(remap_location, 2); // Texture unit 2.
717 _glUniform1i(pal_location, 3); // Texture unit 3.
718 (void)_glGetError(); // Clear errors.
719
720 /* Create pixel buffer object as video buffer storage. */
721 _glGenBuffers(1, &this->vid_pbo);
722 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
723 _glGenBuffers(1, &this->anim_pbo);
724 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
725 if (_glGetError() != GL_NO_ERROR) return "Can't allocate pixel buffer for video buffer";
726
727 /* Prime vertex buffer with a full-screen quad and store
728 * the corresponding state in a vertex array object. */
729 static const Simple2DVertex vert_array[] = {
730 /* x y u v */
731 { 1.f, -1.f, 1.f, 1.f },
732 { 1.f, 1.f, 1.f, 0.f },
733 { -1.f, -1.f, 0.f, 1.f },
734 { -1.f, 1.f, 0.f, 0.f },
735 };
736
737 /* Create VAO. */
738 _glGenVertexArrays(1, &this->vao_quad);
739 _glBindVertexArray(this->vao_quad);
740
741 /* Create and fill VBO. */
742 _glGenBuffers(1, &this->vbo_quad);
743 _glBindBuffer(GL_ARRAY_BUFFER, this->vbo_quad);
744 _glBufferData(GL_ARRAY_BUFFER, sizeof(vert_array), vert_array, GL_STATIC_DRAW);
745 if (_glGetError() != GL_NO_ERROR) return "Can't generate VBO for fullscreen quad";
746
747 /* Set vertex state. */
748 GLint loc_position = _glGetAttribLocation(this->vid_program, "position");
749 GLint colour_position = _glGetAttribLocation(this->vid_program, "colour_uv");
750 _glEnableVertexAttribArray(loc_position);
751 _glEnableVertexAttribArray(colour_position);
752 _glVertexAttribPointer(loc_position, 2, GL_FLOAT, GL_FALSE, sizeof(Simple2DVertex), (GLvoid *)offsetof(Simple2DVertex, x));
753 _glVertexAttribPointer(colour_position, 2, GL_FLOAT, GL_FALSE, sizeof(Simple2DVertex), (GLvoid *)offsetof(Simple2DVertex, u));
754 _glBindVertexArray(0);
755
756 /* Create resources for sprite rendering. */
757 if (!OpenGLSprite::Create()) return "Failed to create sprite rendering resources";
758
759 this->PrepareContext();
760 (void)_glGetError(); // Clear errors.
761
762 return std::nullopt;
763}
764
765void OpenGLBackend::PrepareContext()
766{
767 _glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
768 _glDisable(GL_DEPTH_TEST);
769 /* Enable alpha blending using the src alpha factor. */
770 _glEnable(GL_BLEND);
771 _glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
772}
773
774std::string OpenGLBackend::GetDriverName()
775{
776 auto renderer = GlGetString(GL_RENDERER);
777 auto version = GlGetString(GL_VERSION);
778 /* Skipping GL_VENDOR as it tends to be "obvious" from the renderer and version data, and just makes the string pointlessly longer */
779 return fmt::format("{}, {}", renderer.value_or("Unknown renderer"), version.value_or("Unknown version"));
780}
781
787static bool VerifyShader(GLuint shader)
788{
789 static ReusableBuffer<char> log_buf;
790
791 GLint result = GL_FALSE;
792 _glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
793
794 /* Output log if there is one. */
795 GLint log_len = 0;
796 _glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
797 if (log_len > 0) {
798 _glGetShaderInfoLog(shader, log_len, nullptr, log_buf.Allocate(log_len));
799 Debug(Facility::Driver, result != GL_TRUE ? Severity::Critical : Severity::Warning, "{}", log_buf.GetBuffer()); // Always print on failure.
800 }
801
802 return result == GL_TRUE;
803}
804
810static bool VerifyProgram(GLuint program)
811{
812 static ReusableBuffer<char> log_buf;
813
814 GLint result = GL_FALSE;
815 _glGetProgramiv(program, GL_LINK_STATUS, &result);
816
817 /* Output log if there is one. */
818 GLint log_len = 0;
819 _glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_len);
820 if (log_len > 0) {
821 _glGetProgramInfoLog(program, log_len, nullptr, log_buf.Allocate(log_len));
822 Debug(Facility::Driver, result != GL_TRUE ? Severity::Critical : Severity::Warning, "{}", log_buf.GetBuffer()); // Always print on failure.
823 }
824
825 return result == GL_TRUE;
826}
827
833{
834 auto ver = GlGetString(GL_SHADING_LANGUAGE_VERSION);
835 if (!ver.has_value()) return false;
836
837 auto [glsl_major, glsl_minor] = DecodeVersion(*ver);
838
839 bool glsl_150 = (IsOpenGLVersionAtLeast(3, 2) || glsl_major > 1 || (glsl_major == 1 && glsl_minor >= 5)) && _glBindFragDataLocation != nullptr;
840
841 /* Create vertex shader. */
842 GLuint vert_shader = _glCreateShader(GL_VERTEX_SHADER);
843 _glShaderSource(vert_shader, glsl_150 ? lengthof(_vertex_shader_sprite_150) : lengthof(_vertex_shader_sprite), glsl_150 ? _vertex_shader_sprite_150 : _vertex_shader_sprite, nullptr);
844 _glCompileShader(vert_shader);
845 if (!VerifyShader(vert_shader)) return false;
846
847 /* Create fragment shader for plain RGBA. */
848 GLuint frag_shader_rgb = _glCreateShader(GL_FRAGMENT_SHADER);
849 _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);
850 _glCompileShader(frag_shader_rgb);
851 if (!VerifyShader(frag_shader_rgb)) return false;
852
853 /* Create fragment shader for paletted only. */
854 GLuint frag_shader_pal = _glCreateShader(GL_FRAGMENT_SHADER);
855 _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);
856 _glCompileShader(frag_shader_pal);
857 if (!VerifyShader(frag_shader_pal)) return false;
858
859 /* Sprite remap fragment shader. */
860 GLuint remap_shader = _glCreateShader(GL_FRAGMENT_SHADER);
862 _glCompileShader(remap_shader);
863 if (!VerifyShader(remap_shader)) return false;
864
865 /* Sprite fragment shader. */
866 GLuint sprite_shader = _glCreateShader(GL_FRAGMENT_SHADER);
868 _glCompileShader(sprite_shader);
869 if (!VerifyShader(sprite_shader)) return false;
870
871 /* Link shaders to program. */
872 this->vid_program = _glCreateProgram();
873 _glAttachShader(this->vid_program, vert_shader);
874 _glAttachShader(this->vid_program, frag_shader_rgb);
875
876 this->pal_program = _glCreateProgram();
877 _glAttachShader(this->pal_program, vert_shader);
878 _glAttachShader(this->pal_program, frag_shader_pal);
879
880 this->remap_program = _glCreateProgram();
881 _glAttachShader(this->remap_program, vert_shader);
882 _glAttachShader(this->remap_program, remap_shader);
883
884 this->sprite_program = _glCreateProgram();
885 _glAttachShader(this->sprite_program, vert_shader);
886 _glAttachShader(this->sprite_program, sprite_shader);
887
888 if (glsl_150) {
889 /* Bind fragment shader outputs. */
890 _glBindFragDataLocation(this->vid_program, 0, "colour");
891 _glBindFragDataLocation(this->pal_program, 0, "colour");
892 _glBindFragDataLocation(this->remap_program, 0, "colour");
893 _glBindFragDataLocation(this->sprite_program, 0, "colour");
894 }
895
896 _glLinkProgram(this->vid_program);
897 if (!VerifyProgram(this->vid_program)) return false;
898
899 _glLinkProgram(this->pal_program);
900 if (!VerifyProgram(this->pal_program)) return false;
901
902 _glLinkProgram(this->remap_program);
903 if (!VerifyProgram(this->remap_program)) return false;
904
905 _glLinkProgram(this->sprite_program);
906 if (!VerifyProgram(this->sprite_program)) return false;
907
908 _glDeleteShader(vert_shader);
909 _glDeleteShader(frag_shader_rgb);
910 _glDeleteShader(frag_shader_pal);
911 _glDeleteShader(remap_shader);
912 _glDeleteShader(sprite_shader);
913
914 return true;
915}
916
923template <class T>
924static void ClearPixelBuffer(size_t len, T data)
925{
926 T *buf = reinterpret_cast<T *>(_glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE));
927 for (size_t i = 0; i < len; i++) {
928 *buf++ = data;
929 }
930 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
931}
932
940bool OpenGLBackend::Resize(int w, int h, bool force)
941{
942 if (!force && _screen.width == w && _screen.height == h) return false;
943
945 int pitch = Align(w, 4);
946 size_t line_pixel_count = static_cast<size_t>(pitch) * h;
947
948 _glViewport(0, 0, w, h);
949
950 _glPixelStorei(GL_UNPACK_ROW_LENGTH, pitch);
951
952 this->vid_buffer = nullptr;
954 _glDeleteBuffers(1, &this->vid_pbo);
955 _glGenBuffers(1, &this->vid_pbo);
956 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
957 _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);
958 } else {
959 /* Re-allocate video buffer texture and backing store. */
960 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
961 _glBufferData(GL_PIXEL_UNPACK_BUFFER, line_pixel_count * bpp / 8, nullptr, GL_DYNAMIC_DRAW);
962 }
963
964 if (bpp == 32) {
965 /* Initialize backing store alpha to opaque for 32bpp modes. */
966 Colour black(0, 0, 0);
967 if (_glClearBufferSubData != nullptr) {
968 _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);
969 } else {
970 ClearPixelBuffer<uint32_t>(line_pixel_count, black.data);
971 }
972 } else if (bpp == 8) {
973 if (_glClearBufferSubData != nullptr) {
974 uint8_t b = 0;
975 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_R8, 0, line_pixel_count, GL_RED, GL_UNSIGNED_BYTE, &b);
976 } else {
977 ClearPixelBuffer<uint8_t>(line_pixel_count, 0);
978 }
979 }
980
981 _glActiveTexture(GL_TEXTURE0);
982 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
983 if (bpp == 8) {
984 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
985 } else {
986 _glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
987 }
988 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
989
990 /* Does this blitter need a separate animation buffer? */
991 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
992 this->anim_buffer = nullptr;
994 _glDeleteBuffers(1, &this->anim_pbo);
995 _glGenBuffers(1, &this->anim_pbo);
996 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
997 _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);
998 } else {
999 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1000 _glBufferData(GL_PIXEL_UNPACK_BUFFER, line_pixel_count, nullptr, GL_DYNAMIC_DRAW);
1001 }
1002
1003 /* Initialize buffer as 0 == no remap. */
1004 if (_glClearBufferSubData != nullptr) {
1005 uint8_t b = 0;
1006 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_R8, 0, line_pixel_count, GL_RED, GL_UNSIGNED_BYTE, &b);
1007 } else {
1008 ClearPixelBuffer<uint8_t>(line_pixel_count, 0);
1009 }
1010
1011 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1012 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1013 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1014 } else {
1015 if (this->anim_buffer != nullptr) {
1016 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1017 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1018 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1019 this->anim_buffer = nullptr;
1020 }
1021
1022 /* Allocate dummy texture that always reads as 0 == no remap. */
1023 uint dummy = 0;
1024 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1025 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1026 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, &dummy);
1027 }
1028
1029 _glBindTexture(GL_TEXTURE_2D, 0);
1030
1031 /* Set new viewport. */
1032 _screen.height = h;
1033 _screen.width = w;
1034 _screen.pitch = pitch;
1035 _screen.dst_ptr = nullptr;
1036
1037 /* Update screen size in remap shader program. */
1038 _glUseProgram(this->remap_program);
1039 _glUniform2f(this->remap_screen_loc, (float)_screen.width, (float)_screen.height);
1040
1041 _glClear(GL_COLOR_BUFFER_BIT);
1042
1043 return true;
1044}
1045
1052void OpenGLBackend::UpdatePalette(const Colour *pal, uint first, uint length)
1053{
1054 assert(first + length <= 256);
1055
1056 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1057 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1058 _glActiveTexture(GL_TEXTURE1);
1059 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1060 _glTexSubImage1D(GL_TEXTURE_1D, 0, first, length, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pal + first);
1061}
1062
1067{
1068 _glClear(GL_COLOR_BUFFER_BIT);
1069
1070 _glDisable(GL_BLEND);
1071
1072 /* Blit video buffer to screen. */
1073 _glActiveTexture(GL_TEXTURE0);
1074 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
1075 _glActiveTexture(GL_TEXTURE1);
1076 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1077 /* Is the blitter relying on a separate animation buffer? */
1078 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
1079 _glActiveTexture(GL_TEXTURE2);
1080 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1081 _glUseProgram(this->remap_program);
1082 _glUniform4f(this->remap_sprite_loc, 0.0f, 0.0f, 1.0f, 1.0f);
1083 _glUniform2f(this->remap_screen_loc, 1.0f, 1.0f);
1084 _glUniform1f(this->remap_zoom_loc, 0);
1085 _glUniform1i(this->remap_rgb_loc, 1);
1086 } else {
1087 _glUseProgram(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8 ? this->pal_program : this->vid_program);
1088 }
1089 _glBindVertexArray(this->vao_quad);
1090 _glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1091
1092 _glEnable(GL_BLEND);
1093}
1094
1099{
1100 if (!this->cursor_in_window) return;
1101
1102 /* Draw cursor on screen */
1103 _cur_dpi = &_screen;
1104 for (const auto &cs : this->cursor_sprites) {
1105 /* Sprites are cached by PopulateCursorCache(). */
1106 if (this->cursor_cache.Contains(cs.image.sprite)) {
1107 const OpenGLSprite *spr = this->cursor_cache.Get(cs.image.sprite).get();
1108
1109 this->RenderOglSprite(spr, cs.image.pal,
1110 this->cursor_pos.x + cs.pos.x + UnScaleByZoom(spr->x_offs, _gui_zoom),
1111 this->cursor_pos.y + cs.pos.y + UnScaleByZoom(spr->y_offs, _gui_zoom),
1112 _gui_zoom);
1113 }
1114 }
1115}
1116
1117class OpenGLSpriteAllocator : public SpriteAllocator {
1118public:
1119 OpenGLSpriteLRUCache &lru;
1120 SpriteID sprite;
1121
1122 OpenGLSpriteAllocator(OpenGLSpriteLRUCache &lru, SpriteID sprite) : lru(lru), sprite(sprite) {}
1123protected:
1124 void *AllocatePtr(size_t) override { NOT_REACHED(); }
1125};
1126
1127void OpenGLBackend::PopulateCursorCache()
1128{
1129 if (this->clear_cursor_cache) {
1130 /* We have a pending cursor cache clear to do first. */
1131 this->clear_cursor_cache = false;
1132 this->last_sprite_pal = (PaletteID)-1;
1133
1135 }
1136
1137 this->cursor_pos = _cursor.pos;
1138 this->cursor_in_window = _cursor.in_window;
1139
1140 this->cursor_sprites.clear();
1141 for (const auto &sc : _cursor.sprites) {
1142 this->cursor_sprites.emplace_back(sc);
1143
1144 if (!this->cursor_cache.Contains(sc.image.sprite)) {
1145 OpenGLSpriteAllocator allocator(this->cursor_cache, sc.image.sprite);
1146 GetRawSprite(sc.image.sprite, SpriteType::Normal, &allocator, this);
1147 }
1148 }
1149}
1150
1155{
1156 this->cursor_cache.Clear();
1157}
1158
1163{
1164 /* If the game loop is threaded, this function might be called
1165 * from the game thread. As we can call OpenGL functions only
1166 * on the main thread, just set a flag that is handled the next
1167 * time we prepare the cursor cache for drawing. */
1168 this->clear_cursor_cache = true;
1169}
1170
1176{
1177#ifndef NO_GL_BUFFER_SYNC
1178 if (this->sync_vid_mapping != nullptr) _glClientWaitSync(this->sync_vid_mapping, GL_SYNC_FLUSH_COMMANDS_BIT, 100000000); // 100ms timeout.
1179#endif
1180
1181 if (!this->persistent_mapping_supported) {
1182 assert(this->vid_buffer == nullptr);
1183 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1184 this->vid_buffer = _glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE);
1185 } else if (this->vid_buffer == nullptr) {
1186 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1187 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);
1188 }
1189
1190 return this->vid_buffer;
1191}
1192
1198{
1199 if (this->anim_pbo == 0) return nullptr;
1200
1201#ifndef NO_GL_BUFFER_SYNC
1202 if (this->sync_anim_mapping != nullptr) _glClientWaitSync(this->sync_anim_mapping, GL_SYNC_FLUSH_COMMANDS_BIT, 100000000); // 100ms timeout.
1203#endif
1204
1205 if (!this->persistent_mapping_supported) {
1206 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1207 this->anim_buffer = _glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE);
1208 } else if (this->anim_buffer == nullptr) {
1209 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1210 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);
1211 }
1212
1213 return (uint8_t *)this->anim_buffer;
1214}
1215
1221{
1222 assert(this->vid_pbo != 0);
1223
1224 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1225 if (!this->persistent_mapping_supported) {
1226 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1227 this->vid_buffer = nullptr;
1228 }
1229
1230#ifndef NO_GL_BUFFER_SYNC
1231 if (this->persistent_mapping_supported) {
1232 _glDeleteSync(this->sync_vid_mapping);
1233 this->sync_vid_mapping = nullptr;
1234 }
1235#endif
1236
1237 /* Update changed rect of the video buffer texture. */
1238 if (!IsEmptyRect(update_rect)) {
1239 _glActiveTexture(GL_TEXTURE0);
1240 _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
1241 _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch);
1242 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8) {
1243 _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));
1244 } else {
1245 _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));
1246 }
1247
1248#ifndef NO_GL_BUFFER_SYNC
1249 if (this->persistent_mapping_supported) this->sync_vid_mapping = _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
1250#endif
1251 }
1252}
1253
1259{
1260 if (this->anim_pbo == 0) return;
1261
1262 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1263 if (!this->persistent_mapping_supported) {
1264 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1265 this->anim_buffer = nullptr;
1266 }
1267
1268#ifndef NO_GL_BUFFER_SYNC
1269 if (this->persistent_mapping_supported) {
1270 _glDeleteSync(this->sync_anim_mapping);
1271 this->sync_anim_mapping = nullptr;
1272 }
1273#endif
1274
1275 /* Update changed rect of the video buffer texture. */
1276 if (update_rect.left != update_rect.right) {
1277 _glActiveTexture(GL_TEXTURE0);
1278 _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1279 _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch);
1280 _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));
1281
1282#ifndef NO_GL_BUFFER_SYNC
1283 if (this->persistent_mapping_supported) this->sync_anim_mapping = _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
1284#endif
1285 }
1286}
1287
1288/* virtual */ Sprite *OpenGLBackend::Encode(SpriteType sprite_type, const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator)
1289{
1290 /* 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. */
1291 OpenGLSpriteAllocator &gl_allocator = static_cast<OpenGLSpriteAllocator&>(allocator);
1292 gl_allocator.lru.Insert(gl_allocator.sprite, std::make_unique<OpenGLSprite>(sprite_type, sprite));
1293
1294 return nullptr;
1295}
1296
1305void OpenGLBackend::RenderOglSprite(const OpenGLSprite *gl_sprite, PaletteID pal, int x, int y, ZoomLevel zoom)
1306{
1307 /* Set textures. */
1308 bool rgb = gl_sprite->BindTextures();
1309 _glActiveTexture(GL_TEXTURE0 + 1);
1310 _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1311
1312 /* Set palette remap. */
1313 _glActiveTexture(GL_TEXTURE0 + 3);
1314 if (pal != PAL_NONE) {
1315 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_tex);
1316 if (pal != this->last_sprite_pal) {
1317 /* Different remap palette in use, update texture. */
1318 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, OpenGLSprite::pal_pbo);
1319 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1320
1321 _glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, 256, GetNonSprite(GB(pal, 0, PALETTE_WIDTH), SpriteType::Recolour) + 1);
1322 _glTexSubImage1D(GL_TEXTURE_1D, 0, 0, 256, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1323
1324 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1325
1326 this->last_sprite_pal = pal;
1327 }
1328 } else {
1329 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_identity);
1330 }
1331
1332 /* Set up shader program. */
1333 Dimension dim = gl_sprite->GetSize(zoom);
1334 _glUseProgram(this->sprite_program);
1335 _glUniform4f(this->sprite_sprite_loc, (float)x, (float)y, (float)dim.width, (float)dim.height);
1336 _glUniform1f(this->sprite_zoom_loc, (float)zoom);
1337 _glUniform2f(this->sprite_screen_loc, (float)_screen.width, (float)_screen.height);
1338 _glUniform1i(this->sprite_rgb_loc, rgb ? 1 : 0);
1339 _glUniform1i(this->sprite_crash_loc, pal == PALETTE_CRASH ? 1 : 0);
1340
1341 _glBindVertexArray(this->vao_quad);
1342 _glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1343}
1344
1345
1347/* static */ GLuint OpenGLSprite::pal_identity = 0;
1348/* static */ GLuint OpenGLSprite::pal_tex = 0;
1349/* static */ GLuint OpenGLSprite::pal_pbo = 0;
1350
1355/* static */ bool OpenGLSprite::Create()
1356{
1357 _glGenTextures(static_cast<GLsizei>(OpenGLSprite::dummy_tex.size()), OpenGLSprite::dummy_tex.data());
1358
1360 _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[t]);
1361
1362 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
1363 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1364 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
1365 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1366 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1367 }
1368
1369 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1370 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1371
1372 /* Load dummy RGBA texture. */
1373 const Colour rgb_pixel(0, 0, 0);
1374 _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[Texture::RGBA]);
1375 _glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, &rgb_pixel);
1376
1377 /* Load dummy remap texture. */
1378 const uint pal = 0;
1379 _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[Texture::Remap]);
1380 _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, &pal);
1381
1382 /* Create palette remap textures. */
1383 std::array<uint8_t, 256> identity_pal;
1384 std::iota(std::begin(identity_pal), std::end(identity_pal), 0);
1385
1386 /* Permanent texture for identity remap. */
1387 _glGenTextures(1, &OpenGLSprite::pal_identity);
1388 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_identity);
1389 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1390 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1391 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
1392 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1393 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1394 _glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, 256, 0, GL_RED, GL_UNSIGNED_BYTE, identity_pal.data());
1395
1396 /* Dynamically updated texture for remaps. */
1397 _glGenTextures(1, &OpenGLSprite::pal_tex);
1398 _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_tex);
1399 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1400 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1401 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
1402 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1403 _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1404 _glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, 256, 0, GL_RED, GL_UNSIGNED_BYTE, identity_pal.data());
1405
1406 /* Pixel buffer for remap updates. */
1407 _glGenBuffers(1, &OpenGLSprite::pal_pbo);
1408 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, OpenGLSprite::pal_pbo);
1409 _glBufferData(GL_PIXEL_UNPACK_BUFFER, 256, identity_pal.data(), GL_DYNAMIC_DRAW);
1410 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1411
1412 return _glGetError() == GL_NO_ERROR;
1413}
1414
1416/* static */ void OpenGLSprite::Destroy()
1417{
1418 _glDeleteTextures(static_cast<GLsizei>(OpenGLSprite::dummy_tex.size()), OpenGLSprite::dummy_tex.data());
1419 _glDeleteTextures(1, &OpenGLSprite::pal_identity);
1420 _glDeleteTextures(1, &OpenGLSprite::pal_tex);
1421 if (_glDeleteBuffers != nullptr) _glDeleteBuffers(1, &OpenGLSprite::pal_pbo);
1422}
1423
1430{
1431 const auto &root_sprite = sprite.Root();
1432 this->dim.width = root_sprite.width;
1433 this->dim.height = root_sprite.height;
1434 this->x_offs = root_sprite.x_offs;
1435 this->y_offs = root_sprite.y_offs;
1436
1437 int levels = sprite_type == SpriteType::Font ? 1 : to_underlying(ZoomLevel::End);
1438 assert(levels > 0);
1439 (void)_glGetError();
1440
1441 this->tex = {};
1442 _glActiveTexture(GL_TEXTURE0);
1443 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1444
1446 /* Sprite component present? */
1447 if (t == Texture::RGBA && root_sprite.colours == SpriteComponent::Palette) continue;
1448 if (t == Texture::Remap && !root_sprite.colours.Test(SpriteComponent::Palette)) continue;
1449
1450 /* Allocate texture. */
1451 _glGenTextures(1, &this->tex[t]);
1452 _glBindTexture(GL_TEXTURE_2D, this->tex[t]);
1453
1454 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
1455 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1456 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, levels - 1);
1457 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1458 _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1459
1460 /* Set size. */
1461 for (int i = 0, w = this->dim.width, h = this->dim.height; i < levels; i++, w /= 2, h /= 2) {
1462 assert(w * h != 0);
1463 if (t == Texture::Remap) {
1464 _glTexImage2D(GL_TEXTURE_2D, i, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1465 } else {
1466 _glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
1467 }
1468 }
1469 }
1470
1471 /* Upload texture data. */
1472 for (ZoomLevel zoom = ZoomLevel::Min; zoom <= (sprite_type == SpriteType::Font ? ZoomLevel::Min : ZoomLevel::Max); ++zoom) {
1473 const auto &src_sprite = sprite[zoom];
1474 this->Update(src_sprite.width, src_sprite.height, to_underlying(zoom), src_sprite.data);
1475 }
1476
1477 assert(_glGetError() == GL_NO_ERROR);
1478}
1479
1482{
1483 _glDeleteTextures(static_cast<GLsizei>(this->tex.size()), this->tex.data());
1484}
1485
1493void OpenGLSprite::Update(uint width, uint height, uint level, const SpriteLoader::CommonPixel * data)
1494{
1495 static ReusableBuffer<Colour> buf_rgba;
1496 static ReusableBuffer<uint8_t> buf_pal;
1497
1498 _glActiveTexture(GL_TEXTURE0);
1499 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1500 _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1501
1502 if (this->tex[Texture::RGBA] != 0) {
1503 /* Unpack pixel data */
1504 size_t size = static_cast<size_t>(width) * height;
1505 Colour *rgba = buf_rgba.Allocate(size);
1506 for (size_t i = 0; i < size; i++) {
1507 rgba[i].r = data[i].r;
1508 rgba[i].g = data[i].g;
1509 rgba[i].b = data[i].b;
1510 rgba[i].a = data[i].a;
1511 }
1512
1513 _glBindTexture(GL_TEXTURE_2D, this->tex[Texture::RGBA]);
1514 _glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, rgba);
1515 }
1516
1517 if (this->tex[Texture::Remap] != 0) {
1518 /* Unpack and align pixel data. */
1519 size_t pitch = Align(width, 4);
1520
1521 uint8_t *pal = buf_pal.Allocate(pitch * height);
1522 const SpriteLoader::CommonPixel *row = data;
1523 for (uint y = 0; y < height; y++, pal += pitch, row += width) {
1524 for (uint x = 0; x < width; x++) {
1525 pal[x] = row[x].m;
1526 }
1527 }
1528
1529 _glBindTexture(GL_TEXTURE_2D, this->tex[Texture::Remap]);
1530 _glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, buf_pal.GetBuffer());
1531 }
1532
1533 assert(_glGetError() == GL_NO_ERROR);
1534}
1535
1542{
1543 Dimension sd = { (uint)UnScaleByZoomLower(this->dim.width, level), (uint)UnScaleByZoomLower(this->dim.height, level) };
1544 return sd;
1545}
1546
1552{
1553 _glActiveTexture(GL_TEXTURE0);
1554 _glBindTexture(GL_TEXTURE_2D, this->tex[Texture::RGBA] != 0 ? this->tex[Texture::RGBA] : OpenGLSprite::dummy_tex[Texture::RGBA]);
1555 _glActiveTexture(GL_TEXTURE0 + 2);
1556 _glBindTexture(GL_TEXTURE_2D, this->tex[Texture::Remap] != 0 ? this->tex[Texture::Remap] : OpenGLSprite::dummy_tex[Texture::Remap]);
1557
1558 return this->tex[Texture::RGBA] != 0;
1559}
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:139
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
Iterate a range of enum values.
void Insert(const Tkey &key, Tdata &&item)
Insert a new data item with a specified key.
Definition lrucache.hpp:57
Platform-independent back-end class for OpenGL video drivers.
Definition opengl.h:29
GLint sprite_rgb_loc
Uniform location for RGB mode flag.
Definition opengl.h:60
void * anim_buffer
Pointer to the mapped animation buffer.
Definition opengl.h:46
GLuint remap_program
Shader program for blending and rendering a RGBA + remap texture.
Definition opengl.h:50
bool cursor_in_window
Cursor inside this window.
Definition opengl.h:68
void Paint()
Render video buffer to the screen.
Definition opengl.cpp:1066
GLuint pal_program
Shader program for rendering a paletted video buffer.
Definition opengl.h:41
OpenGLSpriteLRUCache cursor_cache
Cache of encoded cursor sprites.
Definition opengl.h:63
std::vector< CursorSprite > cursor_sprites
Sprites comprising cursor.
Definition opengl.h:69
GLint remap_screen_loc
Uniform location for screen size.
Definition opengl.h:52
~OpenGLBackend() override
Free allocated resources.
Definition opengl.cpp:520
static OpenGLBackend * instance
Singleton instance pointer.
Definition opengl.h:31
uint8_t * GetAnimBuffer()
Get a pointer to the memory for the separate animation buffer.
Definition opengl.cpp:1197
void * GetVideoBuffer()
Get a pointer to the memory for the video driver to draw to.
Definition opengl.cpp:1175
bool persistent_mapping_supported
Persistent pixel buffer mapping supported.
Definition opengl.h:33
GLuint vid_texture
Texture handle for the video buffer texture.
Definition opengl.h:39
GLuint vao_quad
Vertex array object storing the rendering state for the fullscreen quad.
Definition opengl.h:42
GLint sprite_zoom_loc
Uniform location for sprite zoom.
Definition opengl.h:59
GLint remap_zoom_loc
Uniform location for sprite zoom.
Definition opengl.h:53
bool Resize(int w, int h, bool force=false)
Change the size of the drawing window and allocate matching resources.
Definition opengl.cpp:940
OpenGLBackend()
Construct OpenGL back-end class.
Definition opengl.cpp:513
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:491
void * vid_buffer
Pointer to the mapped video buffer.
Definition opengl.h:37
void UpdatePalette(const Colour *pal, uint first, uint length)
Update the stored palette.
Definition opengl.cpp:1052
GLuint anim_texture
Texture handle for the animation buffer texture.
Definition opengl.h:48
void InternalClearCursorCache()
Clear all cached cursor sprites.
Definition opengl.cpp:1154
Sprite * Encode(SpriteType sprite_type, const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator) override
Convert a sprite from the loader to our own format.
Definition opengl.cpp:1288
GLuint sprite_program
Shader program for blending and rendering a sprite to the video buffer.
Definition opengl.h:56
void ReleaseAnimBuffer(const Rect &update_rect)
Update animation buffer texture after the animation buffer was filled.
Definition opengl.cpp:1258
GLuint vid_pbo
Pixel buffer object storing the memory used for the video driver to draw to.
Definition opengl.h:38
GLsync sync_anim_mapping
Sync object for the persistently mapped animation buffer.
Definition opengl.h:35
GLuint vbo_quad
Vertex buffer with a fullscreen quad.
Definition opengl.h:43
bool clear_cursor_cache
A clear of the cursor cache is pending.
Definition opengl.h:65
GLint remap_rgb_loc
Uniform location for RGB mode flag.
Definition opengl.h:54
void ClearCursorCache()
Queue a request for cursor cache clear.
Definition opengl.cpp:1162
GLuint vid_program
Shader program for rendering a RGBA video buffer.
Definition opengl.h:40
GLuint pal_texture
Palette lookup texture.
Definition opengl.h:44
GLint remap_sprite_loc
Uniform location for sprite parameters.
Definition opengl.h:51
bool InitShaders()
Create all needed shader programs.
Definition opengl.cpp:832
void DrawMouseCursor()
Draw mouse cursor on screen.
Definition opengl.cpp:1098
Point cursor_pos
Cursor position.
Definition opengl.h:67
GLint sprite_crash_loc
Uniform location for crash remap mode flag.
Definition opengl.h:61
void ReleaseVideoBuffer(const Rect &update_rect)
Update video buffer texture after the video buffer was filled.
Definition opengl.cpp:1220
GLint sprite_sprite_loc
Uniform location for sprite parameters.
Definition opengl.h:57
void RenderOglSprite(const OpenGLSprite *gl_sprite, PaletteID pal, int x, int y, ZoomLevel zoom)
Render a sprite to the back buffer.
Definition opengl.cpp:1305
PaletteID last_sprite_pal
Last uploaded remap palette.
Definition opengl.h:64
GLuint anim_pbo
Pixel buffer object storing the memory used for the animation buffer.
Definition opengl.h:47
GLsync sync_vid_mapping
Sync object for the persistently mapped video buffer.
Definition opengl.h:34
std::optional< std::string_view > Init(const Dimension &screen_res)
Check for the needed OpenGL functionality and allocate all resources.
Definition opengl.cpp:557
static void Destroy()
Free resources and destroy singleton back-end class.
Definition opengl.cpp:504
GLint sprite_screen_loc
Uniform location for screen size.
Definition opengl.h:58
void * AllocatePtr(size_t) override
Allocate memory for a sprite.
Definition opengl.cpp:1124
Class that encapsulates a RGBA texture together with a paletted remap texture.
Definition opengl.h:120
bool BindTextures() const
Bind textures for rendering this sprite.
Definition opengl.cpp:1551
static EnumIndexArray< GLuint, Texture, Texture::End > dummy_tex
1x1 dummy textures to substitute for unused sprite components.
Definition opengl.h:1346
OpenGLSprite(SpriteType sprite_type, const SpriteLoader::SpriteCollection &sprite)
Create an OpenGL sprite with a palette remap part.
Definition opengl.cpp:1429
Texture
Enum of all used OpenGL texture objects.
Definition opengl.h:123
@ Remap
Remap texture part.
Definition opengl.h:125
@ End
End marker.
Definition opengl.h:126
@ RGBA
RGBA texture part.
Definition opengl.h:124
Dimension GetSize(ZoomLevel level) const
Query the sprite size at a certain zoom level.
Definition opengl.cpp:1541
static bool Create()
Create all common resources for sprite rendering.
Definition opengl.cpp:1355
~OpenGLSprite()
Delete the textures we allocated.
Definition opengl.cpp:1481
static GLuint pal_pbo
Pixel buffer object for remap upload.
Definition opengl.h:138
static GLuint pal_identity
Identity texture mapping.
Definition opengl.h:136
static GLuint pal_tex
Texture for palette remap.
Definition opengl.h:137
int16_t y_offs
Number of pixels to shift the sprite downwards.
Definition opengl.h:132
int16_t x_offs
Number of pixels to shift the sprite to the right.
Definition opengl.h:131
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:1493
EnumIndexArray< GLuint, Texture, Texture::End > tex
The texture objects.
Definition opengl.h:130
static void Destroy()
Free all common resources for sprite rendering.
Definition opengl.cpp:1416
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.
SpriteCollMap< Sprite > SpriteCollection
Type defining a collection of sprites, one for each zoom level.
Parse data from a string / buffer.
@ SKIP_ALL_SEPARATORS
Read and discard all consecutive separators, do not include any in the result.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
std::string_view ReadUntil(std::string_view str, SeparatorUsage sep)
Read data until the first occurrence of 'str', and advance reader.
bool ReadIf(std::string_view str)
Check whether the next data matches 'str', and skip it.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
Functions related to debugging.
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
Definition debug.h:24
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Driver
Driver message facility.
Definition debug_type.h:29
@ Warning
Warning, wrong but okay if you don't know.
Definition debug_type.h:17
@ Notice
Notice.
Definition debug_type.h:18
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Debug2
Debug #2 - Low level debug messages.
Definition debug_type.h:21
@ Trace2
Trace information #2.
Definition debug_type.h:23
@ Error
Error, but we are recovering.
Definition debug_type.h:16
@ Trace3
Trace information #3.
Definition debug_type.h:24
#define T
Climate temperate.
Definition engines.h:91
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Factory to 'query' all available blitters.
Geometry functions.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
ZoomLevel _gui_zoom
GUI Zoom level.
Definition gfx.cpp:57
Functions related to the gfx engine.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
SpriteType
Types of sprites that might be loaded.
Definition gfx_type.h:404
@ Recolour
Recolour sprite.
Definition gfx_type.h:408
@ Font
A sprite used for fonts.
Definition gfx_type.h:407
@ Normal
The most basic (normal) sprite.
Definition gfx_type.h:405
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
Integer math functions.
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
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 bool BindBasicOpenGLProcs()
Bind OpenGL 1.0 and 1.1 functions.
Definition opengl.cpp:241
static void ClearPixelBuffer(size_t len, T data)
Clear the bound pixel buffer to a specific value.
Definition opengl.cpp:924
static const int MAX_CACHED_CURSORS
Maximum number of cursor sprites to cache.
Definition opengl.cpp:131
static bool IsOpenGLExtensionSupported(std::string_view extension)
Check if an OpenGL extension is supported by the current context.
Definition opengl.cpp:166
static bool BindPersistentBufferExtensions()
Bind extension functions for persistent buffer mapping.
Definition opengl.cpp:406
static bool VerifyProgram(GLuint program)
Check a program for link errors and log them if necessary.
Definition opengl.cpp:810
static uint8_t _gl_major_ver
Major OpenGL version.
Definition opengl.cpp:195
static bool BindGLProc(F &f, const char *name)
Try loading an OpenGL function.
Definition opengl.cpp:218
static bool BindVBAExtension()
Bind vertex array object extension functions.
Definition opengl.cpp:315
void SetupDebugOutput()
Enable OpenGL debug messages if supported.
Definition opengl.cpp:456
static uint8_t _gl_minor_ver
Minor OpenGL version.
Definition opengl.cpp:196
static bool BindShaderExtensions()
Bind extension functions for shader support.
Definition opengl.cpp:337
static bool BindBasicInfoProcs()
Bind basic information functions.
Definition opengl.cpp:228
bool HasStringInExtensionList(std::string_view string, std::string_view substring)
Find a substring in a string made of space delimited elements.
Definition opengl.cpp:151
static bool BindTextureExtensions()
Bind texture-related extension functions.
Definition opengl.cpp:267
static bool VerifyShader(GLuint shader)
Check a shader for compilation errors and log them if necessary.
Definition opengl.cpp:787
void DebugOutputCallback(GLenum, GLenum type, GLuint, GLenum severity, GLsizei, const GLchar *message, const void *)
Callback to receive OpenGL debug messages.
Definition opengl.cpp:432
static bool BindVBOExtension()
Bind vertex buffer object extension functions.
Definition opengl.cpp:282
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
OpenGL shader programs.
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.
A number of safeguards to prevent using unsafe methods.
void * GetRawSprite(SpriteID sprite, SpriteType type, SpriteAllocator *allocator, SpriteEncoder *encoder)
Reads a sprite (from disk or sprite cache).
Functions to cache sprites in memory.
@ Palette
Sprite has palette data.
This file contains all sprite-related enums and defines.
static constexpr uint8_t PALETTE_WIDTH
number of bits of the sprite containing the recolour palette
Definition sprites.h:1721
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:261
Parse strings.
std::vector< CursorSprite > sprites
Sprites comprising cursor.
Definition gfx_type.h:136
Point pos
logical mouse position
Definition gfx_type.h:125
bool in_window
mouse inside this window, determines drawing logic
Definition gfx_type.h:147
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Specification of a rectangle with absolute coordinates of all edges.
A simple 2D vertex with just position and texture.
Definition opengl.cpp:125
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.
uint16_t width
Width of the sprite.
Functions related to zooming.
int UnScaleByZoomLower(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min).
Definition zoom_func.h:67
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:34
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:20
@ Max
Maximum zoom level.
Definition zoom_type.h:30
@ Min
Minimum zoom level.
Definition zoom_type.h:23
@ End
End for iteration.
Definition zoom_type.h:31