msdfgen-ts 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,23 +10,29 @@
10
10
  * `screenPxRange = atlas.pxrangeEm × pixelPerEm` uniform, no per-instance
11
11
  * range varying and no per-glyph reasoning about crispness.
12
12
  *
13
- * The MSDF pipeline (normalize → colour → generate → sign-correct →
14
- * error-correct → byte-quantise → y-flip) is byte-for-byte identical to
15
- * the C++ msdfgen reference — see test/msdf/msdf.test.ts for the direct
16
- * pipeline golden. The atlas layout on top (crop + shelf-pack) is our own.
13
+ * Overlapping contours are first merged into their union (src/shape/union.ts,
14
+ * msdfgen's Skia step done without Skia). From there the MSDF pipeline
15
+ * (normalize → colour → generate → sign-correct → error-correct →
16
+ * byte-quantise → y-flip) is byte-for-byte identical to the C++ msdfgen
17
+ * reference — see test/msdf/msdf.test.ts for the direct pipeline golden.
18
+ * The atlas layout on top (crop + shelf-pack) is our own.
17
19
  *
18
20
  * msdfgen is MIT © Viktor Chlumský; this file is original.
19
21
  */
20
22
  import { type Font } from "./font/font.js";
23
+ import { type Shape } from "./shape/shape.js";
21
24
  /** Converts a msdfgen float channel value to a byte, matching C++
22
25
  * `pixelFloatToByte` exactly. */
23
26
  export declare function pixelFloatToByte(x: number): number;
24
27
  /** Options for constructing an {@link Atlas}. */
25
28
  export interface AtlasOptions {
26
- /** Uniform texel-per-em generation scale. Default 40. */
29
+ /** Uniform texel-per-em generation scale. For `parseSvg` shapes, 1 em is the
30
+ * viewBox height, so this is texels per icon height. Default 40. */
27
31
  pixelsPerEm?: number;
28
32
  /** MSDF distance range in texels (msdfgen `-pxrange`). Default 4. */
29
33
  pxrange?: number;
34
+ /** Also keep {@link Atlas.floatTexture}. Default false. */
35
+ float?: boolean;
30
36
  }
31
37
  /** Cached layout + metrics for one atlas-resident glyph. */
32
38
  export interface AtlasGlyph {
@@ -54,7 +60,8 @@ export interface LaidOutGlyph {
54
60
  penY: number;
55
61
  }
56
62
  /**
57
- * Runtime MSDF glyph atlas backed by a single `Font`.
63
+ * Runtime MSDF glyph atlas backed by a single `Font` (or none, for an atlas
64
+ * of arbitrary shapes such as SVG icons — see {@link Atlas.shapes}).
58
65
  *
59
66
  * Prefer {@link Atlas.glyphs} (batched — one potpack for the whole set) over
60
67
  * calling {@link Atlas.glyph} in a loop (one potpack per insert).
@@ -71,22 +78,32 @@ export declare class Atlas {
71
78
  private _width;
72
79
  private _height;
73
80
  private _pixels;
74
- /** Cached glyph + retained float MSDF (for repacking on new inserts).
75
- * Keyed by Unicode codepoint — see {@link Atlas.glyphs}. */
81
+ private _floats;
82
+ /** Cached glyph + retained float MSDF (for repacking on new inserts), keyed
83
+ * by glyph index: codepoints sharing a glyph (every character missing from
84
+ * the font maps to .notdef) share one atlas cell. */
76
85
  private readonly _cache;
77
- /** Same shape as {@link Atlas._cache}, keyed by raw glyph index instead —
78
- * see {@link Atlas.glyphsByIndex}. Separate map: a codepoint and a glyph
79
- * index are different numbers in the same integer space. */
80
- private readonly _cacheByGid;
86
+ /** {@link Atlas._cache}'s glyphs again, indexed by glyph id (the layout hot path). */
87
+ private readonly _byGid;
88
+ /** Same shape as {@link Atlas._cache}, keyed by caller-chosen string — see
89
+ * {@link Atlas.shapes}. */
90
+ private readonly _cacheByKey;
81
91
  /** SDF distance range in em — UNIFORM across all glyphs (that's the point). */
82
92
  readonly pxrangeEm: number;
83
- constructor(font: Font, opts?: AtlasOptions);
93
+ /**
94
+ * @param font Font for the glyph/layout methods; `null` for a shapes-only atlas.
95
+ * @param opts Generation scale and distance range.
96
+ */
97
+ constructor(font: Font | null, opts?: AtlasOptions);
84
98
  /** Packed atlas texture width in texels (chosen by potpack). */
85
99
  get width(): number;
86
100
  /** Packed atlas texture height in texels (chosen by potpack). */
87
101
  get height(): number;
88
102
  /** Packed atlas texture, flat RGBA8 bytes, row-major, y-down. */
89
103
  get texture(): Uint8Array;
104
+ /** {@link Atlas.texture} as raw float RGB, not clamped to [0, 1], for zoom that
105
+ * outruns 8 bits; `null` without the `float` option. */
106
+ get floatTexture(): Float32Array | null;
90
107
  /**
91
108
  * Batched generate + pack. Generates MSDFs for any codepoints not
92
109
  * already cached, then runs potpack **once** over the whole cache.
@@ -104,11 +121,8 @@ export declare class Atlas {
104
121
  * Unicode codepoint — the {@link Atlas.glyphs} twin for glyphs with no
105
122
  * reachable cmap entry. Icon fonts (e.g. Lucide) commonly have far more
106
123
  * glyphs than mapped codepoints; this is how the rest of the set gets
107
- * generated. Shares one packed atlas texture with the codepoint-addressed
108
- * cache — {@link Atlas.texture} always reflects everything requested
109
- * through either method. Cached separately from {@link Atlas.glyphs} (a
110
- * codepoint and a glyph index are different numbers in the same integer
111
- * space — sharing one cache would collide them).
124
+ * generated. Shares one cache and one packed atlas texture with
125
+ * {@link Atlas.glyphs}, which maps codepoints to glyph indices first.
112
126
  */
113
127
  glyphsByIndex(glyphIds: Iterable<number>): AtlasGlyph[];
114
128
  /** Single-glyph convenience for {@link Atlas.glyphsByIndex} — see its
@@ -116,16 +130,27 @@ export declare class Atlas {
116
130
  * (one potpack for the whole batch instead of one per insert). */
117
131
  glyphByIndex(glyphId: number): AtlasGlyph;
118
132
  /**
119
- * Generates the MSDF for `glyphId`. Does not cache and does not pack —
120
- * callers own the cache key (a codepoint for {@link Atlas.glyphs}, the
121
- * glyph ID itself for {@link Atlas.glyphsByIndex}) and the repack.
133
+ * Batched generate + pack for arbitrary shapes (e.g. from `parseSvg`),
134
+ * keyed by a caller-chosen string — the {@link Atlas.glyphs} twin for
135
+ * non-font input. Shapes must be y-up, in the units `pixelsPerEm` scales
136
+ * (`parseSvg` makes 1 unit = the viewBox height). A new shape is mutated
137
+ * (overlaps merged, normalized + coloured); a cached key ignores the shape
138
+ * passed. `advance` is 0. Shares the one packed texture with the glyph cache.
122
139
  */
140
+ shapes(entries: Iterable<readonly [key: string, shape: Shape]>): AtlasGlyph[];
141
+ /** The font, or a clear error for glyph/layout calls on a shapes-only atlas. */
142
+ private _requireFont;
143
+ /** Generates the MSDF for `glyphId`. Does not cache and does not pack. */
123
144
  private _generateForGlyphId;
145
+ /** Generates one entry from an em-unit shape. Does not cache or pack. */
146
+ private _generate;
124
147
  /**
125
- * Lays out `text` left-to-right on a single line, applying kerning.
148
+ * Lays out `text` left-to-right on a single line, kerned the way Chrome
149
+ * kerns it (see src/font/shaper.ts: script runs, GPOS or the `kern` table).
126
150
  * Generates any missing glyphs and packs the atlas **once** for the
127
- * whole run. Baseline is y=0 (`penY` on every result is 0); each `penX`
128
- * is the pen position in em. `text` must not contain `\n` — use
151
+ * whole run. Baseline is y=0 (`penY` is the glyph's GPOS y offset, almost
152
+ * always 0); each `penX` is the glyph's drawing origin in em. One entry
153
+ * per codepoint (no ligatures). `text` must not contain `\n` — use
129
154
  * {@link Atlas.layoutMultiline} for multi-line input.
130
155
  */
131
156
  layout(text: string): {
@@ -152,10 +177,15 @@ export declare class Atlas {
152
177
  widthEm: number;
153
178
  heightEm: number;
154
179
  };
155
- /** Repacks every cached glyph (both the codepoint- and glyph-index-keyed
156
- * caches — one shared texture) with potpack, reallocates the texture,
157
- * and re-blits each MSDF at its assigned rect. Called by `glyphs()`/
158
- * `glyphsByIndex()` after any batch of new inserts — once per batch. */
180
+ /** Repacks every cached entry (glyph-index- and string-keyed caches — one
181
+ * shared texture) with potpack, reallocates the texture, and re-blits each
182
+ * MSDF at its assigned rect. Called by `glyphsByIndex()`/`shapes()` after
183
+ * any batch of new inserts — once per batch.
184
+ *
185
+ * Each cell gets a 1-texel gutter of zeros on its right and bottom, so a
186
+ * quad covering the whole cell can sample its full rect: linear filtering
187
+ * at the edge blends with zeros (further outside the glyph), never with a
188
+ * neighbouring glyph's texels. */
159
189
  private _repack;
160
190
  /**
161
191
  * Quantise `msdf` (float, y-up, row 0 = bottom, w×h×3) into `_pixels` at
@@ -1,3 +1,5 @@
1
+ import { KernTable } from "./tables/kern.js";
2
+ import { Gpos } from "./tables/gpos.js";
1
3
  import { type Shape } from "../shape/shape.js";
2
4
  /** Font-level metrics exposed from `head` and `hhea`. */
3
5
  export interface FontMetrics {
@@ -32,8 +34,21 @@ export declare class Font {
32
34
  private _loca;
33
35
  /** @type {CmapLookup} */
34
36
  private _cmap;
35
- /** @type {KernMap} */
37
+ /** Glyph ids of codepoints below {@link CMAP_CACHE}, +1 (0 = not looked up yet). */
38
+ private _cmapCache;
39
+ /** Layout tables (GDEF, GPOS, kern), parsed on first use: see {@link Font._loadLayout}. */
40
+ private _layoutLoaded;
41
+ private _gdef;
42
+ private _gpos;
36
43
  private _kern;
44
+ /** GSUB's script tags (HarfBuzz picks its shaper from them), or null without GSUB. */
45
+ private _gsubScripts;
46
+ /** HarfBuzz shaper flags per ICU script code, -1 = not chosen yet (see shaper.ts). */
47
+ private _shapers;
48
+ /** See {@link Font._advances}. */
49
+ private _advanceTable;
50
+ /** Memoized {@link Font.kerning} results, keyed by glyph pair. */
51
+ private _pairCache;
37
52
  /** Font-level metrics (unitsPerEm, ascender, descender, lineGap). */
38
53
  readonly metrics: FontMetrics;
39
54
  /**
@@ -75,13 +90,33 @@ export declare class Font {
75
90
  */
76
91
  lsb(glyphId: number): number;
77
92
  /**
78
- * Kerning adjustment between two glyphs in font units.
79
- * Returns 0 if the font has no kern table or the pair is not listed.
93
+ * Kerning between two glyphs in font units: how much positioning the pair
94
+ * on its own changes its total advance (GPOS `kern` and other default
95
+ * positioning features, else the legacy `kern` table, as Chrome applies
96
+ * them). Pairwise only — {@link Atlas.layout} kerns whole runs, which also
97
+ * accounts for script runs and contextual kerning.
80
98
  *
81
99
  * @param leftGlyphId Left glyph index.
82
100
  * @param rightGlyphId Right glyph index.
101
+ * @returns Advance adjustment in font units, 0 for an unkerned pair.
83
102
  */
84
103
  kerning(leftGlyphId: number, rightGlyphId: number): number;
104
+ /** {@link Font.kerning}'s cache miss, kept out of line so the hit path stays small. */
105
+ private _kerningMiss;
106
+ /** Parses GDEF, GPOS, kern and GSUB's script list on first use (keeps `new Font` cheap). */
107
+ private _loadLayout;
108
+ /** @internal GSUB's script tags, or null when the font has no GSUB. */
109
+ _gsubScriptTags(): Uint32Array | null;
110
+ /** @internal Per-script shaper flags cache (see shaper.ts: shaperOf), -1 = unset. */
111
+ _shaperCache(): Int8Array;
112
+ /** @internal Advance widths by glyph id (dense copy of `hmtx` for layout). */
113
+ _advances(): Uint16Array;
114
+ /** @internal GDEF glyph props per glyph, or null (classes are then synthesized). */
115
+ _glyphProps(): Uint16Array | null;
116
+ /** @internal The GPOS table, or null. */
117
+ _gposTable(): Gpos | null;
118
+ /** @internal The legacy kern table, or null. */
119
+ _kernTable(): KernTable | null;
85
120
  /**
86
121
  * Parses and returns the outline of a glyph as a Shape (raw font units, y-up).
87
122
  *
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The glyph buffer text layout works on: HarfBuzz's `hb_buffer_t` info +
3
+ * position arrays, as flat typed arrays reused across calls (grow-once, like
4
+ * the MSDF generator's scratch). Module-scope state: the library is
5
+ * synchronous and single-threaded per worker.
6
+ *
7
+ * Positions are font units: `_xa` advance, `_xo`/`_yo` drawing offset from
8
+ * the pen (y-up, as in HarfBuzz).
9
+ */
10
+ /** Glyph property bits, HarfBuzz's HB_OT_LAYOUT_GLYPH_PROPS_* (mark
11
+ * attachment class in bits 8-15), plus two default-ignorable flags. */
12
+ /** Skipped by lookups looking for a pair or context partner. */
13
+ export declare const PROP_IGNORABLE = 1;
14
+ export declare const PROP_BASE = 2;
15
+ export declare const PROP_LIGATURE = 4;
16
+ export declare const PROP_MARK = 8;
17
+ /** Default ignorable: no advance, nothing drawn (HarfBuzz hides it). */
18
+ export declare const PROP_HIDDEN = 16;
19
+ /** Shared glyph buffer; call {@link reserveRun} before writing `n` glyphs. */
20
+ export declare const run: {
21
+ /** Unicode codepoint per glyph. */
22
+ _cp: Int32Array<ArrayBuffer>;
23
+ /** Glyph index per glyph. */
24
+ _gid: Uint16Array<ArrayBuffer>;
25
+ /** PROP_* bits per glyph. */
26
+ _gp: Uint16Array<ArrayBuffer>;
27
+ /** x advance, font units. */
28
+ _xa: Float64Array<ArrayBuffer>;
29
+ /** x offset, font units. */
30
+ _xo: Float64Array<ArrayBuffer>;
31
+ /** y offset, font units (y-up). */
32
+ _yo: Float64Array<ArrayBuffer>;
33
+ /** Script-run end indices and ICU script codes (see script.ts: itemize). */
34
+ _runEnd: Int32Array<ArrayBuffer>;
35
+ _runScript: Int32Array<ArrayBuffer>;
36
+ };
37
+ /**
38
+ * Whether a lookup with flags `lp` (and mark filtering set `set`) sees glyph
39
+ * `g` with props `gp`. port of harfbuzz hb-ot-layout-gsubgpos.hh:
40
+ * hb_ot_apply_context_t::check_glyph_property + match_properties_mark.
41
+ */
42
+ export declare function checkProps(gp: number, g: number, lp: number, set: Uint16Array | null): boolean;
43
+ /**
44
+ * Next glyph after `i` (before `end`) a lookup can pair with, or −1: skips
45
+ * glyphs the lookup flags ignore and default ignorables. port of
46
+ * skipping_iterator_t::next with no match function, as GPOS uses it.
47
+ */
48
+ export declare function nextGlyph(i: number, end: number, lp: number, set: Uint16Array | null): number;
49
+ /** Grows every {@link run} array to hold at least `n` glyphs (contents are not kept). */
50
+ export declare function reserveRun(n: number): void;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Unicode script itemization: splits text into the same script runs Chrome
3
+ * shapes separately, so kerning never crosses a run boundary (Chrome does not
4
+ * kern Latin "T" against a following Cyrillic "о") and each run selects its
5
+ * own OpenType script.
6
+ *
7
+ * port of Chromium third_party/blink/renderer/platform/fonts/
8
+ * script_run_iterator.cc: ScriptRunIterator + ICUScriptData::GetScripts.
9
+ *
10
+ * Script data comes from the JS engine's own Unicode tables through regex
11
+ * property escapes (`\p{Script=…}`, `\p{Script_Extensions=…}`), so no Unicode
12
+ * data ships in the bundle; in Chrome that is the same ICU data Blink uses.
13
+ * Results are cached per codepoint. Module-scope state: single-threaded, like
14
+ * the rest of the library.
15
+ */
16
+ /** Number of ICU script codes (script codes are `0 … SCRIPT_COUNT - 1`). */
17
+ export declare const SCRIPT_COUNT: number;
18
+ /** `USCRIPT_COMMON` */
19
+ export declare const COMMON = 0;
20
+ /** `USCRIPT_INHERITED` */
21
+ export declare const INHERITED = 1;
22
+ /**
23
+ * ISO 15924 code of an ICU script code.
24
+ *
25
+ * @param code ICU script code (as {@link itemize} returns).
26
+ * @returns The 4-letter code, e.g. "Latn".
27
+ */
28
+ export declare function iso(code: number): string;
29
+ /**
30
+ * Blink's ordered script set for `cp` (ICUScriptData::GetScripts): the
31
+ * Script_Extensions, with the primary script (or Common/Inherited) first.
32
+ * Shared and immutable — callers copy before mutating.
33
+ */
34
+ export declare function scriptSet(cp: number): number[];
35
+ /**
36
+ * Splits `cps[0..n)` into script runs, exactly like Blink's
37
+ * ScriptRunIterator. Writes each run's end index (exclusive) and ICU script
38
+ * code; returns the run count. `runEnd`/`runScript` need room for `n` runs.
39
+ */
40
+ export declare function itemize(cps: Int32Array, n: number, runEnd: Int32Array, runScript: Int32Array): number;
41
+ /** Packs a 4-character tag into a uint32. */
42
+ export declare function tag(s: string): number;
43
+ /**
44
+ * OpenType script tags to try for an ICU script code, most preferred first
45
+ * (port of hb-ot-tag.cc: hb_ot_all_tags_from_script).
46
+ */
47
+ export declare function otScriptTags(code: number): number[];
@@ -0,0 +1,41 @@
1
+ import type { Font } from "./font.js";
2
+ /**
3
+ * Text → positioned glyphs, the way Chrome positions them: Blink's script
4
+ * runs, then per run HarfBuzz's shaping restricted to positioning — one
5
+ * glyph per codepoint (no GSUB yet, so no ligatures), `hmtx` advances, GPOS
6
+ * (or, without GPOS kerning for the script, the legacy `kern` table, if the
7
+ * run's shaper applies it), mark and default-ignorable zeroing.
8
+ *
9
+ * port of harfbuzz src/hb-ot-shape.cc: hb_ot_shape_plan_t::init0 (who does
10
+ * kerning), hb_ot_position / hb_ot_position_plan, zero_mark_widths_by_gdef,
11
+ * hb_ot_zero_width_default_ignorables, hb_synthesize_glyph_classes;
12
+ * hb-ot-shaper.hh: hb_ot_shaper_categorize (shaper flags only).
13
+ *
14
+ * Results land in the shared {@link run} buffer (font units).
15
+ */
16
+ /** port of hb-unicode.hh: hb_unicode_funcs_t::is_default_ignorable. */
17
+ export declare function isDefaultIgnorable(cp: number): boolean;
18
+ /**
19
+ * Lays out `text` (one line) into {@link run}: glyph id, advance and offset
20
+ * per codepoint, in font units. Returns the glyph count (= codepoint count).
21
+ * Default-ignorable characters get zero advance and the PROP_HIDDEN flag
22
+ * (HarfBuzz hides them).
23
+ */
24
+ export declare function shapeText(font: Font, text: string): number;
25
+ /**
26
+ * Positions `run[start, end)` — one HarfBuzz buffer of ICU script `script`
27
+ * whose glyph ids, props and default advances are already set.
28
+ *
29
+ * port of hb-ot-shape.cc: hb_ot_shape_plan_t::init0 (who kerns, zero_marks,
30
+ * adjust_mark_positioning_when_zeroing) + hb_ot_position_plan (the order:
31
+ * early zeroing, GPOS, `kern` table, late zeroing).
32
+ *
33
+ * @param marks Whether any glyph is a mark: if none, there is nothing to
34
+ * zero (positioning never turns a glyph into a mark), so skip the pass.
35
+ */
36
+ export declare function positionRun(font: Font, start: number, end: number, script: number, marks: boolean): void;
37
+ /**
38
+ * Total advance change from positioning two glyphs as a run of their own
39
+ * (Common script: the font's DFLT, else latn, features), in font units.
40
+ */
41
+ export declare function pairKerning(font: Font, left: number, right: number): number;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * GDEF: glyph classes (base / ligature / mark + mark attachment class) and
3
+ * mark glyph sets, the inputs of GPOS lookup flags.
4
+ *
5
+ * port of harfbuzz src/hb-ot-layout-gdef-table.hh: GDEF::get_glyph_props,
6
+ * MarkGlyphSets::covers.
7
+ */
8
+ export declare class Gdef {
9
+ /** Glyph props per glyph (PROP_* | attachClass << 8); null without a glyph ClassDef. */
10
+ readonly _props: Uint16Array | null;
11
+ /** @type {DataView} */
12
+ private _dv;
13
+ /** Absolute offset of MarkGlyphSetsDef, 0 if absent. */
14
+ private _sets;
15
+ /** Decoded mark glyph set coverages, by set index. */
16
+ private _setCache;
17
+ /**
18
+ * @param buffer Full font buffer.
19
+ * @param offset Byte offset of the GDEF table.
20
+ * @param numGlyphs `maxp.numGlyphs`.
21
+ */
22
+ constructor(buffer: ArrayBuffer, offset: number, numGlyphs: number);
23
+ /** Coverage of mark glyph set `index` (empty if the font has none). */
24
+ _markSet(index: number): Uint16Array;
25
+ }
@@ -15,9 +15,11 @@
15
15
  * Composite transforms supported:
16
16
  * ARG_1_AND_2_ARE_WORDS, ARGS_ARE_XY_VALUES,
17
17
  * WE_HAVE_A_SCALE, WE_HAVE_AN_X_AND_Y_SCALE, WE_HAVE_A_TWO_BY_TWO,
18
- * USE_MY_METRICS, MORE_COMPONENTS.
18
+ * MORE_COMPONENTS.
19
19
  *
20
20
  * Not supported (silently ignored / treated as identity):
21
+ * USE_MY_METRICS — advance widths come from `hmtx`, which already holds the
22
+ * composite's own metrics.
21
23
  * ARGS_ARE_XY_VALUES not set (anchor point alignment) — returns origin offset
22
24
  * of 0 for that component.
23
25
  */
@@ -0,0 +1,85 @@
1
+ import type { Gdef } from "./gdef.js";
2
+ /** The lookups one script run applies (hb_ot_map_t, GPOS half). */
3
+ export declare class GposPlan {
4
+ /** Lookup indices, ascending (HarfBuzz applies a stage's lookups in index order). */
5
+ readonly _lookups: number[];
6
+ /** Whether the selected script lists a `kern` feature (else the `kern` table applies). */
7
+ readonly _kern: boolean;
8
+ constructor(lookups: number[], kern: boolean);
9
+ }
10
+ /** Parsed GPOS table. Lookups are decoded on first use. */
11
+ export declare class Gpos {
12
+ /** @type {DataView} */
13
+ private _view;
14
+ private _scripts;
15
+ private _features;
16
+ private _lookupList;
17
+ private _gdef;
18
+ private _lookupCache;
19
+ private _planCache;
20
+ private _covCache;
21
+ private _cdCache;
22
+ /**
23
+ * @param buffer Full font buffer.
24
+ * @param offset Byte offset of the GPOS table.
25
+ * @param gdef The font's GDEF (mark filtering sets), or null.
26
+ */
27
+ constructor(buffer: ArrayBuffer, offset: number, gdef: Gdef | null);
28
+ /** Coverage at `base + rel` (offset 0 = HarfBuzz's Null coverage). */
29
+ private _cov;
30
+ /** ClassDef at `base + rel` (offset 0 = every glyph class 0). */
31
+ private _cd;
32
+ /** Absolute offset of the Script table tagged `t`, or 0. */
33
+ private _script;
34
+ /**
35
+ * The lookups to apply to a run whose OpenType script tags (most
36
+ * preferred first) are `tags`, cached under ICU script code `code`.
37
+ * port of hb-ot-layout.cc: hb_ot_layout_table_select_script (falls back to
38
+ * DFLT, dflt, then latn) + hb-ot-map.cc: hb_ot_map_builder_t::compile.
39
+ */
40
+ _plan(code: number, tags: readonly number[]): GposPlan;
41
+ /** Lookup `li`, decoded on first use; null if out of range. */
42
+ private _lookup;
43
+ /** Decodes one subtable; null for unsupported types/formats. */
44
+ private _sub;
45
+ /** Decodes a plain-kerning PairPos (XAdvance of the first glyph only) into typed arrays. */
46
+ private _decodePairs;
47
+ /**
48
+ * Applies `plan` to `run[start, end)`, one HarfBuzz buffer (a script run).
49
+ * port of hb-ot-layout.cc: apply_forward, for each lookup in turn.
50
+ */
51
+ _position(plan: GposPlan, start: number, end: number): void;
52
+ /** First subtable of `lk` that applies at `i`: returns the next index, or −1. */
53
+ private _applyAt;
54
+ /** One subtable at glyph `i`: returns the index to continue from, or −1. */
55
+ private _applySub;
56
+ /** port of ContextFormat1/2/3::apply (SequenceContext). */
57
+ private _context;
58
+ /** port of ChainContextFormat1/2/3::apply (ChainedSequenceContext). */
59
+ private _chain;
60
+ /** Whether glyph `g` matches rule item `v` (glyph id, class, or coverage offset from `base`). */
61
+ private _matches;
62
+ /**
63
+ * Next glyph after `j` matching item `v`, or −1 (skipping_iterator_t::next
64
+ * with a match function): ignored glyphs are skipped; a default ignorable
65
+ * is skipped unless it matches; any other mismatch fails.
66
+ */
67
+ private _next;
68
+ /** skipping_iterator_t::prev counterpart of {@link Gpos._next}. */
69
+ private _prev;
70
+ /**
71
+ * port of match_input: matches input items 1..count−1 (u16 values from
72
+ * `seq`) after glyph `i`; records match positions for this nesting level.
73
+ * Returns the match end (exclusive), or −1.
74
+ */
75
+ private _input;
76
+ /** port of match_lookahead, starting at `end`. */
77
+ private _lookahead;
78
+ /** port of match_backtrack (item 0 is the glyph right before `i`). */
79
+ private _backtrack;
80
+ /**
81
+ * port of apply_lookup (GPOS: the buffer never changes length): applies
82
+ * each SequenceLookupRecord at its matched position, in design order.
83
+ */
84
+ private _apply;
85
+ }
@@ -1,17 +1,34 @@
1
1
  /**
2
- * Kerning pair map: key = `(leftGlyphId << 16) | rightGlyphId`, value = kern value in font units.
3
- * Returns 0 for unknown pairs.
4
- */
5
- export type KernMap = (left: number, right: number) => number;
6
- /**
7
- * Parses the `kern` table (format 0 horizontal kerning pairs only).
8
- *
9
- * Silently skips sub-tables with unsupported formats (vertical kerning,
10
- * cross-stream, format 2, etc.). Returns a no-op lookup if the table is
11
- * absent or contains no usable format-0 horizontal pairs.
2
+ * The legacy `kern` table, applied the way HarfBuzz does when a font has no
3
+ * GPOS kerning for the run's script: every format-0 horizontal subtable in
4
+ * turn (values accumulate), marks skipped, each pair's kern split half onto
5
+ * each glyph (same drawing positions, caret halfway).
12
6
  *
13
- * @param buffer Full font buffer.
14
- * @param offset Byte offset of the kern table (from TableMap).
15
- * @returns Kern lookup function.
7
+ * port of harfbuzz src/hb-ot-kern-table.hh (OT and AAT `kern` headers),
8
+ * hb-aat-layout-kerx-table.hh: KerxSubTableFormat0 / KerxTable::apply, and
9
+ * hb-kern.hh: hb_kern_machine_t::kern. Formats 1-3 (state machines, class
10
+ * tables) are not ported.
16
11
  */
17
- export declare function parseKern(buffer: ArrayBuffer, offset: number): KernMap;
12
+ export declare class KernTable {
13
+ /** @type {DataView} */
14
+ private _dv;
15
+ /** Per usable subtable: absolute offset of its first pair, pair count, cross-stream flag. */
16
+ private _pairs;
17
+ private _counts;
18
+ private _cross;
19
+ /** Any subtable at all (hb_ot_layout_has_kerning). */
20
+ readonly _hasData: boolean;
21
+ /** Any state-machine subtable (hb_ot_layout_has_machine_kerning). */
22
+ readonly _hasMachine: boolean;
23
+ /** Any cross-stream subtable (hb_ot_layout_has_cross_kerning). */
24
+ readonly _hasCross: boolean;
25
+ /**
26
+ * @param buffer Full font buffer.
27
+ * @param offset Byte offset of the kern table.
28
+ */
29
+ constructor(buffer: ArrayBuffer, offset: number);
30
+ /** Kern value of subtable `s` for a pair, 0 if not listed (binary search, like HarfBuzz). */
31
+ private _get;
32
+ /** Kerns `run[start, end)`. */
33
+ _apply(start: number, end: number): void;
34
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * OpenType Layout common tables (Coverage, ClassDef), decoded once into
3
+ * dense per-glyph arrays so lookups are a single indexed read.
4
+ *
5
+ * port of harfbuzz src/hb-ot-layout-common.hh: Coverage::get_coverage,
6
+ * ClassDef::get_class (same results, dense instead of binary search).
7
+ */
8
+ /** Coverage value for "not covered". */
9
+ export declare const NOT_COVERED = 65535;
10
+ /**
11
+ * The script tags of a GSUB or GPOS table's ScriptList, in table order.
12
+ *
13
+ * @param dv View of the font buffer.
14
+ * @param table Byte offset of the GSUB or GPOS table.
15
+ * @returns The tags (empty when the table has no ScriptList).
16
+ */
17
+ export declare function scriptListTags(dv: DataView, table: number): Uint32Array;
18
+ /**
19
+ * Decodes a Coverage table: `t[glyph]` is the coverage index, or
20
+ * {@link NOT_COVERED}; glyphs past `t.length` are not covered.
21
+ */
22
+ export declare function decodeCoverage(dv: DataView, off: number): Uint16Array;
23
+ /**
24
+ * Decodes a ClassDef table: `t[glyph]` is the class; glyphs past `t.length`
25
+ * (and glyphs the table does not list) are class 0.
26
+ */
27
+ export declare function decodeClassDef(dv: DataView, off: number): Uint16Array;
@@ -4,5 +4,9 @@ export { EdgeSegment, LINEAR, QUADRATIC, CUBIC } from "./shape/segments.js";
4
4
  export type { SegmentType } from "./shape/segments.js";
5
5
  export { Font } from "./font/font.js";
6
6
  export type { FontMetrics } from "./font/font.js";
7
+ export { parseSvg, parseSvgLayers } from "./svg/svg.js";
8
+ export type { SvgLayer, SvgGradient } from "./svg/svg.js";
9
+ export { generateShapeMSDF } from "./msdf/shape-msdf.js";
10
+ export type { ShapeMSDF } from "./msdf/shape-msdf.js";
7
11
  export { Atlas, pixelFloatToByte } from "./atlas-gen.js";
8
12
  export type { AtlasOptions, AtlasGlyph, LaidOutGlyph } from "./atlas-gen.js";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The whole MSDF pipeline for one shape, from any source (font glyph, SVG):
3
+ * merge overlaps → normalize → colour → generate → sign-correct →
4
+ * error-correct, into a bitmap cropped to the shape's bounds plus `pxrange`
5
+ * texels of padding.
6
+ *
7
+ * Byte-for-byte the msdfgen `msdf -scanline` pipeline after the merge (see
8
+ * test/msdf/msdf.test.ts); the merge and the bounds/cropping are original.
9
+ * msdfgen is MIT © Viktor Chlumský.
10
+ */
11
+ import { type Shape } from "../shape/shape.js";
12
+ /** A shape's MSDF bitmap and where it sits in shape space. */
13
+ export interface ShapeMSDF {
14
+ /** Float MSDF, `w × h × 3`, row-major, y-up (row 0 = bottom). */
15
+ msdf: Float32Array;
16
+ w: number;
17
+ h: number;
18
+ /** Bitmap rect in shape units (y-up). */
19
+ planeLeft: number;
20
+ planeBottom: number;
21
+ planeRight: number;
22
+ planeTop: number;
23
+ }
24
+ /**
25
+ * Generates the MSDF of `shape` at `pixelsPerUnit` texels per shape unit.
26
+ * Mutates `shape` (overlaps merged, normalized + edge-coloured). Returns
27
+ * `null` for a shape with no contours.
28
+ *
29
+ * @param shape Closed contours, y-up, in the units `pixelsPerUnit` scales.
30
+ * @param pixelsPerUnit Texels per shape unit (an atlas's `pixelsPerEm`).
31
+ * @param pxrange Distance range in texels (msdfgen `-pxrange`).
32
+ * @param union Merge overlapping contours first (assumes em-sized units).
33
+ * `false` matches msdfgen without Skia, which draws overlaps as cracks.
34
+ * @returns The bitmap and its plane bounds, or `null` if `shape` is empty.
35
+ */
36
+ export declare function generateShapeMSDF(shape: Shape, pixelsPerUnit: number, pxrange: number, union?: boolean): ShapeMSDF | null;
37
+ /**
38
+ * Axis-aligned bounds of a shape, sampled at `BOUNDS_SAMPLES` t-values per
39
+ * segment. Not mathematically tight, but well under a texel of slop at any
40
+ * realistic `pixelsPerUnit` — good enough for cropping (and for SVG
41
+ * `objectBoundingBox` gradients).
42
+ *
43
+ * @param shape Shape to measure.
44
+ * @returns Its axis-aligned bounds, in shape units.
45
+ */
46
+ export declare function shapeBounds(shape: Shape): {
47
+ minX: number;
48
+ minY: number;
49
+ maxX: number;
50
+ maxY: number;
51
+ };
@@ -9,13 +9,15 @@
9
9
  * core/convergent-curve-ordering.cpp: convergentCurveOrdering().
10
10
  * msdfgen © Viktor Chlumský — MIT licence.
11
11
  */
12
+ import { type Contour } from "./contour.js";
12
13
  import { type Shape } from "./shape.js";
13
14
  /**
14
15
  * Divides all control-point coordinates by `unitsPerEm`, converting font
15
16
  * units to the normalised em-square coordinate system used by msdfgen.
16
17
  *
17
18
  * This is the **single named em-normalisation step** (FONT_SCALING_EM_NORMALIZED).
18
- * No other file may perform this division by unitsPerEm.
19
+ * No other file may perform this division by unitsPerEm. SVG input goes
20
+ * through here too, with the viewBox height as its "unitsPerEm".
19
21
  *
20
22
  * @param shape Shape in raw font units (mutated in-place).
21
23
  * @param unitsPerEm Design units per em (from Font.metrics.unitsPerEm).
@@ -36,3 +38,12 @@ export declare function emNormalizeShape(shape: Shape, unitsPerEm: number): void
36
38
  * @param shape Shape to normalize (mutated in-place).
37
39
  */
38
40
  export declare function normalizeShape(shape: Shape): void;
41
+ /**
42
+ * Reverses contours so the nonzero fill of the result equals the even-odd
43
+ * fill of the input (holes wound against their parent). Used for SVG
44
+ * `fill-rule="evenodd"` paths, so the rest of the pipeline stays nonzero.
45
+ * port of core/Shape.cpp: Shape::orientContours
46
+ *
47
+ * @param contours Contours of one even-odd path (mutated in place).
48
+ */
49
+ export declare function orientContours(contours: Contour[]): void;