aorecomp

Anarchy Online classic in the browser

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


commit a3151c7f51b9cfd0f4a17f586183f3cd1a73b4f8
parent a894a2d4d488ee2c5ebe3e0171157805d602a901
Author: anon <anon@example.com>
Date:   Tue, 20 Oct 2026 18:32:56 +0000

Reduce rendering overhead and preserve Safari fallback frames

Retain vertex buffers with write invalidation and uploaded range tracking, cache unchanged graphics state, and avoid context-loss queries during normal rendering. Preserve the page-thread framebuffer during Safari fallback initialization.

Verified native graphics and device tests, browser loading tests, worker and page-thread fixtures, repeated context recovery, and full-game rendering and movement.

Diffstat:
Msrc/browser/index.html | 3++-
Msrc/runtime/gl_renderer.c | 248++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Msrc/runtime/gl_renderer.h | 8+++++++-
Msrc/runtime/linux_graphics.c | 28++++++++++++++++++++++++----
Msrc/tests/browser_context.c | 129++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Msrc/tests/browser_loading.mjs | 6+++++-
Msrc/tests/devices.c | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 428 insertions(+), 55 deletions(-)

diff --git a/src/browser/index.html b/src/browser/index.html @@ -305,7 +305,8 @@ show(); } } if (!workerGraphics) { - if (!canvas.getContext('webgl2', {alpha: false, antialias: false})) { + // Context attributes are fixed by the first call; match Emscripten's framebuffer forwarding. + if (!canvas.getContext('webgl2', {alpha: false, antialias: false, preserveDrawingBuffer: true})) { status.textContent = 'This browser could not initialize WebGL 2. Check graphics settings or try another browser.'; return; } diff --git a/src/runtime/gl_renderer.c b/src/runtime/gl_renderer.c @@ -29,6 +29,8 @@ static GLuint program, vertex_array, vertex_buffer, index_buffer; static GLuint transform_buffer; static GLint transform_enabled, color_bgra; static unsigned input_fvf, input_coordinates[2]; +static GLuint input_buffer; +static unsigned input_offset; static GLuint samplers[2]; static GLint texture_enabled[2], texture_alpha[2], texture_color_op[2], texture_alpha_op[2]; static GLint texture_color_arg2[2], texture_alpha_arg2[2]; @@ -40,6 +42,31 @@ static int depth_write = 1; static uint32_t depth_function = 4; static uint32_t depth_bias; static uint32_t cull_mode = 1; +/* Cache only state owned by this renderer; reset it for each GL context. */ +static struct { + int transform_valid, transform_enabled; + struct gl_vertex_transform transform; + int texture_valid[2], texture_enabled[2]; + struct gl_texture_state texture[2]; + int factor_valid; + uint32_t factor; + int fog_valid, fog_enabled; + uint32_t fog_color; + int alpha_valid; + uint32_t alpha_function, alpha_reference; + int blend_valid, blend_enabled; + uint32_t source_blend, destination_blend; + int raster_valid, depth_test, depth_write; + uint32_t cull, depth_function, depth_bias; +} applied; +struct gl_vertex_buffer { + GLuint buffer; + const void *vertices; + unsigned size; + unsigned uploaded_start, uploaded_end; + struct gl_vertex_buffer *next; +}; +static struct gl_vertex_buffer *vertex_buffers; struct gl_depth { unsigned width, height, references, bits; GLuint buffer; @@ -106,6 +133,7 @@ static void packed_vertex_format(void) int gl_renderer_initialize(void) { if (program) return 1; + memset(&applied, 0, sizeof(applied)); const char *sources[] = { SHADER_VERSION "layout(location=0) in vec4 position;\n" @@ -246,6 +274,7 @@ int gl_renderer_initialize(void) glBufferData(GL_UNIFORM_BUFFER, sizeof(struct gl_vertex_transform), NULL, GL_STREAM_DRAW); glBindBufferBase(GL_UNIFORM_BUFFER, 0, transform_buffer); glGenSamplers(2, samplers); + for (unsigned i = 0; i < 2; ++i) glBindSampler(i, samplers[i]); /* This context owns one program, vertex array and streamed buffer pair. * Keep them bound for all draws and uniform updates. */ @@ -254,6 +283,8 @@ int gl_renderer_initialize(void) glGenBuffers(1, &index_buffer); glBindVertexArray(vertex_array); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); + input_buffer = vertex_buffer; + input_offset = 0; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer); packed_vertex_format(); check_graphics("renderer initialization"); @@ -262,15 +293,23 @@ int gl_renderer_initialize(void) void gl_renderer_set_vertex_transform(const struct gl_vertex_transform *state) { - glUniform1i(transform_enabled, state != NULL); - if (state) { - glBindBuffer(GL_UNIFORM_BUFFER, transform_buffer); + if (!applied.transform_valid || applied.transform_enabled != (state != NULL)) + glUniform1i(transform_enabled, state != NULL); + if (state && (!applied.transform_valid || !applied.transform_enabled || + memcmp(&applied.transform, state, sizeof(*state)))) { glBufferData(GL_UNIFORM_BUFFER, sizeof(*state), state, GL_STREAM_DRAW); + applied.transform = *state; } + applied.transform_valid = 1; + applied.transform_enabled = state != NULL; } void gl_renderer_shutdown(void) { + for (struct gl_vertex_buffer *buffer = vertex_buffers; buffer; buffer = buffer->next) { + glDeleteBuffers(1, &buffer->buffer); + buffer->buffer = 0; + } glDeleteBuffers(1, &transform_buffer); glDeleteSamplers(2, samplers); glDeleteBuffers(1, &index_buffer); @@ -280,6 +319,32 @@ void gl_renderer_shutdown(void) transform_buffer = index_buffer = vertex_buffer = vertex_array = program = 0; } +struct gl_vertex_buffer *gl_vertex_buffer_create(const void *vertices, unsigned size) +{ + struct gl_vertex_buffer *buffer = calloc(1, sizeof(*buffer)); + if (!buffer) abort(); + buffer->vertices = vertices; + buffer->size = size; + buffer->next = vertex_buffers; + vertex_buffers = buffer; + return buffer; +} + +void gl_vertex_buffer_invalidate(struct gl_vertex_buffer *buffer) +{ + buffer->uploaded_end = 0; +} + +void gl_vertex_buffer_destroy(struct gl_vertex_buffer *buffer) +{ + struct gl_vertex_buffer **entry = &vertex_buffers; + while (*entry != buffer) entry = &(*entry)->next; + *entry = buffer->next; + if (input_buffer == buffer->buffer) input_buffer = 0; + glDeleteBuffers(1, &buffer->buffer); + free(buffer); +} + void gl_renderer_restore(void) { /* Release stale GL names while retaining guest surfaces and CPU textures. */ @@ -507,6 +572,7 @@ void gl_target_clear_rect(struct gl_target *target, uint32_t flags, uint32_t arg glScissor(left, top, right - left, bottom - top); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDepthMask(GL_TRUE); + applied.depth_write = 1; glClearColor(((argb >> 16) & 255) / 255.0f, ((argb >> 8) & 255) / 255.0f, (argb & 255) / 255.0f, (argb >> 24) / 255.0f); #ifdef __EMSCRIPTEN__ @@ -519,8 +585,8 @@ void gl_target_clear_rect(struct gl_target *target, uint32_t flags, uint32_t arg glBindFramebuffer(GL_FRAMEBUFFER, 0); } -static void draw_data(struct gl_target *target, unsigned primitive, const void *vertices, - unsigned vertex_bytes, const uint16_t *indices, unsigned index_count, const int32_t clip[4]) +static void draw_data(struct gl_target *target, unsigned primitive, + const uint16_t *indices, unsigned index_count, const int32_t clip[4]) { invalidate_mips(target); make_renderable(target); @@ -529,24 +595,37 @@ static void draw_data(struct gl_target *target, unsigned primitive, const void * glViewport(0, 0, target->width, target->height); glEnable(GL_SCISSOR_TEST); glScissor(clip[0], clip[1], clip[2], clip[3]); - if (cull_mode == 1) glDisable(GL_CULL_FACE); - else { - glEnable(GL_CULL_FACE); - /* Guest clockwise winding becomes GL counterclockwise after the Y mapping. */ - glFrontFace(GL_CCW); - glCullFace(cull_mode == 2 ? GL_FRONT : GL_BACK); + if (!applied.raster_valid || applied.cull != cull_mode) { + if (cull_mode == 1) glDisable(GL_CULL_FACE); + else { + glEnable(GL_CULL_FACE); + /* Guest clockwise winding becomes GL counterclockwise after the Y mapping. */ + glFrontFace(GL_CCW); + glCullFace(cull_mode == 2 ? GL_FRONT : GL_BACK); + } + } + if (!applied.raster_valid || applied.depth_test != (target->depth != NULL)) { + if (target->depth) glEnable(GL_DEPTH_TEST); + else glDisable(GL_DEPTH_TEST); } - if (target->depth) glEnable(GL_DEPTH_TEST); - else glDisable(GL_DEPTH_TEST); - glDepthFunc(GL_NEVER + depth_function - 1); - glDepthMask(depth_write ? GL_TRUE : GL_FALSE); - if (depth_bias) { - glEnable(GL_POLYGON_OFFSET_FILL); - /* D3D7 bias scale, checked on flat/sloped 16/24-bit depth surfaces. */ - glPolygonOffset(-(float)depth_bias * .25f, -(float)depth_bias * .5f); - } else glDisable(GL_POLYGON_OFFSET_FILL); + if (!applied.raster_valid || applied.depth_function != depth_function) + glDepthFunc(GL_NEVER + depth_function - 1); + if (!applied.raster_valid || applied.depth_write != depth_write) + glDepthMask(depth_write ? GL_TRUE : GL_FALSE); + if (!applied.raster_valid || applied.depth_bias != depth_bias) { + if (depth_bias) { + glEnable(GL_POLYGON_OFFSET_FILL); + /* D3D7 bias scale, checked on flat/sloped 16/24-bit depth surfaces. */ + glPolygonOffset(-(float)depth_bias * .25f, -(float)depth_bias * .5f); + } else glDisable(GL_POLYGON_OFFSET_FILL); + } + applied.raster_valid = 1; + applied.cull = cull_mode; + applied.depth_test = target->depth != NULL; + applied.depth_function = depth_function; + applied.depth_write = depth_write; + applied.depth_bias = depth_bias; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - glBufferData(GL_ARRAY_BUFFER, vertex_bytes, vertices, GL_STREAM_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_count * sizeof(*indices), indices, GL_STREAM_DRAW); glDrawElements(primitive == 2 ? GL_LINES : GL_TRIANGLES, index_count, GL_UNSIGNED_SHORT, NULL); glDisable(GL_SCISSOR_TEST); @@ -557,40 +636,77 @@ static void draw_data(struct gl_target *target, unsigned primitive, const void * void gl_target_draw(struct gl_target *target, unsigned primitive, const struct gl_vertex *vertices, unsigned vertex_count, const uint16_t *indices, unsigned index_count, const int32_t clip[4]) { - if (input_fvf) { + if (input_buffer != vertex_buffer) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); + if (input_fvf || input_buffer != vertex_buffer) { packed_vertex_format(); glUniform1i(color_bgra, 0); input_fvf = 0; } - draw_data(target, primitive, vertices, vertex_count * sizeof(*vertices), indices, index_count, clip); + input_buffer = vertex_buffer; + input_offset = 0; + glBufferData(GL_ARRAY_BUFFER, vertex_count * sizeof(*vertices), vertices, GL_STREAM_DRAW); + draw_data(target, primitive, indices, index_count, clip); } void gl_target_draw_fvf(struct gl_target *target, unsigned primitive, const void *vertices, unsigned fvf, const unsigned coordinates[2], const float color[4], unsigned vertex_count, - const uint16_t *indices, unsigned index_count, const int32_t clip[4]) + const uint16_t *indices, unsigned index_count, const int32_t clip[4], + struct gl_vertex_buffer *buffer, unsigned offset) { unsigned textures = (fvf >> 8) & 15; unsigned uv_offset = 12 + (fvf & 0x10 ? 12 : 0) + (fvf & 0x40 ? 4 : 0); unsigned stride = uv_offset + textures * 8; - if (input_fvf != fvf || input_coordinates[0] != coordinates[0] || input_coordinates[1] != coordinates[1]) { - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, NULL); + GLuint name = vertex_buffer; + if (buffer) { + if (!buffer->buffer) { + glGenBuffers(1, &buffer->buffer); + buffer->uploaded_end = 0; + } + name = buffer->buffer; + } + if (input_buffer != name) glBindBuffer(GL_ARRAY_BUFFER, name); + if (!buffer) glBufferData(GL_ARRAY_BUFFER, vertex_count * stride, vertices, GL_STREAM_DRAW); + else { + unsigned end = offset + vertex_count * stride; + /* Orphan dirty storage so edits do not wait for an earlier GPU draw. */ + if (!buffer->uploaded_end) { + glBufferData(GL_ARRAY_BUFFER, buffer->size, NULL, GL_STATIC_DRAW); + buffer->uploaded_start = buffer->uploaded_end = offset; + } + /* Track a contiguous range without copying gaps between disjoint draws. */ + if (end < buffer->uploaded_start || offset > buffer->uploaded_end) + buffer->uploaded_start = buffer->uploaded_end = offset; + if (offset < buffer->uploaded_start) { + glBufferSubData(GL_ARRAY_BUFFER, offset, buffer->uploaded_start - offset, + (const unsigned char *)buffer->vertices + offset); + buffer->uploaded_start = offset; + } + if (end > buffer->uploaded_end) { + glBufferSubData(GL_ARRAY_BUFFER, buffer->uploaded_end, end - buffer->uploaded_end, + (const unsigned char *)buffer->vertices + buffer->uploaded_end); + buffer->uploaded_end = end; + } + } + if (input_fvf != fvf || input_coordinates[0] != coordinates[0] || input_coordinates[1] != coordinates[1] || + input_buffer != name || input_offset != offset) { + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (void *)(uintptr_t)offset); if (fvf & 0x10) { glEnableVertexAttribArray(5); - glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, stride, (void *)(uintptr_t)12); + glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, stride, (void *)(uintptr_t)(offset + 12)); } else { glDisableVertexAttribArray(5); glVertexAttrib3f(5, 0, 0, 0); } if (fvf & 0x40) { glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void *)(uintptr_t)(uv_offset - 4)); + glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void *)(uintptr_t)(offset + uv_offset - 4)); } else glDisableVertexAttribArray(1); for (unsigned stage = 0; stage < 2; ++stage) { unsigned attribute = stage ? 4 : 2; if (coordinates[stage] < textures) { glEnableVertexAttribArray(attribute); glVertexAttribPointer(attribute, 2, GL_FLOAT, GL_FALSE, stride, - (void *)(uintptr_t)(uv_offset + coordinates[stage] * 8)); + (void *)(uintptr_t)(offset + uv_offset + coordinates[stage] * 8)); } else { glDisableVertexAttribArray(attribute); glVertexAttrib2f(attribute, 0, 0); @@ -602,8 +718,10 @@ void gl_target_draw_fvf(struct gl_target *target, unsigned primitive, const void input_fvf = fvf; memcpy(input_coordinates, coordinates, sizeof(input_coordinates)); } + input_buffer = name; + input_offset = offset; if (!(fvf & 0x40)) glVertexAttrib4fv(1, color); - draw_data(target, primitive, vertices, vertex_count * stride, indices, index_count, clip); + draw_data(target, primitive, indices, index_count, clip); } void gl_target_read(struct gl_target *target, unsigned char *rgba) @@ -706,10 +824,12 @@ void gl_target_present(struct gl_target *target, const int32_t rectangle[4], int void gl_renderer_set_texture(unsigned stage, const struct gl_texture_state *state) { assert(stage < 2); - glUniform1i(texture_enabled[stage], state != NULL); + int changed = !applied.texture_valid[stage] || !applied.texture_enabled[stage]; + if (!applied.texture_valid[stage] || applied.texture_enabled[stage] != (state != NULL)) + glUniform1i(texture_enabled[stage], state != NULL); glActiveTexture(GL_TEXTURE0 + stage); - glBindSampler(stage, samplers[stage]); if (state && state->image) { + int sampler_changed = changed || !applied.texture[stage].image; state->image->last_used = texture_frame_time; make_resident(state->image); if (state->image->mip_dirty) { @@ -738,23 +858,42 @@ void gl_renderer_set_texture(unsigned stage, const struct gl_texture_state *stat glBindTexture(GL_TEXTURE_2D, state->image->color); GLint min_filter = state->min_linear ? GL_LINEAR : GL_NEAREST; if (state->mip_point) min_filter = state->min_linear ? GL_LINEAR_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_NEAREST; - glSamplerParameteri(samplers[stage], GL_TEXTURE_MIN_FILTER, min_filter); - glSamplerParameteri(samplers[stage], GL_TEXTURE_MAG_FILTER, state->mag_linear ? GL_LINEAR : GL_NEAREST); - glSamplerParameteri(samplers[stage], GL_TEXTURE_WRAP_S, state->clamp_u ? GL_CLAMP_TO_EDGE : GL_REPEAT); - glSamplerParameteri(samplers[stage], GL_TEXTURE_WRAP_T, state->clamp_v ? GL_CLAMP_TO_EDGE : GL_REPEAT); + if (sampler_changed || applied.texture[stage].min_linear != state->min_linear || + applied.texture[stage].mip_point != state->mip_point) + glSamplerParameteri(samplers[stage], GL_TEXTURE_MIN_FILTER, min_filter); + if (sampler_changed || applied.texture[stage].mag_linear != state->mag_linear) + glSamplerParameteri(samplers[stage], GL_TEXTURE_MAG_FILTER, state->mag_linear ? GL_LINEAR : GL_NEAREST); + if (sampler_changed || applied.texture[stage].clamp_u != state->clamp_u) + glSamplerParameteri(samplers[stage], GL_TEXTURE_WRAP_S, state->clamp_u ? GL_CLAMP_TO_EDGE : GL_REPEAT); + if (sampler_changed || applied.texture[stage].clamp_v != state->clamp_v) + glSamplerParameteri(samplers[stage], GL_TEXTURE_WRAP_T, state->clamp_v ? GL_CLAMP_TO_EDGE : GL_REPEAT); } else glBindTexture(GL_TEXTURE_2D, 0); if (state) { - glUniform1i(texture_alpha[stage], state->alpha); - glUniform1i(texture_color_op[stage], state->color_op); - glUniform1i(texture_alpha_op[stage], state->alpha_op); - glUniform1i(texture_color_arg2[stage], state->color_arg2); - glUniform1i(texture_alpha_arg2[stage], state->alpha_arg2); - glUniform1i(texture_color_arg1[stage], state->color_arg1); - glUniform1i(texture_alpha_arg1[stage], state->alpha_arg1); - glUniform4f(texture_factor, ((state->factor >> 16) & 255) / 255.0f, - ((state->factor >> 8) & 255) / 255.0f, (state->factor & 255) / 255.0f, - (state->factor >> 24) / 255.0f); + if (changed || applied.texture[stage].alpha != state->alpha) + glUniform1i(texture_alpha[stage], state->alpha); + if (changed || applied.texture[stage].color_op != state->color_op) + glUniform1i(texture_color_op[stage], state->color_op); + if (changed || applied.texture[stage].alpha_op != state->alpha_op) + glUniform1i(texture_alpha_op[stage], state->alpha_op); + if (changed || applied.texture[stage].color_arg2 != state->color_arg2) + glUniform1i(texture_color_arg2[stage], state->color_arg2); + if (changed || applied.texture[stage].alpha_arg2 != state->alpha_arg2) + glUniform1i(texture_alpha_arg2[stage], state->alpha_arg2); + if (changed || applied.texture[stage].color_arg1 != state->color_arg1) + glUniform1i(texture_color_arg1[stage], state->color_arg1); + if (changed || applied.texture[stage].alpha_arg1 != state->alpha_arg1) + glUniform1i(texture_alpha_arg1[stage], state->alpha_arg1); + if (!applied.factor_valid || applied.factor != state->factor) { + glUniform4f(texture_factor, ((state->factor >> 16) & 255) / 255.0f, + ((state->factor >> 8) & 255) / 255.0f, (state->factor & 255) / 255.0f, + (state->factor >> 24) / 255.0f); + applied.factor_valid = 1; + applied.factor = state->factor; + } + applied.texture[stage] = *state; } + applied.texture_valid[stage] = 1; + applied.texture_enabled[stage] = state != NULL; glActiveTexture(GL_TEXTURE0); } @@ -785,21 +924,36 @@ static GLenum blend_factor(uint32_t factor) void gl_renderer_set_fog(int enabled, uint32_t color) { + if (applied.fog_valid && applied.fog_enabled == enabled && applied.fog_color == color) return; glUniform1i(fog_enabled, enabled); glUniform3f(fog_color, ((color >> 16) & 255) / 255.0f, ((color >> 8) & 255) / 255.0f, (color & 255) / 255.0f); + applied.fog_valid = 1; + applied.fog_enabled = enabled; + applied.fog_color = color; } void gl_renderer_set_blend(int enabled, uint32_t source, uint32_t destination) { + if (applied.blend_valid && applied.blend_enabled == enabled && + (!enabled || (applied.source_blend == source && applied.destination_blend == destination))) return; if (enabled) { glEnable(GL_BLEND); glBlendFunc(blend_factor(source), blend_factor(destination)); } else glDisable(GL_BLEND); + applied.blend_valid = 1; + applied.blend_enabled = enabled; + applied.source_blend = source; + applied.destination_blend = destination; } void gl_renderer_set_alpha_test(int enabled, uint32_t function, uint32_t reference) { - glUniform1i(alpha_function, enabled ? function : 8); + if (!enabled) function = 8; + if (applied.alpha_valid && applied.alpha_function == function && applied.alpha_reference == reference) return; + glUniform1i(alpha_function, function); glUniform1f(alpha_reference, reference); + applied.alpha_valid = 1; + applied.alpha_function = function; + applied.alpha_reference = reference; } diff --git a/src/runtime/gl_renderer.h b/src/runtime/gl_renderer.h @@ -5,6 +5,7 @@ /* These are host objects. Guest addresses are translated by the API adapter. */ struct gl_target; struct gl_depth; +struct gl_vertex_buffer; struct gl_vertex { float position[4]; /* D3D clip coordinates, or object coordinates with GPU transforms. */ float color[4]; @@ -53,7 +54,12 @@ void gl_target_draw(struct gl_target *target, unsigned primitive, const struct g unsigned vertex_count, const uint16_t *indices, unsigned index_count, const int32_t clip[4]); void gl_target_draw_fvf(struct gl_target *target, unsigned primitive, const void *vertices, unsigned fvf, const unsigned coordinates[2], const float color[4], unsigned vertex_count, - const uint16_t *indices, unsigned index_count, const int32_t clip[4]); + const uint16_t *indices, unsigned index_count, const int32_t clip[4], + struct gl_vertex_buffer *buffer, unsigned offset); +struct gl_vertex_buffer *gl_vertex_buffer_create(const void *vertices, unsigned size); +/* CPU bytes remain owned by the caller; mark writes before the next draw. */ +void gl_vertex_buffer_invalidate(struct gl_vertex_buffer *buffer); +void gl_vertex_buffer_destroy(struct gl_vertex_buffer *buffer); void gl_target_read(struct gl_target *target, unsigned char *rgba); void gl_target_write(struct gl_target *target, const unsigned char *rgba); void gl_target_blit(struct gl_target *source, struct gl_target *target, const int32_t source_rect[4], const int32_t target_rect[4]); diff --git a/src/runtime/linux_graphics.c b/src/runtime/linux_graphics.c @@ -36,6 +36,8 @@ EMSCRIPTEN_KEEPALIVE void browser_graphics_lost(void) int browser_graphics_ready(void) { + /* Only poll the owning thread while recovering from a notified loss. */ + if (!atomic_load(&graphics_lost)) return 1; if (context && emscripten_is_webgl_context_lost(context)) return 0; if (atomic_exchange(&graphics_lost, 0)) { gl_renderer_restore(); @@ -115,6 +117,7 @@ static struct device_object { static struct vertex_buffer { uint32_t interface, references, caps, fvf, count, size, data; struct draw_object *owner; + struct gl_vertex_buffer *gpu; struct vertex_buffer *next; } *vertex_buffers[4096]; static uint32_t vtables[9]; @@ -1978,7 +1981,7 @@ static void light_vertex(struct device_object *device, const float position[4], static void draw_primitive(struct device_object *device, uint32_t primitive, uint32_t fvf, uint32_t input, uint32_t count, uint32_t flags, - uint32_t input_indices, uint32_t element_count) + uint32_t input_indices, uint32_t element_count, struct vertex_buffer *buffer) { unsigned texture_count = (fvf >> 8) & 15, format = fvf & ~0x300u; int untransformed = texture_count >= 1 && (format == 0x12 || format == 0x52 || format == 0x42); @@ -2232,10 +2235,25 @@ static void draw_primitive(struct device_object *device, uint32_t primitive, uin gl_renderer_set_cull(device->cull); const int32_t clip[] = {device->viewport[0], device->viewport[1], device->viewport[2], device->viewport[3]}; if (raw_vertices) { + /* Retain a vertex buffer only when its whole guest allocation is contiguous. */ + unsigned offset = 0; + if (buffer && !buffer->gpu) { + const void *data = (const void *)ADDR(buffer->data); + uint64_t end = (uint64_t)buffer->data + buffer->size; + for (uint64_t page = ((uint64_t)buffer->data | 0xffffu) + 1; page < end; page += 0x10000) { + if (page > UINT32_MAX || ADDR((uint32_t)page) != (uintptr_t)data + page - buffer->data) { + buffer = NULL; + break; + } + } + if (buffer) buffer->gpu = gl_vertex_buffer_create(data, buffer->size); + } + if (buffer) offset = input - buffer->data; const unsigned coordinates[] = {device->stages[0].texture_coordinate, device->stages[1].texture_coordinate}; const float white[] = {1, 1, 1, 1}; gl_target_draw_fvf(device->target->target, primitive == 2 ? 2 : 4, raw_vertices, fvf, coordinates, - device->lighting ? (const float *)device->material : white, count, indices, index_count, clip); + device->lighting ? (const float *)device->material : white, count, indices, index_count, clip, + buffer ? buffer->gpu : NULL, offset); } else gl_target_draw(device->target->target, primitive == 2 ? 2 : 4, vertices, count, indices, index_count, clip); free(indices); free(vertices); @@ -2248,7 +2266,7 @@ static void device_draw_primitive(void) uint32_t primitive = MEM32(g_esp + 8), fvf = MEM32(g_esp + 12), input = MEM32(g_esp + 16); uint32_t count = MEM32(g_esp + 20), flags = MEM32(g_esp + 24); g_esp += 28; - draw_primitive(device, primitive, fvf, input, count, flags, 0, 0); + draw_primitive(device, primitive, fvf, input, count, flags, 0, 0, NULL); } static void device_set_texture(void) @@ -2464,7 +2482,7 @@ static void device_draw_vertex_buffer(void) if (current_slot == 32 && !indices) return; if (start > buffer->count || count > buffer->count - start) return; draw_primitive(device, primitive, buffer->fvf, - buffer->data + start * vertex_stride(buffer->fvf), count, flags, indices, index_count); + buffer->data + start * vertex_stride(buffer->fvf), count, flags, indices, index_count, buffer); } static void vertex_buffer_query_interface(void) @@ -2499,6 +2517,7 @@ static void vertex_buffer_release_reference(void) while (*link != buffer) link = &(*link)->next; *link = buffer->next; release_draw(buffer->owner, 1); + if (buffer->gpu) gl_vertex_buffer_destroy(buffer->gpu); guest_free(buffer->data); guest_free(buffer->interface); free(buffer); @@ -2514,6 +2533,7 @@ static void vertex_buffer_lock(void) g_eax = 0x80070057u; if (!output) return; if (flags & ~0x3831u) { fprintf(stderr, "Unsupported vertex buffer lock flags %08x\n", flags); exit(3); } + if (buffer->gpu && !(flags & 0x10)) gl_vertex_buffer_invalidate(buffer->gpu); MEM32(output) = buffer->data; if (size) MEM32(size) = buffer->size; g_eax = 0; diff --git a/src/tests/browser_context.c b/src/tests/browser_context.c @@ -14,6 +14,119 @@ static struct gl_target *image, *first, *second; static struct gl_depth *depth; static unsigned iteration; static atomic_int restored; +static atomic_int context_queries; +static atomic_int vertex_uploads, vertex_bytes, uniform_updates; +static struct gl_vertex_buffer *buffer; +static struct { + float position[3]; + uint32_t color; + float uv[2]; +} buffer_vertices[64] = { + {{0, 0, 0}, 0, {0, 0}}, {{0, 0, 0}, 0, {0, 0}}, + {{-1, -1, .5f}, 0xffffffff, {0, 0}}, {{1, -1, .5f}, 0xffffffff, {1, 0}}, + {{-1, 1, .5f}, 0xffffffff, {0, 1}}, {{1, 1, .5f}, 0xffffffff, {1, 1}} +}; + +static void count_context_queries_on_owner(void) +{ + EM_ASM({ + const context = GL.currentContext.GLctx; + const original = context.isContextLost; + context.isContextLost = function() { + Atomics.add(HEAP32, $0 >> 2, 1); + return original.call(this); + }; + const upload = context.bufferData; + context.bufferData = function(target, data, ...args) { + if (target === context.ARRAY_BUFFER && typeof data !== 'number') { + Atomics.add(HEAP32, $1 >> 2, 1); + Atomics.add(HEAP32, $3 >> 2, args.length >= 3 ? args[2] : data.byteLength); + } + return upload.call(this, target, data, ...args); + }; + const update = context.bufferSubData; + context.bufferSubData = function(target, offset, data, ...args) { + if (target === context.ARRAY_BUFFER) { + Atomics.add(HEAP32, $1 >> 2, 1); + Atomics.add(HEAP32, $3 >> 2, args.length >= 2 ? args[1] : data.byteLength); + } + return update.call(this, target, offset, data, ...args); + }; + const uniform = context.uniform1i; + context.uniform1i = function(...args) { + Atomics.add(HEAP32, $2 >> 2, 1); + return uniform.call(this, ...args); + }; + }, &context_queries, &vertex_uploads, &uniform_updates, &vertex_bytes); +} + +static void retained_vertices_reuse_uploads(const struct gl_texture_state *texture) +{ + const uint16_t indices[] = {0, 1, 2, 1, 3, 2}; + const unsigned coordinates[] = {0, 1}; + const float white[] = {1, 1, 1, 1}; + const int32_t clip[] = {0, 0, 2, 2}; + memcpy(&buffer_vertices[10], &buffer_vertices[2], 4 * sizeof(buffer_vertices[0])); + buffer = gl_vertex_buffer_create(buffer_vertices, sizeof(buffer_vertices)); + gl_renderer_set_vertex_transform(NULL); + gl_renderer_set_texture(0, texture); + gl_renderer_set_fog(0, 0); + gl_renderer_set_alpha_test(0, 8, 0); + gl_target_draw_fvf(first, 4, NULL, 0x142, coordinates, white, 4, indices, 6, clip, buffer, 48); + unsigned char actual[16]; + gl_target_read(first, actual); + assert(atomic_load(&vertex_uploads) == 1); + assert(atomic_load(&vertex_bytes) == 96); + atomic_store(&uniform_updates, 0); + + for (unsigned index = 0; index < 3; ++index) { + gl_renderer_set_vertex_transform(NULL); + gl_renderer_set_texture(0, texture); + gl_renderer_set_fog(0, 0); + gl_renderer_set_alpha_test(0, 8, 0); + gl_target_draw_fvf(first, 4, NULL, 0x142, coordinates, white, 4, indices, 6, clip, buffer, 48); + } + gl_target_read(first, actual); + + const unsigned char expected[] = {0, 0, 255, 255, 255, 255, 255, 255, + 255, 0, 0, 255, 0, 255, 0, 255}; + assert(!memcmp(actual, expected, sizeof(expected))); + assert(atomic_load(&vertex_uploads) == 1); + assert(atomic_load(&vertex_bytes) == 96); + assert(atomic_load(&uniform_updates) == 0); + + /* Extending a draw uploads only the additional vertices. */ + gl_target_draw_fvf(first, 4, NULL, 0x142, coordinates, white, 6, indices, 6, clip, buffer, 48); + gl_target_read(first, actual); + assert(!memcmp(actual, expected, sizeof(expected))); + assert(atomic_load(&vertex_uploads) == 2); + assert(atomic_load(&vertex_bytes) == 144); + + /* Disjoint slices do not upload their unused gap, and repeated slices reuse data. */ + gl_target_draw_fvf(first, 4, NULL, 0x142, coordinates, white, 4, indices, 6, clip, buffer, 240); + gl_target_draw_fvf(first, 4, NULL, 0x142, coordinates, white, 4, indices, 6, clip, buffer, 240); + gl_target_read(first, actual); + assert(!memcmp(actual, expected, sizeof(expected))); + assert(atomic_load(&vertex_uploads) == 3); + assert(atomic_load(&vertex_bytes) == 240); + gl_target_draw_fvf(first, 4, NULL, 0x142, coordinates, white, 4, indices, 6, clip, buffer, 48); + gl_target_read(first, actual); + assert(!memcmp(actual, expected, sizeof(expected))); + + /* A marked write uploads once and changes the rendered pixels. */ + buffer_vertices[2].position[0] = buffer_vertices[4].position[0] = 1; + gl_vertex_buffer_invalidate(buffer); + gl_target_clear(first, 0xff000000, 1); + gl_target_draw_fvf(first, 4, NULL, 0x142, coordinates, white, 4, indices, 6, clip, buffer, 48); + gl_target_read(first, actual); + const unsigned char black[] = {0, 0, 0, 255, 0, 0, 0, 255, + 0, 0, 0, 255, 0, 0, 0, 255}; + assert(!memcmp(actual, black, sizeof(black))); + assert(atomic_load(&vertex_uploads) == 5); + assert(atomic_load(&vertex_bytes) == 432); + buffer_vertices[2].position[0] = buffer_vertices[4].position[0] = -1; + gl_vertex_buffer_invalidate(buffer); +} static void lose_context_on_owner(void) { @@ -68,6 +181,17 @@ int main(void) gl_target_clear(first, 0xff000000, 1); gl_target_draw(first, 4, vertices, 4, indices, 6, clip); + if (EM_ASM_INT({ return !!GL.currentContextIsProxied; })) + emscripten_sync_run_in_main_runtime_thread(EM_FUNC_SIG_V, count_context_queries_on_owner); + else count_context_queries_on_owner(); + + for (unsigned index = 0; index < 1000; ++index) + assert(linux_graphics_window() == window); + + assert(atomic_load(&context_queries) == 0); + retained_vertices_reuse_uploads(&texture); + + /* Exercise recovery after repeated losses using the same graphics context. */ lose_context(); emscripten_request_animation_frame_loop(restored_frame, NULL); emscripten_exit_with_live_runtime(); @@ -101,7 +225,9 @@ static bool restored_frame(double timestamp, void *argument) gl_target_clear(first, 0xff000000, 1); gl_target_clear(second, 0xff000000, 1); gl_target_draw(first, 4, vertices, 4, indices, 6, clip); - gl_target_draw(second, 4, vertices, 4, indices, 6, clip); + const unsigned coordinates[] = {0, 1}; + const float white[] = {1, 1, 1, 1}; + gl_target_draw_fvf(second, 4, NULL, 0x142, coordinates, white, 4, indices, 6, clip, buffer, 48); unsigned char actual[16]; gl_target_read(first, actual); @@ -127,6 +253,7 @@ static bool restored_frame(double timestamp, void *argument) gl_target_destroy(first); gl_target_destroy(second); gl_depth_destroy(depth); + gl_vertex_buffer_destroy(buffer); linux_graphics_shutdown(); puts("PASS: repeated context loss restores textures, shared depth, shaders, resizing and presentation without JSPI"); return false; diff --git a/src/tests/browser_loading.mjs b/src/tests/browser_loading.mjs @@ -92,7 +92,11 @@ async function reportsUnavailableWebGLOnBothThreadsBeforeDownloading() { async function startsWithMainThreadGraphicsWithoutOffscreenCanvas() { const test = fixture(); const canvas = test.context.document.querySelector('#canvas'); - canvas.getContext = type => { assert.equal(type, 'webgl2'); return {}; }; + canvas.getContext = (type, attributes) => { + assert.equal(type, 'webgl2'); + assert.equal(attributes.preserveDrawingBuffer, true); + return {}; + }; canvas.clientWidth = 1024; canvas.clientHeight = 768; const scripts = []; diff --git a/src/tests/devices.c b/src/tests/devices.c @@ -565,6 +565,66 @@ static void indexed_vertex_buffers_use_relative_indices(uint32_t draw, uint32_t invoke(d3d, 2, 1); } +static void vertex_buffer_writes_update_rendered_pixels(uint32_t draw, uint32_t device, uint32_t target) +{ + const uint32_t iid[] = {0xf5049e77, 0x11d24861, 0xa00007a4, 0xa82906c9}; + uint32_t d3d = query(draw, iid), desc = workspace() + 128, elements = workspace() + 512; + const uint32_t description[] = {16, 0x800, 0x142, 6}; + const float identity[] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; + const float positions[][3] = {{-.75f,.75f,.5f}, {.75f,.75f,.5f}, {-.75f,-.75f,.5f}, {.75f,-.75f,.5f}}; + const uint16_t indices[] = {0,1,2,1,3,2}; + memcpy(memory(desc), description, sizeof(description)); + assert(!invoke(d3d, 5, 4, desc, workspace(), 0u)); + uint32_t buffer = *memory(workspace()); + assert(!invoke(buffer, 3, 4, 0x1020u, workspace(), 0u)); + uint32_t input = *memory(workspace()); + memset(memory(input), 0, 144); + for (unsigned i = 0; i < 4; ++i) { + memcpy(memory(input + (i + 2) * 24), positions[i], 12); + *memory(input + (i + 2) * 24 + 12) = 0xff5a96d2; + } + assert(!invoke(buffer, 4, 1)); + memcpy(memory(elements), indices, sizeof(indices)); + memcpy(memory(workspace() + 256), identity, sizeof(identity)); + for (unsigned transform = 1; transform <= 3; ++transform) + assert(!invoke(device, 11, 3, transform, workspace() + 256)); + assert(!invoke(device, 20, 3, 137u, 0u)); + assert(!invoke(device, 20, 3, 29u, 0u)); + assert(!invoke(device, 20, 3, 27u, 0u)); + assert(!invoke(device, 20, 3, 28u, 0u)); + assert(!invoke(device, 20, 3, 15u, 0u)); + assert(!invoke(device, 20, 3, 22u, 1u)); + assert(!invoke(device, 20, 3, 23u, 8u)); + assert(!invoke(device, 35, 3, 0u, 0u)); + assert(!invoke(device, 37, 4, 0u, 1u, 2u)); + assert(!invoke(device, 37, 4, 0u, 2u, 0u)); + assert(!invoke(device, 37, 4, 1u, 1u, 1u)); + + const uint32_t expected[] = {0x5a96d2, 0xff0000, 0xff0000}; + for (unsigned step = 0; step < 3; ++step) { + if (step) { + assert(!invoke(buffer, 3, 4, step == 1 ? 0x1020u : 0x11u, workspace(), 0u)); + if (step == 1) for (unsigned i = 0; i < 4; ++i) + *memory(*memory(workspace()) + (i + 2) * 24 + 12) = 0xffff0000; + assert(!invoke(buffer, 4, 1)); + } + assert(!invoke(device, 10, 7, 0u, 0u, 3u, 0xff000000u, 0x3f800000u, 0u)); + assert(!invoke(device, 5, 1)); + assert(!invoke(device, 32, 8, 4u, buffer, 2u, 4u, elements, 6u, 0u)); + assert(!invoke(device, 6, 1)); + + *memory(desc) = 124; + assert(!invoke(target, 25, 5, 0u, desc, 0x11u, 0u)); + uint32_t pixels = *memory(desc + 36), pitch = *memory(desc + 16); + assert((*memory(pixels + 16 * pitch + 16 * 4) & 0xffffff) == expected[step]); + assert(!invoke(target, 32, 2, 0u)); + } + invoke(buffer, 2, 1); + invoke(d3d, 2, 1); + assert(!invoke(device, 20, 3, 23u, 4u)); + assert(!invoke(device, 37, 4, 0u, 2u, 2u)); +} + static void line_lists_draw_independent_segments(uint32_t draw, uint32_t device, uint32_t target) { const uint32_t iid[] = {0xf5049e77, 0x11d24861, 0xa00007a4, 0xa82906c9}; @@ -1759,6 +1819,7 @@ static void device_lifetime_and_rendering(const char *pixels_path) transformed_vertex_fog_blends_rgb(device, color, file); vertex_buffer_draws_match_memory_draws(draw, device, color, file); indexed_vertex_buffers_use_relative_indices(draw, device, color, file); + vertex_buffer_writes_update_rendered_pixels(draw, device, color); rectangle_clears_preserve_outside_depth(device, color, file); depth_write_controls_occlusion(device, color); depth_comparisons_control_visibility(device, color);