Commit Graph
60 Commits
Author SHA1 Message Date
Garret Rieger d60f62df48 [util/gpu] Avoid use-after-free on current_text in rebuild_buffer (#6253)
In hb-gpu-web and hb-gpu-web-webgpu, rebuild_buffer() frees current_text
after duplicating the input text, but then passes the original text
pointer to demo_buffer_add_text(). When called from web_load_font(),
web_set_variations(), web_set_features(), or web_set_palette() with
custom text active, text aliases current_text, resulting in a
use-after-free read of recently freed heap memory.

Fix this by:
1. Skipping redundant reallocation when text already equals
   current_text.
2. Passing current_text to demo_buffer_add_text().
3. Handling a null text input safely with a default fallback.

Assisted-by: Gemini
2026-09-10 16:45:59 -06:00
Behdad Esfahbod 5ee942feb6 [gpu_demo] Fix web demo build 2026-05-04 09:58:05 -06:00
Behdad Esfahbod 14259b79dc [util/gpu/web] Silence "empty character constant" warnings
EM_ASM stringifies its body, but the C tokenizer still parses
single-quoted '' as an empty char constant.  Use double-quoted
"" -- valid JS empty string, no warning.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:46:02 -06:00
Behdad Esfahbod 59d819f09c [util/gpu/web] Live palette via postMessage
Add web_set_palette() to both GL and WebGPU bindings (forwards
to demo_font_set_palette + buffer rebuild) and accept a
{ kind: 'palette', value: <int> } message in shell.html.  Lets
the harfbuzz-world.cc host page push the user's CPAL pick into
the embedded GPU iframe alongside text / font / variations.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:22:13 -06:00
Behdad EsfahbodandClaude Opus 4.6 d17ff1e8d6 [util/gpu/web] Live variations via postMessage
Add web_set_variations(const char *) to both the WebGL and
WebGPU hb-gpu-web wasm modules.  Parses a comma-separated
"wght=400,wdth=100" string via hb_variation_from_string,
applies via hb_font_set_variations on the current font, and
rebuilds the shaping buffer.  Cheap to call repeatedly --
suitable for live slider pushes once a slider UI lands.

Shell.html grows a matching applyVariations() helper and a
'variations' postMessage case.  config-override.h undefs
HB_NO_VAR so the new function actually links.  EXPORTED
_FUNCTIONS on both build scripts list _web_set_variations.

Also plumbed in a small cap (32 axes) on the stack so the
parser doesn't need hb's internal containers -- no font has
anywhere near that many.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 12:57:18 -06:00
Behdad Esfahbod 1f813cfb86 [util/gpu] Extract MSL/HLSL/WGSL demo shaders into own files
Matches the GLSL convention: demo-shader.{msl,hlsl,wgsl} live
alongside demo-fragment.glsl and get stringified by the same
gen-gpu-shader-artifacts.py helper into demo-shader-{msl,hlsl,
wgsl}.hh.  No more giant inline R"msl(...)" / R"hlsl(...)" /
R"wgsl(...)" blobs in the .mm / .cc files.

Each language combines vertex and fragment entry points in one
source, as is idiomatic for MSL / HLSL / WGSL compilers; GLSL's
split (demo-vertex.glsl + demo-fragment.glsl) is preserved
because glCompileShader takes separate stages.

No functional change.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 15:33:44 -06:00
Behdad Esfahbod c4da618566 [gpu] Stem-darken by per-fragment color, not by foreground uniform
The demo fragment shaders were passing u_foreground's brightness
to hb_gpu_stem_darken(), which was wrong for color glyphs: a red
cheek on an emoji should darken relative to its own red, not to
whatever the text-foreground uniform happens to be.

Switch all four demo fragment paths (GL, Metal, D3D11, WebGPU)
to compute brightness from the fragment's own straight color
(c.rgb / c.a).  For monochrome glyphs this is identical to the
old formula -- the synthesized single layer's color IS the
foreground uniform -- so non-color rendering is unchanged.

The public hb_gpu_stem_darken() helper is unchanged; only its
callers pass a different brightness.  Document the paint-path
usage in the hb-gpu section.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 15:24:32 -06:00
Behdad Esfahbod f840ae39a2 [util/gpu] Add --draw / --paint flags with auto-detect by font
Adds command-line flags --draw (force monochrome Slug path) and
--paint (force COLRv1 paint path) to hb-gpu, defaulting to
auto-detect based on hb_ot_color_has_paint(face).  Threads a
draw_only bool through the demo layer so each backend compiles
exactly one fragment program (draw or paint, not both).

The paint pipeline is ~10x slower than the draw pipeline on
monochrome content; auto-detect lets monochrome fonts keep the
fast path while still exercising both code paths from the same
binary.

Plumbing:

- demo_renderer_create_{gl,metal,d3d11} and demo_font_create
  take a draw_only argument.
- demo-fragment.{glsl,msl,hlsl} branch on HB_GPU_DEMO_DRAW,
  calling either hb_gpu_draw or hb_gpu_paint.
- demo-shader / glstate / d3d11 / metal include only the
  fragment helper for the chosen path and prepend
  HB_GPU_DEMO_DRAW to the source when draw_only.
- demo-font dispatches glyph upload to hb_gpu_draw_* or
  hb_gpu_paint_* and hides palette/foreground setters in
  draw mode.

Web demos pass false (paint-only) for now; a runtime
re-creation hook on font change would be needed there.

Tested on desktop GL, win64 D3D11, WebGL, WebGPU.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:04:27 -06:00
Behdad Esfahbod 62a8a3a26c [util/gpu] Drop sRGB framebuffer mode; always gamma 2.2
The paint encoder bakes sRGB-encoded font palette values directly
(quantizing 0..255 to 0..32767 without decoding), so the shader
writes sRGB-ish values.  With GL_FRAMEBUFFER_SRGB enabled the
driver then applied linear->sRGB encoding on store, giving a
double-encoded, washed-out result -- most visible on mid-tone
gradients.

The cleanest fix is to stop pretending we're doing linear-space
compositing: drop the sRGB framebuffer mode entirely and always
apply the classic 2.2 gamma exponent for coverage correction
(flipped to 1/2.2 in dark mode to match the existing light/dark
logic).  Removed pieces:

 - demo_view_t::gamma_mode enum, demo_view_set_gamma_mode,
   demo_view_cycle_gamma, and the `g` keybinding + help line
 - demo_renderer_t::set_srgb virtual + every backend override
 - GLFW_SRGB_CAPABLE hint in gpu-output.hh
 - Metal swapchain MTLPixelFormatBGRA8Unorm_sRGB -> BGRA8Unorm

Replaced with demo_view_update_gamma, called on setup() and after
the dark-mode toggle.  Shader side stays the same (only alpha gets
the gamma curve, as before).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:30:45 -06:00
Behdad Esfahbod 087fd84a49 [util/gpu] Drop renderer palette plumbing, forward to hb_gpu_paint
Colors are now baked into encoded blobs (see prior commit), so
nothing needs to upload or bind a palette buffer.  Remove
demo_renderer_t::set_palette from all backends (GL, Metal, D3D11,
WebGPU), the hb_gpu_palette GL uniform plumbing in demo-glstate,
the Metal/D3D11 palette buffers, and the WebGPU storage buffer +
bind-group entry.  demo_font_get_palette is also gone.

Replace with new demo_font accessors that forward to the encoder:

  demo_font_set_palette
  demo_font_set_foreground
  demo_font_clear_custom_palette_colors
  demo_font_set_custom_palette_color

Each invalidates the glyph cache because colors are baked into
the atlas entries.  gpu-output.hh now forwards view-option
--font-palette / --custom-palette through these.

Web demos stop allocating / uploading the palette buffer; the
WGSL fragment shader drops its third bind-group slot.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 18:45:12 -06:00
Behdad Esfahbod 585154aa10 [util/gpu] Web demos: fix URL-param handling for ?font= and ?text=
rebuild_buffer did free(current_text); strdup(text); but was often
called with text == current_text (from web_load_font's
"custom_text ? current_text : default").  Strdup of freed memory
shaped garbage and made multi-char strings look like 1 char.  Fix:
strdup first, then free.

The WebGL rebuild_buffer also called demo_view_display itself,
which runs fine from a main loop tick but not from a fetch
promise's microtask (the canvas back-buffer doesn't swap).  Drop
it: demo_view_reset sets needs_redraw=true, and the next
main_loop_iter renders inside a proper rAF tick.

Emscripten allocates argv on the JS stack, which is unwound when
main returns.  WebGPU's init is async and reads arg_text/arg_font
after main returns, so those pointers were dangling -- early null
bytes in freed stack memory made the emoji URL shape to 1 glyph.
strdup them in main so they survive.

Finally, forward ?font= to argv as --font= (already done for
?text=) so the C side's "skip initial default-font glyph upload
when a font fetch is pending" path actually triggers.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 18:12:47 -06:00
Behdad Esfahbod b616298d73 [util/gpu] Web demos: skip default-font upload when ?font= pending; preserve URL on backend switch; reflect custom text in URL
Three small UX improvements to the web demos.

### Skip default-font upload when ?font= is pending

When ?font= is set, the async fetch replaces the font later.  main
was still populating the atlas with the default font's glyphs for
the initial text, just to throw them away when _web_load_font ran
its own rebuild_buffer.  Gate demo_buffer_add_text() on !arg_font
so the buffer stays empty until the real font lands.

### WebGPU ready signal

WebGPU's init_demo is async (awaits adapter/device), so
onRuntimeInitialized fires before the demo is usable; calling
_web_load_font from the ?font= fetch at that point tripped a wasm
indirect-call signature mismatch.  init_demo now EM_ASMs a
window._webDemoReady() hook at its tail; the shell installs
_webDemoReady = startFontFetch when running the WebGPU build and
starts the fetch immediately for WebGL.

### URL ergonomics

* Backend-selector change now carries location.search across the
  navigation -- ?text= and ?font= survive the WebGL <-> WebGPU
  switch.
* The text-edit modal's Apply button updates history.replaceState
  with a ?text= param so the typed text is copy/pasteable.  Skips
  the update when the text is unchanged from what was open.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 17:10:31 -06:00
Behdad Esfahbod c85b453e90 [util/gpu] Web demos: URL ?text= and ?font=; wider default font
Two user-visible features plus a font swap.

### URL parameters

Forwards ?text= and ?font= from the query string into the C main
as --text=... and --font=... via Module.arguments, so the initial
text is applied before the first rendered frame (no flash of
default demo text).  ?font= is still fetched asynchronously on
the JS side; once loaded, the text is re-applied to the new font.

If neither parameter is present, behaviour is unchanged: the
baked-in default text renders in the baked-in default font.

Data URLs (?font=data:font/ttf;base64,...) work naturally via
fetch().  Remote URLs need CORS; raw.githubusercontent.com and
jsdelivr both work, github.com/.../raw/... does not.

### Wider default font

The baked-in default-font.hh was a narrow subset that didn't
include uppercase Latin, so `?text=Hello` shaped to .notdef for
H and W.  Re-subset Parastoo-Regular.ttf via hb-subset with:

    --unicodes='U+0020-007E,U+0600-06FF,U+FB50-FDFF,U+FE70-FEFF'

covering printable ASCII plus the Arabic block and the two
Arabic presentation-forms blocks.

Font size:
    source Parastoo-Regular.ttf     109152
    new subset                       49940

Wasm size impact (webgl build, Oz+lto):
    before  443628  181597 gz
    after   466657  196209 gz
    delta   +23029  +14612 gz

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 17:03:53 -06:00
Behdad Esfahbod 44a0fb1cd5 [util/gpu] Respect view-options: foreground, background, palette, custom-palette
Wires view_options_t into gpu_output_t so hb-gpu picks up the
same foreground/background/palette flags the rest of the tools
use:

  --foreground=#RRGGBB[AA]
  --background=#RRGGBB[AA]
  --font-palette=N
  --custom-palette=N=#RRGGBB[,N=#RRGGBB,...]

After demo_view_setup() the gpu main loop now:

1. Fetches the active palette from the face via
   demo_font_get_palette(font, view.palette, ...) -- palette index
   out of range falls back to 0.
2. Overlays each view.custom_palette_entries entry on top of that
   palette (clamped to 256 entries).
3. Uploads via renderer->set_palette().  Web demos and the
   headless WebGPU path do the same, with palette_index=0 (they
   don't yet plumb --font-palette).
4. Calls renderer->set_foreground / _background from the
   post-parsed view-options colours.  Defaults match the demo's
   prior LIGHT mode, so no-op when the user passes no flags; the
   dark-mode toggle (b key) still mutates renderer state
   independently.

Other view-options flags (--rainbow, --stroke, --line-space,
--margin, --logical/--ink, --show-extents, --font-extents)
appear in --help-view for familiarity but currently no-op in
hb-gpu; they're inherited wholesale from view_options_t and the
gpu path just doesn't wire them.

demo_font_get_palette() now takes a palette_index parameter so
callers can ask for non-zero palettes (e.g. dark-mode palettes in
fonts that ship them).  Web demos pass 0 for now.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 16:28:09 -06:00
Behdad Esfahbod cf3d69bc54 [util/gpu] Cross-backend palette upload via demo_renderer_t::set_palette
Reorganises the palette-upload plumbing so every backend handles
it uniformly and the hacky atlas-backend palette callback goes
away.

Before: demo_font_upload_palette in demo-font.cc mixed a GL
glUniform4fv direct call with a detour through an extra
demo_atlas_backend_t.upload_palette callback used by the Metal
renderer.  demo-font and demo-atlas both knew about palettes.

After:

* demo_font_get_palette (font, out, capacity) just reports the
  active palette as RGBA floats; demo-font no longer touches GL
  state or the atlas for palettes.

* demo_renderer_t gains a virtual set_palette (rgba, count).
  Default is a no-op.  Backends override:
   - demo-renderer-gl.cc -> demo_glstate_set_palette() ->
     glUniform4fv.
   - demo-metal.mm -> memcpy into the MTLBuffer's contents.
   - demo-renderer-d3d11.cc -> ID3D11DeviceContext::UpdateSubresource
     (palette buffer switched from IMMUTABLE to DEFAULT).
   - hb-gpu-web-webgpu.cc -> wgpuQueueWriteBuffer on the palette
     storage buffer.

* Callers invoke renderer->set_palette (palette, n) right after
  demo_font_create:
   - util/gpu-output.hh (desktop demo: GL / Metal / D3D11).
   - util/gpu/web/hb-gpu-web.cc (WebGL).
   - util/gpu/web/hb-gpu-web-webgpu.cc (WebGPU).

* The extra upload_palette field on demo_atlas_backend_t is
  removed along with demo_atlas_upload_palette / _is_external --
  atlas is back to being about glyph data only.

COLRv0 rendering now works with proper palette colours through
every backend that implements set_palette (WebGL, WebGPU, and
Metal/D3D11 once tested).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 16:19:13 -06:00
Behdad Esfahbod dfd5d5b3cb [gpu] Paint: port to HLSL/WGSL; add _hb_gpu_draw_impl; fix WGSL
This commit unblocks end-to-end paint rendering on the WebGPU
demo, adds the HLSL port, and avoids losing MSAA or stem
darkening along the way.

### Shared: _hb_gpu_draw_impl

hb_gpu_draw internally did fwidth(renderCoord) + MSAA.  That works
fine in the single-call-per-fragment case but not when called from
inside a non-uniform branch (e.g. an op-stream LAYER_SOLID
conditional in the paint fragment shader) -- WGSL rejects fwidth
from non-uniform control flow.

Factor the MSAA-aware body into _hb_gpu_draw_impl, which takes a
caller-supplied pixelsPerEm.  hb_gpu_draw is now a thin wrapper
that computes pixelsPerEm via fwidth and delegates.  The paint
fragment shader in every language now computes pixelsPerEm once
at the top of hb_gpu_paint and calls _hb_gpu_draw_impl per layer
-- MSAA preserved, no redundant fwidth calls per layer.

In WGSL, _hb_gpu_draw_impl also inlines the ppem computation from
pixelsPerEm rather than recurring into hb_gpu_ppem (which itself
calls fwidth).

### Paint shaders

- hb-gpu-paint-fragment.hlsl (new): HLSL transcription.  Assumes
  a caller-declared StructuredBuffer<float4> hb_gpu_palette at
  register(t1).
- hb-gpu-paint-fragment.wgsl: switched from hb_gpu_draw to
  _hb_gpu_draw_impl; comment updated.
- hb-gpu-paint-fragment.msl, .glsl: same switch, cached
  pixelsPerEm at entry.

hb_gpu_paint_shader_source() now returns content for all four
languages.

### Demos

- util/gpu/demo-fragment.glsl: restores stem darkening (dropped in
  the first paint wiring commit); applies to the premultiplied
  RGBA by scaling both colour and alpha.  The desktop GL demo
  regenerates demo-fragment-glsl.hh from this source.
- util/gpu/web/hb-gpu-web-webgpu.cc: WGSL fs_main concatenates the
  paint source, binds a zero-filled palette storage buffer at
  @group(0) @binding(2), and restores stem darkening.  fwidth
  hoisted outside the stem-darkening conditional so WGSL's
  derivative-uniformity rule is happy.
- util/gpu/demo-renderer-d3d11.cc: HLSL ps_main switches to
  hb_gpu_paint.  Adds a second StructuredBuffer<float4>
  hb_gpu_palette at t1, zero-filled for now, bound alongside the
  atlas SRV.

### Misc

- perf/benchmark-gpu.cc: fix stale reset/encode(draw) calls.

Measured build (local Emscripten):
  WebGL   index.wasm  : 443638  181640 gz
  WebGPU  webgpu.wasm : 461626  188400 gz

COLRv0 rendering (BungeeTint, Noto Color Emoji, etc.) now works
end-to-end on WebGL and WebGPU with the correct palette.  Metal
and D3D11 demos should likewise compile against the new shader
flow; real palette upload cross-backend remains a TODO.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:52:21 -06:00
Behdad Esfahbod d5f07d72d0 [gpu] Port paint fragment shader to WGSL; wire WebGPU demo
WGSL transcription of the paint interpreter.  Takes the atlas and
palette as explicit storage-buffer pointer parameters (matching
the WGSL draw helper's calling convention):

  fn hb_gpu_paint (renderCoord: vec2f, glyphLoc: u32,
		   foreground: vec4f,
		   hb_gpu_atlas: ptr<storage, array<vec4<i32>>, read>,
		   hb_gpu_palette: ptr<storage, array<vec4f>, read>) -> vec4f

hb_gpu_paint_shader_source() now returns real content for
HB_GPU_SHADER_LANG_WGSL fragment; HLSL still stubs to "".

util/gpu/web/hb-gpu-web-webgpu.cc:
  - Concats the paint source alongside the draw source into the
    WGSL shader module.
  - Declares @group(0) @binding(2) for hb_gpu_palette.
  - Allocates a 256 * vec4f storage buffer (zero-filled for now;
    real palette upload is TODO), binds it at entry index 2.
  - Fragment main switches from hb_gpu_draw to hb_gpu_paint.

util/gpu/web/gl-stub.h: adds glUniform4fv stub (demo-font.cc now
calls it for the GL palette path) and makes
glGetUniformLocation return -1 so the WebGPU build's
demo_font_upload_palette short-circuits.

Wasm sizes:
  WebGL   index.wasm  : 443628  181597 gz
  WebGPU  webgpu.wasm : 461110  188045 gz

Non-color text should render through WebGPU.  COLRv0 color glyphs
come up transparent until the cross-backend palette upload lands.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:27:41 -06:00
Behdad Esfahbod f587af3ec3 [gpu] Extract shared shader helpers into hb_gpu_shader_source() (#5921)
The draw-renderer fragment shaders defined utilities
(HB_GPU_UNITS_PER_EM, the hb_gpu_atlas uniform, hb_gpu_fetch) that
any future GPU renderer will also need.  The draw-renderer vertex
shader likewise contained only the generic hb_gpu_dilate helper.
If a paint renderer were added today and a caller linked both
fragment sources together, hb_gpu_fetch would be defined twice.

Move these shared helpers into a new family of sources and expose
them via a new public entry point:

  hb_gpu_shader_source (stage, lang);

The existing hb_gpu_draw_shader_source() now returns only the
draw-specific fragment code; it returns an empty string for the
vertex stage because all current vertex logic is shared.  Callers
concatenate the shared source first, then the draw-specific
source, then their own main():

  [#version, hb_gpu_shader_source (...), hb_gpu_draw_shader_source
  (...), main]

Additions:
 - src/hb-gpu-fragment.{glsl,msl,wgsl,hlsl} — shared fragment
 - src/hb-gpu-vertex.{glsl,msl,wgsl,hlsl}   — shared vertex,
   renamed from hb-gpu-draw-vertex.*
 - src/hb-gpu-shaders.cc — hb_gpu_shader_source() dispatcher

Removals:
 - src/hb-gpu-draw-vertex.{glsl,msl,wgsl,hlsl} — moved to common

Shared sources are Behdad-only copyright; the Eric Lengyel / Slug
attribution stays on the draw-specific fragment sources where the
Slug algorithm actually lives.

Updates: test/api/test-gpu.cc, the Metal/D3D11/WebGPU/GL demo
shaders, the hb-gpu SECTION documentation, meson.build,
CMakeLists.txt, gen-gpu-shader-artifacts.py decl_map,
harfbuzz-world.cc, and docs/harfbuzz-sections.txt.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 12:10:23 -06:00
Behdad Esfahbod a44eb976dc [gpu] Rename hb_gpu_draw_darken -> hb_gpu_stem_darken
The previous commit renamed hb_gpu_darken to hb_gpu_draw_darken
for symmetry with hb_gpu_draw (formerly hb_gpu_render).  But the
operation isn't draw-subsystem specific: it adjusts a coverage
value based on foreground brightness and ppem, which is just the
standard stem-darkening recipe.  Name it after what it does.

Paint doesn't need its own variant — it can call this same
function on any alpha/coverage channel it produces.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 02:59:37 -06:00
Behdad Esfahbod daddae08a3 [gpu] Rename fragment-shader entry points with "draw_" prefix
Rename the public fragment-shader entry points provided by the
hb_gpu_draw_t renderer:

  hb_gpu_render(...)   -> hb_gpu_draw(...)
  hb_gpu_darken(...)   -> hb_gpu_draw_darken(...)

Also rename the internal helper:

  _hb_gpu_render_single(...) -> _hb_gpu_draw_single(...)

A COLRv1 paint renderer is planned and will provide its own
fragment entry point (likely hb_gpu_paint returning a vec4); the
existing draw/coverage entry point gets a subsystem-qualified name
now so draw and paint can coexist.

Updates the .glsl/.msl/.wgsl/.hlsl sources, regenerated .hh
artifacts, the documentation block in hb-gpu.cc, and the util/gpu
demo shaders.  No behavior change.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 02:57:07 -06:00
Behdad Esfahbod eeec9bd9fa [gpu] Unify shader source getters; rename for draw/paint split
Replace the two separate getters

  hb_gpu_shader_fragment_source (lang)
  hb_gpu_shader_vertex_source   (lang)

with a single

  hb_gpu_draw_shader_source (stage, lang)

where stage is the new hb_gpu_shader_stage_t enum (VERTEX or
FRAGMENT).  Parameter order is stage-first because "the vertex
shader in GLSL" reads more naturally than the reverse, and stage
is the primary axis (it determines which shader object the source
is compiled into).

The `_draw_` in the new name makes room for the incoming
hb_gpu_paint_shader_source() once the COLRv1 encoder lands —
that family will have its own (likely different) shader sources
per stage and language.

Updated the four in-tree callers: test/api/test-gpu.cc, and the
GPU demos under util/gpu/.  ABI break on a 14.0-only API; the
gpu library is still young enough that this is acceptable.

Marked new API with XSince: REPLACEME.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 02:26:21 -06:00
Behdad Esfahbod 0234df4db6 [gpu] Fix WebGPU error page not showing when adapter unavailable
Check navigator.gpu synchronously in main() before calling
the WebGPU C API.  Previously the error was reported in an
async callback that raced with onRuntimeInitialized, which
hid the loading div before the error message could appear.

Also re-show the loading div and set window._webgpuError in
the adapter callback as a fallback.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-02 01:26:54 -06:00
Behdad Esfahbod 5eb52c7407 [gpu] Fix display() signature in D3D11, Metal, and WebGPU renderers
Drop HB_UNUSED from the generation parameter — it's not
available in MinGW or Emscripten build contexts.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-01 23:52:54 -06:00
Behdad Esfahbod c86cb51bf6 [gpu] Fix garbled rendering after font change in web demo
The GL renderer cached the vertex buffer upload by comparing
the data pointer and count.  After clearing and refilling the
buffer with a new font's glyphs, std::vector reused the same
allocation, so the pointer and count matched — the upload was
skipped and the GPU drew with stale vertex data containing old
atlas offsets.

Fix by adding a generation counter to demo_buffer_t that
increments on clear().  The renderer compares generation and
count to decide whether to re-upload.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-01 23:25:48 -06:00
Behdad EsfahbodandClaude Opus 4.6 14effc302a [gpu] Add hb_gpu_darken() to all shader languages
Library function for stem darkening: pow(2, brightness-0.5)
scaled by ppem. Added to GLSL, MSL, WGSL, HLSL with consistent
brief docs. Demo shaders now call the library function.
Section docs in hb-gpu.cc updated with usage example.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 19:49:42 -06:00
Behdad EsfahbodandClaude Opus 4.6 9e2828622c [gpu] Use pow(2, brightness-0.5) for stem darkening
Replace boolean light_on_dark with continuous brightness-driven
exponent. pow(2, b-0.5) gives sqrt(2)≈1.414 for white text
(thin) and 1/sqrt(2)≈0.707 for black text (fatten), perfectly
symmetric around 1.0 at 50% gray.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 19:25:31 -06:00
Behdad Esfahbod 9e0d8d48c4 Revert "Revert "[webgpu] Align touch handoff with WebGL fixes""
This restores commit 00a3475ce.

Testing:
- source /home/behdad/emsdk/emsdk_env.sh >/dev/null &&
  EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build.sh
- source /home/behdad/emsdk/emsdk_env.sh >/dev/null &&
  EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build-webgpu.sh

Assisted-by: OpenAI Codex
2026-03-30 18:40:40 -06:00
Behdad Esfahbod a7367b65e2 Revert "[webgpu] Align touch handoff with WebGL fixes"
This reverts commit 00a3475ce.

Testing:
- source /home/behdad/emsdk/emsdk_env.sh >/dev/null &&
  EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build.sh
- source /home/behdad/emsdk/emsdk_env.sh >/dev/null &&
  EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build-webgpu.sh

Assisted-by: OpenAI Codex
2026-03-30 18:39:20 -06:00
Behdad Esfahbod 00a3475ce0 [webgpu] Align touch handoff with WebGL fixes
The WebGPU touch path was still using the older gesture state machine.
It handled 3->2 reseeding, but it did not track whether a pinch was
active and it had no explicit 2->1 single-finger pan handoff.

Carry over the proven transition rules from the WebGL path without
changing desktop input handling: track pinch-active and synthetic
single-pan state, preserve the 3->2 reseed, and continue pan after a
pinch when one finger remains. touchcancel now also clears those touch
states consistently.

Testing:
- source /home/behdad/emsdk/emsdk_env.sh >/dev/null &&
  EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build.sh
- source /home/behdad/emsdk/emsdk_env.sh >/dev/null &&
  EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build-webgpu.sh

Assisted-by: OpenAI Codex
2026-03-30 18:36:54 -06:00
Behdad Esfahbod bef4c6a79e [web] Handle touchcancel in touch gestures
Track the last gesture centroid and explicitly handle touchcancel
for both web gesture paths. This clears active gesture state
without turning browser-driven cancellation into a tap, fling, or
stuck drag.

Testing:
- sh -n util/gpu/web/build.sh
- sh -n util/gpu/web/build-webgpu.sh
- EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build.sh
- EM_CACHE=/tmp/emscripten-cache ./util/gpu/web/build-webgpu.sh
  (blocked offline fetching emdawnwebgpu)

Assisted-by: OpenAI Codex
2026-03-30 12:14:59 -06:00
0bdd933a1e [gpu] Fix 3-finger to 2-finger touch transition
Properly handle finger count transitions with cooldown and
state reinitialization to prevent jumps in zoom/rotation.

Co-Authored-By: Codex <noreply@openai.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 11:54:03 -06:00
Behdad EsfahbodandClaude Opus 4.6 d8f1c44fd3 [gpu] Skip first touchmove after finger count change
Prevents jumps during 3→2→1 finger transitions by dropping
one frame and reinitializing pinch state for the new finger
count.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 11:36:22 -06:00
Behdad EsfahbodandClaude Opus 4.6 dac2716b2a [gpu] Fix 3-finger to 2-finger transition jump
Reinitialize pinch state (distance, angle, centroid) when
exiting 3-finger mode with 2 fingers remaining. Prevents
large zoom/rotate delta from stale pinch values.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 11:29:07 -06:00
fa50f16e51 [gpu] Fix black screen on resume with web_request_redraw
Add demo_view_request_redraw() and export as _web_request_redraw.
Shell calls it on visibilitychange, focus, pageshow, and
webglcontextrestored events to force a redraw after phone
lock/unlock or tab switch.

Co-Authored-By: Codex <noreply@openai.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 11:17:42 -06:00
Behdad EsfahbodandClaude Opus 4.6 6b111e5ca2 [gpu] Fix mobile gestures: long-press reset, double-tap-drag zoom
Long-press uses _web_reset directly with 10px jitter threshold.
Double-tap-drag undoes first tap's animation toggle via
_web_toggle_animation, then preventDefault blocks GLFW from
seeing the second tap.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 10:59:04 -06:00
Behdad EsfahbodandClaude Opus 4.6 9da25b8a1f [gpu] Rework pinch: unified pan+zoom+rotate gesture
Single demo_view_pinch() handles all three components atomically:
- Pan from centroid movement
- Zoom around centroid (proven middle-drag math)
- Screen-space Z rotation (separate from 3D quaternion)

Pinch rotation uses a screen_angle field applied as a post-MVP
2D rotation, keeping it independent from the 3D trackball.
Zoom centering works correctly; rotation centering is approximate.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 10:19:45 -06:00
Behdad EsfahbodandClaude Opus 4.6 7659baca01 [gpu] Pinch-zoom around pinch center
Adds demo_view_zoom_around() which scales while compensating
translation so the midpoint between fingers stays fixed.
Same maps-like behavior as the pinch rotation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 09:44:40 -06:00
Behdad EsfahbodandClaude Opus 4.6 c1550337db [gpu] Pinch-rotate around pinch center, not screen center
Adds demo_view_rotate_z_around() which compensates translation
so the point between the two fingers stays fixed during rotation,
like maps apps.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 09:40:56 -06:00
Behdad EsfahbodandClaude Opus 4.6 16c30ac052 [gpu] Add pinch-to-rotate alongside pinch-to-zoom
Two-finger pinch now does both zoom (distance change) and Z-axis
rotation (angle change) simultaneously. Adds demo_view_rotate_z()
for direct Z-axis rotation from touch input.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 09:35:53 -06:00
Behdad EsfahbodandClaude Opus 4.6 2760be8109 [gpu] Add debug heatmap to WebGPU demo
Now that the WGSL shader has _hb_gpu_curve_counts, wire up
the debug uniform and heatmap visualization. Same R/G/B output
as the GL demo.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 22:05:11 -06:00
Behdad EsfahbodandClaude Opus 4.6 23c2d3de0c [gpu] Handle canvas resize in WebGPU demo
Check canvas size each frame and reconfigure the WebGPU surface
when it changes. Fixes black screen when toggling dev tools or
resizing the browser window.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 21:59:59 -06:00
Behdad EsfahbodandClaude Opus 4.6 286c40ad71 [gpu] Add stem darkening to WebGPU demo
Same per-pixel coverage adjustment as the GL demo. Replaces
unused debug uniform with stem_darkening in the uniform buffer.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 20:42:15 -06:00
Behdad EsfahbodandClaude Opus 4.6 07598f4bb2 [gpu] Support middle-click in WebGPU demo
Map DOM button 1 (middle) to GLFW middle button so middle-click
reset and middle-drag zoom work.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 18:42:05 -06:00
Behdad EsfahbodandClaude Opus 4.6 b68fc1de22 [gpu] Fix WebGPU scroll zoom sensitivity
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 18:05:29 -06:00
Behdad EsfahbodandClaude Opus 4.6 5a08291dde [gpu] Use raw string literal for WGSL demo shader
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 18:03:41 -06:00
Behdad EsfahbodandClaude Opus 4.6 b42cd76d05 [gpu] Remove debug heatmap from WebGPU demo
The WGSL shader compilation fails with _hb_gpu_curve_counts.
Debug mode is available in desktop and WebGL demos.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 17:44:30 -06:00
Behdad EsfahbodandClaude Opus 4.6 c2618a00c4 [gpu] Use alpha blending for debug heatmap
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 17:42:21 -06:00
Behdad EsfahbodandClaude Opus 4.6 ddd6a86470 [gpu] Add debug heatmap mode (d key)
Refactor library fragment shaders (GLSL, MSL, WGSL) to extract
_hb_gpu_decode_glyph and _hb_gpu_curve_counts helpers, used by
both hb_gpu_render and the debug visualization.

Debug mode (d key) shows per-pixel curve counts as a heatmap:
R = horizontal band curves, G = vertical band curves, B = text
coverage. Scale 0-8 curves maps to 0-1 intensity.

Also auto-generates demo shader headers via meson, and adds
set_debug to the renderer interface.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 17:40:38 -06:00
Behdad EsfahbodandClaude Opus 4.6 47512ddcb4 [gpu] Add Backspace as alternative reset key
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 16:48:32 -06:00
Behdad EsfahbodandClaude Opus 4.6 98f7d746f3 [gpu] Add 3-finger touch gesture for 3D rotation
Three-finger drag on mobile now does trackball rotation, matching
right-drag on desktop. Uses centroid of three touch points.
Release with momentum triggers spin animation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 16:18:44 -06:00