### Box::take example Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Example for the `Box::take` method, which consumes the box and returns the value plus a box to uninitialized memory. The example shows taking the value, then reusing the allocation with `Box::write`. ```rust #![feature(box_take)] let c = Box::new(5); // take the value out of the box let (value, uninit) = Box::take(c); assert_eq!(value, 5); // reuse the box for a second value let c = Box::write(uninit, 6); assert_eq!(*c, 6); ``` -------------------------------- ### Box::clone_from_ref_in example Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Example for the `Box::clone_from_ref_in` method, which allocates memory in the given allocator and clones `src` into it. The example uses the `System` allocator and requires the `clone_from_ref` and `allocator_api` features. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::clone_from_ref_in("hello", System); ``` -------------------------------- ### Box::try_clone_from_ref_in example Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Example for the `Box::try_clone_from_ref_in` method, which allocates memory in the given allocator and clones `src` into it, returning an error if allocation fails. The example uses the `System` allocator and the `?` operator. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::try_clone_from_ref_in("hello", System)?; ``` -------------------------------- ### Box::from_raw Example: Manual allocation Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Manually create a Box from scratch by using the global allocator. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Box::from_non_null Example: Manual allocation Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Manually create a Box from scratch by using the global allocator with NonNull. ```rust use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("alloc should have successfully allocated memory"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Box::into_raw Example: Manual cleanup Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Manual cleanup by explicitly running the destructor and deallocating the memory. ```rust use std::alloc::{dealloc, Layout}; use std::ptr; let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); unsafe { ptr::drop_in_place(ptr); dealloc(ptr as *mut u8, Layout::new::()); } ``` -------------------------------- ### Box::into_raw Example: Drop equivalent Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Demonstrates an equivalent way to perform cleanup using drop and Box::from_raw. ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); unsafe { drop(Box::from_raw(ptr)); } ``` -------------------------------- ### Demonstration of ambiguous From implementation Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html An example of a discouraged From implementation that creates ambiguity when calling Pin::from. ```rust struct Foo; // A type defined in this crate. impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### Box::into_inner example Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Example for the `into_inner` method, showing how to extract the value from a box. The assertion checks that the extracted value equals 5. ```rust assert_eq!(Box::into_inner(c), 5); ``` -------------------------------- ### Box::from_raw Example: Recreating from pointer Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Recreate a Box which was previously converted to a raw pointer using Box::into_raw. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### Box::try_map example Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Example for the `Box::try_map` associated function, which attempts to map the value in a box and returns a `Result`. The example uses `u32::try_from` and unwraps the result. ```rust #![feature(smart_pointer_try_map)] let b = Box::new(7); let new = Box::try_map(b, u32::try_from).unwrap(); assert_eq!(*new, 7); ``` -------------------------------- ### Box::into_raw Example: Automatic cleanup Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Converting the raw pointer back into a Box with Box::from_raw for automatic cleanup. ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### Box::from_non_null Example: Recreating from pointer Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Recreate a Box which was previously converted to a NonNull pointer using Box::into_non_null. ```rust let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` -------------------------------- ### setup_custom_glyph_font Source: https://docs.rs/klyff/latest/klyff/fn.setup_custom_glyph_font.html Loads the bundled PUA font into the given FontSystem and returns a CustomGlyphFont handle. Call once during setup and register the handle with the renderer or encoder. ```APIDOC ## Function setup_custom_glyph_font ### Description Loads the bundled PUA font into the provided `FontSystem` and returns a handle identifying it. Call this once during setup. The returned `CustomGlyphFont` must be registered with the renderer or encoder that will detect custom glyphs. After this, `crate::StyledTextBuilder::push_custom_glyph` can insert custom glyphs into text. ### Signature ```rust pub fn setup_custom_glyph_font(font_system: &mut FontSystem) -> CustomGlyphFont ``` ### Parameters - **font_system** (`&mut FontSystem`) - Required - The font system to load the bundled PUA font into. ### Returns - **CustomGlyphFont** - A handle identifying the loaded custom glyph font. Must be registered with the renderer or encoder. ### Usage Notes - Call once during setup. - The returned handle must be registered with the renderer or encoder that will detect custom glyphs. - After registration, custom glyphs can be inserted into text using `crate::StyledTextBuilder::push_custom_glyph`. ``` -------------------------------- ### Box::map example Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Example for the `Box::map` associated function, which maps the value in a box and reuses the allocation if possible. The closure adds 7 to the value, and the assertion checks the result. ```rust let b = Box::new(7); let new = Box::map(b, |i| i + 7); assert_eq!(*new, 14); ``` -------------------------------- ### Color from_hex constructor Source: https://docs.rs/klyff/latest/src/klyff/data/mod.rs.html Creates a Color from a 0xRRGGBB hex literal. Example: Color::from_hex(0xFF8800). ```rust pub fn from_hex(rgb: u32) -> Self { Self::from_srgb8( ((rgb >> 16) & 0xFF) as u8, ((rgb >> 8) & 0xFF) as u8, (rgb & 0xFF) as u8, ) } ``` -------------------------------- ### Insert and get entries in Cache Source: https://docs.rs/klyff/latest/src/klyff/atlas/cache.rs.html Tests that inserting entries and retrieving them by key returns the expected values. The test asserts that each inserted key maps to its value. ```rust c.insert("b", 2); c.insert("c", 3); assert_eq!(c.get(&"a"), Some(&1)); assert_eq!(c.get(&"b"), Some(&2)); assert_eq!(c.get(&"c"), Some(&3)); } ``` -------------------------------- ### material_vertex_buffer_layout() -> wgpu::VertexBufferLayout<'static> Source: https://docs.rs/klyff/latest/src/klyff/pipelines/material_encoder.rs.html Gets the vertex buffer layout for per-vertex material inputs, defining the attributes for material index and gradient UV. ```APIDOC ## material_vertex_buffer_layout() -> wgpu::VertexBufferLayout<'static> ### Description Gets the vertex buffer layout for per-vertex material inputs, defining the attributes for material index and gradient UV. ### Returns - **wgpu::VertexBufferLayout<'static>** - The vertex buffer layout with two attributes: `material_index` (Uint32, shader location 3) and `gradient_uv` (Float32x2, shader location 4). ### Example ```rust let layout = MaterialEncoder::material_vertex_buffer_layout(); ``` ``` -------------------------------- ### Box::into_non_null equivalent cleanup with drop(Box::from_non_null) Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Equivalent to the manual cleanup example: converts the NonNull pointer back into a Box and drops it, which runs the destructor and deallocates the memory. ```rust let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); unsafe { drop(Box::from_non_null(non_null)); } ``` -------------------------------- ### Leaking a Box Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Examples of using Box::leak to obtain a static mutable reference to boxed data, including both sized and unsized types. ```rust let x = Box::new(41); let static_ref: &'static mut usize = Box::leak(x); *static_ref += 1; assert_eq!(*static_ref, 42); ``` ```rust let x = vec![1, 2, 3].into_boxed_slice(); let static_ref = Box::leak(x); static_ref[0] = 4; assert_eq!(*static_ref, [4, 2, 3]); ``` -------------------------------- ### storage_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout Source: https://docs.rs/klyff/latest/src/klyff/pipelines/material_encoder.rs.html Gets the bind group layout for the material storage buffer's bind group, which is used to bind the storage buffer to shaders. ```APIDOC ## storage_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout ### Description Gets the bind group layout for the material storage buffer's bind group, which is used to bind the storage buffer to shaders. ### Parameters - **device** (`&wgpu::Device`) - Required - The GPU device used to create the bind group layout. ### Returns - **wgpu::BindGroupLayout** - The bind group layout for the material storage buffer. ### Example ```rust let layout = MaterialEncoder::storage_bind_group_layout(&device); ``` ``` -------------------------------- ### Request WGPU Device for Tests Source: https://docs.rs/klyff/latest/src/klyff/atlas/atlas_retrieve.rs.html Helper function to initialize a wgpu device and queue for testing purposes. ```rust async fn request_device() -> Option<(wgpu::Device, wgpu::Queue)> { let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default()); let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::None, compatible_surface: None, force_fallback_adapter: false, }) .await .ok()?; adapter .request_device(&wgpu::DeviceDescriptor::default()) .await .ok() } ``` -------------------------------- ### ScreenSizeUniform::new Source: https://docs.rs/klyff/latest/klyff/struct.ScreenSizeUniform.html Constructs a new ScreenSizeUniform instance, creating necessary wgpu resources on the provided wgpu device. ```APIDOC ## ScreenSizeUniform::new ### Description Constructs a new ScreenSizeUniform instance, creating necessary wgpu resources on the provided wgpu device. ### Method new ### Signature pub fn new(device: &Device) -> Self ### Parameters - **device** (&Device) - Required - The wgpu device to create resources on. ### Returns - **Self** - A new ScreenSizeUniform instance. ``` -------------------------------- ### Render text with TextRenderer and StyledTextBuilder Source: https://docs.rs/klyff/latest/index.html Shows the full high-level API workflow: create a TextRenderer and TextureAtlas, build a StyledText with StyledTextBuilder, prepare glyphs per frame, and render inside a render pass. Requires wgpu device, queue, surface format, render target, and a cosmic_text FontSystem. Styling effects are drawn as separate draw calls in back-to-front order (shadow, outer glow, outer stroke, fill, inner glow, inner stroke). ```rust use klyff::{ EncoderContext, Rect, StyledTextBuilder, TextRenderer, TextStyle, TextureAtlas, TextureAtlasDescriptor, cosmic_text::{Attrs, Family, FontSystem, Metrics}, }; // Dependencies let device: wgpu::Device = todo!("Obtain a device from wgpu"); let queue: wgpu::Queue = todo!("Obtain a device from wgpu"); let surface_format: wgpu::TextureFormat = todo!("Define your surface format"); let view: wgpu::TextureView = todo!("Obtain your render target"); let mut font_system: FontSystem = todo!("Obtain a font system from cosmic_text"); let (width, height) = (800u32, 600u32); // One-time setup: a renderer for the swapchain format, and an atlas to cache glyphs. let mut renderer = TextRenderer::new(&device, surface_format); let mut atlas = TextureAtlas::new(&device, TextureAtlasDescriptor::default()); // Build a `StyledText` for the given bounding box. Each call to `push_text` adds a run. let attrs = Attrs::new().family(Family::Name("Open Sans")); let mut text_builder = StyledTextBuilder::new( Rect::from_xywh(0.0, 0.0, width as f32, height as f32), &mut font_system, Metrics::new(48.0, 60.0)); text_builder.push_text("Hello, world!", &attrs, TextStyle::default()) let text = text_builder.finish(&mut font_system, &attrs); // Per frame: prepare uploads glyphs into the atlas and writes vertex buffers. let mut cmd_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); renderer.prepare( EncoderContext { atlas: &mut atlas, device: &device, queue: &queue, cmd_encoder: &mut cmd_encoder, font_system: &mut font_system, }, (width, height), std::slice::from_ref(&text), ); // Then issue the draw inside any render pass that targets `surface_format`. let mut pass = cmd_encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, depth_slice: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, occlusion_query_set: None, timestamp_writes: None, }); renderer.render(&mut pass, &atlas); ``` -------------------------------- ### TextureAtlas::atlas_size Source: https://docs.rs/klyff/latest/klyff/atlas/struct.TextureAtlas.html Gets the current atlas size. ```APIDOC ## TextureAtlas::atlas_size ### Description Gets the current atlas size. ### Method atlas_size ### Parameters None ### Returns (u32, u32, u32) ``` -------------------------------- ### MeshEncoder::rasterized_vertex_buffer_layout Source: https://docs.rs/klyff/latest/klyff/struct.MeshEncoder.html Gets the vertex buffer layout for the rasterized rendering path. ```APIDOC ## MeshEncoder::rasterized_vertex_buffer_layout ### Description Gets the vertex buffer layout for the rasterized rendering path. The shader code declaration is expected to be: ``` struct VertexInput { @location(0) uvw: vec3f, @location(1) screen_pos: vec2f, } ``` ### Method rasterized_vertex_buffer_layout ### Signature ```rust pub fn rasterized_vertex_buffer_layout() -> VertexBufferLayout<'static> ``` ### Returns - `VertexBufferLayout<'static>` - The vertex buffer layout for rasterized rendering. ``` -------------------------------- ### pub fn into_pin(boxed: Box) -> Pin> Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Converts a `Box` into a `Pin>`. If `T` does not implement `Unpin`, then `*boxed` will be pinned in memory and unable to be moved. This conversion does not allocate on the heap and happens in place. This is also available via `From`. Constructing and pinning a `Box` with `Box::into_pin(Box::new(x))` can also be written more concisely using `Box::pin(x)`. This `into_pin` method is useful if you already have a `Box`, or you are constructing a (pinned) `Box` in a different way than with `Box::new`. ```APIDOC ## pub fn into_pin(boxed: Box) -> Pin> ### Description Converts a `Box` into a `Pin>`. If `T` does not implement `Unpin`, then `*boxed` will be pinned in memory and unable to be moved. This conversion does not allocate on the heap and happens in place. This is also available via `From`. Constructing and pinning a `Box` with `Box::into_pin(Box::new(x))` can also be written more concisely using `Box::pin(x)`. This `into_pin` method is useful if you already have a `Box`, or you are constructing a (pinned) `Box` in a different way than with `Box::new`. ### Method pub fn into_pin ### Signature pub fn into_pin(boxed: Box) -> Pin> where A: StaticAllocator, ### Parameters - **boxed** (`Box`) - Required - The `Box` to convert into a `Pin>`. ### Returns - **`Pin>`** - A pinned `Box`. ``` -------------------------------- ### MeshEncoder::msdf_vertex_buffer_layout Source: https://docs.rs/klyff/latest/klyff/struct.MeshEncoder.html Gets the vertex buffer layout for the MSDF rendering path. ```APIDOC ## MeshEncoder::msdf_vertex_buffer_layout ### Description Gets the vertex buffer layout for the MSDF rendering path. The shader code declaration is expected to be: ``` struct VertexInput { @location(0) uvw: vec3f, @location(1) screen_pos: vec2f, @location(2) font_size_px: f32, } ``` ### Method msdf_vertex_buffer_layout ### Signature ```rust pub fn msdf_vertex_buffer_layout() -> VertexBufferLayout<'static> ``` ### Returns - `VertexBufferLayout<'static>` - The vertex buffer layout for MSDF rendering. ``` -------------------------------- ### TextRenderer Initialization Source: https://docs.rs/klyff/latest/src/klyff/renderer.rs.html Methods to initialize the TextRenderer with standard or custom pipelines using wgpu devices. ```rust impl TextRenderer { pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Self { let rasterized_pipeline = RasterizedTextPipeline::new(device, surface_format); let msdf_pipeline = MsdfTextPipeline::new(device, surface_format); Self::with_custom_pipeline(device, msdf_pipeline, rasterized_pipeline) } pub fn with_custom_pipeline( device: &wgpu::Device, msdf_pipeline: MsdfTextPipeline, rasterized_pipeline: RasterizedTextPipeline, ) -> Self { let mesh_encoder = MeshEncoder::new(device); Self { enabled_features: Features::empty(), msdf_generator: klyff_msdf::MsdfGenerator::new(), mesh_encoder, msdf_passes: Box::new(MsdfPasses::Single(MsdfPass { encoder: MaterialEncoder::new(device), material_builder: material_fill, })), msdf_pipeline, rasterized_pipeline, screen_size_uniform: ScreenSizeUniform::new(device), } } ``` -------------------------------- ### TextureAtlas::bind_group Source: https://docs.rs/klyff/latest/klyff/atlas/struct.TextureAtlas.html Gets the bind group containing atlas texture and sample for rendering. ```APIDOC ## TextureAtlas::bind_group ### Description Gets the bind group containing atlas texture and sample for rendering. ### Method bind_group ### Parameters None ### Returns &BindGroup ``` -------------------------------- ### new(device: &wgpu::Device) -> Self Source: https://docs.rs/klyff/latest/src/klyff/pipelines/material_encoder.rs.html Creates a new material encoder with GPU buffers for storing glyph material data and per-vertex material attributes. ```APIDOC ## new(device: &wgpu::Device) -> Self ### Description Creates a new material encoder with GPU buffers for storing glyph material data and per-vertex material attributes. ### Parameters - **device** (`&wgpu::Device`) - Required - The GPU device used to create the buffers and bind group layout. ### Returns - **Self** - A new `MaterialEncoder` instance with initialized GPU resources. ### Example ```rust let encoder = MaterialEncoder::new(&device); ``` ``` -------------------------------- ### Box::try_new_uninit Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Attempts to construct a new box with uninitialized contents, returning an error if allocation fails. This is a nightly-only experimental API. ```APIDOC ## Box::try_new_uninit ### Description Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails. This is a nightly-only experimental API. ### Method Associated function ### Signature `pub fn try_new_uninit() -> Result>, AllocError>` ### Parameters None ### Returns - **Result>, AllocError>** - A result containing a box with uninitialized contents or an allocation error. ### Examples ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` ``` -------------------------------- ### TextRenderer::new Source: https://docs.rs/klyff/latest/klyff/struct.TextRenderer.html Creates a new TextRenderer with default pipelines. ```APIDOC ## TextRenderer::new ### Description Creates a new TextRenderer with default pipelines. ### Method new ### Signature pub fn new(device: &Device, surface_format: TextureFormat) -> Self ### Parameters - **device** (&Device) - Required - The GPU device. - **surface_format** (TextureFormat) - Required - The surface format. ### Returns Self - A new TextRenderer instance. ``` -------------------------------- ### Configure scale and gradient region Source: https://docs.rs/klyff/latest/src/klyff/data/styled_text.rs.html Demonstrates setting the scale and gradient region on the builder, ensuring these values are correctly reflected in the finished StyledText object. ```rust #[test] fn set_scale_reflected_on_finish() { let mut fs = font_system(); let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics()); builder.set_scale(2.5); let text = builder.finish(&mut fs, &Attrs::new()); assert_eq!(text.scale, 2.5); } ``` ```rust #[test] fn set_gradient_region_some() { let mut fs = font_system(); let grad = Rect::from_xywh(10.0, 10.0, 400.0, 300.0); let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics()); builder.set_gradient_region(Some(grad)); let text = builder.finish(&mut fs, &Attrs::new()); assert_eq!(text.gradient_region, Some(grad)); } ``` ```rust #[test] fn set_gradient_region_none_clears() { let mut fs = font_system(); let mut builder = StyledTextBuilder::new(region(), &mut fs, metrics()); builder.set_gradient_region(Some(region())); builder.set_gradient_region(None); let text = builder.finish(&mut fs, &Attrs::new()); assert_eq!(text.gradient_region, None); } ``` -------------------------------- ### TextRenderer::prepare Source: https://docs.rs/klyff/latest/klyff/struct.TextRenderer.html Prepares the renderer for rendering a set of text instances. Call once per frame. ```APIDOC ## TextRenderer::prepare ### Description Prepares the renderer for rendering a set of text instances. Call once per frame. ### Method prepare ### Signature pub fn prepare(&mut self, ctx: EncoderContext<'_>, surface_size: (u32, u32), styled_texts: &[StyledText]) ### Parameters - **ctx** (EncoderContext<'_>) - Required - The encoder context. - **surface_size** ((u32, u32)) - Required - The surface size in pixels. - **styled_texts** (&[StyledText]) - Required - The styled texts to prepare. ### Returns None ``` -------------------------------- ### Box::new Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Allocates memory on the heap and places a value into it. This is the primary constructor for Box. ```APIDOC ## Box::new ### Description Allocates memory on the heap and places the given value into it. This does not actually allocate if the type is zero-sized. ### Method Associated function ### Signature `pub fn new(x: T) -> Box` ### Parameters - **x** (T) - Required - The value to place on the heap. ### Returns - **Box** - A box containing the value. ### Examples ```rust let five = Box::new(5); ``` ``` -------------------------------- ### Box::into_raw_with_allocator manual cleanup Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Demonstrates manual memory cleanup by explicitly running the destructor and deallocating memory. ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; use std::ptr::{self, NonNull}; let x = Box::new_in(String::from("Hello"), System); let (ptr, alloc) = Box::into_raw_with_allocator(x); unsafe { ptr::drop_in_place(ptr); let non_null = NonNull::new_unchecked(ptr); alloc.deallocate(non_null.cast(), Layout::new::()); } ``` -------------------------------- ### Test device request helper Source: https://docs.rs/klyff/latest/src/klyff/pipelines/pipeline.rs.html A helper function used in tests to request a wgpu device and queue. ```rust async fn request_device() -> Option<(wgpu::Device, wgpu::Queue)> { let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default()); let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::None, compatible_surface: None, force_fallback_adapter: false, }) .await .ok()?; adapter ``` -------------------------------- ### Rect::from_pivot usage Source: https://docs.rs/klyff/latest/src/klyff/data/mod.rs.html Demonstrates creating a Rect from a pivot point, size, and anchor coordinates. ```rust fn rect_from_pivot_top_left() { // pivot at min corner → same as from_min_size let r = Rect::from_pivot(vec2(1.0, 2.0), vec2(0.0, 0.0), vec2(4.0, 3.0)); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 5.0)); } ``` ```rust #[test] fn rect_from_pivot_center() { // pivot at center → same as from_center_size let r = Rect::from_pivot(vec2(3.0, 3.0), vec2(0.5, 0.5), vec2(4.0, 2.0)); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 4.0)); } ``` ```rust #[test] fn rect_from_pivot_bottom_right() { // pivot at max corner → same as from_max_size let r = Rect::from_pivot(vec2(5.0, 5.0), vec2(1.0, 1.0), vec2(4.0, 3.0)); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 5.0)); } ``` -------------------------------- ### remove returns value and tick Source: https://docs.rs/klyff/latest/src/klyff/atlas/cache.rs.html Tests that remove returns true when the key exists and removes the entry. After removing "a", get returns None. ```rust let mut c: Cache<&str, i32> = Cache::new(); c.insert("a", 1); c.new_tick(); c.insert("b", 2); assert!(c.remove(&"a")); assert_eq!(c.get(&"a"), None); ``` -------------------------------- ### Clone Box from reference using clone_from_ref Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Allocates memory on the heap and clones the source into it. Requires the clone_from_ref feature. ```rust #![feature(clone_from_ref)] let hello: Box = Box::clone_from_ref("hello"); ``` -------------------------------- ### Rect tests: from_min_max, from_xywh, from_min_size, from_max_size, from_center_size Source: https://docs.rs/klyff/latest/src/klyff/data/mod.rs.html Unit tests for Rect constructors using glam::vec2. ```rust #[test] fn rect_from_min_max() { let r = Rect::from_min_max(vec2(1.0, 2.0), vec2(5.0, 6.0)); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 6.0)); } ``` ```rust #[test] fn rect_from_xywh() { let r = Rect::from_xywh(1.0, 2.0, 4.0, 3.0); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 5.0)); } ``` ```rust #[test] fn rect_from_min_size() { let r = Rect::from_min_size(vec2(1.0, 2.0), vec2(4.0, 3.0)); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 5.0)); } ``` ```rust #[test] fn rect_from_max_size() { let r = Rect::from_max_size(vec2(5.0, 5.0), vec2(4.0, 3.0)); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 5.0)); } ``` ```rust #[test] fn rect_from_center_size() { let r = Rect::from_center_size(vec2(3.0, 3.0), vec2(4.0, 2.0)); assert_eq!(r.min, vec2(1.0, 2.0)); assert_eq!(r.max, vec2(5.0, 4.0)); } ``` -------------------------------- ### Color constants and creation Source: https://docs.rs/klyff/latest/src/klyff/data/mod.rs.html Using predefined color constants and creating colors from RGBA values. ```rust #[test] fn color_constants() { assert_eq!(Color::WHITE.0, glam::Vec4::ONE); assert_eq!(Color::BLACK.0, glam::Vec4::new(0.0, 0.0, 0.0, 1.0)); assert_eq!(Color::TRANSPARENT.0, glam::Vec4::ZERO); } ``` ```rust #[test] fn color_from_rgba() { let c = Color::from_rgba(0.2, 0.4, 0.6, 0.8); assert!(approx_eq(c.0.x, 0.2)); assert!(approx_eq(c.0.y, 0.4)); assert!(approx_eq(c.0.z, 0.6)); assert!(approx_eq(c.0.w, 0.8)); } ``` ```rust #[test] fn color_from_rgba_clamped() { let c = Color::from_rgba(-1.0, 2.0, -0.5, 1.5); assert_eq!(c.0.x, 0.0); assert_eq!(c.0.y, 1.0); assert_eq!(c.0.z, 0.0); assert_eq!(c.0.w, 1.0); } ``` ```rust #[test] fn color_from_rgb_alpha_is_one() { let c = Color::from_rgb(0.5, 0.5, 0.5); assert!(approx_eq(c.0.w, 1.0)); } ``` -------------------------------- ### TextureAtlas::ppem Source: https://docs.rs/klyff/latest/klyff/atlas/struct.TextureAtlas.html Returns the atlas pixels-per-em used when generating distance fields. Divide `region.padding_x` by this value to get the maximum outer effect radius in em units for glyphs stored in this atlas. ```APIDOC ## TextureAtlas::ppem ### Description Returns the atlas pixels-per-em used when generating distance fields. Divide `region.padding_x` by this value to get the maximum outer effect radius in em units for glyphs stored in this atlas. ### Method ppem ### Parameters None ### Returns f32 ``` -------------------------------- ### material_vertex_buffer(&self) -> &wgpu::Buffer Source: https://docs.rs/klyff/latest/src/klyff/pipelines/material_encoder.rs.html Gets the buffer containing each vertex's material attributes, including the index into the storage buffer and gradient UV. This buffer can be bound as a vertex buffer on a different slot to the mesh encoder's vertex buffer. ```APIDOC ## material_vertex_buffer(&self) -> &wgpu::Buffer ### Description Gets the buffer containing each vertex's material attributes, including the index into the storage buffer and gradient UV. This buffer can be bound as a vertex buffer on a different slot to the mesh encoder's vertex buffer. ### Returns - **&wgpu::Buffer** - The vertex buffer containing per-vertex material attributes. ### Example ```rust let vertex_buffer = encoder.material_vertex_buffer(); ``` ``` -------------------------------- ### Cache implementation methods Source: https://docs.rs/klyff/latest/src/klyff/atlas/cache.rs.html Core methods for managing the cache, including initialization, tick updates, insertion, retrieval, and internal list management. ```rust 22impl Cache { 23 pub fn new() -> Self { 24 Self { 25 current_tick: 0, 26 values: Vec::new(), 27 map: HashMap::new(), 28 prev: Vec::new(), 29 next: Vec::new(), 30 head: None, 31 tail: None, 32 free: Vec::new(), 33 } 34 } 35 36 pub fn new_tick(&mut self) { 37 self.current_tick += 1; 38 } 39 40 pub fn current_tick(&self) -> u64 { 41 self.current_tick 42 } 43 44 /// Look up a key. Moves the entry to the MRU position. 45 pub fn get(&mut self, key: &K) -> Option<&V> { 46 let idx = *self.map.get(key)?; 47 self.move_to_front(idx); 48 Some(&self.values[idx].1) 49 } 50 51 /// Insert or update a key-value pair at the current tick. 52 pub fn insert(&mut self, key: K, value: V) { 53 if let Some(&idx) = self.map.get(&key) { 54 // Update in-place and move to front. 55 self.values[idx].1 = value; 56 self.values[idx].2 = self.current_tick; 57 self.move_to_front(idx); 58 return; 59 } 60 61 let tick = self.current_tick; 62 let idx = match self.free.pop() { 63 Some(slot) => { 64 self.values[slot] = (key.clone(), value, tick); 65 self.prev[slot] = None; 66 self.next[slot] = None; 67 slot 68 } 69 None => { 70 let slot = self.values.len(); 71 self.values.push((key.clone(), value, tick)); 72 self.prev.push(None); 73 self.next.push(None); 74 slot 75 } 76 }; 77 78 self.map.insert(key, idx); 79 self.attach_front(idx); 80 } 81 82 pub fn remove(&mut self, key: &K) -> bool { 83 let Some(idx) = self.map.remove(key) else { 84 return false; 85 }; 86 self.detach(idx); 87 self.free.push(idx); 88 true 89 } 90 91 /// Iterate over all live key-value pairs in arbitrary order. 92 /// 93 /// Walks the lookup map so evicted (freed) slots are skipped. 94 #[cfg(feature = "serde")] 95 pub fn iter(&self) -> impl Iterator { 96 self.map.iter().map(move |(k, &idx)| (k, &self.values[idx].1)) 97 } 98 99 /// Peek at the least-recently-used entry without changing the order. 100 pub fn peek_lru(&self) -> Option<(&K, &V, u64)> { 101 let idx = self.tail?; 102 let (k, v, t) = &self.values[idx]; 103 Some((k, v, *t)) 104 } 105 106 /// Detach slot `idx` from wherever it sits in the list. 107 fn detach(&mut self, idx: usize) { 108 let p = self.prev[idx]; 109 let n = self.next[idx]; 110 111 match p { 112 Some(pi) => self.next[pi] = n, 113 None => self.head = n, // idx was the head 114 } 115 match n { 116 Some(ni) => self.prev[ni] = p, 117 None => self.tail = p, // idx was the tail 118 } 119 120 self.prev[idx] = None; 121 self.next[idx] = None; 122 } 123 124 /// Insert slot `idx` at the front (MRU end) of the list. 125 fn attach_front(&mut self, idx: usize) { 126 self.prev[idx] = None; 127 self.next[idx] = self.head; 128 129 if let Some(old_head) = self.head { 130 self.prev[old_head] = Some(idx); 131 } else { 132 // List was empty — idx is also the tail. 133 self.tail = Some(idx); 134 } 135 self.head = Some(idx); 136 } 137 138 /// Move an already-linked slot to the front. 139 fn move_to_front(&mut self, idx: usize) { 140 if self.head == Some(idx) { 141 return; // already MRU 142 } 143 self.detach(idx); 144 self.attach_front(idx); 145 } 146} ``` -------------------------------- ### update moves entry to front Source: https://docs.rs/klyff/latest/src/klyff/atlas/cache.rs.html Confirms that re-inserting an existing key moves it to the most recently used position and updates its value. After re-inserting "a" with value 10, the LRU becomes "b" and get returns the new value. ```rust let mut c: Cache<&str, i32> = Cache::new(); c.insert("a", 1); c.insert("b", 2); c.insert("c", 3); // Re-insert "a" — it should now be MRU and LRU should be "b". c.insert("a", 10); let (k, _v, _) = c.peek_lru().unwrap(); assert_eq!(*k, "b"); assert_eq!(c.get(&"a"), Some(&10)); ``` -------------------------------- ### ScreenSizeUniform wgpu uniform buffer and bind group Source: https://docs.rs/klyff/latest/src/klyff/pipelines/screen_size_uniform.rs.html Defines a wgpu uniform buffer and bind group that store the current screen size as a vec2f for shader use. The `new` constructor creates the buffer (8 bytes) and bind group with a vertex-stage uniform binding; `encode` writes the width and height as f32 values via `bytemuck::cast_slice`. The bind group layout is exposed through `bind_group_layout` and the group itself via `uniform_bind_group`. ```rust /// Holds the uniform to encode current screen size, necessary for translating glyph to screen /// space. pub struct ScreenSizeUniform { uniform_bind_group: wgpu::BindGroup, uniform_buf: wgpu::Buffer, } impl ScreenSizeUniform { /// Constructs a new instance, creating necessary wgpu resources on the provided wgpu device. pub fn new(device: &wgpu::Device) -> Self { let uniform_bind_group_layout = Self::bind_group_layout(device); let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("klyff uniform buffer"), size: 8, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("klyff uniform bind group"), layout: &uniform_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform_buf.as_entire_binding(), }], }); Self { uniform_bind_group, uniform_buf, } } pub fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("klyff uniform bind group layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }], }) } /// The bind group, bound before drawing with a pipeline. pub fn uniform_bind_group(&self) -> &wgpu::BindGroup { &self.uniform_bind_group } /// Write the provided screen size to the uniform buffer. pub fn encode(&self, queue: &wgpu::Queue, surface_width: u32, surface_height: u32) { // Shader-side `screen_size` is `vec2f`, not `vec2u` — cast before writing. queue.write_buffer( &self.uniform_buf, 0, bytemuck::cast_slice(&[surface_width as f32, surface_height as f32]), ); } } ``` -------------------------------- ### TextRenderer::prepare_with_glyph_transform Source: https://docs.rs/klyff/latest/klyff/struct.TextRenderer.html Same as prepare but allows modifying per-glyph transforms and styling. ```APIDOC ## TextRenderer::prepare_with_glyph_transform ### Description Same as `Self::prepare` but allows modifying on a per-glyph granularity. ### Method prepare_with_glyph_transform ### Signature pub fn prepare_with_glyph_transform(&mut self, context: EncoderContext<'_>, surface_size: (u32, u32), styled_texts: &[StyledText], per_glyph_transform: impl FnMut(&DecodedGlyph, &mut [Vec2; 4]), per_glyph_styling: impl FnMut(&DecodedGlyph, &mut TextStyle)) ### Parameters - **context** (EncoderContext<'_>) - Required - The encoder context. - **surface_size** ((u32, u32)) - Required - The surface size in pixels. - **styled_texts** (&[StyledText]) - Required - The styled texts to prepare. - **per_glyph_transform** (impl FnMut(&DecodedGlyph, &mut [Vec2; 4])) - Required - A closure to modify glyph transforms. - **per_glyph_styling** (impl FnMut(&DecodedGlyph, &mut TextStyle)) - Required - A closure to modify glyph styling. ### Returns None ``` -------------------------------- ### Clone Box from reference using try_clone_from_ref Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Allocates memory on the heap and clones the source, returning a Result. Requires clone_from_ref and allocator_api features. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] let hello: Box = Box::try_clone_from_ref("hello")?; ``` -------------------------------- ### Box::new_uninit Source: https://docs.rs/klyff/latest/klyff/type.GlyphStyleMap.html Constructs a new box with uninitialized contents. The caller is responsible for initializing the memory before use. ```APIDOC ## Box::new_uninit ### Description Constructs a new box with uninitialized contents. The memory is not initialized until the caller writes to it. ### Method Associated function ### Signature `pub fn new_uninit() -> Box>` ### Parameters None ### Returns - **Box>** - A box with uninitialized contents. ### Examples ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### GlyphKey::new Source: https://docs.rs/klyff/latest/klyff/atlas/struct.GlyphKey.html Creates a new GlyphKey with the given font ID, font size, and glyph ID. ```APIDOC ## GlyphKey::new ### Description Creates a new GlyphKey with the specified font ID, font size, and glyph ID. ### Method `pub fn new(font: ID, font_size: f32, glyph_id: u16) -> Self` ### Parameters - **font** (ID) - Required - The font identifier. - **font_size** (f32) - Required - The font size. - **glyph_id** (u16) - Required - The glyph identifier. ### Returns - **Self** - A new GlyphKey instance. ``` -------------------------------- ### Initialize StyledTextBuilder with default values Source: https://docs.rs/klyff/latest/src/klyff/data/styled_text.rs.html Verifies that a new StyledTextBuilder instance is initialized with the expected region, default scale, and no gradient region. ```rust #[test] fn new_default_val() { let mut fs = font_system(); let r = region(); let text = StyledTextBuilder::new(r, &mut fs, metrics()).finish(&mut fs, &Attrs::new()); assert_eq!(text.region, r); assert_eq!(text.scale, 1.0); assert_eq!(text.gradient_region, None); } ``` -------------------------------- ### Color from_hsv constructor Source: https://docs.rs/klyff/latest/src/klyff/data/mod.rs.html Creates a Color from hue, saturation, and value components. Alpha defaults to fully opaque. ```rust pub fn from_hsv(h: f32, s: f32, v: f32) -> Self { Self::from_hsva(h, s, v, 1.0) } ```