use std::rc::Rc;
use three_rs::core::Object3D;
use three_rs::geometries::plane_geometry;
use three_rs::materials::Side;
use three_rs::math::{Color, Matrix4, Sphere, Vector3};
use three_rs::nodes::tsl;
use three_rs::nodes::{NodeRef, Type};
use three_rs::objects::InstancedMesh;
use three_rs::textures::Texture;
use three_rs::{MeshBasicNodeMaterial, ObjectRef};
use crate::text::Text;
use crate::vector_font::VectorFont;
use crate::vector_font_atlas::VectorFontAtlas;
pub const GLYPH_QUAD_PAD: f64 = 0.12;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct BatchedTextOptions {
pub outline_width: f64,
pub outline_color: Option<Color>,
pub atlas_size: u32,
}
impl Default for BatchedTextOptions {
fn default() -> Self {
Self {
outline_width: 0.03,
outline_color: None,
atlas_size: 1024,
}
}
}
struct Member {
text: Text,
node: ObjectRef,
glyph_start: usize,
glyph_count: usize,
}
pub struct BatchedText {
node: ObjectRef,
pub atlas: VectorFontAtlas,
font: Option<Rc<VectorFont>>,
max_text_count: usize,
max_glyph_count: usize,
members: Vec<Option<Member>>,
member_count: usize,
glyph_count: usize,
outline_width: f64,
outline_color: Option<Color>,
glyph_uv: Vec<f32>,
glyph_bounds: Vec<f32>,
colors: Vec<f32>,
opacities: Vec<f32>,
texture: Texture,
built: Option<BuiltInputs>,
}
struct BuiltInputs {
glyph_uv: Rc<Vec<f32>>,
glyph_bounds: Rc<Vec<f32>>,
colors: Rc<Vec<f32>>,
opacities: Rc<Vec<f32>>,
outline_width: f64,
outline_color: Option<Color>,
texture_id: usize,
}
impl BatchedText {
pub fn new(max_text_count: usize, max_glyph_count: usize, options: BatchedTextOptions) -> Self {
let plane = Rc::new(plane_geometry(1.0, 1.0, 1, 1));
let material = MeshBasicNodeMaterial {
name: "BatchedText",
transparent: true,
depth_write: false,
side: Side::Double,
..Default::default()
};
let node = InstancedMesh::new(plane, material, max_glyph_count);
node.borrow_mut().object_type = "BatchedText";
let atlas = VectorFontAtlas::new(options.atlas_size);
let texture = atlas_texture(&atlas);
let mut batch = Self {
node,
atlas,
font: None,
max_text_count,
max_glyph_count,
members: (0..max_text_count).map(|_| None).collect(),
member_count: 0,
glyph_count: 0,
outline_width: options.outline_width,
outline_color: options.outline_color,
glyph_uv: vec![0.0; max_glyph_count * 4],
glyph_bounds: vec![0.0; max_glyph_count * 4],
colors: vec![0.0; max_glyph_count * 3],
opacities: vec![1.0; max_glyph_count],
texture,
built: None,
};
batch.build_material();
batch.set_count(0);
batch
}
pub fn node(&self) -> &ObjectRef {
&self.node
}
pub fn count(&self) -> usize {
self.glyph_count
}
pub fn member_count(&self) -> usize {
self.member_count
}
pub fn max_glyph_count(&self) -> usize {
self.max_glyph_count
}
pub fn texture(&self) -> &Texture {
&self.texture
}
pub fn set_font(&mut self, font: Rc<VectorFont>) {
self.font = Some(font);
self.atlas.reset();
for member in self.members.iter_mut().flatten() {
member.text.mark_needs_sync();
}
}
pub fn font(&self) -> Option<&Rc<VectorFont>> {
self.font.as_ref()
}
pub fn reset_atlas(&mut self) {
self.atlas.reset();
for member in self.members.iter_mut().flatten() {
member.text.mark_needs_sync();
}
self.sync();
}
pub fn add_text(&mut self, mut text: Text) -> Option<usize> {
if self.member_count >= self.max_text_count {
return None;
}
let id = self.member_count;
self.member_count += 1;
text.set_vector_mode(true);
text.set_vector_font(self.font.clone());
text.mark_needs_sync();
self.members[id] = Some(Member {
text,
node: Object3D::new_node(),
glyph_start: 0,
glyph_count: 0,
});
Some(id)
}
pub fn remove_text(&mut self, member_id: usize) {
if self.members.get(member_id).map(Option::is_some) != Some(true) {
return;
}
self.members[member_id] = None;
if member_id + 1 == self.member_count {
self.member_count -= 1;
}
}
pub fn text_at(&self, member_id: usize) -> Option<&Text> {
self.members.get(member_id)?.as_ref().map(|m| &m.text)
}
pub fn text_at_mut(&mut self, member_id: usize) -> Option<&mut Text> {
self.members
.get_mut(member_id)?
.as_mut()
.map(|m| &mut m.text)
}
pub fn member_node(&self, member_id: usize) -> Option<&ObjectRef> {
self.members.get(member_id)?.as_ref().map(|m| &m.node)
}
pub fn member_glyphs(&self, member_id: usize) -> Option<(usize, usize)> {
self.members
.get(member_id)?
.as_ref()
.map(|m| (m.glyph_start, m.glyph_count))
}
pub fn glyph_uv_array(&self) -> &[f32] {
&self.glyph_uv
}
pub fn glyph_bounds_array(&self) -> &[f32] {
&self.glyph_bounds
}
pub fn color_array(&self) -> &[f32] {
&self.colors
}
pub fn opacity_array(&self) -> &[f32] {
&self.opacities
}
pub fn set_color_at(&mut self, member_id: usize, color: Color) {
let Some(Some(member)) = self.members.get_mut(member_id) else {
return;
};
member.text.color = [color.r, color.g, color.b];
let (start, count) = (member.glyph_start, member.glyph_count);
if count == 0 {
return;
}
for g in start..start + count {
self.colors[g * 3] = color.r as f32;
self.colors[g * 3 + 1] = color.g as f32;
self.colors[g * 3 + 2] = color.b as f32;
}
self.build_material();
}
pub fn set_opacity_at(&mut self, member_id: usize, opacity: f64) {
let Some(Some(member)) = self.members.get_mut(member_id) else {
return;
};
member.text.set_opacity(opacity);
let (start, count) = (member.glyph_start, member.glyph_count);
if count == 0 {
return;
}
for g in start..start + count {
self.opacities[g] = opacity as f32;
}
self.build_material();
}
pub fn outline_color(&self) -> Option<Color> {
self.outline_color
}
pub fn set_outline_color(&mut self, color: Option<Color>) {
self.outline_color = color;
self.build_material();
}
pub fn outline_width(&self) -> f64 {
self.outline_width
}
pub fn set_matrix_at(&mut self, member_id: usize, matrix: &Matrix4) {
let is_member = member_id < self.member_count
&& self.members.get(member_id).map(Option::is_some) == Some(true);
if !is_member {
self.node.borrow_mut().set_matrix_at(member_id, matrix);
return;
}
let member = self.members[member_id]
.as_ref()
.expect("sdf-text: is_member means member_id names a registered member");
member.node.borrow_mut().matrix_world = *matrix;
let (start, count) = (member.glyph_start, member.glyph_count);
if member.text.text_render_info().is_none() || count == 0 {
return;
}
self.write_glyph_matrices(matrix, start, count);
self.update_bounding_sphere();
}
fn write_glyph_matrices(&mut self, world: &Matrix4, start: usize, count: usize) {
let mut object = self.node.borrow_mut();
for g in 0..count {
object.set_matrix_at(start + g, world);
}
}
pub fn sync(&mut self) {
let mut chars: Vec<char> = Vec::new();
let font = self.font.clone();
for member in self.members.iter_mut().flatten() {
member.text.set_vector_font(font.clone());
let info = member.text.sync();
for glyph in &info.glyphs {
if glyph.ch != ' ' && !chars.contains(&glyph.ch) {
chars.push(glyph.ch);
}
}
}
let added = self.atlas.ensure_glyphs(font.as_deref(), chars);
let mut glyph_index = 0usize;
let mut truncated_from = None;
for m in 0..self.member_count {
let Some(member) = self.members[m].as_ref() else {
continue;
};
let Some(info) = member.text.text_render_info() else {
continue;
};
let glyph_start = glyph_index;
let glyph_count = info.glyph_count;
if glyph_index + glyph_count > self.max_glyph_count {
truncated_from = Some(m);
break;
}
let glyphs: Vec<char> = info.glyphs.iter().map(|g| g.ch).collect();
let bounds = info.glyph_bounds.clone();
let color = member.text.color;
let opacity = member.text.opacity();
{
let member = self.members[m]
.as_mut()
.expect("sdf-text: the loop only walks registered members");
member.glyph_start = glyph_start;
member.glyph_count = glyph_count;
}
let world = {
let node = self.members[m]
.as_ref()
.expect("sdf-text: the loop only walks registered members")
.node
.clone();
node.update_matrix_world(false);
let world = node.borrow().matrix_world;
world
};
self.write_glyph_matrices(&world, glyph_start, glyph_count);
for (g, &glyph) in glyphs.iter().enumerate().take(glyph_count) {
let gi = glyph_start + g;
let bi = g * 4;
let (bx0, by0, bx1, by1) =
(bounds[bi], bounds[bi + 1], bounds[bi + 2], bounds[bi + 3]);
if glyph != ' ' {
let metrics = self.atlas.get_glyph(font.as_deref(), glyph);
let vb = metrics.view_box;
let vb = if vb[2] > vb[0] && vb[3] > vb[1] {
vb
} else {
[0.0, 0.0, 1.0, 1.0]
};
let pad = GLYPH_QUAD_PAD as f32;
let bw = bx1 - bx0;
let bh = by1 - by0;
self.glyph_bounds[gi * 4] = bx0 - bw * pad;
self.glyph_bounds[gi * 4 + 1] = by0 - bh * pad;
self.glyph_bounds[gi * 4 + 2] = bx1 + bw * pad;
self.glyph_bounds[gi * 4 + 3] = by1 + bh * pad;
let pad = GLYPH_QUAD_PAD;
let vbw = vb[2] - vb[0];
let vbh = vb[3] - vb[1];
let su0 = (vb[0] - vbw * pad).max(0.0);
let sv0 = (vb[1] - vbh * pad).max(0.0);
let su1 = (vb[2] + vbw * pad).min(1.0);
let sv1 = (vb[3] + vbh * pad).min(1.0);
self.glyph_uv[gi * 4] = (metrics.u + su0 * metrics.w) as f32;
self.glyph_uv[gi * 4 + 1] = (metrics.v + sv0 * metrics.h) as f32;
self.glyph_uv[gi * 4 + 2] = ((su1 - su0) * metrics.w) as f32;
self.glyph_uv[gi * 4 + 3] = ((sv1 - sv0) * metrics.h) as f32;
} else {
self.glyph_bounds[gi * 4] = bx0;
self.glyph_bounds[gi * 4 + 1] = by0;
self.glyph_bounds[gi * 4 + 2] = bx1;
self.glyph_bounds[gi * 4 + 3] = by1;
self.glyph_uv[gi * 4] = 0.0;
self.glyph_uv[gi * 4 + 1] = 0.0;
self.glyph_uv[gi * 4 + 2] = 0.0;
self.glyph_uv[gi * 4 + 3] = 0.0;
}
self.colors[gi * 3] = color[0] as f32;
self.colors[gi * 3 + 1] = color[1] as f32;
self.colors[gi * 3 + 2] = color[2] as f32;
self.opacities[gi] = opacity as f32;
glyph_index += 1;
}
}
if let Some(m) = truncated_from {
eprintln!(
"BatchedText: maxGlyphCount ({}) exceeded; truncating at member {m}.",
self.max_glyph_count
);
}
self.glyph_count = glyph_index;
self.set_count(glyph_index);
if added {
self.texture = atlas_texture(&self.atlas);
}
self.update_bounding_sphere();
self.build_material();
}
fn update_bounding_sphere(&mut self) {
let mut points: Vec<Vector3> = Vec::new();
for member in self.members.iter().flatten() {
let (start, count) = (member.glyph_start, member.glyph_count);
if count == 0 || start + count > self.glyph_count {
continue;
}
let world = member.node.borrow().matrix_world;
for g in start..start + count {
let b = &self.glyph_bounds[g * 4..g * 4 + 4];
for (x, y) in [(b[0], b[1]), (b[2], b[1]), (b[0], b[3]), (b[2], b[3])] {
let mut corner = Vector3::new(x as f64, y as f64, 0.0);
corner.apply_matrix4(&world);
points.push(corner);
}
}
}
let sphere = if points.is_empty() {
None
} else {
let mut sphere = Sphere::default();
sphere.set_from_points(&points, None);
Some(sphere)
};
let mut object = self.node.borrow_mut();
if let Some(instanced) = object.payload.instanced_mesh_mut() {
instanced.bounding_sphere = sphere;
}
}
pub fn bounding_sphere(&self) -> Option<Sphere> {
self.node
.borrow()
.payload
.instanced_mesh()
.and_then(|instanced| instanced.bounding_sphere)
}
fn set_count(&mut self, count: usize) {
let mut object = self.node.borrow_mut();
if let Some(instanced) = object.payload.instanced_mesh_mut() {
instanced.count = count;
}
}
fn build_material(&mut self) {
if let Some(built) = &self.built {
if *built.glyph_uv == self.glyph_uv
&& *built.glyph_bounds == self.glyph_bounds
&& *built.colors == self.colors
&& *built.opacities == self.opacities
&& built.outline_width == self.outline_width
&& built.outline_color == self.outline_color
&& built.texture_id == self.texture.id()
{
return;
}
}
let uv_data = Rc::new(self.glyph_uv.clone());
let bounds_data = Rc::new(self.glyph_bounds.clone());
let color_data = Rc::new(self.colors.clone());
let opacity_data = Rc::new(self.opacities.clone());
self.built = Some(BuiltInputs {
glyph_uv: uv_data.clone(),
glyph_bounds: bounds_data.clone(),
colors: color_data.clone(),
opacities: opacity_data.clone(),
outline_width: self.outline_width,
outline_color: self.outline_color,
texture_id: self.texture.id(),
});
let a_glyph_uv = tsl::instanced_data_attribute(&uv_data, 4, 0, Type::Vec4);
let a_glyph_bounds = tsl::instanced_data_attribute(&bounds_data, 4, 0, Type::Vec4);
let a_color = tsl::instanced_data_attribute(&color_data, 3, 0, Type::Vec3);
let a_opacity = tsl::instanced_data_attribute(&opacity_data, 1, 0, Type::F32);
let outline_width = tsl::uniform_value(Type::F32, vec![self.outline_width]);
let halo = self.outline_color.unwrap_or(Color::new(0.0, 0.0, 0.0));
let outline_color_uniform = tsl::uniform_value(Type::Vec3, vec![halo.r, halo.g, halo.b]);
let outline_color_mix = tsl::uniform_value(
Type::F32,
vec![if self.outline_color.is_some() {
1.0
} else {
0.0
}],
);
let quad_uv = tsl::uv();
let position_node = tsl::join(
Type::Vec3,
vec![
tsl::mix(a_glyph_bounds.x(), a_glyph_bounds.z(), quad_uv.x()),
tsl::mix(a_glyph_bounds.y(), a_glyph_bounds.w(), quad_uv.y()),
tsl::float(0.0),
],
);
let atlas_uv = tsl::join(
Type::Vec2,
vec![
a_glyph_uv.x().add(quad_uv.x().mul(a_glyph_uv.z())),
a_glyph_uv
.y()
.add(tsl::float(1.0).sub(quad_uv.y()).mul(a_glyph_uv.w())),
],
);
let sdf_value = tsl::texture_uv(&self.texture, atlas_uv).x();
let edge = tsl::float(0.5);
let aa_width = tsl::fwidth(sdf_value.clone()).mul(0.5);
let fill_alpha = tsl::smoothstep(
edge.sub(aa_width.clone()),
edge.add(aa_width.clone()),
sdf_value.clone(),
);
let outline_edge = edge.sub(outline_width);
let outline_alpha = tsl::smoothstep(
outline_edge.sub(aa_width.clone()),
outline_edge.add(aa_width),
sdf_value,
);
let outline_only = tsl::max(outline_alpha.sub(fill_alpha.clone()), tsl::float(0.0));
let is_blank = a_glyph_uv.z().equal(tsl::float(0.0));
let alpha = is_blank
.select(tsl::float(0.0), tsl::max(fill_alpha.clone(), outline_only))
.mul(a_opacity);
let halo_rgb = tsl::mix(a_color.clone(), outline_color_uniform, outline_color_mix);
let rgb = tsl::mix(halo_rgb, a_color, fill_alpha);
let color_node: NodeRef = tsl::join(Type::Vec4, vec![rgb, alpha]);
let mut object = self.node.borrow_mut();
let material = object
.payload
.mesh_mut()
.and_then(|mesh| mesh.material.as_mut())
.expect("sdf-text: BatchedText always has a material");
material.position_node = Some(position_node);
material.color_node = Some(color_node);
material.set_needs_update();
}
}
fn atlas_texture(atlas: &VectorFontAtlas) -> Texture {
Texture::data_r32float(atlas.atlas_size(), atlas.atlas_size(), atlas.atlas_data())
}