rustial-renderer-bevy 1.0.0

Bevy Engine renderer for the rustial 2.5D map engine
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
// ---------------------------------------------------------------------------
//! # Tile texture upload system
//!
//! Transfers decoded tile imagery from the engine's per-frame
//! [`VisibleTile`](rustial_engine::VisibleTile) cache into Bevy
//! [`Image`] assets and assigns them to tile entity materials.
//!
//! ## Data flow
//!
//! ```text
//! tile_fetch (PreUpdate)
//!     |  fetches + decodes PNG/JPEG -> DecodedImage (RGBA8)
//!     |  pushes VisibleTile list into MapState
//!     v
//! sync_tiles (Update)
//!     |  spawns TileEntity + Mesh3d + MeshMaterial3d(StandardMaterial)
//!     |  material starts with a flat base_color, no texture
//!     v
//! upload_textures (PostUpdate)          <-- this system
//!     |  reads MapState::visible_tiles()
//!     |  for each TileEntity whose material lacks a texture:
//!     |    look up the matching VisibleTile by tile ID
//!     |    create a Bevy Image from DecodedImage
//!     |    assign it as base_color_texture on the StandardMaterial
//!     v
//! Bevy render graph picks up the new Image handle
//! ```
//!
//! ## Why PostUpdate?
//!
//! Tile entities are spawned in `Update` by [`sync_tiles`].  Bevy
//! deferred commands are flushed between schedule stages, so by
//! `PostUpdate` the new entities and their `MeshMaterial3d` handles
//! are queryable.  Running here guarantees that a texture is applied
//! on the **same frame** the entity appears, avoiding a single-frame
//! grey flash.
//!
//! ## Texture format
//!
//! The engine decodes all tile imagery to **RGBA8** (`Vec<u8>`,
//! row-major, 4 bytes per pixel).  This system creates a Bevy
//! [`Image`] with [`TextureFormat::Rgba8UnormSrgb`] -- the sRGB
//! variant -- which matches the colour space of typical web map tile
//! providers (OSM, Mapbox, etc.).
//!
//! ## Idempotency
//!
//! Once a material has a `base_color_texture`, the system skips it on
//! subsequent frames.  This makes the system safe to run every frame
//! with negligible cost for already-textured tiles.
//!
//! ## Terrain textures
//!
//! Terrain mesh entities use a per-pixel fog material.  When the
//! exact tile texture is not yet available, a parent fallback texture
//! is cropped to the child tile's sub-region so terrain meshes always
//! show geographically correct imagery.
//!
//! [`sync_tiles`]: super::tile_sync::sync_tiles
// ---------------------------------------------------------------------------

use crate::components::{HillshadeEntity, TerrainEntity, TileEntity};
use crate::hillshade_material::HillshadeMaterial;
use crate::painter::{PainterPass, PainterPlanResource};
use crate::plugin::MapStateResource;
use crate::tile_fog_material::TileFogMaterial;
use bevy::asset::RenderAssetUsages;
use bevy::prelude::*;
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
use rustial_engine::{DecodedImage, TileData, TileId, TilePixelRect};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

// ---------------------------------------------------------------------------
// Uploaded texture cache
// ---------------------------------------------------------------------------

/// Cache key for Bevy `Image` assets derived from decoded tile imagery.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum UploadedTextureKey {
    /// Exact tile texture, reusable by both flat tile quads and terrain.
    Exact(TileId),
    /// Cropped parent fallback texture for a terrain child tile.
    Fallback { target: TileId, actual: TileId },
}

/// Strong-handle cache for uploaded tile textures.
///
/// This avoids recreating GPU textures every time tile/terrain entities
/// are rebuilt while the underlying decoded imagery is unchanged.
#[derive(Resource, Default)]
pub struct UploadedTileTextures {
    handles: HashMap<UploadedTextureKey, Handle<Image>>,
}

/// Strong-handle cache for uploaded prepared hillshade textures.
#[derive(Resource, Default)]
pub struct UploadedHillshadeTextures {
    handles: HashMap<TileId, Handle<Image>>,
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Number of colour channels in an RGBA8 pixel.
const RGBA_CHANNELS: u32 = 4;

/// Maximum number of exact tile textures to retain in the Bevy-side GPU
/// cache across frames.  Keeping textures alive avoids re-creating mip
/// chains when the camera revisits a previously seen area (e.g. during
/// cyclic `fly_to` animations).
///
/// At 256x256 RGBA8 with a full mip chain (~350 KB per tile), 512
/// textures use approximately 175 MB of GPU memory.
const MAX_RETAINED_EXACT_TEXTURES: usize = 512;

/// Maximum number of **new** exact mip-chain texture uploads per frame.
///
/// Building a mip chain from a 256x256 RGBA8 tile costs ~1-2 ms of
/// CPU time (sRGB downsample).  During fly-to animations, 40-60 new
/// tiles may become visible in a single frame.  Uploading all of them
/// synchronously produces 80-120 ms `post_update` spikes.
///
/// Limiting to a budget spreads the work across multiple frames:
/// - 16 tiles × ~2 ms = ~32 ms worst-case per frame (fits in 60-fps budget)
/// - Remaining tiles are served from fallback (parent crop) textures
///   until they are uploaded in a subsequent frame.
const MAX_MIP_UPLOADS_PER_FRAME: usize = 16;

// ---------------------------------------------------------------------------
// System
// ---------------------------------------------------------------------------

/// Upload decoded tile imagery to Bevy materials.
///
/// See the [module-level documentation](self) for the full data flow,
/// scheduling rationale, and idempotency guarantees.
pub fn upload_textures(
    state: Res<MapStateResource>,
    mut images: ResMut<Assets<Image>>,
    mut materials: ResMut<Assets<TileFogMaterial>>,
    mut texture_cache: ResMut<UploadedTileTextures>,
    mut queries: ParamSet<(
        Query<(
            &mut TileEntity,
            &MeshMaterial3d<TileFogMaterial>,
            &mut Visibility,
        )>,
        Query<(
            &mut TerrainEntity,
            &MeshMaterial3d<TileFogMaterial>,
            &mut Visibility,
        )>,
    )>,
) {
    let visible = state.0.visible_tiles();

    if visible.is_empty() {
        texture_cache.handles.retain(|key, _| matches!(key, UploadedTextureKey::Exact(_)));
        return;
    }

    let mut loaded_by_actual: HashMap<TileId, &rustial_engine::DecodedImage> =
        HashMap::with_capacity(visible.len());
    let mut by_target: HashMap<TileId, (TileId, &rustial_engine::DecodedImage)> =
        HashMap::with_capacity(visible.len());
    let mut needed_keys: HashSet<UploadedTextureKey> = HashSet::with_capacity(visible.len() * 2);
    let mut fade_by_target: HashMap<TileId, f32> = HashMap::with_capacity(visible.len());

    for vt in visible.iter() {
        // Track the per-tile fade opacity.  When cross-fade emits both a
        // fading child and a complementary parent for the same target, use
        // the maximum opacity so the entity is visible as early as possible.
        fade_by_target
            .entry(vt.target)
            .and_modify(|o| *o = o.max(vt.fade_opacity))
            .or_insert(vt.fade_opacity);

        if let Some(TileData::Raster(ref img)) = vt.data {
            loaded_by_actual.entry(vt.actual).or_insert(img);
            by_target.entry(vt.target).or_insert((vt.actual, img));
            if vt.target == vt.actual {
                by_target.insert(vt.target, (vt.actual, img));
                needed_keys.insert(UploadedTextureKey::Exact(vt.target));
            } else {
                needed_keys.insert(UploadedTextureKey::Fallback {
                    target: vt.target,
                    actual: vt.actual,
                });
            }
        }
    }

    if by_target.is_empty() {
        texture_cache.handles.retain(|key, _| matches!(key, UploadedTextureKey::Exact(_)));
        return;
    }

    // Track how many new mip-chain textures we generate this frame.
    // Cached hits don't count against the budget.
    let mut mip_uploads_this_frame: usize = 0;

    // -----------------------------------------------------------------
    // Iterate tile entities and upload textures where needed.
    // -----------------------------------------------------------------
    for (mut tile, material_handle, mut visibility) in queries.p0().iter_mut() {
        let Some((actual_id, img)) = find_best_texture(tile.tile_id, &by_target, &loaded_by_actual) else {
            continue;
        };

        let Some(material) = materials.get(&material_handle.0) else {
            continue;
        };
        let already_textured = material.flags.has_texture > 0.5;
        let needs_crop = actual_id != tile.tile_id;
        let is_exact = !needs_crop;

        if tile.has_exact_texture && already_textured {
            continue;
        }
        if already_textured && !is_exact {
            continue;
        }

        let texture_key = if needs_crop {
            UploadedTextureKey::Fallback {
                target: tile.tile_id,
                actual: actual_id,
            }
        } else {
            UploadedTextureKey::Exact(tile.tile_id)
        };
        needed_keys.insert(texture_key);

        // Budget gate: if this exact texture requires a new mip chain
        // (not cached) and we've hit the per-frame budget, defer to next
        // frame.  The tile keeps its fallback texture in the meantime.
        if is_exact && !texture_cache.handles.contains_key(&texture_key) {
            if mip_uploads_this_frame >= MAX_MIP_UPLOADS_PER_FRAME {
                continue;
            }
            mip_uploads_this_frame += 1;
        }

        let image_handle = match get_or_create_uploaded_image(
            &mut images,
            &mut texture_cache,
            texture_key,
            img,
            tile.tile_id,
            actual_id,
        ) {
            Some(handle) => handle,
            None => continue,
        };

        // Assign the texture to the material and make it visible.
        if let Some(material) = materials.get_mut(&material_handle.0) {
            material.tile_texture = Some(image_handle);
            material.flags.has_texture = 1.0;
            material.flags.fade_opacity =
                fade_by_target.get(&tile.tile_id).copied().unwrap_or(1.0);
            *visibility = Visibility::Inherited;
            tile.has_exact_texture = is_exact;
        }
    }

    for (mut terrain, material_handle, mut visibility) in queries.p1().iter_mut() {
        let tile_id = terrain.tile_id;
        let Some((actual_id, img)) = find_best_texture(tile_id, &by_target, &loaded_by_actual) else {
            continue;
        };

        let Some(material) = materials.get(&material_handle.0) else {
            continue;
        };
        let already_textured = material.flags.has_texture > 0.5;
        let needs_crop = actual_id != tile_id;
        let is_exact = !needs_crop;

        if terrain.has_exact_texture {
            continue;
        }
        if already_textured && !is_exact {
            continue;
        }

        let texture_key = if needs_crop {
            UploadedTextureKey::Fallback {
                target: tile_id,
                actual: actual_id,
            }
        } else {
            UploadedTextureKey::Exact(tile_id)
        };
        needed_keys.insert(texture_key);

        // Budget gate for terrain tiles — same logic as flat tiles.
        if is_exact && !texture_cache.handles.contains_key(&texture_key) {
            if mip_uploads_this_frame >= MAX_MIP_UPLOADS_PER_FRAME {
                continue;
            }
            mip_uploads_this_frame += 1;
        }

        let image_handle = match get_or_create_uploaded_image(
            &mut images,
            &mut texture_cache,
            texture_key,
            img,
            tile_id,
            actual_id,
        ) {
            Some(handle) => handle,
            None => continue,
        };

        // Assign the texture to the material and make it visible.
        if let Some(material) = materials.get_mut(&material_handle.0) {
            material.tile_texture = Some(image_handle);
            material.flags.has_texture = 1.0;
            *visibility = Visibility::Inherited;
            terrain.has_exact_texture = is_exact;
        }
    }

    // Evict fallback (cropped) textures that are no longer needed this
    // frame -- they are cheap to recreate and specific to a target+actual
    // pair that may never recur.  Exact textures are retained across
    // frames up to a capacity limit so that revisiting a destination
    // during fly_to cycles hits the GPU cache instead of re-building
    // mip chains from decoded data.
    texture_cache.handles.retain(|key, _| {
        match key {
            UploadedTextureKey::Exact(_) => true,
            UploadedTextureKey::Fallback { .. } => needed_keys.contains(key),
        }
    });

    // If the exact-texture pool exceeds the cap, trim entries that
    // are not needed this frame (oldest insertions removed first via
    // HashMap iteration order, which is arbitrary but sufficient).
    if texture_cache.handles.len() > MAX_RETAINED_EXACT_TEXTURES {
        let excess = texture_cache.handles.len() - MAX_RETAINED_EXACT_TEXTURES;
        let mut removed = 0usize;
        texture_cache.handles.retain(|key, _| {
            if removed >= excess {
                return true;
            }
            if needed_keys.contains(key) {
                return true;
            }
            removed += 1;
            false
        });
    }
}

fn get_or_create_uploaded_image(
    images: &mut Assets<Image>,
    texture_cache: &mut UploadedTileTextures,
    texture_key: UploadedTextureKey,
    img: &DecodedImage,
    target_tile: TileId,
    actual_tile: TileId,
) -> Option<Handle<Image>> {
    if let Some(handle) = texture_cache.handles.get(&texture_key) {
        return Some(handle.clone());
    }

    let expected_len = (img.width as usize)
        .saturating_mul(img.height as usize)
        .saturating_mul(RGBA_CHANNELS as usize);

    if img.width == 0 || img.height == 0 || img.data.len() != expected_len {
        log::warn!(
            "texture_upload: skipping tile {:?} -- invalid image \
             ({}x{}, {} bytes, expected {})",
            target_tile,
            img.width,
            img.height,
            img.data.len(),
            expected_len,
        );
        return None;
    }

    let (final_data, final_width, final_height) = if actual_tile != target_tile {
        match crop_parent_texture(img, target_tile, actual_tile) {
            Some(cropped) => cropped,
            None => {
                log::trace!(
                    "texture_upload: skipping tile {:?} -- ancestor {:?} too distant to crop",
                    target_tile,
                    actual_tile,
                );
                return None;
            }
        }
    } else {
        (img.data.to_vec(), img.width, img.height)
    };

    // Exact tiles get a full mip chain for quality at oblique angles.
    // Fallback (cropped parent) tiles skip mip generation - they are
    // temporary stand-ins that will be replaced once the exact tile
    // loads, so a single-level texture is sufficient and much cheaper.
    let is_fallback = actual_tile != target_tile;
    let image = if is_fallback {
        build_single_level_bevy_image(final_width, final_height, final_data)
    } else {
        match build_mipped_bevy_image(final_width, final_height, final_data) {
            Ok(image) => image,
            Err(err) => {
                log::warn!(
                    "texture_upload: failed to build mip chain for tile {:?} from {:?}: {}",
                    target_tile,
                    actual_tile,
                    err,
                );
                return None;
            }
        }
    };

    let handle = images.add(image);
    texture_cache.handles.insert(texture_key, handle.clone());
    Some(handle)
}

fn build_mipped_bevy_image(width: u32, height: u32, data: Vec<u8>) -> Result<Image, rustial_engine::TileError> {
    let decoded = DecodedImage {
        width,
        height,
        data: Arc::new(data),
    };
    let mip_chain = decoded.build_mip_chain_rgba8()?;

    let mut image = Image::new_uninit(
        Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        TextureDimension::D2,
        TextureFormat::Rgba8UnormSrgb,
        RenderAssetUsages::default(),
    );
    image.texture_descriptor.mip_level_count = mip_chain.level_count();
    image.data = Some(mip_chain.into_bytes());
    image.sampler = bevy::image::ImageSampler::Descriptor(
        bevy::image::ImageSamplerDescriptor {
            address_mode_u: bevy::image::ImageAddressMode::ClampToEdge,
            address_mode_v: bevy::image::ImageAddressMode::ClampToEdge,
            mag_filter: bevy::image::ImageFilterMode::Linear,
            min_filter: bevy::image::ImageFilterMode::Linear,
            mipmap_filter: bevy::image::ImageFilterMode::Linear,
            anisotropy_clamp: 16,
            ..Default::default()
        },
    );
    Ok(image)
}

/// Build a single-level (no mip chain) Bevy Image from raw RGBA8 data.
///
/// Used for fallback (parent-cropped) textures that are temporary
/// stand-ins.  Skipping the mip chain avoids the per-pixel sRGB
/// downsample cost, making fallback texture creation near-instant.
fn build_single_level_bevy_image(width: u32, height: u32, data: Vec<u8>) -> Image {
    let mut image = Image::new_uninit(
        Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        TextureDimension::D2,
        TextureFormat::Rgba8UnormSrgb,
        RenderAssetUsages::default(),
    );
    image.data = Some(data);
    image.sampler = bevy::image::ImageSampler::Descriptor(
        bevy::image::ImageSamplerDescriptor {
            address_mode_u: bevy::image::ImageAddressMode::ClampToEdge,
            address_mode_v: bevy::image::ImageAddressMode::ClampToEdge,
            mag_filter: bevy::image::ImageFilterMode::Linear,
            min_filter: bevy::image::ImageFilterMode::Linear,
            ..Default::default()
        },
    );
    image
}

/// Upload prepared DEM-derived hillshade textures to hillshade overlay materials.
pub fn upload_hillshade_textures(
    state: Res<MapStateResource>,
    plan: Res<PainterPlanResource>,
    mut images: ResMut<Assets<Image>>,
    mut materials: ResMut<Assets<HillshadeMaterial>>,
    mut texture_cache: ResMut<UploadedHillshadeTextures>,
    mut query: Query<(
        &HillshadeEntity,
        &MeshMaterial3d<HillshadeMaterial>,
        &mut Visibility,
    )>,
) {
    let rasters = state.0.hillshade_rasters();
    if rasters.is_empty() || !plan.contains(PainterPass::HillshadeOverlay) {
        texture_cache.handles.clear();
        for (_, _, mut visibility) in &mut query {
            *visibility = Visibility::Hidden;
        }
        return;
    }

    let by_tile: HashMap<TileId, &rustial_engine::PreparedHillshadeRaster> = rasters
        .iter()
        .map(|r| (r.tile, r))
        .collect();

    for (hillshade, material_handle, mut visibility) in &mut query {
        let Some(raster) = by_tile.get(&hillshade.tile_id) else {
            continue;
        };

        let image_handle = if let Some(handle) = texture_cache.handles.get(&hillshade.tile_id) {
            handle.clone()
        } else {
            let image = match build_mipped_bevy_image(
                raster.image.width,
                raster.image.height,
                raster.image.data.to_vec(),
            ) {
                Ok(image) => image,
                Err(err) => {
                    log::warn!(
                        "upload_hillshade_textures: failed to build mip chain for tile {:?}: {}",
                        hillshade.tile_id,
                        err,
                    );
                    continue;
                }
            };
            let handle = images.add(image);
            texture_cache.handles.insert(hillshade.tile_id, handle.clone());
            handle
        };

        if let Some(material) = materials.get_mut(&material_handle.0) {
            material.hillshade_texture = image_handle;
            *visibility = Visibility::Inherited;
        }
    }

    texture_cache
        .handles
        .retain(|tile_id, _| by_tile.contains_key(tile_id));
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Maximum ancestor depth for renderer-side fallback texture search.
/// Must match the engine's `MAX_ANCESTOR_DEPTH` to avoid finding ancestors
/// too distant to crop into a meaningful sub-tile texture.
const MAX_FALLBACK_DEPTH: u8 = 8;

/// Find the best available texture for a tile, preferring exact matches
/// but falling back to nearest loaded ancestors as necessary.
fn find_best_texture<'a>(
    tile_id: TileId,
    by_target: &'a HashMap<TileId, (TileId, &'a rustial_engine::DecodedImage)>,
    loaded_by_actual: &'a HashMap<TileId, &'a rustial_engine::DecodedImage>,
) -> Option<(TileId, &'a rustial_engine::DecodedImage)> {
    if let Some(&(actual, img)) = by_target.get(&tile_id) {
        return Some((actual, img));
    }

    let mut current = tile_id;
    let mut depth = 0u8;
    while depth < MAX_FALLBACK_DEPTH {
        let Some(parent) = current.parent() else { break };
        if let Some(&img) = loaded_by_actual.get(&parent) {
            return Some((parent, img));
        }
        current = parent;
        depth += 1;
    }

    None
}

/// Crop a parent tile's RGBA8 texture to the sub-region that corresponds
/// to the child tile.
///
/// When a terrain entity at zoom `z` uses a parent fallback at zoom
/// `pz`, the parent texture covers a `2^(z-pz)` times larger area.
/// This function extracts the pixel rectangle within the parent texture
/// that maps to the child tile's geographic extent.
///
/// Returns `(pixel_data, width, height)` or `None` if the parameters
/// are invalid (e.g., child zoom <= parent zoom, image too small).
fn crop_parent_texture(
    parent_img: &rustial_engine::DecodedImage,
    child: TileId,
    parent: TileId,
) -> Option<(Vec<u8>, u32, u32)> {
    let crop = TilePixelRect::from_tiles(&child, &parent, parent_img.width, parent_img.height)?;
    if crop.width == parent_img.width && crop.height == parent_img.height && crop.x == 0 && crop.y == 0 {
        return Some((parent_img.data.to_vec(), parent_img.width, parent_img.height));
    }

    let channels = RGBA_CHANNELS as usize;
    let src_stride = parent_img.width as usize * channels;
    let dst_stride = crop.width as usize * channels;

    let mut out = vec![0u8; crop.height as usize * dst_stride];
    for row in 0..crop.height as usize {
        let src_row = (crop.y as usize + row) * src_stride + crop.x as usize * channels;
        let dst_row = row * dst_stride;
        out[dst_row..dst_row + dst_stride]
            .copy_from_slice(&parent_img.data[src_row..src_row + dst_stride]);
    }

    Some((out, crop.width, crop.height))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::{HillshadeEntity, TerrainEntity, TileEntity};
    use crate::hillshade_material::HillshadeMaterial;
    use crate::plugin::MapStateResource;
    use crate::tile_fog_material::TileFogMaterial;
    use glam::DVec3;
    use rustial_engine::{MapState, VisibleTile};

    fn test_app() -> App {
        let mut app = App::new();
        app.init_resource::<Assets<Image>>();
        app.init_resource::<Assets<TileFogMaterial>>();
        app.init_resource::<Assets<HillshadeMaterial>>();
        app.init_resource::<UploadedTileTextures>();
        app.init_resource::<UploadedHillshadeTextures>();
        app.init_resource::<crate::painter::PainterPlanResource>();
        app.insert_resource(MapStateResource(MapState::new()));
        app.add_systems(PreUpdate, crate::painter::update_painter_plan);
        app.add_systems(Update, upload_textures);
        app.add_systems(Update, upload_hillshade_textures);
        app
    }

    #[test]
    fn reuses_uploaded_exact_tile_texture_across_entity_rebuilds() {
        let mut app = test_app();
        let tile_id = TileId { zoom: 3, x: 4, y: 2 };

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_visible_tiles(vec![VisibleTile {
                target: tile_id,
                actual: tile_id,
                data: Some(TileData::Raster(rustial_engine::DecodedImage {
                    width: 1,
                    height: 1,
                    data: vec![255, 0, 0, 255].into(),
                })),
                fade_opacity: 1.0,
            }]);
        }

        let first_material = {
            let mut materials = app.world_mut().resource_mut::<Assets<TileFogMaterial>>();
            materials.add(TileFogMaterial::default())
        };

        app.world_mut().spawn((
            TileEntity {
                tile_id,
                spawn_origin: DVec3::ZERO,
                projection: rustial_engine::CameraProjection::default(),
                has_exact_texture: false,
            },
            MeshMaterial3d(first_material.clone()),
            Visibility::Hidden,
        ));

        app.update();

        let first_texture = {
            let world = app.world_mut();
            let materials = world.resource::<Assets<TileFogMaterial>>();
            materials
                .get(&first_material)
                .and_then(|material| material.tile_texture.clone())
                .expect("first upload should assign a texture")
        };

        let first_entity = {
            let world = app.world_mut();
            let mut query = world.query::<(Entity, &TileEntity)>();
            query
                .iter(&world)
                .find(|(_, tile)| tile.tile_id == tile_id)
                .map(|(entity, _)| entity)
                .expect("tile entity should exist")
        };
        app.world_mut().entity_mut(first_entity).despawn();

        let second_material = {
            let mut materials = app.world_mut().resource_mut::<Assets<TileFogMaterial>>();
            materials.add(TileFogMaterial::default())
        };

        app.world_mut().spawn((
            TileEntity {
                tile_id,
                spawn_origin: DVec3::ZERO,
                projection: rustial_engine::CameraProjection::default(),
                has_exact_texture: false,
            },
            MeshMaterial3d(second_material.clone()),
            Visibility::Hidden,
        ));

        app.update();

        let second_texture = {
            let world = app.world_mut();
            let materials = world.resource::<Assets<TileFogMaterial>>();
            materials
                .get(&second_material)
                .and_then(|material| material.tile_texture.clone())
                .expect("rebuilt entity should reuse a texture")
        };

        assert_eq!(first_texture, second_texture);
    }

    #[test]
    fn terrain_uses_loaded_ancestor_texture_when_exact_tile_is_missing() {
        let mut app = test_app();
        let parent = TileId { zoom: 3, x: 4, y: 2 };
        let child = TileId { zoom: 4, x: 8, y: 4 };

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_visible_tiles(vec![VisibleTile {
                target: parent,
                actual: parent,
                data: Some(TileData::Raster(rustial_engine::DecodedImage {
                    width: 2,
                    height: 2,
                    data: vec![
                        255, 0, 0, 255,
                        0, 255, 0, 255,
                        0, 0, 255, 255,
                        255, 255, 0, 255,
                    ]
                    .into(),
                })),
                fade_opacity: 1.0,
            }]);
        }

        let material = {
            let mut materials = app.world_mut().resource_mut::<Assets<TileFogMaterial>>();
            materials.add(TileFogMaterial::default())
        };

        app.world_mut().spawn((
            TerrainEntity {
                tile_id: child,
                spawn_origin: DVec3::ZERO,
                projection: rustial_engine::CameraProjection::default(),
                gpu_displaced: false,
                mesh_generation: 0,
                has_exact_texture: false,
            },
            MeshMaterial3d(material.clone()),
            Visibility::Hidden,
        ));

        app.update();

        let world = app.world_mut();
        let materials = world.resource::<Assets<TileFogMaterial>>();
        let material = materials
            .get(&material)
            .expect("terrain material should exist");

        assert!(material.tile_texture.is_some(), "terrain should receive ancestor imagery");
        assert!(material.flags.has_texture > 0.5, "terrain should be marked textured");
    }

    #[test]
    fn hillshade_overlay_receives_prepared_texture() {
        let mut app = test_app();
        let tile_id = {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_terrain(rustial_engine::TerrainManager::new(
                rustial_engine::TerrainConfig {
                    enabled: true,
                    source: Box::new(rustial_engine::FlatElevationSource::new(2, 2)),
                    ..rustial_engine::TerrainConfig::default()
                },
                16,
            ));
            state.0.push_layer(Box::new(rustial_engine::HillshadeLayer::new("hillshade")));
            state.0.update();
            state.0.hillshade_rasters()[0].tile
        };

        let material = {
            let mut materials = app.world_mut().resource_mut::<Assets<HillshadeMaterial>>();
            materials.add(HillshadeMaterial::default())
        };

        app.world_mut().spawn((
            HillshadeEntity {
                tile_id,
                spawn_origin: DVec3::ZERO,
                projection: rustial_engine::CameraProjection::default(),
                gpu_displaced: false,
                mesh_generation: 0,
            },
            MeshMaterial3d(material.clone()),
            Visibility::Hidden,
        ));

        app.update();

        let world = app.world_mut();
        let materials = world.resource::<Assets<HillshadeMaterial>>();
        let material = materials.get(&material).expect("hillshade material should exist");
        assert!(material.hillshade_texture != Handle::default());
    }
}