native2d: Vektor-Text (Glyph-Umrisse als Dreiecke, instanziert, drehbar) statt SVG-Overlay fuer einfache Texte

This commit is contained in:
karim committed 2026-10-20 00:01:13 +02:00
1 parent 8c3655956c
commit d663d6615c
11 files changed
+783 -5

No files matched your search

+7 -1
View File
@@ -32,7 +32,7 @@ default = []
# Laufzeit dynamisch), rendert aber nur mit einer aktiven Grafik-Session.
# glyphon = GPU-Glyphen-Atlas fuer ECHTE TrueType-Schrift (cosmic-text) —
# gehoert bewusst in die GPU-Schicht, die serde-only-Default-Schicht bleibt fontfrei.
render = ["dep:wgpu", "dep:bytemuck", "dep:pollster", "dep:glyphon"]
render = ["dep:wgpu", "dep:bytemuck", "dep:pollster", "dep:glyphon", "dep:fontdb", "dep:ttf-parser", "dep:lyon_tessellation"]
# Fenster-Spike (winit) inkl. lauffaehigem Binary. Braucht Wayland/X11 + eine
# Display-Session zur visuellen Verifikation.
@@ -75,6 +75,12 @@ pollster = { version = "0.4", optional = true }
# Echte TrueType-Glyphen ueber einen GPU-Atlas (cosmic-text + etagere). Version
# an wgpu gekoppelt: die 0.11er-Reihe ist die zu wgpu 29 passende.
glyphon = { version = "0.11", optional = true }
# Vektor-Text (src/vtext.rs): Systemschrift suchen (fontdb), Glyphen-Umrisse lesen
# (ttf-parser) und einmal je Glyphe zu Dreiecken tessellieren (lyon). Versionen an
# die von cosmic-text/glyphon bereits genutzten gekoppelt (keine Duplikate).
fontdb = { version = "0.23", optional = true }
ttf-parser = { version = "0.25", optional = true }
lyon_tessellation = { version = "1", optional = true }
# --- Headless-PNG-Export (nur mit Feature "headless") ------------------------
# Nur der PNG-Codec noetig (kein volles Format-Universum) -> default-features aus.
+283
View File
@@ -64,6 +64,88 @@ fn fs_main() -> @location(0) vec4<f32> {
}
"#;
/// Vektor-Text: Glyphen-Dreiecke (em-Einheiten) pro Instanz positioniert, skaliert
/// und gedreht. `pos` ist relativ zur Ansichtsmitte (f64 → f32 auf der CPU).
const TEXT_WGSL: &str = r#"
struct Globals {
view_proj : mat4x4<f32>,
color : vec4<f32>,
viewport_px : vec2<f32>,
stroke_px : f32,
stroke_scale : f32,
};
@group(0) @binding(0) var<uniform> globals : Globals;
struct VsIn {
@location(0) g : vec2<f32>, // Glyphenpunkt in em (Y nach oben)
@location(1) pos : vec2<f32>, // Textanker (Bildschirm-Raum, relativ zur Ansichtsmitte)
@location(2) scale : f32, // em → Bildschirm-Einheiten (= Schrifthoehe)
@location(3) xoff : f32, // X-Versatz der Glyphe in em (Vorschub)
@location(4) cs : vec2<f32>, // (cos, sin) der Bildschirm-Drehung
@location(5) color : vec4<f32>,
};
struct VsOut {
@builtin(position) p : vec4<f32>,
@location(0) color : vec4<f32>,
};
@vertex
fn vs_main(in : VsIn) -> VsOut {
let lx = (in.xoff + in.g.x) * in.scale;
let ly = -in.g.y * in.scale;
let x = lx * in.cs.x - ly * in.cs.y;
let y = lx * in.cs.y + ly * in.cs.x;
var o : VsOut;
o.p = globals.view_proj * vec4<f32>(in.pos + vec2<f32>(x, y), 0.0, 1.0);
o.color = in.color;
return o;
}
@fragment
fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
return in.color;
}
"#;
/// Text-Eingabe aus der Webview (Bildschirm-Raum, doppelte Genauigkeit).
#[derive(Clone, Debug, serde::Deserialize)]
pub struct TextIn {
pub id: u32,
pub x: f64,
pub y: f64,
/// Schrifthoehe (= em) in Bildschirm-Einheiten.
pub size: f64,
/// Drehung in Bildschirm-Raum (Radiant, im Uhrzeigersinn positiv).
pub angle: f64,
pub color: [f32; 4],
pub text: String,
}
struct TextItem {
x: f64,
y: f64,
size: f64,
cs: [f32; 2],
color: [f32; 4],
glyphs: Vec<(u16, f32)>,
width_em: f32,
}
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct TextInst {
pos: [f32; 2],
scale: f32,
xoff: f32,
cs: [f32; 2],
color: [f32; 4],
}
/// Obergrenze gleichzeitig gezeichneter Texte; darueber bleiben die groessten.
const MAX_VISIBLE_TEXTS: usize = 6000;
/// Texte unter dieser Hoehe (Geraete-px) werden nicht gezeichnet.
const MIN_TEXT_PX: f64 = 2.0;
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct Globals {
@@ -124,6 +206,13 @@ pub struct ChunkRenderer {
msaa: Option<(wgpu::Texture, (u32, u32))>,
format: wgpu::TextureFormat,
pub clear: [f64; 3],
// --- Vektor-Text ---
text_pipeline: wgpu::RenderPipeline,
font: Option<crate::vtext::VectorFont>,
texts: HashMap<u32, TextItem>,
glyph_vbo: Option<wgpu::Buffer>,
glyph_ibo: Option<wgpu::Buffer>,
inst_buf: Option<(wgpu::Buffer, u64)>,
}
/// Aspekt-korrigierte Grenzen (left,right,bottom,top) wie `orthoBounds`.
@@ -242,7 +331,53 @@ impl ChunkRenderer {
},
"chunks.line.pipeline",
);
let text_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("chunks.text"),
source: wgpu::ShaderSource::Wgsl(TEXT_WGSL.into()),
});
let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("chunks.text.pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &text_module,
entry_point: Some("vs_main"),
buffers: &[
wgpu::VertexBufferLayout {
array_stride: 8,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![0 => Float32x2],
},
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<TextInst>() as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &wgpu::vertex_attr_array![1 => Float32x2, 2 => Float32, 3 => Float32, 4 => Float32x2, 5 => Float32x4],
},
],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &text_module,
entry_point: Some("fs_main"),
targets: &[Some(target.clone())],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState { count: SAMPLE_COUNT, mask: !0, alpha_to_coverage_enabled: false },
multiview_mask: None,
cache: None,
});
Self {
text_pipeline,
font: None,
texts: HashMap::new(),
glyph_vbo: None,
glyph_ibo: None,
inst_buf: None,
fill_pipeline,
line_pipeline,
bind_group_layout,
@@ -275,6 +410,89 @@ impl ChunkRenderer {
}
}
/// Texte einfuegen/ersetzen bzw. entfernen. `false`, wenn keine Schrift
/// verfuegbar ist (die Webview zeichnet die Texte dann selbst).
pub fn set_texts(&mut self, upsert: Vec<TextIn>, remove: &[u32]) -> bool {
if self.font.is_none() {
self.font = crate::vtext::VectorFont::system();
}
let Some(font) = self.font.as_ref() else { return false };
for id in remove {
self.texts.remove(id);
}
for t in upsert {
let (glyphs, width_em) = font.shape(&t.text);
self.texts.insert(
t.id,
TextItem {
x: t.x,
y: t.y,
size: t.size,
cs: [t.angle.cos() as f32, t.angle.sin() as f32],
color: t.color,
glyphs,
width_em,
},
);
}
true
}
pub fn text_count(&self) -> usize {
self.texts.len()
}
/// Sichtbare Texte dieses Frames als nach Glyphe gruppierte Instanzen.
/// Rueckgabe: Instanzen (nach Glyph-ID sortiert) + Gruppen (gid, Instanzbereich).
fn build_text_instances(
&mut self,
bounds: (f64, f64, f64, f64),
px_per_unit: f64,
) -> (Vec<TextInst>, Vec<(u16, std::ops::Range<u32>)>) {
let Some(font) = self.font.as_mut() else { return (Vec::new(), Vec::new()) };
let (left, right, bottom, top) = bounds;
let (cx, cy) = ((left + right) / 2.0, (top + bottom) / 2.0);
let mut vis: Vec<u32> = Vec::new();
for (id, t) in &self.texts {
if t.size * px_per_unit < MIN_TEXT_PX {
continue;
}
let reach = t.size * (t.width_em as f64 + 1.0);
if t.x + reach < left || t.x - reach > right || t.y + reach < top || t.y - reach > bottom {
continue;
}
vis.push(*id);
}
if vis.len() > MAX_VISIBLE_TEXTS {
// Nur die groessten behalten (wie bei Karten: wichtige Beschriftungen bleiben).
let mut sizes: Vec<f64> = vis.iter().map(|id| self.texts[id].size).collect();
let k = vis.len() - MAX_VISIBLE_TEXTS;
sizes.select_nth_unstable_by(k, |a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let threshold = sizes[k];
vis.retain(|id| self.texts[id].size >= threshold);
}
let mut tmp: Vec<(u16, TextInst)> = Vec::new();
for id in &vis {
let t = &self.texts[id];
let pos = [(t.x - cx) as f32, (t.y - cy) as f32];
for &(gid, xoff) in &t.glyphs {
if font.mesh(gid).is_none() {
continue;
}
tmp.push((gid, TextInst { pos, scale: t.size as f32, xoff, cs: t.cs, color: t.color }));
}
}
tmp.sort_by_key(|(g, _)| *g);
let mut groups: Vec<(u16, std::ops::Range<u32>)> = Vec::new();
for (i, (g, _)) in tmp.iter().enumerate() {
match groups.last_mut() {
Some((lg, r)) if lg == g => r.end = i as u32 + 1,
_ => groups.push((*g, i as u32..i as u32 + 1)),
}
}
(tmp.into_iter().map(|(_, i)| i).collect(), groups)
}
pub fn set_layout(&mut self, layout: Vec<ChunkGeom>) {
self.layout = layout;
}
@@ -330,6 +548,52 @@ impl ChunkRenderer {
}
}
// Vektor-Text dieses Frames (sichtbare Texte, nach Glyphe gruppiert).
let (text_insts, text_groups) = self.build_text_instances(bounds, meet);
let text_block = blocks.len() as u32;
if !text_groups.is_empty() {
let centre = [(bounds.0 + bounds.1) / 2.0, (bounds.3 + bounds.2) / 2.0];
blocks.push(Globals {
view_proj: projection(bounds, centre),
color: [0.0; 4],
viewport_px: vp,
stroke_px: 0.0,
stroke_scale: 1.0,
});
// Glyphen-Mesh-Puffer neu aufbauen, wenn neue Glyphen dazukamen.
if let Some(font) = self.font.as_mut() {
if font.dirty || self.glyph_vbo.is_none() {
self.glyph_vbo = Some(device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("chunks.glyph.vbo"),
contents: bytemuck::cast_slice(&font.verts),
usage: wgpu::BufferUsages::VERTEX,
}));
self.glyph_ibo = Some(device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("chunks.glyph.ibo"),
contents: bytemuck::cast_slice(&font.indices),
usage: wgpu::BufferUsages::INDEX,
}));
font.dirty = false;
}
}
let need = (text_insts.len() * std::mem::size_of::<TextInst>()) as u64;
if self.inst_buf.as_ref().map_or(true, |b| b.1 < need) {
let cap = need.next_power_of_two().max(64 * 1024);
self.inst_buf = Some((
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("chunks.text.inst"),
size: cap,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}),
cap,
));
}
if let Some((buf, _)) = &self.inst_buf {
queue.write_buffer(buf, 0, bytemuck::cast_slice(&text_insts));
}
}
// Uniform-Puffer bei Bedarf vergroessern, dann einmal schreiben.
let need = stride * blocks.len().max(1) as u64;
if self.uniform.as_ref().map_or(true, |u| u.2 < need) {
@@ -434,6 +698,25 @@ impl ChunkRenderer {
block += 1;
}
}
// Text zuoberst.
if let (false, Some(vbo), Some(ibo), Some((inst, _)), Some(font)) = (
text_groups.is_empty(),
&self.glyph_vbo,
&self.glyph_ibo,
&self.inst_buf,
self.font.as_ref(),
) {
pass.set_pipeline(&self.text_pipeline);
pass.set_bind_group(0, ubind, &[text_block * stride as u32]);
pass.set_vertex_buffer(0, vbo.slice(..));
pass.set_vertex_buffer(1, inst.slice(..));
pass.set_index_buffer(ibo.slice(..), wgpu::IndexFormat::Uint32);
for (gid, range) in &text_groups {
if let Some(m) = font.mesh_info(*gid) {
pass.draw_indexed(m.first_index..m.first_index + m.index_count, 0, range.clone());
}
}
}
}
queue.submit(Some(enc.finish()));
}
+4
View File
@@ -25,6 +25,10 @@ pub mod gpu;
#[cfg(feature = "render")]
pub mod chunks;
// Vektor-Text (Glyphen-Umrisse → Dreiecke, instanziert, drehbar).
#[cfg(feature = "render")]
pub mod vtext;
// Browser-Bindings (wasm32 + WebGPU), nur mit Feature "web". Setzt "render" voraus
// (dieselbe GPU-Schicht wie das native Fenster), fuegt aber KEINE winit-Abhaengigkeit
// hinzu — die Canvas dient direkt als wgpu-Surface.
+196
View File
@@ -0,0 +1,196 @@
// Vektor-Text: Glyphen-Umrisse einer Systemschrift werden EINMAL je Glyphe zu
// Dreiecken tesselliert (lyon) und danach instanziert gezeichnet — mit beliebiger
// Position, Groesse und DREHUNG (der Glyphen-Atlas-Text aus `glyphon` kann nicht
// drehen, Katastertexte sind aber oft gedreht).
//
// Bewusst einfach: Zeichenfolge → Glyph-IDs + Vorschub (hmtx), KEIN Kerning, kein
// komplexes Shaping (CAD-Beschriftungen: Zahlen, Strassen-/Flurnamen).
use std::collections::HashMap;
use std::sync::Arc;
use lyon_tessellation::geom::point;
use lyon_tessellation::path::Path;
use lyon_tessellation::{BuffersBuilder, FillOptions, FillRule, FillTessellator, FillVertex, VertexBuffers};
/// Indexbereich eines Glyphen-Meshes im gemeinsamen Index-Puffer.
#[derive(Clone, Copy, Debug)]
pub struct GlyphMesh {
pub first_index: u32,
pub index_count: u32,
}
pub struct VectorFont {
data: Arc<Vec<u8>>,
index: u32,
units_per_em: f32,
/// Gemeinsamer Vertex-/Index-Puffer aller bisher tessellierten Glyphen (em-Einheiten, Y nach oben).
pub verts: Vec<[f32; 2]>,
pub indices: Vec<u32>,
meshes: HashMap<u16, GlyphMesh>,
/// true, sobald `verts`/`indices` seit dem letzten Hochladen gewachsen sind.
pub dirty: bool,
}
struct PathSink {
b: lyon_tessellation::path::path::Builder,
open: bool,
s: f32,
}
impl ttf_parser::OutlineBuilder for PathSink {
fn move_to(&mut self, x: f32, y: f32) {
if self.open {
self.b.end(true);
}
self.b.begin(point(x * self.s, y * self.s));
self.open = true;
}
fn line_to(&mut self, x: f32, y: f32) {
self.b.line_to(point(x * self.s, y * self.s));
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
self.b.quadratic_bezier_to(point(x1 * self.s, y1 * self.s), point(x * self.s, y * self.s));
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
self.b.cubic_bezier_to(
point(x1 * self.s, y1 * self.s),
point(x2 * self.s, y2 * self.s),
point(x * self.s, y * self.s),
);
}
fn close(&mut self) {
if self.open {
self.b.end(true);
self.open = false;
}
}
}
impl VectorFont {
/// Sucht eine Systemschrift (Inter, sonst Sans-Serif, sonst irgendeine).
pub fn system() -> Option<Self> {
let mut db = fontdb::Database::new();
db.load_system_fonts();
let q = fontdb::Query {
families: &[
fontdb::Family::Name("Inter"),
fontdb::Family::Name("Helvetica Neue"),
fontdb::Family::Name("Helvetica"),
fontdb::Family::Name("Arial"),
fontdb::Family::SansSerif,
],
..Default::default()
};
let id = db.query(&q).or_else(|| db.faces().next().map(|f| f.id))?;
let (data, index) = db.with_face_data(id, |d, i| (d.to_vec(), i))?;
Self::from_bytes(data, index)
}
pub fn from_bytes(data: Vec<u8>, index: u32) -> Option<Self> {
let upem = {
let face = ttf_parser::Face::parse(&data, index).ok()?;
face.units_per_em() as f32
};
if upem <= 0.0 {
return None;
}
Some(Self {
data: Arc::new(data),
index,
units_per_em: upem,
verts: Vec::new(),
indices: Vec::new(),
meshes: HashMap::new(),
dirty: false,
})
}
/// Zeichen → (Glyph-ID, X-Versatz der Glyphe in em) plus Gesamtbreite in em.
pub fn shape(&self, text: &str) -> (Vec<(u16, f32)>, f32) {
let Ok(face) = ttf_parser::Face::parse(&self.data, self.index) else {
return (Vec::new(), 0.0);
};
let mut out = Vec::with_capacity(text.len());
let mut x = 0.0f32;
for ch in text.chars() {
let gid = face.glyph_index(ch).unwrap_or(ttf_parser::GlyphId(0));
let adv = face.glyph_hor_advance(gid).unwrap_or((self.units_per_em * 0.5) as u16) as f32 / self.units_per_em;
if ch != ' ' && ch != '\u{a0}' {
out.push((gid.0, x));
}
x += adv;
}
(out, x)
}
/// Bereits tesselliertes Mesh einer Glyphe (nur lesend).
pub fn mesh_info(&self, gid: u16) -> Option<GlyphMesh> {
self.meshes.get(&gid).copied().filter(|m| m.index_count > 0)
}
/// Mesh einer Glyphe (beim ersten Bedarf tesselliert). Leere Glyphen → `None`.
pub fn mesh(&mut self, gid: u16) -> Option<GlyphMesh> {
if let Some(m) = self.meshes.get(&gid) {
return if m.index_count == 0 { None } else { Some(*m) };
}
let mesh = self.tessellate(gid);
self.meshes.insert(gid, mesh);
if mesh.index_count == 0 { None } else { Some(mesh) }
}
fn tessellate(&mut self, gid: u16) -> GlyphMesh {
let empty = GlyphMesh { first_index: self.indices.len() as u32, index_count: 0 };
let Ok(face) = ttf_parser::Face::parse(&self.data, self.index) else {
return empty;
};
let mut sink = PathSink { b: Path::builder(), open: false, s: 1.0 / self.units_per_em };
if face.outline_glyph(ttf_parser::GlyphId(gid), &mut sink).is_none() {
return empty;
}
if sink.open {
sink.b.end(true);
}
let path = sink.b.build();
let mut buffers: VertexBuffers<[f32; 2], u32> = VertexBuffers::new();
let mut tess = FillTessellator::new();
// Toleranz in em: 0.0003 em ≈ 0.06 px bei 200 px Schrift.
let opts = FillOptions::tolerance(0.0003).with_fill_rule(FillRule::NonZero);
if tess
.tessellate_path(&path, &opts, &mut BuffersBuilder::new(&mut buffers, |v: FillVertex| v.position().to_array()))
.is_err()
|| buffers.indices.is_empty()
{
return empty;
}
let base = self.verts.len() as u32;
let first_index = self.indices.len() as u32;
self.verts.extend_from_slice(&buffers.vertices);
self.indices.extend(buffers.indices.iter().map(|i| i + base));
self.dirty = true;
GlyphMesh { first_index, index_count: buffers.indices.len() as u32 }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shapes_and_tessellates_a_glyph_if_a_system_font_exists() {
let Some(mut font) = VectorFont::system() else {
eprintln!("keine Systemschrift – Test uebersprungen");
return;
};
let (glyphs, width) = font.shape("AB 1");
assert_eq!(glyphs.len(), 3, "Leerzeichen erzeugt keine Glyphe");
assert!(width > 1.0 && width < 4.0, "Breite in em plausibel: {width}");
let m = font.mesh(glyphs[0].0).expect("A hat einen Umriss");
assert!(m.index_count >= 3 && m.index_count % 3 == 0);
assert!(font.verts.iter().all(|v| v[0].abs() < 2.0 && v[1].abs() < 2.0), "em-normalisiert");
// Zweiter Zugriff liefert dasselbe Mesh ohne neu zu tessellieren.
let n = font.indices.len();
assert_eq!(font.mesh(glyphs[0].0).unwrap().first_index, m.first_index);
assert_eq!(font.indices.len(), n);
}
}