@excaliburjs/plugin-sdf-text 0.0.0-stage → 1.0.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.
- package/LICENSE +25 -0
- package/dist/cli.js +294 -0
- package/dist/excalibur-sdf-text.js +712 -0
- package/dist/excalibur-sdf-text.js.map +1 -0
- package/dist/excalibur-sdf-text.min.js +498 -0
- package/dist/excalibur-sdf-text.min.js.map +1 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/sdf-font.d.ts +227 -0
- package/dist/types/sdf-text-plugin.d.ts +13 -0
- package/dist/types/sdf-text-renderer.d.ts +79 -0
- package/dist/types/sdf-text.d.ts +59 -0
- package/package.json +68 -4
- package/readme.md +112 -0
- package/README.md +0 -3
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
import { BoundingBox, Color, ExcaliburGraphicsContextWebGL, FontSource, Graphic, ImageFiltering, ImageSource, ImageSourceAttributeConstants, Plugin, QuadIndexBuffer, Resource, Shader, Vector, VertexBuffer, VertexLayout, vec } from "excalibur";
|
|
2
|
+
// node_modules/@mapbox/tiny-sdf/index.js
|
|
3
|
+
var INF = 0x56bc75e2d63100000;
|
|
4
|
+
var TinySDF = class {
|
|
5
|
+
constructor({ fontSize = 24, buffer = 3, radius = 8, cutoff = .25, fontFamily = "sans-serif", fontWeight = "normal", fontStyle = "normal", lang = null } = {}) {
|
|
6
|
+
this.buffer = buffer;
|
|
7
|
+
this.cutoff = cutoff;
|
|
8
|
+
this.radius = radius;
|
|
9
|
+
this.lang = lang;
|
|
10
|
+
const size = this.size = fontSize + buffer * 4;
|
|
11
|
+
const canvas = this._createCanvas(size);
|
|
12
|
+
const ctx = this.ctx = canvas.getContext("2d", { willReadFrequently: true });
|
|
13
|
+
ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
|
|
14
|
+
ctx.textBaseline = "alphabetic";
|
|
15
|
+
ctx.textAlign = "left";
|
|
16
|
+
ctx.fillStyle = "black";
|
|
17
|
+
this.gridOuter = new Float64Array(size * size);
|
|
18
|
+
this.gridInner = new Float64Array(size * size);
|
|
19
|
+
this.f = new Float64Array(size);
|
|
20
|
+
this.z = new Float64Array(size + 1);
|
|
21
|
+
this.v = new Uint16Array(size);
|
|
22
|
+
}
|
|
23
|
+
_createCanvas(size) {
|
|
24
|
+
const canvas = document.createElement("canvas");
|
|
25
|
+
canvas.width = canvas.height = size;
|
|
26
|
+
return canvas;
|
|
27
|
+
}
|
|
28
|
+
draw(char) {
|
|
29
|
+
const { width: glyphAdvance, actualBoundingBoxAscent, actualBoundingBoxDescent, actualBoundingBoxLeft, actualBoundingBoxRight } = this.ctx.measureText(char);
|
|
30
|
+
const glyphTop = Math.ceil(actualBoundingBoxAscent);
|
|
31
|
+
const glyphLeft = 0;
|
|
32
|
+
const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight - actualBoundingBoxLeft)));
|
|
33
|
+
const glyphHeight = Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent));
|
|
34
|
+
const width = glyphWidth + 2 * this.buffer;
|
|
35
|
+
const height = glyphHeight + 2 * this.buffer;
|
|
36
|
+
const len = Math.max(width * height, 0);
|
|
37
|
+
const data = new Uint8ClampedArray(len);
|
|
38
|
+
const glyph = {
|
|
39
|
+
data,
|
|
40
|
+
width,
|
|
41
|
+
height,
|
|
42
|
+
glyphWidth,
|
|
43
|
+
glyphHeight,
|
|
44
|
+
glyphTop,
|
|
45
|
+
glyphLeft,
|
|
46
|
+
glyphAdvance
|
|
47
|
+
};
|
|
48
|
+
if (glyphWidth === 0 || glyphHeight === 0) return glyph;
|
|
49
|
+
const { ctx, buffer, gridInner, gridOuter } = this;
|
|
50
|
+
if (this.lang) ctx.lang = this.lang;
|
|
51
|
+
ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);
|
|
52
|
+
ctx.fillText(char, buffer, buffer + glyphTop);
|
|
53
|
+
const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);
|
|
54
|
+
gridOuter.fill(INF, 0, len);
|
|
55
|
+
gridInner.fill(0, 0, len);
|
|
56
|
+
for (let y = 0; y < glyphHeight; y++) for (let x = 0; x < glyphWidth; x++) {
|
|
57
|
+
const a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255;
|
|
58
|
+
if (a === 0) continue;
|
|
59
|
+
const j = (y + buffer) * width + x + buffer;
|
|
60
|
+
if (a === 1) {
|
|
61
|
+
gridOuter[j] = 0;
|
|
62
|
+
gridInner[j] = INF;
|
|
63
|
+
} else {
|
|
64
|
+
const d = .5 - a;
|
|
65
|
+
gridOuter[j] = d > 0 ? d * d : 0;
|
|
66
|
+
gridInner[j] = d < 0 ? d * d : 0;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z);
|
|
70
|
+
edt(gridInner, buffer, buffer, glyphWidth, glyphHeight, width, this.f, this.v, this.z);
|
|
71
|
+
for (let i = 0; i < len; i++) {
|
|
72
|
+
const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);
|
|
73
|
+
data[i] = Math.round(255 - 255 * (d / this.radius + this.cutoff));
|
|
74
|
+
}
|
|
75
|
+
return glyph;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
function edt(data, x0, y0, width, height, gridSize, f, v, z) {
|
|
79
|
+
for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);
|
|
80
|
+
for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z);
|
|
81
|
+
}
|
|
82
|
+
function edt1d(grid, offset, stride, length, f, v, z) {
|
|
83
|
+
v[0] = 0;
|
|
84
|
+
z[0] = -0x56bc75e2d63100000;
|
|
85
|
+
z[1] = INF;
|
|
86
|
+
f[0] = grid[offset];
|
|
87
|
+
for (let q = 1, k = 0, s = 0; q < length; q++) {
|
|
88
|
+
f[q] = grid[offset + q * stride];
|
|
89
|
+
const q2 = q * q;
|
|
90
|
+
do {
|
|
91
|
+
const r = v[k];
|
|
92
|
+
s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;
|
|
93
|
+
} while (s <= z[k] && --k > -1);
|
|
94
|
+
k++;
|
|
95
|
+
v[k] = q;
|
|
96
|
+
z[k] = s;
|
|
97
|
+
z[k + 1] = INF;
|
|
98
|
+
}
|
|
99
|
+
for (let q = 0, k = 0; q < length; q++) {
|
|
100
|
+
while (z[k + 1] < q) k++;
|
|
101
|
+
const r = v[k];
|
|
102
|
+
const qr = q - r;
|
|
103
|
+
grid[offset + q * stride] = f[r] + qr * qr;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
// src/sdf-font.ts
|
|
107
|
+
/**
|
|
108
|
+
* tiny-sdf's default cutoff: the fraction of the distance radius that lies outside the glyph edge
|
|
109
|
+
*/
|
|
110
|
+
var SDF_CUTOFF = .25;
|
|
111
|
+
function getCharactersFromUnicodeRanges(ranges) {
|
|
112
|
+
return ranges.flatMap(([start, end]) => Array.from({ length: end - start + 1 }, (_, i) => String.fromCodePoint(start + i))).join("");
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Everything the renderer needs to lay out and draw text from an SDF atlas. Implemented by
|
|
116
|
+
* {@link SDFFont} (atlas generated in the browser at load time) and {@link SDFAtlas} (pre-generated).
|
|
117
|
+
*/
|
|
118
|
+
var SDFSource = class {
|
|
119
|
+
/**
|
|
120
|
+
* Code point to glyph placement on the atlas
|
|
121
|
+
*/
|
|
122
|
+
glyphs = /* @__PURE__ */ new Map();
|
|
123
|
+
/**
|
|
124
|
+
* Default text color when an {@link SDFText} does not specify one
|
|
125
|
+
*/
|
|
126
|
+
color = Color.Black;
|
|
127
|
+
/**
|
|
128
|
+
* Font size the atlas was generated at, text is scaled relative to this
|
|
129
|
+
*/
|
|
130
|
+
fontSize = 16;
|
|
131
|
+
/**
|
|
132
|
+
* Padding around every glyph on the atlas in pixels
|
|
133
|
+
*/
|
|
134
|
+
buffer = 2;
|
|
135
|
+
/**
|
|
136
|
+
* Max ascent above the baseline of any glyph in atlas pixels, used to place the first line
|
|
137
|
+
*/
|
|
138
|
+
ascent = 0;
|
|
139
|
+
/**
|
|
140
|
+
* Normalized distance at which a pixel counts as inside a glyph (0..1). tiny-sdf encodes the
|
|
141
|
+
* edge at `1 - cutoff`, with the default cutoff of 0.25 that is 0.75.
|
|
142
|
+
*/
|
|
143
|
+
halo = .75;
|
|
144
|
+
/**
|
|
145
|
+
* Antialiasing ramp width around the glyph edge
|
|
146
|
+
*/
|
|
147
|
+
gamma = .1;
|
|
148
|
+
_cachedText;
|
|
149
|
+
_cachedSize;
|
|
150
|
+
_cachedMaxWidth;
|
|
151
|
+
_cachedLines = [];
|
|
152
|
+
/**
|
|
153
|
+
* Split text into lines, honoring explicit newlines and wrapping at `maxWidth` pixels (when given)
|
|
154
|
+
*/
|
|
155
|
+
getLines(text, size, maxWidth) {
|
|
156
|
+
if (this._cachedText === text && this._cachedSize === size && this._cachedMaxWidth === maxWidth) return this._cachedLines;
|
|
157
|
+
const lines = [];
|
|
158
|
+
for (const paragraph of text.split("\n")) {
|
|
159
|
+
if (maxWidth == null || this.measureLine(paragraph, size) <= maxWidth) {
|
|
160
|
+
lines.push(paragraph);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
let line = "";
|
|
164
|
+
for (const word of paragraph.split(" ")) {
|
|
165
|
+
const candidate = line ? line + " " + word : word;
|
|
166
|
+
if (this.measureLine(candidate, size) <= maxWidth) line = candidate;
|
|
167
|
+
else {
|
|
168
|
+
if (line) lines.push(line);
|
|
169
|
+
line = word;
|
|
170
|
+
while (this.measureLine(line, size) > maxWidth && line.length > 1) {
|
|
171
|
+
let fit = line.length - 1;
|
|
172
|
+
while (fit > 1 && this.measureLine(line.slice(0, fit), size) > maxWidth) fit--;
|
|
173
|
+
lines.push(line.slice(0, fit));
|
|
174
|
+
line = line.slice(fit);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
lines.push(line);
|
|
179
|
+
}
|
|
180
|
+
this._cachedText = text;
|
|
181
|
+
this._cachedSize = size;
|
|
182
|
+
this._cachedMaxWidth = maxWidth;
|
|
183
|
+
this._cachedLines = lines;
|
|
184
|
+
return lines;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Width in pixels of a single line of text at `size`
|
|
188
|
+
*/
|
|
189
|
+
measureLine(line, size) {
|
|
190
|
+
const scale = size / this.fontSize;
|
|
191
|
+
let width = 0;
|
|
192
|
+
for (const char of line) {
|
|
193
|
+
const glyph = this.glyphs.get(char);
|
|
194
|
+
if (glyph) width += glyph.glyphAdvance * scale;
|
|
195
|
+
}
|
|
196
|
+
return width;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Bounds of a block of text at `size`, every line is `size * lineHeight` tall
|
|
200
|
+
*/
|
|
201
|
+
measureText(text, size, maxWidth, lineHeight = 1.2) {
|
|
202
|
+
if (!this.isLoaded) throw new Error(`Cannot measureText("${text}") on an SDF source that is not loaded yet`);
|
|
203
|
+
const lines = this.getLines(text, size, maxWidth);
|
|
204
|
+
let width = 0;
|
|
205
|
+
for (const line of lines) width = Math.max(width, this.measureLine(line, size));
|
|
206
|
+
return BoundingBox.fromDimension(width, lines.length * size * lineHeight, Vector.Zero);
|
|
207
|
+
}
|
|
208
|
+
_computeAscent() {
|
|
209
|
+
let ascent = 0;
|
|
210
|
+
for (const glyph of this.glyphs.values()) ascent = Math.max(ascent, glyph.glyphTop);
|
|
211
|
+
this.ascent = ascent;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
/**
|
|
215
|
+
* Generates an SDF atlas when loaded, in the browser or headless. To ship a pre-generated atlas
|
|
216
|
+
* instead use {@link SDFAtlas}.
|
|
217
|
+
*/
|
|
218
|
+
var SDFFont = class extends SDFSource {
|
|
219
|
+
atlas;
|
|
220
|
+
_atlasCtx;
|
|
221
|
+
get data() {
|
|
222
|
+
return this.atlas;
|
|
223
|
+
}
|
|
224
|
+
_isLoaded = false;
|
|
225
|
+
get isLoaded() {
|
|
226
|
+
return this._isLoaded;
|
|
227
|
+
}
|
|
228
|
+
_sdfProvider = (options) => new TinySDF(options);
|
|
229
|
+
_canvasProvider = (width, height) => {
|
|
230
|
+
const canvas = document.createElement("canvas");
|
|
231
|
+
canvas.width = width;
|
|
232
|
+
canvas.height = height;
|
|
233
|
+
return canvas;
|
|
234
|
+
};
|
|
235
|
+
_imageDataProvider = (width, height) => new ImageData(width, height);
|
|
236
|
+
_fontSourceLoader = async (file, family) => {
|
|
237
|
+
await new FontSource(file, family).load();
|
|
238
|
+
};
|
|
239
|
+
fontFamily;
|
|
240
|
+
fontFile;
|
|
241
|
+
fontWeight;
|
|
242
|
+
fontStyle;
|
|
243
|
+
alphabet;
|
|
244
|
+
/**
|
|
245
|
+
* Distance field radius in pixels
|
|
246
|
+
*/
|
|
247
|
+
radius;
|
|
248
|
+
constructor(options) {
|
|
249
|
+
super();
|
|
250
|
+
this._sdfProvider = options.sdfProvider ?? this._sdfProvider;
|
|
251
|
+
this._canvasProvider = options.canvasProvider ?? this._canvasProvider;
|
|
252
|
+
this._imageDataProvider = options.imageDataProvider ?? this._imageDataProvider;
|
|
253
|
+
this._fontSourceLoader = options.fontSourceLoader ?? this._fontSourceLoader;
|
|
254
|
+
this.color = options.color ?? Color.Black;
|
|
255
|
+
this.fontFile = options.fontFile;
|
|
256
|
+
this.fontFamily = options.fontFamily;
|
|
257
|
+
this.fontSize = options.fontSize ?? 48;
|
|
258
|
+
this.fontWeight = options.fontWeight?.toString() ?? "400";
|
|
259
|
+
this.fontStyle = options.fontStyle ?? "normal";
|
|
260
|
+
this.alphabet = Array.isArray(options.alphabet) ? getCharactersFromUnicodeRanges(options.alphabet) : options.alphabet ?? getCharactersFromUnicodeRanges([[32, 126]]);
|
|
261
|
+
this.buffer = Math.ceil(this.fontSize / 8);
|
|
262
|
+
this.radius = Math.ceil(this.fontSize / 3);
|
|
263
|
+
this.gamma = 2.8284 / this.fontSize;
|
|
264
|
+
const cell = this.fontSize + this.buffer * 2;
|
|
265
|
+
const dimension = Math.ceil(Math.sqrt([...this.alphabet].length)) * cell;
|
|
266
|
+
this.atlas = this._canvasProvider(dimension, dimension);
|
|
267
|
+
if (!this.atlas) throw new Error("Cannot build the SDF atlas canvas");
|
|
268
|
+
this.atlas.setAttribute?.(ImageSourceAttributeConstants.Filtering, ImageFiltering.Blended);
|
|
269
|
+
const ctx = this.atlas.getContext("2d");
|
|
270
|
+
if (!ctx) throw new Error("Cannot build the SDF atlas 2D context");
|
|
271
|
+
this._atlasCtx = ctx;
|
|
272
|
+
}
|
|
273
|
+
_toRGBAImageData(alphaChannel, width, height) {
|
|
274
|
+
const imageData = this._imageDataProvider(width, height);
|
|
275
|
+
for (let i = 0; i < alphaChannel.length; i++) {
|
|
276
|
+
imageData.data[4 * i + 0] = alphaChannel[i];
|
|
277
|
+
imageData.data[4 * i + 1] = alphaChannel[i];
|
|
278
|
+
imageData.data[4 * i + 2] = alphaChannel[i];
|
|
279
|
+
imageData.data[4 * i + 3] = 255;
|
|
280
|
+
}
|
|
281
|
+
return imageData;
|
|
282
|
+
}
|
|
283
|
+
async load() {
|
|
284
|
+
if (this._isLoaded) return this.atlas;
|
|
285
|
+
if (this.fontFile) await this._fontSourceLoader(this.fontFile, this.fontFamily);
|
|
286
|
+
const tinySdf = this._sdfProvider({
|
|
287
|
+
fontSize: this.fontSize,
|
|
288
|
+
fontFamily: this.fontFamily,
|
|
289
|
+
fontStyle: this.fontStyle,
|
|
290
|
+
fontWeight: this.fontWeight,
|
|
291
|
+
buffer: this.buffer,
|
|
292
|
+
radius: this.radius,
|
|
293
|
+
cutoff: SDF_CUTOFF
|
|
294
|
+
});
|
|
295
|
+
const glyphs = [];
|
|
296
|
+
for (const char of this.alphabet) glyphs.push([char, tinySdf.draw(char)]);
|
|
297
|
+
let x = 0;
|
|
298
|
+
let y = 0;
|
|
299
|
+
let rowHeight = 0;
|
|
300
|
+
for (const [char, glyph] of glyphs) {
|
|
301
|
+
if (x + glyph.width > this.atlas.width) {
|
|
302
|
+
x = 0;
|
|
303
|
+
y += rowHeight;
|
|
304
|
+
rowHeight = 0;
|
|
305
|
+
}
|
|
306
|
+
if (y + glyph.height > this.atlas.height) throw new Error(`SDF atlas is too small for the alphabet of "${this.fontFamily}", this is a bug`);
|
|
307
|
+
this._atlasCtx.putImageData(this._toRGBAImageData(glyph.data, glyph.width, glyph.height), x, y);
|
|
308
|
+
const { data, ...placement } = glyph;
|
|
309
|
+
this.glyphs.set(char, {
|
|
310
|
+
...placement,
|
|
311
|
+
x,
|
|
312
|
+
y
|
|
313
|
+
});
|
|
314
|
+
x += glyph.width;
|
|
315
|
+
rowHeight = Math.max(rowHeight, glyph.height);
|
|
316
|
+
}
|
|
317
|
+
this._computeAscent();
|
|
318
|
+
this._isLoaded = true;
|
|
319
|
+
return this.atlas;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Metadata describing this atlas, write it next to the atlas image to load later with {@link SDFAtlas}
|
|
323
|
+
*/
|
|
324
|
+
toMetadata(atlasPath) {
|
|
325
|
+
const glyphs = {};
|
|
326
|
+
for (const [char, glyph] of this.glyphs) glyphs[char] = glyph;
|
|
327
|
+
return {
|
|
328
|
+
atlas: atlasPath,
|
|
329
|
+
color: this.color.toHex(),
|
|
330
|
+
alphabet: this.alphabet,
|
|
331
|
+
fontSize: this.fontSize,
|
|
332
|
+
buffer: this.buffer,
|
|
333
|
+
ascent: this.ascent,
|
|
334
|
+
halo: this.halo,
|
|
335
|
+
gamma: this.gamma,
|
|
336
|
+
glyphs
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
/**
|
|
341
|
+
* Loads a pre-generated SDF atlas (image + JSON metadata), see the `ex-generate-sdf` CLI
|
|
342
|
+
*/
|
|
343
|
+
var SDFAtlas = class extends SDFSource {
|
|
344
|
+
data;
|
|
345
|
+
metadata;
|
|
346
|
+
get atlas() {
|
|
347
|
+
return this.data.image;
|
|
348
|
+
}
|
|
349
|
+
get isLoaded() {
|
|
350
|
+
return this.data.isLoaded && this.metadata.isLoaded;
|
|
351
|
+
}
|
|
352
|
+
constructor(options) {
|
|
353
|
+
super();
|
|
354
|
+
this.data = new ImageSource(options.atlasPath, { filtering: ImageFiltering.Blended });
|
|
355
|
+
this.metadata = new Resource(options.metadataPath, "json");
|
|
356
|
+
}
|
|
357
|
+
async load() {
|
|
358
|
+
const [, metadata] = await Promise.all([this.data.load(), this.metadata.load()]);
|
|
359
|
+
for (const [char, glyph] of Object.entries(metadata.glyphs)) this.glyphs.set(char, glyph);
|
|
360
|
+
this.color = Color.fromHex(metadata.color);
|
|
361
|
+
this.halo = metadata.halo;
|
|
362
|
+
this.gamma = metadata.gamma;
|
|
363
|
+
this.fontSize = metadata.fontSize;
|
|
364
|
+
this.buffer = metadata.buffer;
|
|
365
|
+
if (metadata.ascent != null) this.ascent = metadata.ascent;
|
|
366
|
+
else this._computeAscent();
|
|
367
|
+
return this.data;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
// src/shaders/sdf-text.frag.glsl?raw
|
|
371
|
+
var sdf_text_frag_default = "#version 300 es\nprecision mediump float;\n\nin vec2 v_uv;\nin vec4 v_color;\nin lowp float v_textureIndex;\n\n// Atlases in the current batch\nuniform sampler2D u_textures[%%count%%];\n\n// Distance at which a pixel counts as \"inside\" the glyph (0..1, atlas dependent)\nuniform float u_buffer;\n// Width of the antialiasing ramp around that edge\nuniform float u_gamma;\n\nout vec4 fragColor;\n\nvoid main(){\n float dist = 1.0;\n\n // GLSL is templated out to pick the right texture by index\n %%texture_picker%%\n\n float alpha = smoothstep(u_buffer - u_gamma, u_buffer + u_gamma, dist);\n fragColor = vec4(v_color.rgb, alpha * v_color.a);\n // Excalibur expects premultiplied alpha\n fragColor.rgb *= fragColor.a;\n}\n";
|
|
372
|
+
// src/shaders/sdf-text.vert.glsl?raw
|
|
373
|
+
var sdf_text_vert_default = "#version 300 es\nin vec2 a_position;\n\nin vec2 a_uv;\nout vec2 v_uv;\n\nin vec4 a_color;\nout vec4 v_color;\n\nin lowp float a_textureIndex;\nout lowp float v_textureIndex;\n\nuniform mat4 u_matrix;\n\nvoid main(){\n gl_Position = u_matrix * vec4(a_position, 0., 1.);\n v_uv = a_uv;\n v_color = a_color;\n v_textureIndex = a_textureIndex;\n}\n";
|
|
374
|
+
// src/sdf-text-renderer.ts
|
|
375
|
+
/**
|
|
376
|
+
* Finds how many `if` branches the fragment shader can hold on this GPU, which bounds how many
|
|
377
|
+
* atlases a batch can reference
|
|
378
|
+
*/
|
|
379
|
+
function getMaxShaderComplexity(gl, numIfs) {
|
|
380
|
+
const assembleTestShader = (numIfs) => {
|
|
381
|
+
const testShader = `#version 300 es
|
|
382
|
+
precision mediump float;
|
|
383
|
+
out vec4 fragColor;
|
|
384
|
+
void main() {
|
|
385
|
+
float index = 1.01;
|
|
386
|
+
%%complexity%%
|
|
387
|
+
}`;
|
|
388
|
+
let testComplexity = "";
|
|
389
|
+
for (let i = 0; i < numIfs; i++) {
|
|
390
|
+
testComplexity += i === 0 ? `if (index <= ${i}.5) {\n` : ` else if (index <= ${i}.5) {\n`;
|
|
391
|
+
testComplexity += ` fragColor = vec4(1.0);\n`;
|
|
392
|
+
testComplexity += ` }\n`;
|
|
393
|
+
}
|
|
394
|
+
return testShader.replace("%%complexity%%", testComplexity);
|
|
395
|
+
};
|
|
396
|
+
let canCompile = false;
|
|
397
|
+
do {
|
|
398
|
+
const shader = gl.createShader(gl.FRAGMENT_SHADER);
|
|
399
|
+
gl.shaderSource(shader, assembleTestShader(numIfs));
|
|
400
|
+
gl.compileShader(shader);
|
|
401
|
+
canCompile = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
|
|
402
|
+
gl.deleteShader(shader);
|
|
403
|
+
if (!canCompile) numIfs = numIfs / 2 | 0;
|
|
404
|
+
} while (!canCompile && numIfs > 0);
|
|
405
|
+
return Math.max(numIfs, 1);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Name the renderer is registered under on the graphics context
|
|
409
|
+
*/
|
|
410
|
+
var SDF_TEXT_RENDERER = "ex.sdf-text-renderer";
|
|
411
|
+
/**
|
|
412
|
+
* Batched WebGL renderer for SDF text. Register it on the graphics context with
|
|
413
|
+
* {@link SDFTextPlugin}, or by hand with `context.lazyRegister('ex.sdf-text-renderer', () => new SDFTextRenderer())`.
|
|
414
|
+
*
|
|
415
|
+
* Every glyph is one textured quad; quads from any number of {@link SDFText} draws are batched into
|
|
416
|
+
* a single draw call until the vertex buffer or the texture slots fill up.
|
|
417
|
+
*/
|
|
418
|
+
var SDFTextRenderer = class {
|
|
419
|
+
type = SDF_TEXT_RENDERER;
|
|
420
|
+
priority = 0;
|
|
421
|
+
_gl;
|
|
422
|
+
_context;
|
|
423
|
+
_shader;
|
|
424
|
+
_buffer;
|
|
425
|
+
_quads;
|
|
426
|
+
_layout;
|
|
427
|
+
_maxGlyphs = 10922;
|
|
428
|
+
_glyphCount = 0;
|
|
429
|
+
_vertexIndex = 0;
|
|
430
|
+
_maxTextures = 1;
|
|
431
|
+
_textures = [];
|
|
432
|
+
_textureToIndex = /* @__PURE__ */ new Map();
|
|
433
|
+
_images = /* @__PURE__ */ new Set();
|
|
434
|
+
_gamma = 0;
|
|
435
|
+
_halo = 0;
|
|
436
|
+
_quad = [
|
|
437
|
+
0,
|
|
438
|
+
0,
|
|
439
|
+
0,
|
|
440
|
+
0,
|
|
441
|
+
0,
|
|
442
|
+
0,
|
|
443
|
+
0,
|
|
444
|
+
0
|
|
445
|
+
];
|
|
446
|
+
initialize(gl, context) {
|
|
447
|
+
this._gl = gl;
|
|
448
|
+
this._context = context;
|
|
449
|
+
const maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
|
|
450
|
+
this._maxTextures = Math.min(maxTextureUnits, getMaxShaderComplexity(gl, maxTextureUnits));
|
|
451
|
+
this._shader = new Shader({
|
|
452
|
+
name: "ex.sdf-text-renderer",
|
|
453
|
+
graphicsContext: context,
|
|
454
|
+
vertexSource: sdf_text_vert_default,
|
|
455
|
+
fragmentSource: this._transformFragmentSource(sdf_text_frag_default, this._maxTextures)
|
|
456
|
+
});
|
|
457
|
+
this._shader.compile();
|
|
458
|
+
this._shader.use();
|
|
459
|
+
this._shader.setUniformMatrix("u_matrix", context.ortho);
|
|
460
|
+
this._shader.setUniformIntArray("u_textures", [...Array(this._maxTextures)].map((_, i) => i));
|
|
461
|
+
this._buffer = new VertexBuffer({
|
|
462
|
+
gl,
|
|
463
|
+
size: 36 * this._maxGlyphs,
|
|
464
|
+
type: "dynamic"
|
|
465
|
+
});
|
|
466
|
+
this._layout = new VertexLayout({
|
|
467
|
+
gl,
|
|
468
|
+
shader: this._shader,
|
|
469
|
+
vertexBuffer: this._buffer,
|
|
470
|
+
attributes: [
|
|
471
|
+
["a_position", 2],
|
|
472
|
+
["a_uv", 2],
|
|
473
|
+
["a_textureIndex", 1],
|
|
474
|
+
["a_color", 4]
|
|
475
|
+
]
|
|
476
|
+
});
|
|
477
|
+
this._quads = new QuadIndexBuffer(gl, this._maxGlyphs, true);
|
|
478
|
+
}
|
|
479
|
+
_transformFragmentSource(source, maxTextures) {
|
|
480
|
+
let texturePicker = "";
|
|
481
|
+
for (let i = 0; i < maxTextures; i++) {
|
|
482
|
+
texturePicker += i === 0 ? `if (v_textureIndex <= ${i}.5) {\n` : ` else if (v_textureIndex <= ${i}.5) {\n`;
|
|
483
|
+
texturePicker += ` dist = texture(u_textures[${i}], v_uv).r;\n`;
|
|
484
|
+
texturePicker += ` }\n`;
|
|
485
|
+
}
|
|
486
|
+
return source.replace("%%count%%", maxTextures.toString()).replace("%%texture_picker%%", texturePicker);
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Upload the atlas once (the engine's texture loader caches it) and reserve a slot in this batch
|
|
490
|
+
*/
|
|
491
|
+
_addAtlasTexture(image) {
|
|
492
|
+
const texture = this._context.textureLoader.load(image, void 0, image.getAttribute("forceUpload") === "true");
|
|
493
|
+
image.removeAttribute("forceUpload");
|
|
494
|
+
let index = this._textureToIndex.get(texture);
|
|
495
|
+
if (index === void 0) {
|
|
496
|
+
index = this._textures.length;
|
|
497
|
+
this._textures.push(texture);
|
|
498
|
+
this._textureToIndex.set(texture, index);
|
|
499
|
+
this._images.add(image);
|
|
500
|
+
}
|
|
501
|
+
return index;
|
|
502
|
+
}
|
|
503
|
+
_isFull() {
|
|
504
|
+
return this._glyphCount >= this._maxGlyphs || this._textures.length >= this._maxTextures;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Queue a block of text. `pos` is the top left of the text block, `size` the font size in pixels.
|
|
508
|
+
*/
|
|
509
|
+
draw(source, text, pos, size, options) {
|
|
510
|
+
if (!source.isLoaded) return;
|
|
511
|
+
const { visibleCharacters = Infinity, textAlign = "left", maxWidth, lineHeight = 1.2 } = options ?? {};
|
|
512
|
+
const color = options?.color ?? source.color;
|
|
513
|
+
if (this._gamma !== source.gamma || this._halo !== source.halo) {
|
|
514
|
+
this.flush();
|
|
515
|
+
this._gamma = source.gamma;
|
|
516
|
+
this._halo = source.halo;
|
|
517
|
+
}
|
|
518
|
+
if (this._isFull() && !this._images.has(source.atlas)) this.flush();
|
|
519
|
+
const atlas = source.atlas;
|
|
520
|
+
const textureId = this._addAtlasTexture(atlas);
|
|
521
|
+
const atlasWidth = atlas.width;
|
|
522
|
+
const atlasHeight = atlas.height;
|
|
523
|
+
const transform = this._context.getTransform();
|
|
524
|
+
const vertices = this._layout.vertexBuffer.bufferData;
|
|
525
|
+
const scale = size / source.fontSize;
|
|
526
|
+
const lines = source.getLines(text, size, maxWidth);
|
|
527
|
+
const blockWidth = maxWidth ?? Math.max(...lines.map((line) => source.measureLine(line, size)));
|
|
528
|
+
const alignFactor = textAlign === "center" ? .5 : textAlign === "right" ? 1 : 0;
|
|
529
|
+
let drawn = 0;
|
|
530
|
+
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
|
|
531
|
+
const line = lines[lineIndex];
|
|
532
|
+
let penX = pos.x + (blockWidth - source.measureLine(line, size)) * alignFactor;
|
|
533
|
+
const baseline = pos.y + source.ascent * scale + lineIndex * size * lineHeight;
|
|
534
|
+
for (const char of line) {
|
|
535
|
+
if (drawn >= visibleCharacters) return;
|
|
536
|
+
drawn++;
|
|
537
|
+
const glyph = source.glyphs.get(char);
|
|
538
|
+
if (!glyph) continue;
|
|
539
|
+
if (this._isFull()) {
|
|
540
|
+
const resident = atlas;
|
|
541
|
+
this.flush();
|
|
542
|
+
this._addAtlasTexture(resident);
|
|
543
|
+
}
|
|
544
|
+
const x = penX + (glyph.glyphLeft - source.buffer) * scale;
|
|
545
|
+
const y = baseline - (glyph.glyphTop + source.buffer) * scale;
|
|
546
|
+
const w = glyph.width * scale;
|
|
547
|
+
const h = glyph.height * scale;
|
|
548
|
+
penX += glyph.glyphAdvance * scale;
|
|
549
|
+
const quad = this._quad;
|
|
550
|
+
quad[0] = x;
|
|
551
|
+
quad[1] = y;
|
|
552
|
+
quad[2] = x + w;
|
|
553
|
+
quad[3] = y;
|
|
554
|
+
quad[4] = x;
|
|
555
|
+
quad[5] = y + h;
|
|
556
|
+
quad[6] = x + w;
|
|
557
|
+
quad[7] = y + h;
|
|
558
|
+
transform.multiplyQuadInPlace(quad);
|
|
559
|
+
const u0 = glyph.x / atlasWidth;
|
|
560
|
+
const v0 = glyph.y / atlasHeight;
|
|
561
|
+
const u1 = (glyph.x + glyph.width) / atlasWidth;
|
|
562
|
+
const v1 = (glyph.y + glyph.height) / atlasHeight;
|
|
563
|
+
this._pushVertex(vertices, quad[0], quad[1], u0, v0, textureId, color);
|
|
564
|
+
this._pushVertex(vertices, quad[4], quad[5], u0, v1, textureId, color);
|
|
565
|
+
this._pushVertex(vertices, quad[2], quad[3], u1, v0, textureId, color);
|
|
566
|
+
this._pushVertex(vertices, quad[6], quad[7], u1, v1, textureId, color);
|
|
567
|
+
this._glyphCount++;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
_pushVertex(vertices, x, y, u, v, textureId, color) {
|
|
572
|
+
vertices[this._vertexIndex++] = x;
|
|
573
|
+
vertices[this._vertexIndex++] = y;
|
|
574
|
+
vertices[this._vertexIndex++] = u;
|
|
575
|
+
vertices[this._vertexIndex++] = v;
|
|
576
|
+
vertices[this._vertexIndex++] = textureId;
|
|
577
|
+
vertices[this._vertexIndex++] = color.r / 255;
|
|
578
|
+
vertices[this._vertexIndex++] = color.g / 255;
|
|
579
|
+
vertices[this._vertexIndex++] = color.b / 255;
|
|
580
|
+
vertices[this._vertexIndex++] = color.a;
|
|
581
|
+
}
|
|
582
|
+
get hasPendingDraws() {
|
|
583
|
+
return this._glyphCount !== 0;
|
|
584
|
+
}
|
|
585
|
+
flush() {
|
|
586
|
+
if (this._glyphCount === 0) return;
|
|
587
|
+
const gl = this._gl;
|
|
588
|
+
this._shader.use();
|
|
589
|
+
this._layout.use(true, 36 * this._glyphCount);
|
|
590
|
+
this._shader.setUniformMatrix("u_matrix", this._context.ortho);
|
|
591
|
+
this._shader.setUniformFloat("u_gamma", this._gamma);
|
|
592
|
+
this._shader.setUniformFloat("u_buffer", this._halo);
|
|
593
|
+
for (let i = 0; i < this._maxTextures; i++) {
|
|
594
|
+
gl.activeTexture(gl.TEXTURE0 + i);
|
|
595
|
+
gl.bindTexture(gl.TEXTURE_2D, this._textures[i] || this._textures[0]);
|
|
596
|
+
}
|
|
597
|
+
this._quads.bind();
|
|
598
|
+
gl.drawElements(gl.TRIANGLES, this._glyphCount * 6, this._quads.bufferGlType, 0);
|
|
599
|
+
this._glyphCount = 0;
|
|
600
|
+
this._vertexIndex = 0;
|
|
601
|
+
this._textures.length = 0;
|
|
602
|
+
this._textureToIndex.clear();
|
|
603
|
+
this._images.clear();
|
|
604
|
+
}
|
|
605
|
+
dispose() {
|
|
606
|
+
this._buffer.dispose();
|
|
607
|
+
this._quads.dispose();
|
|
608
|
+
this._shader.dispose();
|
|
609
|
+
this._textures.length = 0;
|
|
610
|
+
this._context = null;
|
|
611
|
+
this._gl = null;
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
// src/sdf-text.ts
|
|
615
|
+
/**
|
|
616
|
+
* A text {@link Graphic} drawn from a signed distance field atlas by the {@link SDFTextRenderer}.
|
|
617
|
+
* Crisp at any size, rotation or zoom, and batched with other SDF text in the same frame.
|
|
618
|
+
*/
|
|
619
|
+
var SDFText = class SDFText extends Graphic {
|
|
620
|
+
sdf;
|
|
621
|
+
size;
|
|
622
|
+
color;
|
|
623
|
+
visibleCharacters;
|
|
624
|
+
textAlign;
|
|
625
|
+
maxWidth;
|
|
626
|
+
lineHeight;
|
|
627
|
+
_text;
|
|
628
|
+
_measuredFor;
|
|
629
|
+
constructor(options) {
|
|
630
|
+
super(options);
|
|
631
|
+
this.sdf = options.sdf;
|
|
632
|
+
this._text = options.text;
|
|
633
|
+
this.size = options.size ?? options.sdf.fontSize;
|
|
634
|
+
this.color = options.color;
|
|
635
|
+
this.visibleCharacters = options.visibleCharacters ?? Infinity;
|
|
636
|
+
this.textAlign = options.textAlign ?? "left";
|
|
637
|
+
this.maxWidth = options.maxWidth;
|
|
638
|
+
this.lineHeight = options.lineHeight ?? 1.2;
|
|
639
|
+
this._calculateDimension();
|
|
640
|
+
}
|
|
641
|
+
get text() {
|
|
642
|
+
return this._text;
|
|
643
|
+
}
|
|
644
|
+
set text(value) {
|
|
645
|
+
this._text = value;
|
|
646
|
+
this._calculateDimension();
|
|
647
|
+
}
|
|
648
|
+
get width() {
|
|
649
|
+
this._calculateDimension();
|
|
650
|
+
return super.width;
|
|
651
|
+
}
|
|
652
|
+
set width(value) {
|
|
653
|
+
super.width = value;
|
|
654
|
+
}
|
|
655
|
+
get height() {
|
|
656
|
+
this._calculateDimension();
|
|
657
|
+
return super.height;
|
|
658
|
+
}
|
|
659
|
+
set height(value) {
|
|
660
|
+
super.height = value;
|
|
661
|
+
}
|
|
662
|
+
_calculateDimension() {
|
|
663
|
+
if (!this.sdf.isLoaded) return;
|
|
664
|
+
const key = `${this._text}|${this.size}|${this.maxWidth}|${this.lineHeight}`;
|
|
665
|
+
if (this._measuredFor === key) return;
|
|
666
|
+
this._measuredFor = key;
|
|
667
|
+
const { width, height } = this.sdf.measureText(this._text, this.size, this.maxWidth, this.lineHeight);
|
|
668
|
+
super.width = width;
|
|
669
|
+
super.height = height;
|
|
670
|
+
}
|
|
671
|
+
_drawImage(ex, x, y) {
|
|
672
|
+
if (ex instanceof ExcaliburGraphicsContextWebGL) ex.draw(SDF_TEXT_RENDERER, this.sdf, this._text, vec(x, y), this.size, {
|
|
673
|
+
visibleCharacters: this.visibleCharacters,
|
|
674
|
+
color: this.color,
|
|
675
|
+
textAlign: this.textAlign,
|
|
676
|
+
maxWidth: this.maxWidth,
|
|
677
|
+
lineHeight: this.lineHeight
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
clone() {
|
|
681
|
+
return new SDFText({
|
|
682
|
+
...this.cloneGraphicOptions(),
|
|
683
|
+
sdf: this.sdf,
|
|
684
|
+
text: this._text,
|
|
685
|
+
size: this.size,
|
|
686
|
+
color: this.color,
|
|
687
|
+
visibleCharacters: this.visibleCharacters,
|
|
688
|
+
textAlign: this.textAlign,
|
|
689
|
+
maxWidth: this.maxWidth,
|
|
690
|
+
lineHeight: this.lineHeight
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
};
|
|
694
|
+
// src/sdf-text-plugin.ts
|
|
695
|
+
/**
|
|
696
|
+
* Installs the {@link SDFTextRenderer} on the engine's WebGL graphics context.
|
|
697
|
+
*
|
|
698
|
+
* ```typescript
|
|
699
|
+
* const game = new ex.Engine({ plugins: [new SDFTextPlugin()] });
|
|
700
|
+
* ```
|
|
701
|
+
*/
|
|
702
|
+
var SDFTextPlugin = class extends Plugin {
|
|
703
|
+
constructor() {
|
|
704
|
+
super("sdf-text");
|
|
705
|
+
}
|
|
706
|
+
onGraphicsPostInitialize(context) {
|
|
707
|
+
if (context instanceof ExcaliburGraphicsContextWebGL) context.lazyRegister(SDF_TEXT_RENDERER, () => new SDFTextRenderer());
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
export { SDFAtlas, SDFFont, SDFSource, SDFText, SDFTextPlugin, SDFTextRenderer, SDF_TEXT_RENDERER, getCharactersFromUnicodeRanges, getMaxShaderComplexity };
|
|
711
|
+
|
|
712
|
+
//# sourceMappingURL=excalibur-sdf-text.js.map
|