all repos — mgba @ 09ccf5403eb0a0d85fa119c612b9070fe8807818

mGBA Game Boy Advance Emulator

src/gba/renderers/gl.c (view raw)

   1/* Copyright (c) 2013-2019 Jeffrey Pfau
   2 *
   3 * This Source Code Form is subject to the terms of the Mozilla Public
   4 * License, v. 2.0. If a copy of the MPL was not distributed with this
   5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
   6#include <mgba/internal/gba/renderers/gl.h>
   7
   8#if defined(BUILD_GLES2) || defined(BUILD_GLES3)
   9
  10#include <mgba/core/cache-set.h>
  11#include <mgba/internal/arm/macros.h>
  12#include <mgba/internal/gba/io.h>
  13#include <mgba/internal/gba/renderers/cache-set.h>
  14#include <mgba-util/memory.h>
  15
  16static void GBAVideoGLRendererInit(struct GBAVideoRenderer* renderer);
  17static void GBAVideoGLRendererDeinit(struct GBAVideoRenderer* renderer);
  18static void GBAVideoGLRendererReset(struct GBAVideoRenderer* renderer);
  19static void GBAVideoGLRendererWriteVRAM(struct GBAVideoRenderer* renderer, uint32_t address);
  20static void GBAVideoGLRendererWriteOAM(struct GBAVideoRenderer* renderer, uint32_t oam);
  21static void GBAVideoGLRendererWritePalette(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value);
  22static uint16_t GBAVideoGLRendererWriteVideoRegister(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value);
  23static void GBAVideoGLRendererDrawScanline(struct GBAVideoRenderer* renderer, int y);
  24static void GBAVideoGLRendererFinishFrame(struct GBAVideoRenderer* renderer);
  25static void GBAVideoGLRendererGetPixels(struct GBAVideoRenderer* renderer, size_t* stride, const void** pixels);
  26static void GBAVideoGLRendererPutPixels(struct GBAVideoRenderer* renderer, size_t stride, const void* pixels);
  27
  28static void GBAVideoGLRendererUpdateDISPCNT(struct GBAVideoGLRenderer* renderer);
  29static void GBAVideoGLRendererWriteBGCNT(struct GBAVideoGLBackground* bg, uint16_t value);
  30static void GBAVideoGLRendererWriteBGX_LO(struct GBAVideoGLBackground* bg, uint16_t value);
  31static void GBAVideoGLRendererWriteBGX_HI(struct GBAVideoGLBackground* bg, uint16_t value);
  32static void GBAVideoGLRendererWriteBGY_LO(struct GBAVideoGLBackground* bg, uint16_t value);
  33static void GBAVideoGLRendererWriteBGY_HI(struct GBAVideoGLBackground* bg, uint16_t value);
  34static void GBAVideoGLRendererWriteBLDCNT(struct GBAVideoGLRenderer* renderer, uint16_t value);
  35
  36static void GBAVideoGLRendererDrawSprite(struct GBAVideoGLRenderer* renderer, struct GBAObj* sprite, int y, int spriteY);
  37static void GBAVideoGLRendererDrawBackgroundMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  38static void GBAVideoGLRendererDrawBackgroundMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  39static void GBAVideoGLRendererDrawBackgroundMode3(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  40static void GBAVideoGLRendererDrawBackgroundMode4(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  41static void GBAVideoGLRendererDrawBackgroundMode5(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  42static void GBAVideoGLRendererDrawWindow(struct GBAVideoGLRenderer* renderer, int y);
  43
  44static void _cleanRegister(struct GBAVideoGLRenderer* renderer, int address, uint16_t value);
  45static void _drawScanlines(struct GBAVideoGLRenderer* renderer, int lastY);
  46static void _finalizeLayers(struct GBAVideoGLRenderer* renderer);
  47
  48#define TEST_LAYER_ENABLED(X) !glRenderer->d.disableBG[X] && glRenderer->bg[X].enabled == 4
  49
  50struct GBAVideoGLUniform {
  51	const char* name;
  52	int type;
  53};
  54
  55#define PALETTE_ENTRY "#define PALETTE_ENTRY(x) (vec3((ivec3(0x1F, 0x3E0, 0x7C00) & (x)) >> ivec3(0, 5, 10)) / 31.)\n"
  56
  57static const GLchar* const _gles3Header =
  58	"#version 300 es\n"
  59	"#define OUT(n) layout(location = n)\n"
  60	PALETTE_ENTRY
  61	"precision highp float;\n"
  62	"precision highp int;\n"
  63	"precision highp sampler2D;\n"
  64	"precision highp isampler2D;\n";
  65
  66static const GLchar* const _gl3Header =
  67	"#version 130\n"
  68	"#define OUT(n)\n"
  69	PALETTE_ENTRY
  70	"precision highp float;\n";
  71
  72static const char* const _vertexShader =
  73	"in vec2 position;\n"
  74	"uniform ivec2 loc;\n"
  75	"uniform ivec2 maxPos;\n"
  76	"out vec2 texCoord;\n"
  77
  78	"void main() {\n"
  79	"	vec2 local = vec2(position.x, float(position.y * float(loc.x) + float(loc.y)) / float(maxPos.y));\n"
  80	"	gl_Position = vec4((local * 2. - 1.) * vec2(sign(maxPos)), 0., 1.);\n"
  81	"	texCoord = local * vec2(abs(maxPos));\n"
  82	"}";
  83
  84static const char* const _renderTile16 =
  85	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  86	"	int address = charBase + tile * 16 + (localCoord.x >> 2) + (localCoord.y << 1);\n"
  87	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
  88	"	int entry = int(halfrow[3 - (localCoord.x & 3)] * 15.9);\n"
  89	"	if (entry == 0) {\n"
  90	"		discard;\n"
  91	"	}\n"
  92	"	int paletteEntry = palette[paletteId * 16 + entry];\n"
  93	"	vec4 color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
  94	"	return color;\n"
  95	"}";
  96
  97static const char* const _renderTile256 =
  98	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  99	"	int address = charBase + tile * 32 + (localCoord.x >> 1) + (localCoord.y << 2);\n"
 100	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
 101	"	int entry = int(halfrow[3 - 2 * (localCoord.x & 1)] * 15.9);\n"
 102	"	int pal2 = int(halfrow[2 - 2 * (localCoord.x & 1)] * 15.9);\n"
 103	"	if ((pal2 | entry) == 0) {\n"
 104	"		discard;\n"
 105	"	}\n"
 106	"	int paletteEntry = palette[pal2 * 16 + entry];\n"
 107	"	vec4 color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
 108	"	return color;\n"
 109	"}";
 110
 111static const struct GBAVideoGLUniform _uniformsMode0[] = {
 112	{ "loc", GBA_GL_VS_LOC, },
 113	{ "maxPos", GBA_GL_VS_MAXPOS, },
 114	{ "vram", GBA_GL_BG_VRAM, },
 115	{ "palette", GBA_GL_BG_PALETTE, },
 116	{ "screenBase", GBA_GL_BG_SCREENBASE, },
 117	{ "charBase", GBA_GL_BG_CHARBASE, },
 118	{ "size", GBA_GL_BG_SIZE, },
 119	{ "offset", GBA_GL_BG_OFFSET, },
 120	{ "inflags", GBA_GL_BG_INFLAGS, },
 121	{ "mosaic", GBA_GL_BG_MOSAIC, },
 122	{ 0 }
 123};
 124
 125static const char* const _renderMode0 =
 126	"in vec2 texCoord;\n"
 127	"uniform sampler2D vram;\n"
 128	"uniform int palette[256];\n"
 129	"uniform int screenBase;\n"
 130	"uniform int charBase;\n"
 131	"uniform int size;\n"
 132	"uniform int offset[160];\n"
 133	"uniform ivec4 inflags;\n"
 134	"uniform ivec2 mosaic;\n"
 135	"OUT(0) out vec4 color;\n"
 136	"OUT(1) out ivec4 flags;\n"
 137
 138	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 139
 140	"void main() {\n"
 141	"	ivec2 coord = ivec2(texCoord);\n"
 142	"	if (mosaic.x > 1) {\n"
 143	"		coord.x -= coord.x % mosaic.x;\n"
 144	"	}\n"
 145	"	if (mosaic.y > 1) {\n"
 146	"		coord.y -= coord.y % mosaic.y;\n"
 147	"	}\n"
 148	"	coord += (ivec2(0x3FF, 0x3FF000) & offset[int(texCoord.y)]) >> ivec2(0, 12);\n"
 149	"	ivec2 wrap = ivec2(255, 511);\n"
 150	"	if (size == 3) {\n"
 151	"		coord.y += (coord.y & 256) << 1;\n"
 152	"		wrap.y = 1023;\n"
 153	"	} else if (size == 0) {\n"
 154	"		wrap.y = 255;\n"
 155	"	}\n"
 156	"	if (size != 2) {\n"
 157	"		coord.y &= ~256;\n"
 158	"	}\n"
 159	"	if ((size & 1) == 1) {\n"
 160	"		coord.y += coord.x & 256;\n"
 161	"	}\n"
 162	"	coord &= wrap;\n"
 163	"	int mapAddress = screenBase + (coord.x >> 3) + (coord.y >> 3) * 32;\n"
 164	"	vec4 map = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0);\n"
 165	"	int tileFlags = int(map.g * 15.9);\n"
 166	"	if ((tileFlags & 4) == 4) {\n"
 167	"		coord.x ^= 7;\n"
 168	"	}\n"
 169	"	if ((tileFlags & 8) == 8) {\n"
 170	"		coord.y ^= 7;\n"
 171	"	}\n"
 172	"	int tile = int(map.a * 15.9) + int(map.b * 15.9) * 16 + (tileFlags & 0x3) * 256;\n"
 173	"	color = renderTile(tile, int(map.r * 15.9), coord & 7);\n"
 174	"	flags = inflags;\n"
 175	"}";
 176
 177static const char* const _fetchTileOverflow =
 178	"vec4 fetchTile(ivec2 coord) {\n"
 179	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 180	"	coord &= sizeAdjusted;\n"
 181	"	return renderTile(coord);\n"
 182	"}";
 183
 184static const char* const _fetchTileNoOverflow =
 185	"vec4 fetchTile(ivec2 coord) {\n"
 186	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 187	"	ivec2 outerCoord = coord & ~sizeAdjusted;\n"
 188	"	if ((outerCoord.x | outerCoord.y) != 0) {\n"
 189	"		discard;\n"
 190	"	}\n"
 191	"	return renderTile(coord);\n"
 192	"}";
 193
 194static const struct GBAVideoGLUniform _uniformsMode2[] = {
 195	{ "loc", GBA_GL_VS_LOC, },
 196	{ "maxPos", GBA_GL_VS_MAXPOS, },
 197	{ "vram", GBA_GL_BG_VRAM, },
 198	{ "palette", GBA_GL_BG_PALETTE, },
 199	{ "screenBase", GBA_GL_BG_SCREENBASE, },
 200	{ "charBase", GBA_GL_BG_CHARBASE, },
 201	{ "size", GBA_GL_BG_SIZE, },
 202	{ "inflags", GBA_GL_BG_INFLAGS, },
 203	{ "offset", GBA_GL_BG_OFFSET, },
 204	{ "transform", GBA_GL_BG_TRANSFORM, },
 205	{ "range", GBA_GL_BG_RANGE, },
 206	{ "mosaic", GBA_GL_BG_MOSAIC, },
 207	{ 0 }
 208};
 209
 210static const char* const _interpolate =
 211	"vec2 interpolate(ivec2 arr[4], float x) {\n"
 212	"	float x1m = 1. - x;\n"
 213	"	return x1m * x1m * x1m * vec2(arr[0]) +"
 214		" 3. * x1m * x1m * x   * vec2(arr[1]) +"
 215		" 3. * x1m * x   * x   * vec2(arr[2]) +"
 216		"      x   * x   * x   * vec2(arr[3]);\n"
 217	"}\n"
 218
 219	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]) {\n"
 220	"	int start = max(range.x, y - 3);\n"
 221	"	mat[0] = transform[start + 0].xy;\n"
 222	"	aff[0] = transform[start + 0].zw;\n"
 223	"	mat[1] = transform[start + 1].xy;\n"
 224	"	aff[1] = transform[start + 1].zw;\n"
 225	"	mat[2] = transform[start + 2].xy;\n"
 226	"	aff[2] = transform[start + 2].zw;\n"
 227	"	mat[3] = transform[start + 3].xy;\n"
 228	"	aff[3] = transform[start + 3].zw;\n"
 229	"}\n";
 230
 231static const char* const _renderMode2 =
 232	"in vec2 texCoord;\n"
 233	"uniform sampler2D vram;\n"
 234	"uniform int palette[256];\n"
 235	"uniform int screenBase;\n"
 236	"uniform int charBase;\n"
 237	"uniform int size;\n"
 238	"uniform ivec4 inflags;\n"
 239	"uniform ivec4 transform[160];\n"
 240	"uniform ivec2 range;\n"
 241	"uniform ivec2 mosaic;\n"
 242	"OUT(0) out vec4 color;\n"
 243	"OUT(1) out ivec4 flags;\n"
 244
 245	"vec4 fetchTile(ivec2 coord);\n"
 246	"vec2 interpolate(ivec2 arr[4], float x);\n"
 247	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]);\n"
 248
 249	"vec4 renderTile(ivec2 coord) {\n"
 250	"	int map = (coord.x >> 11) + (((coord.y >> 7) & 0x7F0) << size);\n"
 251	"	int mapAddress = screenBase + (map >> 1);\n"
 252	"	vec4 twomaps = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0);\n"
 253	"	int tile = int(twomaps[3 - 2 * (map & 1)] * 15.9) + int(twomaps[2 - 2 * (map & 1)] * 15.9) * 16;\n"
 254	"	int address = charBase + tile * 32 + ((coord.x >> 9) & 3) + ((coord.y >> 6) & 0x1C);\n"
 255	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
 256	"	int entry = int(halfrow[3 - ((coord.x >> 7) & 2)] * 15.9);\n"
 257	"	int pal2 = int(halfrow[2 - ((coord.x >> 7) & 2)] * 15.9);\n"
 258	"	if ((pal2 | entry) == 0) {\n"
 259	"		discard;\n"
 260	"	}\n"
 261	"	int paletteEntry = palette[pal2 * 16 + entry];\n"
 262	"	vec4 color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
 263	"	return color;\n"
 264	"}\n"
 265
 266	"void main() {\n"
 267	"	ivec2 mat[4];\n"
 268	"	ivec2 offset[4];\n"
 269	"	vec2 incoord = texCoord;\n"
 270	"	if (mosaic.x > 1) {\n"
 271	"		incoord.x = float(int(incoord.x) % mosaic.x);\n"
 272	"	}\n"
 273	"	if (mosaic.y > 1) {\n"
 274	"		incoord.y = float(int(incoord.y) % mosaic.y);\n"
 275	"	}\n"
 276	"	loadAffine(int(incoord.y), mat, offset);\n"
 277	"	float y = fract(incoord.y);\n"
 278	"	float start = 0.75;\n"
 279	"	if (int(incoord.y) - range.x < 4) {\n"
 280	"		y = incoord.y - float(range.x);\n"
 281	"		start = 0.;\n"
 282	"	}\n"
 283	"	float lin = start + y * 0.25;\n"
 284	"	vec2 mixedTransform = interpolate(mat, lin);\n"
 285	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 286	"	color = fetchTile(ivec2(mixedTransform * incoord.x + mixedOffset));\n"
 287	"	flags = inflags;\n"
 288	"}";
 289
 290static const struct GBAVideoGLUniform _uniformsMode35[] = {
 291	{ "loc", GBA_GL_VS_LOC, },
 292	{ "maxPos", GBA_GL_VS_MAXPOS, },
 293	{ "vram", GBA_GL_BG_VRAM, },
 294	{ "charBase", GBA_GL_BG_CHARBASE, },
 295	{ "size", GBA_GL_BG_SIZE, },
 296	{ "inflags", GBA_GL_BG_INFLAGS, },
 297	{ "offset", GBA_GL_BG_OFFSET, },
 298	{ "transform", GBA_GL_BG_TRANSFORM, },
 299	{ "range", GBA_GL_BG_RANGE, },
 300	{ "mosaic", GBA_GL_BG_MOSAIC, },
 301	{ 0 }
 302};
 303
 304static const char* const _renderMode35 =
 305	"in vec2 texCoord;\n"
 306	"uniform sampler2D vram;\n"
 307	"uniform int charBase;\n"
 308	"uniform ivec2 size;\n"
 309	"uniform ivec4 inflags;\n"
 310	"uniform ivec4 transform[160];\n"
 311	"uniform ivec2 range;\n"
 312	"uniform ivec2 mosaic;\n"
 313	"OUT(0) out vec4 color;\n"
 314	"OUT(1) out ivec4 flags;\n"
 315
 316	"vec2 interpolate(ivec2 arr[4], float x);\n"
 317	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]);\n"
 318
 319	"void main() {\n"
 320	"	ivec2 mat[4];\n"
 321	"	ivec2 offset[4];\n"
 322	"	vec2 incoord = texCoord;\n"
 323	"	if (mosaic.x > 1) {\n"
 324	"		incoord.x = float(int(incoord.x) % mosaic.x);\n"
 325	"	}\n"
 326	"	if (mosaic.y > 1) {\n"
 327	"		incoord.y = float(int(incoord.y) % mosaic.y);\n"
 328	"	}\n"
 329	"	loadAffine(int(incoord.y), mat, offset);\n"
 330	"	float y = fract(incoord.y);\n"
 331	"	float start = 0.75;\n"
 332	"	if (int(incoord.y) - range.x < 4) {\n"
 333	"		y = incoord.y - float(range.x);\n"
 334	"		start = 0.;\n"
 335	"	}\n"
 336	"	float lin = start + y * 0.25;\n"
 337	"	vec2 mixedTransform = interpolate(mat, lin);\n"
 338	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 339	"	ivec2 coord = ivec2(mixedTransform * incoord.x + mixedOffset);\n"
 340	"	if (coord.x < 0 || coord.x >= (size.x << 8)) {\n"
 341	"		discard;\n"
 342	"	}\n"
 343	"	if (coord.y < 0 || coord.y >= (size.y << 8)) {\n"
 344	"		discard;\n"
 345	"	}\n"
 346	"	int address = charBase + (coord.x >> 8) + (coord.y >> 8) * size.x;\n"
 347	"	ivec4 entry = ivec4(texelFetch(vram, ivec2(address & 255, address >> 8), 0) * 15.9);\n"
 348	"	int sixteen = (entry.x << 12) | (entry.y << 8) | (entry.z << 4) | entry.w;\n"
 349	"	color = vec4(float(sixteen & 0x1F) / 31., float((sixteen >> 5) & 0x1F) / 31., float((sixteen >> 10) & 0x1F) / 31., 1.);\n"
 350	"	flags = inflags;\n"
 351	"}";
 352
 353static const struct GBAVideoGLUniform _uniformsMode4[] = {
 354	{ "loc", GBA_GL_VS_LOC, },
 355	{ "maxPos", GBA_GL_VS_MAXPOS, },
 356	{ "vram", GBA_GL_BG_VRAM, },
 357	{ "palette", GBA_GL_BG_PALETTE, },
 358	{ "charBase", GBA_GL_BG_CHARBASE, },
 359	{ "size", GBA_GL_BG_SIZE, },
 360	{ "inflags", GBA_GL_BG_INFLAGS, },
 361	{ "offset", GBA_GL_BG_OFFSET, },
 362	{ "transform", GBA_GL_BG_TRANSFORM, },
 363	{ "range", GBA_GL_BG_RANGE, },
 364	{ "mosaic", GBA_GL_BG_MOSAIC, },
 365	{ 0 }
 366};
 367
 368static const char* const _renderMode4 =
 369	"in vec2 texCoord;\n"
 370	"uniform sampler2D vram;\n"
 371	"uniform int palette[256];\n"
 372	"uniform int charBase;\n"
 373	"uniform ivec2 size;\n"
 374	"uniform ivec4 inflags;\n"
 375	"uniform ivec4 transform[160];\n"
 376	"uniform ivec2 range;\n"
 377	"uniform ivec2 mosaic;\n"
 378	"OUT(0) out vec4 color;\n"
 379	"OUT(1) out ivec4 flags;\n"
 380
 381	"vec2 interpolate(ivec2 arr[4], float x);\n"
 382	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]);\n"
 383
 384	"void main() {\n"
 385	"	ivec2 mat[4];\n"
 386	"	ivec2 offset[4];\n"
 387	"	vec2 incoord = texCoord;\n"
 388	"	if (mosaic.x > 1) {\n"
 389	"		incoord.x = float(int(incoord.x) % mosaic.x);\n"
 390	"	}\n"
 391	"	if (mosaic.y > 1) {\n"
 392	"		incoord.y = float(int(incoord.y) % mosaic.y);\n"
 393	"	}\n"
 394	"	loadAffine(int(incoord.y), mat, offset);\n"
 395	"	float y = fract(incoord.y);\n"
 396	"	float start = 0.75;\n"
 397	"	if (int(incoord.y) - range.x < 4) {\n"
 398	"		y = incoord.y - float(range.x);\n"
 399	"		start = 0.;\n"
 400	"	}\n"
 401	"	float lin = start + y * 0.25;\n"
 402	"	vec2 mixedTransform = interpolate(mat, lin);\n"
 403	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 404	"	ivec2 coord = ivec2(mixedTransform * incoord.x + mixedOffset);\n"
 405	"	if (coord.x < 0 || coord.x >= (size.x << 8)) {\n"
 406	"		discard;\n"
 407	"	}\n"
 408	"	if (coord.y < 0 || coord.y >= (size.y << 8)) {\n"
 409	"		discard;\n"
 410	"	}\n"
 411	"	int address = charBase + (coord.x >> 8) + (coord.y >> 8) * size.x;\n"
 412	"	vec4 twoEntries = texelFetch(vram, ivec2((address >> 1) & 255, address >> 9), 0);\n"
 413	"	ivec2 entry = ivec2(twoEntries[3 - 2 * (address & 1)] * 15.9, twoEntries[2 - 2 * (address & 1)] * 15.9);\n"
 414	"	int paletteEntry = palette[entry.y * 16 + entry.x];\n"
 415	"	color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
 416	"	flags = inflags;\n"
 417	"}";
 418
 419static const struct GBAVideoGLUniform _uniformsObj[] = {
 420	{ "loc", GBA_GL_VS_LOC, },
 421	{ "maxPos", GBA_GL_VS_MAXPOS, },
 422	{ "vram", GBA_GL_OBJ_VRAM, },
 423	{ "palette", GBA_GL_OBJ_PALETTE, },
 424	{ "charBase", GBA_GL_OBJ_CHARBASE, },
 425	{ "stride", GBA_GL_OBJ_STRIDE, },
 426	{ "localPalette", GBA_GL_OBJ_LOCALPALETTE, },
 427	{ "inflags", GBA_GL_OBJ_INFLAGS, },
 428	{ "transform", GBA_GL_OBJ_TRANSFORM, },
 429	{ "dims", GBA_GL_OBJ_DIMS, },
 430	{ "objwin", GBA_GL_OBJ_OBJWIN, },
 431	{ "mosaic", GBA_GL_OBJ_MOSAIC, },
 432	{ 0 }
 433};
 434
 435static const char* const _renderObj =
 436	"in vec2 texCoord;\n"
 437	"uniform sampler2D vram;\n"
 438	"uniform int palette[256];\n"
 439	"uniform int charBase;\n"
 440	"uniform int stride;\n"
 441	"uniform int localPalette;\n"
 442	"uniform ivec4 inflags;\n"
 443	"uniform mat2x2 transform;\n"
 444	"uniform ivec4 dims;\n"
 445	"uniform ivec4 objwin;\n"
 446	"uniform ivec4 mosaic;\n"
 447	"OUT(0) out vec4 color;\n"
 448	"OUT(1) out ivec4 flags;\n"
 449	"OUT(2) out ivec4 window;\n"
 450
 451	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 452
 453	"void main() {\n"
 454	"	vec2 incoord = texCoord;\n"
 455	"	if (mosaic.x > 1) {\n"
 456	"		int x = int(incoord.x);\n"
 457	"		incoord.x = float(clamp(x - (mosaic.z + x) % mosaic.x, 0, dims.z - 1));\n"
 458	"	} else if (mosaic.x < -1) {\n"
 459	"		int x = dims.z - int(incoord.x) - 1;\n"
 460	"		incoord.x = float(clamp(dims.z - x + (mosaic.z + x) % -mosaic.x - 1, 0, dims.z - 1));\n"
 461	"	}\n"
 462	"	if (mosaic.y > 1) {\n"
 463	"		int y = int(incoord.y);\n"
 464	"		incoord.y = float(clamp(y - (mosaic.w + y) % mosaic.y, 0, dims.w - 1));\n"
 465	"	}\n"
 466	"	ivec2 coord = ivec2(transform * (incoord - vec2(dims.zw) / 2.) + vec2(dims.xy) / 2.);\n"
 467	"	if ((coord & ~(dims.xy - 1)) != ivec2(0, 0)) {\n"
 468	"		discard;\n"
 469	"	}\n"
 470	"	vec4 pix = renderTile((coord.x >> 3) + (coord.y >> 3) * stride, localPalette, coord & 7);\n"
 471	"	color = pix;\n"
 472	"	flags = inflags;\n"
 473	"	gl_FragDepth = float(flags.x) / 16.;\n"
 474	"	window = ivec4(objwin.yzw, 0);\n"
 475	"}";
 476
 477static const struct GBAVideoGLUniform _uniformsWindow[] = {
 478	{ "loc", GBA_GL_VS_LOC, },
 479	{ "maxPos", GBA_GL_VS_MAXPOS, },
 480	{ "dispcnt", GBA_GL_WIN_DISPCNT, },
 481	{ "blend", GBA_GL_WIN_BLEND, },
 482	{ "flags", GBA_GL_WIN_FLAGS, },
 483	{ "win0", GBA_GL_WIN_WIN0, },
 484	{ "win1", GBA_GL_WIN_WIN1, },
 485	{ 0 }
 486};
 487
 488static const char* const _renderWindow =
 489	"in vec2 texCoord;\n"
 490	"uniform int dispcnt;\n"
 491	"uniform ivec2 blend;\n"
 492	"uniform ivec3 flags;\n"
 493	"uniform ivec4 win0[160];\n"
 494	"uniform ivec4 win1[160];\n"
 495	"OUT(0) out ivec4 window;\n"
 496
 497	"void crop(vec4 windowParams, int flags, inout ivec3 windowFlags) {\n"
 498	"	bvec4 compare = lessThan(texCoord.xxyy, windowParams);\n"
 499	"	compare = equal(compare, bvec4(true, false, true, false));\n"
 500	"	if (any(compare)) {\n"
 501	"		vec2 h = windowParams.xy;\n"
 502	"		vec2 v = windowParams.zw;\n"
 503	"		if (v.x > v.y) {\n"
 504	"			if (compare.z && compare.w) {\n"
 505	"				return;\n"
 506	"			}\n"
 507	"		} else if (compare.z || compare.w) {\n"
 508	"			return;\n"
 509	"		}\n"
 510	"		if (h.x > h.y) {\n"
 511	"			if (compare.x && compare.y) {\n"
 512	"				return;\n"
 513	"			}\n"
 514	"		} else if (compare.x || compare.y) {\n"
 515	"			return;\n"
 516	"		}\n"
 517	"	}\n"
 518	"	windowFlags.x = flags;\n"
 519	"}\n"
 520
 521	"vec4 interpolate(ivec4 win[160]) {\n"
 522	"	vec4 bottom = vec4(win[int(texCoord.y) - 1]);\n"
 523	"	vec4 top = vec4(win[int(texCoord.y)]);\n"
 524	"	if (distance(top, bottom) > 40.) {\n"
 525	"		return top;\n"
 526	"	}\n"
 527	"	return vec4(mix(bottom.xy, top.xy, fract(texCoord.y)), top.zw);\n"
 528	"}\n"
 529
 530	"void main() {\n"
 531	"	int dispflags = (dispcnt & 0x1F) | 0x20;\n"
 532	"	if ((dispcnt & 0xE0) == 0) {\n"
 533	"		window = ivec4(dispflags, blend, 0);\n"
 534	"	} else {\n"
 535	"		ivec3 windowFlags = ivec3(flags.z, blend);\n"
 536	"		if ((dispcnt & 0x40) != 0) { \n"
 537	"			crop(interpolate(win1), flags.y, windowFlags);\n"
 538	"		}\n"
 539	"		if ((dispcnt & 0x20) != 0) { \n"
 540	"			crop(interpolate(win0), flags.x, windowFlags);\n"
 541	"		}\n"
 542	"		window = ivec4(windowFlags, 0);\n"
 543	"	}\n"
 544	"}\n";
 545
 546static const struct GBAVideoGLUniform _uniformsFinalize[] = {
 547	{ "loc", GBA_GL_VS_LOC, },
 548	{ "maxPos", GBA_GL_VS_MAXPOS, },
 549	{ "scale", GBA_GL_FINALIZE_SCALE, },
 550	{ "layers", GBA_GL_FINALIZE_LAYERS, },
 551	{ "flags", GBA_GL_FINALIZE_FLAGS, },
 552	{ "window", GBA_GL_FINALIZE_WINDOW, },
 553	{ "backdrop", GBA_GL_FINALIZE_BACKDROP, },
 554	{ "backdropFlags", GBA_GL_FINALIZE_BACKDROPFLAGS, },
 555	{ 0 }
 556};
 557
 558static const char* const _finalize =
 559	"in vec2 texCoord;\n"
 560	"uniform int scale;\n"
 561	"uniform sampler2D layers[5];\n"
 562	"uniform isampler2D flags[5];\n"
 563	"uniform isampler2D window;\n"
 564	"uniform sampler2D backdrop;\n"
 565	"uniform isampler2D backdropFlags;\n"
 566	"out vec4 color;\n"
 567
 568	"void composite(vec4 pixel, ivec4 flags, inout vec4 topPixel, inout ivec4 topFlags, inout vec4 bottomPixel, inout ivec4 bottomFlags) {\n"
 569	"	if (pixel.a == 0.) {\n"
 570	"		return;\n"
 571	"	}\n"
 572	"	if (flags.x >= topFlags.x) {\n"
 573	"		if (flags.x >= bottomFlags.x) {\n"
 574	"			return;\n"
 575	"		}\n"
 576	"		bottomFlags = flags;\n"
 577	"		bottomPixel = pixel;\n"
 578	"	} else {\n"
 579	"		bottomFlags = topFlags;\n"
 580	"		topFlags = flags;\n"
 581	"		bottomPixel = topPixel;\n"
 582	"		topPixel = pixel;\n"
 583	"	}\n"
 584	"}\n"
 585
 586	"void main() {\n"
 587	"	vec4 topPixel = texelFetch(backdrop, ivec2(0, texCoord.y), 0);\n"
 588	"	vec4 bottomPixel = topPixel;\n"
 589	"	ivec4 topFlags = ivec4(texelFetch(backdropFlags, ivec2(0, texCoord.y), 0));\n"
 590	"	ivec4 bottomFlags = topFlags;\n"
 591	"	ivec4 windowFlags = texelFetch(window, ivec2(texCoord * float(scale)), 0);\n"
 592	"	int layerWindow = windowFlags.x;\n"
 593	"	if ((layerWindow & 16) != 0) {\n"
 594	"		vec4 pix = texelFetch(layers[4], ivec2(texCoord * float(scale)), 0);\n"
 595	"		ivec4 inflags = ivec4(texelFetch(flags[4], ivec2(texCoord * float(scale)), 0));\n"
 596	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 597	"	}\n"
 598	"	if ((layerWindow & 1) != 0) {\n"
 599	"		vec4 pix = texelFetch(layers[0], ivec2(texCoord * float(scale)), 0);\n"
 600	"		ivec4 inflags = ivec4(texelFetch(flags[0], ivec2(texCoord * float(scale)), 0).xyz, 0);\n"
 601	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 602	"	}\n"
 603	"	if ((layerWindow & 2) != 0) {\n"
 604	"		vec4 pix = texelFetch(layers[1], ivec2(texCoord * float(scale)), 0);\n"
 605	"		ivec4 inflags = ivec4(texelFetch(flags[1], ivec2(texCoord * float(scale)), 0).xyz, 0);\n"
 606	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 607	"	}\n"
 608	"	if ((layerWindow & 4) != 0) {\n"
 609	"		vec4 pix = texelFetch(layers[2], ivec2(texCoord * float(scale)), 0);\n"
 610	"		ivec4 inflags = ivec4(texelFetch(flags[2], ivec2(texCoord * float(scale)), 0).xyz.xyz, 0);\n"
 611	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 612	"	}\n"
 613	"	if ((layerWindow & 8) != 0) {\n"
 614	"		vec4 pix = texelFetch(layers[3], ivec2(texCoord * float(scale)), 0);\n"
 615	"		ivec4 inflags = ivec4(texelFetch(flags[3], ivec2(texCoord * float(scale)), 0).xyz, 0);\n"
 616	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 617	"	}\n"
 618	"	if ((layerWindow & 32) == 0) {\n"
 619	"		topFlags.y &= ~1;\n"
 620	"	}\n"
 621	"	if (((topFlags.y & 13) == 5 || topFlags.w > 0) && (bottomFlags.y & 2) == 2) {\n"
 622	"		topPixel.rgb *= float(topFlags.z) / 16.;\n"
 623	"		topPixel.rgb += bottomPixel.rgb * float(windowFlags.y) / 16.;\n"
 624	"	} else if ((topFlags.y & 13) == 9) {\n"
 625	"		topPixel.rgb += (1. - topPixel.rgb) * float(windowFlags.z) / 16.;\n"
 626	"	} else if ((topFlags.y & 13) == 13) {\n"
 627	"		topPixel.rgb -= topPixel.rgb * float(windowFlags.z) / 16.;\n"
 628	"	}\n"
 629	"	color = topPixel;\n"
 630	"}";
 631
 632static const GLint _vertices[] = {
 633	0, 0,
 634	0, 1,
 635	1, 1,
 636	1, 0,
 637};
 638
 639void GBAVideoGLRendererCreate(struct GBAVideoGLRenderer* renderer) {
 640	renderer->d.init = GBAVideoGLRendererInit;
 641	renderer->d.reset = GBAVideoGLRendererReset;
 642	renderer->d.deinit = GBAVideoGLRendererDeinit;
 643	renderer->d.writeVideoRegister = GBAVideoGLRendererWriteVideoRegister;
 644	renderer->d.writeVRAM = GBAVideoGLRendererWriteVRAM;
 645	renderer->d.writeOAM = GBAVideoGLRendererWriteOAM;
 646	renderer->d.writePalette = GBAVideoGLRendererWritePalette;
 647	renderer->d.drawScanline = GBAVideoGLRendererDrawScanline;
 648	renderer->d.finishFrame = GBAVideoGLRendererFinishFrame;
 649	renderer->d.getPixels = GBAVideoGLRendererGetPixels;
 650	renderer->d.putPixels = GBAVideoGLRendererPutPixels;
 651
 652	renderer->d.disableBG[0] = false;
 653	renderer->d.disableBG[1] = false;
 654	renderer->d.disableBG[2] = false;
 655	renderer->d.disableBG[3] = false;
 656	renderer->d.disableOBJ = false;
 657
 658	renderer->d.highlightBG[0] = false;
 659	renderer->d.highlightBG[1] = false;
 660	renderer->d.highlightBG[2] = false;
 661	renderer->d.highlightBG[3] = false;
 662	int i;
 663	for (i = 0; i < 128; ++i) {
 664		renderer->d.highlightOBJ[i] = false;
 665	}
 666	renderer->d.highlightColor = 0xFFFFFF;
 667	renderer->d.highlightAmount = 0;
 668
 669	renderer->scale = 1;
 670}
 671
 672static void _compileShader(struct GBAVideoGLRenderer* glRenderer, struct GBAVideoGLShader* shader, const char** shaderBuffer, int shaderBufferLines, GLuint vs, const struct GBAVideoGLUniform* uniforms, char* log) {
 673	GLuint program = glCreateProgram();
 674	shader->program = program;
 675
 676	GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
 677	glAttachShader(program, vs);
 678	glAttachShader(program, fs);
 679	glShaderSource(fs, shaderBufferLines, shaderBuffer, 0);
 680	glCompileShader(fs);
 681	glGetShaderInfoLog(fs, 2048, 0, log);
 682	if (log[0]) {
 683		mLOG(GBA_VIDEO, ERROR, "Fragment shader compilation failure: %s", log);
 684	}
 685	glLinkProgram(program);
 686	glGetProgramInfoLog(program, 2048, 0, log);
 687	if (log[0]) {
 688		mLOG(GBA_VIDEO, ERROR, "Program link failure: %s", log);
 689	}
 690	glDeleteShader(fs);
 691#ifndef BUILD_GLES3
 692	glBindFragDataLocation(program, 0, "color");
 693	glBindFragDataLocation(program, 1, "flags");
 694#endif
 695
 696	glGenVertexArrays(1, &shader->vao);
 697	glBindVertexArray(shader->vao);
 698	glBindBuffer(GL_ARRAY_BUFFER, glRenderer->vbo);
 699	GLuint positionLocation = glGetAttribLocation(program, "position");
 700	glEnableVertexAttribArray(positionLocation);
 701	glVertexAttribPointer(positionLocation, 2, GL_INT, GL_FALSE, 0, NULL);
 702
 703	size_t i;
 704	for (i = 0; uniforms[i].name; ++i) {
 705		shader->uniforms[uniforms[i].type] = glGetUniformLocation(program, uniforms[i].name);
 706	}
 707}
 708
 709static void _deleteShader(struct GBAVideoGLShader* shader) {
 710	glDeleteProgram(shader->program);
 711	glDeleteVertexArrays(1, &shader->vao);
 712}
 713
 714static void _initFramebufferTextureEx(GLuint tex, GLenum internalFormat, GLenum format, GLenum type, GLenum attachment, int scale) {
 715	glBindTexture(GL_TEXTURE_2D, tex);
 716	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 717	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 718	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 719	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 720	glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, scale > 0 ? GBA_VIDEO_HORIZONTAL_PIXELS * scale : 1, GBA_VIDEO_VERTICAL_PIXELS * (scale > 0 ? scale : 1), 0, format, type, 0);
 721	glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, tex, 0);	
 722}
 723
 724static void _initFramebufferTexture(GLuint tex, GLenum format, GLenum attachment, int scale) {
 725	_initFramebufferTextureEx(tex, format, format, GL_UNSIGNED_BYTE, attachment, scale);
 726}
 727
 728void GBAVideoGLRendererInit(struct GBAVideoRenderer* renderer) {
 729	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 730	glRenderer->temporaryBuffer = NULL;
 731
 732	glGenFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 733	glGenTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 734
 735	glGenTextures(1, &glRenderer->vramTex);
 736	glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
 737	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 738	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 739	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, 256, 192, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 0);
 740
 741	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
 742	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_OBJ_COLOR], GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 743	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_OBJ_FLAGS], GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 744	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_WINDOW], GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT2, glRenderer->scale);
 745	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_OBJ_DEPTH], GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_DEPTH_ATTACHMENT, glRenderer->scale);
 746
 747	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_BACKDROP]);
 748	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_BACKDROP_COLOR], GL_RGB, GL_COLOR_ATTACHMENT0, 0);
 749	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_BACKDROP_FLAGS], GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 750
 751	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_WINDOW]);
 752	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_WINDOW], GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 753
 754	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OUTPUT]);
 755	_initFramebufferTexture(glRenderer->outputTex, GL_RGB, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 756
 757	glBindFramebuffer(GL_FRAMEBUFFER, 0);
 758
 759	glGenBuffers(1, &glRenderer->vbo);
 760	glBindBuffer(GL_ARRAY_BUFFER, glRenderer->vbo);
 761	glBufferData(GL_ARRAY_BUFFER, sizeof(_vertices), _vertices, GL_STATIC_DRAW);
 762
 763	int i;
 764	for (i = 0; i < 4; ++i) {
 765		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 766		bg->index = i;
 767		bg->enabled = 0;
 768		bg->priority = 0;
 769		bg->charBase = 0;
 770		bg->mosaic = 0;
 771		bg->multipalette = 0;
 772		bg->screenBase = 0;
 773		bg->overflow = 0;
 774		bg->size = 0;
 775		bg->target1 = 0;
 776		bg->target2 = 0;
 777		bg->x = 0;
 778		bg->y = 0;
 779		bg->refx = 0;
 780		bg->refy = 0;
 781		bg->affine.dx = 256;
 782		bg->affine.dmx = 0;
 783		bg->affine.dy = 0;
 784		bg->affine.dmy = 256;
 785		bg->affine.sx = 0;
 786		bg->affine.sy = 0;
 787		glGenFramebuffers(1, &bg->fbo);
 788		glGenTextures(1, &bg->tex);
 789		glGenTextures(1, &bg->flags);
 790		glBindFramebuffer(GL_FRAMEBUFFER, bg->fbo);
 791		_initFramebufferTexture(bg->tex, GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 792		_initFramebufferTextureEx(bg->flags, GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 793	}
 794	glBindFramebuffer(GL_FRAMEBUFFER, 0);
 795
 796	char log[2048];
 797	const GLchar* shaderBuffer[4];
 798	const GLubyte* version = glGetString(GL_VERSION);
 799	if (strncmp((const char*) version, "OpenGL ES ", strlen("OpenGL ES "))) {
 800		shaderBuffer[0] = _gl3Header;
 801	} else {
 802		shaderBuffer[0] = _gles3Header;
 803	}
 804
 805	GLuint vs = glCreateShader(GL_VERTEX_SHADER);
 806	shaderBuffer[1] = _vertexShader;
 807	glShaderSource(vs, 2, shaderBuffer, 0);
 808	glCompileShader(vs);
 809	glGetShaderInfoLog(vs, 2048, 0, log);
 810	if (log[0]) {
 811		mLOG(GBA_VIDEO, ERROR, "Vertex shader compilation failure: %s", log);
 812	}
 813
 814	shaderBuffer[1] = _renderMode0;
 815
 816	shaderBuffer[2] = _renderTile16;
 817	_compileShader(glRenderer, &glRenderer->bgShader[0], shaderBuffer, 3, vs, _uniformsMode0, log);
 818
 819	shaderBuffer[2] = _renderTile256;
 820	_compileShader(glRenderer, &glRenderer->bgShader[1], shaderBuffer, 3, vs, _uniformsMode0, log);
 821
 822	shaderBuffer[1] = _renderMode2;
 823	shaderBuffer[2] = _interpolate;
 824
 825	shaderBuffer[3] = _fetchTileOverflow;
 826	_compileShader(glRenderer, &glRenderer->bgShader[2], shaderBuffer, 4, vs, _uniformsMode2, log);
 827
 828	shaderBuffer[3] = _fetchTileNoOverflow;
 829	_compileShader(glRenderer, &glRenderer->bgShader[3], shaderBuffer, 4, vs, _uniformsMode2, log);
 830
 831	shaderBuffer[1] = _renderMode4;
 832	shaderBuffer[2] = _interpolate;
 833	_compileShader(glRenderer, &glRenderer->bgShader[4], shaderBuffer, 3, vs, _uniformsMode4, log);
 834
 835	shaderBuffer[1] = _renderMode35;
 836	shaderBuffer[2] = _interpolate;
 837	_compileShader(glRenderer, &glRenderer->bgShader[5], shaderBuffer, 3, vs, _uniformsMode35, log);
 838
 839	shaderBuffer[1] = _renderObj;
 840
 841	shaderBuffer[2] = _renderTile16;
 842	_compileShader(glRenderer, &glRenderer->objShader[0], shaderBuffer, 3, vs, _uniformsObj, log);
 843#ifndef BUILD_GLES3
 844	glBindFragDataLocation(glRenderer->objShader[0].program, 2, "window");
 845#endif
 846
 847	shaderBuffer[2] = _renderTile256;
 848	_compileShader(glRenderer, &glRenderer->objShader[1], shaderBuffer, 3, vs, _uniformsObj, log);
 849#ifndef BUILD_GLES3
 850	glBindFragDataLocation(glRenderer->objShader[1].program, 2, "window");
 851#endif
 852
 853	shaderBuffer[1] = _renderWindow;
 854	_compileShader(glRenderer, &glRenderer->windowShader, shaderBuffer, 2, vs, _uniformsWindow, log);
 855#ifndef BUILD_GLES3
 856	glBindFragDataLocation(glRenderer->windowShader.program, 0, "window");
 857#endif
 858
 859	shaderBuffer[1] = _finalize;
 860	_compileShader(glRenderer, &glRenderer->finalizeShader, shaderBuffer, 2, vs, _uniformsFinalize, log);
 861
 862	glBindVertexArray(0);
 863	glDeleteShader(vs);
 864
 865	GBAVideoGLRendererReset(renderer);
 866}
 867
 868void GBAVideoGLRendererDeinit(struct GBAVideoRenderer* renderer) {
 869	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 870	if (glRenderer->temporaryBuffer) {
 871		mappedMemoryFree(glRenderer->temporaryBuffer, GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale * glRenderer->scale);
 872	}
 873	glDeleteFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 874	glDeleteTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 875	glDeleteTextures(1, &glRenderer->vramTex);
 876	glDeleteBuffers(1, &glRenderer->vbo);
 877
 878	_deleteShader(&glRenderer->bgShader[0]);
 879	_deleteShader(&glRenderer->bgShader[1]);
 880	_deleteShader(&glRenderer->bgShader[2]);
 881	_deleteShader(&glRenderer->bgShader[3]);
 882	_deleteShader(&glRenderer->objShader[0]);
 883	_deleteShader(&glRenderer->objShader[1]);
 884	_deleteShader(&glRenderer->finalizeShader);
 885
 886	int i;
 887	for (i = 0; i < 4; ++i) {
 888		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 889		glDeleteFramebuffers(1, &bg->fbo);
 890		glDeleteTextures(1, &bg->tex);
 891		glDeleteTextures(1, &bg->flags);
 892	}
 893}
 894
 895void GBAVideoGLRendererReset(struct GBAVideoRenderer* renderer) {
 896	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 897
 898	glRenderer->paletteDirty = true;
 899	glRenderer->vramDirty = 0xFFFFFF;
 900	glRenderer->firstAffine = -1;
 901	glRenderer->firstY = -1;
 902	glRenderer->dispcnt = 0x0080;
 903	glRenderer->mosaic = 0;
 904	memset(glRenderer->shadowRegs, 0, sizeof(glRenderer->shadowRegs));
 905	glRenderer->regsDirty = 0xFFFFFFFFFFFEULL;
 906}
 907
 908void GBAVideoGLRendererWriteVRAM(struct GBAVideoRenderer* renderer, uint32_t address) {
 909	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 910	glRenderer->vramDirty |= 1 << (address >> 12);
 911}
 912
 913void GBAVideoGLRendererWriteOAM(struct GBAVideoRenderer* renderer, uint32_t oam) {
 914	UNUSED(oam);
 915	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 916	glRenderer->oamDirty = true;
 917}
 918
 919void GBAVideoGLRendererWritePalette(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 920	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 921	UNUSED(address);
 922	UNUSED(value);
 923	glRenderer->paletteDirty = true;
 924}
 925
 926uint16_t GBAVideoGLRendererWriteVideoRegister(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 927	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 928	if (renderer->cache) {
 929		GBAVideoCacheWriteVideoRegister(renderer->cache, address, value);
 930	}
 931
 932	bool dirty = false;
 933	switch (address) {
 934	case REG_DISPCNT:
 935		value &= 0xFFF7;
 936		dirty = true;
 937		break;
 938	case REG_BG0CNT:
 939	case REG_BG1CNT:
 940		value &= 0xDFFF;
 941		dirty = true;
 942		break;
 943	case REG_BG0HOFS:
 944		value &= 0x01FF;
 945		glRenderer->bg[0].x = value;
 946		dirty = false;
 947		break;
 948	case REG_BG0VOFS:
 949		value &= 0x01FF;
 950		glRenderer->bg[0].y = value;
 951		dirty = false;
 952		break;
 953	case REG_BG1HOFS:
 954		value &= 0x01FF;
 955		glRenderer->bg[1].x = value;
 956		dirty = false;
 957		break;
 958	case REG_BG1VOFS:
 959		value &= 0x01FF;
 960		glRenderer->bg[1].y = value;
 961		dirty = false;
 962		break;
 963	case REG_BG2HOFS:
 964		value &= 0x01FF;
 965		glRenderer->bg[2].x = value;
 966		dirty = false;
 967		break;
 968	case REG_BG2VOFS:
 969		value &= 0x01FF;
 970		glRenderer->bg[2].y = value;
 971		dirty = false;
 972		break;
 973	case REG_BG3HOFS:
 974		value &= 0x01FF;
 975		glRenderer->bg[3].x = value;
 976		dirty = false;
 977		break;
 978	case REG_BG3VOFS:
 979		value &= 0x01FF;
 980		glRenderer->bg[3].y = value;
 981		dirty = false;
 982		break;
 983	case REG_BG2PA:
 984		glRenderer->bg[2].affine.dx = value;
 985		break;
 986	case REG_BG2PB:
 987		glRenderer->bg[2].affine.dmx = value;
 988		break;
 989	case REG_BG2PC:
 990		glRenderer->bg[2].affine.dy = value;
 991		break;
 992	case REG_BG2PD:
 993		glRenderer->bg[2].affine.dmy = value;
 994		break;
 995	case REG_BG2X_LO:
 996		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[2], value);
 997		break;
 998	case REG_BG2X_HI:
 999		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[2], value);
1000		break;
1001	case REG_BG2Y_LO:
1002		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[2], value);
1003		break;
1004	case REG_BG2Y_HI:
1005		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[2], value);
1006		break;
1007	case REG_BG3PA:
1008		glRenderer->bg[3].affine.dx = value;
1009		break;
1010	case REG_BG3PB:
1011		glRenderer->bg[3].affine.dmx = value;
1012		break;
1013	case REG_BG3PC:
1014		glRenderer->bg[3].affine.dy = value;
1015		break;
1016	case REG_BG3PD:
1017		glRenderer->bg[3].affine.dmy = value;
1018		break;
1019	case REG_BG3X_LO:
1020		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[3], value);
1021		break;
1022	case REG_BG3X_HI:
1023		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[3], value);
1024		break;
1025	case REG_BG3Y_LO:
1026		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[3], value);
1027		break;
1028	case REG_BG3Y_HI:
1029		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[3], value);
1030		break;
1031	case REG_BLDALPHA:
1032		value &= 0x1F1F;
1033		dirty = true;
1034		break;
1035	case REG_BLDY:
1036		value &= 0x1F;
1037		if (value > 0x10) {
1038			value = 0x10;
1039		}
1040		dirty = true;
1041		break;
1042			case REG_WIN0H:
1043		glRenderer->winN[0].h.end = value;
1044		glRenderer->winN[0].h.start = value >> 8;
1045		if (glRenderer->winN[0].h.start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[0].h.start > glRenderer->winN[0].h.end) {
1046			glRenderer->winN[0].h.start = 0;
1047		}
1048		if (glRenderer->winN[0].h.end > GBA_VIDEO_HORIZONTAL_PIXELS) {
1049			glRenderer->winN[0].h.end = GBA_VIDEO_HORIZONTAL_PIXELS;
1050			if (glRenderer->winN[0].h.start > GBA_VIDEO_HORIZONTAL_PIXELS) {
1051				glRenderer->winN[0].h.start = GBA_VIDEO_HORIZONTAL_PIXELS;
1052			}
1053		}
1054		break;
1055	case REG_WIN1H:
1056		glRenderer->winN[1].h.end = value;
1057		glRenderer->winN[1].h.start = value >> 8;
1058		if (glRenderer->winN[1].h.start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[1].h.start > glRenderer->winN[1].h.end) {
1059			glRenderer->winN[1].h.start = 0;
1060		}
1061		if (glRenderer->winN[1].h.end > GBA_VIDEO_HORIZONTAL_PIXELS) {
1062			glRenderer->winN[1].h.end = GBA_VIDEO_HORIZONTAL_PIXELS;
1063			if (glRenderer->winN[1].h.start > GBA_VIDEO_HORIZONTAL_PIXELS) {
1064				glRenderer->winN[1].h.start = GBA_VIDEO_HORIZONTAL_PIXELS;
1065			}
1066		}
1067		break;
1068	case REG_WIN0V:
1069		glRenderer->winN[0].v.end = value;
1070		glRenderer->winN[0].v.start = value >> 8;
1071		if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[0].v.start > glRenderer->winN[0].v.end) {
1072			glRenderer->winN[0].v.start = 0;
1073		}
1074		if (glRenderer->winN[0].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
1075			glRenderer->winN[0].v.end = GBA_VIDEO_VERTICAL_PIXELS;
1076			if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
1077				glRenderer->winN[0].v.start = GBA_VIDEO_VERTICAL_PIXELS;
1078			}
1079		}
1080		break;
1081	case REG_WIN1V:
1082		glRenderer->winN[1].v.end = value;
1083		glRenderer->winN[1].v.start = value >> 8;
1084		if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[1].v.start > glRenderer->winN[1].v.end) {
1085			glRenderer->winN[1].v.start = 0;
1086		}
1087		if (glRenderer->winN[1].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
1088			glRenderer->winN[1].v.end = GBA_VIDEO_VERTICAL_PIXELS;
1089			if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
1090				glRenderer->winN[1].v.start = GBA_VIDEO_VERTICAL_PIXELS;
1091			}
1092		}
1093		break;
1094	case REG_WININ:
1095	case REG_WINOUT:
1096		value &= 0x3F3F;
1097		dirty = true;
1098		break;
1099	default:
1100		dirty = true;
1101		break;
1102	}
1103	if (glRenderer->shadowRegs[address >> 1] == value) {
1104		dirty = false;
1105	} else {
1106		glRenderer->shadowRegs[address >> 1] = value;
1107	}
1108	if (dirty) {
1109		glRenderer->regsDirty |= 1ULL << (address >> 1);
1110	}
1111	return value;
1112}
1113
1114void _cleanRegister(struct GBAVideoGLRenderer* glRenderer, int address, uint16_t value) {
1115	switch (address) {
1116	case REG_DISPCNT:
1117		glRenderer->dispcnt = value;
1118		GBAVideoGLRendererUpdateDISPCNT(glRenderer);
1119		break;
1120	case REG_BG0CNT:
1121		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[0], value);
1122		break;
1123	case REG_BG1CNT:
1124		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[1], value);
1125		break;
1126	case REG_BG2CNT:
1127		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[2], value);
1128		break;
1129	case REG_BG3CNT:
1130		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[3], value);
1131		break;
1132	case REG_BLDCNT:
1133		GBAVideoGLRendererWriteBLDCNT(glRenderer, value);
1134		value &= 0x3FFF;
1135		break;
1136	case REG_BLDALPHA:
1137		glRenderer->blda = value & 0x1F;
1138		if (glRenderer->blda > 0x10) {
1139			glRenderer->blda = 0x10;
1140		}
1141		glRenderer->bldb = (value >> 8) & 0x1F;
1142		if (glRenderer->bldb > 0x10) {
1143			glRenderer->bldb = 0x10;
1144		}
1145		value &= 0x1F1F;
1146		break;
1147	case REG_BLDY:
1148		glRenderer->bldy = value;
1149		break;
1150	case REG_WININ:
1151		glRenderer->winN[0].control = value;
1152		glRenderer->winN[1].control = value >> 8;
1153		break;
1154	case REG_WINOUT:
1155		glRenderer->winout = value;
1156		glRenderer->objwin = value >> 8;
1157		break;
1158	case REG_MOSAIC:
1159		glRenderer->mosaic = value;
1160		break;
1161	default:
1162		break;
1163	}
1164}
1165
1166static bool _dirtyMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1167	UNUSED(y);
1168	if (!background->enabled) {
1169		return false;
1170	}
1171	unsigned screenBase = background->screenBase >> 11; // Lops off one extra bit
1172	unsigned screenMask = (7 << screenBase) & 0xFFFF; // Technically overzealous
1173	if (renderer->vramDirty & screenMask) {
1174		return true;
1175	}
1176	unsigned charBase = background->charBase >> 11;
1177	unsigned charMask = (0xFFFF << charBase) & 0xFFFF;
1178	if (renderer->vramDirty & charMask) {
1179		return true;
1180	}
1181	return false;
1182}
1183
1184static bool _dirtyMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1185	UNUSED(y);
1186	if (!background->enabled) {
1187		return false;
1188	}
1189	unsigned screenBase = background->screenBase >> 11; // Lops off one extra bit
1190	unsigned screenMask = (0xF << screenBase) & 0xFFFF;
1191	if (renderer->vramDirty & screenMask) {
1192		return true;
1193	}
1194	unsigned charBase = background->charBase >> 11;
1195	unsigned charMask = (0x3FFF << charBase) & 0xFFFF;
1196	if (renderer->vramDirty & charMask) {
1197		return true;
1198	}
1199	return false;
1200}
1201
1202static bool _dirtyMode3(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1203	UNUSED(y);
1204	if (!background->enabled) {
1205		return false;
1206	}
1207	if (renderer->vramDirty & 0xFFFFF) {
1208		return true;
1209	}
1210	return false;
1211}
1212
1213static bool _dirtyMode45(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1214	UNUSED(y);
1215	if (!background->enabled) {
1216		return false;
1217	}
1218	int start = GBARegisterDISPCNTIsFrameSelect(renderer->dispcnt) ? 5 : 0;
1219	int mask = 0x3FF << start;
1220	if (renderer->vramDirty & mask) {
1221		return true;
1222	}
1223	return false;
1224}
1225
1226static bool _needsVramUpload(struct GBAVideoGLRenderer* renderer, int y) {
1227	if (!renderer->vramDirty) {
1228		return false;
1229	}
1230	if (y == 0) {
1231		return true;
1232	}
1233
1234	if (GBARegisterDISPCNTIsObjEnable(renderer->dispcnt) && renderer->vramDirty & 0xFF0000) {
1235		return true;
1236	}
1237
1238	bool dirty = false;
1239	switch (GBARegisterDISPCNTGetMode(renderer->dispcnt)) {
1240	case 0:
1241		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[0], y);
1242		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[1], y);
1243		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[2], y);
1244		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[3], y);
1245		break;
1246	case 1:
1247		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[0], y);
1248		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[1], y);
1249		dirty = dirty || _dirtyMode2(renderer, &renderer->bg[2], y);
1250		break;
1251	case 2:
1252		dirty = dirty || _dirtyMode2(renderer, &renderer->bg[2], y);
1253		dirty = dirty || _dirtyMode2(renderer, &renderer->bg[3], y);
1254		break;
1255	case 3:
1256		dirty = _dirtyMode3(renderer, &renderer->bg[2], y);
1257		break;
1258	case 4:
1259		dirty = _dirtyMode45(renderer, &renderer->bg[2], y);
1260		break;
1261	case 5:
1262		dirty = _dirtyMode45(renderer, &renderer->bg[2], y);
1263		break;
1264	}
1265	return dirty;
1266}
1267
1268void GBAVideoGLRendererDrawScanline(struct GBAVideoRenderer* renderer, int y) {
1269	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
1270
1271	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
1272		if (glRenderer->firstAffine < 0) {
1273			glRenderer->firstAffine = y;
1274		}
1275	} else {
1276		glRenderer->firstAffine = -1;
1277	}
1278
1279	if (glRenderer->paletteDirty || _needsVramUpload(glRenderer, y) || glRenderer->oamDirty || glRenderer->regsDirty) {
1280		if (glRenderer->firstY >= 0) {
1281			_drawScanlines(glRenderer, y - 1);
1282			glBindVertexArray(0);
1283		}
1284	}
1285	if (glRenderer->firstY < 0) {
1286		glRenderer->firstY = y;
1287	}
1288
1289	int i;
1290	for (i = 0; i < 0x30; ++i) {
1291		if (!(glRenderer->regsDirty & (1ULL << i))) {
1292			continue;
1293		}
1294		_cleanRegister(glRenderer, i << 1, glRenderer->shadowRegs[i]);
1295	}
1296	glRenderer->regsDirty = 0;
1297
1298	glRenderer->winNHistory[0][y * 4 + 0] = glRenderer->winN[0].h.start;
1299	glRenderer->winNHistory[0][y * 4 + 1] = glRenderer->winN[0].h.end;
1300	glRenderer->winNHistory[0][y * 4 + 2] = glRenderer->winN[0].v.start;
1301	glRenderer->winNHistory[0][y * 4 + 3] = glRenderer->winN[0].v.end;
1302	glRenderer->winNHistory[1][y * 4 + 0] = glRenderer->winN[1].h.start;
1303	glRenderer->winNHistory[1][y * 4 + 1] = glRenderer->winN[1].h.end;
1304	glRenderer->winNHistory[1][y * 4 + 2] = glRenderer->winN[1].v.start;
1305	glRenderer->winNHistory[1][y * 4 + 3] = glRenderer->winN[1].v.end;
1306
1307	glRenderer->bg[0].scanlineOffset[y] = glRenderer->bg[0].x;
1308	glRenderer->bg[0].scanlineOffset[y] |= glRenderer->bg[0].y << 12;
1309	glRenderer->bg[1].scanlineOffset[y] = glRenderer->bg[1].x;
1310	glRenderer->bg[1].scanlineOffset[y] |= glRenderer->bg[1].y << 12;
1311	glRenderer->bg[2].scanlineOffset[y] = glRenderer->bg[2].x;
1312	glRenderer->bg[2].scanlineOffset[y] |= glRenderer->bg[2].y << 12;
1313	glRenderer->bg[2].scanlineAffine[y * 4] = glRenderer->bg[2].affine.dx;
1314	glRenderer->bg[2].scanlineAffine[y * 4 + 1] = glRenderer->bg[2].affine.dy;
1315	glRenderer->bg[2].scanlineAffine[y * 4 + 2] = glRenderer->bg[2].affine.sx;
1316	glRenderer->bg[2].scanlineAffine[y * 4 + 3] = glRenderer->bg[2].affine.sy;
1317	glRenderer->bg[3].scanlineOffset[y] = glRenderer->bg[3].x;
1318	glRenderer->bg[3].scanlineOffset[y] |= glRenderer->bg[3].y << 12;
1319	glRenderer->bg[3].scanlineAffine[y * 4] = glRenderer->bg[3].affine.dx;
1320	glRenderer->bg[3].scanlineAffine[y * 4 + 1] = glRenderer->bg[3].affine.dy;
1321	glRenderer->bg[3].scanlineAffine[y * 4 + 2] = glRenderer->bg[3].affine.sx;
1322	glRenderer->bg[3].scanlineAffine[y * 4 + 3] = glRenderer->bg[3].affine.sy;
1323
1324	if (glRenderer->paletteDirty) {
1325		for (i = 0; i < 512; ++i) {
1326			glRenderer->shadowPalette[i] = glRenderer->d.palette[i];
1327		}
1328		glRenderer->paletteDirty = false;
1329	}
1330
1331	if (_needsVramUpload(glRenderer, y)) {
1332		int first = -1;
1333		glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
1334		for (i = 0; i < 25; ++i) {
1335			if (!(glRenderer->vramDirty & (1 << i))) {
1336				if (first >= 0) {
1337					glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 8 * first, 256, 8 * (i - first), GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, &glRenderer->d.vram[2048 * first]);
1338					first = -1;
1339				}
1340			} else if (first < 0) {
1341				first = i;
1342			}
1343		}
1344		glRenderer->vramDirty = 0;
1345	}
1346
1347	if (glRenderer->oamDirty) {
1348		glRenderer->oamMax = GBAVideoRendererCleanOAM(glRenderer->d.oam->obj, glRenderer->sprites, 0);
1349		glRenderer->oamDirty = false;
1350	}
1351
1352	if (y == 0) {
1353		glDisable(GL_SCISSOR_TEST);
1354		glClearColor(0, 0, 0, 0);
1355#ifdef BUILD_GLES3
1356		glClearDepthf(1.f);
1357#else
1358		glClearDepth(1);
1359#endif
1360		glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
1361		glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1362		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1363
1364		for (i = 0; i < 4; ++i) {
1365			glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->bg[i].fbo);
1366			glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1367			glClear(GL_COLOR_BUFFER_BIT);
1368		}
1369	}
1370
1371	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
1372		glRenderer->bg[2].affine.sx += glRenderer->bg[2].affine.dmx;
1373		glRenderer->bg[2].affine.sy += glRenderer->bg[2].affine.dmy;
1374		glRenderer->bg[3].affine.sx += glRenderer->bg[3].affine.dmx;
1375		glRenderer->bg[3].affine.sy += glRenderer->bg[3].affine.dmy;
1376	}
1377}
1378
1379void _drawScanlines(struct GBAVideoGLRenderer* glRenderer, int y) {
1380	glEnable(GL_SCISSOR_TEST);
1381
1382	uint32_t backdrop = M_RGB5_TO_RGB8(glRenderer->shadowPalette[0]);
1383	glViewport(0, 0, 1, GBA_VIDEO_VERTICAL_PIXELS);
1384	glScissor(0, glRenderer->firstY, 1, y - glRenderer->firstY + 1);
1385	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_BACKDROP]);
1386	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1387	glClearBufferfv(GL_COLOR, 0, (GLfloat[]) { ((backdrop >> 16) & 0xF8) / 248., ((backdrop >> 8) & 0xF8) / 248., (backdrop & 0xF8) / 248., 1.f });
1388	glClearBufferiv(GL_COLOR, 1, (GLint[]) { 32, glRenderer->target1Bd | (glRenderer->target2Bd * 2) | (glRenderer->blendEffect * 4), glRenderer->blda, 0 });
1389	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1390
1391	GBAVideoGLRendererDrawWindow(glRenderer, y);
1392	if (GBARegisterDISPCNTIsObjEnable(glRenderer->dispcnt) && !glRenderer->d.disableOBJ) {
1393		int i;
1394		glDepthFunc(GL_LESS);
1395		for (i = 0; i < glRenderer->oamMax; ++i) {
1396			struct GBAVideoRendererSprite* sprite = &glRenderer->sprites[i];
1397			if ((y < sprite->y && (sprite->endY - 256 < 0 || glRenderer->firstY >= sprite->endY - 256)) || glRenderer->firstY >= sprite->endY) {
1398				continue;
1399			}
1400
1401			GBAVideoGLRendererDrawSprite(glRenderer, &sprite->obj, y, sprite->y);
1402		}
1403		glDisable(GL_DEPTH_TEST);
1404	}
1405
1406	if (TEST_LAYER_ENABLED(0) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
1407		GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[0], y);
1408	}
1409	if (TEST_LAYER_ENABLED(1) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
1410		GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[1], y);
1411	}
1412	if (TEST_LAYER_ENABLED(2)) {
1413		switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
1414		case 0:
1415			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[2], y);
1416			break;
1417		case 1:
1418		case 2:
1419			GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[2], y);
1420			break;
1421		case 3:
1422			GBAVideoGLRendererDrawBackgroundMode3(glRenderer, &glRenderer->bg[2], y);
1423			break;
1424		case 4:
1425			GBAVideoGLRendererDrawBackgroundMode4(glRenderer, &glRenderer->bg[2], y);
1426			break;
1427		case 5:
1428			GBAVideoGLRendererDrawBackgroundMode5(glRenderer, &glRenderer->bg[2], y);
1429			break;
1430		}
1431	}
1432	if (TEST_LAYER_ENABLED(3)) {
1433		switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
1434		case 0:
1435			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[3], y);
1436			break;
1437		case 2:
1438			GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[3], y);
1439			break;
1440		}
1441	}
1442	glRenderer->firstY = -1;
1443}
1444
1445void GBAVideoGLRendererFinishFrame(struct GBAVideoRenderer* renderer) {
1446	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
1447	_drawScanlines(glRenderer, GBA_VIDEO_VERTICAL_PIXELS - 1);
1448	_finalizeLayers(glRenderer);
1449	glDisable(GL_SCISSOR_TEST);
1450	glBindVertexArray(0);
1451	glRenderer->firstAffine = -1;
1452	glRenderer->firstY = -1;
1453	glRenderer->bg[2].affine.sx = glRenderer->bg[2].refx;
1454	glRenderer->bg[2].affine.sy = glRenderer->bg[2].refy;
1455	glRenderer->bg[3].affine.sx = glRenderer->bg[3].refx;
1456	glRenderer->bg[3].affine.sy = glRenderer->bg[3].refy;
1457}
1458
1459void GBAVideoGLRendererGetPixels(struct GBAVideoRenderer* renderer, size_t* stride, const void** pixels) {
1460	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
1461	*stride = GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale;
1462	if (!glRenderer->temporaryBuffer) {
1463		glRenderer->temporaryBuffer = anonymousMemoryMap(GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale * glRenderer->scale * BYTES_PER_PIXEL);
1464	}
1465	glFinish();
1466	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OUTPUT]);
1467	glPixelStorei(GL_PACK_ROW_LENGTH, GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale);
1468	glPixelStorei(GL_PACK_ALIGNMENT, 1);
1469	glReadPixels(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale, GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale, GL_RGBA, GL_UNSIGNED_BYTE, (void*) glRenderer->temporaryBuffer);
1470	*pixels = glRenderer->temporaryBuffer;
1471}
1472
1473void GBAVideoGLRendererPutPixels(struct GBAVideoRenderer* renderer, size_t stride, const void* pixels) {
1474
1475}
1476
1477static void _enableBg(struct GBAVideoGLRenderer* renderer, int bg, bool active) {
1478	int wasActive = renderer->bg[bg].enabled;
1479	if (!active) {
1480		renderer->bg[bg].enabled = 0;
1481	} else if (!wasActive && active) {
1482		/*if (renderer->nextY == 0 || GBARegisterDISPCNTGetMode(renderer->dispcnt) > 2) {
1483			// TODO: Investigate in more depth how switching background works in different modes
1484			renderer->bg[bg].enabled = 4;
1485		} else {
1486			renderer->bg[bg].enabled = 1;
1487		}*/
1488		renderer->bg[bg].enabled = 4;
1489	}
1490}
1491
1492static void GBAVideoGLRendererUpdateDISPCNT(struct GBAVideoGLRenderer* renderer) {
1493	_enableBg(renderer, 0, GBARegisterDISPCNTGetBg0Enable(renderer->dispcnt));
1494	_enableBg(renderer, 1, GBARegisterDISPCNTGetBg1Enable(renderer->dispcnt));
1495	_enableBg(renderer, 2, GBARegisterDISPCNTGetBg2Enable(renderer->dispcnt));
1496	_enableBg(renderer, 3, GBARegisterDISPCNTGetBg3Enable(renderer->dispcnt));
1497}
1498
1499static void GBAVideoGLRendererWriteBGCNT(struct GBAVideoGLBackground* bg, uint16_t value) {
1500	bg->priority = GBARegisterBGCNTGetPriority(value);
1501	bg->charBase = GBARegisterBGCNTGetCharBase(value) << 13;
1502	bg->mosaic = GBARegisterBGCNTGetMosaic(value);
1503	bg->multipalette = GBARegisterBGCNTGet256Color(value);
1504	bg->screenBase = GBARegisterBGCNTGetScreenBase(value) << 10;
1505	bg->overflow = GBARegisterBGCNTGetOverflow(value);
1506	bg->size = GBARegisterBGCNTGetSize(value);
1507}
1508
1509static void GBAVideoGLRendererWriteBGX_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1510	bg->refx = (bg->refx & 0xFFFF0000) | value;
1511	bg->affine.sx = bg->refx;
1512}
1513
1514static void GBAVideoGLRendererWriteBGX_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1515	bg->refx = (bg->refx & 0x0000FFFF) | (value << 16);
1516	bg->refx <<= 4;
1517	bg->refx >>= 4;
1518	bg->affine.sx = bg->refx;
1519}
1520
1521static void GBAVideoGLRendererWriteBGY_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1522	bg->refy = (bg->refy & 0xFFFF0000) | value;
1523	bg->affine.sy = bg->refy;
1524}
1525
1526static void GBAVideoGLRendererWriteBGY_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1527	bg->refy = (bg->refy & 0x0000FFFF) | (value << 16);
1528	bg->refy <<= 4;
1529	bg->refy >>= 4;
1530	bg->affine.sy = bg->refy;
1531}
1532
1533static void GBAVideoGLRendererWriteBLDCNT(struct GBAVideoGLRenderer* renderer, uint16_t value) {
1534	renderer->bg[0].target1 = GBARegisterBLDCNTGetTarget1Bg0(value);
1535	renderer->bg[1].target1 = GBARegisterBLDCNTGetTarget1Bg1(value);
1536	renderer->bg[2].target1 = GBARegisterBLDCNTGetTarget1Bg2(value);
1537	renderer->bg[3].target1 = GBARegisterBLDCNTGetTarget1Bg3(value);
1538	renderer->bg[0].target2 = GBARegisterBLDCNTGetTarget2Bg0(value);
1539	renderer->bg[1].target2 = GBARegisterBLDCNTGetTarget2Bg1(value);
1540	renderer->bg[2].target2 = GBARegisterBLDCNTGetTarget2Bg2(value);
1541	renderer->bg[3].target2 = GBARegisterBLDCNTGetTarget2Bg3(value);
1542
1543	renderer->blendEffect = GBARegisterBLDCNTGetEffect(value);
1544	renderer->target1Obj = GBARegisterBLDCNTGetTarget1Obj(value);
1545	renderer->target1Bd = GBARegisterBLDCNTGetTarget1Bd(value);
1546	renderer->target2Obj = GBARegisterBLDCNTGetTarget2Obj(value);
1547	renderer->target2Bd = GBARegisterBLDCNTGetTarget2Bd(value);
1548}
1549
1550void _finalizeLayers(struct GBAVideoGLRenderer* renderer) {
1551	const GLuint* uniforms = renderer->finalizeShader.uniforms;
1552	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OUTPUT]);
1553	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1554	glScissor(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1555	if (GBARegisterDISPCNTIsForcedBlank(renderer->dispcnt)) {
1556		glClearColor(1.f, 1.f, 1.f, 1.f);
1557		glClear(GL_COLOR_BUFFER_BIT);
1558	} else {
1559		glUseProgram(renderer->finalizeShader.program);
1560		glBindVertexArray(renderer->finalizeShader.vao);
1561		glActiveTexture(GL_TEXTURE0);
1562		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_WINDOW]);
1563		glActiveTexture(GL_TEXTURE0 + 1);
1564		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_OBJ_COLOR]);
1565		glActiveTexture(GL_TEXTURE0 + 2);
1566		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_OBJ_FLAGS]);
1567		glActiveTexture(GL_TEXTURE0 + 3);
1568		glBindTexture(GL_TEXTURE_2D, renderer->bg[0].tex);
1569		glActiveTexture(GL_TEXTURE0 + 4);
1570		glBindTexture(GL_TEXTURE_2D, renderer->bg[0].flags);
1571		glActiveTexture(GL_TEXTURE0 + 5);
1572		glBindTexture(GL_TEXTURE_2D, renderer->bg[1].tex);
1573		glActiveTexture(GL_TEXTURE0 + 6);
1574		glBindTexture(GL_TEXTURE_2D, renderer->bg[1].flags);
1575		glActiveTexture(GL_TEXTURE0 + 7);
1576		glBindTexture(GL_TEXTURE_2D, renderer->bg[2].tex);
1577		glActiveTexture(GL_TEXTURE0 + 8);
1578		glBindTexture(GL_TEXTURE_2D, renderer->bg[2].flags);
1579		glActiveTexture(GL_TEXTURE0 + 9);
1580		glBindTexture(GL_TEXTURE_2D, renderer->bg[3].tex);
1581		glActiveTexture(GL_TEXTURE0 + 10);
1582		glBindTexture(GL_TEXTURE_2D, renderer->bg[3].flags);
1583		glActiveTexture(GL_TEXTURE0 + 11);
1584		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_BACKDROP_COLOR]);
1585		glActiveTexture(GL_TEXTURE0 + 12);
1586		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_BACKDROP_FLAGS]);
1587
1588		glUniform2i(uniforms[GBA_GL_VS_LOC], GBA_VIDEO_VERTICAL_PIXELS, 0);
1589		glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1590		glUniform1i(uniforms[GBA_GL_FINALIZE_SCALE], renderer->scale);
1591		glUniform1iv(uniforms[GBA_GL_FINALIZE_LAYERS], 5, (GLint[]) { 3, 5, 7, 9, 1 });
1592		glUniform1iv(uniforms[GBA_GL_FINALIZE_FLAGS], 5, (GLint[]) { 4, 6, 8, 10, 2 });
1593		glUniform1i(uniforms[GBA_GL_FINALIZE_WINDOW], 0);
1594		glUniform1i(uniforms[GBA_GL_FINALIZE_WINDOW], 0);
1595		glUniform1i(uniforms[GBA_GL_FINALIZE_BACKDROP], 11);
1596		glUniform1i(uniforms[GBA_GL_FINALIZE_BACKDROPFLAGS], 12);
1597		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1598	}
1599	glBindFramebuffer(GL_FRAMEBUFFER, 0);
1600}
1601
1602void GBAVideoGLRendererDrawSprite(struct GBAVideoGLRenderer* renderer, struct GBAObj* sprite, int y, int spriteY) {
1603	int width = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][0];
1604	int height = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][1];
1605	int32_t x = (uint32_t) GBAObjAttributesBGetX(sprite->b) << 23;
1606	x >>= 23;
1607
1608	int align = GBAObjAttributesAIs256Color(sprite->a) && !GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt);
1609	unsigned charBase = (BASE_TILE >> 1) + (GBAObjAttributesCGetTile(sprite->c) & ~align) * 0x10;
1610	int stride = GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt) ? (width >> 3) : (0x20 >> GBAObjAttributesAGet256Color(sprite->a));
1611
1612	if (spriteY + height >= 256) {
1613		spriteY -= 256;
1614	}
1615
1616	int totalWidth = width;
1617	int totalHeight = height;
1618	if (GBAObjAttributesAIsTransformed(sprite->a) && GBAObjAttributesAIsDoubleSize(sprite->a)) {
1619		totalWidth <<= 1;
1620		totalHeight <<= 1;
1621	}
1622
1623	const struct GBAVideoGLShader* shader = &renderer->objShader[GBAObjAttributesAGet256Color(sprite->a)];
1624	const GLuint* uniforms = shader->uniforms;
1625	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OBJ]);
1626	glViewport(x * renderer->scale, spriteY * renderer->scale, totalWidth * renderer->scale, totalHeight * renderer->scale);
1627	glScissor(x * renderer->scale, renderer->firstY * renderer->scale, totalWidth * renderer->scale, (y - renderer->firstY + 1) * renderer->scale);
1628	glUseProgram(shader->program);
1629	glBindVertexArray(shader->vao);
1630	glActiveTexture(GL_TEXTURE0);
1631	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1632	glUniform2i(uniforms[GBA_GL_VS_LOC], totalHeight, 0);
1633	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], totalWidth, totalHeight);
1634	glUniform1i(uniforms[GBA_GL_OBJ_VRAM], 0);
1635	glUniform1iv(uniforms[GBA_GL_OBJ_PALETTE], 256, &renderer->shadowPalette[256]);
1636	glUniform1i(uniforms[GBA_GL_OBJ_CHARBASE], charBase);
1637	glUniform1i(uniforms[GBA_GL_OBJ_STRIDE], stride);
1638	glUniform1i(uniforms[GBA_GL_OBJ_LOCALPALETTE], GBAObjAttributesCGetPalette(sprite->c));
1639	glUniform4i(uniforms[GBA_GL_OBJ_INFLAGS], GBAObjAttributesCGetPriority(sprite->c),
1640	                                          (renderer->target1Obj || GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT) | (renderer->target2Obj * 2) | (renderer->blendEffect * 4),
1641	                                          renderer->blda, GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT);
1642	if (GBAObjAttributesAIsTransformed(sprite->a)) {
1643		struct GBAOAMMatrix mat;
1644		LOAD_16(mat.a, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].a);
1645		LOAD_16(mat.b, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].b);
1646		LOAD_16(mat.c, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].c);
1647		LOAD_16(mat.d, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].d);
1648
1649		glUniformMatrix2fv(uniforms[GBA_GL_OBJ_TRANSFORM], 1, GL_FALSE, (GLfloat[]) { mat.a / 256.f, mat.c / 256.f, mat.b / 256.f, mat.d / 256.f });
1650	} else {
1651		int flipX = 1;
1652		int flipY = 1;
1653		if (GBAObjAttributesBIsHFlip(sprite->b)) {
1654			flipX = -1;
1655		}
1656		if (GBAObjAttributesBIsVFlip(sprite->b)) {
1657			flipY = -1;
1658		}
1659		glUniformMatrix2fv(uniforms[GBA_GL_OBJ_TRANSFORM], 1, GL_FALSE, (GLfloat[]) { flipX, 0, 0, flipY });
1660	}
1661	glUniform4i(uniforms[GBA_GL_OBJ_DIMS], width, height, totalWidth, totalHeight);
1662	if (GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_OBJWIN) {
1663		glDisable(GL_DEPTH_TEST);
1664		int window = renderer->objwin & 0x3F;
1665		glUniform4i(uniforms[GBA_GL_OBJ_OBJWIN], 1, window, renderer->bldb, renderer->bldy);
1666		glDrawBuffers(3, (GLenum[]) { GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT2 });
1667	} else {
1668		glEnable(GL_DEPTH_TEST);
1669		glUniform4i(uniforms[GBA_GL_OBJ_OBJWIN], 0, 0, 0, 0);
1670		glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1671	}
1672	if (GBAObjAttributesAIsMosaic(sprite->a) && GBAObjAttributesAGetMode(sprite->a) != OBJ_MODE_OBJWIN) {
1673		int mosaicH = GBAMosaicControlGetObjH(renderer->mosaic) + 1;
1674		if (GBAObjAttributesBIsHFlip(sprite->b)) {
1675			mosaicH = -mosaicH;
1676		}
1677		glUniform4i(uniforms[GBA_GL_OBJ_MOSAIC], mosaicH, GBAMosaicControlGetObjV(renderer->mosaic) + 1, x, spriteY);
1678	} else {
1679		glUniform4i(uniforms[GBA_GL_OBJ_MOSAIC], 0, 0, 0, 0);
1680	}
1681	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1682	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1683}
1684
1685void _prepareBackground(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, const GLuint* uniforms) {
1686	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1687	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1688	glActiveTexture(GL_TEXTURE0);
1689	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1690	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1691	glUniform1i(uniforms[GBA_GL_BG_VRAM], 0);
1692	glUniform1iv(uniforms[GBA_GL_OBJ_PALETTE], 256, renderer->shadowPalette);
1693	if (background->mosaic) {
1694		glUniform2i(uniforms[GBA_GL_BG_MOSAIC], GBAMosaicControlGetBgV(renderer->mosaic) + 1, GBAMosaicControlGetBgH(renderer->mosaic) + 1);
1695	} else {
1696		glUniform2i(uniforms[GBA_GL_BG_MOSAIC], 0, 0);
1697	}
1698	glUniform4i(uniforms[GBA_GL_BG_INFLAGS], background->priority,
1699		                                     background->target1 | (background->target2 * 2) | (renderer->blendEffect * 4),
1700		                                     renderer->blda, 0);
1701	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1702}
1703
1704void GBAVideoGLRendererDrawBackgroundMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1705	const struct GBAVideoGLShader* shader = &renderer->bgShader[background->multipalette ? 1 : 0];
1706	const GLuint* uniforms = shader->uniforms;
1707	glUseProgram(shader->program);
1708	glBindVertexArray(shader->vao);
1709	_prepareBackground(renderer, background, uniforms);
1710	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1711	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1712	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1713	glUniform1iv(uniforms[GBA_GL_BG_OFFSET], GBA_VIDEO_VERTICAL_PIXELS, background->scanlineOffset);
1714
1715	glScissor(0, renderer->firstY * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, (y - renderer->firstY + 1) * renderer->scale);
1716	glUniform2i(uniforms[GBA_GL_VS_LOC], y - renderer->firstY + 1, renderer->firstY);
1717	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1718
1719	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1720}
1721
1722void _prepareTransform(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, const GLuint* uniforms, int y) {
1723	glScissor(0, renderer->firstY * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale * (y - renderer->firstY + 1));
1724	glUniform2i(uniforms[GBA_GL_VS_LOC], y - renderer->firstY + 1, renderer->firstY);
1725	glUniform2i(uniforms[GBA_GL_BG_RANGE], renderer->firstAffine, y);
1726
1727	glUniform4iv(uniforms[GBA_GL_BG_TRANSFORM], GBA_VIDEO_VERTICAL_PIXELS, background->scanlineAffine);
1728	_prepareBackground(renderer, background, uniforms);
1729}
1730
1731void GBAVideoGLRendererDrawBackgroundMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1732	const struct GBAVideoGLShader* shader = &renderer->bgShader[background->overflow ? 2 : 3];
1733	const GLuint* uniforms = shader->uniforms;
1734	glUseProgram(shader->program);
1735	glBindVertexArray(shader->vao);
1736	_prepareTransform(renderer, background, uniforms, y);
1737	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1738	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1739	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1740	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1741	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1742}
1743
1744void GBAVideoGLRendererDrawBackgroundMode3(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1745	const struct GBAVideoGLShader* shader = &renderer->bgShader[5];
1746	const GLuint* uniforms = shader->uniforms;
1747	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1748	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1749	glUseProgram(shader->program);
1750	glBindVertexArray(shader->vao);
1751	_prepareTransform(renderer, background, uniforms, y);
1752	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], 0);
1753	glUniform2i(uniforms[GBA_GL_BG_SIZE], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1754	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1755	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1756}
1757
1758void GBAVideoGLRendererDrawBackgroundMode4(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1759	const struct GBAVideoGLShader* shader = &renderer->bgShader[4];
1760	const GLuint* uniforms = shader->uniforms;
1761	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1762	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1763	glUseProgram(shader->program);
1764	glBindVertexArray(shader->vao);
1765	_prepareTransform(renderer, background, uniforms, y);
1766	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], GBARegisterDISPCNTIsFrameSelect(renderer->dispcnt) ? 0xA000 : 0);
1767	glUniform2i(uniforms[GBA_GL_BG_SIZE], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1768	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1769	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1770}
1771
1772void GBAVideoGLRendererDrawBackgroundMode5(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1773	const struct GBAVideoGLShader* shader = &renderer->bgShader[5];
1774	const GLuint* uniforms = shader->uniforms;
1775	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1776	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1777	glUseProgram(shader->program);
1778	glBindVertexArray(shader->vao);
1779	_prepareTransform(renderer, background, uniforms, y);
1780	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], GBARegisterDISPCNTIsFrameSelect(renderer->dispcnt) ? 0x5000 : 0);
1781	glUniform2i(uniforms[GBA_GL_BG_SIZE], 160, 128);
1782	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1783	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1784}
1785
1786void GBAVideoGLRendererDrawWindow(struct GBAVideoGLRenderer* renderer, int y) {
1787	const struct GBAVideoGLShader* shader = &renderer->windowShader;
1788	const GLuint* uniforms = shader->uniforms;
1789	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_WINDOW]);
1790	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1791	glScissor(0, renderer->firstY * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale * (y - renderer->firstY + 1));
1792	glUseProgram(shader->program);
1793	glBindVertexArray(shader->vao);
1794	glUniform2i(uniforms[GBA_GL_VS_LOC], y - renderer->firstY + 1, renderer->firstY);
1795	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1796	glUniform1i(uniforms[GBA_GL_WIN_DISPCNT], renderer->dispcnt >> 8);
1797	glUniform2i(uniforms[GBA_GL_WIN_BLEND], renderer->bldb, renderer->bldy);
1798	glUniform3i(uniforms[GBA_GL_WIN_FLAGS], renderer->winN[0].control, renderer->winN[1].control, renderer->winout);
1799	glUniform4iv(uniforms[GBA_GL_WIN_WIN0], GBA_VIDEO_VERTICAL_PIXELS, renderer->winNHistory[0]);
1800	glUniform4iv(uniforms[GBA_GL_WIN_WIN1], GBA_VIDEO_VERTICAL_PIXELS, renderer->winNHistory[1]);
1801	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1802	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1803}
1804
1805#endif