bevy_fontmesh 0.6.0

Simple and focused Bevy plugin for generating 3D text meshes from fonts
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
use crate::component::{
    GlyphMesh, JustifyText, ScreenSize, ScreenSizeCamera, TextAnchor, TextMesh, TextMeshGlyphs,
};
use bevy::asset::RenderAssetUsages;
use bevy::ecs::message::MessageReader;
use bevy::ecs::query::{QueryData, QueryFilter};
use bevy::ecs::system::SystemParam;
use bevy::mesh::Indices;
use bevy::platform::collections::HashMap;
use bevy::prelude::*;
use bevy::render::render_resource::PrimitiveTopology;
use bevy::text::Font;
use fontmesh::{glyph_to_mesh_3d, parse_font, FontRef, GlyphId};
use parley::{Alignment, AlignmentOptions, FontContext, FontFamily, LayoutContext, StyleProperty};

// Parley shapes in pixel space. We pick a fixed pixel size and divide
// back out so positions land in the same em-normalized space (1 em = 1.0)
// that fontmesh emits outlines in.
const SHAPING_FONT_SIZE: f32 = 64.0;
const LINE_HEIGHT_FACTOR: f32 = 1.2;

// ── parley shaping context ────────────────────────────────────────────────────

/// Owns the parley contexts used to lay text out before tessellation.
///
/// Bevy 0.19 dropped cosmic-text in favour of parley, so there is no shared
/// `CosmicFontSystem` resource to borrow any more. We keep our own
/// [`FontContext`] (font database + cache) and [`LayoutContext`] (layout
/// scratch space) so shaping is fully self-contained and doesn't depend on
/// Bevy's text-collection lifecycle (which clears/rebuilds on font removal).
#[derive(Resource, Default)]
pub struct FontMeshShaper {
    font_cx: FontContext,
    layout_cx: LayoutContext<()>,
    /// Maps each registered `Handle<Font>` to the parley family name we resolved
    /// for it, so we can target that exact face when shaping. Without this we'd
    /// re-register the same bytes every frame, ballooning the collection.
    registered: HashMap<AssetId<Font>, RegisteredFont>,
}

struct RegisteredFont {
    family: String,
}

impl FontMeshShaper {
    /// Register the font behind `handle` into our parley collection (once),
    /// returning the resolved family name to target during shaping.
    fn ensure_registered(
        &mut self,
        handle: &Handle<Font>,
        fonts: &Assets<Font>,
    ) -> Option<&RegisteredFont> {
        let id = handle.id();
        if !self.registered.contains_key(&id) {
            let font_asset = fonts.get(id)?;
            // `Font::data` is already a `fontique::Blob<u8>` in Bevy 0.19.
            let registered = self
                .font_cx
                .collection
                .register_fonts(font_asset.data.clone(), None);
            let (family_id, _) = registered.first()?;
            let family = self.font_cx.collection.family_name(*family_id)?.to_string();
            self.registered.insert(id, RegisteredFont { family });
        }
        self.registered.get(&id)
    }

    fn invalidate(&mut self, id: AssetId<Font>) {
        self.registered.remove(&id);
    }
}

pub fn on_font_asset_event(
    mut events: MessageReader<AssetEvent<Font>>,
    mut shaper: ResMut<FontMeshShaper>,
    mut cache: ResMut<GlyphMeshCache>,
) {
    for ev in events.read() {
        match ev {
            &AssetEvent::Modified { id }
            | &AssetEvent::Removed { id }
            | &AssetEvent::Unused { id } => {
                shaper.invalidate(id);
                cache.invalidate_font(id);
            }
            AssetEvent::Added { .. } | AssetEvent::LoadedWithDependencies { .. } => {}
        }
    }
}

// ── Glyph mesh cache ──────────────────────────────────────────────────────────

/// Caches generated per-glyph meshes keyed by `(font, glyph id, depth, subdivision)`.
///
/// Cosmic-text returns the same glyph id many times across a paragraph (every
/// 'e' in "the", etc.), and the layout system also runs every time the text
/// changes; without a cache we'd retessellate identical glyphs over and over.
#[derive(Resource, Default)]
pub struct GlyphMeshCache {
    entries: HashMap<GlyphMeshKey, CachedGlyph>,
}

#[derive(Clone)]
struct CachedGlyph {
    handle: Handle<Mesh>,
    /// Axis-aligned bounds of the cached mesh in the glyph's local frame
    /// (before per-glyph layout offset). Pre-computed so per-glyph layout
    /// can derive paragraph bounds without going through `Assets<Mesh>`.
    min: Vec3,
    max: Vec3,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct GlyphMeshKey {
    font: AssetId<Font>,
    glyph_id: u16,
    /// Depth quantized to 4 decimal places to keep the key hashable while
    /// still letting users tweak depth freely.
    depth_q: i32,
    subdivision: u8,
}

impl GlyphMeshCache {
    fn key(font: AssetId<Font>, glyph_id: u16, depth: f32, subdivision: u8) -> GlyphMeshKey {
        GlyphMeshKey {
            font,
            glyph_id,
            depth_q: (depth * 10_000.0).round() as i32,
            subdivision,
        }
    }

    fn invalidate_font(&mut self, font: AssetId<Font>) {
        self.entries.retain(|k, _| k.font != font);
    }
}

fn get_or_build_glyph_mesh(
    cache: &mut GlyphMeshCache,
    meshes: &mut Assets<Mesh>,
    font_ref: &FontRef,
    font_id: AssetId<Font>,
    glyph_id: u16,
    depth: f32,
    subdivision: u8,
) -> Option<CachedGlyph> {
    let key = GlyphMeshCache::key(font_id, glyph_id, depth, subdivision);
    if let Some(cached) = cache.entries.get(&key) {
        return Some(cached.clone());
    }
    let mesh_data =
        glyph_to_mesh_3d(font_ref, GlyphId::new(glyph_id as u32), depth, subdivision).ok()?;
    let mut min = Vec3::splat(f32::MAX);
    let mut max = Vec3::splat(f32::MIN);
    for v in &mesh_data.vertices {
        let p = Vec3::new(v.x, v.y, v.z);
        min = min.min(p);
        max = max.max(p);
    }
    let handle = meshes.add(fontmesh_to_bevy(&mesh_data));
    let cached = CachedGlyph { handle, min, max };
    cache.entries.insert(key, cached.clone());
    Some(cached)
}

// ── Mesh helpers ──────────────────────────────────────────────────────────────

fn fontmesh_to_bevy(mesh_data: &fontmesh::Mesh3D) -> Mesh {
    let vertices: Vec<[f32; 3]> = mesh_data.vertices.iter().map(|v| [v.x, v.y, v.z]).collect();
    let normals: Vec<[f32; 3]> = mesh_data.normals.iter().map(|n| [n.x, n.y, n.z]).collect();
    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices);
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
    mesh.insert_indices(Indices::U32(mesh_data.indices.clone()));
    mesh
}

// ── Layout: cosmic-text → fontmesh ────────────────────────────────────────────

#[derive(Clone, Copy)]
struct ShapedGlyph {
    glyph_id: u16,
    char_index: usize,
    line_index: usize,
    /// First scalar from the source cluster, used for the per-glyph
    /// `GlyphMesh.character` field. For multi-char clusters (ligatures,
    /// combining marks) this is the leading character.
    character: char,
    /// Em-normalized position (cosmic coordinates / SHAPING_FONT_SIZE).
    position: Vec2,
}

/// Shape `text` with parley against the registered `family`, returning
/// em-normalized glyph positions and the y range we'll need for anchor offset
/// later.
///
/// Parley lays out in pixel space (y grows downward); we divide every
/// coordinate by [`SHAPING_FONT_SIZE`] so positions land in the same
/// em-normalized space (1 em = 1.0) that fontmesh emits outlines in, and flip y
/// so line 0 sits on top.
fn shape_text(
    text: &str,
    family: &str,
    justify: JustifyText,
    shaper: &mut FontMeshShaper,
) -> (Vec<ShapedGlyph>, f32, f32) {
    let FontMeshShaper {
        font_cx, layout_cx, ..
    } = shaper;

    let mut builder = layout_cx.ranged_builder(font_cx, text, 1.0, true);
    builder.push_default(StyleProperty::FontFamily(FontFamily::named(family)));
    builder.push_default(StyleProperty::FontSize(SHAPING_FONT_SIZE));
    builder.push_default(StyleProperty::LineHeight(
        parley::LineHeight::FontSizeRelative(LINE_HEIGHT_FACTOR),
    ));

    let mut layout = builder.build(text);
    // No wrapping: a single line per `\n`-delimited paragraph.
    layout.break_all_lines(None);
    let alignment = match justify {
        JustifyText::Left => Alignment::Left,
        JustifyText::Center => Alignment::Center,
        JustifyText::Right => Alignment::Right,
    };
    layout.align(alignment, AlignmentOptions::default());

    let scale = 1.0 / SHAPING_FONT_SIZE;

    let mut shaped = Vec::new();
    let mut max_y_top = f32::NEG_INFINITY;
    let mut min_y_bottom = f32::INFINITY;

    for (line_index, line) in layout.lines().enumerate() {
        let lm = line.metrics();
        // Parley y grows downward; flip so line 0 is on top.
        let line_top_em = -(lm.baseline - lm.ascent) * scale;
        let line_bottom_em = -(lm.baseline + lm.descent) * scale;
        max_y_top = max_y_top.max(line_top_em);
        min_y_bottom = min_y_bottom.min(line_bottom_em);

        for item in line.items() {
            let parley::PositionedLayoutItem::GlyphRun(glyph_run) = item else {
                continue;
            };
            let mut x = glyph_run.offset();
            let baseline = glyph_run.baseline();
            for cluster in glyph_run.run().visual_clusters() {
                let cluster_x = x;
                x += cluster.advance();
                // For ligature clusters this only exposes the leading codepoint.
                let character = cluster.source_char();
                let char_index = cluster.text_range().start;
                let mut gx = cluster_x;
                for glyph in cluster.glyphs() {
                    let glyph_x_em = (gx + glyph.x) * scale;
                    let glyph_y_em = -(baseline + glyph.y) * scale;
                    shaped.push(ShapedGlyph {
                        glyph_id: glyph.id as u16,
                        char_index,
                        line_index,
                        character,
                        position: Vec2::new(glyph_x_em, glyph_y_em),
                    });
                    gx += glyph.advance;
                }
            }
        }
    }

    (shaped, min_y_bottom, max_y_top)
}

fn calculate_anchor_offset(anchor: TextAnchor, min_bound: Vec3, max_bound: Vec3) -> Vec3 {
    let size = max_bound - min_bound;
    let center = min_bound + size * 0.5;
    match anchor {
        TextAnchor::TopLeft => Vec3::new(-min_bound.x, -max_bound.y, 0.0),
        TextAnchor::TopCenter => Vec3::new(-center.x, -max_bound.y, 0.0),
        TextAnchor::TopRight => Vec3::new(-max_bound.x, -max_bound.y, 0.0),
        TextAnchor::CenterLeft => Vec3::new(-min_bound.x, -center.y, 0.0),
        TextAnchor::Center => Vec3::new(-center.x, -center.y, 0.0),
        TextAnchor::CenterRight => Vec3::new(-max_bound.x, -center.y, 0.0),
        TextAnchor::BottomLeft => Vec3::new(-min_bound.x, -min_bound.y, 0.0),
        TextAnchor::BottomCenter => Vec3::new(-center.x, -min_bound.y, 0.0),
        TextAnchor::BottomRight => Vec3::new(-max_bound.x, -min_bound.y, 0.0),
        TextAnchor::Custom(pivot) => {
            let pivot_pos = min_bound.truncate() + size.truncate() * pivot;
            Vec3::new(-pivot_pos.x, -pivot_pos.y, 0.0)
        }
    }
}

// ── Combined-mesh builder (single Mesh3d output) ─────────────────────────────

fn combine_shaped_meshes(glyphs: &[(ShapedGlyph, fontmesh::Mesh3D)], anchor_offset: Vec3) -> Mesh {
    let mut all_vertices: Vec<[f32; 3]> = Vec::new();
    let mut all_normals: Vec<[f32; 3]> = Vec::new();
    let mut all_indices: Vec<u32> = Vec::new();
    let mut index_offset = 0u32;

    for (glyph, mesh_data) in glyphs {
        let ox = glyph.position.x + anchor_offset.x;
        let oy = glyph.position.y + anchor_offset.y;
        let oz = anchor_offset.z;
        all_vertices.extend(
            mesh_data
                .vertices
                .iter()
                .map(|v| [v.x + ox, v.y + oy, v.z + oz]),
        );
        all_normals.extend(mesh_data.normals.iter().map(|n| [n.x, n.y, n.z]));
        all_indices.extend(mesh_data.indices.iter().map(|i| i + index_offset));
        index_offset += mesh_data.vertices.len() as u32;
    }

    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, all_vertices);
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, all_normals);
    mesh.insert_indices(Indices::U32(all_indices));
    mesh
}

// ── Marker components ─────────────────────────────────────────────────────────

#[derive(Component)]
pub struct TextMeshComputed;

#[derive(Component)]
pub struct TextMeshGlyphsComputed;

// ── Systems ───────────────────────────────────────────────────────────────────

/// Shared resources used by both mesh-generation systems. Bundled into a single
/// [`SystemParam`] so the per-system signatures stay under clippy's
/// `too_many_arguments` threshold without scattering related state across many
/// arguments.
#[derive(SystemParam)]
pub struct FontMeshResources<'w> {
    meshes: ResMut<'w, Assets<Mesh>>,
    fonts: Res<'w, Assets<Font>>,
    shaper: ResMut<'w, FontMeshShaper>,
}

#[derive(QueryData)]
#[query_data(mutable)]
pub struct TextMeshData {
    entity: Entity,
    text_mesh: &'static TextMesh,
    mesh: &'static mut Mesh3d,
}

#[derive(QueryFilter)]
pub struct TextMeshFilter {
    _changed: Or<(Changed<TextMesh>, Without<TextMeshComputed>)>,
}

pub fn update_text_meshes(
    mut commands: Commands,
    mut res: FontMeshResources,
    mut query: Query<TextMeshData, TextMeshFilter>,
) {
    for TextMeshDataItem {
        entity,
        text_mesh,
        mesh: mut mesh_handle,
    } in query.iter_mut()
    {
        let family = match res.shaper.ensure_registered(&text_mesh.font, &res.fonts) {
            Some(r) => r.family.clone(),
            None => continue,
        };
        let Some(font_asset) = res.fonts.get(&text_mesh.font) else {
            continue;
        };
        let Ok(font_ref) = parse_font(font_asset.data.data()) else {
            continue;
        };

        let (shaped, _y_min, _y_max) = shape_text(
            &text_mesh.text,
            &family,
            text_mesh.style.justify,
            &mut res.shaper,
        );

        // Combined-mesh path: every TextMesh produces a single Mesh3d, so
        // we skip the per-glyph cache and tessellate inline.
        let mut per_glyph: Vec<(ShapedGlyph, fontmesh::Mesh3D)> = Vec::with_capacity(shaped.len());
        let mut min_bound = Vec3::splat(f32::MAX);
        let mut max_bound = Vec3::splat(f32::MIN);
        for g in shaped {
            let Ok(mesh_data) = glyph_to_mesh_3d(
                &font_ref,
                GlyphId::new(g.glyph_id as u32),
                text_mesh.style.depth,
                text_mesh.style.subdivision,
            ) else {
                continue;
            };
            for v in &mesh_data.vertices {
                let pos = Vec3::new(v.x + g.position.x, v.y + g.position.y, v.z);
                min_bound = min_bound.min(pos);
                max_bound = max_bound.max(pos);
            }
            per_glyph.push((g, mesh_data));
        }

        let anchor_offset = if per_glyph.is_empty() {
            Vec3::ZERO
        } else {
            calculate_anchor_offset(text_mesh.style.anchor, min_bound, max_bound)
        };

        let combined = combine_shaped_meshes(&per_glyph, anchor_offset);
        mesh_handle.0 = res.meshes.add(combined);
        commands.entity(entity).insert(TextMeshComputed);
    }
}

#[derive(QueryData)]
pub struct TextMeshGlyphsData<M: Material> {
    entity: Entity,
    text_glyphs: &'static TextMeshGlyphs,
    default_material: &'static MeshMaterial3d<M>,
}

#[derive(QueryFilter)]
pub struct TextMeshGlyphsFilter {
    _changed: Or<(Changed<TextMeshGlyphs>, Without<TextMeshGlyphsComputed>)>,
}

/// System to generate per-character mesh entities for [`TextMeshGlyphs`].
pub fn update_glyph_meshes<M: Material>(
    mut commands: Commands,
    mut res: FontMeshResources,
    mut cache: ResMut<GlyphMeshCache>,
    query: Query<TextMeshGlyphsData<M>, TextMeshGlyphsFilter>,
    children_query: Query<&Children>,
    glyph_query: Query<Entity, With<GlyphMesh>>,
) {
    for TextMeshGlyphsDataItem {
        entity,
        text_glyphs,
        default_material,
    } in query.iter()
    {
        let family = match res.shaper.ensure_registered(&text_glyphs.font, &res.fonts) {
            Some(r) => r.family.clone(),
            None => continue,
        };
        let Some(font_asset) = res.fonts.get(&text_glyphs.font) else {
            continue;
        };
        let Ok(font_ref) = parse_font(font_asset.data.data()) else {
            continue;
        };

        despawn_existing_glyphs(&mut commands, entity, &children_query, &glyph_query);

        let (shaped, _, _) = shape_text(
            &text_glyphs.text,
            &family,
            text_glyphs.style.justify,
            &mut res.shaper,
        );

        let font_id = text_glyphs.font.id();

        // Bounds first so the anchor offset matches the combined-mesh path.
        // Forces a cache populate now since we need per-glyph extents.
        let mut min_bound = Vec3::splat(f32::MAX);
        let mut max_bound = Vec3::splat(f32::MIN);
        let mut to_spawn: Vec<(ShapedGlyph, Handle<Mesh>)> = Vec::with_capacity(shaped.len());

        for g in shaped {
            let Some(cached) = get_or_build_glyph_mesh(
                &mut cache,
                &mut res.meshes,
                &font_ref,
                font_id,
                g.glyph_id,
                text_glyphs.style.depth,
                text_glyphs.style.subdivision,
            ) else {
                continue;
            };
            let offset = Vec3::new(g.position.x, g.position.y, 0.0);
            min_bound = min_bound.min(cached.min + offset);
            max_bound = max_bound.max(cached.max + offset);
            to_spawn.push((g, cached.handle));
        }

        let anchor_offset = if to_spawn.is_empty() {
            Vec3::ZERO
        } else {
            calculate_anchor_offset(text_glyphs.style.anchor, min_bound, max_bound)
        };

        commands.entity(entity).with_children(|parent| {
            for (g, mesh_handle) in to_spawn {
                parent.spawn((
                    GlyphMesh {
                        char_index: g.char_index,
                        line_index: g.line_index,
                        character: g.character,
                    },
                    Mesh3d(mesh_handle),
                    default_material.clone(),
                    Transform::from_xyz(
                        g.position.x + anchor_offset.x,
                        g.position.y + anchor_offset.y,
                        anchor_offset.z,
                    ),
                ));
            }
        });

        commands.entity(entity).insert(TextMeshGlyphsComputed);
    }
}

fn despawn_existing_glyphs(
    commands: &mut Commands,
    entity: Entity,
    children_query: &Query<&Children>,
    glyph_query: &Query<Entity, With<GlyphMesh>>,
) {
    if let Ok(children) = children_query.get(entity) {
        for child in children.iter() {
            if glyph_query.contains(child) {
                commands.entity(child).despawn();
            }
        }
    }
}

// ── ScreenSize: keep text at a target on-screen pixel height ─────────────────

pub fn scale_screen_size(
    cam_marked: Query<(&Camera, &GlobalTransform, &Projection), With<ScreenSizeCamera>>,
    cam_any: Query<(&Camera, &GlobalTransform, &Projection), Without<ScreenSizeCamera>>,
    mut targets: Query<(&ScreenSize, &GlobalTransform, &mut Transform)>,
) {
    let (camera, cam_xform, projection) = match cam_marked.single() {
        Ok(c) => c,
        Err(_) => match cam_any.iter().next() {
            Some(c) => c,
            None => return,
        },
    };
    let Some(target_size) = camera.logical_target_size() else {
        return;
    };
    let target_h = target_size.y.max(1.0);

    for (size, gxform, mut transform) in targets.iter_mut() {
        let world_per_px = match projection {
            Projection::Orthographic(ortho) => orthographic_world_per_px(ortho, target_h),
            Projection::Perspective(persp) => {
                perspective_world_per_px(persp, cam_xform, gxform, target_h)
            }
            _ => continue,
        };
        let s = size.pixel_height * world_per_px;
        if s.is_finite() && s > 0.0 {
            transform.scale = Vec3::splat(s);
        }
    }
}

#[inline]
fn orthographic_world_per_px(ortho: &OrthographicProjection, target_h: f32) -> f32 {
    let viewport_h = match ortho.scaling_mode {
        bevy::camera::ScalingMode::FixedVertical { viewport_height } => viewport_height,
        bevy::camera::ScalingMode::FixedHorizontal { viewport_width } => {
            let aspect = ortho.area.width() / ortho.area.height().max(f32::EPSILON);
            viewport_width / aspect.max(f32::EPSILON)
        }
        bevy::camera::ScalingMode::WindowSize => ortho.area.height(),
        _ => ortho.area.height(),
    };
    viewport_h / target_h
}

#[inline]
fn perspective_world_per_px(
    persp: &PerspectiveProjection,
    cam_xform: &GlobalTransform,
    target_xform: &GlobalTransform,
    target_h: f32,
) -> f32 {
    let depth = (target_xform.translation() - cam_xform.translation()).length();
    let visible_h = 2.0 * depth * (persp.fov * 0.5).tan();
    visible_h / target_h
}