1 /***********************************************************************
2 Freeciv - Copyright (C) 2002 - The Freeciv Project
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2, or (at your option)
6 any later version.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12 ***********************************************************************/
13
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
17
18 #include <stdlib.h>
19 #include <string.h>
20
21 /* utility */
22 #include "fcintl.h"
23 #include "log.h"
24 #include "mem.h"
25 #include "shared.h"
26 #include "support.h"
27 #include "timing.h"
28
29 /* common */
30 #include "city.h"
31 #include "game.h"
32 #include "government.h"
33 #include "map.h"
34 #include "specialist.h"
35
36 #include "cm.h"
37
38 /*
39 * Terms used
40 * ==========
41 *
42 * Stats: food, shields, trade, luxury, science, and gold.
43 * Production: amount of stats you get directly from farming tiles or
44 * having specialists.
45 * Surplus: amount of stats you get, taking buildings, taxes, disorder, and
46 * any other effects into account.
47 *
48 * Happy State: disorder (unhappy), content (!unhappy && !happy) and
49 * happy (happy)
50 *
51 * Tile type: usually, many tiles produce the same f/s/t. So we bin the
52 * tiles into tile types. Specialists are also a 'tile type.'
53 *
54 * Unlike the original CM code, which used a dynamic programming approach,
55 * this code uses a branch-and-bound approach. The DP approach allowed
56 * cacheing, but it was hard to guarantee the correctness of the cache, so
57 * it was usually tossed and recomputed.
58 *
59 * The B&B approach also allows a very simple greedy search, whereas the DP
60 * approach required a lot of pre-computing. And, it appears to be very
61 * slightly faster. It evaluates about half as many solutions, but each
62 * candidate solution is more expensive due to the lack of cacheing.
63 *
64 * We use highly specific knowledge about how the city computes its stats
65 * in two places:
66 * - setting the min_production array. Ideally the city should tell us.
67 * - computing the weighting for tiles. Ditto.
68 */
69
70
71 /****************************************************************************
72 defines, structs, globals, forward declarations
73 *****************************************************************************/
74
75 /* Maximal iterations before the search loop is stopped. */
76 #define CM_MAX_LOOP 25000
77
78 #define CPUHOG_CM_MAX_LOOP (CM_MAX_LOOP * 4)
79
80 #ifdef DEBUG_TIMERS
81 #define GATHER_TIME_STATS
82 #endif
83 #ifdef DEBUG
84 #define CM_DEBUG
85 #endif
86
87 /* whether to print every query, or just at cm_free ; matters only
88 if GATHER_TIME_STATS is on */
89 #define PRINT_TIME_STATS_EVERY_QUERY
90
91 #define LOG_TIME_STATS LOG_DEBUG
92 #define LOG_CM_STATE LOG_DEBUG
93 #define LOG_LATTICE LOG_DEBUG
94 #define LOG_REACHED_LEAF LOG_DEBUG
95 #define LOG_BETTER_LEAF LOG_DEBUG
96 #define LOG_PRUNE_BRANCH LOG_DEBUG
97
98 #ifdef GATHER_TIME_STATS
99 static struct {
100 struct one_perf {
101 struct timer *wall_timer;
102 int query_count;
103 int apply_count;
104 const char *name;
105 } greedy, opt;
106
107 struct one_perf *current;
108 } performance;
109
110 static void print_performance(struct one_perf *counts);
111 #endif /* GATHER_TIME_STATS */
112
113 /* Fitness of a solution. */
114 struct cm_fitness {
115 int weighted; /* weighted sum */
116 bool sufficient; /* false => doesn't meet constraints */
117 };
118
119
120 /*
121 * We have a cyclic structure here, so we need to forward-declare the
122 * structs
123 */
124 struct cm_tile_type;
125 struct cm_tile;
126
127 /*
128 * A tile. Has a pointer to the type, and the x/y coords.
129 * Used mostly just for converting to cm_result.
130 */
131 struct cm_tile {
132 const struct cm_tile_type *type;
133 int index; /* city map index; only valid if !is_specialist */
134 };
135
136 /* define the tile_vector as array<cm_tile> */
137 #define SPECVEC_TAG tile
138 #define SPECVEC_TYPE struct cm_tile
139 #include "specvec.h"
140
141 /* define the tile_type_vector as array <cm_tile_type*> */
142 #define SPECVEC_TAG tile_type
143 #define SPECVEC_TYPE struct cm_tile_type *
144 #include "specvec.h"
145 #define tile_type_vector_iterate(vector, var) { \
146 struct cm_tile_type *var; \
147 TYPED_VECTOR_ITERATE(struct cm_tile_type*, vector, var##p) { \
148 var = *var##p; \
149 {
150 #define tile_type_vector_iterate_end }} VECTOR_ITERATE_END; }
151
152 /*
153 * A tile type.
154 * Holds the production (a hill produces 1/0/0);
155 * Holds a list of which tiles match this (all the hills and tundra);
156 * Holds a list of other types that are strictly better
157 * (grassland 2/0/0, plains 1/1/0, but not gold mine 0/1/6).
158 * Holds a list of other types that are strictly worse
159 * (the grassland and plains hold a pointer to the hill).
160 *
161 * Specialists are special types; is_specialist is set, and the tile
162 * vector is empty. We can never run out of specialists.
163 */
164 struct cm_tile_type {
165 int production[O_LAST];
166 double estimated_fitness; /* weighted sum of production */
167 bool is_specialist;
168 Specialist_type_id spec; /* valid only if is_specialist */
169 struct tile_vector tiles; /* valid only if !is_specialist */
170 struct tile_type_vector better_types;
171 struct tile_type_vector worse_types;
172 int lattice_index; /* index in state->lattice */
173 int lattice_depth; /* depth = sum(#tiles) over all better types */
174 };
175
176
177 /*
178 * A partial solution.
179 * Has the count of workers assigned to each lattice position, and
180 * a count of idle workers yet unassigned.
181 */
182 struct partial_solution {
183 /* indices for these two match the lattice indices */
184 int *worker_counts; /* number of workers on each type */
185 int *prereqs_filled; /* number of better types filled up */
186
187 int production[O_LAST]; /* raw production, cached for the heuristic */
188 int idle; /* number of idle workers */
189 };
190
191 /*
192 * State of the search.
193 * This holds all the information needed to do the search, all in one
194 * struct, in order to clean up the function calls.
195 */
196 struct cm_state {
197 /* input from the caller */
198 struct cm_parameter parameter;
199 /*mutable*/ struct city *pcity;
200
201 /* the tile lattice */
202 struct tile_type_vector lattice;
203 struct tile_type_vector lattice_by_prod[O_LAST];
204
205 /* the best known solution, and its fitness */
206 struct partial_solution best;
207 struct cm_fitness best_value;
208
209 /* hard constraints on production: any solution with less production than
210 * this fails to satisfy the constraints, so we can stop investigating
211 * this branch. A solution with more production than this may still
212 * fail (for being unhappy, for instance). */
213 int min_production[O_LAST];
214
215 /* needed luxury to be content, this includes effects by specialists */
216 int min_luxury;
217
218 /* the current solution we're examining. */
219 struct partial_solution current;
220
221 /*
222 * Where we are in the search. When we add a worker to the current
223 * partial solution, we also push the tile type index on the stack.
224 */
225 struct {
226 int *stack;
227 int size;
228 } choice;
229
230 bool *workers_map; /* placement of the workers within the city map */
231 };
232
233
234 /* return #fields + specialist types */
235 static int num_types(const struct cm_state *state);
236
237
238 /* debugging functions */
239 #ifdef CM_DEBUG
240 static void real_print_tile_type(enum log_level level, const char *file,
241 const char *function, int line,
242 const struct cm_tile_type *ptype,
243 const char *prefix);
244 #define print_tile_type(loglevel, ptype, prefix) \
245 if (log_do_output_for_level(loglevel)) { \
246 real_print_tile_type(loglevel, __FILE__, __FUNCTION__, __FC_LINE__, \
247 ptype, prefix); \
248 }
249
250 static void real_print_lattice(enum log_level level, const char *file,
251 const char *function, int line,
252 const struct tile_type_vector *lattice);
253 #define print_lattice(loglevel, lattice) \
254 if (log_do_output_for_level(loglevel)) { \
255 real_print_lattice(loglevel, __FILE__, __FUNCTION__, __FC_LINE__, \
256 lattice); \
257 }
258
259 static void real_print_partial_solution(enum log_level level,
260 const char *file,
261 const char *function, int line,
262 const struct partial_solution *soln,
263 const struct cm_state *state);
264 #define print_partial_solution(loglevel, soln, state) \
265 if (log_do_output_for_level(loglevel)) { \
266 real_print_partial_solution(loglevel, __FILE__, __FUNCTION__, \
267 __FC_LINE__, soln, state); \
268 }
269
270 #else
271 #define print_tile_type(loglevel, ptype, prefix)
272 #define print_lattice(loglevel, lattice)
273 #define print_partial_solution(loglevel, soln, state)
274 #endif /* CM_DEBUG */
275
276 static void cm_result_copy(struct cm_result *result,
277 const struct city *pcity, bool *workers_map);
278
279 static double estimate_fitness(const struct cm_state *state,
280 const int production[]);
281 static bool choice_is_promising(struct cm_state *state, int newchoice,
282 bool negative_ok);
283
284 /****************************************************************************
285 Initialize the CM data at the start of each game. Note the citymap
286 indices will not have been initialized yet (cm_init_citymap is called
287 when they are).
288 ****************************************************************************/
cm_init(void)289 void cm_init(void)
290 {
291 /* In the B&B algorithm there's not really anything to initialize. */
292 #ifdef GATHER_TIME_STATS
293 memset(&performance, 0, sizeof(performance));
294
295 performance.greedy.wall_timer = timer_new(TIMER_USER, TIMER_ACTIVE);
296 performance.greedy.name = "greedy";
297
298 performance.opt.wall_timer = timer_new(TIMER_USER, TIMER_ACTIVE);
299 performance.opt.name = "opt";
300 #endif /* GATHER_TIME_STATS */
301 }
302
303 /****************************************************************************
304 Initialize the CM citymap data. This function is called when the
305 city map indices are generated (basically when the topology is set,
306 shortly after the start of the game).
307 ****************************************************************************/
cm_init_citymap(void)308 void cm_init_citymap(void)
309 {
310 /* In the B&B algorithm there's not really anything to initialize. */
311 }
312
313 /****************************************************************************
314 Clear the cache for a city.
315 ****************************************************************************/
cm_clear_cache(struct city * pcity)316 void cm_clear_cache(struct city *pcity)
317 {
318 /* The B&B algorithm doesn't have city caches so there's nothing to do. */
319 }
320
321 /****************************************************************************
322 Called at the end of a game to free any CM data.
323 ****************************************************************************/
cm_free(void)324 void cm_free(void)
325 {
326 #ifdef GATHER_TIME_STATS
327 print_performance(&performance.greedy);
328 print_performance(&performance.opt);
329
330 timer_destroy(performance.greedy.wall_timer);
331 timer_destroy(performance.opt.wall_timer);
332 memset(&performance, 0, sizeof(performance));
333 #endif /* GATHER_TIME_STATS */
334 }
335
336 /****************************************************************************
337 Create a new cm_result.
338 ****************************************************************************/
cm_result_new(struct city * pcity)339 struct cm_result *cm_result_new(struct city *pcity)
340 {
341 struct cm_result *result;
342
343 /* initialise all values */
344 result = fc_calloc(1, sizeof(*result));
345 result->city_radius_sq = pcity ? city_map_radius_sq_get(pcity)
346 : CITY_MAP_MAX_RADIUS_SQ;
347 result->worker_positions
348 = fc_calloc(city_map_tiles(result->city_radius_sq),
349 sizeof(*result->worker_positions));
350
351 /* test if the city pointer is valid; the cm_result struct can be
352 * returned as it uses the maximal possible value for the size of
353 * 'worker_positions' (= city_map_tiles(CITY_MAP_MAX_RADIUS_SQ))*/
354 fc_assert_ret_val(pcity != NULL, result);
355
356 return result;
357 }
358
359 /****************************************************************************
360 Destroy a cm_result.
361 ****************************************************************************/
cm_result_destroy(struct cm_result * result)362 void cm_result_destroy(struct cm_result *result)
363 {
364 if (result != NULL) {
365 if (result->worker_positions != NULL) {
366 FC_FREE(result->worker_positions);
367 }
368 FC_FREE(result);
369 }
370 }
371
372 /***************************************************************************
373 Functions of tile-types.
374 ***************************************************************************/
375
376 /****************************************************************************
377 Set all production to zero and initialize the vectors for this tile type.
378 ****************************************************************************/
tile_type_init(struct cm_tile_type * type)379 static void tile_type_init(struct cm_tile_type *type)
380 {
381 memset(type, 0, sizeof(*type));
382 tile_vector_init(&type->tiles);
383 tile_type_vector_init(&type->better_types);
384 tile_type_vector_init(&type->worse_types);
385 }
386
387 /****************************************************************************
388 Duplicate a tile type, except for the vectors - the vectors of the new tile
389 type will be empty.
390 ****************************************************************************/
tile_type_dup(const struct cm_tile_type * oldtype)391 static struct cm_tile_type *tile_type_dup(const struct cm_tile_type *oldtype)
392 {
393 struct cm_tile_type *newtype = fc_malloc(sizeof(*newtype));
394
395 memcpy(newtype, oldtype, sizeof(*oldtype));
396 tile_vector_init(&newtype->tiles);
397 tile_type_vector_init(&newtype->better_types);
398 tile_type_vector_init(&newtype->worse_types);
399 return newtype;
400 }
401
402 /****************************************************************************
403 Free all the storage in the tile type (but don't free the type itself).
404 ****************************************************************************/
tile_type_destroy(struct cm_tile_type * type)405 static void tile_type_destroy(struct cm_tile_type *type)
406 {
407 /* The call to vector_free() will magically free all the tiles in the
408 * vector. */
409 tile_vector_free(&type->tiles);
410 tile_type_vector_free(&type->better_types);
411 tile_type_vector_free(&type->worse_types);
412 }
413
414 /****************************************************************************
415 Destroy and free all types in the vector, and the vector itself. This
416 will free all memory associated with the vector.
417 ****************************************************************************/
tile_type_vector_free_all(struct tile_type_vector * vec)418 static void tile_type_vector_free_all(struct tile_type_vector *vec)
419 {
420 tile_type_vector_iterate(vec, type) {
421 /* Destroy all data in the type, and free the type itself. */
422 tile_type_destroy(type);
423 free(type);
424 } tile_type_vector_iterate_end;
425
426 tile_type_vector_free(vec);
427 }
428
429 /****************************************************************************
430 Return TRUE iff all categories of the two types are equal. This means
431 all production outputs are equal and the is_specialist fields are also
432 equal.
433 ****************************************************************************/
tile_type_equal(const struct cm_tile_type * a,const struct cm_tile_type * b)434 static bool tile_type_equal(const struct cm_tile_type *a,
435 const struct cm_tile_type *b)
436 {
437 output_type_iterate(stat_index) {
438 if (a->production[stat_index] != b->production[stat_index]) {
439 return FALSE;
440 }
441 } output_type_iterate_end;
442
443 if (a->is_specialist != b->is_specialist) {
444 return FALSE;
445 }
446
447 return TRUE;
448 }
449
450 /****************************************************************************
451 Return TRUE if tile a is better or equal to tile b in all categories.
452
453 Specialists are considered better than workers (all else being equal)
454 since we have an unlimited number of them.
455 ****************************************************************************/
tile_type_better(const struct cm_tile_type * a,const struct cm_tile_type * b)456 static bool tile_type_better(const struct cm_tile_type *a,
457 const struct cm_tile_type *b)
458 {
459 output_type_iterate(stat_index) {
460 if (a->production[stat_index] < b->production[stat_index]) {
461 return FALSE;
462 }
463 } output_type_iterate_end;
464
465 if (a->is_specialist && !b->is_specialist) {
466 /* If A is a specialist and B isn't, and all of A's production is at
467 * least as good as B's, then A is better because it doesn't tie up
468 * the map tile. */
469 return TRUE;
470 } else if (!a->is_specialist && b->is_specialist) {
471 /* Vice versa. */
472 return FALSE;
473 }
474
475 return TRUE;
476 }
477
478 /****************************************************************************
479 If there is a tile type in the vector that is equivalent to the given
480 type, return its index. If not, return -1.
481
482 Equivalence is defined in tile_type_equal().
483 ****************************************************************************/
tile_type_vector_find_equivalent(const struct tile_type_vector * vec,const struct cm_tile_type * ptype)484 static int tile_type_vector_find_equivalent(
485 const struct tile_type_vector *vec,
486 const struct cm_tile_type *ptype)
487 {
488 int i;
489
490 for (i = 0; i < vec->size; i++) {
491 if (tile_type_equal(vec->p[i], ptype)) {
492 return i;
493 }
494 }
495
496 return -1;
497 }
498
499 /****************************************************************************
500 Return the number of tiles of this type that can be worked. For
501 is_specialist types this will always be infinite but for other types of
502 tiles it is limited by what's available in the citymap.
503 ****************************************************************************/
tile_type_num_tiles(const struct cm_tile_type * type)504 static int tile_type_num_tiles(const struct cm_tile_type *type)
505 {
506 if (type->is_specialist) {
507 return FC_INFINITY;
508 } else {
509 return tile_vector_size(&type->tiles);
510 }
511 }
512
513 /****************************************************************************
514 Return the number of tile types that are better than this type.
515
516 Note this isn't the same as the number of *tiles* that are better. There
517 may be more than one tile of each type (see tile_type_num_tiles).
518 ****************************************************************************/
tile_type_num_prereqs(const struct cm_tile_type * ptype)519 static int tile_type_num_prereqs(const struct cm_tile_type *ptype)
520 {
521 return ptype->better_types.size;
522 }
523
524 /****************************************************************************
525 Retrieve a tile type by index. For a given state there are a certain
526 number of tile types, which may be iterated over using this function
527 as a lookup.
528 ****************************************************************************/
tile_type_get(const struct cm_state * state,int type)529 static const struct cm_tile_type *tile_type_get(const struct cm_state *state,
530 int type)
531 {
532 /* Sanity check the index. */
533 fc_assert_ret_val(0 <= type, NULL);
534 fc_assert_ret_val(state->lattice.size > type, NULL);
535 return state->lattice.p[type];
536 }
537
538 /****************************************************************************
539 Retrieve a tile of a particular type by index. For a given tile type
540 there are a certain number of tiles (1 or more), which may be iterated
541 over using this function for index. Don't call this for is_specialist
542 types. See also tile_type_num_tiles().
543 ****************************************************************************/
tile_get(const struct cm_tile_type * ptype,int j)544 static const struct cm_tile *tile_get(const struct cm_tile_type *ptype, int j)
545 {
546 fc_assert_ret_val(!ptype->is_specialist, NULL);
547 fc_assert_ret_val(0 <= j, NULL);
548 fc_assert_ret_val(j < ptype->tiles.size, NULL);
549 return &ptype->tiles.p[j];
550 }
551
552
553 /**************************************************************************
554 Functions on the cm_fitness struct.
555 **************************************************************************/
556
557 /****************************************************************************
558 Return TRUE iff fitness A is strictly better than fitness B.
559 ****************************************************************************/
fitness_better(struct cm_fitness a,struct cm_fitness b)560 static bool fitness_better(struct cm_fitness a, struct cm_fitness b)
561 {
562 if (a.sufficient != b.sufficient) {
563 return a.sufficient;
564 }
565 return a.weighted > b.weighted;
566 }
567
568 /****************************************************************************
569 Return a fitness struct that is the worst possible result we can
570 represent.
571 ****************************************************************************/
worst_fitness(void)572 static struct cm_fitness worst_fitness(void)
573 {
574 struct cm_fitness f;
575
576 f.sufficient = FALSE;
577 f.weighted = -FC_INFINITY;
578 return f;
579 }
580
581 /****************************************************************************
582 Compute the fitness of the given surplus (and disorder/happy status)
583 according to the weights and minimums given in the parameter.
584 ****************************************************************************/
compute_fitness(const int surplus[],bool disorder,bool happy,const struct cm_parameter * parameter)585 static struct cm_fitness compute_fitness(const int surplus[],
586 bool disorder, bool happy,
587 const struct cm_parameter *parameter)
588 {
589 struct cm_fitness fitness;
590
591 fitness.sufficient = TRUE;
592 fitness.weighted = 0;
593
594 output_type_iterate(stat_index) {
595 fitness.weighted += surplus[stat_index] * parameter->factor[stat_index];
596 if (surplus[stat_index] < parameter->minimal_surplus[stat_index]) {
597 fitness.sufficient = FALSE;
598 }
599 } output_type_iterate_end;
600
601 if (happy) {
602 fitness.weighted += parameter->happy_factor;
603 } else if (parameter->require_happy) {
604 fitness.sufficient = FALSE;
605 }
606
607 if (disorder && !parameter->allow_disorder) {
608 fitness.sufficient = FALSE;
609 }
610
611 return fitness;
612 }
613
614 /***************************************************************************
615 Handle struct partial_solution.
616 - perform a deep copy
617 - convert to city
618 - convert to cm_result
619 ***************************************************************************/
620
621 /****************************************************************************
622 Allocate and initialize an empty solution.
623 ****************************************************************************/
init_partial_solution(struct partial_solution * into,int ntypes,int idle,bool negative_ok)624 static void init_partial_solution(struct partial_solution *into,
625 int ntypes, int idle, bool negative_ok)
626 {
627 into->worker_counts = fc_calloc(ntypes, sizeof(*into->worker_counts));
628 into->prereqs_filled = fc_calloc(ntypes, sizeof(*into->prereqs_filled));
629 if (negative_ok) {
630 output_type_iterate(otype) {
631 into->production[otype] = -FC_INFINITY;
632 } output_type_iterate_end;
633 } else {
634 memset(into->production, 0, sizeof(into->production));
635 }
636 into->idle = idle;
637 }
638
639 /****************************************************************************
640 Free all storage associated with the solution. This is basically the
641 opposite of init_partial_solution().
642 ****************************************************************************/
destroy_partial_solution(struct partial_solution * into)643 static void destroy_partial_solution(struct partial_solution *into)
644 {
645 free(into->worker_counts);
646 free(into->prereqs_filled);
647 }
648
649 /****************************************************************************
650 Copy the source solution into the destination one (the destination
651 solution must already be allocated).
652 ****************************************************************************/
copy_partial_solution(struct partial_solution * dst,const struct partial_solution * src,const struct cm_state * state)653 static void copy_partial_solution(struct partial_solution *dst,
654 const struct partial_solution *src,
655 const struct cm_state *state)
656 {
657 memcpy(dst->worker_counts, src->worker_counts,
658 sizeof(*dst->worker_counts) * num_types(state));
659 memcpy(dst->prereqs_filled, src->prereqs_filled,
660 sizeof(*dst->prereqs_filled) * num_types(state));
661 memcpy(dst->production, src->production, sizeof(dst->production));
662 dst->idle = src->idle;
663 }
664
665
666 /**************************************************************************
667 Evaluating a completed solution.
668 **************************************************************************/
669
670 /****************************************************************************
671 Apply the solution to state->workers_map.
672 ****************************************************************************/
apply_solution(struct cm_state * state,const struct partial_solution * soln)673 static void apply_solution(struct cm_state *state,
674 const struct partial_solution *soln)
675 {
676 struct city *pcity = state->pcity;
677 int i, citizen_count = 0, city_radius_sq = city_map_radius_sq_get(pcity);
678
679 #ifdef GATHER_TIME_STATS
680 performance.current->apply_count++;
681 #endif
682
683 fc_assert_ret(0 == soln->idle);
684
685 /* Clear all specialists, and remove all workers from fields (except
686 * the city center). */
687 memset(&pcity->specialists, 0, sizeof(pcity->specialists));
688
689 city_map_iterate(city_radius_sq, cindex, x, y) {
690 if (is_free_worked_index(cindex)) {
691 state->workers_map[cindex] = TRUE;
692 } else {
693 state->workers_map[cindex] = FALSE;
694 }
695 } city_map_iterate_end;
696
697 /* Now for each tile type, find the right number of such tiles and set them
698 * as worked. For specialists we just increase the number of specialists
699 * of that type. */
700 for (i = 0 ; i < num_types(state); i++) {
701 int nworkers = soln->worker_counts[i];
702 const struct cm_tile_type *type;
703
704 if (nworkers == 0) {
705 /* No citizens of this type. */
706 continue;
707 }
708 citizen_count += nworkers;
709
710 type = tile_type_get(state, i);
711
712 if (type->is_specialist) {
713 /* Just increase the number of specialists. */
714 pcity->specialists[type->spec] += nworkers;
715 } else {
716 int j;
717
718 /* Place citizen workers onto the citymap tiles. */
719 for (j = 0; j < nworkers; j++) {
720 const struct cm_tile *cmtile = tile_get(type, j);
721
722 state->workers_map[cmtile->index] = TRUE;
723 }
724 }
725 }
726
727 /* Finally we must refresh the city to reset all the precomputed fields. */
728 city_refresh_from_main_map(pcity, state->workers_map);
729 fc_assert_ret(citizen_count == city_size_get(pcity));
730 }
731
732 /****************************************************************************
733 Convert the city's surplus numbers into an array. Get the happy/disorder
734 values, too. This fills in the surplus array and disorder and happy
735 values based on the city's data.
736 ****************************************************************************/
get_city_surplus(const struct city * pcity,int surplus[],bool * disorder,bool * happy)737 static void get_city_surplus(const struct city *pcity,
738 int surplus[],
739 bool *disorder, bool *happy)
740 {
741 output_type_iterate(o) {
742 surplus[o] = pcity->surplus[o];
743 } output_type_iterate_end;
744
745 *disorder = city_unhappy(pcity);
746 *happy = city_happy(pcity);
747 }
748
749 /****************************************************************************
750 Compute the fitness of the solution. This is a fairly expensive operation.
751 ****************************************************************************/
evaluate_solution(struct cm_state * state,const struct partial_solution * soln)752 static struct cm_fitness evaluate_solution(struct cm_state *state,
753 const struct partial_solution *soln)
754 {
755 struct city *pcity = state->pcity;
756 int surplus[O_LAST];
757 bool disorder, happy;
758
759 /* apply and evaluate the solution, backup is done in find_best_solution */
760 apply_solution(state, soln);
761 get_city_surplus(pcity, surplus, &disorder, &happy);
762
763 /* if this solution is not content, we have an estimate on min. luxuries */
764 if (disorder) {
765 /* We have to consider the influence of each specialist in this
766 solution possibly 'hiding' a potential unhappy citizen who
767 could require luxuries.
768 Since we know the city is in disorder, we can discount most
769 effects that make citizens content, since they clearly weren't
770 sufficient.
771 This may not be sufficient luxury to make the city content (due
772 to military unhappiness etc), but certainly no less will do.
773 (Specialists may also be making angry citizens content, requiring
774 additional luxuries, but we don't try to consider that here; this
775 just means we might explore some solutions unnecessarily.) */
776 int specialists_amount = city_specialists(pcity);
777 int max_content = player_content_citizens(city_owner(pcity));
778
779 state->min_luxury = surplus[O_LUXURY]
780 + game.info.happy_cost * MAX(specialists_amount - max_content, 0)
781 + 1;
782 }
783
784 return compute_fitness(surplus, disorder, happy, &state->parameter);
785 }
786
787 /****************************************************************************
788 Convert the solution into a cm_result. This is a fairly expensive
789 operation.
790 ****************************************************************************/
convert_solution_to_result(struct cm_state * state,const struct partial_solution * soln,struct cm_result * result)791 static void convert_solution_to_result(struct cm_state *state,
792 const struct partial_solution *soln,
793 struct cm_result *result)
794 {
795 struct cm_fitness fitness;
796
797 if (soln->idle != 0) {
798 /* If there are unplaced citizens it's not a real solution, so the
799 * result is invalid. */
800 result->found_a_valid = FALSE;
801 return;
802 }
803
804 /* apply and evaluate the solution, backup is done in find_best_solution */
805 apply_solution(state, soln);
806 cm_result_copy(result, state->pcity, state->workers_map);
807
808 /* result->found_a_valid should be only true if it matches the
809 * parameter; figure out if it does */
810 fitness = compute_fitness(result->surplus, result->disorder,
811 result->happy, &state->parameter);
812 result->found_a_valid = fitness.sufficient;
813 }
814
815 /***************************************************************************
816 Compare functions to allow sorting lattice vectors.
817 ***************************************************************************/
818
819 /****************************************************************************
820 All the sorting in this code needs to respect the partial order
821 in the lattice: if a is a parent of b, then a must sort before b.
822 This routine enforces that relatively cheaply (without looking through
823 the worse_types vectors of a and b), but requires that lattice_depth
824 has already been computed.
825 ****************************************************************************/
compare_tile_type_by_lattice_order(const struct cm_tile_type * a,const struct cm_tile_type * b)826 static int compare_tile_type_by_lattice_order(const struct cm_tile_type *a,
827 const struct cm_tile_type *b)
828 {
829 if (a == b) {
830 return 0;
831 }
832
833 /* Least depth first */
834 if (a->lattice_depth != b->lattice_depth) {
835 return a->lattice_depth - b->lattice_depth;
836 }
837
838 /* With equal depth, break ties arbitrarily, more production first. */
839 output_type_iterate(stat_index) {
840 if (a->production[stat_index] != b->production[stat_index]) {
841 return b->production[stat_index] - a->production[stat_index];
842 }
843 } output_type_iterate_end;
844
845 /* If we get here, then we have two copies of identical types, an error */
846 fc_assert(FALSE);
847 return 0;
848 }
849
850 /****************************************************************************
851 Sort by fitness. Since fitness is monotone in the production,
852 if a has higher fitness than b, then a cannot be a child of b, so
853 this respects the partial order -- unless a and b have equal fitness.
854 In that case, use compare_tile_type_by_lattice_order.
855 ****************************************************************************/
compare_tile_type_by_fitness(const void * va,const void * vb)856 static int compare_tile_type_by_fitness(const void *va, const void *vb)
857 {
858 struct cm_tile_type * const *a = va;
859 struct cm_tile_type * const *b = vb;
860 double diff;
861
862 if (*a == *b) {
863 return 0;
864 }
865
866 /* To avoid double->int roundoff problems, we call a result non-zero only
867 * if it's larger than 0.5. */
868 diff = (*b)->estimated_fitness - (*a)->estimated_fitness;
869 if (diff > 0.5) {
870 return 1; /* return value is int; don't round down! */
871 }
872 if (diff < -0.5) {
873 return -1;
874 }
875
876 return compare_tile_type_by_lattice_order(*a, *b);
877 }
878
879 static Output_type_id compare_key;
880 static double compare_key_trade_bonus;
881
882 /****************************************************************************
883 Compare by the production of type compare_key.
884 If a produces more food than b, then a cannot be a child of b, so
885 this respects the partial order -- unless a and b produce equal food.
886 In that case, use compare_tile_type_by_lattice_order.
887 ****************************************************************************/
compare_tile_type_by_stat(const void * va,const void * vb)888 static int compare_tile_type_by_stat(const void *va, const void *vb)
889 {
890 struct cm_tile_type * const *a = va;
891 struct cm_tile_type * const *b = vb;
892
893 if (*a == *b) {
894 return 0;
895 }
896
897 /* consider the influence of trade on science, luxury, gold
898 for compute_max_stats_heuristics, which uses these sorted arrays,
899 it is essential, that the sorting is correct, else promising
900 branches get pruned */
901 double valuea = (*a)->production[compare_key] +
902 compare_key_trade_bonus * (*a)->production[O_TRADE];
903 double valueb = (*b)->production[compare_key] +
904 compare_key_trade_bonus * (*b)->production[O_TRADE];
905
906 /* most production of what we care about goes first */
907 /* double compare is ok, both values are calculated in the same way
908 and should only be considered equal, if equal in compare_key
909 and O_TRADE */
910 if (valuea != valueb) {
911 /* b-a so we sort big numbers first */
912 return valueb - valuea;
913 }
914
915 return compare_tile_type_by_lattice_order(*a, *b);
916 }
917
918 /***************************************************************************
919 Compute the tile-type lattice.
920 ***************************************************************************/
921
922 /****************************************************************************
923 Compute the production of tile [x,y] and stuff it into the tile type.
924 Doesn't touch the other fields.
925 ****************************************************************************/
compute_tile_production(const struct city * pcity,const struct tile * ptile,struct cm_tile_type * out)926 static void compute_tile_production(const struct city *pcity,
927 const struct tile *ptile,
928 struct cm_tile_type *out)
929 {
930 bool is_celebrating = base_city_celebrating(pcity);
931
932 output_type_iterate(o) {
933 out->production[o] = city_tile_output(pcity, ptile, is_celebrating, o);
934 } output_type_iterate_end;
935 }
936
937 /****************************************************************************
938 Add the tile [x,y], with production indicated by type, to
939 the tile-type lattice. 'newtype' can be on the stack.
940 x/y are ignored if the type is a specialist.
941 If the type is new, it is linked in and the lattice_index set.
942 The lattice_depth is not set.
943 ****************************************************************************/
tile_type_lattice_add(struct tile_type_vector * lattice,const struct cm_tile_type * newtype,int tindex)944 static void tile_type_lattice_add(struct tile_type_vector *lattice,
945 const struct cm_tile_type *newtype,
946 int tindex)
947 {
948 struct cm_tile_type *type;
949 int i;
950
951 i = tile_type_vector_find_equivalent(lattice, newtype);
952 if (i >= 0) {
953 /* We already have this type of tile; use it. */
954 type = lattice->p[i];
955 } else {
956 /* This is a new tile type; add it to the lattice. */
957 type = tile_type_dup(newtype);
958
959 /* link up to the types we dominate, and those that dominate us */
960 tile_type_vector_iterate(lattice, other) {
961 if (tile_type_better(other, type)) {
962 tile_type_vector_append(&type->better_types, other);
963 tile_type_vector_append(&other->worse_types, type);
964 } else if (tile_type_better(type, other)) {
965 tile_type_vector_append(&other->better_types, type);
966 tile_type_vector_append(&type->worse_types, other);
967 }
968 } tile_type_vector_iterate_end;
969
970 /* insert into the list */
971 type->lattice_index = lattice->size;
972 tile_type_vector_append(lattice, type);
973 }
974
975 /* Finally, add the tile to the tile type. */
976 if (!type->is_specialist) {
977 struct cm_tile tile;
978
979 tile.type = type;
980 tile.index = tindex;
981
982 tile_vector_append(&type->tiles, tile);
983 }
984 }
985
986 /*
987 * Add the specialist types to the lattice.
988 */
989
990 /****************************************************************************
991 Create lattice nodes for each type of specialist. This adds a new
992 tile_type for each specialist type.
993 ****************************************************************************/
init_specialist_lattice_nodes(struct tile_type_vector * lattice,const struct city * pcity)994 static void init_specialist_lattice_nodes(struct tile_type_vector *lattice,
995 const struct city *pcity)
996 {
997 struct cm_tile_type type;
998
999 tile_type_init(&type);
1000 type.is_specialist = TRUE;
1001
1002 /* for each specialist type, create a tile_type that has as production
1003 * the bonus for the specialist (if the city is allowed to use it) */
1004 specialist_type_iterate(i) {
1005 if (city_can_use_specialist(pcity, i)) {
1006 type.spec = i;
1007 output_type_iterate(output) {
1008 type.production[output] = get_specialist_output(pcity, i, output);
1009 } output_type_iterate_end;
1010
1011 tile_type_lattice_add(lattice, &type, 0);
1012 }
1013 } specialist_type_iterate_end;
1014 }
1015
1016 /****************************************************************************
1017 Topologically sort the lattice.
1018 Sets the lattice_depth field.
1019 Important assumption in this code: we've computed the transitive
1020 closure of the lattice. That is, better_types includes all types that
1021 are better.
1022 ****************************************************************************/
top_sort_lattice(struct tile_type_vector * lattice)1023 static void top_sort_lattice(struct tile_type_vector *lattice)
1024 {
1025 int i;
1026 bool marked[lattice->size];
1027 bool will_mark[lattice->size];
1028 struct tile_type_vector vectors[2];
1029 struct tile_type_vector *current, *next;
1030
1031 memset(marked, 0, sizeof(marked));
1032 memset(will_mark, 0, sizeof(will_mark));
1033
1034 tile_type_vector_init(&vectors[0]);
1035 tile_type_vector_init(&vectors[1]);
1036 current = &vectors[0];
1037 next = &vectors[1];
1038
1039 /* fill up 'next' */
1040 tile_type_vector_iterate(lattice, ptype) {
1041 if (tile_type_num_prereqs(ptype) == 0) {
1042 tile_type_vector_append(next, ptype);
1043 }
1044 } tile_type_vector_iterate_end;
1045
1046 /* while we have nodes to process: mark the nodes whose prereqs have
1047 * all been visited. Then, store all the new nodes on the frontier. */
1048 while (next->size != 0) {
1049 /* what was the next frontier is now the current frontier */
1050 struct tile_type_vector *vtmp = current;
1051
1052 current = next;
1053 next = vtmp;
1054 next->size = 0; /* clear out the contents */
1055
1056 /* look over the current frontier and process everyone */
1057 tile_type_vector_iterate(current, ptype) {
1058 /* see if all prereqs were marked. If so, decide to mark this guy,
1059 and put all the descendents on 'next'. */
1060 bool can_mark = TRUE;
1061 int sumdepth = 0;
1062
1063 if (will_mark[ptype->lattice_index]) {
1064 continue; /* we've already been processed */
1065 }
1066 tile_type_vector_iterate(&ptype->better_types, better) {
1067 if (!marked[better->lattice_index]) {
1068 can_mark = FALSE;
1069 break;
1070 } else {
1071 sumdepth += tile_type_num_tiles(better);
1072 if (sumdepth >= FC_INFINITY) {
1073 /* if this is the case, then something better could
1074 always be used, and the same holds for our children */
1075 sumdepth = FC_INFINITY;
1076 can_mark = TRUE;
1077 break;
1078 }
1079 }
1080 } tile_type_vector_iterate_end;
1081 if (can_mark) {
1082 /* mark and put successors on the next frontier */
1083 will_mark[ptype->lattice_index] = TRUE;
1084 tile_type_vector_iterate(&ptype->worse_types, worse) {
1085 tile_type_vector_append(next, worse);
1086 } tile_type_vector_iterate_end;
1087
1088 /* this is what we spent all this time computing. */
1089 ptype->lattice_depth = sumdepth;
1090 }
1091 } tile_type_vector_iterate_end;
1092
1093 /* now, actually mark everyone and get set for next loop */
1094 for (i = 0; i < lattice->size; i++) {
1095 marked[i] = marked[i] || will_mark[i];
1096 will_mark[i] = FALSE;
1097 }
1098 }
1099
1100 tile_type_vector_free(&vectors[0]);
1101 tile_type_vector_free(&vectors[1]);
1102 }
1103
1104 /****************************************************************************
1105 Remove unreachable lattice nodes to speed up processing later.
1106 This doesn't reduce the number of evaluations we do, it just
1107 reduces the number of times we loop over and reject tile types
1108 we can never use.
1109
1110 A node is unreachable if there are fewer available workers
1111 than are needed to fill up all predecessors. A node at depth
1112 two needs three workers to be reachable, for example (two to fill
1113 the predecessors, and one for the tile). We remove a node if
1114 its depth is equal to the city size, or larger.
1115
1116 We could clean up the tile arrays in each type (if we have two workers,
1117 we can use only the first tile of a depth 1 tile type), but that
1118 wouldn't save us anything later.
1119 ****************************************************************************/
clean_lattice(struct tile_type_vector * lattice,const struct city * pcity)1120 static void clean_lattice(struct tile_type_vector *lattice,
1121 const struct city *pcity)
1122 {
1123 int i, j; /* i is the index we read, j is the index we write */
1124 struct tile_type_vector tofree;
1125 bool forced_loop = FALSE;
1126
1127 /* We collect the types we want to remove and free them in one fell
1128 swoop at the end, in order to avoid memory errors. */
1129 tile_type_vector_init(&tofree);
1130
1131 /* forced_loop is workaround for what seems like gcc optimization
1132 * bug.
1133 * This applies to -O2 optimization on some distributions. */
1134 if (lattice->size > 0) {
1135 forced_loop = TRUE;
1136 }
1137 for (i = 0, j = 0; i < lattice->size || forced_loop; i++) {
1138 struct cm_tile_type *ptype = lattice->p[i];
1139
1140 forced_loop = FALSE;
1141
1142 if (ptype->lattice_depth >= city_size_get(pcity)) {
1143 tile_type_vector_append(&tofree, ptype);
1144 } else {
1145 /* Remove links to children that are being removed. */
1146
1147 int ci, cj; /* 'c' for 'child'; read from ci, write to cj */
1148
1149 lattice->p[j] = ptype;
1150 lattice->p[j]->lattice_index = j;
1151 j++;
1152
1153 for (ci = 0, cj = 0; ci < ptype->worse_types.size; ci++) {
1154 const struct cm_tile_type *ptype2 = ptype->worse_types.p[ci];
1155
1156 if (ptype2->lattice_depth < city_size_get(pcity)) {
1157 ptype->worse_types.p[cj] = ptype->worse_types.p[ci];
1158 cj++;
1159 }
1160 }
1161 ptype->worse_types.size = cj;
1162 }
1163 }
1164 lattice->size = j;
1165
1166 tile_type_vector_free_all(&tofree);
1167 }
1168
1169 /****************************************************************************
1170 Determine the estimated_fitness fields, and sort by that.
1171 estimate_fitness is later, in a section of code that isolates
1172 much of the domain-specific knowledge.
1173 ****************************************************************************/
sort_lattice_by_fitness(const struct cm_state * state,struct tile_type_vector * lattice)1174 static void sort_lattice_by_fitness(const struct cm_state *state,
1175 struct tile_type_vector *lattice)
1176 {
1177 int i;
1178
1179 /* compute fitness */
1180 tile_type_vector_iterate(lattice, ptype) {
1181 ptype->estimated_fitness = estimate_fitness(state, ptype->production);
1182 } tile_type_vector_iterate_end;
1183
1184 /* sort by it */
1185 qsort(lattice->p, lattice->size, sizeof(*lattice->p),
1186 compare_tile_type_by_fitness);
1187
1188 /* fix the lattice indices */
1189 for (i = 0; i < lattice->size; i++) {
1190 lattice->p[i]->lattice_index = i;
1191 }
1192
1193 log_base(LOG_LATTICE, "sorted lattice:");
1194 print_lattice(LOG_LATTICE, lattice);
1195 }
1196
1197 /****************************************************************************
1198 Create the lattice.
1199 ****************************************************************************/
init_tile_lattice(struct city * pcity,struct tile_type_vector * lattice)1200 static void init_tile_lattice(struct city *pcity,
1201 struct tile_type_vector *lattice)
1202 {
1203 struct cm_tile_type type;
1204 struct tile *pcenter = city_tile(pcity);
1205
1206 /* add all the fields into the lattice */
1207 tile_type_init(&type); /* init just once */
1208
1209 city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
1210 ctindex) {
1211 if (is_free_worked(pcity, ptile)) {
1212 continue;
1213 } else if (city_can_work_tile(pcity, ptile)) {
1214 compute_tile_production(pcity, ptile, &type); /* clobbers type */
1215 tile_type_lattice_add(lattice, &type, ctindex); /* copy type if needed */
1216 }
1217 } city_tile_iterate_index_end;
1218
1219 /* Add all the specialists into the lattice. */
1220 init_specialist_lattice_nodes(lattice, pcity);
1221
1222 /* Set the lattice_depth fields, and clean up unreachable nodes. */
1223 top_sort_lattice(lattice);
1224 clean_lattice(lattice, pcity);
1225
1226 /* All done now. */
1227 print_lattice(LOG_LATTICE, lattice);
1228 }
1229
1230
1231 /****************************************************************************
1232
1233 Handling the choice stack for the bb algorithm.
1234
1235 ****************************************************************************/
1236
1237
1238 /****************************************************************************
1239 Return TRUE iff the stack is empty.
1240 ****************************************************************************/
choice_stack_empty(struct cm_state * state)1241 static bool choice_stack_empty(struct cm_state *state)
1242 {
1243 return state->choice.size == 0;
1244 }
1245
1246 /****************************************************************************
1247 Return the last choice in the stack.
1248 ****************************************************************************/
last_choice(struct cm_state * state)1249 static int last_choice(struct cm_state *state)
1250 {
1251 fc_assert_ret_val(!choice_stack_empty(state), -1);
1252 return state->choice.stack[state->choice.size - 1];
1253 }
1254
1255 /****************************************************************************
1256 Return the number of different tile types. There is one tile type for
1257 each type specialist, plus one for each distinct (different amounts of
1258 production) citymap tile.
1259 ****************************************************************************/
num_types(const struct cm_state * state)1260 static int num_types(const struct cm_state *state)
1261 {
1262 return tile_type_vector_size(&state->lattice);
1263 }
1264
1265 /****************************************************************************
1266 Update the solution to assign 'number' more workers on to tiles of the
1267 given type. 'number' may be negative, in which case we're removing
1268 workers.
1269 We do lots of sanity checking, since many bugs can get caught here.
1270 ****************************************************************************/
add_workers(struct partial_solution * soln,int itype,int number,const struct cm_state * state)1271 static void add_workers(struct partial_solution *soln,
1272 int itype, int number,
1273 const struct cm_state *state)
1274 {
1275 const struct cm_tile_type *ptype = tile_type_get(state, itype);
1276 int newcount;
1277 int old_worker_count = soln->worker_counts[itype];
1278
1279 if (number == 0) {
1280 return;
1281 }
1282
1283 /* update the number of idle workers */
1284 newcount = soln->idle - number;
1285 fc_assert_ret(newcount >= 0);
1286 fc_assert_ret(newcount <= city_size_get(state->pcity));
1287 soln->idle = newcount;
1288
1289 /* update the worker counts */
1290 newcount = soln->worker_counts[itype] + number;
1291 fc_assert_ret(newcount >= 0);
1292 fc_assert_ret(newcount <= tile_type_num_tiles(ptype));
1293 soln->worker_counts[itype] = newcount;
1294
1295 /* update prereqs array: if we are no longer full but we were,
1296 * we need to decrement the count, and vice-versa. */
1297 if (old_worker_count == tile_type_num_tiles(ptype)) {
1298 fc_assert_ret(number < 0);
1299 tile_type_vector_iterate(&ptype->worse_types, other) {
1300 soln->prereqs_filled[other->lattice_index]--;
1301 fc_assert_ret(soln->prereqs_filled[other->lattice_index] >= 0);
1302 } tile_type_vector_iterate_end;
1303 } else if (soln->worker_counts[itype] == tile_type_num_tiles(ptype)) {
1304 fc_assert_ret(number > 0);
1305 tile_type_vector_iterate(&ptype->worse_types, other) {
1306 soln->prereqs_filled[other->lattice_index]++;
1307 fc_assert_ret(soln->prereqs_filled[other->lattice_index]
1308 <= tile_type_num_prereqs(other));
1309 } tile_type_vector_iterate_end;
1310 }
1311
1312 /* update production */
1313 output_type_iterate(stat_index) {
1314 newcount = soln->production[stat_index] + number * ptype->production[stat_index];
1315 soln->production[stat_index] = newcount;
1316 } output_type_iterate_end;
1317 }
1318
1319 /****************************************************************************
1320 Add just one worker to the solution.
1321 ****************************************************************************/
add_worker(struct partial_solution * soln,int itype,const struct cm_state * state)1322 static void add_worker(struct partial_solution *soln,
1323 int itype, const struct cm_state *state)
1324 {
1325 add_workers(soln, itype, 1, state);
1326 }
1327
1328 /****************************************************************************
1329 Remove just one worker from the solution.
1330 ****************************************************************************/
remove_worker(struct partial_solution * soln,int itype,const struct cm_state * state)1331 static void remove_worker(struct partial_solution *soln,
1332 int itype, const struct cm_state *state)
1333 {
1334 add_workers(soln, itype, -1, state);
1335 }
1336
1337 /****************************************************************************
1338 Remove a worker from the current solution, and pop once off the
1339 choice stack.
1340 ****************************************************************************/
pop_choice(struct cm_state * state)1341 static void pop_choice(struct cm_state *state)
1342 {
1343 fc_assert_ret(!choice_stack_empty(state));
1344 remove_worker(&state->current, last_choice(state), state);
1345 state->choice.size--;
1346 }
1347
1348 /****************************************************************************
1349 True if all tiles better than this type have been used.
1350 ****************************************************************************/
prereqs_filled(const struct partial_solution * soln,int type,const struct cm_state * state)1351 static bool prereqs_filled(const struct partial_solution *soln, int type,
1352 const struct cm_state *state)
1353 {
1354 const struct cm_tile_type *ptype = tile_type_get(state, type);
1355 int prereqs = tile_type_num_prereqs(ptype);
1356
1357 return soln->prereqs_filled[type] == prereqs;
1358 }
1359
1360 /****************************************************************************
1361 Return the next choice to make after oldchoice.
1362 A choice can be made if:
1363 - we haven't used all the tiles
1364 - we've used up all the better tiles
1365 - using that choice, we have a hope of doing better than the best
1366 solution so far.
1367 If oldchoice == -1 then we return the first possible choice.
1368 ****************************************************************************/
next_choice(struct cm_state * state,int oldchoice,bool negative_ok)1369 static int next_choice(struct cm_state *state, int oldchoice, bool negative_ok)
1370 {
1371 int newchoice;
1372
1373 for (newchoice = oldchoice + 1;
1374 newchoice < num_types(state); newchoice++) {
1375 const struct cm_tile_type *ptype = tile_type_get(state, newchoice);
1376
1377 if (!ptype->is_specialist && (state->current.worker_counts[newchoice]
1378 == tile_vector_size(&ptype->tiles))) {
1379 /* we've already used all these tiles */
1380 continue;
1381 }
1382 if (!prereqs_filled(&state->current, newchoice, state)) {
1383 /* we could use a strictly better tile instead */
1384 continue;
1385 }
1386 if (!choice_is_promising(state, newchoice, negative_ok)) {
1387 /* heuristic says we can't beat the best going this way */
1388 log_base(LOG_PRUNE_BRANCH, "--- pruning branch ---");
1389 print_partial_solution(LOG_PRUNE_BRANCH, &state->current, state);
1390 print_tile_type(LOG_PRUNE_BRANCH, tile_type_get(state, newchoice),
1391 " + worker on ");
1392 log_base(LOG_PRUNE_BRANCH, "--- branch pruned ---");
1393 continue;
1394 }
1395 break;
1396 }
1397
1398 /* returns num_types if no next choice was available. */
1399 return newchoice;
1400 }
1401
1402
1403 /****************************************************************************
1404 Pick a sibling choice to the last choice. This works down the branch to
1405 see if a choice that actually looks worse may actually be better.
1406 ****************************************************************************/
take_sibling_choice(struct cm_state * state,bool negative_ok)1407 static bool take_sibling_choice(struct cm_state *state, bool negative_ok)
1408 {
1409 int oldchoice = last_choice(state);
1410 int newchoice;
1411
1412 /* need to remove first, to run the heuristic */
1413 remove_worker(&state->current, oldchoice, state);
1414 newchoice = next_choice(state, oldchoice, negative_ok);
1415
1416 if (newchoice == num_types(state)) {
1417 /* add back in so the caller can then remove it again. */
1418 add_worker(&state->current, oldchoice, state);
1419 return FALSE;
1420 } else {
1421 add_worker(&state->current, newchoice, state);
1422 state->choice.stack[state->choice.size-1] = newchoice;
1423 /* choice.size is unchanged */
1424 return TRUE;
1425 }
1426 }
1427
1428 /****************************************************************************
1429 Go down from the current branch, if we can.
1430 Thanks to the fact that the lattice is sorted by depth, we can keep the
1431 choice stack sorted -- that is, we can start our next choice as
1432 last_choice - 1. This keeps us from trying out all permutations of the
1433 same combination.
1434 ****************************************************************************/
take_child_choice(struct cm_state * state,bool negative_ok)1435 static bool take_child_choice(struct cm_state *state, bool negative_ok)
1436 {
1437 int oldchoice, newchoice;
1438
1439 if (state->current.idle == 0) {
1440 return FALSE;
1441 }
1442
1443 if (state->choice.size == 0) {
1444 oldchoice = 0;
1445 } else {
1446 oldchoice = last_choice(state);
1447 }
1448
1449 /* oldchoice-1 because we can use oldchoice again */
1450 newchoice = next_choice(state, oldchoice - 1, negative_ok);
1451
1452 /* did we fail? */
1453 if (newchoice == num_types(state)) {
1454 return FALSE;
1455 }
1456
1457 /* now push the new choice on the choice stack */
1458 add_worker(&state->current, newchoice, state);
1459 state->choice.stack[state->choice.size] = newchoice;
1460 state->choice.size++;
1461 return TRUE;
1462 }
1463
1464
1465 /****************************************************************************
1466 Complete the solution by choosing tiles in order off the given
1467 tile lattice.
1468 ****************************************************************************/
complete_solution(struct partial_solution * soln,const struct cm_state * state,const struct tile_type_vector * lattice)1469 static void complete_solution(struct partial_solution *soln,
1470 const struct cm_state *state,
1471 const struct tile_type_vector *lattice)
1472 {
1473 int last_worker_choice = -1;
1474 int i;
1475
1476 if (soln->idle == 0) {
1477 return;
1478 }
1479
1480 /* find the last worker type added (-1 if none) */
1481 for (i = 0; i < num_types(state); i++) {
1482 if (soln->worker_counts[i] != 0) {
1483 last_worker_choice = i;
1484 }
1485 }
1486
1487 /* While there are idle workers, pick up the next-best kind of tile,
1488 * and assign the workers to the tiles.
1489 * Respect lexicographic order and prerequisites. */
1490 tile_type_vector_iterate(lattice, ptype) {
1491 int used = soln->worker_counts[ptype->lattice_index];
1492 int total = tile_type_num_tiles(ptype);
1493 int touse;
1494
1495 if (ptype->lattice_index < last_worker_choice) {
1496 /* lex-order: we can't use ptype (some other branch
1497 will check this combination, or already did) */
1498 continue;
1499 }
1500 if (!prereqs_filled(soln, ptype->lattice_index, state)) {
1501 /* don't bother using this tile before all better tiles are used */
1502 continue;
1503 }
1504
1505 touse = total - used;
1506 if (touse > soln->idle) {
1507 touse = soln->idle;
1508 }
1509 add_workers(soln, ptype->lattice_index, touse, state);
1510
1511 if (soln->idle == 0) {
1512 /* nothing left to do here */
1513 return;
1514 }
1515 } tile_type_vector_iterate_end;
1516 }
1517
1518 /****************************************************************************
1519 return number of specialists used in partial solution
1520 ****************************************************************************/
specialists_in_solution(const struct cm_state * state,const struct partial_solution * soln)1521 static int specialists_in_solution(const struct cm_state *state,
1522 const struct partial_solution *soln)
1523 {
1524 int count = 0;
1525 int i;
1526
1527 for (i = 0 ; i < num_types(state); i++) {
1528 if (soln->worker_counts[i] > 0 && tile_type_get(state, i)->is_specialist) {
1529 count += soln->worker_counts[i];
1530 }
1531 }
1532
1533 return count;
1534 }
1535
1536 /****************************************************************************
1537 The heuristic:
1538 A partial solution cannot produce more food than the amount of food it
1539 currently generates plus then placing all its workers on the best food
1540 tiles. Similarly with all the other stats.
1541 If we take the max along each production, and it's not better than the
1542 best in at least one stat, the partial solution isn't worth anything.
1543
1544 This function computes the max-stats produced by a partial solution.
1545 ****************************************************************************/
compute_max_stats_heuristic(const struct cm_state * state,const struct partial_solution * soln,int production[],int check_choice,bool negative_ok)1546 static void compute_max_stats_heuristic(const struct cm_state *state,
1547 const struct partial_solution *soln,
1548 int production[],
1549 int check_choice, bool negative_ok)
1550 {
1551 struct partial_solution solnplus; /* will be soln, plus some tiles */
1552
1553 /* Production is whatever the solution produces, plus the
1554 most possible of each kind of production the idle workers could
1555 produce */
1556
1557 if (soln->idle == 1) {
1558 /* Then the total solution is soln + this new worker. So we know the
1559 production exactly, and can shortcut the later code. */
1560 const struct cm_tile_type *ptype = tile_type_get(state, check_choice);
1561
1562 memcpy(production, soln->production, sizeof(soln->production));
1563 output_type_iterate(stat_index) {
1564 production[stat_index] += ptype->production[stat_index];
1565 } output_type_iterate_end;
1566
1567 } else {
1568
1569 /* initialize solnplus here, after the shortcut check */
1570 init_partial_solution(&solnplus, num_types(state),
1571 city_size_get(state->pcity),
1572 negative_ok);
1573
1574 output_type_iterate(stat_index) {
1575 /* compute the solution that has soln, then the check_choice,
1576 then complete it with the best available tiles for the stat. */
1577 copy_partial_solution(&solnplus, soln, state);
1578 add_worker(&solnplus, check_choice, state);
1579 complete_solution(&solnplus, state, &state->lattice_by_prod[stat_index]);
1580
1581 production[stat_index] = solnplus.production[stat_index];
1582 } output_type_iterate_end;
1583
1584 destroy_partial_solution(&solnplus);
1585
1586 }
1587
1588 /* we found the basic production, however, bonus, taxes,
1589 free production, tithes, traderoutes are missing
1590 we add free production, and have the city.c code do the rest */
1591
1592 struct city *pcity = state->pcity;
1593 struct tile *pcenter = city_tile(pcity);
1594 bool is_celebrating = base_city_celebrating(pcity);
1595
1596 output_type_iterate(stat_index) {
1597 int base = production[stat_index];
1598
1599 city_tile_iterate(city_map_radius_sq_get(pcity), pcenter, ptile) {
1600 if (is_free_worked(pcity, ptile)) {
1601 base += city_tile_output(pcity, ptile, is_celebrating, stat_index);
1602 }
1603 } city_tile_iterate_end;
1604 pcity->citizen_base[stat_index] = base;
1605 } output_type_iterate_end;
1606
1607 set_city_production(pcity);
1608 memcpy(production, pcity->prod, sizeof(pcity->prod));
1609 }
1610
1611 /****************************************************************************
1612 A choice is unpromising if isn't better than the best in at least
1613 one way.
1614 A choice is also unpromising if any of the stats is less than the
1615 absolute minimum (in practice, this matters a lot more).
1616 ****************************************************************************/
choice_is_promising(struct cm_state * state,int newchoice,bool negative_ok)1617 static bool choice_is_promising(struct cm_state *state, int newchoice,
1618 bool negative_ok)
1619 {
1620 int production[O_LAST];
1621 bool beats_best = FALSE;
1622
1623 /* this computes an upper bound (componentwise) for the current branch,
1624 if it is worse in every component than the best, or still unsufficient,
1625 then we can prune the whole branch */
1626 compute_max_stats_heuristic(state, &state->current, production, newchoice,
1627 negative_ok);
1628
1629 output_type_iterate(stat_index) {
1630 if (production[stat_index] < state->min_production[stat_index]) {
1631 log_base(LOG_PRUNE_BRANCH, "--- pruning: insufficient %s (%d < %d)",
1632 get_output_name(stat_index), production[stat_index],
1633 state->min_production[stat_index]);
1634 return FALSE;
1635 }
1636 if (production[stat_index] > state->best.production[stat_index]
1637 && state->parameter.factor[stat_index] > 0 ) {
1638 beats_best = TRUE;
1639 /* may still fail to meet min at another production type, so
1640 * don't short-circuit */
1641 }
1642 } output_type_iterate_end;
1643
1644 /* If we don't get the city content, we assume using every idle worker
1645 as specialist and the maximum producible luxury already computed.
1646 If this is less than the amount of luxury we calculated in
1647 evaluate_solution() (where min_luxury is set), when we observed the
1648 city in disorder, then this is clearly not worth pursuing.
1649 (Since we're comparing to evaluate_solution()'s calculation, we
1650 don't need to take effects, angry citizens etc into account here
1651 either.)
1652 FIXME: this heuristic will break in rulesets where specialists can
1653 influence happiness other than by direct production of luxury. */
1654 {
1655 int specialists_amount = specialists_in_solution(state, &state->current);
1656 int max_content = player_content_citizens(city_owner(state->pcity));
1657 int specialists_suppress_unhappy
1658 = MAX(specialists_amount + state->current.idle - max_content, 0);
1659 int max_luxury = production[O_LUXURY]
1660 + game.info.happy_cost * specialists_suppress_unhappy;
1661
1662 if (max_luxury < state->min_luxury ) {
1663 log_base(LOG_PRUNE_BRANCH, "--- pruning: disorder (%d + %d*%d < %d)",
1664 production[O_LUXURY],
1665 game.info.happy_cost,
1666 specialists_suppress_unhappy,
1667 state->min_luxury);
1668 return FALSE;
1669 }
1670 }
1671 if (!beats_best) {
1672 log_base(LOG_PRUNE_BRANCH, "--- pruning: best is better in all important ways");
1673 }
1674 return beats_best;
1675 }
1676
1677 /****************************************************************************
1678 Initialize minimal production needed to be sufficient
1679 ****************************************************************************/
init_min_production(struct cm_state * state)1680 static void init_min_production(struct cm_state *state)
1681 {
1682 struct city *pcity = state->pcity;
1683
1684 output_type_iterate(o) {
1685 state->min_production[o] = pcity->usage[o] + state->parameter.minimal_surplus[o];
1686 } output_type_iterate_end;
1687
1688 /* We could get a minimum on luxury if we knew how many luxuries were
1689 * needed to make us content. */
1690 }
1691
1692 /****************************************************************************
1693 get the tax rates, see city.c
1694 ****************************************************************************/
get_tax_rates(const struct player * pplayer,int rates[])1695 static void get_tax_rates(const struct player *pplayer, int rates[])
1696 {
1697 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1698
1699 if (game.info.changable_tax) {
1700 rates[SCIENCE] = pplayer->economic.science;
1701 rates[LUXURY] = pplayer->economic.luxury;
1702 rates[TAX] = 100 - rates[SCIENCE] - rates[LUXURY];
1703 } else {
1704 rates[SCIENCE] = game.info.forced_science;
1705 rates[LUXURY] = game.info.forced_luxury;
1706 rates[TAX] = game.info.forced_gold;
1707 }
1708
1709 /* ANARCHY */
1710 if (government_of_player(pplayer) == game.government_during_revolution) {
1711 rates[SCIENCE] = 0;
1712 rates[LUXURY] = 100;
1713 rates[TAX] = 0;
1714 }
1715 }
1716
1717 /****************************************************************************
1718 Estimate the fitness of a tile. Tiles are put into the lattice in
1719 fitness order, so that we start off choosing better tiles.
1720 The estimate MUST be monotone in the inputs; if it isn't, then
1721 the BB algorithm will fail.
1722
1723 The only fields of the state used are the city and parameter.
1724 ****************************************************************************/
estimate_fitness(const struct cm_state * state,const int production[])1725 static double estimate_fitness(const struct cm_state *state,
1726 const int production[])
1727 {
1728 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1729 const struct city *pcity = state->pcity;
1730 const struct player *pplayer = city_owner(pcity);
1731 int rates[3];
1732 double estimates[O_LAST];
1733 double sum = 0;
1734 int trade;
1735
1736 output_type_iterate(stat_index) {
1737 estimates[stat_index] = production[stat_index];
1738 } output_type_iterate_end;
1739
1740 /* bonus to trade is applied before calculating taxes, see city.c */
1741 trade = estimates[O_TRADE] * pcity->bonus[O_TRADE] / 100.0;
1742
1743 get_tax_rates(pplayer, rates);
1744
1745 /* sci/lux/gold get benefit from the tax rates (in percentage) */
1746 estimates[O_SCIENCE]
1747 += rates[SCIENCE] * trade / 100.0;
1748 estimates[O_LUXURY]
1749 += rates[LUXURY] * trade / 100.0;
1750 estimates[O_GOLD]
1751 += rates[TAX] * trade / 100.0;
1752
1753 /* now add in the bonuses from building effects (in percentage) */
1754 output_type_iterate(stat_index) {
1755 estimates[stat_index] *= pcity->bonus[stat_index] / 100.0;
1756 } output_type_iterate_end;
1757
1758 /* finally, sum it all up, weighted by the parameter, but give additional
1759 * weight to luxuries to take account of disorder/happy constraints */
1760 output_type_iterate(stat_index) {
1761 sum += estimates[stat_index] * state->parameter.factor[stat_index];
1762 } output_type_iterate_end;
1763 sum += estimates[O_LUXURY];
1764 return sum;
1765 }
1766
1767
1768
1769 /****************************************************************************
1770 The high-level algorithm is:
1771
1772 for each idle worker,
1773 non-deterministically choose a position for the idle worker to use
1774
1775 To implement this, we keep a stack of the choices we've made.
1776 When we want the next node in the tree, we see if there are any idle
1777 workers left. We push an idle worker, and make it take the first field
1778 in the lattice. If there are no idle workers left, then we pop out
1779 until we can make another choice.
1780 ****************************************************************************/
bb_next(struct cm_state * state,bool negative_ok)1781 static bool bb_next(struct cm_state *state, bool negative_ok)
1782 {
1783 /* if no idle workers, then look at our solution. */
1784 if (state->current.idle == 0) {
1785 struct cm_fitness value = evaluate_solution(state, &state->current);
1786
1787 print_partial_solution(LOG_REACHED_LEAF, &state->current, state);
1788 if (fitness_better(value, state->best_value)) {
1789 log_base(LOG_BETTER_LEAF, "-> replaces previous best");
1790 copy_partial_solution(&state->best, &state->current, state);
1791 state->best_value = value;
1792 }
1793 }
1794
1795 /* try to move to a child branch, if we can. If not (including if we're
1796 at a leaf), then move to a sibling. */
1797 if (!take_child_choice(state, negative_ok)) {
1798 /* keep trying to move to a sibling branch, or popping out a level if
1799 we're stuck (fully examined the current branch) */
1800 while ((!choice_stack_empty(state))
1801 && !take_sibling_choice(state, negative_ok)) {
1802 pop_choice(state);
1803 }
1804
1805 /* if we popped out all the way, we're done */
1806 if (choice_stack_empty(state)) {
1807 return TRUE;
1808 }
1809 }
1810
1811 /* if we didn't detect that we were done, we aren't */
1812 return FALSE;
1813 }
1814
1815 /****************************************************************************
1816 Initialize the state for the branch-and-bound algorithm.
1817 ****************************************************************************/
cm_state_init(struct city * pcity,bool negative_ok)1818 static struct cm_state *cm_state_init(struct city *pcity, bool negative_ok)
1819 {
1820 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1821 const struct player *pplayer = city_owner(pcity);
1822 int numtypes;
1823 struct cm_state *state = fc_malloc(sizeof(*state));
1824 int rates[3];
1825
1826 log_base(LOG_CM_STATE, "creating cm_state for %s (size %d)",
1827 city_name_get(pcity), city_size_get(pcity));
1828
1829 /* copy the arguments */
1830 state->pcity = pcity;
1831
1832 /* create the lattice */
1833 tile_type_vector_init(&state->lattice);
1834 init_tile_lattice(pcity, &state->lattice);
1835 numtypes = tile_type_vector_size(&state->lattice);
1836
1837 get_tax_rates(pplayer, rates);
1838
1839 /* For the heuristic, make sorted copies of the lattice */
1840 output_type_iterate(stat_index) {
1841 tile_type_vector_init(&state->lattice_by_prod[stat_index]);
1842 tile_type_vector_copy(&state->lattice_by_prod[stat_index], &state->lattice);
1843 compare_key = stat_index;
1844 /* calculate effect of 1 trade production on interesting production */
1845 switch (stat_index) {
1846 case O_SCIENCE:
1847 compare_key_trade_bonus = rates[SCIENCE] * pcity->bonus[O_TRADE] / 100.0;
1848 break;
1849 case O_LUXURY:
1850 compare_key_trade_bonus = rates[LUXURY] * pcity->bonus[O_TRADE] / 100.0;
1851 break;
1852 case O_GOLD:
1853 compare_key_trade_bonus = rates[TAX] * pcity->bonus[O_TRADE] / 100.0;
1854 break;
1855 default:
1856 compare_key_trade_bonus = 0.0;
1857 break;
1858 }
1859 qsort(state->lattice_by_prod[stat_index].p, state->lattice_by_prod[stat_index].size,
1860 sizeof(*state->lattice_by_prod[stat_index].p),
1861 compare_tile_type_by_stat);
1862 } output_type_iterate_end;
1863
1864 state->min_luxury = - FC_INFINITY;
1865
1866 /* We have no best solution yet, so its value is the worst possible. */
1867 init_partial_solution(&state->best, numtypes, city_size_get(pcity),
1868 negative_ok);
1869 state->best_value = worst_fitness();
1870
1871 /* Initialize the current solution and choice stack to empty */
1872 init_partial_solution(&state->current, numtypes, city_size_get(pcity),
1873 negative_ok);
1874 state->choice.stack = fc_malloc(city_size_get(pcity)
1875 * sizeof(*state->choice.stack));
1876 state->choice.size = 0;
1877
1878 /* Initialize workers map */
1879 state->workers_map = fc_calloc(city_map_tiles_from_city(state->pcity),
1880 sizeof(state->workers_map));
1881
1882 return state;
1883 }
1884
1885 /****************************************************************************
1886 Set the parameter for the state. This is the first step in actually
1887 solving anything.
1888 ****************************************************************************/
begin_search(struct cm_state * state,const struct cm_parameter * parameter,bool negative_ok)1889 static void begin_search(struct cm_state *state,
1890 const struct cm_parameter *parameter,
1891 bool negative_ok)
1892 {
1893 #ifdef GATHER_TIME_STATS
1894 timer_start(performance.current->wall_timer);
1895 performance.current->query_count++;
1896 #endif
1897
1898 /* copy the parameter and sort the main lattice by it */
1899 cm_copy_parameter(&state->parameter, parameter);
1900 sort_lattice_by_fitness(state, &state->lattice);
1901 init_min_production(state);
1902
1903 /* clear out the old solution */
1904 state->best_value = worst_fitness();
1905 destroy_partial_solution(&state->current);
1906 init_partial_solution(&state->current, num_types(state),
1907 city_size_get(state->pcity),
1908 negative_ok);
1909 state->choice.size = 0;
1910 }
1911
1912
1913 /****************************************************************************
1914 Clean up after a search.
1915 Currently, does nothing except stop the timer and output.
1916 ****************************************************************************/
end_search(struct cm_state * state)1917 static void end_search(struct cm_state *state)
1918 {
1919 #ifdef GATHER_TIME_STATS
1920 timer_stop(performance.current->wall_timer);
1921
1922 #ifdef PRINT_TIME_STATS_EVERY_QUERY
1923 print_performance(performance.current);
1924 #endif
1925
1926 performance.current = NULL;
1927 #endif /* GATHER_TIME_STATS */
1928 }
1929
1930 /****************************************************************************
1931 Release all the memory allocated by the state.
1932 ****************************************************************************/
cm_state_free(struct cm_state * state)1933 static void cm_state_free(struct cm_state *state)
1934 {
1935 tile_type_vector_free_all(&state->lattice);
1936 output_type_iterate(stat_index) {
1937 tile_type_vector_free(&state->lattice_by_prod[stat_index]);
1938 } output_type_iterate_end;
1939 destroy_partial_solution(&state->best);
1940 destroy_partial_solution(&state->current);
1941
1942 FC_FREE(state->choice.stack);
1943 FC_FREE(state->workers_map);
1944 FC_FREE(state);
1945 }
1946
1947
1948 /****************************************************************************
1949 Run B&B until we find the best solution.
1950 ****************************************************************************/
cm_find_best_solution(struct cm_state * state,const struct cm_parameter * const parameter,struct cm_result * result,bool negative_ok)1951 static void cm_find_best_solution(struct cm_state *state,
1952 const struct cm_parameter *const parameter,
1953 struct cm_result *result, bool negative_ok)
1954 {
1955 int loop_count = 0;
1956 int max_count;
1957 struct city backup;
1958
1959 #ifdef GATHER_TIME_STATS
1960 performance.current = &performance.opt;
1961 #endif
1962
1963 begin_search(state, parameter, negative_ok);
1964
1965 /* make a backup of the city to restore at the very end */
1966 memcpy(&backup, state->pcity, sizeof(backup));
1967
1968 if (player_is_cpuhog(city_owner(state->pcity))) {
1969 max_count = CPUHOG_CM_MAX_LOOP;
1970 } else {
1971 max_count = CM_MAX_LOOP;
1972 }
1973
1974 /* search until we find a feasible solution */
1975 while (!bb_next(state, negative_ok)) {
1976 /* Limit the number of loops. */
1977 loop_count++;
1978
1979 if (loop_count > max_count) {
1980 log_error("Did not find a cm solution in %d iterations for %s.",
1981 max_count, city_name_get(state->pcity));
1982 break;
1983 }
1984 }
1985
1986 /* convert to the caller's format */
1987 convert_solution_to_result(state, &state->best, result);
1988
1989 memcpy(state->pcity, &backup, sizeof(backup));
1990
1991 end_search(state);
1992 }
1993
1994 /***************************************************************************
1995 Wrapper that actually runs the branch & bound, and returns the best
1996 solution.
1997 ***************************************************************************/
cm_query_result(struct city * pcity,const struct cm_parameter * param,struct cm_result * result,bool negative_ok)1998 void cm_query_result(struct city *pcity,
1999 const struct cm_parameter *param,
2000 struct cm_result *result, bool negative_ok)
2001 {
2002 struct cm_state *state = cm_state_init(pcity, negative_ok);
2003
2004 /* Refresh the city. Otherwise the CM can give wrong results or just be
2005 * slower than necessary. Note that cities are often passed in in an
2006 * unrefreshed state (which should probably be fixed). */
2007 city_refresh_from_main_map(pcity, NULL);
2008
2009 cm_find_best_solution(state, param, result, negative_ok);
2010 cm_state_free(state);
2011 }
2012
2013 /**************************************************************************
2014 Returns true if the two cm_parameters are equal.
2015 **************************************************************************/
cm_are_parameter_equal(const struct cm_parameter * const p1,const struct cm_parameter * const p2)2016 bool cm_are_parameter_equal(const struct cm_parameter *const p1,
2017 const struct cm_parameter *const p2)
2018 {
2019 output_type_iterate(i) {
2020 if (p1->minimal_surplus[i] != p2->minimal_surplus[i]) {
2021 return FALSE;
2022 }
2023 if (p1->factor[i] != p2->factor[i]) {
2024 return FALSE;
2025 }
2026 } output_type_iterate_end;
2027 if (p1->require_happy != p2->require_happy) {
2028 return FALSE;
2029 }
2030 if (p1->allow_disorder != p2->allow_disorder) {
2031 return FALSE;
2032 }
2033 if (p1->allow_specialists != p2->allow_specialists) {
2034 return FALSE;
2035 }
2036 if (p1->happy_factor != p2->happy_factor) {
2037 return FALSE;
2038 }
2039
2040 return TRUE;
2041 }
2042
2043 /**************************************************************************
2044 Copy the parameter from the source to the destination field.
2045 **************************************************************************/
cm_copy_parameter(struct cm_parameter * dest,const struct cm_parameter * const src)2046 void cm_copy_parameter(struct cm_parameter *dest,
2047 const struct cm_parameter *const src)
2048 {
2049 memcpy(dest, src, sizeof(struct cm_parameter));
2050 }
2051
2052 /**************************************************************************
2053 Initialize the parameter to sane default values.
2054 **************************************************************************/
cm_init_parameter(struct cm_parameter * dest)2055 void cm_init_parameter(struct cm_parameter *dest)
2056 {
2057 output_type_iterate(stat_index) {
2058 dest->minimal_surplus[stat_index] = 0;
2059 dest->factor[stat_index] = 1;
2060 } output_type_iterate_end;
2061
2062 dest->happy_factor = 1;
2063 dest->require_happy = FALSE;
2064 dest->allow_disorder = FALSE;
2065 dest->allow_specialists = TRUE;
2066 }
2067
2068 /***************************************************************************
2069 Initialize the parameter to sane default values that will always produce
2070 a result.
2071 ***************************************************************************/
cm_init_emergency_parameter(struct cm_parameter * dest)2072 void cm_init_emergency_parameter(struct cm_parameter *dest)
2073 {
2074 output_type_iterate(stat_index) {
2075 dest->minimal_surplus[stat_index] = -FC_INFINITY;
2076 dest->factor[stat_index] = 1;
2077 } output_type_iterate_end;
2078
2079 dest->happy_factor = 1;
2080 dest->require_happy = FALSE;
2081 dest->allow_disorder = TRUE;
2082 dest->allow_specialists = TRUE;
2083 }
2084
2085 /****************************************************************************
2086 Count the total number of workers in the result.
2087 ****************************************************************************/
cm_result_workers(const struct cm_result * result)2088 int cm_result_workers(const struct cm_result *result)
2089 {
2090 int count = 0;
2091
2092 city_map_iterate(result->city_radius_sq, cindex, x, y) {
2093 if (is_free_worked_index(cindex)) {
2094 continue;
2095 }
2096
2097 if (result->worker_positions[cindex]) {
2098 count++;
2099 }
2100 } city_map_iterate_end;
2101
2102 return count;
2103 }
2104
2105 /****************************************************************************
2106 Count the total number of specialists in the result.
2107 ****************************************************************************/
cm_result_specialists(const struct cm_result * result)2108 int cm_result_specialists(const struct cm_result *result)
2109 {
2110 int count = 0;
2111
2112 specialist_type_iterate(spec) {
2113 count += result->specialists[spec];
2114 } specialist_type_iterate_end;
2115
2116 return count;
2117 }
2118
2119 /****************************************************************************
2120 Count the total number of citizens in the result.
2121 ****************************************************************************/
cm_result_citizens(const struct cm_result * result)2122 int cm_result_citizens(const struct cm_result *result)
2123 {
2124 return cm_result_workers(result) + cm_result_specialists(result);
2125 }
2126
2127 /****************************************************************************
2128 Copy the city's current setup into the cm result structure. Wrapper for
2129 cm_result_main().
2130 ****************************************************************************/
cm_result_from_main_map(struct cm_result * result,const struct city * pcity)2131 void cm_result_from_main_map(struct cm_result *result,
2132 const struct city *pcity)
2133 {
2134 cm_result_copy(result, pcity, NULL);
2135 }
2136
2137 /****************************************************************************
2138 Copy the city's current setup into the cm result structure. 'workers_map'
2139 is a bool array with the size city_map_tiles_from_city(pcity). It is TRUE
2140 for tiles worked by the city.
2141 ****************************************************************************/
cm_result_copy(struct cm_result * result,const struct city * pcity,bool * workers_map)2142 static void cm_result_copy(struct cm_result *result,
2143 const struct city *pcity, bool *workers_map)
2144 {
2145 struct tile *pcenter = city_tile(pcity);
2146
2147 /* clear worker positions */
2148 memset(result->worker_positions, 0,
2149 sizeof(*result->worker_positions)
2150 * city_map_tiles(result->city_radius_sq));
2151
2152 city_tile_iterate_index(result->city_radius_sq, pcenter, ptile, ctindex) {
2153 if (workers_map == NULL) {
2154 /* use the main map */
2155 struct city *pwork = tile_worked(ptile);
2156
2157 result->worker_positions[ctindex] = (NULL != pwork && pwork == pcity);
2158 } else {
2159 result->worker_positions[ctindex] = workers_map[ctindex];
2160 }
2161 } city_tile_iterate_index_end;
2162
2163 /* copy the specialist counts */
2164 specialist_type_iterate(spec) {
2165 result->specialists[spec] = pcity->specialists[spec];
2166 } specialist_type_iterate_end;
2167
2168 /* find the surplus production numbers */
2169 get_city_surplus(pcity, result->surplus,
2170 &result->disorder, &result->happy);
2171
2172 /* this is a valid result, in a sense */
2173 result->found_a_valid = TRUE;
2174 }
2175
2176 /****************************************************************************
2177 Debugging routines.
2178 ****************************************************************************/
2179 #ifdef CM_DEBUG
snprint_production(char * buffer,size_t bufsz,const int production[])2180 static void snprint_production(char *buffer, size_t bufsz,
2181 const int production[])
2182 {
2183 fc_snprintf(buffer, bufsz, "[%d %d %d %d %d %d]",
2184 production[O_FOOD], production[O_SHIELD],
2185 production[O_TRADE], production[O_GOLD],
2186 production[O_LUXURY], production[O_SCIENCE]);
2187 }
2188
2189 /****************************************************************************
2190 Print debugging data about a particular tile type.
2191 ****************************************************************************/
real_print_tile_type(enum log_level level,const char * file,const char * function,int line,const struct cm_tile_type * ptype,const char * prefix)2192 static void real_print_tile_type(enum log_level level, const char *file,
2193 const char *function, int line,
2194 const struct cm_tile_type *ptype,
2195 const char *prefix)
2196 {
2197 char prodstr[256];
2198
2199 snprint_production(prodstr, sizeof(prodstr), ptype->production);
2200 do_log(file, function, line, FALSE, level,
2201 "%s%s fitness %g depth %d, idx %d; %d tiles", prefix,
2202 prodstr, ptype->estimated_fitness, ptype->lattice_depth,
2203 ptype->lattice_index, tile_type_num_tiles(ptype));
2204 }
2205
2206 /****************************************************************************
2207 Print debugging data about a whole B&B lattice.
2208 ****************************************************************************/
real_print_lattice(enum log_level level,const char * file,const char * function,int line,const struct tile_type_vector * lattice)2209 static void real_print_lattice(enum log_level level, const char *file,
2210 const char *function, int line,
2211 const struct tile_type_vector *lattice)
2212 {
2213 do_log(file, function, line, FALSE, level,
2214 "lattice has %u terrain types", (unsigned) lattice->size);
2215 tile_type_vector_iterate(lattice, ptype) {
2216 real_print_tile_type(level, file, function, line, ptype, " ");
2217 } tile_type_vector_iterate_end;
2218 }
2219
2220
2221 /****************************************************************************
2222 Print debugging data about a partial CM solution.
2223 ****************************************************************************/
real_print_partial_solution(enum log_level level,const char * file,const char * function,int line,const struct partial_solution * soln,const struct cm_state * state)2224 static void real_print_partial_solution(enum log_level level,
2225 const char *file,
2226 const char *function, int line,
2227 const struct partial_solution *soln,
2228 const struct cm_state *state)
2229 {
2230 int i;
2231 int last_type = 0;
2232 char buf[256];
2233
2234 if (soln->idle != 0) {
2235 do_log(file, function, line, FALSE, level,
2236 "** partial solution has %d idle workers", soln->idle);
2237 } else {
2238 do_log(file, function, line, FALSE, level, "** completed solution:");
2239 }
2240
2241 snprint_production(buf, sizeof(buf), soln->production);
2242 do_log(file, function, line, FALSE, level, "production: %s", buf);
2243
2244 do_log(file, function, line, FALSE, level, "tiles used:");
2245 for (i = 0; i < num_types(state); i++) {
2246 if (soln->worker_counts[i] != 0) {
2247 fc_snprintf(buf, sizeof(buf), " %d tiles of type ",
2248 soln->worker_counts[i]);
2249 real_print_tile_type(level, file, function, line,
2250 tile_type_get(state, i), buf);
2251 }
2252 }
2253
2254 for (i = 0; i < num_types(state); i++) {
2255 if (soln->worker_counts[i] != 0) {
2256 last_type = i;
2257 }
2258 }
2259
2260 do_log(file, function, line, FALSE, level, "tiles available:");
2261 for (i = last_type; i < num_types(state); i++) {
2262 const struct cm_tile_type *ptype = tile_type_get(state, i);
2263
2264 if (soln->prereqs_filled[i] == tile_type_num_prereqs(ptype)
2265 && soln->worker_counts[i] < tile_type_num_tiles(ptype)) {
2266 real_print_tile_type(level, file, function, line,
2267 tile_type_get(state, i), " ");
2268 }
2269 }
2270 }
2271
2272 #endif /* CM_DEBUG */
2273
2274 #ifdef GATHER_TIME_STATS
2275 /****************************************************************************
2276 Print debugging performance data.
2277 ****************************************************************************/
print_performance(struct one_perf * counts)2278 static void print_performance(struct one_perf *counts)
2279 {
2280 double s, ms;
2281 double q;
2282 int queries, applies;
2283
2284 s = timer_read_seconds(counts->wall_timer);
2285 ms = 1000.0 * s;
2286
2287 queries = counts->query_count;
2288 q = queries;
2289
2290 applies = counts->apply_count;
2291
2292 log_base(LOG_TIME_STATS,
2293 "CM-%s: overall=%fs queries=%d %fms / query, %d applies",
2294 counts->name, s, queries, ms / q, applies);
2295 }
2296 #endif /* GATHER_TIME_STATS */
2297
2298 /****************************************************************************
2299 Print debugging information about one city.
2300 ****************************************************************************/
cm_print_city(const struct city * pcity)2301 void cm_print_city(const struct city *pcity)
2302 {
2303 struct tile *pcenter = city_tile(pcity);
2304
2305 log_test("cm_print_city(city %d=\"%s\")", pcity->id, city_name_get(pcity));
2306 log_test(" size=%d, specialists=%s",
2307 city_size_get(pcity), specialists_string(pcity->specialists));
2308
2309 log_test(" workers at:");
2310 city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
2311 cindex) {
2312 struct city *pwork = tile_worked(ptile);
2313
2314 if (NULL != pwork && pwork == pcity) {
2315 int cx, cy;
2316 city_tile_index_to_xy(&cx, &cy, cindex,
2317 city_map_radius_sq_get(pcity));
2318 log_test(" {%2d,%2d} (%4d,%4d)", cx, cy, TILE_XY(ptile));
2319 }
2320 } city_tile_iterate_index_end;
2321
2322 log_test(" food = %3d (%+3d)",
2323 pcity->prod[O_FOOD], pcity->surplus[O_FOOD]);
2324 log_test(" shield = %3d (%+3d)",
2325 pcity->prod[O_SHIELD], pcity->surplus[O_SHIELD]);
2326 log_test(" trade = %3d", pcity->surplus[O_TRADE]);
2327
2328 log_test(" gold = %3d (%+3d)",
2329 pcity->prod[O_GOLD], pcity->surplus[O_GOLD]);
2330 log_test(" luxury = %3d", pcity->prod[O_LUXURY]);
2331 log_test(" science = %3d", pcity->prod[O_SCIENCE]);
2332 }
2333
2334 /****************************************************************************
2335 Print debugging information about a full CM result.
2336 ****************************************************************************/
cm_print_result(const struct cm_result * result)2337 void cm_print_result(const struct cm_result *result)
2338 {
2339 int *city_map_data = fc_calloc(city_map_tiles(result->city_radius_sq),
2340 sizeof(*city_map_data));
2341
2342 log_test("cm_print_result(result=%p)", (void *) result);
2343 log_test(" found_a_valid=%d disorder=%d happy=%d",
2344 result->found_a_valid, result->disorder, result->happy);
2345
2346 city_map_iterate(result->city_radius_sq, cindex, x, y) {
2347 if (is_free_worked_index(cindex)) {
2348 city_map_data[cindex] = 2;
2349 } else if (result->worker_positions[cindex]) {
2350 city_map_data[cindex] = 1;
2351 } else {
2352 city_map_data[cindex] = 0;
2353 }
2354 } city_map_iterate_end;
2355 log_test("workers map (2: free worked; 1: worker; 0: not used):");
2356 citylog_map_data(LOG_TEST, result->city_radius_sq, city_map_data);
2357 FC_FREE(city_map_data);
2358
2359 log_test(" (workers/specialists) %d/%s", cm_result_workers(result),
2360 specialists_string(result->specialists));
2361
2362 output_type_iterate(i) {
2363 log_test(" %10s surplus=%d", get_output_name(i), result->surplus[i]);
2364 } output_type_iterate_end;
2365 }
2366