-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathfinder.py
More file actions
2153 lines (1727 loc) · 68.9 KB
/
pathfinder.py
File metadata and controls
2153 lines (1727 loc) · 68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Circle-WFC Pathfinder
원주 기반 제약 충족 경로 탐색 알고리즘 메인 클래스
"""
from typing import List, Tuple, Optional, Set
from collections import deque
try:
from .grid import Grid, Tile, TileState
from .wfc import WFCEngine
from .circle_layer import CircleLayer, Point, calculate_optimal_layers
from .constraints import ConstraintManager, BasicRoadConstraint, PathConstraint
except ImportError:
from grid import Grid, Tile, TileState
from wfc import WFCEngine
from circle_layer import CircleLayer, Point, calculate_optimal_layers
from constraints import ConstraintManager, BasicRoadConstraint, PathConstraint
# 방향 상수 (리팩토링: 중복 제거)
DIRECTIONS_4 = [(0, 1), (0, -1), (1, 0), (-1, 0)] # 4방향 (상하좌우)
DIRECTIONS_8 = DIRECTIONS_4 + [(1, 1), (1, -1), (-1, 1), (-1, -1)] # 8방향 (대각선 포함)
class CircleWFC:
"""Circle-WFC 경로 탐색기
중간 원주에서 시작하여 양방향으로 붕괴하며 경로 탐색
"""
def __init__(self, grid: Grid, num_layers: Optional[int] = None):
"""
Args:
grid: 탐색할 그리드
num_layers: 레이어 수 (None이면 자동 계산)
"""
self.grid = grid
self.num_layers = num_layers
self.wfc_engine: Optional[WFCEngine] = None
self.circle_layer: Optional[CircleLayer] = None
self.path: List[Tuple[int, int]] = []
# 동적 복잡도 추적
self.contradiction_count = 0 # 모순 발생 횟수
self.collapse_count = 0 # 총 붕괴 시도 횟수
self.expansion_count = 0 # 터널 확장 횟수 (복잡도 지표)
def find(
self,
start: Tuple[int, int],
end: Tuple[int, int],
num_layers: Optional[int] = None
) -> List[Tuple[int, int]]:
"""경로 탐색
Args:
start: 시작점 (x, y)
end: 끝점 (x, y)
num_layers: 레이어 수 (None이면 자동)
Returns:
경로 좌표 리스트 [(x1, y1), (x2, y2), ...]
"""
# 복잡도 추적 카운터 초기화
self.contradiction_count = 0
self.collapse_count = 0
self.expansion_count = 0
# 레이어 수 결정
if num_layers is None:
if self.num_layers is None:
distance = ((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2) ** 0.5
num_layers = calculate_optimal_layers(distance)
else:
num_layers = self.num_layers
# 원주 레이어 생성
self.circle_layer = CircleLayer(start, end, num_layers)
# 제약 조건 설정
constraints = ConstraintManager()
constraints.add(BasicRoadConstraint())
constraints.add(PathConstraint(prefer_road=True))
# WFC 엔진 생성 (대각선 지원 명시)
self.wfc_engine = WFCEngine(self.grid, constraints, allow_diagonal=True)
# 시작점과 끝점을 도로로 고정
self.wfc_engine.collapse_at(start[0], start[1], TileState.ROAD)
self.wfc_engine.collapse_at(end[0], end[1], TileState.ROAD)
# 1. Bresenham 직선 힌트 제공
line_points = self._bresenham_line(start[0], start[1], end[0], end[1])
line_blocked = False
line_hints = 0
for x, y in line_points:
if (x, y) == start or (x, y) == end:
continue
if 0 <= x < self.grid.width and 0 <= y < self.grid.height:
tile = self.grid.get(x, y)
if tile and tile.can_be_road() and not tile.is_collapsed:
self.wfc_engine.collapse_at(x, y, TileState.ROAD)
line_hints += 1
elif tile and not tile.can_be_road():
line_blocked = True
# 1-1. 직선이 막혔어도 WFC propagation이 알아서 우회 경로 찾음
# (순수 WFC 방식: BFS detour 사용 안 함)
# 2. Circle 교점 힌트 + 교점 간 연결 (미로 해결 핵심)
waypoints = [start] # 시작점부터
if self.circle_layer:
intersection_order = self.circle_layer.get_intersection_order_from_middle()
for idx in intersection_order:
if idx < len(self.circle_layer.intersection_points):
points = self.circle_layer.intersection_points[idx]
if points:
# 첫 번째 교점만 사용 (waypoint로)
grid_coord = points[0].to_grid()
x, y = grid_coord
if 0 <= x < self.grid.width and 0 <= y < self.grid.height:
tile = self.grid.get(x, y)
if tile and tile.can_be_road():
waypoints.append((x, y))
waypoints.append(end) # 끝점 추가
# Waypoint 사이를 연결 (Bresenham 또는 BFS detour)
for i in range(len(waypoints) - 1):
p1 = waypoints[i]
p2 = waypoints[i + 1]
# 먼저 직선 시도
segment = self._bresenham_line(p1[0], p1[1], p2[0], p2[1])
can_use_line = all(
self.grid.get(x, y) and self.grid.get(x, y).can_be_road()
for x, y in segment
if 0 <= x < self.grid.width and 0 <= y < self.grid.height
)
# 직선 가능하면 힌트로 제공 (막혔어도 WFC가 알아서 우회)
if can_use_line:
for x, y in segment:
if 0 <= x < self.grid.width and 0 <= y < self.grid.height:
tile = self.grid.get(x, y)
if tile and tile.can_be_road() and not tile.is_collapsed:
self.wfc_engine.collapse_at(x, y, TileState.ROAD)
# 직선이 막혔어도 BFS 우회 경로 사용 안 함 (순수 WFC 방식)
# 3. 계층적 WFC 전파: Circle layer 기반 chunk 붕괴
self._hierarchical_collapse(start, end)
# 경로 추출
if self._verify_connection(start, end):
self.path = self._extract_path(start, end)
return self.path
return []
def _bidirectional_collapse(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> bool:
"""중간 원주에서 시작하여 양방향으로 붕괴
Args:
start: 시작점
end: 끝점
Returns:
성공 여부
"""
# 교점 순서 (중간부터 바깥으로)
intersection_order = self.circle_layer.get_intersection_order_from_middle()
if not intersection_order:
# 레이어가 1개 이하면 직접 연결 시도
return self._direct_connect(start, end)
# 경로상의 모든 점 수집 (시작점 → 교점들 → 끝점)
# 교점 중 하나를 선택 (첫 번째 교점 사용)
waypoints = [start]
# 원주 순서대로 교점 추가 (0, 1, 2, ... 순)
for idx in range(len(self.circle_layer.intersection_points)):
points = self.circle_layer.intersection_points[idx]
if points:
# 첫 번째 교점 사용 (또는 시작점에 가까운 교점)
grid_coord = points[0].to_grid()
if (0 <= grid_coord[0] < self.grid.width and
0 <= grid_coord[1] < self.grid.height):
waypoints.append(grid_coord)
waypoints.append(end)
# 연속된 waypoint 사이를 연결
for i in range(len(waypoints) - 1):
p1 = waypoints[i]
p2 = waypoints[i + 1]
# 먼저 직선 연결 시도
line_points = self._bresenham_line(p1[0], p1[1], p2[0], p2[1])
can_use_line = True
for x, y in line_points:
tile = self.grid.get(x, y)
if tile is None or not tile.can_be_road():
can_use_line = False
break
if can_use_line:
# 직선 사용 가능
for x, y in line_points:
tile = self.grid.get(x, y)
if tile and tile.can_be_road():
self.wfc_engine.collapse_at(x, y, TileState.ROAD)
else:
# 직선 불가 → BFS로 우회 경로 탐색
detour = self._find_detour(p1, p2)
for x, y in detour:
tile = self.grid.get(x, y)
if tile and tile.can_be_road():
self.wfc_engine.collapse_at(x, y, TileState.ROAD)
# 시작점과 끝점이 도로로 연결되었는지 확인
return self._verify_connection(start, end)
def _find_detour(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> List[Tuple[int, int]]:
"""BFS로 우회 경로 탐색 (장애물 회피, 8방향)"""
visited = {start: None}
queue = deque([start])
while queue:
x, y = queue.popleft()
if (x, y) == end:
# 경로 역추적
path = []
current = end
while current is not None:
path.append(current)
current = visited[current]
path.reverse()
return path
# 8방향 탐색 (대각선 포함)
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0),
(1, 1), (1, -1), (-1, 1), (-1, -1)]:
nx, ny = x + dx, y + dy
if (nx, ny) in visited:
continue
if not (0 <= nx < self.grid.width and 0 <= ny < self.grid.height):
continue
tile = self.grid.get(nx, ny)
if tile and tile.can_be_road():
visited[(nx, ny)] = (x, y)
queue.append((nx, ny))
# 경로 없음
return []
def _direct_connect(self, start: Tuple[int, int], end: Tuple[int, int]) -> bool:
"""레이어 없이 직접 연결 시도
간단한 직선/맨해튼 경로로 연결
"""
x1, y1 = start
x2, y2 = end
# Bresenham 알고리즘으로 직선 경로 생성
points = self._bresenham_line(x1, y1, x2, y2)
for x, y in points:
tile = self.grid.get(x, y)
if tile and tile.can_be_road():
self.wfc_engine.collapse_at(x, y, TileState.ROAD)
return self._verify_connection(start, end)
def _bresenham_line(
self,
x1: int, y1: int,
x2: int, y2: int
) -> List[Tuple[int, int]]:
"""4방향 연결을 보장하는 직선 알고리즘
대각선 이동 대신 가로/세로 이동만 사용하여
모든 점이 4방향으로 연결되도록 함
"""
points = []
dx = abs(x2 - x1)
dy = abs(y2 - y1)
sx = 1 if x1 < x2 else -1
sy = 1 if y1 < y2 else -1
x, y = x1, y1
points.append((x, y))
if dx >= dy:
# x축 기준 이동
err = dx // 2
while x != x2:
x += sx
points.append((x, y))
err -= dy
if err < 0:
y += sy
points.append((x, y))
err += dx
# 마지막 y 조정
while y != y2:
y += sy
points.append((x, y))
else:
# y축 기준 이동
err = dy // 2
while y != y2:
y += sy
points.append((x, y))
err -= dx
if err < 0:
x += sx
points.append((x, y))
err += dy
# 마지막 x 조정
while x != x2:
x += sx
points.append((x, y))
return points
def _verify_connection(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> bool:
"""시작점과 끝점이 도로로 연결되었는지 확인 (BFS, 8방향)"""
visited = set()
queue = deque([start])
visited.add(start)
while queue:
x, y = queue.popleft()
if (x, y) == end:
return True
# 인접 타일 확인 (8방향 - 대각선 포함)
for dx, dy in DIRECTIONS_8:
nx, ny = x + dx, y + dy
if (nx, ny) in visited:
continue
if not (0 <= nx < self.grid.width and 0 <= ny < self.grid.height):
continue
tile = self.grid.get(nx, ny)
if tile and tile.is_road():
visited.add((nx, ny))
queue.append((nx, ny))
return False
def _extract_path(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> List[Tuple[int, int]]:
"""도로 타일에서 경로 추출 (BFS로 최단 경로, 8방향)"""
visited = {start: None} # 이전 노드 저장
queue = deque([start])
while queue:
x, y = queue.popleft()
if (x, y) == end:
# 경로 역추적
path = []
current = end
while current is not None:
path.append(current)
current = visited[current]
path.reverse()
return path
# 인접 타일 확인 (8방향 - 대각선 포함)
for dx, dy in DIRECTIONS_8:
nx, ny = x + dx, y + dy
if (nx, ny) in visited:
continue
if not (0 <= nx < self.grid.width and 0 <= ny < self.grid.height):
continue
tile = self.grid.get(nx, ny)
if tile and tile.is_road():
visited[(nx, ny)] = (x, y)
queue.append((nx, ny))
return []
def get_stats(self) -> dict:
"""탐색 통계 반환"""
road_count = sum(
1 for row in self.grid.tiles
for tile in row
if tile.is_road()
)
return {
"grid_size": f"{self.grid.width}x{self.grid.height}",
"num_layers": self.num_layers or (
self.circle_layer.num_layers if self.circle_layer else 0
),
"path_length": len(self.path),
"road_tiles": road_count,
"total_tiles": self.grid.width * self.grid.height,
"collapse_count": self.collapse_count,
"contradiction_count": self.contradiction_count,
"expansion_count": self.expansion_count,
"complexity_score": self._get_complexity_score(),
}
def _hierarchical_collapse(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> None:
"""광선 기반 붕괴: Line of Sight (LoS) 방식
원을 확장하지 않고, 현재 위치에서 목표까지 광선을 쏴서
보이는 만큼만 붕괴 → 막히면 우회 → 반복
Args:
start: 시작점
end: 끝점
"""
# 광선 기반 붕괴로 전환
self._ray_based_collapse(start, end)
def _ray_based_collapse(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> None:
"""Lazy Tunnel: ray-first, 실패 시 세그먼트별 터널 업그레이드
전략:
1. 모든 세그먼트를 ray-only로 시작 (터널 없음)
2. WFC 붕괴 시도
3. 연결 실패 시, 끊어진 세그먼트만 터널로 업그레이드
4. 성공할 때까지 반복
Args:
start: 시작점
end: 끝점
"""
# 1. 앵커 포인트 찾기 (타입 정보 없이)
anchors_raw = self._find_anchors_for_lazy_tunnel(start, end)
# 1-1. 앵커 압축 (Greedy Anchor Compression)
anchors = self._compress_anchors(anchors_raw)
# 2. 세그먼트별 상태 추적
# segments[i] = (p1, p2, is_tunnel)
# 장애물이 있는 세그먼트는 초기부터 터널로 시작
segments = []
for i in range(len(anchors) - 1):
p1 = anchors[i]
p2 = anchors[i + 1]
# 직선 경로에 장애물이 있는지 확인
ray = self._bresenham_line(p1[0], p1[1], p2[0], p2[1])
has_obstacle = False
for x, y in ray:
tile = self.grid.get(x, y)
if tile and not tile.can_be_road():
has_obstacle = True
break
segments.append({
'p1': p1,
'p2': p2,
'is_tunnel': has_obstacle, # 장애물 있으면 터널로 시작
'tunnel_width': 1 if has_obstacle else 0
})
# 3. Lazy Tunnel 루프
max_upgrade_rounds = 10 # 최대 업그레이드 라운드
for round_idx in range(max_upgrade_rounds):
# 3-1. 현재 세그먼트 설정으로 road_zone 생성
road_zone_tiles = self._build_road_zone_from_segments(segments)
# 3-2. WFC 붕괴 시도 (세그먼트 정보 전달)
connected = self._try_wfc_collapse(start, end, road_zone_tiles, segments)
if connected:
return # 성공!
# 3-3. 실패 → 끊어진 세그먼트 찾기
failed_segments = self._find_disconnected_segments(segments, start, end)
if not failed_segments:
# 끊어진 세그먼트 찾을 수 없음 → 전체 확장
for seg in segments:
if not seg['is_tunnel']:
seg['is_tunnel'] = True
seg['tunnel_width'] = 1
break # 하나씩만 업그레이드
continue
# 3-4. 실패한 세그먼트만 터널로 업그레이드
upgraded = False
for seg_idx in failed_segments:
seg = segments[seg_idx]
if not seg['is_tunnel']:
# ray → tunnel 업그레이드
seg['is_tunnel'] = True
seg['tunnel_width'] = 1
upgraded = True
elif seg['tunnel_width'] < 3:
# 터널 폭 증가
seg['tunnel_width'] += 1
upgraded = True
if not upgraded:
# 모든 세그먼트가 이미 최대 터널 → 전역 확장
road_zone_tiles = self._build_road_zone_from_segments(segments)
new_tiles = self._expand_tunnel_around_roads(road_zone_tiles, radius=1)
# 그리드 리셋 없이 계속 시도
self.expansion_count += 1
def _find_anchors_for_lazy_tunnel(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> List[Tuple[int, int]]:
"""Lazy Tunnel용 앵커 찾기 (타입 없이 좌표만)
Args:
start: 시작점
end: 끝점
Returns:
앵커 좌표 리스트 [start, anchor1, ..., end]
"""
anchors = [start]
current = start
max_iterations = 100
for _ in range(max_iterations):
if current == end:
break
# 현재 → 목표 광선
ray = self._bresenham_line(current[0], current[1], end[0], end[1])
# 충돌 지점 찾기
collision_point = None
last_visible = current
for x, y in ray:
if (x, y) == current:
continue
tile = self.grid.get(x, y)
if tile and not tile.can_be_road():
collision_point = last_visible
break
last_visible = (x, y)
if collision_point:
# 충돌 지점 추가
if collision_point != current and collision_point not in anchors:
anchors.append(collision_point)
# 우회 앵커 찾기
next_anchor = self._find_nearest_empty_towards_goal(
collision_point, end, search_radius=20
)
if next_anchor and next_anchor != collision_point:
if next_anchor not in anchors:
anchors.append(next_anchor)
current = next_anchor
else:
break
else:
# 목표까지 직선 가능
break
if end not in anchors:
anchors.append(end)
return anchors
def _compress_anchors(
self,
anchors: List[Tuple[int, int]]
) -> List[Tuple[int, int]]:
"""앵커 압축: 불필요한 중간 앵커 제거 (Greedy Anchor Compression)
역방향으로 훑으며 "건너뛰어도 LoS가 가능한" 앵커들을 제거
Args:
anchors: 원본 앵커 리스트 [start, ..., end]
Returns:
압축된 앵커 리스트
"""
if len(anchors) <= 2:
return anchors
compressed = [anchors[0]] # 시작점
i = 0
while i < len(anchors) - 1:
# 현재 앵커에서 가장 멀리 보이는 앵커 찾기 (역방향 탐색)
farthest = i + 1
for j in range(len(anchors) - 1, i, -1):
if self._has_line_of_sight(anchors[i], anchors[j]):
farthest = j
break
compressed.append(anchors[farthest])
i = farthest
return compressed
def _has_line_of_sight(
self,
p1: Tuple[int, int],
p2: Tuple[int, int]
) -> bool:
"""두 점 사이에 장애물 없이 직선 연결 가능한지 확인 (LoS)
Args:
p1: 시작점
p2: 끝점
Returns:
직선 연결 가능 여부
"""
ray = self._bresenham_line(p1[0], p1[1], p2[0], p2[1])
for x, y in ray:
tile = self.grid.get(x, y)
if tile and not tile.can_be_road():
return False
return True
def _build_road_zone_from_segments(
self,
segments: List[dict]
) -> set:
"""세그먼트 설정에 따라 road_zone 생성
Args:
segments: 세그먼트 리스트 [{p1, p2, is_tunnel, tunnel_width}, ...]
Returns:
road_zone 타일 좌표 set
"""
road_zone = set()
for seg in segments:
p1, p2 = seg['p1'], seg['p2']
if seg['is_tunnel']:
# 터널: 폭 있는 경로
tunnel_tiles = self._bresenham_tunnel_fixed_width(
p1[0], p1[1], p2[0], p2[1],
width=seg['tunnel_width']
)
road_zone.update(tunnel_tiles)
else:
# Ray-only: 선만
ray_points = self._bresenham_line(p1[0], p1[1], p2[0], p2[1])
for x, y in ray_points:
if 0 <= x < self.grid.width and 0 <= y < self.grid.height:
road_zone.add((x, y))
return road_zone
def _bresenham_tunnel_fixed_width(
self,
x1: int, y1: int,
x2: int, y2: int,
width: int
) -> set:
"""고정 폭 터널 생성
Args:
x1, y1: 시작점
x2, y2: 끝점
width: 터널 폭
Returns:
터널 타일 좌표 set
"""
tunnel_tiles = set()
# 기본 선 생성
line_points = self._bresenham_line(x1, y1, x2, y2)
for x, y in line_points:
# 폭만큼 확장
for dx in range(-width, width + 1):
for dy in range(-width, width + 1):
if abs(dx) + abs(dy) <= width: # 맨해튼 거리
nx, ny = x + dx, y + dy
if 0 <= nx < self.grid.width and 0 <= ny < self.grid.height:
tunnel_tiles.add((nx, ny))
return tunnel_tiles
def _try_wfc_collapse(
self,
start: Tuple[int, int],
end: Tuple[int, int],
road_zone_tiles: set,
segments: List[dict] = None
) -> bool:
"""road_zone 내에서 Coarse-to-Fine WFC 붕괴 시도
전략: 디딤돌(stepping stones)만 먼저 붕괴 → 사이는 직선 보간
Args:
start: 시작점
end: 끝점
road_zone_tiles: 붕괴 대상 타일 set
segments: 세그먼트 리스트 (디딤돌 선정용)
Returns:
연결 성공 여부
"""
# Phase 1: 디딤돌 선정 (세그먼트 경로 기반)
if segments:
stepping_stones = self._select_stepping_stones_from_segments(segments, step=3)
else:
stepping_stones = list(road_zone_tiles)[::3] # fallback
# Phase 2: 디딤돌만 먼저 붕괴
for x, y in stepping_stones:
tile = self.grid.get(x, y)
if tile and not tile.is_collapsed and tile.can_be_road():
self.collapse_count += 1
if self.wfc_engine.collapse_tile(tile, TileState.ROAD):
self.wfc_engine.propagate(tile)
# Phase 3: 연결 확인 - 성공하면 바로 리턴
if self._verify_connection(start, end):
return True
# Phase 4: 실패 시 촘촘하게 붕괴 (fallback)
distance = ((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2) ** 0.5
max_steps = int(distance * 50) # 줄임
max_steps = max(500, min(max_steps, 5000))
check_interval = 20
for step in range(max_steps):
tile = self._get_lowest_entropy_in_tiles(road_zone_tiles)
if tile is None:
# 타일 고갈 → 주변 확장
new_tiles = self._expand_tunnel_around_roads(road_zone_tiles, radius=1)
if new_tiles:
road_zone_tiles.update(new_tiles)
self.expansion_count += 1
continue
break
self.collapse_count += 1
if not self.wfc_engine.collapse_tile(tile, TileState.ROAD):
continue
if not self.wfc_engine.propagate(tile):
continue
if step % check_interval == 0:
if self._verify_connection(start, end):
return True
return self._verify_connection(start, end)
def _select_stepping_stones_from_segments(
self,
segments: List[dict],
step: int = 3
) -> List[Tuple[int, int]]:
"""세그먼트 경로를 따라 디딤돌 선정
각 세그먼트의 직선 경로에서 일정 간격으로 샘플링
Args:
segments: 세그먼트 리스트
step: 샘플링 간격
Returns:
디딤돌 좌표 리스트
"""
stepping_stones = []
for seg in segments:
p1, p2 = seg['p1'], seg['p2']
# 세그먼트 직선 경로
line = self._bresenham_line(p1[0], p1[1], p2[0], p2[1])
# step 간격으로 샘플링
for i, (x, y) in enumerate(line):
if i % step == 0:
stepping_stones.append((x, y))
return stepping_stones
def _find_disconnected_segments(
self,
segments: List[dict],
start: Tuple[int, int],
end: Tuple[int, int]
) -> List[int]:
"""끊어진 세그먼트 인덱스 찾기
각 세그먼트의 시작/끝점이 도로로 연결되었는지 확인
Args:
segments: 세그먼트 리스트
start: 전체 시작점
end: 전체 끝점
Returns:
끊어진 세그먼트 인덱스 리스트
"""
failed = []
for i, seg in enumerate(segments):
p1, p2 = seg['p1'], seg['p2']
# p1에서 p2로 도로 연결 확인
if not self._is_segment_connected(p1, p2):
failed.append(i)
return failed
def _is_segment_connected(
self,
p1: Tuple[int, int],
p2: Tuple[int, int]
) -> bool:
"""두 점이 도로로 연결되었는지 확인 (BFS)
Args:
p1: 시작점
p2: 끝점
Returns:
연결 여부
"""
# p1이 도로가 아니면 실패
tile1 = self.grid.get(p1[0], p1[1])
if not tile1 or not tile1.is_road():
return False
visited = set()
queue = deque([p1])
visited.add(p1)
# 탐색 범위 제한 (세그먼트 주변만)
min_x = min(p1[0], p2[0]) - 5
max_x = max(p1[0], p2[0]) + 5
min_y = min(p1[1], p2[1]) - 5
max_y = max(p1[1], p2[1]) + 5
while queue:
x, y = queue.popleft()
if (x, y) == p2:
return True
for dx, dy in DIRECTIONS_8:
nx, ny = x + dx, y + dy
if (nx, ny) in visited:
continue
# 범위 제한
if not (min_x <= nx <= max_x and min_y <= ny <= max_y):
continue
if not (0 <= nx < self.grid.width and 0 <= ny < self.grid.height):
continue
tile = self.grid.get(nx, ny)
if tile and tile.is_road():
visited.add((nx, ny))
queue.append((nx, ny))
return False
def _get_lowest_entropy_in_tiles(
self,
tiles_set: set
) -> Optional[Tile]:
"""지정된 타일 set 내에서 가장 낮은 엔트로피 타일 찾기
Args:
tiles_set: 탐색 대상 타일 좌표 set {(x, y), ...}
Returns:
set 내 최저 엔트로피 타일 (없으면 None)
"""
min_entropy = float('inf')
best_tile = None
for x, y in tiles_set:
tile = self.grid.get(x, y)
if not tile:
continue
if tile.is_collapsed:
continue
if tile.entropy == 0:
continue
# set 내에서 최저 엔트로피 찾기
if tile.entropy < min_entropy:
min_entropy = tile.entropy
best_tile = tile
return best_tile
def _global_wfc_collapse(
self,
start: Tuple[int, int],
end: Tuple[int, int]
) -> None:
"""전역 WFC 붕괴 (fallback)
Circle layer 없을 때 사용
"""
distance = ((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2) ** 0.5
max_steps = int(distance * 200)
max_steps = max(5000, min(max_steps, 20000))
check_interval = 30
for step in range(max_steps):
success, tile = self.wfc_engine.step(prefer_state=TileState.ROAD)
if not success or tile is None:
break
if step % check_interval == 0:
if self._verify_connection(start, end):
return
def _bresenham_tunnel_with_error(
self,
x1: int, y1: int,
x2: int, y2: int
) -> set:
"""Bresenham 오차항 기반 동적 터널
핵심: 오차항(Decision Parameter)이 클수록 터널 확장
- 직선 구간: 좁은 터널 (폭 2~3)
- 꺾이는 구간: 넓은 터널 (폭 자동 증가)
이건 휴리스틱이 아니라 기하학적 제약기(Constraint Filter)!
Args:
x1, y1: 시작점
x2, y2: 끝점
Returns:
터널 타일 좌표 set
"""
tunnel_tiles = set()
dx = abs(x2 - x1)
dy = abs(y2 - y1)
sx = 1 if x1 < x2 else -1