authoravatarclover caruso<git@paperclover.net>2026-12-01 14:46:24-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 14:56:10-08:00
logde5c6ae72b3c41dc1fa498b17a13ad09d826fd45
treef602fe60e2e1a0600f13606c54b837915dc415d6
parent77ddd505408d3e7449f36f8c597a005212f5c4cd
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): optimize TextPlus font/glyph caching and core WGSL compute shaders


4 files changed, 1009 insertions(+), 328 deletions(-)

crates/engine/src/shaders/composite.wgsl+118-60
......@@ -8,50 +8,58 @@
88fn bg_op(@builtin(global_invocation_id) gid: vec3<u32>) {
99 let dims = textureDimensions(dst_tex);
1010 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
11 let fu = pix_to_fu(gid.xy, dims);
1211 let kind = i32(u.p[4].x + 0.5);
13 let has_lut = u.p[4].y > 0.5;
12 let has_mask = u.p[5].z;
13 if (kind == 0 && has_mask < 0.5) {
14 store_dst(vec2<i32>(gid.xy), u.p[0]);
15 return;
16 }
1417 var col = u.p[0];
15 if (kind == 1) {
16 col = mix(u.p[0], u.p[1], fu.x);
17 } else if (kind == 2) {
18 col = mix(u.p[2], u.p[0], fu.y);
19 } else if (kind == 3) {
20 let top = mix(u.p[0], u.p[1], fu.x);
21 let bot = mix(u.p[2], u.p[3], fu.x);
22 col = mix(bot, top, fu.y);
23 } else if (kind >= 4) {
24 let fdims = vec2<f32>(dims);
25 let p_px = fu * fdims;
26 let s_px = u.p[4].zw * fdims;
27 let e_px = u.p[5].xy * fdims;
28 let d_px = e_px - s_px;
29 var t = 0.0;
30 if (kind == 5) {
31 let r = max(length(d_px), 1e-5);
32 t = clamp(length(p_px - s_px) / r, 0.0, 1.0);
33 } else if (kind == 6) {
34 let rel = p_px - s_px;
35 let a_p = select(0.0, atan2(rel.y, rel.x), dot(rel, rel) > 1e-12);
36 let a_d = select(0.0, atan2(d_px.y, d_px.x), dot(d_px, d_px) > 1e-12);
37 t = fract((a_p - a_d) / 6.28318530718);
38 } else if (kind == 7) {
39 let len2 = max(dot(d_px, d_px), 1e-6);
40 t = clamp(abs(dot(p_px - s_px, d_px) / len2), 0.0, 1.0);
41 } else {
42 let len2 = max(dot(d_px, d_px), 1e-6);
43 t = clamp(dot(p_px - s_px, d_px) / len2, 0.0, 1.0);
44 }
45 if (has_lut) {
46 let lut_w = max(f32(textureDimensions(src_b).x), 1.0);
47 let lut_u = (0.5 + t * (lut_w - 1.0)) / lut_w;
48 col = textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u, 0.5), 0.0);
18 if (kind != 0) {
19 let fu = pix_to_fu(gid.xy, dims);
20 let has_lut = u.p[4].y > 0.5;
21 if (kind == 1) {
22 col = mix(u.p[0], u.p[1], fu.x);
23 } else if (kind == 2) {
24 col = mix(u.p[2], u.p[0], fu.y);
25 } else if (kind == 3) {
26 let top = mix(u.p[0], u.p[1], fu.x);
27 let bot = mix(u.p[2], u.p[3], fu.x);
28 col = mix(bot, top, fu.y);
4929 } else {
50 col = mix(u.p[0], u.p[1], t);
30 let fdims = vec2<f32>(dims);
31 let p_px = fu * fdims;
32 let s_px = u.p[4].zw * fdims;
33 let e_px = u.p[5].xy * fdims;
34 let d_px = e_px - s_px;
35 var t = 0.0;
36 if (kind == 5) {
37 let r = max(length(d_px), 1e-5);
38 t = clamp(length(p_px - s_px) / r, 0.0, 1.0);
39 } else if (kind == 6) {
40 let rel = p_px - s_px;
41 let a_p = select(0.0, atan2(rel.y, rel.x), dot(rel, rel) > 1e-12);
42 let a_d = select(0.0, atan2(d_px.y, d_px.x), dot(d_px, d_px) > 1e-12);
43 t = fract((a_p - a_d) / 6.28318530718);
44 } else if (kind == 7) {
45 let len2 = max(dot(d_px, d_px), 1e-6);
46 t = clamp(abs(dot(p_px - s_px, d_px) / len2), 0.0, 1.0);
47 } else {
48 let len2 = max(dot(d_px, d_px), 1e-6);
49 t = clamp(dot(p_px - s_px, d_px) / len2, 0.0, 1.0);
50 }
51 if (has_lut) {
52 let lut_w = max(f32(textureDimensions(src_b).x), 1.0);
53 let lut_u = (0.5 + t * (lut_w - 1.0)) / lut_w;
54 col = textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u, 0.5), 0.0);
55 } else {
56 col = mix(u.p[0], u.p[1], t);
57 }
5158 }
5259 }
53 let m = read_mask(gid.xy, dims, u.p[5].z, u.p[5].w);
54 col = col * m;
60 if (has_mask >= 0.5) {
61 col = col * read_mask(gid.xy, dims, has_mask, u.p[5].w);
62 }
5563 store_dst(vec2<i32>(gid.xy), col);
5664}
5765
......@@ -257,23 +265,53 @@ fn merge_sample_fg(tex: texture_2d<f32>, fu: vec2<f32>, edges: i32, dod: vec4<f3
257265 uv = fu_to_uv(fu);
258266 }
259267 let inv_s = clamp(1.0 / max(size, 0.1), 1.0, 4.0);
268 let inv_scale = 1.0 / inv_s;
260269 let sx_c = uv.x * tdims.x - 0.5;
261270 let sy_c = uv.y * tdims.y - 0.5;
262271 let ixc = i32(floor(sx_c));
263272 let iyc = i32(floor(sy_c));
264273 let rad = i32(ceil(2.0 * inv_s));
274 let x0 = ixc - rad;
275 let x1 = ixc + rad + 1;
276 let y0 = iyc - rad;
277 let y1 = iyc + rad + 1;
278 if (edges == 0 && (x1 < 0 || x0 >= itdims.x || y1 < 0 || y0 >= itdims.y)) {
279 return vec4<f32>(0.0);
280 }
281 // Precompute separable 1D horizontal weights once (`rad <= 8`, so at most 18 taps).
282 var wx_arr: array<f32, 18>;
283 let x_count = x1 - x0 + 1;
284 for (var k = 0; k < x_count; k = k + 1) {
285 wx_arr[k] = merge_bspline_w((f32(x0 + k) - sx_c) * inv_scale);
286 }
287 let interior = x0 >= 0 && x1 < itdims.x && y0 >= 0 && y1 < itdims.y;
265288 var acc = vec4<f32>(0.0);
266289 var wsum = 0.0;
267 for (var iy = iyc - rad; iy <= iyc + rad + 1; iy = iy + 1) {
268 let wy = merge_bspline_w((f32(iy) - sy_c) / inv_s);
269 if (wy <= 0.0) { continue; }
270 for (var ix = ixc - rad; ix <= ixc + rad + 1; ix = ix + 1) {
271 let wx = merge_bspline_w((f32(ix) - sx_c) / inv_s);
272 let w = wx * wy;
273 if (w <= 0.0) { continue; }
274 let s = merge_fetch_edges(tex, ix, iy, itdims, edges);
275 wsum = wsum + w;
276 acc = acc + s * w;
290 if (interior) {
291 for (var iy = y0; iy <= y1; iy = iy + 1) {
292 let wy = merge_bspline_w((f32(iy) - sy_c) * inv_scale);
293 if (wy <= 0.0) { continue; }
294 for (var k = 0; k < x_count; k = k + 1) {
295 let wx = wx_arr[k];
296 let w = wx * wy;
297 if (w <= 0.0) { continue; }
298 let s = textureLoad(tex, vec2<i32>(x0 + k, iy), 0);
299 wsum = wsum + w;
300 acc = acc + s * w;
301 }
302 }
303 } else {
304 for (var iy = y0; iy <= y1; iy = iy + 1) {
305 let wy = merge_bspline_w((f32(iy) - sy_c) * inv_scale);
306 if (wy <= 0.0) { continue; }
307 for (var k = 0; k < x_count; k = k + 1) {
308 let wx = wx_arr[k];
309 let w = wx * wy;
310 if (w <= 0.0) { continue; }
311 let s = merge_fetch_edges(tex, x0 + k, iy, itdims, edges);
312 wsum = wsum + w;
313 acc = acc + s * w;
314 }
277315 }
278316 }
279317 if (wsum > 1e-6) {
......@@ -298,6 +336,14 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
298336 if (bg_coord.x >= 0 && bg_coord.y >= 0 && bg_coord.x < bg_tex_dims.x && bg_coord.y < bg_tex_dims.y) {
299337 bg = textureLoad(src_a, bg_coord, 0);
300338 }
339
340 let blend = u.p[1].x;
341 let mbm = u.p[7].x > 0.5;
342 if (blend <= 0.0 && !mbm) {
343 store_dst(vec2<i32>(gid.xy), bg);
344 return;
345 }
346
301347 // If BG has expanded DoD, map output texel into logical BG canvas Fusion UV!
302348 let canvas_px = select(
303349 vec2<f32>(gid.xy) + vec2<f32>(0.5),
......@@ -309,30 +355,42 @@ fn merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
309355 let center = u.p[0].xy;
310356 let size = max(u.p[0].z, 1e-5);
311357 let angle = u.p[0].w;
312 let blend = u.p[1].x;
313358 let gain = clamp(u.p[1].y, 0.0, 1.0);
314359 let mode = i32(u.p[1].z + 0.5);
315360 let edges = i32(u.p[1].w + 0.5);
316361 let nearest = u.p[2].z > 0.5;
362 let op = i32(u.p[2].w + 0.5); // 0=Over, 1=Under, 2=In, 3=HeldOut, 4=Atop, 5=XOr
363 let has_mask = u.p[3].x;
364 let burn_in = u.p[6].x;
365 let sub_add = u.p[6].y;
317366
318367 // Map output pixel in Fusion pixel space relative to Center into FG pixel space.
319368 let delta_px = (fu - center) * bg_dims;
320 let c = cos(angle);
321 let s = sin(angle);
322 // Fusion Angle rotates CCW in Y-up, so inverse rotates CW:
323 let rot_px = vec2<f32>(delta_px.x * c + delta_px.y * s, -delta_px.x * s + delta_px.y * c) / size;
369 var rot_px: vec2<f32>;
370 if (abs(angle) < 1e-6) {
371 rot_px = delta_px / size;
372 } else {
373 let c = cos(angle);
374 let s = sin(angle);
375 // Fusion Angle rotates CCW in Y-up, so inverse rotates CW:
376 rot_px = vec2<f32>(delta_px.x * c + delta_px.y * s, -delta_px.x * s + delta_px.y * c) / size;
377 }
324378 var fg_fu = rot_px / fg_dims + vec2<f32>(0.5);
325379 if (u.p[2].x > 0.5) { fg_fu.x = 1.0 - fg_fu.x; }
326380 if (u.p[2].y > 0.5) { fg_fu.y = 1.0 - fg_fu.y; }
327381
328382 let fg = merge_sample_fg(src_b, fg_fu, edges, u.p[4], nearest, size);
329 let mask = read_mask_uv(canvas_px / bg_dims, u.p[3].x, u.p[3].y);
330 let mbm = u.p[7].x > 0.5;
331 let eff_blend = select(clamp(blend * mask, 0.0, 1.0), clamp(blend, 0.0, 1.0), mbm);
332 let op = i32(u.p[2].w + 0.5); // 0=Over, 1=Under, 2=In, 3=HeldOut, 4=Atop, 5=XOr
333383
334 let burn_in = u.p[6].x;
335 let sub_add = u.p[6].y;
384 // Fast path for the common Normal + Over + Gain=1.0 + no mask + Blend=1.0 case.
385 if (mode == 0 && op == 0 && gain >= 0.9999 && has_mask < 0.5 && blend >= 0.9999 && !mbm && burn_in == 0.0) {
386 let fg_rgb = select(fg.rgb * mix(fg.a, 1.0, sub_add), fg.rgb, sub_add >= 0.9999);
387 let out_col = vec4<f32>(fg_rgb + bg.rgb * (1.0 - fg.a), fg.a + bg.a * (1.0 - fg.a));
388 store_dst(vec2<i32>(gid.xy), out_col);
389 return;
390 }
391
392 let mask = read_mask_uv(canvas_px / bg_dims, has_mask, u.p[3].y);
393 let eff_blend = select(clamp(blend * mask, 0.0, 1.0), clamp(blend, 0.0, 1.0), mbm);
336394
337395 var out_col: vec4<f32>;
338396 if (mode == 0) {
crates/engine/src/shaders/keyers_gen.wgsl+37-24
......@@ -70,7 +70,7 @@ fn luma_key_op(@builtin(global_invocation_id) gid: vec3<u32>) {
7070// p[3] = color1 RGBA, p[4] = color2 RGBA (used directly in Two Color mode without clamping `val`)
7171// src_b = 256x1 straight-alpha color LUT indexed by the noise value in Gradient mode
7272// ============================================================================
73var<private> PERM: array<u32, 256> = array<u32, 256>(
73const PERM: array<u32, 256> = array<u32, 256>(
7474 151u, 160u, 137u, 91u, 90u, 15u, 131u, 13u, 201u, 95u, 96u, 53u, 194u, 233u, 7u, 225u,
7575 140u, 36u, 103u, 30u, 69u, 142u, 8u, 99u, 37u, 240u, 21u, 10u, 23u, 190u, 6u, 148u,
7676 247u, 120u, 234u, 75u, 0u, 26u, 197u, 62u, 94u, 252u, 219u, 203u, 117u, 35u, 11u, 32u,
......@@ -99,8 +99,8 @@ const GRAD16: array<vec3<f32>, 16> = array<vec3<f32>, 16>(
9999fn simplex_corner(ijk: vec3<i32>, d: vec3<f32>) -> f32 {
100100 let t = SIMPLEX_RADIUS2 - dot(d, d);
101101 if (t <= 0.0) { return 0.0; }
102 let c = ijk & vec3<i32>(255);
103 let h = PERM[(u32(c.z) + PERM[(u32(c.y) + PERM[u32(c.x)]) & 255u]) & 255u] & 15u;
102 let c = vec3<u32>(ijk & vec3<i32>(255));
103 let h = PERM[(c.z + PERM[(c.y + PERM[c.x]) & 255u]) & 255u] & 15u;
104104 let t2 = t * t;
105105 return t2 * t2 * dot(GRAD16[h], d);
106106}
......@@ -108,9 +108,9 @@ fn simplex_corner(ijk: vec3<i32>, d: vec3<f32>) -> f32 {
108108// Fusion's lattice: Gustavson-style 3D simplex noise with kernel (0.5196 - r^2)^4 and a 16-entry
109109// gradient table, recovered from Float32 probes (residual 2e-7).
110110fn simplex3d(p: vec3<f32>) -> f32 {
111 let cell = floor(p + (p.x + p.y + p.z) / 3.0);
111 let cell = floor(p + (p.x + p.y + p.z) * (1.0 / 3.0));
112112 let ijk = vec3<i32>(cell);
113 let d0 = p - (cell - (cell.x + cell.y + cell.z) / 6.0);
113 let d0 = p - (cell - (cell.x + cell.y + cell.z) * (1.0 / 6.0));
114114 var a = vec3<i32>(0);
115115 var b = vec3<i32>(0);
116116 if (d0.x >= d0.y) {
......@@ -127,7 +127,7 @@ fn simplex3d(p: vec3<f32>) -> f32 {
127127 simplex_corner(ijk, d0)
128128 + simplex_corner(ijk + a, d0 - vec3<f32>(a) + g)
129129 + simplex_corner(ijk + b, d0 - vec3<f32>(b) + 2.0 * g)
130 + simplex_corner(ijk + vec3<i32>(1), d0 - 1.0 + 3.0 * g)
130 + simplex_corner(ijk + vec3<i32>(1), d0 - 0.5)
131131 );
132132}
133133
......@@ -153,25 +153,38 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {
153153 let angle = u.p[2].y;
154154 let gradient = u.p[2].w > 1.5;
155155
156 // Frame-width units, y up, measured from the pixel corner.
157 let w = f32(dims.x);
158 let h = f32(dims.y);
159 let rel = vec2<f32>(f32(gid.x) / w, (h - 1.0 - f32(gid.y)) / w) - center * vec2<f32>(1.0, h / w);
160 let ca = cos(angle);
161 let sa = sin(angle);
162 let p = vec2<f32>(rel.x * ca + rel.y * sa, rel.y * ca - rel.x * sa) * scale;
163
164 let octaves = i32(ceil(detail));
165156 var sum = 0.0;
166 var amp = 1.0;
167 var freq = 1.0;
168 for (var i = 0; i < octaves; i = i + 1) {
169 let weight = amp * clamp(detail - f32(i), 0.0, 1.0);
170 let off = OCTAVE_OFFSET * f32(i);
171 let n = simplex3d(vec3<f32>(p * freq + off, seethe * freq + off));
172 sum = sum + weight * select(n, 2.0 * abs(n), disc);
173 freq = freq * 2.0;
174 amp = amp * 0.5;
157 if (abs(contrast) > 1e-6 && detail > 0.0) {
158 // Frame-width units, y up, measured from the pixel corner.
159 let w = f32(dims.x);
160 let h = f32(dims.y);
161 let inv_w = 1.0 / w;
162 let rel = vec2<f32>(f32(gid.x) * inv_w, (h - 1.0 - f32(gid.y)) * inv_w) - center * vec2<f32>(1.0, h * inv_w);
163 var p: vec2<f32>;
164 if (abs(angle) < 1e-6) {
165 p = rel * scale;
166 } else {
167 let ca = cos(angle);
168 let sa = sin(angle);
169 p = vec2<f32>(rel.x * ca + rel.y * sa, rel.y * ca - rel.x * sa) * scale;
170 }
171
172 let full_octaves = i32(floor(detail));
173 let frac_w = detail - f32(full_octaves);
174 var amp = select(1.0, 2.0, disc);
175 var cur = vec3<f32>(p, seethe);
176 var off = 0.0;
177 for (var i = 0; i < full_octaves; i = i + 1) {
178 let n = simplex3d(cur + vec3<f32>(off));
179 sum = sum + amp * select(n, abs(n), disc);
180 cur = cur * 2.0;
181 off = off + OCTAVE_OFFSET;
182 amp = amp * 0.5;
183 }
184 if (frac_w > 0.0) {
185 let n = simplex3d(cur + vec3<f32>(off));
186 sum = sum + (amp * frac_w) * select(n, abs(n), disc);
187 }
175188 }
176189
177190 var val = select(0.5 + sum, sum, disc);
crates/engine/src/shaders/transform.wgsl+97-46
......@@ -21,6 +21,15 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
2121 has_dst_dod,
2222 );
2323
24 let nearest = u.p[3].y > 0.5;
25 let blend = u.p[2].z;
26 let has_mask = u.p[2].w;
27 let mbm = u.p[3].z > 0.5;
28 if (blend <= 0.0 && !mbm) {
29 store_dst(vec2<i32>(gid.xy), sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest));
30 return;
31 }
32
2433 let center = u.p[0].xy;
2534 let pivot = u.p[0].zw;
2635 let sx = max(u.p[1].x, 1e-5);
......@@ -30,8 +39,6 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
3039
3140 // Forward in Fusion: p' = R(angle) * S(sx, sy) * (p - pivot) + pivot + (center - 0.5)
3241 let shift = center - vec2<f32>(0.5);
33 let c = cos(angle);
34 let s = sin(angle);
3542 var src_fu: vec2<f32>;
3643 if (u.p[3].w > 0.5) {
3744 // InvertTransform samples through the forward map instead of its inverse (flips apply first).
......@@ -39,31 +46,48 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
3946 if (u.p[2].x > 0.5) { p.x = 1.0 - p.x; }
4047 if (u.p[2].y > 0.5) { p.y = 1.0 - p.y; }
4148 let scaled = (p - pivot) * fdims * vec2<f32>(sx, sy);
42 let rot = vec2<f32>(scaled.x * c - scaled.y * s, scaled.x * s + scaled.y * c);
43 src_fu = rot / fdims + pivot + shift;
49 if (abs(angle) < 1e-6) {
50 src_fu = scaled / fdims + pivot + shift;
51 } else {
52 let c = cos(angle);
53 let s = sin(angle);
54 let rot = vec2<f32>(scaled.x * c - scaled.y * s, scaled.x * s + scaled.y * c);
55 src_fu = rot / fdims + pivot + shift;
56 }
4457 } else {
45 let rel_px = (fu - pivot - shift) * fdims;
46 let unrot = vec2<f32>(rel_px.x * c + rel_px.y * s, -rel_px.x * s + rel_px.y * c);
47 src_fu = vec2<f32>(unrot.x / sx, unrot.y / sy) / fdims + pivot;
58 let rel = fu - pivot - shift;
59 if (abs(angle) < 1e-6) {
60 src_fu = rel / vec2<f32>(sx, sy) + pivot;
61 } else {
62 let c = cos(angle);
63 let s = sin(angle);
64 let rel_px = rel * fdims;
65 let unrot = vec2<f32>(rel_px.x * c + rel_px.y * s, -rel_px.x * s + rel_px.y * c);
66 src_fu = vec2<f32>(unrot.x / sx, unrot.y / sy) / fdims + pivot;
67 }
4868 if (u.p[2].x > 0.5) { src_fu.x = 1.0 - src_fu.x; }
4969 if (u.p[2].y > 0.5) { src_fu.y = 1.0 - src_fu.y; }
5070 }
5171
52 let nearest = u.p[3].y > 0.5;
53 let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest);
5472 let moved = sample_dod_edges_mode(src_a, src_fu, edges, u.p[4], nearest);
55 let raw_mask = select(
56 read_mask(gid.xy, dims, u.p[2].w, u.p[3].x),
57 read_mask_uv(fu_to_uv(fu), u.p[2].w, u.p[3].x),
58 has_dst_dod,
59 );
60 let mbm = u.p[3].z > 0.5;
61 let m = select(raw_mask, 1.0, mbm) * u.p[2].z;
73 let skip_mask = u.p[6] > vec4<f32>(0.5);
74 if (blend >= 1.0 && has_mask < 0.5 && !mbm && !any(skip_mask)) {
75 store_dst(vec2<i32>(gid.xy), moved);
76 return;
77 }
78
79 let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest);
80 var raw_mask = 1.0;
81 if (has_mask >= 0.5) {
82 let mask_uv = select((vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims), fu_to_uv(fu), has_dst_dod);
83 raw_mask = read_mask_uv(mask_uv, has_mask, u.p[3].x);
84 }
85 let m = select(raw_mask, 1.0, mbm) * blend;
6286 var out_col = mix(orig, moved, clamp(m, 0.0, 1.0));
6387 if (mbm) {
6488 out_col = out_col * raw_mask;
6589 }
66 store_dst(vec2<i32>(gid.xy), select(out_col, orig, u.p[6] > vec4<f32>(0.5)));
90 store_dst(vec2<i32>(gid.xy), select(out_col, orig, skip_mask));
6791}
6892// MultiplyByMask scales the warped result by mask * blend instead of mixing against the source.
6993fn mask_mix(orig: vec4<f32>, warped: vec4<f32>, raw_mask: f32, blend: f32, mbm: bool) -> vec4<f32> {
......@@ -112,8 +136,14 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
112136 store_dst(vec2<i32>(gid.xy), textureLoad(src_a, vec2<i32>(gid.xy), 0) + d * (u.p[2].z * m));
113137 return;
114138 }
139 let blend = u.p[1].z;
140 let has_mask = u.p[1].w;
141 let mbm = u.p[4].z > 0.5;
142 if (blend <= 0.0 && !mbm) {
143 store_dst(vec2<i32>(gid.xy), textureLoad(src_a, vec2<i32>(gid.xy), 0));
144 return;
145 }
115146 let kind = i32(u.p[0].x + 0.5);
116 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
117147
118148 var warped: vec4<f32>;
119149 if (kind == 1) {
......@@ -123,11 +153,11 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
123153 let ych = i32(u.p[3].w + 0.5);
124154 let vx = pick_channel(fg, xch);
125155 let vy = pick_channel(fg, ych);
126 let disp = vec2<f32>(
156 let disp_uv = vec2<f32>(
127157 (vx + u.p[0].w) * u.p[0].y,
128 (vy + u.p[1].x) * u.p[0].z,
158 -((vy + u.p[1].x) * u.p[0].z),
129159 );
130 warped = sample_edges(src_a, fu + disp, 2);
160 warped = textureSampleLevel(src_a, samp_lin, clamp(uv + disp_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
131161 } else {
132162 // Radial displace: Fusion shifts radially from Center by -(fu - center) * (luma + offset) * strength * 0.51.
133163 let fg_c = textureSampleLevel(src_b, samp_lin, uv, 0.0);
......@@ -136,21 +166,26 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
136166 let strength = u.p[1].y;
137167 let spread = u.p[2].y;
138168 let center = u.p[3].xy;
139 let dir_c = fu - center;
140 let base_disp = -dir_c * (l_c + offset) * strength * 0.51;
169 let base_disp = -(fu - center) * ((l_c + offset) * (strength * 0.51));
170 let base_uv = vec2<f32>(base_disp.x, -base_disp.y);
141171
142172 if (abs(spread) > 1e-4) {
143173 let sp = spread * 0.02;
144 let sr = sample_edges(src_a, fu + base_disp * (1.0 - sp), 2);
145 let sg = sample_edges(src_a, fu + base_disp, 2);
146 let sb = sample_edges(src_a, fu + base_disp * (1.0 + sp), 2);
174 let sr = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv * (1.0 - sp), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
175 let sg = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
176 let sb = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv * (1.0 + sp), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
147177 warped = vec4<f32>(sr.r, sg.g, sb.b, max(sr.a, max(sg.a, sb.a)));
148178 } else {
149 warped = sample_edges(src_a, fu + base_disp, 2);
179 warped = textureSampleLevel(src_a, samp_lin, clamp(uv + base_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
150180 }
151181 }
152182
153 store_dst(vec2<i32>(gid.xy), mask_mix(orig, warped, read_mask(gid.xy, dims, u.p[1].w, u.p[2].x), u.p[1].z, u.p[4].z > 0.5));
183 if (blend >= 1.0 && has_mask < 0.5 && !mbm) {
184 store_dst(vec2<i32>(gid.xy), warped);
185 return;
186 }
187 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
188 store_dst(vec2<i32>(gid.xy), mask_mix(orig, warped, read_mask(gid.xy, dims, has_mask, u.p[2].x), blend, mbm));
154189}
155190// ============================================================================
156191// 14. Crop / Scale / Copy
......@@ -193,12 +228,20 @@ fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {
193228fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {
194229 let dims = textureDimensions(dst_tex);
195230 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
231 let blend = u.p[3].x;
196232 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
233 if (blend <= 0.0) {
234 store_dst(vec2<i32>(gid.xy), orig);
235 return;
236 }
197237 let aspect = f32(dims.x) / max(f32(dims.y), 1.0);
238 let aspect_v = vec2<f32>(aspect, 1.0);
239 let inv_aspect_v = vec2<f32>(1.0 / aspect, 1.0);
198240 let fu = pix_to_fu(gid.xy, dims);
199241
200242 let center = u.p[0].xy;
201243 let pivot = u.p[0].zw;
244 let piv_off = pivot - vec2<f32>(0.5, 0.5);
202245 let xsize = u.p[1].x;
203246 let ysize = u.p[1].y;
204247 let angle = u.p[1].z;
......@@ -207,16 +250,18 @@ fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {
207250 let normalize = u.p[2].y > 0.5;
208251 let gain = u.p[2].z;
209252 let gamma = max(u.p[2].w, 0.05);
210 let blend = u.p[3].x;
253 let do_gamma = abs(gamma - 1.0) > 1e-3;
211254
212255 var acc = vec4<f32>(0.0);
213256 var grad_sum = vec4<f32>(0.0);
214257 let inv_steps = 1.0 / f32(steps);
215258
216259 let grad_n = f32(textureDimensions(src_b).x);
260 let grad_scale = (grad_n - 1.0) / grad_n;
261 let grad_bias = 0.5 / grad_n;
217262 for (var i = 0; i <= steps; i = i + 1) {
218263 let n = f32(i) * inv_steps;
219 let grad_u = (0.5 + clamp(n, 0.0, 1.0) * (grad_n - 1.0)) / grad_n;
264 let grad_u = grad_bias + clamp(n, 0.0, 1.0) * grad_scale;
220265 let grad = textureSampleLevel(src_b, samp_lin, vec2<f32>(grad_u, 0.5), 0.0);
221266
222267 let cur_c = mix(vec2<f32>(0.5, 0.5), center, n);
......@@ -225,15 +270,20 @@ fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3<u32>) {
225270 let cur_a = angle * n;
226271
227272 // Inverse transform matching Fusion Transform/XfChroma around pivot
228 let rel = (fu - cur_c + (pivot - vec2<f32>(0.5, 0.5))) * vec2<f32>(aspect, 1.0);
229 let ca = cos(cur_a);
230 let sa = sin(cur_a);
231 let rot = vec2<f32>(rel.x * ca + rel.y * sa, -rel.x * sa + rel.y * ca);
273 let rel = (fu - cur_c + piv_off) * aspect_v;
274 var rot: vec2<f32>;
275 if (abs(cur_a) < 1e-6) {
276 rot = rel;
277 } else {
278 let ca = cos(cur_a);
279 let sa = sin(cur_a);
280 rot = vec2<f32>(rel.x * ca + rel.y * sa, -rel.x * sa + rel.y * ca);
281 }
232282 let scaled = rot / vec2<f32>(cur_sx, cur_sy);
233 let src_fu = pivot + scaled / vec2<f32>(aspect, 1.0);
283 let src_fu = pivot + scaled * inv_aspect_v;
234284
235285 var s = sample_dod_edges_mode(src_a, src_fu, 0, u.p[4], false);
236 if (abs(gamma - 1.0) > 1e-3) {
286 if (do_gamma) {
237287 s = vec4<f32>(pow(max(s.rgb, vec3<f32>(0.0)), vec3<f32>(gamma)), s.a);
238288 }
239289 let tinted = s * grad;
......@@ -328,11 +378,12 @@ fn homography_op(@builtin(global_invocation_id) gid: vec3<u32>) {
328378 ),
329379 has_dod,
330380 );
331 let orig = select(
332 textureLoad(src_a, vec2<i32>(gid.xy), 0),
333 sample_edges(src_a, fu, 0),
334 has_dod,
335 );
381 var orig = vec4<f32>(0.0);
382 if (has_dod) {
383 orig = sample_edges(src_a, fu, 0);
384 } else {
385 orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
386 }
336387
337388 var s_fu = vec2<f32>(0.0);
338389 var valid = false;
......@@ -355,11 +406,11 @@ fn homography_op(@builtin(global_invocation_id) gid: vec3<u32>) {
355406 warped.a = 1.0;
356407 }
357408 }
358 let raw_mask = select(
359 read_mask(gid.xy, dims, u.p[2].z, u.p[2].w),
360 read_mask_uv(fu_to_uv(fu), u.p[2].z, u.p[2].w),
361 has_dod,
362 );
409 var raw_mask = 1.0;
410 if (u.p[2].z >= 0.5) {
411 let mask_uv = select((vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims), fu_to_uv(fu), has_dod);
412 raw_mask = read_mask_uv(mask_uv, u.p[2].z, u.p[2].w);
413 }
363414 let res = mask_mix(orig, warped, raw_mask, u.p[2].y, u.p[3].y > 0.5);
364415 let unproc = select(orig, vec4<f32>(0.0), u.p[3].y > 0.5);
365416 store_dst(vec2<i32>(gid.xy), select(res, unproc, u.p[5] > vec4<f32>(0.5)));
crates/engine/src/text_engine.rs+757-198
......@@ -4,7 +4,10 @@
44
55use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag};
66use rustybuzz::{Face, Feature, UnicodeBuffer, Variation};
7use std::collections::{HashMap, HashSet};
7use std::collections::{HashMap, HashSet, VecDeque};
8#[cfg(not(target_arch = "wasm32"))]
9use std::path::PathBuf;
10use std::sync::atomic::{AtomicU64, Ordering};
811use std::sync::{Arc, Mutex, OnceLock, RwLock};
912use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};
1013
......@@ -15,8 +18,11 @@ const FALLBACK_FAMILIES: [&str; 6] =
1518/// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face.
1619const SYNTHETIC_ITALIC: f32 = 0.2126;
1720
21static NEXT_FONT_ID: AtomicU64 = AtomicU64::new(1);
22
1823/// A resolved font file; `face()` parses it on demand.
1924pub struct Font {
25 id: u64,
2026 data: Vec<u8>,
2127 index: u32,
2228 weight: u16,
......@@ -28,15 +34,21 @@ impl Font {
2834 /// system fonts and any fonts registered via [`register_font_bytes`], falling back through
2935 /// [`FALLBACK_FAMILIES`] and finally any installed face.
3036 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {
37 {
38 let cache = font_cache().lock().unwrap();
39 if let Some(hit) = cache.get(&(family.to_owned(), style.to_owned())) {
40 return hit.clone();
41 }
42 }
43 let resolved = {
44 let mut reg = registry().write().unwrap();
45 resolve_lazy(&mut reg, family, style).map(Arc::new)
46 };
3147 let mut cache = font_cache().lock().unwrap();
32 cache
48 let entry = cache
3349 .entry((family.to_owned(), style.to_owned()))
34 .or_insert_with(|| {
35 let db = database().read().unwrap();
36 let aliases = font_aliases().read().unwrap();
37 resolve(&db, &aliases, family, style).map(Arc::new)
38 })
39 .clone()
50 .or_insert_with(|| resolved.clone());
51 entry.clone()
4052 }
4153
4254 pub fn face(&self) -> Face<'_> {
......@@ -48,33 +60,198 @@ impl Font {
4860 }
4961}
5062
63struct FontRegistry {
64 db: fontdb::Database,
65 aliases: HashMap<String, Vec<fontdb::ID>>,
66 #[cfg(not(target_arch = "wasm32"))]
67 system_fonts_loaded: bool,
68 #[cfg(not(target_arch = "wasm32"))]
69 loaded_paths: HashSet<PathBuf>,
70 #[cfg(not(target_arch = "wasm32"))]
71 loaded_families: HashSet<String>,
72 #[cfg(not(target_arch = "wasm32"))]
73 loaded_style_keys: HashSet<(String, String)>,
74}
75
76impl FontRegistry {
77 fn new() -> Self {
78 Self {
79 db: fontdb::Database::new(),
80 aliases: HashMap::new(),
81 #[cfg(not(target_arch = "wasm32"))]
82 system_fonts_loaded: false,
83 #[cfg(not(target_arch = "wasm32"))]
84 loaded_paths: HashSet::new(),
85 #[cfg(not(target_arch = "wasm32"))]
86 loaded_families: HashSet::new(),
87 #[cfg(not(target_arch = "wasm32"))]
88 loaded_style_keys: HashSet::new(),
89 }
90 }
91
92 #[cfg(not(target_arch = "wasm32"))]
93 fn ensure_system_fonts_loaded(&mut self) {
94 if !self.system_fonts_loaded {
95 self.db.load_system_fonts();
96 self.system_fonts_loaded = true;
97 }
98 }
99}
100
51101fn font_cache() -> &'static Mutex<HashMap<(String, String), Option<Arc<Font>>>> {
52102 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();
53103 CACHE.get_or_init(Default::default)
54104}
55105
56fn font_aliases() -> &'static RwLock<HashMap<String, Vec<fontdb::ID>>> {
57 static ALIASES: OnceLock<RwLock<HashMap<String, Vec<fontdb::ID>>>> = OnceLock::new();
58 ALIASES.get_or_init(Default::default)
106fn registry() -> &'static RwLock<FontRegistry> {
107 static REG: OnceLock<RwLock<FontRegistry>> = OnceLock::new();
108 REG.get_or_init(|| RwLock::new(FontRegistry::new()))
109}
110
111#[cfg(not(target_arch = "wasm32"))]
112struct FontFileEntry {
113 path: PathBuf,
114 stem_norm: String,
115}
116
117#[cfg(not(target_arch = "wasm32"))]
118fn norm_alnum(s: &str) -> String {
119 s.chars()
120 .filter(|c| c.is_ascii_alphanumeric())
121 .map(|c| c.to_ascii_lowercase())
122 .collect()
123}
124
125#[cfg(not(target_arch = "wasm32"))]
126fn is_font_extension(path: &std::path::Path) -> bool {
127 path.extension()
128 .and_then(|e| e.to_str())
129 .is_some_and(|ext| {
130 ext.eq_ignore_ascii_case("ttf")
131 || ext.eq_ignore_ascii_case("otf")
132 || ext.eq_ignore_ascii_case("ttc")
133 || ext.eq_ignore_ascii_case("otc")
134 })
59135}
60136
61fn database() -> &'static RwLock<fontdb::Database> {
62 static DB: OnceLock<RwLock<fontdb::Database>> = OnceLock::new();
63 DB.get_or_init(|| {
64 #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
65 let mut db = fontdb::Database::new();
66 #[cfg(not(target_arch = "wasm32"))]
67 db.load_system_fonts();
68 RwLock::new(db)
137#[cfg(not(target_arch = "wasm32"))]
138fn collect_font_dir(dir: &std::path::Path, depth: u8, out: &mut Vec<FontFileEntry>) {
139 let Ok(entries) = std::fs::read_dir(dir) else {
140 return;
141 };
142 for entry in entries.flatten() {
143 let path = entry.path();
144 if path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.')) {
145 continue;
146 }
147 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
148 || (entry.file_type().map(|ft| ft.is_symlink()).unwrap_or(false) && path.is_dir());
149 if is_dir {
150 if depth > 0 {
151 collect_font_dir(&path, depth - 1, out);
152 }
153 } else if is_font_extension(&path) {
154 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
155 let stem_norm = norm_alnum(stem);
156 if !stem_norm.is_empty() {
157 out.push(FontFileEntry { path, stem_norm });
158 }
159 }
160 }
161 }
162}
163
164#[cfg(not(target_arch = "wasm32"))]
165fn system_font_index() -> &'static [FontFileEntry] {
166 static INDEX: OnceLock<Vec<FontFileEntry>> = OnceLock::new();
167 INDEX.get_or_init(|| {
168 let mut out = Vec::with_capacity(768);
169 let mut dirs: Vec<PathBuf> = Vec::new();
170 #[cfg(target_os = "macos")]
171 {
172 dirs.push(PathBuf::from("/System/Library/Fonts"));
173 dirs.push(PathBuf::from("/Library/Fonts"));
174 if let Some(home) = std::env::var_os("HOME") {
175 dirs.push(PathBuf::from(home).join("Library/Fonts"));
176 }
177 }
178 #[cfg(all(unix, not(target_os = "macos")))]
179 {
180 dirs.push(PathBuf::from("/usr/share/fonts"));
181 dirs.push(PathBuf::from("/usr/local/share/fonts"));
182 if let Some(home) = std::env::var_os("HOME") {
183 let h = PathBuf::from(home);
184 dirs.push(h.join(".local/share/fonts"));
185 dirs.push(h.join(".fonts"));
186 }
187 }
188 #[cfg(target_os = "windows")]
189 {
190 if let Some(win) = std::env::var_os("WINDIR") {
191 dirs.push(PathBuf::from(win).join("Fonts"));
192 }
193 if let Some(local) = std::env::var_os("LOCALAPPDATA") {
194 dirs.push(PathBuf::from(local).join("Microsoft/Windows/Fonts"));
195 }
196 }
197 for d in &dirs {
198 collect_font_dir(d, 4, &mut out);
199 }
200 out
69201 })
70202}
71203
204#[cfg(not(target_arch = "wasm32"))]
205fn is_style_suffix(rest: &str) -> bool {
206 const PREFIXES: &[&str] = &[
207 "regular", "bold", "italic", "oblique", "medium", "light", "thin", "black", "heavy",
208 "semi", "demi", "extra", "ultra", "hairline", "book", "roman", "condensed", "narrow",
209 "extended", "variable", "vf", "bd", "bi", "it", "mt", "ps",
210 ];
211 rest.is_empty() || PREFIXES.iter().any(|p| rest.starts_with(p))
212}
213
214#[cfg(not(target_arch = "wasm32"))]
215fn load_style_candidates(reg: &mut FontRegistry, fam_norm: &str, style_key: &str) {
216 if fam_norm.is_empty() || reg.system_fonts_loaded || reg.loaded_families.contains(fam_norm) {
217 return;
218 }
219 let key = (fam_norm.to_owned(), style_key.to_owned());
220 if !reg.loaded_style_keys.insert(key) {
221 return;
222 }
223 let combined_len = fam_norm.len() + style_key.len();
224 for entry in system_font_index() {
225 let exact_match = entry.stem_norm == fam_norm
226 || (entry.stem_norm.len() == combined_len
227 && entry.stem_norm.starts_with(fam_norm)
228 && entry.stem_norm.ends_with(style_key));
229 if exact_match && reg.loaded_paths.insert(entry.path.clone()) {
230 let _ = reg.db.load_font_file(&entry.path);
231 }
232 }
233}
234
235#[cfg(not(target_arch = "wasm32"))]
236fn load_family_candidates(reg: &mut FontRegistry, fam_norm: &str) {
237 if fam_norm.is_empty() || reg.system_fonts_loaded || !reg.loaded_families.insert(fam_norm.to_owned()) {
238 return;
239 }
240 for entry in system_font_index() {
241 if let Some(rest) = entry.stem_norm.strip_prefix(fam_norm) {
242 if is_style_suffix(rest) && reg.loaded_paths.insert(entry.path.clone()) {
243 let _ = reg.db.load_font_file(&entry.path);
244 }
245 }
246 }
247}
248
72249/// Registers font bytes (`.ttf`/`.otf`/`.ttc`) into the global font database at runtime
73250/// (used e.g. on `wasm32` where no OS system fonts are available) and clears the resolution cache.
74251pub fn register_font_bytes(bytes: Vec<u8>) {
75252 {
76 let mut db = database().write().unwrap();
77 db.load_font_data(bytes);
253 let mut reg = registry().write().unwrap();
254 reg.db.load_font_data(bytes);
78255 }
79256 font_cache().lock().unwrap().clear();
80257}
......@@ -83,15 +260,13 @@ pub fn register_font_bytes(bytes: Vec<u8>) {
83260/// and clears the resolution cache.
84261pub fn register_font_bytes_with_name(family: &str, bytes: Vec<u8>) {
85262 {
86 let mut db = database().write().unwrap();
87 let before: HashSet<fontdb::ID> = db.faces().map(|f| f.id).collect();
88 db.load_font_data(bytes);
263 let mut reg = registry().write().unwrap();
264 let before: HashSet<fontdb::ID> = reg.db.faces().map(|f| f.id).collect();
265 reg.db.load_font_data(bytes);
89266 if !family.is_empty() {
90 let added: Vec<fontdb::ID> = db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect();
267 let added: Vec<fontdb::ID> = reg.db.faces().filter(|f| !before.contains(&f.id)).map(|f| f.id).collect();
91268 if !added.is_empty() {
92 font_aliases()
93 .write()
94 .unwrap()
269 reg.aliases
95270 .entry(family.to_ascii_lowercase())
96271 .or_default()
97272 .extend(added);
......@@ -142,25 +317,102 @@ fn metric_alias(family: &str) -> Option<&'static str> {
142317 }
143318}
144319
145fn resolve(
320#[cfg(not(target_arch = "wasm32"))]
321fn is_exact_face_match(
146322 db: &fontdb::Database,
147 aliases: &HashMap<String, Vec<fontdb::ID>>,
323 id: fontdb::ID,
324 wanted_style: &str,
325 weight: u16,
326 italic: bool,
327) -> bool {
328 if !wanted_style.is_empty() {
329 let matched_name = db
330 .with_face_data(id, |data, index| {
331 let face = ttf_parser::Face::parse(data, index).ok()?;
332 let names = face.names();
333 let name = [17, 2].into_iter().find_map(|nid| {
334 names.into_iter().find(|n| n.name_id == nid && n.is_unicode()).and_then(|n| n.to_string())
335 })?;
336 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
337 })
338 .flatten()
339 .unwrap_or(false);
340 if matched_name {
341 return true;
342 }
343 }
344 let Some(info) = db.face(id) else {
345 return false;
346 };
347 let want_style = if italic { fontdb::Style::Italic } else { fontdb::Style::Normal };
348 info.weight.0 == weight && info.style == want_style
349}
350
351fn try_pick_family_lazy(
352 reg: &mut FontRegistry,
148353 family: &str,
149 style: &str,
150) -> Option<Font> {
354 wanted_style: &str,
355 weight: u16,
356 italic: bool,
357) -> Option<fontdb::ID> {
358 if family.is_empty() {
359 return None;
360 }
361 #[cfg(not(target_arch = "wasm32"))]
362 {
363 let fam_norm = norm_alnum(family);
364 let style_key = if wanted_style.is_empty() { "regular" } else { wanted_style };
365 if !reg.system_fonts_loaded
366 && !reg.loaded_families.contains(&fam_norm)
367 && !reg.aliases.contains_key(&family.to_ascii_lowercase())
368 {
369 load_style_candidates(reg, &fam_norm, style_key);
370 if let Some(id) = pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic) {
371 if is_exact_face_match(&reg.db, id, wanted_style, weight, italic) {
372 return Some(id);
373 }
374 }
375 load_family_candidates(reg, &fam_norm);
376 }
377 }
378 pick(&reg.db, &reg.aliases, family, wanted_style, weight, italic)
379}
380
381fn resolve_lazy(reg: &mut FontRegistry, family: &str, style: &str) -> Option<Font> {
151382 let (weight, italic) = parse_style(style);
152383 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
153 let id = std::iter::once(family)
154 .chain(metric_alias(family))
155 .chain(FALLBACK_FAMILIES)
156 .find_map(|name| pick(db, aliases, name, &wanted, weight, italic))
157 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
158 .or_else(|| db.faces().map(|f| f.id).next())?;
159 let info = db.face(id)?;
160 let data = db.with_face_data(id, |data, _| data.to_vec())?;
384
385 let mut id = try_pick_family_lazy(reg, family, &wanted, weight, italic)
386 .or_else(|| metric_alias(family).and_then(|alias| try_pick_family_lazy(reg, alias, &wanted, weight, italic)));
387
388 #[cfg(not(target_arch = "wasm32"))]
389 if id.is_none() && !family.is_empty() && !reg.system_fonts_loaded {
390 reg.ensure_system_fonts_loaded();
391 id = pick(&reg.db, &reg.aliases, family, &wanted, weight, italic)
392 .or_else(|| metric_alias(family).and_then(|alias| pick(&reg.db, &reg.aliases, alias, &wanted, weight, italic)));
393 }
394
395 if id.is_none() {
396 id = FALLBACK_FAMILIES
397 .iter()
398 .find_map(|fb| try_pick_family_lazy(reg, fb, &wanted, weight, italic));
399 }
400
401 #[cfg(not(target_arch = "wasm32"))]
402 if id.is_none() && !reg.system_fonts_loaded {
403 reg.ensure_system_fonts_loaded();
404 }
405
406 let id = id
407 .or_else(|| reg.db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
408 .or_else(|| reg.db.faces().map(|f| f.id).next())?;
409
410 let info = reg.db.face(id)?;
411 let data = reg.db.with_face_data(id, |data, _| data.to_vec())?;
161412 let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 };
162413 Face::from_slice(&data, info.index)?;
163 Some(Font { data, index: info.index, weight, lean })
414 let font_id = NEXT_FONT_ID.fetch_add(1, Ordering::Relaxed);
415 Some(Font { id: font_id, data, index: info.index, weight, lean })
164416}
165417
166418/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest
......@@ -186,20 +438,22 @@ fn pick(
186438 .collect();
187439 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));
188440 let first = candidates.first()?;
189 let exact = candidates.iter().find(|f| {
190 db.with_face_data(f.id, |data, index| {
191 let face = ttf_parser::Face::parse(data, index).ok()?;
192 let names = face.names();
193 let name = [17, 2].into_iter().find_map(|id| {
194 names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string())
195 })?;
196 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
197 })
198 .flatten()
199 .unwrap_or(false)
200 });
201 if let Some(face) = exact {
202 return Some(face.id);
441 if !wanted_style.is_empty() {
442 let exact = candidates.iter().find(|f| {
443 db.with_face_data(f.id, |data, index| {
444 let face = ttf_parser::Face::parse(data, index).ok()?;
445 let names = face.names();
446 let name = [17, 2].into_iter().find_map(|id| {
447 names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string())
448 })?;
449 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
450 })
451 .flatten()
452 .unwrap_or(false)
453 });
454 if let Some(face) = exact {
455 return Some(face.id);
456 }
203457 }
204458 if let Some(name) = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family)).map(|(n, _)| n.as_str()) {
205459 return db.query(&fontdb::Query {
......@@ -451,12 +705,20 @@ fn resolve_char_styles(params: &RichTextPlusParams<'_>) -> Vec<CharStyle> {
451705
452706struct PlacedGlyph {
453707 commands: Vec<Command>,
454 char_idx: usize,
708}
709
710struct GlyphSpec {
711 font: Arc<Font>,
712 glyph_id: GlyphId,
713 font_px: f32,
714 shear: f32,
455715 outline_w: f32,
716 abs_x: f32,
717 abs_y: f32,
456718}
457719
458struct LayoutLine {
459 glyphs: Vec<PlacedGlyph>,
720struct LayoutSpecLine {
721 glyphs: Vec<GlyphSpec>,
460722 width: f32,
461723 ascent: f32,
462724 descent: f32,
......@@ -470,7 +732,7 @@ fn size_metrics(face: &Face<'_>, size_norm: f32, canvas_w: f32) -> (f32, f32, f3
470732 (font_px, asc_em * font_px, desc_em * font_px)
471733}
472734
473fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<PlacedGlyph>, usize)> {
735fn layout_glyph_specs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<GlyphSpec>, usize)> {
474736 let [w, h] = dims;
475737 let total_chars = params.text.chars().count();
476738 if total_chars == 0 || params.size_norm <= 1e-4 {
......@@ -481,7 +743,6 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
481743 if c_start >= c_end || c_start >= total_chars {
482744 return None;
483745 }
484 let styles = resolve_char_styles(params);
485746 let wf = w as f32;
486747 let hf = h as f32;
487748 let base_font = Font::find(params.font_family, params.font_style)?;
......@@ -489,87 +750,141 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
489750
490751 let mut lines = Vec::new();
491752 let mut char_cursor = 0usize;
492 for raw_line in params.text.split('\n') {
493 let raw_char_len = raw_line.chars().count();
494 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
495 let line_chars: Vec<char> = line_str.chars().collect();
496 let mut shaped_runs: Vec<(usize, usize, Arc<Font>, f32, ShapedLine)> = Vec::new();
497 let mut line_max_size = 0.0_f32;
498 let mut max_asc = 0.0_f32;
499 let mut max_desc = 0.0_f32;
500 let mut max_top_anchor = 0.0_f32;
501
502 if line_chars.is_empty() {
503 let st = styles.get(char_cursor).map(|s| s.size_norm).unwrap_or(params.size_norm);
504 let (font_px, asc, desc) = size_metrics(&base_face, st, wf);
505 max_asc = asc;
506 max_desc = desc;
507 max_top_anchor = (font_px - desc).max(0.0);
753
754 if params.cls.is_empty() {
755 let (font_px, asc, desc) = size_metrics(&base_face, params.size_norm, wf);
756 let top_anchor = (font_px - desc).max(0.0);
757 let extra_track = (params.tracking - 1.0) * params.size_norm * wf;
758 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {
759 (params.outline_thickness_norm * params.size_norm * wf).clamp(1.0, 128.0)
508760 } else {
509 let mut r0 = 0usize;
510 while r0 < line_chars.len() {
511 let st0 = &styles[char_cursor + r0];
512 let mut r1 = r0 + 1;
513 while r1 < line_chars.len() {
514 let st1 = &styles[char_cursor + r1];
515 if st1.family != st0.family
516 || st1.style != st0.style
517 || (st1.size_norm - st0.size_norm).abs() > 1e-5
518 {
519 break;
761 0.0
762 };
763 for raw_line in params.text.split('\n') {
764 let raw_char_len = raw_line.chars().count();
765 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
766 let mut line_glyphs = Vec::new();
767 let width = if line_str.is_empty() {
768 0.0
769 } else {
770 let shaped = shape_line(&base_face, line_str, font_px, extra_track);
771 line_glyphs.reserve(shaped.glyphs.len());
772 for g in &shaped.glyphs {
773 let idx = char_cursor + g.char_index;
774 if idx < c_start || idx >= c_end {
775 continue;
520776 }
521 r1 += 1;
777 line_glyphs.push(GlyphSpec {
778 font: Arc::clone(&base_font),
779 glyph_id: g.id,
780 font_px,
781 shear: -params.shear_x,
782 outline_w,
783 abs_x: g.x,
784 abs_y: -g.y,
785 });
522786 }
523 let run_str: String = line_chars[r0..r1].iter().collect();
524 let font = Font::find(&st0.family, &st0.style).unwrap_or_else(|| Arc::clone(&base_font));
525 let face = font.face();
526 let (font_px, asc, desc) = size_metrics(&face, st0.size_norm, wf);
527 max_asc = max_asc.max(asc);
528 max_desc = max_desc.max(desc);
529 max_top_anchor = max_top_anchor.max((font_px - desc).max(0.0));
530 line_max_size = line_max_size.max(st0.size_norm);
531 let extra_track = (params.tracking - 1.0) * st0.size_norm * wf;
532 let shaped = shape_line(&face, &run_str, font_px, extra_track);
533 shaped_runs.push((r0, r1, font, font_px, shaped));
534 r0 = r1;
535 }
787 shaped.width
788 };
789 lines.push(LayoutSpecLine {
790 glyphs: line_glyphs,
791 width,
792 ascent: asc,
793 descent: desc,
794 top_anchor,
795 });
796 char_cursor += raw_char_len + 1;
536797 }
537
538 let mut total_w = 0.0_f32;
539 let mut line_glyphs = Vec::new();
540 for (ri, &(r0, _, ref font, font_px, ref shaped)) in shaped_runs.iter().enumerate() {
541 if ri > 0 {
542 let st_prev = &styles[char_cursor + r0 - 1];
543 total_w += (params.tracking - 1.0) * st_prev.size_norm * wf;
544 }
545 let face = font.face();
546 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {
547 let size_px = styles[char_cursor + r0].size_norm * wf;
548 (params.outline_thickness_norm * size_px).clamp(1.0, 128.0)
798 } else {
799 let styles = resolve_char_styles(params);
800 for raw_line in params.text.split('\n') {
801 let raw_char_len = raw_line.chars().count();
802 let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line);
803 let line_chars: Vec<char> = line_str.chars().collect();
804 let mut shaped_runs: Vec<(usize, Arc<Font>, f32, ShapedLine)> = Vec::new();
805 let mut max_asc = 0.0_f32;
806 let mut max_desc = 0.0_f32;
807 let mut max_top_anchor = 0.0_f32;
808
809 if line_chars.is_empty() {
810 let st = styles.get(char_cursor).map(|s| s.size_norm).unwrap_or(params.size_norm);
811 let (font_px, asc, desc) = size_metrics(&base_face, st, wf);
812 max_asc = asc;
813 max_desc = desc;
814 max_top_anchor = (font_px - desc).max(0.0);
549815 } else {
550 0.0
551 };
552 for g in &shaped.glyphs {
553 let idx = char_cursor + r0 + g.char_index;
554 if idx < c_start || idx >= c_end {
555 continue;
816 let mut r0 = 0usize;
817 while r0 < line_chars.len() {
818 let st0 = &styles[char_cursor + r0];
819 let mut r1 = r0 + 1;
820 while r1 < line_chars.len() {
821 let st1 = &styles[char_cursor + r1];
822 if st1.family != st0.family
823 || st1.style != st0.style
824 || (st1.size_norm - st0.size_norm).abs() > 1e-5
825 {
826 break;
827 }
828 r1 += 1;
829 }
830 let run_str: String = line_chars[r0..r1].iter().collect();
831 let font = if st0.family == params.font_family && st0.style == params.font_style {
832 Arc::clone(&base_font)
833 } else {
834 Font::find(&st0.family, &st0.style).unwrap_or_else(|| Arc::clone(&base_font))
835 };
836 let face = font.face();
837 let (font_px, asc, desc) = size_metrics(&face, st0.size_norm, wf);
838 max_asc = max_asc.max(asc);
839 max_desc = max_desc.max(desc);
840 max_top_anchor = max_top_anchor.max((font_px - desc).max(0.0));
841 let extra_track = (params.tracking - 1.0) * st0.size_norm * wf;
842 let shaped = shape_line(&face, &run_str, font_px, extra_track);
843 shaped_runs.push((r0, font, font_px, shaped));
844 r0 = r1;
556845 }
557 let st = &styles[idx];
558 let local_origin = [total_w + g.x + st.dx * wf, -g.y - st.dy * wf];
559 let cmds = glyph_path(font, &face, g.id, font_px, local_origin, -st.shear_x);
560 line_glyphs.push(PlacedGlyph { commands: cmds, char_idx: idx, outline_w });
561846 }
562 total_w += shaped.width;
563 }
564 let _ = line_max_size;
565 lines.push(LayoutLine {
566 glyphs: line_glyphs,
567 width: total_w,
568 ascent: max_asc,
569 descent: max_desc,
570 top_anchor: max_top_anchor,
571 });
572 char_cursor += raw_char_len + 1;
847
848 let mut total_w = 0.0_f32;
849 let mut line_glyphs = Vec::new();
850 for (ri, &(r0, ref font, font_px, ref shaped)) in shaped_runs.iter().enumerate() {
851 if ri > 0 {
852 let st_prev = &styles[char_cursor + r0 - 1];
853 total_w += (params.tracking - 1.0) * st_prev.size_norm * wf;
854 }
855 let outline_w = if params.outline_enabled && params.outline_thickness_norm > 1e-4 {
856 let size_px = styles[char_cursor + r0].size_norm * wf;
857 (params.outline_thickness_norm * size_px).clamp(1.0, 128.0)
858 } else {
859 0.0
860 };
861 for g in &shaped.glyphs {
862 let idx = char_cursor + r0 + g.char_index;
863 if idx < c_start || idx >= c_end {
864 continue;
865 }
866 let st = &styles[idx];
867 line_glyphs.push(GlyphSpec {
868 font: Arc::clone(font),
869 glyph_id: g.id,
870 font_px,
871 shear: -st.shear_x,
872 outline_w,
873 abs_x: total_w + g.x + st.dx * wf,
874 abs_y: -g.y - st.dy * wf,
875 });
876 }
877 total_w += shaped.width;
878 }
879 lines.push(LayoutSpecLine {
880 glyphs: line_glyphs,
881 width: total_w,
882 ascent: max_asc,
883 descent: max_desc,
884 top_anchor: max_top_anchor,
885 });
886 char_cursor += raw_char_len + 1;
887 }
573888 }
574889
575890 let cx = params.center[0] * wf;
......@@ -602,37 +917,146 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec
602917 for (li, line) in lines.into_iter().enumerate() {
603918 let start_x = cx - line.width * h_frac;
604919 let base_y = baseline_0 + baselines[li];
605 for mut pg in line.glyphs {
606 for cmd in &mut pg.commands {
607 match cmd {
608 Command::MoveTo(p) | Command::LineTo(p) => {
609 p.x += start_x;
610 p.y += base_y;
611 }
612 Command::QuadTo(c, p) => {
613 c.x += start_x;
614 c.y += base_y;
615 p.x += start_x;
616 p.y += base_y;
617 }
618 Command::CurveTo(c1, c2, p) => {
619 c1.x += start_x;
620 c1.y += base_y;
621 c2.x += start_x;
622 c2.y += base_y;
623 p.x += start_x;
624 p.y += base_y;
625 }
626 Command::Close => {}
627 }
628 }
629 let _ = pg.char_idx;
630 out.push(pg);
920 for mut spec in line.glyphs {
921 spec.abs_x += start_x;
922 spec.abs_y += base_y;
923 out.push(spec);
631924 }
632925 }
633926 Some((out, total_chars))
634927}
635928
929fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec<PlacedGlyph>, usize)> {
930 let (specs, total_chars) = layout_glyph_specs(dims, params)?;
931 let mut out = Vec::with_capacity(specs.len());
932 for spec in &specs {
933 let face = spec.font.face();
934 let commands = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, [spec.abs_x, spec.abs_y], spec.shear);
935 out.push(PlacedGlyph { commands });
936 }
937 Some((out, total_chars))
938}
939
940const GLYPH_BASELINE_ANCHOR: f32 = 256.0;
941const GLYPH_BASELINE_ANCHOR_I32: i32 = 256;
942const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;
943const MAX_GLYPH_CACHE_BYTES: usize = 8 * 1024 * 1024;
944
945#[derive(Clone, Copy, PartialEq, Eq, Hash)]
946struct GlyphCacheKey {
947 font_id: u64,
948 glyph_id: u16,
949 size_bits: u32,
950 lean_bits: u32,
951 stroke_bits: u32,
952 sub_x_bits: u32,
953 sub_y_bits: u32,
954}
955
956struct CachedGlyphCoverage {
957 fill: Option<Coverage>,
958 stroke: Option<Coverage>,
959 bytes: usize,
960}
961
962struct GlyphCache {
963 map: HashMap<GlyphCacheKey, Arc<CachedGlyphCoverage>>,
964 order: VecDeque<GlyphCacheKey>,
965 total_bytes: usize,
966}
967
968impl GlyphCache {
969 fn new() -> Self {
970 Self {
971 map: HashMap::new(),
972 order: VecDeque::new(),
973 total_bytes: 0,
974 }
975 }
976
977 fn get(&self, key: &GlyphCacheKey) -> Option<Arc<CachedGlyphCoverage>> {
978 self.map.get(key).cloned()
979 }
980
981 fn insert(&mut self, key: GlyphCacheKey, val: Arc<CachedGlyphCoverage>) {
982 if val.bytes > MAX_GLYPH_CACHE_BYTES || self.map.contains_key(&key) {
983 return;
984 }
985 while self.map.len() >= MAX_GLYPH_CACHE_ENTRIES || self.total_bytes + val.bytes > MAX_GLYPH_CACHE_BYTES {
986 let Some(old_key) = self.order.pop_front() else {
987 break;
988 };
989 if let Some(removed) = self.map.remove(&old_key) {
990 self.total_bytes = self.total_bytes.saturating_sub(removed.bytes);
991 }
992 }
993 self.total_bytes += val.bytes;
994 self.order.push_back(key);
995 self.map.insert(key, val);
996 }
997}
998
999fn glyph_cache() -> &'static Mutex<GlyphCache> {
1000 static CACHE: OnceLock<Mutex<GlyphCache>> = OnceLock::new();
1001 CACHE.get_or_init(|| Mutex::new(GlyphCache::new()))
1002}
1003
1004fn cached_glyph_coverage(spec: &GlyphSpec, want_outline: bool) -> (i32, i32, Arc<CachedGlyphCoverage>) {
1005 let ix = spec.abs_x.floor() as i32;
1006 let iy = spec.abs_y.floor() as i32;
1007 let fx = spec.abs_x - ix as f32;
1008 let fy = spec.abs_y - iy as f32;
1009
1010 let total_lean = spec.font.lean + spec.shear;
1011 let lean_norm = if total_lean == 0.0 { 0.0 } else { total_lean };
1012 let stroke_bits = if want_outline {
1013 spec.outline_w.to_bits()
1014 } else {
1015 0
1016 };
1017 let key = GlyphCacheKey {
1018 font_id: spec.font.id,
1019 glyph_id: spec.glyph_id.0,
1020 size_bits: spec.font_px.to_bits(),
1021 lean_bits: lean_norm.to_bits(),
1022 stroke_bits,
1023 sub_x_bits: if fx == 0.0 { 0 } else { fx.to_bits() },
1024 sub_y_bits: if fy == 0.0 { 0 } else { fy.to_bits() },
1025 };
1026
1027 if let Some(hit) = glyph_cache().lock().unwrap().get(&key) {
1028 return (ix, iy, hit);
1029 }
1030
1031 // Anchor outlines near 256px so zeno's flattening precision matches full-canvas rasterization.
1032 let sub_origin = [GLYPH_BASELINE_ANCHOR + fx, GLYPH_BASELINE_ANCHOR + fy];
1033 let face = spec.font.face();
1034 let path = glyph_path(&spec.font, &face, spec.glyph_id, spec.font_px, sub_origin, spec.shear);
1035 let fill_cov = fill(&path).map(|mut c| {
1036 c.left -= GLYPH_BASELINE_ANCHOR_I32;
1037 c.top -= GLYPH_BASELINE_ANCHOR_I32;
1038 c
1039 });
1040 let stroke_cov = if want_outline {
1041 stroke(&path, spec.outline_w).map(|mut c| {
1042 c.left -= GLYPH_BASELINE_ANCHOR_I32;
1043 c.top -= GLYPH_BASELINE_ANCHOR_I32;
1044 c
1045 })
1046 } else {
1047 None
1048 };
1049 let bytes = fill_cov.as_ref().map_or(0, |c| c.data.len())
1050 + stroke_cov.as_ref().map_or(0, |c| c.data.len());
1051 let entry = Arc::new(CachedGlyphCoverage {
1052 fill: fill_cov,
1053 stroke: stroke_cov,
1054 bytes,
1055 });
1056 glyph_cache().lock().unwrap().insert(key, Arc::clone(&entry));
1057 (ix, iy, entry)
1058}
1059
6361060fn gaussian_kernel_1d(sigma: f32) -> (isize, Vec<f32>) {
6371061 if !sigma.is_finite() || sigma < 0.05 {
6381062 return (0, vec![1.0]);
......@@ -730,20 +1154,22 @@ fn apply_separable_gaussian(plane: &mut [f32], w: usize, h: usize, sigma_x: f32,
7301154 }
7311155}
7321156
733fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) {
1157fn blit_plane_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [f32]) {
1158 let c_left = c.left + offset[0];
1159 let c_top = c.top + offset[1];
7341160 let cw = c.width as i32;
7351161 let ch = c.height as i32;
736 let x0 = (origin[0] - c.left).max(0);
737 let y0 = (origin[1] - c.top).max(0);
738 let x1 = (origin[0] + tw as i32 - c.left).min(cw);
739 let y1 = (origin[1] + th as i32 - c.top).min(ch);
1162 let x0 = (origin[0] - c_left).max(0);
1163 let y0 = (origin[1] - c_top).max(0);
1164 let x1 = (origin[0] + tw as i32 - c_left).min(cw);
1165 let y1 = (origin[1] + th as i32 - c_top).min(ch);
7401166 if x0 >= x1 || y0 >= y1 {
7411167 return;
7421168 }
7431169 let span = (x1 - x0) as usize;
744 let dst_x0 = (c.left + x0 - origin[0]) as usize;
1170 let dst_x0 = (c_left + x0 - origin[0]) as usize;
7451171 for y in y0..y1 {
746 let py = (c.top + y - origin[1]) as usize;
1172 let py = (c_top + y - origin[1]) as usize;
7471173 let src_start = y as usize * c.width as usize + x0 as usize;
7481174 let src_row = &c.data[src_start..src_start + span];
7491175 let dst_start = py * tw + dst_x0;
......@@ -756,6 +1182,32 @@ fn blit_plane_max(c: &Coverage, origin: [i32; 2], tw: usize, th: usize, plane: &
7561182 }
7571183}
7581184
1185fn blit_plane_u8_max_offset(c: &Coverage, offset: [i32; 2], origin: [i32; 2], tw: usize, th: usize, plane: &mut [u8]) {
1186 let c_left = c.left + offset[0];
1187 let c_top = c.top + offset[1];
1188 let cw = c.width as i32;
1189 let ch = c.height as i32;
1190 let x0 = (origin[0] - c_left).max(0);
1191 let y0 = (origin[1] - c_top).max(0);
1192 let x1 = (origin[0] + tw as i32 - c_left).min(cw);
1193 let y1 = (origin[1] + th as i32 - c_top).min(ch);
1194 if x0 >= x1 || y0 >= y1 {
1195 return;
1196 }
1197 let span = (x1 - x0) as usize;
1198 let dst_x0 = (c_left + x0 - origin[0]) as usize;
1199 for y in y0..y1 {
1200 let py = (c_top + y - origin[1]) as usize;
1201 let src_start = y as usize * c.width as usize + x0 as usize;
1202 let src_row = &c.data[src_start..src_start + span];
1203 let dst_start = py * tw + dst_x0;
1204 let dst_row = &mut plane[dst_start..dst_start + span];
1205 for (d, &a) in dst_row.iter_mut().zip(src_row.iter()) {
1206 *d = (*d).max(a);
1207 }
1208 }
1209}
1210
7591211/// Extended `TextPlus` / `Text3D` rasterizer with `StyledTextCLS` per-character styling and
7601212/// Element 1/2 Softness blur + glow. Returns a tight-DoD `(tex_size, origin, rgba)` buffer.
7611213pub fn rasterize_text_plus_rich(
......@@ -769,10 +1221,10 @@ pub fn rasterize_text_plus_rich(
7691221 if params.fill_rgba[3] <= 0.0 && !has_outline && dod_pad <= 0 {
7701222 return empty();
7711223 }
772 let Some((glyphs, _)) = layout_glyphs(dims, params) else {
1224 let Some((specs, _)) = layout_glyph_specs(dims, params) else {
7731225 return empty();
7741226 };
775 if glyphs.is_empty() {
1227 if specs.is_empty() {
7761228 return empty();
7771229 }
7781230
......@@ -788,31 +1240,31 @@ pub fn rasterize_text_plus_rich(
7881240 let eff_pad = dod_pad.clamp(0, 4096).max(blur_pad).max(1);
7891241
7901242 let (mut min_x, mut min_y, mut max_x, mut max_y) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
791 let mut grow = |c: &Coverage, pad: i32| {
792 min_x = min_x.min(c.left.saturating_sub(pad));
793 min_y = min_y.min(c.top.saturating_sub(pad));
794 max_x = max_x.max((c.left + c.width as i32).saturating_add(pad));
795 max_y = max_y.max((c.top + c.height as i32).saturating_add(pad));
1243 let mut grow = |c: &Coverage, ox: i32, oy: i32, pad: i32| {
1244 let left = c.left.saturating_add(ox);
1245 let top = c.top.saturating_add(oy);
1246 min_x = min_x.min(left.saturating_sub(pad));
1247 min_y = min_y.min(top.saturating_sub(pad));
1248 max_x = max_x.max((left + c.width as i32).saturating_add(pad));
1249 max_y = max_y.max((top + c.height as i32).saturating_add(pad));
7961250 };
7971251
798 let mut placed = Vec::with_capacity(glyphs.len());
1252 let mut placed = Vec::with_capacity(specs.len());
7991253 let mut any_outline = false;
800 for g in &glyphs {
801 let f = fill(&g.commands);
802 let l = if has_outline && g.outline_w > 1e-3 {
803 let s = stroke(&g.commands, g.outline_w);
804 any_outline |= s.is_some();
805 s
806 } else {
807 None
808 };
809 if let Some(c) = &f {
810 grow(c, eff_pad);
1254 for spec in &specs {
1255 if !spec.abs_x.is_finite() || !spec.abs_y.is_finite() {
1256 continue;
1257 }
1258 let want_outline = has_outline && spec.outline_w > 1e-3;
1259 let (ix, iy, cov) = cached_glyph_coverage(spec, want_outline);
1260 if let Some(c) = &cov.fill {
1261 grow(c, ix, iy, eff_pad);
8111262 }
812 if let Some(c) = &l {
813 grow(c, eff_pad);
1263 if let Some(c) = &cov.stroke {
1264 any_outline = true;
1265 grow(c, ix, iy, eff_pad);
8141266 }
815 placed.push((f, l));
1267 placed.push((ix, iy, cov));
8161268 }
8171269 if min_x > max_x || min_y > max_y {
8181270 return empty();
......@@ -828,14 +1280,47 @@ pub fn rasterize_text_plus_rich(
8281280 let tw = (end_x - origin_x) as usize;
8291281 let th = (end_y - origin_y) as usize;
8301282
1283 let glow1 = 1.0 / (1.0 - params.soft_fill[2].clamp(0.0, 0.999));
1284 let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999));
1285 let (fc, oc) = (params.fill_rgba, params.outline_rgba);
1286 let mut out = vec![0u8; tw * th * 4];
1287
1288 if !any_outline && sx1 <= 0.05 && sy1 <= 0.05 {
1289 let mut fill_u8 = vec![0u8; tw * th];
1290 for (ix, iy, cov) in &placed {
1291 if let Some(c) = &cov.fill {
1292 blit_plane_u8_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_u8);
1293 }
1294 }
1295 let f_scale = fc[3] * glow1;
1296 let mut lut = [[0u8; 4]; 256];
1297 for (a_u8, entry) in lut.iter_mut().enumerate().skip(1) {
1298 let fa = ((a_u8 as f32 / 255.0) * f_scale).clamp(0.0, 1.0);
1299 if fa > 0.0 {
1300 *entry = [
1301 (fc[0] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1302 (fc[1] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1303 (fc[2] * fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1304 (fa * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
1305 ];
1306 }
1307 }
1308 for (px, &a) in out.chunks_exact_mut(4).zip(fill_u8.iter()) {
1309 if a != 0 {
1310 px.copy_from_slice(&lut[a as usize]);
1311 }
1312 }
1313 return ([tw as u32, th as u32], [origin_x, origin_y], out);
1314 }
1315
8311316 let mut fill_plane = vec![0.0_f32; tw * th];
8321317 let mut line_plane = vec![0.0_f32; if any_outline { tw * th } else { 0 }];
833 for (f, l) in &placed {
834 if let Some(c) = f {
835 blit_plane_max(c, [origin_x, origin_y], tw, th, &mut fill_plane);
1318 for (ix, iy, cov) in &placed {
1319 if let Some(c) = &cov.fill {
1320 blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut fill_plane);
8361321 }
837 if let Some(c) = l {
838 blit_plane_max(c, [origin_x, origin_y], tw, th, &mut line_plane);
1322 if let Some(c) = &cov.stroke {
1323 blit_plane_max_offset(c, [*ix, *iy], [origin_x, origin_y], tw, th, &mut line_plane);
8391324 }
8401325 }
8411326
......@@ -846,10 +1331,6 @@ pub fn rasterize_text_plus_rich(
8461331 apply_separable_gaussian(&mut line_plane, tw, th, sx2, sy2);
8471332 }
8481333
849 let glow1 = 1.0 / (1.0 - params.soft_fill[2].clamp(0.0, 0.999));
850 let glow2 = 1.0 / (1.0 - params.soft_outline[2].clamp(0.0, 0.999));
851 let (fc, oc) = (params.fill_rgba, params.outline_rgba);
852 let mut out = vec![0u8; tw * th * 4];
8531334 if any_outline {
8541335 let f_scale = fc[3] * glow1;
8551336 let o_scale = oc[3] * glow2;
......@@ -1956,4 +2437,82 @@ mod tests {
19562437 }
19572438 }
19582439 }
2440
2441 #[test]
2442 fn glyph_cache_is_deterministic_and_bounded() {
2443 let p = RichTextPlusParams {
2444 text: "Mississippi 1234",
2445 font_family: "Helvetica",
2446 font_style: "Regular",
2447 size_norm: 0.08,
2448 tracking: 1.0,
2449 line_spacing: 1.0,
2450 center: [0.5, 0.5],
2451 h_lcr: 0.0,
2452 v_tcb: 0.0,
2453 fill_rgba: [1.0, 0.85, 0.7, 1.0],
2454 write_on_start: 0.0,
2455 write_on_end: 1.0,
2456 shear_x: 0.0,
2457 cls: &[],
2458 outline_rgba: [0.1, 0.2, 0.3, 0.9],
2459 outline_thickness_norm: 0.03,
2460 outline_enabled: true,
2461 soft_fill: [0.0; 3],
2462 soft_outline: [0.0; 3],
2463 baseline_at_center: false,
2464 };
2465 let first = rasterize_text_plus_rich([960, 540], &p, 0);
2466 let second = rasterize_text_plus_rich([960, 540], &p, 0);
2467 assert_eq!(first, second, "cached glyph rasterization must be bit-identical");
2468
2469 let mut p_plain = p;
2470 p_plain.outline_enabled = false;
2471 let p1 = rasterize_text_plus_rich([960, 540], &p_plain, 0);
2472 let p2 = rasterize_text_plus_rich([960, 540], &p_plain, 0);
2473 assert_eq!(p1, p2, "u8 fast-path glyph rasterization must be bit-identical");
2474
2475 // Verify bounded eviction in GlyphCache.
2476 let mut cache = GlyphCache::new();
2477 for i in 0..(MAX_GLYPH_CACHE_ENTRIES + 64) {
2478 let key = GlyphCacheKey {
2479 font_id: 999,
2480 glyph_id: i as u16,
2481 size_bits: 1000,
2482 lean_bits: 0,
2483 stroke_bits: 0,
2484 sub_x_bits: 0,
2485 sub_y_bits: 0,
2486 };
2487 let entry = Arc::new(CachedGlyphCoverage {
2488 fill: Some(Coverage {
2489 left: 0,
2490 top: 0,
2491 width: 4,
2492 height: 4,
2493 data: vec![255; 16],
2494 }),
2495 stroke: None,
2496 bytes: 16,
2497 });
2498 cache.insert(key, entry);
2499 }
2500 assert!(cache.map.len() <= MAX_GLYPH_CACHE_ENTRIES);
2501 assert!(cache.total_bytes <= MAX_GLYPH_CACHE_BYTES);
2502 }
2503
2504 #[test]
2505 fn lazy_font_lookup_resolves_and_caches() {
2506 let f1 = Font::find("Helvetica Neue", "Regular").expect("Helvetica Neue");
2507 let f2 = Font::find("Helvetica Neue", "Regular").expect("cached Helvetica Neue");
2508 assert_eq!(f1.id, f2.id);
2509 let mut t_sum = std::time::Duration::ZERO;
2510 for _ in 0..20 {
2511 let t0 = std::time::Instant::now();
2512 let f = Font::find("Helvetica Neue", "Regular").unwrap();
2513 t_sum += t0.elapsed();
2514 assert_eq!(f.id, f1.id);
2515 }
2516 assert!(t_sum.as_millis() < 50, "repeated cached lookups took {t_sum:?}");
2517 }
19592518}