chore: checkpoint web Blender migration source, tools and docs
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

Accumulated uncommitted work: GHOST Web backend, WebGL/GPU web layer,
web workflow engine and protocol, tooling, docs and task records.
Large generated evidence, user-testing archives, build snapshots and
imported test assets remain untracked.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-10 11:18:01 +08:00
parent 122142c26c
commit f3e21c6b98
6887 changed files with 257154 additions and 12294 deletions

View File

@@ -18,6 +18,10 @@
#include "GPU_vertex_buffer.hh"
#ifdef __EMSCRIPTEN__
# include <stdexcept>
#endif
namespace blender::gpu {
class Context;
@@ -38,7 +42,7 @@ class VertBuf;
class GPUBackend {
protected:
ShaderCompiler *compiler_;
ShaderCompiler *compiler_ = nullptr;
public:
virtual ~GPUBackend() = default;
@@ -52,6 +56,11 @@ class GPUBackend {
ShaderCompiler *get_compiler()
{
#ifdef __EMSCRIPTEN__
if (!compiler_) {
throw std::runtime_error("Blender GPU shader compiler is not initialized");
}
#endif
return compiler_;
}

View File

@@ -356,7 +356,7 @@ static void polyline_draw_workaround(
Batch *batch, int vertex_first, int vertex_count, int instance_first, int instance_count)
{
/* Early out as this can cause crashes on some backend (see #136831). */
if (vertex_count == 0) {
if (vertex_count < 2) {
return;
}
/* Check compatible input primitive. */
@@ -364,26 +364,36 @@ static void polyline_draw_workaround(
GPU_batch_bind_as_resources(batch, batch->shader);
IndexRange range = GPU_batch_draw_expanded_parameter_get(
batch->prim_type, GPU_PRIM_TRIS, vertex_count, vertex_first, 2);
batch->prim_type, GPU_PRIM_TRIS, vertex_count, 0, 2);
Batch *tri_batch = Context::get()->procedural_triangles_batch_get();
GPU_batch_set_shader(tri_batch, batch->shader);
int vert_stride_count[3] = {(batch->prim_type == GPU_PRIM_LINES) ? 2 : 1, vertex_count, 0};
GPU_shader_uniform_3iv(batch->shader, "gpu_vert_stride_count_offset", vert_stride_count);
/* Expansion and loop wrapping are relative to this draw, then address the parent index buffer. */
const int index_start = vertex_first + (batch->elem ? batch->elem->index_start_get() : 0);
GPU_shader_uniform_1i(batch->shader, "gpu_polyline_index_start", index_start);
/* Assume GPU_FETCH_FLOAT for now. A bit cumbersome to assert for this or to find the correct
* attribute. */
GPU_shader_uniform_1b(batch->shader, "gpu_attr_0_fetch_int", false);
/* Allow byte color fetch. */
const GPUVertFormat *format = GPU_vertbuf_get_format(batch->verts[0]);
int id = GPU_vertformat_attr_id_get(format, "color");
if (id != -1) {
for (int v = 0; v < GPU_BATCH_VBO_MAX_LEN; v++) {
if (!batch->verts[v]) {
continue;
}
const GPUVertFormat *format = GPU_vertbuf_get_format(batch->verts[v]);
int id = GPU_vertformat_attr_id_get(format, "color");
if (id == -1) {
continue;
}
const GPUVertAttr &attr = format->attrs[id];
const bool is_unorm8 = attr.type.format == gpu::VertAttrType::UNORM_8_8_8_8;
BLI_assert_msg(is_unorm8 || attr.type.fetch_mode() == GPU_FETCH_FLOAT,
"color attribute for polylines can only use GPU_FETCH_INT_TO_FLOAT_UNIT or "
"GPU_FETCH_FLOAT");
GPU_shader_uniform_1b(batch->shader, "gpu_attr_1_fetch_unorm8", is_unorm8);
break;
}
GPU_batch_draw_advanced(tri_batch, range.start(), range.size(), instance_first, instance_count);

View File

@@ -13,6 +13,8 @@
* - free can be called from any thread
*/
#include <mutex>
#include "BKE_global.hh"
#include "BLI_assert.h"
@@ -38,7 +40,10 @@
#ifdef WITH_VULKAN_BACKEND
# include "vk_backend.hh"
#endif
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
# include "GPU_init_exit.hh"
# include "webgl_backend.hh"
#elif defined(WITH_OPENGL_BACKEND)
# include "gl_backend.hh"
# include "gl_context.hh"
#endif
@@ -51,6 +56,9 @@
#include <cstdio>
#include <mutex>
#ifdef WITH_WEBGL_BACKEND
# include <stdexcept>
#endif
namespace blender {
@@ -198,14 +206,40 @@ GPUContext *GPU_context_create(GHOST_IWindow *ghost_window, GHOST_IContext *ghos
/* Automatically create backend when first context is created. */
gpu_backend_create();
}
#ifdef WITH_WEBGL_BACKEND
else if (GPU_backend_get_type() != GPU_backend_type_selection_get()) {
throw std::runtime_error("Cannot change Blender GPU backend while contexts are alive");
}
#endif
num_backend_users++;
}
#ifdef WITH_WEBGL_BACKEND
Context *previous = active_ctx;
Context *ctx = nullptr;
try {
ctx = GPUBackend::get()->context_alloc(ghost_window, ghost_context);
GPU_context_active_set(wrap(ctx));
}
catch (...) {
delete ctx;
active_ctx = nullptr;
GPU_context_active_set(wrap(previous));
std::scoped_lock lock(backend_users_mutex);
if (--num_backend_users == 0) {
gpu_backend_discard();
}
throw;
}
/* DebugDraw::acquire allocates SSBOs even with WITH_DRAW_DEBUG disabled.
* WebGL2 cannot provide those optional diagnostic buffers. */
#else
Context *ctx = GPUBackend::get()->context_alloc(ghost_window, ghost_context);
GPU_context_active_set(wrap(ctx));
draw::DebugDraw::get().acquire();
#endif
return wrap(ctx);
}
@@ -215,7 +249,21 @@ void GPU_context_discard(GPUContext *ctx_)
Context *ctx = unwrap(ctx_);
BLI_assert(active_ctx == ctx);
#ifdef WITH_WEBGL_BACKEND
/* Registry/compiler lifetime must end before the final canvas context/backend is released. */
bool last_context;
{
std::scoped_lock lock(backend_users_mutex);
last_context = num_backend_users == 1;
}
if (last_context) {
GPU_exit();
}
#endif
#ifndef WITH_WEBGL_BACKEND
draw::DebugDraw::get().release();
#endif
GPUBackend *backend = GPUBackend::get();
/* Flush any remaining printf while making sure we are inside render boundaries. */
@@ -240,6 +288,9 @@ void GPU_context_discard(GPUContext *ctx_)
void GPU_context_active_set(GPUContext *ctx_)
{
Context *ctx = unwrap(ctx_);
#ifdef WITH_WEBGL_BACKEND
Context *previous = active_ctx;
#endif
if (active_ctx) {
GPU_shader_unbind();
@@ -249,7 +300,20 @@ void GPU_context_active_set(GPUContext *ctx_)
active_ctx = ctx;
if (ctx) {
#ifdef WITH_WEBGL_BACKEND
try {
ctx->activate();
}
catch (...) {
active_ctx = previous;
if (previous) {
previous->activate();
}
throw;
}
#else
ctx->activate();
#endif
/* It can happen that the previous context drew with a different color-space.
* In the case where the new context is drawing with the same shader that was previously bound
* (shader binding optimization), the uniform would not be set again because the dirty flag
@@ -265,6 +329,11 @@ GPUContext *GPU_context_active_get()
return wrap(Context::get());
}
uint64_t GPU_context_active_id_get()
{
return active_ctx ? active_ctx->context_id : uint64_t(-1);
}
void GPU_context_begin_frame(GPUContext *ctx)
{
gpu::Context *_ctx = unwrap(ctx);
@@ -295,7 +364,11 @@ void GPU_context_debug_pipeline_creation(GPUContext *ctx, bool enable)
* Used to avoid crash on some old drivers.
* \{ */
#if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__)
static std::recursive_mutex main_context_mutex;
#else
static Mutex main_context_mutex;
#endif
void GPU_context_main_lock()
{
@@ -451,7 +524,11 @@ static const char *gpu_backend_type_name(const GPUBackendType backend_type)
{
switch (backend_type) {
case GPU_BACKEND_OPENGL:
#ifdef WITH_WEBGL_BACKEND
return "WebGL2";
#else
return "OpenGL";
#endif
case GPU_BACKEND_VULKAN:
return "Vulkan";
case GPU_BACKEND_METAL:
@@ -478,7 +555,7 @@ bool GPU_backend_type_selection_detect()
if (g_backend_type_override.has_value()) {
backends_to_check.add(*g_backend_type_override);
}
#if defined(WITH_OPENGL_BACKEND)
#if defined(WITH_OPENGL_BACKEND) || defined(WITH_WEBGL_BACKEND)
backends_to_check.add(GPU_BACKEND_OPENGL);
#elif defined(WITH_METAL_BACKEND)
backends_to_check.add(GPU_BACKEND_METAL);
@@ -512,7 +589,11 @@ static bool gpu_backend_supported()
{
switch (g_backend_type) {
case GPU_BACKEND_OPENGL:
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
/* WM selects the backend before creating its first GHOST window. The actual
* WebGL2 context is checked by WebGLBackend and context_alloc after creation. */
return true;
#elif defined(WITH_OPENGL_BACKEND)
return true;
#else
return false;
@@ -551,7 +632,11 @@ static void gpu_backend_create()
BLI_assert(GPU_backend_supported());
switch (g_backend_type) {
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
case GPU_BACKEND_OPENGL:
g_backend = MEM_new<WebGLBackend>(__func__);
break;
#elif defined(WITH_OPENGL_BACKEND)
case GPU_BACKEND_OPENGL:
g_backend = MEM_new<GLBackend>(__func__);
break;
@@ -597,7 +682,11 @@ void gpu_backend_discard()
GPUBackendType GPU_backend_get_type()
{
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
if (g_backend && dynamic_cast<WebGLBackend *>(g_backend) != nullptr) {
return GPU_BACKEND_OPENGL;
}
#elif defined(WITH_OPENGL_BACKEND)
if (g_backend && dynamic_cast<GLBackend *>(g_backend) != nullptr) {
return GPU_BACKEND_OPENGL;
}
@@ -639,7 +728,10 @@ namespace gpu {
static GHOST_TDrawingContextType ghost_context_type()
{
switch (GPU_backend_type_selection_get()) {
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
case GPU_BACKEND_OPENGL:
return GHOST_kDrawingContextTypeWebGL;
#elif defined(WITH_OPENGL_BACKEND)
case GPU_BACKEND_OPENGL:
return GHOST_kDrawingContextTypeOpenGL;
#endif

View File

@@ -8,6 +8,8 @@
#include "MEM_guardedalloc.h"
#include <memory>
#include "BLI_math_base.h"
#include "BLI_string.h"
#include "BLI_utildefines.h"
@@ -137,6 +139,18 @@ void FrameBuffer::attachment_remove(GPUAttachmentType type)
void FrameBuffer::subpass_transition(const GPUAttachmentState depth_attachment_state,
Span<GPUAttachmentState> color_attachment_states)
{
#ifdef __EMSCRIPTEN__
/* The browser's default color attachment has no Texture wrapper. Route it explicitly
* instead of treating it as an absent attachment and clearing its write bit. */
Context *context = Context::get();
if (this == context->back_left || this == context->back_right) {
BLI_assert(depth_attachment_state == GPU_ATTACHMENT_IGNORE);
BLI_assert(color_attachment_states.size() == 1);
color_attachments_bits_ = color_attachment_states[0] == GPU_ATTACHMENT_WRITE ? 1 : 0;
subpass_transition_impl(depth_attachment_state, color_attachment_states);
return;
}
#endif
/* NOTE: Depth is not supported as input attachment because the Metal API doesn't support it and
* because depth is not compatible with the framebuffer fetch implementation. */
BLI_assert(depth_attachment_state != GPU_ATTACHMENT_READ);
@@ -171,6 +185,19 @@ void FrameBuffer::load_store_config_array(const GPULoadStore *load_store_actions
Span<GPULoadStore> color_attachment_actions(load_store_actions + 1, actions_len - 1);
BLI_assert(color_attachment_actions.size() <= GPU_FB_MAX_COLOR_ATTACHMENT);
#ifdef __EMSCRIPTEN__
/* Window composition uses the implicit browser color buffer, not a texture attachment.
* Depth/stencil are unused by this pass; keep their unsupported load/store contract explicit. */
Context *context = Context::get();
if (this == context->back_left || this == context->back_right) {
BLI_assert(actions_len == 2);
BLI_assert(depth_action.load_action == GPU_LOADACTION_DONT_CARE &&
depth_action.store_action == GPU_STOREACTION_DONT_CARE);
this->attachment_set_loadstore_op(GPU_FB_COLOR_ATTACHMENT0, color_attachment_actions[0]);
return;
}
#endif
if (!attachments_[GPU_FB_DEPTH_ATTACHMENT].tex &&
!attachments_[GPU_FB_DEPTH_STENCIL_ATTACHMENT].tex)
{
@@ -734,7 +761,8 @@ GPUOffScreen *GPU_offscreen_create(int width,
bool clear,
char err_out[256])
{
GPUOffScreen *ofs = MEM_new_zeroed<GPUOffScreen>(__func__);
std::unique_ptr<GPUOffScreen, decltype(&GPU_offscreen_free)> ofs(
MEM_new_zeroed<GPUOffScreen>(__func__), GPU_offscreen_free);
/* Sometimes areas can have 0 height or width and this will
* create a 1D texture which we don't want. */
@@ -766,19 +794,31 @@ GPUOffScreen *GPU_offscreen_create(int width,
else {
fprintf(stderr, "%s", error);
}
GPU_offscreen_free(ofs);
return nullptr;
}
gpu::FrameBuffer *fb = gpu_offscreen_fb_get(ofs);
gpu::FrameBuffer *fb = gpu_offscreen_fb_get(ofs.get());
/* check validity at the very end! */
if (!GPU_framebuffer_check_valid(fb, err_out)) {
GPU_offscreen_free(ofs);
return nullptr;
}
if (clear) {
#ifdef __EMSCRIPTEN__
/* Native WM region buffers (including headers and popup regions) start transparent.
* Express this as a full attachment load clear, independent of a previous region's
* scissor. The stored color is subsequently reused by partial redraw and compositing. */
const GPULoadStore actions[] = {
{with_depth_buffer ? GPU_LOADACTION_CLEAR : GPU_LOADACTION_DONT_CARE,
with_depth_buffer ? GPU_STOREACTION_STORE : GPU_STOREACTION_DONT_CARE,
{0.0, 0.0, 0.0, 0.0}},
{GPU_LOADACTION_CLEAR, GPU_STOREACTION_STORE, {0.0, 0.0, 0.0, 0.0}},
};
GPU_framebuffer_bind_loadstore(fb, actions, ARRAY_SIZE(actions));
/* Editor callbacks use ordinary scissored clears, not explicit load/store passes. */
GPU_framebuffer_bind(fb);
#else
GPU_framebuffer_bind(fb);
if (with_depth_buffer) {
GPU_framebuffer_clear_color_depth(fb, {0.0, 0.0, 0.0, 0.0}, 0.0f);
@@ -786,10 +826,11 @@ GPUOffScreen *GPU_offscreen_create(int width,
else {
GPU_framebuffer_clear_color(fb, {0.0, 0.0, 0.0, 0.0});
}
#endif
}
GPU_framebuffer_restore();
return ofs;
return ofs.release();
}
void GPU_offscreen_free(GPUOffScreen *offscreen)

View File

@@ -300,6 +300,7 @@ void Immediate::polyline_draw_workaround(uint64_t offset)
int data[3] = {stride, int(imm->vertex_idx), int(offset / 4)};
GPU_shader_uniform_3iv(imm->shader, "gpu_vert_stride_count_offset", data);
GPU_shader_uniform_1b(imm->shader, "gpu_index_no_buffer", true);
GPU_shader_uniform_1i(imm->shader, "gpu_polyline_index_start", 0);
{
/* Setup attributes metadata uniforms. */

View File

@@ -23,6 +23,19 @@ namespace blender {
* (except for the extensions), I chose alphabetical and reverse alphabetical order
*/
static bool initialized = false;
static bool shader_resources_initialized = false;
void GPU_init_shader_resources()
{
if (shader_resources_initialized) {
return;
}
gpu_backend_init_resources();
gpu_shader_dependency_init();
gpu_shader_create_info_init();
GPU_pass_cache_init();
shader_resources_initialized = true;
}
void GPU_init()
{
@@ -31,22 +44,24 @@ void GPU_init()
return;
}
initialized = true;
gpu_backend_init_resources();
gpu_shader_dependency_init();
gpu_shader_create_info_init();
GPU_init_shader_resources();
#ifndef WITH_WEBGL_BACKEND
/* Browser resources are canvas-owned. Compile supported shaders lazily in their draw context. */
GPU_shader_builtin_warm_up();
GPU_pass_cache_init();
#endif
gpu_batch_init();
initialized = true;
}
void GPU_exit()
{
gpu_batch_exit();
if (!shader_resources_initialized) {
return;
}
if (initialized) {
gpu_batch_exit();
}
GPU_pass_cache_free();
@@ -59,6 +74,7 @@ void GPU_exit()
gpu_shader_create_info_exit();
initialized = false;
shader_resources_initialized = false;
}
bool GPU_is_init()

View File

@@ -41,6 +41,9 @@ class QueryPool {
* drawn.
*/
virtual void get_occlusion_result(MutableSpan<uint32_t> r_values) = 0;
/** Nonblocking availability probe; desktop pools retain synchronous behavior. */
virtual bool occlusion_result_ready() { return true; }
};
} // namespace blender::gpu

View File

@@ -10,6 +10,7 @@
*/
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include "GPU_select.hh"
@@ -19,6 +20,10 @@
#include "gpu_select_private.hh"
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
namespace blender {
/* -------------------------------------------------------------------- */
@@ -135,12 +140,24 @@ static void gpu_select_begin_ex(GPUSelectBuffer *buffer,
void GPU_select_begin_next(
GPUSelectBuffer *buffer, const rcti *input, const int radius, GPUSelectMode mode, int oldhits)
{
gpu_select_begin_ex(buffer, input, radius, mode, oldhits, true);
try {
gpu_select_begin_ex(buffer, input, radius, mode, oldhits, true);
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
void GPU_select_begin(GPUSelectBuffer *buffer, const rcti *input, GPUSelectMode mode, int oldhits)
{
gpu_select_begin_ex(buffer, input, 0, mode, oldhits, false);
try {
gpu_select_begin_ex(buffer, input, 0, mode, oldhits, false);
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
bool GPU_select_load_id(uint id)
@@ -166,29 +183,63 @@ bool GPU_select_load_id(uint id)
}
}
GPUSelectQueryAsync *GPU_select_query_submit()
{
if (!g_select_state.select_is_active || g_select_state.algorithm != ALGO_SAMPLE_QUERY) {
throw std::runtime_error("Detached selection requires an active sample query");
}
try {
GPUSelectQueryAsync *query = gpu_select_query_detach();
g_select_state.select_is_active = false;
return query;
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
uint GPU_select_end()
{
uint hits = 0;
switch (g_select_state.algorithm) {
case ALGO_SELECT_NEXT: {
hits = gpu_select_next_end();
break;
}
case ALGO_SAMPLE_QUERY: {
hits = gpu_select_query_end();
break;
}
default: /* ALGO_DEPTH_PICK */
{
hits = gpu_select_pick_end();
break;
}
if (!g_select_state.select_is_active) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: selection is no longer active");
}
try {
uint hits = 0;
g_select_state.select_is_active = false;
switch (g_select_state.algorithm) {
case ALGO_SELECT_NEXT: {
hits = gpu_select_next_end();
break;
}
case ALGO_SAMPLE_QUERY: {
hits = gpu_select_query_end();
break;
}
default: /* ALGO_DEPTH_PICK */
{
hits = gpu_select_pick_end();
break;
}
}
return hits;
#ifdef WITH_WEBGL_BACKEND
/* Includes CPU-cache replay, which never enters the GPU readback interrupt
* checkpoints. The editor's exception boundary rolls back this query's hits. */
if (g_select_state.algorithm != ALGO_SAMPLE_QUERY) {
/* Sample queries check after readback/restoration, before committing their
* result transaction. Do not cancel after releasing that rollback owner. */
gpu::webgl_select_check_interrupt();
}
#endif
g_select_state.select_is_active = false;
return hits;
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
/** \} */
@@ -213,6 +264,9 @@ void GPU_select_cache_begin()
void GPU_select_cache_load_id()
{
if (!GPU_select_cache_revalidate()) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: selection cache context retired");
}
BLI_assert(g_select_state.use_cache == true);
if (g_select_state.algorithm == ALGO_DEPTH_PICK) {
gpu_select_pick_cache_load_id();
@@ -221,9 +275,26 @@ void GPU_select_cache_load_id()
void GPU_select_cache_end()
{
if (g_select_state.algorithm == ALGO_DEPTH_PICK) {
BLI_assert(g_select_state.use_cache == true);
if (g_select_state.algorithm == ALGO_SAMPLE_QUERY && g_select_state.select_is_active) {
/* Query begin/draw/readback can fail before end, including context loss.
* Release the pool and editor result owner before another gesture starts. */
g_select_state.select_is_active = false;
gpu_select_query_cancel();
}
if (g_select_state.algorithm == ALGO_SELECT_NEXT && g_select_state.select_is_active) {
/* A failed draw can leave before GPU_select_end(). The next engine retains
* the editor-owned result buffer until end, so cancellation/context teardown
* must roll back its results and release that reference and the cache flags.
* This is CPU-only and safe after the browser has lost its drawing context. */
gpu_select_next_cancel();
g_select_state.select_is_active = false;
}
if (g_select_state.algorithm == ALGO_DEPTH_PICK &&
(g_select_state.use_cache || g_select_state.select_is_active))
{
/* Cleanup can run both at the failed editor boundary and context teardown. */
gpu_select_pick_cache_end();
g_select_state.select_is_active = false;
}
g_select_state.use_cache = false;
/* Paranoid assignment, should already be false. */
@@ -232,7 +303,24 @@ void GPU_select_cache_end()
bool GPU_select_is_cached()
{
return g_select_state.use_cache && gpu_select_pick_is_cached();
if (!g_select_state.use_cache) {
return false;
}
if (gpu_select_pick_is_cached()) {
return true;
}
/* Retire both the algorithm's CPU allocations and the dispatch flags. The
* View3D caller then redraws instead of replaying IDs from a lost context. */
GPU_select_cache_end();
return false;
}
bool GPU_select_cache_revalidate()
{
/* This delegates to the WebGL-owned lifetime closure used by the pick
* cache. A restored browser context therefore retires stale IDs before a
* native WM frame dispatches its next View3D gesture. */
return GPU_select_is_cached();
}
/** \} */

View File

@@ -8,9 +8,11 @@
* Glue to make the new Select-Next engine work with the old GPU select API.
*/
#include <cfloat>
#include <stdexcept>
#include "BLI_rect.h"
#include "BLI_span.hh"
#include "BLI_utildefines.h"
#include "gpu_select_private.hh"
@@ -19,6 +21,9 @@ namespace blender {
struct GPUSelectNextState {
/** Result buffer set on initialization. */
GPUSelectBuffer *buffer = nullptr;
uint64_t token = 0;
int64_t result_start = 0;
bool published = false;
/** Area of the viewport to render / select from. */
rcti rect = {0, 0, 0, 0};
/** The radius relative to the center of `rect` in which to select. Ignored if 0. */
@@ -30,6 +35,7 @@ struct GPUSelectNextState {
};
static GPUSelectNextState g_state = {};
static uint64_t next_token = 0;
void gpu_select_next_begin(GPUSelectBuffer *buffer,
const rcti *input,
@@ -37,10 +43,24 @@ void gpu_select_next_begin(GPUSelectBuffer *buffer,
GPUSelectMode mode)
{
if (g_state.buffer || !buffer ||
!ELEM(mode, GPU_SELECT_ALL, GPU_SELECT_PICK_ALL, GPU_SELECT_PICK_NEAREST))
{
throw std::runtime_error("Invalid or overlapping native selection transaction");
}
/* Zero always denotes an inactive producer, including after cancellation. */
if (++next_token == 0) {
++next_token;
}
g_state.token = next_token;
g_state.buffer = buffer;
g_state.result_start = buffer->storage.size();
g_state.published = false;
g_state.rect = *input;
g_state.mode = mode;
g_state.radius = radius;
/* A failed/empty draw must not reuse the preceding region's hit count. */
g_state.hits = 0;
}
int2 gpu_select_next_get_pick_area_center()
@@ -58,8 +78,24 @@ int gpu_select_next_get_radius()
return g_state.radius;
}
void gpu_select_next_set_result(GPUSelectResult *hit_buf, uint hit_len)
uint64_t gpu_select_next_get_token()
{
return g_state.token;
}
void gpu_select_next_validate_token(uint64_t token)
{
if (!token || token != g_state.token || !g_state.buffer) {
throw std::runtime_error("Native selection result belongs to a cancelled draw");
}
}
void gpu_select_next_set_result(uint64_t token, GPUSelectResult *hit_buf, uint hit_len)
{
gpu_select_next_validate_token(token);
if (g_state.published || (hit_len && !hit_buf)) {
throw std::runtime_error("Invalid or duplicate native selection result");
}
const int old_size = g_state.buffer->storage.size();
g_state.buffer->storage.resize(old_size + hit_len);
MutableSpan<GPUSelectResult> hit_results = g_state.buffer->storage.as_mutable_span().slice(
@@ -85,11 +121,31 @@ void gpu_select_next_set_result(GPUSelectResult *hit_buf, uint hit_len)
}
g_state.hits = hit_len;
g_state.published = true;
}
uint gpu_select_next_end()
{
return g_state.hits;
gpu_select_next_validate_token(g_state.token);
if (!g_state.published) {
gpu_select_next_cancel();
throw std::runtime_error("Native selection draw ended without a result");
}
const uint hits = g_state.hits;
/* The editor owns this buffer, often on its stack. Do not retain that
* address after the draw transaction, including its exception cleanup. */
g_state = {};
return hits;
}
void gpu_select_next_cancel()
{
/* Preserve entries owned by earlier queries while discarding this draw's
* publication. No GPU access: context-loss cleanup must remain possible. */
if (g_state.buffer && g_state.buffer->storage.size() > g_state.result_start) {
g_state.buffer->storage.resize(g_state.result_start);
}
g_state = {};
}
} // namespace blender

View File

@@ -11,6 +11,11 @@
#include <cfloat>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
#include "GPU_debug.hh"
#include "GPU_framebuffer.hh"
@@ -232,6 +237,9 @@ struct GPUPickState {
GPUSelectBuffer *buffer;
/** Mode of this operation. */
GPUSelectMode mode;
#ifdef WITH_WEBGL_BACKEND
std::function<bool()> context_is_valid;
#endif
/** GPU drawing, never use when `is_cached == true`. */
struct {
@@ -295,10 +303,28 @@ struct GPUPickState {
static GPUPickState g_pick_state{};
static void gpu_select_pick_check_interrupt()
{
#ifdef WITH_WEBGL_BACKEND
gpu::webgl_select_check_interrupt();
if (!g_pick_state.context_is_valid || !g_pick_state.context_is_valid()) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: selection context retired");
}
#endif
}
void gpu_select_pick_begin(GPUSelectBuffer *buffer, const rcti *input, GPUSelectMode mode)
{
GPUPickState *ps = &g_pick_state;
#ifdef WITH_WEBGL_BACKEND
gpu::webgl_select_check_interrupt();
if (!ps->is_cached) {
ps->context_is_valid = gpu::webgl_select_cache_validity_capture();
}
gpu_select_pick_check_interrupt();
#endif
#ifdef DEBUG_PRINT
printf("%s: mode=%d, use_cache=%d, is_cache=%d\n",
__func__,
@@ -331,14 +357,13 @@ void gpu_select_pick_begin(GPUSelectBuffer *buffer, const rcti *input, GPUSelect
* these to have the correct distance information. */
GPU_depth_test(GPU_DEPTH_LESS_EQUAL);
float viewport[4];
GPU_viewport_size_get_f(viewport);
GPU_viewport_size_get_i(ps->viewport);
ps->src.clip_rect = *input;
ps->src.rect_len = rect_len;
ps->gpu.clip_readpixels[0] = int(viewport[0]);
ps->gpu.clip_readpixels[1] = int(viewport[1]);
ps->gpu.clip_readpixels[0] = ps->viewport[0];
ps->gpu.clip_readpixels[1] = ps->viewport[1];
ps->gpu.clip_readpixels[2] = BLI_rcti_size_x(&ps->src.clip_rect);
ps->gpu.clip_readpixels[3] = BLI_rcti_size_y(&ps->src.clip_rect);
@@ -538,6 +563,7 @@ bool gpu_select_pick_load_id(uint id, bool end)
uint gpu_select_pick_end()
{
GPUPickState *ps = &g_pick_state;
gpu_select_pick_check_interrupt();
#ifdef DEBUG_PRINT
printf("%s\n", __func__);
@@ -658,7 +684,16 @@ uint gpu_select_pick_end()
/* Leave sorting up to the caller. */
qsort(depth_data, depth_data_len, sizeof(DepthID), depth_cmp);
g_pick_state.buffer->storage.reserve(g_pick_state.buffer->storage.size() + depth_data_len);
/* Sorting/replay can run while the UI thread cancels the gesture. Do not turn
* an interrupted cached pick into either selection or intentional deselection. */
try {
gpu_select_pick_check_interrupt();
g_pick_state.buffer->storage.reserve(g_pick_state.buffer->storage.size() + depth_data_len);
}
catch (...) {
MEM_delete(depth_data);
throw;
}
for (uint i = 0; i < depth_data_len; i++) {
#ifdef DEBUG_PRINT
printf(" hit: %u: depth %u\n", depth_data[i].id, depth_data[i].depth);
@@ -687,6 +722,7 @@ uint gpu_select_pick_end()
ps->is_cached = true;
}
ps->buffer = nullptr;
return hits;
}
@@ -717,21 +753,46 @@ void gpu_select_pick_cache_end()
g_pick_state.is_cached = false;
g_pick_state.cache.bufs.free_no_destruct();
/* A cancelled read may not reach pick_end. These buffers are not yet in
* the retained cache; release them without reading GPU state or publishing
* hits, including when the browser context has already been lost. */
MEM_SAFE_DELETE(g_pick_state.gpu.rect_depth);
MEM_SAFE_DELETE(g_pick_state.gpu.rect_depth_test);
if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
MEM_SAFE_DELETE(g_pick_state.all.hits);
g_pick_state.all.hits_len = 0;
g_pick_state.all.hits_len_alloc = 0;
}
else if (g_pick_state.mode == GPU_SELECT_PICK_NEAREST) {
MEM_SAFE_DELETE(g_pick_state.nearest.rect_id);
}
g_pick_state.gpu.is_init = false;
g_pick_state.buffer = nullptr;
#ifdef WITH_WEBGL_BACKEND
g_pick_state.context_is_valid = {};
#endif
}
bool gpu_select_pick_is_cached()
{
#ifdef WITH_WEBGL_BACKEND
return g_pick_state.is_cached && g_pick_state.context_is_valid &&
g_pick_state.context_is_valid();
#else
return g_pick_state.is_cached;
#endif
}
void gpu_select_pick_cache_load_id()
{
gpu_select_pick_check_interrupt();
BLI_assert(g_pick_state.is_cached == true);
GPUPickState *ps = &g_pick_state;
#ifdef DEBUG_PRINT
printf("%s (building depth from cache)\n", __func__);
#endif
for (DepthBufCache &rect_depth : ps->cache.bufs) {
gpu_select_pick_check_interrupt();
if (rect_depth.next != nullptr) {
/* We know the buffers differ, but this sub-region may not.
* Double check before adding an id-pass. */
@@ -748,6 +809,7 @@ void gpu_select_pick_cache_load_id()
}
}
}
gpu_select_pick_check_interrupt();
}
/** \} */

View File

@@ -10,6 +10,8 @@
#pragma once
#include <cstdint>
#include "BLI_math_vector_types.hh"
#include "GPU_select.hh"
@@ -37,6 +39,8 @@ void gpu_select_query_begin(GPUSelectBuffer *buffer,
int oldhits);
bool gpu_select_query_load_id(uint id);
uint gpu_select_query_end();
void gpu_select_query_cancel();
GPUSelectQueryAsync *gpu_select_query_detach();
/* gpu_select_next */
@@ -45,6 +49,10 @@ void gpu_select_next_begin(GPUSelectBuffer *buffer,
int radius,
GPUSelectMode mode);
uint gpu_select_next_end();
void gpu_select_next_cancel();
/** Identify the draw transaction across backend readback and context cancellation. */
uint64_t gpu_select_next_get_token();
void gpu_select_next_validate_token(uint64_t token);
/**
* Returns the center relative to the corner of the rect stored in the GPUSelectNextState.
@@ -52,7 +60,7 @@ uint gpu_select_next_end();
int2 gpu_select_next_get_pick_area_center();
GPUSelectMode gpu_select_next_get_mode();
int gpu_select_next_get_radius();
void gpu_select_next_set_result(GPUSelectResult *hit_buf, uint hit_len);
void gpu_select_next_set_result(uint64_t token, GPUSelectResult *hit_buf, uint hit_len);
#define SELECT_ID_NONE ((uint)0xffffffff)

View File

@@ -10,11 +10,16 @@
*/
#include <cstdlib>
#include <functional>
#include <exception>
#include <stdexcept>
#include <utility>
#include "GPU_debug.hh"
#include "GPU_framebuffer.hh"
#include "GPU_select.hh"
#include "GPU_state.hh"
#include "GPU_state_snapshot.hh"
#include "BLI_rect.h"
@@ -25,12 +30,15 @@
#include "gpu_query.hh"
#include "gpu_select_private.hh"
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
namespace blender {
using namespace blender::gpu;
struct GPUSelectQueryState {
struct GPUSelectQueryAsync {
/** Tracks whether a query has been issued so that gpu_load_id can end the previous one. */
bool query_issued;
/** GPU queries abstraction. Contains an array of queries. */
@@ -39,6 +47,10 @@ struct GPUSelectQueryState {
Vector<uint, QUERY_MIN_LEN> *ids;
/** Cache on initialization. */
GPUSelectBuffer *buffer;
GPUSelectBuffer *result_before;
StateSnapshot *pipeline;
std::function<bool()> owner_valid;
bool debug_group;
/** Mode of operation. */
GPUSelectMode mode;
uint index;
@@ -47,18 +59,69 @@ struct GPUSelectQueryState {
/** Previous state to restore after drawing. */
int viewport[4];
int scissor[4];
GPUWriteMask write_mask;
GPUDepthTest depth_test;
};
using GPUSelectQueryState = GPUSelectQueryAsync;
static GPUSelectQueryState g_query_state = {false};
/* Detach the transaction first. Repeated editor/context cleanup must neither
* end another query nor keep a pointer to a destroyed editor result buffer. */
static void gpu_select_query_release(const bool rollback)
{
GPUSelectQueryState state = std::move(g_query_state);
g_query_state = {};
if (rollback && state.buffer && state.result_before) {
std::swap(state.buffer->storage, state.result_before->storage);
}
delete state.queries;
delete state.ids;
delete state.result_before;
delete state.pipeline;
}
static void gpu_select_query_restore()
{
if (g_query_state.owner_valid && !g_query_state.owner_valid()) {
throw std::runtime_error("Native selection query context retired before publication");
}
std::exception_ptr failure;
if (g_query_state.pipeline) {
try { g_query_state.pipeline->restore(); }
catch (...) { failure = std::current_exception(); }
try {
GPU_viewport(UNPACK4(g_query_state.viewport));
GPU_scissor(UNPACK4(g_query_state.scissor));
}
catch (...) { if (!failure) { failure = std::current_exception(); } }
}
if (g_query_state.debug_group) {
g_query_state.debug_group = false;
try { GPU_debug_group_end(); }
catch (...) { if (!failure) { failure = std::current_exception(); } }
}
if (failure) { std::rethrow_exception(failure); }
}
void gpu_select_query_cancel()
{
/* The pool destructor ends only its own live query. No GL restoration is
* attempted against a replacement context; the editor schedules a redraw. */
try { gpu_select_query_restore(); } catch (...) {}
gpu_select_query_release(true);
}
void gpu_select_query_begin(GPUSelectBuffer *buffer,
const rcti *input,
const GPUSelectMode mode,
int oldhits)
{
GPU_debug_group_begin("Selection Queries");
BLI_assert(!g_query_state.buffer);
if (mode == GPU_SELECT_NEAREST_SECOND_PASS &&
(oldhits < 0 || oldhits > buffer->storage.size()))
{
throw std::runtime_error("Selection second pass requires a valid first-pass result range");
}
g_query_state.query_issued = false;
g_query_state.buffer = buffer;
@@ -66,15 +129,20 @@ void gpu_select_query_begin(GPUSelectBuffer *buffer,
g_query_state.index = 0;
g_query_state.oldhits = oldhits;
g_query_state.result_before = new GPUSelectBuffer(*buffer);
#ifdef WITH_WEBGL_BACKEND
g_query_state.owner_valid = webgl_select_cache_validity_capture();
#endif
GPU_scissor_get(g_query_state.scissor);
GPU_viewport_size_get_i(g_query_state.viewport);
g_query_state.pipeline = new StateSnapshot();
GPU_debug_group_begin("Selection Queries");
g_query_state.debug_group = true;
g_query_state.ids = new Vector<uint, QUERY_MIN_LEN>();
g_query_state.queries = GPUBackend::get()->querypool_alloc();
g_query_state.queries->init(GPU_QUERY_OCCLUSION);
g_query_state.write_mask = GPU_write_mask_get();
g_query_state.depth_test = GPU_depth_test_get();
GPU_scissor_get(g_query_state.scissor);
GPU_viewport_size_get_i(g_query_state.viewport);
/* Write to color buffer. Seems to fix issues with selecting alpha blended geom (see #7997). */
GPU_color_mask(true, true, true, true);
@@ -113,10 +181,11 @@ bool gpu_select_query_load_id(uint id)
{
if (g_query_state.query_issued) {
g_query_state.queries->end_query();
g_query_state.query_issued = false;
}
g_query_state.queries->begin_query();
g_query_state.ids->append(id);
g_query_state.queries->begin_query();
g_query_state.query_issued = true;
if (g_query_state.mode == GPU_SELECT_NEAREST_SECOND_PASS) {
@@ -134,48 +203,95 @@ bool gpu_select_query_load_id(uint id)
return true;
}
GPUSelectQueryAsync *gpu_select_query_detach()
{
if (g_query_state.query_issued) {
g_query_state.queries->end_query();
g_query_state.query_issued = false;
}
gpu_select_query_restore();
delete g_query_state.pipeline;
g_query_state.pipeline = nullptr;
auto *query = new GPUSelectQueryAsync(std::move(g_query_state));
g_query_state = {};
return query;
}
void GPU_select_query_dispose(GPUSelectQueryAsync *&query)
{
if (!query) { return; }
/* No restoration: a later WM frame owns the current drawing state. */
delete query->queries;
delete query->ids;
delete query->result_before;
delete query->pipeline;
delete query;
query = nullptr;
}
static uint gpu_select_query_publish(GPUSelectQueryAsync &state, Span<uint32_t> result)
{
uint hits = 0;
for (int i = 0; i < result.size(); i++) {
if (result[i] == 0) { continue; }
if (state.mode != GPU_SELECT_NEAREST_SECOND_PASS) {
state.buffer->storage.append({(*state.ids)[i], 0xFFFF});
hits++;
}
else {
for (int j = 0; j < state.oldhits; j++) {
if (state.buffer->storage[j].id == (*state.ids)[i]) {
state.buffer->storage[j].depth = 0;
}
}
break;
}
}
return hits;
}
bool GPU_select_query_poll(GPUSelectQueryAsync *query, uint &r_hits)
{
if (!query || !query->queries || (query->owner_valid && !query->owner_valid())) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: detached query owner retired");
}
if (!query->queries->occlusion_result_ready()) { return false; }
Vector<uint32_t, QUERY_MIN_LEN> result(query->ids->size());
query->queries->get_occlusion_result(result);
#ifdef WITH_WEBGL_BACKEND
webgl_select_check_interrupt();
#endif
try { r_hits = gpu_select_query_publish(*query, result); }
catch (...) {
std::swap(query->buffer->storage, query->result_before->storage);
throw;
}
return true;
}
uint gpu_select_query_end()
{
uint hits = 0;
if (g_query_state.query_issued) {
g_query_state.queries->end_query();
g_query_state.query_issued = false;
}
Span<uint> ids = *g_query_state.ids;
Vector<uint32_t, QUERY_MIN_LEN> result(ids.size());
g_query_state.queries->get_occlusion_result(result);
for (int i = 0; i < result.size(); i++) {
if (result[i] != 0) {
if (g_query_state.mode != GPU_SELECT_NEAREST_SECOND_PASS) {
GPUSelectResult hit_result{};
hit_result.id = ids[i];
hit_result.depth = 0xFFFF;
g_query_state.buffer->storage.append(hit_result);
hits++;
}
else {
int j;
/* search in buffer and make selected object first */
for (j = 0; j < g_query_state.oldhits; j++) {
if (g_query_state.buffer->storage[j].id == ids[i]) {
g_query_state.buffer->storage[j].depth = 0;
}
}
break;
}
}
}
/* Restore and check cancellation before publishing either appended IDs or
* the second-pass changes to existing depths. Cancel retains a full backup. */
gpu_select_query_restore();
#ifdef WITH_WEBGL_BACKEND
webgl_select_check_interrupt();
#endif
delete g_query_state.queries;
delete g_query_state.ids;
hits = gpu_select_query_publish(g_query_state, result);
GPU_write_mask(g_query_state.write_mask);
GPU_depth_test(g_query_state.depth_test);
GPU_viewport(UNPACK4(g_query_state.viewport));
GPU_debug_group_end();
gpu_select_query_release(false);
return hits;
}

View File

@@ -29,6 +29,7 @@
#include "gpu_shader_metadata_private.hh"
#include "gpu_shader_private.hh"
#include <filesystem>
#include <string>
@@ -220,7 +221,15 @@ gpu::Shader *GPU_shader_create_from_info_name(const char *info_name)
std::cerr << "Warning: Trying to compile \"" << info.name_
<< "\" which was not marked for static compilation.\n";
}
return GPU_shader_create_from_info(_info);
gpu::Shader *shader = GPU_shader_create_from_info(_info);
#ifdef WITH_WEBGL_BACKEND
/* Native draw callers assume builtin compilation succeeds. Propagate an
* unsupported browser shader to the frame boundary before they dereference it. */
if (!shader) {
throw std::runtime_error(std::string("Blender WebGL shader unavailable: ") + info_name);
}
#endif
return shader;
}
gpu::Shader *GPU_shader_create_from_info(const GPUShaderCreateInfo *_info)
@@ -387,6 +396,12 @@ void GPU_shader_bind(gpu::Shader *gpu_shader,
Context *ctx = Context::get();
#ifdef WITH_WEB
/* WebGPU compilation, specialization and uniform setup may throw. Do not
* cache a failed binding: the next region redraw must retry the complete
* native bind even when it selects this same shader. */
try {
#endif
if (ctx->shader != shader) {
ctx->shader = shader;
shader->bind(constants_state);
@@ -412,6 +427,13 @@ void GPU_shader_bind(gpu::Shader *gpu_shader,
GPU_storagebuf_bind(ctx->printf_buf.last(), GPU_SHADER_PRINTF_SLOT);
}
#endif
#ifdef WITH_WEB
}
catch (...) {
ctx->shader = nullptr;
throw;
}
#endif
}
void GPU_shader_unbind()
@@ -806,7 +828,9 @@ Shader *ShaderCompiler::compile(const shader::ShaderCreateInfo &orig_info, bool
CLOG_DEBUG(&LOG, "Compiling Shader \"%s\"", orig_info.name_.c_str());
Shader *shader = GPUBackend::get()->shader_alloc(orig_info.name_.c_str());
/* Backend context loss and source generation can fail before finalize. Retain ownership until
* compilation succeeds, including the create-info error return below. */
std::unique_ptr<Shader> shader(GPUBackend::get()->shader_alloc(orig_info.name_.c_str()));
ShaderCreateInfo specialized_info = orig_info;
@@ -974,8 +998,7 @@ Shader *ShaderCompiler::compile(const shader::ShaderCreateInfo &orig_info, bool
}
if (!shader->finalize(&info)) {
delete shader;
shader = nullptr;
shader.reset();
}
if (Context::get()) {
@@ -994,7 +1017,7 @@ Shader *ShaderCompiler::compile(const shader::ShaderCreateInfo &orig_info, bool
end_time.time_since_epoch().count());
}
return shader;
return shader.release();
}
static ThreadQueueWorkPriority to_work_priority(CompilationPriority priority)

View File

@@ -242,8 +242,8 @@ struct GPUSource {
shader::PrintfFormat::Block::ArgumentType type =
shader::PrintfFormat::Block::ArgumentType::NONE;
int64_t start = 0, end = 0, cursor = -1;
while ((end = format.find_first_of('%', cursor + 1)) != -1) {
size_t start = 0, end = 0, cursor = std::string::npos;
while ((end = format.find_first_of('%', cursor + 1)) != std::string::npos) {
if (end - start > 0) {
/* Add the previous block without the newly found % character. */
fmt.format_blocks.append({type, format.substr(start, end - start)});

View File

@@ -17,6 +17,16 @@
#include "BLI_utildefines.h"
#include "GPU_state.hh"
#include "GPU_state_snapshot.hh"
#include <exception>
#include <stdexcept>
#include <functional>
#include "GPU_framebuffer.hh"
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
#include "gpu_backend.hh"
#include "gpu_context_private.hh"
@@ -27,6 +37,93 @@ namespace blender {
using namespace blender::gpu;
struct gpu::ResourceBindingSnapshot::Data {
Context *context;
std::function<void()> resume;
};
gpu::ResourceBindingSnapshot::ResourceBindingSnapshot()
: data_(std::make_unique<Data>(Data{Context::get(), {}}))
{
#ifdef WITH_WEBGL_BACKEND
data_->resume = webgl_resource_state_capture();
#endif
}
gpu::ResourceBindingSnapshot::~ResourceBindingSnapshot() = default;
void gpu::ResourceBindingSnapshot::restore() const
{
if (Context::get() != data_->context) {
throw std::runtime_error("GPU resource bindings restored in a different context");
}
if (data_->resume) { data_->resume(); }
}
struct gpu::StateSnapshot::Data {
Context *context;
GPUState state;
GPUStateMutable mutable_state;
FrameBuffer *framebuffer;
bool scissor_test;
std::function<void()> resume_framebuffer;
ResourceBindingSnapshot resources;
};
gpu::StateSnapshot::StateSnapshot()
{
Context *context = Context::get();
data_.reset(new Data{context,
context->state_manager->state,
context->state_manager->mutable_state,
context->active_fb,
context->active_fb->scissor_test_get(),
{},
{}});
#ifdef WITH_WEBGL_BACKEND
data_->resume_framebuffer = webgl_framebuffer_state_capture(context->active_fb);
#endif
}
gpu::StateSnapshot::~StateSnapshot() = default;
void gpu::StateSnapshot::restore() const
{
if (Context::get() != data_->context) {
throw std::runtime_error("GPU pipeline state restored in a different context");
}
/* Restore the native desired state, not raw GL state behind its cache. This
* includes masks, blending, stencil ops/reference, clipping, culling, FIRST,
* point size and line width. The next backend draw applies these values. */
data_->context->state_manager->state = data_->state;
data_->context->state_manager->mutable_state = data_->mutable_state;
data_->framebuffer->scissor_test_set(data_->scissor_test);
}
void gpu::StateSnapshot::restore_framebuffer() const
{
if (Context::get() != data_->context) {
throw std::runtime_error("GPU framebuffer state restored in a different context");
}
/* Restore resources even if framebuffer recovery fails; never leave the
* auxiliary shader/selection bindings installed while unwinding. */
std::exception_ptr failure;
try {
if (data_->resume_framebuffer) {
data_->resume_framebuffer();
}
else {
GPU_framebuffer_bind(data_->framebuffer);
}
}
catch (...) { failure = std::current_exception(); }
try {
data_->resources.restore();
}
catch (...) { if (!failure) { failure = std::current_exception(); } }
if (failure) { std::rethrow_exception(failure); }
}
#define SET_STATE(_prefix, _state, _value) \
do { \
StateManager *stack = Context::get()->state_manager; \
@@ -260,6 +357,11 @@ void GPU_scissor_get(int coords[4])
Context::get()->active_fb->scissor_get(coords);
}
bool GPU_polygon_smooth_get()
{
return bool(Context::get()->state_manager->state.polygon_smooth);
}
void GPU_viewport_size_get_f(float coords[4])
{
int viewport[4];

View File

@@ -8,6 +8,8 @@
#include "BLI_string.h"
#include <memory>
#include "DNA_userdef_types.h"
#include "GPU_framebuffer.hh"
@@ -264,7 +266,7 @@ static inline gpu::Texture *gpu_texture_create(const char *name,
eGPUDataFormat data_format = GPU_DATA_FLOAT)
{
BLI_assert(mip_len > 0);
Texture *tex = GPUBackend::get()->texture_alloc(name);
std::unique_ptr<Texture> tex(GPUBackend::get()->texture_alloc(name));
tex->usage_set(usage);
bool success = false;
@@ -289,13 +291,12 @@ static inline gpu::Texture *gpu_texture_create(const char *name,
}
if (!success) {
delete tex;
return nullptr;
}
if (pixels) {
tex->update(data_format, pixels);
}
return reinterpret_cast<gpu::Texture *>(tex);
return tex.release();
}
gpu::Texture *GPU_texture_create_1d(const char *name,
@@ -478,7 +479,7 @@ gpu::Texture *GPU_texture_create_view(const char *name,
"Source texture of TextureView must have GPU_TEXTURE_USAGE_FORMAT_VIEW usage "
"flag if view texture format is different.");
Texture *view = GPUBackend::get()->texture_alloc(name);
view->init_view(source_texture,
if (!view->init_view(source_texture,
view_format,
source_texture->type_get(),
mip_start,
@@ -486,7 +487,11 @@ gpu::Texture *GPU_texture_create_view(const char *name,
layer_start,
layer_len,
cube_as_array,
use_stencil);
use_stencil))
{
delete view;
return nullptr;
}
/* On integer textures, disable filtering by default, as this is not guaranteed to be
* consistently supported across backends. */

View File

@@ -18,6 +18,12 @@
#include "fmt/format.h"
#ifdef __EMSCRIPTEN__
# include "BLI_memory_utils.hh"
# include "../webgl/webgl_texture.hh"
# include <stdexcept>
#endif
namespace blender::gpu {
TexturePool &TexturePool::get()
@@ -51,6 +57,24 @@ Texture *TexturePoolImpl::acquire_texture_impl(int3 extent,
/* TODO(not_mark): this flag can likely be removed from TexturePoolImpl entirely. */
usage |= GPU_TEXTURE_USAGE_FORMAT_VIEW;
#ifdef __EMSCRIPTEN__
/* GP returns mask/layer/depth attachments after every draw. Browser restoration
* keeps their descriptors and this pool alive, but destroys their GL storage.
* Only idle owners can be discarded here; acquired owners still belong to the
* native caller. Pool contents are undefined on acquire, so allocate normally
* and let the original mask/depth passes initialize the replacement. */
const auto context = emscripten_webgl_get_current_context();
if (!Context::get() || context <= 0 || emscripten_is_webgl_context_lost(context)) {
throw std::runtime_error("Native texture pool acquisition requires a live WebGL context");
}
for (int64_t i = pool_.size() - 1; i >= 0; i--) {
if (!webgl_texture_has_live_storage(pool_[i].texture)) {
GPU_texture_free(pool_[i].texture);
pool_.remove_and_reorder(i);
}
}
#endif
/* Search pool for compatible available texture first. */
int64_t match_index = -1;
for (uint64_t i : pool_.index_range()) {
@@ -95,6 +119,15 @@ Texture *TexturePoolImpl::acquire_texture_impl(int3 extent,
/* Otherwise, allocate a new texture of the specified type. */
TextureHandle handle = {GPUBackend::get()->texture_alloc(name_str.c_str())};
#ifdef __EMSCRIPTEN__
/* Failed allocation must not enter acquired_ or leak an unowned texture.
* The GP caller can then release the other attachments and retry as a group. */
BLI_SCOPED_DEFER([&]() {
if (handle.texture) {
GPU_texture_free(handle.texture);
}
});
#endif
handle.texture->usage_set(usage);
bool init_result = false;
switch (type) {
@@ -117,11 +150,22 @@ Texture *TexturePoolImpl::acquire_texture_impl(int3 extent,
BLI_assert_unreachable();
break;
}
#ifdef __EMSCRIPTEN__
if (!init_result || !webgl_texture_has_live_storage(handle.texture)) {
throw std::runtime_error("Native WebGL pooled texture allocation failed");
}
#endif
UNUSED_VARS_NDEBUG(init_result);
BLI_assert(init_result);
acquired_.add(handle);
#ifdef __EMSCRIPTEN__
Texture *texture = handle.texture;
handle.texture = nullptr;
return texture;
#else
return handle.texture;
#endif
} // namespace blender::gpu
void TexturePoolImpl::release_texture(Texture *tex)

View File

@@ -9,6 +9,8 @@
*/
#include <cstring>
#include <memory>
#include <stdexcept>
#include "BLI_math_vector.h"
#include "BLI_math_vector_types.hh"
@@ -29,6 +31,10 @@
#include "GPU_texture.hh"
#include "GPU_viewport.hh"
#ifdef __EMSCRIPTEN__
# include "../webgl/webgl_texture.hh"
#endif
#include "DRW_engine.hh"
#include "MEM_guardedalloc.h"
@@ -94,6 +100,24 @@ enum {
GPU_VIEWPORT_STEREO = (1 << 1),
};
#ifdef __EMSCRIPTEN__
static bool gpu_viewport_has_live_textures(const GPUViewport *viewport)
{
if (!gpu::webgl_texture_has_live_storage(viewport->depth_tx)) {
return false;
}
const int views = (viewport->flag & GPU_VIEWPORT_STEREO) ? 2 : 1;
for (int view = 0; view < views; view++) {
if (!gpu::webgl_texture_has_live_storage(viewport->color_render_tx[view]) ||
!gpu::webgl_texture_has_live_storage(viewport->color_overlay_tx[view]))
{
return false;
}
}
return true;
}
#endif
void GPU_viewport_tag_update(GPUViewport *viewport)
{
viewport->flag |= DO_UPDATE;
@@ -103,6 +127,11 @@ bool GPU_viewport_do_update(GPUViewport *viewport)
{
bool ret = (viewport->flag & DO_UPDATE);
viewport->flag &= ~DO_UPDATE;
#ifdef __EMSCRIPTEN__
/* A restored canvas can have the same dimensions and no pending scene edits.
* Ask WM to draw before it composites retained, but lost, region textures. */
ret |= !gpu_viewport_has_live_textures(viewport);
#endif
return ret;
}
@@ -146,6 +175,12 @@ static void gpu_viewport_textures_create(GPUViewport *viewport)
viewport->color_overlay_tx[0] = GPU_texture_create_2d(
"dtxl_color_overlay", UNPACK2(size), 1, gpu::TextureFormat::SRGBA_8_8_8_8, usage, nullptr);
#ifdef __EMSCRIPTEN__
if (!viewport->color_render_tx[0] || !viewport->color_overlay_tx[0]) {
throw std::runtime_error("WebGL viewport color attachment allocation failed");
}
#endif
GPU_texture_clear(viewport->color_render_tx[0], GPU_DATA_FLOAT, empty_pixel);
GPU_texture_clear(viewport->color_overlay_tx[0], GPU_DATA_FLOAT, empty_pixel);
}
@@ -164,6 +199,12 @@ static void gpu_viewport_textures_create(GPUViewport *viewport)
usage,
nullptr);
#ifdef __EMSCRIPTEN__
if (!viewport->color_render_tx[1] || !viewport->color_overlay_tx[1]) {
throw std::runtime_error("WebGL stereo viewport attachment allocation failed");
}
#endif
GPU_texture_clear(viewport->color_render_tx[1], GPU_DATA_FLOAT, empty_pixel);
GPU_texture_clear(viewport->color_overlay_tx[1], GPU_DATA_FLOAT, empty_pixel);
}
@@ -179,12 +220,23 @@ static void gpu_viewport_textures_create(GPUViewport *viewport)
usage | GPU_TEXTURE_USAGE_HOST_READ |
GPU_TEXTURE_USAGE_FORMAT_VIEW,
nullptr);
#ifdef __EMSCRIPTEN__
if (!viewport->depth_tx) {
throw std::runtime_error("WebGL viewport depth attachment allocation failed");
}
#endif
const float depth_clear = 0.0f;
GPU_texture_clear(viewport->depth_tx, GPU_DATA_FLOAT, &depth_clear);
}
if (!viewport->depth_tx || !viewport->color_render_tx[0] || !viewport->color_overlay_tx[0]) {
#ifdef __EMSCRIPTEN__
/* The caller owns this viewport. Freeing it in a void allocation helper
* leaves offscreen render callers with a dangling pointer. */
throw std::runtime_error("WebGL viewport attachment allocation failed");
#else
GPU_viewport_free(viewport);
#endif
}
}
@@ -211,11 +263,33 @@ void GPU_viewport_bind(GPUViewport *viewport, int view, const rcti *rect)
DRW_gpu_context_enable();
#ifdef __EMSCRIPTEN__
try {
/* GP placement queries bind through WM before the next regular redraw.
* Restore the whole region target here, before DRW borrows its depth owner.
* Keep DRWData and the original scene/cache producers; only pixels were lost. */
if (viewport->size != rect_size || !gpu_viewport_has_live_textures(viewport)) {
copy_v2_v2_int(viewport->size, rect_size);
gpu_viewport_textures_free(viewport);
gpu_viewport_textures_create(viewport);
GPU_viewport_tag_update(viewport);
}
}
catch (...) {
/* No partial stereo/color/depth set may survive an allocation or clear
* failure. The next bind retries even though size already matches. */
gpu_viewport_textures_free(viewport);
GPU_viewport_tag_update(viewport);
DRW_gpu_context_disable();
throw;
}
#else
if (viewport->size != rect_size) {
copy_v2_v2_int(viewport->size, rect_size);
gpu_viewport_textures_free(viewport);
gpu_viewport_textures_create(viewport);
}
#endif
viewport->active_view = view;
}
@@ -239,6 +313,7 @@ void GPU_viewport_bind_from_offscreen(GPUViewport *viewport, GPUOffScreen *ofs,
/* This is the only texture we can share. */
viewport->depth_tx = depth;
if (depth) { GPU_texture_ref(depth); }
gpu_viewport_textures_create(viewport);
}
@@ -291,6 +366,11 @@ void GPU_viewport_stereo_composite(GPUViewport *viewport, Stereo3dFormat *stereo
* done from a single viewport. See `wm_stereo.cc`. */
return;
}
#ifdef __EMSCRIPTEN__
if (!gpu_viewport_has_live_textures(viewport)) {
throw std::runtime_error("Browser region requires redraw before stereo composition");
}
#endif
/* The composite framebuffer object needs to be created in the window context. */
GPU_framebuffer_ensure_config(
&viewport->stereo_comp_fb,
@@ -461,7 +541,22 @@ static void gpu_viewport_draw_colormanaged(GPUViewport *viewport,
viewport->dither,
false,
do_overlay_merge);
#ifdef __EMSCRIPTEN__
/* A requested native display transform must not become a successful
* untransformed preview when OCIO shader/resource construction fails. */
if (!use_ocio) {
throw std::runtime_error("Native viewport composition: OCIO display transform is unavailable");
}
#endif
}
auto release_composition = [&](GPUViewport *) {
/* Run all cleanup even if context loss prevents one unbind. */
try { GPU_texture_unbind(color); } catch (...) {}
try { GPU_texture_unbind(color_overlay); } catch (...) {}
try { if (use_ocio) { IMB_colormanagement_finish_glsl_draw(); } } catch (...) {}
};
std::unique_ptr<GPUViewport, decltype(release_composition)> composition_scope(
viewport, release_composition);
gpu::Batch *batch = gpu_viewport_batch_get(viewport, rect_pos, rect_uv);
if (use_ocio) {
@@ -477,12 +572,6 @@ static void gpu_viewport_draw_colormanaged(GPUViewport *viewport,
GPU_texture_bind(color, 0);
GPU_texture_bind(color_overlay, 1);
GPU_batch_draw(batch);
GPU_texture_unbind(color);
GPU_texture_unbind(color_overlay);
if (use_ocio) {
IMB_colormanagement_finish_glsl_draw();
}
}
void GPU_viewport_draw_to_screen_ex(GPUViewport *viewport,
@@ -547,6 +636,8 @@ void GPU_viewport_unbind_from_offscreen(GPUViewport *viewport,
bool do_overlay_merge)
{
const int view = 0;
auto release_depth = [](GPUViewport *view) { GPU_TEXTURE_FREE_SAFE(view->depth_tx); };
std::unique_ptr<GPUViewport, decltype(release_depth)> depth_scope(viewport, release_depth);
if (viewport->color_render_tx[view] == nullptr) {
return;
@@ -570,8 +661,8 @@ void GPU_viewport_unbind_from_offscreen(GPUViewport *viewport,
gpu_viewport_draw_colormanaged(
viewport, view, &pos_rect, &uv_rect, display_colorspace, do_overlay_merge);
/* This one is from the offscreen. Don't free it with the viewport. */
viewport->depth_tx = nullptr;
/* Release the reference acquired by bind_from_offscreen on success, early
* return or a backend exception; the offscreen keeps its original reference. */
}
void GPU_viewport_unbind(GPUViewport * /*viewport*/)