### GpuRenderer Usage Example Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/gpu_renderer/struct.GpuRenderer.html Demonstrates the typical usage pattern for GpuRenderer, including initialization, text layout, and rendering callbacks for atlas updates and drawing glyphs. This example shows how to integrate the renderer with a FontSystem. ```rust use suzuri { FontSystem, fontdb, renderer::{GpuCacheConfig, AtlasUpdate, GlyphInstance, StandaloneGlyph}, text::{TextData, TextElement, TextLayoutConfig}, }; use std::num::NonZeroUsize; let font_system = FontSystem::new(); font_system.load_system_fonts(); // 1. Initialize Renderer let cache_configs = [ GpuCacheConfig { texture_size: NonZeroUsize::new(1024).unwrap(), tile_size: NonZeroUsize::new(32).unwrap(), // one side length tiles_per_axis: NonZeroUsize::new(32).unwrap(), }, ]; font_system.gpu_init(&cache_configs); // 2. Layout Text let mut data = TextData::::new(); // ... (append text elements) ... let layout = font_system.layout_text(&data, &TextLayoutConfig::default()); // 3. Render (Generic Loop) font_system.gpu_render( &layout, |updates: &[AtlasUpdate]| { // Upload 'pixels' to texture 'texture_index' at (x, y) }, |instances: &[GlyphInstance]| { // Add instances to a vertex buffer or draw them directly }, |standalone: &StandaloneGlyph| { // Handle large glyphs separately (e.g. create a temporary texture) }, ); ``` -------------------------------- ### Initialize FontSystem and Load Fonts Source: https://docs.rs/suzuri/0.2.1/suzuri/index.html Initialize the FontSystem, which is the entry point for Suzuri, and load system fonts. This example also shows how to query for a specific font. ```rust use suzuri::{FontSystem, fontdb::{self, Family, Query}}; let font_system = FontSystem::new(); font_system.load_system_fonts(); // Query a font let font_id = font_system .query(&Query { families: &[Family::Name("Arial"), Family::SansSerif], weight: fontdb::Weight::NORMAL, stretch: fontdb::Stretch::Normal, style: fontdb::Style::Normal, }) .map(|(id, _)| id); // .expect("Font not found"); // Handle error appropriately ``` -------------------------------- ### WGPU Renderer Usage Example Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Demonstrates the typical workflow for using the WgpuRenderer, including initializing the FontSystem, setting up cache configurations, laying out text, and performing the WGPU render pass. ```rust use suzuri:: FontSystem, fontdb, renderer::GpuCacheConfig, text::{TextData, TextElement, TextLayoutConfig} ; use std::num::NonZeroUsize; // Assume standard wgpu setup (device, queue, etc.) # async fn example() { # let (device, queue): (wgpu::Device, wgpu::Queue) = todo!(); # let texture_format = wgpu::TextureFormat::Bgra8Unorm; # let view: wgpu::TextureView = todo!(); # let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); let font_system = FontSystem::new(); font_system.load_system_fonts(); // 1. Initialize Renderer let cache_configs = [ GpuCacheConfig { texture_size: NonZeroUsize::new(1024).unwrap(), tile_size: NonZeroUsize::new(32).unwrap(), // one side length tiles_per_axis: NonZeroUsize::new(32).unwrap(), }, ]; // Pre-compile pipeline for the target format font_system.wgpu_init(&device, &cache_configs, &[texture_format]); // 2. Layout Text let mut data: TextData<[f32; 4]> = TextData::new(); // ... (append text elements) ... let layout = font_system.layout_text(&data, &TextLayoutConfig::default()); // 3. Render font_system.wgpu_render( &layout, &device, &mut encoder, &view ); # } ``` -------------------------------- ### Initialize WgpuRenderer and Render Text Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/wgpu_renderer/struct.WgpuRenderer.html Demonstrates the typical workflow for initializing the WgpuRenderer, laying out text, and performing the rendering operation. Assumes a standard wgpu setup and that device, encoder, and view are already available. ```rust use suzuri { FontSystem, fontdb, renderer::GpuCacheConfig, text::{TextData, TextElement, TextLayoutConfig}, }; use std::num::NonZeroUsize; // Assume standard wgpu setup (device, queue, etc.) let font_system = FontSystem::new(); font_system.load_system_fonts(); // 1. Initialize Renderer let cache_configs = [ GpuCacheConfig { texture_size: NonZeroUsize::new(1024).unwrap(), tile_size: NonZeroUsize::new(32).unwrap(), // one side length tiles_per_axis: NonZeroUsize::new(32).unwrap(), }, ]; // Pre-compile pipeline for the target format font_system.wgpu_init(&device, &cache_configs, &[texture_format]); // 2. Layout Text let mut data: TextData<[f32; 4]> = TextData::new(); // ... (append text elements) ... let layout = font_system.layout_text(&data, &TextLayoutConfig::default()); // 3. Render font_system.wgpu_render( &layout, &device, &mut encoder, &view ); ``` -------------------------------- ### Create WGPU Bind Group Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Creates a bind group for WGPU, associating resources like buffers, samplers, and texture views with bindings. This example shows the globals bind group. ```rust let globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Globals Bind Group"), layout: &bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: globals_buffer.as_entire_binding(), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&sampler), }, wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&atlas_view), }, ], }); ``` -------------------------------- ### Start New Batch in FallbackGpuCache Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Initiates a new batch processing cycle for all internal caches. ```rust fn new_batch(&mut self) { for cache in &mut self.caches { cache.new_batch(); } } ``` -------------------------------- ### Mark Start of New Batch Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/gpu_renderer/enum.GpuCache.html Indicates the beginning of a new batch of operations on the GpuCache. This is a mutable operation. ```rust pub fn new_batch(&mut self) ``` -------------------------------- ### TextLayout Methods: len_lines and len_glyphs Source: https://docs.rs/suzuri/0.2.1/src/suzuri/text/layout.rs.html Provides utility methods for `TextLayout` to get the number of lines and the total number of glyphs across all lines. These are useful for analyzing the layout results. ```rust impl TextLayout { /// Returns the number of lines in the layout. pub fn len_lines(&self) -> usize { self.lines.len() } /// Returns the total number of glyphs in the layout (sum of glyphs in all lines). pub fn len_glyphs(&self) -> usize { self.lines.iter().map(|line| line.glyphs.len()).sum() } } ``` -------------------------------- ### Define Custom Color Type and Text Data Source: https://docs.rs/suzuri/0.2.1/suzuri/index.html Prepare text content and styling. This includes defining a custom color type and appending TextElements to TextData. The example shows how to convert a custom color to a format suitable for wgpu rendering. ```rust // Color type is user-definable #[derive(Clone, Copy, Debug)] struct MyColor { r: f32, g: f32, b: f32, a: f32 } // For wgpu rendering, convert to [f32; 4] (Premultiplied Alpha) implement From for [f32; 4] { fn from(c: MyColor) -> Self { [c.r * c.a, c.g * c.a, c.b * c.a, c.a] } } let mut data = TextData::new(); if let Some(id) = font_id { data.append(TextElement { content: "Hello, Suzuri!".to_string(), font_id: id, font_size: 32.0, user_data: MyColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }, }); } ``` -------------------------------- ### Get Type ID Source: https://docs.rs/suzuri/0.2.1/suzuri/glyph_id/struct.GlyphId.html Gets the TypeId of a generic type T. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### CacheAtlas::new_batch Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Starts a new batch for cache operations. ```APIDOC fn new_batch(&mut self) ``` -------------------------------- ### wgpu_init Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Initializes the WGPU renderer with the specified device, cache configurations, and texture formats. ```APIDOC ## wgpu_init ### Description Initializes the WGPU renderer. `configs` specifies the atlas configuration. `formats` specifies the texture formats that will be used for rendering, allowing pipeline pre-compilation. ### Method Signature `pub fn wgpu_init(&self, device: &wgpu::Device, configs: &[GpuCacheConfig], formats: &[wgpu::TextureFormat])` ### Parameters - `device`: A reference to the `wgpu::Device` to be used for rendering. - `configs`: A slice of `GpuCacheConfig` specifying the atlas configurations. - `formats`: A slice of `wgpu::TextureFormat` specifying the texture formats for rendering. ``` -------------------------------- ### Get Target Size Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/wgpu_renderer/struct.SimpleRenderPass.html Returns the dimensions of the target rendering area in pixels. ```rust fn target_size(&self) -> Result<[f32; 2], ()> ``` -------------------------------- ### Get Face by ID Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_storage.rs.html Retrieves face information for a specific font ID. ```APIDOC ## face ### Description Returns face info for an ID. ### Signature `pub fn face(&self, id: fontdb::ID) -> Option<&fontdb::FaceInfo>` ### Parameters #### Path Parameters - **id** (fontdb::ID) - Required - The unique identifier for the font face. ``` -------------------------------- ### WGPU Renderer Initialization Source: https://docs.rs/suzuri/0.2.1/suzuri/font_system/struct.FontSystem.html Methods for initializing the WGPU renderer, available when the 'wgpu' feature is enabled. ```APIDOC ## pub fn wgpu_init( &self, device: &Device, configs: &[GpuCacheConfig], formats: &[TextureFormat], ) ### Description Available on **crate feature`wgpu`** only. Initializes the WGPU renderer. `configs` specifies the atlas configuration. `formats` specifies the texture formats that will be used for rendering, allowing pipeline pre-compilation. ### Method `wgpu_init` ### Parameters - `device` (&Device): The WGPU device. - `configs` (slice of `GpuCacheConfig`): Atlas configuration. - `formats` (slice of `TextureFormat`): Texture formats for rendering. ``` ```APIDOC ## pub fn wgpu_ensure_init( &self, device: &Device, configs: &[GpuCacheConfig], formats: &[TextureFormat], ) ### Description Available on **crate feature`wgpu`** only. Initializes the WGPU renderer with the given cache configuration if it is not already initialized. ### Method `wgpu_ensure_init` ### Parameters - `device` (&Device): The WGPU device. - `configs` (slice of `GpuCacheConfig`): Atlas configuration. - `formats` (slice of `TextureFormat`): Texture formats for rendering. ``` -------------------------------- ### Initialize and Use CpuRenderer Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/cpu_renderer/struct.CpuRenderer.html Demonstrates the standalone usage of CpuRenderer by initializing FontSystem, loading fonts, configuring the CPU renderer, preparing text data, performing layout, and finally rendering the text into a pixel buffer with alpha blending. ```rust use suzuri:: FontSystem, fontdb, renderer::CpuCacheConfig, text::{TextData, TextElement, TextLayoutConfig} ; use std::num::NonZeroUsize; // 1. Initialize FontSystem & Load Fonts let font_system = FontSystem::new(); font_system.load_system_fonts(); // 2. Initialize CPU Renderer let cache_configs = [ CpuCacheConfig { block_size: NonZeroUsize::new(32 * 32).unwrap(), capacity: NonZeroUsize::new(1024).unwrap(), }, ]; font_system.cpu_init(&cache_configs); // 3. Prepare Text Data (UserData = u8 brightness) let mut data = TextData::::new(); // ... append text elements ... // data.append(TextElement { ... }); // 4. Layout let layout = font_system.layout_text(&data, &TextLayoutConfig::default()); // 5. Render let width = 640; let height = 480; let mut buffer = vec![0u8; width * height]; font_system.cpu_render( &layout, [width, height], &mut |pos, alpha, color| { let idx = pos[1] * width + pos[0]; // Alpha blending with user_data (color) let val = (alpha as u16 * *color as u16 / 255) as u8; buffer[idx] = buffer[idx].saturating_add(val); } ); ``` -------------------------------- ### Get GlyphId Font Size Source: https://docs.rs/suzuri/0.2.1/suzuri/glyph_id/struct.GlyphId.html Retrieves the font size associated with the GlyphId. ```rust pub fn font_size(&self) -> f32 ``` -------------------------------- ### Initialize WGPU Resources Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Initializes a collection of WGPU resources including pipelines, shaders, buffers, and bind groups. It also pre-fetches pipelines for given formats. ```rust let resources = WgpuResources { pipelines: std::cell::RefCell::new(HashMap::new()), standalone_pipelines: std::cell::RefCell::new(HashMap::new()), pipeline_layout, standalone_pipeline_layout, shader, standalone_shader, atlas_texture, sampler, instance_buffer: std::cell::RefCell::new(instance_buffer), _bind_group_layout: bind_group_layout, standalone_bind_group_layout, globals_buffer, globals_bind_group, standalone_resources: std::cell::RefCell::new(None), instance_data_staging: std::cell::RefCell::new(Vec::new()), pixel_staging: std::cell::RefCell::new(Vec::new()), }; for &format in formats { resources.get_pipeline(device, format); resources.get_standalone_pipeline(device, format); } ``` -------------------------------- ### Get GlyphId Glyph Index Source: https://docs.rs/suzuri/0.2.1/suzuri/glyph_id/struct.GlyphId.html Retrieves the glyph index associated with the GlyphId. ```rust pub fn glyph_index(&self) -> u16 ``` -------------------------------- ### Get GlyphId Font ID Source: https://docs.rs/suzuri/0.2.1/suzuri/glyph_id/struct.GlyphId.html Retrieves the font ID associated with the GlyphId. ```rust pub fn font_id(&self) -> ID ``` -------------------------------- ### Generic GPU Renderer Initialization Source: https://docs.rs/suzuri/0.2.1/suzuri/font_system/struct.FontSystem.html Methods for initializing and ensuring the generic GPU renderer is ready. ```APIDOC ## pub fn gpu_init(&self, configs: &[GpuCacheConfig]) ### Description Initializes the generic GPU renderer with the given cache configuration. This will replace any existing GPU renderer. ### Method `gpu_init` ### Parameters - `configs` (slice of `GpuCacheConfig`): Configuration for the GPU cache. ``` ```APIDOC ## pub fn gpu_ensure_init(&self, configs: &[GpuCacheConfig]) ### Description Initializes the generic GPU renderer with the given cache configuration if it is not already initialized. ### Method `gpu_ensure_init` ### Parameters - `configs` (slice of `GpuCacheConfig`): Configuration for the GPU cache. ``` -------------------------------- ### Get LayoutBuffer Width Source: https://docs.rs/suzuri/0.2.1/src/suzuri/text/layout.rs.html Returns the current width of the buffer. Ensures the width is non-negative. ```rust pub fn width(&self) -> f32 { self.instance_length.max(0.0) } ``` -------------------------------- ### GpuRenderer Initialization and Usage Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer.rs.html Demonstrates how to initialize the GpuRenderer with cache configurations and use it to render text via callbacks for texture updates and drawing glyphs. ```rust use suzuri:: { FontSystem, fontdb, renderer::{GpuCacheConfig, AtlasUpdate, GlyphInstance, StandaloneGlyph}, text::{TextData, TextElement, TextLayoutConfig} }; use std::num::NonZeroUsize; let font_system = FontSystem::new(); font_system.load_system_fonts(); // 1. Initialize Renderer let cache_configs = [ GpuCacheConfig { texture_size: NonZeroUsize::new(1024).unwrap(), tile_size: NonZeroUsize::new(32).unwrap(), // one side length tiles_per_axis: NonZeroUsize::new(32).unwrap(), }, ]; font_system.gpu_init(&cache_configs); // 2. Layout Text let mut data = TextData::::new(); // ... (append text elements) ... let layout = font_system.layout_text(&data, &TextLayoutConfig::default()); // 3. Render (Generic Loop) font_system.gpu_render( &layout, |updates: &[AtlasUpdate]| { // Upload 'pixels' to texture 'texture_index' at (x, y) }, |instances: &[GlyphInstance]| { // Add instances to a vertex buffer or draw them directly }, |standalone: &StandaloneGlyph| { // Handle large glyphs separately (e.g. create a temporary texture) } ); ``` -------------------------------- ### Get Face Source Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_storage.rs.html Retrieves the source information and index for a given font ID. ```APIDOC ## face_source ### Description Returns the source of a face. ### Signature `pub fn face_source(&self, id: fontdb::ID) -> Option<(fontdb::Source, u32)>` ### Parameters #### Path Parameters - **id** (fontdb::ID) - Required - The unique identifier for the font face. ``` -------------------------------- ### WgpuRenderer::new Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/wgpu_renderer/struct.WgpuRenderer.html Initializes a new WgpuRenderer instance. It requires a wgpu Device, cache configurations, and a list of texture formats for pipeline caching. Panics if the provided cache configurations are empty. ```APIDOC ## WgpuRenderer::new ### Description Initializes a new `WgpuRenderer` instance. It requires a wgpu `Device`, cache configurations, and a list of texture formats for pipeline caching. Panics if the provided cache configurations are empty. ### Parameters - `device`: A reference to the wgpu `Device`. - `configs`: A slice of `GpuCacheConfig` specifying texture cache parameters. - `formats`: A slice of `wgpu::TextureFormat` to pre-compile render pipelines for. ### Panics Panics if `configs` is empty. ``` -------------------------------- ### LayoutEngine::new Constructor Source: https://docs.rs/suzuri/0.2.1/src/suzuri/text/layout.rs.html Initializes a new `LayoutEngine` with the given configuration and font storage. It sets up internal buffers for lines, words, and line metrics. ```rust fn new( config: &'a TextLayoutConfig, font_storage: &'a mut crate::font_storage::FontStorage, ) -> Self { Self { config, font_storage, lines: Vec::new(), line_buf: None, word_buf: None, last_line_metrics: None, } } ``` -------------------------------- ### Get Number of Loaded Faces Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Returns the total count of font faces currently loaded in the system. ```rust pub fn len(&self) -> usize { self.font_storage.lock().len() } ``` -------------------------------- ### Initialize FontSystem Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Creates a new FontSystem with default font storage and uninitialized renderers. Use `Default::default()` for the same effect. ```rust pub struct FontSystem { /// The underlying font storage. pub font_storage: Mutex, /// The CPU renderer instance (optional). pub cpu_renderer: Mutex>>, /// The generic GPU renderer instance (optional). pub gpu_renderer: Mutex>>, #[cfg(feature = "wgpu")] /// The wgpu renderer instance (optional). pub wgpu_renderer: Mutex>> } impl Default for FontSystem { fn default() -> Self { Self::new() } } impl FontSystem { /// Creates a new font system with empty renderers and default storage. pub fn new() -> Self { Self { font_storage: Mutex::new(FontStorage::new()), cpu_renderer: Mutex::new(None), gpu_renderer: Mutex::new(None), #[cfg(feature = "wgpu")] wgpu_renderer: Mutex::new(None), } } } ``` -------------------------------- ### Get Target Texture Format Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/wgpu_renderer/struct.SimpleRenderPass.html Returns the target texture format, which is used for selecting the appropriate graphics pipeline. ```rust fn format(&self) -> Result ``` -------------------------------- ### Create WGPU Sampler Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Initializes a WGPU sampler with clamp-to-edge addressing modes and linear filtering for both magnification and minification. This sampler is used for texture lookups during rendering. ```rust let sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() }); ``` -------------------------------- ### wgpu_ensure_init Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Initializes the WGPU renderer with the given cache configuration if it is not already initialized. ```APIDOC ## wgpu_ensure_init ### Description Initializes the WGPU renderer with the given cache configuration if it is not already initialized. ### Method Signature `pub fn wgpu_ensure_init(&self, device: &wgpu::Device, configs: &[GpuCacheConfig], formats: &[wgpu::TextureFormat])` ### Parameters - `device`: A reference to the `wgpu::Device` to be used for rendering. - `configs`: A slice of `GpuCacheConfig` specifying the atlas configurations. - `formats`: A slice of `wgpu::TextureFormat` specifying the texture formats for rendering. ``` -------------------------------- ### Get Font Family Name Source: https://docs.rs/suzuri/0.2.1/suzuri/font_storage/struct.FontStorage.html Retrieves the name of a given font family. Useful for display or identification purposes. ```rust pub fn family_name<'a>(&'a self, family: &'a Family<'_>) -> &'a str ``` -------------------------------- ### Create WGPU Pipeline Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Creates a WGPU pipeline for rendering, configuring primitive topology, front face, polygon mode, and depth stencil state. ```rust topology: wgpu::PrimitiveTopology::TriangleStrip, strip_index_format: None, front_face: wgpu::FrontFace::Ccw, cull_mode: None, unclipped_depth: false, polygon_mode: wgpu::PolygonMode::Fill, conservative: false, }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), multiview: None, cache: None, }); self.standalone_pipelines .borrow_mut() .insert(format, pipeline.clone()); pipeline ``` -------------------------------- ### Get Number of Loaded Font Faces Source: https://docs.rs/suzuri/0.2.1/suzuri/font_storage/struct.FontStorage.html Returns the total number of font faces currently loaded in the storage. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Get Face Information by ID Source: https://docs.rs/suzuri/0.2.1/suzuri/font_storage/struct.FontStorage.html Retrieves the FaceInfo for a specific font face ID. Returns None if the ID is not found. ```rust pub fn face(&self, id: ID) -> Option<&FaceInfo> ``` -------------------------------- ### Render Instances with WGPU Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Renders a batch of instances using the WGPU API. Ensures sufficient capacity in the instance buffer before copying data and drawing. ```rust let instance_size = std::mem::size_of::() as u64; let needed_bytes = current_offset.get() + instance_data.len() as u64 * instance_size; self.ensure_instance_buffer_capacity(device, needed_bytes, &mut instance_buffer); let offset = current_offset.get(); let bytes = bytemuck::cast_slice(&instance_data); let staging_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Instance Staging Buffer"), contents: bytes, usage: wgpu::BufferUsages::COPY_SRC, }); controller.encoder()?.copy_buffer_to_buffer( &staging_buffer, 0, &instance_buffer, offset, bytes.len() as u64, ); let format = controller.format()?; let mut rpass = controller.create_pass()?; // Use cached pipeline or create new one based on format let pipeline = self.get_pipeline(device, format); rpass.set_pipeline(&pipeline); rpass.set_bind_group(0, &self.globals_bind_group, &[]); rpass.set_vertex_buffer( 0, instance_buffer.slice(offset..offset + bytes.len() as u64), ); rpass.draw(0..4, 0..instance_data.len() as u32); current_offset.set(offset + bytes.len() as u64); Ok(()) } ``` -------------------------------- ### FontSystem Initialization Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Provides methods for creating and initializing the FontSystem, including setting up default storage and renderers. ```APIDOC ## FontSystem::new() ### Description Creates a new font system with empty renderers and default storage. ### Method `FontSystem::new()` ### Returns A new instance of `FontSystem`. ``` ```APIDOC ## FontSystem::default() ### Description Creates a new font system with empty renderers and default storage, using the `Default` trait implementation. ### Method `FontSystem::default()` ### Returns A new instance of `FontSystem`. ``` -------------------------------- ### Get Family Name Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_storage.rs.html Retrieves the string name of a given font family. This is useful for displaying font names or for debugging. ```rust pub fn family_name<'a>(&'a self, family: &'a fontdb::Family<'_>) -> &'a str { self.font_db.family_name(family) } ``` -------------------------------- ### wgpu_render_to Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Renders text using the WGPU renderer with a custom render pass controller. ```APIDOC ## wgpu_render_to ### Description Renders text using the WGPU renderer with a custom render pass controller. This allows for more flexible rendering scenarios, such as custom render passes or integration with other rendering pipelines. ### Method Signature `pub fn wgpu_render_to + Copy, E>(&self, text_layout: &TextLayout, device: &wgpu::Device, controller: &mut impl WgpuRenderPassController) -> Result<(), E>` ### Parameters - `text_layout`: A reference to the `TextLayout` to be rendered. - `device`: A reference to the `wgpu::Device`. - `controller`: A mutable reference to a type implementing `WgpuRenderPassController`. ### Returns - `Result<(), E>`: Returns `Ok(())` on success or an error `E` if the WGPU renderer is not initialized or if the controller returns an error. ``` -------------------------------- ### Get and Protect Glyph Cache Entry Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Retrieves a glyph entry from the cache, protecting it from eviction. Use when an entry is actively being used. ```rust match self { Self::Fixed(c) => c.get_and_protect_entry(glyph_id, font_storage), Self::Fallback(c) => c.get_and_protect_entry(glyph_id, font_storage), } ``` -------------------------------- ### Initialize WGPU Renderer Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Initializes the WGPU renderer. `configs` specifies the atlas configuration. `formats` specifies the texture formats that will be used for rendering, allowing pipeline pre-compilation. ```rust pub fn wgpu_init( &self, device: &wgpu::Device, configs: &[GpuCacheConfig], formats: &[wgpu::TextureFormat], ) { // ensures first drop previous resource and then create new one to avoid unnecessary memory usage. *self.wgpu_renderer.lock() = None; *self.wgpu_renderer.lock() = Some(Box::new(WgpuRenderer::new(device, configs, formats))); } ``` -------------------------------- ### Get Number of Lines in TextLayout Source: https://docs.rs/suzuri/0.2.1/suzuri/text/layout/struct.TextLayout.html Returns the count of text lines within the TextLayout. This is useful for iterating or processing line by line. ```rust pub fn len_lines(&self) -> usize ``` -------------------------------- ### SimpleRenderPass::new Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Creates a new `SimpleRenderPass` instance, initializing it with default settings. ```APIDOC ## SimpleRenderPass::new ### Description Constructs a new `SimpleRenderPass` with a given `CommandEncoder` and `TextureView`. By default, the render pass will clear the screen to black on the first draw call. ### Parameters - `encoder`: A mutable reference to the `wgpu::CommandEncoder` to be used for rendering. - `view`: A reference to the `wgpu::TextureView` onto which the rendering will occur. ``` -------------------------------- ### Get Mutable Command Encoder Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/wgpu_renderer/struct.SimpleRenderPass.html Returns a mutable reference to the command encoder associated with the SimpleRenderPass. This is used for recording copy commands. ```rust fn encoder(&mut self) -> Result<&mut CommandEncoder, ()> ``` -------------------------------- ### Get and Protect Glyph Entry Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Retrieves the texture coordinates for a cached glyph and protects its entry from eviction. Returns `None` if the glyph is not found in the cache. ```rust let index = self.cache_state.get_and_protect_entry(glyph_id)?; let x = (index % self.tiles_per_axis) * self.tile_size; let y = (index / self.tiles_per_axis) * self.tile_size; Some([x, y]) ``` -------------------------------- ### Get Number of Loaded Faces Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_storage.rs.html Returns the total count of font faces currently loaded in the storage. This includes all faces managed by the internal fontdb. ```rust pub fn len(&self) -> usize { self.font_db.len() } ``` -------------------------------- ### Initialize and Use CpuRenderer with FontSystem Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/cpu_renderer.rs.html Demonstrates the high-level integration of CpuRenderer through FontSystem, including font loading, renderer initialization with cache configurations, text data preparation, layout, and rendering with custom pixel blending. ```rust use suzuri { FontSystem, fontdb, renderer::CpuCacheConfig, text::{TextData, TextElement, TextLayoutConfig} }; use std::num::NonZeroUsize; // 1. Initialize FontSystem & Load Fonts let font_system = FontSystem::new(); font_system.load_system_fonts(); // 2. Initialize CPU Renderer let cache_configs = [ CpuCacheConfig { block_size: NonZeroUsize::new(32 * 32).unwrap(), capacity: NonZeroUsize::new(1024).unwrap(), }, ]; font_system.cpu_init(&cache_configs); // 3. Prepare Text Data (UserData = u8 brightness) let mut data = TextData::::new(); // ... append text elements ... // data.append(TextElement { ... }); // 4. Layout let layout = font_system.layout_text(&data, &TextLayoutConfig::default()); // 5. Render let width = 640; let height = 480; let mut buffer = vec![0u8; width * height]; font_system.cpu_render( &layout, [width, height], &mut |pos, alpha, color| { let idx = pos[1] * width + pos[0]; // Alpha blending with user_data (color) let val = (alpha as u16 * *color as u16 / 255) as u8; buffer[idx] = buffer[idx].saturating_add(val); } ); ``` -------------------------------- ### Initialize FontStorage Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_storage.rs.html Creates a new, empty FontStorage instance. Initializes an empty fontdb database and a HashMap for loaded fonts with a default FxBuildHasher. ```rust pub fn new() -> Self { Self { font_db: fontdb::Database::new(), loaded_font: HashMap::with_hasher(fxhash::FxBuildHasher::default()), } } ``` -------------------------------- ### Get Line Metrics from LayoutBuffer Source: https://docs.rs/suzuri/0.2.1/src/suzuri/text/layout.rs.html Returns line metrics (max accent, max descent, max line gap) derived from the buffered glyph fragments. ```rust pub fn line_metrics(&self) -> (f32, f32, f32) { (self.max_accent, self.max_descent, self.max_line_gap) } ``` -------------------------------- ### FallbackGpuCache: Get and Protect Entry Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Retrieves a glyph's cached item if it exists and is protected, without performing eviction. This method is part of the `FallbackGpuCache` strategy. ```rust fn get_and_protect_entry( &mut self, glyph_id: &GlyphId, font_storage: &mut FontStorage, ) -> Option { let glyph_index = glyph_id.glyph_index(); let font_size = glyph_id.font_size(); let font_id = glyph_id.font_id(); let font = font_storage.font(font_id)?; let glyph_metrics = font.metrics_indexed(glyph_index, font_size); let glyph_bitmap_size = glyph_metrics.width.max(glyph_metrics.height) + ATLAS_MARGIN; let start_index = self .caches .iter() .position(|cache| glyph_bitmap_size <= cache.tile_size)?; for i in start_index..self.caches.len() { if let Some([x_min, y_min]) = self.caches[i].get_and_protect_entry(glyph_id) { let cache = &self.caches[i]; let texture_index = i; let texture_size = cache.texture_size; let x_max = x_min + glyph_metrics.width; let y_max = y_min + glyph_metrics.height; let glyph_box = Box2D::new(Point2D::new(x_min, y_min), Point2D::new(x_max, y_max)); return Some(GpuCacheItem { texture_index, texture_size, glyph_box, }); } } None } ``` -------------------------------- ### Configure and Instantiate CpuCache Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/cpu_renderer/glyph_cache.rs.html Defines cache configurations with specific block sizes and capacities, then instantiates a CpuCache with these settings. Asserts the number of caches and their block sizes. ```rust let config = [ CpuCacheConfig { block_size: NonZeroUsize::new(10).unwrap(), capacity: NonZeroUsize::new(100).unwrap(), }, CpuCacheConfig { block_size: NonZeroUsize::new(20).unwrap(), capacity: NonZeroUsize::new(50).unwrap(), }, ]; let cache = CpuCache::new(&config); assert_eq!(cache.caches.len(), 2); assert_eq!(cache.caches[0].block_size, 10); assert_eq!(cache.caches[1].block_size, 20); ``` -------------------------------- ### FontSystem::cpu_init Source: https://docs.rs/suzuri/0.2.1/suzuri/font_system/struct.FontSystem.html Initializes the CPU renderer with specified cache configurations. ```APIDOC ## FontSystem::cpu_init ### Description Initializes the CPU renderer with the given cache configuration. This will replace any existing CPU renderer. ### Method ```rust pub fn cpu_init(&self, configs: &[CpuCacheConfig]) ``` ### Parameters - `configs`: A slice of `CpuCacheConfig` to configure the CPU renderer's cache. ``` -------------------------------- ### Get Total Number of Glyphs in TextLayout Source: https://docs.rs/suzuri/0.2.1/suzuri/text/layout/struct.TextLayout.html Calculates and returns the total number of glyphs across all lines in the TextLayout. Useful for performance analysis or resource estimation. ```rust pub fn len_glyphs(&self) -> usize ``` -------------------------------- ### Create WGPU Pipeline Layout Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Creates a pipeline layout for WGPU, defining bind group layouts and push constant ranges. Used for both standard and standalone pipelines. ```rust let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("WgpuRenderer Pipeline Layout"), bind_group_layouts: &[&bind_group_layout], push_constant_ranges: &[], }); let standalone_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("WgpuRenderer Standalone Pipeline Layout"), bind_group_layouts: &[&standalone_bind_group_layout], push_constant_ranges: &[], }); ``` -------------------------------- ### Get All Face Information Source: https://docs.rs/suzuri/0.2.1/suzuri/font_system/struct.FontSystem.html Returns a vector containing information about all loaded font faces. This method clones face info to avoid holding a lock on storage. ```rust pub fn faces(&self) -> Vec ``` -------------------------------- ### CpuRenderer::new Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/cpu_renderer.rs.html Creates a new CpuRenderer instance with the specified cache configurations. ```APIDOC ## CpuRenderer::new ### Description Creates a new `CpuRenderer` instance, initializing its internal glyph cache with the provided configurations. ### Signature ```rust pub fn new(configs: &[CpuCacheConfig]) -> Self ``` ### Parameters * `configs` (`&[CpuCacheConfig]`) - A slice of `CpuCacheConfig` structs defining the properties of the glyph caches to be used. ``` -------------------------------- ### Get Font Face Source Information Source: https://docs.rs/suzuri/0.2.1/suzuri/font_storage/struct.FontStorage.html Returns the source information (e.g., file path or data origin) and index for a given font face ID. ```rust pub fn face_source(&self, id: ID) -> Option<(Source, u32)> ``` -------------------------------- ### Get Glyph from CpuCache Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/cpu_renderer/struct.CpuCache.html Retrieves a glyph from the cache using its ID. If the glyph is not found, it will be rasterized and then cached. Requires mutable access to both the cache and font storage. ```rust pub fn get( &mut self, glyph_id: &GlyphId, font_storage: &mut FontStorage, ) -> Option> ``` -------------------------------- ### Create WGPU Shader Module Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/wgpu_renderer.rs.html Creates a shader module from WGSL source code for WGPU rendering. Supports both standard and standalone shaders. ```rust let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("WgpuRenderer Shader"), source: wgpu::ShaderSource::Wgsl(SHADER.into()), }); let standalone_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("WgpuRenderer Standalone Shader"), source: wgpu::ShaderSource::Wgsl(STANDALONE_SHADER.into()), }); ``` -------------------------------- ### Ensure WGPU Renderer Initialization Source: https://docs.rs/suzuri/0.2.1/src/suzuri/font_system.rs.html Initializes the WGPU renderer with the given cache configuration if it is not already initialized. ```rust pub fn wgpu_ensure_init( &self, device: &wgpu::Device, configs: &[GpuCacheConfig], formats: &[wgpu::TextureFormat], ) { if self.wgpu_renderer.lock().is_none() { self.wgpu_init(device, configs, formats); } } ``` -------------------------------- ### Get and Protect Glyph Entry Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Retrieves a glyph's `GpuCacheItem` from the cache and protects it, ensuring it is not immediately evicted. This is useful when a glyph is actively being used and should be prioritized for retention. ```rust fn get_and_protect_entry( &mut self, glyph_id: &GlyphId, font_storage: &mut FontStorage, ) -> Option { let glyph_index = glyph_id.glyph_index(); let font_size = glyph_id.font_size(); let font_id = glyph_id.font_id(); let font = font_storage.font(font_id)?; let glyph_metrics = font.metrics_indexed(glyph_index, font_size); let glyph_bitmap_size = glyph_metrics.width.max(glyph_metrics.height) + ATLAS_MARGIN; let cache_index = self .caches .iter() .position(|cache| glyph_bitmap_size <= cache.tile_size)?; let cache = &mut self.caches[cache_index]; let texture_index = cache_index; let texture_size = cache.texture_size; let [x_min, y_min] = cache.get_and_protect_entry(glyph_id)?; let x_max = x_min + glyph_metrics.width; let y_max = y_min + glyph_metrics.height; let glyph_box = Box2D::new(Point2D::new(x_min, y_min), Point2D::new(x_max, y_max)); Some(GpuCacheItem { texture_index, texture_size, glyph_box, }) } ``` -------------------------------- ### CacheAtlas::new Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Creates a new `CacheAtlas` instance with the given configuration. Panics if configuration is invalid. ```APIDOC /// Creates a new `CacheAtlas` instance. /// /// # Panics /// When: /// - tile_size * tiles_per_axis > texture_size /// - texture_size^2 > usize::MAX #[allow(clippy::unwrap_used)] fn new(config: &GpuCacheConfig) -> Self ``` -------------------------------- ### FontSystem::new Source: https://docs.rs/suzuri/0.2.1/suzuri/font_system/struct.FontSystem.html Creates a new font system instance with empty renderers and default font storage. ```APIDOC ## FontSystem::new ### Description Creates a new font system with empty renderers and default storage. ### Method ```rust pub fn new() -> Self ``` ### Returns A new `FontSystem` instance. ``` -------------------------------- ### Get Face Information by ID Source: https://docs.rs/suzuri/0.2.1/suzuri/font_system/struct.FontSystem.html Retrieves the specific information for a font face identified by its ID. This method clones the face info to avoid holding a lock on storage. ```rust pub fn face(&self, id: ID) -> Option ``` -------------------------------- ### Get and Protect Cache Entry Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/gpu_renderer/enum.GpuCache.html Retrieves a protected entry from the GpuCache without triggering eviction. Requires mutable access to the cache, glyph ID, and font storage. ```rust pub fn get_and_protect_entry( &mut self, glyph_id: &GlyphId, font_storage: &mut FontStorage, ) -> Option ``` -------------------------------- ### CpuCache::new Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/cpu_renderer/struct.CpuCache.html Creates a new CPU cache with the provided configurations. ```APIDOC ## CpuCache::new ### Description Creates a new CPU cache with the provided configurations. ### Signature `pub fn new(configs: &[CpuCacheConfig]) -> Self` ``` -------------------------------- ### Append Fragments with Layout Rules Source: https://docs.rs/suzuri/0.2.1/src/suzuri/text/layout.rs.html Appends glyph fragments to the current line, applying rules to drop leading spaces if they start a new line to prevent indentation. ```rust fn append_fragments_with_rules( &mut self, fragments: &[layout_utl::GlyphFragment], allow_leading_space: bool, ) { if fragments.is_empty() { return; } // Rule: Drop leading spaces if they start a new line. // This prevents lines from looking indented due to a wrapped space. if !allow_leading_space && let Some(first) = fragments.first() && first.ch.is_whitespace() && self .line_buf .as_ref() .map(|line| line.glyphs.is_empty()) .unwrap_or(true) { return; } self.append_fragments_to_line(fragments); } ``` -------------------------------- ### Configure and Perform Text Layout Source: https://docs.rs/suzuri/0.2.1/suzuri/index.html Configure text layout settings using TextLayoutConfig, specifying parameters like maximum width, alignment, and line height. Then, use the FontSystem to calculate the text layout. ```rust use suzuri::text::{TextLayoutConfig, HorizontalAlign, VerticalAlign, WrapStyle}; let config = TextLayoutConfig { max_width: Some(800.0), max_height: None, horizontal_align: HorizontalAlign::Left, vertical_align: VerticalAlign::Top, line_height_scale: 1.2, wrap_style: WrapStyle::WordWrap, ..Default::default() }; let layout = font_system.layout_text(&data, &config); ``` -------------------------------- ### Create GpuCache with Specific Strategy Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/gpu_renderer/enum.GpuCache.html Initializes a new GpuCache instance with a specified GpuCacheStrategy. Requires configuration and the desired strategy. ```rust pub fn new_with_strategy( configs: &[GpuCacheConfig], strategy: GpuCacheStrategy, ) -> Self ``` -------------------------------- ### Get Generic Font Family Name Source: https://docs.rs/suzuri/0.2.1/suzuri/font_system/struct.FontSystem.html Retrieves the name of a specified generic font family. This method allocates a new String to avoid holding a lock on the font storage. ```rust pub fn family_name<'a>(&'a self, family: &'a Family<'_>) -> String ``` -------------------------------- ### Create GpuCache with Default Strategy Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/gpu_renderer/enum.GpuCache.html Initializes a new GpuCache instance using the default (Fallback) strategy. Requires a slice of GpuCacheConfig. ```rust pub fn new(configs: &[GpuCacheConfig]) -> Self ``` -------------------------------- ### CpuCache Get Function Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/cpu_renderer/glyph_cache.rs.html Retrieves a glyph from the cache. If the glyph is not found, it rasterizes the glyph using the provided font storage and then caches it. Requires mutable access to `self` and `font_storage`. ```rust pub fn get( &'_ mut self, glyph_id: &GlyphId, font_storage: &mut FontStorage, ) -> Option> { let glyph_index = glyph_id.glyph_index(); let font_size = glyph_id.font_size(); let font_id = glyph_id.font_id(); let font = font_storage.font(font_id)?; let glyph_metrics = font.metrics_indexed(glyph_index, font_size); let glyph_bitmap_size = glyph_metrics.width * glyph_metrics.height; let cache = self .caches .iter_mut() .find(|cache| cache.block_size >= glyph_bitmap_size)?; let data = cache.get_or_insert_with(glyph_id, || { let bitmap = font.rasterize_indexed(glyph_index, font_size); bitmap.1 }); Some(CpuCacheItem { width: glyph_metrics.width, height: glyph_metrics.height, data: Cow::Borrowed(data), }) } ``` -------------------------------- ### Enable WGPU Feature in Cargo.toml Source: https://docs.rs/suzuri/0.2.1/suzuri/index.html To use wgpu features, enable the 'wgpu' feature in your Cargo.toml. ```toml [dependencies] suzuri = { version = "0.2.0", features = ["wgpu"] } ``` -------------------------------- ### Get and Push with Evicting Unprotected Source: https://docs.rs/suzuri/0.2.1/src/suzuri/renderer/gpu_renderer/glyph_cache.rs.html Retrieves texture coordinates for a glyph, pushing it if not present. If the cache is full, it evicts unprotected entries to make space. Returns `None` if the glyph cannot be added. ```rust let index = self.cache_state.push_and_evicting_unprotected(glyph_id)?; let x = (index % self.tiles_per_axis) * self.tile_size; let y = (index / self.tiles_per_axis) * self.tile_size; Some([x, y]) ``` -------------------------------- ### Create New CpuCache Source: https://docs.rs/suzuri/0.2.1/suzuri/renderer/cpu_renderer/struct.CpuCache.html Initializes a new CpuCache instance with a slice of CpuCacheConfig. Ensure configurations are valid before calling. ```rust pub fn new(configs: &[CpuCacheConfig]) -> Self> ```