pretty_text 0.1.0

Core implementation for Bevy Pretty Text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Material [`effects`](crate::parser#effects) are `Bevy` [assets](bevy::asset)
//! that are dynamically constructed at run time and inserted into text hierarchies.
//!
//! Material effects refer to shader driven effects, such as `glitch`. For ECS
//! effects, see [`dynamic_effects`](crate::dynamic_effects).
//!
//! Materials are applied with [`MeshMaterial2d`] components on
//! [`Glyph`](crate::glyph::Glyph) entities. This means that only 1 material
//! effect will work at a time, whereas [`dynamic_effects`](crate::dynamic_effects)
//! can be layered.
//!
//! # Using Material Effects
//!
//! ```
//! # use bevy::prelude::*;
#![doc = include_str!("../docs/pretty.txt")]
//! #
//! # let mut world = World::new();
//! // Built-in effects are provided with the `default_effects` feature!
//! world.spawn(pretty!("`my glitchy text span`[glitch]"));
//! // ...
//!
//! // Default arguments example
//!
//! #[derive(Default)]
//! struct Glitch {
//!     atlas: Handle<Image>,
//!     arg1: usize,
//!     arg2: f32,
//! }
//!
//! world.spawn(
//!     pretty!("`my shaky text span`[glitch(10)]"),
//! //                     arg2 is defaulted! -^
//! );
//!
//! // This is just syntax sugar for:
//! Glitch {
//!     atlas: Handle::default(),
//! //  ^^^^^ The atlas field is always skipped!
//!     arg1: 10,
//!     ..Default::default()
//! };
//! ```
//!
//! # Defining Custom Materials
//!
//! Material effects are normal `Bevy` [`Material2d`] types that contain a special
//! `atlas` field. The `atlas` field is a handle to the glyph atlas asset which
//! allows glyphs to directly sample from the glyph atlas in the fragment shader.
//!
//! The glyph meshes are packed with extra vertex data to define the position and
//! size of a glyph in the glyph atlas texture.
//!
//! Refer to `Bevy`'s [`Material2d`] or the [default glyph shader] to get started
//! with writing your custom shader.
//!
//! [default glyph shader]: https://github.com/void-scape/pretty-text/blob/a0a0a5631b9302d1db292b9e19d6955809835633/crates/pretty_text/src/shaders/default_glyph_material.wgsl
//!
//! ```ignore
#![doc = include_str!("../docs/material.txt")]
//! ```

use std::borrow::Cow;
use std::marker::PhantomData;

use bevy::asset::weak_handle;
use bevy::platform::collections::HashMap;
use bevy::prelude::*;
use bevy::sprite::{Material2d, Material2dPlugin};

use crate::PrettyText;
use crate::glyph::{GlyphSystems, SpanAtlasImage};

pub(super) fn plugin(app: &mut App) {
    sealed::plugin(app);

    app.init_resource::<DynMaterialRegistry>()
        .register_type::<ErasedPrettyTextMaterial>();
}

/// The default shader for [`Glyph`](crate::glyph::Glyph)s.
///
/// Custom text materials can use the default vertex or fragment shader if no
/// special behavior is required.
pub const DEFAULT_GLYPH_SHADER_HANDLE: Handle<Shader> =
    weak_handle!("35d4f25c-eb2b-4f26-872f-ef666a76554e");

/// A special [material](Material2d) used for rendering a [`Glyph`](crate::glyph::Glyph).
///
/// See [`Material2d`] for general information about 2D materials.
///
/// See [`material`](crate::material) for general information about text materials
/// and how to implement your own.
#[derive(Debug, Default, Clone, Component, Reflect)]
#[require(PrettyText, sealed::Material::new::<Self>())]
pub struct PrettyTextMaterial<M: TextMaterial2d>(pub Handle<M>);

/// A special [`Material2d`] that renders [`Glyph`](crate::glyph::Glyph)s.
///
/// This trait should be derived with
/// [`TextMaterial2d`](https://docs.rs/bevy_pretty_text/material/trait.TextMaterial2d.html),
/// which provides a [`DynamicTextMaterial`] implementation.
///
/// See [`Material2d`] for general information about 2D materials.
///
/// See [`material`](crate::material) for general information about text materials
/// and how to implement your own.
pub trait TextMaterial2d: Material2d {
    /// Assigns this material's atlas.
    fn set_atlas(&mut self, atlas: Handle<Image>);
}

/// Extension trait for registering [text materials](crate::material).
pub trait PrettyTextMaterialAppExt {
    /// Register material `T` with a `tag`.
    fn register_pretty_material<T>(&mut self, tag: &'static str) -> &mut Self
    where
        T: Default + TextMaterial2d + DynamicTextMaterial,
        T::Data: PartialEq + Eq + std::hash::Hash + Clone;
}

impl PrettyTextMaterialAppExt for App {
    fn register_pretty_material<T>(&mut self, tag: &'static str) -> &mut Self
    where
        T: Default + TextMaterial2d + DynamicTextMaterial,
        T::Data: PartialEq + Eq + std::hash::Hash + Clone,
    {
        self.register_type::<PrettyTextMaterial<T>>();

        self.add_plugins(PrettyTextMaterialPlugin::<T>::default())
            .add_systems(PreStartup, sealed::register_dyn_material::<T>(tag))
    }
}

/// Adds the necessary ECS resources and render logic to enable rendering entities
/// using the given [`TextMaterial2d`] asset type.
pub struct PrettyTextMaterialPlugin<T>(PhantomData<T>);

impl<T> Default for PrettyTextMaterialPlugin<T> {
    fn default() -> Self {
        PrettyTextMaterialPlugin(PhantomData)
    }
}

impl<T> std::fmt::Debug for PrettyTextMaterialPlugin<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("PrettyTextMaterialPlugin")
            .field(&std::any::type_name::<T>())
            .finish()
    }
}

impl<T> Plugin for PrettyTextMaterialPlugin<T>
where
    T: TextMaterial2d,
    T::Data: PartialEq + Eq + std::hash::Hash + Clone,
{
    fn build(&self, app: &mut App) {
        app.add_plugins(Material2dPlugin::<T>::default())
            .add_systems(
                PostUpdate,
                (
                    sealed::apply_material::<T>,
                    set_material_atlas::<T>,
                    // Workaround for bevyengine/bevy#19048, ensuring the mesh components are
                    // present before extraction-relevant systems.
                    ApplyDeferred,
                )
                    .before(bevy::sprite::check_entities_needing_specialization::<T>)
                    .after(sealed::default_material)
                    .in_set(GlyphSystems::PropagateMaterial),
            );
    }
}

/// Constructs `Self` from `args` and inserts into an entity.
///
/// See [`material`](crate::material).
///
/// This trait should be derived with `TextMaterial2d`.
pub trait DynamicTextMaterial: Send + Sync + 'static {
    /// Construct a dynamic material from `args` and insert into `entity`.
    ///
    /// Returns a [`BevyError`] if the material can not constructed from `args`.
    fn insert_from_args(
        &self,
        args: &[Cow<'static, str>],
        entity: &mut EntityCommands,
        server: &AssetServer,
    ) -> Result<()>;
}

/// A dynamic representation of a text material.
///
/// Used by [`bevy_pretty_text::parser`] to dynamically insert text materials.
#[derive(Debug, Default, Clone, Component, Reflect)]
pub struct ErasedPrettyTextMaterial {
    /// Tag associated to a [registered material](PrettyTextMaterialAppExt).
    pub tag: Cow<'static, str>,

    /// Field arguments for a dynamic material.
    pub args: Vec<Cow<'static, str>>,
}

/// Dynamic material registry.
///
/// See [`material`](crate::material).
#[derive(Default, Resource)]
pub struct DynMaterialRegistry(HashMap<&'static str, Box<dyn DynamicTextMaterial>>);

impl std::fmt::Debug for DynMaterialRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("DynMaterialRegistry")
            .field(&self.0.keys())
            .finish()
    }
}

impl DynMaterialRegistry {
    /// Register a `material` with `tag`.
    #[inline]
    pub fn register(&mut self, tag: &'static str, material: impl DynamicTextMaterial) {
        if self.0.get(tag).is_some() {
            error!("material `{tag}` is already registered");
        }

        self.0.insert(tag, Box::new(material));
    }

    /// Unregisters the material with `tag`.
    #[inline]
    pub fn unregister(&mut self, tag: &'static str) {
        self.0.remove(tag);
    }

    /// Retrieves the material registered with `tag`.
    #[inline]
    pub fn get(&self, tag: &str) -> Option<&dyn DynamicTextMaterial> {
        self.0.get(tag).map(|mat| mat.as_ref())
    }
}

/// Propagate the glyph atlas handle from span entities to glyph entities.
pub fn set_material_atlas<T: TextMaterial2d>(
    text: Query<
        (&PrettyTextMaterial<T>, &SpanAtlasImage),
        Or<(
            Added<SpanAtlasImage>,
            Added<PrettyTextMaterial<T>>,
            Changed<SpanAtlasImage>,
            Changed<PrettyTextMaterial<T>>,
        )>,
    >,
    mut materials: ResMut<Assets<T>>,
) {
    for (material, atlas) in text.iter() {
        if let Some(material) = materials.get_mut(&material.0) {
            material.set_atlas(atlas.0.clone());
        }
    }
}

mod sealed {
    use bevy::prelude::*;
    use bevy::render::render_resource::{AsBindGroup, ShaderRef};
    use bevy::sprite::{AlphaMode2d, Material2d};

    use crate::PrettyText;
    use crate::glyph::{GlyphOf, GlyphSpanEntity, GlyphSystems};

    use super::{
        DEFAULT_GLYPH_SHADER_HANDLE, DynMaterialRegistry, DynamicTextMaterial,
        ErasedPrettyTextMaterial, PrettyTextMaterial, PrettyTextMaterialPlugin, TextMaterial2d,
    };

    pub(super) fn plugin(app: &mut App) {
        app.add_plugins(PrettyTextMaterialPlugin::<DefaultGlyphMaterial>::default())
            .add_systems(
                PostUpdate,
                default_material.in_set(GlyphSystems::PropagateMaterial),
            )
            .add_observer(insert_erased_materials)
            .register_type::<Material>()
            .register_type::<DefaultGlyphMaterial>();
    }

    #[derive(Debug, Clone, Component, Reflect)]
    pub(super) struct Material(&'static str);

    impl Material {
        pub fn new<T: 'static>() -> Self {
            Self(std::any::type_name::<T>())
        }
    }

    pub(super) fn default_material(
        mut commands: Commands,
        unmaterialized_text: Query<
            (Entity, Option<&Text2d>, Option<&TextSpan>),
            (
                With<PrettyText>,
                Without<Material>,
                Or<(Added<Text2d>, Added<TextSpan>, Added<PrettyText>)>,
            ),
        >,
        mut materials: ResMut<Assets<DefaultGlyphMaterial>>,
    ) {
        for (entity, text2d, span) in unmaterialized_text.iter() {
            if text2d.is_some_and(|text| !text.0.is_empty())
                || span.is_some_and(|text| !text.0.is_empty())
            {
                commands.entity(entity).insert(PrettyTextMaterial(
                    materials.add(DefaultGlyphMaterial::default()),
                ));
            }
        }
    }

    pub(super) fn apply_material<T: TextMaterial2d>(
        mut commands: Commands,
        glyphs: Query<
            (Entity, &GlyphSpanEntity),
            (
                With<GlyphOf>,
                Without<Material>,
                Without<PrettyTextMaterial<T>>,
            ),
        >,
        spans: Query<&PrettyTextMaterial<T>>,
    ) {
        for (entity, span_entity) in glyphs.iter() {
            if let Ok(material) = spans.get(span_entity.0) {
                commands
                    .entity(entity)
                    .insert(MeshMaterial2d(material.0.clone()));
            }
        }
    }

    pub(super) fn register_dyn_material<T: Default + DynamicTextMaterial>(
        tag: &'static str,
    ) -> impl Fn(ResMut<DynMaterialRegistry>) {
        move |mut registry| {
            registry.register(tag, T::default());
        }
    }

    fn insert_erased_materials(
        trigger: Trigger<OnAdd, ErasedPrettyTextMaterial>,
        mut commands: Commands,
        server: Res<AssetServer>,
        materials: Query<&ErasedPrettyTextMaterial>,
        registry: Res<DynMaterialRegistry>,
    ) -> Result {
        let material = materials.get(trigger.target())?;
        let handler = registry.0.get(material.tag.as_ref()).ok_or_else(|| {
            format!(
                "failed to insert text material: `{}` is not registered",
                material.tag
            )
        })?;

        let mut commands = commands.entity(trigger.target());
        handler.insert_from_args(material.args.as_ref(), &mut commands, &server)?;
        commands.remove::<ErasedPrettyTextMaterial>();

        Ok(())
    }

    #[derive(Default, Clone, Asset, AsBindGroup, Reflect)]
    pub(super) struct DefaultGlyphMaterial {
        #[texture(0)]
        #[sampler(1)]
        pub atlas: Handle<Image>,
    }

    impl Material2d for DefaultGlyphMaterial {
        fn vertex_shader() -> ShaderRef {
            ShaderRef::Handle(DEFAULT_GLYPH_SHADER_HANDLE)
        }

        fn fragment_shader() -> ShaderRef {
            ShaderRef::Handle(DEFAULT_GLYPH_SHADER_HANDLE)
        }

        fn alpha_mode(&self) -> AlphaMode2d {
            AlphaMode2d::Blend
        }
    }

    impl TextMaterial2d for DefaultGlyphMaterial {
        fn set_atlas(&mut self, atlas: Handle<Image>) {
            self.atlas = atlas;
        }
    }

    #[cfg(feature = "proc-macro")]
    impl quote::ToTokens for ErasedPrettyTextMaterial {
        fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
            use quote::TokenStreamExt;
            let tag = &self.tag;
            let args = &self.args;
            tokens.append_all(quote::quote! {
                bevy_pretty_text::material::erased::ErasedPrettyTextMaterial::Tag {
                    tag: #tag.into(),
                    args: vec![#(#args.into(),)*]
                }
            });
        }
    }
}

#[cfg(test)]
mod test {
    use bevy::prelude::*;
    use bevy::render::render_resource::AsBindGroup;
    use bevy::sprite::Material2d;

    use crate::dynamic_effects::PrettyTextEffect;
    use crate::material::{PrettyTextMaterial, PrettyTextMaterialAppExt};
    use crate::parser::{Modifier, Modifiers};
    use crate::test::{prepare_app_with, run, run_tests};

    use super::{DynamicTextMaterial, TextMaterial2d};

    #[derive(Default, Clone, TypePath, AsBindGroup, Asset)]
    struct Material {
        atlas: Handle<Image>,
    }

    impl Material2d for Material {}

    impl TextMaterial2d for Material {
        fn set_atlas(&mut self, atlas: Handle<Image>) {
            self.atlas = atlas;
        }
    }

    impl DynamicTextMaterial for Material {
        fn insert_from_args(
            &self,
            args: &[std::borrow::Cow<'static, str>],
            entity: &mut EntityCommands,
            server: &AssetServer,
        ) -> Result<()> {
            assert_eq!(args.len(), 2);
            entity.insert(PrettyTextMaterial(server.add(Material::default())));
            Ok(())
        }
    }

    #[test]
    fn insert_material() {
        run_tests(
            || {
                let mut app = prepare_app_with(|app| {
                    app.register_pretty_material::<Material>("material");
                });
                app.world_mut().run_schedule(PreStartup);
                app.world_mut().flush();
                app
            },
            |app, entity, str| {
                app.world_mut()
                    .entity_mut(entity)
                    .insert(Modifiers(vec![Modifier::Effect(PrettyTextEffect {
                        tag: "material".into(),
                        args: vec!["1".into(), "2".into()],
                    })]));

                let has_spans = app
                    .world()
                    .entity(entity)
                    .get_components::<&Children>()
                    .is_some();

                app.world_mut().run_schedule(PostUpdate);
                app.world_mut().flush();
                run(
                    app,
                    move |effect: Query<&PrettyTextMaterial<Material>>,
                          glyphs: Query<&MeshMaterial2d<Material>>| {
                        assert!(
                            effect.single().is_ok(),
                            "expected 1, got {}",
                            effect.iter().len()
                        );

                        if !has_spans {
                            assert_eq!(
                                glyphs.iter().count(),
                                str.chars().count(),
                                "expected {}, got {}",
                                str.chars().count(),
                                glyphs.iter().len()
                            );
                        } else {
                            // spans should not inherit root effects
                            assert_eq!(
                                glyphs.iter().count(),
                                0,
                                "expected 0, got {}",
                                glyphs.iter().len(),
                            );
                        }
                    },
                );

                app.world_mut().entity_mut(entity).despawn();
                run(
                    app,
                    |effect: Query<&PrettyTextMaterial<Material>>,
                     glyphs: Query<&MeshMaterial2d<Material>>| {
                        assert!(effect.is_empty(), "expected 0, got {}", effect.iter().len());
                        assert!(glyphs.is_empty(), "expected 0, got {}", glyphs.iter().len());
                    },
                );
            },
        );
    }
}