Commit Graph
16190 Commits
Author SHA1 Message Date
Behdad EsfahbodandClaude Opus 4.6 dba4dab3ef [vector-paint] Fold scale_factor into PDF per-glyph cm
Follow-up to 152aa0fd8c.  The SVG branch of
hb_vector_paint_glyph divides the instance transform by
x_scale_factor/y_scale_factor (via
hb_vector_svg_append_instance_transform) so input-space
glyph paths land in the pixel-space viewBox.  The PDF
branch emitted the raw paint matrix, which kept the CTM in
input space while the MediaBox lived in pixel space —
at any non-identity scale_factor, the glyph rendered
entirely outside the page.

Divide the matrix columns by sx/sy in the emitted cm so
PDF matches SVG.  Covers hb-vector's font-size != 20 case
and the website's scale_factor = 64 case, where emoji
rendered blank at 72 px.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 02:42:29 -06:00
Behdad Esfahbod 152aa0fd8c [vector] Divide explicit set_extents by scale_factor
hb_vector_{paint,draw}_set_extents stored caller-supplied
extents as-is, while per-glyph extents accumulated via
hb_vector_set_glyph_extents_common were divided by
scale_factor on the way in.  When callers passed extents in
input-space (the natural unit alongside the glyph geometry
they're feeding) and a non-1 scale_factor, the resulting
viewBox didn't match what the glyphs drew.

Make set_extents divide by scale_factor too, matching the
accumulate path; callers can now pass input-space extents
uniformly.

Also:

* hb-vector-paint's global transform wrapper dropped the
  redundant /scale_factor division.  Each per-glyph
  <use transform="... scale(1/scale_factor, ...)"> already
  applies scale_factor; wrapping the body in another
  /scale_factor matrix double-scaled the output, shrinking
  color-glyph output to 1/scale_factor^2 of its intended
  size.  The wrapper now only fires when the user set a
  non-identity paint->transform, and emits that transform
  as-is.

* util/vector-output.hh simplification: now that set_extents
  handles the divide, drop the local pre-multiply of extents
  by upem_to_pixel -- pass the upem-space extents through.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:04:26 -06:00
Behdad Esfahbod d8980e94e0 [draw] Add line/rect/circle drawing helpers (#5925)
* [gpu] Add hb_gpu_draw_line / _rect / _circle shape helpers

The GPU draw encoder already consumes arbitrary curves via the
hb_draw_funcs_t machinery -- that's how glyph outlines feed in.
Expose three convenience helpers so callers can emit common
shapes (tapered line, rectangle, circle) without having to
hand-roll the curve math:

    hb_gpu_draw_line   (draw, x0,y0,w0, x1,y1,w1);
    hb_gpu_draw_rect   (draw, x,y,w,h, stroke_width);
    hb_gpu_draw_circle (draw, cx,cy,r, stroke_width);

stroke_width = NaN means "filled".  A finite positive value
produces a stroked outline by emitting an outer contour CCW
and an inner contour CW so the fill rule carves a hole.

For shapes beyond these three helpers, callers can feed any
outline through hb_draw_move_to / _line_to / _quadratic_to /
_cubic_to / _close_path with the funcs from
hb_gpu_draw_get_funcs() and the hb_gpu_draw_t as data -- the
helpers are thin wrappers over that path.

Useful for game UI: health bars, progress rings, custom
line-art decorations, rendered through the same slug shader
as text.

Assisted-by: Claude <noreply@anthropic.com>

* [util/gpu] Add --show-extents flag

Exercises hb_gpu_draw_rect: when the flag is set, each glyph
blob encodes its ink-extent frame as an extra stroked
rectangle alongside the glyph outline, so the frame is cached
with the glyph and renders with no extra draw call.

The frame is padded outward by stroke_width / 2 so the stroke
sits entirely outside the glyph ink (otherwise the inner half
would knock out against the glyph shape, since both fill in
the same blob).

Cmdline-only for now -- a runtime 'e' toggle would require a
buffer re-shape hook that native hb-gpu doesn't yet expose.

Assisted-by: Claude <noreply@anthropic.com>

* [util/gpu] Cmdline toggles mirroring interactive keybindings

Add --dark / --no-vsync / --fullscreen / --no-stem-darken /
--debug so scripts and CI can start hb-gpu in any of the
states previously reachable only by pressing a key
interactively.  Applied via the same keystroke path by
synthesizing the corresponding key characters through
demo_view_type() at startup -- single source of truth for
each toggle.

Assisted-by: Claude <noreply@anthropic.com>

* [draw] Promote shape helpers from hb-gpu-draw to hb-draw

Three shape-emitting helpers (line, rect, circle) operate on
any hb_draw_funcs_t, not specifically the GPU backend.  Move
them out of the GPU-only API surface into the core hb-draw
API so any pen (raster, vector, gpu, user-supplied) gets
them.

API rename / move:

  hb_gpu_draw_line   -> hb_draw_line   (in src/hb-draw.h)
  hb_gpu_draw_rect   -> hb_draw_rect
  hb_gpu_draw_circle -> hb_draw_circle

Signatures gain a (dfuncs, draw_data, st) prefix to match the
existing hb_draw_move_to / line_to / cubic_to / close_path
shape -- the helpers are thin wrappers over those.

Callers in test/api/test-gpu.cc and util/gpu/demo-font.cc
updated to call hb_draw_* with hb_gpu_draw_get_funcs() and a
local hb_draw_state_t.

Updated harfbuzz-sections.txt with the new entries; removed
hb_gpu_draw_line / _rect / _circle from hb-gpu.h.

Assisted-by: Claude <noreply@anthropic.com>

* [draw] hb_draw_line: NaN second width defaults to first

Common case is a uniform-width line.  Letting @w1 default to
@w0 when NaN is passed makes the call shorter:

  hb_draw_line (..., x0, y0, 4, x1, y1, NAN);  /* uniform 4 */

Mirrors the NaN-as-sentinel convention used in hb_draw_rect /
hb_draw_circle for the stroke_width parameter.

Assisted-by: Claude <noreply@anthropic.com>

* [draw] hb_draw_line: add cap parameter (butt / square)

Add hb_draw_line_cap_t enum with HB_DRAW_LINE_CAP_BUTT (the
existing default behavior) and HB_DRAW_LINE_CAP_SQUARE, which
extends each endpoint along the line direction by half its
local stroke width.

Square caps let four hb_draw_line() calls form a closed
rectangle without gaps at the corners -- a meaningfully
cheaper alternative to hb_draw_rect() for thin outlined
rectangles, since each line's bbox is just stroke_width tall
instead of covering the full rectangle interior.

Round caps not implemented yet; can be added as a third enum
value when a use case shows up.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 21:49:45 -06:00
Behdad Esfahbod f53d20c425 [gpu] Use centralized paint helpers; rename sweep tiler
Two cleanups:

* Drop hb-gpu-paint's local reduce_linear_anchors and
  normalize_stops, use the shared
  hb_paint_reduce_linear_anchors() and
  hb_paint_normalize_color_line() from hb-paint.hh.  All
  four backends (cairo, raster, vector, gpu) now share one
  implementation.

* Rename the sweep-gradient tiler from hb_sweep_gradient_tiles
  to hb_paint_sweep_gradient_tiles to match the namespace
  convention of the other paint helpers.

No behavior change.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 17:31:37 -06:00
Behdad Esfahbod 80807b128d [vector] Normalize color-line stops to [0, 1] before emit
SVG <stop offset="..."> requires offsets in [0, 1].  Out-of-
range stops were silently clamped by browsers, producing
visually wrong gradients for COLR fonts whose color lines
extend past those bounds.

Use the centralized hb_paint_normalize_color_line() to rescale
stops in place; shift the gradient axis (linear) / centers and
radii (radial) / start+end angles (sweep) by (mn, mx) along
the gradient axis to keep the visible gradient in the same
place.

Drop the now-unused local hb_vector_color_stop_cmp -- the
shared normalize helper sorts internally.

Regenerate the two affected basic.tests expected SVGs.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 17:31:37 -06:00
Behdad Esfahbod 6bbf421030 [paint] Centralize normalize_color_line in hb-paint.hh
Same routine appeared in hb-cairo-utils and hb-raster-paint.
Move to hb-paint.hh as hb_paint_normalize_color_line() and
update both call sites.  Behavior unchanged.

(hb-vector-paint and hb-gpu-paint still need normalization
work, separately.)

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 17:31:37 -06:00
Matej Smycka 488922519f [arabic] Fix overflow handling in apply_stch (#5929) 2026-04-15 16:19:06 -06:00
Behdad Esfahbod f8491cdb66 [paint] Centralize reduce_anchors in hb-paint.hh
hb-cairo-utils and hb-raster-paint each carried their own
identical static copy of the COLR 3-anchor → 2-point gradient
projection.  Drop both, use the shared
hb_paint_reduce_linear_anchors() added in the previous commit.
Behavior unchanged.

(hb-gpu-paint keeps its own copy intentionally -- it has
slightly different surrounding code paths and we don't want
to perturb the GPU encoder in this round.)

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:44:28 -06:00
Behdad Esfahbod ce4199c303 [vector] Fix linear-gradient anchor reduction
hb-vector-paint emitted (2*x1 - x2, 2*y1 - y2) as the SVG end
point -- the reflection of P2 about P1, not the projection.
For COLR linear gradients the SVG end should be P1 projected
onto the line through P0 perpendicular to (P2 - P0); that's
the gradient's actual axis (perpendicular to the rotation
line).  With the old formula, fonts with rotation references
far from the color line ended up with massively over-scaled
gradient axes -- e.g. BungeeSpice's ABC showed solid red where
raster shows a full red->yellow gradient.

Add hb_paint_reduce_linear_anchors() to hb-paint.hh as the
shared canonical implementation (matches hb-raster-paint and
hb-cairo) and use it from hb-vector-paint.

Regenerate the two affected basic.tests expected SVGs; the
new gradient endpoints are now consistent with the cairo /
raster outputs.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:44:10 -06:00
Behdad Esfahbod addaafd255 [vector] Rename svg_{set,get}_prefix to {set,get}_svg_prefix
Verb-then-thing matches the rest of the hb-vector setter/getter
naming (set_precision, set_palette, etc.).  Update the renamed
internal references and the NEWS / harfbuzz-sections.txt entries
to match.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:07:05 -06:00
Behdad EsfahbodandClaude Opus 4.6 ca75fd5ff9 [vector] Drop hb_vector_{draw,paint}_{set,get}_flat (#5927)
Flat mode disabled glyph reuse / caching to produce inline-
everything SVG output.  Its main use case was making
hb-vector SVGs safe to concatenate side-by-side in a single
document, but the recently-added svg_set_prefix API solves
that without giving up the cache.  No remaining callers in
tree (util/vector-output.hh's --flat option goes too).

Removes:
  - hb_vector_draw_set_flat / get_flat
  - hb_vector_paint_set_flat / get_flat
  - the `flat` field on both contexts
  - all `if (flat)` / `bool can_cache = !flat` branches
  - the --flat option in util/vector-output.hh
  - the four "flat*" expected files in test/vector/basic
  - the flat_draw / flat_paint params in the vector fuzzer
  - sections-list entries

meson test --no-rebuild green (241/241).

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:03:43 -06:00
Behdad EsfahbodandClaude Opus 4.6 7fe31859ca [config] Drop HB_NO_SUBSET_LAYOUT from HB_LEAN
HB_LEAN was dropping GSUB/GPOS out of the subset output,
which turns subsetting Arabic / Indic / any complex-script
font into a paperweight: the produced subset has no layout
so it can't shape the text it was subsetted for.  That's
not really "lean", that's broken for most non-Latin use.

Subset layout is load-bearing enough that it should stay in
any HB_LEAN / HB_TINY build.  Callers that truly don't want
it can still #define HB_NO_SUBSET_LAYOUT themselves.

meson test --no-rebuild is green (241/241).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 12:48:05 -06:00
Behdad EsfahbodandClaude Opus 4.6 251c9d26e0 [vector] Apply svg prefix to the color-glyph first-use <use href>
Missed one emission site in the SVG color-glyph path: when a
color glyph is first seen, hb-vector both defines it in
<defs id="cg<N>"> (which I prefixed) and emits an initial
<use href="#cg<N>"> in the body (which I did not).  The mix
meant body refs for the first use of every color glyph went
unprefixed, so a caller-prefixed document had refs pointing
to nonexistent IDs and the whole image came out blank.

Fix: route that href="#cg<N>" through the prefix too.

Verified on Noto Emoji subset: rsvg-convert with a "v1-"
prefix now renders the full color glyph (was blank before).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 11:52:23 -06:00
Behdad EsfahbodandClaude Opus 4.6 c3b0c4e282 [vector] Add hb_vector_{draw,paint}_svg_{set,get}_prefix
New public API for namespacing SVG output: callers that embed
multiple hb-vector-produced SVGs into the same document can
set a distinct id prefix per context, so hb-vector's short
internal IDs (p<N>, c<N>, clip-g<N>, gr<N>, cg<N>) don't
collide across snippets.

Example collision the new API prevents: page embeds two
hb-vector SVGs produced by different contexts.  Both use
id="clip-g10"; the browser's url(#clip-g10) resolves to
whichever element appears first, so paint layers in the
second SVG get clipped against the first SVG's glyph outline
-- visible as giant unclipped color rects bleeding across
the wrong glyph shape.

With the new API the second caller passes e.g. "b-" as its
prefix; the clash disappears.  Empty/NULL prefix preserves
the existing output byte-for-byte.

Affects every id / url(#...) / href="#..." emission in SVG
output:
  - hb-vector-draw: <path id="p..."> + <use href="#p...">
  - hb-vector-paint: <path>, <clipPath>, <linearGradient>,
    <radialGradient>, <g id="cg..."> color-glyph cache, and
    every corresponding url(#...) / href="#..." ref.
PDF output is unaffected (no ids).

Docs/harfbuzz-sections.txt updated; check-symbols passes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 11:48:54 -06:00
Behdad Esfahbod cd1af387ba Revert "[vector] Flat mode: inline clip-path="path('...')" instead of <clipPath>"
This reverts commit 3fe077d713.
2026-04-15 11:40:04 -06:00
Behdad EsfahbodandClaude Opus 4.6 3fe077d713 [vector] Flat mode: inline clip-path="path('...')" instead of <clipPath>
Flat output was still emitting <clipPath id="..."> into <defs>
and referencing them via clip-path="url(#...)".  That meant
flat SVGs couldn't be safely concatenated: two documents'
short IDs (c0, clip-g10, ...) would collide and url(#c0)
resolves to whichever element appears first in document
order, producing the wrong clip and giant paint rects
falling through their clips.

SVG 2 lets clip-path take inline basic-shape or path()
values.  In flat mode, emit:

  push_clip_glyph     -> clip-path="path('<glyph-d>')"
  push_clip_rectangle -> clip-path="path('M..H..V..H..Z')"

...directly on the wrapping <g>, skipping defs entirely.
The resulting flat SVG truly has no defs for clips and is
safe to embed alongside other hb-vector output.

Gradients still use defs (paint servers need URL refs), but
those only affect color, not geometry -- a gradient
resolution mismatch yields wrong colors, never the
unclipped-rect bleed that was the visible symptom.

Verified on util/gpu/web/ / harfbuzz-world.cc's Noto color
emoji subset: no <clipPath> tags, no clip-path="url(...)",
69 inline clip-path="path('...')" refs instead.  Meson
test --suite vector remains 22/22 green.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 11:34:51 -06:00
Behdad EsfahbodandClaude Opus 4.6 b7a7d33052 [src] Add HB_*_CC include guards to three world.cc dup-include sources
src/harfbuzz-world.cc unconditionally #includes hb-number.cc,
hb-ot-cff1-table.cc, and hb-ot-cff2-table.cc in its core
group, then re-#includes the same three files in its
HB_HAS_SUBSET group (carried over from when the subset
library was its own translation unit).  In the single-TU
amalgamation that's a redefinition error and prevents
HB_HAS_SUBSET from being enabled.

Wrap each file in the same HB_FOO_CC ifndef/define/ifdef
guard pattern already used by hb-static.cc and hb-zlib.cc, so
a second #include is a no-op.

Verified with a wasm build of harfbuzz-world.cc that has both
the core and subset blocks active, and a full meson test
run (241/241 OK) on the regular library build.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 05:14:50 -06:00
Behdad Esfahbod a0ae5ee262 [config] In HB_TINY, don't disable draw/paint if any libs need it 2026-04-15 04:31:22 -06:00
Behdad Esfahbod fd2a6968ab [draw] hb_draw_line: add cap parameter (butt / square)
Add hb_draw_line_cap_t enum with HB_DRAW_LINE_CAP_BUTT (the
existing default behavior) and HB_DRAW_LINE_CAP_SQUARE, which
extends each endpoint along the line direction by half its
local stroke width.

Square caps let four hb_draw_line() calls form a closed
rectangle without gaps at the corners -- a meaningfully
cheaper alternative to hb_draw_rect() for thin outlined
rectangles, since each line's bbox is just stroke_width tall
instead of covering the full rectangle interior.

Round caps not implemented yet; can be added as a third enum
value when a use case shows up.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 02:35:10 -06:00
Behdad Esfahbod 28122c755d [draw] hb_draw_line: NaN second width defaults to first
Common case is a uniform-width line.  Letting @w1 default to
@w0 when NaN is passed makes the call shorter:

  hb_draw_line (..., x0, y0, 4, x1, y1, NAN);  /* uniform 4 */

Mirrors the NaN-as-sentinel convention used in hb_draw_rect /
hb_draw_circle for the stroke_width parameter.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 02:28:55 -06:00
Behdad Esfahbod e731c38975 [draw] Promote shape helpers from hb-gpu-draw to hb-draw
Three shape-emitting helpers (line, rect, circle) operate on
any hb_draw_funcs_t, not specifically the GPU backend.  Move
them out of the GPU-only API surface into the core hb-draw
API so any pen (raster, vector, gpu, user-supplied) gets
them.

API rename / move:

  hb_gpu_draw_line   -> hb_draw_line   (in src/hb-draw.h)
  hb_gpu_draw_rect   -> hb_draw_rect
  hb_gpu_draw_circle -> hb_draw_circle

Signatures gain a (dfuncs, draw_data, st) prefix to match the
existing hb_draw_move_to / line_to / cubic_to / close_path
shape -- the helpers are thin wrappers over those.

Callers in test/api/test-gpu.cc and util/gpu/demo-font.cc
updated to call hb_draw_* with hb_gpu_draw_get_funcs() and a
local hb_draw_state_t.

Updated harfbuzz-sections.txt with the new entries; removed
hb_gpu_draw_line / _rect / _circle from hb-gpu.h.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 02:27:43 -06:00
Behdad Esfahbod cfdcea6c79 [gpu] Add hb_gpu_draw_line / _rect / _circle shape helpers
The GPU draw encoder already consumes arbitrary curves via the
hb_draw_funcs_t machinery -- that's how glyph outlines feed in.
Expose three convenience helpers so callers can emit common
shapes (tapered line, rectangle, circle) without having to
hand-roll the curve math:

    hb_gpu_draw_line   (draw, x0,y0,w0, x1,y1,w1);
    hb_gpu_draw_rect   (draw, x,y,w,h, stroke_width);
    hb_gpu_draw_circle (draw, cx,cy,r, stroke_width);

stroke_width = NaN means "filled".  A finite positive value
produces a stroked outline by emitting an outer contour CCW
and an inner contour CW so the fill rule carves a hole.

For shapes beyond these three helpers, callers can feed any
outline through hb_draw_move_to / _line_to / _quadratic_to /
_cubic_to / _close_path with the funcs from
hb_gpu_draw_get_funcs() and the hb_gpu_draw_t as data -- the
helpers are thin wrappers over that path.

Useful for game UI: health bars, progress rings, custom
line-art decorations, rendered through the same slug shader
as text.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 01:54:08 -06:00
Behdad Esfahbod d529a3ca90 [bit-set][hashmap] clear() under error state: early-out on empty
Previously clear() bailed outright under !successful, to protect
the Null singleton which lives in (possibly read-only) static
storage.  That meant a real instance entering error state would
silently fail to clear, leaving stale contents for the next
caller.

Replace the `!successful` guard with an early-out on already-
empty state.  The Null singleton is zero-initialized (population,
occupancy, mask all 0), so the early-out catches it before any
write.  Any non-empty instance is by construction a real heap
object with writable storage, so clearing is safe there even
under !successful.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 22:13:42 -06:00
Behdad Esfahbod 8e7e29a691 [bit-set] Revert clear() change -- can't touch Null singleton
The prior commit (2adb01a47c) made hb_bit_set_t::clear() always
zero length/population, parallel to the hb_vector_t::clear()
March fix.  But hb_bit_set_t (and hb_hashmap_t) have a different
invariant: an instance returned from a failed create-or-reference
path is an inert / Null singleton in possibly read-only storage,
so clear() MUST bail on !successful or it would segfault.

This was exactly what the `if (unlikely (!successful)) return;`
guard was protecting.  test-set caught the regression.

Vector is different: it has no Null singleton returned to users,
so always-clearing is safe there.

The graph/serialize.hh resize(0) -> clear() change from the same
commit is still correct -- that's a caller-supplied vector, not
a set.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 22:11:04 -06:00
Behdad Esfahbod 2adb01a47c [internal] Replace remaining vector resize(0) with clear()
Two callers were still using vector.resize(0) to drop accumulated
data: graph/serialize.hh's overflow tracking and hb_bit_set_t's
clear() (via its own internal resize()).  resize(0) on a vector
in error state short-circuits without zeroing length, leaving
stale entries that downstream code then walks as if valid.

Fix both:

 - serialize.hh: call overflows->clear() instead.
 - hb-bit-set.hh: reimplement clear() to zero length/population
   unconditionally by calling pages.clear() / page_map.clear()
   directly, bypassing the internal resize() that bails when
   `successful` is false.

Mirrors the March clear() fix in hb-vector.hh (commit d134f88824).

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 22:04:57 -06:00
Behdad Esfahbod fe04146acb [vector] Simplify reset() to use clear() instead of resize(0)
After the March refactor that made clear() a direct
shrink_vector(0), reset() going through resize(0) adds an
indirection (resize_full -> alloc(0) no-op -> shrink_vector(0))
for identical observable behavior.  Use clear() directly.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 22:00:32 -06:00
Behdad Esfahbod df4be0cec8 [gpu] Use vector.reset() not resize(0) in hb_gpu_paint_clear
Three accumulator vectors -- ops, sub_blobs, transform_stack --
can enter error state via failed push_or_fail() under
failing-malloc.  Once in error state, resize(0) short-circuits
at the in_error() guard in alloc() and leaves length unchanged.

In hb_gpu_paint_clear that means the next iteration's clear
walks the stale entries again.  For sub_blobs this is a
double-destroy: the blob pointers were already freed in the
previous clear, and hb_blob_destroy reads the dead ref_count
field -- heap-use-after-free.

Fix by calling vector.reset(), which clears the error state
before resizing to 0.  Matches the pattern hb_gpu_draw_clear
already uses for draw->curves.

Found by oss-fuzz/CIFuzz on hb-gpu-fuzzer; minimized testcase
added to the fuzz corpus.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 21:49:12 -06:00
Behdad Esfahbod 24aa15d39a [gpu] Cap accumulated curves per glyph to bound memory
The curve accumulator grew without bound, reaching 2.9 GB on
fuzzer-crafted inputs (VARC components expanded recursively, or
cu2qu subdivisions on degenerate cubics, or a glyf with absurd
contour counts).  libFuzzer flags this as OOM.

Add HB_GPU_DRAW_MAX_CURVES = 0x10000 (65536) -- far above any
real glyph's needs -- and refuse to emit beyond it, flipping
success=false so the encoder returns a valid empty/failure
blob.  Catches all upstream explosions (glyf / cu2qu / VARC /
any future source) at the single choke point.

Found by oss-fuzz/CIFuzz on hb-gpu-fuzzer.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 21:36:18 -06:00
Behdad Esfahbod 25bfb5adc3 [vector-paint/pdf] Check color-stops vector resize under failing-malloc
Two sites queried color-stop count, resized the scratch vector to
match, then called hb_color_line_get_color_stops() passing the
requested count as the write capacity.  If the resize() failed
(OOM), the vector stayed at its previous (smaller) length while
the callee still wrote the full requested count -- heap-buffer-
overflow.

Fixed by checking resize() and bailing: build_gradient_function
returns 0, paint_sweep_gradient returns.  Matches the pattern
already used in hb-raster-paint.cc and hb-vector-paint.cc.

Found by oss-fuzz/CIFuzz on hb-vector-fuzzer against a sweep-
gradient COLRv1 glyph under failing-malloc.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 21:36:18 -06:00
Behdad Esfahbod 19aace663f [gpu] Fix blob leaks under failing-malloc in paint encoder
hb_vector_t::push(args) returns &Crap(Type) on allocation failure,
not nullptr -- Crap is a static pool slot, always non-null.  So
`!vec.push(item)` is *always* false and the cleanup branch never
fires.  Use push_or_fail(), which is a bool-returning wrapper that
checks against the Crap address properly.

Under failing-malloc the five affected call sites would:
  - leak the clip sub-blob in emit_clip_sub_blob (and its 1.9KB
    draw-encoded buffer + 32-byte data-wrapper)
  - leak the gradient parameters sub-blob in the three
    emit_{linear,radial,sweep}_gradient paths
  - silently ignore the overflow in push_transform

The blob leaks reproduce cleanly on oss-fuzz/CIFuzz (2056 bytes
in 6 allocations on the reported crash).  Confirmed by running the
gpu tests after the fix.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 20:08:37 -06:00
Behdad Esfahbod ccb55d6009 [gpu] Factor layer coverage into _hb_gpu_layer_coverage helper
The LAYER_SOLID and LAYER_GRADIENT paths both walked the clip
stack (1-3 slug evaluations) inline, so the coverage logic was
duplicated across six call sites in each of GLSL, MSL, HLSL, and
WGSL.  Hoist that walk into a single helper used by both ops.

Same behavior; cleaner surface; single place to edit if the clip
mask logic changes.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 19:49:34 -06:00
Behdad Esfahbod 7c7b1756c1 [gpu] Support 3 nested glyph clips per layer
Replace the single-slot pending_clip / pending_clip_glyph /
pending_clip_font / pending_clip_transform fields with a stack of
up to HB_GPU_PAINT_MAX_CLIP_DEPTH (3) clips.  push_clip_glyph
appends; pop_clip pops; depth > 3 sets `unsupported`.

LAYER_SOLID and LAYER_GRADIENT ops grow from 2 to 3 texels:

  texel 0: (op_type, flags, clip1_hi, clip1_lo)
  texel 1: (clip2_hi, clip2_lo, clip3_hi, clip3_lo)
  texel 2: color (SOLID) or grad meta (GRADIENT)

The existing flags slot (i16) gains:
  bit 0   IS_FOREGROUND          (SOLID only -- was already there)
  bit 8   HAS_CLIP2              (new)
  bit 9   HAS_CLIP3              (new)
For GRADIENT the gradient subtype lives in bits 0..7.

Shader: nest the HAS_CLIP2 / HAS_CLIP3 checks (HAS_CLIP3 implies
HAS_CLIP2) so single-clip layers pay only one branch, two-clip
layers pay one extra slug call, three-clip layers pay two extra.
On Noto-COLRv1 the bench is unchanged (~320 fps with the emoji
text the user benches against), within noise of the depth-1
baseline -- the extra branches don't fire on most layers.

Ports across all four shader languages (GLSL, MSL, HLSL, WGSL).

NEWS: limitation entry updated to "up to 3 levels are intersected
exactly; deeper nests set unsupported".

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:25:58 -06:00
Behdad Esfahbod f6cd414c9f [gpu] Add hb_gpu_paint_set_scale / _get_scale
Mirror the draw API.  hb_gpu_paint_t already had x_scale / y_scale
fields and hb_gpu_paint_glyph() set them directly, but no public
setter / getter -- callers that want to use the paint funcs
without going through paint_glyph had no way to wire the scale.

Add the public setters / getters and route paint_glyph through
them, matching hb_gpu_draw_glyph's pattern.  Document on both
draw and paint that the convenience wrappers call _set_scale.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:08:03 -06:00
Behdad Esfahbod 8403dce620 [gpu] hb_gpu_paint_glyph: fix docstring
Two errors:

- We use hb_font_paint_glyph (not _or_fail) so non-color glyphs go
  through the synthesized-foreground fallback, which the body's
  comment already explains.
- The return is the encoder-supported flag (!paint->unsupported),
  not "has color paint data".  Monochrome glyphs return true; the
  return is false only when paint walk hit a feature the encoder
  doesn't represent (PaintImage, group-stack overflow, ...).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:06:24 -06:00
Behdad Esfahbod a01bd008ad [gpu] paint_encode: empty-blob singleton for "no ink" (match draw)
hb_gpu_draw_encode already returns the empty-blob singleton (not
NULL) when the encoder has accumulated no curves -- the convention
is "NULL = encoder failed, empty blob = nothing to render".

Make hb_gpu_paint_encode follow the same shape:
  - NULL  -> hard failure (paint_glyph hit an unsupported feature
             or allocation failed).
  - empty -> no ink (e.g. space glyph or paint tree that produced
             no layer ops).

Document on both encode functions, and update the tests to expect
empty (not NULL) for the no-ink path.

The demo already short-circuits on length 0 (no atlas upload) and
_hb_gpu_blob_recycle drops the empty singleton instead of stashing
it, so nothing downstream needs to change.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:50:16 -06:00
Behdad Esfahbod b38c5189df [gpu] Detect paint-encoder limits, fail rather than misrender
Paint encoder used to push past several limits and produce a blob
that wraps an int16, overflows the shader's group stack, or skips
unsupported callbacks entirely.  Detect each:

- num_ops > 32767 (the i16 blob header field's range): set
  paint->unsupported in every emit path.
- group depth > HB_GPU_PAINT_MAX_GROUP_DEPTH (4 -- matches the
  fragment shader's HB_GPU_PAINT_GROUP_DEPTH): set unsupported
  in push_group; mirror the symmetric pop guard.
- PaintImage: register an `image` callback that sets unsupported
  (the slug+gradient encoder can't represent raster images).

push_clip_rectangle is intentionally NOT trapped -- the encoder
silently ignores it; rendered output is wider than the rectangle
asks but doesn't fail.

Nested PaintGlyph clips still silently override the outer clip
(only depth 1 is faithfully stored); follow-up commit will lift
this to depth 2.

Document all of the above in NEWS, and relax the COLR test to
tolerate a font where every glyph trips one of these limits.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:45:35 -06:00
Behdad Esfahbod 24e1bde6f2 [gpu] Name composite modes; approximate unsupported ones
a) Add inline /* MODE_NAME */ comments next to each mode == N
   branch in all four paint-shader languages.  The numbers were
   bare hb_paint_composite_mode_t values; the comments match.

b) Approximate unsupported modes with the nearest Porter-Duff
   mode rather than silently SRC_OVER'ing them:

     OVERLAY (14) / COLOR_BURN (18) / HARD_LIGHT (19) -> MULTIPLY
     COLOR_DODGE (17) / SOFT_LIGHT (20)              -> SCREEN

   DIFFERENCE (21), EXCLUSION (22) and HSL_HUE..HSL_LUMINOSITY
   (24-27) still fall through to SRC_OVER -- they're not similar
   enough to anything we have to be worth a misleading
   approximation.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:27:12 -06:00
Behdad Esfahbod 228e1792ac [gpu] Move encoder cleanup out of dtors, into _destroy
LSan flagged sub_blobs and recycled_blob leaks under failing-malloc
in hb_gpu_paint and hb_gpu_draw.  Both structs relied on a C++
destructor invoked indirectly via hb_object_actually_destroy() to
free their nested resources -- the same pattern that fooled me into
not noticing the path is fragile.

Match the established harfbuzz convention (hb_raster_paint_destroy,
hb_face_destroy, ...): drop the destructors, call
hb_object_should_destroy() to take ownership of the dec, do the
nested-resource cleanup explicitly, then hb_object_actually_destroy
+ hb_free.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:38:07 -06:00
Behdad Esfahbod 52b97c7f79 [gpu] Share blob-recycling between draw and paint encoders
hb_gpu_draw already recycled its output blob: hand the blob back
via hb_gpu_draw_recycle_blob() and the next hb_gpu_draw_encode()
reused the underlying buffer (and even returned the same blob
handle), avoiding malloc / blob allocation traffic in the
glyph-by-glyph loop.

Paint had a recycled_blob field but its recycle_blob entry point
just hb_blob_destroy()'d the input.  Lift the recycle machinery
out of hb-gpu-draw.cc into a small set of helpers
(_hb_gpu_blob_acquire / _finalize / _abort / _recycle) that live
in hb-gpu.cc, declared in a new internal header hb-gpu.hh, and
share the destroy-callback identity between both encoders.  Both
paint and draw now reuse the same buffer pool semantics.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:26:16 -06:00
Behdad Esfahbod 5fac9a0560 [array] Adapt qsort comparator return type to std::sort's bool
Restore the historical qsort contract: a C-style int comparator
(negative / zero / positive) is the canonical convention, and
hb_array_t::qsort accepted that for years -- until it was
switched from hb_qsort to std::sort.  std::sort wants bool
less-than: a +1 return for a > b looked truthy, broke
strict-weak-ordering, and caused out-of-bounds writes that ASAN
flagged from normalize_stops in hb-gpu-paint.

Wrap the std::sort call with a small overloaded helper
_qsort_lt: bool returns pass through; any other arithmetic
return is treated as the int signed comparator (< 0).  Existing
bool-returning callers (hb-cairo-utils, hb-face-builder, _qsort)
keep working; int-returning callers (hb-gpu-paint,
hb-ot-post-table) sort correctly again.

Discovered after extending hb-gpu-fuzzer to also exercise
hb_gpu_paint, which surfaced the latent UB on
noto_handwriting-glyf_colr_1.ttf.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:16:22 -06:00
Behdad Esfahbod 80e517a31a [gpu] Use real em-dashes in section docs
The existing hb-gpu section uses real em-dashes; my recent
additions slipped some ASCII -- in.  gtk-doc converts -- to en-dash
in the HTML output, but matching the rest of the file with real
em-dashes is cleaner.

Reported by Khaled.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:02:18 -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 819fce8352 [gpu] Document Paint renderer; drop encode-time foreground API
Integrates the paint renderer into the hb-gpu module docs:

- Intro notes two renderers (Draw for monochrome, Paint for
  COLRv0/COLRv1, with explicit note that Paint also handles
  monochrome outlines at some cost).
- New Paint section parallel to Draw covers encoding, shader
  composition, and fragment shader, referencing Draw for the
  shared atlas / vertex / dilation / stem-darkening pieces.
- Encoding examples drop hb_gpu_*_reset() in favour of
  hb_gpu_*_encode()'s auto-clear.

Drops hb_gpu_paint_set_foreground() / _get_foreground() and the
foreground field from hb_gpu_paint_t.  The encoded blob only
records an is_foreground flag per layer/stop; the actual
foreground color has always been a shader uniform passed to
hb_gpu_paint() at render time.  The encoder API was never
load-bearing -- the value was handed to hb_font_paint_glyph() but
the encoder callback ignores everything except the flag.

Also makes hb_gpu_paint_encode() auto-clear on return (matching
hb_gpu_draw_encode()), and removes the now-dead
demo_font_set_foreground() wrapper from the demo layer.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 15:15:53 -06:00
Behdad Esfahbod e8534b6673 [gpu] Bake inverse transform into gradient ops
Previously we baked the current transform into gradient geometry
at encode time -- transformed centers + sqrt(|det|) scaling for
the radial radius, and added the rotation angle to sweep
start/end.  That worked for conformal (scale + rotate) transforms
but was wrong under non-uniform scale or shear: a circle maps to
an ellipse, and angles warp non-linearly.  The prior code
documented this as a known limitation.

This commit stores the inverse of the transform's 2x2 linear part
(Q10 fixed-point, i16, +1 texel per gradient op) in the gradient
params blob, and stores geometry relative to a rendered origin
plus untransformed deltas and radii.  The shader computes
p_canonical = L^-1 * (renderCoord - origin_rendered) and evaluates
the gradient in its untransformed frame, so shear / non-uniform
scale produce proper ellipses and angular distortion exactly
rather than scalar-fudged.

Layouts (per gradient, before the color stops):

  linear: (p0_rendered.xy, d_canonical.xy), (L^-1 Q10 row-major)
  radial: (c0_rendered.xy, d_canonical.xy), (r0, r1, 0, 0),
          (L^-1 Q10 row-major)
  sweep:  (center_rendered.xy, start_q14, end_q14),
          (L^-1 Q10 row-major)

Per-fragment cost: one 2x2 mat-vec (6 flops).  Noto-COLRv1 emoji
bench fps unchanged.  Ported across GLSL / MSL / HLSL / WGSL.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 14:56:39 -06:00
Behdad Esfahbod 86772bf453 [gpu] Regenerated shaders 2026-04-14 00:25:32 -06:00
Behdad Esfahbod e2d58c6e07 [gpu] Skip out-of-bbox layers in paint shader (MSL, HLSL, WGSL)
Port the GLSL _hb_gpu_slug_clipped helper from the previous
commit to the other three shader languages so the paint-path
sub-glyph bbox short-circuit applies on Metal, D3D11, and
WebGPU as well.

Builds cleanly; runtime shader compile in each backend will
validate the syntax.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:24:41 -06:00
Behdad Esfahbod 59da0441d9 [gpu] Skip out-of-bbox layers in paint shader (GLSL)
Many COLRv1 paint layers cover a small region of the outer
glyph quad; emoji fonts in particular can have dozens of
sub-glyphs each clipped to a few percent of the outer bbox.
For fragments outside a layer's clip-outline bbox (plus a
2-pixel AA + MSAA-spread margin) the slug coverage is exactly
0, so the band/curve walk is wasted work.

Adds a paint-shader-only helper _hb_gpu_slug_clipped that
fetches the sub-glyph header and bails out before invoking
_hb_gpu_slug when the fragment is outside.  Draw path is
untouched, paint path on a Noto-COLRv1 emoji frame went from
~200 fps to >300 fps in local testing.

GLSL only for now; MSL, HLSL, WGSL to follow.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:22:27 -06:00
Behdad Esfahbod a63afbee9e [gpu] Regenerate hb-gpu-fragment-msl.hh
Regenerate from the .msl source after the missing closing brace
fix in 6ef71b9a6.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 23:54:05 -06:00
Behdad Esfahbod 6ef71b9a69 [gpu] Fix missing closing brace in Metal fragment shader
_hb_gpu_slug in hb-gpu-fragment.msl was missing its closing
brace, so hb_gpu_stem_darken got parsed as a nested function
definition, which MSL rejects:

    error: function definition is not allowed here

The other three shader languages already had the brace; this
regression was limited to the Metal source during the recent
refactor that moved the slug body to the shared fragment file.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 23:53:18 -06:00
Behdad Esfahbod 18360b24fd [gpu] Shaders: move Slug body to shared, rename _hb_gpu_draw_impl to _hb_gpu_slug
The Slug coverage algorithm (root-code math, band decode, single-
sample coverage, MSAA wrapper) and stem-darkening curve are useful
to both the draw renderer and the paint renderer.  Until now they
lived inside hb-gpu-draw-fragment.{glsl,msl,hlsl,wgsl} and
hb-gpu-paint-fragment had to include the draw source to reach them,
even though the paint renderer doesn't need hb_gpu_draw itself.

Move everything except the thin fwidth wrapper into the already-
shared hb-gpu-fragment.{ext} helpers, and rename the MSAA-aware
entry point _hb_gpu_draw_impl -> _hb_gpu_slug since it's no longer
specific to the draw renderer.  hb_gpu_draw is now a one-liner in
hb-gpu-draw-fragment that calls _hb_gpu_slug with pixelsPerEm
derived from fwidth at uniform control flow.

No functional change.  bench --demo stays at ~1750fps.

Next step: demo dispatches to either the draw or paint shader
based on whether the font has any color paint, recovering the ~25%
perf gap for monochrome fonts while still exercising both paths
from the same binary.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 23:41:26 -06:00