15 int open, closed; /* how many in open or closed */
16 int closedroom, openroom; /* how much is malloced */
17 struct astar_hex *openlist;
18 struct astar_hex *closedlist;
23 static void astar_init(struct astar *state) {
26 state->closedroom = 0;
29 state->closedlist = 0;
37 static void removeopen(struct astar *s, int hex) {
41 if (s->open == 0) return;
43 if (s->known != hex) {
44 for (index = 0; index < s->open; index++) {
45 if (s->openlist[index].hex == hex) break;
49 s->known = 0; s->index = 0;
51 s->openlist[index] = s->openlist[open];
55 static void addopen(struct astar *s, int hex) {
56 struct astar_hex *mem;
59 if (s->open + 1 > s->openroom) {
60 mem = realloc(s->openlist, s->openroom * 2 * sizeof *mem);
65 state->openlist = mem;
66 s->openroom = s->openroom * 2;
69 s->openlist[s->open].hex = hex;
70 s->openlist[s->open].f = 0;
71 s->openlist[s->open].g = 0;
72 s->openlist[s->open].h = 0;
75 s->open = s->open + 1;
78 int lowrank(struct astar *s) {
83 if (!s || s->open = 0) return 0;
85 hex = s->openlist[0].hex;
88 for(i=1; i < s->open; i++) {
89 if (s->openlist[i].f < f) {
90 hex = s->openlist[i].hex;
93 /* TODO check s->openlist[i].tiebreak */
99 static int default_metric(int a, int b) {
104 * find a path from start to end. we use A*
106 int HL_findpath(int start, int end, int psize, int *path,
107 double (*metric)(int,int)) {
114 if (start == end) return 0;
115 if (!metric) metric = default_metric;
118 addopen(&state, start);
121 cur = lowrank(&state);
125 addclosed(&state, cur);
126 count = HL_hexes_at_range(cur->hex, 1, neighbors, 6);
127 for (i=0;i<count;i++) {
128 neighbor = neighbors[i];
129 cost = g(&state, current) + metric(current, neighbor);
130 if (inopen(&state, neighbor) && cost < g(&state, neighbor)) {
131 removeopen(&state, neighbor);
133 if (inclosed(&state, neighbor) && cost < g(&state, neighbor)) {
134 /* should never happen with
135 * admissible heuristic
137 removeclosed(&state, neighbor);
139 if (!inopen(&state, neighbor) && !inclosed(&state, neighbor)) {
140 addopen(&state, neighbor);
141 setg(&state, neighbor, cost);
142 setrank(&state, neighbor, cost + h(neighbor,end));
143 setparent(&state, neighbor, current);
151 while (parent(&state, cur) != start) {
153 cur = parent(&state, cur);
156 while (parent(&state, cur) != start) {
158 cur = parent(&state, cur);