aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/gl_renderer.c (42800B)


      1 #define GL_GLEXT_PROTOTYPES
      2 #include "gl_renderer.h"
      3 #ifdef __EMSCRIPTEN__
      4 #include <GLES3/gl3.h>
      5 #include <emscripten.h>
      6 #include <emscripten/html5.h>
      7 #include <stdatomic.h>
      8 static atomic_int capture_remaining;
      9 
     10 EMSCRIPTEN_KEEPALIVE void browser_capture_frames(int count)
     11 {
     12     /* Bound diagnostic readback memory, and allow an unfinished capture to stop. */
     13     atomic_store(&capture_remaining, count > 0 && count <= 120 ? count : 0);
     14 }
     15 #define SHADER_VERSION "#version 300 es\nprecision highp float;\nprecision highp int;\n"
     16 #else
     17 #include <SDL2/SDL_opengl.h>
     18 #include <SDL2/SDL_timer.h>
     19 #define SHADER_VERSION "#version 330 core\n"
     20 #endif
     21 #include <stddef.h>
     22 #include <stdio.h>
     23 #include <stdlib.h>
     24 #include <string.h>
     25 #include <assert.h>
     26 #include <zlib.h>
     27 
     28 static GLuint program, vertex_array, vertex_buffer, index_buffer;
     29 static GLuint transform_buffer;
     30 static GLint transform_enabled, color_bgra;
     31 static unsigned input_fvf, input_coordinates[2];
     32 static GLuint input_buffer;
     33 static unsigned input_offset;
     34 static GLuint samplers[2];
     35 static GLint texture_enabled[2], texture_alpha[2], texture_color_op[2], texture_alpha_op[2];
     36 static GLint texture_color_arg2[2], texture_alpha_arg2[2];
     37 static GLint texture_color_arg1[2], texture_alpha_arg1[2];
     38 static GLint texture_factor;
     39 static GLint fog_enabled, fog_color;
     40 static GLint alpha_function, alpha_reference;
     41 static int depth_enabled = 1, depth_write = 1;
     42 static uint32_t depth_function = 4;
     43 static uint32_t depth_bias;
     44 static uint32_t cull_mode = 1;
     45 /* Cache only state owned by this renderer; reset it for each GL context. */
     46 static struct {
     47     int transform_valid, transform_enabled;
     48     struct gl_vertex_transform transform;
     49     int texture_valid[2], texture_enabled[2];
     50     struct gl_texture_state texture[2];
     51     int factor_valid;
     52     uint32_t factor;
     53     int fog_valid, fog_enabled;
     54     uint32_t fog_color;
     55     int alpha_valid;
     56     uint32_t alpha_function, alpha_reference;
     57     int blend_valid, blend_enabled;
     58     uint32_t source_blend, destination_blend;
     59     int raster_valid, depth_test, depth_write;
     60     uint32_t cull, depth_function, depth_bias;
     61 } applied;
     62 struct gl_vertex_buffer {
     63     GLuint buffer;
     64     const void *vertices;
     65     unsigned size;
     66     unsigned uploaded_start, uploaded_end;
     67     struct gl_vertex_buffer *next;
     68 };
     69 static struct gl_vertex_buffer *vertex_buffers;
     70 struct gl_depth {
     71     unsigned width, height, references, bits;
     72     GLuint buffer;
     73     struct gl_depth *next;
     74 };
     75 static struct gl_depth *depths;
     76 struct gl_target {
     77     unsigned width, height;
     78     GLuint framebuffer, color;
     79     struct gl_depth *depth;
     80     unsigned char *saved_pixels;
     81     uLong saved_compressed_size;
     82     struct gl_target *mip, *parent;
     83     int mip_dirty;
     84     double last_used;
     85     struct gl_target *previous, *next;
     86 };
     87 static struct gl_target *targets;
     88 static double texture_frame_time, texture_last_sweep;
     89 static void make_resident(struct gl_target *target);
     90 static void make_renderable(struct gl_target *target);
     91 
     92 static void invalidate_mips(struct gl_target *target)
     93 {
     94     for (; target; target = target->parent) target->mip_dirty = 1;
     95 }
     96 
     97 void gl_target_set_mip(struct gl_target *target, struct gl_target *mip)
     98 {
     99     target->mip = mip;
    100     mip->parent = target;
    101     invalidate_mips(target);
    102 }
    103 
    104 static void check_graphics(const char *operation)
    105 {
    106     GLenum error = glGetError();
    107 #ifdef __EMSCRIPTEN__
    108     /* The loss event is delivered when the current Wasm call yields. */
    109     if (error && emscripten_is_webgl_context_lost(emscripten_webgl_get_current_context())) return;
    110 #endif
    111     if (error != GL_NO_ERROR) {
    112         fprintf(stderr, "OpenGL %s failed: %04x\n", operation, error);
    113         abort();
    114     }
    115 }
    116 
    117 static void packed_vertex_format(void)
    118 {
    119     glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(struct gl_vertex), (void *)offsetof(struct gl_vertex, position));
    120     glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(struct gl_vertex), (void *)offsetof(struct gl_vertex, color));
    121     glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(struct gl_vertex), (void *)offsetof(struct gl_vertex, uv));
    122     glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(struct gl_vertex), (void *)offsetof(struct gl_vertex, fog));
    123     glVertexAttribPointer(4, 2, GL_FLOAT, GL_FALSE, sizeof(struct gl_vertex), (void *)offsetof(struct gl_vertex, uv_second));
    124     glEnableVertexAttribArray(4);
    125     glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, sizeof(struct gl_vertex), (void *)offsetof(struct gl_vertex, specular));
    126     glEnableVertexAttribArray(5);
    127     glEnableVertexAttribArray(3);
    128     glEnableVertexAttribArray(0);
    129     glEnableVertexAttribArray(1);
    130     glEnableVertexAttribArray(2);
    131 }
    132 
    133 int gl_renderer_initialize(void)
    134 {
    135     if (program) return 1;
    136     memset(&applied, 0, sizeof(applied));
    137     const char *sources[] = {
    138         SHADER_VERSION
    139         "layout(location=0) in vec4 position;\n"
    140         "layout(location=1) in vec4 diffuse;\n"
    141         "layout(location=2) in vec2 texcoord;\n"
    142         "layout(location=3) in float fog;\n"
    143         "layout(location=4) in vec2 texcoord_second;\n"
    144         "layout(location=5) in vec3 specular; out vec3 highlight;\n"
    145         "out vec4 color; out vec2 uv, uv_second; out float fog_factor;\n"
    146         "uniform bool transform_enabled, color_bgra;\n"
    147         "struct VertexLight { vec4 vector, diffuse, ambient, attenuation; };\n"
    148         "layout(std140) uniform VertexTransform {\n"
    149         "    mat4 world_view, projection; mat3 normal_matrix;\n"
    150         "    vec4 viewport, material_diffuse, material_ambient, material_emissive;\n"
    151         "    vec4 ambient; VertexLight lights[8]; vec4 fog_range, flags;\n"
    152         "};\n"
    153         "void main() {\n"
    154         "    vec4 projected = position;\n"
    155         "    vec4 vertex_diffuse = color_bgra ? diffuse.bgra : diffuse;\n"
    156         "    color = vertex_diffuse; uv = texcoord; uv_second = texcoord_second;\n"
    157         "    fog_factor = fog; highlight = specular;\n"
    158         "    if (transform_enabled) {\n"
    159         "        vec4 camera = world_view * position;\n"
    160         "        projected = projection * camera;\n"
    161         "        projected.xy = projected.xy * viewport.xy + projected.w * viewport.zw;\n"
    162         "        vec3 normal = normal_matrix * specular;\n"
    163         "        if (flags.y != 0.0) {\n"
    164         "            float length = sqrt(dot(normal, normal));\n"
    165         "            if (length != 0.0) normal /= length;\n"
    166         "        }\n"
    167         "        if (flags.x != 0.0) {\n"
    168         "            vec4 lit_diffuse = flags.z != 0.0 ? vertex_diffuse : material_diffuse;\n"
    169         "            vec3 emissive = flags.w != 0.0 ? vertex_diffuse.rgb : material_emissive.rgb;\n"
    170         "            color = vec4(emissive + material_ambient.rgb * ambient.rgb, lit_diffuse.a);\n"
    171         "            for (int i = 0; i < 8; ++i) {\n"
    172         "                if (lights[i].vector.w == 0.0) break;\n"
    173         "                vec3 direction = lights[i].vector.xyz; float attenuation = 1.0;\n"
    174         "                if (lights[i].vector.w == 1.0) {\n"
    175         "                    direction -= camera.xyz;\n"
    176         "                    float distance = sqrt(dot(direction, direction));\n"
    177         "                    if (distance > lights[i].attenuation.w) continue;\n"
    178         "                    if (distance != 0.0) direction /= distance;\n"
    179         "                    vec3 a = lights[i].attenuation.xyz;\n"
    180         "                    attenuation = 1.0 / (a.x + distance * a.y + distance * distance * a.z);\n"
    181         "                }\n"
    182         "                float intensity = max(0.0, dot(normal, direction));\n"
    183         "                color.rgb += attenuation * (lit_diffuse.rgb * lights[i].diffuse.rgb * intensity + material_ambient.rgb * lights[i].ambient.rgb);\n"
    184         "            }\n"
    185         "            color = clamp(color, 0.0, 1.0);\n"
    186         "        }\n"
    187         "        highlight = vec3(0.0);\n"
    188         "        fog_factor = fog_range.z != 0.0 ? clamp((fog_range.y - abs(camera.z)) / (fog_range.y - fog_range.x), 0.0, 1.0) : 0.0;\n"
    189         "    }\n"
    190         "    gl_Position = vec4(projected.x, -projected.y, 2.0 * projected.z - projected.w, projected.w);\n"
    191         "}\n",
    192         SHADER_VERSION
    193         "in vec4 color; in vec2 uv, uv_second; in float fog_factor; out vec4 pixel;\n"
    194         "in vec3 highlight;\n"
    195         "uniform bool fog_enabled; uniform vec3 fog_color;\n"
    196         "uniform sampler2D image0, image1;\n"
    197         "uniform bool textured[2], has_alpha[2]; uniform int color_op[2], alpha_op[2], color_arg2[2], alpha_arg2[2];\n"
    198         "uniform int color_arg1[2], alpha_arg1[2];\n"
    199         "uniform vec4 texture_factor;\n"
    200         "uniform int alpha_function; uniform float alpha_reference;\n"
    201         "vec4 argument(int a, vec4 t) { int source=a&15;"
    202         "vec4 value=source==0 ? color : source==1 ? pixel : source==2 ? t : texture_factor;"
    203         "return (a&32)!=0 ? vec4(value.a) : value; }\n"
    204         "void combine(int s, vec4 t) { if(!has_alpha[s]) t.a=1.0;"
    205         "vec3 c1=argument(color_arg1[s],t).rgb, c2=argument(color_arg2[s],t).rgb;"
    206         "float a1=argument(alpha_arg1[s],t).a, a2=argument(alpha_arg2[s],t).a;"
    207         "pixel.rgb=color_op[s]==4 ? c1*c2 : color_op[s]==7 ? min(vec3(1.0),c1+c2) : c1;"
    208         "if(color_op[s]==6) pixel.rgb=min(vec3(1.0),4.0*c1*c2);"
    209         "if(color_op[s]==20) pixel.rgb=min(vec3(1.0),c1+(1.0-argument(color_arg1[s],t).a)*c2);"
    210         "if(alpha_op[s]!=1) pixel.a=alpha_op[s]==3 ? a2 : alpha_op[s]==4 ? a1*a2 : alpha_op[s]==6 ? min(1.0,4.0*a1*a2) : a1; }\n"
    211         "void main() { pixel=color; if(textured[0]) { combine(0,texture(image0,uv));"
    212         "if(textured[1]) combine(1,texture(image1,uv_second)); }"
    213         "pixel.rgb=min(vec3(1.0),pixel.rgb+highlight);"
    214         "if(fog_enabled) pixel.rgb=mix(fog_color,pixel.rgb,clamp(fog_factor,0.0,1.0));"
    215         /* Compare quantized eight-bit alpha; exact halfway values round down. */
    216         "float alpha=ceil(clamp(pixel.a,0.0,1.0)*255.0-0.5);"
    217         "bool pass=alpha_function==1 ? false : alpha_function==2 ? alpha<alpha_reference :"
    218         "alpha_function==3 ? alpha==alpha_reference : alpha_function==4 ? alpha<=alpha_reference :"
    219         "alpha_function==5 ? alpha>alpha_reference : alpha_function==6 ? alpha!=alpha_reference :"
    220         "alpha_function==7 ? alpha>=alpha_reference : true; if(!pass) discard; }\n"
    221     };
    222     program = glCreateProgram();
    223     for (unsigned i = 0; i < 2; ++i) {
    224         GLuint shader = glCreateShader(i ? GL_FRAGMENT_SHADER : GL_VERTEX_SHADER);
    225         glShaderSource(shader, 1, &sources[i], NULL);
    226         glCompileShader(shader);
    227         GLint success;
    228         glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
    229         if (!success) {
    230             char log[2048];
    231             glGetShaderInfoLog(shader, sizeof(log), NULL, log);
    232             fprintf(stderr, "Native shader compilation failed: %s\n", log);
    233             glDeleteShader(shader);
    234             gl_renderer_shutdown();
    235             return 0;
    236         }
    237         glAttachShader(program, shader);
    238         glDeleteShader(shader);
    239     }
    240     glLinkProgram(program);
    241     GLint success;
    242     glGetProgramiv(program, GL_LINK_STATUS, &success);
    243     if (!success) {
    244         char log[2048];
    245         glGetProgramInfoLog(program, sizeof(log), NULL, log);
    246         fprintf(stderr, "Native shader link failed: %s\n", log);
    247         gl_renderer_shutdown();
    248         return 0;
    249     }
    250 
    251     for (unsigned i = 0; i < 2; ++i) {
    252         texture_enabled[i] = glGetUniformLocation(program, i ? "textured[1]" : "textured[0]");
    253         texture_alpha[i] = glGetUniformLocation(program, i ? "has_alpha[1]" : "has_alpha[0]");
    254         texture_color_op[i] = glGetUniformLocation(program, i ? "color_op[1]" : "color_op[0]");
    255         texture_alpha_op[i] = glGetUniformLocation(program, i ? "alpha_op[1]" : "alpha_op[0]");
    256         texture_color_arg2[i] = glGetUniformLocation(program, i ? "color_arg2[1]" : "color_arg2[0]");
    257         texture_alpha_arg2[i] = glGetUniformLocation(program, i ? "alpha_arg2[1]" : "alpha_arg2[0]");
    258         texture_color_arg1[i] = glGetUniformLocation(program, i ? "color_arg1[1]" : "color_arg1[0]");
    259         texture_alpha_arg1[i] = glGetUniformLocation(program, i ? "alpha_arg1[1]" : "alpha_arg1[0]");
    260     }
    261     fog_enabled = glGetUniformLocation(program, "fog_enabled");
    262     fog_color = glGetUniformLocation(program, "fog_color");
    263     texture_factor = glGetUniformLocation(program, "texture_factor");
    264     alpha_function = glGetUniformLocation(program, "alpha_function");
    265     alpha_reference = glGetUniformLocation(program, "alpha_reference");
    266     glUseProgram(program);
    267     glUniform1i(glGetUniformLocation(program, "image0"), 0);
    268     glUniform1i(glGetUniformLocation(program, "image1"), 1);
    269     color_bgra = glGetUniformLocation(program, "color_bgra");
    270     input_fvf = 0;
    271     transform_enabled = glGetUniformLocation(program, "transform_enabled");
    272     glUniformBlockBinding(program, glGetUniformBlockIndex(program, "VertexTransform"), 0);
    273     glGenBuffers(1, &transform_buffer);
    274     glBindBuffer(GL_UNIFORM_BUFFER, transform_buffer);
    275     glBufferData(GL_UNIFORM_BUFFER, sizeof(struct gl_vertex_transform), NULL, GL_STREAM_DRAW);
    276     glBindBufferBase(GL_UNIFORM_BUFFER, 0, transform_buffer);
    277     glGenSamplers(2, samplers);
    278     for (unsigned i = 0; i < 2; ++i) glBindSampler(i, samplers[i]);
    279 
    280     /* This context owns one program, vertex array and streamed buffer pair.
    281      * Keep them bound for all draws and uniform updates. */
    282     glGenVertexArrays(1, &vertex_array);
    283     glGenBuffers(1, &vertex_buffer);
    284     glGenBuffers(1, &index_buffer);
    285     glBindVertexArray(vertex_array);
    286     glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    287     input_buffer = vertex_buffer;
    288     input_offset = 0;
    289     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
    290     packed_vertex_format();
    291     check_graphics("renderer initialization");
    292     return 1;
    293 }
    294 
    295 void gl_renderer_set_vertex_transform(const struct gl_vertex_transform *state)
    296 {
    297     if (!applied.transform_valid || applied.transform_enabled != (state != NULL))
    298         glUniform1i(transform_enabled, state != NULL);
    299     if (state && (!applied.transform_valid || !applied.transform_enabled ||
    300                   memcmp(&applied.transform, state, sizeof(*state)))) {
    301         glBufferData(GL_UNIFORM_BUFFER, sizeof(*state), state, GL_STREAM_DRAW);
    302         applied.transform = *state;
    303     }
    304     applied.transform_valid = 1;
    305     applied.transform_enabled = state != NULL;
    306 }
    307 
    308 void gl_renderer_shutdown(void)
    309 {
    310     for (struct gl_vertex_buffer *buffer = vertex_buffers; buffer; buffer = buffer->next) {
    311         glDeleteBuffers(1, &buffer->buffer);
    312         buffer->buffer = 0;
    313     }
    314     glDeleteBuffers(1, &transform_buffer);
    315     glDeleteSamplers(2, samplers);
    316     glDeleteBuffers(1, &index_buffer);
    317     glDeleteBuffers(1, &vertex_buffer);
    318     glDeleteVertexArrays(1, &vertex_array);
    319     glDeleteProgram(program);
    320     transform_buffer = index_buffer = vertex_buffer = vertex_array = program = 0;
    321 }
    322 
    323 struct gl_vertex_buffer *gl_vertex_buffer_create(const void *vertices, unsigned size)
    324 {
    325     struct gl_vertex_buffer *buffer = calloc(1, sizeof(*buffer));
    326     if (!buffer) abort();
    327     buffer->vertices = vertices;
    328     buffer->size = size;
    329     buffer->next = vertex_buffers;
    330     vertex_buffers = buffer;
    331     return buffer;
    332 }
    333 
    334 void gl_vertex_buffer_invalidate(struct gl_vertex_buffer *buffer)
    335 {
    336     buffer->uploaded_end = 0;
    337 }
    338 
    339 void gl_vertex_buffer_destroy(struct gl_vertex_buffer *buffer)
    340 {
    341     struct gl_vertex_buffer **entry = &vertex_buffers;
    342     while (*entry != buffer) entry = &(*entry)->next;
    343     *entry = buffer->next;
    344     if (input_buffer == buffer->buffer) input_buffer = 0;
    345     glDeleteBuffers(1, &buffer->buffer);
    346     free(buffer);
    347 }
    348 
    349 void gl_renderer_restore(void)
    350 {
    351     /* Release stale GL names while retaining guest surfaces and CPU textures. */
    352     gl_renderer_shutdown();
    353     for (struct gl_target *target = targets; target; target = target->next) {
    354         glDeleteFramebuffers(1, &target->framebuffer);
    355         glDeleteTextures(1, &target->color);
    356         target->framebuffer = target->color = 0;
    357         target->mip_dirty = 1;
    358     }
    359 
    360     /* Depth surfaces can be shared or temporarily detached from draw targets. */
    361     for (struct gl_depth *depth = depths; depth; depth = depth->next) {
    362         glDeleteRenderbuffers(1, &depth->buffer);
    363     }
    364 #ifdef __EMSCRIPTEN__
    365     /* Deleting objects from the lost context can report INVALID_OPERATION. */
    366     while (glGetError() != GL_NO_ERROR) {}
    367 #endif
    368     for (struct gl_depth *depth = depths; depth; depth = depth->next) {
    369         glGenRenderbuffers(1, &depth->buffer);
    370         glBindRenderbuffer(GL_RENDERBUFFER, depth->buffer);
    371         glRenderbufferStorage(GL_RENDERBUFFER,
    372             depth->bits == 16 ? GL_DEPTH_COMPONENT16 : GL_DEPTH_COMPONENT24, depth->width, depth->height);
    373     }
    374     if (!gl_renderer_initialize()) abort();
    375 }
    376 
    377 struct gl_depth *gl_depth_create(unsigned width, unsigned height, unsigned bits)
    378 {
    379     assert(bits == 16 || bits == 24);
    380     struct gl_depth *depth = calloc(1, sizeof(*depth));
    381     if (!depth) return NULL;
    382     depth->width = width;
    383     depth->height = height;
    384     depth->references = 1;
    385     depth->bits = bits;
    386     depth->next = depths;
    387     depths = depth;
    388     glGenRenderbuffers(1, &depth->buffer);
    389     glBindRenderbuffer(GL_RENDERBUFFER, depth->buffer);
    390     glRenderbufferStorage(GL_RENDERBUFFER, bits == 16 ? GL_DEPTH_COMPONENT16 : GL_DEPTH_COMPONENT24, width, height);
    391     check_graphics("depth allocation");
    392     return depth;
    393 }
    394 
    395 void gl_depth_destroy(struct gl_depth *depth)
    396 {
    397     if (--depth->references) return;
    398     struct gl_depth **entry = &depths;
    399     while (*entry != depth) entry = &(*entry)->next;
    400     *entry = depth->next;
    401     glDeleteRenderbuffers(1, &depth->buffer);
    402     free(depth);
    403 }
    404 
    405 void gl_target_set_depth(struct gl_target *target, struct gl_depth *depth)
    406 {
    407     make_renderable(target);
    408     assert(!depth || (depth->width == target->width && depth->height == target->height));
    409     if (depth) ++depth->references;
    410     if (target->depth) gl_depth_destroy(target->depth);
    411     target->depth = depth;
    412     glBindFramebuffer(GL_FRAMEBUFFER, target->framebuffer);
    413     glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth ? depth->buffer : 0);
    414 #ifndef __EMSCRIPTEN__
    415     assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
    416 #endif
    417     glBindFramebuffer(GL_FRAMEBUFFER, 0);
    418     check_graphics("depth attachment");
    419 }
    420 
    421 /* Raw saved pixels are borrowed; compressed pixels need a temporary buffer. */
    422 static unsigned char *decode_pixels(struct gl_target *target)
    423 {
    424     if (!target->saved_compressed_size) return target->saved_pixels;
    425     uLongf size = (size_t)target->width * target->height * 4;
    426     unsigned char *pixels = malloc(size);
    427     if (!pixels || uncompress(pixels, &size, target->saved_pixels,
    428             target->saved_compressed_size) != Z_OK ||
    429             size != (size_t)target->width * target->height * 4) abort();
    430     return pixels;
    431 }
    432 
    433 static void save_pixels(struct gl_target *target, unsigned char *pixels)
    434 {
    435     /* Small mip tails stay raw; compress larger inactive images losslessly. */
    436     uLong size = (size_t)target->width * target->height * 4;
    437     if (size > 64) {
    438         uLongf compressed_size = compressBound(size);
    439         unsigned char *compressed = malloc(compressed_size);
    440         if (!compressed || compress2(compressed, &compressed_size, pixels, size, Z_BEST_SPEED) != Z_OK) abort();
    441         if (compressed_size < size) {
    442             free(pixels);
    443             pixels = realloc(compressed, compressed_size);
    444             if (!pixels) abort();
    445             target->saved_compressed_size = compressed_size;
    446         } else free(compressed);
    447     }
    448     target->saved_pixels = pixels;
    449 }
    450 
    451 static void discard_saved_pixels(struct gl_target *target)
    452 {
    453     free(target->saved_pixels);
    454     target->saved_pixels = NULL;
    455     target->saved_compressed_size = 0;
    456 }
    457 
    458 static void allocate_texture(struct gl_target *target)
    459 {
    460     invalidate_mips(target);
    461     glGenTextures(1, &target->color);
    462     glBindTexture(GL_TEXTURE_2D, target->color);
    463     unsigned char *pixels = decode_pixels(target);
    464     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, target->width, target->height, 0,
    465                  GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    466     if (pixels != target->saved_pixels) free(pixels);
    467     if (target->depth) discard_saved_pixels(target);
    468     target->last_used = texture_frame_time;
    469     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    470     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    471     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
    472 }
    473 
    474 static void make_resident(struct gl_target *target)
    475 {
    476     if (!target->color) allocate_texture(target);
    477 }
    478 
    479 static void make_renderable(struct gl_target *target)
    480 {
    481     /* Restoring a draw destination must preserve the currently sampled image. */
    482     if (!target->color) {
    483         GLint texture;
    484         glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
    485         make_resident(target);
    486         glBindTexture(GL_TEXTURE_2D, texture);
    487     }
    488     if (target->framebuffer) return;
    489     /* Sampled textures need no framebuffer or synchronous completeness query. */
    490     glGenFramebuffers(1, &target->framebuffer);
    491     glBindFramebuffer(GL_FRAMEBUFFER, target->framebuffer);
    492     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target->color, 0);
    493     glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER,
    494                               target->depth ? target->depth->buffer : 0);
    495     /* RGBA8 attachments have a fixed layout. Browser completeness queries would
    496      * synchronize each newly visible mip; explicit readback checks GL errors. */
    497 #ifndef __EMSCRIPTEN__
    498     GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    499     if (status != GL_FRAMEBUFFER_COMPLETE) {
    500         fprintf(stderr, "Native framebuffer creation failed: %04x\n", status);
    501         abort();
    502     }
    503 #endif
    504     glBindFramebuffer(GL_FRAMEBUFFER, 0);
    505 }
    506 
    507 struct gl_target *gl_target_create(unsigned width, unsigned height, int with_depth)
    508 {
    509     struct gl_target *target = calloc(1, sizeof(*target));
    510     if (!target) return NULL;
    511     target->next = targets;
    512     if (targets) targets->previous = target;
    513     targets = target;
    514     target->width = width;
    515     target->height = height;
    516     if (with_depth) target->depth = gl_depth_create(width, height, 24);
    517     if (with_depth && !target->depth) { gl_target_destroy(target); return NULL; }
    518     return target;
    519 }
    520 
    521 void gl_target_destroy(struct gl_target *target)
    522 {
    523     if (target->previous) target->previous->next = target->next;
    524     else targets = target->next;
    525     if (target->next) target->next->previous = target->previous;
    526     if (target->mip) target->mip->parent = NULL;
    527     if (target->parent) {
    528         target->parent->mip = NULL;
    529         invalidate_mips(target->parent);
    530     }
    531     glDeleteFramebuffers(1, &target->framebuffer);
    532     if (target->depth) gl_depth_destroy(target->depth);
    533     glDeleteTextures(1, &target->color);
    534     free(target->saved_pixels);
    535     free(target);
    536 }
    537 
    538 void gl_target_evict(struct gl_target *target, const unsigned char *rgba)
    539 {
    540     assert(!target->depth);
    541     if (!target->color && !rgba) return;
    542     if (rgba || !target->saved_pixels) {
    543         unsigned char *pixels = malloc((size_t)target->width * target->height * 4);
    544         if (!pixels) abort();
    545         if (rgba) memcpy(pixels, rgba, (size_t)target->width * target->height * 4);
    546         else gl_target_read(target, pixels);
    547         discard_saved_pixels(target);
    548         save_pixels(target, pixels);
    549     }
    550     glDeleteFramebuffers(1, &target->framebuffer);
    551     glDeleteTextures(1, &target->color);
    552     target->framebuffer = target->color = 0;
    553     invalidate_mips(target);
    554 }
    555 
    556 void gl_target_clear(struct gl_target *target, uint32_t argb, float depth)
    557 {
    558     const int32_t rectangle[] = {0, 0, target->width, target->height};
    559     gl_target_clear_rect(target, 3, argb, depth, rectangle);
    560 }
    561 
    562 void gl_target_clear_rect(struct gl_target *target, uint32_t flags, uint32_t argb, float depth, const int32_t rectangle[4])
    563 {
    564     invalidate_mips(target);
    565     make_renderable(target);
    566     int32_t left = rectangle[0] < 0 ? 0 : rectangle[0], top = rectangle[1] < 0 ? 0 : rectangle[1];
    567     int32_t right = rectangle[2] > (int32_t)target->width ? (int32_t)target->width : rectangle[2];
    568     int32_t bottom = rectangle[3] > (int32_t)target->height ? (int32_t)target->height : rectangle[3];
    569     if (left >= right || top >= bottom) return;
    570     discard_saved_pixels(target);
    571     glBindFramebuffer(GL_FRAMEBUFFER, target->framebuffer);
    572     glEnable(GL_SCISSOR_TEST);
    573     glScissor(left, top, right - left, bottom - top);
    574     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    575     glDepthMask(GL_TRUE);
    576     applied.depth_write = 1;
    577     glClearColor(((argb >> 16) & 255) / 255.0f, ((argb >> 8) & 255) / 255.0f,
    578                  (argb & 255) / 255.0f, (argb >> 24) / 255.0f);
    579 #ifdef __EMSCRIPTEN__
    580     glClearDepthf(depth);
    581 #else
    582     glClearDepth(depth);
    583 #endif
    584     glClear((flags & 1 ? GL_COLOR_BUFFER_BIT : 0) | (flags & 2 ? GL_DEPTH_BUFFER_BIT : 0));
    585     glDisable(GL_SCISSOR_TEST);
    586     glBindFramebuffer(GL_FRAMEBUFFER, 0);
    587 }
    588 
    589 static void draw_data(struct gl_target *target, unsigned primitive,
    590                     const uint16_t *indices, unsigned index_count, const int32_t clip[4])
    591 {
    592     invalidate_mips(target);
    593     make_renderable(target);
    594     discard_saved_pixels(target);
    595     glBindFramebuffer(GL_FRAMEBUFFER, target->framebuffer);
    596     glViewport(0, 0, target->width, target->height);
    597     glEnable(GL_SCISSOR_TEST);
    598     glScissor(clip[0], clip[1], clip[2], clip[3]);
    599     if (!applied.raster_valid || applied.cull != cull_mode) {
    600         if (cull_mode == 1) glDisable(GL_CULL_FACE);
    601         else {
    602             glEnable(GL_CULL_FACE);
    603             /* Guest clockwise winding becomes GL counterclockwise after the Y mapping. */
    604             glFrontFace(GL_CCW);
    605             glCullFace(cull_mode == 2 ? GL_FRONT : GL_BACK);
    606         }
    607     }
    608     int depth_test = depth_enabled && target->depth;
    609     if (!applied.raster_valid || applied.depth_test != depth_test) {
    610         if (depth_test) glEnable(GL_DEPTH_TEST);
    611         else glDisable(GL_DEPTH_TEST);
    612     }
    613     if (!applied.raster_valid || applied.depth_function != depth_function)
    614         glDepthFunc(GL_NEVER + depth_function - 1);
    615     if (!applied.raster_valid || applied.depth_write != depth_write)
    616         glDepthMask(depth_write ? GL_TRUE : GL_FALSE);
    617     if (!applied.raster_valid || applied.depth_bias != depth_bias) {
    618         if (depth_bias) {
    619             glEnable(GL_POLYGON_OFFSET_FILL);
    620             /* D3D7 bias scale, checked on flat/sloped 16/24-bit depth surfaces. */
    621             glPolygonOffset(-(float)depth_bias * .25f, -(float)depth_bias * .5f);
    622         } else glDisable(GL_POLYGON_OFFSET_FILL);
    623     }
    624     applied.raster_valid = 1;
    625     applied.cull = cull_mode;
    626     applied.depth_test = depth_test;
    627     applied.depth_function = depth_function;
    628     applied.depth_write = depth_write;
    629     applied.depth_bias = depth_bias;
    630     glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    631     glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_count * sizeof(*indices), indices, GL_STREAM_DRAW);
    632     glDrawElements(primitive == 2 ? GL_LINES : GL_TRIANGLES, index_count, GL_UNSIGNED_SHORT, NULL);
    633     glDisable(GL_SCISSOR_TEST);
    634     /* Leave the draw target bound; other framebuffer operations bind their own. */
    635     /* Check errors at presentation/readback without synchronizing every draw. */
    636 }
    637 
    638 void gl_target_draw(struct gl_target *target, unsigned primitive, const struct gl_vertex *vertices,
    639     unsigned vertex_count, const uint16_t *indices, unsigned index_count, const int32_t clip[4])
    640 {
    641     if (input_buffer != vertex_buffer) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    642     if (input_fvf || input_buffer != vertex_buffer) {
    643         packed_vertex_format();
    644         glUniform1i(color_bgra, 0);
    645         input_fvf = 0;
    646     }
    647     input_buffer = vertex_buffer;
    648     input_offset = 0;
    649     glBufferData(GL_ARRAY_BUFFER, vertex_count * sizeof(*vertices), vertices, GL_STREAM_DRAW);
    650     draw_data(target, primitive, indices, index_count, clip);
    651 }
    652 
    653 void gl_target_draw_fvf(struct gl_target *target, unsigned primitive, const void *vertices,
    654     unsigned fvf, const unsigned coordinates[2], const float color[4], unsigned vertex_count,
    655     const uint16_t *indices, unsigned index_count, const int32_t clip[4],
    656     struct gl_vertex_buffer *buffer, unsigned offset)
    657 {
    658     unsigned textures = (fvf >> 8) & 15;
    659     unsigned uv_offset = 12 + (fvf & 0x10 ? 12 : 0) + (fvf & 0x40 ? 4 : 0);
    660     unsigned stride = uv_offset + textures * 8;
    661     GLuint name = vertex_buffer;
    662     if (buffer) {
    663         if (!buffer->buffer) {
    664             glGenBuffers(1, &buffer->buffer);
    665             buffer->uploaded_end = 0;
    666         }
    667         name = buffer->buffer;
    668     }
    669     if (input_buffer != name) glBindBuffer(GL_ARRAY_BUFFER, name);
    670     if (!buffer) glBufferData(GL_ARRAY_BUFFER, vertex_count * stride, vertices, GL_STREAM_DRAW);
    671     else {
    672         unsigned end = offset + vertex_count * stride;
    673         /* Orphan dirty storage so edits do not wait for an earlier GPU draw. */
    674         if (!buffer->uploaded_end) {
    675             glBufferData(GL_ARRAY_BUFFER, buffer->size, NULL, GL_STATIC_DRAW);
    676             buffer->uploaded_start = buffer->uploaded_end = offset;
    677         }
    678         /* Track a contiguous range without copying gaps between disjoint draws. */
    679         if (end < buffer->uploaded_start || offset > buffer->uploaded_end)
    680             buffer->uploaded_start = buffer->uploaded_end = offset;
    681         if (offset < buffer->uploaded_start) {
    682             glBufferSubData(GL_ARRAY_BUFFER, offset, buffer->uploaded_start - offset,
    683                             (const unsigned char *)buffer->vertices + offset);
    684             buffer->uploaded_start = offset;
    685         }
    686         if (end > buffer->uploaded_end) {
    687             glBufferSubData(GL_ARRAY_BUFFER, buffer->uploaded_end, end - buffer->uploaded_end,
    688                             (const unsigned char *)buffer->vertices + buffer->uploaded_end);
    689             buffer->uploaded_end = end;
    690         }
    691     }
    692     if (input_fvf != fvf || input_coordinates[0] != coordinates[0] || input_coordinates[1] != coordinates[1] ||
    693         input_buffer != name || input_offset != offset) {
    694         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (void *)(uintptr_t)offset);
    695         if (fvf & 0x10) {
    696             glEnableVertexAttribArray(5);
    697             glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, stride, (void *)(uintptr_t)(offset + 12));
    698         } else {
    699             glDisableVertexAttribArray(5);
    700             glVertexAttrib3f(5, 0, 0, 0);
    701         }
    702         if (fvf & 0x40) {
    703             glEnableVertexAttribArray(1);
    704             glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void *)(uintptr_t)(offset + uv_offset - 4));
    705         } else glDisableVertexAttribArray(1);
    706         for (unsigned stage = 0; stage < 2; ++stage) {
    707             unsigned attribute = stage ? 4 : 2;
    708             if (coordinates[stage] < textures) {
    709                 glEnableVertexAttribArray(attribute);
    710                 glVertexAttribPointer(attribute, 2, GL_FLOAT, GL_FALSE, stride,
    711                     (void *)(uintptr_t)(offset + uv_offset + coordinates[stage] * 8));
    712             } else {
    713                 glDisableVertexAttribArray(attribute);
    714                 glVertexAttrib2f(attribute, 0, 0);
    715             }
    716         }
    717         glDisableVertexAttribArray(3);
    718         glVertexAttrib1f(3, 0);
    719         glUniform1i(color_bgra, (fvf & 0x40) != 0);
    720         input_fvf = fvf;
    721         memcpy(input_coordinates, coordinates, sizeof(input_coordinates));
    722     }
    723     input_buffer = name;
    724     input_offset = offset;
    725     if (!(fvf & 0x40)) glVertexAttrib4fv(1, color);
    726     draw_data(target, primitive, indices, index_count, clip);
    727 }
    728 
    729 void gl_target_read(struct gl_target *target, unsigned char *rgba)
    730 {
    731     if (target->saved_pixels) {
    732         unsigned char *pixels = decode_pixels(target);
    733         memcpy(rgba, pixels, (size_t)target->width * target->height * 4);
    734         if (pixels != target->saved_pixels) free(pixels);
    735         return;
    736     }
    737     make_renderable(target);
    738     glBindFramebuffer(GL_FRAMEBUFFER, target->framebuffer);
    739     glReadPixels(0, 0, target->width, target->height, GL_RGBA, GL_UNSIGNED_BYTE, rgba);
    740     glBindFramebuffer(GL_FRAMEBUFFER, 0);
    741     check_graphics("rendering and target readback");
    742 
    743     /* The shader puts the logical top row at GL row zero. This also maps GL's
    744      * bottom-left edge inclusion to Direct3D's top-left rasterization rule. */
    745 }
    746 
    747 void gl_target_write(struct gl_target *target, const unsigned char *rgba)
    748 {
    749     invalidate_mips(target);
    750     /* Retain compressed contents for GPU eviction without readback. */
    751     if (!target->color || !target->depth) {
    752         size_t size = (size_t)target->width * target->height * 4;
    753         unsigned char *pixels = malloc(size);
    754         if (!pixels) abort();
    755         memcpy(pixels, rgba, size);
    756         discard_saved_pixels(target);
    757         save_pixels(target, pixels);
    758     }
    759     if (!target->color) return;
    760     glBindTexture(GL_TEXTURE_2D, target->color);
    761     glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, target->width, target->height,
    762                     GL_RGBA, GL_UNSIGNED_BYTE, rgba);
    763 }
    764 
    765 void gl_target_blit(struct gl_target *source, struct gl_target *target, const int32_t source_rect[4], const int32_t target_rect[4])
    766 {
    767     invalidate_mips(target);
    768     make_resident(source);
    769     make_resident(target);
    770     make_renderable(source);
    771     make_renderable(target);
    772     discard_saved_pixels(target);
    773     source->last_used = target->last_used = texture_frame_time;
    774     glBindFramebuffer(GL_READ_FRAMEBUFFER, source->framebuffer);
    775     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target->framebuffer);
    776     glDisable(GL_SCISSOR_TEST);
    777     glBlitFramebuffer(source_rect[0], source_rect[1], source_rect[2], source_rect[3],
    778                       target_rect[0], target_rect[1], target_rect[2], target_rect[3], GL_COLOR_BUFFER_BIT, GL_NEAREST);
    779     glBindFramebuffer(GL_FRAMEBUFFER, 0);
    780 }
    781 
    782 void gl_target_present(struct gl_target *target, const int32_t rectangle[4], int width, int height)
    783 {
    784     target->last_used = texture_frame_time;
    785     make_renderable(target);
    786     glBindFramebuffer(GL_READ_FRAMEBUFFER, target->framebuffer);
    787     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
    788     glDisable(GL_SCISSOR_TEST);
    789     /* Guest rows run top-down; the native window framebuffer runs bottom-up. */
    790     glBlitFramebuffer(rectangle[0], rectangle[1], rectangle[2], rectangle[3],
    791                       0, height, width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
    792     glBindFramebuffer(GL_FRAMEBUFFER, 0);
    793 #ifdef __EMSCRIPTEN__
    794     /* Capture each actual presentation on the GL worker, before the browser
    795      * can discard its default framebuffer. Readback is opt-in and synchronous. */
    796     int remaining = atomic_load(&capture_remaining);
    797     if (remaining > 0) {
    798         unsigned char *pixels = malloc((size_t)width * height * 4);
    799         assert(pixels);
    800         glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    801         check_graphics("frame capture");
    802         MAIN_THREAD_EM_ASM({
    803             Module.captureFrame(HEAPU8.slice($0, $0 + $1 * $2 * 4), $1, $2, $3);
    804         }, pixels, width, height, EM_ASM_DOUBLE({ return performance.timeOrigin + performance.now(); }));
    805         free(pixels);
    806         /* A stop request from the UI must not be overwritten by this frame. */
    807         atomic_compare_exchange_strong(&capture_remaining, &remaining, remaining - 1);
    808     }
    809 #else
    810     check_graphics("frame rendering and presentation");
    811 #endif
    812     /* Release inactive sampled textures from their retained CPU contents. */
    813     if (texture_frame_time - texture_last_sweep >= 1000) {
    814         for (struct gl_target *image = targets; image; image = image->next)
    815             if (!image->depth && image->color && image->saved_pixels &&
    816                 texture_frame_time - image->last_used > 3000) gl_target_evict(image, NULL);
    817         texture_last_sweep = texture_frame_time;
    818     }
    819 #ifdef __EMSCRIPTEN__
    820     texture_frame_time = emscripten_get_now();
    821 #else
    822     texture_frame_time = SDL_GetTicks64();
    823 #endif
    824 }
    825 
    826 void gl_renderer_set_texture(unsigned stage, const struct gl_texture_state *state)
    827 {
    828     assert(stage < 2);
    829     int changed = !applied.texture_valid[stage] || !applied.texture_enabled[stage];
    830     if (!applied.texture_valid[stage] || applied.texture_enabled[stage] != (state != NULL))
    831         glUniform1i(texture_enabled[stage], state != NULL);
    832     glActiveTexture(GL_TEXTURE0 + stage);
    833     if (state && state->image) {
    834         int sampler_changed = changed || !applied.texture[stage].image;
    835         state->image->last_used = texture_frame_time;
    836         make_resident(state->image);
    837         if (state->image->mip_dirty) {
    838             /* Sublevels keep independent storage for edits and framebuffer readback. */
    839             unsigned level = 0;
    840             for (struct gl_target *mip = state->image->mip; mip; mip = mip->mip) {
    841                 if (!mip->color) {
    842                     /* Upload a copy without allocating another GPU texture. */
    843                     unsigned char *pixels = decode_pixels(mip);
    844                     glBindTexture(GL_TEXTURE_2D, state->image->color);
    845                     glTexImage2D(GL_TEXTURE_2D, ++level, GL_RGBA8, mip->width, mip->height, 0,
    846                                  GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    847                     if (pixels != mip->saved_pixels) free(pixels);
    848                 } else {
    849                     make_renderable(mip);
    850                     glBindFramebuffer(GL_READ_FRAMEBUFFER, mip->framebuffer);
    851                     glBindTexture(GL_TEXTURE_2D, state->image->color);
    852                     glCopyTexImage2D(GL_TEXTURE_2D, ++level, GL_RGBA8, 0, 0, mip->width, mip->height, 0);
    853                 }
    854             }
    855             glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    856             glBindTexture(GL_TEXTURE_2D, state->image->color);
    857             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level);
    858             state->image->mip_dirty = 0;
    859         }
    860         glBindTexture(GL_TEXTURE_2D, state->image->color);
    861         GLint min_filter = state->min_linear ? GL_LINEAR : GL_NEAREST;
    862         if (state->mip_point) min_filter = state->min_linear ? GL_LINEAR_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_NEAREST;
    863         if (sampler_changed || applied.texture[stage].min_linear != state->min_linear ||
    864             applied.texture[stage].mip_point != state->mip_point)
    865             glSamplerParameteri(samplers[stage], GL_TEXTURE_MIN_FILTER, min_filter);
    866         if (sampler_changed || applied.texture[stage].mag_linear != state->mag_linear)
    867             glSamplerParameteri(samplers[stage], GL_TEXTURE_MAG_FILTER, state->mag_linear ? GL_LINEAR : GL_NEAREST);
    868         if (sampler_changed || applied.texture[stage].clamp_u != state->clamp_u)
    869             glSamplerParameteri(samplers[stage], GL_TEXTURE_WRAP_S, state->clamp_u ? GL_CLAMP_TO_EDGE : GL_REPEAT);
    870         if (sampler_changed || applied.texture[stage].clamp_v != state->clamp_v)
    871             glSamplerParameteri(samplers[stage], GL_TEXTURE_WRAP_T, state->clamp_v ? GL_CLAMP_TO_EDGE : GL_REPEAT);
    872     } else glBindTexture(GL_TEXTURE_2D, 0);
    873     if (state) {
    874         if (changed || applied.texture[stage].alpha != state->alpha)
    875             glUniform1i(texture_alpha[stage], state->alpha);
    876         if (changed || applied.texture[stage].color_op != state->color_op)
    877             glUniform1i(texture_color_op[stage], state->color_op);
    878         if (changed || applied.texture[stage].alpha_op != state->alpha_op)
    879             glUniform1i(texture_alpha_op[stage], state->alpha_op);
    880         if (changed || applied.texture[stage].color_arg2 != state->color_arg2)
    881             glUniform1i(texture_color_arg2[stage], state->color_arg2);
    882         if (changed || applied.texture[stage].alpha_arg2 != state->alpha_arg2)
    883             glUniform1i(texture_alpha_arg2[stage], state->alpha_arg2);
    884         if (changed || applied.texture[stage].color_arg1 != state->color_arg1)
    885             glUniform1i(texture_color_arg1[stage], state->color_arg1);
    886         if (changed || applied.texture[stage].alpha_arg1 != state->alpha_arg1)
    887             glUniform1i(texture_alpha_arg1[stage], state->alpha_arg1);
    888         if (!applied.factor_valid || applied.factor != state->factor) {
    889             glUniform4f(texture_factor, ((state->factor >> 16) & 255) / 255.0f,
    890                         ((state->factor >> 8) & 255) / 255.0f, (state->factor & 255) / 255.0f,
    891                         (state->factor >> 24) / 255.0f);
    892             applied.factor_valid = 1;
    893             applied.factor = state->factor;
    894         }
    895         applied.texture[stage] = *state;
    896     }
    897     applied.texture_valid[stage] = 1;
    898     applied.texture_enabled[stage] = state != NULL;
    899     glActiveTexture(GL_TEXTURE0);
    900 }
    901 
    902 void gl_renderer_set_depth(int enabled, int write, uint32_t function, uint32_t bias)
    903 {
    904     depth_enabled = enabled;
    905     depth_write = write;
    906     depth_function = function;
    907     depth_bias = bias;
    908 }
    909 
    910 void gl_renderer_set_cull(uint32_t mode)
    911 {
    912     cull_mode = mode;
    913 }
    914 
    915 static GLenum blend_factor(uint32_t factor)
    916 {
    917     /* Direct3D blend factors supported by the platform adapter. */
    918     switch (factor) {
    919     case 1: return GL_ZERO;
    920     case 2: return GL_ONE;
    921     case 3: return GL_SRC_COLOR;
    922     case 5: return GL_SRC_ALPHA;
    923     case 6: return GL_ONE_MINUS_SRC_ALPHA;
    924     case 9: return GL_DST_COLOR;
    925     default: abort();
    926     }
    927 }
    928 
    929 void gl_renderer_set_fog(int enabled, uint32_t color)
    930 {
    931     if (applied.fog_valid && applied.fog_enabled == enabled && applied.fog_color == color) return;
    932     glUniform1i(fog_enabled, enabled);
    933     glUniform3f(fog_color, ((color >> 16) & 255) / 255.0f,
    934                 ((color >> 8) & 255) / 255.0f, (color & 255) / 255.0f);
    935     applied.fog_valid = 1;
    936     applied.fog_enabled = enabled;
    937     applied.fog_color = color;
    938 }
    939 
    940 void gl_renderer_set_blend(int enabled, uint32_t source, uint32_t destination)
    941 {
    942     if (applied.blend_valid && applied.blend_enabled == enabled &&
    943         (!enabled || (applied.source_blend == source && applied.destination_blend == destination))) return;
    944     if (enabled) {
    945         glEnable(GL_BLEND);
    946         glBlendFunc(blend_factor(source), blend_factor(destination));
    947     } else glDisable(GL_BLEND);
    948     applied.blend_valid = 1;
    949     applied.blend_enabled = enabled;
    950     applied.source_blend = source;
    951     applied.destination_blend = destination;
    952 }
    953 
    954 void gl_renderer_set_alpha_test(int enabled, uint32_t function, uint32_t reference)
    955 {
    956     if (!enabled) function = 8;
    957     if (applied.alpha_valid && applied.alpha_function == function && applied.alpha_reference == reference) return;
    958     glUniform1i(alpha_function, function);
    959     glUniform1f(alpha_reference, reference);
    960     applied.alpha_valid = 1;
    961     applied.alpha_function = function;
    962     applied.alpha_reference = reference;
    963 }