Skip to main content

flatland_client_ui/
world.rs

1use crate::color::RgbColor;
2use crate::interior_wall_layout::{interior_door_display_xy, interior_wall_glyph_line};
3use flatland_client_lib::GameState;
4use flatland_protocol::{BuildingView, InteriorMapView, TerrainKindView};
5
6use crate::map_presentation::{self, MapPresentation};
7
8/// The TUI map uses one terminal cell per world meter on both axes so terrain, entities,
9/// resources, and mouse targeting share the same grid. Terminal fonts are taller than wide,
10/// so buildings look vertically stretched compared to the content-admin editor.
11
12pub struct WorldView {
13    pub width: usize,
14    pub height: usize,
15    pub cells: Vec<String>,
16    /// Per-cell foreground color from presentation catalog (None = entity-specific style).
17    pub cell_fg: Vec<Option<RgbColor>>,
18    /// T1 target ring (red).
19    pub target_t1_cells: Vec<bool>,
20    /// T2 target ring (blue).
21    pub target_t2_cells: Vec<bool>,
22    pub origin_x: f32,
23    pub origin_y: f32,
24    pub inside_building: Option<String>,
25}
26
27/// Presentation flags for [`WorldView::build_with_options`].
28#[derive(Debug, Clone, Copy)]
29pub struct WorldViewOptions {
30    /// Paint local player `@` at view center (TUI). Gfx uses a sprite instead.
31    pub paint_local_player: bool,
32    /// Paint NPCs, resources, loot, chests, quest boards, entities into the cell grid.
33    /// Gfx sets this false and draws those at continuous world coordinates.
34    pub paint_overlays: bool,
35}
36
37impl Default for WorldViewOptions {
38    fn default() -> Self {
39        Self {
40            paint_local_player: true,
41            paint_overlays: true,
42        }
43    }
44}
45
46impl WorldViewOptions {
47    /// Terrain / walls only — gfx draws movers at precise x,y.
48    pub fn terrain_only() -> Self {
49        Self {
50            paint_local_player: false,
51            paint_overlays: false,
52        }
53    }
54}
55
56impl WorldView {
57    pub fn build_with_target(
58        state: &GameState,
59        view_w: usize,
60        view_h: usize,
61        map_target: Option<(f32, f32)>,
62    ) -> Self {
63        Self::build_with_options(
64            state,
65            view_w,
66            view_h,
67            map_target,
68            WorldViewOptions::default(),
69        )
70    }
71
72    /// Like [`build_with_target`] with gfx/TUI presentation flags.
73    pub fn build_with_options(
74        state: &GameState,
75        view_w: usize,
76        view_h: usize,
77        map_target: Option<(f32, f32)>,
78        options: WorldViewOptions,
79    ) -> Self {
80        let (px, py) = state.player_position();
81        Self::build_with_anchor(state, view_w, view_h, px, py, map_target, options)
82    }
83
84    /// Build a view anchored at explicit world coordinates (gfx uses smoothed camera).
85    pub fn build_with_anchor(
86        state: &GameState,
87        view_w: usize,
88        view_h: usize,
89        anchor_x: f32,
90        anchor_y: f32,
91        map_target: Option<(f32, f32)>,
92        options: WorldViewOptions,
93    ) -> Self {
94        map_presentation::maybe_reload_for_content_rev(state.content_rev);
95        let px = anchor_x;
96        let py = anchor_y;
97        let inside_building = state.effective_inside_building();
98
99        let width = view_w.max(3);
100        let height = view_h.max(3);
101        let grass = map_presentation::terrain_for(TerrainKindView::Grass);
102        let mut cells = vec![grass.glyph.clone(); width * height];
103        let mut cell_fg = vec![Some(grass.color); width * height];
104
105        let half_w = (width / 2) as i32;
106        let half_h = (height / 2) as i32;
107
108        // Interior rendering is authoritative from `inside_building`, not stale `interior_map`.
109        if let (Some(_bid), Some(interior)) =
110            (inside_building.as_deref(), state.interior_map.as_ref())
111        {
112            let player_z = state
113                .player
114                .as_ref()
115                .map(|p| p.transform.position.z)
116                .unwrap_or(0.0);
117            let active_floor = if interior.floor_height_m > f32::EPSILON {
118                (player_z / interior.floor_height_m).round() as i32
119            } else {
120                0
121            };
122            paint_interior_background(&mut cells, &mut cell_fg, width, height, interior);
123            paint_interior_rooms(
124                &mut cells,
125                &mut cell_fg,
126                width,
127                height,
128                interior,
129                px,
130                py,
131                half_w,
132                half_h,
133                active_floor,
134            );
135            let door_gaps = interior_door_gaps_snapped(interior, &state.doors, active_floor);
136            paint_interior_merged_walls(
137                &mut cells,
138                &mut cell_fg,
139                width,
140                height,
141                &interior.rooms,
142                active_floor,
143                px,
144                py,
145                half_w,
146                half_h,
147                &door_gaps,
148            );
149        } else {
150            paint_terrain(
151                &mut cells,
152                &mut cell_fg,
153                width,
154                height,
155                state,
156                px,
157                py,
158                half_w,
159                half_h,
160            );
161
162            for building in &state.buildings {
163                if building.tags.iter().any(|t| t == "well") {
164                    paint_well(
165                        &mut cells,
166                        &mut cell_fg,
167                        width,
168                        height,
169                        building,
170                        px,
171                        py,
172                        half_w,
173                        half_h,
174                    );
175                } else {
176                    paint_building_walls_centered(
177                        &mut cells,
178                        &mut cell_fg,
179                        width,
180                        height,
181                        building,
182                        px,
183                        py,
184                        half_w,
185                        half_h,
186                    );
187                }
188            }
189        }
190
191        if options.paint_overlays {
192            for door in &state.doors {
193                let (wx, wy) = match (inside_building.as_ref(), state.interior_map.as_ref()) {
194                    (Some(_), Some(interior)) => {
195                        let player_z = state
196                            .player
197                            .as_ref()
198                            .map(|p| p.transform.position.z)
199                            .unwrap_or(0.0);
200                        let active_floor = if interior.floor_height_m > f32::EPSILON {
201                            (player_z / interior.floor_height_m).round() as i32
202                        } else {
203                            0
204                        };
205                        interior_door_display_xy(interior, active_floor, &door.id, door.x, door.y)
206                    }
207                    _ => (door.x, door.y),
208                };
209                if let Some((gx, gy)) = world_to_grid(wx, wy, px, py, half_w, half_h, width, height)
210                {
211                    let idx = gy * width + gx;
212                    paint_presentation(
213                        &mut cells,
214                        &mut cell_fg,
215                        idx,
216                        &map_presentation::door_presentation(door.open, door.locked),
217                    );
218                }
219            }
220
221            for npc in &state.npcs {
222                if let Some((gx, gy)) =
223                    world_to_grid(npc.x, npc.y, px, py, half_w, half_h, width, height)
224                {
225                    let idx = gy * width + gx;
226                    paint_presentation(
227                        &mut cells,
228                        &mut cell_fg,
229                        idx,
230                        &map_presentation::npc_for(npc),
231                    );
232                }
233            }
234
235            let ground = empty_ground_glyph();
236            let player_glyph = map_presentation::player_presentation().glyph;
237            for node in &state.resource_nodes {
238                if let Some((gx, gy)) =
239                    world_to_grid(node.x, node.y, px, py, half_w, half_h, width, height)
240                {
241                    let idx = gy * width + gx;
242                    let pres = map_presentation::resource_for(node);
243                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
244                        paint_presentation(&mut cells, &mut cell_fg, idx, &pres);
245                    }
246                }
247            }
248
249            for drop in &state.ground_drops {
250                if let Some((gx, gy)) =
251                    world_to_grid(drop.x, drop.y, px, py, half_w, half_h, width, height)
252                {
253                    let idx = gy * width + gx;
254                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
255                        paint_presentation(
256                            &mut cells,
257                            &mut cell_fg,
258                            idx,
259                            &map_presentation::loot_presentation(),
260                        );
261                    }
262                }
263            }
264
265            for chest in &state.placed_containers {
266                if !state.placed_container_in_current_space(chest) {
267                    continue;
268                }
269                if let Some((gx, gy)) =
270                    world_to_grid(chest.x, chest.y, px, py, half_w, half_h, width, height)
271                {
272                    let idx = gy * width + gx;
273                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
274                        paint_presentation(
275                            &mut cells,
276                            &mut cell_fg,
277                            idx,
278                            &map_presentation::chest_presentation(chest.locked),
279                        );
280                    }
281                }
282            }
283
284            if state.effective_inside_building().is_none() {
285                for inter in &state.interactables {
286                    if inter.kind != "quest_board" {
287                        continue;
288                    }
289                    if let Some((gx, gy)) =
290                        world_to_grid(inter.x, inter.y, px, py, half_w, half_h, width, height)
291                    {
292                        let idx = gy * width + gx;
293                        if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
294                            paint_presentation(
295                                &mut cells,
296                                &mut cell_fg,
297                                idx,
298                                &map_presentation::quest_board_presentation(),
299                            );
300                        }
301                    }
302                }
303            }
304
305            for entity in &state.entities {
306                // When gfx draws a sprite for the local player, omit the `@` glyph.
307                if !options.paint_local_player && entity.id == state.entity_id {
308                    continue;
309                }
310                if entity.id != state.entity_id
311                    && entity.inside_building.as_deref() != inside_building.as_deref()
312                {
313                    continue;
314                }
315                if let (Some(_), Some(interior)) =
316                    (inside_building.as_deref(), state.interior_map.as_ref())
317                {
318                    let player_z = state
319                        .player
320                        .as_ref()
321                        .map(|p| p.transform.position.z)
322                        .unwrap_or(0.0);
323                    if interior.floor_height_m > f32::EPSILON {
324                        let pf = (player_z / interior.floor_height_m).round() as i32;
325                        let ef =
326                            (entity.transform.position.z / interior.floor_height_m).round() as i32;
327                        if pf != ef {
328                            continue;
329                        }
330                    }
331                }
332                if let Some(pres) = entity_presentation(entity, state.entity_id) {
333                    if let Some((gx, gy)) = world_to_grid(
334                        entity.transform.position.x,
335                        entity.transform.position.y,
336                        px,
337                        py,
338                        half_w,
339                        half_h,
340                        width,
341                        height,
342                    ) {
343                        let idx = gy * width + gx;
344                        paint_presentation(&mut cells, &mut cell_fg, idx, &pres);
345                    }
346                }
347            }
348        }
349
350        if options.paint_local_player {
351            if state.player_entity().is_some() {
352                let cx = half_w as usize;
353                let cy = half_h as usize;
354                let idx = cy * width + cx;
355                if idx < cells.len() {
356                    paint_presentation(
357                        &mut cells,
358                        &mut cell_fg,
359                        idx,
360                        &map_presentation::player_presentation(),
361                    );
362                }
363            }
364        }
365
366        let mut target_t1_cells = vec![false; cells.len()];
367        let mut target_t2_cells = vec![false; cells.len()];
368        if options.paint_overlays {
369            for (slot, cells_out) in [(1, &mut target_t1_cells), (2, &mut target_t2_cells)] {
370                let target_id = state
371                    .combat_slots
372                    .iter()
373                    .find(|s| s.slot_index == slot)
374                    .and_then(|s| s.target_entity_id)
375                    .or_else(|| if slot == 1 { state.combat_target } else { None });
376                let Some(target_id) = target_id else {
377                    continue;
378                };
379                let (tx, ty) =
380                    if let Some(npc) = state.npcs.iter().find(|n| n.entity_id == Some(target_id)) {
381                        (npc.x, npc.y)
382                    } else if let Some(entity) = state.entities.iter().find(|e| e.id == target_id) {
383                        (entity.transform.position.x, entity.transform.position.y)
384                    } else {
385                        continue;
386                    };
387                if let Some((gx, gy)) = world_to_grid(tx, ty, px, py, half_w, half_h, width, height)
388                {
389                    let idx = gy * width + gx;
390                    if idx < cells_out.len() {
391                        cells_out[idx] = true;
392                    }
393                }
394            }
395        }
396
397        if options.paint_overlays {
398            if let Some((tx, ty)) = map_target {
399                if let Some((gx, gy)) = world_to_grid(tx, ty, px, py, half_w, half_h, width, height)
400                {
401                    let idx = gy * width + gx;
402                    if idx < cells.len() {
403                        cells[idx] = "X".into();
404                        cell_fg[idx] = Some(RgbColor::YELLOW);
405                    }
406                }
407            }
408        }
409
410        Self {
411            width,
412            height,
413            cells,
414            cell_fg,
415            target_t1_cells,
416            target_t2_cells,
417            origin_x: px,
418            origin_y: py,
419            inside_building,
420        }
421    }
422}
423
424fn paint_presentation(
425    cells: &mut [String],
426    cell_fg: &mut [Option<RgbColor>],
427    idx: usize,
428    pres: &MapPresentation,
429) {
430    cells[idx] = pres.glyph.clone();
431    cell_fg[idx] = Some(pres.color);
432}
433
434fn empty_ground_glyph() -> String {
435    map_presentation::terrain_for(TerrainKindView::Grass).glyph
436}
437
438fn entity_presentation(
439    entity: &flatland_protocol::EntityState,
440    player_id: u64,
441) -> Option<MapPresentation> {
442    if entity.id == player_id {
443        return Some(map_presentation::player_presentation());
444    }
445    if entity
446        .vitals
447        .as_ref()
448        .is_some_and(|v| v.life_state == flatland_protocol::LifeState::Dead)
449    {
450        return Some(map_presentation::corpse_presentation());
451    }
452    Some(map_presentation::entity_fallback(&entity.label))
453}
454
455fn paint_interior_background(
456    cells: &mut [String],
457    cell_fg: &mut [Option<RgbColor>],
458    _width: usize,
459    _height: usize,
460    interior: &InteriorMapView,
461) {
462    let bg = crate::color::parse_color(&interior.background_color).unwrap_or(RgbColor::BLACK);
463    for idx in 0..cells.len() {
464        cells[idx] = " ".into();
465        cell_fg[idx] = Some(bg);
466    }
467}
468
469fn paint_interior_rooms(
470    cells: &mut [String],
471    cell_fg: &mut [Option<RgbColor>],
472    width: usize,
473    height: usize,
474    interior: &InteriorMapView,
475    px: f32,
476    py: f32,
477    half_w: i32,
478    half_h: i32,
479    active_floor: i32,
480) {
481    let default_color = interior
482        .default_floor_color
483        .as_deref()
484        .and_then(crate::color::parse_color)
485        .unwrap_or(RgbColor::rgb(0x2a, 0x2a, 0x2a));
486    for room in &interior.rooms {
487        if room.floor != active_floor {
488            continue;
489        }
490        let floor_color = room
491            .floor_color
492            .as_deref()
493            .and_then(crate::color::parse_color)
494            .unwrap_or(default_color);
495        let glyph = room.floor_glyph.as_deref().unwrap_or(".").to_string();
496        let x0 = room.x0.floor() as i32;
497        let y0 = room.y0.floor() as i32;
498        let x1 = room.x1.ceil() as i32 - 1;
499        let y1 = room.y1.ceil() as i32 - 1;
500        for wy in y0..=y1 {
501            for wx in x0..=x1 {
502                if let Some((gx, gy)) =
503                    world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
504                {
505                    let idx = gy * width + gx;
506                    cells[idx] = glyph.clone();
507                    cell_fg[idx] = Some(floor_color);
508                }
509            }
510        }
511    }
512}
513
514fn interior_door_gaps(
515    interior: &InteriorMapView,
516    doors: &[flatland_protocol::DoorView],
517    active_floor: i32,
518) -> Vec<(f32, f32)> {
519    let room_floor =
520        |id: &str| -> Option<i32> { interior.rooms.iter().find(|r| r.id == id).map(|r| r.floor) };
521    let mut gaps: Vec<(f32, f32)> = interior
522        .room_doors
523        .iter()
524        .filter_map(|d| {
525            let on_floor = room_floor(&d.room_a) == Some(active_floor)
526                || room_floor(&d.room_b) == Some(active_floor);
527            if !on_floor {
528                return None;
529            }
530            doors
531                .iter()
532                .find(|door| door.id == d.id)
533                .filter(|door| door.open || d.kind == "stairs")
534                .map(|door| (door.x, door.y))
535        })
536        .collect();
537    for door in doors {
538        if door.portal.is_some() && door.open {
539            gaps.push((door.x, door.y));
540        }
541    }
542    gaps
543}
544
545fn interior_door_gaps_snapped(
546    interior: &flatland_protocol::InteriorMapView,
547    doors: &[flatland_protocol::DoorView],
548    floor: i32,
549) -> Vec<(f32, f32)> {
550    let mut gaps = Vec::new();
551    for (x, y) in interior_door_gaps(interior, doors, floor) {
552        // Match gap carving to door sprite — find door id at this authored position.
553        let door_id = doors
554            .iter()
555            .find(|d| (d.x - x).abs() < 0.05 && (d.y - y).abs() < 0.05)
556            .map(|d| d.id.as_str())
557            .unwrap_or("");
558        gaps.push(interior_door_display_xy(interior, floor, door_id, x, y));
559    }
560    gaps
561}
562
563fn near_door_gap(wx: i32, wy: i32, door_gaps: &[(f32, f32)]) -> bool {
564    door_gaps
565        .iter()
566        .any(|(dx, dy)| (wx as f32 - dx).abs() < 1.0 && (wy as f32 - dy).abs() < 1.0)
567}
568
569const INTERIOR_WALL_EDGE_TOL: f32 = 0.6;
570
571/// World grid row/column for a merged wall line (half-meter room edges).
572fn interior_wall_grid_line(fixed: f32) -> i32 {
573    interior_wall_glyph_line(fixed)
574}
575
576fn quant_interior_wall_coord(v: f32) -> i64 {
577    (v * 1000.0).round() as i64
578}
579
580fn merge_interior_wall_intervals(mut intervals: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
581    if intervals.is_empty() {
582        return intervals;
583    }
584    intervals.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
585    let mut out = vec![intervals[0]];
586    for &(a, b) in intervals.iter().skip(1) {
587        let last_idx = out.len() - 1;
588        if a <= out[last_idx].1 + INTERIOR_WALL_EDGE_TOL {
589            out[last_idx].1 = out[last_idx].1.max(b);
590        } else {
591            out.push((a, b));
592        }
593    }
594    out
595}
596
597/// Paint merged interior walls — shared room edges become a single wall strip (matches sim).
598fn paint_interior_merged_walls(
599    cells: &mut [String],
600    cell_fg: &mut [Option<RgbColor>],
601    width: usize,
602    height: usize,
603    rooms: &[flatland_protocol::InteriorRoomView],
604    floor: i32,
605    px: f32,
606    py: f32,
607    half_w: i32,
608    half_h: i32,
609    door_gaps: &[(f32, f32)],
610) {
611    use std::collections::HashMap;
612
613    let mut horiz: HashMap<i64, Vec<(f32, f32)>> = HashMap::new();
614    let mut vert: HashMap<i64, Vec<(f32, f32)>> = HashMap::new();
615
616    for room in rooms.iter().filter(|r| r.floor == floor) {
617        let west = room.x0.min(room.x1);
618        let east = room.x0.max(room.x1);
619        let south = room.y0.min(room.y1);
620        let north = room.y0.max(room.y1);
621        if east - west >= 0.25 {
622            horiz
623                .entry(quant_interior_wall_coord(south))
624                .or_default()
625                .push((west, east));
626            horiz
627                .entry(quant_interior_wall_coord(north))
628                .or_default()
629                .push((west, east));
630        }
631        if north - south >= 0.25 {
632            vert.entry(quant_interior_wall_coord(west))
633                .or_default()
634                .push((south, north));
635            vert.entry(quant_interior_wall_coord(east))
636                .or_default()
637                .push((south, north));
638        }
639    }
640
641    for (key, intervals) in horiz {
642        let fixed = key as f32 / 1000.0;
643        let merged = merge_interior_wall_intervals(intervals);
644        let wy = interior_wall_grid_line(fixed);
645        for (start, end) in merged {
646            if end - start < 0.2 {
647                continue;
648            }
649            let x0 = start.round() as i32;
650            let x1 = end.round() as i32;
651            for wx in x0..=x1 {
652                if !near_door_gap(wx, wy, door_gaps) {
653                    paint_wall_cell(
654                        cells, cell_fg, width, height, wx, wy, px, py, half_w, half_h, "-",
655                    );
656                }
657            }
658        }
659    }
660
661    for (key, intervals) in vert {
662        let fixed = key as f32 / 1000.0;
663        let merged = merge_interior_wall_intervals(intervals);
664        let wx = interior_wall_grid_line(fixed);
665        for (start, end) in merged {
666            if end - start < 0.2 {
667                continue;
668            }
669            let y0 = start.round() as i32;
670            let y1 = end.round() as i32;
671            for wy in y0..=y1 {
672                if !near_door_gap(wx, wy, door_gaps) {
673                    paint_wall_cell(
674                        cells, cell_fg, width, height, wx, wy, px, py, half_w, half_h, "|",
675                    );
676                }
677            }
678        }
679    }
680}
681
682fn paint_terrain(
683    cells: &mut [String],
684    cell_fg: &mut [Option<RgbColor>],
685    width: usize,
686    height: usize,
687    state: &GameState,
688    px: f32,
689    py: f32,
690    _half_w: i32,
691    _half_h: i32,
692) {
693    for gy in 0..height {
694        for gx in 0..width {
695            let Some((wx, wy)) = grid_to_world(gx, gy, px, py, width, height) else {
696                continue;
697            };
698            let zone = state.terrain_zone_at(wx, wy);
699            let kind = zone.map(|z| z.kind).unwrap_or(TerrainKindView::Grass);
700            let elev = zone.map(|z| z.elevation).unwrap_or(0.0);
701            let style = map_presentation::terrain_for_zone(
702                kind,
703                elev,
704                zone.and_then(|z| z.glyph.as_deref()),
705                zone.and_then(|z| z.color.as_deref()),
706            );
707            let idx = gy * width + gx;
708            paint_presentation(cells, cell_fg, idx, &style);
709        }
710    }
711}
712
713fn paint_well(
714    cells: &mut [String],
715    cell_fg: &mut [Option<RgbColor>],
716    width: usize,
717    height: usize,
718    building: &BuildingView,
719    px: f32,
720    py: f32,
721    half_w: i32,
722    half_h: i32,
723) {
724    let hw = building.width_m / 2.0;
725    let hd = building.depth_m / 2.0;
726    let x0 = (building.x - hw).floor() as i32;
727    let y0 = (building.y - hd).floor() as i32;
728    let x1 = (building.x + hw).ceil() as i32 - 1;
729    let y1 = (building.y + hd).ceil() as i32 - 1;
730    let water = map_presentation::shallow_water_presentation();
731    let center = map_presentation::well_center_presentation();
732
733    for wy in y0..=y1 {
734        for wx in x0..=x1 {
735            let pres = if wx == building.x.round() as i32 && wy == building.y.round() as i32 {
736                center.clone()
737            } else {
738                water.clone()
739            };
740            if let Some((gx, gy)) =
741                world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
742            {
743                let idx = gy * width + gx;
744                if !is_wall(&cells[idx]) {
745                    paint_presentation(cells, cell_fg, idx, &pres);
746                }
747            }
748        }
749    }
750}
751
752fn paint_building_walls_centered(
753    cells: &mut [String],
754    cell_fg: &mut [Option<RgbColor>],
755    width: usize,
756    height: usize,
757    building: &BuildingView,
758    px: f32,
759    py: f32,
760    half_w: i32,
761    half_h: i32,
762) {
763    let hw = building.width_m / 2.0;
764    let hd = building.depth_m / 2.0;
765    paint_building_walls(
766        cells,
767        cell_fg,
768        width,
769        height,
770        building.x - hw,
771        building.y - hd,
772        building.width_m,
773        building.depth_m,
774        px,
775        py,
776        half_w,
777        half_h,
778        &[],
779    );
780}
781
782/// Paint perimeter walls for an axis-aligned rectangle (origin = south-west corner).
783fn paint_building_walls(
784    cells: &mut [String],
785    cell_fg: &mut [Option<RgbColor>],
786    width: usize,
787    height: usize,
788    origin_x: f32,
789    origin_y: f32,
790    width_m: f32,
791    depth_m: f32,
792    px: f32,
793    py: f32,
794    half_w: i32,
795    half_h: i32,
796    door_gaps: &[(f32, f32)],
797) {
798    let x0 = origin_x.floor() as i32;
799    let y0 = origin_y.floor() as i32;
800    let x1 = (origin_x + width_m).ceil() as i32 - 1;
801    let y1 = (origin_y + depth_m).ceil() as i32 - 1;
802
803    if x1 < x0 || y1 < y0 {
804        return;
805    }
806
807    for wx in x0..=x1 {
808        if !near_door_gap(wx, y0, door_gaps) {
809            paint_wall_cell(
810                cells, cell_fg, width, height, wx, y0, px, py, half_w, half_h, "-",
811            );
812        }
813        if !near_door_gap(wx, y1, door_gaps) {
814            paint_wall_cell(
815                cells, cell_fg, width, height, wx, y1, px, py, half_w, half_h, "-",
816            );
817        }
818    }
819    for wy in y0 + 1..y1 {
820        if !near_door_gap(x0, wy, door_gaps) {
821            paint_wall_cell(
822                cells, cell_fg, width, height, x0, wy, px, py, half_w, half_h, "|",
823            );
824        }
825        if !near_door_gap(x1, wy, door_gaps) {
826            paint_wall_cell(
827                cells, cell_fg, width, height, x1, wy, px, py, half_w, half_h, "|",
828            );
829        }
830    }
831    if !near_door_gap(x0, y0, door_gaps) {
832        paint_wall_cell(
833            cells, cell_fg, width, height, x0, y0, px, py, half_w, half_h, "+",
834        );
835    }
836    if !near_door_gap(x1, y0, door_gaps) {
837        paint_wall_cell(
838            cells, cell_fg, width, height, x1, y0, px, py, half_w, half_h, "+",
839        );
840    }
841    if !near_door_gap(x0, y1, door_gaps) {
842        paint_wall_cell(
843            cells, cell_fg, width, height, x0, y1, px, py, half_w, half_h, "+",
844        );
845    }
846    if !near_door_gap(x1, y1, door_gaps) {
847        paint_wall_cell(
848            cells, cell_fg, width, height, x1, y1, px, py, half_w, half_h, "+",
849        );
850    }
851}
852
853fn paint_wall_cell(
854    cells: &mut [String],
855    cell_fg: &mut [Option<RgbColor>],
856    width: usize,
857    height: usize,
858    wx: i32,
859    wy: i32,
860    px: f32,
861    py: f32,
862    half_w: i32,
863    half_h: i32,
864    ch: &str,
865) {
866    let Some((gx, gy)) = world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
867    else {
868        return;
869    };
870    let idx = gy * width + gx;
871    let ground = empty_ground_glyph();
872    // Paint over terrain/floor, the interior background, and existing wall cells
873    // (corner merge). Skipping the " " interior background is what made outer
874    // perimeter walls (e.g. the south wall of a room at negative y) invisible.
875    if cells[idx] == ground || cells[idx] == " " || is_wall(&cells[idx]) {
876        cells[idx] = merge_wall_corner(&cells[idx], ch, &ground);
877        cell_fg[idx] = Some(map_presentation::wall_presentation().color);
878    }
879}
880
881fn is_wall(glyph: &str) -> bool {
882    matches!(glyph.chars().next(), Some('+' | '-' | '|'))
883}
884
885/// Overlays (resources, loot, chests, boards) paint on any non-wall cell.
886fn can_paint_world_object(glyph: &str, _ground: &str, _player_glyph: &str) -> bool {
887    !is_wall(glyph)
888}
889
890fn merge_wall_corner(existing: &str, incoming: &str, ground: &str) -> String {
891    // Interior background counts as paintable ground (outer perimeter walls sit on it).
892    if existing == ground || existing == " " {
893        return incoming.to_string();
894    }
895    if existing == incoming {
896        return existing.to_string();
897    }
898    "+".to_string()
899}
900
901fn world_to_grid(
902    x: f32,
903    y: f32,
904    px: f32,
905    py: f32,
906    half_w: i32,
907    half_h: i32,
908    width: usize,
909    height: usize,
910) -> Option<(usize, usize)> {
911    let dx = (x - px).round() as i32;
912    let dy = (y - py).round() as i32;
913
914    if dx.abs() > half_w || dy.abs() > half_h {
915        return None;
916    }
917
918    let gx = half_w + dx;
919    let gy = half_h - dy;
920
921    if gx < 0 || gy < 0 {
922        return None;
923    }
924    let gx = gx as usize;
925    let gy = gy as usize;
926    if gx >= width || gy >= height {
927        return None;
928    }
929    Some((gx, gy))
930}
931
932/// Inverse of [`world_to_grid`]: map view cell → world meters (cell center).
933pub fn grid_to_world(
934    gx: usize,
935    gy: usize,
936    px: f32,
937    py: f32,
938    view_w: usize,
939    view_h: usize,
940) -> Option<(f32, f32)> {
941    if gx >= view_w || gy >= view_h {
942        return None;
943    }
944    let half_w = (view_w / 2) as i32;
945    let half_h = (view_h / 2) as i32;
946    let dx = gx as i32 - half_w;
947    let dy = half_h - gy as i32;
948    Some((px + dx as f32, py + dy as f32))
949}
950
951#[cfg(test)]
952mod tests {
953    use super::*;
954    use flatland_protocol::{
955        BuildingView, EntityState, PlayerVitals, PrimaryAttributes, Transform, WorldCoord,
956    };
957
958    fn state_with_building(building: BuildingView) -> GameState {
959        GameState {
960            session_id: 1,
961            entity_id: 1,
962            character_id: None,
963            tick: 0,
964            chunk_rev: 0,
965            content_rev: 0,
966            publish_rev: 0,
967            entities: vec![EntityState {
968                id: 1,
969                label: "You".into(),
970                transform: Transform {
971                    position: WorldCoord::surface(148.0, 118.0),
972                    yaw: 0.0,
973                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
974                },
975                vitals: Some(PlayerVitals::default()),
976                attributes: Some(PrimaryAttributes::default()),
977                skills: Some(flatland_protocol::PlayerSkills::default()),
978                inside_building: None,
979                tile_id: None,
980                paperdoll_ref: None,
981                draw_scale: 1.0,
982                presentation_state: None,
983                sprite_mode: None,
984                progression_xp: None,
985                combat_cues: Vec::new(),
986                statuses: Vec::new(),
987            }],
988            player: None,
989            resource_nodes: vec![],
990            ground_drops: vec![],
991            placed_containers: vec![],
992            buildings: vec![building],
993            doors: vec![],
994            interior_map: None,
995            npcs: vec![],
996            blueprints: vec![],
997            building_materials: vec![],
998            world_x0: 0.0,
999            world_y0: 0.0,
1000            world_width_m: 256.0,
1001            world_height_m: 256.0,
1002            terrain_zones: vec![],
1003            z_platforms: vec![],
1004            z_transitions: vec![],
1005            z_bands_outdoor_backup: None,
1006            world_clock: flatland_protocol::WorldClock::default(),
1007            inventory: Default::default(),
1008            inventory_hints: Default::default(),
1009            logs: Default::default(),
1010            intents_sent: 0,
1011            ticks_received: 0,
1012            connected: true,
1013            disconnect_reason: None,
1014            show_stats: false,
1015            hud_log_hidden: false,
1016            show_equip_menu: false,
1017            equip_menu_index: 0,
1018            ledger: None,
1019            career: None,
1020            character_sheet_tab: flatland_client_lib::CharacterSheetTab::Character,
1021            ledger_period: flatland_client_lib::LedgerPeriod::Day,
1022            show_craft_menu: false,
1023            show_plot_build_menu: false,
1024            plot_build_focus_wall: true,
1025            plot_build_wall_index: 0,
1026            plot_build_roof_index: 0,
1027            craft_menu_index: 0,
1028            craft_batch_quantity: 1,
1029            show_shop_menu: false,
1030            shop_catalog: None,
1031            bank_panel: None,
1032            bank_menu_index: 0,
1033            bank_ui_mode: flatland_client_lib::BankUiMode::Menu,
1034            storage_panel: None,
1035            market_panel: None,
1036            market_menu_index: 0,
1037            market_filter: String::new(),
1038            market_filter_focused: false,
1039            market_category_filter: None,
1040            market_buy_confirm: None,
1041            market_ui_mode: flatland_client_lib::MarketUiMode::Browse,
1042            storage_menu_index: 0,
1043            storage_ui_mode: flatland_client_lib::StorageUiMode::Menu,
1044            property_zones: vec![],
1045            tax_zones: vec![],
1046            growth_zones: vec![],
1047            biome_zones: vec![],
1048            terrain_kind_nav: vec![],
1049            property_plots: vec![],
1050            property_plot_settings: None,
1051            claim_mode: None,
1052            relocate_mode: None,
1053            sell_plot_confirm: None,
1054            sell_plot_armed_at: None,
1055            show_plant_menu: false,
1056            plant_menu_index: 0,
1057            show_farm_access: false,
1058            farm_access_name_draft: String::new(),
1059            farm_access_discount_bps: 0,
1060            farm_access_index: 0,
1061            plant_quantity: 1,
1062            shop_tab: flatland_client_lib::ShopTab::default(),
1063            shop_menu_index: 0,
1064            shop_quantity: 1,
1065            shop_trade_log: std::collections::VecDeque::new(),
1066            show_npc_verb_menu: false,
1067            npc_verb_target: None,
1068            npc_verb_index: 0,
1069            player_verbs: Default::default(),
1070            social_chat: Default::default(),
1071            trade_ui: Default::default(),
1072            whisper_pouch_ui: Default::default(),
1073            show_npc_chat: false,
1074            npc_chat: None,
1075            show_inventory_menu: false,
1076            inventory_menu_index: 0,
1077            inventory_tab: flatland_client_lib::InventoryTab::OnPerson,
1078            inventory_filter: String::new(),
1079            inventory_filter_focused: false,
1080            show_move_picker: false,
1081            show_rename_prompt: false,
1082            rename_plot_id: None,
1083            highlighted_plot_id: None,
1084            show_worker_rename: false,
1085            rename_buffer: String::new(),
1086            move_picker_index: 0,
1087            move_picker: None,
1088            show_grant_picker: false,
1089            grant_picker_index: 0,
1090            grant_picker: None,
1091            show_destroy_picker: false,
1092            destroy_confirm_pending: false,
1093            destroy_picker: None,
1094            combat_target: None,
1095            combat_target_label: None,
1096            ground_target: None,
1097            combat_fx: Vec::new(),
1098            ground_hazards: Vec::new(),
1099            in_combat: false,
1100            auto_attack: true,
1101            combat_has_los: false,
1102            attack_cd_ticks: 0,
1103            gcd_ticks: 0,
1104            weapon_ability_id: "unarmed".into(),
1105            mainhand_template_id: None,
1106            mainhand_label: None,
1107            mainhand_instance_id: None,
1108            offhand_template_id: None,
1109            offhand_label: None,
1110            offhand_instance_id: None,
1111            mainhand_hand_slots: 1,
1112            defense: None,
1113            worn: std::collections::BTreeMap::new(),
1114            carry_mass: 0.0,
1115            carry_mass_max: 0.0,
1116            encumbrance: flatland_protocol::EncumbranceState::Light,
1117            inventory_stacks: Vec::new(),
1118            keychain_stacks: Vec::new(),
1119            whisper_pouch_stacks: Vec::new(),
1120            combat_target_detail: None,
1121            statuses: Vec::new(),
1122            cast_progress: None,
1123            timed_channel: None,
1124            plot_build_offer: None,
1125            ability_cooldowns: Vec::new(),
1126            blocking_active: false,
1127            max_target_slots: 1,
1128            combat_slots: Vec::new(),
1129            rotation_presets: Vec::new(),
1130            known_abilities: Vec::new(),
1131            ability_meta: std::collections::HashMap::new(),
1132            ability_mastery: std::collections::HashMap::new(),
1133            hotbar: vec![None; 9],
1134            max_abilities_per_rotation: 0,
1135            show_loadout_menu: false,
1136            show_keychain_menu: false,
1137            keychain_menu_index: 0,
1138            show_rotation_editor: false,
1139            loadout_menu_index: 0,
1140            loadout_hotbar_slot: 1,
1141            loadout_ability_index: 0,
1142            loadout_focus_presets: false,
1143            rotation_editor: Default::default(),
1144            harvest_in_progress: false,
1145            harvest_started_at: None,
1146            pending_craft_ack: None,
1147            pending_worker_job_ack: None,
1148            attending_worker_instance_id: None,
1149            quest_log: Vec::new(),
1150            interactables: Vec::new(),
1151            show_quest_offer: false,
1152            pending_quest_offer: None,
1153            show_quest_menu: false,
1154            quest_menu_index: 0,
1155            quest_withdraw_confirm: false,
1156            hired_workers: Vec::new(),
1157            show_workers_menu: false,
1158            workers_menu_index: 0,
1159            worker_dismiss_confirmation: None,
1160            workers_menu_compact: false,
1161            worker_step_display: std::collections::BTreeMap::new(),
1162            worker_error_display: std::collections::BTreeMap::new(),
1163            worker_health_ring_until: std::collections::BTreeMap::new(),
1164            show_worker_give_picker: false,
1165            worker_give_picker_index: 0,
1166            worker_give_picker: None,
1167            show_worker_give_target_picker: false,
1168            worker_give_target_picker_index: 0,
1169            worker_give_target_picker: None,
1170            show_worker_take_picker: false,
1171            worker_take_picker_index: 0,
1172            worker_take_picker: None,
1173            show_worker_teach_picker: false,
1174            worker_teach_picker_index: 0,
1175            worker_teach_picker: None,
1176            worker_route_editor: None,
1177            progression_curve: None,
1178        }
1179    }
1180
1181    #[test]
1182    fn shallow_water_terrain_paints_tilde() {
1183        use flatland_protocol::TerrainZoneView;
1184        let mut state = state_with_building(BuildingView {
1185            id: "x".into(),
1186            label: "X".into(),
1187            x: 128.0,
1188            y: 128.0,
1189            width_m: 1.0,
1190            depth_m: 1.0,
1191            interior_blueprint: None,
1192            tags: vec![],
1193            market_boundary_zone_ids: vec![],
1194            market_max_volume: None,
1195            wall_set: None,
1196            roof_set: None,
1197        });
1198        state.terrain_zones.push(TerrainZoneView {
1199            id: "pond".into(),
1200            x0: 126.0,
1201            y0: 126.0,
1202            x1: 130.0,
1203            y1: 130.0,
1204            kind: TerrainKindView::ShallowWater,
1205            elevation: -0.5,
1206            glyph: None,
1207            color: None,
1208            tile_id: None,
1209            z_order: 0,
1210            channel_start_tick: None,
1211            channel_end_tick: None,
1212        });
1213        state.entities = vec![EntityState {
1214            id: 1,
1215            label: "You".into(),
1216            transform: Transform {
1217                position: WorldCoord::surface(128.0, 128.0),
1218                yaw: 0.0,
1219                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1220            },
1221            vitals: Some(PlayerVitals::default()),
1222            attributes: Some(PrimaryAttributes::default()),
1223            skills: Some(flatland_protocol::PlayerSkills::default()),
1224            inside_building: None,
1225            tile_id: None,
1226            paperdoll_ref: None,
1227            draw_scale: 1.0,
1228            presentation_state: None,
1229            sprite_mode: None,
1230            progression_xp: None,
1231            combat_cues: Vec::new(),
1232            statuses: Vec::new(),
1233        }];
1234        state.player = state.entities.first().cloned();
1235        let view = WorldView::build_with_target(&state, 9, 9, None);
1236        let flat = view.cells.join("");
1237        let water = map_presentation::shallow_water_presentation();
1238        assert!(
1239            flat.contains(&water.glyph),
1240            "expected water tiles ({:?}): {flat}",
1241            water.glyph
1242        );
1243        assert!(
1244            view.cell_fg.iter().any(|c| *c == Some(water.color)),
1245            "expected water color on terrain cells"
1246        );
1247    }
1248
1249    #[test]
1250    fn zone_glyph_and_color_overrides_paint_on_map() {
1251        use flatland_protocol::TerrainZoneView;
1252        let mut state = state_with_building(BuildingView {
1253            id: "x".into(),
1254            label: "X".into(),
1255            x: 128.0,
1256            y: 128.0,
1257            width_m: 1.0,
1258            depth_m: 1.0,
1259            interior_blueprint: None,
1260            tags: vec![],
1261            market_boundary_zone_ids: vec![],
1262            market_max_volume: None,
1263            wall_set: None,
1264            roof_set: None,
1265        });
1266        state.terrain_zones.push(TerrainZoneView {
1267            id: "marked".into(),
1268            x0: 126.0,
1269            y0: 126.0,
1270            x1: 130.0,
1271            y1: 130.0,
1272            kind: TerrainKindView::Grass,
1273            elevation: 0.0,
1274            glyph: Some("%".into()),
1275            color: Some("magenta".into()),
1276            tile_id: None,
1277            z_order: 0,
1278            channel_start_tick: None,
1279            channel_end_tick: None,
1280        });
1281        state.entities = vec![EntityState {
1282            id: 1,
1283            label: "You".into(),
1284            transform: Transform {
1285                position: WorldCoord::surface(128.0, 128.0),
1286                yaw: 0.0,
1287                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1288            },
1289            vitals: Some(PlayerVitals::default()),
1290            attributes: Some(PrimaryAttributes::default()),
1291            skills: Some(flatland_protocol::PlayerSkills::default()),
1292            inside_building: None,
1293            tile_id: None,
1294            paperdoll_ref: None,
1295            draw_scale: 1.0,
1296            presentation_state: None,
1297            sprite_mode: None,
1298            progression_xp: None,
1299            combat_cues: Vec::new(),
1300            statuses: Vec::new(),
1301        }];
1302        state.player = state.entities.first().cloned();
1303        let view = WorldView::build_with_target(&state, 9, 9, None);
1304        let flat = view.cells.join("");
1305        assert!(
1306            flat.contains('%'),
1307            "expected custom zone glyph on map: {flat}"
1308        );
1309        assert!(
1310            view.cell_fg.iter().any(|c| *c == Some(RgbColor::MAGENTA)),
1311            "expected custom zone color on terrain cells"
1312        );
1313    }
1314
1315    #[test]
1316    fn well_paints_water_ring_and_center() {
1317        let building = BuildingView {
1318            id: "town_well".into(),
1319            label: "Well".into(),
1320            x: 122.0,
1321            y: 106.0,
1322            width_m: 3.0,
1323            depth_m: 3.0,
1324            interior_blueprint: None,
1325            tags: vec!["well".into()],
1326            market_boundary_zone_ids: vec![],
1327            market_max_volume: None,
1328            wall_set: None,
1329            roof_set: None,
1330        };
1331        let mut state = state_with_building(building);
1332        state.entities = vec![EntityState {
1333            id: 1,
1334            label: "You".into(),
1335            transform: Transform {
1336                position: WorldCoord::surface(120.0, 106.0),
1337                yaw: 0.0,
1338                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1339            },
1340            vitals: Some(PlayerVitals::default()),
1341            attributes: Some(PrimaryAttributes::default()),
1342            skills: Some(flatland_protocol::PlayerSkills::default()),
1343            inside_building: None,
1344            tile_id: None,
1345            paperdoll_ref: None,
1346            draw_scale: 1.0,
1347            presentation_state: None,
1348            sprite_mode: None,
1349            progression_xp: None,
1350            combat_cues: Vec::new(),
1351            statuses: Vec::new(),
1352        }];
1353        state.player = state.entities.first().cloned();
1354        let view = WorldView::build_with_target(&state, 9, 9, None);
1355        let flat = view.cells.join("");
1356        assert!(flat.contains('~'), "expected well water: {flat}");
1357        assert!(flat.contains('O'), "expected well center: {flat}");
1358    }
1359
1360    #[test]
1361    fn broker_hut_draws_wall_outline() {
1362        let building = BuildingView {
1363            id: "broker_hut".into(),
1364            label: "Broker's Hut".into(),
1365            x: 148.0,
1366            y: 118.0,
1367            width_m: 8.0,
1368            depth_m: 6.0,
1369            interior_blueprint: None,
1370            tags: vec![],
1371            market_boundary_zone_ids: vec![],
1372            market_max_volume: None,
1373            wall_set: None,
1374            roof_set: None,
1375        };
1376        let mut state = state_with_building(building);
1377        state.player = state.entities.first().cloned();
1378        let view = WorldView::build_with_target(&state, 25, 15, None);
1379        let flat = view.cells.join("");
1380        assert!(flat.contains('+'), "expected corners: {flat}");
1381        assert!(flat.contains('-'), "expected horiz walls: {flat}");
1382        assert!(flat.contains('|'), "expected vert walls: {flat}");
1383    }
1384
1385    #[test]
1386    fn interior_map_renders_rooms_and_walls() {
1387        use flatland_protocol::{InteriorMapView, InteriorRoomView};
1388        let building = BuildingView {
1389            id: "broker_hut".into(),
1390            label: "Broker's Hut".into(),
1391            x: 148.0,
1392            y: 118.0,
1393            width_m: 8.0,
1394            depth_m: 6.0,
1395            interior_blueprint: Some("broker_hut".into()),
1396            tags: vec![],
1397            market_boundary_zone_ids: vec![],
1398            market_max_volume: None,
1399            wall_set: None,
1400            roof_set: None,
1401        };
1402        let mut state = state_with_building(building);
1403        state.interior_map = Some(InteriorMapView {
1404            building_id: "broker_hut".into(),
1405            blueprint_id: "broker_hut".into(),
1406            background_color: "#000000".into(),
1407            default_floor_color: Some("#2a2a2a".into()),
1408            floor_height_m: 3.0,
1409            z_platforms: vec![],
1410            z_transitions: vec![],
1411            rooms: vec![InteriorRoomView {
1412                id: "main".into(),
1413                label: "Main".into(),
1414                floor: 0,
1415                x0: 0.0,
1416                y0: 0.0,
1417                x1: 8.5,
1418                y1: 7.0,
1419                floor_color: None,
1420                floor_glyph: None,
1421            }],
1422            room_doors: vec![],
1423        });
1424        state.entities = vec![EntityState {
1425            id: 1,
1426            label: "You".into(),
1427            transform: Transform {
1428                position: WorldCoord::surface(4.0, 3.0),
1429                yaw: 0.0,
1430                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1431            },
1432            vitals: Some(PlayerVitals::default()),
1433            attributes: Some(PrimaryAttributes::default()),
1434            skills: Some(flatland_protocol::PlayerSkills::default()),
1435            inside_building: Some("broker_hut".into()),
1436            tile_id: None,
1437            paperdoll_ref: None,
1438            draw_scale: 1.0,
1439            presentation_state: None,
1440            sprite_mode: None,
1441            progression_xp: None,
1442            combat_cues: Vec::new(),
1443            statuses: Vec::new(),
1444        }];
1445        state.player = state.entities.first().cloned();
1446        let view = WorldView::build_with_target(&state, 25, 15, None);
1447        assert_eq!(view.inside_building.as_deref(), Some("broker_hut"));
1448        let flat = view.cells.join("");
1449        assert!(flat.contains('+'), "expected interior walls: {flat}");
1450        assert!(flat.contains('@'), "expected player marker: {flat}");
1451    }
1452
1453    #[test]
1454    fn stale_interior_map_renders_outdoor_when_outside() {
1455        use flatland_protocol::{InteriorMapView, InteriorRoomView};
1456        let building = BuildingView {
1457            id: "town_hall".into(),
1458            label: "Town Hall".into(),
1459            x: 163.0,
1460            y: 137.0,
1461            width_m: 20.0,
1462            depth_m: 10.0,
1463            interior_blueprint: Some("town_hall".into()),
1464            tags: vec![],
1465            market_boundary_zone_ids: vec![],
1466            market_max_volume: None,
1467            wall_set: None,
1468            roof_set: None,
1469        };
1470        let mut state = state_with_building(building);
1471        state.interior_map = Some(InteriorMapView {
1472            building_id: "town_hall".into(),
1473            blueprint_id: "town_hall".into(),
1474            background_color: "#000000".into(),
1475            default_floor_color: Some("#2a2a2a".into()),
1476            floor_height_m: 3.0,
1477            z_platforms: vec![],
1478            z_transitions: vec![],
1479            rooms: vec![InteriorRoomView {
1480                id: "main_hall".into(),
1481                label: "Main".into(),
1482                floor: 0,
1483                x0: -3.5,
1484                y0: -8.0,
1485                x1: 18.5,
1486                y1: 6.0,
1487                floor_color: None,
1488                floor_glyph: None,
1489            }],
1490            room_doors: vec![],
1491        });
1492        state.player = state.entities.first().cloned();
1493        let view = WorldView::build_with_target(&state, 25, 15, None);
1494        assert!(view.inside_building.is_none());
1495        let flat = view.cells.join("");
1496        let grass = map_presentation::terrain_for(TerrainKindView::Grass).glyph;
1497        assert!(
1498            flat.contains(&grass),
1499            "expected outdoor terrain, not stale interior background: {flat}"
1500        );
1501        assert!(
1502            !flat.chars().all(|c| c == ' ' || c == '@'),
1503            "stale interior_map must not paint black interior when outside"
1504        );
1505    }
1506
1507    #[test]
1508    fn stale_inside_flag_still_renders_outdoor_world() {
1509        use flatland_protocol::ResourceNodeState;
1510        let building = BuildingView {
1511            id: "broker_hut".into(),
1512            label: "Broker's Hut".into(),
1513            x: 148.0,
1514            y: 118.0,
1515            width_m: 8.0,
1516            depth_m: 6.0,
1517            interior_blueprint: None,
1518            tags: vec![],
1519            market_boundary_zone_ids: vec![],
1520            market_max_volume: None,
1521            wall_set: None,
1522            roof_set: None,
1523        };
1524        let mut state = state_with_building(building);
1525        state.entities = vec![EntityState {
1526            id: 1,
1527            label: "You".into(),
1528            transform: Transform {
1529                position: WorldCoord::surface(128.0, 128.0),
1530                yaw: 0.0,
1531                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1532            },
1533            vitals: Some(PlayerVitals::default()),
1534            attributes: Some(PrimaryAttributes::default()),
1535            skills: Some(flatland_protocol::PlayerSkills::default()),
1536            inside_building: Some("broker_hut".into()),
1537            tile_id: None,
1538            paperdoll_ref: None,
1539            draw_scale: 1.0,
1540            presentation_state: None,
1541            sprite_mode: None,
1542            progression_xp: None,
1543            combat_cues: Vec::new(),
1544            statuses: Vec::new(),
1545        }];
1546        state.player = state.entities.first().cloned();
1547        state
1548            .resource_nodes
1549            .push(flatland_protocol::ResourceNodeView {
1550                id: "oak".into(),
1551                label: "Oak".into(),
1552                x: 126.0,
1553                y: 134.0,
1554                z: 0.0,
1555                item_template: "oak_log".into(),
1556                state: ResourceNodeState::Available,
1557                blocking: true,
1558                blocking_radius_m: 0.8,
1559                harvest_off: false,
1560                tile_id: None,
1561                yaw: 0.0,
1562                pitch: 0.0,
1563                roll: 0.0,
1564                draw_scale: 1.0,
1565                sprite_mode: None,
1566                growth_progress: None,
1567                presentation_state: None,
1568                channel_start_tick: None,
1569                channel_end_tick: None,
1570                harvest_drop_templates: Vec::new(),
1571            });
1572        let view = WorldView::build_with_target(&state, 25, 15, None);
1573        assert_eq!(
1574            view.inside_building.as_deref(),
1575            Some("broker_hut"),
1576            "server inside flag is authoritative"
1577        );
1578        let flat = view.cells.join("");
1579        let oak = map_presentation::resource_for(&flatland_protocol::ResourceNodeView {
1580            id: "oak".into(),
1581            label: "Oak".into(),
1582            x: 0.0,
1583            y: 0.0,
1584            z: 0.0,
1585            item_template: "oak_log".into(),
1586            state: flatland_protocol::ResourceNodeState::Available,
1587            blocking: true,
1588            blocking_radius_m: 0.8,
1589            harvest_off: false,
1590            tile_id: None,
1591            yaw: 0.0,
1592            pitch: 0.0,
1593            roll: 0.0,
1594            draw_scale: 1.0,
1595            sprite_mode: None,
1596            growth_progress: None,
1597            presentation_state: None,
1598            channel_start_tick: None,
1599            channel_end_tick: None,
1600            harvest_drop_templates: Vec::new(),
1601        });
1602        assert!(
1603            flat.contains(&oak.glyph),
1604            "expected nearby tree ({:?}): {flat}",
1605            oak.glyph
1606        );
1607        assert!(flat.contains('@'), "expected player: {flat}");
1608    }
1609
1610    #[test]
1611    fn inside_building_flag_selects_active_instance() {
1612        let town = BuildingView {
1613            id: "town_hall".into(),
1614            label: "Town Hall".into(),
1615            x: 160.0,
1616            y: 136.0,
1617            width_m: 20.0,
1618            depth_m: 10.0,
1619            interior_blueprint: Some("town_hall".into()),
1620            tags: vec![],
1621            market_boundary_zone_ids: vec![],
1622            market_max_volume: None,
1623            wall_set: None,
1624            roof_set: None,
1625        };
1626        let guild = BuildingView {
1627            id: "guild_hall".into(),
1628            label: "Guild Hall".into(),
1629            x: 164.0,
1630            y: 152.0,
1631            width_m: 20.0,
1632            depth_m: 14.0,
1633            interior_blueprint: Some("guild_hall".into()),
1634            tags: vec![],
1635            market_boundary_zone_ids: vec![],
1636            market_max_volume: None,
1637            wall_set: None,
1638            roof_set: None,
1639        };
1640        let mut state = state_with_building(town);
1641        state.buildings.push(guild);
1642        state.entities = vec![EntityState {
1643            id: 1,
1644            label: "You".into(),
1645            transform: Transform {
1646                position: WorldCoord::surface(4.0, 3.0),
1647                yaw: 0.0,
1648                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1649            },
1650            vitals: Some(PlayerVitals::default()),
1651            attributes: Some(PrimaryAttributes::default()),
1652            skills: Some(flatland_protocol::PlayerSkills::default()),
1653            inside_building: Some("guild_hall".into()),
1654            tile_id: None,
1655            paperdoll_ref: None,
1656            draw_scale: 1.0,
1657            presentation_state: None,
1658            sprite_mode: None,
1659            progression_xp: None,
1660            combat_cues: Vec::new(),
1661            statuses: Vec::new(),
1662        }];
1663        state.player = state.entities.first().cloned();
1664        state.world_width_m = 256.0;
1665        state.world_height_m = 256.0;
1666
1667        let view = WorldView::build_with_target(&state, 25, 15, None);
1668        assert_eq!(view.inside_building.as_deref(), Some("guild_hall"));
1669    }
1670
1671    #[test]
1672    fn combat_target_marks_creature_cell() {
1673        let building = BuildingView {
1674            id: "x".into(),
1675            label: "X".into(),
1676            x: 128.0,
1677            y: 128.0,
1678            width_m: 1.0,
1679            depth_m: 1.0,
1680            interior_blueprint: None,
1681            tags: vec![],
1682            market_boundary_zone_ids: vec![],
1683            market_max_volume: None,
1684            wall_set: None,
1685            roof_set: None,
1686        };
1687        let mut state = state_with_building(building);
1688        state.entities = vec![
1689            EntityState {
1690                id: 1,
1691                label: "You".into(),
1692                transform: Transform {
1693                    position: WorldCoord::surface(100.0, 100.0),
1694                    yaw: 0.0,
1695                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1696                },
1697                vitals: Some(PlayerVitals::default()),
1698                attributes: Some(PrimaryAttributes::default()),
1699                skills: Some(flatland_protocol::PlayerSkills::default()),
1700                inside_building: None,
1701                tile_id: None,
1702                paperdoll_ref: None,
1703                draw_scale: 1.0,
1704                presentation_state: None,
1705                sprite_mode: None,
1706                progression_xp: None,
1707                combat_cues: Vec::new(),
1708                statuses: Vec::new(),
1709            },
1710            EntityState {
1711                id: 42,
1712                label: "Rabbit".into(),
1713                transform: Transform {
1714                    position: WorldCoord::surface(103.0, 100.0),
1715                    yaw: 0.0,
1716                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1717                },
1718                vitals: None,
1719                attributes: None,
1720                skills: None,
1721                inside_building: None,
1722                tile_id: None,
1723                paperdoll_ref: None,
1724                draw_scale: 1.0,
1725                presentation_state: None,
1726                sprite_mode: None,
1727                progression_xp: None,
1728                combat_cues: Vec::new(),
1729                statuses: Vec::new(),
1730            },
1731        ];
1732        state.player = state.entities.first().cloned();
1733        state.combat_target = Some(42);
1734        state.combat_target_label = Some("Rabbit".into());
1735
1736        let view = WorldView::build_with_target(&state, 25, 15, None);
1737        let marked: usize = view
1738            .target_t1_cells
1739            .iter()
1740            .chain(view.target_t2_cells.iter())
1741            .filter(|b| **b)
1742            .count();
1743        assert_eq!(marked, 1, "exactly one targeted cell");
1744        let idx = view
1745            .target_t1_cells
1746            .iter()
1747            .chain(view.target_t2_cells.iter())
1748            .position(|b| *b)
1749            .expect("target cell");
1750        assert_eq!(view.cells[idx], "R");
1751    }
1752
1753    #[test]
1754    fn combat_target_ring_prefers_live_npc_coords() {
1755        let building = BuildingView {
1756            id: "x".into(),
1757            label: "X".into(),
1758            x: 128.0,
1759            y: 128.0,
1760            width_m: 1.0,
1761            depth_m: 1.0,
1762            interior_blueprint: None,
1763            tags: vec![],
1764            market_boundary_zone_ids: vec![],
1765            market_max_volume: None,
1766            wall_set: None,
1767            roof_set: None,
1768        };
1769        let mut state = state_with_building(building);
1770        state.entities = vec![
1771            EntityState {
1772                id: 1,
1773                label: "You".into(),
1774                transform: Transform {
1775                    position: WorldCoord::surface(100.0, 100.0),
1776                    yaw: 0.0,
1777                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1778                },
1779                vitals: Some(PlayerVitals::default()),
1780                attributes: Some(PrimaryAttributes::default()),
1781                skills: Some(flatland_protocol::PlayerSkills::default()),
1782                inside_building: None,
1783                tile_id: None,
1784                paperdoll_ref: None,
1785                draw_scale: 1.0,
1786                presentation_state: None,
1787                sprite_mode: None,
1788                progression_xp: None,
1789                combat_cues: Vec::new(),
1790                statuses: Vec::new(),
1791            },
1792            EntityState {
1793                id: 42,
1794                label: "Rabbit".into(),
1795                // Stale entity transform — NPC view has the live position.
1796                transform: Transform {
1797                    position: WorldCoord::surface(90.0, 100.0),
1798                    yaw: 0.0,
1799                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1800                },
1801                vitals: None,
1802                attributes: None,
1803                skills: None,
1804                inside_building: None,
1805                tile_id: None,
1806                paperdoll_ref: None,
1807                draw_scale: 1.0,
1808                presentation_state: None,
1809                sprite_mode: None,
1810                progression_xp: None,
1811                combat_cues: Vec::new(),
1812                statuses: Vec::new(),
1813            },
1814        ];
1815        state.npcs = vec![flatland_protocol::NpcView {
1816            id: "rabbit-1".into(),
1817            label: "Rabbit".into(),
1818            role: "wildlife".into(),
1819            x: 103.0,
1820            y: 100.0,
1821            building_id: None,
1822            entity_id: Some(42),
1823            life_state: Some(flatland_protocol::LifeState::Alive),
1824            hp_pct: Some(1.0),
1825            can_trade: false,
1826            buy_templates: Vec::new(),
1827            tile_id: None,
1828            behavior_state: None,
1829            presentation_state: None,
1830            sprite_mode: None,
1831            paperdoll_ref: None,
1832            draw_scale: 1.0,
1833            yaw: None,
1834            perception_fov_deg: None,
1835            perception_sight_m: None,
1836            perception_hear_m: None,
1837        }];
1838        state.player = state.entities.first().cloned();
1839        state.combat_target = Some(42);
1840
1841        let view = WorldView::build_with_target(&state, 25, 15, None);
1842        let marked = view
1843            .target_t1_cells
1844            .iter()
1845            .position(|b| *b)
1846            .expect("target cell");
1847        let half_w = (view.width / 2) as i32;
1848        let half_h = (view.height / 2) as i32;
1849        let (live_gx, live_gy) = world_to_grid(
1850            103.0,
1851            100.0,
1852            100.0,
1853            100.0,
1854            half_w,
1855            half_h,
1856            view.width,
1857            view.height,
1858        )
1859        .expect("live npc in view");
1860        let (stale_gx, stale_gy) = world_to_grid(
1861            90.0,
1862            100.0,
1863            100.0,
1864            100.0,
1865            half_w,
1866            half_h,
1867            view.width,
1868            view.height,
1869        )
1870        .expect("stale entity in view");
1871        let live_idx = live_gy * view.width + live_gx;
1872        let stale_idx = stale_gy * view.width + stale_gx;
1873        assert_eq!(marked, live_idx, "ring must follow live NPC coords");
1874        assert_ne!(
1875            marked, stale_idx,
1876            "ring must not stay on stale entity coords"
1877        );
1878    }
1879
1880    #[test]
1881    fn grid_to_world_roundtrips_center() {
1882        let px = 10.0;
1883        let py = 20.0;
1884        let view_w = 11;
1885        let view_h = 11;
1886        let half_w = (view_w / 2) as i32;
1887        let half_h = (view_h / 2) as i32;
1888        let (gx, gy) =
1889            world_to_grid(12.0, 18.0, px, py, half_w, half_h, view_w, view_h).expect("in view");
1890        let (wx, wy) = grid_to_world(gx, gy, px, py, view_w, view_h).expect("inverse");
1891        assert!((wx - 12.0).abs() < 0.01);
1892        assert!((wy - 18.0).abs() < 0.01);
1893    }
1894
1895    #[test]
1896    fn vertical_axis_quantizes_to_one_meter() {
1897        let px = 0.0;
1898        let py = 0.0;
1899        let view_w = 21;
1900        let view_h = 21;
1901        let half_w = (view_w / 2) as i32;
1902        let half_h = (view_h / 2) as i32;
1903        let (gx, gy) =
1904            world_to_grid(3.0, 3.0, px, py, half_w, half_h, view_w, view_h).expect("in view");
1905        let (wx, wy) = grid_to_world(gx, gy, px, py, view_w, view_h).expect("inverse");
1906        assert!(
1907            (wx - 3.0).abs() < 0.01,
1908            "x should stay exact to 1m: got {wx}"
1909        );
1910        assert!(
1911            (wy - 3.0).abs() < 0.01,
1912            "y should stay exact to 1m: got {wy}"
1913        );
1914    }
1915
1916    #[test]
1917    fn square_extent_spans_equal_rows_and_columns() {
1918        let px = 0.0;
1919        let py = 0.0;
1920        let half_w = 50;
1921        let half_h = 50;
1922        let width = 101;
1923        let height = 101;
1924        let (gx0, gy0) =
1925            world_to_grid(-4.0, -4.0, px, py, half_w, half_h, width, height).expect("in view");
1926        let (gx1, gy1) =
1927            world_to_grid(4.0, 4.0, px, py, half_w, half_h, width, height).expect("in view");
1928        let cols_spanned = (gx1 as i32 - gx0 as i32).unsigned_abs();
1929        let rows_spanned = (gy1 as i32 - gy0 as i32).unsigned_abs();
1930        assert_eq!(cols_spanned, 8, "8m wide should span 8 columns");
1931        assert_eq!(rows_spanned, 8, "8m tall should span 8 rows");
1932    }
1933
1934    #[test]
1935    fn resource_paints_on_terrain_cell_for_same_world_coords() {
1936        use flatland_protocol::{ResourceNodeState, ResourceNodeView, TerrainZoneView};
1937
1938        let px = 128.0;
1939        let py = 128.0;
1940        let rx = 131.0;
1941        let ry = 132.0;
1942        let mut state = state_with_building(BuildingView {
1943            id: "x".into(),
1944            label: "X".into(),
1945            x: 128.0,
1946            y: 128.0,
1947            width_m: 1.0,
1948            depth_m: 1.0,
1949            interior_blueprint: None,
1950            tags: vec![],
1951            market_boundary_zone_ids: vec![],
1952            market_max_volume: None,
1953            wall_set: None,
1954            roof_set: None,
1955        });
1956        state.terrain_zones.push(TerrainZoneView {
1957            id: "pond".into(),
1958            x0: rx,
1959            y0: ry,
1960            x1: rx + 1.0,
1961            y1: ry + 1.0,
1962            kind: TerrainKindView::ShallowWater,
1963            elevation: -0.5,
1964            glyph: None,
1965            color: None,
1966            tile_id: None,
1967            z_order: 0,
1968            channel_start_tick: None,
1969            channel_end_tick: None,
1970        });
1971        state.resource_nodes.push(ResourceNodeView {
1972            id: "oak".into(),
1973            label: "Oak".into(),
1974            x: rx,
1975            y: ry,
1976            z: 0.0,
1977            item_template: "oak_log".into(),
1978            state: ResourceNodeState::Available,
1979            blocking: true,
1980            blocking_radius_m: 0.8,
1981            harvest_off: false,
1982            tile_id: None,
1983            yaw: 0.0,
1984            pitch: 0.0,
1985            roll: 0.0,
1986            draw_scale: 1.0,
1987            sprite_mode: None,
1988            growth_progress: None,
1989            presentation_state: None,
1990            channel_start_tick: None,
1991            channel_end_tick: None,
1992            harvest_drop_templates: Vec::new(),
1993        });
1994        state.entities[0].transform.position = WorldCoord::surface(px, py);
1995        state.player = state.entities.first().cloned();
1996
1997        let view = WorldView::build_with_target(&state, 25, 15, None);
1998        let half_w = (view.width / 2) as i32;
1999        let half_h = (view.height / 2) as i32;
2000        let (gx, gy) = world_to_grid(rx, ry, px, py, half_w, half_h, view.width, view.height)
2001            .expect("resource in view");
2002        let idx = gy * view.width + gx;
2003        let oak = map_presentation::resource_for(&state.resource_nodes[0]);
2004        assert_eq!(
2005            view.cells[idx], oak.glyph,
2006            "resource should paint on the grid cell for its world coords"
2007        );
2008        let (wx, wy) = grid_to_world(gx, gy, px, py, view.width, view.height).expect("inverse");
2009        assert!(
2010            (wx - rx).abs() < 0.01 && (wy - ry).abs() < 0.01,
2011            "resource grid cell should sample terrain at ({wx}, {wy}), expected ({rx}, {ry})"
2012        );
2013    }
2014
2015    #[test]
2016    fn chest_and_loot_paint_on_non_grass_terrain() {
2017        use flatland_protocol::{GroundDropView, PlacedContainerView, TerrainZoneView};
2018
2019        let px = 50.0;
2020        let py = 50.0;
2021        let cx = 53.0;
2022        let cy = 52.0;
2023        let lx = 54.0;
2024        let ly = 52.0;
2025        let mut state = state_with_building(BuildingView {
2026            id: "x".into(),
2027            label: "X".into(),
2028            x: 50.0,
2029            y: 50.0,
2030            width_m: 1.0,
2031            depth_m: 1.0,
2032            interior_blueprint: None,
2033            tags: vec![],
2034            market_boundary_zone_ids: vec![],
2035            market_max_volume: None,
2036            wall_set: None,
2037            roof_set: None,
2038        });
2039        state.terrain_zones.push(TerrainZoneView {
2040            id: "trail".into(),
2041            x0: 52.0,
2042            y0: 51.0,
2043            x1: 56.0,
2044            y1: 54.0,
2045            kind: TerrainKindView::Trail,
2046            elevation: 0.0,
2047            glyph: None,
2048            color: None,
2049            tile_id: None,
2050            z_order: 0,
2051            channel_start_tick: None,
2052            channel_end_tick: None,
2053        });
2054        state.placed_containers.push(PlacedContainerView {
2055            id: "chest_1".into(),
2056            template_id: "wood_chest".into(),
2057            display_name: "Storage".into(),
2058            x: cx,
2059            y: cy,
2060            z: 0.0,
2061            locked: false,
2062            accessible: true,
2063            owner_character_id: None,
2064            contents: vec![],
2065            lock_id: None,
2066            capacity_volume: Some(40.0),
2067            item_instance_id: None,
2068            tile_id: None,
2069            worker_lodging_capacity: None,
2070            blocking: true,
2071            blocking_radius_m: 0.8,
2072            building_id: None,
2073        });
2074        state.ground_drops.push(GroundDropView {
2075            id: "drop_1".into(),
2076            template_id: "lumber".into(),
2077            quantity: 2,
2078            x: lx,
2079            y: ly,
2080            z: 0.0,
2081            tile_id: None,
2082            display_name: None,
2083            yaw: 0.0,
2084            pitch: 0.0,
2085            roll: 0.0,
2086            draw_scale: 1.0,
2087        });
2088        state.entities[0].transform.position = WorldCoord::surface(px, py);
2089        state.player = state.entities.first().cloned();
2090
2091        let view = WorldView::build_with_target(&state, 25, 15, None);
2092        let half_w = (view.width / 2) as i32;
2093        let half_h = (view.height / 2) as i32;
2094        let (gx, gy) =
2095            world_to_grid(cx, cy, px, py, half_w, half_h, view.width, view.height).expect("chest");
2096        let chest = map_presentation::chest_presentation(false);
2097        assert_eq!(
2098            view.cells[gy * view.width + gx],
2099            chest.glyph,
2100            "chest must paint on trail/non-grass cells"
2101        );
2102        let (gx2, gy2) =
2103            world_to_grid(lx, ly, px, py, half_w, half_h, view.width, view.height).expect("loot");
2104        let loot = map_presentation::loot_presentation();
2105        assert_eq!(
2106            view.cells[gy2 * view.width + gx2],
2107            loot.glyph,
2108            "ground loot must paint on trail/non-grass cells"
2109        );
2110    }
2111
2112    #[test]
2113    fn build_with_anchor_sets_view_origin() {
2114        let mut state = state_with_building(BuildingView {
2115            id: "x".into(),
2116            label: "X".into(),
2117            x: 128.0,
2118            y: 128.0,
2119            width_m: 1.0,
2120            depth_m: 1.0,
2121            interior_blueprint: None,
2122            tags: vec![],
2123            market_boundary_zone_ids: vec![],
2124            market_max_volume: None,
2125            wall_set: None,
2126            roof_set: None,
2127        });
2128        state.entities[0].transform.position = WorldCoord::surface(100.0, 200.0);
2129        state.player = state.entities.first().cloned();
2130        let view = WorldView::build_with_anchor(
2131            &state,
2132            21,
2133            15,
2134            12.3,
2135            40.7,
2136            None,
2137            WorldViewOptions::terrain_only(),
2138        );
2139        assert!((view.origin_x - 12.3).abs() < 0.01);
2140        assert!((view.origin_y - 40.7).abs() < 0.01);
2141    }
2142
2143    #[test]
2144    fn skip_local_player_glyph_when_paint_local_player_false() {
2145        let mut state = state_with_building(BuildingView {
2146            id: "x".into(),
2147            label: "X".into(),
2148            x: 10.0,
2149            y: 10.0,
2150            width_m: 1.0,
2151            depth_m: 1.0,
2152            interior_blueprint: None,
2153            tags: vec![],
2154            market_boundary_zone_ids: vec![],
2155            market_max_volume: None,
2156            wall_set: None,
2157            roof_set: None,
2158        });
2159        state.entities[0].transform.position = WorldCoord::surface(128.0, 128.0);
2160        state.player = state.entities.first().cloned();
2161        let player_glyph = map_presentation::player_presentation().glyph;
2162
2163        let with_player =
2164            WorldView::build_with_options(&state, 21, 15, None, WorldViewOptions::default());
2165        let cx = with_player.width / 2;
2166        let cy = with_player.height / 2;
2167        assert_eq!(
2168            with_player.cells[cy * with_player.width + cx],
2169            player_glyph,
2170            "default build paints @"
2171        );
2172
2173        let without =
2174            WorldView::build_with_options(&state, 21, 15, None, WorldViewOptions::terrain_only());
2175        assert_ne!(
2176            without.cells[cy * without.width + cx],
2177            player_glyph,
2178            "gfx sprite mode must not paint local player @"
2179        );
2180    }
2181
2182    fn town_hall_state(px: f32, py: f32) -> GameState {
2183        use flatland_protocol::{InteriorMapView, InteriorRoomView};
2184        let mut state = state_with_building(BuildingView {
2185            id: "town_hall".into(),
2186            label: "Town Hall".into(),
2187            x: 156.0,
2188            y: 153.0,
2189            width_m: 20.0,
2190            depth_m: 9.0,
2191            interior_blueprint: Some("town_hall".into()),
2192            tags: vec![],
2193            market_boundary_zone_ids: vec![],
2194            market_max_volume: None,
2195            wall_set: None,
2196            roof_set: None,
2197        });
2198        state.interior_map = Some(InteriorMapView {
2199            building_id: "town_hall".into(),
2200            blueprint_id: "town_hall".into(),
2201            background_color: "#000".into(),
2202            default_floor_color: Some("#2a2a2a".into()),
2203            floor_height_m: 3.0,
2204            z_platforms: vec![],
2205            z_transitions: vec![],
2206            rooms: vec![
2207                InteriorRoomView {
2208                    id: "main".into(),
2209                    label: "Main".into(),
2210                    floor: 0,
2211                    x0: -3.5,
2212                    y0: -8.0,
2213                    x1: 18.5,
2214                    y1: 6.0,
2215                    floor_color: None,
2216                    floor_glyph: None,
2217                },
2218                InteriorRoomView {
2219                    id: "kitchen".into(),
2220                    label: "Kitchen".into(),
2221                    floor: 0,
2222                    x0: 18.5,
2223                    y0: -8.0,
2224                    x1: 23.5,
2225                    y1: 0.0,
2226                    floor_color: None,
2227                    floor_glyph: None,
2228                },
2229                InteriorRoomView {
2230                    id: "weapon".into(),
2231                    label: "Weapon".into(),
2232                    floor: 0,
2233                    x0: 18.5,
2234                    y0: 0.0,
2235                    x1: 25.5,
2236                    y1: 12.5,
2237                    floor_color: None,
2238                    floor_glyph: None,
2239                },
2240                InteriorRoomView {
2241                    id: "hall_n".into(),
2242                    label: "Hall N".into(),
2243                    floor: 0,
2244                    x0: -3.5,
2245                    y0: 6.0,
2246                    x1: 12.0,
2247                    y1: 12.5,
2248                    floor_color: None,
2249                    floor_glyph: None,
2250                },
2251                InteriorRoomView {
2252                    id: "meeting".into(),
2253                    label: "Meeting".into(),
2254                    floor: 0,
2255                    x0: -3.5,
2256                    y0: 12.5,
2257                    x1: 12.0,
2258                    y1: 23.5,
2259                    floor_color: None,
2260                    floor_glyph: None,
2261                },
2262                InteriorRoomView {
2263                    id: "office".into(),
2264                    label: "Office".into(),
2265                    floor: 0,
2266                    x0: 12.0,
2267                    y0: 6.0,
2268                    x1: 18.5,
2269                    y1: 12.5,
2270                    floor_color: None,
2271                    floor_glyph: None,
2272                },
2273            ],
2274            room_doors: vec![],
2275        });
2276        state.entities[0].transform.position = WorldCoord::surface(px, py);
2277        state.entities[0].inside_building = Some("town_hall".into());
2278        state.player = state.entities.first().cloned();
2279        state
2280    }
2281
2282    /// Outer perimeter walls (east/south edges at half-meter coords) must paint even
2283    /// when the wall glyph cell sits outside every room's floor fill (background void).
2284    #[test]
2285    fn outer_perimeter_walls_render_at_positive_anchor() {
2286        let state = town_hall_state(20.0, 6.0);
2287        let view = WorldView::build_with_anchor(
2288            &state,
2289            31,
2290            31,
2291            20.0,
2292            6.0,
2293            None,
2294            WorldViewOptions::terrain_only(),
2295        );
2296        let cell = |x: i32, y: i32| {
2297            let (gx, gy) = world_to_grid(
2298                x as f32,
2299                y as f32,
2300                20.0,
2301                6.0,
2302                15,
2303                15,
2304                view.width,
2305                view.height,
2306            )
2307            .expect("in view");
2308            view.cells[gy * view.width + gx].clone()
2309        };
2310        // Weapon shack east wall (x=25.5 → glyph col 26) on a mid-room row and at the
2311        // top-wall corner (row 13) — the corner cell is background void otherwise.
2312        assert!(
2313            is_wall(&cell(26, 9)),
2314            "weapon east wall at (26,9): {}",
2315            cell(26, 9)
2316        );
2317        assert!(
2318            cell(26, 13) == "+" || cell(26, 13) == "-" || cell(26, 13) == "|",
2319            "top wall east corner (26,13): {}",
2320            cell(26, 13)
2321        );
2322        // Small office east wall (x=18.5 → glyph col 19) on a mid-row.
2323        assert!(
2324            is_wall(&cell(19, 9)),
2325            "office east wall at (19,9): {}",
2326            cell(19, 9)
2327        );
2328        // Kitchen east wall (x=23.5 → glyph col 24) on a mid-row.
2329        assert!(
2330            is_wall(&cell(24, -4)),
2331            "kitchen east wall at (24,-4): {}",
2332            cell(24, -4)
2333        );
2334        // Bottom wall spans the merged kitchen+main hall width incl. the kitchen east corner.
2335        assert!(
2336            cell(24, -8) == "+" || cell(24, -8) == "-" || cell(24, -8) == "|",
2337            "bottom wall kitchen-east corner (24,-8): {}",
2338            cell(24, -8)
2339        );
2340        // Top wall spans the full merged width to the weapon east corner (x=26, row 13).
2341        assert!(
2342            cell(12, 13) == "+" || cell(12, 13) == "-" || cell(12, 13) == "|",
2343            "top wall at (12,13): {}",
2344            cell(12, 13)
2345        );
2346    }
2347}