Skip to main content

flatland_client_ui/
world.rs

1use crate::color::RgbColor;
2use flatland_client_lib::GameState;
3use flatland_protocol::{BuildingView, InteriorMapView, TerrainKindView};
4
5use crate::map_presentation::{self, MapPresentation};
6
7/// The TUI map uses one terminal cell per world meter on both axes so terrain, entities,
8/// resources, and mouse targeting share the same grid. Terminal fonts are taller than wide,
9/// so buildings look vertically stretched compared to the content-admin editor.
10
11pub struct WorldView {
12    pub width: usize,
13    pub height: usize,
14    pub cells: Vec<String>,
15    /// Per-cell foreground color from presentation catalog (None = entity-specific style).
16    pub cell_fg: Vec<Option<RgbColor>>,
17    /// T1 target ring (red).
18    pub target_t1_cells: Vec<bool>,
19    /// T2 target ring (blue).
20    pub target_t2_cells: Vec<bool>,
21    pub origin_x: f32,
22    pub origin_y: f32,
23    pub inside_building: Option<String>,
24}
25
26/// Presentation flags for [`WorldView::build_with_options`].
27#[derive(Debug, Clone, Copy)]
28pub struct WorldViewOptions {
29    /// Paint local player `@` at view center (TUI). Gfx uses a sprite instead.
30    pub paint_local_player: bool,
31    /// Paint NPCs, resources, loot, chests, quest boards, entities into the cell grid.
32    /// Gfx sets this false and draws those at continuous world coordinates.
33    pub paint_overlays: bool,
34}
35
36impl Default for WorldViewOptions {
37    fn default() -> Self {
38        Self {
39            paint_local_player: true,
40            paint_overlays: true,
41        }
42    }
43}
44
45impl WorldViewOptions {
46    /// Terrain / walls only — gfx draws movers at precise x,y.
47    pub fn terrain_only() -> Self {
48        Self {
49            paint_local_player: false,
50            paint_overlays: false,
51        }
52    }
53}
54
55impl WorldView {
56    pub fn build_with_target(
57        state: &GameState,
58        view_w: usize,
59        view_h: usize,
60        map_target: Option<(f32, f32)>,
61    ) -> Self {
62        Self::build_with_options(
63            state,
64            view_w,
65            view_h,
66            map_target,
67            WorldViewOptions::default(),
68        )
69    }
70
71    /// Like [`build_with_target`] with gfx/TUI presentation flags.
72    pub fn build_with_options(
73        state: &GameState,
74        view_w: usize,
75        view_h: usize,
76        map_target: Option<(f32, f32)>,
77        options: WorldViewOptions,
78    ) -> Self {
79        let (px, py) = state.player_position();
80        Self::build_with_anchor(state, view_w, view_h, px, py, map_target, options)
81    }
82
83    /// Build a view anchored at explicit world coordinates (gfx uses smoothed camera).
84    pub fn build_with_anchor(
85        state: &GameState,
86        view_w: usize,
87        view_h: usize,
88        anchor_x: f32,
89        anchor_y: f32,
90        map_target: Option<(f32, f32)>,
91        options: WorldViewOptions,
92    ) -> Self {
93        map_presentation::maybe_reload_for_content_rev(state.content_rev);
94        let px = anchor_x;
95        let py = anchor_y;
96        let inside_building = state.effective_inside_building();
97
98        let width = view_w.max(3);
99        let height = view_h.max(3);
100        let grass = map_presentation::terrain_for(TerrainKindView::Grass);
101        let mut cells = vec![grass.glyph.clone(); width * height];
102        let mut cell_fg = vec![Some(grass.color); width * height];
103
104        let half_w = (width / 2) as i32;
105        let half_h = (height / 2) as i32;
106
107        // Interior rendering is authoritative from `inside_building`, not stale `interior_map`.
108        if let (Some(_bid), Some(interior)) =
109            (inside_building.as_deref(), state.interior_map.as_ref())
110        {
111            paint_interior_background(&mut cells, &mut cell_fg, width, height, interior);
112            paint_interior_rooms(
113                &mut cells,
114                &mut cell_fg,
115                width,
116                height,
117                interior,
118                px,
119                py,
120                half_w,
121                half_h,
122            );
123            let door_gaps = interior_door_gaps(interior, &state.doors);
124            for room in &interior.rooms {
125                paint_building_walls(
126                    &mut cells,
127                    &mut cell_fg,
128                    width,
129                    height,
130                    room.x0,
131                    room.y0,
132                    room.x1 - room.x0,
133                    room.y1 - room.y0,
134                    px,
135                    py,
136                    half_w,
137                    half_h,
138                    &door_gaps,
139                );
140            }
141        } else {
142            paint_terrain(
143                &mut cells,
144                &mut cell_fg,
145                width,
146                height,
147                state,
148                px,
149                py,
150                half_w,
151                half_h,
152            );
153
154            for building in &state.buildings {
155                if building.tags.iter().any(|t| t == "well") {
156                    paint_well(
157                        &mut cells,
158                        &mut cell_fg,
159                        width,
160                        height,
161                        building,
162                        px,
163                        py,
164                        half_w,
165                        half_h,
166                    );
167                } else {
168                    paint_building_walls_centered(
169                        &mut cells,
170                        &mut cell_fg,
171                        width,
172                        height,
173                        building,
174                        px,
175                        py,
176                        half_w,
177                        half_h,
178                    );
179                }
180            }
181        }
182
183        if options.paint_overlays {
184            for door in &state.doors {
185                if let Some((gx, gy)) =
186                    world_to_grid(door.x, door.y, px, py, half_w, half_h, width, height)
187                {
188                    let idx = gy * width + gx;
189                    paint_presentation(
190                        &mut cells,
191                        &mut cell_fg,
192                        idx,
193                        &map_presentation::door_presentation(door.open),
194                    );
195                }
196            }
197
198            for npc in &state.npcs {
199                if let Some((gx, gy)) =
200                    world_to_grid(npc.x, npc.y, px, py, half_w, half_h, width, height)
201                {
202                    let idx = gy * width + gx;
203                    paint_presentation(
204                        &mut cells,
205                        &mut cell_fg,
206                        idx,
207                        &map_presentation::npc_for(npc),
208                    );
209                }
210            }
211
212            let ground = empty_ground_glyph();
213            let player_glyph = map_presentation::player_presentation().glyph;
214            for node in &state.resource_nodes {
215                if let Some((gx, gy)) =
216                    world_to_grid(node.x, node.y, px, py, half_w, half_h, width, height)
217                {
218                    let idx = gy * width + gx;
219                    let pres = map_presentation::resource_for(node);
220                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
221                        paint_presentation(&mut cells, &mut cell_fg, idx, &pres);
222                    }
223                }
224            }
225
226            for drop in &state.ground_drops {
227                if let Some((gx, gy)) =
228                    world_to_grid(drop.x, drop.y, px, py, half_w, half_h, width, height)
229                {
230                    let idx = gy * width + gx;
231                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
232                        paint_presentation(
233                            &mut cells,
234                            &mut cell_fg,
235                            idx,
236                            &map_presentation::loot_presentation(),
237                        );
238                    }
239                }
240            }
241
242            for chest in &state.placed_containers {
243                if let Some((gx, gy)) =
244                    world_to_grid(chest.x, chest.y, px, py, half_w, half_h, width, height)
245                {
246                    let idx = gy * width + gx;
247                    if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
248                        paint_presentation(
249                            &mut cells,
250                            &mut cell_fg,
251                            idx,
252                            &map_presentation::chest_presentation(chest.locked),
253                        );
254                    }
255                }
256            }
257
258            if state.effective_inside_building().is_none() {
259                for inter in &state.interactables {
260                    if inter.kind != "quest_board" {
261                        continue;
262                    }
263                    if let Some((gx, gy)) =
264                        world_to_grid(inter.x, inter.y, px, py, half_w, half_h, width, height)
265                    {
266                        let idx = gy * width + gx;
267                        if can_paint_world_object(&cells[idx], &ground, &player_glyph) {
268                            paint_presentation(
269                                &mut cells,
270                                &mut cell_fg,
271                                idx,
272                                &map_presentation::quest_board_presentation(),
273                            );
274                        }
275                    }
276                }
277            }
278
279            for entity in &state.entities {
280                // When gfx draws a sprite for the local player, omit the `@` glyph.
281                if !options.paint_local_player && entity.id == state.entity_id {
282                    continue;
283                }
284                if let Some(pres) = entity_presentation(entity, state.entity_id) {
285                    if let Some((gx, gy)) = world_to_grid(
286                        entity.transform.position.x,
287                        entity.transform.position.y,
288                        px,
289                        py,
290                        half_w,
291                        half_h,
292                        width,
293                        height,
294                    ) {
295                        let idx = gy * width + gx;
296                        paint_presentation(&mut cells, &mut cell_fg, idx, &pres);
297                    }
298                }
299            }
300        }
301
302        if options.paint_local_player {
303            if state.player_entity().is_some() {
304                let cx = half_w as usize;
305                let cy = half_h as usize;
306                let idx = cy * width + cx;
307                if idx < cells.len() {
308                    paint_presentation(
309                        &mut cells,
310                        &mut cell_fg,
311                        idx,
312                        &map_presentation::player_presentation(),
313                    );
314                }
315            }
316        }
317
318        let mut target_t1_cells = vec![false; cells.len()];
319        let mut target_t2_cells = vec![false; cells.len()];
320        if options.paint_overlays {
321            for (slot, cells_out) in [(1, &mut target_t1_cells), (2, &mut target_t2_cells)] {
322                let target_id = state
323                    .combat_slots
324                    .iter()
325                    .find(|s| s.slot_index == slot)
326                    .and_then(|s| s.target_entity_id)
327                    .or_else(|| if slot == 1 { state.combat_target } else { None });
328                let Some(target_id) = target_id else {
329                    continue;
330                };
331                if let Some(entity) = state.entities.iter().find(|e| e.id == target_id) {
332                    if let Some((gx, gy)) = world_to_grid(
333                        entity.transform.position.x,
334                        entity.transform.position.y,
335                        px,
336                        py,
337                        half_w,
338                        half_h,
339                        width,
340                        height,
341                    ) {
342                        let idx = gy * width + gx;
343                        if idx < cells_out.len() {
344                            cells_out[idx] = true;
345                        }
346                    }
347                }
348            }
349        }
350
351        if options.paint_overlays {
352            if let Some((tx, ty)) = map_target {
353                if let Some((gx, gy)) = world_to_grid(tx, ty, px, py, half_w, half_h, width, height)
354                {
355                    let idx = gy * width + gx;
356                    if idx < cells.len() {
357                        cells[idx] = "X".into();
358                        cell_fg[idx] = Some(RgbColor::YELLOW);
359                    }
360                }
361            }
362        }
363
364        Self {
365            width,
366            height,
367            cells,
368            cell_fg,
369            target_t1_cells,
370            target_t2_cells,
371            origin_x: px,
372            origin_y: py,
373            inside_building,
374        }
375    }
376}
377
378fn paint_presentation(
379    cells: &mut [String],
380    cell_fg: &mut [Option<RgbColor>],
381    idx: usize,
382    pres: &MapPresentation,
383) {
384    cells[idx] = pres.glyph.clone();
385    cell_fg[idx] = Some(pres.color);
386}
387
388fn empty_ground_glyph() -> String {
389    map_presentation::terrain_for(TerrainKindView::Grass).glyph
390}
391
392fn entity_presentation(
393    entity: &flatland_protocol::EntityState,
394    player_id: u64,
395) -> Option<MapPresentation> {
396    if entity.id == player_id {
397        return Some(map_presentation::player_presentation());
398    }
399    if entity
400        .vitals
401        .as_ref()
402        .is_some_and(|v| v.life_state == flatland_protocol::LifeState::Dead)
403    {
404        return Some(map_presentation::corpse_presentation());
405    }
406    Some(map_presentation::entity_fallback(&entity.label))
407}
408
409fn paint_interior_background(
410    cells: &mut [String],
411    cell_fg: &mut [Option<RgbColor>],
412    _width: usize,
413    _height: usize,
414    interior: &InteriorMapView,
415) {
416    let bg = crate::color::parse_color(&interior.background_color).unwrap_or(RgbColor::BLACK);
417    for idx in 0..cells.len() {
418        cells[idx] = " ".into();
419        cell_fg[idx] = Some(bg);
420    }
421}
422
423fn paint_interior_rooms(
424    cells: &mut [String],
425    cell_fg: &mut [Option<RgbColor>],
426    width: usize,
427    height: usize,
428    interior: &InteriorMapView,
429    px: f32,
430    py: f32,
431    half_w: i32,
432    half_h: i32,
433) {
434    let default_color = interior
435        .default_floor_color
436        .as_deref()
437        .and_then(crate::color::parse_color)
438        .unwrap_or(RgbColor::rgb(0x2a, 0x2a, 0x2a));
439    for room in &interior.rooms {
440        let floor_color = room
441            .floor_color
442            .as_deref()
443            .and_then(crate::color::parse_color)
444            .unwrap_or(default_color);
445        let glyph = room.floor_glyph.as_deref().unwrap_or(".").to_string();
446        let x0 = room.x0.floor() as i32;
447        let y0 = room.y0.floor() as i32;
448        let x1 = room.x1.ceil() as i32 - 1;
449        let y1 = room.y1.ceil() as i32 - 1;
450        for wy in y0..=y1 {
451            for wx in x0..=x1 {
452                if let Some((gx, gy)) =
453                    world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
454                {
455                    let idx = gy * width + gx;
456                    cells[idx] = glyph.clone();
457                    cell_fg[idx] = Some(floor_color);
458                }
459            }
460        }
461    }
462}
463
464fn interior_door_gaps(
465    interior: &InteriorMapView,
466    doors: &[flatland_protocol::DoorView],
467) -> Vec<(f32, f32)> {
468    let mut gaps: Vec<(f32, f32)> = interior
469        .room_doors
470        .iter()
471        .filter_map(|d| {
472            doors
473                .iter()
474                .find(|door| door.id == d.id)
475                .filter(|door| door.open)
476                .map(|door| (door.x, door.y))
477        })
478        .collect();
479    for door in doors {
480        if door.portal.is_some() && door.open {
481            gaps.push((door.x, door.y));
482        }
483    }
484    gaps
485}
486
487fn near_door_gap(wx: i32, wy: i32, door_gaps: &[(f32, f32)]) -> bool {
488    door_gaps
489        .iter()
490        .any(|(dx, dy)| (wx as f32 - dx).abs() < 0.75 && (wy as f32 - dy).abs() < 0.75)
491}
492
493fn paint_terrain(
494    cells: &mut [String],
495    cell_fg: &mut [Option<RgbColor>],
496    width: usize,
497    height: usize,
498    state: &GameState,
499    px: f32,
500    py: f32,
501    _half_w: i32,
502    _half_h: i32,
503) {
504    for gy in 0..height {
505        for gx in 0..width {
506            let Some((wx, wy)) = grid_to_world(gx, gy, px, py, width, height) else {
507                continue;
508            };
509            let zone = state.terrain_zone_at(wx, wy);
510            let kind = zone.map(|z| z.kind).unwrap_or(TerrainKindView::Grass);
511            let elev = zone.map(|z| z.elevation).unwrap_or(0.0);
512            let style = map_presentation::terrain_for_zone(
513                kind,
514                elev,
515                zone.and_then(|z| z.glyph.as_deref()),
516                zone.and_then(|z| z.color.as_deref()),
517            );
518            let idx = gy * width + gx;
519            paint_presentation(cells, cell_fg, idx, &style);
520        }
521    }
522}
523
524fn paint_well(
525    cells: &mut [String],
526    cell_fg: &mut [Option<RgbColor>],
527    width: usize,
528    height: usize,
529    building: &BuildingView,
530    px: f32,
531    py: f32,
532    half_w: i32,
533    half_h: i32,
534) {
535    let hw = building.width_m / 2.0;
536    let hd = building.depth_m / 2.0;
537    let x0 = (building.x - hw).floor() as i32;
538    let y0 = (building.y - hd).floor() as i32;
539    let x1 = (building.x + hw).ceil() as i32 - 1;
540    let y1 = (building.y + hd).ceil() as i32 - 1;
541    let water = map_presentation::shallow_water_presentation();
542    let center = map_presentation::well_center_presentation();
543
544    for wy in y0..=y1 {
545        for wx in x0..=x1 {
546            let pres = if wx == building.x.round() as i32 && wy == building.y.round() as i32 {
547                center.clone()
548            } else {
549                water.clone()
550            };
551            if let Some((gx, gy)) =
552                world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
553            {
554                let idx = gy * width + gx;
555                if !is_wall(&cells[idx]) {
556                    paint_presentation(cells, cell_fg, idx, &pres);
557                }
558            }
559        }
560    }
561}
562
563fn paint_building_walls_centered(
564    cells: &mut [String],
565    cell_fg: &mut [Option<RgbColor>],
566    width: usize,
567    height: usize,
568    building: &BuildingView,
569    px: f32,
570    py: f32,
571    half_w: i32,
572    half_h: i32,
573) {
574    let hw = building.width_m / 2.0;
575    let hd = building.depth_m / 2.0;
576    paint_building_walls(
577        cells,
578        cell_fg,
579        width,
580        height,
581        building.x - hw,
582        building.y - hd,
583        building.width_m,
584        building.depth_m,
585        px,
586        py,
587        half_w,
588        half_h,
589        &[],
590    );
591}
592
593/// Paint perimeter walls for an axis-aligned rectangle (origin = south-west corner).
594fn paint_building_walls(
595    cells: &mut [String],
596    cell_fg: &mut [Option<RgbColor>],
597    width: usize,
598    height: usize,
599    origin_x: f32,
600    origin_y: f32,
601    width_m: f32,
602    depth_m: f32,
603    px: f32,
604    py: f32,
605    half_w: i32,
606    half_h: i32,
607    door_gaps: &[(f32, f32)],
608) {
609    let x0 = origin_x.floor() as i32;
610    let y0 = origin_y.floor() as i32;
611    let x1 = (origin_x + width_m).ceil() as i32 - 1;
612    let y1 = (origin_y + depth_m).ceil() as i32 - 1;
613
614    if x1 < x0 || y1 < y0 {
615        return;
616    }
617
618    for wx in x0..=x1 {
619        if !near_door_gap(wx, y0, door_gaps) {
620            paint_wall_cell(
621                cells, cell_fg, width, height, wx, y0, px, py, half_w, half_h, "-",
622            );
623        }
624        if !near_door_gap(wx, y1, door_gaps) {
625            paint_wall_cell(
626                cells, cell_fg, width, height, wx, y1, px, py, half_w, half_h, "-",
627            );
628        }
629    }
630    for wy in y0 + 1..y1 {
631        if !near_door_gap(x0, wy, door_gaps) {
632            paint_wall_cell(
633                cells, cell_fg, width, height, x0, wy, px, py, half_w, half_h, "|",
634            );
635        }
636        if !near_door_gap(x1, wy, door_gaps) {
637            paint_wall_cell(
638                cells, cell_fg, width, height, x1, wy, px, py, half_w, half_h, "|",
639            );
640        }
641    }
642    if !near_door_gap(x0, y0, door_gaps) {
643        paint_wall_cell(
644            cells, cell_fg, width, height, x0, y0, px, py, half_w, half_h, "+",
645        );
646    }
647    if !near_door_gap(x1, y0, door_gaps) {
648        paint_wall_cell(
649            cells, cell_fg, width, height, x1, y0, px, py, half_w, half_h, "+",
650        );
651    }
652    if !near_door_gap(x0, y1, door_gaps) {
653        paint_wall_cell(
654            cells, cell_fg, width, height, x0, y1, px, py, half_w, half_h, "+",
655        );
656    }
657    if !near_door_gap(x1, y1, door_gaps) {
658        paint_wall_cell(
659            cells, cell_fg, width, height, x1, y1, px, py, half_w, half_h, "+",
660        );
661    }
662}
663
664fn paint_wall_cell(
665    cells: &mut [String],
666    cell_fg: &mut [Option<RgbColor>],
667    width: usize,
668    height: usize,
669    wx: i32,
670    wy: i32,
671    px: f32,
672    py: f32,
673    half_w: i32,
674    half_h: i32,
675    ch: &str,
676) {
677    let Some((gx, gy)) = world_to_grid(wx as f32, wy as f32, px, py, half_w, half_h, width, height)
678    else {
679        return;
680    };
681    let idx = gy * width + gx;
682    let ground = empty_ground_glyph();
683    if cells[idx] == ground || is_wall(&cells[idx]) {
684        cells[idx] = merge_wall_corner(&cells[idx], ch, &ground);
685        cell_fg[idx] = Some(map_presentation::wall_presentation().color);
686    }
687}
688
689fn is_wall(glyph: &str) -> bool {
690    matches!(glyph.chars().next(), Some('+' | '-' | '|'))
691}
692
693/// Overlays (resources, loot, chests, boards) paint on any non-wall cell.
694fn can_paint_world_object(glyph: &str, _ground: &str, _player_glyph: &str) -> bool {
695    !is_wall(glyph)
696}
697
698fn merge_wall_corner(existing: &str, incoming: &str, ground: &str) -> String {
699    if existing == ground {
700        return incoming.to_string();
701    }
702    if existing == incoming {
703        return existing.to_string();
704    }
705    "+".to_string()
706}
707
708fn world_to_grid(
709    x: f32,
710    y: f32,
711    px: f32,
712    py: f32,
713    half_w: i32,
714    half_h: i32,
715    width: usize,
716    height: usize,
717) -> Option<(usize, usize)> {
718    let dx = (x - px).round() as i32;
719    let dy = (y - py).round() as i32;
720
721    if dx.abs() > half_w || dy.abs() > half_h {
722        return None;
723    }
724
725    let gx = half_w + dx;
726    let gy = half_h - dy;
727
728    if gx < 0 || gy < 0 {
729        return None;
730    }
731    let gx = gx as usize;
732    let gy = gy as usize;
733    if gx >= width || gy >= height {
734        return None;
735    }
736    Some((gx, gy))
737}
738
739/// Inverse of [`world_to_grid`]: map view cell → world meters (cell center).
740pub fn grid_to_world(
741    gx: usize,
742    gy: usize,
743    px: f32,
744    py: f32,
745    view_w: usize,
746    view_h: usize,
747) -> Option<(f32, f32)> {
748    if gx >= view_w || gy >= view_h {
749        return None;
750    }
751    let half_w = (view_w / 2) as i32;
752    let half_h = (view_h / 2) as i32;
753    let dx = gx as i32 - half_w;
754    let dy = half_h - gy as i32;
755    Some((px + dx as f32, py + dy as f32))
756}
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761    use flatland_protocol::{
762        BuildingView, EntityState, PlayerVitals, PrimaryAttributes, Transform, WorldCoord,
763    };
764
765    fn state_with_building(building: BuildingView) -> GameState {
766        GameState {
767            session_id: 1,
768            entity_id: 1,
769            character_id: None,
770            tick: 0,
771            chunk_rev: 0,
772            content_rev: 0,
773            entities: vec![EntityState {
774                id: 1,
775                label: "You".into(),
776                transform: Transform {
777                    position: WorldCoord::surface(148.0, 118.0),
778                    yaw: 0.0,
779                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
780                },
781                vitals: Some(PlayerVitals::default()),
782                attributes: Some(PrimaryAttributes::default()),
783                skills: Some(flatland_protocol::PlayerSkills::default()),
784                inside_building: None,
785                tile_id: None,
786                presentation_state: None,
787                sprite_mode: None,
788                progression_xp: None,
789            }],
790            player: None,
791            resource_nodes: vec![],
792            ground_drops: vec![],
793            placed_containers: vec![],
794            buildings: vec![building],
795            doors: vec![],
796            interior_map: None,
797            npcs: vec![],
798            blueprints: vec![],
799            world_width_m: 256.0,
800            world_height_m: 256.0,
801            terrain_zones: vec![],
802            z_platforms: vec![],
803            z_transitions: vec![],
804            world_clock: flatland_protocol::WorldClock::default(),
805            inventory: Default::default(),
806            inventory_hints: Default::default(),
807            logs: Default::default(),
808            intents_sent: 0,
809            ticks_received: 0,
810            connected: true,
811            disconnect_reason: None,
812            show_stats: false,
813            show_craft_menu: false,
814            craft_menu_index: 0,
815            craft_batch_quantity: 1,
816            show_shop_menu: false,
817            shop_catalog: None,
818            shop_tab: flatland_client_lib::ShopTab::default(),
819            shop_menu_index: 0,
820            shop_quantity: 1,
821            shop_trade_log: std::collections::VecDeque::new(),
822            show_npc_verb_menu: false,
823            npc_verb_target: None,
824            npc_verb_index: 0,
825            show_npc_chat: false,
826            npc_chat: None,
827            show_inventory_menu: false,
828            inventory_menu_index: 0,
829            show_move_picker: false,
830            show_rename_prompt: false,
831            rename_buffer: String::new(),
832            move_picker_index: 0,
833            move_picker: None,
834            show_destroy_picker: false,
835            destroy_confirm_pending: false,
836            destroy_picker: None,
837            combat_target: None,
838            combat_target_label: None,
839            in_combat: false,
840            auto_attack: true,
841            combat_has_los: false,
842            attack_cd_ticks: 0,
843            gcd_ticks: 0,
844            weapon_ability_id: "unarmed".into(),
845            mainhand_template_id: None,
846            mainhand_label: None,
847            worn: std::collections::BTreeMap::new(),
848            carry_mass: 0.0,
849            carry_mass_max: 0.0,
850            encumbrance: flatland_protocol::EncumbranceState::Light,
851            inventory_stacks: Vec::new(),
852            keychain_stacks: Vec::new(),
853            combat_target_detail: None,
854            cast_progress: None,
855            ability_cooldowns: Vec::new(),
856            blocking_active: false,
857            max_target_slots: 1,
858            combat_slots: Vec::new(),
859            rotation_presets: Vec::new(),
860            show_loadout_menu: false,
861            show_keychain_menu: false,
862            keychain_menu_index: 0,
863            show_rotation_editor: false,
864            loadout_menu_index: 0,
865            rotation_editor: Default::default(),
866            harvest_in_progress: false,
867            harvest_started_at: None,
868            pending_craft_ack: None,
869            quest_log: Vec::new(),
870            interactables: Vec::new(),
871            show_quest_offer: false,
872            pending_quest_offer: None,
873            show_quest_menu: false,
874            quest_menu_index: 0,
875            quest_withdraw_confirm: false,
876            progression_curve: None,
877        }
878    }
879
880    #[test]
881    fn shallow_water_terrain_paints_tilde() {
882        use flatland_protocol::TerrainZoneView;
883        let mut state = state_with_building(BuildingView {
884            id: "x".into(),
885            label: "X".into(),
886            x: 128.0,
887            y: 128.0,
888            width_m: 1.0,
889            depth_m: 1.0,
890            interior_blueprint: None,
891            tags: vec![],
892        });
893        state.terrain_zones.push(TerrainZoneView {
894            id: "pond".into(),
895            x0: 126.0,
896            y0: 126.0,
897            x1: 130.0,
898            y1: 130.0,
899            kind: TerrainKindView::ShallowWater,
900            elevation: -0.5,
901            glyph: None,
902            color: None,
903            tile_id: None,
904        });
905        state.entities = vec![EntityState {
906            id: 1,
907            label: "You".into(),
908            transform: Transform {
909                position: WorldCoord::surface(128.0, 128.0),
910                yaw: 0.0,
911                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
912            },
913            vitals: Some(PlayerVitals::default()),
914            attributes: Some(PrimaryAttributes::default()),
915            skills: Some(flatland_protocol::PlayerSkills::default()),
916            inside_building: None,
917            tile_id: None,
918            presentation_state: None,
919            sprite_mode: None,
920            progression_xp: None,
921        }];
922        state.player = state.entities.first().cloned();
923        let view = WorldView::build_with_target(&state, 9, 9, None);
924        let flat = view.cells.join("");
925        let water = map_presentation::shallow_water_presentation();
926        assert!(
927            flat.contains(&water.glyph),
928            "expected water tiles ({:?}): {flat}",
929            water.glyph
930        );
931        assert!(
932            view.cell_fg.iter().any(|c| *c == Some(water.color)),
933            "expected water color on terrain cells"
934        );
935    }
936
937    #[test]
938    fn zone_glyph_and_color_overrides_paint_on_map() {
939        use flatland_protocol::TerrainZoneView;
940        let mut state = state_with_building(BuildingView {
941            id: "x".into(),
942            label: "X".into(),
943            x: 128.0,
944            y: 128.0,
945            width_m: 1.0,
946            depth_m: 1.0,
947            interior_blueprint: None,
948            tags: vec![],
949        });
950        state.terrain_zones.push(TerrainZoneView {
951            id: "marked".into(),
952            x0: 126.0,
953            y0: 126.0,
954            x1: 130.0,
955            y1: 130.0,
956            kind: TerrainKindView::Grass,
957            elevation: 0.0,
958            glyph: Some("%".into()),
959            color: Some("magenta".into()),
960            tile_id: None,
961        });
962        state.entities = vec![EntityState {
963            id: 1,
964            label: "You".into(),
965            transform: Transform {
966                position: WorldCoord::surface(128.0, 128.0),
967                yaw: 0.0,
968                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
969            },
970            vitals: Some(PlayerVitals::default()),
971            attributes: Some(PrimaryAttributes::default()),
972            skills: Some(flatland_protocol::PlayerSkills::default()),
973            inside_building: None,
974            tile_id: None,
975            presentation_state: None,
976            sprite_mode: None,
977            progression_xp: None,
978        }];
979        state.player = state.entities.first().cloned();
980        let view = WorldView::build_with_target(&state, 9, 9, None);
981        let flat = view.cells.join("");
982        assert!(
983            flat.contains('%'),
984            "expected custom zone glyph on map: {flat}"
985        );
986        assert!(
987            view.cell_fg.iter().any(|c| *c == Some(RgbColor::MAGENTA)),
988            "expected custom zone color on terrain cells"
989        );
990    }
991
992    #[test]
993    fn well_paints_water_ring_and_center() {
994        let building = BuildingView {
995            id: "town_well".into(),
996            label: "Well".into(),
997            x: 122.0,
998            y: 106.0,
999            width_m: 3.0,
1000            depth_m: 3.0,
1001            interior_blueprint: None,
1002            tags: vec!["well".into()],
1003        };
1004        let mut state = state_with_building(building);
1005        state.entities = vec![EntityState {
1006            id: 1,
1007            label: "You".into(),
1008            transform: Transform {
1009                position: WorldCoord::surface(120.0, 106.0),
1010                yaw: 0.0,
1011                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1012            },
1013            vitals: Some(PlayerVitals::default()),
1014            attributes: Some(PrimaryAttributes::default()),
1015            skills: Some(flatland_protocol::PlayerSkills::default()),
1016            inside_building: None,
1017            tile_id: None,
1018            presentation_state: None,
1019            sprite_mode: None,
1020            progression_xp: None,
1021        }];
1022        state.player = state.entities.first().cloned();
1023        let view = WorldView::build_with_target(&state, 9, 9, None);
1024        let flat = view.cells.join("");
1025        assert!(flat.contains('~'), "expected well water: {flat}");
1026        assert!(flat.contains('O'), "expected well center: {flat}");
1027    }
1028
1029    #[test]
1030    fn broker_hut_draws_wall_outline() {
1031        let building = BuildingView {
1032            id: "broker_hut".into(),
1033            label: "Broker's Hut".into(),
1034            x: 148.0,
1035            y: 118.0,
1036            width_m: 8.0,
1037            depth_m: 6.0,
1038            interior_blueprint: None,
1039            tags: vec![],
1040        };
1041        let mut state = state_with_building(building);
1042        state.player = state.entities.first().cloned();
1043        let view = WorldView::build_with_target(&state, 25, 15, None);
1044        let flat = view.cells.join("");
1045        assert!(flat.contains('+'), "expected corners: {flat}");
1046        assert!(flat.contains('-'), "expected horiz walls: {flat}");
1047        assert!(flat.contains('|'), "expected vert walls: {flat}");
1048    }
1049
1050    #[test]
1051    fn interior_map_renders_rooms_and_walls() {
1052        use flatland_protocol::{InteriorMapView, InteriorRoomView};
1053        let building = BuildingView {
1054            id: "broker_hut".into(),
1055            label: "Broker's Hut".into(),
1056            x: 148.0,
1057            y: 118.0,
1058            width_m: 8.0,
1059            depth_m: 6.0,
1060            interior_blueprint: Some("broker_hut".into()),
1061            tags: vec![],
1062        };
1063        let mut state = state_with_building(building);
1064        state.interior_map = Some(InteriorMapView {
1065            building_id: "broker_hut".into(),
1066            blueprint_id: "broker_hut".into(),
1067            background_color: "#000000".into(),
1068            default_floor_color: Some("#2a2a2a".into()),
1069            floor_height_m: 3.0,
1070            rooms: vec![InteriorRoomView {
1071                id: "main".into(),
1072                label: "Main".into(),
1073                floor: 0,
1074                x0: 0.0,
1075                y0: 0.0,
1076                x1: 8.5,
1077                y1: 7.0,
1078                floor_color: None,
1079                floor_glyph: None,
1080            }],
1081            room_doors: vec![],
1082        });
1083        state.entities = vec![EntityState {
1084            id: 1,
1085            label: "You".into(),
1086            transform: Transform {
1087                position: WorldCoord::surface(4.0, 3.0),
1088                yaw: 0.0,
1089                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1090            },
1091            vitals: Some(PlayerVitals::default()),
1092            attributes: Some(PrimaryAttributes::default()),
1093            skills: Some(flatland_protocol::PlayerSkills::default()),
1094            inside_building: Some("broker_hut".into()),
1095            tile_id: None,
1096            presentation_state: None,
1097            sprite_mode: None,
1098            progression_xp: None,
1099        }];
1100        state.player = state.entities.first().cloned();
1101        let view = WorldView::build_with_target(&state, 25, 15, None);
1102        assert_eq!(view.inside_building.as_deref(), Some("broker_hut"));
1103        let flat = view.cells.join("");
1104        assert!(flat.contains('+'), "expected interior walls: {flat}");
1105        assert!(flat.contains('@'), "expected player marker: {flat}");
1106    }
1107
1108    #[test]
1109    fn stale_interior_map_renders_outdoor_when_outside() {
1110        use flatland_protocol::{InteriorMapView, InteriorRoomView};
1111        let building = BuildingView {
1112            id: "town_hall".into(),
1113            label: "Town Hall".into(),
1114            x: 163.0,
1115            y: 137.0,
1116            width_m: 20.0,
1117            depth_m: 10.0,
1118            interior_blueprint: Some("town_hall".into()),
1119            tags: vec![],
1120        };
1121        let mut state = state_with_building(building);
1122        state.interior_map = Some(InteriorMapView {
1123            building_id: "town_hall".into(),
1124            blueprint_id: "town_hall".into(),
1125            background_color: "#000000".into(),
1126            default_floor_color: Some("#2a2a2a".into()),
1127            floor_height_m: 3.0,
1128            rooms: vec![InteriorRoomView {
1129                id: "main_hall".into(),
1130                label: "Main".into(),
1131                floor: 0,
1132                x0: -3.5,
1133                y0: -8.0,
1134                x1: 18.5,
1135                y1: 6.0,
1136                floor_color: None,
1137                floor_glyph: None,
1138            }],
1139            room_doors: vec![],
1140        });
1141        state.player = state.entities.first().cloned();
1142        let view = WorldView::build_with_target(&state, 25, 15, None);
1143        assert!(view.inside_building.is_none());
1144        let flat = view.cells.join("");
1145        let grass = map_presentation::terrain_for(TerrainKindView::Grass).glyph;
1146        assert!(
1147            flat.contains(&grass),
1148            "expected outdoor terrain, not stale interior background: {flat}"
1149        );
1150        assert!(
1151            !flat.chars().all(|c| c == ' ' || c == '@'),
1152            "stale interior_map must not paint black interior when outside"
1153        );
1154    }
1155
1156    #[test]
1157    fn stale_inside_flag_still_renders_outdoor_world() {
1158        use flatland_protocol::ResourceNodeState;
1159        let building = BuildingView {
1160            id: "broker_hut".into(),
1161            label: "Broker's Hut".into(),
1162            x: 148.0,
1163            y: 118.0,
1164            width_m: 8.0,
1165            depth_m: 6.0,
1166            interior_blueprint: None,
1167            tags: vec![],
1168        };
1169        let mut state = state_with_building(building);
1170        state.entities = vec![EntityState {
1171            id: 1,
1172            label: "You".into(),
1173            transform: Transform {
1174                position: WorldCoord::surface(128.0, 128.0),
1175                yaw: 0.0,
1176                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1177            },
1178            vitals: Some(PlayerVitals::default()),
1179            attributes: Some(PrimaryAttributes::default()),
1180            skills: Some(flatland_protocol::PlayerSkills::default()),
1181            inside_building: Some("broker_hut".into()),
1182            tile_id: None,
1183            presentation_state: None,
1184            sprite_mode: None,
1185            progression_xp: None,
1186        }];
1187        state.player = state.entities.first().cloned();
1188        state
1189            .resource_nodes
1190            .push(flatland_protocol::ResourceNodeView {
1191                id: "oak".into(),
1192                label: "Oak".into(),
1193                x: 126.0,
1194                y: 134.0,
1195                z: 0.0,
1196                item_template: "oak_log".into(),
1197                state: ResourceNodeState::Available,
1198                blocking: true,
1199                blocking_radius_m: 0.8,
1200                tile_id: None,
1201                sprite_mode: None,
1202                presentation_state: None,
1203            });
1204        let view = WorldView::build_with_target(&state, 25, 15, None);
1205        assert_eq!(
1206            view.inside_building.as_deref(),
1207            Some("broker_hut"),
1208            "server inside flag is authoritative"
1209        );
1210        let flat = view.cells.join("");
1211        let oak = map_presentation::resource_for(&flatland_protocol::ResourceNodeView {
1212            id: "oak".into(),
1213            label: "Oak".into(),
1214            x: 0.0,
1215            y: 0.0,
1216            z: 0.0,
1217            item_template: "oak_log".into(),
1218            state: flatland_protocol::ResourceNodeState::Available,
1219            blocking: true,
1220            blocking_radius_m: 0.8,
1221            tile_id: None,
1222            sprite_mode: None,
1223            presentation_state: None,
1224        });
1225        assert!(
1226            flat.contains(&oak.glyph),
1227            "expected nearby tree ({:?}): {flat}",
1228            oak.glyph
1229        );
1230        assert!(flat.contains('@'), "expected player: {flat}");
1231    }
1232
1233    #[test]
1234    fn inside_building_flag_selects_active_instance() {
1235        let town = BuildingView {
1236            id: "town_hall".into(),
1237            label: "Town Hall".into(),
1238            x: 160.0,
1239            y: 136.0,
1240            width_m: 20.0,
1241            depth_m: 10.0,
1242            interior_blueprint: Some("town_hall".into()),
1243            tags: vec![],
1244        };
1245        let guild = BuildingView {
1246            id: "guild_hall".into(),
1247            label: "Guild Hall".into(),
1248            x: 164.0,
1249            y: 152.0,
1250            width_m: 20.0,
1251            depth_m: 14.0,
1252            interior_blueprint: Some("guild_hall".into()),
1253            tags: vec![],
1254        };
1255        let mut state = state_with_building(town);
1256        state.buildings.push(guild);
1257        state.entities = vec![EntityState {
1258            id: 1,
1259            label: "You".into(),
1260            transform: Transform {
1261                position: WorldCoord::surface(4.0, 3.0),
1262                yaw: 0.0,
1263                velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1264            },
1265            vitals: Some(PlayerVitals::default()),
1266            attributes: Some(PrimaryAttributes::default()),
1267            skills: Some(flatland_protocol::PlayerSkills::default()),
1268            inside_building: Some("guild_hall".into()),
1269            tile_id: None,
1270            presentation_state: None,
1271            sprite_mode: None,
1272            progression_xp: None,
1273        }];
1274        state.player = state.entities.first().cloned();
1275        state.world_width_m = 256.0;
1276        state.world_height_m = 256.0;
1277
1278        let view = WorldView::build_with_target(&state, 25, 15, None);
1279        assert_eq!(view.inside_building.as_deref(), Some("guild_hall"));
1280    }
1281
1282    #[test]
1283    fn combat_target_marks_creature_cell() {
1284        let building = BuildingView {
1285            id: "x".into(),
1286            label: "X".into(),
1287            x: 128.0,
1288            y: 128.0,
1289            width_m: 1.0,
1290            depth_m: 1.0,
1291            interior_blueprint: None,
1292            tags: vec![],
1293        };
1294        let mut state = state_with_building(building);
1295        state.entities = vec![
1296            EntityState {
1297                id: 1,
1298                label: "You".into(),
1299                transform: Transform {
1300                    position: WorldCoord::surface(100.0, 100.0),
1301                    yaw: 0.0,
1302                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1303                },
1304                vitals: Some(PlayerVitals::default()),
1305                attributes: Some(PrimaryAttributes::default()),
1306                skills: Some(flatland_protocol::PlayerSkills::default()),
1307                inside_building: None,
1308                tile_id: None,
1309                presentation_state: None,
1310                sprite_mode: None,
1311                progression_xp: None,
1312            },
1313            EntityState {
1314                id: 42,
1315                label: "Rabbit".into(),
1316                transform: Transform {
1317                    position: WorldCoord::surface(103.0, 100.0),
1318                    yaw: 0.0,
1319                    velocity: flatland_protocol::Velocity2D { vx: 0.0, vy: 0.0 },
1320                },
1321                vitals: None,
1322                attributes: None,
1323                skills: None,
1324                inside_building: None,
1325                tile_id: None,
1326                presentation_state: None,
1327                sprite_mode: None,
1328                progression_xp: None,
1329            },
1330        ];
1331        state.player = state.entities.first().cloned();
1332        state.combat_target = Some(42);
1333        state.combat_target_label = Some("Rabbit".into());
1334
1335        let view = WorldView::build_with_target(&state, 25, 15, None);
1336        let marked: usize = view
1337            .target_t1_cells
1338            .iter()
1339            .chain(view.target_t2_cells.iter())
1340            .filter(|b| **b)
1341            .count();
1342        assert_eq!(marked, 1, "exactly one targeted cell");
1343        let idx = view
1344            .target_t1_cells
1345            .iter()
1346            .chain(view.target_t2_cells.iter())
1347            .position(|b| *b)
1348            .expect("target cell");
1349        assert_eq!(view.cells[idx], "R");
1350    }
1351
1352    #[test]
1353    fn grid_to_world_roundtrips_center() {
1354        let px = 10.0;
1355        let py = 20.0;
1356        let view_w = 11;
1357        let view_h = 11;
1358        let half_w = (view_w / 2) as i32;
1359        let half_h = (view_h / 2) as i32;
1360        let (gx, gy) =
1361            world_to_grid(12.0, 18.0, px, py, half_w, half_h, view_w, view_h).expect("in view");
1362        let (wx, wy) = grid_to_world(gx, gy, px, py, view_w, view_h).expect("inverse");
1363        assert!((wx - 12.0).abs() < 0.01);
1364        assert!((wy - 18.0).abs() < 0.01);
1365    }
1366
1367    #[test]
1368    fn vertical_axis_quantizes_to_one_meter() {
1369        let px = 0.0;
1370        let py = 0.0;
1371        let view_w = 21;
1372        let view_h = 21;
1373        let half_w = (view_w / 2) as i32;
1374        let half_h = (view_h / 2) as i32;
1375        let (gx, gy) =
1376            world_to_grid(3.0, 3.0, px, py, half_w, half_h, view_w, view_h).expect("in view");
1377        let (wx, wy) = grid_to_world(gx, gy, px, py, view_w, view_h).expect("inverse");
1378        assert!(
1379            (wx - 3.0).abs() < 0.01,
1380            "x should stay exact to 1m: got {wx}"
1381        );
1382        assert!(
1383            (wy - 3.0).abs() < 0.01,
1384            "y should stay exact to 1m: got {wy}"
1385        );
1386    }
1387
1388    #[test]
1389    fn square_extent_spans_equal_rows_and_columns() {
1390        let px = 0.0;
1391        let py = 0.0;
1392        let half_w = 50;
1393        let half_h = 50;
1394        let width = 101;
1395        let height = 101;
1396        let (gx0, gy0) =
1397            world_to_grid(-4.0, -4.0, px, py, half_w, half_h, width, height).expect("in view");
1398        let (gx1, gy1) =
1399            world_to_grid(4.0, 4.0, px, py, half_w, half_h, width, height).expect("in view");
1400        let cols_spanned = (gx1 as i32 - gx0 as i32).unsigned_abs();
1401        let rows_spanned = (gy1 as i32 - gy0 as i32).unsigned_abs();
1402        assert_eq!(cols_spanned, 8, "8m wide should span 8 columns");
1403        assert_eq!(rows_spanned, 8, "8m tall should span 8 rows");
1404    }
1405
1406    #[test]
1407    fn resource_paints_on_terrain_cell_for_same_world_coords() {
1408        use flatland_protocol::{ResourceNodeState, ResourceNodeView, TerrainZoneView};
1409
1410        let px = 128.0;
1411        let py = 128.0;
1412        let rx = 131.0;
1413        let ry = 132.0;
1414        let mut state = state_with_building(BuildingView {
1415            id: "x".into(),
1416            label: "X".into(),
1417            x: 128.0,
1418            y: 128.0,
1419            width_m: 1.0,
1420            depth_m: 1.0,
1421            interior_blueprint: None,
1422            tags: vec![],
1423        });
1424        state.terrain_zones.push(TerrainZoneView {
1425            id: "pond".into(),
1426            x0: rx,
1427            y0: ry,
1428            x1: rx + 1.0,
1429            y1: ry + 1.0,
1430            kind: TerrainKindView::ShallowWater,
1431            elevation: -0.5,
1432            glyph: None,
1433            color: None,
1434            tile_id: None,
1435        });
1436        state.resource_nodes.push(ResourceNodeView {
1437            id: "oak".into(),
1438            label: "Oak".into(),
1439            x: rx,
1440            y: ry,
1441            z: 0.0,
1442            item_template: "oak_log".into(),
1443            state: ResourceNodeState::Available,
1444            blocking: true,
1445            blocking_radius_m: 0.8,
1446            tile_id: None,
1447            sprite_mode: None,
1448            presentation_state: None,
1449        });
1450        state.entities[0].transform.position = WorldCoord::surface(px, py);
1451        state.player = state.entities.first().cloned();
1452
1453        let view = WorldView::build_with_target(&state, 25, 15, None);
1454        let half_w = (view.width / 2) as i32;
1455        let half_h = (view.height / 2) as i32;
1456        let (gx, gy) = world_to_grid(rx, ry, px, py, half_w, half_h, view.width, view.height)
1457            .expect("resource in view");
1458        let idx = gy * view.width + gx;
1459        let oak = map_presentation::resource_for(&state.resource_nodes[0]);
1460        assert_eq!(
1461            view.cells[idx], oak.glyph,
1462            "resource should paint on the grid cell for its world coords"
1463        );
1464        let (wx, wy) = grid_to_world(gx, gy, px, py, view.width, view.height).expect("inverse");
1465        assert!(
1466            (wx - rx).abs() < 0.01 && (wy - ry).abs() < 0.01,
1467            "resource grid cell should sample terrain at ({wx}, {wy}), expected ({rx}, {ry})"
1468        );
1469    }
1470
1471    #[test]
1472    fn chest_and_loot_paint_on_non_grass_terrain() {
1473        use flatland_protocol::{GroundDropView, PlacedContainerView, TerrainZoneView};
1474
1475        let px = 50.0;
1476        let py = 50.0;
1477        let cx = 53.0;
1478        let cy = 52.0;
1479        let lx = 54.0;
1480        let ly = 52.0;
1481        let mut state = state_with_building(BuildingView {
1482            id: "x".into(),
1483            label: "X".into(),
1484            x: 50.0,
1485            y: 50.0,
1486            width_m: 1.0,
1487            depth_m: 1.0,
1488            interior_blueprint: None,
1489            tags: vec![],
1490        });
1491        state.terrain_zones.push(TerrainZoneView {
1492            id: "trail".into(),
1493            x0: 52.0,
1494            y0: 51.0,
1495            x1: 56.0,
1496            y1: 54.0,
1497            kind: TerrainKindView::Trail,
1498            elevation: 0.0,
1499            glyph: None,
1500            color: None,
1501            tile_id: None,
1502        });
1503        state.placed_containers.push(PlacedContainerView {
1504            id: "chest_1".into(),
1505            template_id: "wood_chest".into(),
1506            display_name: "Storage".into(),
1507            x: cx,
1508            y: cy,
1509            z: 0.0,
1510            locked: false,
1511            accessible: true,
1512            owner_character_id: None,
1513            contents: vec![],
1514            lock_id: None,
1515            capacity_volume: Some(40.0),
1516            item_instance_id: None,
1517            tile_id: None,
1518        });
1519        state.ground_drops.push(GroundDropView {
1520            id: "drop_1".into(),
1521            template_id: "lumber".into(),
1522            quantity: 2,
1523            x: lx,
1524            y: ly,
1525            z: 0.0,
1526            tile_id: None,
1527        });
1528        state.entities[0].transform.position = WorldCoord::surface(px, py);
1529        state.player = state.entities.first().cloned();
1530
1531        let view = WorldView::build_with_target(&state, 25, 15, None);
1532        let half_w = (view.width / 2) as i32;
1533        let half_h = (view.height / 2) as i32;
1534        let (gx, gy) =
1535            world_to_grid(cx, cy, px, py, half_w, half_h, view.width, view.height).expect("chest");
1536        let chest = map_presentation::chest_presentation(false);
1537        assert_eq!(
1538            view.cells[gy * view.width + gx],
1539            chest.glyph,
1540            "chest must paint on trail/non-grass cells"
1541        );
1542        let (gx2, gy2) =
1543            world_to_grid(lx, ly, px, py, half_w, half_h, view.width, view.height).expect("loot");
1544        let loot = map_presentation::loot_presentation();
1545        assert_eq!(
1546            view.cells[gy2 * view.width + gx2],
1547            loot.glyph,
1548            "ground loot must paint on trail/non-grass cells"
1549        );
1550    }
1551
1552    #[test]
1553    fn build_with_anchor_sets_view_origin() {
1554        let mut state = state_with_building(BuildingView {
1555            id: "x".into(),
1556            label: "X".into(),
1557            x: 128.0,
1558            y: 128.0,
1559            width_m: 1.0,
1560            depth_m: 1.0,
1561            interior_blueprint: None,
1562            tags: vec![],
1563        });
1564        state.entities[0].transform.position = WorldCoord::surface(100.0, 200.0);
1565        state.player = state.entities.first().cloned();
1566        let view = WorldView::build_with_anchor(
1567            &state,
1568            21,
1569            15,
1570            12.3,
1571            40.7,
1572            None,
1573            WorldViewOptions::terrain_only(),
1574        );
1575        assert!((view.origin_x - 12.3).abs() < 0.01);
1576        assert!((view.origin_y - 40.7).abs() < 0.01);
1577    }
1578
1579    #[test]
1580    fn skip_local_player_glyph_when_paint_local_player_false() {
1581        let mut state = state_with_building(BuildingView {
1582            id: "x".into(),
1583            label: "X".into(),
1584            x: 10.0,
1585            y: 10.0,
1586            width_m: 1.0,
1587            depth_m: 1.0,
1588            interior_blueprint: None,
1589            tags: vec![],
1590        });
1591        state.entities[0].transform.position = WorldCoord::surface(128.0, 128.0);
1592        state.player = state.entities.first().cloned();
1593        let player_glyph = map_presentation::player_presentation().glyph;
1594
1595        let with_player =
1596            WorldView::build_with_options(&state, 21, 15, None, WorldViewOptions::default());
1597        let cx = with_player.width / 2;
1598        let cy = with_player.height / 2;
1599        assert_eq!(
1600            with_player.cells[cy * with_player.width + cx],
1601            player_glyph,
1602            "default build paints @"
1603        );
1604
1605        let without =
1606            WorldView::build_with_options(&state, 21, 15, None, WorldViewOptions::terrain_only());
1607        assert_ne!(
1608            without.cells[cy * without.width + cx],
1609            player_glyph,
1610            "gfx sprite mode must not paint local player @"
1611        );
1612    }
1613}