Freeciv-3.1
Loading...
Searching...
No Matches
cm.c
Go to the documentation of this file.
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 * caching, 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 caching.
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/* If this is uncommented, research loop runs without limit on iterations. */
76/* #define CM_LOOP_NO_LIMIT */
77
78/* Maximal iterations before the search loop is stopped, or until warning is
79 * printed if CM_LOOP_NO_LIMIT is defined. */
80#define CM_MAX_LOOP 27500
81
82#define CPUHOG_CM_MAX_LOOP (CM_MAX_LOOP * 4)
83
84#ifdef DEBUG_TIMERS
85#define GATHER_TIME_STATS
86#endif
87#ifdef FREECIV_DEBUG
88#define CM_DEBUG
89#endif
90
91/* Whether to print every query, or just at cm_free ; matters only
92 if GATHER_TIME_STATS is on */
93#define PRINT_TIME_STATS_EVERY_QUERY
94
95#define LOG_TIME_STATS LOG_DEBUG
96#define LOG_CM_STATE LOG_DEBUG
97#define LOG_LATTICE LOG_DEBUG
98#define LOG_REACHED_LEAF LOG_DEBUG
99#define LOG_BETTER_LEAF LOG_DEBUG
100#define LOG_PRUNE_BRANCH LOG_DEBUG
101
102#ifdef GATHER_TIME_STATS
103static struct {
104 struct one_perf {
105 struct timer *wall_timer;
106 int query_count;
107 int apply_count;
108 const char *name;
109 } greedy, opt;
110
111 struct one_perf *current;
112} performance;
113
114static void print_performance(struct one_perf *counts);
115#endif /* GATHER_TIME_STATS */
116
117/* Fitness of a solution. */
119 int weighted; /* weighted sum */
120 bool sufficient; /* false => doesn't meet constraints */
121};
122
123
124/*
125 * We have a cyclic structure here, so we need to forward-declare the
126 * structs
127 */
128struct cm_tile_type;
129struct cm_tile;
130
131/*
132 * A tile. Has a pointer to the type, and the x/y coords.
133 * Used mostly just for converting to cm_result.
134 */
135struct cm_tile {
136 const struct cm_tile_type *type;
137 int index; /* city map index; only valid if !is_specialist */
138};
139
140/* define the tile_vector as array<cm_tile> */
141#define SPECVEC_TAG tile
142#define SPECVEC_TYPE struct cm_tile
143#include "specvec.h"
144
145/* define the tile_type_vector as array <cm_tile_type*> */
146#define SPECVEC_TAG tile_type
147#define SPECVEC_TYPE struct cm_tile_type *
148#include "specvec.h"
149#define tile_type_vector_iterate(vector, var) { \
150 struct cm_tile_type *var; \
151 TYPED_VECTOR_ITERATE(struct cm_tile_type*, vector, var##p) { \
152 var = *var##p; \
153 {
154#define tile_type_vector_iterate_end }} VECTOR_ITERATE_END; }
155
156/*
157 * A tile type.
158 * Holds the production (a hill produces 1/0/0);
159 * Holds a list of which tiles match this (all the hills and tundra);
160 * Holds a list of other types that are strictly better
161 * (grassland 2/0/0, plains 1/1/0, but not gold mine 0/1/6).
162 * Holds a list of other types that are strictly worse
163 * (the grassland and plains hold a pointer to the hill).
164 *
165 * Specialists are special types; is_specialist is set, and the tile
166 * vector is empty. We can never run out of specialists.
167 */
170 double estimated_fitness; /* weighted sum of production */
172 Specialist_type_id spec; /* valid only if is_specialist */
173 struct tile_vector tiles; /* valid only if !is_specialist */
174 struct tile_type_vector better_types;
175 struct tile_type_vector worse_types;
176 int lattice_index; /* index in state->lattice */
177 int lattice_depth; /* depth = sum(#tiles) over all better types */
178};
179
180
181/*
182 * A partial solution.
183 * Has the count of workers assigned to each lattice position, and
184 * a count of idle workers yet unassigned.
185 */
187 /* indices for these two match the lattice indices */
188 int *worker_counts; /* number of workers on each type */
189 int *prereqs_filled; /* number of better types filled up */
190
191 int production[O_LAST]; /* raw production, cached for the heuristic */
192 int idle; /* number of idle workers */
193};
194
195/*
196 * State of the search.
197 * This holds all the information needed to do the search, all in one
198 * struct, in order to clean up the function calls.
199 */
200struct cm_state {
201 /* input from the caller */
203 /*mutable*/ struct city *pcity;
204
205 /* the tile lattice */
206 struct tile_type_vector lattice;
207 struct tile_type_vector lattice_by_prod[O_LAST];
208
209 /* the best known solution, and its fitness */
212
213 /* hard constraints on production: any solution with less production than
214 * this fails to satisfy the constraints, so we can stop investigating
215 * this branch. A solution with more production than this may still
216 * fail (for being unhappy, for instance). */
218
219 /* needed luxury to be content, this includes effects by specialists */
221
222 /* the current solution we're examining. */
224
225 /*
226 * Where we are in the search. When we add a worker to the current
227 * partial solution, we also push the tile type index on the stack.
228 */
229 struct {
230 int *stack;
231 int size;
233
234 bool *workers_map; /* placement of the workers within the city map */
235};
236
237
238/* return #fields + specialist types */
239static int num_types(const struct cm_state *state);
240
241
242/* debugging functions */
243#ifdef CM_DEBUG
244static void real_print_tile_type(enum log_level level, const char *file,
245 const char *function, int line,
246 const struct cm_tile_type *ptype,
247 const char *prefix);
248#define print_tile_type(loglevel, ptype, prefix) \
249 if (log_do_output_for_level(loglevel)) { \
250 real_print_tile_type(loglevel, __FILE__, __FUNCTION__, __FC_LINE__, \
251 ptype, prefix); \
252 }
253
254static void real_print_lattice(enum log_level level, const char *file,
255 const char *function, int line,
256 const struct tile_type_vector *lattice);
257#define print_lattice(loglevel, lattice) \
258 if (log_do_output_for_level(loglevel)) { \
259 real_print_lattice(loglevel, __FILE__, __FUNCTION__, __FC_LINE__, \
260 lattice); \
261 }
262
263static void real_print_partial_solution(enum log_level level,
264 const char *file,
265 const char *function, int line,
266 const struct partial_solution *soln,
267 const struct cm_state *state);
268#define print_partial_solution(loglevel, soln, state) \
269 if (log_do_output_for_level(loglevel)) { \
270 real_print_partial_solution(loglevel, __FILE__, __FUNCTION__, \
271 __FC_LINE__, soln, state); \
272 }
273
274#else
275#define print_tile_type(loglevel, ptype, prefix)
276#define print_lattice(loglevel, lattice)
277#define print_partial_solution(loglevel, soln, state)
278#endif /* CM_DEBUG */
279
280static void cm_result_copy(struct cm_result *result,
281 const struct city *pcity, bool *workers_map);
282
283static double estimate_fitness(const struct cm_state *state,
284 const int production[]);
285static bool choice_is_promising(struct cm_state *state, int newchoice,
286 bool negative_ok);
287
288/************************************************************************/
293void cm_init(void)
294{
295 /* In the B&B algorithm there's not really anything to initialize. */
296#ifdef GATHER_TIME_STATS
297 memset(&performance, 0, sizeof(performance));
298
299 performance.greedy.wall_timer = timer_new(TIMER_USER, TIMER_ACTIVE);
300 performance.greedy.name = "greedy";
301
302 performance.opt.wall_timer = timer_new(TIMER_USER, TIMER_ACTIVE);
303 performance.opt.name = "opt";
304#endif /* GATHER_TIME_STATS */
305}
306
307/************************************************************************/
313{
314 /* In the B&B algorithm there's not really anything to initialize. */
315}
316
317/************************************************************************/
320void cm_clear_cache(struct city *pcity)
321{
322 /* The B&B algorithm doesn't have city caches so there's nothing to do. */
323}
324
325/************************************************************************/
328void cm_free(void)
329{
330#ifdef GATHER_TIME_STATS
331 print_performance(&performance.greedy);
332 print_performance(&performance.opt);
333
334 timer_destroy(performance.greedy.wall_timer);
335 timer_destroy(performance.opt.wall_timer);
336 memset(&performance, 0, sizeof(performance));
337#endif /* GATHER_TIME_STATS */
338}
339
340/************************************************************************/
343struct cm_result *cm_result_new(struct city *pcity)
344{
345 struct cm_result *result;
346
347 /* initialise all values */
348 result = fc_calloc(1, sizeof(*result));
349 result->city_radius_sq = pcity ? city_map_radius_sq_get(pcity)
351 result->worker_positions
353 sizeof(*result->worker_positions));
354
355 /* test if the city pointer is valid; the cm_result struct can be
356 * returned as it uses the maximal possible value for the size of
357 * 'worker_positions' (= city_map_tiles(CITY_MAP_MAX_RADIUS_SQ))*/
358 fc_assert_ret_val(pcity != NULL, result);
359
360 return result;
361}
362
363/************************************************************************/
366void cm_result_destroy(struct cm_result *result)
367{
368 if (result != NULL) {
369 if (result->worker_positions != NULL) {
370 FC_FREE(result->worker_positions);
371 }
372 FC_FREE(result);
373 }
374}
375
376/****************************************************************************
377 Functions of tile-types.
378****************************************************************************/
379
380/************************************************************************/
383static void tile_type_init(struct cm_tile_type *type)
384{
385 memset(type, 0, sizeof(*type));
386 tile_vector_init(&type->tiles);
387 tile_type_vector_init(&type->better_types);
388 tile_type_vector_init(&type->worse_types);
389}
390
391/************************************************************************/
395static struct cm_tile_type *tile_type_dup(const struct cm_tile_type *oldtype)
396{
397 struct cm_tile_type *newtype = fc_malloc(sizeof(*newtype));
398
399 memcpy(newtype, oldtype, sizeof(*oldtype));
400 tile_vector_init(&newtype->tiles);
401 tile_type_vector_init(&newtype->better_types);
402 tile_type_vector_init(&newtype->worse_types);
403
404 return newtype;
405}
406
407/************************************************************************/
411{
412 /* The call to vector_free() will magically free all the tiles in the
413 * vector. */
414 tile_vector_free(&type->tiles);
415 tile_type_vector_free(&type->better_types);
416 tile_type_vector_free(&type->worse_types);
417}
418
419/************************************************************************/
423static void tile_type_vector_free_all(struct tile_type_vector *vec)
424{
426 /* Destroy all data in the type, and free the type itself. */
428 free(type);
430
431 tile_type_vector_free(vec);
432}
433
434/************************************************************************/
439static bool tile_type_equal(const struct cm_tile_type *a,
440 const struct cm_tile_type *b)
441{
442 output_type_iterate(stat_index) {
443 if (a->production[stat_index] != b->production[stat_index]) {
444 return FALSE;
445 }
447
448 if (a->is_specialist != b->is_specialist) {
449 return FALSE;
450 }
451
452 return TRUE;
453}
454
455/************************************************************************/
463static int tile_type_better(const struct cm_tile_type *a,
464 const struct cm_tile_type *b)
465{
466 int ret = 0;
467
468 output_type_iterate(stat_index) {
469 if (a->production[stat_index] < b->production[stat_index]) {
470 if (ret > 0) {
471 return 0;
472 }
473 ret = -1;
474 } else if (b->production[stat_index] < a->production[stat_index]) {
475 if (ret < 0) {
476 return 0;
477 }
478 ret = 1;
479 }
481
482 if (a->is_specialist && !b->is_specialist) {
483 /* If A is a specialist and B isn't, and all of A's production is at
484 * least as good as B's, then A is better because it doesn't tie up
485 * the map tile. */
486 if (ret < 0) {
487 return 0;
488 }
489 return 1;
490 } else if (!a->is_specialist && b->is_specialist) {
491 /* Vice versa. */
492 if (ret > 0) {
493 return 0;
494 }
495 return -1;
496 }
497
498 return ret;
499}
500
501/************************************************************************/
508 const struct tile_type_vector *vec,
509 const struct cm_tile_type *ptype)
510{
511 int i;
512
513 for (i = 0; i < vec->size; i++) {
514 if (tile_type_equal(vec->p[i], ptype)) {
515 return i;
516 }
517 }
518
519 return -1;
520}
521
522/************************************************************************/
527static int tile_type_num_tiles(const struct cm_tile_type *type)
528{
529 if (type->is_specialist) {
530 return FC_INFINITY;
531 } else {
532 return tile_vector_size(&type->tiles);
533 }
534}
535
536/************************************************************************/
542static int tile_type_num_prereqs(const struct cm_tile_type *ptype)
543{
544 return ptype->better_types.size;
545}
546
547/************************************************************************/
552static const struct cm_tile_type *tile_type_get(const struct cm_state *state,
553 int type)
554{
555 /* Sanity check the index. */
556 fc_assert_ret_val(0 <= type, NULL);
557 fc_assert_ret_val(state->lattice.size > type, NULL);
558
559 return state->lattice.p[type];
560}
561
562/************************************************************************/
568static const struct cm_tile *tile_get(const struct cm_tile_type *ptype, int j)
569{
570 fc_assert_ret_val(!ptype->is_specialist, NULL);
571 fc_assert_ret_val(0 <= j, NULL);
572 fc_assert_ret_val(j < ptype->tiles.size, NULL);
573
574 return &ptype->tiles.p[j];
575}
576
577
578/****************************************************************************
579 Functions on the cm_fitness struct.
580****************************************************************************/
581
582/************************************************************************/
585static bool fitness_better(struct cm_fitness a, struct cm_fitness b)
586{
587 if (a.sufficient != b.sufficient) {
588 return a.sufficient;
589 }
590 return a.weighted > b.weighted;
591}
592
593/************************************************************************/
597static struct cm_fitness worst_fitness(void)
598{
599 struct cm_fitness f;
600
601 f.sufficient = FALSE;
603 return f;
604}
605
606/************************************************************************/
610static struct cm_fitness compute_fitness(const int surplus[],
611 bool disorder, bool happy,
612 const struct cm_parameter *parameter)
613{
614 struct cm_fitness fitness;
615
616 fitness.sufficient = TRUE;
617 fitness.weighted = 0;
618
619 output_type_iterate(stat_index) {
620 fitness.weighted += surplus[stat_index] * parameter->factor[stat_index];
621 if (surplus[stat_index] < parameter->minimal_surplus[stat_index]) {
622 fitness.sufficient = FALSE;
623 }
625
626 if (happy) {
627 fitness.weighted += parameter->happy_factor;
628 } else if (parameter->require_happy) {
629 fitness.sufficient = FALSE;
630 }
631
632 if (disorder && !parameter->allow_disorder) {
633 fitness.sufficient = FALSE;
634 }
635
636 return fitness;
637}
638
639/****************************************************************************
640 Handle struct partial_solution.
641 - perform a deep copy
642 - convert to city
643 - convert to cm_result
644****************************************************************************/
645
646/************************************************************************/
650 int ntypes, int idle, bool negative_ok)
651{
652 into->worker_counts = fc_calloc(ntypes, sizeof(*into->worker_counts));
653 into->prereqs_filled = fc_calloc(ntypes, sizeof(*into->prereqs_filled));
654 if (negative_ok) {
655 output_type_iterate(otype) {
656 into->production[otype] = -FC_INFINITY;
658 } else {
659 memset(into->production, 0, sizeof(into->production));
660 }
661 into->idle = idle;
662}
663
664/************************************************************************/
669{
670 free(into->worker_counts);
671 free(into->prereqs_filled);
672}
673
674/************************************************************************/
679 const struct partial_solution *src,
680 const struct cm_state *state)
681{
682 memcpy(dst->worker_counts, src->worker_counts,
683 sizeof(*dst->worker_counts) * num_types(state));
684 memcpy(dst->prereqs_filled, src->prereqs_filled,
685 sizeof(*dst->prereqs_filled) * num_types(state));
686 memcpy(dst->production, src->production, sizeof(dst->production));
687 dst->idle = src->idle;
688}
689
690
691/****************************************************************************
692 Evaluating a completed solution.
693****************************************************************************/
694
695/************************************************************************/
698static void apply_solution(struct cm_state *state,
699 const struct partial_solution *soln)
700{
701 struct city *pcity = state->pcity;
703#ifndef FREECIV_NDEBUG
704 int citizen_count = 0;
705#endif
706
707#ifdef GATHER_TIME_STATS
708 performance.current->apply_count++;
709#endif
710
711 fc_assert_ret(0 == soln->idle);
712
713 /* Clear all specialists, and remove all workers from fields (except
714 * the city center). */
715 memset(&pcity->specialists, 0, sizeof(pcity->specialists));
716
717 city_map_iterate(city_radius_sq, cindex, x, y) {
718 if (is_free_worked_index(cindex)) {
719 state->workers_map[cindex] = TRUE;
720 } else {
721 state->workers_map[cindex] = FALSE;
722 }
724
725 /* Now for each tile type, find the right number of such tiles and set them
726 * as worked. For specialists we just increase the number of specialists
727 * of that type. */
728 for (i = 0 ; i < num_types(state); i++) {
729 int nworkers = soln->worker_counts[i];
730 const struct cm_tile_type *type;
731
732 if (nworkers == 0) {
733 /* No citizens of this type. */
734 continue;
735 }
736#ifndef FREECIV_NDEBUG
737 citizen_count += nworkers;
738#endif
739
740 type = tile_type_get(state, i);
741
742 if (type->is_specialist) {
743 /* Just increase the number of specialists. */
744 pcity->specialists[type->spec] += nworkers;
745 } else {
746 int j;
747
748 /* Place citizen workers onto the citymap tiles. */
749 for (j = 0; j < nworkers; j++) {
750 const struct cm_tile *cmtile = tile_get(type, j);
751
752 state->workers_map[cmtile->index] = TRUE;
753 }
754 }
755 }
756
757 /* Finally we must refresh the city to reset all the precomputed fields. */
759 fc_assert_ret(citizen_count == city_size_get(pcity));
760}
761
762/************************************************************************/
767static void get_city_surplus(const struct city *pcity,
768 int surplus[],
769 bool *disorder, bool *happy)
770{
772 surplus[o] = pcity->surplus[o];
774
775 *disorder = city_unhappy(pcity);
776 *happy = city_happy(pcity);
777}
778
779/************************************************************************/
782static struct cm_fitness evaluate_solution(struct cm_state *state,
783 const struct partial_solution *soln)
784{
785 struct city *pcity = state->pcity;
786 int surplus[O_LAST];
787 bool disorder, happy;
788
789 /* apply and evaluate the solution, backup is done in find_best_solution */
790 apply_solution(state, soln);
791 get_city_surplus(pcity, surplus, &disorder, &happy);
792
793 /* if this solution is not content, we have an estimate on min. luxuries */
794 if (disorder) {
795 /* We have to consider the influence of each specialist in this
796 solution possibly 'hiding' a potential unhappy citizen who
797 could require luxuries.
798 Since we know the city is in disorder, we can discount most
799 effects that make citizens content, since they clearly weren't
800 sufficient.
801 This may not be sufficient luxury to make the city content (due
802 to military unhappiness etc), but certainly no less will do.
803 (Specialists may also be making angry citizens content, requiring
804 additional luxuries, but we don't try to consider that here; this
805 just means we might explore some solutions unnecessarily.) */
806 int specialists_amount = city_specialists(pcity);
807 int max_content = player_content_citizens(city_owner(pcity));
808
809 state->min_luxury = surplus[O_LUXURY]
810 + game.info.happy_cost * MAX(specialists_amount - max_content, 0)
811 + 1;
812 }
813
814 return compute_fitness(surplus, disorder, happy, &state->parameter);
815}
816
817/************************************************************************/
821static void convert_solution_to_result(struct cm_state *state,
822 const struct partial_solution *soln,
823 struct cm_result *result)
824{
825 struct cm_fitness fitness;
826
827 if (soln->idle != 0) {
828 /* If there are unplaced citizens it's not a real solution, so the
829 * result is invalid. */
830 result->found_a_valid = FALSE;
831 return;
832 }
833
834 /* apply and evaluate the solution, backup is done in find_best_solution */
835 apply_solution(state, soln);
836 cm_result_copy(result, state->pcity, state->workers_map);
837
838 /* result->found_a_valid should be only true if it matches the
839 * parameter; figure out if it does */
840 fitness = compute_fitness(result->surplus, result->disorder,
841 result->happy, &state->parameter);
842 result->found_a_valid = fitness.sufficient;
843}
844
845/****************************************************************************
846 Compare functions to allow sorting lattice vectors.
847****************************************************************************/
848
849/************************************************************************/
857 const struct cm_tile_type *b)
858{
859 if (a == b) {
860 return 0;
861 }
862
863 /* Least depth first */
864 if (a->lattice_depth != b->lattice_depth) {
865 return a->lattice_depth - b->lattice_depth;
866 }
867
868 /* With equal depth, break ties arbitrarily, more production first. */
869 output_type_iterate(stat_index) {
870 if (a->production[stat_index] != b->production[stat_index]) {
871 return b->production[stat_index] - a->production[stat_index];
872 }
874
875 /* If we get here, then we have two copies of identical types, an error */
877 return 0;
878}
879
880/************************************************************************/
886static int compare_tile_type_by_fitness(const void *va, const void *vb)
887{
888 struct cm_tile_type * const *a = va;
889 struct cm_tile_type * const *b = vb;
890 double diff;
891
892 if (*a == *b) {
893 return 0;
894 }
895
896 /* To avoid double->int roundoff problems, we call a result non-zero only
897 * if it's larger than 0.5. */
898 diff = (*b)->estimated_fitness - (*a)->estimated_fitness;
899 if (diff > 0.5) {
900 return 1; /* return value is int; don't round down! */
901 }
902 if (diff < -0.5) {
903 return -1;
904 }
905
907}
908
911
912/************************************************************************/
918static int compare_tile_type_by_stat(const void *va, const void *vb)
919{
920 struct cm_tile_type * const *a = va;
921 struct cm_tile_type * const *b = vb;
922
923 if (*a == *b) {
924 return 0;
925 }
926
927 /* Consider the influence of trade on science, luxury, gold
928 for compute_max_stats_heuristics, which uses these sorted arrays,
929 it is essential, that the sorting is correct, else promising
930 branches get pruned */
931 double valuea = (*a)->production[compare_key] +
932 compare_key_trade_bonus * (*a)->production[O_TRADE];
933 double valueb = (*b)->production[compare_key] +
934 compare_key_trade_bonus * (*b)->production[O_TRADE];
935
936 /* Most production of what we care about goes first */
937 /* Double compare is ok, both values are calculated in the same way
938 and should only be considered equal, if equal in compare_key
939 and O_TRADE */
940 if (valuea != valueb) {
941 /* b-a so we sort big numbers first */
942 return valueb - valuea;
943 }
944
946}
947
948/****************************************************************************
949 Compute the tile-type lattice.
950****************************************************************************/
951
952/************************************************************************/
956static void compute_tile_production(const struct city *pcity,
957 const struct tile *ptile,
958 struct cm_tile_type *out)
959{
960 bool is_celebrating = base_city_celebrating(pcity);
961
963 out->production[o] = city_tile_output(pcity, ptile, is_celebrating, o);
965}
966
967/************************************************************************/
974static void tile_type_lattice_add(struct tile_type_vector *lattice,
975 const struct cm_tile_type *newtype,
976 int tindex)
977{
978 struct cm_tile_type *type;
979 int i;
980
981 i = tile_type_vector_find_equivalent(lattice, newtype);
982 if (i >= 0) {
983 /* We already have this type of tile; use it. */
984 type = lattice->p[i];
985 } else {
986 /* This is a new tile type; add it to the lattice. */
987 type = tile_type_dup(newtype);
988
989 /* Link up to the types we dominate, and those that dominate us */
990 tile_type_vector_iterate(lattice, other) {
991 int cmp = tile_type_better(other, type);
992
993 if (cmp > 0) {
994 tile_type_vector_append(&type->better_types, other);
995 tile_type_vector_append(&other->worse_types, type);
996 } else if (cmp < 0) {
997 tile_type_vector_append(&other->better_types, type);
998 tile_type_vector_append(&type->worse_types, other);
999 }
1001
1002 /* Insert into the list */
1003 type->lattice_index = lattice->size;
1004 tile_type_vector_append(lattice, type);
1005 }
1006
1007 /* Finally, add the tile to the tile type. */
1008 if (!type->is_specialist) {
1009 struct cm_tile tile;
1010
1011 tile.type = type;
1012 tile.index = tindex;
1013
1014 tile_vector_append(&type->tiles, tile);
1015 }
1016}
1017
1018/*
1019 * Add the specialist types to the lattice.
1020 */
1021
1022/************************************************************************/
1026static void init_specialist_lattice_nodes(struct tile_type_vector *lattice,
1027 const struct city *pcity)
1028{
1029 struct cm_tile_type type;
1030
1032 type.is_specialist = TRUE;
1033
1034 /* for each specialist type, create a tile_type that has as production
1035 * the bonus for the specialist (if the city is allowed to use it) */
1037 if (city_can_use_specialist(pcity, i)) {
1038 type.spec = i;
1039 output_type_iterate(output) {
1040 type.production[output] = get_specialist_output(pcity, i, output);
1042
1043 tile_type_lattice_add(lattice, &type, 0);
1044 }
1046}
1047
1048/************************************************************************/
1055static void top_sort_lattice(struct tile_type_vector *lattice)
1056{
1057 if (lattice->size > 0) {
1058 int i;
1059 bool marked[lattice->size];
1060 bool will_mark[lattice->size];
1061 struct tile_type_vector vectors[2];
1062 struct tile_type_vector *current, *next;
1063
1064 memset(marked, 0, sizeof(marked));
1065 memset(will_mark, 0, sizeof(will_mark));
1066
1067 tile_type_vector_init(&vectors[0]);
1068 tile_type_vector_init(&vectors[1]);
1069 current = &vectors[0];
1070 next = &vectors[1];
1071
1072 /* Fill up 'next' */
1073 tile_type_vector_iterate(lattice, ptype) {
1074 if (tile_type_num_prereqs(ptype) == 0) {
1075 tile_type_vector_append(next, ptype);
1076 }
1078
1079 /* While we have nodes to process: mark the nodes whose prereqs have
1080 * all been visited. Then, store all the new nodes on the frontier. */
1081 while (next->size != 0) {
1082 /* What was the next frontier is now the current frontier */
1083 struct tile_type_vector *vtmp = current;
1084
1085 current = next;
1086 next = vtmp;
1087 next->size = 0; /* Clear out the contents */
1088
1089 /* Look over the current frontier and process everyone */
1090 tile_type_vector_iterate(current, ptype) {
1091 /* See if all prereqs were marked. If so, decide to mark this guy,
1092 and put all the descendents on 'next'. */
1093 bool can_mark = TRUE;
1094 int sumdepth = 0;
1095
1096 if (will_mark[ptype->lattice_index]) {
1097 continue; /* We've already been processed */
1098 }
1099 tile_type_vector_iterate(&ptype->better_types, better) {
1100 if (!marked[better->lattice_index]) {
1101 can_mark = FALSE;
1102 break;
1103 } else {
1104 sumdepth += tile_type_num_tiles(better);
1105 if (sumdepth >= FC_INFINITY) {
1106 /* If this is the case, then something better could
1107 always be used, and the same holds for our children */
1108 sumdepth = FC_INFINITY;
1109 can_mark = TRUE;
1110 break;
1111 }
1112 }
1114 if (can_mark) {
1115 /* Mark and put successors on the next frontier */
1116 will_mark[ptype->lattice_index] = TRUE;
1117 tile_type_vector_iterate(&ptype->worse_types, worse) {
1118 tile_type_vector_append(next, worse);
1120
1121 /* This is what we spent all this time computing. */
1122 ptype->lattice_depth = sumdepth;
1123 }
1125
1126 /* Now, actually mark everyone and get set for next loop */
1127 for (i = 0; i < lattice->size; i++) {
1128 marked[i] = marked[i] || will_mark[i];
1129 will_mark[i] = FALSE;
1130 }
1131 }
1132
1133 tile_type_vector_free(&vectors[0]);
1134 tile_type_vector_free(&vectors[1]);
1135 }
1136}
1137
1138/************************************************************************/
1154static void clean_lattice(struct tile_type_vector *lattice,
1155 const struct city *pcity)
1156{
1157 int i, j; /* i is the index we read, j is the index we write */
1158 struct tile_type_vector tofree;
1159 bool forced_loop = FALSE;
1160
1161 /* We collect the types we want to remove and free them in one fell
1162 swoop at the end, in order to avoid memory errors. */
1163 tile_type_vector_init(&tofree);
1164
1165 /* forced_loop is workaround for what seems like gcc optimization
1166 * bug.
1167 * This applies to -O2 optimization on some distributions. */
1168 if (lattice->size > 0) {
1169 forced_loop = TRUE;
1170 }
1171 for (i = 0, j = 0; i < lattice->size || forced_loop; i++) {
1172 struct cm_tile_type *ptype = lattice->p[i];
1173 citizens csize = city_size_get(pcity);
1174
1175 forced_loop = FALSE;
1176
1177 if (ptype->lattice_depth >= csize) {
1178 tile_type_vector_append(&tofree, ptype);
1179 } else {
1180 /* Remove links to children that are being removed. */
1181
1182 int ci, cj; /* 'c' for 'child'; read from ci, write to cj */
1183
1184 lattice->p[j] = ptype;
1185 lattice->p[j]->lattice_index = j;
1186 j++;
1187
1188 for (ci = 0, cj = 0; ci < ptype->worse_types.size; ci++) {
1189 const struct cm_tile_type *ptype2 = ptype->worse_types.p[ci];
1190
1191 if (ptype2->lattice_depth < csize) {
1192 ptype->worse_types.p[cj] = ptype->worse_types.p[ci];
1193 cj++;
1194 }
1195 }
1196 ptype->worse_types.size = cj;
1197 }
1198 }
1199 lattice->size = j;
1200
1202}
1203
1204/************************************************************************/
1209static void sort_lattice_by_fitness(const struct cm_state *state,
1210 struct tile_type_vector *lattice)
1211{
1212 int i;
1213
1214 /* compute fitness */
1215 tile_type_vector_iterate(lattice, ptype) {
1216 ptype->estimated_fitness = estimate_fitness(state, ptype->production);
1218
1219 /* sort by it */
1220 qsort(lattice->p, lattice->size, sizeof(*lattice->p),
1222
1223 /* fix the lattice indices */
1224 for (i = 0; i < lattice->size; i++) {
1225 lattice->p[i]->lattice_index = i;
1226 }
1227
1228 log_base(LOG_LATTICE, "sorted lattice:");
1229 print_lattice(LOG_LATTICE, lattice);
1230}
1231
1232/************************************************************************/
1235static void init_tile_lattice(struct city *pcity,
1236 struct tile_type_vector *lattice)
1237{
1238 struct cm_tile_type type;
1239 struct tile *pcenter = city_tile(pcity);
1240 const struct civ_map *nmap = &(wld.map);
1241
1242 /* Add all the fields into the lattice */
1243 tile_type_init(&type); /* Init just once */
1244
1245 city_tile_iterate_index(nmap, city_map_radius_sq_get(pcity), pcenter, ptile,
1246 ctindex) {
1247 if (is_free_worked(pcity, ptile)) {
1248 continue;
1249 } else if (city_can_work_tile(pcity, ptile)) {
1250 compute_tile_production(pcity, ptile, &type); /* Clobbers type */
1251 tile_type_lattice_add(lattice, &type, ctindex); /* Copy type if needed */
1252 }
1254
1255 /* Add all the specialists into the lattice. */
1256 init_specialist_lattice_nodes(lattice, pcity);
1257
1258 /* Set the lattice_depth fields, and clean up unreachable nodes. */
1259 top_sort_lattice(lattice);
1260 clean_lattice(lattice, pcity);
1261
1262 /* All done now. */
1263 print_lattice(LOG_LATTICE, lattice);
1264}
1265
1266
1267/****************************************************************************
1268
1269 Handling the choice stack for the bb algorithm.
1270
1271****************************************************************************/
1272
1273
1274/************************************************************************/
1277static bool choice_stack_empty(struct cm_state *state)
1278{
1279 return state->choice.size == 0;
1280}
1281
1282/************************************************************************/
1285static int last_choice(struct cm_state *state)
1286{
1288
1289 return state->choice.stack[state->choice.size - 1];
1290}
1291
1292/************************************************************************/
1297static int num_types(const struct cm_state *state)
1298{
1299 return tile_type_vector_size(&state->lattice);
1300}
1301
1302/************************************************************************/
1308static void add_workers(struct partial_solution *soln,
1309 int itype, int number,
1310 const struct cm_state *state)
1311{
1312 const struct cm_tile_type *ptype = tile_type_get(state, itype);
1313 int newcount;
1314 int old_worker_count = soln->worker_counts[itype];
1315
1316 if (number == 0) {
1317 return;
1318 }
1319
1320 /* update the number of idle workers */
1321 newcount = soln->idle - number;
1322 fc_assert_ret(newcount >= 0);
1323 fc_assert_ret(newcount <= city_size_get(state->pcity));
1324 soln->idle = newcount;
1325
1326 /* update the worker counts */
1327 newcount = soln->worker_counts[itype] + number;
1328 fc_assert_ret(newcount >= 0);
1329 fc_assert_ret(newcount <= tile_type_num_tiles(ptype));
1330 soln->worker_counts[itype] = newcount;
1331
1332 /* update prereqs array: if we are no longer full but we were,
1333 * we need to decrement the count, and vice-versa. */
1334 if (old_worker_count == tile_type_num_tiles(ptype)) {
1335 fc_assert_ret(number < 0);
1336 tile_type_vector_iterate(&ptype->worse_types, other) {
1337 soln->prereqs_filled[other->lattice_index]--;
1338 fc_assert_ret(soln->prereqs_filled[other->lattice_index] >= 0);
1340 } else if (soln->worker_counts[itype] == tile_type_num_tiles(ptype)) {
1341 fc_assert_ret(number > 0);
1342 tile_type_vector_iterate(&ptype->worse_types, other) {
1343 soln->prereqs_filled[other->lattice_index]++;
1344 fc_assert_ret(soln->prereqs_filled[other->lattice_index]
1345 <= tile_type_num_prereqs(other));
1347 }
1348
1349 /* update production */
1350 output_type_iterate(stat_index) {
1351 newcount = soln->production[stat_index] + number * ptype->production[stat_index];
1352 soln->production[stat_index] = newcount;
1354}
1355
1356/************************************************************************/
1359static void add_worker(struct partial_solution *soln,
1360 int itype, const struct cm_state *state)
1361{
1362 add_workers(soln, itype, 1, state);
1363}
1364
1365/************************************************************************/
1368static void remove_worker(struct partial_solution *soln,
1369 int itype, const struct cm_state *state)
1370{
1371 add_workers(soln, itype, -1, state);
1372}
1373
1374/************************************************************************/
1378static void pop_choice(struct cm_state *state)
1379{
1381 remove_worker(&state->current, last_choice(state), state);
1382 state->choice.size--;
1383}
1384
1385/************************************************************************/
1388static bool prereqs_filled(const struct partial_solution *soln, int type,
1389 const struct cm_state *state)
1390{
1391 const struct cm_tile_type *ptype = tile_type_get(state, type);
1392 int prereqs = tile_type_num_prereqs(ptype);
1393
1394 return soln->prereqs_filled[type] == prereqs;
1395}
1396
1397/************************************************************************/
1406static int next_choice(struct cm_state *state, int oldchoice, bool negative_ok)
1407{
1408 int newchoice;
1409
1410 for (newchoice = oldchoice + 1;
1411 newchoice < num_types(state); newchoice++) {
1412 const struct cm_tile_type *ptype = tile_type_get(state, newchoice);
1413
1414 if (!ptype->is_specialist && (state->current.worker_counts[newchoice]
1415 == tile_vector_size(&ptype->tiles))) {
1416 /* we've already used all these tiles */
1417 continue;
1418 }
1419 if (!prereqs_filled(&state->current, newchoice, state)) {
1420 /* we could use a strictly better tile instead */
1421 continue;
1422 }
1423 if (!choice_is_promising(state, newchoice, negative_ok)) {
1424 /* heuristic says we can't beat the best going this way */
1425 log_base(LOG_PRUNE_BRANCH, "--- pruning branch ---");
1428 " + worker on ");
1429 log_base(LOG_PRUNE_BRANCH, "--- branch pruned ---");
1430 continue;
1431 }
1432 break;
1433 }
1434
1435 /* returns num_types if no next choice was available. */
1436 return newchoice;
1437}
1438
1439
1440/************************************************************************/
1444static bool take_sibling_choice(struct cm_state *state, bool negative_ok)
1445{
1446 int oldchoice = last_choice(state);
1447 int newchoice;
1448
1449 /* need to remove first, to run the heuristic */
1450 remove_worker(&state->current, oldchoice, state);
1451 newchoice = next_choice(state, oldchoice, negative_ok);
1452
1453 if (newchoice == num_types(state)) {
1454 /* add back in so the caller can then remove it again. */
1455 add_worker(&state->current, oldchoice, state);
1456 return FALSE;
1457 } else {
1458 add_worker(&state->current, newchoice, state);
1459 state->choice.stack[state->choice.size-1] = newchoice;
1460 /* choice.size is unchanged */
1461 return TRUE;
1462 }
1463}
1464
1465/************************************************************************/
1472static bool take_child_choice(struct cm_state *state, bool negative_ok)
1473{
1474 int oldchoice, newchoice;
1475
1476 if (state->current.idle == 0) {
1477 return FALSE;
1478 }
1479
1480 if (state->choice.size == 0) {
1481 oldchoice = 0;
1482 } else {
1483 oldchoice = last_choice(state);
1484 }
1485
1486 /* oldchoice-1 because we can use oldchoice again */
1487 newchoice = next_choice(state, oldchoice - 1, negative_ok);
1488
1489 /* did we fail? */
1490 if (newchoice == num_types(state)) {
1491 return FALSE;
1492 }
1493
1494 /* now push the new choice on the choice stack */
1495 add_worker(&state->current, newchoice, state);
1496 state->choice.stack[state->choice.size] = newchoice;
1497 state->choice.size++;
1498
1499 return TRUE;
1500}
1501
1502/************************************************************************/
1506static void complete_solution(struct partial_solution *soln,
1507 const struct cm_state *state,
1508 const struct tile_type_vector *lattice)
1509{
1510 int last_worker_choice = -1;
1511 int i;
1512
1513 if (soln->idle == 0) {
1514 return;
1515 }
1516
1517 /* find the last worker type added (-1 if none) */
1518 for (i = 0; i < num_types(state); i++) {
1519 if (soln->worker_counts[i] != 0) {
1520 last_worker_choice = i;
1521 }
1522 }
1523
1524 /* While there are idle workers, pick up the next-best kind of tile,
1525 * and assign the workers to the tiles.
1526 * Respect lexicographic order and prerequisites. */
1527 tile_type_vector_iterate(lattice, ptype) {
1528 int used = soln->worker_counts[ptype->lattice_index];
1529 int total = tile_type_num_tiles(ptype);
1530 int touse;
1531
1532 if (ptype->lattice_index < last_worker_choice) {
1533 /* lex-order: we can't use ptype (some other branch
1534 will check this combination, or already did) */
1535 continue;
1536 }
1537 if (!prereqs_filled(soln, ptype->lattice_index, state)) {
1538 /* don't bother using this tile before all better tiles are used */
1539 continue;
1540 }
1541
1542 touse = total - used;
1543 if (touse > soln->idle) {
1544 touse = soln->idle;
1545 }
1546 add_workers(soln, ptype->lattice_index, touse, state);
1547
1548 if (soln->idle == 0) {
1549 /* nothing left to do here */
1550 return;
1551 }
1553}
1554
1555/************************************************************************/
1558static int specialists_in_solution(const struct cm_state *state,
1559 const struct partial_solution *soln)
1560{
1561 int count = 0;
1562 int i;
1563
1564 for (i = 0 ; i < num_types(state); i++) {
1565 if (soln->worker_counts[i] > 0 && tile_type_get(state, i)->is_specialist) {
1566 count += soln->worker_counts[i];
1567 }
1568 }
1569
1570 return count;
1571}
1572
1573/************************************************************************/
1583static void compute_max_stats_heuristic(const struct cm_state *state,
1584 const struct partial_solution *soln,
1585 int production[],
1586 int check_choice, bool negative_ok)
1587{
1588 struct partial_solution solnplus; /* Will be soln, plus some tiles */
1589 const struct civ_map *nmap = &(wld.map);
1590
1591 /* Production is whatever the solution produces, plus the
1592 most possible of each kind of production the idle workers could
1593 produce */
1594
1595 if (soln->idle == 1) {
1596 /* Then the total solution is soln + this new worker. So we know the
1597 production exactly, and can shortcut the later code. */
1598 const struct cm_tile_type *ptype = tile_type_get(state, check_choice);
1599
1600 memcpy(production, soln->production, sizeof(soln->production));
1601 output_type_iterate(stat_index) {
1602 production[stat_index] += ptype->production[stat_index];
1604
1605 } else {
1606
1607 /* Initialize solnplus here, after the shortcut check */
1608 init_partial_solution(&solnplus, num_types(state),
1609 city_size_get(state->pcity),
1610 negative_ok);
1611
1612 output_type_iterate(stat_index) {
1613 /* compute the solution that has soln, then the check_choice,
1614 then complete it with the best available tiles for the stat. */
1615 copy_partial_solution(&solnplus, soln, state);
1616 add_worker(&solnplus, check_choice, state);
1617 complete_solution(&solnplus, state, &state->lattice_by_prod[stat_index]);
1618
1619 production[stat_index] = solnplus.production[stat_index];
1621
1622 destroy_partial_solution(&solnplus);
1623
1624 }
1625
1626 /* We found the basic production, however, bonus, taxes,
1627 * free production, tithes, trade routes are missing.
1628 * We add free production, and have the city.c code do the rest */
1629
1630 struct city *pcity = state->pcity;
1631 struct tile *pcenter = city_tile(pcity);
1632 bool is_celebrating = base_city_celebrating(pcity);
1633
1634 output_type_iterate(stat_index) {
1635 int base = production[stat_index];
1636
1637 city_tile_iterate(nmap, city_map_radius_sq_get(pcity), pcenter, ptile) {
1638 if (is_free_worked(pcity, ptile)) {
1639 base += city_tile_output(pcity, ptile, is_celebrating, stat_index);
1640 }
1642 pcity->citizen_base[stat_index] = base;
1644
1645 set_city_production(pcity);
1646 memcpy(production, pcity->prod, sizeof(pcity->prod));
1647}
1648
1649/************************************************************************/
1655static bool choice_is_promising(struct cm_state *state, int newchoice,
1656 bool negative_ok)
1657{
1658 int production[O_LAST];
1659 bool beats_best = FALSE;
1660
1661 /* this computes an upper bound (componentwise) for the current branch,
1662 if it is worse in every component than the best, or still insufficient,
1663 then we can prune the whole branch */
1664 compute_max_stats_heuristic(state, &state->current, production, newchoice,
1665 negative_ok);
1666
1667 output_type_iterate(stat_index) {
1668 if (production[stat_index] < state->min_production[stat_index]) {
1669 log_base(LOG_PRUNE_BRANCH, "--- pruning: insufficient %s (%d < %d)",
1670 get_output_name(stat_index), production[stat_index],
1671 state->min_production[stat_index]);
1672 return FALSE;
1673 }
1674 if (production[stat_index] > state->best.production[stat_index]
1675 && state->parameter.factor[stat_index] > 0 ) {
1676 beats_best = TRUE;
1677 /* may still fail to meet min at another production type, so
1678 * don't short-circuit */
1679 }
1681
1682 /* If we don't get the city content, we assume using every idle worker
1683 as specialist and the maximum producible luxury already computed.
1684 If this is less than the amount of luxury we calculated in
1685 evaluate_solution() (where min_luxury is set), when we observed the
1686 city in disorder, then this is clearly not worth pursuing.
1687 (Since we're comparing to evaluate_solution()'s calculation, we
1688 don't need to take effects, angry citizens etc into account here
1689 either.)
1690 FIXME: this heuristic will break in rulesets where specialists can
1691 influence happiness other than by direct production of luxury. */
1692 {
1693 int specialists_amount = specialists_in_solution(state, &state->current);
1694 int max_content = player_content_citizens(city_owner(state->pcity));
1695 int specialists_suppress_unhappy
1696 = MAX(specialists_amount + state->current.idle - max_content, 0);
1697 int max_luxury = production[O_LUXURY]
1698 + game.info.happy_cost * specialists_suppress_unhappy;
1699
1700 if (max_luxury < state->min_luxury ) {
1701 log_base(LOG_PRUNE_BRANCH, "--- pruning: disorder (%d + %d*%d < %d)",
1702 production[O_LUXURY],
1704 specialists_suppress_unhappy,
1705 state->min_luxury);
1706 return FALSE;
1707 }
1708 }
1709 if (!beats_best) {
1710 log_base(LOG_PRUNE_BRANCH, "--- pruning: best is better in all important ways");
1711 }
1712
1713 return beats_best;
1714}
1715
1716/************************************************************************/
1719static void init_min_production(struct cm_state *state)
1720{
1721 struct city *pcity = state->pcity;
1722
1724 state->min_production[o] = pcity->usage[o] + state->parameter.minimal_surplus[o];
1726
1727 /* We could get a minimum on luxury if we knew how many luxuries were
1728 * needed to make us content. */
1729}
1730
1731/************************************************************************/
1734static void get_tax_rates(const struct player *pplayer, int rates[])
1735{
1736 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1737
1738 if (game.info.changable_tax) {
1739 rates[SCIENCE] = pplayer->economic.science;
1740 rates[LUXURY] = pplayer->economic.luxury;
1741 rates[TAX] = 100 - rates[SCIENCE] - rates[LUXURY];
1742 } else {
1743 rates[SCIENCE] = game.info.forced_science;
1744 rates[LUXURY] = game.info.forced_luxury;
1745 rates[TAX] = game.info.forced_gold;
1746 }
1747
1748 /* ANARCHY */
1750 rates[SCIENCE] = 0;
1751 rates[LUXURY] = 100;
1752 rates[TAX] = 0;
1753 }
1754}
1755
1756/************************************************************************/
1764static double estimate_fitness(const struct cm_state *state,
1765 const int production[])
1766{
1767 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1768 const struct city *pcity = state->pcity;
1769 const struct player *pplayer = city_owner(pcity);
1770 int rates[3];
1771 double estimates[O_LAST];
1772 double sum = 0;
1773 int trade;
1774
1775 output_type_iterate(stat_index) {
1776 estimates[stat_index] = production[stat_index];
1778
1779 /* bonus to trade is applied before calculating taxes, see city.c */
1780 trade = estimates[O_TRADE] * pcity->bonus[O_TRADE] / 100.0;
1781
1782 get_tax_rates(pplayer, rates);
1783
1784 /* sci/lux/gold get benefit from the tax rates (in percentage) */
1785 estimates[O_SCIENCE]
1786 += rates[SCIENCE] * trade / 100.0;
1787 estimates[O_LUXURY]
1788 += rates[LUXURY] * trade / 100.0;
1789 estimates[O_GOLD]
1790 += rates[TAX] * trade / 100.0;
1791
1792 /* now add in the bonuses from building effects (in percentage) */
1793 output_type_iterate(stat_index) {
1794 estimates[stat_index] *= pcity->bonus[stat_index] / 100.0;
1796
1797 /* finally, sum it all up, weighted by the parameter, but give additional
1798 * weight to luxuries to take account of disorder/happy constraints */
1799 output_type_iterate(stat_index) {
1800 sum += estimates[stat_index] * state->parameter.factor[stat_index];
1802 sum += estimates[O_LUXURY];
1803
1804 return sum;
1805}
1806
1807/************************************************************************/
1819static bool bb_next(struct cm_state *state, bool negative_ok)
1820{
1821 /* if no idle workers, then look at our solution. */
1822 if (state->current.idle == 0) {
1823 struct cm_fitness value = evaluate_solution(state, &state->current);
1824
1826 if (fitness_better(value, state->best_value)) {
1827 log_base(LOG_BETTER_LEAF, "-> replaces previous best");
1828 copy_partial_solution(&state->best, &state->current, state);
1829 state->best_value = value;
1830 }
1831 }
1832
1833 /* try to move to a child branch, if we can. If not (including if we're
1834 at a leaf), then move to a sibling. */
1835 if (!take_child_choice(state, negative_ok)) {
1836 /* keep trying to move to a sibling branch, or popping out a level if
1837 we're stuck (fully examined the current branch) */
1838 while ((!choice_stack_empty(state))
1839 && !take_sibling_choice(state, negative_ok)) {
1840 pop_choice(state);
1841 }
1842
1843 /* if we popped out all the way, we're done */
1844 if (choice_stack_empty(state)) {
1845 return TRUE;
1846 }
1847 }
1848
1849 /* if we didn't detect that we were done, we aren't */
1850 return FALSE;
1851}
1852
1853/************************************************************************/
1856static struct cm_state *cm_state_init(struct city *pcity, bool negative_ok)
1857{
1858 const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1859 const struct player *pplayer = city_owner(pcity);
1860 int numtypes;
1861 struct cm_state *state = fc_malloc(sizeof(*state));
1862 int rates[3];
1863 citizens csize = city_size_get(pcity);
1864
1865 log_base(LOG_CM_STATE, "creating cm_state for %s (size %d)",
1866 city_name_get(pcity), csize);
1867
1868 /* copy the arguments */
1869 state->pcity = pcity;
1870
1871 /* create the lattice */
1872 tile_type_vector_init(&state->lattice);
1874 numtypes = tile_type_vector_size(&state->lattice);
1875
1876 get_tax_rates(pplayer, rates);
1877
1878 /* For the heuristic, make sorted copies of the lattice */
1879 output_type_iterate(stat_index) {
1880 int lsize = tile_type_vector_size(&state->lattice);
1881
1882 if (lsize > 0) {
1883 tile_type_vector_init(&state->lattice_by_prod[stat_index]);
1884 tile_type_vector_copy(&state->lattice_by_prod[stat_index], &state->lattice);
1885 compare_key = stat_index;
1886 /* Calculate effect of 1 trade production on interesting production */
1887 switch (stat_index) {
1888 case O_SCIENCE:
1889 compare_key_trade_bonus = rates[SCIENCE] * pcity->bonus[O_TRADE] / 100.0;
1890 break;
1891 case O_LUXURY:
1892 compare_key_trade_bonus = rates[LUXURY] * pcity->bonus[O_TRADE] / 100.0;
1893 break;
1894 case O_GOLD:
1895 compare_key_trade_bonus = rates[TAX] * pcity->bonus[O_TRADE] / 100.0;
1896 break;
1897 default:
1899 break;
1900 }
1901 qsort(state->lattice_by_prod[stat_index].p, lsize,
1902 sizeof(*state->lattice_by_prod[stat_index].p),
1904 }
1906
1907 state->min_luxury = - FC_INFINITY;
1908
1909 /* We have no best solution yet, so its value is the worst possible. */
1910 init_partial_solution(&state->best, numtypes, csize, negative_ok);
1911 state->best_value = worst_fitness();
1912
1913 /* Initialize the current solution and choice stack to empty */
1914 init_partial_solution(&state->current, numtypes, csize, negative_ok);
1915 state->choice.stack = fc_malloc(csize * sizeof(*state->choice.stack));
1916 state->choice.size = 0;
1917
1918 /* Initialize workers map */
1920 sizeof(state->workers_map));
1921
1922 return state;
1923}
1924
1925/************************************************************************/
1929{
1930 struct city *pcity = state->pcity;
1932 citizens city_size = city_size_get(pcity);
1933 int max_surplus = -game.info.food_cost * city_size;
1934 bool is_celebrating = base_city_celebrating(pcity);
1935 citizens workers = city_size;
1936 int food_needed = city_granary_size(city_size) - pcity->food_stock;
1937 int min_turns;
1938 const struct civ_map *nmap = &(wld.map);
1939
1940 city_map_iterate(city_radius_sq, cindex, x, y) {
1941 struct tile *ptile = city_map_to_tile(nmap, pcity->tile, city_radius_sq, x, y);
1942 if (!ptile) {
1943 continue;
1944 }
1945 if (is_free_worked_index(cindex)) {
1946 max_surplus += city_tile_output(pcity, ptile, is_celebrating, O_FOOD);
1947 }
1949
1950 if (max_surplus <= 0) {
1951 return max_surplus;
1952 }
1953
1954 if (food_needed <= 0) {
1955 return 0;
1956 }
1957
1959 int num = tile_vector_size(&ptype->tiles);
1960
1961 if (ptype->is_specialist || workers < num) {
1962 max_surplus += workers * ptype->production[O_FOOD];
1963 break;
1964 }
1965 max_surplus += num * ptype->production[O_FOOD];
1966 workers -= num;
1968
1969 /* min_turns will always be positive because if food_needed or
1970 * max_surplus are non-positive, this function returns earlier. */
1971 min_turns = (food_needed + max_surplus - 1) / max_surplus;
1972
1973 return (food_needed + min_turns - 1) / min_turns;
1974}
1975
1976/************************************************************************/
1980static void begin_search(struct cm_state *state,
1981 const struct cm_parameter *parameter,
1982 bool negative_ok)
1983{
1984#ifdef GATHER_TIME_STATS
1985 timer_start(performance.current->wall_timer);
1986 performance.current->query_count++;
1987#endif /* GATHER_TIME_STATS */
1988
1989 /* copy the parameter and sort the main lattice by it */
1990 cm_copy_parameter(&state->parameter, parameter);
1991 sort_lattice_by_fitness(state, &state->lattice);
1992
1993 if (parameter->max_growth) {
1996 }
1997
1998 init_min_production(state);
1999
2000 /* Clear out the old solution */
2001 state->best_value = worst_fitness();
2003 init_partial_solution(&state->current, num_types(state),
2004 city_size_get(state->pcity),
2005 negative_ok);
2006 state->choice.size = 0;
2007}
2008
2009/************************************************************************/
2013static void end_search(struct cm_state *state)
2014{
2015#ifdef GATHER_TIME_STATS
2016 timer_stop(performance.current->wall_timer);
2017
2018#ifdef PRINT_TIME_STATS_EVERY_QUERY
2019 print_performance(performance.current);
2020#endif /* PRINT_TIME_STATS_EVERY_QUERY */
2021
2022 performance.current = NULL;
2023#endif /* GATHER_TIME_STATS */
2024}
2025
2026/************************************************************************/
2029static void cm_state_free(struct cm_state *state)
2030{
2032 output_type_iterate(stat_index) {
2033 tile_type_vector_free(&state->lattice_by_prod[stat_index]);
2037
2038 FC_FREE(state->choice.stack);
2039 FC_FREE(state->workers_map);
2040 FC_FREE(state);
2041}
2042
2043/************************************************************************/
2046static void cm_find_best_solution(struct cm_state *state,
2047 const struct cm_parameter *const parameter,
2048 struct cm_result *result, bool negative_ok)
2049{
2050 int loop_count = 0;
2051 int max_count;
2052 struct city backup;
2053
2054#ifdef GATHER_TIME_STATS
2055 performance.current = &performance.opt;
2056#endif
2057
2058 begin_search(state, parameter, negative_ok);
2059
2060 /* Make a backup of the city to restore at the very end */
2061 memcpy(&backup, state->pcity, sizeof(backup));
2062
2063 if (player_is_cpuhog(city_owner(state->pcity))) {
2064 max_count = CPUHOG_CM_MAX_LOOP;
2065 } else {
2066 max_count = CM_MAX_LOOP;
2067 }
2068
2069 result->aborted = FALSE;
2070
2071 /* search until we find a feasible solution */
2072 while (!bb_next(state, negative_ok)) {
2073 /* Limit the number of loops. */
2074 loop_count++;
2075
2076 if (loop_count == max_count + 1) {
2077#ifdef FREECIV_TESTMATIC
2078 /* This happens at a rate inversely proportional to the number of needed iterations
2079 * https://osdn.net/projects/freeciv/ticket/44438
2080 * we mostly find solutions in less than 100 iteration
2081 * 33% in less than 24 iterations
2082 * 66% in less than 100
2083 * 99% in less than 1800
2084 * extremely rarely 10 000+
2085 * it is not a bug it is normal, so just silent this warning
2086 */
2087 log_base(
2088 LOG_DEBUG,
2089 "Did not find a cm solution in %d iterations for %s.",
2090 max_count, city_name_get(state->pcity));
2091#endif /* FREECIV_TESTMATIC */
2092
2093#ifndef CM_LOOP_NO_LIMIT
2094 result->aborted = TRUE;
2095 break;
2096#endif /* CM_LOOP_NO_LIMIT */
2097 }
2098 }
2099
2100#ifdef CM_LOOP_NO_LIMIT
2101 if (loop_count > max_count) {
2102 log_warn("It took %d iterations to finish.", loop_count);
2103 }
2104#endif /* CM_LOOP_NO_LIMIT */
2105
2106 /* convert to the caller's format */
2107 convert_solution_to_result(state, &state->best, result);
2108
2109 memcpy(state->pcity, &backup, sizeof(backup));
2110
2111 end_search(state);
2112}
2113
2114/************************************************************************/
2118void cm_query_result(struct city *pcity,
2119 const struct cm_parameter *param,
2120 struct cm_result *result, bool negative_ok)
2121{
2122 struct cm_state *state = cm_state_init(pcity, negative_ok);
2123
2124 /* Refresh the city. Otherwise the CM can give wrong results or just be
2125 * slower than necessary. Note that cities are often passed in in an
2126 * unrefreshed state (which should probably be fixed). */
2128
2129 cm_find_best_solution(state, param, result, negative_ok);
2130 cm_state_free(state);
2131}
2132
2133/************************************************************************/
2136bool cm_are_parameter_equal(const struct cm_parameter *const p1,
2137 const struct cm_parameter *const p2)
2138{
2140 if (p1->minimal_surplus[i] != p2->minimal_surplus[i]) {
2141 return FALSE;
2142 }
2143 if (p1->factor[i] != p2->factor[i]) {
2144 return FALSE;
2145 }
2147 if (p1->require_happy != p2->require_happy) {
2148 return FALSE;
2149 }
2150 if (p1->allow_disorder != p2->allow_disorder) {
2151 return FALSE;
2152 }
2153 if (p1->allow_specialists != p2->allow_specialists) {
2154 return FALSE;
2155 }
2156 if (p1->happy_factor != p2->happy_factor) {
2157 return FALSE;
2158 }
2159 if (p1->max_growth != p2->max_growth) {
2160 return FALSE;
2161 }
2162
2163 return TRUE;
2164}
2165
2166/************************************************************************/
2170 const struct cm_parameter *const src)
2171{
2172 memcpy(dest, src, sizeof(struct cm_parameter));
2173}
2174
2175/************************************************************************/
2179{
2180 output_type_iterate(stat_index) {
2181 dest->minimal_surplus[stat_index] = 0;
2182 dest->factor[stat_index] = 1;
2184
2185 dest->happy_factor = 1;
2186 dest->require_happy = FALSE;
2187 dest->allow_disorder = FALSE;
2188 dest->allow_specialists = TRUE;
2189 dest->max_growth = FALSE;
2190}
2191
2192/************************************************************************/
2197{
2198 output_type_iterate(stat_index) {
2199 dest->minimal_surplus[stat_index] = -FC_INFINITY;
2200 dest->factor[stat_index] = 1;
2202
2203 dest->happy_factor = 1;
2204 dest->require_happy = FALSE;
2205 dest->allow_disorder = TRUE;
2206 dest->allow_specialists = TRUE;
2207 dest->max_growth = FALSE;
2208}
2209
2210/************************************************************************/
2213int cm_result_workers(const struct cm_result *result)
2214{
2215 int count = 0;
2216
2217 city_map_iterate(result->city_radius_sq, cindex, x, y) {
2218 if (is_free_worked_index(cindex)) {
2219 continue;
2220 }
2221
2222 if (result->worker_positions[cindex]) {
2223 count++;
2224 }
2226
2227 return count;
2228}
2229
2230/************************************************************************/
2233int cm_result_specialists(const struct cm_result *result)
2234{
2235 int count = 0;
2236
2238 count += result->specialists[spec];
2240
2241 return count;
2242}
2243
2244/************************************************************************/
2247int cm_result_citizens(const struct cm_result *result)
2248{
2249 return cm_result_workers(result) + cm_result_specialists(result);
2250}
2251
2252/************************************************************************/
2257 const struct city *pcity)
2258{
2259 cm_result_copy(result, pcity, NULL);
2260}
2261
2262/************************************************************************/
2267static void cm_result_copy(struct cm_result *result,
2268 const struct city *pcity, bool *workers_map)
2269{
2270 struct tile *pcenter = city_tile(pcity);
2271 const struct civ_map *nmap = &(wld.map);
2272
2273 /* Clear worker positions */
2274 memset(result->worker_positions, 0,
2275 sizeof(*result->worker_positions)
2276 * city_map_tiles(result->city_radius_sq));
2277
2278 city_tile_iterate_index(nmap, result->city_radius_sq, pcenter, ptile, ctindex) {
2279 if (workers_map == NULL) {
2280 /* Use the main map */
2281 struct city *pwork = tile_worked(ptile);
2282
2283 result->worker_positions[ctindex] = (NULL != pwork && pwork == pcity);
2284 } else {
2285 result->worker_positions[ctindex] = workers_map[ctindex];
2286 }
2288
2289 /* Copy the specialist counts */
2291 result->specialists[spec] = pcity->specialists[spec];
2293
2294 /* Find the surplus production numbers */
2295 get_city_surplus(pcity, result->surplus,
2296 &result->disorder, &result->happy);
2297
2298 /* This is a valid result, in a sense */
2299 result->found_a_valid = TRUE;
2300}
2301
2302/************************************************************************/
2305#ifdef CM_DEBUG
2306static void snprint_production(char *buffer, size_t bufsz,
2307 const int production[])
2308{
2309 fc_snprintf(buffer, bufsz, "[%d %d %d %d %d %d]",
2313}
2314
2315/************************************************************************/
2318static void real_print_tile_type(enum log_level level, const char *file,
2319 const char *function, int line,
2320 const struct cm_tile_type *ptype,
2321 const char *prefix)
2322{
2323 char prodstr[256];
2324
2325 snprint_production(prodstr, sizeof(prodstr), ptype->production);
2326 do_log(file, function, line, FALSE, level,
2327 "%s%s fitness %g depth %d, idx %d; %d tiles", prefix,
2328 prodstr, ptype->estimated_fitness, ptype->lattice_depth,
2329 ptype->lattice_index, tile_type_num_tiles(ptype));
2330}
2331
2332/************************************************************************/
2335static void real_print_lattice(enum log_level level, const char *file,
2336 const char *function, int line,
2337 const struct tile_type_vector *lattice)
2338{
2339 do_log(file, function, line, FALSE, level,
2340 "lattice has %u terrain types", (unsigned) lattice->size);
2341 tile_type_vector_iterate(lattice, ptype) {
2342 real_print_tile_type(level, file, function, line, ptype, " ");
2344}
2345
2346/************************************************************************/
2349static void real_print_partial_solution(enum log_level level,
2350 const char *file,
2351 const char *function, int line,
2352 const struct partial_solution *soln,
2353 const struct cm_state *state)
2354{
2355 int i;
2356 int last_type = 0;
2357 char buf[256];
2358
2359 if (soln->idle != 0) {
2360 do_log(file, function, line, FALSE, level,
2361 "** partial solution has %d idle workers", soln->idle);
2362 } else {
2363 do_log(file, function, line, FALSE, level, "** completed solution:");
2364 }
2365
2366 snprint_production(buf, sizeof(buf), soln->production);
2367 do_log(file, function, line, FALSE, level, "production: %s", buf);
2368
2369 do_log(file, function, line, FALSE, level, "tiles used:");
2370 for (i = 0; i < num_types(state); i++) {
2371 if (soln->worker_counts[i] != 0) {
2372 fc_snprintf(buf, sizeof(buf), " %d tiles of type ",
2373 soln->worker_counts[i]);
2374 real_print_tile_type(level, file, function, line,
2375 tile_type_get(state, i), buf);
2376 }
2377 }
2378
2379 for (i = 0; i < num_types(state); i++) {
2380 if (soln->worker_counts[i] != 0) {
2381 last_type = i;
2382 }
2383 }
2384
2385 do_log(file, function, line, FALSE, level, "tiles available:");
2386 for (i = last_type; i < num_types(state); i++) {
2387 const struct cm_tile_type *ptype = tile_type_get(state, i);
2388
2389 if (soln->prereqs_filled[i] == tile_type_num_prereqs(ptype)
2390 && soln->worker_counts[i] < tile_type_num_tiles(ptype)) {
2391 real_print_tile_type(level, file, function, line,
2392 tile_type_get(state, i), " ");
2393 }
2394 }
2395}
2396
2397#endif /* CM_DEBUG */
2398
2399#ifdef GATHER_TIME_STATS
2400/************************************************************************/
2403static void print_performance(struct one_perf *counts)
2404{
2405 double s, ms;
2406 double q;
2407 int queries, applies;
2408
2409 s = timer_read_seconds(counts->wall_timer);
2410 ms = 1000.0 * s;
2411
2412 queries = counts->query_count;
2413 q = queries;
2414
2415 applies = counts->apply_count;
2416
2418 "CM-%s: overall=%fs queries=%d %fms / query, %d applies",
2419 counts->name, s, queries, ms / q, applies);
2420}
2421#endif /* GATHER_TIME_STATS */
2422
2423/************************************************************************/
2426void cm_print_city(const struct city *pcity)
2427{
2428 struct tile *pcenter = city_tile(pcity);
2429 const struct civ_map *nmap = &(wld.map);
2430
2431 log_test("cm_print_city(city %d=\"%s\")", pcity->id, city_name_get(pcity));
2432 log_test(" size=%d, specialists=%s",
2434
2435 log_test(" workers at:");
2436 city_tile_iterate_index(nmap, city_map_radius_sq_get(pcity), pcenter, ptile,
2437 cindex) {
2438 struct city *pwork = tile_worked(ptile);
2439
2440 if (NULL != pwork && pwork == pcity) {
2441 int cx, cy;
2442
2443 city_tile_index_to_xy(&cx, &cy, cindex,
2444 city_map_radius_sq_get(pcity));
2445 log_test(" {%2d,%2d} (%4d,%4d)", cx, cy, TILE_XY(ptile));
2446 }
2448
2449 log_test(" food = %3d (%+3d)",
2450 pcity->prod[O_FOOD], pcity->surplus[O_FOOD]);
2451 log_test(" shield = %3d (%+3d)",
2452 pcity->prod[O_SHIELD], pcity->surplus[O_SHIELD]);
2453 log_test(" trade = %3d", pcity->surplus[O_TRADE]);
2454
2455 log_test(" gold = %3d (%+3d)",
2456 pcity->prod[O_GOLD], pcity->surplus[O_GOLD]);
2457 log_test(" luxury = %3d", pcity->prod[O_LUXURY]);
2458 log_test(" science = %3d", pcity->prod[O_SCIENCE]);
2459}
2460
2461/************************************************************************/
2464void cm_print_result(const struct cm_result *result)
2465{
2466 int *city_map_data = fc_calloc(city_map_tiles(result->city_radius_sq),
2467 sizeof(*city_map_data));
2468
2469 log_test("cm_print_result(result=%p)", (void *) result);
2470 log_test(" found_a_valid=%d disorder=%d happy=%d",
2471 result->found_a_valid, result->disorder, result->happy);
2472
2473 city_map_iterate(result->city_radius_sq, cindex, x, y) {
2474 if (is_free_worked_index(cindex)) {
2475 city_map_data[cindex] = 2;
2476 } else if (result->worker_positions[cindex]) {
2477 city_map_data[cindex] = 1;
2478 } else {
2479 city_map_data[cindex] = 0;
2480 }
2482 log_test("workers map (2: free worked; 1: worker; 0: not used):");
2483 citylog_map_data(LOG_TEST, result->city_radius_sq, city_map_data);
2484 FC_FREE(city_map_data);
2485
2486 log_test(" (workers/specialists) %d/%s", cm_result_workers(result),
2488
2490 log_test(" %10s surplus=%d", get_output_name(i), result->surplus[i]);
2492}
bool base_city_celebrating(const struct city *pcity)
Definition city.c:1606
bool is_free_worked(const struct city *pcity, const struct tile *ptile)
Definition city.c:3496
int city_granary_size(int city_size)
Definition city.c:2101
struct tile * city_map_to_tile(const struct civ_map *nmap, const struct tile *city_center, int city_radius_sq, int city_map_x, int city_map_y)
Definition city.c:300
const char * city_name_get(const struct city *pcity)
Definition city.c:1111
bool city_can_use_specialist(const struct city *pcity, Specialist_type_id type)
Definition city.c:1039
void city_refresh_from_main_map(struct city *pcity, bool *workers_map)
Definition city.c:3065
bool city_tile_index_to_xy(int *city_map_x, int *city_map_y, int city_tile_index, int city_radius_sq)
Definition city.c:96
citizens player_content_citizens(const struct player *pplayer)
Definition city.c:2155
void citylog_map_data(enum log_level level, int radius_sq, int *map_data)
Definition city.c:406
bool city_unhappy(const struct city *pcity)
Definition city.c:1595
void set_city_production(struct city *pcity)
Definition city.c:2852
const char * get_output_name(Output_type_id output)
Definition city.c:624
bool city_happy(const struct city *pcity)
Definition city.c:1583
int city_map_radius_sq_get(const struct city *pcity)
Definition city.c:132
citizens city_specialists(const struct city *pcity)
Definition city.c:3226
static int cmp(int v1, int v2)
Definition city.c:320
int city_tile_output(const struct city *pcity, const struct tile *ptile, bool is_celebrating, Output_type_id otype)
Definition city.c:1255
int city_map_tiles(int city_radius_sq)
Definition city.c:166
bool city_can_work_tile(const struct city *pcity, const struct tile *ptile)
Definition city.c:1425
#define city_tile(_pcity_)
Definition city.h:544
#define city_tile_iterate_index(_nmap, _radius_sq, _city_tile, _tile, _index)
Definition city.h:193
#define CITY_MAP_MAX_RADIUS_SQ
Definition city.h:78
static citizens city_size_get(const struct city *pcity)
Definition city.h:549
#define city_tile_iterate_index_end
Definition city.h:201
#define output_type_iterate(output)
Definition city.h:812
#define city_owner(_pcity_)
Definition city.h:543
#define city_tile_iterate(_nmap, _radius_sq, _city_tile, _tile)
Definition city.h:222
#define city_map_iterate_end
Definition city.h:169
#define city_map_iterate(_radius_sq, _index, _x, _y)
Definition city.h:165
#define city_tile_iterate_end
Definition city.h:230
#define is_free_worked_index(city_tile_index)
Definition city.h:847
#define city_map_tiles_from_city(_pcity)
Definition city.h:119
#define output_type_iterate_end
Definition city.h:818
void cm_init_citymap(void)
Definition cm.c:312
static void convert_solution_to_result(struct cm_state *state, const struct partial_solution *soln, struct cm_result *result)
Definition cm.c:821
static void sort_lattice_by_fitness(const struct cm_state *state, struct tile_type_vector *lattice)
Definition cm.c:1209
static double estimate_fitness(const struct cm_state *state, const int production[])
Definition cm.c:1764
static void get_tax_rates(const struct player *pplayer, int rates[])
Definition cm.c:1734
static int specialists_in_solution(const struct cm_state *state, const struct partial_solution *soln)
Definition cm.c:1558
static void begin_search(struct cm_state *state, const struct cm_parameter *parameter, bool negative_ok)
Definition cm.c:1980
static int min_food_surplus_for_fastest_growth(struct cm_state *state)
Definition cm.c:1928
static int next_choice(struct cm_state *state, int oldchoice, bool negative_ok)
Definition cm.c:1406
static void tile_type_destroy(struct cm_tile_type *type)
Definition cm.c:410
#define LOG_TIME_STATS
Definition cm.c:95
static struct cm_fitness compute_fitness(const int surplus[], bool disorder, bool happy, const struct cm_parameter *parameter)
Definition cm.c:610
static void init_partial_solution(struct partial_solution *into, int ntypes, int idle, bool negative_ok)
Definition cm.c:649
static void complete_solution(struct partial_solution *soln, const struct cm_state *state, const struct tile_type_vector *lattice)
Definition cm.c:1506
static const struct cm_tile * tile_get(const struct cm_tile_type *ptype, int j)
Definition cm.c:568
static struct cm_fitness worst_fitness(void)
Definition cm.c:597
static bool take_child_choice(struct cm_state *state, bool negative_ok)
Definition cm.c:1472
static void compute_tile_production(const struct city *pcity, const struct tile *ptile, struct cm_tile_type *out)
Definition cm.c:956
void cm_clear_cache(struct city *pcity)
Definition cm.c:320
static const struct cm_tile_type * tile_type_get(const struct cm_state *state, int type)
Definition cm.c:552
#define LOG_LATTICE
Definition cm.c:97
static Output_type_id compare_key
Definition cm.c:909
static struct cm_fitness evaluate_solution(struct cm_state *state, const struct partial_solution *soln)
Definition cm.c:782
static int tile_type_vector_find_equivalent(const struct tile_type_vector *vec, const struct cm_tile_type *ptype)
Definition cm.c:507
void cm_copy_parameter(struct cm_parameter *dest, const struct cm_parameter *const src)
Definition cm.c:2169
static bool choice_stack_empty(struct cm_state *state)
Definition cm.c:1277
static void tile_type_vector_free_all(struct tile_type_vector *vec)
Definition cm.c:423
static struct cm_state * cm_state_init(struct city *pcity, bool negative_ok)
Definition cm.c:1856
static struct cm_tile_type * tile_type_dup(const struct cm_tile_type *oldtype)
Definition cm.c:395
static bool prereqs_filled(const struct partial_solution *soln, int type, const struct cm_state *state)
Definition cm.c:1388
static void clean_lattice(struct tile_type_vector *lattice, const struct city *pcity)
Definition cm.c:1154
void cm_init_parameter(struct cm_parameter *dest)
Definition cm.c:2178
static int tile_type_num_prereqs(const struct cm_tile_type *ptype)
Definition cm.c:542
static void copy_partial_solution(struct partial_solution *dst, const struct partial_solution *src, const struct cm_state *state)
Definition cm.c:678
static void cm_state_free(struct cm_state *state)
Definition cm.c:2029
static int compare_tile_type_by_fitness(const void *va, const void *vb)
Definition cm.c:886
struct cm_result * cm_result_new(struct city *pcity)
Definition cm.c:343
static void destroy_partial_solution(struct partial_solution *into)
Definition cm.c:668
int cm_result_specialists(const struct cm_result *result)
Definition cm.c:2233
#define print_partial_solution(loglevel, soln, state)
Definition cm.c:277
void cm_result_from_main_map(struct cm_result *result, const struct city *pcity)
Definition cm.c:2256
#define print_lattice(loglevel, lattice)
Definition cm.c:276
static bool tile_type_equal(const struct cm_tile_type *a, const struct cm_tile_type *b)
Definition cm.c:439
static void tile_type_init(struct cm_tile_type *type)
Definition cm.c:383
static void cm_result_copy(struct cm_result *result, const struct city *pcity, bool *workers_map)
Definition cm.c:2267
#define tile_type_vector_iterate(vector, var)
Definition cm.c:149
#define LOG_REACHED_LEAF
Definition cm.c:98
static void add_worker(struct partial_solution *soln, int itype, const struct cm_state *state)
Definition cm.c:1359
static bool choice_is_promising(struct cm_state *state, int newchoice, bool negative_ok)
Definition cm.c:1655
bool cm_are_parameter_equal(const struct cm_parameter *const p1, const struct cm_parameter *const p2)
Definition cm.c:2136
static double compare_key_trade_bonus
Definition cm.c:910
static void init_tile_lattice(struct city *pcity, struct tile_type_vector *lattice)
Definition cm.c:1235
static bool take_sibling_choice(struct cm_state *state, bool negative_ok)
Definition cm.c:1444
static void cm_find_best_solution(struct cm_state *state, const struct cm_parameter *const parameter, struct cm_result *result, bool negative_ok)
Definition cm.c:2046
static void apply_solution(struct cm_state *state, const struct partial_solution *soln)
Definition cm.c:698
static void init_min_production(struct cm_state *state)
Definition cm.c:1719
void cm_result_destroy(struct cm_result *result)
Definition cm.c:366
void cm_print_result(const struct cm_result *result)
Definition cm.c:2464
static void end_search(struct cm_state *state)
Definition cm.c:2013
static int compare_tile_type_by_stat(const void *va, const void *vb)
Definition cm.c:918
static int tile_type_num_tiles(const struct cm_tile_type *type)
Definition cm.c:527
static bool fitness_better(struct cm_fitness a, struct cm_fitness b)
Definition cm.c:585
void cm_query_result(struct city *pcity, const struct cm_parameter *param, struct cm_result *result, bool negative_ok)
Definition cm.c:2118
static bool bb_next(struct cm_state *state, bool negative_ok)
Definition cm.c:1819
static void top_sort_lattice(struct tile_type_vector *lattice)
Definition cm.c:1055
static void get_city_surplus(const struct city *pcity, int surplus[], bool *disorder, bool *happy)
Definition cm.c:767
#define LOG_BETTER_LEAF
Definition cm.c:99
static void compute_max_stats_heuristic(const struct cm_state *state, const struct partial_solution *soln, int production[], int check_choice, bool negative_ok)
Definition cm.c:1583
static int last_choice(struct cm_state *state)
Definition cm.c:1285
#define print_tile_type(loglevel, ptype, prefix)
Definition cm.c:275
static int compare_tile_type_by_lattice_order(const struct cm_tile_type *a, const struct cm_tile_type *b)
Definition cm.c:856
static void remove_worker(struct partial_solution *soln, int itype, const struct cm_state *state)
Definition cm.c:1368
#define CPUHOG_CM_MAX_LOOP
Definition cm.c:82
void cm_init(void)
Definition cm.c:293
static int tile_type_better(const struct cm_tile_type *a, const struct cm_tile_type *b)
Definition cm.c:463
static void init_specialist_lattice_nodes(struct tile_type_vector *lattice, const struct city *pcity)
Definition cm.c:1026
static void add_workers(struct partial_solution *soln, int itype, int number, const struct cm_state *state)
Definition cm.c:1308
int cm_result_citizens(const struct cm_result *result)
Definition cm.c:2247
static void tile_type_lattice_add(struct tile_type_vector *lattice, const struct cm_tile_type *newtype, int tindex)
Definition cm.c:974
void cm_init_emergency_parameter(struct cm_parameter *dest)
Definition cm.c:2196
static void pop_choice(struct cm_state *state)
Definition cm.c:1378
#define LOG_PRUNE_BRANCH
Definition cm.c:100
static int num_types(const struct cm_state *state)
Definition cm.c:1297
#define tile_type_vector_iterate_end
Definition cm.c:154
#define LOG_CM_STATE
Definition cm.c:96
#define CM_MAX_LOOP
Definition cm.c:80
void cm_print_city(const struct city *pcity)
Definition cm.c:2426
int cm_result_workers(const struct cm_result *result)
Definition cm.c:2213
void cm_free(void)
Definition cm.c:328
struct timer * wall_timer
Definition cma_core.c:90
static void base(QVariant data1, QVariant data2)
Definition dialogs.cpp:2839
unsigned char citizens
Definition fc_types.h:358
int Specialist_type_id
Definition fc_types.h:345
@ O_SHIELD
Definition fc_types.h:91
@ O_FOOD
Definition fc_types.h:91
@ O_TRADE
Definition fc_types.h:91
@ O_SCIENCE
Definition fc_types.h:91
@ O_LUXURY
Definition fc_types.h:91
@ O_GOLD
Definition fc_types.h:91
@ O_LAST
Definition fc_types.h:91
enum output_type_id Output_type_id
Definition fc_types.h:348
struct civ_game game
Definition game.c:57
struct world wld
Definition game.c:58
struct government * government_of_player(const struct player *pplayer)
Definition government.c:113
GType type
Definition repodlgs.c:1312
static const int bufsz
Definition helpdlg.c:70
const char * name
Definition inputfile.c:127
void do_log(const char *file, const char *function, int line, bool print_from_where, enum log_level level, const char *message,...)
Definition log.c:514
#define fc_assert_ret(condition)
Definition log.h:191
#define log_warn(message,...)
Definition log.h:105
#define log_test
Definition log.h:136
#define fc_assert(condition)
Definition log.h:176
#define LOG_TEST
Definition log.h:139
#define fc_assert_ret_val(condition, val)
Definition log.h:194
#define log_base(level, message,...)
Definition log.h:94
log_level
Definition log.h:28
@ LOG_DEBUG
Definition log.h:34
#define fc_calloc(n, esz)
Definition mem.h:38
#define FC_FREE(ptr)
Definition mem.h:41
#define fc_malloc(sz)
Definition mem.h:34
static bool player_is_cpuhog(const struct player *pplayer)
Definition player.h:573
struct setting_list * level[OLEVELS_NUM]
Definition settings.c:183
#define FC_INFINITY
Definition shared.h:36
#define MAX(x, y)
Definition shared.h:54
const char * specialists_string(const citizens *specialist_list)
Definition specialist.c:199
int get_specialist_output(const struct city *pcity, Specialist_type_id sp, Output_type_id otype)
Definition specialist.c:217
#define specialist_type_iterate_end
Definition specialist.h:79
#define specialist_type_iterate(sp)
Definition specialist.h:73
Definition city.h:309
int surplus[O_LAST]
Definition city.h:343
int food_stock
Definition city.h:354
int id
Definition city.h:315
int city_radius_sq
Definition city.h:362
int citizen_base[O_LAST]
Definition city.h:347
int usage[O_LAST]
Definition city.h:348
struct universal production
Definition city.h:382
bool happy
Definition city.h:445
int bonus[O_LAST]
Definition city.h:351
citizens specialists[SP_MAX]
Definition city.h:324
struct tile * tile
Definition city.h:311
int prod[O_LAST]
Definition city.h:346
struct packet_game_info info
Definition game.h:89
struct government * government_during_revolution
Definition game.h:94
int weighted
Definition cm.c:119
bool sufficient
Definition cm.c:120
bool allow_disorder
Definition cm.h:44
int factor[O_LAST]
Definition cm.h:47
bool max_growth
Definition cm.h:42
bool allow_specialists
Definition cm.h:45
bool require_happy
Definition cm.h:43
int minimal_surplus[O_LAST]
Definition cm.h:41
int happy_factor
Definition cm.h:48
Definition cm.h:52
bool found_a_valid
Definition cm.h:54
bool disorder
Definition cm.h:54
bool aborted
Definition cm.h:53
int surplus[O_LAST]
Definition cm.h:56
bool happy
Definition cm.h:54
bool * worker_positions
Definition cm.h:59
int city_radius_sq
Definition cm.h:58
citizens specialists[SP_MAX]
Definition cm.h:60
Definition cm.c:200
int size
Definition cm.c:231
struct partial_solution best
Definition cm.c:210
struct cm_parameter parameter
Definition cm.c:202
int min_production[O_LAST]
Definition cm.c:217
struct tile_type_vector lattice
Definition cm.c:206
struct partial_solution current
Definition cm.c:223
struct tile_type_vector lattice_by_prod[O_LAST]
Definition cm.c:207
struct cm_fitness best_value
Definition cm.c:211
bool * workers_map
Definition cm.c:234
int min_luxury
Definition cm.c:220
struct city * pcity
Definition cm.c:203
int * stack
Definition cm.c:230
struct cm_state::@15 choice
int production[O_LAST]
Definition cm.c:169
Specialist_type_id spec
Definition cm.c:172
struct tile_type_vector better_types
Definition cm.c:174
struct tile_vector tiles
Definition cm.c:173
bool is_specialist
Definition cm.c:171
int lattice_depth
Definition cm.c:177
int lattice_index
Definition cm.c:176
struct tile_type_vector worse_types
Definition cm.c:175
double estimated_fitness
Definition cm.c:170
Definition cm.c:135
const struct cm_tile_type * type
Definition cm.c:136
int index
Definition cm.c:137
int production[O_LAST]
Definition cm.c:191
int * worker_counts
Definition cm.c:188
int * prereqs_filled
Definition cm.c:189
struct player_economic economic
Definition player.h:284
Definition tile.h:49
int index
Definition tile.h:50
Definition timing.c:81
struct civ_map map
int fc_snprintf(char *str, size_t n, const char *format,...)
Definition support.c:969
#define TRUE
Definition support.h:46
#define FALSE
Definition support.h:47
#define bool
Definition support.h:61
#define tile_worked(_tile)
Definition tile.h:113
#define TILE_XY(ptile)
Definition tile.h:42
struct timer * timer_new(enum timer_timetype type, enum timer_use use)
Definition timing.c:157
void timer_destroy(struct timer *t)
Definition timing.c:191
void timer_start(struct timer *t)
Definition timing.c:224
void timer_stop(struct timer *t)
Definition timing.c:268
double timer_read_seconds(struct timer *t)
Definition timing.c:344
@ TIMER_ACTIVE
Definition timing.h:45
@ TIMER_USER
Definition timing.h:41