all repos — mgba @ e11dc3fad05bd655228c078147d5af2ec5733c1e

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