use crate::font::Font;
use crate::font::atlas::{GlyphAtlas, SUBPIXEL_BINS};
use crate::font::color::ColorGlyphCache;
use crate::font::layout::PositionedGlyph;
use crate::image::{AtlasImage, ImageAtlas, NineSliceImage, TextureId, slice_bands, slice_cuts};
use crate::text::FontAtlas;
use crate::text::GLYPH_HEIGHT;
use crate::widget::SkinInsets;
use core::fmt;
use core::ops::Range;
use glam::Vec2;
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct Vertex2d {
pub pos: Vec2,
pub uv: Vec2,
pub color: [f32; 4],
pub clip: [f32; 4],
pub shape: [f32; 4],
pub radii: [f32; 4],
pub border: [f32; 4],
}
impl Vertex2d {
#[must_use]
pub const fn new(pos: Vec2, uv: Vec2, color: [f32; 4], primitive: Primitive) -> Self {
Self {
pos,
uv,
color,
clip: ClipRect::NONE.lane(),
shape: [0.0, 0.0, 0.0, primitive.lane()],
radii: [0.0; 4],
border: [0.0; 4],
}
}
#[must_use]
pub fn primitive(&self) -> Option<Primitive> {
Primitive::ALL
.into_iter()
.find(|primitive| primitive.lane() == self.shape[3])
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Primitive {
Solid,
Glyph,
Image,
RoundedRect,
FontGlyph,
Texture,
}
impl Primitive {
pub const ALL: [Self; 6] = [
Self::Solid,
Self::Glyph,
Self::Image,
Self::RoundedRect,
Self::FontGlyph,
Self::Texture,
];
#[must_use]
pub const fn lane(self) -> f32 {
match self {
Self::Solid => 0.0,
Self::Glyph => 1.0,
Self::Image => 2.0,
Self::RoundedRect => 3.0,
Self::FontGlyph => 4.0,
Self::Texture => 5.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClipRect {
pub min: Vec2,
pub max: Vec2,
}
impl ClipRect {
pub const NONE: Self = Self {
min: Vec2::splat(f32::MIN),
max: Vec2::splat(f32::MAX),
};
#[must_use]
pub fn intersect(self, other: Self) -> Self {
let min = self.min.max(other.min);
let max = self.max.min(other.max).max(min);
Self { min, max }
}
fn scaled(self, scale: f32) -> Self {
if scale == 1.0 {
return self;
}
let side = |value: f32| {
if value.abs() == f32::MAX {
value
} else {
value * scale
}
};
Self {
min: Vec2::new(side(self.min.x), side(self.min.y)),
max: Vec2::new(side(self.max.x), side(self.max.y)),
}
}
#[must_use]
pub const fn lane(self) -> [f32; 4] {
[self.min.x, self.min.y, self.max.x, self.max.y]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClipUnderflow;
impl fmt::Display for ClipUnderflow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("pop_clip was called with no clip rectangle pushed")
}
}
impl std::error::Error for ClipUnderflow {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpacityUnderflow;
impl fmt::Display for OpacityUnderflow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("pop_opacity was called with no opacity group pushed")
}
}
impl std::error::Error for OpacityUnderflow {}
#[derive(Debug, Clone, PartialEq)]
pub struct OpacityGroup {
pub commands: Range<usize>,
pub opacity: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct CornerRadii {
pub top_left: f32,
pub top_right: f32,
pub bottom_right: f32,
pub bottom_left: f32,
}
impl CornerRadii {
#[must_use]
pub const fn uniform(radius: f32) -> Self {
Self {
top_left: radius,
top_right: radius,
bottom_right: radius,
bottom_left: radius,
}
}
#[must_use]
pub fn lane(self, limit: f32) -> [f32; 4] {
[
self.top_left,
self.top_right,
self.bottom_right,
self.bottom_left,
]
.map(|radius| radius.max(0.0).min(limit))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Border {
pub width: f32,
pub color: [f32; 4],
}
impl Border {
pub const NONE: Self = Self {
width: 0.0,
color: [0.0; 4],
};
}
#[derive(Debug, Clone)]
pub enum DrawCommand {
Rect {
min: Vec2,
max: Vec2,
color: [f32; 4],
},
RectOutline {
min: Vec2,
max: Vec2,
thickness: f32,
color: [f32; 4],
},
Line {
from: Vec2,
to: Vec2,
thickness: f32,
color: [f32; 4],
},
Polyline {
points: Vec<Vec2>,
thickness: f32,
closed: bool,
color: [f32; 4],
},
Text {
pos: Vec2,
text: String,
color: [f32; 4],
size: f32,
},
Glyphs {
origin: Vec2,
font: Font,
size: f32,
color: [f32; 4],
glyphs: Vec<PositionedGlyph>,
text: Option<Arc<str>>,
},
Image {
min: Vec2,
max: Vec2,
uv_min: Vec2,
uv_max: Vec2,
tint: [f32; 4],
},
Texture {
texture: TextureId,
min: Vec2,
max: Vec2,
uv_min: Vec2,
uv_max: Vec2,
tint: [f32; 4],
},
RoundedRect {
min: Vec2,
max: Vec2,
radii: CornerRadii,
color: [f32; 4],
border: Border,
},
}
impl DrawCommand {
fn scaled(self, scale: f32) -> Self {
match self {
Self::Rect { min, max, color } => Self::Rect {
min: min * scale,
max: max * scale,
color,
},
Self::RectOutline {
min,
max,
thickness,
color,
} => Self::RectOutline {
min: min * scale,
max: max * scale,
thickness: thickness * scale,
color,
},
Self::Line {
from,
to,
thickness,
color,
} => Self::Line {
from: from * scale,
to: to * scale,
thickness: thickness * scale,
color,
},
Self::Polyline {
mut points,
thickness,
closed,
color,
} => {
for point in &mut points {
*point *= scale;
}
Self::Polyline {
points,
thickness: thickness * scale,
closed,
color,
}
}
Self::Text {
pos,
text,
color,
size,
} => Self::Text {
pos: pos * scale,
text,
color,
size: size * scale,
},
Self::Glyphs {
origin,
font,
size,
color,
mut glyphs,
text,
} => {
for glyph in &mut glyphs {
glyph.offset *= scale;
}
Self::Glyphs {
origin: origin * scale,
font,
size: size * scale,
color,
glyphs,
text,
}
}
Self::Image {
min,
max,
uv_min,
uv_max,
tint,
} => Self::Image {
min: min * scale,
max: max * scale,
uv_min,
uv_max,
tint,
},
Self::Texture {
texture,
min,
max,
uv_min,
uv_max,
tint,
} => Self::Texture {
texture,
min: min * scale,
max: max * scale,
uv_min,
uv_max,
tint,
},
Self::RoundedRect {
min,
max,
radii,
color,
border,
} => Self::RoundedRect {
min: min * scale,
max: max * scale,
radii: CornerRadii {
top_left: radii.top_left * scale,
top_right: radii.top_right * scale,
bottom_right: radii.bottom_right * scale,
bottom_left: radii.bottom_left * scale,
},
color,
border: Border {
width: border.width * scale,
color: border.color,
},
},
}
}
}
#[derive(Debug, Clone)]
pub struct DrawList {
commands: Vec<DrawCommand>,
clips: Vec<ClipRect>,
clip_stack: Vec<ClipRect>,
groups: Vec<OpacityGroup>,
opacity_stack: Vec<Option<usize>>,
overlay_start: Option<usize>,
scale: f32,
}
impl Default for DrawList {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Triangles {
pub vertices: Vec<Vertex2d>,
pub indices: Vec<u32>,
pub overlay: usize,
pub textures: Vec<TextureRun>,
pub groups: Vec<OpacityRun>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct OpacityRun {
pub indices: Range<u32>,
pub opacity: f32,
pub bounds: ClipRect,
}
impl OpacityRun {
#[must_use]
pub fn layer_quad(&self, viewport: (u32, u32)) -> [Vertex2d; 4] {
let size = Vec2::new(viewport.0 as f32, viewport.1 as f32);
let min = self.bounds.min.floor().max(Vec2::ZERO).min(size);
let max = self.bounds.max.ceil().max(min).min(size);
let uv = |pos: Vec2| {
if size.x > 0.0 && size.y > 0.0 {
pos / size
} else {
Vec2::ZERO
}
};
let color = [self.opacity; 4];
quad_corners(min, max).map(|pos| Vertex2d::new(pos, uv(pos), color, Primitive::Texture))
}
}
pub const QUAD_INDICES: [u32; 6] = [0, 1, 2, 0, 2, 3];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextureRun {
pub texture: TextureId,
pub indices: Range<u32>,
}
impl DrawList {
#[must_use]
pub fn new() -> Self {
Self {
commands: Vec::new(),
clips: Vec::new(),
clip_stack: Vec::new(),
groups: Vec::new(),
opacity_stack: Vec::new(),
overlay_start: None,
scale: 1.0,
}
}
pub fn set_scale(&mut self, scale: f32) {
self.scale = if scale.is_finite() && scale > 0.0 {
scale
} else {
1.0
};
}
#[must_use]
pub const fn scale(&self) -> f32 {
self.scale
}
#[must_use]
pub fn to_logical(&self, point: Vec2) -> Vec2 {
point / self.scale
}
pub fn push_command(&mut self, command: DrawCommand) {
self.push(command);
}
fn push(&mut self, command: DrawCommand) {
let command = if self.scale == 1.0 {
command
} else {
command.scaled(self.scale)
};
self.commands.push(command);
self.clips.push(self.clip());
let len = self.commands.len();
for open in self.opacity_stack.iter().flatten() {
self.groups[*open].commands.end = len;
}
}
pub fn rect(&mut self, min: Vec2, max: Vec2, color: [f32; 4]) {
self.push(DrawCommand::Rect { min, max, color });
}
pub fn rect_outline(&mut self, min: Vec2, max: Vec2, thickness: f32, color: [f32; 4]) {
self.push(DrawCommand::RectOutline {
min,
max,
thickness,
color,
});
}
pub fn line(&mut self, from: Vec2, to: Vec2, thickness: f32, color: [f32; 4]) {
self.push(DrawCommand::Line {
from,
to,
thickness,
color,
});
}
pub fn polyline(
&mut self,
points: impl Into<Vec<Vec2>>,
thickness: f32,
closed: bool,
color: [f32; 4],
) {
self.push(DrawCommand::Polyline {
points: points.into(),
thickness,
closed,
color,
});
}
pub fn text(&mut self, pos: Vec2, text: impl Into<String>, color: [f32; 4], size: f32) {
self.push(DrawCommand::Text {
pos,
text: text.into(),
color,
size,
});
}
pub fn glyphs(
&mut self,
origin: Vec2,
font: &Font,
size: f32,
color: [f32; 4],
glyphs: impl Into<Vec<PositionedGlyph>>,
) {
self.push(DrawCommand::Glyphs {
origin,
font: font.clone(),
size,
color,
glyphs: glyphs.into(),
text: None,
});
}
pub fn text_glyphs(
&mut self,
origin: Vec2,
font: &Font,
size: f32,
color: [f32; 4],
glyphs: impl Into<Vec<PositionedGlyph>>,
text: &str,
) {
self.push(DrawCommand::Glyphs {
origin,
font: font.clone(),
size,
color,
glyphs: glyphs.into(),
text: Some(Arc::from(text)),
});
}
pub fn image(&mut self, min: Vec2, max: Vec2, image: &AtlasImage, tint: [f32; 4]) {
self.push(DrawCommand::Image {
min,
max,
uv_min: image.uv_min(),
uv_max: image.uv_max(),
tint,
});
}
pub fn texture(
&mut self,
min: Vec2,
max: Vec2,
texture: TextureId,
uv: (Vec2, Vec2),
tint: [f32; 4],
) {
self.push(DrawCommand::Texture {
texture,
min,
max,
uv_min: uv.0,
uv_max: uv.1,
tint,
});
}
pub fn nine_slice(
&mut self,
min: Vec2,
max: Vec2,
sliced: &NineSliceImage,
scale: f32,
tint: [f32; 4],
) {
if !(scale.is_finite() && scale > 0.0) {
return;
}
let insets = sliced.clamped_insets();
let bands = SkinInsets::new(
insets.left * scale,
insets.right * scale,
insets.top * scale,
insets.bottom * scale,
);
self.nine_slice_bands(min, max, sliced, bands, true, tint);
}
pub fn nine_slice_bands(
&mut self,
min: Vec2,
max: Vec2,
sliced: &NineSliceImage,
bands: SkinInsets,
fill: bool,
tint: [f32; 4],
) {
let widths = [bands.left, bands.right, bands.top, bands.bottom];
if !(min.is_finite()
&& max.is_finite()
&& widths
.iter()
.all(|width| width.is_finite() && *width >= 0.0))
{
return;
}
let insets = sliced.clamped_insets();
let size = sliced.image.size();
let texel_x = [0.0, insets.left, size.x - insets.right, size.x];
let texel_y = [0.0, insets.top, size.y - insets.bottom, size.y];
let extent = max - min;
let xs = slice_cuts(
min.x,
slice_bands(bands.left, bands.right, extent.x),
extent.x,
);
let ys = slice_cuts(
min.y,
slice_bands(bands.top, bands.bottom, extent.y),
extent.y,
);
for row in 0..3 {
if texel_y[row] == texel_y[row + 1] || ys[row + 1] <= ys[row] {
continue;
}
for column in 0..3 {
if texel_x[column] == texel_x[column + 1]
|| xs[column + 1] <= xs[column]
|| (!fill && row == 1 && column == 1)
{
continue;
}
self.push(DrawCommand::Image {
min: Vec2::new(xs[column], ys[row]),
max: Vec2::new(xs[column + 1], ys[row + 1]),
uv_min: sliced.image.uv(Vec2::new(texel_x[column], texel_y[row])),
uv_max: sliced
.image
.uv(Vec2::new(texel_x[column + 1], texel_y[row + 1])),
tint,
});
}
}
}
pub fn rounded_rect(
&mut self,
min: Vec2,
max: Vec2,
radii: CornerRadii,
color: [f32; 4],
border: Border,
) {
self.push(DrawCommand::RoundedRect {
min,
max,
radii,
color,
border,
});
}
pub fn push_clip(&mut self, min: Vec2, max: Vec2) {
let clip = self
.clip()
.intersect(ClipRect { min, max }.scaled(self.scale));
self.clip_stack.push(clip);
}
pub fn pop_clip(&mut self) -> Result<(), ClipUnderflow> {
self.clip_stack.pop().map(|_| ()).ok_or(ClipUnderflow)
}
#[must_use]
pub fn clip(&self) -> ClipRect {
self.clip_stack.last().copied().unwrap_or(ClipRect::NONE)
}
#[must_use]
pub fn clips(&self) -> &[ClipRect] {
&self.clips
}
pub fn push_opacity(&mut self, opacity: f32) {
let opacity = if opacity.is_nan() {
1.0
} else {
opacity.clamp(0.0, 1.0)
};
if opacity == 1.0 {
self.opacity_stack.push(None);
return;
}
let start = self.commands.len();
self.opacity_stack.push(Some(self.groups.len()));
self.groups.push(OpacityGroup {
commands: start..start,
opacity,
});
}
pub fn pop_opacity(&mut self) -> Result<(), OpacityUnderflow> {
self.opacity_stack.pop().map(|_| ()).ok_or(OpacityUnderflow)
}
#[must_use]
pub fn opacity_groups(&self) -> &[OpacityGroup] {
&self.groups
}
#[must_use]
pub fn into_commands(self) -> Vec<DrawCommand> {
self.commands
}
#[must_use]
pub fn commands(&self) -> &[DrawCommand] {
&self.commands
}
pub fn begin_overlay(&mut self) {
self.overlay_start = Some(self.commands.len());
self.clip_stack.clear();
self.opacity_stack.clear();
}
#[must_use]
pub fn base_commands(&self) -> &[DrawCommand] {
&self.commands[..self.overlay_start()]
}
#[must_use]
pub fn overlay_commands(&self) -> &[DrawCommand] {
&self.commands[self.overlay_start()..]
}
fn overlay_start(&self) -> usize {
self.overlay_start
.unwrap_or(self.commands.len())
.min(self.commands.len())
}
#[must_use]
pub fn len(&self) -> usize {
self.commands.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.commands.is_empty()
}
pub fn clear(&mut self) {
self.commands.clear();
self.clips.clear();
self.clip_stack.clear();
self.groups.clear();
self.opacity_stack.clear();
self.overlay_start = None;
}
pub fn resolve_color_glyphs(
&mut self,
cache: &mut ColorGlyphCache,
images: &mut ImageAtlas,
scale: f32,
) {
let mut colors = ColorGlyphs { cache, images };
let cut = self.overlay_start.map(|_| self.overlay_start());
let mut commands = Vec::with_capacity(self.commands.len());
let mut clips = Vec::with_capacity(self.clips.len());
let mut overlay = None;
let mut moved = Vec::with_capacity(self.commands.len() + 1);
for (index, (mut command, clip)) in core::mem::take(&mut self.commands)
.into_iter()
.zip(core::mem::take(&mut self.clips))
.enumerate()
{
if Some(index) == cut {
overlay = Some(commands.len());
}
moved.push(commands.len());
let quads = match &mut command {
DrawCommand::Glyphs {
origin,
font,
size,
color,
glyphs,
..
} => match colors.split((*origin, font, *size, *color), glyphs, scale) {
Some((outlines, quads)) => {
*glyphs = outlines;
quads
}
None => Vec::new(),
},
_ => Vec::new(),
};
commands.push(command);
clips.push(clip);
for quad in quads {
commands.push(quad);
clips.push(clip);
}
}
moved.push(commands.len());
for group in &mut self.groups {
group.commands = moved[group.commands.start]..moved[group.commands.end];
}
self.commands = commands;
self.clips = clips;
self.overlay_start = self
.overlay_start
.map(|_| overlay.unwrap_or(self.commands.len()));
}
#[must_use]
pub fn to_triangles(
&self,
atlas: Option<&FontAtlas>,
glyphs: Option<&mut GlyphAtlas>,
scale: f32,
) -> (Vec<Vertex2d>, Vec<u32>) {
let triangles = self.to_triangles_split(atlas, glyphs, scale);
(triangles.vertices, triangles.indices)
}
#[must_use]
pub fn to_triangles_split(
&self,
atlas: Option<&FontAtlas>,
glyphs: Option<&mut GlyphAtlas>,
scale: f32,
) -> Triangles {
self.to_triangles_with_colors(atlas, glyphs, None, scale)
}
#[must_use]
pub fn to_triangles_with_colors(
&self,
atlas: Option<&FontAtlas>,
mut glyphs: Option<&mut GlyphAtlas>,
mut colors: Option<ColorGlyphs<'_>>,
scale: f32,
) -> Triangles {
let mut vertices = Vec::new();
let mut indices = Vec::new();
let cut = self.overlay_start();
let mut overlay = 0;
let mut textures: Vec<TextureRun> = Vec::new();
let mut hidden = vec![false; self.commands.len()];
for group in self.groups.iter().filter(|group| group.opacity == 0.0) {
hidden[group.commands.clone()].fill(true);
}
let mut starts = Vec::with_capacity(self.commands.len() + 1);
for (index, (cmd, clip)) in self.commands.iter().zip(&self.clips).enumerate() {
if index == cut {
overlay = indices.len();
}
let first = vertices.len();
let first_index = indices.len() as u32;
starts.push((first, first_index));
if hidden[index] {
continue;
}
expand(
cmd,
(atlas, glyphs.as_deref_mut(), colors.as_mut()),
scale,
&mut vertices,
&mut indices,
);
for vertex in &mut vertices[first..] {
vertex.clip = clip.lane();
}
if let DrawCommand::Texture { texture, .. } = cmd {
let end = indices.len() as u32;
match textures.last_mut() {
Some(run)
if run.texture == *texture
&& run.indices.end == first_index
&& index != cut =>
{
run.indices.end = end;
}
_ if end > first_index => textures.push(TextureRun {
texture: *texture,
indices: first_index..end,
}),
_ => {}
}
}
}
if cut == self.commands.len() {
overlay = indices.len();
}
starts.push((vertices.len(), indices.len() as u32));
let groups = self
.groups
.iter()
.filter(|group| group.opacity > 0.0)
.filter_map(|group| {
let (first, first_index) = starts[group.commands.start];
let (end, end_index) = starts[group.commands.end];
(end_index > first_index).then(|| OpacityRun {
indices: first_index..end_index,
opacity: group.opacity,
bounds: bounds(&vertices[first..end]),
})
})
.collect();
Triangles {
vertices,
indices,
overlay,
textures,
groups,
}
}
}
fn bounds(vertices: &[Vertex2d]) -> ClipRect {
let mut min = Vec2::splat(f32::MAX);
let mut max = Vec2::splat(f32::MIN);
for vertex in vertices {
let [x0, y0, x1, y1] = vertex.clip;
let pos = vertex.pos.max(Vec2::new(x0, y0)).min(Vec2::new(x1, y1));
min = min.min(pos);
max = max.max(pos);
}
ClipRect { min, max }
}
#[derive(Debug)]
pub struct ColorGlyphs<'a> {
pub cache: &'a mut ColorGlyphCache,
pub images: &'a mut ImageAtlas,
}
impl ColorGlyphs<'_> {
fn split(
&mut self,
(origin, font, size, color): (Vec2, &Font, f32, [f32; 4]),
glyphs: &[PositionedGlyph],
scale: f32,
) -> Option<(Vec<PositionedGlyph>, Vec<DrawCommand>)> {
if !font.has_color_tables() {
return None;
}
let mut outlines = Vec::with_capacity(glyphs.len());
let mut quads = Vec::new();
for glyph in glyphs {
let pen = origin + glyph.offset * scale;
let colour = pen
.is_finite()
.then(|| {
self.cache
.glyph(self.images, font, glyph.glyph, size * scale)
})
.flatten();
let Some(colour) = colour else {
outlines.push(*glyph);
continue;
};
let min = pen.round() + Vec2::new(colour.left as f32, colour.top as f32);
quads.push(DrawCommand::Image {
min,
max: min + colour.image.size(),
uv_min: colour.image.uv_min(),
uv_max: colour.image.uv_max(),
tint: [1.0, 1.0, 1.0, color[3]],
});
}
Some((outlines, quads))
}
}
fn expand(
cmd: &DrawCommand,
(atlas, glyph_atlas, colors): (
Option<&FontAtlas>,
Option<&mut GlyphAtlas>,
Option<&mut ColorGlyphs<'_>>,
),
scale: f32,
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
match cmd {
DrawCommand::Rect { min, max, color } => {
push_quad(
*min,
*max,
(Vec2::ZERO, Vec2::ZERO),
*color,
Primitive::Solid,
vertices,
indices,
);
}
DrawCommand::RectOutline {
min,
max,
thickness,
color,
} => {
let half = (*max - *min) * 0.5;
let t = thickness.max(0.0).min(half.x.max(0.0)).min(half.y.max(0.0));
let c = *color;
let inner_min = Vec2::new(min.x + t, min.y + t);
let inner_max = Vec2::new(max.x - t, max.y - t);
let mut edge = |q_min: Vec2, q_max: Vec2| {
push_quad(
q_min,
q_max,
(Vec2::ZERO, Vec2::ZERO),
c,
Primitive::Solid,
vertices,
indices,
);
};
edge(*min, Vec2::new(max.x, inner_min.y));
edge(Vec2::new(min.x, inner_max.y), *max);
edge(
Vec2::new(min.x, inner_min.y),
Vec2::new(inner_min.x, inner_max.y),
);
edge(
Vec2::new(inner_max.x, inner_min.y),
Vec2::new(max.x, inner_max.y),
);
}
DrawCommand::Line {
from,
to,
thickness,
color,
} => {
push_stroke(&[*from, *to], false, *thickness, *color, vertices, indices);
}
DrawCommand::Polyline {
points,
thickness,
closed,
color,
} => {
push_stroke(points, *closed, *thickness, *color, vertices, indices);
}
DrawCommand::Text {
pos,
text,
color,
size,
} => {
if let Some(atlas) = atlas {
let layout_scale = (*size / GLYPH_HEIGHT as f32) * scale;
let glyphs = atlas.glyph_positions(text, *pos, layout_scale);
for (c, min, max) in glyphs {
let uv_min = Vec2::new(atlas.glyph_u_min(c), 0.0);
let uv_max = Vec2::new(atlas.glyph_u_max(c), 1.0);
push_quad(
min,
max,
(uv_min, uv_max),
*color,
Primitive::Glyph,
vertices,
indices,
);
}
}
}
DrawCommand::Glyphs {
origin,
font,
size,
color,
glyphs,
text: _,
} => {
let split = colors
.and_then(|colors| colors.split((*origin, font, *size, *color), glyphs, scale));
let (outlines, quads) = match &split {
Some((outlines, quads)) => (outlines.as_slice(), quads.as_slice()),
None => (glyphs.as_slice(), &[][..]),
};
if let Some(glyph_atlas) = glyph_atlas {
push_glyphs(
glyph_atlas,
(*origin, font, *size * scale, scale),
outlines,
*color,
vertices,
indices,
);
}
for quad in quads {
expand(quad, (None, None, None), scale, vertices, indices);
}
}
DrawCommand::Image {
min,
max,
uv_min,
uv_max,
tint,
} => {
push_quad(
*min,
*max,
(*uv_min, *uv_max),
*tint,
Primitive::Image,
vertices,
indices,
);
}
DrawCommand::Texture {
texture,
min,
max,
uv_min,
uv_max,
tint,
} => {
let first = vertices.len();
push_quad(
*min,
*max,
(*uv_min, *uv_max),
*tint,
Primitive::Texture,
vertices,
indices,
);
for vertex in &mut vertices[first..] {
vertex.shape[0] = texture.index() as f32;
}
}
DrawCommand::RoundedRect {
min,
max,
radii,
color,
border,
} => push_rounded_rect(*min, *max, *radii, *color, *border, vertices, indices),
}
}
fn push_glyphs(
atlas: &mut GlyphAtlas,
(origin, font, pixel_size, scale): (Vec2, &Font, f32, f32),
glyphs: &[PositionedGlyph],
color: [f32; 4],
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
let bins = f32::from(SUBPIXEL_BINS);
let page = atlas.page_size() as f32;
for glyph in glyphs {
let pen = origin + glyph.offset * scale;
if !pen.is_finite() {
continue;
}
let steps = (pen.x * bins).round();
let whole = (steps / bins).floor();
let bin = (steps - whole * bins) as u8;
let Some(placed) = atlas.glyph(font, glyph.glyph, pixel_size, bin) else {
continue;
};
if placed.is_empty() {
continue;
}
let min = Vec2::new(
whole + placed.left as f32,
pen.y.round() + placed.top as f32,
);
let extent = Vec2::new(placed.width as f32, placed.height as f32);
let texel = Vec2::new(placed.x as f32, placed.y as f32);
let first = vertices.len();
push_quad(
min,
min + extent,
(texel / page, (texel + extent) / page),
color,
Primitive::FontGlyph,
vertices,
indices,
);
for vertex in &mut vertices[first..] {
vertex.shape[0] = placed.page as f32;
}
}
}
fn push_rounded_rect(
min: Vec2,
max: Vec2,
radii: CornerRadii,
color: [f32; 4],
border: Border,
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
if !(min.is_finite() && max.is_finite()) || max.x <= min.x || max.y <= min.y {
return;
}
let half = (max - min) * 0.5;
let limit = half.x.min(half.y);
let first = vertices.len();
push_quad(
min,
max,
(-half, half),
color,
Primitive::RoundedRect,
vertices,
indices,
);
for vertex in &mut vertices[first..] {
vertex.shape = [
half.x,
half.y,
border.width.max(0.0).min(limit),
Primitive::RoundedRect.lane(),
];
vertex.radii = radii.lane(limit);
vertex.border = border.color;
}
}
fn push_stroke(
points: &[Vec2],
closed: bool,
thickness: f32,
color: [f32; 4],
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
let half = thickness * 0.5;
if half.is_nan() || half <= 0.0 || half.is_infinite() {
return;
}
let mut run: Vec<Vec2> = Vec::with_capacity(points.len());
let mut split = false;
for &point in points {
if !point.is_finite() {
split = true;
push_run(&run, false, half, color, vertices, indices);
run.clear();
continue;
}
if run.last().is_none_or(|&last| (point - last).length() > 0.0) {
run.push(point);
}
}
push_run(&run, closed && !split, half, color, vertices, indices);
}
fn push_run(
points: &[Vec2],
closed: bool,
half: f32,
color: [f32; 4],
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
let closed =
closed && points.len() >= 3 && (points[points.len() - 1] - points[0]).length() > 0.0;
let count = points.len();
if count < 2 {
return;
}
let segments = if closed { count } else { count - 1 };
let mut directions: Vec<Vec2> = Vec::with_capacity(segments);
for index in 0..segments {
let delta = points[(index + 1) % count] - points[index];
directions.push(delta / delta.length());
}
let normal = |direction: Vec2| Vec2::new(-direction.y, direction.x) * half;
for index in 0..segments {
let (a, b) = (points[index], points[(index + 1) % count]);
let offset = normal(directions[index]);
push_quad_free(
a + offset,
b + offset,
b - offset,
a - offset,
color,
vertices,
indices,
);
}
let joints = if closed { segments } else { segments - 1 };
for index in 0..joints {
let incoming = directions[index];
let outgoing = directions[(index + 1) % segments];
let turn = incoming.perp_dot(outgoing);
if turn == 0.0 {
continue;
}
let side = if turn > 0.0 { -1.0 } else { 1.0 };
let corner = points[(index + 1) % count];
push_triangle(
corner,
corner + normal(incoming) * side,
corner + normal(outgoing) * side,
color,
vertices,
indices,
);
}
}
fn push_quad_free(
p0: Vec2,
p1: Vec2,
p2: Vec2,
p3: Vec2,
color: [f32; 4],
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
let base = vertices.len() as u32;
for pos in [p0, p1, p2, p3] {
vertices.push(Vertex2d::new(pos, Vec2::ZERO, color, Primitive::Solid));
}
indices.extend(QUAD_INDICES.map(|index| base + index));
}
fn push_triangle(
p0: Vec2,
p1: Vec2,
p2: Vec2,
color: [f32; 4],
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
let base = vertices.len() as u32;
for pos in [p0, p1, p2] {
vertices.push(Vertex2d::new(pos, Vec2::ZERO, color, Primitive::Solid));
}
indices.extend_from_slice(&[base, base + 1, base + 2]);
}
fn push_quad(
min: Vec2,
max: Vec2,
(uv_min, uv_max): (Vec2, Vec2),
color: [f32; 4],
primitive: Primitive,
vertices: &mut Vec<Vertex2d>,
indices: &mut Vec<u32>,
) {
let base = vertices.len() as u32;
for (pos, uv) in quad_corners(min, max)
.into_iter()
.zip(quad_corners(uv_min, uv_max))
{
vertices.push(Vertex2d::new(pos, uv, color, primitive));
}
indices.extend(QUAD_INDICES.map(|index| base + index));
}
fn quad_corners(min: Vec2, max: Vec2) -> [Vec2; 4] {
[
Vec2::new(min.x, max.y),
Vec2::new(max.x, max.y),
Vec2::new(max.x, min.y),
Vec2::new(min.x, min.y),
]
}
unsafe impl bytemuck::Pod for Vertex2d {}
unsafe impl bytemuck::Zeroable for Vertex2d {}
#[cfg(all(test, feature = "parsed-font"))]
mod color_tests;
#[cfg(test)]
mod opacity_tests;
#[cfg(test)]
mod scale_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod texture_tests;