aboutsummaryrefslogtreecommitdiff
path: root/internal/game/render_map.go
blob: 6b80688aeb380363ce161d29dc23ef620f24166a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
package game

import (
	"strings"
	"unicode/utf8"

	"thehouseoficarus/internal/color"
	"thehouseoficarus/internal/net"
	"thehouseoficarus/internal/world"
)

type mapGlyphs struct {
	topLeft, topRight       rune
	bottomLeft, bottomRight rune
	side                    rune
	topFill                 rune
	connectorH, connectorV  rune
	upArrow, downArrow      rune
	leftArrow, rightArrow   rune
	upRight, upLeft         rune
	downRight, downLeft     rune
	connectorNE, connectorNW rune
}

func mapGlyphsForPlayer(unicode bool) mapGlyphs {
	if unicode {
		return mapGlyphs{
			topLeft: '╔', topRight: '╗', bottomLeft: '╚', bottomRight: '╝',
			side: '║', topFill: '═', connectorH: '-', connectorV: '│',
			upArrow: '↑', downArrow: '↓', leftArrow: '←', rightArrow: '→',
			upRight: '↗', upLeft: '↖', downRight: '↘', downLeft: '↙',
			connectorNE: '/', connectorNW: '\\',
		}
	}
	return mapGlyphs{
		topLeft: '.', topRight: '.', bottomLeft: ':', bottomRight: ':',
		side: ':', topFill: '.', connectorH: '-', connectorV: '|',
		upArrow: '^', downArrow: 'v', leftArrow: '<', rightArrow: '>',
		upRight: '/', upLeft: '\\', downRight: '\\', downLeft: '/',
		connectorNE: '/', connectorNW: '\\',
	}
}

type mapCell struct {
	char rune
	spec color.ColorSpec
}

type mapGraph struct {
	posToRoom map[[2]int]int
	roomToPos map[int][2]int
	dist      map[int]int
}



func buildGraph(g *Game, startRoomID int, visited map[int]bool) *mapGraph {
	mg := &mapGraph{
		posToRoom: make(map[[2]int]int),
		roomToPos: make(map[int][2]int),
		dist:      make(map[int]int),
	}

	type node struct {
		roomID int
		x, y   int
	}
	queue := []node{{startRoomID, 0, 0}}
	mg.posToRoom[[2]int{0, 0}] = startRoomID
	mg.roomToPos[startRoomID] = [2]int{0, 0}
	mg.dist[startRoomID] = 0

	for len(queue) > 0 {
		n := queue[0]
		queue = queue[1:]

		room, ok := loadRoom(g, n.roomID)
		if !ok {
			continue
		}

		if visited != nil && !visited[n.roomID] {
			continue
		}

		for dir, delta := range world.DirectionDeltas {
			targetID, ok := exitTarget(room, dir)
			if !ok {
				continue
			}
			if _, seen := mg.roomToPos[targetID]; seen {
				continue
			}
			nx, ny := n.x+delta[0], n.y+delta[1]
			mg.posToRoom[[2]int{nx, ny}] = targetID
			mg.roomToPos[targetID] = [2]int{nx, ny}
			mg.dist[targetID] = mg.dist[n.roomID] + 1
			queue = append(queue, node{targetID, nx, ny})
		}
	}

	return mg
}

func renderMapCells(grid [][]mapCell, colorMode string, startRow, endRow int, border rune) []string {
	lines := make([]string, 0, endRow-startRow)
	for row := startRow; row < endRow; row++ {
		var sb strings.Builder
		if border != 0 {
			sb.WriteRune(border)
		}
		for _, cell := range grid[row] {
			if cell.char == ' ' {
				sb.WriteRune(' ')
			} else if !cell.spec.Empty() {
				sb.WriteString(color.Render(colorMode, cell.spec, string(cell.char)))
			} else {
				sb.WriteRune(cell.char)
			}
		}
		if border != 0 {
			sb.WriteRune(border)
		}
		lines = append(lines, sb.String())
	}
	return lines
}

func buildTinyMap(g *Game, sess *net.Session, roomID int, mg mapGlyphs) []string {
	visited := roomsVisited(sess)
	bg := buildGraph(g, roomID, visited)

	colorMode := colorModeFor(sess)
	atSpec := resolveMapAt(g, sess)
	dimSpec := resolveDim(g, sess)
	ctx := &mapRenderCtx{
		g: g, sess: sess, bg: bg, visited: visited, currentRoom: roomID,
		atSpec: atSpec, dimSpec: dimSpec, blockedSpec: resolveMapBlocked(g, sess), mg: mg,
		diagPairs: make(map[[2]int][2]int),
	}

	grid := make([][]mapCell, 5)
	for i := range grid {
		grid[i] = make([]mapCell, 5)
		for j := range grid[i] {
			grid[i][j] = mapCell{char: ' '}
		}
	}

	for y := -1; y <= 1; y++ {
		for x := -1; x <= 1; x++ {
			pos := [2]int{x, y}
			rid, ok := bg.posToRoom[pos]
			if !ok {
				continue
			}
			gr := (y + 1) * 2
			gc := (x + 1) * 2
			if rid == roomID {
				grid[gr][gc] = mapCell{char: '@', spec: atSpec}
			} else {
				unvisited := visited != nil && !visited[rid]
				ch, spec := roomMapSymbol(g, sess, rid, unvisited)
				if unvisited {
					spec = dimSpec
				}
				grid[gr][gc] = mapCell{char: ch, spec: spec}
			}
		}
	}

	for y := -1; y <= 1; y++ {
		for x := -1; x <= 0; x++ {
			leftPos := [2]int{x, y}
			rightPos := [2]int{x + 1, y}
			leftRoom, leftOK := bg.posToRoom[leftPos]
			rightRoom, rightOK := bg.posToRoom[rightPos]
			if !leftOK || !rightOK {
				continue
			}
			if cell, ok := ctx.connectorCell(leftRoom, rightRoom, world.East, world.West); ok {
				grid[(y+1)*2][(x+1)*2+1] = cell
			}
		}
	}

	for y := -1; y <= 0; y++ {
		for x := -1; x <= 1; x++ {
			topPos := [2]int{x, y}
			bottomPos := [2]int{x, y + 1}
			topRoom, topOK := bg.posToRoom[topPos]
			bottomRoom, bottomOK := bg.posToRoom[bottomPos]
			if !topOK || !bottomOK {
				continue
			}
			if cell, ok := ctx.connectorCell(topRoom, bottomRoom, world.South, world.North); ok {
				grid[(y+1)*2+1][(x+1)*2] = cell
			}
		}
	}

	// NE connectors: (x,y) -> (x+1, y-1), connector at grid[2*y+1][2*x+3]
	for y := 0; y <= 1; y++ {
		for x := -1; x <= 0; x++ {
			aPos, bPos := [2]int{x, y}, [2]int{x + 1, y - 1}
			aRoom, aOK := bg.posToRoom[aPos]
			bRoom, bOK := bg.posToRoom[bPos]
			if !aOK || !bOK {
				continue
			}
			if cell, ok := ctx.connectorCell(aRoom, bRoom, world.Northeast, world.Southwest); ok {
				gr, gc := 2*y+1, 2*x+3
				key := [2]int{gr, gc}
				if isDiagonalGlyph(grid[gr][gc].char) {
					if grid[gr][gc].char != cell.char {
						prev := ctx.diagPairs[key]
						spec := color.Average(
							color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
							color.Average(ctx.nodeSpec(aRoom), ctx.nodeSpec(bRoom)),
						)
						grid[gr][gc] = mapCell{char: 'X', spec: spec}
					}
				} else {
					grid[gr][gc] = cell
					ctx.diagPairs[key] = [2]int{aRoom, bRoom}
				}
			}
		}
	}
	// NW connectors: (x,y) -> (x-1, y-1), connector at grid[2*y+1][2*x+1]
	for y := 0; y <= 1; y++ {
		for x := 0; x <= 1; x++ {
			aPos, bPos := [2]int{x, y}, [2]int{x - 1, y - 1}
			aRoom, aOK := bg.posToRoom[aPos]
			bRoom, bOK := bg.posToRoom[bPos]
			if !aOK || !bOK {
				continue
			}
			if cell, ok := ctx.connectorCell(aRoom, bRoom, world.Northwest, world.Southeast); ok {
				gr, gc := 2*y+1, 2*x+1
				key := [2]int{gr, gc}
				if isDiagonalGlyph(grid[gr][gc].char) {
					if grid[gr][gc].char != cell.char {
						prev := ctx.diagPairs[key]
						spec := color.Average(
							color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
							color.Average(ctx.nodeSpec(aRoom), ctx.nodeSpec(bRoom)),
						)
						grid[gr][gc] = mapCell{char: 'X', spec: spec}
					}
				} else {
					grid[gr][gc] = cell
					ctx.diagPairs[key] = [2]int{aRoom, bRoom}
				}
			}
		}
	}
	// SE connectors: (x,y) -> (x+1, y+1), connector at grid[2*y+3][2*x+3]
	for y := -1; y <= 0; y++ {
		for x := -1; x <= 0; x++ {
			aPos, bPos := [2]int{x, y}, [2]int{x + 1, y + 1}
			aRoom, aOK := bg.posToRoom[aPos]
			bRoom, bOK := bg.posToRoom[bPos]
			if !aOK || !bOK {
				continue
			}
			if cell, ok := ctx.connectorCell(aRoom, bRoom, world.Southeast, world.Northwest); ok {
				gr, gc := 2*y+3, 2*x+3
				key := [2]int{gr, gc}
				if isDiagonalGlyph(grid[gr][gc].char) {
					if grid[gr][gc].char != cell.char {
						prev := ctx.diagPairs[key]
						spec := color.Average(
							color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
							color.Average(ctx.nodeSpec(aRoom), ctx.nodeSpec(bRoom)),
						)
						grid[gr][gc] = mapCell{char: 'X', spec: spec}
					}
				} else {
					grid[gr][gc] = cell
					ctx.diagPairs[key] = [2]int{aRoom, bRoom}
				}
			}
		}
	}
	// SW connectors: (x,y) -> (x-1, y+1), connector at grid[2*y+3][2*x+1]
	for y := -1; y <= 0; y++ {
		for x := 0; x <= 1; x++ {
			aPos, bPos := [2]int{x, y}, [2]int{x - 1, y + 1}
			aRoom, aOK := bg.posToRoom[aPos]
			bRoom, bOK := bg.posToRoom[bPos]
			if !aOK || !bOK {
				continue
			}
			if cell, ok := ctx.connectorCell(aRoom, bRoom, world.Southwest, world.Northeast); ok {
				gr, gc := 2*y+3, 2*x+1
				key := [2]int{gr, gc}
				if isDiagonalGlyph(grid[gr][gc].char) {
					if grid[gr][gc].char != cell.char {
						prev := ctx.diagPairs[key]
						spec := color.Average(
							color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
							color.Average(ctx.nodeSpec(aRoom), ctx.nodeSpec(bRoom)),
						)
						grid[gr][gc] = mapCell{char: 'X', spec: spec}
					}
				} else {
					grid[gr][gc] = cell
					ctx.diagPairs[key] = [2]int{aRoom, bRoom}
				}
			}
		}
	}

	cur, _ := loadRoom(g, roomID)
	if cur != nil {
		if upTarget, hasUp := exitTarget(cur, world.Up); hasUp {
			spec := color.NoColor()
			if exitStateTo(g, sess, roomID, world.Up, upTarget) == exitBlocked {
				spec = ctx.blockedSpec
			}
			switch {
			case grid[1][3].char == ' ':
				grid[1][3] = mapCell{char: mg.upArrow, spec: spec}
			case grid[1][1].char == ' ':
				grid[1][1] = mapCell{char: mg.upArrow, spec: spec}
			case grid[1][2].char == ' ':
				grid[1][2] = mapCell{char: mg.upArrow, spec: spec}
			}
		}
		if downTarget, hasDown := exitTarget(cur, world.Down); hasDown {
			spec := color.NoColor()
			if exitStateTo(g, sess, roomID, world.Down, downTarget) == exitBlocked {
				spec = ctx.blockedSpec
			}
			if grid[3][1].char == ' ' {
				grid[3][1] = mapCell{char: mg.downArrow, spec: spec}
			} else if grid[3][3].char == ' ' {
				grid[3][3] = mapCell{char: mg.downArrow, spec: spec}
			}
		}
	}

	topFill := strings.Repeat(string(mg.topFill), 5)
	lines := make([]string, 7)
	lines[0] = string(mg.topLeft) + topFill + string(mg.topRight)
	inner := renderMapCells(grid, colorMode, 0, 5, mg.side)
	copy(lines[1:], inner)
	botFill := strings.Repeat(string(mg.topFill), 5)
	lines[6] = string(mg.bottomLeft) + botFill + string(mg.bottomRight)

	return lines
}

func buildFullMap(g *Game, sess *net.Session, roomID, mapWidth, mapHeight int, mg mapGlyphs) []string {
	visited := roomsVisited(sess)
	bg := buildGraph(g, roomID, visited)

	colorMode := colorModeFor(sess)
	atSpec := resolveMapAt(g, sess)
	dimSpec := resolveDim(g, sess)
	ctx := &mapRenderCtx{
		g: g, sess: sess, bg: bg, visited: visited, currentRoom: roomID,
		atSpec: atSpec, dimSpec: dimSpec, blockedSpec: resolveMapBlocked(g, sess), mg: mg,
		diagPairs: make(map[[2]int][2]int),
	}

	grid := make([][]mapCell, mapHeight)
	for i := range grid {
		grid[i] = make([]mapCell, mapWidth)
		for j := range grid[i] {
			grid[i][j] = mapCell{char: ' '}
		}
	}

	cx := mapWidth / 2
	cy := mapHeight / 2

	for pos, rid := range bg.posToRoom {
		gr := cy + pos[1]*2
		gc := cx + pos[0]*2
		if gr < 0 || gr >= mapHeight || gc < 0 || gc >= mapWidth {
			continue
		}
		if rid == roomID {
			grid[gr][gc] = mapCell{char: '@', spec: atSpec}
		} else {
			unvisited := visited != nil && !visited[rid]
			ch, spec := roomMapSymbol(g, sess, rid, unvisited)
			if unvisited {
				spec = dimSpec
			}
			grid[gr][gc] = mapCell{char: ch, spec: spec}
		}
	}

	for pos, rid := range bg.posToRoom {
		x, y := pos[0], pos[1]

		if rightID, exists := bg.posToRoom[[2]int{x + 1, y}]; exists {
			gr := cy + y*2
			gc := cx + x*2 + 1
			if gr >= 0 && gr < mapHeight && gc >= 0 && gc < mapWidth {
				if cell, ok := ctx.connectorCell(rid, rightID, world.East, world.West); ok {
					grid[gr][gc] = cell
				}
			}
		}

		if bottomID, exists := bg.posToRoom[[2]int{x, y + 1}]; exists {
			gr := cy + y*2 + 1
			gc := cx + x*2
			if gr >= 0 && gr < mapHeight && gc >= 0 && gc < mapWidth {
				if cell, ok := ctx.connectorCell(rid, bottomID, world.South, world.North); ok {
					grid[gr][gc] = cell
				}
			}
		}

		if neID, exists := bg.posToRoom[[2]int{x + 1, y - 1}]; exists {
			gr := cy + y*2 - 1
			gc := cx + x*2 + 1
			if gr >= 0 && gr < mapHeight && gc >= 0 && gc < mapWidth {
				if cell, ok := ctx.connectorCell(rid, neID, world.Northeast, world.Southwest); ok {
					key := [2]int{gr, gc}
					if isDiagonalGlyph(grid[gr][gc].char) {
						if grid[gr][gc].char != cell.char {
							prev := ctx.diagPairs[key]
							spec := color.Average(
								color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
								color.Average(ctx.nodeSpec(rid), ctx.nodeSpec(neID)),
							)
							grid[gr][gc] = mapCell{char: 'X', spec: spec}
						}
					} else {
						grid[gr][gc] = cell
						ctx.diagPairs[key] = [2]int{rid, neID}
					}
				}
			}
		}

		if nwID, exists := bg.posToRoom[[2]int{x - 1, y - 1}]; exists {
			gr := cy + y*2 - 1
			gc := cx + x*2 - 1
			if gr >= 0 && gr < mapHeight && gc >= 0 && gc < mapWidth {
				if cell, ok := ctx.connectorCell(rid, nwID, world.Northwest, world.Southeast); ok {
					key := [2]int{gr, gc}
					if isDiagonalGlyph(grid[gr][gc].char) {
						if grid[gr][gc].char != cell.char {
							prev := ctx.diagPairs[key]
							spec := color.Average(
								color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
								color.Average(ctx.nodeSpec(rid), ctx.nodeSpec(nwID)),
							)
							grid[gr][gc] = mapCell{char: 'X', spec: spec}
						}
					} else {
						grid[gr][gc] = cell
						ctx.diagPairs[key] = [2]int{rid, nwID}
					}
				}
			}
		}

		if seID, exists := bg.posToRoom[[2]int{x + 1, y + 1}]; exists {
			gr := cy + y*2 + 1
			gc := cx + x*2 + 1
			if gr >= 0 && gr < mapHeight && gc >= 0 && gc < mapWidth {
				if cell, ok := ctx.connectorCell(rid, seID, world.Southeast, world.Northwest); ok {
					key := [2]int{gr, gc}
					if isDiagonalGlyph(grid[gr][gc].char) {
						if grid[gr][gc].char != cell.char {
							prev := ctx.diagPairs[key]
							spec := color.Average(
								color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
								color.Average(ctx.nodeSpec(rid), ctx.nodeSpec(seID)),
							)
							grid[gr][gc] = mapCell{char: 'X', spec: spec}
						}
					} else {
						grid[gr][gc] = cell
						ctx.diagPairs[key] = [2]int{rid, seID}
					}
				}
			}
		}

		if swID, exists := bg.posToRoom[[2]int{x - 1, y + 1}]; exists {
			gr := cy + y*2 + 1
			gc := cx + x*2 - 1
			if gr >= 0 && gr < mapHeight && gc >= 0 && gc < mapWidth {
				if cell, ok := ctx.connectorCell(rid, swID, world.Southwest, world.Northeast); ok {
					key := [2]int{gr, gc}
					if isDiagonalGlyph(grid[gr][gc].char) {
						if grid[gr][gc].char != cell.char {
							prev := ctx.diagPairs[key]
							spec := color.Average(
								color.Average(ctx.nodeSpec(prev[0]), ctx.nodeSpec(prev[1])),
								color.Average(ctx.nodeSpec(rid), ctx.nodeSpec(swID)),
							)
							grid[gr][gc] = mapCell{char: 'X', spec: spec}
						}
					} else {
						grid[gr][gc] = cell
						ctx.diagPairs[key] = [2]int{rid, swID}
					}
				}
			}
		}
	}

	return renderMapCells(grid, colorMode, 0, mapHeight, 0)
}

func roomsVisited(sess *net.Session) map[int]bool {
	if sess != nil && sess.Player != nil {
		return sess.Player.Stats.RoomsVisited
	}
	return nil
}

func colorModeFor(sess *net.Session) string {
	if sess != nil && sess.Player != nil {
		return sess.Player.OptionString("color")
	}
	return "none"
}

func resolveMapAt(g *Game, sess *net.Session) color.ColorSpec {
	if sess != nil {
		return g.resolveColor(sess, "map_at")
	}
	return color.Parse("0F")
}

func resolveDim(g *Game, sess *net.Session) color.ColorSpec {
	if sess != nil {
		return g.resolveColor(sess, "dim")
	}
	return color.Parse("F3 dim")
}

func resolveMapBlocked(g *Game, sess *net.Session) color.ColorSpec {
	if sess != nil {
		return g.resolveColor(sess, "map_blocked")
	}
	return color.Parse("C4")
}

// mapRenderCtx bundles the per-render state shared by node and connector drawing
// so the tiny and full maps build cells the same way.
type mapRenderCtx struct {
	g           *Game
	sess        *net.Session
	bg          *mapGraph
	visited     map[int]bool
	currentRoom int
	atSpec      color.ColorSpec
	dimSpec     color.ColorSpec
	blockedSpec color.ColorSpec
	mg          mapGlyphs
	diagPairs   map[[2]int][2]int
}

// nodeSpec returns the effective color a room's node is drawn with, mirroring
// the logic used when placing room glyphs.
func (c *mapRenderCtx) nodeSpec(roomID int) color.ColorSpec {
	if roomID == c.currentRoom {
		return c.atSpec
	}
	if c.visited != nil && !c.visited[roomID] {
		return c.dimSpec
	}
	_, spec := roomMapSymbol(c.g, c.sess, roomID, false)
	return spec
}

// connectorCell builds the link cell between two grid-adjacent rooms based on
// the per-direction traversability of the two exits joining them. ok is false
// when there is no link at all, so the caller draws nothing:
//   - both directions open       -> bidirectional bar (- / |)
//   - outward direction open      -> arrow pointing outward
//   - outward direction blocked   -> blocked 'X'
//   - only inward direction open  -> arrow pointing inward
//   - none traversable            -> blocked 'X'
//   - neither exit exists         -> ok == false (no cell)
//
// "Outward" is the exit from the room nearer the player (smaller BFS distance)
// toward the farther one — i.e. the link as reached along the shortest path.
// Since each BFS hop is a unit grid step, grid-adjacent rooms always differ in
// distance parity, so there is never a tie to break.
//
// Bars and arrows use the normal link coloring (dim if an endpoint is unvisited,
// otherwise the gradient average); only 'X' uses the blocked color.
func (c *mapRenderCtx) connectorCell(roomA, roomB int, dirAB, dirBA world.ExitDir) (mapCell, bool) {
	fwd := exitStateTo(c.g, c.sess, roomA, dirAB, roomB) // A -> B
	bwd := exitStateTo(c.g, c.sess, roomB, dirBA, roomA) // B -> A

	switch {
	case fwd == exitAbsent && bwd == exitAbsent:
		return mapCell{}, false
	case fwd == exitOpen && bwd == exitOpen:
		return c.coloredCell(roomA, roomB, barGlyph(c.mg, dirAB))
	}

	// Orient the link outward, from near room to far room.
	outDir, inDir, out, in := dirAB, dirBA, fwd, bwd
	if c.bg.dist[roomB] < c.bg.dist[roomA] {
		outDir, inDir, out, in = dirBA, dirAB, bwd, fwd
	}

	switch {
	case out == exitOpen:
		return c.coloredCell(roomA, roomB, arrowGlyph(c.mg, outDir))
	case out == exitAbsent && in == exitOpen:
		return c.coloredCell(roomA, roomB, arrowGlyph(c.mg, inDir))
	default:
		return mapCell{char: 'X', spec: c.blockedSpec}, true
	}
}

// coloredCell applies the shared link coloring logic for bar/arrow glyphs
// (dim if either endpoint is unvisited, otherwise the gradient average).
func (c *mapRenderCtx) coloredCell(roomA, roomB int, glyph rune) (mapCell, bool) {
	if c.visited != nil && (!c.visited[roomA] || !c.visited[roomB]) {
		return mapCell{char: glyph, spec: c.dimSpec}, true
	}
	return mapCell{char: glyph, spec: color.Average(c.nodeSpec(roomA), c.nodeSpec(roomB))}, true
}

type exitState int

const (
	exitAbsent exitState = iota
	exitOpen
	exitBlocked
)

// exitStateTo reports whether the exit from `from` in `dir` leads to `neighbor`
// and, if so, whether it is currently traversable for this player. A missing
// session/player (e.g. in tests or background renders) treats conditional exits
// as open so rendering never depends on player evaluation.
func exitStateTo(g *Game, sess *net.Session, from int, dir world.ExitDir, neighbor int) exitState {
	room, ok := loadRoom(g, from)
	if !ok {
		return exitAbsent
	}
	exit, ok := room.Exits[dir]
	if !ok || exit.Room != neighbor {
		return exitAbsent
	}
	if exit.Condition == nil || sess == nil || sess.Player == nil {
		return exitOpen
	}
	if sess.Player.GodMode || g.checkCondition(sess, exit.Condition) {
		return exitOpen
	}
	return exitBlocked
}

func isDiagonalGlyph(ch rune) bool {
	return ch == '\\' || ch == '/' || ch == '↗' || ch == '↖' || ch == '↘' || ch == '↙'
}

// barGlyph returns the bidirectional connector glyph for a link's orientation.
func barGlyph(mg mapGlyphs, dir world.ExitDir) rune {
	switch dir {
	case world.East, world.West:
		return mg.connectorH
	case world.North, world.South:
		return mg.connectorV
	case world.Northeast, world.Southwest:
		return mg.connectorNE
	case world.Northwest, world.Southeast:
		return mg.connectorNW
	}
	return mg.connectorH
}

// arrowGlyph returns the one-way arrow pointing along the direction of travel.
func arrowGlyph(mg mapGlyphs, dir world.ExitDir) rune {
	switch dir {
	case world.East:
		return mg.rightArrow
	case world.West:
		return mg.leftArrow
	case world.South:
		return mg.downArrow
	case world.North:
		return mg.upArrow
	case world.Northeast:
		return mg.upRight
	case world.Northwest:
		return mg.upLeft
	case world.Southeast:
		return mg.downRight
	case world.Southwest:
		return mg.downLeft
	}
	return mg.connectorH
}

// roomDefaultColorSpec resolves the room's own default map color (feature 3).
// Empty/unset returns NoColor.
func roomDefaultColorSpec(g *Game, roomID int) color.ColorSpec {
	if room, ok := loadRoom(g, roomID); ok && room.Color != "" {
		return color.Parse(room.Color)
	}
	return color.NoColor()
}

func roomMapSymbol(g *Game, sess *net.Session, roomID int, unvisited bool) (rune, color.ColorSpec) {
	roomSpec := roomDefaultColorSpec(g, roomID)
	if sess != nil && sess.Player != nil {
		if data, ok := sess.Player.MapSymbols[roomID]; ok {
			r, size := utf8.DecodeRuneInString(data.Char)
			if size > 0 && r != utf8.RuneError {
				// precedence: player symbol color > room default color > none
				spec := roomSpec
				if data.Color != "" {
					spec = color.Parse(data.Color)
				}
				// non-ASCII custom symbols fall back to 'o'
				// when unicode mode is off, but preserve the color.
				if !sess.Player.OptionBool("unicode") && r > 127 {
					return 'o', spec
				}
				return r, spec
			}
		}
		if sess.Player.OptionBool("unicode") {
			if unvisited {
				return '□', roomSpec
			}
			return '■', roomSpec
		}
		return 'o', roomSpec
	}
	return '■', roomSpec
}

func exitTarget(room *world.Room, dir world.ExitDir) (int, bool) {
	if room == nil {
		return 0, false
	}
	exit, ok := room.Exits[dir]
	if !ok {
		return 0, false
	}
	return exit.Room, true
}

func loadRoom(g *Game, roomID int) (*world.Room, bool) {
	if roomID == 0 {
		return nil, false
	}
	room, err := g.World.LoadRoom(roomID)
	if err != nil {
		return nil, false
	}
	return room, true
}

func stripBlankRows(lines []string) []string {
	var out []string
	for _, line := range lines {
		if strings.TrimSpace(line) != "" {
			out = append(out, line)
		}
	}
	return out
}

func leftTrimCommon(lines []string) []string {
	min := -1
	for _, line := range lines {
		if strings.TrimSpace(line) == "" {
			continue
		}
		n := 0
		for _, r := range line {
			if r == ' ' {
				n++
			} else {
				break
			}
		}
		if min < 0 || n < min {
			min = n
		}
	}
	if min <= 0 {
		return lines
	}
	result := make([]string, len(lines))
	for i, line := range lines {
		if len(line) <= min {
			result[i] = ""
		} else {
			result[i] = line[min:]
		}
	}
	return result
}