pixi-silk 1.0.2 → 1.1.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.
@@ -23,6 +23,14 @@ export interface Glyph {
23
23
  left: number;
24
24
  /** Top edge of the cell relative to the baseline (negative is above it). */
25
25
  top: number;
26
+ /**
27
+ * Where a colour glyph (an emoji) keeps its colours: the top left of a cell of the same size in
28
+ * {@link SdfAtlas.colorSource}. Absent for one-colour glyphs.
29
+ */
30
+ color?: {
31
+ x: number;
32
+ y: number;
33
+ };
26
34
  }
27
35
  /** Vertical metrics of a font at the atlas size, measured the way PixiJS `Text` measures them. */
28
36
  export interface FontMetrics {
@@ -44,6 +52,11 @@ export interface GlyphContext {
44
52
  textBaseline: string;
45
53
  /** Horizontal anchor of `fillText`. The atlas sets `left`. */
46
54
  textAlign: string;
55
+ /**
56
+ * Base direction of `fillText` and `measureText`. The atlas sets `ltr` where the context has it,
57
+ * so a run of Arabic letters starts at the pen like any other glyph.
58
+ */
59
+ direction?: string;
47
60
  /** The canvas behind the context. The atlas grows it when a glyph does not fit. */
48
61
  readonly canvas: {
49
62
  /** Width in pixels. */
@@ -109,6 +122,12 @@ export declare class SdfAtlas {
109
122
  version: number;
110
123
  private _data;
111
124
  private _source;
125
+ private _cData;
126
+ private _cSource;
127
+ private _cHeight;
128
+ private _cShelves;
129
+ private _cNextY;
130
+ private _cDirty;
112
131
  private readonly _shaders;
113
132
  private _height;
114
133
  private readonly _width;
@@ -120,6 +139,13 @@ export declare class SdfAtlas {
120
139
  private _ctx;
121
140
  private _listening;
122
141
  constructor(options?: SdfAtlasOptions);
142
+ /**
143
+ * The RGBA texture with the colours of colour glyphs (emoji), premultiplied. It starts small and
144
+ * grows like {@link SdfAtlas.source}. Read it again after {@link SdfAtlas.flush}.
145
+ */
146
+ get colorSource(): BufferImageSource;
147
+ /** How full the atlas is, 0 to 1: the share of its largest texture that holds glyphs. Near 1 it will start over soon. */
148
+ get usage(): number;
123
149
  /**
124
150
  * The R8 texture with every glyph. When the atlas grows it moves to a new, taller texture, and
125
151
  * the shaders it tracks follow. Read it again after {@link SdfAtlas.flush} rather than keeping it.
@@ -129,12 +155,33 @@ export declare class SdfAtlas {
129
155
  get dimensions(): [width: number, height: number];
130
156
  /** Vertical metrics of a font at {@link SdfAtlas.size}. */
131
157
  metrics(font: FontSpec): FontMetrics;
132
- /** Advance width of one character at {@link SdfAtlas.size}, from `measureText`. */
158
+ /** Advance width of one character, or of a run of joined letters, at {@link SdfAtlas.size}, from `measureText`. */
133
159
  advance(font: FontSpec, char: string): number;
134
160
  /** Kerning between two characters at {@link SdfAtlas.size}: how much closer (negative) Canvas puts them. */
135
161
  kerning(font: FontSpec, a: string, b: string): number;
136
- /** The baked glyph of a character, baking it now if needed. Call {@link SdfAtlas.flush} to upload. */
162
+ /**
163
+ * The baked glyph of a character, or of a cluster (a base with its marks, a run of joined Arabic
164
+ * letters), baking it now if needed. Call {@link SdfAtlas.flush} to upload.
165
+ */
137
166
  glyph(font: FontSpec, char: string): Glyph;
167
+ /**
168
+ * The box `measureText` reports for a string at {@link SdfAtlas.size}: its ink above and below
169
+ * the baseline, and its advance. Nothing is baked. Stacked marks may reach past it, see
170
+ * {@link SdfAtlas.ink} for the exact ink of one glyph.
171
+ */
172
+ measure(font: FontSpec, text: string): {
173
+ ascent: number;
174
+ descent: number;
175
+ width: number;
176
+ };
177
+ /**
178
+ * Where a glyph's ink reaches, from its baked pixels, at {@link SdfAtlas.size}: up from the
179
+ * baseline (`ascent`) and down from it (`descent`). Zero for glyphs with no ink. Bakes the glyph.
180
+ */
181
+ ink(font: FontSpec, char: string): {
182
+ ascent: number;
183
+ descent: number;
184
+ };
138
185
  /** Uploads the texture if glyphs were baked since the last call. */
139
186
  flush(): void;
140
187
  /** Forgets every glyph and starts over. Texts rebake what they need on their next frame. */
@@ -142,6 +189,9 @@ export declare class SdfAtlas {
142
189
  /** Frees the texture. */
143
190
  destroy(): void;
144
191
  private _createSource;
192
+ private _createColorSource;
193
+ /** Shelf packing in the colour texture, which grows to {@link SdfAtlas} `maxHeight` like the other. */
194
+ private _placeColor;
145
195
  private _context;
146
196
  private _font;
147
197
  private _bake;
@@ -9,6 +9,43 @@ const NO_INK = {
9
9
  w: 0,
10
10
  h: 0
11
11
  };
12
+ /** Width of the colour texture in texels. */
13
+ const COLOR_WIDTH = 512;
14
+ /** Starting height of the colour texture. */
15
+ const COLOR_START = 16;
16
+ /** True when some inked pixel of the box is not black: the glyph comes from a colour font. */
17
+ function hasColor(pixels, w, x0, y0, x1, y1) {
18
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
19
+ const i = (y * w + x) * 4;
20
+ if (pixels[i + 3] > 32 && pixels[i] + pixels[i + 1] + pixels[i + 2] > 48) return true;
21
+ }
22
+ return false;
23
+ }
24
+ /** Object replacement character: stands for inline objects, never baked. */
25
+ const OBJECT = "";
26
+ /** The rows and columns that hold ink in RGBA pixels, as a half-open box, or null when there is none. */
27
+ function inkBox(pixels, w, h) {
28
+ let x0 = w;
29
+ let y0 = h;
30
+ let x1 = 0;
31
+ let y1 = 0;
32
+ for (let y = 0; y < h; y++) {
33
+ const row = y * w * 4;
34
+ for (let x = 0; x < w; x++) {
35
+ if (pixels[row + x * 4 + 3] === 0) continue;
36
+ if (x < x0) x0 = x;
37
+ if (x >= x1) x1 = x + 1;
38
+ if (y < y0) y0 = y;
39
+ y1 = y + 1;
40
+ }
41
+ }
42
+ return x1 > x0 && y1 > y0 ? {
43
+ x0,
44
+ y0,
45
+ x1,
46
+ y1
47
+ } : null;
48
+ }
12
49
  /** CSS `font` shorthand for a spec at a size. */
13
50
  function fontString(font, size) {
14
51
  return `${font.style ?? "normal"} ${font.weight ?? 400} ${size}px ${font.family}`;
@@ -43,6 +80,12 @@ var SdfAtlas = class SdfAtlas {
43
80
  version = 0;
44
81
  _data;
45
82
  _source;
83
+ _cData;
84
+ _cSource;
85
+ _cHeight = COLOR_START;
86
+ _cShelves = [];
87
+ _cNextY = 0;
88
+ _cDirty = false;
46
89
  _shaders = /* @__PURE__ */ new Set();
47
90
  _height;
48
91
  _width;
@@ -64,6 +107,19 @@ var SdfAtlas = class SdfAtlas {
64
107
  this._data = new Uint8Array(this._width * this._height);
65
108
  this._ctx = options.context ?? null;
66
109
  this._source = this._createSource();
110
+ this._cData = new Uint8Array(COLOR_WIDTH * this._cHeight * 4);
111
+ this._cSource = this._createColorSource();
112
+ }
113
+ /**
114
+ * The RGBA texture with the colours of colour glyphs (emoji), premultiplied. It starts small and
115
+ * grows like {@link SdfAtlas.source}. Read it again after {@link SdfAtlas.flush}.
116
+ */
117
+ get colorSource() {
118
+ return this._cSource;
119
+ }
120
+ /** How full the atlas is, 0 to 1: the share of its largest texture that holds glyphs. Near 1 it will start over soon. */
121
+ get usage() {
122
+ return Math.min(1, this._nextY / this._maxHeight);
67
123
  }
68
124
  /**
69
125
  * The R8 texture with every glyph. When the atlas grows it moves to a new, taller texture, and
@@ -80,6 +136,8 @@ var SdfAtlas = class SdfAtlas {
80
136
  this._shaders.add(shader);
81
137
  shader.resources.uAtlas = this._source;
82
138
  shader.resources.uAtlasSampler = this._source.style;
139
+ shader.resources.uColorAtlas = this._cSource;
140
+ shader.resources.uColorSampler = this._cSource.style;
83
141
  }
84
142
  /** @internal Stops updating a shader passed to {@link SdfAtlas.track}. */
85
143
  untrack(shader) {
@@ -93,7 +151,7 @@ var SdfAtlas = class SdfAtlas {
93
151
  metrics(font) {
94
152
  return this._font(font).metrics;
95
153
  }
96
- /** Advance width of one character at {@link SdfAtlas.size}, from `measureText`. */
154
+ /** Advance width of one character, or of a run of joined letters, at {@link SdfAtlas.size}, from `measureText`. */
97
155
  advance(font, char) {
98
156
  const entry = this._font(font);
99
157
  let w = entry.advances.get(char);
@@ -115,7 +173,10 @@ var SdfAtlas = class SdfAtlas {
115
173
  }
116
174
  return k;
117
175
  }
118
- /** The baked glyph of a character, baking it now if needed. Call {@link SdfAtlas.flush} to upload. */
176
+ /**
177
+ * The baked glyph of a character, or of a cluster (a base with its marks, a run of joined Arabic
178
+ * letters), baking it now if needed. Call {@link SdfAtlas.flush} to upload.
179
+ */
119
180
  glyph(font, char) {
120
181
  const entry = this._font(font);
121
182
  let g = entry.glyphs.get(char);
@@ -125,8 +186,48 @@ var SdfAtlas = class SdfAtlas {
125
186
  }
126
187
  return g;
127
188
  }
189
+ /**
190
+ * The box `measureText` reports for a string at {@link SdfAtlas.size}: its ink above and below
191
+ * the baseline, and its advance. Nothing is baked. Stacked marks may reach past it, see
192
+ * {@link SdfAtlas.ink} for the exact ink of one glyph.
193
+ */
194
+ measure(font, text) {
195
+ const m = this._context(this._font(font).css).measureText(text);
196
+ return {
197
+ ascent: m.actualBoundingBoxAscent,
198
+ descent: m.actualBoundingBoxDescent,
199
+ width: m.width
200
+ };
201
+ }
202
+ /**
203
+ * Where a glyph's ink reaches, from its baked pixels, at {@link SdfAtlas.size}: up from the
204
+ * baseline (`ascent`) and down from it (`descent`). Zero for glyphs with no ink. Bakes the glyph.
205
+ */
206
+ ink(font, char) {
207
+ const g = this.glyph(font, char);
208
+ if (g.w === 0) return {
209
+ ascent: 0,
210
+ descent: 0
211
+ };
212
+ return {
213
+ ascent: -(g.top + this.pad),
214
+ descent: g.top + g.h - this.pad
215
+ };
216
+ }
128
217
  /** Uploads the texture if glyphs were baked since the last call. */
129
218
  flush() {
219
+ if (this._cDirty) {
220
+ this._cDirty = false;
221
+ if (this._cSource.resource !== this._cData) {
222
+ const old = this._cSource;
223
+ this._cSource = this._createColorSource();
224
+ for (const shader of this._shaders) {
225
+ shader.resources.uColorAtlas = this._cSource;
226
+ shader.resources.uColorSampler = this._cSource.style;
227
+ }
228
+ setTimeout(() => old.destroy(), 0);
229
+ } else this._cSource.update();
230
+ }
130
231
  if (!this._dirty) return;
131
232
  this._dirty = false;
132
233
  if (this._source.resource !== this._data) {
@@ -147,7 +248,11 @@ var SdfAtlas = class SdfAtlas {
147
248
  this._shelves = [];
148
249
  this._nextY = 0;
149
250
  this._data.fill(0);
251
+ this._cShelves = [];
252
+ this._cNextY = 0;
253
+ this._cData.fill(0);
150
254
  this._dirty = true;
255
+ this._cDirty = true;
151
256
  this.version++;
152
257
  }
153
258
  /** Frees the texture. */
@@ -155,6 +260,7 @@ var SdfAtlas = class SdfAtlas {
155
260
  this._fonts.clear();
156
261
  this._shaders.clear();
157
262
  this._source.destroy();
263
+ this._cSource.destroy();
158
264
  if (SdfAtlas._shared === this) SdfAtlas._shared = null;
159
265
  }
160
266
  _createSource() {
@@ -170,6 +276,51 @@ var SdfAtlas = class SdfAtlas {
170
276
  label: "silk-text-atlas"
171
277
  });
172
278
  }
279
+ _createColorSource() {
280
+ return new BufferImageSource({
281
+ resource: this._cData,
282
+ width: COLOR_WIDTH,
283
+ height: this._cHeight,
284
+ format: "rgba8unorm",
285
+ alphaMode: "premultiplied-alpha",
286
+ scaleMode: "linear",
287
+ addressMode: "clamp-to-edge",
288
+ autoGenerateMipmaps: false,
289
+ label: "silk-text-colors"
290
+ });
291
+ }
292
+ /** Shelf packing in the colour texture, which grows to {@link SdfAtlas} `maxHeight` like the other. */
293
+ _placeColor(w, h) {
294
+ if (w > COLOR_WIDTH) return null;
295
+ for (const shelf of this._cShelves) if (h <= shelf.h && h >= shelf.h * .7 && shelf.x + w <= COLOR_WIDTH) {
296
+ const x = shelf.x;
297
+ shelf.x += w + 1;
298
+ return {
299
+ x,
300
+ y: shelf.y
301
+ };
302
+ }
303
+ while (this._cNextY + h > this._cHeight) {
304
+ if (this._cHeight >= this._maxHeight) return null;
305
+ const height = Math.min(this._maxHeight, this._cHeight * 2);
306
+ const data = new Uint8Array(COLOR_WIDTH * height * 4);
307
+ data.set(this._cData);
308
+ this._cData = data;
309
+ this._cHeight = height;
310
+ this._cDirty = true;
311
+ }
312
+ const shelf = {
313
+ y: this._cNextY,
314
+ h,
315
+ x: w + 1
316
+ };
317
+ this._cShelves.push(shelf);
318
+ this._cNextY += h + 1;
319
+ return {
320
+ x: 0,
321
+ y: shelf.y
322
+ };
323
+ }
173
324
  _context(css) {
174
325
  if (!this._ctx) {
175
326
  const ctx = DOMAdapter.get().createCanvas(256, 256).getContext("2d", { willReadFrequently: true });
@@ -178,6 +329,7 @@ var SdfAtlas = class SdfAtlas {
178
329
  }
179
330
  const ctx = this._ctx;
180
331
  if (ctx.font !== css) ctx.font = css;
332
+ if (ctx.direction !== void 0 && ctx.direction !== "ltr") ctx.direction = "ltr";
181
333
  return ctx;
182
334
  }
183
335
  _font(font) {
@@ -202,35 +354,65 @@ var SdfAtlas = class SdfAtlas {
202
354
  return entry;
203
355
  }
204
356
  _bake(entry, char) {
357
+ if (char.trim() === "" || char === OBJECT) return {
358
+ ...NO_INK,
359
+ left: 0,
360
+ top: 0
361
+ };
205
362
  const ctx = this._context(entry.css);
206
363
  const m = ctx.measureText(char);
207
- const left = Math.ceil(m.actualBoundingBoxLeft);
208
- const right = Math.ceil(m.actualBoundingBoxRight);
209
- const ascent = Math.ceil(m.actualBoundingBoxAscent);
210
- const descent = Math.ceil(m.actualBoundingBoxDescent);
211
364
  const pad = this.pad;
212
- const inkW = left + right;
213
- const inkH = ascent + descent;
214
- if (inkW <= 0 || inkH <= 0 || char.trim() === "") return {
365
+ let slack = Math.ceil(this.size * .5);
366
+ let found = null;
367
+ let penX = 0;
368
+ let baseY = 0;
369
+ for (let attempt = 0; attempt < 3; attempt++) {
370
+ const left = Math.max(0, Math.ceil(m.actualBoundingBoxLeft));
371
+ const right = Math.max(Math.ceil(m.actualBoundingBoxRight), Math.ceil(m.width));
372
+ const ascent = Math.max(0, Math.ceil(m.actualBoundingBoxAscent));
373
+ const descent = Math.max(0, Math.ceil(m.actualBoundingBoxDescent));
374
+ const rw = left + right + 2 * slack;
375
+ const rh = ascent + descent + 2 * slack;
376
+ const canvas = ctx.canvas;
377
+ if (canvas.width < rw || canvas.height < rh) {
378
+ canvas.width = Math.max(canvas.width, rw);
379
+ canvas.height = Math.max(canvas.height, rh);
380
+ ctx.font = entry.css;
381
+ if (ctx.direction !== void 0) ctx.direction = "ltr";
382
+ }
383
+ ctx.textBaseline = "alphabetic";
384
+ ctx.textAlign = "left";
385
+ ctx.fillStyle = "#000";
386
+ ctx.clearRect(0, 0, rw, rh);
387
+ penX = slack + left;
388
+ baseY = slack + ascent;
389
+ ctx.fillText(char, penX, baseY);
390
+ const pixels = ctx.getImageData(0, 0, rw, rh).data;
391
+ const ink = inkBox(pixels, rw, rh);
392
+ if (!ink) return {
393
+ ...NO_INK,
394
+ left: 0,
395
+ top: 0
396
+ };
397
+ found = {
398
+ ...ink,
399
+ pixels,
400
+ rw
401
+ };
402
+ if (ink.x0 > 0 && ink.y0 > 0 && ink.x1 < rw && ink.y1 < rh) break;
403
+ slack *= 2;
404
+ }
405
+ if (!found) return {
215
406
  ...NO_INK,
216
407
  left: 0,
217
408
  top: 0
218
409
  };
219
- const w = inkW + 2 * pad;
220
- const h = inkH + 2 * pad;
221
- const canvas = ctx.canvas;
222
- if (canvas.width < w || canvas.height < h) {
223
- canvas.width = Math.max(canvas.width, w);
224
- canvas.height = Math.max(canvas.height, h);
225
- ctx.font = entry.css;
226
- }
227
- ctx.textBaseline = "alphabetic";
228
- ctx.textAlign = "left";
229
- ctx.fillStyle = "#000";
230
- ctx.clearRect(0, 0, w, h);
231
- ctx.fillText(char, pad + left, pad + ascent);
232
- const pixels = ctx.getImageData(0, 0, w, h).data;
233
- const field = sdfFromAlpha(pixels, w, h, this.radius, this.cutoff, 4);
410
+ const { x0, y0, x1, y1, pixels, rw } = found;
411
+ const w = x1 - x0 + 2 * pad;
412
+ const h = y1 - y0 + 2 * pad;
413
+ const cell = new Uint8Array(w * h);
414
+ for (let row = y0; row < y1; row++) for (let col = x0; col < x1; col++) cell[(row - y0 + pad) * w + col - x0 + pad] = pixels[(row * rw + col) * 4 + 3];
415
+ const field = sdfFromAlpha(cell, w, h, this.radius, this.cutoff, 1);
234
416
  let at = this._place(w, h);
235
417
  if (!at) {
236
418
  console.warn("[pixi-silk] SilkText atlas is full; starting over with the glyphs in use");
@@ -248,14 +430,32 @@ var SdfAtlas = class SdfAtlas {
248
430
  const W = this._width;
249
431
  for (let row = 0; row < h; row++) data.set(field.subarray(row * w, row * w + w), (at.y + row) * W + at.x);
250
432
  this._dirty = true;
251
- return {
433
+ const glyph = {
252
434
  x: at.x,
253
435
  y: at.y,
254
436
  w,
255
437
  h,
256
- left: -(left + pad),
257
- top: -(ascent + pad)
438
+ left: x0 - pad - penX,
439
+ top: y0 - pad - baseY
258
440
  };
441
+ if (hasColor(pixels, rw, x0, y0, x1, y1)) {
442
+ const c = this._placeColor(w, h);
443
+ if (c) {
444
+ const cd = this._cData;
445
+ for (let row = y0; row < y1; row++) for (let col = x0; col < x1; col++) {
446
+ const src = (row * rw + col) * 4;
447
+ const dst = ((c.y + row - y0 + pad) * COLOR_WIDTH + c.x + col - x0 + pad) * 4;
448
+ const a = pixels[src + 3];
449
+ cd[dst] = pixels[src] * a / 255;
450
+ cd[dst + 1] = pixels[src + 1] * a / 255;
451
+ cd[dst + 2] = pixels[src + 2] * a / 255;
452
+ cd[dst + 3] = a;
453
+ }
454
+ this._cDirty = true;
455
+ glyph.color = c;
456
+ }
457
+ }
458
+ return glyph;
259
459
  }
260
460
  /** Shelf packing: rows of similar height, left to right. Grows the texture, or null when it cannot. */
261
461
  _place(w, h) {
@@ -0,0 +1,36 @@
1
+ //#region src/text/bidi.d.ts
2
+ /**
3
+ * Bidirectional text for {@link layoutText}: the Unicode Bidirectional Algorithm (UAX #9).
4
+ *
5
+ * Covered: paragraph direction (P2, P3), and embeddings, overrides and isolates (X1 to X10, U+202A
6
+ * to U+202E and U+2066 to U+2069). Also weak types (W1 to W7), bracket pairs (N0), neutrals (N1,
7
+ * N2), implicit levels (I1, I2), trailing whitespace (L1), reordering (L2) and mirrored brackets (L4).
8
+ */
9
+ /** Base direction of a paragraph. `auto` takes it from the first strong character, left to right when there is none. */
10
+ export type TextDirection = "ltr" | "rtl" | "auto";
11
+ /** Bidi character types used here (UAX #9 table 4, minus the explicit formatting types). */
12
+ export type BidiClass = "L" | "R" | "AL" | "EN" | "ES" | "ET" | "AN" | "CS" | "NSM" | "BN" | "B" | "S" | "WS" | "ON" | "LRE" | "RLE" | "LRO" | "RLO" | "PDF" | "LRI" | "RLI" | "FSI" | "PDI";
13
+ /** The bidi type of one code point. Covers the common scripts. Anything unlisted is `L`, or `ON` for punctuation and symbols. */
14
+ export declare function bidiClass(cp: number): BidiClass;
15
+ /** True when the text holds a right-to-left character or a bidi control, so it needs the bidi pass. */
16
+ export declare function hasRtl(text: string): boolean;
17
+ /** Paragraph level from the first strong type (P2, P3): 1 for `R` or `AL`, 0 for `L` or none. Text inside isolates is skipped. */
18
+ export declare function paragraphLevel(types: readonly BidiClass[], direction?: TextDirection): 0 | 1;
19
+ /**
20
+ * Embedding levels of one paragraph, one per unit, in logical order (UAX #9 rules X1 to X10, W1 to
21
+ * W7, N0 to N2, I1 and I2). `types` are the original types. `chars` are the units' text, used to
22
+ * pair brackets (N0). Even levels run left to right, odd ones right to left. Embedding controls and
23
+ * boundary neutrals take the level of the unit before them.
24
+ */
25
+ export declare function resolveLevels(types: readonly BidiClass[], level: 0 | 1, chars?: readonly string[]): number[];
26
+ /**
27
+ * L1 for one line: whitespace and isolate controls at the end of the line, and before tabs, fall
28
+ * back to the paragraph level. `types` are the original types of the line's units. Changes
29
+ * `levels` in place.
30
+ */
31
+ export declare function resetWhitespace(types: readonly BidiClass[], levels: number[], level: number): void;
32
+ /** L2: the visual order of a line as indices into `levels`, left to right. */
33
+ export declare function visualOrder(levels: readonly number[]): number[];
34
+ /** L4: the mirrored form of a character drawn right to left, such as `)` for `(`, or the character itself. */
35
+ export declare function mirror(char: string): string;
36
+ //#endregion