Skip to main content

sdf_text/
batched_text.rs

1//! Port of lib3's `src/sdf-text/BatchedText.js` — steps 4–5 of the ladder.
2//!
3//! One `InstancedMesh` of unit plane quads, one quad per glyph of every member
4//! [`Text`], with four per-instance attributes (`aGlyphUV`, `aGlyphBounds`,
5//! `aColor`, `aOpacity`) and the member's `matrixWorld` in the instance matrix.
6//! The material is `buildMaterial()`'s TSL chain: `fwidth`-derived
7//! anti-aliasing on a bilinear sample of the `R32Float` SDF atlas, with an
8//! outline/halo band inside the 0.5 contour.
9//!
10//! Three things differ from the JS, all forced rather than chosen:
11//!
12//! 1. **The batch owns its members.** `addText( text )` in the JS keeps a
13//!    reference to an object the page also holds; here [`BatchedText::add_text`]
14//!    moves the [`Text`] in and [`BatchedText::text_at_mut`] hands it back. The
15//!    member's transform is an `Object3D` the batch owns too
16//!    ([`BatchedText::member_node`]), since `Text` itself stays the pure layout
17//!    type steps 1–3 graded (README deviation 6). `text._batchedText = this` is
18//!    therefore *not* set: the opacity write-through exists for a `Text` the
19//!    page owns, and a batch that owns its members writes the opacity array
20//!    itself — wiring it anyway would be an `Rc` cycle.
21//! 2. **The per-instance data travels with the node graph**, as
22//!    [`tsl::instanced_data_attribute`], not as a named geometry attribute:
23//!    three-rs resolves `attribute( name )` against the geometry's per-*vertex*
24//!    map only, and `InstanceBuffer` is the port's existing mechanism for
25//!    anything that steps per instance. The consequence is that the four
26//!    `needsUpdate = true` flags become one `build_material()` call, which
27//!    rebuilds the nodes around fresh copies of the arrays and ends with the
28//!    material's own `set_needs_update()`, so the renderer builds the program
29//!    once per `sync()` that changed something rather than every frame.
30//! 3. **`positionNode` is kept**, unlike d33's `LabelBatch` workaround, because
31//!    three-rs applies `position_node` *before* the instance matrix (plan §5.2,
32//!    `docs/nodes.md` §10) — the order lib3 was written against. On a unit
33//!    `PlaneGeometry( 1, 1 )` d33's baked `world × translate × scale` and lib3's
34//!    `mix( bounds.x, bounds.z, uv.x )` place every vertex identically, so this
35//!    matches d33's pixels as well as lib3's.
36//!
37//! `sync()` also computes the batch's own bounding sphere over the members'
38//! glyph quads and stores it on the node, which is `BatchedMesh`'s
39//! `computeBoundingSphere` in three.js and is what keeps the frustum cull from
40//! dropping a batch whose node sits at the origin while its members do not
41//! (#42). See [`BatchedText::bounding_sphere`].
42//!
43//! `Fn( … )()` around `positionNode` and `colorNode` is dropped: it takes no
44//! parameters, so `FunctionNode` inlines its body and the emitted WGSL is the
45//! same expression either way.
46
47use std::rc::Rc;
48
49use three_rs::core::Object3D;
50use three_rs::geometries::plane_geometry;
51use three_rs::materials::Side;
52use three_rs::math::{Color, Matrix4, Sphere, Vector3};
53use three_rs::nodes::tsl;
54use three_rs::nodes::{NodeRef, Type};
55use three_rs::objects::InstancedMesh;
56use three_rs::textures::Texture;
57use three_rs::{MeshBasicNodeMaterial, ObjectRef};
58
59use crate::text::Text;
60use crate::vector_font::VectorFont;
61use crate::vector_font_atlas::VectorFontAtlas;
62
63/// `BatchedText.js:23` — the fraction of each glyph's ink size that the quad
64/// *and* the sampled sub-rect are both grown by, so the outline/AA halo around
65/// the ink is not clipped at the ink bbox while the mapping stays ink↔ink.
66pub const GLYPH_QUAD_PAD: f64 = 0.12;
67
68/// The `options` object of `new BatchedText( maxTextCount, maxGlyphCount,
69/// _baseMaterial, options )`, vector mode only — `FontAtlas` is in the skip
70/// register, so `options.font != null` is assumed and `_vectorMode` is always
71/// true.
72#[derive(Clone, Debug)]
73#[non_exhaustive]
74pub struct BatchedTextOptions {
75    /// `options.outlineWidth ?? 0.03`, in SDF units.
76    pub outline_width: f64,
77    /// `options.outlineColor`, **linear** — `new THREE.Color( hex )` applies
78    /// `SRGBToLinear`, so pass `Color::from_hex( 0xffffff )`. `None` is the
79    /// legacy same-colour outline.
80    pub outline_color: Option<Color>,
81    /// `options.atlasSize ?? 1024`, forwarded to [`VectorFontAtlas::new`].
82    pub atlas_size: u32,
83}
84
85impl Default for BatchedTextOptions {
86    fn default() -> Self {
87        Self {
88            outline_width: 0.03,
89            outline_color: None,
90            atlas_size: 1024,
91        }
92    }
93}
94
95/// One member: the `Text` the JS holds in `_members[ id ]`, the `Object3D` it is
96/// a subclass of there, and its `_memberGlyphs[ id ]` slice.
97struct Member {
98    text: Text,
99    node: ObjectRef,
100    glyph_start: usize,
101    glyph_count: usize,
102}
103
104/// The instanced draw for a batch of [`Text`] members — a port of lib3's
105/// `BatchedText`. See the module doc for the shape of the instance data and
106/// where it deliberately diverges from the JS.
107pub struct BatchedText {
108    node: ObjectRef,
109    /// `this.atlas`.
110    pub atlas: VectorFontAtlas,
111    font: Option<Rc<VectorFont>>,
112
113    max_text_count: usize,
114    max_glyph_count: usize,
115    members: Vec<Option<Member>>,
116    member_count: usize,
117    glyph_count: usize,
118
119    outline_width: f64,
120    outline_color: Option<Color>,
121
122    glyph_uv: Vec<f32>,
123    glyph_bounds: Vec<f32>,
124    colors: Vec<f32>,
125    opacities: Vec<f32>,
126
127    /// The `DataTexture` over `atlas.atlas_data()`. Rebuilt rather than mutated
128    /// whenever the atlas gains a glyph: the renderer caches GPU textures by
129    /// identity, so `needsUpdate` on the old handle would upload nothing.
130    texture: Texture,
131
132    /// What the material's nodes were last built around, so a `sync()` that
133    /// changed nothing — the second of the page's two rounds — leaves the
134    /// material, and therefore its program, alone.
135    built: Option<BuiltInputs>,
136}
137
138/// The inputs `build_material()` closes over: the four attribute arrays (the
139/// very `Rc`s the nodes hold), the two outline settings baked as uniforms, and
140/// the atlas texture. In lib3 the arrays are `needsUpdate = true` attributes
141/// that re-upload without touching the program; here they travel in the node
142/// graph, so "unchanged" has to be checked before rebuilding it.
143struct BuiltInputs {
144    glyph_uv: Rc<Vec<f32>>,
145    glyph_bounds: Rc<Vec<f32>>,
146    colors: Rc<Vec<f32>>,
147    opacities: Rc<Vec<f32>>,
148    outline_width: f64,
149    outline_color: Option<Color>,
150    texture_id: usize,
151}
152
153impl BatchedText {
154    /// `new BatchedText( maxTextCount = 64, maxGlyphCount = 1024, undefined,
155    /// options )`. The constructor ends with `this.count = 0`.
156    pub fn new(max_text_count: usize, max_glyph_count: usize, options: BatchedTextOptions) -> Self {
157        // `const plane = new THREE.PlaneGeometry( 1, 1 )`.
158        let plane = Rc::new(plane_geometry(1.0, 1.0, 1, 1));
159
160        // `const material = new THREE.NodeMaterial()` — the port has no bare
161        // `NodeMaterial`; `MeshBasicNodeMaterial` with a `color_node` is the
162        // same flow, since `colorNode` replaces the diffuse colour entirely.
163        let material = MeshBasicNodeMaterial {
164            name: "BatchedText",
165            transparent: true,
166            depth_write: false,
167            side: Side::Double,
168            ..Default::default()
169        };
170
171        let node = InstancedMesh::new(plane, material, max_glyph_count);
172        node.borrow_mut().object_type = "BatchedText";
173
174        let atlas = VectorFontAtlas::new(options.atlas_size);
175        let texture = atlas_texture(&atlas);
176
177        let mut batch = Self {
178            node,
179            atlas,
180            font: None,
181            max_text_count,
182            max_glyph_count,
183            members: (0..max_text_count).map(|_| None).collect(),
184            member_count: 0,
185            glyph_count: 0,
186            outline_width: options.outline_width,
187            outline_color: options.outline_color,
188            glyph_uv: vec![0.0; max_glyph_count * 4],
189            glyph_bounds: vec![0.0; max_glyph_count * 4],
190            colors: vec![0.0; max_glyph_count * 3],
191            opacities: vec![1.0; max_glyph_count],
192            texture,
193            built: None,
194        };
195
196        batch.build_material();
197        batch.set_count(0);
198        batch
199    }
200
201    /// The scene-graph node: `scene.add( batch.node() )`.
202    pub fn node(&self) -> &ObjectRef {
203        &self.node
204    }
205
206    /// `InstancedMesh.count` — the glyph quads the renderer draws.
207    pub fn count(&self) -> usize {
208        self.glyph_count
209    }
210
211    /// `get memberCount()`.
212    pub fn member_count(&self) -> usize {
213        self.member_count
214    }
215
216    /// The glyph capacity this batch was created with.
217    pub fn max_glyph_count(&self) -> usize {
218        self.max_glyph_count
219    }
220
221    /// The atlas texture the material samples.
222    pub fn texture(&self) -> &Texture {
223        &self.texture
224    }
225
226    /// The font-loaded continuation of the JS constructor:
227    /// `this.vectorFont = font; this.atlas.setFont( font ); … t._needsSync = true`.
228    ///
229    /// `VectorFontAtlas` here takes the font per call rather than holding it
230    /// (README deviation 11), so `setFont`'s whole effect is its reset.
231    pub fn set_font(&mut self, font: Rc<VectorFont>) {
232        self.font = Some(font);
233        self.atlas.reset();
234        for member in self.members.iter_mut().flatten() {
235            member.text.mark_needs_sync();
236        }
237    }
238
239    /// The font set by [`BatchedText::set_font`], if any.
240    pub fn font(&self) -> Option<&Rc<VectorFont>> {
241        self.font.as_ref()
242    }
243
244    /// `resetAtlas()`.
245    pub fn reset_atlas(&mut self) {
246        self.atlas.reset();
247        for member in self.members.iter_mut().flatten() {
248            member.text.mark_needs_sync();
249        }
250        self.sync();
251    }
252
253    /// `addText( text )` — the member id, or `None` at capacity (`-1` in the
254    /// JS).
255    pub fn add_text(&mut self, mut text: Text) -> Option<usize> {
256        if self.member_count >= self.max_text_count {
257            return None;
258        }
259        let id = self.member_count;
260        self.member_count += 1;
261
262        text.set_vector_mode(true);
263        text.set_vector_font(self.font.clone());
264        text.mark_needs_sync();
265
266        self.members[id] = Some(Member {
267            text,
268            node: Object3D::new_node(),
269            glyph_start: 0,
270            glyph_count: 0,
271        });
272        Some(id)
273    }
274
275    /// `removeText( text )`, by id: the slot is cleared, and `_memberCount`
276    /// shrinks only when the *last* member went.
277    pub fn remove_text(&mut self, member_id: usize) {
278        if self.members.get(member_id).map(Option::is_some) != Some(true) {
279            return;
280        }
281        self.members[member_id] = None;
282        if member_id + 1 == self.member_count {
283            self.member_count -= 1;
284        }
285    }
286
287    /// `getTextAt( memberId )`.
288    pub fn text_at(&self, member_id: usize) -> Option<&Text> {
289        self.members.get(member_id)?.as_ref().map(|m| &m.text)
290    }
291
292    /// `getTextAt( memberId )`, for mutation. A layout property changed through
293    /// this needs a [`BatchedText::sync`] to reach the attributes, as in the JS.
294    pub fn text_at_mut(&mut self, member_id: usize) -> Option<&mut Text> {
295        self.members
296            .get_mut(member_id)?
297            .as_mut()
298            .map(|m| &mut m.text)
299    }
300
301    /// The member's own `Object3D` — `text.position` / `text.quaternion` in the
302    /// JS, where `Text extends Object3D`. `sync()` composes its `matrixWorld`.
303    ///
304    /// Every glyph of the member is drawn with that whole `matrix_world` as its
305    /// instance matrix, so rotation and scale are honoured along with position:
306    /// `member_node( id ).borrow_mut().set_rotation( -PI / 2.0, 0.0, 0.0 )` lays
307    /// the label flat on the floor. Members are not billboarded.
308    pub fn member_node(&self, member_id: usize) -> Option<&ObjectRef> {
309        self.members.get(member_id)?.as_ref().map(|m| &m.node)
310    }
311
312    /// `_memberGlyphs[ memberId ]`.
313    pub fn member_glyphs(&self, member_id: usize) -> Option<(usize, usize)> {
314        self.members
315            .get(member_id)?
316            .as_ref()
317            .map(|m| (m.glyph_start, m.glyph_count))
318    }
319
320    /// `aGlyphUV`, for tests and for callers checking the packing without a GPU.
321    pub fn glyph_uv_array(&self) -> &[f32] {
322        &self.glyph_uv
323    }
324
325    /// `aGlyphBounds`.
326    pub fn glyph_bounds_array(&self) -> &[f32] {
327        &self.glyph_bounds
328    }
329
330    /// `aColor`.
331    pub fn color_array(&self) -> &[f32] {
332        &self.colors
333    }
334
335    /// `aOpacity`.
336    pub fn opacity_array(&self) -> &[f32] {
337        &self.opacities
338    }
339
340    /// `setColorAt( memberId, color )`. The colour is **linear**, as
341    /// `THREE.Color` stores it (plan §5.3).
342    pub fn set_color_at(&mut self, member_id: usize, color: Color) {
343        let Some(Some(member)) = self.members.get_mut(member_id) else {
344            return;
345        };
346        member.text.color = [color.r, color.g, color.b];
347        let (start, count) = (member.glyph_start, member.glyph_count);
348        if count == 0 {
349            return;
350        }
351        for g in start..start + count {
352            self.colors[g * 3] = color.r as f32;
353            self.colors[g * 3 + 1] = color.g as f32;
354            self.colors[g * 3 + 2] = color.b as f32;
355        }
356        self.build_material();
357    }
358
359    /// `setOpacityAt( memberId, opacity )`. `text._opacity = opacity` is
360    /// [`Text::set_opacity`] here: the batch owns the member, so its
361    /// write-through sink is `None` and there is no recursion.
362    pub fn set_opacity_at(&mut self, member_id: usize, opacity: f64) {
363        let Some(Some(member)) = self.members.get_mut(member_id) else {
364            return;
365        };
366        member.text.set_opacity(opacity);
367        let (start, count) = (member.glyph_start, member.glyph_count);
368        if count == 0 {
369            return;
370        }
371        for g in start..start + count {
372            self.opacities[g] = opacity as f32;
373        }
374        self.build_material();
375    }
376
377    /// `get outlineColor()`.
378    pub fn outline_color(&self) -> Option<Color> {
379        self.outline_color
380    }
381
382    /// `set outlineColor( color )` — `None` restores the legacy same-colour
383    /// outline by zeroing the mix uniform.
384    pub fn set_outline_color(&mut self, color: Option<Color>) {
385        self.outline_color = color;
386        self.build_material();
387    }
388
389    /// Outline/halo band width, in SDF units.
390    pub fn outline_width(&self) -> f64 {
391        self.outline_width
392    }
393
394    /// `setMatrixAt( memberId, matrix )` — the member's world matrix when
395    /// `memberId` names a registered member, rewriting that member's glyph
396    /// matrices; past `_memberCount` it is `InstancedMesh.setMatrixAt`, i.e. one
397    /// glyph instance.
398    pub fn set_matrix_at(&mut self, member_id: usize, matrix: &Matrix4) {
399        let is_member = member_id < self.member_count
400            && self.members.get(member_id).map(Option::is_some) == Some(true);
401        if !is_member {
402            self.node.borrow_mut().set_matrix_at(member_id, matrix);
403            return;
404        }
405
406        let member = self.members[member_id]
407            .as_ref()
408            .expect("sdf-text: is_member means member_id names a registered member");
409        member.node.borrow_mut().matrix_world = *matrix;
410
411        let (start, count) = (member.glyph_start, member.glyph_count);
412        if member.text.text_render_info().is_none() || count == 0 {
413            return;
414        }
415        self.write_glyph_matrices(matrix, start, count);
416        // The member moved, so the batch's own bounding sphere moved with it.
417        self.update_bounding_sphere();
418    }
419
420    /// `_writeGlyphMatrices( text, info, glyphStart, glyphCount )` — every glyph
421    /// of a member gets the member's plain `matrixWorld`; the quad itself comes
422    /// from `positionNode`.
423    fn write_glyph_matrices(&mut self, world: &Matrix4, start: usize, count: usize) {
424        let mut object = self.node.borrow_mut();
425        for g in 0..count {
426            object.set_matrix_at(start + g, world);
427        }
428    }
429
430    /// `sync( callback )` — lay every member out, grow the atlas, pack the
431    /// attributes. The callback is an idiom for a path that never awaits and is
432    /// dropped, as in `Text::sync`.
433    pub fn sync(&mut self) {
434        // Pass 1: lay out, and collect the distinct non-space glyphs in
435        // first-seen order. `new Set()` preserves insertion order and
436        // `ensureGlyphs` assigns atlas slots in iteration order, so the order
437        // here *is* the slot assignment (plan §5.4).
438        let mut chars: Vec<char> = Vec::new();
439        let font = self.font.clone();
440        for member in self.members.iter_mut().flatten() {
441            member.text.set_vector_font(font.clone());
442            let info = member.text.sync();
443            for glyph in &info.glyphs {
444                if glyph.ch != ' ' && !chars.contains(&glyph.ch) {
445                    chars.push(glyph.ch);
446                }
447            }
448        }
449        let added = self.atlas.ensure_glyphs(font.as_deref(), chars);
450
451        // Pass 2: pack, in member order then glyph order. Member state is
452        // copied out first so the atlas can be borrowed mutably below
453        // (`get_glyph` memoises, so it takes `&mut self`).
454        let mut glyph_index = 0usize;
455        let mut truncated_from = None;
456
457        for m in 0..self.member_count {
458            let Some(member) = self.members[m].as_ref() else {
459                continue;
460            };
461            let Some(info) = member.text.text_render_info() else {
462                continue;
463            };
464
465            let glyph_start = glyph_index;
466            let glyph_count = info.glyph_count;
467
468            if glyph_index + glyph_count > self.max_glyph_count {
469                // `console.warn( '… maxGlyphCount … exceeded; truncating.' )`
470                truncated_from = Some(m);
471                break;
472            }
473
474            let glyphs: Vec<char> = info.glyphs.iter().map(|g| g.ch).collect();
475            let bounds = info.glyph_bounds.clone();
476            let color = member.text.color;
477            let opacity = member.text.opacity();
478
479            {
480                let member = self.members[m]
481                    .as_mut()
482                    .expect("sdf-text: the loop only walks registered members");
483                member.glyph_start = glyph_start;
484                member.glyph_count = glyph_count;
485            }
486            // `t.updateMatrixWorld()`
487            let world = {
488                let node = self.members[m]
489                    .as_ref()
490                    .expect("sdf-text: the loop only walks registered members")
491                    .node
492                    .clone();
493                node.update_matrix_world(false);
494                let world = node.borrow().matrix_world;
495                world
496            };
497            self.write_glyph_matrices(&world, glyph_start, glyph_count);
498
499            for (g, &glyph) in glyphs.iter().enumerate().take(glyph_count) {
500                let gi = glyph_start + g;
501                let bi = g * 4;
502                let (bx0, by0, bx1, by1) =
503                    (bounds[bi], bounds[bi + 1], bounds[bi + 2], bounds[bi + 3]);
504
505                if glyph != ' ' {
506                    let metrics = self.atlas.get_glyph(font.as_deref(), glyph);
507
508                    // `uvRect.viewBox ?? [ 0, 0, 1, 1 ]`, with a degenerate box
509                    // falling back to the whole tile.
510                    let vb = metrics.view_box;
511                    let vb = if vb[2] > vb[0] && vb[3] > vb[1] {
512                        vb
513                    } else {
514                        [0.0, 0.0, 1.0, 1.0]
515                    };
516
517                    // Grow the quad and the sampled sub-rect by the same
518                    // fraction of their own size, so the mapping stays ink↔ink
519                    // while the SDF margin the halo lives in is revealed.
520                    let pad = GLYPH_QUAD_PAD as f32;
521                    let bw = bx1 - bx0;
522                    let bh = by1 - by0;
523                    self.glyph_bounds[gi * 4] = bx0 - bw * pad;
524                    self.glyph_bounds[gi * 4 + 1] = by0 - bh * pad;
525                    self.glyph_bounds[gi * 4 + 2] = bx1 + bw * pad;
526                    self.glyph_bounds[gi * 4 + 3] = by1 + bh * pad;
527
528                    let pad = GLYPH_QUAD_PAD;
529                    let vbw = vb[2] - vb[0];
530                    let vbh = vb[3] - vb[1];
531                    let su0 = (vb[0] - vbw * pad).max(0.0);
532                    let sv0 = (vb[1] - vbh * pad).max(0.0);
533                    let su1 = (vb[2] + vbw * pad).min(1.0);
534                    let sv1 = (vb[3] + vbh * pad).min(1.0);
535
536                    self.glyph_uv[gi * 4] = (metrics.u + su0 * metrics.w) as f32;
537                    self.glyph_uv[gi * 4 + 1] = (metrics.v + sv0 * metrics.h) as f32;
538                    self.glyph_uv[gi * 4 + 2] = ((su1 - su0) * metrics.w) as f32;
539                    self.glyph_uv[gi * 4 + 3] = ((sv1 - sv0) * metrics.h) as f32;
540                } else {
541                    // A blank glyph keeps its unpadded bounds and gets a zero UV
542                    // rect, but still consumes an instance: `aGlyphUV.z == 0` is
543                    // what the shader's `isBlank` tests, and the instance counts
544                    // have to match the JS or the painter order shifts (§5.4).
545                    self.glyph_bounds[gi * 4] = bx0;
546                    self.glyph_bounds[gi * 4 + 1] = by0;
547                    self.glyph_bounds[gi * 4 + 2] = bx1;
548                    self.glyph_bounds[gi * 4 + 3] = by1;
549
550                    self.glyph_uv[gi * 4] = 0.0;
551                    self.glyph_uv[gi * 4 + 1] = 0.0;
552                    self.glyph_uv[gi * 4 + 2] = 0.0;
553                    self.glyph_uv[gi * 4 + 3] = 0.0;
554                }
555
556                self.colors[gi * 3] = color[0] as f32;
557                self.colors[gi * 3 + 1] = color[1] as f32;
558                self.colors[gi * 3 + 2] = color[2] as f32;
559                self.opacities[gi] = opacity as f32;
560
561                glyph_index += 1;
562            }
563        }
564
565        if let Some(m) = truncated_from {
566            eprintln!(
567                "BatchedText: maxGlyphCount ({}) exceeded; truncating at member {m}.",
568                self.max_glyph_count
569            );
570        }
571
572        self.glyph_count = glyph_index;
573        self.set_count(glyph_index);
574
575        if added {
576            self.texture = atlas_texture(&self.atlas);
577        }
578
579        // `BatchedMesh.computeBoundingSphere()`: without it the batch node is
580        // culled as a point at its own origin and a batch whose members sit far
581        // from it renders nothing at all (#42).
582        self.update_bounding_sphere();
583
584        // The four `needsUpdate = true` flags: the nodes holding the arrays are
585        // rebuilt around fresh copies.
586        self.build_material();
587    }
588
589    /// The batch's own bounding sphere, over every glyph quad of every member
590    /// in the batch node's space — three.js' `BatchedMesh.computeBoundingSphere`
591    /// / `InstancedMesh.computeBoundingSphere`, which the frustum cull prefers
592    /// to the geometry's.
593    ///
594    /// `InstancedMesh::compute_bounding_sphere` would spread the *geometry's*
595    /// sphere through the instance matrices; that is the unit
596    /// `PlaneGeometry( 1, 1 )` here, and the quad a glyph actually covers comes
597    /// from `positionNode` over `aGlyphBounds`. So the corners are taken from
598    /// the packed bounds and pushed through the member's `matrixWorld`, which is
599    /// what the instance matrix holds.
600    fn update_bounding_sphere(&mut self) {
601        let mut points: Vec<Vector3> = Vec::new();
602        for member in self.members.iter().flatten() {
603            let (start, count) = (member.glyph_start, member.glyph_count);
604            // A member past the `maxGlyphCount` truncation point has stale slice
605            // bounds; its glyphs are not drawn, so they are not bounded either.
606            if count == 0 || start + count > self.glyph_count {
607                continue;
608            }
609            let world = member.node.borrow().matrix_world;
610            for g in start..start + count {
611                let b = &self.glyph_bounds[g * 4..g * 4 + 4];
612                for (x, y) in [(b[0], b[1]), (b[2], b[1]), (b[0], b[3]), (b[2], b[3])] {
613                    let mut corner = Vector3::new(x as f64, y as f64, 0.0);
614                    corner.apply_matrix4(&world);
615                    points.push(corner);
616                }
617            }
618        }
619
620        let sphere = if points.is_empty() {
621            // Nothing packed: `boundingSphere` stays `null` and the geometry's
622            // sphere stands in, as it did before the first `sync()`.
623            None
624        } else {
625            let mut sphere = Sphere::default();
626            sphere.set_from_points(&points, None);
627            Some(sphere)
628        };
629
630        let mut object = self.node.borrow_mut();
631        if let Some(instanced) = object.payload.instanced_mesh_mut() {
632            instanced.bounding_sphere = sphere;
633        }
634    }
635
636    /// The batch's bounding sphere as [`BatchedText::sync`] last computed it, in
637    /// the batch node's own space. `None` before the first `sync()` that packs a
638    /// glyph.
639    pub fn bounding_sphere(&self) -> Option<Sphere> {
640        self.node
641            .borrow()
642            .payload
643            .instanced_mesh()
644            .and_then(|instanced| instanced.bounding_sphere)
645    }
646
647    /// `this.count = n`.
648    ///
649    /// `instanceMatrix` keeps its full `maxGlyphCount` length: `InstanceNode`
650    /// sizes the uniform-or-attribute decision on `instanceMatrix.count`, not on
651    /// the draw count, so trimming the array would flip that branch per frame.
652    fn set_count(&mut self, count: usize) {
653        let mut object = self.node.borrow_mut();
654        if let Some(instanced) = object.payload.instanced_mesh_mut() {
655            instanced.count = count;
656        }
657    }
658
659    /// `buildMaterial( material )`.
660    fn build_material(&mut self) {
661        if let Some(built) = &self.built {
662            if *built.glyph_uv == self.glyph_uv
663                && *built.glyph_bounds == self.glyph_bounds
664                && *built.colors == self.colors
665                && *built.opacities == self.opacities
666                && built.outline_width == self.outline_width
667                && built.outline_color == self.outline_color
668                && built.texture_id == self.texture.id()
669            {
670                return;
671            }
672        }
673
674        let uv_data = Rc::new(self.glyph_uv.clone());
675        let bounds_data = Rc::new(self.glyph_bounds.clone());
676        let color_data = Rc::new(self.colors.clone());
677        let opacity_data = Rc::new(self.opacities.clone());
678        self.built = Some(BuiltInputs {
679            glyph_uv: uv_data.clone(),
680            glyph_bounds: bounds_data.clone(),
681            colors: color_data.clone(),
682            opacities: opacity_data.clone(),
683            outline_width: self.outline_width,
684            outline_color: self.outline_color,
685            texture_id: self.texture.id(),
686        });
687
688        // `attribute( 'aGlyphUV', 'vec4' )` and friends.
689        let a_glyph_uv = tsl::instanced_data_attribute(&uv_data, 4, 0, Type::Vec4);
690        let a_glyph_bounds = tsl::instanced_data_attribute(&bounds_data, 4, 0, Type::Vec4);
691        let a_color = tsl::instanced_data_attribute(&color_data, 3, 0, Type::Vec3);
692        let a_opacity = tsl::instanced_data_attribute(&opacity_data, 1, 0, Type::F32);
693
694        let outline_width = tsl::uniform_value(Type::F32, vec![self.outline_width]);
695        let halo = self.outline_color.unwrap_or(Color::new(0.0, 0.0, 0.0));
696        let outline_color_uniform = tsl::uniform_value(Type::Vec3, vec![halo.r, halo.g, halo.b]);
697        let outline_color_mix = tsl::uniform_value(
698            Type::F32,
699            vec![if self.outline_color.is_some() {
700                1.0
701            } else {
702                0.0
703            }],
704        );
705
706        let quad_uv = tsl::uv();
707
708        // positionNode = vec3( mix( b.x, b.z, st.x ), mix( b.y, b.w, st.y ), 0 )
709        let position_node = tsl::join(
710            Type::Vec3,
711            vec![
712                tsl::mix(a_glyph_bounds.x(), a_glyph_bounds.z(), quad_uv.x()),
713                tsl::mix(a_glyph_bounds.y(), a_glyph_bounds.w(), quad_uv.y()),
714                tsl::float(0.0),
715            ],
716        );
717
718        // The JS builds a `vec4` and swizzles `.xy`; the two zero lanes are
719        // dead, so only the `vec2` is built here. The atlas is Y-down, hence the
720        // `1 - uv.y`.
721        let atlas_uv = tsl::join(
722            Type::Vec2,
723            vec![
724                a_glyph_uv.x().add(quad_uv.x().mul(a_glyph_uv.z())),
725                a_glyph_uv
726                    .y()
727                    .add(tsl::float(1.0).sub(quad_uv.y()).mul(a_glyph_uv.w())),
728            ],
729        );
730
731        let sdf_value = tsl::texture_uv(&self.texture, atlas_uv).x();
732        let edge = tsl::float(0.5);
733        let aa_width = tsl::fwidth(sdf_value.clone()).mul(0.5);
734
735        let fill_alpha = tsl::smoothstep(
736            edge.sub(aa_width.clone()),
737            edge.add(aa_width.clone()),
738            sdf_value.clone(),
739        );
740
741        let outline_edge = edge.sub(outline_width);
742        let outline_alpha = tsl::smoothstep(
743            outline_edge.sub(aa_width.clone()),
744            outline_edge.add(aa_width),
745            sdf_value,
746        );
747        let outline_only = tsl::max(outline_alpha.sub(fill_alpha.clone()), tsl::float(0.0));
748
749        let is_blank = a_glyph_uv.z().equal(tsl::float(0.0));
750        let alpha = is_blank
751            .select(tsl::float(0.0), tsl::max(fill_alpha.clone(), outline_only))
752            .mul(a_opacity);
753
754        // Outline pixels take the halo colour (when set); fill pixels keep the
755        // per-member colour, with the SDF fill coverage blending the boundary.
756        let halo_rgb = tsl::mix(a_color.clone(), outline_color_uniform, outline_color_mix);
757        let rgb = tsl::mix(halo_rgb, a_color, fill_alpha);
758
759        let color_node: NodeRef = tsl::join(Type::Vec4, vec![rgb, alpha]);
760
761        let mut object = self.node.borrow_mut();
762        let material = object
763            .payload
764            .mesh_mut()
765            .and_then(|mesh| mesh.material.as_mut())
766            .expect("sdf-text: BatchedText always has a material");
767        material.position_node = Some(position_node);
768        material.color_node = Some(color_node);
769        // `material.needsUpdate = true`: the nodes above close over fresh
770        // copies of the arrays, and the renderer keys the built program on the
771        // material's version — without the bump it would keep drawing the
772        // previous `sync()`'s glyphs.
773        material.set_needs_update();
774    }
775}
776
777/// `new THREE.DataTexture( atlasData, atlasSize, atlasSize, RedFormat,
778/// FloatType )` with `minFilter = magFilter = LinearFilter` — the bilinear
779/// filtering is load-bearing (it is what makes the SDF a *field* rather than a
780/// staircase), and the texture must not be tagged sRGB (plan §5.3).
781fn atlas_texture(atlas: &VectorFontAtlas) -> Texture {
782    Texture::data_r32float(atlas.atlas_size(), atlas.atlas_size(), atlas.atlas_data())
783}