@babylonjs/lite-gl 1.19.0 → 1.20.0-preview

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +1350 -0
  2. package/LICENSE +201 -0
  3. package/README.md +31 -0
  4. package/index.d.ts +13 -0
  5. package/index.js +7 -0
  6. package/index.js.map +1 -1
  7. package/package.json +9 -3
  8. package/text/_gpu/text-effect.d.ts +1 -0
  9. package/text/_gpu/text-effect.js +70 -0
  10. package/text/_gpu/text-effect.js.map +1 -0
  11. package/text/_gpu/text-instances.d.ts +1 -0
  12. package/text/_gpu/text-instances.js +57 -0
  13. package/text/_gpu/text-instances.js.map +1 -0
  14. package/text/_gpu/text-textures.d.ts +1 -0
  15. package/text/_gpu/text-textures.js +82 -0
  16. package/text/_gpu/text-textures.js.map +1 -0
  17. package/text/_gpu/text-vao.d.ts +1 -0
  18. package/text/_gpu/text-vao.js +49 -0
  19. package/text/_gpu/text-vao.js.map +1 -0
  20. package/text/default-text-data.d.ts +28 -0
  21. package/text/default-text-data.js +103 -0
  22. package/text/default-text-data.js.map +1 -0
  23. package/text/font.d.ts +16 -0
  24. package/text/font.js +24 -0
  25. package/text/font.js.map +1 -0
  26. package/text/glyph-extraction.d.ts +19 -0
  27. package/text/glyph-extraction.js +115 -0
  28. package/text/glyph-extraction.js.map +1 -0
  29. package/text/glyph-storage.d.ts +68 -0
  30. package/text/glyph-storage.js +298 -0
  31. package/text/glyph-storage.js.map +1 -0
  32. package/text/layout.d.ts +18 -0
  33. package/text/layout.js +219 -0
  34. package/text/layout.js.map +1 -0
  35. package/text/set-font-weight-offset.d.ts +5 -0
  36. package/text/set-font-weight-offset.js +67 -0
  37. package/text/set-font-weight-offset.js.map +1 -0
  38. package/text/shaders/slug-shader.d.ts +1 -0
  39. package/text/shaders/slug-shader.js +181 -0
  40. package/text/shaders/slug-shader.js.map +1 -0
  41. package/text/shaders/text-shader-fragment.d.ts +1 -0
  42. package/text/shaders/text-shader-fragment.js +2 -0
  43. package/text/shaders/text-shader-fragment.js.map +1 -0
  44. package/text/shaders/weight-shader-fragment.d.ts +1 -0
  45. package/text/shaders/weight-shader-fragment.js +75 -0
  46. package/text/shaders/weight-shader-fragment.js.map +1 -0
  47. package/text/text-data.d.ts +109 -0
  48. package/text/text-data.js +723 -0
  49. package/text/text-data.js.map +1 -0
  50. package/text/text-renderer.d.ts +68 -0
  51. package/text/text-renderer.js +238 -0
  52. package/text/text-renderer.js.map +1 -0
@@ -0,0 +1,298 @@
1
+ /** Glyph storage: per-curve-set CPU outline catalog plus the GPU atlas packed from it.
2
+ *
3
+ * Layered:
4
+ * - `GLGlyphStorage` is the opaque public handle. Holds one or more curve-sets keyed by
5
+ * `GLCurveSetId` (typically a font family name). Each curve-set owns its glyph
6
+ * outlines plus the `SharedAtlas` packed from them.
7
+ * - `SharedAtlas` stages float32 curve control points and uint32 band headers/
8
+ * curve-reference lists in append-only RGBA and RG arrays, respectively.
9
+ * - Atlas packing (`packAppendGlyph`) and spatial-band partitioning (`buildGlyphBands`)
10
+ * live here as internal helpers — they implement the storage's invariants and are
11
+ * not callable from outside the module.
12
+ * - GPU creation/upload (`SharedAtlasGpu`, `ensureSharedAtlasGpu`) lives in
13
+ * `_gpu/text-textures.ts`; the shared types are exported from here. GPU teardown
14
+ * is performed inline in `disposeGlyphStorage` to avoid a circular import edge.
15
+ *
16
+ * Lifetime is caller-owned (matches `Texture2D` semantics):
17
+ * - `createGlyphStorage(initial?)` allocates a fresh storage, optionally seeded.
18
+ * - `updateGlyphStorage(storage, curveSetId, curves)` adds glyphs (creating the
19
+ * curve-set on demand). Glyph ids already present are skipped.
20
+ * - `disposeGlyphStorage(storage)` releases every atlas. The caller must ensure no
21
+ * `GLTextData` is still drawing from it — using a disposed storage is undefined
22
+ * behavior. Idempotent.
23
+ */
24
+ import { disposeTexture } from "../texture.js";
25
+ // ─── Internal supporting types ────────────────────────────────────────────
26
+ // Tagged `@internal` on the type itself so the d.ts trim pass strips them from the
27
+ // published types. Fields still use `_` prefixes so production property mangling can
28
+ // shorten them.
29
+ /** @internal Width of the curve / band textures (texels). */
30
+ export const TEX_WIDTH = 4096;
31
+ /** @internal Floats per glyph in `SharedAtlas._metaData`, laid out as three `vec4<f32>` to match
32
+ * the shader's `GlyphMetadata`: bounds (xMin, yMin, xMax, yMax), atlas (glyphLocX, glyphLocY,
33
+ * bandMaxX, bandMaxY), band (bandScaleX, bandScaleY, bandOffsetX, bandOffsetY).
34
+ *
35
+ * All twelve depend only on the glyph, so they live here — written once when the glyph is
36
+ * appended — instead of being copied into every instance that references the glyph. */
37
+ export const GLYPH_METADATA_FLOATS = 12;
38
+ // ─── Public API ───────────────────────────────────────────────────────────
39
+ /** Build a `GLGlyphStorage`. If `initial` is provided, each curve-set is packed into its
40
+ * own atlas synchronously. The passed inner maps are *adopted* by the storage — the
41
+ * caller must not mutate them directly afterward (use `updateGlyphStorage` instead). */
42
+ export function createGlyphStorage(initial) {
43
+ const _curveSets = new Map();
44
+ if (initial) {
45
+ for (const [curveSetId, curves] of initial) {
46
+ _curveSets.set(curveSetId, makeCurveSet(curves));
47
+ }
48
+ }
49
+ return { _curveSets };
50
+ }
51
+ /** Add glyphs to the named curve-set, creating it if it doesn't exist yet. Glyph ids
52
+ * already present in the curve-set are skipped (the existing outline + atlas slot wins).
53
+ * Safe to call between frames: the atlas grows in place and the next render uploads the
54
+ * new glyphs. */
55
+ export function updateGlyphStorage(storage, curveSetId, curves) {
56
+ let cs = storage._curveSets.get(curveSetId);
57
+ if (!cs) {
58
+ cs = makeCurveSet(new Map());
59
+ storage._curveSets.set(curveSetId, cs);
60
+ }
61
+ for (const [glyphId, glyph] of curves) {
62
+ if (cs._curves.has(glyphId)) {
63
+ continue;
64
+ }
65
+ cs._curves.set(glyphId, glyph);
66
+ cs._atlas._glyphSlots.set(glyphId, packAppendGlyph(cs._atlas, glyph));
67
+ }
68
+ }
69
+ /** Release every GPU atlas owned by `storage`. Idempotent. The caller is responsible for
70
+ * ensuring no `GLTextData` is still drawing from this storage. */
71
+ export function disposeGlyphStorage(storage) {
72
+ for (const cs of storage._curveSets.values()) {
73
+ const gpu = cs._atlas._gpu;
74
+ if (gpu) {
75
+ disposeTexture(gpu._engine, gpu._curveTex);
76
+ disposeTexture(gpu._engine, gpu._bandTex);
77
+ disposeTexture(gpu._engine, gpu._metaTex);
78
+ cs._atlas._gpu = null;
79
+ }
80
+ }
81
+ storage._curveSets.clear();
82
+ }
83
+ // ─── Internal: SharedAtlas construction + glyph packing ───────────────────
84
+ const ROW_COMPONENTS = TEX_WIDTH * 4;
85
+ /** @internal Create an empty `SharedAtlas`. */
86
+ export function createSharedAtlas() {
87
+ return {
88
+ _curveTexData: new Float32Array(ROW_COMPONENTS),
89
+ _curveTexelsUsed: 0,
90
+ _bandTexData: new Uint32Array(TEX_WIDTH * 2),
91
+ _bandTexelsUsed: 0,
92
+ _glyphSlots: new Map(),
93
+ _metaData: new Float32Array(GLYPH_METADATA_FLOATS * 16),
94
+ _slotCount: 0,
95
+ _version: 0,
96
+ _gpu: null,
97
+ };
98
+ }
99
+ function makeCurveSet(curves) {
100
+ const atlas = createSharedAtlas();
101
+ for (const [glyphId, glyph] of curves) {
102
+ atlas._glyphSlots.set(glyphId, packAppendGlyph(atlas, glyph));
103
+ }
104
+ return { _curves: curves, _atlas: atlas };
105
+ }
106
+ /** Grow a texel-staging array to hold at least `neededTexels` texels,
107
+ * rounded up to a whole 4096-texel row. Returns the same array when already large enough. */
108
+ function ensureTexelCapacity(current, neededTexels, ArrayType, componentsPerTexel = 4) {
109
+ const neededComponents = neededTexels * componentsPerTexel;
110
+ const rowComponents = TEX_WIDTH * componentsPerTexel;
111
+ if (current.length >= neededComponents) {
112
+ return current;
113
+ }
114
+ let newLength = Math.max(current.length * 2, rowComponents);
115
+ while (newLength < neededComponents) {
116
+ newLength *= 2;
117
+ }
118
+ // Round up to a whole row to keep texel math aligned.
119
+ newLength = Math.ceil(newLength / rowComponents) * rowComponents;
120
+ const grown = new ArrayType(newLength);
121
+ grown.set(current);
122
+ return grown;
123
+ }
124
+ /** @internal Append `glyph` to `atlas`. Returns the new slot. Caller must guarantee
125
+ * glyph is not already present. */
126
+ export function packAppendGlyph(atlas, glyph) {
127
+ const bands = buildGlyphBands(glyph);
128
+ const curves = glyph.curves;
129
+ // ── Curve texels: 2 texels per curve, must not straddle a row boundary. ──
130
+ let curveTexel = atlas._curveTexelsUsed;
131
+ const curveTexelPositions = new Array(curves.length);
132
+ for (let i = 0; i < curves.length; i++) {
133
+ const row0 = (curveTexel / TEX_WIDTH) | 0;
134
+ const row1 = ((curveTexel + 1) / TEX_WIDTH) | 0;
135
+ if (row0 !== row1) {
136
+ curveTexel = row1 * TEX_WIDTH;
137
+ }
138
+ curveTexelPositions[i] = curveTexel;
139
+ curveTexel += 2;
140
+ }
141
+ const curveTexelsEnd = curveTexel;
142
+ atlas._curveTexData = ensureTexelCapacity(atlas._curveTexData, curveTexelsEnd, Float32Array);
143
+ const curveData = atlas._curveTexData;
144
+ for (let i = 0; i < curves.length; i++) {
145
+ const c = curves[i];
146
+ const tl = curveTexelPositions[i];
147
+ const o0 = tl * 4;
148
+ curveData[o0] = c.p0x;
149
+ curveData[o0 + 1] = c.p0y;
150
+ curveData[o0 + 2] = c.p1x;
151
+ curveData[o0 + 3] = c.p1y;
152
+ const o1 = (tl + 1) * 4;
153
+ curveData[o1] = c.p2x;
154
+ curveData[o1 + 1] = c.p2y;
155
+ // (.zw left zero; padded.)
156
+ }
157
+ atlas._curveTexelsUsed = curveTexelsEnd;
158
+ // ── Band block: headers must not straddle a row; followed by curve-index lists. ──
159
+ const headerCount = bands._hBandCount + bands._vBandCount;
160
+ let bandStart = atlas._bandTexelsUsed;
161
+ const curX = bandStart % TEX_WIDTH;
162
+ if (curX + headerCount > TEX_WIDTH) {
163
+ bandStart = (((bandStart / TEX_WIDTH) | 0) + 1) * TEX_WIDTH;
164
+ }
165
+ const glyphLocX = bandStart % TEX_WIDTH;
166
+ const glyphLocY = (bandStart / TEX_WIDTH) | 0;
167
+ const allBands = [...bands._hBands, ...bands._vBands];
168
+ let curveListOffset = headerCount;
169
+ const bandOffsets = new Array(allBands.length);
170
+ for (let i = 0; i < allBands.length; i++) {
171
+ bandOffsets[i] = curveListOffset;
172
+ curveListOffset += allBands[i]._curveIndices.length;
173
+ }
174
+ const bandTexelsEnd = bandStart + curveListOffset;
175
+ atlas._bandTexData = ensureTexelCapacity(atlas._bandTexData, bandTexelsEnd, Uint32Array, 2);
176
+ const bandData = atlas._bandTexData;
177
+ // Headers.
178
+ for (let i = 0; i < allBands.length; i++) {
179
+ const tl = bandStart + i;
180
+ const di = tl * 2;
181
+ bandData[di] = allBands[i]._curveIndices.length;
182
+ bandData[di + 1] = bandOffsets[i];
183
+ }
184
+ // Curve refs.
185
+ for (let i = 0; i < allBands.length; i++) {
186
+ const band = allBands[i];
187
+ const listStart = bandStart + bandOffsets[i];
188
+ for (let j = 0; j < band._curveIndices.length; j++) {
189
+ const ci = band._curveIndices[j];
190
+ const curveTexelAbs = curveTexelPositions[ci];
191
+ const cTexX = curveTexelAbs % TEX_WIDTH;
192
+ const cTexY = (curveTexelAbs / TEX_WIDTH) | 0;
193
+ const tl = listStart + j;
194
+ const di = tl * 2;
195
+ bandData[di] = cTexX;
196
+ bandData[di + 1] = cTexY;
197
+ }
198
+ }
199
+ atlas._bandTexelsUsed = bandTexelsEnd;
200
+ atlas._version++;
201
+ const { xMin, yMin, xMax, yMax } = glyph.bounds;
202
+ const widthFu = xMax - xMin;
203
+ const heightFu = yMax - yMin;
204
+ const bandScaleX = widthFu > 0 ? bands._vBandCount / widthFu : 0;
205
+ const bandScaleY = heightFu > 0 ? bands._hBandCount / heightFu : 0;
206
+ // ── Glyph metadata: written once here, read by every instance that uses this glyph. ──
207
+ const index = atlas._slotCount++;
208
+ const needMetaFloats = atlas._slotCount * GLYPH_METADATA_FLOATS;
209
+ if (atlas._metaData.length < needMetaFloats) {
210
+ const grown = new Float32Array(Math.max(atlas._metaData.length * 2, needMetaFloats));
211
+ grown.set(atlas._metaData);
212
+ atlas._metaData = grown;
213
+ }
214
+ const m = index * GLYPH_METADATA_FLOATS;
215
+ const meta = atlas._metaData;
216
+ meta[m] = xMin;
217
+ meta[m + 1] = yMin;
218
+ meta[m + 2] = xMax;
219
+ meta[m + 3] = yMax;
220
+ meta[m + 4] = glyphLocX;
221
+ meta[m + 5] = glyphLocY;
222
+ meta[m + 6] = bands._vBandCount - 1;
223
+ meta[m + 7] = bands._hBandCount - 1;
224
+ meta[m + 8] = bandScaleX;
225
+ meta[m + 9] = bandScaleY;
226
+ meta[m + 10] = -xMin * bandScaleX;
227
+ meta[m + 11] = -yMin * bandScaleY;
228
+ return { _index: index };
229
+ }
230
+ // ─── Internal: spatial-band partitioning ──────────────────────────────────
231
+ function curveAt(curves, i) {
232
+ const c = curves[i];
233
+ if (!c) {
234
+ throw new Error("buildGlyphBands: invalid curve index");
235
+ }
236
+ return c;
237
+ }
238
+ function buildBandsInternal(g) {
239
+ const { curves, bounds } = g;
240
+ const numBands = Math.max(1, Math.min(8, Math.floor(curves.length / 2)));
241
+ const { xMin, yMin, xMax, yMax } = bounds;
242
+ const width = xMax - xMin;
243
+ const height = yMax - yMin;
244
+ const bandH = height / numBands;
245
+ const bandW = width / numBands;
246
+ const hBands = [];
247
+ const vBands = [];
248
+ for (let i = 0; i < numBands; i++) {
249
+ hBands.push({ _curveIndices: [] });
250
+ vBands.push({ _curveIndices: [] });
251
+ }
252
+ for (let ci = 0; ci < curves.length; ci++) {
253
+ const c = curveAt(curves, ci);
254
+ const cyMin = Math.min(c.p0y, c.p1y, c.p2y);
255
+ const cyMax = Math.max(c.p0y, c.p1y, c.p2y);
256
+ const cxMin = Math.min(c.p0x, c.p1x, c.p2x);
257
+ const cxMax = Math.max(c.p0x, c.p1x, c.p2x);
258
+ if (height > 0) {
259
+ for (let b = 0; b < numBands; b++) {
260
+ const bMinY = yMin + b * bandH;
261
+ const bMaxY = yMin + (b + 1) * bandH;
262
+ if (cyMax >= bMinY && cyMin <= bMaxY) {
263
+ hBands[b]._curveIndices.push(ci);
264
+ }
265
+ }
266
+ }
267
+ if (width > 0) {
268
+ for (let b = 0; b < numBands; b++) {
269
+ const bMinX = xMin + b * bandW;
270
+ const bMaxX = xMin + (b + 1) * bandW;
271
+ if (cxMax >= bMinX && cxMin <= bMaxX) {
272
+ vBands[b]._curveIndices.push(ci);
273
+ }
274
+ }
275
+ }
276
+ }
277
+ // Sort curves: h-bands by descending max x, v-bands by descending max y (early-exit in shader).
278
+ for (const band of hBands) {
279
+ band._curveIndices.sort((a, b) => {
280
+ const ca = curveAt(curves, a);
281
+ const cb = curveAt(curves, b);
282
+ return Math.max(cb.p0x, cb.p1x, cb.p2x) - Math.max(ca.p0x, ca.p1x, ca.p2x);
283
+ });
284
+ }
285
+ for (const band of vBands) {
286
+ band._curveIndices.sort((a, b) => {
287
+ const ca = curveAt(curves, a);
288
+ const cb = curveAt(curves, b);
289
+ return Math.max(cb.p0y, cb.p1y, cb.p2y) - Math.max(ca.p0y, ca.p1y, ca.p2y);
290
+ });
291
+ }
292
+ return { _hBands: hBands, _vBands: vBands, _hBandCount: numBands, _vBandCount: numBands };
293
+ }
294
+ /** @internal Get (and memoize) the band partitioning for a glyph's curves. */
295
+ export function buildGlyphBands(g) {
296
+ return (g._bands ??= buildBandsInternal(g));
297
+ }
298
+ //# sourceMappingURL=glyph-storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"glyph-storage.js","sourceRoot":"","sources":["../../src/text/glyph-storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAsD/C,6EAA6E;AAC7E,mFAAmF;AACnF,qFAAqF;AACrF,gBAAgB;AAEhB,6DAA6D;AAC7D,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAkB9B;;;;;wFAK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M,EAAE,CAAC,CAAC,CAAC;YAC9B,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;QAC/E,CAAC,CAAC,CAAC;IACP,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;QACxB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;YAC7B,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YAC9B,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YAC9B,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;QAC/E,CAAC,CAAC,CAAC;IACP,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC;AAC9F,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,eAAe,CAAC,CAAgB;IAC5C,OAAO,CAAC,CAAC,CAAC,MAAM,KAAK,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC;AAChD,CAAC","sourcesContent":["/** Glyph storage: per-curve-set CPU outline catalog plus the GPU atlas packed from it.\n *\n * Layered:\n * - `GLGlyphStorage` is the opaque public handle. Holds one or more curve-sets keyed by\n * `GLCurveSetId` (typically a font family name). Each curve-set owns its glyph\n * outlines plus the `SharedAtlas` packed from them.\n * - `SharedAtlas` stages float32 curve control points and uint32 band headers/\n * curve-reference lists in append-only RGBA and RG arrays, respectively.\n * - Atlas packing (`packAppendGlyph`) and spatial-band partitioning (`buildGlyphBands`)\n * live here as internal helpers — they implement the storage's invariants and are\n * not callable from outside the module.\n * - GPU creation/upload (`SharedAtlasGpu`, `ensureSharedAtlasGpu`) lives in\n * `_gpu/text-textures.ts`; the shared types are exported from here. GPU teardown\n * is performed inline in `disposeGlyphStorage` to avoid a circular import edge.\n *\n * Lifetime is caller-owned (matches `Texture2D` semantics):\n * - `createGlyphStorage(initial?)` allocates a fresh storage, optionally seeded.\n * - `updateGlyphStorage(storage, curveSetId, curves)` adds glyphs (creating the\n * curve-set on demand). Glyph ids already present are skipped.\n * - `disposeGlyphStorage(storage)` releases every atlas. The caller must ensure no\n * `GLTextData` is still drawing from it — using a disposed storage is undefined\n * behavior. Idempotent.\n */\n\nimport type { GLEngineContext } from \"../context.js\";\nimport type { GLTexture } from \"../texture.js\";\nimport { disposeTexture } from \"../texture.js\";\n\ndeclare const glyphStorageBrand: unique symbol;\n\n// ─── Glyph outline geometry (public value types) ──────────────────────\n//\n// These describe the input contract for `updateGlyphStorage` /\n// `createGlyphStorage`. Live here (not with the default extraction module) so a\n// caller bringing their own outline source (DirectWrite, FreeType, hand-rolled)\n// can produce `GLGlyphCurves` values without importing `glyph-extraction.ts` or\n// pulling `text-shaper` into their bundle.\n\n/** Quadratic Bézier curve describing one segment of a glyph outline in font units. */\nexport type GLQuadCurve = {\n readonly p0x: number;\n readonly p0y: number;\n readonly p1x: number;\n readonly p1y: number;\n readonly p2x: number;\n readonly p2y: number;\n};\n\n/** Axis-aligned glyph extents in font units, used to size the rendered quad and spatial curve bands. */\nexport type GLGlyphBounds = {\n readonly xMin: number;\n readonly yMin: number;\n readonly xMax: number;\n readonly yMax: number;\n};\n\n/** Complete outline data for one glyph id, ready to be packed into a `GLGlyphStorage` atlas. */\nexport type GLGlyphCurves = {\n readonly glyphId: number;\n readonly curves: readonly GLQuadCurve[];\n readonly bounds: GLGlyphBounds;\n /** @internal Lazily-computed band partitioning (memoized by `buildGlyphBands`). */\n _bands?: GlyphBands;\n};\n\n// ─── Public types ─────────────────────────────────────────────────────────\n\n/** Identifier for a curve set (a font's glyph-curves map). Strings let callers use a\n * human-readable key (e.g. the font face name) for easy debugging. */\nexport type GLCurveSetId = string;\n\n/** Opaque bundle of glyph outlines (organized by curve-set) and the GPU atlases packed\n * from them. Holds an arbitrary number of curve-sets — each curve-set gets its own atlas.\n * Shared by reference across any number of `GLTextData`s that need the same glyph catalog. */\nexport interface GLGlyphStorage {\n readonly [glyphStorageBrand]: true;\n /** @internal Per-curve-set glyph outlines + the SharedAtlas they're packed into. */\n _curveSets: Map<GLCurveSetId, GlyphStorageCurveSet>;\n}\n\n// ─── Internal supporting types ────────────────────────────────────────────\n// Tagged `@internal` on the type itself so the d.ts trim pass strips them from the\n// published types. Fields still use `_` prefixes so production property mangling can\n// shorten them.\n\n/** @internal Width of the curve / band textures (texels). */\nexport const TEX_WIDTH = 4096;\n\n/** @internal Per-curve-set entry within a GLGlyphStorage. */\nexport type GlyphStorageCurveSet = {\n /** @internal */\n _curves: Map<number, GLGlyphCurves>;\n /** @internal */\n _atlas: SharedAtlas;\n};\n\n/** @internal Atlas slot for a single glyph inside a SharedAtlas. */\nexport type AtlasSlot = {\n /** @internal Dense index of this glyph's entry in `SharedAtlas._metaData`, and the value the vertex\n * shader uses to look it up in the GPU metadata texture. Slots are append-only and never\n * moved, so an index stays valid for the atlas's lifetime. */\n _index: number;\n};\n\n/** @internal Floats per glyph in `SharedAtlas._metaData`, laid out as three `vec4<f32>` to match\n * the shader's `GlyphMetadata`: bounds (xMin, yMin, xMax, yMax), atlas (glyphLocX, glyphLocY,\n * bandMaxX, bandMaxY), band (bandScaleX, bandScaleY, bandOffsetX, bandOffsetY).\n *\n * All twelve depend only on the glyph, so they live here — written once when the glyph is\n * appended — instead of being copied into every instance that references the glyph. */\nexport const GLYPH_METADATA_FLOATS = 12;\n\n/** @internal CPU + (lazy) GPU staging packed from a `GLGlyphStorage`'s glyph outlines.\n * One `SharedAtlas` per curve-set; lifetime is bound to the storage. */\nexport type SharedAtlas = {\n /** @internal Pooled curve texel staging (rgba32float, width 4096). */\n _curveTexData: Float32Array;\n /** @internal Number of curve texels actually used. */\n _curveTexelsUsed: number;\n /** @internal Pooled band texel staging (rg32uint, two components, width 4096). */\n _bandTexData: Uint32Array;\n /** @internal Number of band texels actually used. */\n _bandTexelsUsed: number;\n /** @internal Per-glyph atlas slot lookup. Slots are append-only and never moved. */\n _glyphSlots: Map<number, AtlasSlot>;\n /** @internal Glyph-invariant shader data, `GLYPH_METADATA_FLOATS` per slot, indexed by `AtlasSlot._index`.\n * Uploaded verbatim as the vertex shader's metadata lookup texture. */\n _metaData: Float32Array;\n /** @internal Number of slots appended so far; also the next `AtlasSlot._index`. */\n _slotCount: number;\n /** @internal Monotonic version bumped whenever a new glyph is appended. */\n _version: number;\n /** @internal Lazy GPU resources (one set per SharedAtlas; recreated only on capacity grow). */\n _gpu: SharedAtlasGpu | null;\n};\n\n/** @internal GPU-side companion to a `SharedAtlas`; populated lazily by\n * `ensureSharedAtlasGpu` in `_gpu/text-textures.ts`. */\nexport type SharedAtlasGpu = {\n /** @internal */\n _engine: GLEngineContext;\n /** @internal */\n _curveTex: GLTexture;\n /** @internal */\n _bandTex: GLTexture;\n /** @internal */\n _metaTex: GLTexture;\n /** @internal */\n _metaPixels: Float32Array;\n /** @internal */\n _uploadedVersion: number;\n};\n\n/** @internal Spatial-band partitioning for a glyph's curves. Memoized per `GLGlyphCurves`\n * via `GLGlyphCurves._bands`. */\nexport type GlyphBands = {\n /** @internal */\n _hBands: BandEntry[];\n /** @internal */\n _vBands: BandEntry[];\n /** @internal */\n _hBandCount: number;\n /** @internal */\n _vBandCount: number;\n};\n\n/** @internal */\nexport type BandEntry = {\n /** @internal */\n _curveIndices: number[];\n};\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/** Build a `GLGlyphStorage`. If `initial` is provided, each curve-set is packed into its\n * own atlas synchronously. The passed inner maps are *adopted* by the storage — the\n * caller must not mutate them directly afterward (use `updateGlyphStorage` instead). */\nexport function createGlyphStorage(initial?: Map<GLCurveSetId, Map<number, GLGlyphCurves>>): GLGlyphStorage {\n const _curveSets = new Map<GLCurveSetId, GlyphStorageCurveSet>();\n if (initial) {\n for (const [curveSetId, curves] of initial) {\n _curveSets.set(curveSetId, makeCurveSet(curves));\n }\n }\n return { _curveSets } as unknown as GLGlyphStorage;\n}\n\n/** Add glyphs to the named curve-set, creating it if it doesn't exist yet. Glyph ids\n * already present in the curve-set are skipped (the existing outline + atlas slot wins).\n * Safe to call between frames: the atlas grows in place and the next render uploads the\n * new glyphs. */\nexport function updateGlyphStorage(storage: GLGlyphStorage, curveSetId: GLCurveSetId, curves: ReadonlyMap<number, GLGlyphCurves>): void {\n let cs = storage._curveSets.get(curveSetId);\n if (!cs) {\n cs = makeCurveSet(new Map());\n storage._curveSets.set(curveSetId, cs);\n }\n for (const [glyphId, glyph] of curves) {\n if (cs._curves.has(glyphId)) {\n continue;\n }\n cs._curves.set(glyphId, glyph);\n cs._atlas._glyphSlots.set(glyphId, packAppendGlyph(cs._atlas, glyph));\n }\n}\n\n/** Release every GPU atlas owned by `storage`. Idempotent. The caller is responsible for\n * ensuring no `GLTextData` is still drawing from this storage. */\nexport function disposeGlyphStorage(storage: GLGlyphStorage): void {\n for (const cs of storage._curveSets.values()) {\n const gpu = cs._atlas._gpu;\n if (gpu) {\n disposeTexture(gpu._engine, gpu._curveTex);\n disposeTexture(gpu._engine, gpu._bandTex);\n disposeTexture(gpu._engine, gpu._metaTex);\n cs._atlas._gpu = null;\n }\n }\n storage._curveSets.clear();\n}\n\n// ─── Internal: SharedAtlas construction + glyph packing ───────────────────\n\nconst ROW_COMPONENTS = TEX_WIDTH * 4;\n\n/** @internal Create an empty `SharedAtlas`. */\nexport function createSharedAtlas(): SharedAtlas {\n return {\n _curveTexData: new Float32Array(ROW_COMPONENTS),\n _curveTexelsUsed: 0,\n _bandTexData: new Uint32Array(TEX_WIDTH * 2),\n _bandTexelsUsed: 0,\n _glyphSlots: new Map(),\n _metaData: new Float32Array(GLYPH_METADATA_FLOATS * 16),\n _slotCount: 0,\n _version: 0,\n _gpu: null,\n };\n}\n\nfunction makeCurveSet(curves: Map<number, GLGlyphCurves>): GlyphStorageCurveSet {\n const atlas = createSharedAtlas();\n for (const [glyphId, glyph] of curves) {\n atlas._glyphSlots.set(glyphId, packAppendGlyph(atlas, glyph));\n }\n return { _curves: curves, _atlas: atlas };\n}\n\n/** Grow a texel-staging array to hold at least `neededTexels` texels,\n * rounded up to a whole 4096-texel row. Returns the same array when already large enough. */\nfunction ensureTexelCapacity<T extends Float32Array | Uint32Array>(current: T, neededTexels: number, ArrayType: new (length: number) => T, componentsPerTexel: 2 | 4 = 4): T {\n const neededComponents = neededTexels * componentsPerTexel;\n const rowComponents = TEX_WIDTH * componentsPerTexel;\n if (current.length >= neededComponents) {\n return current;\n }\n let newLength = Math.max(current.length * 2, rowComponents);\n while (newLength < neededComponents) {\n newLength *= 2;\n }\n // Round up to a whole row to keep texel math aligned.\n newLength = Math.ceil(newLength / rowComponents) * rowComponents;\n const grown = new ArrayType(newLength);\n grown.set(current);\n return grown;\n}\n\n/** @internal Append `glyph` to `atlas`. Returns the new slot. Caller must guarantee\n * glyph is not already present. */\nexport function packAppendGlyph(atlas: SharedAtlas, glyph: GLGlyphCurves): AtlasSlot {\n const bands = buildGlyphBands(glyph);\n const curves = glyph.curves;\n\n // ── Curve texels: 2 texels per curve, must not straddle a row boundary. ──\n let curveTexel = atlas._curveTexelsUsed;\n const curveTexelPositions: number[] = new Array(curves.length);\n for (let i = 0; i < curves.length; i++) {\n const row0 = (curveTexel / TEX_WIDTH) | 0;\n const row1 = ((curveTexel + 1) / TEX_WIDTH) | 0;\n if (row0 !== row1) {\n curveTexel = row1 * TEX_WIDTH;\n }\n curveTexelPositions[i] = curveTexel;\n curveTexel += 2;\n }\n const curveTexelsEnd = curveTexel;\n atlas._curveTexData = ensureTexelCapacity(atlas._curveTexData, curveTexelsEnd, Float32Array);\n\n const curveData = atlas._curveTexData;\n for (let i = 0; i < curves.length; i++) {\n const c = curves[i]!;\n const tl = curveTexelPositions[i]!;\n const o0 = tl * 4;\n curveData[o0] = c.p0x;\n curveData[o0 + 1] = c.p0y;\n curveData[o0 + 2] = c.p1x;\n curveData[o0 + 3] = c.p1y;\n const o1 = (tl + 1) * 4;\n curveData[o1] = c.p2x;\n curveData[o1 + 1] = c.p2y;\n // (.zw left zero; padded.)\n }\n atlas._curveTexelsUsed = curveTexelsEnd;\n\n // ── Band block: headers must not straddle a row; followed by curve-index lists. ──\n const headerCount = bands._hBandCount + bands._vBandCount;\n let bandStart = atlas._bandTexelsUsed;\n const curX = bandStart % TEX_WIDTH;\n if (curX + headerCount > TEX_WIDTH) {\n bandStart = (((bandStart / TEX_WIDTH) | 0) + 1) * TEX_WIDTH;\n }\n const glyphLocX = bandStart % TEX_WIDTH;\n const glyphLocY = (bandStart / TEX_WIDTH) | 0;\n\n const allBands = [...bands._hBands, ...bands._vBands];\n let curveListOffset = headerCount;\n const bandOffsets: number[] = new Array(allBands.length);\n for (let i = 0; i < allBands.length; i++) {\n bandOffsets[i] = curveListOffset;\n curveListOffset += allBands[i]!._curveIndices.length;\n }\n const bandTexelsEnd = bandStart + curveListOffset;\n atlas._bandTexData = ensureTexelCapacity(atlas._bandTexData, bandTexelsEnd, Uint32Array, 2);\n\n const bandData = atlas._bandTexData;\n // Headers.\n for (let i = 0; i < allBands.length; i++) {\n const tl = bandStart + i;\n const di = tl * 2;\n bandData[di] = allBands[i]!._curveIndices.length;\n bandData[di + 1] = bandOffsets[i]!;\n }\n // Curve refs.\n for (let i = 0; i < allBands.length; i++) {\n const band = allBands[i]!;\n const listStart = bandStart + bandOffsets[i]!;\n for (let j = 0; j < band._curveIndices.length; j++) {\n const ci = band._curveIndices[j]!;\n const curveTexelAbs = curveTexelPositions[ci]!;\n const cTexX = curveTexelAbs % TEX_WIDTH;\n const cTexY = (curveTexelAbs / TEX_WIDTH) | 0;\n const tl = listStart + j;\n const di = tl * 2;\n bandData[di] = cTexX;\n bandData[di + 1] = cTexY;\n }\n }\n atlas._bandTexelsUsed = bandTexelsEnd;\n\n atlas._version++;\n\n const { xMin, yMin, xMax, yMax } = glyph.bounds;\n const widthFu = xMax - xMin;\n const heightFu = yMax - yMin;\n const bandScaleX = widthFu > 0 ? bands._vBandCount / widthFu : 0;\n const bandScaleY = heightFu > 0 ? bands._hBandCount / heightFu : 0;\n\n // ── Glyph metadata: written once here, read by every instance that uses this glyph. ──\n const index = atlas._slotCount++;\n const needMetaFloats = atlas._slotCount * GLYPH_METADATA_FLOATS;\n if (atlas._metaData.length < needMetaFloats) {\n const grown = new Float32Array(Math.max(atlas._metaData.length * 2, needMetaFloats));\n grown.set(atlas._metaData);\n atlas._metaData = grown;\n }\n const m = index * GLYPH_METADATA_FLOATS;\n const meta = atlas._metaData;\n meta[m] = xMin;\n meta[m + 1] = yMin;\n meta[m + 2] = xMax;\n meta[m + 3] = yMax;\n meta[m + 4] = glyphLocX;\n meta[m + 5] = glyphLocY;\n meta[m + 6] = bands._vBandCount - 1;\n meta[m + 7] = bands._hBandCount - 1;\n meta[m + 8] = bandScaleX;\n meta[m + 9] = bandScaleY;\n meta[m + 10] = -xMin * bandScaleX;\n meta[m + 11] = -yMin * bandScaleY;\n\n return { _index: index };\n}\n\n// ─── Internal: spatial-band partitioning ──────────────────────────────────\n\nfunction curveAt(curves: readonly GLQuadCurve[], i: number): GLQuadCurve {\n const c = curves[i];\n if (!c) {\n throw new Error(\"buildGlyphBands: invalid curve index\");\n }\n return c;\n}\n\nfunction buildBandsInternal(g: GLGlyphCurves): GlyphBands {\n const { curves, bounds } = g;\n const numBands = Math.max(1, Math.min(8, Math.floor(curves.length / 2)));\n const { xMin, yMin, xMax, yMax } = bounds;\n const width = xMax - xMin;\n const height = yMax - yMin;\n const bandH = height / numBands;\n const bandW = width / numBands;\n\n const hBands: BandEntry[] = [];\n const vBands: BandEntry[] = [];\n for (let i = 0; i < numBands; i++) {\n hBands.push({ _curveIndices: [] });\n vBands.push({ _curveIndices: [] });\n }\n\n for (let ci = 0; ci < curves.length; ci++) {\n const c = curveAt(curves, ci);\n const cyMin = Math.min(c.p0y, c.p1y, c.p2y);\n const cyMax = Math.max(c.p0y, c.p1y, c.p2y);\n const cxMin = Math.min(c.p0x, c.p1x, c.p2x);\n const cxMax = Math.max(c.p0x, c.p1x, c.p2x);\n if (height > 0) {\n for (let b = 0; b < numBands; b++) {\n const bMinY = yMin + b * bandH;\n const bMaxY = yMin + (b + 1) * bandH;\n if (cyMax >= bMinY && cyMin <= bMaxY) {\n hBands[b]!._curveIndices.push(ci);\n }\n }\n }\n if (width > 0) {\n for (let b = 0; b < numBands; b++) {\n const bMinX = xMin + b * bandW;\n const bMaxX = xMin + (b + 1) * bandW;\n if (cxMax >= bMinX && cxMin <= bMaxX) {\n vBands[b]!._curveIndices.push(ci);\n }\n }\n }\n }\n\n // Sort curves: h-bands by descending max x, v-bands by descending max y (early-exit in shader).\n for (const band of hBands) {\n band._curveIndices.sort((a, b) => {\n const ca = curveAt(curves, a);\n const cb = curveAt(curves, b);\n return Math.max(cb.p0x, cb.p1x, cb.p2x) - Math.max(ca.p0x, ca.p1x, ca.p2x);\n });\n }\n for (const band of vBands) {\n band._curveIndices.sort((a, b) => {\n const ca = curveAt(curves, a);\n const cb = curveAt(curves, b);\n return Math.max(cb.p0y, cb.p1y, cb.p2y) - Math.max(ca.p0y, ca.p1y, ca.p2y);\n });\n }\n\n return { _hBands: hBands, _vBands: vBands, _hBandCount: numBands, _vBandCount: numBands };\n}\n\n/** @internal Get (and memoize) the band partitioning for a glyph's curves. */\nexport function buildGlyphBands(g: GLGlyphCurves): GlyphBands {\n return (g._bands ??= buildBandsInternal(g));\n}\n"]}
@@ -0,0 +1,18 @@
1
+ /** Default LTR + word-wrap + align layout, backed by text-shaper.
2
+ *
3
+ * Public surface: `GLTextLayoutOptions` (the options bag, public) and `layoutText` (the
4
+ * internal implementation; not exported from `src/index.ts`). Callers driving their own
5
+ * layout don't import this module and pay zero bytes for it. */
6
+ /** Options for the default text layout helper, expressed in output pixels with simple LTR word wrapping. */
7
+ export type GLTextLayoutOptions = {
8
+ /** Max line width in pixels before word-wrap. Default: Infinity. */
9
+ readonly maxWidth?: number;
10
+ /** Line-height multiplier. Default: 1.2. */
11
+ readonly lineHeight?: number;
12
+ /** Horizontal alignment. Default: "left". */
13
+ readonly align?: "left" | "center" | "right";
14
+ /** Extra spacing in font units. Default: 0. */
15
+ readonly letterSpacing?: number;
16
+ /** Tab size in spaces. Default: 4. */
17
+ readonly tabSize?: number;
18
+ };
package/text/layout.js ADDED
@@ -0,0 +1,219 @@
1
+ /** Default LTR + word-wrap + align layout, backed by text-shaper.
2
+ *
3
+ * Public surface: `GLTextLayoutOptions` (the options bag, public) and `layoutText` (the
4
+ * internal implementation; not exported from `src/index.ts`). Callers driving their own
5
+ * layout don't import this module and pay zero bytes for it. */
6
+ import { GlyphBuffer, UnicodeBuffer, shapeInto } from "text-shaper";
7
+ /** Shaping scratch buffers, reused across every `layoutText` call.
8
+ *
9
+ * `shape()` pulls from a pool inside text-shaper that is only refilled by `releaseBuffer()`
10
+ * — which the package does not export — so every `shape()` call allocates a fresh
11
+ * `GlyphBuffer` whose object pools start empty, then allocates one `GlyphInfo` and one
12
+ * `GlyphPosition` per codepoint. Because layout shapes one paragraph per call, a block of
13
+ * N paragraphs pays that N times per frame.
14
+ *
15
+ * Holding the buffers here and driving `shapeInto` keeps the pools warm across calls, so
16
+ * after the first block the shaping stage allocates nothing. Retained memory is bounded by
17
+ * the largest chunk ever shaped (see `BATCH_CODEPOINTS`). `layoutText` is synchronous and
18
+ * never re-enters, so a single shared set is safe.
19
+ *
20
+ * Lazily initialised: a module-level `new` would be an import-time side effect and would
21
+ * defeat tree-shaking for callers that drive their own layout. */
22
+ let scratchInput = null;
23
+ let scratchOutput = null;
24
+ /** Per-chunk paragraph end clusters; see the batching notes in `layoutText`. */
25
+ let scratchEnds = null;
26
+ /** Paragraphs shaped per `shapeInto` call once batching is enabled.
27
+ *
28
+ * `shapeInto` carries a fixed per-call cost (buffer reset, codepoint init, script detection,
29
+ * GSUB/GPOS driver setup) that is independent of the text length, so shaping one paragraph at
30
+ * a time makes a block of N paragraphs pay it N times. Batching amortises it, but the benefit
31
+ * saturates quickly: measured against an 840-paragraph grid, going from 840 calls to ~26 (this
32
+ * chunk size) recovers essentially the whole win, while halving the call count again lands
33
+ * inside run-to-run noise. Chunking rather than shaping the whole block keeps the window that
34
+ * any cross-paragraph shaping effect could reach small and bounds retained scratch memory. */
35
+ const BATCH_PARAGRAPHS = 32;
36
+ /** Soft codepoint cap per chunk, so the retained scratch buffers stay bounded when paragraphs
37
+ * are long. Checked before appending, so a chunk may overshoot by its final paragraph. */
38
+ const BATCH_CODEPOINTS = 4096;
39
+ /** Batching is limited to text whose code units all fall below this.
40
+ *
41
+ * Below it lie Latin, Greek, Cyrillic, Armenian, punctuation and symbols — all simple LTR.
42
+ * At and above it begin Hebrew, Arabic, the Indic blocks and the other complex scripts, whose
43
+ * shaping is decided for the buffer as a whole: `shapeInto` samples only the head of the
44
+ * buffer to select complex shaping, and reverses the entire buffer for RTL. Batching those
45
+ * would let one paragraph decide its neighbours' treatment, so they keep one shape call per
46
+ * paragraph.
47
+ *
48
+ * The test is on UTF-16 code units, so surrogates (0xD800-0xDFFF) also fall outside and any
49
+ * text beyond the BMP takes the per-paragraph path too. That is intended — astral sequences
50
+ * carry their own shaping rules — and falling back is always correct, only slower. */
51
+ const SIMPLE_SCRIPT_LIMIT = 0x0590;
52
+ /** @internal Default LTR + word-wrap + align layout. Returns placed glyphs, the layout scale,
53
+ * and the run's pixel-space bounding size. Caller wraps into a `GLGlyphRun` with the appropriate `curveSet`. */
54
+ export function layoutText(font, text, fontSizePx, options) {
55
+ const rawFont = font._font;
56
+ const maxWidth = options?.maxWidth ?? Infinity;
57
+ const lineHeightMult = options?.lineHeight ?? 1.2;
58
+ const textAlign = options?.align ?? "left";
59
+ const letterSpacing = options?.letterSpacing ?? 0;
60
+ const tabSize = options?.tabSize ?? 4;
61
+ const scale = rawFont.scaleForSize(fontSizePx);
62
+ const lineHeightPx = fontSizePx * lineHeightMult;
63
+ const spaceGid = rawFont.glyphId(32);
64
+ const collapsed = text.replace(/\t/g, " ".repeat(tabSize)).replace(/ +/g, " ");
65
+ const paragraphs = collapsed.split("\n");
66
+ const lines = [];
67
+ const lineWidths = [];
68
+ const input = (scratchInput ??= new UnicodeBuffer());
69
+ const output = (scratchOutput ??= new GlyphBuffer());
70
+ const ends = (scratchEnds ??= new Int32Array(BATCH_PARAGRAPHS));
71
+ const paraCount = paragraphs.length;
72
+ let batchSize = 1;
73
+ if (paraCount >= 8) {
74
+ batchSize = BATCH_PARAGRAPHS;
75
+ for (let i = 0; i < collapsed.length; i++) {
76
+ if (collapsed.charCodeAt(i) >= SIMPLE_SCRIPT_LIMIT) {
77
+ batchSize = 1;
78
+ break;
79
+ }
80
+ }
81
+ }
82
+ for (let base = 0; base < paraCount;) {
83
+ // Fill one chunk, separating paragraphs with "\n" so shaping cannot run across them.
84
+ // `addStr` restarts its cluster counter at the `startCluster` argument on every call, so
85
+ // pass the running codepoint count to keep clusters chunk-global. Deriving the range
86
+ // from the buffer's own counter means no offset arithmetic against `text`/`collapsed`
87
+ // (which the collapse and per-paragraph trim have already shifted) and no surrogate-pair
88
+ // handling — `length` counts codepoints, exactly what a cluster indexes.
89
+ input.clear();
90
+ let count = 0;
91
+ while (base + count < paraCount && count < batchSize && (count === 0 || input.length < BATCH_CODEPOINTS)) {
92
+ if (count > 0) {
93
+ input.addStr("\n", input.length);
94
+ }
95
+ input.addStr(paragraphs[base + count].trim(), input.length);
96
+ ends[count] = input.length;
97
+ count++;
98
+ }
99
+ shapeInto(rawFont, input, output);
100
+ // Read straight off the shaped buffer — the glyphs of this chunk are fully consumed into
101
+ // `lines` before the next chunk overwrites `output`.
102
+ const infos = output.infos;
103
+ const positions = output.positions;
104
+ const shapedCount = infos.length;
105
+ let gi = 0;
106
+ for (let k = 0; k < count; k++) {
107
+ // A paragraph starts one cluster past its predecessor's end (that gap is the
108
+ // separator) and runs to its own end. Clusters are non-decreasing here — the guard
109
+ // above excludes the RTL scripts that would reverse the buffer — so one forward walk
110
+ // partitions the chunk, and separator glyphs land in no paragraph's range.
111
+ const clusterEnd = ends[k];
112
+ const clusterStart = k === 0 ? 0 : ends[k - 1] + 1;
113
+ while (gi < shapedCount && infos[gi].cluster < clusterStart) {
114
+ gi++;
115
+ }
116
+ const paraStart = gi;
117
+ while (gi < shapedCount && infos[gi].cluster < clusterEnd) {
118
+ gi++;
119
+ }
120
+ const paraEnd = gi;
121
+ if (paraStart === paraEnd) {
122
+ lines.push([]);
123
+ lineWidths.push(0);
124
+ continue;
125
+ }
126
+ let currentLine = [];
127
+ let lineCursorX = 0;
128
+ let i = paraStart;
129
+ while (i < paraEnd) {
130
+ // Eat leading spaces (consume into current line — gets trimmed on wrap).
131
+ // `codepoint` is the pre-shaping character and survives GSUB (substitutions
132
+ // rewrite `glyphId` only), so it stays aligned with the glyph even when
133
+ // shaping is not one glyph per character.
134
+ while (i < paraEnd && infos[i].codepoint === 32) {
135
+ const pos = positions[i];
136
+ const xAdvance = pos.xAdvance + letterSpacing;
137
+ currentLine.push({
138
+ _glyphId: infos[i].glyphId,
139
+ _x: lineCursorX,
140
+ _line: lines.length,
141
+ _xAdvance: xAdvance,
142
+ _xOffset: pos.xOffset,
143
+ _yOffset: pos.yOffset,
144
+ });
145
+ lineCursorX += xAdvance * scale;
146
+ i++;
147
+ }
148
+ const wordStart = i;
149
+ let wordWidth = 0;
150
+ while (i < paraEnd && infos[i].codepoint !== 32) {
151
+ wordWidth += (positions[i].xAdvance + letterSpacing) * scale;
152
+ i++;
153
+ }
154
+ const wordEnd = i;
155
+ if (lineCursorX + wordWidth > maxWidth && currentLine.length > 0) {
156
+ while (currentLine.length > 0 && currentLine[currentLine.length - 1]._glyphId === spaceGid) {
157
+ currentLine.pop();
158
+ }
159
+ const last = currentLine[currentLine.length - 1];
160
+ const lw = last ? last._x + last._xAdvance * scale : 0;
161
+ lines.push(currentLine);
162
+ lineWidths.push(lw);
163
+ currentLine = [];
164
+ lineCursorX = 0;
165
+ }
166
+ for (let w = wordStart; w < wordEnd; w++) {
167
+ const pos = positions[w];
168
+ const xAdvance = pos.xAdvance + letterSpacing;
169
+ currentLine.push({
170
+ _glyphId: infos[w].glyphId,
171
+ _x: lineCursorX,
172
+ _line: lines.length,
173
+ _xAdvance: xAdvance,
174
+ _xOffset: pos.xOffset,
175
+ _yOffset: pos.yOffset,
176
+ });
177
+ lineCursorX += xAdvance * scale;
178
+ }
179
+ }
180
+ if (currentLine.length > 0) {
181
+ lines.push(currentLine);
182
+ lineWidths.push(lineCursorX);
183
+ }
184
+ }
185
+ base += count;
186
+ }
187
+ let totalWidth = 0;
188
+ for (const w of lineWidths) {
189
+ if (w > totalWidth) {
190
+ totalWidth = w;
191
+ }
192
+ }
193
+ const totalHeight = lines.length * lineHeightPx;
194
+ const placed = [];
195
+ for (let li = 0; li < lines.length; li++) {
196
+ const line = lines[li];
197
+ const lw = lineWidths[li];
198
+ let alignOffset = 0;
199
+ if (textAlign === "center") {
200
+ alignOffset = (totalWidth - lw) * 0.5;
201
+ }
202
+ else if (textAlign === "right") {
203
+ alignOffset = totalWidth - lw;
204
+ }
205
+ const lineY = -li * lineHeightPx;
206
+ for (const g of line) {
207
+ placed.push({
208
+ glyphId: g._glyphId,
209
+ x: g._x + alignOffset + g._xOffset * scale,
210
+ // Y up in pixel space: line 0 sits at y=0, subsequent lines go negative.
211
+ // Pairs naturally with em-space y-up glyph bounds so 3D scenes with a
212
+ // Y-up camera render text upright with no extra transform.
213
+ y: lineY + g._yOffset * scale,
214
+ });
215
+ }
216
+ }
217
+ return { _glyphs: placed, _pixelsPerFontUnit: scale, _width: totalWidth, _height: totalHeight };
218
+ }
219
+ //# sourceMappingURL=layout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layout.js","sourceRoot":"","sources":["../../src/text/layout.ts"],"names":[],"mappings":"AAAA;;;;iEAIiE;AAEjE,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AA6BpE;;;;;;;;;;;;;;mEAcmE;AACnE,IAAI,YAAY,GAAyB,IAAI,CAAC;AAC9C,IAAI,aAAa,GAAuB,IAAI,CAAC;AAC7C,gFAAgF;AAChF,IAAI,WAAW,GAAsB,IAAI,CAAC;AAE1C;;;;;;;;+FAQ+F;AAC/F,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B;2FAC2F;AAC3F,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAE9B;;;;;;;;;;;uFAWuF;AACvF,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAEnC;iHACiH;AACjH,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,IAAY,EAAE,UAAkB,EAAE,OAA6B;IACpG,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;IAC3B,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,QAAQ,CAAC;IAC/C,MAAM,cAAc,GAAG,OAAO,EAAE,UAAU,IAAI,GAAG,CAAC;IAClD,MAAM,SAAS,GAAG,OAAO,EAAE,KAAK,IAAI,MAAM,CAAC;IAC3C,MAAM,aAAa,GAAG,OAAO,EAAE,aAAa,IAAI,CAAC,CAAC;IAClD,MAAM,OAAO,GAAG,OAAO,EAAE,OAAO,IAAI,CAAC,CAAC;IAEtC,MAAM,KAAK,GAAG,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;IAC/C,MAAM,YAAY,GAAG,UAAU,GAAG,cAAc,CAAC;IACjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;I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AAC,IAAI,IAAI,EAAE,CAAC;YACnB,MAAM,CAAC,IAAI,CAAC;gBACR,OAAO,EAAE,CAAC,CAAC,QAAQ;gBACnB,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,WAAW,GAAG,CAAC,CAAC,QAAQ,GAAG,KAAK;gBAC1C,yEAAyE;gBACzE,sEAAsE;gBACtE,2DAA2D;gBAC3D,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,QAAQ,GAAG,KAAK;aAChC,CAAC,CAAC;QACP,CAAC;IACL,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,kBAAkB,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC;AACpG,CAAC","sourcesContent":["/** Default LTR + word-wrap + align layout, backed by text-shaper.\n *\n * Public surface: `GLTextLayoutOptions` (the options bag, public) and `layoutText` (the\n * internal implementation; not exported from `src/index.ts`). Callers driving their own\n * layout don't import this module and pay zero bytes for it. */\n\nimport { GlyphBuffer, UnicodeBuffer, shapeInto } from \"text-shaper\";\nimport type { GLFont } from \"./font.js\";\nimport type { GLPlacedGlyph } from \"./text-data.js\";\n\n/** Options for the default text layout helper, expressed in output pixels with simple LTR word wrapping. */\nexport type GLTextLayoutOptions = {\n /** Max line width in pixels before word-wrap. Default: Infinity. */\n readonly maxWidth?: number;\n /** Line-height multiplier. Default: 1.2. */\n readonly lineHeight?: number;\n /** Horizontal alignment. Default: \"left\". */\n readonly align?: \"left\" | \"center\" | \"right\";\n /** Extra spacing in font units. Default: 0. */\n readonly letterSpacing?: number;\n /** Tab size in spaces. Default: 4. */\n readonly tabSize?: number;\n};\n\ninterface LayoutGlyph {\n _glyphId: number;\n /** Pixel x at line start (line-relative). */\n _x: number;\n /** Line index — used to bake the Y after alignment. */\n _line: number;\n _xAdvance: number;\n _xOffset: number;\n _yOffset: number;\n}\n\n/** Shaping scratch buffers, reused across every `layoutText` call.\n *\n * `shape()` pulls from a pool inside text-shaper that is only refilled by `releaseBuffer()`\n * — which the package does not export — so every `shape()` call allocates a fresh\n * `GlyphBuffer` whose object pools start empty, then allocates one `GlyphInfo` and one\n * `GlyphPosition` per codepoint. Because layout shapes one paragraph per call, a block of\n * N paragraphs pays that N times per frame.\n *\n * Holding the buffers here and driving `shapeInto` keeps the pools warm across calls, so\n * after the first block the shaping stage allocates nothing. Retained memory is bounded by\n * the largest chunk ever shaped (see `BATCH_CODEPOINTS`). `layoutText` is synchronous and\n * never re-enters, so a single shared set is safe.\n *\n * Lazily initialised: a module-level `new` would be an import-time side effect and would\n * defeat tree-shaking for callers that drive their own layout. */\nlet scratchInput: UnicodeBuffer | null = null;\nlet scratchOutput: GlyphBuffer | null = null;\n/** Per-chunk paragraph end clusters; see the batching notes in `layoutText`. */\nlet scratchEnds: Int32Array | null = null;\n\n/** Paragraphs shaped per `shapeInto` call once batching is enabled.\n *\n * `shapeInto` carries a fixed per-call cost (buffer reset, codepoint init, script detection,\n * GSUB/GPOS driver setup) that is independent of the text length, so shaping one paragraph at\n * a time makes a block of N paragraphs pay it N times. Batching amortises it, but the benefit\n * saturates quickly: measured against an 840-paragraph grid, going from 840 calls to ~26 (this\n * chunk size) recovers essentially the whole win, while halving the call count again lands\n * inside run-to-run noise. Chunking rather than shaping the whole block keeps the window that\n * any cross-paragraph shaping effect could reach small and bounds retained scratch memory. */\nconst BATCH_PARAGRAPHS = 32;\n\n/** Soft codepoint cap per chunk, so the retained scratch buffers stay bounded when paragraphs\n * are long. Checked before appending, so a chunk may overshoot by its final paragraph. */\nconst BATCH_CODEPOINTS = 4096;\n\n/** Batching is limited to text whose code units all fall below this.\n *\n * Below it lie Latin, Greek, Cyrillic, Armenian, punctuation and symbols — all simple LTR.\n * At and above it begin Hebrew, Arabic, the Indic blocks and the other complex scripts, whose\n * shaping is decided for the buffer as a whole: `shapeInto` samples only the head of the\n * buffer to select complex shaping, and reverses the entire buffer for RTL. Batching those\n * would let one paragraph decide its neighbours' treatment, so they keep one shape call per\n * paragraph.\n *\n * The test is on UTF-16 code units, so surrogates (0xD800-0xDFFF) also fall outside and any\n * text beyond the BMP takes the per-paragraph path too. That is intended — astral sequences\n * carry their own shaping rules — and falling back is always correct, only slower. */\nconst SIMPLE_SCRIPT_LIMIT = 0x0590;\n\n/** @internal Default LTR + word-wrap + align layout. Returns placed glyphs, the layout scale,\n * and the run's pixel-space bounding size. Caller wraps into a `GLGlyphRun` with the appropriate `curveSet`. */\nexport function layoutText(font: GLFont, text: string, fontSizePx: number, options?: GLTextLayoutOptions) {\n const rawFont = font._font;\n const maxWidth = options?.maxWidth ?? Infinity;\n const lineHeightMult = options?.lineHeight ?? 1.2;\n const textAlign = options?.align ?? \"left\";\n const letterSpacing = options?.letterSpacing ?? 0;\n const tabSize = options?.tabSize ?? 4;\n\n const scale = rawFont.scaleForSize(fontSizePx);\n const lineHeightPx = fontSizePx * lineHeightMult;\n const spaceGid = rawFont.glyphId(32);\n\n const collapsed = text.replace(/\\t/g, \" \".repeat(tabSize)).replace(/ +/g, \" \");\n const paragraphs = collapsed.split(\"\\n\");\n\n const lines: LayoutGlyph[][] = [];\n const lineWidths: number[] = [];\n\n const input = (scratchInput ??= new UnicodeBuffer());\n const output = (scratchOutput ??= new GlyphBuffer());\n const ends = (scratchEnds ??= new Int32Array(BATCH_PARAGRAPHS));\n\n const paraCount = paragraphs.length;\n let batchSize = 1;\n if (paraCount >= 8) {\n batchSize = BATCH_PARAGRAPHS;\n for (let i = 0; i < collapsed.length; i++) {\n if (collapsed.charCodeAt(i) >= SIMPLE_SCRIPT_LIMIT) {\n batchSize = 1;\n break;\n }\n }\n }\n\n for (let base = 0; base < paraCount;) {\n // Fill one chunk, separating paragraphs with \"\\n\" so shaping cannot run across them.\n // `addStr` restarts its cluster counter at the `startCluster` argument on every call, so\n // pass the running codepoint count to keep clusters chunk-global. Deriving the range\n // from the buffer's own counter means no offset arithmetic against `text`/`collapsed`\n // (which the collapse and per-paragraph trim have already shifted) and no surrogate-pair\n // handling — `length` counts codepoints, exactly what a cluster indexes.\n input.clear();\n let count = 0;\n while (base + count < paraCount && count < batchSize && (count === 0 || input.length < BATCH_CODEPOINTS)) {\n if (count > 0) {\n input.addStr(\"\\n\", input.length);\n }\n input.addStr(paragraphs[base + count]!.trim(), input.length);\n ends[count] = input.length;\n count++;\n }\n shapeInto(rawFont, input, output);\n\n // Read straight off the shaped buffer — the glyphs of this chunk are fully consumed into\n // `lines` before the next chunk overwrites `output`.\n const infos = output.infos;\n const positions = output.positions;\n const shapedCount = infos.length;\n\n let gi = 0;\n for (let k = 0; k < count; k++) {\n // A paragraph starts one cluster past its predecessor's end (that gap is the\n // separator) and runs to its own end. Clusters are non-decreasing here — the guard\n // above excludes the RTL scripts that would reverse the buffer — so one forward walk\n // partitions the chunk, and separator glyphs land in no paragraph's range.\n const clusterEnd = ends[k]!;\n const clusterStart = k === 0 ? 0 : ends[k - 1]! + 1;\n while (gi < shapedCount && infos[gi]!.cluster < clusterStart) {\n gi++;\n }\n const paraStart = gi;\n while (gi < shapedCount && infos[gi]!.cluster < clusterEnd) {\n gi++;\n }\n const paraEnd = gi;\n if (paraStart === paraEnd) {\n lines.push([]);\n lineWidths.push(0);\n continue;\n }\n\n let currentLine: LayoutGlyph[] = [];\n let lineCursorX = 0;\n let i = paraStart;\n while (i < paraEnd) {\n // Eat leading spaces (consume into current line — gets trimmed on wrap).\n // `codepoint` is the pre-shaping character and survives GSUB (substitutions\n // rewrite `glyphId` only), so it stays aligned with the glyph even when\n // shaping is not one glyph per character.\n while (i < paraEnd && infos[i]!.codepoint === 32) {\n const pos = positions[i]!;\n const xAdvance = pos.xAdvance + letterSpacing;\n currentLine.push({\n _glyphId: infos[i]!.glyphId,\n _x: lineCursorX,\n _line: lines.length,\n _xAdvance: xAdvance,\n _xOffset: pos.xOffset,\n _yOffset: pos.yOffset,\n });\n lineCursorX += xAdvance * scale;\n i++;\n }\n const wordStart = i;\n let wordWidth = 0;\n while (i < paraEnd && infos[i]!.codepoint !== 32) {\n wordWidth += (positions[i]!.xAdvance + letterSpacing) * scale;\n i++;\n }\n const wordEnd = i;\n if (lineCursorX + wordWidth > maxWidth && currentLine.length > 0) {\n while (currentLine.length > 0 && currentLine[currentLine.length - 1]!._glyphId === spaceGid) {\n currentLine.pop();\n }\n const last = currentLine[currentLine.length - 1];\n const lw = last ? last._x + last._xAdvance * scale : 0;\n lines.push(currentLine);\n lineWidths.push(lw);\n currentLine = [];\n lineCursorX = 0;\n }\n for (let w = wordStart; w < wordEnd; w++) {\n const pos = positions[w]!;\n const xAdvance = pos.xAdvance + letterSpacing;\n currentLine.push({\n _glyphId: infos[w]!.glyphId,\n _x: lineCursorX,\n _line: lines.length,\n _xAdvance: xAdvance,\n _xOffset: pos.xOffset,\n _yOffset: pos.yOffset,\n });\n lineCursorX += xAdvance * scale;\n }\n }\n if (currentLine.length > 0) {\n lines.push(currentLine);\n lineWidths.push(lineCursorX);\n }\n }\n base += count;\n }\n\n let totalWidth = 0;\n for (const w of lineWidths) {\n if (w > totalWidth) {\n totalWidth = w;\n }\n }\n const totalHeight = lines.length * lineHeightPx;\n\n const placed: GLPlacedGlyph[] = [];\n for (let li = 0; li < lines.length; li++) {\n const line = lines[li]!;\n const lw = lineWidths[li]!;\n let alignOffset = 0;\n if (textAlign === \"center\") {\n alignOffset = (totalWidth - lw) * 0.5;\n } else if (textAlign === \"right\") {\n alignOffset = totalWidth - lw;\n }\n const lineY = -li * lineHeightPx;\n for (const g of line) {\n placed.push({\n glyphId: g._glyphId,\n x: g._x + alignOffset + g._xOffset * scale,\n // Y up in pixel space: line 0 sits at y=0, subsequent lines go negative.\n // Pairs naturally with em-space y-up glyph bounds so 3D scenes with a\n // Y-up camera render text upright with no extra transform.\n y: lineY + g._yOffset * scale,\n });\n }\n }\n\n return { _glyphs: placed, _pixelsPerFontUnit: scale, _width: totalWidth, _height: totalHeight };\n}\n"]}