From ca2fb1eb682cea3fb72db6b0a73025077af8b90a Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sun, 29 Mar 2026 15:36:19 -0600 Subject: [PATCH] [gpu] Share demo_view between WebGL and WebGPU web demos Refactor demo_view to work without GLFW (guarded by HB_GPU_NO_GLFW): - Add demo_view_create_headless() for non-GLFW use - Store fb/window dimensions in the view struct - Use emscripten_get_now() for timing when on Emscripten - Guard GLFW-specific calls (fullscreen, window close, cursor query) Rewrite WebGPU entry point to use demo_view and demo_renderer_t interface instead of duplicated view/input code. This gives the WebGPU demo identical trackball rotation, drag-release animation, keyboard shortcuts, and gamma cycling as the GL demos. Co-Authored-By: Claude Opus 4.6 (1M context) --- util/gpu/demo-renderer.h | 2 + util/gpu/demo-view.cc | 67 ++- util/gpu/demo-view.h | 7 + util/gpu/web/build-webgpu.sh | 2 + util/gpu/web/gl-stub.h | 35 ++ util/gpu/web/hb-gpu-web-webgpu.cc | 845 ++++++++++++------------------ 6 files changed, 442 insertions(+), 516 deletions(-) diff --git a/util/gpu/demo-renderer.h b/util/gpu/demo-renderer.h index fb594603c..0a1e34cf4 100644 --- a/util/gpu/demo-renderer.h +++ b/util/gpu/demo-renderer.h @@ -38,6 +38,7 @@ struct demo_renderer_t }; +#ifndef HB_GPU_NO_GLFW demo_renderer_t * demo_renderer_create_gl (GLFWwindow *window); @@ -45,6 +46,7 @@ demo_renderer_create_gl (GLFWwindow *window); demo_renderer_t * demo_renderer_create_metal (GLFWwindow *window); #endif +#endif #endif /* DEMO_RENDERER_H */ diff --git a/util/gpu/demo-view.cc b/util/gpu/demo-view.cc index 75cfefba7..2169d65dc 100644 --- a/util/gpu/demo-view.cc +++ b/util/gpu/demo-view.cc @@ -5,12 +5,22 @@ #include "demo-view.h" +#ifdef __EMSCRIPTEN__ +#include +#endif + #include "trackball.hh" #include "matrix4x4.hh" struct demo_view_t { demo_renderer_t *renderer; +#ifndef HB_GPU_NO_GLFW GLFWwindow *window; +#endif + + /* Cached window/framebuffer dimensions */ + int fb_width, fb_height; + int win_width, win_height; /* Output */ bool vsync; @@ -59,6 +69,7 @@ struct demo_view_t { int height; }; +#ifndef HB_GPU_NO_GLFW demo_view_t * demo_view_create (demo_renderer_t *renderer, GLFWwindow *window) { @@ -71,6 +82,25 @@ demo_view_create (demo_renderer_t *renderer, GLFWwindow *window) return vu; } +#endif + +demo_view_t * +demo_view_create_headless (demo_renderer_t *renderer, + int fb_width, int fb_height, + int win_width, int win_height) +{ + demo_view_t *vu = (demo_view_t *) calloc (1, sizeof (demo_view_t)); + + vu->renderer = renderer; + vu->fb_width = fb_width; + vu->fb_height = fb_height; + vu->win_width = win_width; + vu->win_height = win_height; + vu->needs_redraw = true; + demo_view_reset (vu); + + return vu; +} void demo_view_destroy (demo_view_t *vu) @@ -156,7 +186,11 @@ demo_view_apply_transform (demo_view_t *vu, float *mat, int width, int height) static double current_time (void) { +#ifdef __EMSCRIPTEN__ + return emscripten_get_now () / 1000.0; +#else return glfwGetTime (); +#endif } static void @@ -237,9 +271,11 @@ demo_view_toggle_dark (demo_view_t *vu) vu->needs_redraw = true; } +#ifndef HB_GPU_NO_GLFW static void demo_view_toggle_fullscreen (demo_view_t *vu) { + if (!vu->window) return; vu->fullscreen = !vu->fullscreen; if (vu->fullscreen) { glfwGetWindowPos (vu->window, &vu->x, &vu->y); @@ -251,12 +287,17 @@ demo_view_toggle_fullscreen (demo_view_t *vu) glfwSetWindowMonitor (vu->window, NULL, vu->x, vu->y, vu->width, vu->height, 0); } } +#endif void demo_view_reshape_func (demo_view_t *vu, int width, int height) { + vu->fb_width = width; + vu->fb_height = height; + vu->win_width = width; + vu->win_height = height; vu->needs_redraw = true; } @@ -326,7 +367,10 @@ demo_view_key_func (demo_view_t *vu, int key, int scancode, int action, int mods { case GLFW_KEY_ESCAPE: case GLFW_KEY_Q: - glfwSetWindowShouldClose (vu->window, GLFW_TRUE); +#ifndef HB_GPU_NO_GLFW + if (vu->window) + glfwSetWindowShouldClose (vu->window, GLFW_TRUE); +#endif break; case GLFW_KEY_SPACE: @@ -346,9 +390,11 @@ demo_view_key_func (demo_view_t *vu, int key, int scancode, int action, int mods demo_view_toggle_vsync (vu); break; +#ifndef HB_GPU_NO_GLFW case GLFW_KEY_F: demo_view_toggle_fullscreen (vu); break; +#endif case GLFW_KEY_R: demo_view_reset (vu); @@ -383,7 +429,10 @@ demo_view_mouse_func (demo_view_t *vu, int button, int action, int mods) vu->buttons &= ~(1 << button); vu->modifiers = mods; - glfwGetCursorPos (vu->window, &vu->cursorx, &vu->cursory); +#ifndef HB_GPU_NO_GLFW + if (vu->window) + glfwGetCursorPos (vu->window, &vu->cursorx, &vu->cursory); +#endif double x = vu->cursorx, y = vu->cursory; switch (button) @@ -452,8 +501,11 @@ demo_view_motion_func (demo_view_t *vu, double x, double y) return; } - int width, height; - glfwGetWindowSize (vu->window, &width, &height); + int width = vu->win_width, height = vu->win_height; +#ifndef HB_GPU_NO_GLFW + if (vu->window) + glfwGetWindowSize (vu->window, &width, &height); +#endif if (vu->buttons & (1 << GLFW_MOUSE_BUTTON_LEFT)) { @@ -564,8 +616,11 @@ demo_view_display (demo_view_t *vu, demo_buffer_t *buffer) } } - int width, height; - glfwGetFramebufferSize (vu->window, &width, &height); + int width = vu->fb_width, height = vu->fb_height; +#ifndef HB_GPU_NO_GLFW + if (vu->window) + glfwGetFramebufferSize (vu->window, &width, &height); +#endif float mat[16]; diff --git a/util/gpu/demo-view.h b/util/gpu/demo-view.h index 8cb006802..e39bdbb10 100644 --- a/util/gpu/demo-view.h +++ b/util/gpu/demo-view.h @@ -13,8 +13,15 @@ typedef struct demo_view_t demo_view_t; +#ifndef HB_GPU_NO_GLFW demo_view_t * demo_view_create (demo_renderer_t *renderer, GLFWwindow *window); +#endif + +demo_view_t * +demo_view_create_headless (demo_renderer_t *renderer, + int fb_width, int fb_height, + int win_width, int win_height); void demo_view_destroy (demo_view_t *vu); diff --git a/util/gpu/web/build-webgpu.sh b/util/gpu/web/build-webgpu.sh index 3bdb312f8..0c6c2737b 100755 --- a/util/gpu/web/build-webgpu.sh +++ b/util/gpu/web/build-webgpu.sh @@ -18,11 +18,13 @@ em++ \ -DHB_NO_MT \ -DHAVE_ROUND \ -DHB_HAS_GPU \ + -DHB_GPU_NO_GLFW \ -include gl-stub.h \ "$SRCDIR/src/harfbuzz-world.cc" \ "$SRCDIR/util/gpu/demo-atlas.cc" \ "$SRCDIR/util/gpu/demo-buffer.cc" \ "$SRCDIR/util/gpu/demo-font.cc" \ + "$SRCDIR/util/gpu/demo-view.cc" \ "$SRCDIR/util/gpu/web/hb-gpu-web-webgpu.cc" \ --use-port=emdawnwebgpu \ -sALLOW_MEMORY_GROWTH=1 \ diff --git a/util/gpu/web/gl-stub.h b/util/gpu/web/gl-stub.h index 14c244ce3..abf393747 100644 --- a/util/gpu/web/gl-stub.h +++ b/util/gpu/web/gl-stub.h @@ -52,4 +52,39 @@ static inline GLint glGetUniformLocation (GLuint, const GLchar *) { return 0; } static inline void glUniform1i (GLint, GLint) {} static inline GLenum glGetError () { return 0; } +/* GLFW type and constant stubs */ +typedef void GLFWwindow; + +#define GLFW_RELEASE 0 +#define GLFW_PRESS 1 +#define GLFW_REPEAT 2 +#define GLFW_TRUE 1 +#define GLFW_FALSE 0 + +#define GLFW_MOD_SHIFT 0x0001 + +#define GLFW_MOUSE_BUTTON_1 0 +#define GLFW_MOUSE_BUTTON_2 1 +#define GLFW_MOUSE_BUTTON_3 2 +#define GLFW_MOUSE_BUTTON_LEFT 0 +#define GLFW_MOUSE_BUTTON_RIGHT 1 +#define GLFW_MOUSE_BUTTON_MIDDLE 2 + +#define GLFW_KEY_SPACE 32 +#define GLFW_KEY_SLASH 47 +#define GLFW_KEY_0 48 +#define GLFW_KEY_9 57 +#define GLFW_KEY_A 65 +#define GLFW_KEY_B 66 +#define GLFW_KEY_F 70 +#define GLFW_KEY_G 71 +#define GLFW_KEY_Q 81 +#define GLFW_KEY_R 82 +#define GLFW_KEY_V 86 +#define GLFW_KEY_ESCAPE 256 +#define GLFW_KEY_RIGHT 262 +#define GLFW_KEY_LEFT 263 +#define GLFW_KEY_DOWN 264 +#define GLFW_KEY_UP 265 + #endif /* GL_STUB_H */ diff --git a/util/gpu/web/hb-gpu-web-webgpu.cc b/util/gpu/web/hb-gpu-web-webgpu.cc index 3140add71..ee10f588f 100644 --- a/util/gpu/web/hb-gpu-web-webgpu.cc +++ b/util/gpu/web/hb-gpu-web-webgpu.cc @@ -27,8 +27,8 @@ /* * WebGPU web demo. * - * Uses Emscripten WebGPU bindings (-sUSE_WEBGPU=1) instead of WebGL. - * Does not use GLFW; input is handled via Emscripten HTML5 APIs. + * Uses Emscripten WebGPU bindings instead of WebGL. + * Uses demo_view for input/view (with HB_GPU_NO_GLFW). */ #include @@ -44,17 +44,14 @@ #include #include -/* Math helpers — no GL dependency */ -#include "../trackball.hh" -#include "../matrix4x4.hh" - -/* Font/buffer infrastructure needs GL type stubs */ +/* GL type stubs for headers */ #include "gl-stub.h" -/* Now we can include the demo headers for shaping */ #include "../demo-common.h" #include "../demo-font.h" #include "../demo-buffer.h" +#include "../demo-renderer.h" +#include "../demo-view.h" #include "../default-text-combined.hh" #include "../default-text-en.hh" @@ -129,18 +126,19 @@ struct Uniforms { struct atlas_t { WGPUBuffer buf; - int32_t *shadow; /* CPU shadow (i32 expanded from i16) */ - unsigned capacity; /* in texels */ - unsigned cursor; /* in texels */ + int32_t *shadow; + unsigned capacity; + unsigned cursor; + bool dirty; }; static atlas_t atlas; static unsigned -atlas_alloc (void *ctx, const char *data, unsigned len_bytes) +atlas_alloc_cb (void *ctx, const char *data, unsigned len_bytes) { atlas_t *at = (atlas_t *) ctx; - unsigned len_texels = len_bytes / 8; /* 8 bytes per i16x4 texel */ + unsigned len_texels = len_bytes / 8; if (at->cursor + len_texels > at->capacity) { @@ -151,443 +149,177 @@ atlas_alloc (void *ctx, const char *data, unsigned len_bytes) unsigned offset = at->cursor; at->cursor += len_texels; - /* Expand i16x4 → i32x4 into shadow buffer */ const int16_t *src = (const int16_t *) data; int32_t *dst = at->shadow + offset * 4; for (unsigned i = 0; i < len_texels * 4; i++) dst[i] = (int32_t) src[i]; + at->dirty = true; return offset; } static unsigned -atlas_get_used (void *ctx) -{ - return ((atlas_t *) ctx)->cursor; -} +atlas_get_used_cb (void *ctx) { return ((atlas_t *) ctx)->cursor; } static void -atlas_clear (void *ctx) -{ - ((atlas_t *) ctx)->cursor = 0; -} +atlas_clear_cb (void *ctx) { ((atlas_t *) ctx)->cursor = 0; ((atlas_t *) ctx)->dirty = true; } /* ---- WebGPU state ---- */ -static WGPUAdapter adapter; -static WGPUDevice device; -static WGPUQueue queue; -static WGPUSurface surface; -static WGPURenderPipeline pipeline; -static WGPUBuffer uniform_buf; -static WGPUBuffer vertex_buf; -static unsigned vertex_buf_capacity; -static WGPUBindGroup bind_group; -static WGPUTextureFormat surface_format; +static WGPUAdapter g_adapter; +static WGPUDevice g_device; +static WGPUQueue g_queue; +static WGPUSurface g_surface; +static WGPURenderPipeline g_pipeline; +static WGPUBuffer g_uniform_buf; +static WGPUBuffer g_vertex_buf; +static unsigned g_vertex_buf_capacity; +static WGPUBindGroup g_bind_group; +static WGPUTextureFormat g_surface_format; + +static int canvas_w, canvas_h; +static int css_w, css_h; + + +/* ---- WebGPU renderer (implements demo_renderer_t) ---- */ + +struct demo_renderer_webgpu_t : demo_renderer_t +{ + float bg_r, bg_g, bg_b, bg_a; + float fg_r, fg_g, fg_b, fg_a; + float gamma; + demo_atlas_t *demo_atlas; + + demo_renderer_webgpu_t () + : bg_r (1), bg_g (1), bg_b (1), bg_a (1), + fg_r (0), fg_g (0), fg_b (0), fg_a (1), + gamma (1), demo_atlas (nullptr) {} + + ~demo_renderer_webgpu_t () override + { + if (demo_atlas) + demo_atlas_destroy (demo_atlas); + } + + demo_atlas_t *get_atlas () override { return demo_atlas; } + + void setup () override + { + /* Gamma defaults to 2.2 correction */ + gamma = 1.f / 2.2f; + } + + void set_gamma (float g) override { gamma = g; } + void set_foreground (float r, float g, float b, float a) override + { fg_r = r; fg_g = g; fg_b = b; fg_a = a; } + void set_background (float r, float g, float b, float a) override + { bg_r = r; bg_g = g; bg_b = b; bg_a = a; } + + bool set_srgb (bool enabled) override { return false; /* no sRGB framebuffer */ } + + void toggle_vsync (bool &vsync) override { /* always vsync in browser */ } + + void display (glyph_vertex_t *vertices, unsigned int count, + int width, int height, float mat[16]) override + { + WGPUSurfaceTexture surfTex; + wgpuSurfaceGetCurrentTexture (g_surface, &surfTex); + if (surfTex.status != WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal && + surfTex.status != WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal) + return; + + WGPUTextureView view = wgpuTextureCreateView (surfTex.texture, NULL); + + /* Update uniforms */ + Uniforms u; + memcpy (u.mvp, mat, sizeof (u.mvp)); + u.viewport[0] = (float) width; + u.viewport[1] = (float) height; + u.gamma = gamma; + u._pad = 0; + u.foreground[0] = fg_r; u.foreground[1] = fg_g; + u.foreground[2] = fg_b; u.foreground[3] = fg_a; + wgpuQueueWriteBuffer (g_queue, g_uniform_buf, 0, &u, sizeof (u)); + + /* Upload atlas if dirty */ + if (atlas.dirty && atlas.cursor > 0) + { + wgpuQueueWriteBuffer (g_queue, atlas.buf, 0, + atlas.shadow, atlas.cursor * 4 * sizeof (int32_t)); + atlas.dirty = false; + } + + /* Upload vertices */ + if (count > 0) + { + unsigned needed = count * sizeof (glyph_vertex_t); + if (needed > g_vertex_buf_capacity) + { + if (g_vertex_buf) + wgpuBufferRelease (g_vertex_buf); + WGPUBufferDescriptor desc = {}; + desc.size = needed; + desc.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst; + g_vertex_buf = wgpuDeviceCreateBuffer (g_device, &desc); + g_vertex_buf_capacity = needed; + } + wgpuQueueWriteBuffer (g_queue, g_vertex_buf, 0, vertices, needed); + } + + /* Render pass */ + WGPURenderPassColorAttachment colorAtt = {}; + colorAtt.view = view; + colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED; + colorAtt.loadOp = WGPULoadOp_Clear; + colorAtt.storeOp = WGPUStoreOp_Store; + colorAtt.clearValue = {bg_r, bg_g, bg_b, bg_a}; + + WGPURenderPassDescriptor rpDesc = {}; + rpDesc.colorAttachmentCount = 1; + rpDesc.colorAttachments = &colorAtt; + + WGPUCommandEncoderDescriptor ceDesc = {}; + WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder (g_device, &ceDesc); + WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass (encoder, &rpDesc); + + if (count > 0) + { + wgpuRenderPassEncoderSetPipeline (pass, g_pipeline); + wgpuRenderPassEncoderSetBindGroup (pass, 0, g_bind_group, 0, NULL); + wgpuRenderPassEncoderSetVertexBuffer (pass, 0, g_vertex_buf, 0, + count * sizeof (glyph_vertex_t)); + wgpuRenderPassEncoderDraw (pass, count, 1, 0, 0); + } + + wgpuRenderPassEncoderEnd (pass); + wgpuRenderPassEncoderRelease (pass); + + WGPUCommandBufferDescriptor cbDesc = {}; + WGPUCommandBuffer cmdBuf = wgpuCommandEncoderFinish (encoder, &cbDesc); + wgpuCommandEncoderRelease (encoder); + wgpuQueueSubmit (g_queue, 1, &cmdBuf); + wgpuCommandBufferRelease (cmdBuf); + + wgpuTextureViewRelease (view); + wgpuTextureRelease (surfTex.texture); + } +}; + +static demo_renderer_webgpu_t *renderer; + /* ---- Demo state ---- */ -static demo_font_t *current_demo_font; +static demo_view_t *vu; static demo_buffer_t *buffer; +static demo_font_t *current_demo_font; static hb_blob_t *current_blob; static hb_face_t *current_face; static hb_font_t *current_font; static char *current_text; static bool custom_text; -static int canvas_w, canvas_h; -static int css_w, css_h; -static bool needs_redraw = true; -static bool dark_mode = false; -static int gamma_mode = 0; /* 0=2.2, 1=none */ -static bool animate = false; - -/* View state */ -/* View state matching demo_view_t */ -static double translate_x, translate_y; -static double scalex = 1, scaley = 1; -static double perspective = 16; -static float quat[4]; -static float rot_axis[3] = {0, 0, 1}; -static double rot_speed = 1.0; - -static float -compute_gamma () -{ - if (gamma_mode == 0) - return dark_mode ? 1.f / 2.2f : 2.2f; - return 1.f; /* none */ -} - -static bool dragging = false; -static bool right_dragging = false; -static double last_mouse_x, last_mouse_y; -static double drag_start_x, drag_start_y; -static bool drag_started = false; - - -/* ---- Forward declarations ---- */ - -static void rebuild_buffer (const char *text); -static void render_frame (); -static void create_bind_group (); - - -/* ---- View helpers ---- */ - -static void -compute_mvp (float mat[16]) -{ - int width = canvas_w, height = canvas_h; - - m4LoadIdentity (mat); - - /* Apply view transform — matches demo_view_apply_transform exactly */ - m4Scale (mat, scalex, scaley, 1); - m4Translate (mat, translate_x, translate_y, 0); - - { - double d = std::max (width, height); - double near = d / perspective; - double far = near + d; - double factor = near / (2 * near + d); - m4Frustum (mat, -width * factor, width * factor, -height * factor, height * factor, near, far); - m4Translate (mat, 0, 0, -(near + d * .5)); - } - - float m[4][4]; - build_rotmatrix (m, quat); - m4MultMatrix (mat, &m[0][0]); - - m4Scale (mat, 1, -1, 1); - - /* Content centering — matches demo_view_display */ - demo_extents_t extents; - demo_buffer_extents (buffer, NULL, &extents); - double content_scale = .9 * std::min (width / (extents.max_x - extents.min_x), - height / (extents.max_y - extents.min_y)); - m4Scale (mat, content_scale, content_scale, 1); - m4Translate (mat, - -(extents.max_x + extents.min_x) / 2., - -(extents.max_y + extents.min_y) / 2., 0); -} - - -/* ---- Atlas upload to GPU ---- */ - -static void -atlas_upload () -{ - unsigned used = atlas.cursor; - if (used == 0) return; - wgpuQueueWriteBuffer (queue, atlas.buf, 0, - atlas.shadow, used * 4 * sizeof (int32_t)); -} - - -/* ---- Rendering ---- */ - -static void -render_frame () -{ - WGPUSurfaceTexture surfTex; - wgpuSurfaceGetCurrentTexture (surface, &surfTex); - if (surfTex.status != WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal && - surfTex.status != WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal) - return; - - WGPUTextureView view = wgpuTextureCreateView (surfTex.texture, NULL); - - /* Update uniforms */ - Uniforms u; - compute_mvp (u.mvp); - u.viewport[0] = (float) canvas_w; - u.viewport[1] = (float) canvas_h; - u.gamma = compute_gamma (); - u._pad = 0; - if (dark_mode) - { - u.foreground[0] = u.foreground[1] = u.foreground[2] = 1.0f; - u.foreground[3] = 1.0f; - } - else - { - u.foreground[0] = u.foreground[1] = u.foreground[2] = 0.0f; - u.foreground[3] = 1.0f; - } - wgpuQueueWriteBuffer (queue, uniform_buf, 0, &u, sizeof (u)); - - /* Upload atlas data */ - atlas_upload (); - - /* Upload vertices */ - unsigned vtx_count = 0; - glyph_vertex_t *vertices = demo_buffer_get_vertices (buffer, &vtx_count); - - if (vtx_count > 0) - { - unsigned needed = vtx_count * sizeof (glyph_vertex_t); - if (needed > vertex_buf_capacity) - { - if (vertex_buf) - wgpuBufferRelease (vertex_buf); - WGPUBufferDescriptor desc = {}; - desc.size = needed; - desc.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst; - vertex_buf = wgpuDeviceCreateBuffer (device, &desc); - vertex_buf_capacity = needed; - } - wgpuQueueWriteBuffer (queue, vertex_buf, 0, vertices, needed); - } - - /* Render pass */ - float bg_r, bg_g, bg_b; - if (dark_mode) - bg_r = bg_g = bg_b = 0.133f; - else - bg_r = bg_g = bg_b = 1.0f; - - WGPURenderPassColorAttachment colorAtt = {}; - colorAtt.view = view; - colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED; - colorAtt.loadOp = WGPULoadOp_Clear; - colorAtt.storeOp = WGPUStoreOp_Store; - colorAtt.clearValue = {bg_r, bg_g, bg_b, 1.0}; - - WGPURenderPassDescriptor rpDesc = {}; - rpDesc.colorAttachmentCount = 1; - rpDesc.colorAttachments = &colorAtt; - - WGPUCommandEncoderDescriptor ceDesc = {}; - WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder (device, &ceDesc); - WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass (encoder, &rpDesc); - - if (vtx_count > 0) - { - wgpuRenderPassEncoderSetPipeline (pass, pipeline); - wgpuRenderPassEncoderSetBindGroup (pass, 0, bind_group, 0, NULL); - wgpuRenderPassEncoderSetVertexBuffer (pass, 0, vertex_buf, 0, vtx_count * sizeof (glyph_vertex_t)); - wgpuRenderPassEncoderDraw (pass, vtx_count, 1, 0, 0); - } - - wgpuRenderPassEncoderEnd (pass); - wgpuRenderPassEncoderRelease (pass); - - WGPUCommandBufferDescriptor cbDesc = {}; - WGPUCommandBuffer cmdBuf = wgpuCommandEncoderFinish (encoder, &cbDesc); - wgpuCommandEncoderRelease (encoder); - wgpuQueueSubmit (queue, 1, &cmdBuf); - wgpuCommandBufferRelease (cmdBuf); - - wgpuTextureViewRelease (view); - wgpuTextureRelease (surfTex.texture); - - /* Browser auto-presents; wgpuSurfacePresent is not supported in Emscripten. */ -} - - -/* ---- Input handling ---- */ - -static EM_BOOL -on_mousedown (int type, const EmscriptenMouseEvent *e, void *ud) -{ - last_mouse_x = e->targetX; - last_mouse_y = e->targetY; - drag_start_x = e->targetX; - drag_start_y = e->targetY; - drag_started = false; - - if (e->button == 0) - dragging = true; - else if (e->button == 2) - right_dragging = true; - return EM_TRUE; -} - -static EM_BOOL -on_mouseup (int type, const EmscriptenMouseEvent *e, void *ud) -{ - if (e->button == 0 && dragging && !drag_started) - { - /* Click — toggle animation */ - animate = !animate; - needs_redraw = true; - } - dragging = false; - right_dragging = false; - return EM_TRUE; -} - -static EM_BOOL -on_mousemove (int type, const EmscriptenMouseEvent *e, void *ud) -{ - double prev_x = last_mouse_x; - double prev_y = last_mouse_y; - last_mouse_x = e->targetX; - last_mouse_y = e->targetY; - - if (!dragging && !right_dragging) - return EM_FALSE; - - double dist = sqrt ((e->targetX - drag_start_x) * (e->targetX - drag_start_x) + - (e->targetY - drag_start_y) * (e->targetY - drag_start_y)); - if (dist > 5) drag_started = true; - - if (dragging && drag_started) - { - double dx = last_mouse_x - prev_x; - double dy = last_mouse_y - prev_y; - translate_x += 2.0 * dx / css_w / scalex; - translate_y -= 2.0 * dy / css_h / scaley; - needs_redraw = true; - } - else if (right_dragging) - { - float dquat[4]; - trackball (dquat, - (2.0 * prev_x - css_w) / css_w, - (css_h - 2.0 * prev_y) / css_h, - (2.0 * last_mouse_x - css_w) / css_w, - (css_h - 2.0 * last_mouse_y) / css_h); - add_quats (dquat, quat, quat); - needs_redraw = true; - } - return EM_TRUE; -} - -static EM_BOOL -on_wheel (int type, const EmscriptenWheelEvent *e, void *ud) -{ - float delta = (float) -e->deltaY; - if (e->deltaMode == DOM_DELTA_LINE) - delta *= 40.0f; - double factor = pow (1.001, delta); - scalex *= factor; - scaley *= factor; - needs_redraw = true; - return EM_TRUE; -} - -static EM_BOOL -on_keydown (int type, const EmscriptenKeyboardEvent *e, void *ud) -{ - if (strcmp (e->key, "b") == 0) - { - dark_mode = !dark_mode; - printf ("Dark mode: %s\n", dark_mode ? "on" : "off"); - needs_redraw = true; - } - else if (strcmp (e->key, "g") == 0) - { - gamma_mode = (gamma_mode + 1) % 2; - const char *names[] = {"gamma 2.2", "none"}; - printf ("Gamma correction: %s\n", names[gamma_mode]); - needs_redraw = true; - } - else if (strcmp (e->key, "r") == 0) - { - perspective = 16; - scalex = scaley = 1; - translate_x = translate_y = 0; - trackball (quat, 0., 0., 0., 0.); - needs_redraw = true; - } - else if (strcmp (e->key, " ") == 0) - { - animate = !animate; - needs_redraw = true; - } - else if (strcmp (e->key, "=") == 0 || strcmp (e->key, "+") == 0) - { - scalex *= 1.2; - scaley *= 1.2; - needs_redraw = true; - } - else if (strcmp (e->key, "-") == 0) - { - scalex /= 1.2; - scaley /= 1.2; - needs_redraw = true; - } - return EM_FALSE; /* let text modal handler see it too */ -} - -/* Touch handling */ -static double pinch_dist; - -static EM_BOOL -on_touchstart (int type, const EmscriptenTouchEvent *e, void *ud) -{ - if (e->numTouches == 1) - { - last_mouse_x = e->touches[0].targetX; - last_mouse_y = e->touches[0].targetY; - drag_start_x = last_mouse_x; - drag_start_y = last_mouse_y; - drag_started = false; - dragging = true; - } - else if (e->numTouches == 2) - { - dragging = false; - double dx = e->touches[1].targetX - e->touches[0].targetX; - double dy = e->touches[1].targetY - e->touches[0].targetY; - pinch_dist = sqrt (dx * dx + dy * dy); - } - return EM_TRUE; -} - -static EM_BOOL -on_touchmove (int type, const EmscriptenTouchEvent *e, void *ud) -{ - if (e->numTouches == 1 && dragging) - { - double dx = e->touches[0].targetX - last_mouse_x; - double dy = e->touches[0].targetY - last_mouse_y; - last_mouse_x = e->touches[0].targetX; - last_mouse_y = e->touches[0].targetY; - - double dist = sqrt ((last_mouse_x - drag_start_x) * (last_mouse_x - drag_start_x) + - (last_mouse_y - drag_start_y) * (last_mouse_y - drag_start_y)); - if (dist > 5) drag_started = true; - - if (drag_started) - { - translate_x += 2.0 * dx / css_w / scalex; - translate_y -= 2.0 * dy / css_h / scaley; - needs_redraw = true; - } - } - else if (e->numTouches == 2) - { - double dx = e->touches[1].targetX - e->touches[0].targetX; - double dy = e->touches[1].targetY - e->touches[0].targetY; - double dist = sqrt (dx * dx + dy * dy); - if (pinch_dist > 0) - { - double factor = dist / pinch_dist; - scalex *= factor; - scaley *= factor; - needs_redraw = true; - } - pinch_dist = dist; - } - return EM_TRUE; -} - -static EM_BOOL -on_touchend (int type, const EmscriptenTouchEvent *e, void *ud) -{ - if (dragging && !drag_started) - { - animate = !animate; - needs_redraw = true; - } - dragging = false; - return EM_TRUE; -} - /* ---- Buffer rebuild ---- */ @@ -598,16 +330,15 @@ rebuild_buffer (const char *text) current_text = strdup (text); demo_font_clear_cache (current_demo_font); - atlas_clear (&atlas); + atlas_clear_cb (&atlas); demo_buffer_clear (buffer); demo_point_t top_left = {0, 0}; demo_buffer_move_to (buffer, &top_left); demo_buffer_add_text (buffer, text, current_demo_font, 1); - /* Re-upload atlas and recreate bind group (buffer contents changed) */ - atlas_upload (); - needs_redraw = true; + atlas.dirty = true; + demo_view_reset (vu); } @@ -633,13 +364,7 @@ web_load_font (const char *data, int len) current_font = font; demo_font_destroy (current_demo_font); - demo_atlas_backend_t backend = {}; - backend.ctx = &atlas; - backend.alloc = atlas_alloc; - backend.get_used = atlas_get_used; - backend.clear = atlas_clear; - demo_atlas_t *new_atlas = demo_atlas_create_external (&backend); - current_demo_font = demo_font_create (font, new_atlas); + current_demo_font = demo_font_create (font, renderer->get_atlas ()); rebuild_buffer (custom_text ? current_text : default_text_en); demo_font_print_stats (current_demo_font); @@ -661,32 +386,142 @@ web_get_text () } /* extern "C" */ +/* ---- Input handling (feeds into demo_view) ---- */ + +/* GLFW-compatible button/action constants */ +#define BUTTON_LEFT 0 +#define BUTTON_RIGHT 1 +#define ACTION_RELEASE 0 +#define ACTION_PRESS 1 + +static EM_BOOL +on_mousedown (int type, const EmscriptenMouseEvent *e, void *ud) +{ + int button = (e->button == 2) ? BUTTON_RIGHT : BUTTON_LEFT; + demo_view_motion_func (vu, e->targetX, e->targetY); + demo_view_mouse_func (vu, button, ACTION_PRESS, 0); + return EM_TRUE; +} + +static EM_BOOL +on_mouseup (int type, const EmscriptenMouseEvent *e, void *ud) +{ + int button = (e->button == 2) ? BUTTON_RIGHT : BUTTON_LEFT; + demo_view_motion_func (vu, e->targetX, e->targetY); + demo_view_mouse_func (vu, button, ACTION_RELEASE, 0); + return EM_TRUE; +} + +static EM_BOOL +on_mousemove (int type, const EmscriptenMouseEvent *e, void *ud) +{ + demo_view_motion_func (vu, e->targetX, e->targetY); + return EM_TRUE; +} + +static EM_BOOL +on_wheel (int type, const EmscriptenWheelEvent *e, void *ud) +{ + double delta = -e->deltaY; + if (e->deltaMode == DOM_DELTA_LINE) + delta *= 40.0; + demo_view_scroll_func (vu, 0, delta / 120.0); + return EM_TRUE; +} + +/* Key mapping from DOM key strings to GLFW key codes */ +static int +dom_key_to_glfw (const char *key) +{ + if (!strcmp (key, " ")) return 32; /* GLFW_KEY_SPACE */ + if (!strcmp (key, "Escape")) return 256; /* GLFW_KEY_ESCAPE */ + if (!strcmp (key, "ArrowUp")) return 265; /* GLFW_KEY_UP */ + if (!strcmp (key, "ArrowDown")) return 264; /* GLFW_KEY_DOWN */ + if (!strcmp (key, "ArrowLeft")) return 263; /* GLFW_KEY_LEFT */ + if (!strcmp (key, "ArrowRight"))return 262; /* GLFW_KEY_RIGHT */ + if (key[0] >= 'a' && key[0] <= 'z' && key[1] == 0) + return key[0] - 'a' + 65; /* GLFW_KEY_A..Z */ + return 0; +} + +static EM_BOOL +on_keydown (int type, const EmscriptenKeyboardEvent *e, void *ud) +{ + /* Let char_func handle printable characters */ + int key = dom_key_to_glfw (e->key); + if (key) + demo_view_key_func (vu, key, 0, ACTION_PRESS, e->shiftKey ? 1 : 0); + + /* Also send as char for =/-/etc */ + if (e->key[0] && !e->key[1]) + demo_view_char_func (vu, (unsigned int) e->key[0]); + + return EM_FALSE; +} + +/* Touch handling */ +static double pinch_dist; + +static EM_BOOL +on_touchstart (int type, const EmscriptenTouchEvent *e, void *ud) +{ + if (e->numTouches == 1) + { + demo_view_motion_func (vu, e->touches[0].targetX, e->touches[0].targetY); + demo_view_mouse_func (vu, BUTTON_LEFT, ACTION_PRESS, 0); + } + else if (e->numTouches == 2) + { + demo_view_mouse_func (vu, BUTTON_LEFT, ACTION_RELEASE, 0); + double dx = e->touches[1].targetX - e->touches[0].targetX; + double dy = e->touches[1].targetY - e->touches[0].targetY; + pinch_dist = sqrt (dx * dx + dy * dy); + } + return EM_TRUE; +} + +static EM_BOOL +on_touchmove (int type, const EmscriptenTouchEvent *e, void *ud) +{ + if (e->numTouches == 1) + { + demo_view_motion_func (vu, e->touches[0].targetX, e->touches[0].targetY); + } + else if (e->numTouches == 2) + { + double dx = e->touches[1].targetX - e->touches[0].targetX; + double dy = e->touches[1].targetY - e->touches[0].targetY; + double dist = sqrt (dx * dx + dy * dy); + if (pinch_dist > 0) + demo_view_scroll_func (vu, 0, (dist - pinch_dist) * 0.05); + pinch_dist = dist; + } + return EM_TRUE; +} + +static EM_BOOL +on_touchend (int type, const EmscriptenTouchEvent *e, void *ud) +{ + demo_view_mouse_func (vu, BUTTON_LEFT, ACTION_RELEASE, 0); + return EM_TRUE; +} + + /* ---- Main loop ---- */ static void main_loop_iter () { - if (animate) - { - float dquat[4]; - float axis[3] = {rot_axis[0], rot_axis[1], rot_axis[2]}; - axis_to_quat (axis, (float) (rot_speed * 0.02), dquat); - add_quats (dquat, quat, quat); - needs_redraw = true; - } - - if (needs_redraw && pipeline) - { - render_frame (); - needs_redraw = false; - } + if (demo_view_should_redraw (vu)) + demo_view_display (vu, buffer); } -/* ---- WebGPU initialization chain ---- */ +/* ---- WebGPU initialization ---- */ static void init_demo (); static void create_pipeline (); +static void create_bind_group (); static void on_device (WGPURequestDeviceStatus status, @@ -701,9 +536,8 @@ on_device (WGPURequestDeviceStatus status, }); return; } - device = dev; - queue = wgpuDeviceGetQueue (device); - + g_device = dev; + g_queue = wgpuDeviceGetQueue (g_device); init_demo (); } @@ -726,28 +560,27 @@ on_adapter (WGPURequestAdapterStatus status, 'google-chrome --enable-unsafe-webgpu --ozone-platform=x11 ' + '--use-angle=vulkan --enable-features=Vulkan,VulkanFromANGLE'; el.innerHTML = html; - el.style.fontSize = '16px'; - el.style.padding = '40px'; + el.style.font = '18px sans-serif'; el.style.color = '#666'; + el.style.textAlign = 'center'; + el.style.flexDirection = 'column'; } }); return; } - adapter = adpt; + g_adapter = adpt; WGPUDeviceDescriptor devDesc = {}; WGPURequestDeviceCallbackInfo cbInfo = {}; cbInfo.mode = WGPUCallbackMode_AllowSpontaneous; cbInfo.callback = on_device; - wgpuAdapterRequestDevice (adapter, &devDesc, cbInfo); + wgpuAdapterRequestDevice (g_adapter, &devDesc, cbInfo); } - static void create_pipeline () { - /* Assemble full WGSL: library vertex + library fragment + demo shader */ std::string wgsl; wgsl += hb_gpu_shader_vertex_source (HB_GPU_SHADER_LANG_WGSL); wgsl += "\n"; @@ -761,27 +594,21 @@ create_pipeline () WGPUShaderModuleDescriptor smDesc = {}; smDesc.nextInChain = &wgslSrc.chain; - WGPUShaderModule module = wgpuDeviceCreateShaderModule (device, &smDesc); + WGPUShaderModule module = wgpuDeviceCreateShaderModule (g_device, &smDesc); - /* Vertex buffer layout matching glyph_vertex_t */ WGPUVertexAttribute attrs[5] = {}; - /* position: float2 at offset 0 */ attrs[0].format = WGPUVertexFormat_Float32x2; attrs[0].offset = offsetof (glyph_vertex_t, x); attrs[0].shaderLocation = 0; - /* texcoord: float2 at offset 8 */ attrs[1].format = WGPUVertexFormat_Float32x2; attrs[1].offset = offsetof (glyph_vertex_t, tx); attrs[1].shaderLocation = 1; - /* normal: float2 at offset 16 */ attrs[2].format = WGPUVertexFormat_Float32x2; attrs[2].offset = offsetof (glyph_vertex_t, nx); attrs[2].shaderLocation = 2; - /* emPerPos: float at offset 24 */ attrs[3].format = WGPUVertexFormat_Float32; attrs[3].offset = offsetof (glyph_vertex_t, emPerPos); attrs[3].shaderLocation = 3; - /* atlas_offset: uint32 at offset 28 */ attrs[4].format = WGPUVertexFormat_Uint32; attrs[4].offset = offsetof (glyph_vertex_t, atlas_offset); attrs[4].shaderLocation = 4; @@ -792,7 +619,6 @@ create_pipeline () vbLayout.attributeCount = 5; vbLayout.attributes = attrs; - /* Color target with alpha blending */ WGPUBlendState blend = {}; blend.color.srcFactor = WGPUBlendFactor_SrcAlpha; blend.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha; @@ -802,7 +628,7 @@ create_pipeline () blend.alpha.operation = WGPUBlendOperation_Add; WGPUColorTargetState colorTarget = {}; - colorTarget.format = surface_format; + colorTarget.format = g_surface_format; colorTarget.blend = &blend; colorTarget.writeMask = WGPUColorWriteMask_All; @@ -823,79 +649,82 @@ create_pipeline () pipeDesc.multisample.mask = ~0u; pipeDesc.fragment = &fragState; - pipeline = wgpuDeviceCreateRenderPipeline (device, &pipeDesc); + g_pipeline = wgpuDeviceCreateRenderPipeline (g_device, &pipeDesc); wgpuShaderModuleRelease (module); } - static void create_bind_group () { WGPUBindGroupEntry entries[2] = {}; entries[0].binding = 0; - entries[0].buffer = uniform_buf; + entries[0].buffer = g_uniform_buf; entries[0].size = sizeof (Uniforms); - entries[1].binding = 1; entries[1].buffer = atlas.buf; entries[1].size = atlas.capacity * 4 * sizeof (int32_t); WGPUBindGroupDescriptor bgDesc = {}; - bgDesc.layout = wgpuRenderPipelineGetBindGroupLayout (pipeline, 0); + bgDesc.layout = wgpuRenderPipelineGetBindGroupLayout (g_pipeline, 0); bgDesc.entryCount = 2; bgDesc.entries = entries; - if (bind_group) - wgpuBindGroupRelease (bind_group); - bind_group = wgpuDeviceCreateBindGroup (device, &bgDesc); + if (g_bind_group) + wgpuBindGroupRelease (g_bind_group); + g_bind_group = wgpuDeviceCreateBindGroup (g_device, &bgDesc); } - static void init_demo () { /* Configure surface */ WGPUSurfaceCapabilities caps = {}; - wgpuSurfaceGetCapabilities (surface, adapter, &caps); - surface_format = caps.formats[0]; /* preferred format */ + wgpuSurfaceGetCapabilities (g_surface, g_adapter, &caps); + g_surface_format = caps.formats[0]; WGPUSurfaceConfiguration config = {}; - config.device = device; - config.format = surface_format; + config.device = g_device; + config.format = g_surface_format; config.usage = WGPUTextureUsage_RenderAttachment; config.width = canvas_w; config.height = canvas_h; config.presentMode = WGPUPresentMode_Fifo; config.alphaMode = WGPUCompositeAlphaMode_Opaque; - wgpuSurfaceConfigure (surface, &config); + wgpuSurfaceConfigure (g_surface, &config); /* Create atlas storage buffer */ - unsigned atlas_capacity = 256 * 1024; /* 256K texels */ + unsigned atlas_capacity = 256 * 1024; atlas.capacity = atlas_capacity; atlas.cursor = 0; + atlas.dirty = true; atlas.shadow = (int32_t *) calloc (atlas_capacity * 4, sizeof (int32_t)); WGPUBufferDescriptor atlasDesc = {}; atlasDesc.size = atlas_capacity * 4 * sizeof (int32_t); atlasDesc.usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst; - atlas.buf = wgpuDeviceCreateBuffer (device, &atlasDesc); + atlas.buf = wgpuDeviceCreateBuffer (g_device, &atlasDesc); /* Create uniform buffer */ WGPUBufferDescriptor uniDesc = {}; uniDesc.size = sizeof (Uniforms); uniDesc.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst; - uniform_buf = wgpuDeviceCreateBuffer (device, &uniDesc); + g_uniform_buf = wgpuDeviceCreateBuffer (g_device, &uniDesc); - /* Create pipeline */ + /* Create pipeline and bind group */ create_pipeline (); - /* Set up atlas backend for demo-font */ + /* Set up renderer with atlas backend */ + renderer = new demo_renderer_webgpu_t (); + demo_atlas_backend_t backend = {}; backend.ctx = &atlas; - backend.alloc = atlas_alloc; - backend.get_used = atlas_get_used; - backend.clear = atlas_clear; - demo_atlas_t *demo_atlas = demo_atlas_create_external (&backend); + backend.alloc = atlas_alloc_cb; + backend.get_used = atlas_get_used_cb; + backend.clear = atlas_clear_cb; + renderer->demo_atlas = demo_atlas_create_external (&backend); + + /* Create view (headless — no GLFW) */ + vu = demo_view_create_headless (renderer, canvas_w, canvas_h, css_w, css_h); /* Create font and buffer */ current_blob = hb_blob_create ((const char *) default_font, @@ -904,7 +733,7 @@ init_demo () NULL, NULL); current_face = hb_face_create (current_blob, 0); current_font = hb_font_create (current_face); - current_demo_font = demo_font_create (current_font, demo_atlas); + current_demo_font = demo_font_create (current_font, renderer->get_atlas ()); current_text = strdup (default_text_combined); @@ -915,14 +744,11 @@ init_demo () demo_font_print_stats (current_demo_font); - /* Upload atlas to GPU */ - atlas_upload (); - - /* Create bind group */ + /* Create bind group (after atlas populated) */ create_bind_group (); - /* Initialize trackball */ - trackball (quat, 0., 0., 0., 0.); + /* Setup renderer (sets initial gamma/colors) */ + demo_view_setup (vu); /* Register input handlers */ emscripten_set_mousedown_callback ("#canvas", NULL, EM_TRUE, on_mousedown); @@ -934,31 +760,31 @@ init_demo () emscripten_set_touchmove_callback ("#canvas", NULL, EM_TRUE, on_touchmove); emscripten_set_touchend_callback ("#canvas", NULL, EM_TRUE, on_touchend); - /* Start render loop */ - emscripten_set_main_loop (main_loop_iter, 0, 0); - /* Hide loading screen */ EM_ASM ({ var el = document.getElementById ('loading'); - if (el) el.style.display = 'none'; - document.body.style.background = '#222'; + if (el && !window._webgpuError) { + el.style.display = 'none'; + document.body.style.background = '#222'; + } }); - printf ("WebGPU demo initialized: %u atlas texels\n", atlas.cursor); + printf ("WebGPU demo initialized\n"); + + /* Start render loop */ + emscripten_set_main_loop (main_loop_iter, 0, 0); } int main () { - /* Get canvas size */ emscripten_get_canvas_element_size ("#canvas", &canvas_w, &canvas_h); double css_w_d, css_h_d; emscripten_get_element_css_size ("#canvas", &css_w_d, &css_h_d); css_w = (int) css_w_d; css_h = (int) css_h_d; - /* Create WebGPU surface from canvas */ WGPUInstanceDescriptor instDesc = {}; WGPUInstance instance = wgpuCreateInstance (&instDesc); @@ -968,11 +794,10 @@ main () WGPUSurfaceDescriptor surfDesc = {}; surfDesc.nextInChain = &canvasDesc.chain; - surface = wgpuInstanceCreateSurface (instance, &surfDesc); + g_surface = wgpuInstanceCreateSurface (instance, &surfDesc); - /* Request adapter → device → init_demo */ WGPURequestAdapterOptions opts = {}; - opts.compatibleSurface = surface; + opts.compatibleSurface = g_surface; opts.powerPreference = WGPUPowerPreference_HighPerformance; WGPURequestAdapterCallbackInfo cbInfo = {};