all repos — mgba @ 2752c98b17a2d0e4fdb6a1b2a456bf5bb2968aa5

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#include <mgba/core/cache-set.h>
   9#include <mgba/internal/arm/macros.h>
  10#include <mgba/internal/gba/io.h>
  11#include <mgba/internal/gba/renderers/cache-set.h>
  12
  13static void GBAVideoGLRendererInit(struct GBAVideoRenderer* renderer);
  14static void GBAVideoGLRendererDeinit(struct GBAVideoRenderer* renderer);
  15static void GBAVideoGLRendererReset(struct GBAVideoRenderer* renderer);
  16static void GBAVideoGLRendererWriteVRAM(struct GBAVideoRenderer* renderer, uint32_t address);
  17static void GBAVideoGLRendererWriteOAM(struct GBAVideoRenderer* renderer, uint32_t oam);
  18static void GBAVideoGLRendererWritePalette(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value);
  19static uint16_t GBAVideoGLRendererWriteVideoRegister(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value);
  20static void GBAVideoGLRendererDrawScanline(struct GBAVideoRenderer* renderer, int y);
  21static void GBAVideoGLRendererFinishFrame(struct GBAVideoRenderer* renderer);
  22static void GBAVideoGLRendererGetPixels(struct GBAVideoRenderer* renderer, size_t* stride, const void** pixels);
  23static void GBAVideoGLRendererPutPixels(struct GBAVideoRenderer* renderer, size_t stride, const void* pixels);
  24
  25static void GBAVideoGLRendererUpdateDISPCNT(struct GBAVideoGLRenderer* renderer);
  26static void GBAVideoGLRendererWriteBGCNT(struct GBAVideoGLBackground* bg, uint16_t value);
  27static void GBAVideoGLRendererWriteBGX_LO(struct GBAVideoGLBackground* bg, uint16_t value);
  28static void GBAVideoGLRendererWriteBGX_HI(struct GBAVideoGLBackground* bg, uint16_t value);
  29static void GBAVideoGLRendererWriteBGY_LO(struct GBAVideoGLBackground* bg, uint16_t value);
  30static void GBAVideoGLRendererWriteBGY_HI(struct GBAVideoGLBackground* bg, uint16_t value);
  31static void GBAVideoGLRendererWriteBLDCNT(struct GBAVideoGLRenderer* renderer, uint16_t value);
  32
  33static void GBAVideoGLRendererDrawSprite(struct GBAVideoGLRenderer* renderer, struct GBAObj* sprite, int y, int spriteY);
  34static void GBAVideoGLRendererDrawBackgroundMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  35static void GBAVideoGLRendererDrawBackgroundMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  36static void GBAVideoGLRendererDrawBackgroundMode3(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  37static void GBAVideoGLRendererDrawBackgroundMode4(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  38static void GBAVideoGLRendererDrawBackgroundMode5(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  39static void GBAVideoGLRendererDrawWindow(struct GBAVideoGLRenderer* renderer, int y);
  40
  41static void _compositeLayer(struct GBAVideoGLRenderer* renderer, GLuint tex, GLuint flags, int id, int y);
  42static void _finalizeLayers(struct GBAVideoGLRenderer* renderer, int y);
  43
  44#define TEST_LAYER_ENABLED(X) !renderer->disableBG[X] && glRenderer->bg[X].enabled == 4 && glRenderer->bg[X].priority == priority
  45
  46struct GBAVideoGLUniform {
  47	const char* name;
  48	int type;
  49};
  50
  51static const GLchar* const _gl3Header =
  52	"#version 130\n";
  53
  54static const char* const _vertexShader =
  55	"in vec2 position;\n"
  56	"uniform ivec2 loc;\n"
  57	"uniform ivec2 maxPos;\n"
  58	"out vec2 texCoord;\n"
  59
  60	"void main() {\n"
  61	"	vec2 local = vec2(position.x, float(position.y * loc.x + loc.y) / abs(maxPos.y));\n"
  62	"	gl_Position = vec4((local * 2. - 1.) * sign(maxPos), 0., 1.);\n"
  63	"	texCoord = local * abs(maxPos);\n"
  64	"}";
  65
  66static const char* const _renderTile16 =
  67	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  68	"	int address = charBase + tile * 16 + (localCoord.x >> 2) + (localCoord.y << 1);\n"
  69	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
  70	"	int entry = int(halfrow[3 - (localCoord.x & 3)] * 15.9);\n"
  71	"	vec4 color = texelFetch(palette, ivec2(entry, paletteId), 0);\n"
  72	"	if (entry == 0) {\n"
  73	"		discard;\n"
  74	"	}\n"
  75	"	color.a = 1;\n"
  76	"	return color;\n"
  77	"}";
  78
  79static const char* const _renderTile256 =
  80	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  81	"	int address = charBase + tile * 32 + (localCoord.x >> 1) + (localCoord.y << 2);\n"
  82	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
  83	"	int entry = int(halfrow[3 - 2 * (localCoord.x & 1)] * 15.9);\n"
  84	"	int pal2 = int(halfrow[2 - 2 * (localCoord.x & 1)] * 15.9);\n"
  85	"	vec4 color = texelFetch(palette, ivec2(entry, pal2 + (paletteId & 16)), 0);\n"
  86	"	if ((pal2 | entry) == 0) {\n"
  87	"		discard;\n"
  88	"	}\n"
  89	"	color.a = 1.;\n"
  90	"	return color;\n"
  91	"}";
  92
  93const static struct GBAVideoGLUniform _uniformsMode0[] = {
  94	{ "loc", GBA_GL_VS_LOC, },
  95	{ "maxPos", GBA_GL_VS_MAXPOS, },
  96	{ "vram", GBA_GL_BG_VRAM, },
  97	{ "palette", GBA_GL_BG_PALETTE, },
  98	{ "screenBase", GBA_GL_BG_SCREENBASE, },
  99	{ "charBase", GBA_GL_BG_CHARBASE, },
 100	{ "size", GBA_GL_BG_SIZE, },
 101	{ "offset", GBA_GL_BG_OFFSET, },
 102	{ "inflags", GBA_GL_BG_INFLAGS, },
 103	{ 0 }
 104};
 105
 106static const char* const _renderMode0 =
 107	"in vec2 texCoord;\n"
 108	"uniform sampler2D vram;\n"
 109	"uniform sampler2D palette;\n"
 110	"uniform int screenBase;\n"
 111	"uniform int charBase;\n"
 112	"uniform int size;\n"
 113	"uniform ivec2 offset;\n"
 114	"uniform ivec4 inflags;\n"
 115	"out vec4 color;\n"
 116	"out vec4 flags;\n"
 117	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 118
 119	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 120
 121	"void main() {\n"
 122	"	ivec2 coord = ivec2(texCoord) + offset;\n"
 123	"	if ((size & 1) == 1) {\n"
 124	"		coord.y += coord.x & 256;\n"
 125	"	}\n"
 126	"	coord.x &= 255;\n"
 127	"	int mapAddress = screenBase + (coord.x >> 3) + (coord.y >> 3) * 32;\n"
 128	"	vec4 map = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0);\n"
 129	"	int tileFlags = int(map.g * 15.9);\n"
 130	"	if ((tileFlags & 4) == 4) {\n"
 131	"		coord.x ^= 7;\n"
 132	"	}\n"
 133	"	if ((tileFlags & 8) == 8) {\n"
 134	"		coord.y ^= 7;\n"
 135	"	}\n"
 136	"	int tile = int(map.a * 15.9) + int(map.b * 15.9) * 16 + (tileFlags & 0x3) * 256;\n"
 137	"	color = renderTile(tile, int(map.r * 15.9), coord & 7);\n"
 138	"	flags = inflags / flagCoeff;\n"
 139	"}";
 140
 141static const char* const _fetchTileOverflow =
 142	"vec4 fetchTile(ivec2 coord) {\n"
 143	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 144	"	coord &= sizeAdjusted;\n"
 145	"	return renderTile(coord);\n"
 146	"}";
 147
 148static const char* const _fetchTileNoOverflow =
 149	"vec4 fetchTile(ivec2 coord) {\n"
 150	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 151	"	ivec2 outerCoord = coord & ~sizeAdjusted;\n"
 152	"	if ((outerCoord.x | outerCoord.y) != 0) {\n"
 153	"		discard;\n"
 154	"	}\n"
 155	"	return renderTile(coord);\n"
 156	"}";
 157
 158const static struct GBAVideoGLUniform _uniformsMode2[] = {
 159	{ "loc", GBA_GL_VS_LOC, },
 160	{ "maxPos", GBA_GL_VS_MAXPOS, },
 161	{ "vram", GBA_GL_BG_VRAM, },
 162	{ "palette", GBA_GL_BG_PALETTE, },
 163	{ "screenBase", GBA_GL_BG_SCREENBASE, },
 164	{ "charBase", GBA_GL_BG_CHARBASE, },
 165	{ "size", GBA_GL_BG_SIZE, },
 166	{ "inflags", GBA_GL_BG_INFLAGS, },
 167	{ "offset", GBA_GL_BG_OFFSET, },
 168	{ "transform", GBA_GL_BG_TRANSFORM, },
 169	{ 0 }
 170};
 171
 172static const char* const _renderMode2 =
 173	"in vec2 texCoord;\n"
 174	"uniform sampler2D vram;\n"
 175	"uniform sampler2D palette;\n"
 176	"uniform int screenBase;\n"
 177	"uniform int charBase;\n"
 178	"uniform int size;\n"
 179	"uniform ivec4 inflags;\n"
 180	"uniform ivec2[4] offset;\n"
 181	"uniform ivec2[4] transform;\n"
 182	"out vec4 color;\n"
 183	"out vec4 flags;\n"
 184	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 185	"precision highp float;\n"
 186	"precision highp int;\n"
 187
 188	"vec4 fetchTile(ivec2 coord);\n"
 189
 190	"vec4 renderTile(ivec2 coord) {\n"
 191	"	int map = (coord.x >> 11) + (((coord.y >> 7) & 0x7F0) << size);\n"
 192	"	int mapAddress = screenBase + (map >> 1);\n"
 193	"	vec4 twomaps = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0);\n"
 194	"	int tile = int(twomaps[3 - 2 * (map & 1)] * 15.9) + int(twomaps[2 - 2 * (map & 1)] * 15.9) * 16;\n"
 195	"	int address = charBase + tile * 32 + ((coord.x >> 9) & 3) + ((coord.y >> 6) & 0x1C);\n"
 196	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
 197	"	int entry = int(halfrow[3 - ((coord.x >> 7) & 2)] * 15.9);\n"
 198	"	int pal2 = int(halfrow[2 - ((coord.x >> 7) & 2)] * 15.9);\n"
 199	"	vec4 color = texelFetch(palette, ivec2(entry, pal2), 0);\n"
 200	"	if ((pal2 | entry) == 0) {\n"
 201	"		discard;\n"
 202	"	}\n"
 203	"	color.a = 1.;\n"
 204	"	return color;\n"
 205	"}\n"
 206
 207	"vec2 interpolate(ivec2 arr[4], float x) {\n"
 208	"	float x1m = 1. - x;\n"
 209	"	return x1m * x1m * x1m * arr[0] +"
 210		"  3 * x1m * x1m * x   * arr[1] +"
 211		"  3 * x1m * x   * x   * arr[2] +"
 212		"      x   * x   * x   * arr[3];\n"
 213	"}\n"
 214
 215	"void main() {\n"
 216	"	float y = fract(texCoord.y);\n"
 217	"	float lin = 0.5 - y / ceil(y) * 0.25;\n"
 218	"	vec2 mixedTransform = interpolate(transform, lin);\n"
 219	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 220	"	color = fetchTile(ivec2(mixedTransform * texCoord.x + mixedOffset));\n"
 221	"	flags = inflags / flagCoeff;\n"
 222	"}";
 223
 224const static struct GBAVideoGLUniform _uniformsObj[] = {
 225	{ "loc", GBA_GL_VS_LOC, },
 226	{ "maxPos", GBA_GL_VS_MAXPOS, },
 227	{ "vram", GBA_GL_OBJ_VRAM, },
 228	{ "palette", GBA_GL_OBJ_PALETTE, },
 229	{ "charBase", GBA_GL_OBJ_CHARBASE, },
 230	{ "stride", GBA_GL_OBJ_STRIDE, },
 231	{ "localPalette", GBA_GL_OBJ_LOCALPALETTE, },
 232	{ "inflags", GBA_GL_OBJ_INFLAGS, },
 233	{ "transform", GBA_GL_OBJ_TRANSFORM, },
 234	{ "dims", GBA_GL_OBJ_DIMS, },
 235	{ 0 }
 236};
 237
 238static const char* const _renderObj =
 239	"in vec2 texCoord;\n"
 240	"uniform sampler2D vram;\n"
 241	"uniform sampler2D palette;\n"
 242	"uniform int charBase;\n"
 243	"uniform int stride;\n"
 244	"uniform int localPalette;\n"
 245	"uniform ivec4 inflags;\n"
 246	"uniform mat2x2 transform;\n"
 247	"uniform ivec4 dims;\n"
 248	"out vec4 color;\n"
 249	"out vec4 flags;\n"
 250	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 251
 252	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 253
 254	"void main() {\n"
 255	"	ivec2 coord = ivec2(transform * (texCoord - dims.zw / 2) + dims.xy / 2);\n"
 256	"	if ((coord & ~(dims.xy - 1)) != ivec2(0, 0)) {\n"
 257	"		discard;\n"
 258	"	}\n"
 259	"	color = renderTile((coord.x >> 3) + (coord.y >> 3) * stride, 16 + localPalette, coord & 7);\n"
 260	"	flags = inflags / flagCoeff;\n"
 261	"}";
 262
 263const static struct GBAVideoGLUniform _uniformsComposite[] = {
 264	{ "loc", GBA_GL_VS_LOC, },
 265	{ "maxPos", GBA_GL_VS_MAXPOS, },
 266	{ "scale", GBA_GL_COMPOSITE_SCALE, },
 267	{ "layerId", GBA_GL_COMPOSITE_LAYERID, },
 268	{ "layer", GBA_GL_COMPOSITE_LAYER, },
 269	{ "layerFlags", GBA_GL_COMPOSITE_LAYERFLAGS, },
 270	{ "oldLayer", GBA_GL_COMPOSITE_OLDLAYER, },
 271	{ "oldLayerFlags", GBA_GL_COMPOSITE_OLDLAYERFLAGS, },
 272	{ "oldOldFlags", GBA_GL_COMPOSITE_OLDOLDFLAGS, },
 273	{ "window", GBA_GL_COMPOSITE_WINDOW, },
 274	{ 0 }
 275};
 276
 277static const char* const _composite =
 278	"in vec2 texCoord;\n"
 279	"uniform int scale;\n"
 280	"uniform int layerId\n;"
 281	"uniform sampler2D layer;\n"
 282	"uniform sampler2D layerFlags;\n"
 283	"uniform sampler2D oldLayer;\n"
 284	"uniform sampler2D oldLayerFlags;\n"
 285	"uniform sampler2D oldOldFlags;\n"
 286	"uniform sampler2D window;\n"
 287	"out vec4 color;\n"
 288	"out vec4 flags;\n"
 289	"out vec4 oldColor;\n"
 290	"out vec4 oldFlags;\n"
 291	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 292
 293	"void main() {\n"
 294	"	vec4 pix = texelFetch(layer, ivec2(texCoord * scale), 0);\n"
 295	"	if (pix.a == 0) {\n"
 296	"		discard;\n"
 297	"	}\n"
 298	"	ivec2 windowFlags = ivec2(texelFetch(window, ivec2(texCoord * scale), 0).xy * 32.);\n"
 299	"	if (((windowFlags.x | (windowFlags.y << 4)) & layerId) != 0) {\n"
 300	"		discard;\n"
 301	"	}\n"
 302	"	ivec4 inflags = ivec4(texelFetch(layerFlags, ivec2(texCoord * scale), 0) * flagCoeff);\n"
 303	"	ivec4 oflags = ivec4(texelFetch(oldLayerFlags, ivec2(texCoord * scale), 0) * flagCoeff);\n"
 304	"	if ((windowFlags.y & 2) != 0) {\n"
 305	"		inflags.y = 0;\n"
 306	"	}\n"
 307	"	if (inflags.x >= oflags.x) {\n"
 308	"		ivec4 ooflags = ivec4(texelFetch(oldOldFlags, ivec2(texCoord * scale), 0) * flagCoeff);\n"
 309	"		if (inflags.x >= ooflags.x) {\n"
 310	"			discard;\n"
 311	"		}\n"
 312	"		oldFlags = inflags / flagCoeff;\n"
 313	"		flags = oflags / flagCoeff;\n"
 314	"		oldColor = pix;\n"
 315	"		color = texelFetch(oldLayer, ivec2(texCoord * scale), 0);\n"
 316	"	} else {\n"
 317	"		color = pix;\n"
 318	"		oldColor = texelFetch(oldLayer, ivec2(texCoord * scale), 0);\n"
 319	"		flags = inflags / flagCoeff;\n"
 320	"		oldFlags = oflags / flagCoeff;\n"
 321	"	}\n"
 322	"}";
 323
 324const static struct GBAVideoGLUniform _uniformsFinalize[] = {
 325	{ "loc", GBA_GL_VS_LOC, },
 326	{ "maxPos", GBA_GL_VS_MAXPOS, },
 327	{ "scale", GBA_GL_FINALIZE_SCALE, },
 328	{ "layer", GBA_GL_FINALIZE_LAYER, },
 329	{ "layerFlags", GBA_GL_FINALIZE_LAYERFLAGS, },
 330	{ "oldLayer", GBA_GL_FINALIZE_OLDLAYER, },
 331	{ "oldFlags", GBA_GL_FINALIZE_OLDFLAGS, },
 332	{ 0 }
 333};
 334
 335static const char* const _finalize =
 336	"in vec2 texCoord;\n"
 337	"uniform int scale;\n"
 338	"uniform sampler2D layer;\n"
 339	"uniform sampler2D layerFlags;\n"
 340	"uniform sampler2D oldLayer;\n"
 341	"uniform sampler2D oldFlags;\n"
 342	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 343	"out vec4 color;\n"
 344
 345	"void main() {\n"
 346	"	vec4 pix = texelFetch(layer, ivec2(texCoord * scale), 0);\n"
 347	"	ivec4 inflags = ivec4(texelFetch(layerFlags, ivec2(texCoord * scale), 0) * flagCoeff);\n"
 348	"	if ((inflags.y & 13) == 5) {\n"
 349	"		ivec4 oflags = ivec4(texelFetch(oldFlags, ivec2(texCoord * scale), 0) * flagCoeff);\n"
 350	"		if ((oflags.y & 2) == 2) {\n"
 351	"			vec4 oldpix = texelFetch(oldLayer, ivec2(texCoord * scale), 0);\n"
 352	"			pix *= inflags.z / 16.;\n"
 353	"			pix += oldpix * oflags.w / 16.;\n"
 354	"		}\n"
 355	"	} else if ((inflags.y & 13) == 9) {\n"
 356	"		pix += (1. - pix) * inflags.z / 16.;\n"
 357	"	} else if ((inflags.y & 13) == 13) {\n"
 358	"		pix -= pix * inflags.z / 16.;\n"
 359	"	}\n"
 360	"	color = pix;\n"
 361	"}";
 362
 363static const GLint _vertices[] = {
 364	0, 0,
 365	0, 1,
 366	1, 1,
 367	1, 0,
 368};
 369
 370void GBAVideoGLRendererCreate(struct GBAVideoGLRenderer* renderer) {
 371	renderer->d.init = GBAVideoGLRendererInit;
 372	renderer->d.reset = GBAVideoGLRendererReset;
 373	renderer->d.deinit = GBAVideoGLRendererDeinit;
 374	renderer->d.writeVideoRegister = GBAVideoGLRendererWriteVideoRegister;
 375	renderer->d.writeVRAM = GBAVideoGLRendererWriteVRAM;
 376	renderer->d.writeOAM = GBAVideoGLRendererWriteOAM;
 377	renderer->d.writePalette = GBAVideoGLRendererWritePalette;
 378	renderer->d.drawScanline = GBAVideoGLRendererDrawScanline;
 379	renderer->d.finishFrame = GBAVideoGLRendererFinishFrame;
 380	renderer->d.getPixels = GBAVideoGLRendererGetPixels;
 381	renderer->d.putPixels = GBAVideoGLRendererPutPixels;
 382
 383	renderer->d.disableBG[0] = false;
 384	renderer->d.disableBG[1] = false;
 385	renderer->d.disableBG[2] = false;
 386	renderer->d.disableBG[3] = false;
 387	renderer->d.disableOBJ = false;
 388
 389	renderer->scale = 1;
 390}
 391
 392void _compileShader(struct GBAVideoGLRenderer* glRenderer, GLuint program, const char** shaderBuffer, int shaderBufferLines, GLuint vs, char* log) {
 393	GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
 394	glAttachShader(program, vs);
 395	glAttachShader(program, fs);
 396	glShaderSource(fs, shaderBufferLines, shaderBuffer, 0);
 397	glCompileShader(fs);
 398	glGetShaderInfoLog(fs, 1024, 0, log);
 399	if (log[0]) {
 400		mLOG(GBA_VIDEO, ERROR, "Fragment shader compilation failure: %s", log);
 401	}
 402	glLinkProgram(program);
 403	glGetProgramInfoLog(program, 1024, 0, log);
 404	if (log[0]) {
 405		mLOG(GBA_VIDEO, ERROR, "Program link failure: %s", log);
 406	}
 407	glDeleteShader(fs);
 408	glBindFragDataLocation(program, 0, "color");
 409	glBindFragDataLocation(program, 1, "flags");
 410}
 411
 412static void _initFramebufferTexture(GLuint tex, GLenum format, GLenum attachment, int scale) {
 413	glBindTexture(GL_TEXTURE_2D, tex);
 414	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 415	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 416	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 417	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 418	glTexImage2D(GL_TEXTURE_2D, 0, format, GBA_VIDEO_HORIZONTAL_PIXELS * scale, GBA_VIDEO_VERTICAL_PIXELS * scale, 0, format, GL_UNSIGNED_BYTE, 0);
 419	glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, tex, 0);	
 420}
 421
 422static void _lookupUniforms(GLuint program, GLuint* out, const struct GBAVideoGLUniform* uniforms) {
 423	size_t i;
 424	for (i = 0; uniforms[i].name; ++i) {
 425		out[uniforms[i].type] = glGetUniformLocation(program, uniforms[i].name);
 426	}
 427}
 428
 429void GBAVideoGLRendererInit(struct GBAVideoRenderer* renderer) {
 430	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 431	glGenFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 432	glGenTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 433
 434	glGenTextures(1, &glRenderer->paletteTex);
 435	glBindTexture(GL_TEXTURE_2D, glRenderer->paletteTex);
 436	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 437	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 438
 439	glGenTextures(1, &glRenderer->vramTex);
 440	glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
 441	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 442	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 443	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, 256, 192, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 0);
 444
 445	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
 446	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_OBJ_COLOR], GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 447	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_OBJ_FLAGS], GL_RGBA, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 448
 449	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_COMPOSITE]);
 450	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_COMPOSITE_COLOR], GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 451	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_COMPOSITE_FLAGS], GL_RGBA, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 452	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_COMPOSITE_OLD_COLOR], GL_RGBA, GL_COLOR_ATTACHMENT2, glRenderer->scale);
 453	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_COMPOSITE_OLD_FLAGS], GL_RGBA, GL_COLOR_ATTACHMENT3, glRenderer->scale);
 454
 455	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_WINDOW]);
 456	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_WINDOW], GL_RG, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 457
 458	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OUTPUT]);
 459	_initFramebufferTexture(glRenderer->outputTex, GL_RGB, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 460
 461	glBindFramebuffer(GL_FRAMEBUFFER, 0);
 462
 463	int i;
 464	for (i = 0; i < 4; ++i) {
 465		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 466		bg->index = i;
 467		bg->enabled = 0;
 468		bg->priority = 0;
 469		bg->charBase = 0;
 470		bg->mosaic = 0;
 471		bg->multipalette = 0;
 472		bg->screenBase = 0;
 473		bg->overflow = 0;
 474		bg->size = 0;
 475		bg->target1 = 0;
 476		bg->target2 = 0;
 477		bg->x = 0;
 478		bg->y = 0;
 479		bg->refx = 0;
 480		bg->refy = 0;
 481		bg->affine[0].dx = 256;
 482		bg->affine[0].dmx = 0;
 483		bg->affine[0].dy = 0;
 484		bg->affine[0].dmy = 256;
 485		bg->affine[0].sx = 0;
 486		bg->affine[0].sy = 0;
 487		glGenFramebuffers(1, &bg->fbo);
 488		glGenTextures(1, &bg->tex);
 489		glGenTextures(1, &bg->flags);
 490		glBindFramebuffer(GL_FRAMEBUFFER, bg->fbo);
 491		_initFramebufferTexture(bg->tex, GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 492		_initFramebufferTexture(bg->flags, GL_RGBA, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 493		glBindFramebuffer(GL_FRAMEBUFFER, 0);
 494	}
 495
 496	glRenderer->compositeProgram = glCreateProgram();
 497	glRenderer->finalizeProgram = glCreateProgram();
 498	glRenderer->objProgram[0] = glCreateProgram();
 499	glRenderer->objProgram[1] = glCreateProgram();
 500	glRenderer->bgProgram[0] = glCreateProgram();
 501	glRenderer->bgProgram[1] = glCreateProgram();
 502	glRenderer->bgProgram[2] = glCreateProgram();
 503	glRenderer->bgProgram[3] = glCreateProgram();
 504	glRenderer->bgProgram[4] = glCreateProgram();
 505	glRenderer->bgProgram[5] = glCreateProgram();
 506
 507	char log[1024];
 508	const GLchar* shaderBuffer[8];
 509	shaderBuffer[0] = _gl3Header;
 510
 511	GLuint vs = glCreateShader(GL_VERTEX_SHADER);
 512	shaderBuffer[1] = _vertexShader;
 513	glShaderSource(vs, 2, shaderBuffer, 0);
 514	glCompileShader(vs);
 515	glGetShaderInfoLog(vs, 1024, 0, log);
 516	if (log[0]) {
 517		mLOG(GBA_VIDEO, ERROR, "Vertex shader compilation failure: %s", log);
 518	}
 519
 520	shaderBuffer[1] = _renderMode0;
 521
 522	shaderBuffer[2] = _renderTile16;
 523	_compileShader(glRenderer, glRenderer->bgProgram[0], shaderBuffer, 3, vs, log);
 524	_lookupUniforms(glRenderer->bgProgram[0], glRenderer->bgUniforms[0], _uniformsMode0);
 525
 526	shaderBuffer[2] = _renderTile256;
 527	_compileShader(glRenderer, glRenderer->bgProgram[1], shaderBuffer, 3, vs, log);
 528	_lookupUniforms(glRenderer->bgProgram[1], glRenderer->bgUniforms[1], _uniformsMode0);
 529
 530	shaderBuffer[1] = _renderMode2;
 531
 532	shaderBuffer[2] = _fetchTileOverflow;
 533	_compileShader(glRenderer, glRenderer->bgProgram[2], shaderBuffer, 3, vs, log);
 534	_lookupUniforms(glRenderer->bgProgram[2], glRenderer->bgUniforms[2], _uniformsMode2);
 535
 536	shaderBuffer[2] = _fetchTileNoOverflow;
 537	_compileShader(glRenderer, glRenderer->bgProgram[3], shaderBuffer, 3, vs, log);
 538	_lookupUniforms(glRenderer->bgProgram[3], glRenderer->bgUniforms[3], _uniformsMode2);
 539
 540	shaderBuffer[1] = _renderObj;
 541
 542	shaderBuffer[2] = _renderTile16;
 543	_compileShader(glRenderer, glRenderer->objProgram[0], shaderBuffer, 3, vs, log);
 544	_lookupUniforms(glRenderer->objProgram[0], glRenderer->objUniforms[0], _uniformsObj);
 545
 546	shaderBuffer[2] = _renderTile256;
 547	_compileShader(glRenderer, glRenderer->objProgram[1], shaderBuffer, 3, vs, log);
 548	_lookupUniforms(glRenderer->objProgram[1], glRenderer->objUniforms[1], _uniformsObj);
 549
 550	shaderBuffer[1] = _composite;
 551	_compileShader(glRenderer, glRenderer->compositeProgram, shaderBuffer, 2, vs, log);
 552	_lookupUniforms(glRenderer->compositeProgram, glRenderer->compositeUniforms, _uniformsComposite);
 553	glBindFragDataLocation(glRenderer->compositeProgram, 2, "oldColor");
 554	glBindFragDataLocation(glRenderer->compositeProgram, 3, "oldFlags");
 555
 556	shaderBuffer[1] = _finalize;
 557	_compileShader(glRenderer, glRenderer->finalizeProgram, shaderBuffer, 2, vs, log);
 558	_lookupUniforms(glRenderer->finalizeProgram, glRenderer->finalizeUniforms, _uniformsFinalize);
 559
 560	glDeleteShader(vs);
 561
 562	GBAVideoGLRendererReset(renderer);
 563}
 564
 565void GBAVideoGLRendererDeinit(struct GBAVideoRenderer* renderer) {
 566	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 567	glDeleteFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 568	glDeleteTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 569	glDeleteTextures(1, &glRenderer->paletteTex);
 570	glDeleteTextures(1, &glRenderer->vramTex);
 571
 572	glDeleteProgram(glRenderer->bgProgram[0]);
 573	glDeleteProgram(glRenderer->bgProgram[1]);
 574	glDeleteProgram(glRenderer->bgProgram[2]);
 575	glDeleteProgram(glRenderer->bgProgram[3]);
 576	glDeleteProgram(glRenderer->bgProgram[4]);
 577	glDeleteProgram(glRenderer->bgProgram[5]);
 578	glDeleteProgram(glRenderer->bgProgram[6]);
 579	glDeleteProgram(glRenderer->objProgram[0]);
 580	glDeleteProgram(glRenderer->objProgram[1]);
 581	glDeleteProgram(glRenderer->compositeProgram);
 582}
 583
 584void GBAVideoGLRendererReset(struct GBAVideoRenderer* renderer) {
 585	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 586
 587	glRenderer->paletteDirty = true;
 588	glRenderer->vramDirty = 0xFFFFFF;
 589	glRenderer->firstAffine = -1;
 590}
 591
 592void GBAVideoGLRendererWriteVRAM(struct GBAVideoRenderer* renderer, uint32_t address) {
 593	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 594	glRenderer->vramDirty |= 1 << (address >> 12);
 595}
 596
 597void GBAVideoGLRendererWriteOAM(struct GBAVideoRenderer* renderer, uint32_t oam) {
 598	UNUSED(oam);
 599	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 600	glRenderer->oamDirty = true;
 601}
 602
 603void GBAVideoGLRendererWritePalette(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 604	UNUSED(address);
 605	UNUSED(value);
 606	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 607	glRenderer->paletteDirty = true;
 608}
 609
 610uint16_t GBAVideoGLRendererWriteVideoRegister(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 611	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 612	if (renderer->cache) {
 613		GBAVideoCacheWriteVideoRegister(renderer->cache, address, value);
 614	}
 615
 616	switch (address) {
 617	case REG_DISPCNT:
 618		value &= 0xFFF7;
 619		glRenderer->dispcnt = value;
 620		GBAVideoGLRendererUpdateDISPCNT(glRenderer);
 621		break;
 622	case REG_BG0CNT:
 623		value &= 0xDFFF;
 624		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[0], value);
 625		break;
 626	case REG_BG1CNT:
 627		value &= 0xDFFF;
 628		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[1], value);
 629		break;
 630	case REG_BG2CNT:
 631		value &= 0xFFFF;
 632		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[2], value);
 633		break;
 634	case REG_BG3CNT:
 635		value &= 0xFFFF;
 636		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[3], value);
 637		break;
 638	case REG_BG0HOFS:
 639		value &= 0x01FF;
 640		glRenderer->bg[0].x = value;
 641		break;
 642	case REG_BG0VOFS:
 643		value &= 0x01FF;
 644		glRenderer->bg[0].y = value;
 645		break;
 646	case REG_BG1HOFS:
 647		value &= 0x01FF;
 648		glRenderer->bg[1].x = value;
 649		break;
 650	case REG_BG1VOFS:
 651		value &= 0x01FF;
 652		glRenderer->bg[1].y = value;
 653		break;
 654	case REG_BG2HOFS:
 655		value &= 0x01FF;
 656		glRenderer->bg[2].x = value;
 657		break;
 658	case REG_BG2VOFS:
 659		value &= 0x01FF;
 660		glRenderer->bg[2].y = value;
 661		break;
 662	case REG_BG3HOFS:
 663		value &= 0x01FF;
 664		glRenderer->bg[3].x = value;
 665		break;
 666	case REG_BG3VOFS:
 667		value &= 0x01FF;
 668		glRenderer->bg[3].y = value;
 669		break;
 670	case REG_BG2PA:
 671		glRenderer->bg[2].affine[0].dx = value;
 672		break;
 673	case REG_BG2PB:
 674		glRenderer->bg[2].affine[0].dmx = value;
 675		break;
 676	case REG_BG2PC:
 677		glRenderer->bg[2].affine[0].dy = value;
 678		break;
 679	case REG_BG2PD:
 680		glRenderer->bg[2].affine[0].dmy = value;
 681		break;
 682	case REG_BG2X_LO:
 683		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[2], value);
 684		break;
 685	case REG_BG2X_HI:
 686		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[2], value);
 687		break;
 688	case REG_BG2Y_LO:
 689		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[2], value);
 690		break;
 691	case REG_BG2Y_HI:
 692		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[2], value);
 693		break;
 694	case REG_BG3PA:
 695		glRenderer->bg[3].affine[0].dx = value;
 696		break;
 697	case REG_BG3PB:
 698		glRenderer->bg[3].affine[0].dmx = value;
 699		break;
 700	case REG_BG3PC:
 701		glRenderer->bg[3].affine[0].dy = value;
 702		break;
 703	case REG_BG3PD:
 704		glRenderer->bg[3].affine[0].dmy = value;
 705		break;
 706	case REG_BG3X_LO:
 707		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[3], value);
 708		break;
 709	case REG_BG3X_HI:
 710		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[3], value);
 711		break;
 712	case REG_BG3Y_LO:
 713		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[3], value);
 714		break;
 715	case REG_BG3Y_HI:
 716		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[3], value);
 717		break;
 718	case REG_BLDCNT:
 719		GBAVideoGLRendererWriteBLDCNT(glRenderer, value);
 720		value &= 0x3FFF;
 721		break;
 722	case REG_BLDALPHA:
 723		glRenderer->blda = value & 0x1F;
 724		if (glRenderer->blda > 0x10) {
 725			glRenderer->blda = 0x10;
 726		}
 727		glRenderer->bldb = (value >> 8) & 0x1F;
 728		if (glRenderer->bldb > 0x10) {
 729			glRenderer->bldb = 0x10;
 730		}
 731		value &= 0x1F1F;
 732		break;
 733	case REG_BLDY:
 734		value &= 0x1F;
 735		if (value > 0x10) {
 736			value = 0x10;
 737		}
 738		glRenderer->bldy = value;
 739		break;
 740	case REG_WIN0H:
 741		glRenderer->winN[0].h.end = value;
 742		glRenderer->winN[0].h.start = value >> 8;
 743		if (glRenderer->winN[0].h.start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[0].h.start > glRenderer->winN[0].h.end) {
 744			glRenderer->winN[0].h.start = 0;
 745		}
 746		if (glRenderer->winN[0].h.end > GBA_VIDEO_HORIZONTAL_PIXELS) {
 747			glRenderer->winN[0].h.end = GBA_VIDEO_HORIZONTAL_PIXELS;
 748			if (glRenderer->winN[0].h.start > GBA_VIDEO_HORIZONTAL_PIXELS) {
 749				glRenderer->winN[0].h.start = GBA_VIDEO_HORIZONTAL_PIXELS;
 750			}
 751		}
 752		break;
 753	case REG_WIN1H:
 754		glRenderer->winN[1].h.end = value;
 755		glRenderer->winN[1].h.start = value >> 8;
 756		if (glRenderer->winN[1].h.start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[1].h.start > glRenderer->winN[1].h.end) {
 757			glRenderer->winN[1].h.start = 0;
 758		}
 759		if (glRenderer->winN[1].h.end > GBA_VIDEO_HORIZONTAL_PIXELS) {
 760			glRenderer->winN[1].h.end = GBA_VIDEO_HORIZONTAL_PIXELS;
 761			if (glRenderer->winN[1].h.start > GBA_VIDEO_HORIZONTAL_PIXELS) {
 762				glRenderer->winN[1].h.start = GBA_VIDEO_HORIZONTAL_PIXELS;
 763			}
 764		}
 765		break;
 766	case REG_WIN0V:
 767		glRenderer->winN[0].v.end = value;
 768		glRenderer->winN[0].v.start = value >> 8;
 769		if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[0].v.start > glRenderer->winN[0].v.end) {
 770			glRenderer->winN[0].v.start = 0;
 771		}
 772		if (glRenderer->winN[0].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
 773			glRenderer->winN[0].v.end = GBA_VIDEO_VERTICAL_PIXELS;
 774			if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
 775				glRenderer->winN[0].v.start = GBA_VIDEO_VERTICAL_PIXELS;
 776			}
 777		}
 778		break;
 779	case REG_WIN1V:
 780		glRenderer->winN[1].v.end = value;
 781		glRenderer->winN[1].v.start = value >> 8;
 782		if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[1].v.start > glRenderer->winN[1].v.end) {
 783			glRenderer->winN[1].v.start = 0;
 784		}
 785		if (glRenderer->winN[1].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
 786			glRenderer->winN[1].v.end = GBA_VIDEO_VERTICAL_PIXELS;
 787			if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
 788				glRenderer->winN[1].v.start = GBA_VIDEO_VERTICAL_PIXELS;
 789			}
 790		}
 791		break;
 792	case REG_WININ:
 793		value &= 0x3F3F;
 794		glRenderer->winN[0].control = value;
 795		glRenderer->winN[1].control = value >> 8;
 796		break;
 797	case REG_WINOUT:
 798		value &= 0x3F3F;
 799		glRenderer->winout = value;
 800		glRenderer->objwin = value >> 8;
 801		break;
 802	case REG_MOSAIC:
 803		glRenderer->mosaic = value;
 804		break;
 805	default:
 806		break;
 807	}
 808	return value;
 809}
 810
 811void GBAVideoGLRendererDrawScanline(struct GBAVideoRenderer* renderer, int y) {
 812	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 813	if (glRenderer->paletteDirty) {
 814		glBindTexture(GL_TEXTURE_2D, glRenderer->paletteTex);
 815		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB5_A1, 16, 32, 0, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, glRenderer->d.palette);
 816		glRenderer->paletteDirty = false;
 817	}
 818	int i;
 819	for (i = 0; i < 24; ++i) {
 820		if (!(glRenderer->vramDirty & (1 << i))) {
 821			continue;
 822		}
 823		// TODO: PBOs
 824		glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
 825		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 8 * i, 256, 8, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, &glRenderer->d.vram[2048 * i]);
 826	}
 827	glRenderer->vramDirty = 0;
 828
 829	uint32_t backdrop = M_RGB5_TO_RGB8(renderer->palette[0]);
 830	glClearColor(((backdrop >> 16) & 0xFF) / 256., ((backdrop >> 8) & 0xFF) / 256., (backdrop & 0xFF) / 256., 0.f);
 831	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_COMPOSITE]);
 832	glEnable(GL_SCISSOR_TEST);
 833	glScissor(0, y * glRenderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale, glRenderer->scale);
 834	glDrawBuffer(GL_COLOR_ATTACHMENT0);
 835	glClear(GL_COLOR_BUFFER_BIT);
 836	if (y == 0) {
 837		glDisable(GL_SCISSOR_TEST);
 838		glDrawBuffer(GL_COLOR_ATTACHMENT1);
 839		glClearColor(1, (glRenderer->target1Bd | (glRenderer->target2Bd * 2) | (glRenderer->blendEffect * 4)) / 32.f,
 840		             (glRenderer->blendEffect == BLEND_ALPHA ? glRenderer->blda : glRenderer->bldy) / 16.f, glRenderer->bldb / 16.f);
 841		glClear(GL_COLOR_BUFFER_BIT);
 842		
 843		glClearColor(0, 0, 0, 0);
 844		glDrawBuffer(GL_COLOR_ATTACHMENT3);
 845		glClear(GL_COLOR_BUFFER_BIT);
 846
 847		glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
 848		glDrawBuffer(GL_COLOR_ATTACHMENT0);
 849		glClear(GL_COLOR_BUFFER_BIT);
 850		glDrawBuffer(GL_COLOR_ATTACHMENT1);
 851		glClear(GL_COLOR_BUFFER_BIT);
 852
 853		for (i = 0; i < 4; ++i) {
 854			glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->bg[i].fbo);
 855			glDrawBuffer(GL_COLOR_ATTACHMENT0);
 856			glClear(GL_COLOR_BUFFER_BIT);
 857			glDrawBuffer(GL_COLOR_ATTACHMENT1);
 858			glClear(GL_COLOR_BUFFER_BIT);
 859		}
 860		glDrawBuffer(GL_COLOR_ATTACHMENT0);
 861		glEnable(GL_SCISSOR_TEST);
 862	}
 863	glBindFramebuffer(GL_FRAMEBUFFER, 0);
 864
 865	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
 866		if (glRenderer->firstAffine < 0) {
 867			memcpy(&glRenderer->bg[2].affine[3], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 868			memcpy(&glRenderer->bg[3].affine[3], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 869			memcpy(&glRenderer->bg[2].affine[2], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 870			memcpy(&glRenderer->bg[3].affine[2], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 871			memcpy(&glRenderer->bg[2].affine[1], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 872			memcpy(&glRenderer->bg[3].affine[1], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 873			glRenderer->firstAffine = y;
 874		} else if (y - glRenderer->firstAffine == 1) {
 875			memcpy(&glRenderer->bg[2].affine[1], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 876			memcpy(&glRenderer->bg[3].affine[1], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));			
 877		}
 878	} else {
 879		glRenderer->firstAffine = -1;
 880	}
 881
 882	int spriteLayers = 0;
 883	if (GBARegisterDISPCNTIsObjEnable(glRenderer->dispcnt) && !glRenderer->d.disableOBJ) {
 884		if (glRenderer->oamDirty) {
 885			glRenderer->oamMax = GBAVideoRendererCleanOAM(glRenderer->d.oam->obj, glRenderer->sprites, 0);
 886			glRenderer->oamDirty = false;
 887		}
 888		int i;
 889		for (i = glRenderer->oamMax; i--;) {
 890			struct GBAVideoRendererSprite* sprite = &glRenderer->sprites[i];
 891			if ((y < sprite->y && (sprite->endY - 256 < 0 || y >= sprite->endY - 256)) || y >= sprite->endY) {
 892				continue;
 893			}
 894
 895			GBAVideoGLRendererDrawSprite(glRenderer, &sprite->obj, y, sprite->y);
 896			spriteLayers |= 1 << GBAObjAttributesCGetPriority(sprite->obj.c);
 897		}
 898	}
 899
 900	GBAVideoGLRendererDrawWindow(glRenderer, y);
 901	_compositeLayer(glRenderer, glRenderer->layers[GBA_GL_TEX_OBJ_COLOR], glRenderer->layers[GBA_GL_TEX_OBJ_FLAGS], 4, y);
 902	unsigned priority;
 903	for (priority = 4; priority--;) {
 904		if (TEST_LAYER_ENABLED(0) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
 905			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[0], y);
 906		}
 907		if (TEST_LAYER_ENABLED(1) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
 908			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[1], y);
 909		}
 910		if (TEST_LAYER_ENABLED(2)) {
 911			switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
 912			case 0:
 913				GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[2], y);
 914				break;
 915			case 1:
 916			case 2:
 917				GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[2], y);
 918				break;
 919			case 3:
 920				//GBAVideoGLRendererDrawBackgroundMode3(glRenderer, &glRenderer->bg[2], y);
 921				break;
 922			case 4:
 923				//GBAVideoGLRendererDrawBackgroundMode4(glRenderer, &glRenderer->bg[2], y);
 924				break;
 925			case 5:
 926				//GBAVideoGLRendererDrawBackgroundMode5(glRenderer, &glRenderer->bg[2], y);
 927				break;
 928			}
 929		}
 930		if (TEST_LAYER_ENABLED(3)) {
 931			switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
 932			case 0:
 933				GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[3], y);
 934				break;
 935			case 2:
 936				GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[3], y);
 937				break;
 938			}
 939		}
 940	}
 941	_finalizeLayers(glRenderer, y);
 942
 943	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
 944		memcpy(&glRenderer->bg[2].affine[3], &glRenderer->bg[2].affine[2], sizeof(struct GBAVideoGLAffine));
 945		memcpy(&glRenderer->bg[3].affine[3], &glRenderer->bg[3].affine[2], sizeof(struct GBAVideoGLAffine));
 946		memcpy(&glRenderer->bg[2].affine[2], &glRenderer->bg[2].affine[1], sizeof(struct GBAVideoGLAffine));
 947		memcpy(&glRenderer->bg[3].affine[2], &glRenderer->bg[3].affine[1], sizeof(struct GBAVideoGLAffine));
 948		memcpy(&glRenderer->bg[2].affine[1], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 949		memcpy(&glRenderer->bg[3].affine[1], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 950
 951		glRenderer->bg[2].affine[0].sx += glRenderer->bg[2].affine[0].dmx;
 952		glRenderer->bg[2].affine[0].sy += glRenderer->bg[2].affine[0].dmy;
 953		glRenderer->bg[3].affine[0].sx += glRenderer->bg[3].affine[0].dmx;
 954		glRenderer->bg[3].affine[0].sy += glRenderer->bg[3].affine[0].dmy;
 955	}
 956}
 957
 958void GBAVideoGLRendererFinishFrame(struct GBAVideoRenderer* renderer) {
 959	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 960	glRenderer->firstAffine = -1;
 961	glRenderer->bg[2].affine[0].sx = glRenderer->bg[2].refx;
 962	glRenderer->bg[2].affine[0].sy = glRenderer->bg[2].refy;
 963	glRenderer->bg[3].affine[0].sx = glRenderer->bg[3].refx;
 964	glRenderer->bg[3].affine[0].sy = glRenderer->bg[3].refy;
 965	glFlush();
 966}
 967
 968void GBAVideoGLRendererGetPixels(struct GBAVideoRenderer* renderer, size_t* stride, const void** pixels) {
 969
 970}
 971
 972void GBAVideoGLRendererPutPixels(struct GBAVideoRenderer* renderer, size_t stride, const void* pixels) {
 973
 974}
 975
 976static void _enableBg(struct GBAVideoGLRenderer* renderer, int bg, bool active) {
 977	int wasActive = renderer->bg[bg].enabled;
 978	if (!active) {
 979		renderer->bg[bg].enabled = 0;
 980	} else if (!wasActive && active) {
 981		/*if (renderer->nextY == 0 || GBARegisterDISPCNTGetMode(renderer->dispcnt) > 2) {
 982			// TODO: Investigate in more depth how switching background works in different modes
 983			renderer->bg[bg].enabled = 4;
 984		} else {
 985			renderer->bg[bg].enabled = 1;
 986		}*/
 987		renderer->bg[bg].enabled = 4;
 988	}
 989}
 990
 991static void GBAVideoGLRendererUpdateDISPCNT(struct GBAVideoGLRenderer* renderer) {
 992	_enableBg(renderer, 0, GBARegisterDISPCNTGetBg0Enable(renderer->dispcnt));
 993	_enableBg(renderer, 1, GBARegisterDISPCNTGetBg1Enable(renderer->dispcnt));
 994	_enableBg(renderer, 2, GBARegisterDISPCNTGetBg2Enable(renderer->dispcnt));
 995	_enableBg(renderer, 3, GBARegisterDISPCNTGetBg3Enable(renderer->dispcnt));
 996}
 997
 998static void GBAVideoGLRendererWriteBGCNT(struct GBAVideoGLBackground* bg, uint16_t value) {
 999	bg->priority = GBARegisterBGCNTGetPriority(value);
1000	bg->charBase = GBARegisterBGCNTGetCharBase(value) << 13;
1001	bg->mosaic = GBARegisterBGCNTGetMosaic(value);
1002	bg->multipalette = GBARegisterBGCNTGet256Color(value);
1003	bg->screenBase = GBARegisterBGCNTGetScreenBase(value) << 10;
1004	bg->overflow = GBARegisterBGCNTGetOverflow(value);
1005	bg->size = GBARegisterBGCNTGetSize(value);
1006}
1007
1008static void GBAVideoGLRendererWriteBGX_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1009	bg->refx = (bg->refx & 0xFFFF0000) | value;
1010	bg->affine[0].sx = bg->refx;
1011}
1012
1013static void GBAVideoGLRendererWriteBGX_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1014	bg->refx = (bg->refx & 0x0000FFFF) | (value << 16);
1015	bg->refx <<= 4;
1016	bg->refx >>= 4;
1017	bg->affine[0].sx = bg->refx;
1018}
1019
1020static void GBAVideoGLRendererWriteBGY_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1021	bg->refy = (bg->refy & 0xFFFF0000) | value;
1022	bg->affine[0].sy = bg->refy;
1023}
1024
1025static void GBAVideoGLRendererWriteBGY_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1026	bg->refy = (bg->refy & 0x0000FFFF) | (value << 16);
1027	bg->refy <<= 4;
1028	bg->refy >>= 4;
1029	bg->affine[0].sy = bg->refy;
1030}
1031
1032static void GBAVideoGLRendererWriteBLDCNT(struct GBAVideoGLRenderer* renderer, uint16_t value) {
1033	renderer->bg[0].target1 = GBARegisterBLDCNTGetTarget1Bg0(value);
1034	renderer->bg[1].target1 = GBARegisterBLDCNTGetTarget1Bg1(value);
1035	renderer->bg[2].target1 = GBARegisterBLDCNTGetTarget1Bg2(value);
1036	renderer->bg[3].target1 = GBARegisterBLDCNTGetTarget1Bg3(value);
1037	renderer->bg[0].target2 = GBARegisterBLDCNTGetTarget2Bg0(value);
1038	renderer->bg[1].target2 = GBARegisterBLDCNTGetTarget2Bg1(value);
1039	renderer->bg[2].target2 = GBARegisterBLDCNTGetTarget2Bg2(value);
1040	renderer->bg[3].target2 = GBARegisterBLDCNTGetTarget2Bg3(value);
1041
1042	renderer->blendEffect = GBARegisterBLDCNTGetEffect(value);
1043	renderer->target1Obj = GBARegisterBLDCNTGetTarget1Obj(value);
1044	renderer->target1Bd = GBARegisterBLDCNTGetTarget1Bd(value);
1045	renderer->target2Obj = GBARegisterBLDCNTGetTarget2Obj(value);
1046	renderer->target2Bd = GBARegisterBLDCNTGetTarget2Bd(value);
1047}
1048
1049static void _compositeLayer(struct GBAVideoGLRenderer* renderer, GLuint tex, GLuint flags, int id, int y) {
1050	if ((y & 0x1F) != 0x1F) {
1051		return;
1052	}
1053	const GLuint* uniforms = renderer->compositeUniforms;
1054	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_COMPOSITE]);
1055	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1056	glScissor(0, (y & ~0x1F) * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, 0x20 * renderer->scale);
1057	glUseProgram(renderer->compositeProgram);
1058	glActiveTexture(GL_TEXTURE0);
1059	glBindTexture(GL_TEXTURE_2D, tex);
1060	glActiveTexture(GL_TEXTURE0 + 1);
1061	glBindTexture(GL_TEXTURE_2D, flags);
1062	glActiveTexture(GL_TEXTURE0 + 2);
1063	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_COMPOSITE_COLOR]);
1064	glActiveTexture(GL_TEXTURE0 + 3);
1065	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_COMPOSITE_FLAGS]);
1066	glActiveTexture(GL_TEXTURE0 + 4);
1067	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_COMPOSITE_OLD_FLAGS]);
1068	glActiveTexture(GL_TEXTURE0 + 5);
1069	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_WINDOW]);
1070	glUniform2i(uniforms[GBA_GL_VS_LOC], 0x20, y & ~0x1F);
1071	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1072	glUniform1i(uniforms[GBA_GL_COMPOSITE_SCALE], renderer->scale);
1073	glUniform1i(uniforms[GBA_GL_COMPOSITE_LAYERID], 1 << id);
1074	glUniform1i(uniforms[GBA_GL_COMPOSITE_LAYER], 0);
1075	glUniform1i(uniforms[GBA_GL_COMPOSITE_LAYERFLAGS], 1);
1076	glUniform1i(uniforms[GBA_GL_COMPOSITE_OLDLAYER], 2);
1077	glUniform1i(uniforms[GBA_GL_COMPOSITE_OLDLAYERFLAGS], 3);
1078	glUniform1i(uniforms[GBA_GL_COMPOSITE_OLDOLDFLAGS], 4);
1079	glUniform1i(uniforms[GBA_GL_COMPOSITE_WINDOW], 5);
1080	glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 0, _vertices);
1081	glEnableVertexAttribArray(0);
1082	glDrawBuffers(4, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 });
1083	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1084	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1085	glBindFramebuffer(GL_FRAMEBUFFER, 0);
1086}
1087
1088void _finalizeLayers(struct GBAVideoGLRenderer* renderer, int y) {
1089	if ((y & 0x1F) != 0x1F) {
1090		return;
1091	}
1092	const GLuint* uniforms = renderer->finalizeUniforms;
1093	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OUTPUT]);
1094	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1095	glScissor(0, (y & ~0x1F) * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, 0x20 * renderer->scale);
1096	glUseProgram(renderer->finalizeProgram);
1097	glActiveTexture(GL_TEXTURE0);
1098	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_COMPOSITE_COLOR]);
1099	glActiveTexture(GL_TEXTURE0 + 1);
1100	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_COMPOSITE_FLAGS]);
1101	glActiveTexture(GL_TEXTURE0 + 2);
1102	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_COMPOSITE_OLD_COLOR]);
1103	glActiveTexture(GL_TEXTURE0 + 3);
1104	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_COMPOSITE_OLD_FLAGS]);
1105	glUniform2i(uniforms[GBA_GL_VS_LOC], 0x20, y & ~0x1F);
1106	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1107	glUniform1i(uniforms[GBA_GL_FINALIZE_SCALE], renderer->scale);
1108	glUniform1i(uniforms[GBA_GL_FINALIZE_LAYER], 0);
1109	glUniform1i(uniforms[GBA_GL_FINALIZE_LAYERFLAGS], 1);
1110	glUniform1i(uniforms[GBA_GL_FINALIZE_OLDLAYER], 2);
1111	glUniform1i(uniforms[GBA_GL_FINALIZE_OLDFLAGS], 3);
1112	glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 0, _vertices);
1113	glEnableVertexAttribArray(0);
1114	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1115	glBindFramebuffer(GL_FRAMEBUFFER, 0);
1116}
1117
1118void GBAVideoGLRendererDrawSprite(struct GBAVideoGLRenderer* renderer, struct GBAObj* sprite, int y, int spriteY) {
1119	int width = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][0];
1120	int height = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][1];
1121	int32_t x = (uint32_t) GBAObjAttributesBGetX(sprite->b) << 23;
1122	x >>= 23;
1123
1124	int align = GBAObjAttributesAIs256Color(sprite->a) && !GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt);
1125	unsigned charBase = (BASE_TILE >> 1) + (GBAObjAttributesCGetTile(sprite->c) & ~align) * 0x10;
1126	int stride = GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt) ? (width >> 3) : (0x40 >> !GBAObjAttributesAIs256Color(sprite->a));
1127
1128	if (spriteY + height >= 256) {
1129		spriteY -= 256;
1130	}
1131
1132	if (!GBAObjAttributesAIsTransformed(sprite->a) && GBAObjAttributesBIsVFlip(sprite->b)) {
1133		spriteY = (y - height) + (y - spriteY) + 1;
1134	}
1135
1136	int totalWidth = width;
1137	int totalHeight = height;
1138	if (GBAObjAttributesAIsTransformed(sprite->a) && GBAObjAttributesAIsDoubleSize(sprite->a)) {
1139		totalWidth <<= 1;
1140		totalHeight <<= 1;
1141	}
1142
1143	enum GBAVideoBlendEffect blendEffect = GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT ? BLEND_ALPHA : renderer->blendEffect;
1144
1145	const GLuint* uniforms = renderer->objUniforms[GBAObjAttributesAGet256Color(sprite->a)];
1146	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OBJ]);
1147	glViewport(x * renderer->scale, spriteY * renderer->scale, totalWidth * renderer->scale, totalHeight * renderer->scale);
1148	glScissor(x * renderer->scale, y * renderer->scale, totalWidth * renderer->scale, renderer->scale);
1149	glUseProgram(renderer->objProgram[GBAObjAttributesAGet256Color(sprite->a)]);
1150	glActiveTexture(GL_TEXTURE0);
1151	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1152	glActiveTexture(GL_TEXTURE0 + 1);
1153	glBindTexture(GL_TEXTURE_2D, renderer->paletteTex);
1154	glUniform2i(uniforms[GBA_GL_VS_LOC], 1, y - spriteY);
1155	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], (GBAObjAttributesBIsHFlip(sprite->b) && !GBAObjAttributesAIsTransformed(sprite->a)) ? -totalWidth : totalWidth, totalHeight);
1156	glUniform1i(uniforms[GBA_GL_OBJ_VRAM], 0);
1157	glUniform1i(uniforms[GBA_GL_OBJ_PALETTE], 1);
1158	glUniform1i(uniforms[GBA_GL_OBJ_CHARBASE], charBase);
1159	glUniform1i(uniforms[GBA_GL_OBJ_STRIDE], stride);
1160	glUniform1i(uniforms[GBA_GL_OBJ_LOCALPALETTE], GBAObjAttributesCGetPalette(sprite->c));
1161	glUniform4i(uniforms[GBA_GL_OBJ_INFLAGS], GBAObjAttributesCGetPriority(sprite->c) << 3,
1162	               (renderer->target1Obj || GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT) | (renderer->target2Obj * 2) | (blendEffect * 4),
1163	               blendEffect == BLEND_ALPHA ? renderer->blda : renderer->bldy, renderer->bldb);
1164	if (GBAObjAttributesAIsTransformed(sprite->a)) {
1165		struct GBAOAMMatrix mat;
1166		LOAD_16(mat.a, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].a);
1167		LOAD_16(mat.b, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].b);
1168		LOAD_16(mat.c, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].c);
1169		LOAD_16(mat.d, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].d);
1170
1171		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 });
1172	} else {
1173		glUniformMatrix2fv(uniforms[GBA_GL_OBJ_TRANSFORM], 1, GL_FALSE, (GLfloat[]) { 1.f, 0, 0, 1.f });
1174	}
1175	glUniform4i(uniforms[GBA_GL_OBJ_DIMS], width, height, totalWidth, totalHeight);
1176	glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 0, _vertices);
1177	glEnableVertexAttribArray(0);
1178	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1179	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1180	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1181}
1182
1183void GBAVideoGLRendererDrawBackgroundMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1184	int inY = y + background->y;
1185	int yBase = inY & 0xFF;
1186	if (background->size == 2) {
1187		yBase += inY & 0x100;
1188	} else if (background->size == 3) {
1189		yBase += (inY & 0x100) << 1;
1190	}
1191	const GLuint* uniforms = renderer->bgUniforms[background->multipalette ? 1 : 0];
1192	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1193	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1194	glScissor(0, y * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale);
1195	glUseProgram(renderer->bgProgram[background->multipalette ? 1 : 0]);
1196	glActiveTexture(GL_TEXTURE0);
1197	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1198	glActiveTexture(GL_TEXTURE0 + 1);
1199	glBindTexture(GL_TEXTURE_2D, renderer->paletteTex);
1200	glUniform2i(uniforms[GBA_GL_VS_LOC], 1, y);
1201	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1202	glUniform1i(uniforms[GBA_GL_BG_VRAM], 0);
1203	glUniform1i(uniforms[GBA_GL_BG_PALETTE], 1);
1204	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1205	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1206	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1207	glUniform2i(uniforms[GBA_GL_BG_OFFSET], background->x, yBase - y);
1208	glUniform4i(uniforms[GBA_GL_BG_INFLAGS], (background->priority << 3) + (background->index << 1) + 1,
1209		                                     background->target1 | (background->target2 * 2) | (renderer->blendEffect * 4),
1210		                                     renderer->blendEffect == BLEND_ALPHA ? renderer->blda : renderer->bldy, renderer->bldb);
1211	glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 0, _vertices);
1212	glEnableVertexAttribArray(0);
1213	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1214	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1215	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1216
1217	_compositeLayer(renderer, background->tex, background->flags, background->index, y);
1218}
1219
1220void GBAVideoGLRendererDrawBackgroundMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1221	const GLuint* uniforms = renderer->bgUniforms[background->overflow ? 2 : 3];
1222	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1223	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1224	glScissor(0, y * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale);
1225	glUseProgram(renderer->bgProgram[background->overflow ? 2 : 3]);
1226	glActiveTexture(GL_TEXTURE0);
1227	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1228	glActiveTexture(GL_TEXTURE0 + 1);
1229	glBindTexture(GL_TEXTURE_2D, renderer->paletteTex);
1230	glUniform2i(uniforms[GBA_GL_VS_LOC], 1, y);
1231	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1232	glUniform1i(uniforms[GBA_GL_BG_VRAM], 0);
1233	glUniform1i(uniforms[GBA_GL_BG_PALETTE], 1);
1234	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1235	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1236	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1237	glUniform4i(uniforms[GBA_GL_BG_INFLAGS], (background->priority << 3) + (background->index << 1) + 1,
1238		           background->target1 | (background->target2 * 2) | (renderer->blendEffect * 4),
1239		           renderer->blendEffect == BLEND_ALPHA ? renderer->blda : renderer->bldy, renderer->bldb);
1240	if (renderer->scale > 1) {
1241		glUniform2iv(uniforms[GBA_GL_BG_OFFSET], 4, (GLint[]) {
1242			background->affine[0].sx, background->affine[0].sy,
1243			background->affine[1].sx, background->affine[1].sy,
1244			background->affine[2].sx, background->affine[2].sy,
1245			background->affine[3].sx, background->affine[3].sy,
1246		});
1247		glUniform2iv(uniforms[GBA_GL_BG_TRANSFORM], 4, (GLint[]) {
1248			background->affine[0].dx, background->affine[0].dy,
1249			background->affine[1].dx, background->affine[1].dy,
1250			background->affine[2].dx, background->affine[2].dy,
1251			background->affine[3].dx, background->affine[3].dy,
1252		});
1253	} else {
1254		glUniform2iv(uniforms[GBA_GL_BG_OFFSET], 4, (GLint[]) {
1255			background->affine[0].sx, background->affine[0].sy,
1256			background->affine[0].sx, background->affine[0].sy,
1257			background->affine[0].sx, background->affine[0].sy,
1258			background->affine[0].sx, background->affine[0].sy,
1259		});
1260		glUniform2iv(uniforms[GBA_GL_BG_TRANSFORM], 4, (GLint[]) {
1261			background->affine[0].dx, background->affine[0].dy,
1262			background->affine[0].dx, background->affine[0].dy,
1263			background->affine[0].dx, background->affine[0].dy,
1264			background->affine[0].dx, background->affine[0].dy,
1265		});
1266	}
1267	glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 0, _vertices);
1268	glEnableVertexAttribArray(0);
1269	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1270	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1271	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1272
1273	_compositeLayer(renderer, background->tex, background->flags, background->index, y);
1274}
1275
1276static void _clearWindow(GBAWindowControl window, int start, int end, int y, int scale) {
1277	glScissor(start, y, end - start, scale);
1278	window = ~window & 0xFF;
1279	glClearColor((window & 0xF) / 32.f, (window >> 4) / 32.f, 0, 0);
1280	glClear(GL_COLOR_BUFFER_BIT);
1281}
1282
1283void GBAVideoGLRendererDrawWindow(struct GBAVideoGLRenderer* renderer, int y) {
1284	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_WINDOW]);
1285	if (!(renderer->dispcnt & 0xE000)) {
1286		_clearWindow(0xFF, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, y * renderer->scale, renderer->scale);
1287	} else {
1288		_clearWindow(renderer->winout, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, y * renderer->scale, renderer->scale);
1289		if (GBARegisterDISPCNTIsWin1Enable(renderer->dispcnt) && y >= renderer->winN[1].v.start && y < renderer->winN[1].v.end) {
1290			_clearWindow(renderer->winN[1].control, renderer->winN[1].h.start * renderer->scale, renderer->winN[1].h.end * renderer->scale, y * renderer->scale, renderer->scale);
1291		}
1292		if (GBARegisterDISPCNTIsWin0Enable(renderer->dispcnt) && y >= renderer->winN[0].v.start && y < renderer->winN[0].v.end) {
1293			_clearWindow(renderer->winN[0].control, renderer->winN[0].h.start * renderer->scale, renderer->winN[0].h.end * renderer->scale, y * renderer->scale, renderer->scale);
1294		}
1295	}
1296	glBindFramebuffer(GL_FRAMEBUFFER, 0);
1297}