Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to cosmic-text #23

Merged
merged 23 commits into from
Jan 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ license = "MIT OR Apache-2.0 OR Zlib"

[dependencies]
wgpu = "0.14.0"
fontdue = { git = "https://github.com/mooman219/fontdue", rev = "828b4f4" }
etagere = "0.2.6"
cosmic-text = { git = "https://github.com/pop-os/cosmic-text", rev = "a5903bb", features = ["std", "swash"] }

[dev-dependencies]
winit = "0.27.0"
Expand Down
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@

This crate provides a simple way to render 2D text with [`wgpu`](https://github.com/gfx-rs/wgpu/) by:

- rasterizing glyphs (with [`fontdue`](https://github.com/mooman219/fontdue/))
- shaping/calculating layout/rasterizing glyphs (with [`cosmic-text`](https://github.com/pop-os/cosmic-text/))
- packing the glyphs into texture atlas (with [`etagere`](https://github.com/nical/etagere/))
- calculate layout for text (with [`fontdue`](https://github.com/mooman219/fontdue/))
- sampling from the texture atlas to render text (with [`wgpu`](https://github.com/gfx-rs/wgpu/))

To avoid extra render passes, rendering uses existing render passes (following the middleware pattern described in [`wgpu`'s Encapsulating Graphics Work wiki page](https://github.com/gfx-rs/wgpu/wiki/Encapsulating-Graphics-Work).
Expand Down
124 changes: 51 additions & 73 deletions examples/hello-world.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,39 @@
use fontdue::layout::{HorizontalAlign, VerticalAlign};
use glyphon::{
fontdue::{
layout::{CoordinateSystem, Layout, LayoutSettings, TextStyle},
Font, FontSettings,
},
Color, HasColor, Resolution, TextAtlas, TextOverflow, TextRenderer,
Attrs, Buffer, Color, Family, FontSystem, Metrics, Resolution, SwashCache, TextArea, TextAtlas,
TextBounds, TextRenderer,
};
use wgpu::{
Backends, CommandEncoderDescriptor, CompositeAlphaMode, DeviceDescriptor, Features, Instance,
Limits, LoadOp, Operations, PresentMode, RenderPassColorAttachment, RenderPassDescriptor,
RequestAdapterOptions, SurfaceConfiguration, TextureUsages, TextureViewDescriptor,
RequestAdapterOptions, SurfaceConfiguration, TextureFormat, TextureUsages,
TextureViewDescriptor,
};
use winit::{
dpi::LogicalSize,
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::Window,
window::WindowBuilder,
};

fn main() {
pollster::block_on(run());
}

#[derive(Clone, Copy)]
struct GlyphUserData;

impl HasColor for GlyphUserData {
fn color(&self) -> Color {
Color {
r: 255,
g: 255,
b: 0,
a: 255,
}
}
}
static mut FONT_SYSTEM: Option<FontSystem> = None;

async fn run() {
// Set up window
let (width, height) = (800, 600);
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_inner_size(LogicalSize::new(width as f64, height as f64))
.with_title("glyphon hello world")
.build(&event_loop)
.unwrap();
let size = window.inner_size();
let scale_factor = window.scale_factor();

// Set up surface
let instance = Instance::new(Backends::all());
let adapter = instance
.request_adapter(&RequestAdapterOptions::default())
Expand All @@ -52,28 +50,37 @@ async fn run() {
)
.await
.unwrap();

let event_loop = EventLoop::new();
let window = Window::new(&event_loop).unwrap();
let surface = unsafe { instance.create_surface(&window) };
let size = window.inner_size();
let swapchain_format = surface.get_supported_formats(&adapter)[0];
// TODO: handle srgb
let swapchain_format = TextureFormat::Bgra8Unorm;
let mut config = SurfaceConfiguration {
usage: TextureUsages::RENDER_ATTACHMENT,
format: swapchain_format,
width: size.width,
height: size.height,
present_mode: PresentMode::Mailbox,
present_mode: PresentMode::Fifo,
alpha_mode: CompositeAlphaMode::Opaque,
};
surface.configure(&device, &config);

let mut atlas = TextAtlas::new(&device, &queue, swapchain_format);
// Set up text renderer
let mut text_renderer = TextRenderer::new(&device, &queue);
unsafe {
FONT_SYSTEM = Some(FontSystem::new());
}
let mut cache = SwashCache::new(unsafe { FONT_SYSTEM.as_ref().unwrap() });
let mut atlas = TextAtlas::new(&device, &queue, swapchain_format);
let mut buffer = Buffer::new(
unsafe { FONT_SYSTEM.as_ref().unwrap() },
Metrics::new(30, 42),
);

let font = include_bytes!("./Inter-Bold.ttf") as &[u8];
let font = Font::from_bytes(font, FontSettings::default()).unwrap();
let fonts = vec![font];
let physical_width = (width as f64 * scale_factor) as i32;
let physical_height = (height as f64 * scale_factor) as i32;

buffer.set_size(physical_width, physical_height);
buffer.set_text("Hello world! 👋\nThis is rendered with 🦅 glyphon 🦁\nThe text below should be partially clipped.\na b c d e f g h i j k l m n o p q r s t u v w x y z", Attrs::new().family(Family::SansSerif));
buffer.shape_until_scroll();

event_loop.run(move |event, _, control_flow| {
let _ = (&instance, &adapter);
Expand All @@ -90,46 +97,6 @@ async fn run() {
window.request_redraw();
}
Event::RedrawRequested(_) => {
let mut layout1 = Layout::new(CoordinateSystem::PositiveYDown);

layout1.reset(&LayoutSettings {
x: 0.0,
y: 0.0,
..LayoutSettings::default()
});

layout1.append(
fonts.as_slice(),
&TextStyle::with_user_data(
"Hello world!\nI'm on a new line!",
50.0,
0,
GlyphUserData,
),
);

let mut layout2 = Layout::new(CoordinateSystem::PositiveYDown);

layout2.reset(&LayoutSettings {
x: 0.0,
y: 200.0,
max_width: Some(200.0),
max_height: Some(190.0),
horizontal_align: HorizontalAlign::Center,
vertical_align: VerticalAlign::Middle,
..LayoutSettings::default()
});

layout2.append(
fonts.as_slice(),
&TextStyle::with_user_data(
"abcdefghijklmnopqrstuvwxyz\nThis should be partially clipped!\nabcdefghijklmnopqrstuvwxyz",
25.0,
0,
GlyphUserData,
),
);

text_renderer
.prepare(
&device,
Expand All @@ -139,8 +106,19 @@ async fn run() {
width: config.width,
height: config.height,
},
&fonts,
&[(layout1, TextOverflow::Hide), (layout2, TextOverflow::Hide)],
&[TextArea {
buffer: &buffer,
left: 10,
top: 10,
bounds: TextBounds {
left: 0,
top: 0,
right: 600,
bottom: 160,
},
}],
Color::rgb(255, 255, 255),
&mut cache,
)
.unwrap();

Expand Down
Loading