├── .github └── workflows │ └── test.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── README.md ├── examples ├── Inconsolata-Regular.ttf ├── OFL.txt ├── clipping.rs ├── depth.rs ├── hello.rs └── lipsum.txt ├── rustfmt.toml └── src ├── GLYPH_BRUSH_LICENSE ├── builder.rs ├── lib.rs ├── pipeline.rs ├── pipeline └── cache.rs ├── region.rs └── shader └── glyph.wgsl /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [push, pull_request] 3 | jobs: 4 | native: 5 | runs-on: ${{ matrix.os }} 6 | strategy: 7 | matrix: 8 | os: [ubuntu-latest, windows-latest, macOS-latest] 9 | rust: [stable] 10 | steps: 11 | - uses: actions/checkout@master 12 | - uses: hecrj/setup-rust-action@v1 13 | with: 14 | rust-version: ${{ matrix.rust }} 15 | - name: Run tests 16 | run: cargo test --verbose 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [0.23.0] - 2024-12-10 10 | ### Changed 11 | - Updated `wgpu` to `23`. [#108] 12 | 13 | [#108]: https://github.com/hecrj/wgpu_glyph/pull/108 14 | 15 | ## [0.22.0] - 2024-01-16 16 | ### Changed 17 | - Updated `wgpu` to `0.18`. [#105] 18 | 19 | [#105]: https://github.com/hecrj/wgpu_glyph/pull/105 20 | 21 | ## [0.21.0] - 2023-09-08 22 | ### Changed 23 | - Updated `wgpu` to `0.17`. [#104] 24 | 25 | [#104]: https://github.com/hecrj/wgpu_glyph/pull/104 26 | 27 | ## [0.20.0] - 2023-04-21 28 | ### Changed 29 | - Updated `wgpu` to `0.16`. [#101] 30 | 31 | [#101]: https://github.com/hecrj/wgpu_glyph/pull/101 32 | 33 | ## [0.19.0] - 2023-03-31 34 | ### Changed 35 | - Updated `wgpu` to `0.15`. [#95] 36 | 37 | [#95]: https://github.com/hecrj/wgpu_glyph/pull/95 38 | 39 | ## [0.18.0] - 2022-11-01 40 | ### Added 41 | - Support for passing a custom `MultisampleState`. [#91] 42 | 43 | ### Changed 44 | - Updated `wgpu` to `0.14`. [#94] 45 | 46 | [#91]: https://github.com/hecrj/wgpu_glyph/pull/91 47 | [#94]: https://github.com/hecrj/wgpu_glyph/pull/94 48 | 49 | ## [0.17.0] - 2022-07-03 50 | ### Changed 51 | - Updated `wgpu` to `0.13`. [#89] 52 | 53 | [#89]: https://github.com/hecrj/wgpu_glyph/pull/89 54 | 55 | ## [0.16.0] - 2021-12-20 56 | ### Changed 57 | - Updated `wgpu` to `0.12`. [#83] 58 | 59 | [#83]: https://github.com/hecrj/wgpu_glyph/pull/83 60 | 61 | ## [0.15.2] - 2021-12-05 62 | ### Added 63 | - Re-export `OwnedSection` and `OwnedText` from `glyph_brush`. [#77] 64 | 65 | ### Fixed 66 | - Added default branch to WGSL switch in shader. [#79] 67 | - Set `strip_index` format. [#80] 68 | - Set glyph texture to `filterable`. [#80] 69 | 70 | [#77]: https://github.com/hecrj/wgpu_glyph/pull/77 71 | [#79]: https://github.com/hecrj/wgpu_glyph/pull/79 72 | [#80]: https://github.com/hecrj/wgpu_glyph/pull/80 73 | 74 | ## [0.15.1] - 2021-10-13 75 | ### Removed 76 | - Removed installation section from the `README`. 77 | 78 | ## [0.15.0] - 2021-10-13 79 | ### Changed 80 | - Updated `wgpu` to `0.11`. [#75] 81 | 82 | [#75]: https://github.com/hecrj/wgpu_glyph/pull/75 83 | 84 | 85 | ## [0.14.1] - 2021-09-19 86 | ### Fixed 87 | - Fixed incorrect version in the `README`. 88 | 89 | 90 | ## [0.14.0] - 2021-09-19 91 | ### Changed 92 | - Updated `wgpu` to `0.10`. [#73] 93 | 94 | [#73]: https://github.com/hecrj/wgpu_glyph/pull/73 95 | 96 | 97 | ## [0.13.0] - 2021-06-22 98 | ### Changed 99 | - Updated `wgpu` to `0.9`. [#70] 100 | 101 | [#70]: https://github.com/hecrj/wgpu_glyph/pull/70 102 | 103 | 104 | ## [0.12.0] - 2021-05-19 105 | ### Changed 106 | - Updated `wgpu` to `0.8`. [#62] 107 | 108 | [#62]: https://github.com/hecrj/wgpu_glyph/pull/62 109 | 110 | 111 | ## [0.11.0] - 2021-02-06 112 | ### Changed 113 | - Updated `wgpu` to `0.7`. [#50] 114 | - Replaced `zerocopy` with `bytemuck`. [#51] 115 | 116 | [#50]: https://github.com/hecrj/wgpu_glyph/pull/50 117 | [#51]: https://github.com/hecrj/wgpu_glyph/pull/51 118 | 119 | 120 | ## [0.10.0] - 2020-08-27 121 | ### Changed 122 | - Updated `wgpu` to `0.6`. [#44] 123 | - Introduced `StagingBelt` for uploading data. [#46] 124 | 125 | [#44]: https://github.com/hecrj/wgpu_glyph/pull/44 126 | [#46]: https://github.com/hecrj/wgpu_glyph/pull/46 127 | 128 | 129 | ## [0.9.0] - 2020-04-29 130 | ### Added 131 | - `orthographic_projection` helper to easily build a projection matrix. [#39] 132 | 133 | ### Changed 134 | - Updated `glyph_brush` to `0.7`. [#43] 135 | 136 | [#39]: https://github.com/hecrj/wgpu_glyph/pull/39 137 | [#43]: https://github.com/hecrj/wgpu_glyph/pull/43 138 | 139 | 140 | ## [0.8.0] - 2020-04-13 141 | ### Changed 142 | - `wgpu` dependency updated to `0.5`. [#33] 143 | - The Y axis has been flipped to match the new NDC sytem in `wgpu`. [#33] 144 | 145 | [#33]: https://github.com/hecrj/wgpu_glyph/pull/33 146 | 147 | 148 | ## [0.7.0] - 2020-03-02 149 | ### Changed 150 | - `GlyphBrush::build` and `GlyphBrush::draw_queued*` methods take an immutable reference of a `wgpu::Device` now. [#29] [#30] 151 | - `GlyphBrush::using_font_bytes` and `GlyphBrush::using_fonts_bytes` return an error instead of panicking when the provided font cannot be loaded. [#27] 152 | 153 | [#27]: https://github.com/hecrj/wgpu_glyph/pull/27 154 | [#29]: https://github.com/hecrj/wgpu_glyph/pull/29 155 | [#30]: https://github.com/hecrj/wgpu_glyph/pull/30 156 | 157 | 158 | ## [0.6.0] - 2019-11-24 159 | ### Added 160 | - `GlyphBrush::add_font_bytes` and `GlyphBrush::add_font`, which allow loading fonts after building a `GlyphBrush` [#25] 161 | - `GlyphBrush::draw_queued_with_transform_and_scissoring`, which allows clipping text in the given `Region`. [#25] 162 | 163 | [#25]: https://github.com/hecrj/wgpu_glyph/pull/25 164 | 165 | 166 | ## [0.5.0] - 2019-11-05 167 | ### Added 168 | - `From` implementation for `wgpu_glyph::GlyphBrushBuilder`. [#19] 169 | 170 | ### Changed 171 | - `glyph-brush` dependency updated to `0.6`. [#21] 172 | - `wgpu` dependency updated to `0.4`. [#24] 173 | 174 | [#19]: https://github.com/hecrj/wgpu_glyph/pull/19 175 | [#21]: https://github.com/hecrj/wgpu_glyph/pull/21 176 | [#24]: https://github.com/hecrj/wgpu_glyph/pull/24 177 | 178 | 179 | ## [0.4.0] - 2019-10-23 180 | ### Added 181 | - Depth testing support. It can be easily enabled using the new 182 | `GlyphBrushBuilder::depth_stencil_state` method. [#13] 183 | 184 | ### Changed 185 | - `wgpu` dependency has been bumped to version `0.3`. [#17] 186 | 187 | ### Fixed 188 | - Incorrect use of old cache on resize, causing validation errors and panics. [#9] 189 | 190 | [#9]: https://github.com/hecrj/wgpu_glyph/pull/9 191 | [#13]: https://github.com/hecrj/wgpu_glyph/pull/13 192 | [#17]: https://github.com/hecrj/wgpu_glyph/pull/17 193 | 194 | 195 | ## [0.3.1] - 2019-06-09 196 | ### Fixed 197 | - Panic when drawing an empty `GlyphBrush`. 198 | 199 | 200 | ## [0.3.0] - 2019-05-03 201 | ### Added 202 | - This changelog. 203 | 204 | ### Changed 205 | - The transformation matrix in `draw_queued_with_transform` will be applied 206 | directly to vertices in absolute coordinates. This makes reusing vertices with 207 | different projections much easier. See [glyph_brush/pull/64]. 208 | 209 | ### Removed 210 | - Target dimensions in `draw_queued_with_transform`. The transform needs to take 211 | care of translating vertices coordinates into the normalized space. 212 | 213 | [glyph_brush/pull/64]: https://github.com/alexheretic/glyph-brush/pull/64 214 | 215 | 216 | ## [0.2.0] - 2019-04-28 217 | ### Added 218 | - Configurable render target format. 219 | 220 | 221 | ## [0.1.1] - 2019-04-27 222 | ### Fixed 223 | - Instance buffer resize issue. Now, the instance buffer resizes when necessary. 224 | 225 | 226 | ## 0.1.0 - 2019-04-27 227 | ### Added 228 | - First release! :tada: 229 | 230 | 231 | [Unreleased]: https://github.com/hecrj/wgpu_glyph/compare/0.23.0...HEAD 232 | [0.23.0]: https://github.com/hecrj/wgpu_glyph/compare/0.22.0...0.23.0 233 | [0.22.0]: https://github.com/hecrj/wgpu_glyph/compare/0.21.0...0.22.0 234 | [0.21.0]: https://github.com/hecrj/wgpu_glyph/compare/0.20.0...0.21.0 235 | [0.20.0]: https://github.com/hecrj/wgpu_glyph/compare/0.19.0...0.20.0 236 | [0.19.0]: https://github.com/hecrj/wgpu_glyph/compare/0.18.0...0.19.0 237 | [0.18.0]: https://github.com/hecrj/wgpu_glyph/compare/0.17.0...0.18.0 238 | [0.17.0]: https://github.com/hecrj/wgpu_glyph/compare/0.16.0...0.17.0 239 | [0.16.0]: https://github.com/hecrj/wgpu_glyph/compare/0.15.2...0.16.0 240 | [0.15.2]: https://github.com/hecrj/wgpu_glyph/compare/0.15.1...0.15.2 241 | [0.15.1]: https://github.com/hecrj/wgpu_glyph/compare/0.15.0...0.15.1 242 | [0.15.0]: https://github.com/hecrj/wgpu_glyph/compare/0.14.0...0.15.0 243 | [0.14.1]: https://github.com/hecrj/wgpu_glyph/compare/0.14.0...0.14.1 244 | [0.14.0]: https://github.com/hecrj/wgpu_glyph/compare/0.13.0...0.14.0 245 | [0.13.0]: https://github.com/hecrj/wgpu_glyph/compare/0.12.0...0.13.0 246 | [0.12.0]: https://github.com/hecrj/wgpu_glyph/compare/0.11.0...0.12.0 247 | [0.11.0]: https://github.com/hecrj/wgpu_glyph/compare/0.10.0...0.11.0 248 | [0.10.0]: https://github.com/hecrj/wgpu_glyph/compare/0.9.0...0.10.0 249 | [0.9.0]: https://github.com/hecrj/wgpu_glyph/compare/0.8.0...0.9.0 250 | [0.8.0]: https://github.com/hecrj/wgpu_glyph/compare/0.7.0...0.8.0 251 | [0.7.0]: https://github.com/hecrj/wgpu_glyph/compare/0.6.0...0.7.0 252 | [0.6.0]: https://github.com/hecrj/wgpu_glyph/compare/0.5.0...0.6.0 253 | [0.5.0]: https://github.com/hecrj/wgpu_glyph/compare/0.4.0...0.5.0 254 | [0.4.0]: https://github.com/hecrj/wgpu_glyph/compare/0.3.1...0.4.0 255 | [0.3.1]: https://github.com/hecrj/wgpu_glyph/compare/0.3.0...0.3.1 256 | [0.3.0]: https://github.com/hecrj/wgpu_glyph/compare/0.2.0...0.3.0 257 | [0.2.0]: https://github.com/hecrj/wgpu_glyph/compare/0.1.1...0.2.0 258 | [0.1.1]: https://github.com/hecrj/wgpu_glyph/compare/0.1.0...0.1.1 259 | [0.1.0]: https://github.com/hecrj/wgpu_glyph/releases/tag/0.1.0 260 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wgpu_glyph" 3 | version = "0.23.0" 4 | authors = ["Héctor Ramón Jiménez "] 5 | edition = "2021" 6 | description = "A fast text renderer for wgpu, powered by glyph_brush" 7 | license = "MIT" 8 | keywords = ["font", "ttf", "truetype", "wgpu", "text"] 9 | repository = "https://github.com/hecrj/wgpu_glyph" 10 | documentation = "https://docs.rs/wgpu_glyph" 11 | readme = "README.md" 12 | 13 | [dependencies] 14 | wgpu = "23" 15 | glyph_brush = "0.7" 16 | log = "0.4" 17 | 18 | [dependencies.bytemuck] 19 | version = "1.9" 20 | features = ["derive"] 21 | 22 | [dev-dependencies] 23 | env_logger = "0.10" 24 | winit = "0.29" 25 | futures = "0.3" 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 Héctor Ramón, wgpu_glyph contributors 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so, 8 | subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 15 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 16 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 17 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 18 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wgpu_glyph 2 | 3 | > [!WARNING] 4 | > This crate has been superseded by [`glyphon`]. 5 | > 6 | > [`glyphon`] has a simpler design that fits better with [`wgpu`]. Furthermore, it is built on top of [`cosmic-text`], which supports many more advanced text use cases. 7 | 8 | [`glyphon`]: https://github.com/grovesNL/glyphon 9 | [`wgpu`]: https://github.com/gfx-rs/wgpu 10 | [`cosmic-text`]: https://github.com/pop-os/cosmic-text 11 | 12 | [![Test Status](https://img.shields.io/github/actions/workflow/status/hecrj/wgpu_glyph/test.yml?branch=master&event=push&label=test)](https://github.com/hecrj/wgpu_glyph/actions) 13 | [![crates.io](https://img.shields.io/crates/v/wgpu_glyph.svg)](https://crates.io/crates/wgpu_glyph) 14 | [![Documentation](https://docs.rs/wgpu_glyph/badge.svg)](https://docs.rs/wgpu_glyph) 15 | [![License](https://img.shields.io/crates/l/wgpu_glyph.svg)](https://github.com/hecrj/wgpu_glyph/blob/master/LICENSE) 16 | 17 | A fast text renderer for [wgpu](https://github.com/gfx-rs/wgpu), powered by 18 | [glyph_brush](https://github.com/alexheretic/glyph-brush/tree/master/glyph-brush). 19 | 20 | ## Examples 21 | 22 | Have a look at 23 | * [The examples directory](examples). 24 | * [Iced](https://github.com/hecrj/iced), a cross-platform GUI library. 25 | * [Coffee](https://github.com/hecrj/coffee), a 2D game library. 26 | -------------------------------------------------------------------------------- /examples/Inconsolata-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hecrj/wgpu_glyph/649d6ce507ab824eae47b6ec45ea8de67d414c57/examples/Inconsolata-Regular.ttf -------------------------------------------------------------------------------- /examples/OFL.txt: -------------------------------------------------------------------------------- 1 | Copyright 2006 The Inconsolata Project Authors 2 | 3 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 4 | This license is copied below, and is also available with a FAQ at: 5 | http://scripts.sil.org/OFL 6 | 7 | 8 | ----------------------------------------------------------- 9 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 10 | ----------------------------------------------------------- 11 | 12 | PREAMBLE 13 | The goals of the Open Font License (OFL) are to stimulate worldwide 14 | development of collaborative font projects, to support the font creation 15 | efforts of academic and linguistic communities, and to provide a free and 16 | open framework in which fonts may be shared and improved in partnership 17 | with others. 18 | 19 | The OFL allows the licensed fonts to be used, studied, modified and 20 | redistributed freely as long as they are not sold by themselves. The 21 | fonts, including any derivative works, can be bundled, embedded, 22 | redistributed and/or sold with any software provided that any reserved 23 | names are not used by derivative works. The fonts and derivatives, 24 | however, cannot be released under any other type of license. The 25 | requirement for fonts to remain under this license does not apply 26 | to any document created using the fonts or their derivatives. 27 | 28 | DEFINITIONS 29 | "Font Software" refers to the set of files released by the Copyright 30 | Holder(s) under this license and clearly marked as such. This may 31 | include source files, build scripts and documentation. 32 | 33 | "Reserved Font Name" refers to any names specified as such after the 34 | copyright statement(s). 35 | 36 | "Original Version" refers to the collection of Font Software components as 37 | distributed by the Copyright Holder(s). 38 | 39 | "Modified Version" refers to any derivative made by adding to, deleting, 40 | or substituting -- in part or in whole -- any of the components of the 41 | Original Version, by changing formats or by porting the Font Software to a 42 | new environment. 43 | 44 | "Author" refers to any designer, engineer, programmer, technical 45 | writer or other person who contributed to the Font Software. 46 | 47 | PERMISSION & CONDITIONS 48 | Permission is hereby granted, free of charge, to any person obtaining 49 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 50 | redistribute, and sell modified and unmodified copies of the Font 51 | Software, subject to the following conditions: 52 | 53 | 1) Neither the Font Software nor any of its individual components, 54 | in Original or Modified Versions, may be sold by itself. 55 | 56 | 2) Original or Modified Versions of the Font Software may be bundled, 57 | redistributed and/or sold with any software, provided that each copy 58 | contains the above copyright notice and this license. These can be 59 | included either as stand-alone text files, human-readable headers or 60 | in the appropriate machine-readable metadata fields within text or 61 | binary files as long as those fields can be easily viewed by the user. 62 | 63 | 3) No Modified Version of the Font Software may use the Reserved Font 64 | Name(s) unless explicit written permission is granted by the corresponding 65 | Copyright Holder. This restriction only applies to the primary font name as 66 | presented to the users. 67 | 68 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 69 | Software shall not be used to promote, endorse or advertise any 70 | Modified Version, except to acknowledge the contribution(s) of the 71 | Copyright Holder(s) and the Author(s) or with their explicit written 72 | permission. 73 | 74 | 5) The Font Software, modified or unmodified, in part or in whole, 75 | must be distributed entirely under this license, and must not be 76 | distributed under any other license. The requirement for fonts to 77 | remain under this license does not apply to any document created 78 | using the Font Software. 79 | 80 | TERMINATION 81 | This license becomes null and void if any of the above conditions are 82 | not met. 83 | 84 | DISCLAIMER 85 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 86 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 87 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 88 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 89 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 90 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 91 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 92 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 93 | OTHER DEALINGS IN THE FONT SOFTWARE. 94 | -------------------------------------------------------------------------------- /examples/clipping.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use wgpu::CompositeAlphaMode; 3 | use wgpu_glyph::{ab_glyph, GlyphBrushBuilder, Region, Section, Text}; 4 | 5 | fn main() -> Result<(), Box> { 6 | env_logger::init(); 7 | 8 | // Open window and create a surface 9 | let event_loop = winit::event_loop::EventLoop::new()?; 10 | 11 | let window = winit::window::WindowBuilder::new() 12 | .with_resizable(false) 13 | .build(&event_loop) 14 | .unwrap(); 15 | 16 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default()); 17 | let surface = instance.create_surface(&window)?; 18 | 19 | // Initialize GPU 20 | let (device, queue) = futures::executor::block_on(async { 21 | let adapter = instance 22 | .request_adapter(&wgpu::RequestAdapterOptions { 23 | power_preference: wgpu::PowerPreference::HighPerformance, 24 | compatible_surface: Some(&surface), 25 | force_fallback_adapter: false, 26 | }) 27 | .await 28 | .expect("Request adapter"); 29 | 30 | adapter 31 | .request_device(&wgpu::DeviceDescriptor::default(), None) 32 | .await 33 | .expect("Request device") 34 | }); 35 | 36 | // Create staging belt 37 | let mut staging_belt = wgpu::util::StagingBelt::new(1024); 38 | 39 | // Prepare swap chain 40 | let render_format = wgpu::TextureFormat::Bgra8UnormSrgb; 41 | let mut size = window.inner_size(); 42 | 43 | surface.configure( 44 | &device, 45 | &wgpu::SurfaceConfiguration { 46 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, 47 | format: render_format, 48 | width: size.width, 49 | height: size.height, 50 | present_mode: wgpu::PresentMode::AutoVsync, 51 | alpha_mode: CompositeAlphaMode::Auto, 52 | view_formats: vec![], 53 | desired_maximum_frame_latency: 2, 54 | }, 55 | ); 56 | 57 | // Prepare glyph_brush 58 | let inconsolata = ab_glyph::FontArc::try_from_slice(include_bytes!( 59 | "Inconsolata-Regular.ttf" 60 | ))?; 61 | 62 | let mut glyph_brush = GlyphBrushBuilder::using_font(inconsolata) 63 | .build(&device, render_format); 64 | 65 | // Render loop 66 | window.request_redraw(); 67 | 68 | event_loop.run(move |event, elwt| { 69 | match event { 70 | winit::event::Event::WindowEvent { 71 | event: winit::event::WindowEvent::CloseRequested, 72 | .. 73 | } => elwt.exit(), 74 | winit::event::Event::WindowEvent { 75 | event: winit::event::WindowEvent::Resized(new_size), 76 | .. 77 | } => { 78 | size = new_size; 79 | 80 | surface.configure( 81 | &device, 82 | &wgpu::SurfaceConfiguration { 83 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, 84 | format: render_format, 85 | width: size.width, 86 | height: size.height, 87 | present_mode: wgpu::PresentMode::AutoVsync, 88 | alpha_mode: CompositeAlphaMode::Auto, 89 | view_formats: vec![], 90 | desired_maximum_frame_latency: 2, 91 | }, 92 | ); 93 | } 94 | winit::event::Event::WindowEvent { 95 | event: winit::event::WindowEvent::RedrawRequested, 96 | .. 97 | } => { 98 | // Get a command encoder for the current frame 99 | let mut encoder = device.create_command_encoder( 100 | &wgpu::CommandEncoderDescriptor { 101 | label: Some("Redraw"), 102 | }, 103 | ); 104 | 105 | // Get the next frame 106 | let frame = 107 | surface.get_current_texture().expect("Get next frame"); 108 | let view = &frame 109 | .texture 110 | .create_view(&wgpu::TextureViewDescriptor::default()); 111 | 112 | // Clear frame 113 | { 114 | let _ = encoder.begin_render_pass( 115 | &wgpu::RenderPassDescriptor { 116 | label: Some("Render pass"), 117 | color_attachments: &[Some( 118 | wgpu::RenderPassColorAttachment { 119 | view, 120 | resolve_target: None, 121 | ops: wgpu::Operations { 122 | load: wgpu::LoadOp::Clear( 123 | wgpu::Color { 124 | r: 0.4, 125 | g: 0.4, 126 | b: 0.4, 127 | a: 1.0, 128 | }, 129 | ), 130 | store: wgpu::StoreOp::Store, 131 | }, 132 | }, 133 | )], 134 | depth_stencil_attachment: None, 135 | timestamp_writes: None, 136 | occlusion_query_set: None, 137 | }, 138 | ); 139 | } 140 | 141 | glyph_brush.queue(Section { 142 | screen_position: (30.0, 30.0), 143 | bounds: (size.width as f32, size.height as f32), 144 | text: vec![Text::new("Hello wgpu_glyph!") 145 | .with_color([0.0, 0.0, 0.0, 1.0]) 146 | .with_scale(40.0)], 147 | ..Section::default() 148 | }); 149 | 150 | // Draw the text! 151 | glyph_brush 152 | .draw_queued( 153 | &device, 154 | &mut staging_belt, 155 | &mut encoder, 156 | view, 157 | size.width, 158 | size.height, 159 | ) 160 | .expect("Draw queued"); 161 | 162 | glyph_brush.queue(Section { 163 | screen_position: (30.0, 90.0), 164 | bounds: (size.width as f32, size.height as f32), 165 | text: vec![Text::new("Hello wgpu_glyph!") 166 | .with_color([1.0, 1.0, 1.0, 1.0]) 167 | .with_scale(40.0)], 168 | ..Section::default() 169 | }); 170 | 171 | // Draw the text! 172 | glyph_brush 173 | .draw_queued_with_transform_and_scissoring( 174 | &device, 175 | &mut staging_belt, 176 | &mut encoder, 177 | view, 178 | wgpu_glyph::orthographic_projection( 179 | size.width, 180 | size.height, 181 | ), 182 | Region { 183 | x: 40, 184 | y: 105, 185 | width: 200, 186 | height: 15, 187 | }, 188 | ) 189 | .expect("Draw queued"); 190 | 191 | // Submit the work! 192 | staging_belt.finish(); 193 | queue.submit(Some(encoder.finish())); 194 | frame.present(); 195 | // Recall unused staging buffers 196 | staging_belt.recall(); 197 | } 198 | _ => {} 199 | } 200 | }).map_err(Into::into) 201 | } 202 | -------------------------------------------------------------------------------- /examples/depth.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use wgpu::CompositeAlphaMode; 3 | use wgpu_glyph::{ab_glyph, GlyphBrushBuilder, Section, Text}; 4 | 5 | const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb; 6 | 7 | fn main() -> Result<(), Box> { 8 | env_logger::init(); 9 | 10 | // Open window and create a surface 11 | let event_loop = winit::event_loop::EventLoop::new()?; 12 | 13 | let window = winit::window::WindowBuilder::new() 14 | .with_resizable(false) 15 | .build(&event_loop) 16 | .unwrap(); 17 | 18 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default()); 19 | let surface = instance.create_surface(&window)?; 20 | 21 | // Initialize GPU 22 | let (device, queue) = futures::executor::block_on(async { 23 | let adapter = instance 24 | .request_adapter(&wgpu::RequestAdapterOptions { 25 | power_preference: wgpu::PowerPreference::HighPerformance, 26 | compatible_surface: Some(&surface), 27 | force_fallback_adapter: false, 28 | }) 29 | .await 30 | .expect("Request adapter"); 31 | 32 | adapter 33 | .request_device(&wgpu::DeviceDescriptor::default(), None) 34 | .await 35 | .expect("Request device") 36 | }); 37 | 38 | // Create staging belt 39 | let mut staging_belt = wgpu::util::StagingBelt::new(1024); 40 | 41 | // Prepare swap chain and depth buffer 42 | let mut size = window.inner_size(); 43 | let mut new_size = None; 44 | 45 | let mut depth_view = create_frame_views(&device, &surface, size); 46 | 47 | // Prepare glyph_brush 48 | let inconsolata = ab_glyph::FontArc::try_from_slice(include_bytes!( 49 | "Inconsolata-Regular.ttf" 50 | ))?; 51 | 52 | let mut glyph_brush = GlyphBrushBuilder::using_font(inconsolata) 53 | .depth_stencil_state(wgpu::DepthStencilState { 54 | format: wgpu::TextureFormat::Depth32Float, 55 | depth_write_enabled: true, 56 | depth_compare: wgpu::CompareFunction::Greater, 57 | stencil: wgpu::StencilState::default(), 58 | bias: wgpu::DepthBiasState::default(), 59 | }) 60 | .build(&device, FORMAT); 61 | 62 | // Render loop 63 | window.request_redraw(); 64 | 65 | event_loop.run(move |event, elwt| { 66 | match event { 67 | winit::event::Event::WindowEvent { 68 | event: winit::event::WindowEvent::CloseRequested, 69 | .. 70 | } => elwt.exit(), 71 | winit::event::Event::WindowEvent { 72 | event: winit::event::WindowEvent::Resized(size), 73 | .. 74 | } => { 75 | new_size = Some(size); 76 | } 77 | winit::event::Event::WindowEvent { 78 | event: winit::event::WindowEvent::RedrawRequested, 79 | .. 80 | } => { 81 | if let Some(new_size) = new_size.take() { 82 | depth_view = 83 | create_frame_views(&device, &surface, new_size); 84 | size = new_size; 85 | } 86 | 87 | // Get a command encoder for the current frame 88 | let mut encoder = device.create_command_encoder( 89 | &wgpu::CommandEncoderDescriptor { 90 | label: Some("Redraw"), 91 | }, 92 | ); 93 | 94 | // Get the next frame 95 | let frame = 96 | surface.get_current_texture().expect("Get next frame"); 97 | let view = &frame 98 | .texture 99 | .create_view(&wgpu::TextureViewDescriptor::default()); 100 | 101 | // Clear frame 102 | { 103 | let _ = encoder.begin_render_pass( 104 | &wgpu::RenderPassDescriptor { 105 | label: Some("Render pass"), 106 | color_attachments: &[Some( 107 | wgpu::RenderPassColorAttachment { 108 | view, 109 | resolve_target: None, 110 | ops: wgpu::Operations { 111 | load: wgpu::LoadOp::Clear( 112 | wgpu::Color { 113 | r: 0.4, 114 | g: 0.4, 115 | b: 0.4, 116 | a: 1.0, 117 | }, 118 | ), 119 | store: wgpu::StoreOp::Store, 120 | }, 121 | }, 122 | )], 123 | depth_stencil_attachment: None, 124 | timestamp_writes: None, 125 | occlusion_query_set: None, 126 | }, 127 | ); 128 | } 129 | 130 | // Queue text on top, it will be drawn first. 131 | // Depth buffer will make it appear on top. 132 | glyph_brush.queue(Section { 133 | screen_position: (30.0, 30.0), 134 | text: vec![Text::default() 135 | .with_text("On top") 136 | .with_scale(95.0) 137 | .with_color([0.8, 0.8, 0.8, 1.0]) 138 | .with_z(0.9)], 139 | ..Section::default() 140 | }); 141 | 142 | // Queue background text next. 143 | // Without a depth buffer, this text would be rendered on top of the 144 | // previous queued text. 145 | glyph_brush.queue(Section { 146 | bounds: (size.width as f32, size.height as f32), 147 | text: vec![Text::default() 148 | .with_text( 149 | &include_str!("lipsum.txt") 150 | .replace("\n\n", "") 151 | .repeat(10), 152 | ) 153 | .with_scale(30.0) 154 | .with_color([0.05, 0.05, 0.1, 1.0]) 155 | .with_z(0.2)], 156 | ..Section::default() 157 | }); 158 | 159 | // Draw all the text! 160 | glyph_brush 161 | .draw_queued( 162 | &device, 163 | &mut staging_belt, 164 | &mut encoder, 165 | view, 166 | wgpu::RenderPassDepthStencilAttachment { 167 | view: &depth_view, 168 | depth_ops: Some(wgpu::Operations { 169 | load: wgpu::LoadOp::Clear(0.0), 170 | store: wgpu::StoreOp::Store, 171 | }), 172 | stencil_ops: Some(wgpu::Operations { 173 | load: wgpu::LoadOp::Clear(0), 174 | store: wgpu::StoreOp::Store, 175 | }), 176 | }, 177 | size.width, 178 | size.height, 179 | ) 180 | .expect("Draw queued"); 181 | 182 | // Submit the work! 183 | staging_belt.finish(); 184 | queue.submit(Some(encoder.finish())); 185 | frame.present(); 186 | // Recall unused staging buffers 187 | staging_belt.recall(); 188 | } 189 | _ => {} 190 | } 191 | }).map_err(Into::into) 192 | } 193 | 194 | fn create_frame_views( 195 | device: &wgpu::Device, 196 | surface: &wgpu::Surface, 197 | size: winit::dpi::PhysicalSize, 198 | ) -> wgpu::TextureView { 199 | let (width, height) = (size.width, size.height); 200 | 201 | surface.configure( 202 | device, 203 | &wgpu::SurfaceConfiguration { 204 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, 205 | format: FORMAT, 206 | width, 207 | height, 208 | present_mode: wgpu::PresentMode::AutoVsync, 209 | alpha_mode: CompositeAlphaMode::Auto, 210 | view_formats: vec![], 211 | desired_maximum_frame_latency: 2, 212 | }, 213 | ); 214 | 215 | let depth_texture = device.create_texture(&wgpu::TextureDescriptor { 216 | label: Some("Depth buffer"), 217 | size: wgpu::Extent3d { 218 | width, 219 | height, 220 | depth_or_array_layers: 1, 221 | }, 222 | mip_level_count: 1, 223 | sample_count: 1, 224 | dimension: wgpu::TextureDimension::D2, 225 | format: wgpu::TextureFormat::Depth32Float, 226 | view_formats: &[], 227 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, 228 | }); 229 | 230 | depth_texture.create_view(&wgpu::TextureViewDescriptor::default()) 231 | } 232 | -------------------------------------------------------------------------------- /examples/hello.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use wgpu::CompositeAlphaMode; 3 | use wgpu_glyph::{ab_glyph, GlyphBrushBuilder, Section, Text}; 4 | 5 | fn main() -> Result<(), Box> { 6 | env_logger::init(); 7 | 8 | // Open window and create a surface 9 | let event_loop = winit::event_loop::EventLoop::new()?; 10 | 11 | let window = winit::window::WindowBuilder::new() 12 | .with_resizable(false) 13 | .build(&event_loop) 14 | .unwrap(); 15 | 16 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default()); 17 | let surface = instance.create_surface(&window)?; 18 | 19 | // Initialize GPU 20 | let (device, queue) = futures::executor::block_on(async { 21 | let adapter = instance 22 | .request_adapter(&wgpu::RequestAdapterOptions { 23 | power_preference: wgpu::PowerPreference::HighPerformance, 24 | compatible_surface: Some(&surface), 25 | force_fallback_adapter: false, 26 | }) 27 | .await 28 | .expect("Request adapter"); 29 | 30 | adapter 31 | .request_device(&wgpu::DeviceDescriptor::default(), None) 32 | .await 33 | .expect("Request device") 34 | }); 35 | 36 | // Create staging belt 37 | let mut staging_belt = wgpu::util::StagingBelt::new(1024); 38 | 39 | // Prepare swap chain 40 | let render_format = wgpu::TextureFormat::Bgra8UnormSrgb; 41 | let mut size = window.inner_size(); 42 | 43 | surface.configure( 44 | &device, 45 | &wgpu::SurfaceConfiguration { 46 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, 47 | format: render_format, 48 | width: size.width, 49 | height: size.height, 50 | present_mode: wgpu::PresentMode::AutoVsync, 51 | alpha_mode: CompositeAlphaMode::Auto, 52 | view_formats: vec![], 53 | desired_maximum_frame_latency: 2, 54 | }, 55 | ); 56 | 57 | // Prepare glyph_brush 58 | let inconsolata = ab_glyph::FontArc::try_from_slice(include_bytes!( 59 | "Inconsolata-Regular.ttf" 60 | ))?; 61 | 62 | let mut glyph_brush = GlyphBrushBuilder::using_font(inconsolata) 63 | .build(&device, render_format); 64 | 65 | // Render loop 66 | window.request_redraw(); 67 | 68 | event_loop.run(move |event, elwt| { 69 | match event { 70 | winit::event::Event::WindowEvent { 71 | event: winit::event::WindowEvent::CloseRequested, 72 | .. 73 | } => elwt.exit(), 74 | winit::event::Event::WindowEvent { 75 | event: winit::event::WindowEvent::Resized(new_size), 76 | .. 77 | } => { 78 | size = new_size; 79 | 80 | surface.configure( 81 | &device, 82 | &wgpu::SurfaceConfiguration { 83 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, 84 | format: render_format, 85 | width: size.width, 86 | height: size.height, 87 | present_mode: wgpu::PresentMode::AutoVsync, 88 | alpha_mode: CompositeAlphaMode::Auto, 89 | view_formats: vec![render_format], 90 | desired_maximum_frame_latency: 2, 91 | }, 92 | ); 93 | } 94 | winit::event::Event::WindowEvent { 95 | event: winit::event::WindowEvent::RedrawRequested, 96 | .. 97 | } => { 98 | // Get a command encoder for the current frame 99 | let mut encoder = device.create_command_encoder( 100 | &wgpu::CommandEncoderDescriptor { 101 | label: Some("Redraw"), 102 | }, 103 | ); 104 | 105 | // Get the next frame 106 | let frame = 107 | surface.get_current_texture().expect("Get next frame"); 108 | let view = &frame 109 | .texture 110 | .create_view(&wgpu::TextureViewDescriptor::default()); 111 | 112 | // Clear frame 113 | { 114 | let _ = encoder.begin_render_pass( 115 | &wgpu::RenderPassDescriptor { 116 | label: Some("Render pass"), 117 | color_attachments: &[Some( 118 | wgpu::RenderPassColorAttachment { 119 | view, 120 | resolve_target: None, 121 | ops: wgpu::Operations { 122 | load: wgpu::LoadOp::Clear( 123 | wgpu::Color { 124 | r: 0.4, 125 | g: 0.4, 126 | b: 0.4, 127 | a: 1.0, 128 | }, 129 | ), 130 | store: wgpu::StoreOp::Store, 131 | }, 132 | }, 133 | )], 134 | depth_stencil_attachment: None, 135 | timestamp_writes: None, 136 | occlusion_query_set: None, 137 | }, 138 | ); 139 | } 140 | 141 | glyph_brush.queue(Section { 142 | screen_position: (30.0, 30.0), 143 | bounds: (size.width as f32, size.height as f32), 144 | text: vec![Text::new("Hello wgpu_glyph!") 145 | .with_color([0.0, 0.0, 0.0, 1.0]) 146 | .with_scale(40.0)], 147 | ..Section::default() 148 | }); 149 | 150 | glyph_brush.queue(Section { 151 | screen_position: (30.0, 90.0), 152 | bounds: (size.width as f32, size.height as f32), 153 | text: vec![Text::new("Hello wgpu_glyph!") 154 | .with_color([1.0, 1.0, 1.0, 1.0]) 155 | .with_scale(40.0)], 156 | ..Section::default() 157 | }); 158 | 159 | // Draw the text! 160 | glyph_brush 161 | .draw_queued( 162 | &device, 163 | &mut staging_belt, 164 | &mut encoder, 165 | view, 166 | size.width, 167 | size.height, 168 | ) 169 | .expect("Draw queued"); 170 | 171 | // Submit the work! 172 | staging_belt.finish(); 173 | queue.submit(Some(encoder.finish())); 174 | frame.present(); 175 | // Recall unused staging buffers 176 | staging_belt.recall(); 177 | } 178 | _ => {} 179 | } 180 | }).map_err(Into::into) 181 | } 182 | -------------------------------------------------------------------------------- /examples/lipsum.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, ferri simul omittantur eam eu, no debet doming dolorem ius. Iriure vocibus est te, natum delicata dignissim pri ea. Purto docendi definitiones no qui. Vel ridens instructior ad, vidisse percipitur et eos. Alienum ocurreret laboramus mei cu, usu ne meliore nostrum, usu tritani luptatum electram ad. 2 | 3 | Vis oratio tantas prodesset et, id stet inermis mea, at his copiosae accusata. Mel diam accusata argumentum cu, ut agam consul invidunt est. Ocurreret appellantur deterruisset no vis, his alia postulant inciderint no. Has albucius offendit at. An has noluisse comprehensam, vel veri dicit blandit ea, per paulo noluisse reformidans no. Nec ad sale illum soleat, agam scriptorem ad per. 4 | 5 | An cum odio mucius apeirian, labores conceptam ex nec, eruditi habemus qualisque eam an. Eu facilisi maluisset eos, fabulas apeirian ut qui, no atqui blandit vix. Apeirian phaedrum pri ex, vel hinc omnes sapientem et, vim vocibus legendos disputando ne. Et vel semper nominati rationibus, eum lorem causae scripta no. 6 | 7 | Ut quo elitr viderer constituam, pro omnesque forensibus at. Timeam scaevola mediocrem ut pri, te pro congue delicatissimi. Mei wisi nostro imperdiet ea, ridens salutatus per no, ut viris partem disputationi sit. Exerci eripuit referrentur vix at, sale mediocrem repudiare per te, modus admodum an eam. No vocent indoctum vis, ne quodsi patrioque vix. Vocent labores omittam et usu. 8 | 9 | Democritum signiferumque id nam, enim idque facilis at his. Inermis percipitur scriptorem sea cu, est ne error ludus option. Graecis expetenda contentiones cum et, ius nullam impetus suscipit ex. Modus clita corrumpit mel te, qui at lorem harum, primis cetero habemus sea id. Ei mutat affert dolorum duo, eum dissentias voluptatibus te, libris theophrastus duo id. 10 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width=80 2 | -------------------------------------------------------------------------------- /src/GLYPH_BRUSH_LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Alex Butler 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/builder.rs: -------------------------------------------------------------------------------- 1 | use core::hash::BuildHasher; 2 | 3 | use glyph_brush::ab_glyph::Font; 4 | use glyph_brush::delegate_glyph_brush_builder_fns; 5 | use glyph_brush::DefaultSectionHasher; 6 | 7 | use super::GlyphBrush; 8 | 9 | /// Builder for a [`GlyphBrush`](struct.GlyphBrush.html). 10 | pub struct GlyphBrushBuilder { 11 | inner: glyph_brush::GlyphBrushBuilder, 12 | texture_filter_method: wgpu::FilterMode, 13 | multisample_state: wgpu::MultisampleState, 14 | depth: D, 15 | } 16 | 17 | impl From> 18 | for GlyphBrushBuilder<(), F, H> 19 | { 20 | fn from(inner: glyph_brush::GlyphBrushBuilder) -> Self { 21 | GlyphBrushBuilder { 22 | inner, 23 | texture_filter_method: wgpu::FilterMode::Linear, 24 | multisample_state: wgpu::MultisampleState::default(), 25 | depth: (), 26 | } 27 | } 28 | } 29 | 30 | impl GlyphBrushBuilder<(), ()> { 31 | /// Specifies the default font used to render glyphs. 32 | /// Referenced with `FontId(0)`, which is default. 33 | #[inline] 34 | pub fn using_font(font: F) -> GlyphBrushBuilder<(), F> { 35 | Self::using_fonts(vec![font]) 36 | } 37 | 38 | pub fn using_fonts(fonts: Vec) -> GlyphBrushBuilder<(), F> { 39 | GlyphBrushBuilder { 40 | inner: glyph_brush::GlyphBrushBuilder::using_fonts(fonts), 41 | texture_filter_method: wgpu::FilterMode::Linear, 42 | multisample_state: wgpu::MultisampleState::default(), 43 | depth: (), 44 | } 45 | } 46 | } 47 | 48 | impl GlyphBrushBuilder { 49 | delegate_glyph_brush_builder_fns!(inner); 50 | 51 | /// When multiple CPU cores are available spread rasterization work across 52 | /// all cores. 53 | /// 54 | /// Significantly reduces worst case latency in multicore environments. 55 | /// 56 | /// By default, this feature is __enabled__. 57 | /// 58 | /// # Platform-specific behaviour 59 | /// 60 | /// This option has no effect on wasm32. 61 | pub fn draw_cache_multithread(mut self, multithread: bool) -> Self { 62 | self.inner.draw_cache_builder = 63 | self.inner.draw_cache_builder.multithread(multithread); 64 | 65 | self 66 | } 67 | 68 | /// Sets the texture filtering method. 69 | pub fn texture_filter_method( 70 | mut self, 71 | filter_method: wgpu::FilterMode, 72 | ) -> Self { 73 | self.texture_filter_method = filter_method; 74 | self 75 | } 76 | 77 | /// Sets the multi-sampling state of the render pipeline. 78 | pub fn multisample_state( 79 | mut self, 80 | multisample_state: wgpu::MultisampleState, 81 | ) -> Self { 82 | self.multisample_state = multisample_state; 83 | self 84 | } 85 | 86 | /// Sets the section hasher. `GlyphBrush` cannot handle absolute section 87 | /// hash collisions so use a good hash algorithm. 88 | /// 89 | /// This hasher is used to distinguish sections, rather than for hashmap 90 | /// internal use. 91 | /// 92 | /// Defaults to [xxHash](https://docs.rs/twox-hash). 93 | pub fn section_hasher( 94 | self, 95 | section_hasher: T, 96 | ) -> GlyphBrushBuilder { 97 | GlyphBrushBuilder { 98 | inner: self.inner.section_hasher(section_hasher), 99 | texture_filter_method: self.texture_filter_method, 100 | multisample_state: self.multisample_state, 101 | depth: self.depth, 102 | } 103 | } 104 | 105 | /// Sets the depth stencil. 106 | pub fn depth_stencil_state( 107 | self, 108 | depth_stencil_state: wgpu::DepthStencilState, 109 | ) -> GlyphBrushBuilder { 110 | GlyphBrushBuilder { 111 | inner: self.inner, 112 | texture_filter_method: self.texture_filter_method, 113 | multisample_state: self.multisample_state, 114 | depth: depth_stencil_state, 115 | } 116 | } 117 | } 118 | 119 | impl GlyphBrushBuilder<(), F, H> { 120 | /// Builds a `GlyphBrush` using the given `wgpu::Device` that can render 121 | /// text for texture views with the given `render_format`. 122 | pub fn build( 123 | self, 124 | device: &wgpu::Device, 125 | render_format: wgpu::TextureFormat, 126 | ) -> GlyphBrush<(), F, H> { 127 | GlyphBrush::<(), F, H>::new( 128 | device, 129 | self.texture_filter_method, 130 | self.multisample_state, 131 | render_format, 132 | self.inner, 133 | ) 134 | } 135 | } 136 | 137 | impl 138 | GlyphBrushBuilder 139 | { 140 | /// Builds a `GlyphBrush` using the given `wgpu::Device` that can render 141 | /// text for texture views with the given `render_format`. 142 | pub fn build( 143 | self, 144 | device: &wgpu::Device, 145 | render_format: wgpu::TextureFormat, 146 | ) -> GlyphBrush { 147 | GlyphBrush::::new( 148 | device, 149 | self.texture_filter_method, 150 | self.multisample_state, 151 | render_format, 152 | self.depth, 153 | self.inner, 154 | ) 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A fast text renderer for [`wgpu`]. Powered by [`glyph_brush`]. 2 | //! 3 | //! [`wgpu`]: https://github.com/gfx-rs/wgpu 4 | //! [`glyph_brush`]: https://github.com/alexheretic/glyph-brush/tree/master/glyph-brush 5 | #![deny(unused_results)] 6 | mod builder; 7 | mod pipeline; 8 | mod region; 9 | 10 | pub use region::Region; 11 | 12 | use pipeline::{Instance, Pipeline}; 13 | 14 | pub use builder::GlyphBrushBuilder; 15 | pub use glyph_brush::ab_glyph; 16 | pub use glyph_brush::{ 17 | BuiltInLineBreaker, Extra, FontId, GlyphCruncher, GlyphPositioner, 18 | HorizontalAlign, Layout, LineBreak, LineBreaker, OwnedSection, OwnedText, 19 | Section, SectionGeometry, SectionGlyph, SectionGlyphIter, SectionText, 20 | Text, VerticalAlign, 21 | }; 22 | 23 | use ab_glyph::{Font, Rect}; 24 | use core::hash::BuildHasher; 25 | use std::borrow::Cow; 26 | 27 | use glyph_brush::{BrushAction, BrushError, DefaultSectionHasher}; 28 | use log::{log_enabled, warn}; 29 | 30 | /// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing, 31 | /// glyph draw caching & efficient GPU texture cache updating and re-sizing on demand. 32 | /// 33 | /// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html). 34 | pub struct GlyphBrush { 35 | pipeline: Pipeline, 36 | glyph_brush: glyph_brush::GlyphBrush, 37 | } 38 | 39 | impl GlyphBrush { 40 | /// Queues a section/layout to be drawn by the next call of 41 | /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be 42 | /// called multiple times to queue multiple sections for drawing. 43 | /// 44 | /// Benefits from caching, see [caching behaviour](#caching-behaviour). 45 | #[inline] 46 | pub fn queue<'a, S>(&mut self, section: S) 47 | where 48 | S: Into>>, 49 | { 50 | self.glyph_brush.queue(section) 51 | } 52 | 53 | /// Queues a section/layout to be drawn by the next call of 54 | /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be 55 | /// called multiple times to queue multiple sections for drawing. 56 | /// 57 | /// Used to provide custom `GlyphPositioner` logic, if using built-in 58 | /// [`Layout`](enum.Layout.html) simply use 59 | /// [`queue`](struct.GlyphBrush.html#method.queue) 60 | /// 61 | /// Benefits from caching, see [caching behaviour](#caching-behaviour). 62 | #[inline] 63 | pub fn queue_custom_layout<'a, S, G>( 64 | &mut self, 65 | section: S, 66 | custom_layout: &G, 67 | ) where 68 | G: GlyphPositioner, 69 | S: Into>>, 70 | { 71 | self.glyph_brush.queue_custom_layout(section, custom_layout) 72 | } 73 | 74 | /// Queues pre-positioned glyphs to be processed by the next call of 75 | /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be 76 | /// called multiple times. 77 | #[inline] 78 | pub fn queue_pre_positioned( 79 | &mut self, 80 | glyphs: Vec, 81 | extra: Vec, 82 | bounds: Rect, 83 | ) { 84 | self.glyph_brush.queue_pre_positioned(glyphs, extra, bounds) 85 | } 86 | 87 | /// Retains the section in the cache as if it had been used in the last 88 | /// draw-frame. 89 | /// 90 | /// Should not be necessary unless using multiple draws per frame with 91 | /// distinct transforms, see [caching behaviour](#caching-behaviour). 92 | #[inline] 93 | pub fn keep_cached_custom_layout<'a, S, G>( 94 | &mut self, 95 | section: S, 96 | custom_layout: &G, 97 | ) where 98 | S: Into>>, 99 | G: GlyphPositioner, 100 | { 101 | self.glyph_brush 102 | .keep_cached_custom_layout(section, custom_layout) 103 | } 104 | 105 | /// Retains the section in the cache as if it had been used in the last 106 | /// draw-frame. 107 | /// 108 | /// Should not be necessary unless using multiple draws per frame with 109 | /// distinct transforms, see [caching behaviour](#caching-behaviour). 110 | #[inline] 111 | pub fn keep_cached<'a, S>(&mut self, section: S) 112 | where 113 | S: Into>>, 114 | { 115 | self.glyph_brush.keep_cached(section) 116 | } 117 | 118 | /// Returns the available fonts. 119 | /// 120 | /// The `FontId` corresponds to the index of the font data. 121 | #[inline] 122 | pub fn fonts(&self) -> &[F] { 123 | self.glyph_brush.fonts() 124 | } 125 | 126 | /// Adds an additional font to the one(s) initially added on build. 127 | /// 128 | /// Returns a new [`FontId`](struct.FontId.html) to reference this font. 129 | pub fn add_font(&mut self, font: F) -> FontId { 130 | self.glyph_brush.add_font(font) 131 | } 132 | } 133 | 134 | impl GlyphBrush 135 | where 136 | F: Font + Sync, 137 | H: BuildHasher, 138 | { 139 | fn process_queued( 140 | &mut self, 141 | device: &wgpu::Device, 142 | staging_belt: &mut wgpu::util::StagingBelt, 143 | encoder: &mut wgpu::CommandEncoder, 144 | ) { 145 | let pipeline = &mut self.pipeline; 146 | 147 | let mut brush_action; 148 | 149 | loop { 150 | brush_action = self.glyph_brush.process_queued( 151 | |rect, tex_data| { 152 | let offset = [rect.min[0] as u16, rect.min[1] as u16]; 153 | let size = [rect.width() as u16, rect.height() as u16]; 154 | 155 | pipeline.update_cache( 156 | device, 157 | staging_belt, 158 | encoder, 159 | offset, 160 | size, 161 | tex_data, 162 | ); 163 | }, 164 | Instance::from_vertex, 165 | ); 166 | 167 | match brush_action { 168 | Ok(_) => break, 169 | Err(BrushError::TextureTooSmall { suggested }) => { 170 | // TODO: Obtain max texture dimensions using `wgpu` 171 | // This is currently not possible I think. Ask! 172 | let max_image_dimension = 2048; 173 | 174 | let (new_width, new_height) = if (suggested.0 175 | > max_image_dimension 176 | || suggested.1 > max_image_dimension) 177 | && (self.glyph_brush.texture_dimensions().0 178 | < max_image_dimension 179 | || self.glyph_brush.texture_dimensions().1 180 | < max_image_dimension) 181 | { 182 | (max_image_dimension, max_image_dimension) 183 | } else { 184 | suggested 185 | }; 186 | 187 | if log_enabled!(log::Level::Warn) { 188 | warn!( 189 | "Increasing glyph texture size {old:?} -> {new:?}. \ 190 | Consider building with `.initial_cache_size({new:?})` to avoid \ 191 | resizing", 192 | old = self.glyph_brush.texture_dimensions(), 193 | new = (new_width, new_height), 194 | ); 195 | } 196 | 197 | pipeline.increase_cache_size(device, new_width, new_height); 198 | self.glyph_brush.resize_texture(new_width, new_height); 199 | } 200 | } 201 | } 202 | 203 | match brush_action.unwrap() { 204 | BrushAction::Draw(verts) => { 205 | self.pipeline.upload(device, staging_belt, encoder, &verts); 206 | } 207 | BrushAction::ReDraw => {} 208 | }; 209 | } 210 | } 211 | 212 | impl GlyphBrush<(), F, H> { 213 | fn new( 214 | device: &wgpu::Device, 215 | filter_mode: wgpu::FilterMode, 216 | multisample: wgpu::MultisampleState, 217 | render_format: wgpu::TextureFormat, 218 | raw_builder: glyph_brush::GlyphBrushBuilder, 219 | ) -> Self { 220 | let glyph_brush = raw_builder.build(); 221 | let (cache_width, cache_height) = glyph_brush.texture_dimensions(); 222 | GlyphBrush { 223 | pipeline: Pipeline::<()>::new( 224 | device, 225 | filter_mode, 226 | multisample, 227 | render_format, 228 | cache_width, 229 | cache_height, 230 | ), 231 | glyph_brush, 232 | } 233 | } 234 | 235 | /// Draws all queued sections onto a render target. 236 | /// See [`queue`](struct.GlyphBrush.html#method.queue). 237 | /// 238 | /// It __does not__ submit the encoder command buffer to the device queue. 239 | /// 240 | /// Trims the cache, see [caching behaviour](#caching-behaviour). 241 | /// 242 | /// # Panics 243 | /// Panics if the provided `target` has a texture format that does not match 244 | /// the `render_format` provided on creation of the `GlyphBrush`. 245 | #[inline] 246 | pub fn draw_queued( 247 | &mut self, 248 | device: &wgpu::Device, 249 | staging_belt: &mut wgpu::util::StagingBelt, 250 | encoder: &mut wgpu::CommandEncoder, 251 | target: &wgpu::TextureView, 252 | target_width: u32, 253 | target_height: u32, 254 | ) -> Result<(), String> { 255 | self.draw_queued_with_transform( 256 | device, 257 | staging_belt, 258 | encoder, 259 | target, 260 | orthographic_projection(target_width, target_height), 261 | ) 262 | } 263 | 264 | /// Draws all queued sections onto a render target, applying a position 265 | /// transform (e.g. a projection). 266 | /// See [`queue`](struct.GlyphBrush.html#method.queue). 267 | /// 268 | /// It __does not__ submit the encoder command buffer to the device queue. 269 | /// 270 | /// Trims the cache, see [caching behaviour](#caching-behaviour). 271 | /// 272 | /// # Panics 273 | /// Panics if the provided `target` has a texture format that does not match 274 | /// the `render_format` provided on creation of the `GlyphBrush`. 275 | #[inline] 276 | pub fn draw_queued_with_transform( 277 | &mut self, 278 | device: &wgpu::Device, 279 | staging_belt: &mut wgpu::util::StagingBelt, 280 | encoder: &mut wgpu::CommandEncoder, 281 | target: &wgpu::TextureView, 282 | transform: [f32; 16], 283 | ) -> Result<(), String> { 284 | self.process_queued(device, staging_belt, encoder); 285 | self.pipeline.draw( 286 | device, 287 | staging_belt, 288 | encoder, 289 | target, 290 | transform, 291 | None, 292 | ); 293 | 294 | Ok(()) 295 | } 296 | 297 | /// Draws all queued sections onto a render target, applying a position 298 | /// transform (e.g. a projection) and a scissoring region. 299 | /// See [`queue`](struct.GlyphBrush.html#method.queue). 300 | /// 301 | /// It __does not__ submit the encoder command buffer to the device queue. 302 | /// 303 | /// Trims the cache, see [caching behaviour](#caching-behaviour). 304 | /// 305 | /// # Panics 306 | /// Panics if the provided `target` has a texture format that does not match 307 | /// the `render_format` provided on creation of the `GlyphBrush`. 308 | #[inline] 309 | pub fn draw_queued_with_transform_and_scissoring( 310 | &mut self, 311 | device: &wgpu::Device, 312 | staging_belt: &mut wgpu::util::StagingBelt, 313 | encoder: &mut wgpu::CommandEncoder, 314 | target: &wgpu::TextureView, 315 | transform: [f32; 16], 316 | region: Region, 317 | ) -> Result<(), String> { 318 | self.process_queued(device, staging_belt, encoder); 319 | self.pipeline.draw( 320 | device, 321 | staging_belt, 322 | encoder, 323 | target, 324 | transform, 325 | Some(region), 326 | ); 327 | 328 | Ok(()) 329 | } 330 | } 331 | 332 | impl GlyphBrush { 333 | fn new( 334 | device: &wgpu::Device, 335 | filter_mode: wgpu::FilterMode, 336 | multisample: wgpu::MultisampleState, 337 | render_format: wgpu::TextureFormat, 338 | depth_stencil_state: wgpu::DepthStencilState, 339 | raw_builder: glyph_brush::GlyphBrushBuilder, 340 | ) -> Self { 341 | let glyph_brush = raw_builder.build(); 342 | let (cache_width, cache_height) = glyph_brush.texture_dimensions(); 343 | GlyphBrush { 344 | pipeline: Pipeline::::new( 345 | device, 346 | filter_mode, 347 | multisample, 348 | render_format, 349 | depth_stencil_state, 350 | cache_width, 351 | cache_height, 352 | ), 353 | glyph_brush, 354 | } 355 | } 356 | 357 | /// Draws all queued sections onto a render target. 358 | /// See [`queue`](struct.GlyphBrush.html#method.queue). 359 | /// 360 | /// It __does not__ submit the encoder command buffer to the device queue. 361 | /// 362 | /// Trims the cache, see [caching behaviour](#caching-behaviour). 363 | /// 364 | /// # Panics 365 | /// Panics if the provided `target` has a texture format that does not match 366 | /// the `render_format` provided on creation of the `GlyphBrush`. 367 | #[inline] 368 | pub fn draw_queued( 369 | &mut self, 370 | device: &wgpu::Device, 371 | staging_belt: &mut wgpu::util::StagingBelt, 372 | encoder: &mut wgpu::CommandEncoder, 373 | target: &wgpu::TextureView, 374 | depth_stencil_attachment: wgpu::RenderPassDepthStencilAttachment, 375 | target_width: u32, 376 | target_height: u32, 377 | ) -> Result<(), String> { 378 | self.draw_queued_with_transform( 379 | device, 380 | staging_belt, 381 | encoder, 382 | target, 383 | depth_stencil_attachment, 384 | orthographic_projection(target_width, target_height), 385 | ) 386 | } 387 | 388 | /// Draws all queued sections onto a render target, applying a position 389 | /// transform (e.g. a projection). 390 | /// See [`queue`](struct.GlyphBrush.html#method.queue). 391 | /// 392 | /// It __does not__ submit the encoder command buffer to the device queue. 393 | /// 394 | /// Trims the cache, see [caching behaviour](#caching-behaviour). 395 | /// 396 | /// # Panics 397 | /// Panics if the provided `target` has a texture format that does not match 398 | /// the `render_format` provided on creation of the `GlyphBrush`. 399 | #[inline] 400 | pub fn draw_queued_with_transform( 401 | &mut self, 402 | device: &wgpu::Device, 403 | staging_belt: &mut wgpu::util::StagingBelt, 404 | encoder: &mut wgpu::CommandEncoder, 405 | target: &wgpu::TextureView, 406 | depth_stencil_attachment: wgpu::RenderPassDepthStencilAttachment, 407 | transform: [f32; 16], 408 | ) -> Result<(), String> { 409 | self.process_queued(device, staging_belt, encoder); 410 | self.pipeline.draw( 411 | device, 412 | staging_belt, 413 | encoder, 414 | target, 415 | depth_stencil_attachment, 416 | transform, 417 | None, 418 | ); 419 | 420 | Ok(()) 421 | } 422 | 423 | /// Draws all queued sections onto a render target, applying a position 424 | /// transform (e.g. a projection) and a scissoring region. 425 | /// See [`queue`](struct.GlyphBrush.html#method.queue). 426 | /// 427 | /// It __does not__ submit the encoder command buffer to the device queue. 428 | /// 429 | /// Trims the cache, see [caching behaviour](#caching-behaviour). 430 | /// 431 | /// # Panics 432 | /// Panics if the provided `target` has a texture format that does not match 433 | /// the `render_format` provided on creation of the `GlyphBrush`. 434 | #[inline] 435 | pub fn draw_queued_with_transform_and_scissoring( 436 | &mut self, 437 | device: &wgpu::Device, 438 | staging_belt: &mut wgpu::util::StagingBelt, 439 | encoder: &mut wgpu::CommandEncoder, 440 | target: &wgpu::TextureView, 441 | depth_stencil_attachment: wgpu::RenderPassDepthStencilAttachment, 442 | transform: [f32; 16], 443 | region: Region, 444 | ) -> Result<(), String> { 445 | self.process_queued(device, staging_belt, encoder); 446 | 447 | self.pipeline.draw( 448 | device, 449 | staging_belt, 450 | encoder, 451 | target, 452 | depth_stencil_attachment, 453 | transform, 454 | Some(region), 455 | ); 456 | 457 | Ok(()) 458 | } 459 | } 460 | 461 | /// Helper function to generate a generate a transform matrix. 462 | pub fn orthographic_projection(width: u32, height: u32) -> [f32; 16] { 463 | #[cfg_attr(rustfmt, rustfmt_skip)] 464 | [ 465 | 2.0 / width as f32, 0.0, 0.0, 0.0, 466 | 0.0, -2.0 / height as f32, 0.0, 0.0, 467 | 0.0, 0.0, 1.0, 0.0, 468 | -1.0, 1.0, 0.0, 1.0, 469 | ] 470 | } 471 | 472 | impl GlyphCruncher for GlyphBrush { 473 | #[inline] 474 | fn glyphs_custom_layout<'a, 'b, S, L>( 475 | &'b mut self, 476 | section: S, 477 | custom_layout: &L, 478 | ) -> SectionGlyphIter<'b> 479 | where 480 | L: GlyphPositioner + std::hash::Hash, 481 | S: Into>>, 482 | { 483 | self.glyph_brush 484 | .glyphs_custom_layout(section, custom_layout) 485 | } 486 | 487 | #[inline] 488 | fn fonts(&self) -> &[F] { 489 | self.glyph_brush.fonts() 490 | } 491 | 492 | #[inline] 493 | fn glyph_bounds_custom_layout<'a, S, L>( 494 | &mut self, 495 | section: S, 496 | custom_layout: &L, 497 | ) -> Option 498 | where 499 | L: GlyphPositioner + std::hash::Hash, 500 | S: Into>>, 501 | { 502 | self.glyph_brush 503 | .glyph_bounds_custom_layout(section, custom_layout) 504 | } 505 | } 506 | 507 | impl std::fmt::Debug for GlyphBrush { 508 | #[inline] 509 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 510 | write!(f, "GlyphBrush") 511 | } 512 | } 513 | -------------------------------------------------------------------------------- /src/pipeline.rs: -------------------------------------------------------------------------------- 1 | mod cache; 2 | 3 | use crate::Region; 4 | use cache::Cache; 5 | 6 | use bytemuck::{Pod, Zeroable}; 7 | use core::num::NonZeroU64; 8 | use glyph_brush::ab_glyph::{point, Rect}; 9 | use std::marker::PhantomData; 10 | use std::mem; 11 | 12 | pub struct Pipeline { 13 | transform: wgpu::Buffer, 14 | sampler: wgpu::Sampler, 15 | cache: Cache, 16 | uniform_layout: wgpu::BindGroupLayout, 17 | uniforms: wgpu::BindGroup, 18 | raw: wgpu::RenderPipeline, 19 | instances: wgpu::Buffer, 20 | current_instances: usize, 21 | supported_instances: usize, 22 | current_transform: [f32; 16], 23 | depth: PhantomData, 24 | } 25 | 26 | impl Pipeline<()> { 27 | pub fn new( 28 | device: &wgpu::Device, 29 | filter_mode: wgpu::FilterMode, 30 | multisample: wgpu::MultisampleState, 31 | render_format: wgpu::TextureFormat, 32 | cache_width: u32, 33 | cache_height: u32, 34 | ) -> Pipeline<()> { 35 | build( 36 | device, 37 | filter_mode, 38 | multisample, 39 | render_format, 40 | None, 41 | cache_width, 42 | cache_height, 43 | ) 44 | } 45 | 46 | pub fn draw( 47 | &mut self, 48 | device: &wgpu::Device, 49 | staging_belt: &mut wgpu::util::StagingBelt, 50 | encoder: &mut wgpu::CommandEncoder, 51 | target: &wgpu::TextureView, 52 | transform: [f32; 16], 53 | region: Option, 54 | ) { 55 | draw( 56 | self, 57 | device, 58 | staging_belt, 59 | encoder, 60 | target, 61 | None, 62 | transform, 63 | region, 64 | ); 65 | } 66 | } 67 | 68 | impl Pipeline { 69 | pub fn new( 70 | device: &wgpu::Device, 71 | filter_mode: wgpu::FilterMode, 72 | multisample: wgpu::MultisampleState, 73 | render_format: wgpu::TextureFormat, 74 | depth_stencil_state: wgpu::DepthStencilState, 75 | cache_width: u32, 76 | cache_height: u32, 77 | ) -> Pipeline { 78 | build( 79 | device, 80 | filter_mode, 81 | multisample, 82 | render_format, 83 | Some(depth_stencil_state), 84 | cache_width, 85 | cache_height, 86 | ) 87 | } 88 | 89 | pub fn draw( 90 | &mut self, 91 | device: &wgpu::Device, 92 | staging_belt: &mut wgpu::util::StagingBelt, 93 | encoder: &mut wgpu::CommandEncoder, 94 | target: &wgpu::TextureView, 95 | depth_stencil_attachment: wgpu::RenderPassDepthStencilAttachment, 96 | transform: [f32; 16], 97 | region: Option, 98 | ) { 99 | draw( 100 | self, 101 | device, 102 | staging_belt, 103 | encoder, 104 | target, 105 | Some(depth_stencil_attachment), 106 | transform, 107 | region, 108 | ); 109 | } 110 | } 111 | 112 | impl Pipeline { 113 | pub fn update_cache( 114 | &mut self, 115 | device: &wgpu::Device, 116 | staging_belt: &mut wgpu::util::StagingBelt, 117 | encoder: &mut wgpu::CommandEncoder, 118 | offset: [u16; 2], 119 | size: [u16; 2], 120 | data: &[u8], 121 | ) { 122 | self.cache 123 | .update(device, staging_belt, encoder, offset, size, data); 124 | } 125 | 126 | pub fn increase_cache_size( 127 | &mut self, 128 | device: &wgpu::Device, 129 | width: u32, 130 | height: u32, 131 | ) { 132 | self.cache = Cache::new(device, width, height); 133 | 134 | self.uniforms = create_uniforms( 135 | device, 136 | &self.uniform_layout, 137 | &self.transform, 138 | &self.sampler, 139 | &self.cache.view, 140 | ); 141 | } 142 | 143 | pub fn upload( 144 | &mut self, 145 | device: &wgpu::Device, 146 | staging_belt: &mut wgpu::util::StagingBelt, 147 | encoder: &mut wgpu::CommandEncoder, 148 | instances: &[Instance], 149 | ) { 150 | if instances.is_empty() { 151 | self.current_instances = 0; 152 | return; 153 | } 154 | 155 | if instances.len() > self.supported_instances { 156 | self.instances = device.create_buffer(&wgpu::BufferDescriptor { 157 | label: Some("wgpu_glyph::Pipeline instances"), 158 | size: mem::size_of::() as u64 159 | * instances.len() as u64, 160 | usage: wgpu::BufferUsages::VERTEX 161 | | wgpu::BufferUsages::COPY_DST, 162 | mapped_at_creation: false, 163 | }); 164 | 165 | self.supported_instances = instances.len(); 166 | } 167 | 168 | let instances_bytes = bytemuck::cast_slice(instances); 169 | 170 | if let Some(size) = NonZeroU64::new(instances_bytes.len() as u64) { 171 | let mut instances_view = staging_belt.write_buffer( 172 | encoder, 173 | &self.instances, 174 | 0, 175 | size, 176 | device, 177 | ); 178 | 179 | instances_view.copy_from_slice(instances_bytes); 180 | } 181 | 182 | self.current_instances = instances.len(); 183 | } 184 | } 185 | 186 | // Helpers 187 | #[cfg_attr(rustfmt, rustfmt_skip)] 188 | const IDENTITY_MATRIX: [f32; 16] = [ 189 | 1.0, 0.0, 0.0, 0.0, 190 | 0.0, 1.0, 0.0, 0.0, 191 | 0.0, 0.0, 1.0, 0.0, 192 | 0.0, 0.0, 0.0, 1.0, 193 | ]; 194 | 195 | fn build( 196 | device: &wgpu::Device, 197 | filter_mode: wgpu::FilterMode, 198 | multisample: wgpu::MultisampleState, 199 | render_format: wgpu::TextureFormat, 200 | depth_stencil: Option, 201 | cache_width: u32, 202 | cache_height: u32, 203 | ) -> Pipeline { 204 | use wgpu::util::DeviceExt; 205 | 206 | let transform = 207 | device.create_buffer_init(&wgpu::util::BufferInitDescriptor { 208 | label: None, 209 | contents: bytemuck::cast_slice(&IDENTITY_MATRIX), 210 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, 211 | }); 212 | 213 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { 214 | address_mode_u: wgpu::AddressMode::ClampToEdge, 215 | address_mode_v: wgpu::AddressMode::ClampToEdge, 216 | address_mode_w: wgpu::AddressMode::ClampToEdge, 217 | mag_filter: filter_mode, 218 | min_filter: filter_mode, 219 | mipmap_filter: filter_mode, 220 | ..Default::default() 221 | }); 222 | 223 | let cache = Cache::new(device, cache_width, cache_height); 224 | 225 | let uniform_layout = 226 | device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { 227 | label: Some("wgpu_glyph::Pipeline uniforms"), 228 | entries: &[ 229 | wgpu::BindGroupLayoutEntry { 230 | binding: 0, 231 | visibility: wgpu::ShaderStages::VERTEX, 232 | ty: wgpu::BindingType::Buffer { 233 | ty: wgpu::BufferBindingType::Uniform, 234 | has_dynamic_offset: false, 235 | min_binding_size: wgpu::BufferSize::new( 236 | mem::size_of::<[f32; 16]>() as u64, 237 | ), 238 | }, 239 | count: None, 240 | }, 241 | wgpu::BindGroupLayoutEntry { 242 | binding: 1, 243 | visibility: wgpu::ShaderStages::FRAGMENT, 244 | ty: wgpu::BindingType::Sampler( 245 | wgpu::SamplerBindingType::Filtering, 246 | ), 247 | count: None, 248 | }, 249 | wgpu::BindGroupLayoutEntry { 250 | binding: 2, 251 | visibility: wgpu::ShaderStages::FRAGMENT, 252 | ty: wgpu::BindingType::Texture { 253 | sample_type: wgpu::TextureSampleType::Float { 254 | filterable: true, 255 | }, 256 | view_dimension: wgpu::TextureViewDimension::D2, 257 | multisampled: false, 258 | }, 259 | count: None, 260 | }, 261 | ], 262 | }); 263 | 264 | let uniforms = create_uniforms( 265 | device, 266 | &uniform_layout, 267 | &transform, 268 | &sampler, 269 | &cache.view, 270 | ); 271 | 272 | let instances = device.create_buffer(&wgpu::BufferDescriptor { 273 | label: Some("wgpu_glyph::Pipeline instances"), 274 | size: mem::size_of::() as u64 275 | * Instance::INITIAL_AMOUNT as u64, 276 | usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, 277 | mapped_at_creation: false, 278 | }); 279 | 280 | let layout = 281 | device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { 282 | label: None, 283 | push_constant_ranges: &[], 284 | bind_group_layouts: &[&uniform_layout], 285 | }); 286 | 287 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { 288 | label: Some("Glyph Shader"), 289 | source: wgpu::ShaderSource::Wgsl(crate::Cow::Borrowed(include_str!( 290 | "shader/glyph.wgsl" 291 | ))), 292 | }); 293 | 294 | let raw = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { 295 | label: None, 296 | cache: None, 297 | layout: Some(&layout), 298 | vertex: wgpu::VertexState { 299 | module: &shader, 300 | entry_point: Some("vs_main"), 301 | buffers: &[wgpu::VertexBufferLayout { 302 | array_stride: mem::size_of::() as u64, 303 | step_mode: wgpu::VertexStepMode::Instance, 304 | attributes: &wgpu::vertex_attr_array![ 305 | 0 => Float32x3, 306 | 1 => Float32x2, 307 | 2 => Float32x2, 308 | 3 => Float32x2, 309 | 4 => Float32x4, 310 | ], 311 | }], 312 | compilation_options: wgpu::PipelineCompilationOptions::default(), 313 | }, 314 | primitive: wgpu::PrimitiveState { 315 | topology: wgpu::PrimitiveTopology::TriangleStrip, 316 | front_face: wgpu::FrontFace::Cw, 317 | strip_index_format: Some(wgpu::IndexFormat::Uint16), 318 | ..Default::default() 319 | }, 320 | depth_stencil, 321 | multisample, 322 | fragment: Some(wgpu::FragmentState { 323 | module: &shader, 324 | entry_point: Some("fs_main"), 325 | targets: &[Some(wgpu::ColorTargetState { 326 | format: render_format, 327 | blend: Some(wgpu::BlendState { 328 | color: wgpu::BlendComponent { 329 | src_factor: wgpu::BlendFactor::SrcAlpha, 330 | dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, 331 | operation: wgpu::BlendOperation::Add, 332 | }, 333 | alpha: wgpu::BlendComponent { 334 | src_factor: wgpu::BlendFactor::One, 335 | dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, 336 | operation: wgpu::BlendOperation::Add, 337 | }, 338 | }), 339 | write_mask: wgpu::ColorWrites::ALL, 340 | })], 341 | compilation_options: wgpu::PipelineCompilationOptions::default(), 342 | }), 343 | multiview: None, 344 | }); 345 | 346 | Pipeline { 347 | transform, 348 | sampler, 349 | cache, 350 | uniform_layout, 351 | uniforms, 352 | raw, 353 | instances, 354 | current_instances: 0, 355 | supported_instances: Instance::INITIAL_AMOUNT, 356 | current_transform: [0.0; 16], 357 | depth: PhantomData, 358 | } 359 | } 360 | 361 | fn draw( 362 | pipeline: &mut Pipeline, 363 | device: &wgpu::Device, 364 | staging_belt: &mut wgpu::util::StagingBelt, 365 | encoder: &mut wgpu::CommandEncoder, 366 | target: &wgpu::TextureView, 367 | depth_stencil_attachment: Option, 368 | transform: [f32; 16], 369 | region: Option, 370 | ) { 371 | if transform != pipeline.current_transform { 372 | let mut transform_view = staging_belt.write_buffer( 373 | encoder, 374 | &pipeline.transform, 375 | 0, 376 | unsafe { NonZeroU64::new_unchecked(16 * 4) }, 377 | device, 378 | ); 379 | 380 | transform_view.copy_from_slice(bytemuck::cast_slice(&transform)); 381 | 382 | pipeline.current_transform = transform; 383 | } 384 | 385 | let mut render_pass = 386 | encoder.begin_render_pass(&wgpu::RenderPassDescriptor { 387 | label: Some("wgpu_glyph::pipeline render pass"), 388 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { 389 | view: target, 390 | resolve_target: None, 391 | ops: wgpu::Operations { 392 | load: wgpu::LoadOp::Load, 393 | store: wgpu::StoreOp::Store, 394 | }, 395 | })], 396 | depth_stencil_attachment, 397 | timestamp_writes: None, 398 | occlusion_query_set: None, 399 | }); 400 | 401 | render_pass.set_pipeline(&pipeline.raw); 402 | render_pass.set_bind_group(0, &pipeline.uniforms, &[]); 403 | render_pass.set_vertex_buffer(0, pipeline.instances.slice(..)); 404 | 405 | if let Some(region) = region { 406 | render_pass.set_scissor_rect( 407 | region.x, 408 | region.y, 409 | region.width, 410 | region.height, 411 | ); 412 | } 413 | 414 | render_pass.draw(0..4, 0..pipeline.current_instances as u32); 415 | } 416 | 417 | fn create_uniforms( 418 | device: &wgpu::Device, 419 | layout: &wgpu::BindGroupLayout, 420 | transform: &wgpu::Buffer, 421 | sampler: &wgpu::Sampler, 422 | cache: &wgpu::TextureView, 423 | ) -> wgpu::BindGroup { 424 | device.create_bind_group(&wgpu::BindGroupDescriptor { 425 | label: Some("wgpu_glyph::Pipeline uniforms"), 426 | layout: layout, 427 | entries: &[ 428 | wgpu::BindGroupEntry { 429 | binding: 0, 430 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { 431 | buffer: transform, 432 | offset: 0, 433 | size: None, 434 | }), 435 | }, 436 | wgpu::BindGroupEntry { 437 | binding: 1, 438 | resource: wgpu::BindingResource::Sampler(sampler), 439 | }, 440 | wgpu::BindGroupEntry { 441 | binding: 2, 442 | resource: wgpu::BindingResource::TextureView(cache), 443 | }, 444 | ], 445 | }) 446 | } 447 | 448 | #[repr(C)] 449 | #[derive(Debug, Clone, Copy, Zeroable, Pod)] 450 | pub struct Instance { 451 | left_top: [f32; 3], 452 | right_bottom: [f32; 2], 453 | tex_left_top: [f32; 2], 454 | tex_right_bottom: [f32; 2], 455 | color: [f32; 4], 456 | } 457 | 458 | impl Instance { 459 | const INITIAL_AMOUNT: usize = 50_000; 460 | 461 | pub fn from_vertex( 462 | glyph_brush::GlyphVertex { 463 | mut tex_coords, 464 | pixel_coords, 465 | bounds, 466 | extra, 467 | }: glyph_brush::GlyphVertex, 468 | ) -> Instance { 469 | let gl_bounds = bounds; 470 | 471 | let mut gl_rect = Rect { 472 | min: point(pixel_coords.min.x as f32, pixel_coords.min.y as f32), 473 | max: point(pixel_coords.max.x as f32, pixel_coords.max.y as f32), 474 | }; 475 | 476 | // handle overlapping bounds, modify uv_rect to preserve texture aspect 477 | if gl_rect.max.x > gl_bounds.max.x { 478 | let old_width = gl_rect.width(); 479 | gl_rect.max.x = gl_bounds.max.x; 480 | tex_coords.max.x = tex_coords.min.x 481 | + tex_coords.width() * gl_rect.width() / old_width; 482 | } 483 | 484 | if gl_rect.min.x < gl_bounds.min.x { 485 | let old_width = gl_rect.width(); 486 | gl_rect.min.x = gl_bounds.min.x; 487 | tex_coords.min.x = tex_coords.max.x 488 | - tex_coords.width() * gl_rect.width() / old_width; 489 | } 490 | 491 | if gl_rect.max.y > gl_bounds.max.y { 492 | let old_height = gl_rect.height(); 493 | gl_rect.max.y = gl_bounds.max.y; 494 | tex_coords.max.y = tex_coords.min.y 495 | + tex_coords.height() * gl_rect.height() / old_height; 496 | } 497 | 498 | if gl_rect.min.y < gl_bounds.min.y { 499 | let old_height = gl_rect.height(); 500 | gl_rect.min.y = gl_bounds.min.y; 501 | tex_coords.min.y = tex_coords.max.y 502 | - tex_coords.height() * gl_rect.height() / old_height; 503 | } 504 | 505 | Instance { 506 | left_top: [gl_rect.min.x, gl_rect.max.y, extra.z], 507 | right_bottom: [gl_rect.max.x, gl_rect.min.y], 508 | tex_left_top: [tex_coords.min.x, tex_coords.max.y], 509 | tex_right_bottom: [tex_coords.max.x, tex_coords.min.y], 510 | color: extra.color, 511 | } 512 | } 513 | } 514 | -------------------------------------------------------------------------------- /src/pipeline/cache.rs: -------------------------------------------------------------------------------- 1 | use core::num::NonZeroU64; 2 | 3 | pub struct Cache { 4 | texture: wgpu::Texture, 5 | pub(super) view: wgpu::TextureView, 6 | upload_buffer: wgpu::Buffer, 7 | upload_buffer_size: u64, 8 | } 9 | 10 | impl Cache { 11 | const INITIAL_UPLOAD_BUFFER_SIZE: u64 = 12 | wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64 * 100; 13 | 14 | pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Cache { 15 | let texture = device.create_texture(&wgpu::TextureDescriptor { 16 | label: Some("wgpu_glyph::Cache"), 17 | size: wgpu::Extent3d { 18 | width, 19 | height, 20 | depth_or_array_layers: 1, 21 | }, 22 | dimension: wgpu::TextureDimension::D2, 23 | format: wgpu::TextureFormat::R8Unorm, 24 | usage: wgpu::TextureUsages::COPY_DST 25 | | wgpu::TextureUsages::TEXTURE_BINDING, 26 | mip_level_count: 1, 27 | sample_count: 1, 28 | view_formats: &[], 29 | }); 30 | 31 | let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); 32 | 33 | let upload_buffer = device.create_buffer(&wgpu::BufferDescriptor { 34 | label: Some("wgpu_glyph::Cache upload buffer"), 35 | size: Self::INITIAL_UPLOAD_BUFFER_SIZE, 36 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, 37 | mapped_at_creation: false, 38 | }); 39 | 40 | Cache { 41 | texture, 42 | view, 43 | upload_buffer, 44 | upload_buffer_size: Self::INITIAL_UPLOAD_BUFFER_SIZE, 45 | } 46 | } 47 | 48 | pub fn update( 49 | &mut self, 50 | device: &wgpu::Device, 51 | staging_belt: &mut wgpu::util::StagingBelt, 52 | encoder: &mut wgpu::CommandEncoder, 53 | offset: [u16; 2], 54 | size: [u16; 2], 55 | data: &[u8], 56 | ) { 57 | let width = size[0] as usize; 58 | let height = size[1] as usize; 59 | 60 | // It is a webgpu requirement that: 61 | // BufferCopyView.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0 62 | // So we calculate padded_width by rounding width 63 | // up to the next multiple of wgpu::COPY_BYTES_PER_ROW_ALIGNMENT. 64 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; 65 | let padded_width_padding = (align - width % align) % align; 66 | let padded_width = width + padded_width_padding; 67 | 68 | let padded_data_size = (padded_width * height) as u64; 69 | 70 | if self.upload_buffer_size < padded_data_size { 71 | self.upload_buffer = 72 | device.create_buffer(&wgpu::BufferDescriptor { 73 | label: Some("wgpu_glyph::Cache upload buffer"), 74 | size: padded_data_size, 75 | usage: wgpu::BufferUsages::COPY_DST 76 | | wgpu::BufferUsages::COPY_SRC, 77 | mapped_at_creation: false, 78 | }); 79 | 80 | self.upload_buffer_size = padded_data_size; 81 | } 82 | 83 | let mut padded_data = staging_belt.write_buffer( 84 | encoder, 85 | &self.upload_buffer, 86 | 0, 87 | NonZeroU64::new(padded_data_size).unwrap(), 88 | device, 89 | ); 90 | 91 | for row in 0..height { 92 | padded_data[row * padded_width..row * padded_width + width] 93 | .copy_from_slice(&data[row * width..(row + 1) * width]) 94 | } 95 | 96 | // TODO: Move to use Queue for less buffer usage 97 | encoder.copy_buffer_to_texture( 98 | wgpu::ImageCopyBuffer { 99 | buffer: &self.upload_buffer, 100 | layout: wgpu::ImageDataLayout { 101 | offset: 0, 102 | bytes_per_row: Some(padded_width as u32), 103 | rows_per_image: Some(height as u32), 104 | }, 105 | }, 106 | wgpu::ImageCopyTexture { 107 | texture: &self.texture, 108 | mip_level: 0, 109 | origin: wgpu::Origin3d { 110 | x: u32::from(offset[0]), 111 | y: u32::from(offset[1]), 112 | z: 0, 113 | }, 114 | aspect: wgpu::TextureAspect::All, 115 | }, 116 | wgpu::Extent3d { 117 | width: size[0] as u32, 118 | height: size[1] as u32, 119 | depth_or_array_layers: 1, 120 | }, 121 | ); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/region.rs: -------------------------------------------------------------------------------- 1 | /// A region of the screen. 2 | pub struct Region { 3 | pub x: u32, 4 | pub y: u32, 5 | pub width: u32, 6 | pub height: u32, 7 | } 8 | -------------------------------------------------------------------------------- /src/shader/glyph.wgsl: -------------------------------------------------------------------------------- 1 | struct Globals { 2 | transform: mat4x4, 3 | } 4 | 5 | @group(0) @binding(0) var globals: Globals; 6 | @group(0) @binding(1) var font_sampler: sampler; 7 | @group(0) @binding(2) var font_tex: texture_2d; 8 | 9 | struct VertexInput { 10 | @builtin(vertex_index) vertex_index: u32, 11 | @location(0) left_top: vec3f, 12 | @location(1) right_bottom: vec2f, 13 | @location(2) tex_left_top: vec2f, 14 | @location(3) tex_right_bottom: vec2f, 15 | @location(4) color: vec4f, 16 | } 17 | 18 | struct VertexOutput { 19 | @builtin(position) position: vec4f, 20 | @location(0) f_tex_pos: vec2f, 21 | @location(1) f_color: vec4f, 22 | } 23 | 24 | @vertex 25 | fn vs_main(input: VertexInput) -> VertexOutput { 26 | var out: VertexOutput; 27 | 28 | var pos = vec2f(0, 0); 29 | let left = input.left_top.x; 30 | let right = input.right_bottom.x; 31 | let top = input.left_top.y; 32 | let bottom = input.right_bottom.y; 33 | 34 | switch input.vertex_index { 35 | case 0u: { 36 | pos = vec2(left, top); 37 | out.f_tex_pos = input.tex_left_top; 38 | } 39 | case 1u: { 40 | pos = vec2(right, top); 41 | out.f_tex_pos = vec2(input.tex_right_bottom.x, input.tex_left_top.y); 42 | } 43 | case 2u: { 44 | pos = vec2(left, bottom); 45 | out.f_tex_pos = vec2(input.tex_left_top.x, input.tex_right_bottom.y); 46 | } 47 | case 3u: { 48 | pos = vec2(right, bottom); 49 | out.f_tex_pos = input.tex_right_bottom; 50 | } 51 | default: {} 52 | } 53 | 54 | out.f_color = input.color; 55 | out.position = globals.transform * vec4(pos, input.left_top.z, 1.0); 56 | 57 | return out; 58 | } 59 | 60 | @fragment 61 | fn fs_main(input: VertexOutput) -> @location(0) vec4f { 62 | var alpha = textureSample(font_tex, font_sampler, input.f_tex_pos).r; 63 | 64 | if (alpha <= 0.0) { 65 | discard; 66 | } 67 | 68 | return input.f_color * vec4f(1.0, 1.0, 1.0, alpha); 69 | } 70 | --------------------------------------------------------------------------------