4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file opengl_v.cpp OpenGL video driver support. */
12 #include "../stdafx.h"
14 /* Define to disable buffer syncing. Will increase max fast forward FPS but produces artifacts. Mainly useful for performance testing. */
15 // #define NO_GL_BUFFER_SYNC
16 /* Define to allow software rendering backends. */
17 // #define GL_ALLOW_SOFTWARE_RENDERER
23 #define GL_GLEXT_PROTOTYPES
24 #if defined(__APPLE__)
25 # define GL_SILENCE_DEPRECATION
26 # include <OpenGL/gl3.h>
30 #include "../3rdparty/opengl/glext.h"
33 #include "../core/geometry_func.hpp"
34 #include "../core/mem_func.hpp"
35 #include "../core/math_func.hpp"
36 #include "../core/mem_func.hpp"
37 #include "../gfx_func.h"
39 #include "../blitter/factory.hpp"
40 #include "../zoom_func.h"
44 #include "../table/opengl_shader.h"
45 #include "../table/sprites.h"
48 #include "../safeguards.h"
51 /* Define function pointers of all OpenGL functions that we load dynamically. */
53 #define GL(function) static decltype(&function) _ ## function
58 GL(glDebugMessageControl
);
59 GL(glDebugMessageCallback
);
88 GL(glClearBufferSubData
);
96 GL(glGenVertexArrays
);
97 GL(glDeleteVertexArrays
);
98 GL(glBindVertexArray
);
105 GL(glGetProgramInfoLog
);
112 GL(glGetShaderInfoLog
);
113 GL(glGetUniformLocation
);
119 GL(glGetAttribLocation
);
120 GL(glEnableVertexAttribArray
);
121 GL(glDisableVertexAttribArray
);
122 GL(glVertexAttribPointer
);
123 GL(glBindFragDataLocation
);
128 /** A simple 2D vertex with just position and texture. */
129 struct Simple2DVertex
{
134 /** Maximum number of cursor sprites to cache. */
135 static const int MAX_CACHED_CURSORS
= 48;
137 /* static */ OpenGLBackend
*OpenGLBackend::instance
= nullptr;
139 GetOGLProcAddressProc GetOGLProcAddress
;
142 * Find a substring in a string made of space delimited elements. The substring
143 * has to match the complete element, partial matches don't count.
144 * @param string List of space delimited elements.
145 * @param substring Substring to find.
146 * @return Pointer to the start of the match or nullptr if the substring is not present.
148 const char *FindStringInExtensionList(const char *string
, const char *substring
)
151 /* Is the extension string present at all? */
152 const char *pos
= strstr(string
, substring
);
153 if (pos
== nullptr) break;
155 /* Is this a real match, i.e. are the chars before and after the matched string
156 * indeed spaces (or the start or end of the string, respectively)? */
157 const char *end
= pos
+ strlen(substring
);
158 if ((pos
== string
|| pos
[-1] == ' ') && (*end
== ' ' || *end
== '\0')) return pos
;
160 /* False hit, try again for the remaining string. */
168 * Check if an OpenGL extension is supported by the current context.
169 * @param extension The extension string to test.
170 * @return True if the extension is supported, false if not.
172 static bool IsOpenGLExtensionSupported(const char *extension
)
174 static PFNGLGETSTRINGIPROC glGetStringi
= nullptr;
175 static bool glGetStringi_loaded
= false;
177 /* Starting with OpenGL 3.0 the preferred API to get the extensions
178 * has changed. Try to load the required function once. */
179 if (!glGetStringi_loaded
) {
180 if (IsOpenGLVersionAtLeast(3, 0)) glGetStringi
= (PFNGLGETSTRINGIPROC
)GetOGLProcAddress("glGetStringi");
181 glGetStringi_loaded
= true;
184 if (glGetStringi
!= nullptr) {
185 /* New style: Each supported extension can be queried and compared independently. */
187 _glGetIntegerv(GL_NUM_EXTENSIONS
, &num_exts
);
189 for (GLint i
= 0; i
< num_exts
; i
++) {
190 const char *entry
= (const char *)glGetStringi(GL_EXTENSIONS
, i
);
191 if (strcmp(entry
, extension
) == 0) return true;
194 /* Old style: A single, space-delimited string for all extensions. */
195 return FindStringInExtensionList((const char *)_glGetString(GL_EXTENSIONS
), extension
) != nullptr;
201 static byte _gl_major_ver
= 0; ///< Major OpenGL version.
202 static byte _gl_minor_ver
= 0; ///< Minor OpenGL version.
205 * Check if the current OpenGL version is equal or higher than a given one.
206 * @param major Minimal major version.
207 * @param minor Minimal minor version.
208 * @pre OpenGL was initialized.
209 * @return True if the OpenGL version is equal or higher than the requested one.
211 bool IsOpenGLVersionAtLeast(byte major
, byte minor
)
213 return (_gl_major_ver
> major
) || (_gl_major_ver
== major
&& _gl_minor_ver
>= minor
);
217 * Try loading an OpenGL function.
218 * @tparam F Type of the function pointer.
219 * @param f Reference where to store the function pointer in.
220 * @param name Name of the function.
221 * @return True if the function could be bound.
223 template <typename F
>
224 static bool BindGLProc(F
&f
, const char *name
)
226 f
= reinterpret_cast<F
>(GetOGLProcAddress(name
));
230 /** Bind basic information functions. */
231 static bool BindBasicInfoProcs()
233 if (!BindGLProc(_glGetString
, "glGetString")) return false;
234 if (!BindGLProc(_glGetIntegerv
, "glGetIntegerv")) return false;
235 if (!BindGLProc(_glGetError
, "glGetError")) return false;
240 /** Bind OpenGL 1.0 and 1.1 functions. */
241 static bool BindBasicOpenGLProcs()
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;
263 /** Bind texture-related extension functions. */
264 static bool BindTextureExtensions()
266 if (IsOpenGLVersionAtLeast(1, 3)) {
267 if (!BindGLProc(_glActiveTexture
, "glActiveTexture")) return false;
269 if (!BindGLProc(_glActiveTexture
, "glActiveTextureARB")) return false;
275 /** Bind vertex buffer object extension functions. */
276 static bool BindVBOExtension()
278 if (IsOpenGLVersionAtLeast(1, 5)) {
279 if (!BindGLProc(_glGenBuffers
, "glGenBuffers")) return false;
280 if (!BindGLProc(_glDeleteBuffers
, "glDeleteBuffers")) return false;
281 if (!BindGLProc(_glBindBuffer
, "glBindBuffer")) return false;
282 if (!BindGLProc(_glBufferData
, "glBufferData")) return false;
283 if (!BindGLProc(_glBufferSubData
, "glBufferSubData")) return false;
284 if (!BindGLProc(_glMapBuffer
, "glMapBuffer")) return false;
285 if (!BindGLProc(_glUnmapBuffer
, "glUnmapBuffer")) return false;
287 if (!BindGLProc(_glGenBuffers
, "glGenBuffersARB")) return false;
288 if (!BindGLProc(_glDeleteBuffers
, "glDeleteBuffersARB")) return false;
289 if (!BindGLProc(_glBindBuffer
, "glBindBufferARB")) return false;
290 if (!BindGLProc(_glBufferData
, "glBufferDataARB")) return false;
291 if (!BindGLProc(_glBufferSubData
, "glBufferSubDataARB")) return false;
292 if (!BindGLProc(_glMapBuffer
, "glMapBufferARB")) return false;
293 if (!BindGLProc(_glUnmapBuffer
, "glUnmapBufferARB")) return false;
296 if (IsOpenGLVersionAtLeast(4, 3) || IsOpenGLExtensionSupported("GL_ARB_clear_buffer_object")) {
297 BindGLProc(_glClearBufferSubData
, "glClearBufferSubData");
299 _glClearBufferSubData
= nullptr;
305 /** Bind vertex array object extension functions. */
306 static bool BindVBAExtension()
308 /* The APPLE and ARB variants have different semantics (that don't matter for us).
309 * Successfully getting pointers to one variant doesn't mean it is supported for
310 * the current context. Always check the extension strings as well. */
311 if (IsOpenGLVersionAtLeast(3, 0) || IsOpenGLExtensionSupported("GL_ARB_vertex_array_object")) {
312 if (!BindGLProc(_glGenVertexArrays
, "glGenVertexArrays")) return false;
313 if (!BindGLProc(_glDeleteVertexArrays
, "glDeleteVertexArrays")) return false;
314 if (!BindGLProc(_glBindVertexArray
, "glBindVertexArray")) return false;
315 } else if (IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object")) {
316 if (!BindGLProc(_glGenVertexArrays
, "glGenVertexArraysAPPLE")) return false;
317 if (!BindGLProc(_glDeleteVertexArrays
, "glDeleteVertexArraysAPPLE")) return false;
318 if (!BindGLProc(_glBindVertexArray
, "glBindVertexArrayAPPLE")) return false;
324 /** Bind extension functions for shader support. */
325 static bool BindShaderExtensions()
327 if (IsOpenGLVersionAtLeast(2, 0)) {
328 if (!BindGLProc(_glCreateProgram
, "glCreateProgram")) return false;
329 if (!BindGLProc(_glDeleteProgram
, "glDeleteProgram")) return false;
330 if (!BindGLProc(_glLinkProgram
, "glLinkProgram")) return false;
331 if (!BindGLProc(_glUseProgram
, "glUseProgram")) return false;
332 if (!BindGLProc(_glGetProgramiv
, "glGetProgramiv")) return false;
333 if (!BindGLProc(_glGetProgramInfoLog
, "glGetProgramInfoLog")) return false;
334 if (!BindGLProc(_glCreateShader
, "glCreateShader")) return false;
335 if (!BindGLProc(_glDeleteShader
, "glDeleteShader")) return false;
336 if (!BindGLProc(_glShaderSource
, "glShaderSource")) return false;
337 if (!BindGLProc(_glCompileShader
, "glCompileShader")) return false;
338 if (!BindGLProc(_glAttachShader
, "glAttachShader")) return false;
339 if (!BindGLProc(_glGetShaderiv
, "glGetShaderiv")) return false;
340 if (!BindGLProc(_glGetShaderInfoLog
, "glGetShaderInfoLog")) return false;
341 if (!BindGLProc(_glGetUniformLocation
, "glGetUniformLocation")) return false;
342 if (!BindGLProc(_glUniform1i
, "glUniform1i")) return false;
343 if (!BindGLProc(_glUniform1f
, "glUniform1f")) return false;
344 if (!BindGLProc(_glUniform2f
, "glUniform2f")) return false;
345 if (!BindGLProc(_glUniform4f
, "glUniform4f")) return false;
347 if (!BindGLProc(_glGetAttribLocation
, "glGetAttribLocation")) return false;
348 if (!BindGLProc(_glEnableVertexAttribArray
, "glEnableVertexAttribArray")) return false;
349 if (!BindGLProc(_glDisableVertexAttribArray
, "glDisableVertexAttribArray")) return false;
350 if (!BindGLProc(_glVertexAttribPointer
, "glVertexAttribPointer")) return false;
352 /* In the ARB extension programs and shaders are in the same object space. */
353 if (!BindGLProc(_glCreateProgram
, "glCreateProgramObjectARB")) return false;
354 if (!BindGLProc(_glDeleteProgram
, "glDeleteObjectARB")) return false;
355 if (!BindGLProc(_glLinkProgram
, "glLinkProgramARB")) return false;
356 if (!BindGLProc(_glUseProgram
, "glUseProgramObjectARB")) return false;
357 if (!BindGLProc(_glGetProgramiv
, "glGetObjectParameterivARB")) return false;
358 if (!BindGLProc(_glGetProgramInfoLog
, "glGetInfoLogARB")) return false;
359 if (!BindGLProc(_glCreateShader
, "glCreateShaderObjectARB")) return false;
360 if (!BindGLProc(_glDeleteShader
, "glDeleteObjectARB")) return false;
361 if (!BindGLProc(_glShaderSource
, "glShaderSourceARB")) return false;
362 if (!BindGLProc(_glCompileShader
, "glCompileShaderARB")) return false;
363 if (!BindGLProc(_glAttachShader
, "glAttachObjectARB")) return false;
364 if (!BindGLProc(_glGetShaderiv
, "glGetObjectParameterivARB")) return false;
365 if (!BindGLProc(_glGetShaderInfoLog
, "glGetInfoLogARB")) return false;
366 if (!BindGLProc(_glGetUniformLocation
, "glGetUniformLocationARB")) return false;
367 if (!BindGLProc(_glUniform1i
, "glUniform1iARB")) return false;
368 if (!BindGLProc(_glUniform1f
, "glUniform1fARB")) return false;
369 if (!BindGLProc(_glUniform2f
, "glUniform2fARB")) return false;
370 if (!BindGLProc(_glUniform4f
, "glUniform4fARB")) return false;
372 if (!BindGLProc(_glGetAttribLocation
, "glGetAttribLocationARB")) return false;
373 if (!BindGLProc(_glEnableVertexAttribArray
, "glEnableVertexAttribArrayARB")) return false;
374 if (!BindGLProc(_glDisableVertexAttribArray
, "glDisableVertexAttribArrayARB")) return false;
375 if (!BindGLProc(_glVertexAttribPointer
, "glVertexAttribPointerARB")) return false;
378 /* Bind functions only needed when using GLSL 1.50 shaders. */
379 if (IsOpenGLVersionAtLeast(3, 0)) {
380 BindGLProc(_glBindFragDataLocation
, "glBindFragDataLocation");
381 } else if (IsOpenGLExtensionSupported("GL_EXT_gpu_shader4")) {
382 BindGLProc(_glBindFragDataLocation
, "glBindFragDataLocationEXT");
384 _glBindFragDataLocation
= nullptr;
390 /** Bind extension functions for persistent buffer mapping. */
391 static bool BindPersistentBufferExtensions()
393 /* Optional functions for persistent buffer mapping. */
394 if (IsOpenGLVersionAtLeast(3, 0)) {
395 if (!BindGLProc(_glMapBufferRange
, "glMapBufferRange")) return false;
397 if (IsOpenGLVersionAtLeast(4, 4) || IsOpenGLExtensionSupported("GL_ARB_buffer_storage")) {
398 if (!BindGLProc(_glBufferStorage
, "glBufferStorage")) return false;
400 #ifndef NO_GL_BUFFER_SYNC
401 if (IsOpenGLVersionAtLeast(3, 2) || IsOpenGLExtensionSupported("GL_ARB_sync")) {
402 if (!BindGLProc(_glClientWaitSync
, "glClientWaitSync")) return false;
403 if (!BindGLProc(_glFenceSync
, "glFenceSync")) return false;
404 if (!BindGLProc(_glDeleteSync
, "glDeleteSync")) return false;
411 /** Callback to receive OpenGL debug messages. */
412 void APIENTRY
DebugOutputCallback(GLenum source
, GLenum type
, GLuint id
, GLenum severity
, GLsizei length
, const GLchar
*message
, const void *userParam
)
414 /* Make severity human readable. */
415 const char *severity_str
= "";
417 case GL_DEBUG_SEVERITY_HIGH
: severity_str
= "high"; break;
418 case GL_DEBUG_SEVERITY_MEDIUM
: severity_str
= "medium"; break;
419 case GL_DEBUG_SEVERITY_LOW
: severity_str
= "low"; break;
422 /* Make type human readable.*/
423 const char *type_str
= "Other";
425 case GL_DEBUG_TYPE_ERROR
: type_str
= "Error"; break;
426 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR
: type_str
= "Deprecated"; break;
427 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR
: type_str
= "Undefined behaviour"; break;
428 case GL_DEBUG_TYPE_PERFORMANCE
: type_str
= "Performance"; break;
429 case GL_DEBUG_TYPE_PORTABILITY
: type_str
= "Portability"; break;
432 Debug(driver
, 6, "OpenGL: {} ({}) - {}", type_str
, severity_str
, message
);
435 /** Enable OpenGL debug messages if supported. */
436 void SetupDebugOutput()
438 #ifndef NO_DEBUG_MESSAGES
439 if (_debug_driver_level
< 6) return;
441 if (IsOpenGLVersionAtLeast(4, 3)) {
442 BindGLProc(_glDebugMessageControl
, "glDebugMessageControl");
443 BindGLProc(_glDebugMessageCallback
, "glDebugMessageCallback");
444 } else if (IsOpenGLExtensionSupported("GL_ARB_debug_output")) {
445 BindGLProc(_glDebugMessageControl
, "glDebugMessageControlARB");
446 BindGLProc(_glDebugMessageCallback
, "glDebugMessageCallbackARB");
449 if (_glDebugMessageControl
!= nullptr && _glDebugMessageCallback
!= nullptr) {
450 /* Enable debug output. As synchronous debug output costs performance, we only enable it with a high debug level. */
451 _glEnable(GL_DEBUG_OUTPUT
);
452 if (_debug_driver_level
>= 8) _glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS
);
454 _glDebugMessageCallback(&DebugOutputCallback
, nullptr);
455 /* Enable all messages on highest debug level.*/
456 _glDebugMessageControl(GL_DONT_CARE
, GL_DONT_CARE
, GL_DONT_CARE
, 0, nullptr, _debug_driver_level
>= 9 ? GL_TRUE
: GL_FALSE
);
457 /* Get debug messages for errors and undefined/deprecated behaviour. */
458 _glDebugMessageControl(GL_DONT_CARE
, GL_DEBUG_TYPE_ERROR
, GL_DONT_CARE
, 0, nullptr, GL_TRUE
);
459 _glDebugMessageControl(GL_DONT_CARE
, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR
, GL_DONT_CARE
, 0, nullptr, GL_TRUE
);
460 _glDebugMessageControl(GL_DONT_CARE
, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR
, GL_DONT_CARE
, 0, nullptr, GL_TRUE
);
466 * Create and initialize the singleton back-end class.
467 * @param get_proc Callback to get an OpenGL function from the OS driver.
468 * @param screen_res Current display resolution.
469 * @return nullptr on success, error message otherwise.
471 /* static */ const char *OpenGLBackend::Create(GetOGLProcAddressProc get_proc
, const Dimension
&screen_res
)
473 if (OpenGLBackend::instance
!= nullptr) OpenGLBackend::Destroy();
475 GetOGLProcAddress
= get_proc
;
477 OpenGLBackend::instance
= new OpenGLBackend();
478 return OpenGLBackend::instance
->Init(screen_res
);
482 * Free resources and destroy singleton back-end class.
484 /* static */ void OpenGLBackend::Destroy()
486 delete OpenGLBackend::instance
;
487 OpenGLBackend::instance
= nullptr;
491 * Construct OpenGL back-end class.
493 OpenGLBackend::OpenGLBackend() : cursor_cache(MAX_CACHED_CURSORS
)
498 * Free allocated resources.
500 OpenGLBackend::~OpenGLBackend()
502 if (_glDeleteProgram
!= nullptr) {
503 _glDeleteProgram(this->remap_program
);
504 _glDeleteProgram(this->vid_program
);
505 _glDeleteProgram(this->pal_program
);
506 _glDeleteProgram(this->sprite_program
);
508 if (_glDeleteVertexArrays
!= nullptr) _glDeleteVertexArrays(1, &this->vao_quad
);
509 if (_glDeleteBuffers
!= nullptr) {
510 _glDeleteBuffers(1, &this->vbo_quad
);
511 _glDeleteBuffers(1, &this->vid_pbo
);
512 _glDeleteBuffers(1, &this->anim_pbo
);
514 if (_glDeleteTextures
!= nullptr) {
515 this->InternalClearCursorCache();
516 OpenGLSprite::Destroy();
518 _glDeleteTextures(1, &this->vid_texture
);
519 _glDeleteTextures(1, &this->anim_texture
);
520 _glDeleteTextures(1, &this->pal_texture
);
525 * Check for the needed OpenGL functionality and allocate all resources.
526 * @param screen_res Current display resolution.
527 * @return Error string or nullptr if successful.
529 const char *OpenGLBackend::Init(const Dimension
&screen_res
)
531 if (!BindBasicInfoProcs()) return "OpenGL not supported";
533 /* Always query the supported OpenGL version as the current context might have changed. */
534 const char *ver
= (const char *)_glGetString(GL_VERSION
);
535 const char *vend
= (const char *)_glGetString(GL_VENDOR
);
536 const char *renderer
= (const char *)_glGetString(GL_RENDERER
);
538 if (ver
== nullptr || vend
== nullptr || renderer
== nullptr) return "OpenGL not supported";
540 Debug(driver
, 1, "OpenGL driver: {} - {} ({})", vend
, renderer
, ver
);
542 #ifndef GL_ALLOW_SOFTWARE_RENDERER
543 /* Don't use MESA software rendering backends as they are slower than
544 * just using a non-OpenGL video driver. */
545 if (strncmp(renderer
, "llvmpipe", 8) == 0 || strncmp(renderer
, "softpipe", 8) == 0) return "Software renderer detected, not using OpenGL";
548 const char *minor
= strchr(ver
, '.');
549 _gl_major_ver
= atoi(ver
);
550 _gl_minor_ver
= minor
!= nullptr ? atoi(minor
+ 1) : 0;
553 /* Old drivers on Windows (especially if made by Intel) seem to be
554 * unstable, so cull the oldest stuff here. */
555 if (!IsOpenGLVersionAtLeast(3, 2)) return "Need at least OpenGL version 3.2 on Windows";
558 if (!BindBasicOpenGLProcs()) return "Failed to bind basic OpenGL functions.";
562 /* OpenGL 1.3 is the absolute minimum. */
563 if (!IsOpenGLVersionAtLeast(1, 3)) return "OpenGL version >= 1.3 required";
564 /* Check for non-power-of-two texture support. */
565 if (!IsOpenGLVersionAtLeast(2, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_non_power_of_two")) return "Non-power-of-two textures not supported";
566 /* Check for single element texture formats. */
567 if (!IsOpenGLVersionAtLeast(3, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_rg")) return "Single element texture formats not supported";
568 if (!BindTextureExtensions()) return "Failed to bind texture extension functions";
569 /* Check for vertex buffer objects. */
570 if (!IsOpenGLVersionAtLeast(1, 5) && !IsOpenGLExtensionSupported("ARB_vertex_buffer_object")) return "Vertex buffer objects not supported";
571 if (!BindVBOExtension()) return "Failed to bind VBO extension functions";
572 /* Check for pixel buffer objects. */
573 if (!IsOpenGLVersionAtLeast(2, 1) && !IsOpenGLExtensionSupported("GL_ARB_pixel_buffer_object")) return "Pixel buffer objects not supported";
574 /* Check for vertex array objects. */
575 if (!IsOpenGLVersionAtLeast(3, 0) && (!IsOpenGLExtensionSupported("GL_ARB_vertex_array_object") || !IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object"))) return "Vertex array objects not supported";
576 if (!BindVBAExtension()) return "Failed to bind VBA extension functions";
577 /* Check for shader objects. */
578 if (!IsOpenGLVersionAtLeast(2, 0) && (!IsOpenGLExtensionSupported("GL_ARB_shader_objects") || !IsOpenGLExtensionSupported("GL_ARB_fragment_shader") || !IsOpenGLExtensionSupported("GL_ARB_vertex_shader"))) return "No shader support";
579 if (!BindShaderExtensions()) return "Failed to bind shader extension functions";
580 if (IsOpenGLVersionAtLeast(3, 2) && _glBindFragDataLocation
== nullptr) return "OpenGL claims to support version 3.2 but doesn't have glBindFragDataLocation";
582 this->persistent_mapping_supported
= IsOpenGLVersionAtLeast(3, 0) && (IsOpenGLVersionAtLeast(4, 4) || IsOpenGLExtensionSupported("GL_ARB_buffer_storage"));
583 #ifndef NO_GL_BUFFER_SYNC
584 this->persistent_mapping_supported
= this->persistent_mapping_supported
&& (IsOpenGLVersionAtLeast(3, 2) || IsOpenGLExtensionSupported("GL_ARB_sync"));
587 if (this->persistent_mapping_supported
&& !BindPersistentBufferExtensions()) {
588 Debug(driver
, 1, "OpenGL claims to support persistent buffer mapping but doesn't export all functions, not using persistent mapping.");
589 this->persistent_mapping_supported
= false;
591 if (this->persistent_mapping_supported
) Debug(driver
, 3, "OpenGL: Using persistent buffer mapping");
593 /* Check maximum texture size against screen resolution. */
594 GLint max_tex_size
= 0;
595 _glGetIntegerv(GL_MAX_TEXTURE_SIZE
, &max_tex_size
);
596 if (std::max(screen_res
.width
, screen_res
.height
) > (uint
)max_tex_size
) return "Max supported texture size is too small";
598 /* Check available texture units. */
599 GLint max_tex_units
= 0;
600 _glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
, &max_tex_units
);
601 if (max_tex_units
< 4) return "Not enough simultaneous textures supported";
603 Debug(driver
, 2, "OpenGL shading language version: {}, texture units = {}", (const char *)_glGetString(GL_SHADING_LANGUAGE_VERSION
), (int)max_tex_units
);
605 if (!this->InitShaders()) return "Failed to initialize shaders";
607 /* Setup video buffer texture. */
608 _glGenTextures(1, &this->vid_texture
);
609 _glBindTexture(GL_TEXTURE_2D
, this->vid_texture
);
610 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST
);
611 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
612 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAX_LEVEL
, 0);
613 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
614 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
615 _glBindTexture(GL_TEXTURE_2D
, 0);
616 if (_glGetError() != GL_NO_ERROR
) return "Can't generate video buffer texture";
618 /* Setup video buffer texture. */
619 _glGenTextures(1, &this->anim_texture
);
620 _glBindTexture(GL_TEXTURE_2D
, this->anim_texture
);
621 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST
);
622 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
623 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAX_LEVEL
, 0);
624 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
625 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
626 _glBindTexture(GL_TEXTURE_2D
, 0);
627 if (_glGetError() != GL_NO_ERROR
) return "Can't generate animation buffer texture";
629 /* Setup palette texture. */
630 _glGenTextures(1, &this->pal_texture
);
631 _glBindTexture(GL_TEXTURE_1D
, this->pal_texture
);
632 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST
);
633 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
634 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MAX_LEVEL
, 0);
635 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
636 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
637 _glTexImage1D(GL_TEXTURE_1D
, 0, GL_RGBA8
, 256, 0, GL_BGRA
, GL_UNSIGNED_INT_8_8_8_8_REV
, nullptr);
638 _glBindTexture(GL_TEXTURE_1D
, 0);
639 if (_glGetError() != GL_NO_ERROR
) return "Can't generate palette lookup texture";
641 /* Bind uniforms in rendering shader program. */
642 GLint tex_location
= _glGetUniformLocation(this->vid_program
, "colour_tex");
643 GLint palette_location
= _glGetUniformLocation(this->vid_program
, "palette");
644 GLint sprite_location
= _glGetUniformLocation(this->vid_program
, "sprite");
645 GLint screen_location
= _glGetUniformLocation(this->vid_program
, "screen");
646 _glUseProgram(this->vid_program
);
647 _glUniform1i(tex_location
, 0); // Texture unit 0.
648 _glUniform1i(palette_location
, 1); // Texture unit 1.
649 /* Values that result in no transform. */
650 _glUniform4f(sprite_location
, 0.0f
, 0.0f
, 1.0f
, 1.0f
);
651 _glUniform2f(screen_location
, 1.0f
, 1.0f
);
653 /* Bind uniforms in palette rendering shader program. */
654 tex_location
= _glGetUniformLocation(this->pal_program
, "colour_tex");
655 palette_location
= _glGetUniformLocation(this->pal_program
, "palette");
656 sprite_location
= _glGetUniformLocation(this->pal_program
, "sprite");
657 screen_location
= _glGetUniformLocation(this->pal_program
, "screen");
658 _glUseProgram(this->pal_program
);
659 _glUniform1i(tex_location
, 0); // Texture unit 0.
660 _glUniform1i(palette_location
, 1); // Texture unit 1.
661 _glUniform4f(sprite_location
, 0.0f
, 0.0f
, 1.0f
, 1.0f
);
662 _glUniform2f(screen_location
, 1.0f
, 1.0f
);
664 /* Bind uniforms in remap shader program. */
665 tex_location
= _glGetUniformLocation(this->remap_program
, "colour_tex");
666 palette_location
= _glGetUniformLocation(this->remap_program
, "palette");
667 GLint remap_location
= _glGetUniformLocation(this->remap_program
, "remap_tex");
668 this->remap_sprite_loc
= _glGetUniformLocation(this->remap_program
, "sprite");
669 this->remap_screen_loc
= _glGetUniformLocation(this->remap_program
, "screen");
670 this->remap_zoom_loc
= _glGetUniformLocation(this->remap_program
, "zoom");
671 this->remap_rgb_loc
= _glGetUniformLocation(this->remap_program
, "rgb");
672 _glUseProgram(this->remap_program
);
673 _glUniform1i(tex_location
, 0); // Texture unit 0.
674 _glUniform1i(palette_location
, 1); // Texture unit 1.
675 _glUniform1i(remap_location
, 2); // Texture unit 2.
677 /* Bind uniforms in sprite shader program. */
678 tex_location
= _glGetUniformLocation(this->sprite_program
, "colour_tex");
679 palette_location
= _glGetUniformLocation(this->sprite_program
, "palette");
680 remap_location
= _glGetUniformLocation(this->sprite_program
, "remap_tex");
681 GLint pal_location
= _glGetUniformLocation(this->sprite_program
, "pal");
682 this->sprite_sprite_loc
= _glGetUniformLocation(this->sprite_program
, "sprite");
683 this->sprite_screen_loc
= _glGetUniformLocation(this->sprite_program
, "screen");
684 this->sprite_zoom_loc
= _glGetUniformLocation(this->sprite_program
, "zoom");
685 this->sprite_rgb_loc
= _glGetUniformLocation(this->sprite_program
, "rgb");
686 this->sprite_crash_loc
= _glGetUniformLocation(this->sprite_program
, "crash");
687 _glUseProgram(this->sprite_program
);
688 _glUniform1i(tex_location
, 0); // Texture unit 0.
689 _glUniform1i(palette_location
, 1); // Texture unit 1.
690 _glUniform1i(remap_location
, 2); // Texture unit 2.
691 _glUniform1i(pal_location
, 3); // Texture unit 3.
692 (void)_glGetError(); // Clear errors.
694 /* Create pixel buffer object as video buffer storage. */
695 _glGenBuffers(1, &this->vid_pbo
);
696 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->vid_pbo
);
697 _glGenBuffers(1, &this->anim_pbo
);
698 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->anim_pbo
);
699 if (_glGetError() != GL_NO_ERROR
) return "Can't allocate pixel buffer for video buffer";
701 /* Prime vertex buffer with a full-screen quad and store
702 * the corresponding state in a vertex array object. */
703 static const Simple2DVertex vert_array
[] = {
705 { 1.f
, -1.f
, 1.f
, 1.f
},
706 { 1.f
, 1.f
, 1.f
, 0.f
},
707 { -1.f
, -1.f
, 0.f
, 1.f
},
708 { -1.f
, 1.f
, 0.f
, 0.f
},
712 _glGenVertexArrays(1, &this->vao_quad
);
713 _glBindVertexArray(this->vao_quad
);
715 /* Create and fill VBO. */
716 _glGenBuffers(1, &this->vbo_quad
);
717 _glBindBuffer(GL_ARRAY_BUFFER
, this->vbo_quad
);
718 _glBufferData(GL_ARRAY_BUFFER
, sizeof(vert_array
), vert_array
, GL_STATIC_DRAW
);
719 if (_glGetError() != GL_NO_ERROR
) return "Can't generate VBO for fullscreen quad";
721 /* Set vertex state. */
722 GLint loc_position
= _glGetAttribLocation(this->vid_program
, "position");
723 GLint colour_position
= _glGetAttribLocation(this->vid_program
, "colour_uv");
724 _glEnableVertexAttribArray(loc_position
);
725 _glEnableVertexAttribArray(colour_position
);
726 _glVertexAttribPointer(loc_position
, 2, GL_FLOAT
, GL_FALSE
, sizeof(Simple2DVertex
), (GLvoid
*)offsetof(Simple2DVertex
, x
));
727 _glVertexAttribPointer(colour_position
, 2, GL_FLOAT
, GL_FALSE
, sizeof(Simple2DVertex
), (GLvoid
*)offsetof(Simple2DVertex
, u
));
728 _glBindVertexArray(0);
730 /* Create resources for sprite rendering. */
731 if (!OpenGLSprite::Create()) return "Failed to create sprite rendering resources";
733 this->PrepareContext();
734 (void)_glGetError(); // Clear errors.
739 void OpenGLBackend::PrepareContext()
741 _glClearColor(0.0f
, 0.0f
, 0.0f
, 1.0f
);
742 _glDisable(GL_DEPTH_TEST
);
743 /* Enable alpha blending using the src alpha factor. */
745 _glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
748 std::string
OpenGLBackend::GetDriverName()
751 /* Skipping GL_VENDOR as it tends to be "obvious" from the renderer and version data, and just makes the string pointlessly longer */
752 res
+= reinterpret_cast<const char *>(_glGetString(GL_RENDERER
));
754 res
+= reinterpret_cast<const char *>(_glGetString(GL_VERSION
));
759 * Check a shader for compilation errors and log them if necessary.
760 * @param shader Shader to check.
761 * @return True if the shader is valid.
763 static bool VerifyShader(GLuint shader
)
765 static ReusableBuffer
<char> log_buf
;
767 GLint result
= GL_FALSE
;
768 _glGetShaderiv(shader
, GL_COMPILE_STATUS
, &result
);
770 /* Output log if there is one. */
772 _glGetShaderiv(shader
, GL_INFO_LOG_LENGTH
, &log_len
);
774 _glGetShaderInfoLog(shader
, log_len
, nullptr, log_buf
.Allocate(log_len
));
775 Debug(driver
, result
!= GL_TRUE
? 0 : 2, "{}", log_buf
.GetBuffer()); // Always print on failure.
778 return result
== GL_TRUE
;
782 * Check a program for link errors and log them if necessary.
783 * @param program Program to check.
784 * @return True if the program is valid.
786 static bool VerifyProgram(GLuint program
)
788 static ReusableBuffer
<char> log_buf
;
790 GLint result
= GL_FALSE
;
791 _glGetProgramiv(program
, GL_LINK_STATUS
, &result
);
793 /* Output log if there is one. */
795 _glGetProgramiv(program
, GL_INFO_LOG_LENGTH
, &log_len
);
797 _glGetProgramInfoLog(program
, log_len
, nullptr, log_buf
.Allocate(log_len
));
798 Debug(driver
, result
!= GL_TRUE
? 0 : 2, "{}", log_buf
.GetBuffer()); // Always print on failure.
801 return result
== GL_TRUE
;
805 * Create all needed shader programs.
806 * @return True if successful, false otherwise.
808 bool OpenGLBackend::InitShaders()
810 const char *ver
= (const char *)_glGetString(GL_SHADING_LANGUAGE_VERSION
);
811 if (ver
== nullptr) return false;
813 int glsl_major
= ver
[0] - '0';
814 int glsl_minor
= ver
[2] - '0';
816 bool glsl_150
= (IsOpenGLVersionAtLeast(3, 2) || glsl_major
> 1 || (glsl_major
== 1 && glsl_minor
>= 5)) && _glBindFragDataLocation
!= nullptr;
818 /* Create vertex shader. */
819 GLuint vert_shader
= _glCreateShader(GL_VERTEX_SHADER
);
820 _glShaderSource(vert_shader
, glsl_150
? lengthof(_vertex_shader_sprite_150
) : lengthof(_vertex_shader_sprite
), glsl_150
? _vertex_shader_sprite_150
: _vertex_shader_sprite
, nullptr);
821 _glCompileShader(vert_shader
);
822 if (!VerifyShader(vert_shader
)) return false;
824 /* Create fragment shader for plain RGBA. */
825 GLuint frag_shader_rgb
= _glCreateShader(GL_FRAGMENT_SHADER
);
826 _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);
827 _glCompileShader(frag_shader_rgb
);
828 if (!VerifyShader(frag_shader_rgb
)) return false;
830 /* Create fragment shader for paletted only. */
831 GLuint frag_shader_pal
= _glCreateShader(GL_FRAGMENT_SHADER
);
832 _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);
833 _glCompileShader(frag_shader_pal
);
834 if (!VerifyShader(frag_shader_pal
)) return false;
836 /* Sprite remap fragment shader. */
837 GLuint remap_shader
= _glCreateShader(GL_FRAGMENT_SHADER
);
838 _glShaderSource(remap_shader
, glsl_150
? lengthof(_frag_shader_rgb_mask_blend_150
) : lengthof(_frag_shader_rgb_mask_blend
), glsl_150
? _frag_shader_rgb_mask_blend_150
: _frag_shader_rgb_mask_blend
, nullptr);
839 _glCompileShader(remap_shader
);
840 if (!VerifyShader(remap_shader
)) return false;
842 /* Sprite fragment shader. */
843 GLuint sprite_shader
= _glCreateShader(GL_FRAGMENT_SHADER
);
844 _glShaderSource(sprite_shader
, glsl_150
? lengthof(_frag_shader_sprite_blend_150
) : lengthof(_frag_shader_sprite_blend
), glsl_150
? _frag_shader_sprite_blend_150
: _frag_shader_sprite_blend
, nullptr);
845 _glCompileShader(sprite_shader
);
846 if (!VerifyShader(sprite_shader
)) return false;
848 /* Link shaders to program. */
849 this->vid_program
= _glCreateProgram();
850 _glAttachShader(this->vid_program
, vert_shader
);
851 _glAttachShader(this->vid_program
, frag_shader_rgb
);
853 this->pal_program
= _glCreateProgram();
854 _glAttachShader(this->pal_program
, vert_shader
);
855 _glAttachShader(this->pal_program
, frag_shader_pal
);
857 this->remap_program
= _glCreateProgram();
858 _glAttachShader(this->remap_program
, vert_shader
);
859 _glAttachShader(this->remap_program
, remap_shader
);
861 this->sprite_program
= _glCreateProgram();
862 _glAttachShader(this->sprite_program
, vert_shader
);
863 _glAttachShader(this->sprite_program
, sprite_shader
);
866 /* Bind fragment shader outputs. */
867 _glBindFragDataLocation(this->vid_program
, 0, "colour");
868 _glBindFragDataLocation(this->pal_program
, 0, "colour");
869 _glBindFragDataLocation(this->remap_program
, 0, "colour");
870 _glBindFragDataLocation(this->sprite_program
, 0, "colour");
873 _glLinkProgram(this->vid_program
);
874 if (!VerifyProgram(this->vid_program
)) return false;
876 _glLinkProgram(this->pal_program
);
877 if (!VerifyProgram(this->pal_program
)) return false;
879 _glLinkProgram(this->remap_program
);
880 if (!VerifyProgram(this->remap_program
)) return false;
882 _glLinkProgram(this->sprite_program
);
883 if (!VerifyProgram(this->sprite_program
)) return false;
885 _glDeleteShader(vert_shader
);
886 _glDeleteShader(frag_shader_rgb
);
887 _glDeleteShader(frag_shader_pal
);
888 _glDeleteShader(remap_shader
);
889 _glDeleteShader(sprite_shader
);
895 * Clear the bound pixel buffer to a specific value.
896 * @param len Length of the buffer.
897 * @param data Value to set.
898 * @tparam T Pixel type.
901 static void ClearPixelBuffer(size_t len
, T data
)
903 T
*buf
= reinterpret_cast<T
*>(_glMapBuffer(GL_PIXEL_UNPACK_BUFFER
, GL_READ_WRITE
));
904 for (size_t i
= 0; i
< len
; i
++) {
907 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER
);
911 * Change the size of the drawing window and allocate matching resources.
912 * @param w New width of the window.
913 * @param h New height of the window.
914 * @param force Recreate resources even if size didn't change.
915 * @param False if nothing had to be done, true otherwise.
917 bool OpenGLBackend::Resize(int w
, int h
, bool force
)
919 if (!force
&& _screen
.width
== w
&& _screen
.height
== h
) return false;
921 int bpp
= BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
922 int pitch
= Align(w
, 4);
924 _glViewport(0, 0, w
, h
);
926 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, pitch
);
928 this->vid_buffer
= nullptr;
929 if (this->persistent_mapping_supported
) {
930 _glDeleteBuffers(1, &this->vid_pbo
);
931 _glGenBuffers(1, &this->vid_pbo
);
932 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->vid_pbo
);
933 _glBufferStorage(GL_PIXEL_UNPACK_BUFFER
, pitch
* h
* bpp
/ 8, nullptr, GL_MAP_READ_BIT
| GL_MAP_WRITE_BIT
| GL_MAP_PERSISTENT_BIT
| GL_MAP_COHERENT_BIT
| GL_CLIENT_STORAGE_BIT
);
935 /* Re-allocate video buffer texture and backing store. */
936 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->vid_pbo
);
937 _glBufferData(GL_PIXEL_UNPACK_BUFFER
, pitch
* h
* bpp
/ 8, nullptr, GL_DYNAMIC_DRAW
);
941 /* Initialize backing store alpha to opaque for 32bpp modes. */
942 Colour
black(0, 0, 0);
943 if (_glClearBufferSubData
!= nullptr) {
944 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER
, GL_RGBA8
, 0, pitch
* h
* bpp
/ 8, GL_BGRA
, GL_UNSIGNED_INT_8_8_8_8_REV
, &black
.data
);
946 ClearPixelBuffer
<uint32
>(pitch
* h
, black
.data
);
948 } else if (bpp
== 8) {
949 if (_glClearBufferSubData
!= nullptr) {
951 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER
, GL_R8
, 0, pitch
* h
, GL_RED
, GL_UNSIGNED_BYTE
, &b
);
953 ClearPixelBuffer
<byte
>(pitch
* h
, 0);
957 _glActiveTexture(GL_TEXTURE0
);
958 _glBindTexture(GL_TEXTURE_2D
, this->vid_texture
);
961 _glTexImage2D(GL_TEXTURE_2D
, 0, GL_R8
, w
, h
, 0, GL_RED
, GL_UNSIGNED_BYTE
, nullptr);
965 _glTexImage2D(GL_TEXTURE_2D
, 0, GL_RGBA8
, w
, h
, 0, GL_BGRA
, GL_UNSIGNED_INT_8_8_8_8_REV
, nullptr);
968 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
970 /* Does this blitter need a separate animation buffer? */
971 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
972 this->anim_buffer
= nullptr;
973 if (this->persistent_mapping_supported
) {
974 _glDeleteBuffers(1, &this->anim_pbo
);
975 _glGenBuffers(1, &this->anim_pbo
);
976 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->anim_pbo
);
977 _glBufferStorage(GL_PIXEL_UNPACK_BUFFER
, pitch
* h
, nullptr, GL_MAP_READ_BIT
| GL_MAP_WRITE_BIT
| GL_MAP_PERSISTENT_BIT
| GL_MAP_COHERENT_BIT
| GL_CLIENT_STORAGE_BIT
);
979 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->anim_pbo
);
980 _glBufferData(GL_PIXEL_UNPACK_BUFFER
, pitch
* h
, nullptr, GL_DYNAMIC_DRAW
);
983 /* Initialize buffer as 0 == no remap. */
984 if (_glClearBufferSubData
!= nullptr) {
986 _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER
, GL_R8
, 0, pitch
* h
, GL_RED
, GL_UNSIGNED_BYTE
, &b
);
988 ClearPixelBuffer
<byte
>(pitch
* h
, 0);
991 _glBindTexture(GL_TEXTURE_2D
, this->anim_texture
);
992 _glTexImage2D(GL_TEXTURE_2D
, 0, GL_R8
, w
, h
, 0, GL_RED
, GL_UNSIGNED_BYTE
, nullptr);
993 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
995 if (this->anim_buffer
!= nullptr) {
996 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->anim_pbo
);
997 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER
);
998 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
999 this->anim_buffer
= nullptr;
1002 /* Allocate dummy texture that always reads as 0 == no remap. */
1004 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, 0);
1005 _glBindTexture(GL_TEXTURE_2D
, this->anim_texture
);
1006 _glTexImage2D(GL_TEXTURE_2D
, 0, GL_R8
, 1, 1, 0, GL_RED
, GL_UNSIGNED_BYTE
, &dummy
);
1009 _glBindTexture(GL_TEXTURE_2D
, 0);
1011 /* Set new viewport. */
1014 _screen
.pitch
= pitch
;
1015 _screen
.dst_ptr
= nullptr;
1017 /* Update screen size in remap shader program. */
1018 _glUseProgram(this->remap_program
);
1019 _glUniform2f(this->remap_screen_loc
, (float)_screen
.width
, (float)_screen
.height
);
1021 _glClear(GL_COLOR_BUFFER_BIT
);
1027 * Update the stored palette.
1028 * @param pal Palette array with at least 256 elements.
1029 * @param first First entry to update.
1030 * @param length Number of entries to update.
1032 void OpenGLBackend::UpdatePalette(const Colour
*pal
, uint first
, uint length
)
1034 assert(first
+ length
<= 256);
1036 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, 0);
1037 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
1038 _glActiveTexture(GL_TEXTURE1
);
1039 _glBindTexture(GL_TEXTURE_1D
, this->pal_texture
);
1040 _glTexSubImage1D(GL_TEXTURE_1D
, 0, first
, length
, GL_BGRA
, GL_UNSIGNED_INT_8_8_8_8_REV
, pal
+ first
);
1044 * Render video buffer to the screen.
1046 void OpenGLBackend::Paint()
1048 _glClear(GL_COLOR_BUFFER_BIT
);
1050 _glDisable(GL_BLEND
);
1052 /* Blit video buffer to screen. */
1053 _glActiveTexture(GL_TEXTURE0
);
1054 _glBindTexture(GL_TEXTURE_2D
, this->vid_texture
);
1055 _glActiveTexture(GL_TEXTURE1
);
1056 _glBindTexture(GL_TEXTURE_1D
, this->pal_texture
);
1057 /* Is the blitter relying on a separate animation buffer? */
1058 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
1059 _glActiveTexture(GL_TEXTURE2
);
1060 _glBindTexture(GL_TEXTURE_2D
, this->anim_texture
);
1061 _glUseProgram(this->remap_program
);
1062 _glUniform4f(this->remap_sprite_loc
, 0.0f
, 0.0f
, 1.0f
, 1.0f
);
1063 _glUniform2f(this->remap_screen_loc
, 1.0f
, 1.0f
);
1064 _glUniform1f(this->remap_zoom_loc
, 0);
1065 _glUniform1i(this->remap_rgb_loc
, 1);
1067 _glUseProgram(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8 ? this->pal_program
: this->vid_program
);
1069 _glBindVertexArray(this->vao_quad
);
1070 _glDrawArrays(GL_TRIANGLE_STRIP
, 0, 4);
1072 _glEnable(GL_BLEND
);
1076 * Draw mouse cursor on screen.
1078 void OpenGLBackend::DrawMouseCursor()
1080 if (!this->cursor_in_window
) return;
1082 /* Draw cursor on screen */
1083 _cur_dpi
= &_screen
;
1084 for (uint i
= 0; i
< this->cursor_sprite_count
; ++i
) {
1085 SpriteID sprite
= this->cursor_sprite_seq
[i
].sprite
;
1087 /* Sprites are cached by PopulateCursorCache(). */
1088 if (this->cursor_cache
.Contains(sprite
)) {
1089 Sprite
*spr
= this->cursor_cache
.Get(sprite
);
1091 this->RenderOglSprite((OpenGLSprite
*)spr
->data
, this->cursor_sprite_seq
[i
].pal
,
1092 this->cursor_pos
.x
+ this->cursor_sprite_pos
[i
].x
+ UnScaleByZoom(spr
->x_offs
, ZOOM_LVL_GUI
),
1093 this->cursor_pos
.y
+ this->cursor_sprite_pos
[i
].y
+ UnScaleByZoom(spr
->y_offs
, ZOOM_LVL_GUI
),
1099 void OpenGLBackend::PopulateCursorCache()
1101 static_assert(lengthof(_cursor
.sprite_seq
) == lengthof(this->cursor_sprite_seq
));
1102 static_assert(lengthof(_cursor
.sprite_pos
) == lengthof(this->cursor_sprite_pos
));
1104 if (this->clear_cursor_cache
) {
1105 /* We have a pending cursor cache clear to do first. */
1106 this->clear_cursor_cache
= false;
1107 this->last_sprite_pal
= (PaletteID
)-1;
1109 this->InternalClearCursorCache();
1112 this->cursor_pos
= _cursor
.pos
;
1113 this->cursor_sprite_count
= _cursor
.sprite_count
;
1114 this->cursor_in_window
= _cursor
.in_window
;
1116 for (uint i
= 0; i
< _cursor
.sprite_count
; ++i
) {
1117 this->cursor_sprite_seq
[i
] = _cursor
.sprite_seq
[i
];
1118 this->cursor_sprite_pos
[i
] = _cursor
.sprite_pos
[i
];
1119 SpriteID sprite
= _cursor
.sprite_seq
[i
].sprite
;
1121 if (!this->cursor_cache
.Contains(sprite
)) {
1122 Sprite
*old
= this->cursor_cache
.Insert(sprite
, (Sprite
*)GetRawSprite(sprite
, ST_NORMAL
, &SimpleSpriteAlloc
, this));
1123 if (old
!= nullptr) {
1124 OpenGLSprite
*sprite
= (OpenGLSprite
*)old
->data
;
1125 sprite
->~OpenGLSprite();
1133 * Clear all cached cursor sprites.
1135 void OpenGLBackend::InternalClearCursorCache()
1138 while ((sp
= this->cursor_cache
.Pop()) != nullptr) {
1139 OpenGLSprite
*sprite
= (OpenGLSprite
*)sp
->data
;
1140 sprite
->~OpenGLSprite();
1146 * Queue a request for cursor cache clear.
1148 void OpenGLBackend::ClearCursorCache()
1150 /* If the game loop is threaded, this function might be called
1151 * from the game thread. As we can call OpenGL functions only
1152 * on the main thread, just set a flag that is handled the next
1153 * time we prepare the cursor cache for drawing. */
1154 this->clear_cursor_cache
= true;
1158 * Get a pointer to the memory for the video driver to draw to.
1159 * @return Pointer to draw on.
1161 void *OpenGLBackend::GetVideoBuffer()
1163 #ifndef NO_GL_BUFFER_SYNC
1164 if (this->sync_vid_mapping
!= nullptr) _glClientWaitSync(this->sync_vid_mapping
, GL_SYNC_FLUSH_COMMANDS_BIT
, 100000000); // 100ms timeout.
1167 if (!this->persistent_mapping_supported
) {
1168 assert(this->vid_buffer
== nullptr);
1169 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->vid_pbo
);
1170 this->vid_buffer
= _glMapBuffer(GL_PIXEL_UNPACK_BUFFER
, GL_READ_WRITE
);
1171 } else if (this->vid_buffer
== nullptr) {
1172 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->vid_pbo
);
1173 this->vid_buffer
= _glMapBufferRange(GL_PIXEL_UNPACK_BUFFER
, 0, _screen
.pitch
* _screen
.height
* BlitterFactory::GetCurrentBlitter()->GetScreenDepth() / 8, GL_MAP_READ_BIT
| GL_MAP_WRITE_BIT
| GL_MAP_PERSISTENT_BIT
| GL_MAP_COHERENT_BIT
);
1176 return this->vid_buffer
;
1180 * Get a pointer to the memory for the separate animation buffer.
1181 * @return Pointer to draw on.
1183 uint8
*OpenGLBackend::GetAnimBuffer()
1185 if (this->anim_pbo
== 0) return nullptr;
1187 #ifndef NO_GL_BUFFER_SYNC
1188 if (this->sync_anim_mapping
!= nullptr) _glClientWaitSync(this->sync_anim_mapping
, GL_SYNC_FLUSH_COMMANDS_BIT
, 100000000); // 100ms timeout.
1191 if (!this->persistent_mapping_supported
) {
1192 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->anim_pbo
);
1193 this->anim_buffer
= _glMapBuffer(GL_PIXEL_UNPACK_BUFFER
, GL_READ_WRITE
);
1194 } else if (this->anim_buffer
== nullptr) {
1195 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->anim_pbo
);
1196 this->anim_buffer
= _glMapBufferRange(GL_PIXEL_UNPACK_BUFFER
, 0, _screen
.pitch
* _screen
.height
, GL_MAP_READ_BIT
| GL_MAP_WRITE_BIT
| GL_MAP_PERSISTENT_BIT
| GL_MAP_COHERENT_BIT
);
1199 return (uint8
*)this->anim_buffer
;
1203 * Update video buffer texture after the video buffer was filled.
1204 * @param update_rect Rectangle encompassing the dirty region of the video buffer.
1206 void OpenGLBackend::ReleaseVideoBuffer(const Rect
&update_rect
)
1208 assert(this->vid_pbo
!= 0);
1210 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->vid_pbo
);
1211 if (!this->persistent_mapping_supported
) {
1212 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER
);
1213 this->vid_buffer
= nullptr;
1216 #ifndef NO_GL_BUFFER_SYNC
1217 if (this->persistent_mapping_supported
) {
1218 _glDeleteSync(this->sync_vid_mapping
);
1219 this->sync_vid_mapping
= nullptr;
1223 /* Update changed rect of the video buffer texture. */
1224 if (!IsEmptyRect(update_rect
)) {
1225 _glActiveTexture(GL_TEXTURE0
);
1226 _glBindTexture(GL_TEXTURE_2D
, this->vid_texture
);
1227 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, _screen
.pitch
);
1228 switch (BlitterFactory::GetCurrentBlitter()->GetScreenDepth()) {
1230 _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
));
1234 _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));
1238 #ifndef NO_GL_BUFFER_SYNC
1239 if (this->persistent_mapping_supported
) this->sync_vid_mapping
= _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE
, 0);
1245 * Update animation buffer texture after the animation buffer was filled.
1246 * @param update_rect Rectangle encompassing the dirty region of the animation buffer.
1248 void OpenGLBackend::ReleaseAnimBuffer(const Rect
&update_rect
)
1250 if (this->anim_pbo
== 0) return;
1252 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, this->anim_pbo
);
1253 if (!this->persistent_mapping_supported
) {
1254 _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER
);
1255 this->anim_buffer
= nullptr;
1258 #ifndef NO_GL_BUFFER_SYNC
1259 if (this->persistent_mapping_supported
) {
1260 _glDeleteSync(this->sync_anim_mapping
);
1261 this->sync_anim_mapping
= nullptr;
1265 /* Update changed rect of the video buffer texture. */
1266 if (update_rect
.left
!= update_rect
.right
) {
1267 _glActiveTexture(GL_TEXTURE0
);
1268 _glBindTexture(GL_TEXTURE_2D
, this->anim_texture
);
1269 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, _screen
.pitch
);
1270 _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
));
1272 #ifndef NO_GL_BUFFER_SYNC
1273 if (this->persistent_mapping_supported
) this->sync_anim_mapping
= _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE
, 0);
1278 /* virtual */ Sprite
*OpenGLBackend::Encode(const SpriteLoader::Sprite
*sprite
, AllocatorProc
*allocator
)
1280 /* Allocate and construct sprite data. */
1281 Sprite
*dest_sprite
= (Sprite
*)allocator(sizeof(*dest_sprite
) + sizeof(OpenGLSprite
));
1283 OpenGLSprite
*gl_sprite
= (OpenGLSprite
*)dest_sprite
->data
;
1284 new (gl_sprite
) OpenGLSprite(sprite
->width
, sprite
->height
, sprite
->type
== ST_FONT
? 1 : ZOOM_LVL_COUNT
, sprite
->colours
);
1286 /* Upload texture data. */
1287 for (int i
= 0; i
< (sprite
->type
== ST_FONT
? 1 : ZOOM_LVL_COUNT
); i
++) {
1288 gl_sprite
->Update(sprite
[i
].width
, sprite
[i
].height
, i
, sprite
[i
].data
);
1291 dest_sprite
->height
= sprite
->height
;
1292 dest_sprite
->width
= sprite
->width
;
1293 dest_sprite
->x_offs
= sprite
->x_offs
;
1294 dest_sprite
->y_offs
= sprite
->y_offs
;
1300 * Render a sprite to the back buffer.
1301 * @param gl_sprite Sprite to render.
1302 * @param x X position of the sprite.
1303 * @param y Y position of the sprite.
1304 * @param zoom Zoom level to use.
1306 void OpenGLBackend::RenderOglSprite(OpenGLSprite
*gl_sprite
, PaletteID pal
, int x
, int y
, ZoomLevel zoom
)
1309 bool rgb
= gl_sprite
->BindTextures();
1310 _glActiveTexture(GL_TEXTURE0
+ 1);
1311 _glBindTexture(GL_TEXTURE_1D
, this->pal_texture
);
1313 /* Set palette remap. */
1314 _glActiveTexture(GL_TEXTURE0
+ 3);
1315 if (pal
!= PAL_NONE
) {
1316 _glBindTexture(GL_TEXTURE_1D
, OpenGLSprite::pal_tex
);
1317 if (pal
!= this->last_sprite_pal
) {
1318 /* Different remap palette in use, update texture. */
1319 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, OpenGLSprite::pal_pbo
);
1320 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, 0);
1322 _glBufferSubData(GL_PIXEL_UNPACK_BUFFER
, 0, 256, GetNonSprite(GB(pal
, 0, PALETTE_WIDTH
), ST_RECOLOUR
) + 1);
1323 _glTexSubImage1D(GL_TEXTURE_1D
, 0, 0, 256, GL_RED
, GL_UNSIGNED_BYTE
, nullptr);
1325 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
1327 this->last_sprite_pal
= pal
;
1330 _glBindTexture(GL_TEXTURE_1D
, OpenGLSprite::pal_identity
);
1333 /* Set up shader program. */
1334 Dimension dim
= gl_sprite
->GetSize(zoom
);
1335 _glUseProgram(this->sprite_program
);
1336 _glUniform4f(this->sprite_sprite_loc
, (float)x
, (float)y
, (float)dim
.width
, (float)dim
.height
);
1337 _glUniform1f(this->sprite_zoom_loc
, (float)(zoom
- ZOOM_LVL_BEGIN
));
1338 _glUniform2f(this->sprite_screen_loc
, (float)_screen
.width
, (float)_screen
.height
);
1339 _glUniform1i(this->sprite_rgb_loc
, rgb
? 1 : 0);
1340 _glUniform1i(this->sprite_crash_loc
, pal
== PALETTE_CRASH
? 1 : 0);
1342 _glBindVertexArray(this->vao_quad
);
1343 _glDrawArrays(GL_TRIANGLE_STRIP
, 0, 4);
1347 /* static */ GLuint
OpenGLSprite::dummy_tex
[] = { 0, 0 };
1348 /* static */ GLuint
OpenGLSprite::pal_identity
= 0;
1349 /* static */ GLuint
OpenGLSprite::pal_tex
= 0;
1350 /* static */ GLuint
OpenGLSprite::pal_pbo
= 0;
1353 * Create all common resources for sprite rendering.
1354 * @return True if no error occurred.
1356 /* static */ bool OpenGLSprite::Create()
1358 _glGenTextures(NUM_TEX
, OpenGLSprite::dummy_tex
);
1360 for (int t
= TEX_RGBA
; t
< NUM_TEX
; t
++) {
1361 _glBindTexture(GL_TEXTURE_2D
, OpenGLSprite::dummy_tex
[t
]);
1363 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST_MIPMAP_NEAREST
);
1364 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
1365 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAX_LEVEL
, 0);
1366 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
1367 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
1370 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
1371 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, 0);
1373 /* Load dummy RGBA texture. */
1374 const Colour
rgb_pixel(0, 0, 0);
1375 _glBindTexture(GL_TEXTURE_2D
, OpenGLSprite::dummy_tex
[TEX_RGBA
]);
1376 _glTexImage2D(GL_TEXTURE_2D
, 0, GL_RGBA8
, 1, 1, 0, GL_BGRA
, GL_UNSIGNED_INT_8_8_8_8_REV
, &rgb_pixel
);
1378 /* Load dummy remap texture. */
1380 _glBindTexture(GL_TEXTURE_2D
, OpenGLSprite::dummy_tex
[TEX_REMAP
]);
1381 _glTexImage2D(GL_TEXTURE_2D
, 0, GL_R8
, 1, 1, 0, GL_RED
, GL_UNSIGNED_BYTE
, &pal
);
1383 /* Create palette remap textures. */
1384 std::array
<uint8
, 256> identity_pal
;
1385 std::iota(std::begin(identity_pal
), std::end(identity_pal
), 0);
1387 /* Permanent texture for identity remap. */
1388 _glGenTextures(1, &OpenGLSprite::pal_identity
);
1389 _glBindTexture(GL_TEXTURE_1D
, OpenGLSprite::pal_identity
);
1390 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST
);
1391 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
1392 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MAX_LEVEL
, 0);
1393 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
1394 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
1395 _glTexImage1D(GL_TEXTURE_1D
, 0, GL_R8
, 256, 0, GL_RED
, GL_UNSIGNED_BYTE
, identity_pal
.data());
1397 /* Dynamically updated texture for remaps. */
1398 _glGenTextures(1, &OpenGLSprite::pal_tex
);
1399 _glBindTexture(GL_TEXTURE_1D
, OpenGLSprite::pal_tex
);
1400 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST
);
1401 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
1402 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_MAX_LEVEL
, 0);
1403 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
1404 _glTexParameteri(GL_TEXTURE_1D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
1405 _glTexImage1D(GL_TEXTURE_1D
, 0, GL_R8
, 256, 0, GL_RED
, GL_UNSIGNED_BYTE
, identity_pal
.data());
1407 /* Pixel buffer for remap updates. */
1408 _glGenBuffers(1, &OpenGLSprite::pal_pbo
);
1409 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, OpenGLSprite::pal_pbo
);
1410 _glBufferData(GL_PIXEL_UNPACK_BUFFER
, 256, identity_pal
.data(), GL_DYNAMIC_DRAW
);
1411 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
1413 return _glGetError() == GL_NO_ERROR
;
1416 /** Free all common resources for sprite rendering. */
1417 /* static */ void OpenGLSprite::Destroy()
1419 _glDeleteTextures(NUM_TEX
, OpenGLSprite::dummy_tex
);
1420 _glDeleteTextures(1, &OpenGLSprite::pal_identity
);
1421 _glDeleteTextures(1, &OpenGLSprite::pal_tex
);
1422 if (_glDeleteBuffers
!= nullptr) _glDeleteBuffers(1, &OpenGLSprite::pal_pbo
);
1426 * Create an OpenGL sprite with a palette remap part.
1427 * @param width Width of the top-level texture.
1428 * @param height Height of the top-level texture.
1429 * @param levels Number of mip-map levels.
1430 * @param components Indicates which sprite components are used.
1432 OpenGLSprite::OpenGLSprite(uint width
, uint height
, uint levels
, SpriteColourComponent components
)
1435 (void)_glGetError();
1437 this->dim
.width
= width
;
1438 this->dim
.height
= height
;
1440 MemSetT(this->tex
, 0, NUM_TEX
);
1441 _glActiveTexture(GL_TEXTURE0
);
1442 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
1444 for (int t
= TEX_RGBA
; t
< NUM_TEX
; t
++) {
1445 /* Sprite component present? */
1446 if (t
== TEX_RGBA
&& components
== SCC_PAL
) continue;
1447 if (t
== TEX_REMAP
&& (components
& SCC_PAL
) != SCC_PAL
) continue;
1449 /* Allocate texture. */
1450 _glGenTextures(1, &this->tex
[t
]);
1451 _glBindTexture(GL_TEXTURE_2D
, this->tex
[t
]);
1453 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_NEAREST_MIPMAP_NEAREST
);
1454 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_NEAREST
);
1455 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAX_LEVEL
, levels
- 1);
1456 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
1457 _glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
1460 for (uint i
= 0, w
= width
, h
= height
; i
< levels
; i
++, w
/= 2, h
/= 2) {
1462 if (t
== TEX_REMAP
) {
1463 _glTexImage2D(GL_TEXTURE_2D
, i
, GL_R8
, w
, h
, 0, GL_RED
, GL_UNSIGNED_BYTE
, nullptr);
1465 _glTexImage2D(GL_TEXTURE_2D
, i
, GL_RGBA8
, w
, h
, 0, GL_BGRA
, GL_UNSIGNED_INT_8_8_8_8_REV
, nullptr);
1470 assert(_glGetError() == GL_NO_ERROR
);
1473 OpenGLSprite::~OpenGLSprite()
1475 _glDeleteTextures(NUM_TEX
, this->tex
);
1479 * Update a single mip-map level with new pixel data.
1480 * @param width Width of the level.
1481 * @param height Height of the level.
1482 * @param level Mip-map level.
1483 * @param data New pixel data.
1485 void OpenGLSprite::Update(uint width
, uint height
, uint level
, const SpriteLoader::CommonPixel
* data
)
1487 static ReusableBuffer
<Colour
> buf_rgba
;
1488 static ReusableBuffer
<uint8
> buf_pal
;
1490 _glActiveTexture(GL_TEXTURE0
);
1491 _glBindBuffer(GL_PIXEL_UNPACK_BUFFER
, 0);
1492 _glPixelStorei(GL_UNPACK_ROW_LENGTH
, 0);
1494 if (this->tex
[TEX_RGBA
] != 0) {
1495 /* Unpack pixel data */
1496 Colour
*rgba
= buf_rgba
.Allocate(width
* height
);
1497 for (size_t i
= 0; i
< width
* height
; i
++) {
1498 rgba
[i
].r
= data
[i
].r
;
1499 rgba
[i
].g
= data
[i
].g
;
1500 rgba
[i
].b
= data
[i
].b
;
1501 rgba
[i
].a
= data
[i
].a
;
1504 _glBindTexture(GL_TEXTURE_2D
, this->tex
[TEX_RGBA
]);
1505 _glTexSubImage2D(GL_TEXTURE_2D
, level
, 0, 0, width
, height
, GL_BGRA
, GL_UNSIGNED_INT_8_8_8_8_REV
, rgba
);
1508 if (this->tex
[TEX_REMAP
] != 0) {
1509 /* Unpack and align pixel data. */
1510 int pitch
= Align(width
, 4);
1512 uint8
*pal
= buf_pal
.Allocate(pitch
* height
);
1513 const SpriteLoader::CommonPixel
*row
= data
;
1514 for (uint y
= 0; y
< height
; y
++, pal
+= pitch
, row
+= width
) {
1515 for (uint x
= 0; x
< width
; x
++) {
1520 _glBindTexture(GL_TEXTURE_2D
, this->tex
[TEX_REMAP
]);
1521 _glTexSubImage2D(GL_TEXTURE_2D
, level
, 0, 0, width
, height
, GL_RED
, GL_UNSIGNED_BYTE
, buf_pal
.GetBuffer());
1524 assert(_glGetError() == GL_NO_ERROR
);
1528 * Query the sprite size at a certain zoom level.
1529 * @param level The zoom level to query.
1530 * @return Sprite size at the given zoom level.
1532 inline Dimension
OpenGLSprite::GetSize(ZoomLevel level
) const
1534 Dimension sd
= { (uint
)UnScaleByZoomLower(this->dim
.width
, level
), (uint
)UnScaleByZoomLower(this->dim
.height
, level
) };
1539 * Bind textures for rendering this sprite.
1540 * @return True if the sprite has RGBA data.
1542 bool OpenGLSprite::BindTextures()
1544 _glActiveTexture(GL_TEXTURE0
);
1545 _glBindTexture(GL_TEXTURE_2D
, this->tex
[TEX_RGBA
] != 0 ? this->tex
[TEX_RGBA
] : OpenGLSprite::dummy_tex
[TEX_RGBA
]);
1546 _glActiveTexture(GL_TEXTURE0
+ 2);
1547 _glBindTexture(GL_TEXTURE_2D
, this->tex
[TEX_REMAP
] != 0 ? this->tex
[TEX_REMAP
] : OpenGLSprite::dummy_tex
[TEX_REMAP
]);
1549 return this->tex
[TEX_RGBA
] != 0;