]> mj.ucw.cz Git - leo.git/blob - labeller.c
Labelling: Degree/radian conversions have functions
[leo.git] / labeller.c
1 #include <ucw/lib.h>
2 #include <ucw/conf.h>
3 #include <ucw/gary.h>
4 #include <ucw/mempool.h>
5 #include <ucw/eltpool.h>
6
7 #include "leo.h"
8 #include "sym.h"
9 #include "map.h"
10 #include "labeller.h"
11
12 #define HASH_NODE struct graph_node
13 #define HASH_PREFIX(x) hash_##x
14 #define HASH_KEY_ATOMIC id
15 #define HASH_WANT_FIND
16 #define HASH_WANT_NEW
17 #define HASH_WANT_CLEANUP
18 #include <ucw/hashtable.h>
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <math.h>
23 #include <fcntl.h>
24 #include <limits.h>
25
26 #define BLOCK_SIZE 4096
27
28 #define DEBUG(dbg_sec, dbg_lvl, msg, ...) if (dbg_sec >= dbg_lvl) printf(msg, ##__VA_ARGS__)
29
30 static struct request_point *requests_point;
31 static struct request_line *requests_line;
32 static struct request_area *requests_area;
33
34 static struct graph_edge **bfs_queue;
35 static struct longline *longlines;
36 static struct buffer_line *buffer_line;
37 static struct buffer_linelabel *buffer_linelabel;
38
39 struct eltpool *ep_individuals;
40
41 struct individual **population1;
42 struct individual **population2;
43
44 int dbg_segments = VERBOSITY_NONE;
45 int dbg_plan = VERBOSITY_NONE;
46 int dbg_requests = VERBOSITY_NONE;
47 int dbg_graph = VERBOSITY_NONE;
48 int dbg_bfs = VERBOSITY_NONE;
49 int dbg_map_parts = VERBOSITY_NONE;
50 int dbg_movement = VERBOSITY_NONE;
51 int dbg_init = VERBOSITY_NONE;
52 int dbg_overlaps = VERBOSITY_GENERAL;
53 int dbg_rank = VERBOSITY_NONE;
54 int dbg_evolution = VERBOSITY_POPULATION;
55 int dbg_mutation = VERBOSITY_NONE;
56 int dbg_breeding = VERBOSITY_NONE;
57
58 int page_width_int;
59 int page_height_int;
60
61 int num_nodes;
62 int num_edges = 0;
63 int dbg_num_hits = 0;
64
65 int breed_pop_size;
66 int breed_rbest_size;
67
68 int mutate_pop_size;
69 int mutate_rbest_size;
70
71 int elite_pop_size;
72
73
74 int old_best = INT_MAX;
75 int iteration = 0;
76 int pop2_ind;
77
78 // In milimeters
79 int move_min = 0;
80 int move_max = 5;
81
82 int num_requests = 0;
83 int num_placements = 0;
84
85 // In milimeters
86 int conf_map_part_width = 5;
87 int conf_map_part_height = 5;
88
89 uns num_map_parts_row;
90 uns num_map_parts_col;
91 uns num_map_parts;
92
93 int conf_pop_size = 200, conf_fit_size = 1, conf_term_cond = TERM_COND_ITERATIONS;
94
95 double conf_penalty_bound = 100, conf_stagnation_bound = 10;
96 int conf_iteration_limit = 200;
97
98 double conf_breed_pop_size = 0.45, conf_breed_rbest = 1,
99        conf_mutate_children, conf_mutate_children_prob = 0.6,
100        conf_mutate_pop_size = 0.45, conf_mutate_rbest = 1,
101        conf_mutate_move_bound = 0.1, conf_mutate_regen_bound = 0.05, conf_mutate_chvar_bound = 0.1,
102        conf_elite_pop_size = 0.1;
103
104 double conf_max_section_length = 80, conf_max_section_overlay = 10;
105
106 static struct cf_section evolution_cf = {
107   CF_ITEMS {
108     CF_INT("PopSize", &conf_pop_size),
109     CF_INT("FitSize", &conf_fit_size),
110     CF_INT("TermCond", &conf_term_cond),
111     CF_DOUBLE("PenaltyBound", &conf_penalty_bound),
112     CF_DOUBLE("StagnationBound", &conf_stagnation_bound),
113     CF_INT("IterationLimit", &conf_iteration_limit),
114     CF_DOUBLE("BreedPopSize", &conf_breed_pop_size),
115     CF_DOUBLE("BreedNumBest", &conf_breed_rbest),
116     CF_DOUBLE("MutateChild", &conf_mutate_children_prob),
117     CF_DOUBLE("MutatePopSize", &conf_mutate_pop_size),
118     CF_DOUBLE("MutateNumBest", &conf_mutate_rbest),
119     CF_DOUBLE("MutateMoveBound", &conf_mutate_move_bound),
120     CF_DOUBLE("MutateRegenBound", &conf_mutate_regen_bound),
121     CF_DOUBLE("MutateChvarBound", &conf_mutate_chvar_bound),
122     CF_DOUBLE("ElitePopSize", &conf_elite_pop_size),
123     CF_DOUBLE("MaxSectionLenght", &conf_max_section_length),
124     CF_DOUBLE("MaxSectionOverlay", &conf_max_section_overlay),
125     CF_END
126   }
127 };
128
129 double convert_to_deg(double rotate_rad);
130 double convert_to_rad(double rotate_deg);
131
132 void compute_sizes(void);
133
134 void make_population(void);
135 bool shall_terminate(void);
136 void breed(void);
137 void mutate(void);
138 void elite(void);
139 void rank_population(void);
140 void plan_individual(struct individual *individual);
141
142 int overlaps(struct placement *p1, struct placement *p2);
143 int get_overlap(struct placement *p, int **planed_ptr, int iteration);
144 int individual_overlap(struct individual *individual);
145
146 double get_distance(struct placement *p);
147 double individual_distances(struct individual *individual);
148
149 double get_omittment(struct placement *p);
150 double individual_omittment(struct individual *individual);
151
152 void labeller_add_linelabel(struct symbol *sym, struct osm_object *o, z_index_t zindex);
153 void labeller_add_arealabel(struct symbol *sym, struct osm_object *o, z_index_t zindex);
154
155 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2);
156 void perform_mutation(struct individual *individual);
157 void init_placement(struct placement *p, struct individual *individual, struct request *r);
158 void init_individual(struct individual *i);
159 void copy_individual(struct individual *src, struct individual *dest);
160 int cmp_individual(const void *a, const void *b);
161
162 void clear_individual(struct individual *individual);
163 void clear_population(struct individual **pop);
164
165 void make_bitmap(struct variant *v, struct symbol *sym);
166 void make_bitmap_icon(struct variant *v, struct sym_icon *si);
167 void make_bitmap_point(struct variant *v, struct sym_point *sp);
168 void make_bitmap_label(struct variant *v, struct sym_text *text);
169
170 double gen_movement(void);
171 double gen_movement_uniform(void);
172 void move_symbol(struct placement *p);
173 void move_symbol_point(struct placement *p);
174 void move_symbol_segment(struct placement *p);
175 void hide_segment_labels(struct individual *individual);
176
177 void gen_coords(struct placement *p);
178 void gen_coords_point(struct placement *p);
179 void gen_coords_segment(struct placement *p);
180 void gen_coords_area(struct placement *p);
181
182 struct map_part **get_map_parts(struct placement *p);
183 void update_map_parts(struct placement *p);
184 void update_map_parts_delete(struct placement *p);
185 void update_map_parts_create(struct placement *p);
186 struct placement **get_closure(struct placement *placement);
187 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child, bool **processed_ptr);
188 struct placement **get_overlapping(struct placement *p);
189 struct placement **filter(struct placement **list, bool **pred_ptr);
190
191
192 void make_graph(void);
193 void label_graph(void);
194 void bfs_wrapper(void);
195 void bfs(uns longline);
196 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir);
197 void make_segments(void);
198
199 void cut_edge(struct graph_edge *e, double dist);
200 struct request_line *make_new_line(void);
201 struct request_section *make_new_section(struct request_line *rl);
202 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym);
203
204 void dump_bitmaps(struct individual *individual);
205 void dump_graph(void);
206 void dump_longlines(void);
207 void dump_linelabel_requests(void);
208 void dump_individual(struct individual *individual);
209 void dump_label(struct symbol *sym);
210 void dump_penalties(struct individual **population);
211 void dump_placements(struct individual *individual);
212 void dump_placement_links(struct placement *p);
213 void dump_part_links(struct map_part *part);
214 void dump_links(struct individual *individual);
215
216 int randint(int min, int max);
217 int flip(int a, int b);
218 double randdouble(void);
219
220 int max2(int a, int b);
221 int min2(int a, int b);
222 int max4(int a, int b, int c, int d);
223 int min4(int a, int b, int c, int d);
224
225 struct placement dummy_placement;
226
227 int max2(int a, int b)
228 {
229   return (a > b ? a : b);
230 }
231
232 int min2(int a, int b)
233 {
234   return (a < b ? a : b);
235 }
236
237 int max4(int a, int b, int c, int d)
238 {
239   return max2(max2(a, b), max2(c, d));
240 }
241
242 int min4(int a, int b, int c, int d)
243 {
244   return min2(min2(a, b), min2(c, d));
245 }
246
247 double convert_to_deg(double rotate_rad)
248 {
249   return rotate_rad * (-180 / M_PI);
250 }
251
252 double convert_to_rad(double rotate_deg)
253 {
254   return rotate_deg / (-180 / M_PI);
255 }
256
257 void dump_label(struct symbol *sym)
258 {
259   switch (sym->type)
260   {
261     case SYMBOLIZER_TEXT: ;
262       struct sym_text *st = (struct sym_text *) sym;
263       printf("%s\n", osm_val_decode(st->text));
264     default:
265       // FIXME
266       ;
267   }
268 }
269
270 void labeller_conf(void)
271 {
272   cf_declare_section("Evolution", &evolution_cf, 0);
273 }
274
275 void labeller_init(void)
276 {
277   GARY_INIT(requests_point, 0);
278   GARY_INIT(requests_line, 0);
279   GARY_INIT(requests_area, 0);
280   GARY_INIT(buffer_line, 0);
281   GARY_INIT(buffer_linelabel, 0);
282   ep_individuals = ep_new(sizeof(struct individual), 1);
283
284   compute_sizes();
285 }
286
287 void make_bitmap(struct variant *v, struct symbol *sym)
288 {
289   v->offset_x = v->offset_y = 0;
290
291   switch (sym->type)
292   {
293     case SYMBOLIZER_POINT:
294       make_bitmap_point(v, (struct sym_point *) sym);
295       break;
296     case SYMBOLIZER_ICON:
297       make_bitmap_icon(v, (struct sym_icon *) sym);
298       break;
299     case SYMBOLIZER_TEXT:
300       make_bitmap_label(v, (struct sym_text *) sym);
301       break;
302     default:
303       ASSERT(sym->type != SYMBOLIZER_INVALID);
304   }
305 }
306
307 void make_bitmap_icon(struct variant *v, struct sym_icon *si)
308 {
309   v->width = si->sir.width + 1;
310   v->height = si->sir.height + 1;
311   v->bitmap = xmalloc(v->width * v->height * sizeof(bool));
312   for (int i=0; i<v->width*v->height; i++) v->bitmap[i] = 1;
313 }
314
315 void make_bitmap_point(struct variant *v, struct sym_point *sp)
316 {
317   v->width = v->height = sp->size + 1;
318   v->bitmap = xmalloc(v->width * v->height * sizeof(bool));
319   // FIXME: Okay, memset would be much nicer here
320   for (int i=0; i<sp->size*sp->size; i++) v->bitmap[i] = 1;
321 }
322
323 void make_bitmap_label(struct variant *v, struct sym_text *text)
324 {
325   int tw = ceil(text->tw);
326   int th = ceil(text->th);
327
328   double rotate_rad = convert_to_rad(text->rotate);
329
330   // Initially, ll = [0; 0], lr = [tw, 0], ul = [0, th], ur = [tw, th]
331   // They could be declared before but should not be initialized in code
332   // as reassigning x-coordinate affects computation of y-cordinate
333   int llx = 0;
334   int lly = 0;
335
336   int lrx = tw * cos(rotate_rad);
337   int lry = tw * sin(rotate_rad);
338
339   int ulx = th * sin(rotate_rad);
340   int uly = th * cos(rotate_rad);
341
342   int urx = tw * cos(rotate_rad) + th * sin(rotate_rad);
343   int ury = tw * sin(rotate_rad) + th * cos(rotate_rad);
344
345   int min_x = min4(llx, lrx, ulx, urx);
346   int min_y = min4(lly, lry, uly, ury);
347   int max_x = max4(llx, lrx, ulx, urx);
348   int max_y = max4(lly, lry, uly, ury);
349
350   v->width = max_x - min_x + 1;
351   v->height = max_y - min_y + 1;
352   v->bitmap = xmalloc(v->width * v->height * sizeof(bool));
353   memset(v->bitmap, 0, v->width * v->height * sizeof(bool));
354
355   for (int i=0; i<th; i++)
356   {
357     for (int j=0; j<tw; j++)
358     {
359       int nx = j*cos(rotate_rad) + i*sin(rotate_rad);
360       int ny = j*sin(rotate_rad) + i*cos(rotate_rad);
361       v->bitmap[(ny-min_y)*v->width + (nx-min_x)] = 1;
362     }
363   }
364 }
365
366 void labeller_add_point(struct symbol *sym, struct osm_object *object, z_index_t zindex)
367 {
368   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Adding point\n");
369   if (object->type != OSM_TYPE_NODE)
370   {
371     printf("Warning: Point label requested on non-point object\n");
372     return;
373   }
374
375   struct request_point *r = GARY_PUSH(requests_point);
376
377   r->request.type = REQUEST_POINT;
378   r->request.ind = num_requests++;
379
380   r->sym = sym;
381   r->zindex = zindex;
382
383   r->offset_x = 0;
384   r->offset_y = 0;
385
386   r->num_variants = 1;
387   GARY_INIT(r->request.variants, 0);
388
389   struct variant *v = GARY_PUSH(r->request.variants);
390
391   struct osm_node *n = (struct osm_node *) object; // FIXME: Compiler warning
392   r->x = n->x;
393   r->y = n->y;
394   make_bitmap(v, sym);
395   switch (sym->type)
396   {
397     case SYMBOLIZER_ICON:
398       // FIXME: Really?
399       r->x = ((struct sym_icon *)sym)->sir.x;
400       r->y = ((struct sym_icon *)sym)->sir.y;
401       break;
402     default:
403       // FIXME
404       return;
405   }
406
407   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Inited point to [%.2f; %.2f] on %u\n", r->x, r->y, r->zindex);
408 }
409
410 void labeller_notify_line(struct symbol *sym, z_index_t zindex)
411 {
412   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Adding line on %u\n", zindex);
413   struct buffer_line *b = GARY_PUSH(buffer_line);
414   b->line = (struct sym_line *) sym;
415   b->zindex = zindex;
416 }
417
418 void labeller_add_label(struct symbol *sym, struct osm_object *o, z_index_t zindex)
419 {
420   switch (o->type)
421   {
422     case OSM_TYPE_WAY:
423       if (osm_way_cyclic_p((struct osm_way *) o))
424         labeller_add_arealabel(sym, o, zindex);
425       else
426         labeller_add_linelabel(sym, o, zindex);
427       break;
428     default:
429       ;
430   }
431 }
432
433 void labeller_add_linelabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
434 {
435   if (o->type != OSM_TYPE_WAY)
436   {
437     printf("Linelabel request on object which is not way\n");
438     return;
439   }
440
441   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Labelling way %ju on %u\n", o->id, zindex);
442   struct buffer_linelabel *ll = GARY_PUSH(buffer_linelabel);
443   ll->way = (struct osm_way *) o;
444   ll->label = sym;
445   ll->zindex = zindex;
446 }
447
448 void labeller_add_arealabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
449 {
450   DEBUG(dbg_requests, VERBOSITY_PLACEMENT, "Adding area on %u\n", zindex);
451   struct request_area *r = GARY_PUSH(requests_area);
452
453   r->request.type = REQUEST_AREA;
454   r->request.ind = num_requests++;
455
456   r->o = (struct osm_multipolygon *) o;
457   r->zindex = zindex;
458   r->label = sym;
459
460   osm_obj_center(o, &(r->cx), &(r->cy));
461
462   GARY_INIT(r->request.variants, 0);
463   struct variant *v = GARY_PUSH(r->request.variants);
464   make_bitmap(v, sym);
465 }
466
467 void make_graph(void)
468 {
469   hash_init();
470   struct mempool *mp_edges = mp_new(BLOCK_SIZE);
471
472   DEBUG(dbg_graph, VERBOSITY_GENERAL, "Extracting nodes, will iterate over %zu ways\n", GARY_SIZE(buffer_line));
473   for (uns i=0; i<GARY_SIZE(buffer_line); i++)
474   {
475     struct osm_way *way = (struct osm_way *) buffer_line[i].line->s.o;
476     struct graph_node *g_prev = NULL;
477     struct osm_node *o_prev = NULL;
478
479     CLIST_FOR_EACH(struct osm_ref *, ref, way->nodes)
480     {
481       // FIXME: Shall osm_object's type be checked here?
482       struct osm_node *o_node = (struct osm_node *) ref->o;
483
484       struct graph_node *g_node = hash_find(ref->o->id);
485       if (!g_node)
486       {
487         g_node = hash_new(ref->o->id);
488         GARY_INIT(g_node->edges, 0);
489         g_node->o = o_node;
490         g_node->id = ref->o->id;
491         g_node->num = num_nodes++;
492       }
493
494       if (! g_prev)
495       {
496         g_prev = g_node;
497         o_prev = o_node;
498         continue;
499       }
500
501       struct graph_edge *e = mp_alloc(mp_edges, sizeof(struct graph_edge));
502       e->num = num_edges++;
503       e->id = buffer_line[i].line->s.o->id;
504       e->color = buffer_line[i].line->color;
505       e->length = hypot(abs(o_prev->x - o_node->x), abs(o_prev->y - o_node->y));
506       e->visited = -1;
507       e->prev = NULL;
508       e->next = NULL;
509       e->n1 = g_prev;
510       e->n2 = g_node;
511       e->longline = (uns) -1;
512       e->line = buffer_line[i].line;
513       e->dir = DIR_UNSET;
514       e->label = NULL;
515
516       struct graph_edge **edge = GARY_PUSH(g_prev->edges);
517       *edge = e;
518       edge = GARY_PUSH(g_node->edges);
519       *edge = e;
520
521       g_prev = g_node;
522       o_prev = o_node;
523     }
524   }
525 }
526
527 void dump_graph(void)
528 {
529   HASH_FOR_ALL(hash, node)
530   {
531     printf("* Node: (%d) #%ju [%.2f; %.2f]\n", node->num, node->id, node->o->x, node->o->y);
532     for (uns i=0; i<GARY_SIZE(node->edges); i++)
533     {
534       struct graph_edge *e = node->edges[i];
535       printf("\t edge (%d) #%ju to ", e->num, e->id);
536       if (node->edges[i]->n1->id == node->id)
537         printf("(%d) #%ju [%.2f; %.2f]\n", e->n2->num, e->n2->id, e->n2->o->x, e->n2->o->y);
538       else if (node->edges[i]->n2->id == node->id)
539         printf("(%d) #%ju [%.2f; %.2f]\n", e->n1->num, e->n1->id, e->n1->o->x, e->n1->o->y);
540       else
541       {
542         // This shouldn't ever happen
543         printf("BEWARE! Edge is associated with a node it doesn't belongs to!\n");
544       }
545
546       printf("\t\t");
547
548       if ((node->edges[i]->label) && (node->edges[i]->label->type == SYMBOLIZER_TEXT)) printf(" labelled %s;", osm_val_decode(((struct sym_text *) node->edges[i]->label)->text));
549       else if ((node->edges[i]->label)) printf("Labelled\n");
550
551       printf(" colored %d;", node->edges[i]->color);
552       printf("   length %.2f", node->edges[i]->length);
553       printf("\n");
554     }
555   }
556   HASH_END_FOR;
557 }
558
559 void label_graph(void)
560 {
561   DEBUG(dbg_graph, VERBOSITY_GENERAL, "There are %zu line labels requested\n", GARY_SIZE(buffer_linelabel));
562   for (uns i=0; i<GARY_SIZE(buffer_linelabel); i++)
563   {
564     if (buffer_linelabel[i].label->type == SYMBOLIZER_TEXT)
565     DEBUG(dbg_graph, VERBOSITY_INDIVIDUAL, "Labelling nodes of way %s\n", osm_val_decode(((struct sym_text *) buffer_linelabel[i].label)->text));
566     CLIST_FOR_EACH(struct osm_ref *, ref, buffer_linelabel[i].way->nodes)
567     {
568       DEBUG(dbg_graph, VERBOSITY_PLACEMENT, "Looking for node %ju\n", ref->o->id);
569       struct graph_node *n = hash_find(ref->o->id);
570       if (n == NULL)
571       {
572         printf("BEWARE! Requested node couldn't be found.\n");
573       }
574       else
575       {
576         DEBUG(dbg_graph, VERBOSITY_ALL, "Searching among %zu edges\n", GARY_SIZE(n->edges));
577         for (uns j=0; j<GARY_SIZE(n->edges); j++)
578         {
579           if (n->edges[j]->id == buffer_linelabel[i].way->o.id)
580           {
581             DEBUG(dbg_graph, VERBOSITY_ALL, "Labelling node %ju\n", n->id);
582             n->edges[j]->label = buffer_linelabel[i].label;
583             n->edges[j]->zindex = buffer_linelabel[i].zindex;
584           }
585         }
586       }
587     }
588   }
589 }
590
591 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir)
592 {
593   DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "BFS edge called for edge %d (going %d) in direction %d\n", e->num, e->dir, dir);
594   struct graph_edge *candidate = NULL;
595
596   for (uns i=0; i<GARY_SIZE(node->edges); i++)
597   {
598     struct graph_edge *other = node->edges[i];
599     if ((other->longline != (uns) -1) && (other->longline != e->longline)) continue;
600
601     if ((uns) other->visited != e->longline) {
602     DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "Pushing new edge %d / %ju\n", other->num, other->id);
603     struct graph_edge **e_ptr = GARY_PUSH(bfs_queue);
604     *e_ptr = other;
605     other->visited = e->longline;
606     }
607
608     if (((other->n1->id == node->id) && (other->n2->id == anode->id)) ||
609         ((other->n2->id == node->id) && (other->n1->id == anode->id)))
610         continue;
611
612     if (((other->n1->id == node->id) || (other->n2->id == node->id)) &&
613         (e->label) && (other->label) &&
614         (e->label->type == SYMBOLIZER_TEXT) && (other->label->type == SYMBOLIZER_TEXT) &&
615         (((struct sym_text *) e->label)->text == ((struct sym_text *) other->label)->text))
616     {
617       if (! candidate || (other->length > candidate->length))
618       candidate = other;
619     }
620   }
621
622   if (candidate)
623   {
624     DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "New line in longline %u\n", e->longline);
625     struct graph_edge *other = candidate;
626       other->longline = e->longline;
627       other->dir = dir;
628       if (((dir == DIR_BWD) && (other->n1->id == node->id)) ||
629           ((dir == DIR_FWD) && (other->n2->id == node->id)))
630       {
631         struct graph_node *swp = other->n2;
632         other->n2 = other->n1;
633         other->n1 = swp;
634       }
635
636       switch (dir)
637       {
638         case DIR_BWD:
639           e->prev = other;
640           other->next = e;
641           longlines[other->longline].first = other;
642           break;
643         case DIR_FWD:
644           e->next = other;
645           other->prev = e;
646           break;
647         default:
648           printf("Oops\n");
649           ASSERT(0);
650       }
651   }
652 }
653
654 void bfs(uns longline)
655 {
656   DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "BFS called for longline %u\n", longline);
657   DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "%zu longlines exist\n", GARY_SIZE(longlines));
658
659   for (uns i=0; i<GARY_SIZE(bfs_queue); i++)
660   {
661     struct graph_edge *cur = bfs_queue[i];
662     DEBUG(dbg_bfs, VERBOSITY_PLACEMENT, "Exploring new edge %d; %zu remaining\n", cur->num, GARY_SIZE(bfs_queue));
663
664     cur->visited = longline;
665
666     if (cur->longline == (uns) -1)
667       continue;
668
669     if (cur->dir == DIR_UNSET)
670     {
671       cur->dir = DIR_CENTER;
672       bfs_edge(cur, cur->n1, cur->n2, DIR_BWD);
673       bfs_edge(cur, cur->n2, cur->n1, DIR_FWD);
674     }
675     else
676     {
677       switch (cur->dir)
678       {
679         case DIR_BWD:
680           bfs_edge(cur, cur->n1, cur->n2, cur->dir);
681           break;
682         case DIR_FWD:
683           bfs_edge(cur, cur->n2, cur->n1, cur->dir);
684           break;
685         default:
686           // FIXME
687           ;
688       }
689     }
690   }
691 }
692
693 void bfs_wrapper(void)
694 {
695   GARY_INIT(bfs_queue, 0);
696   GARY_INIT(longlines, 0);
697
698   HASH_FOR_ALL(hash, node)
699   {
700     for (uns i=0; i<GARY_SIZE(node->edges); i++)
701     {
702       if ((node->edges[i]->label) && (node->edges[i]->longline == (uns) -1))
703       {
704         GARY_PUSH(longlines);
705         longlines[GARY_SIZE(longlines)-1].first = node->edges[i];
706
707         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Running new BFS\n");
708         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Creating longline %zu\n", GARY_SIZE(longlines)-1);
709
710         GARY_RESIZE(bfs_queue, 0);
711         struct graph_edge **e = GARY_PUSH(bfs_queue);
712         *e = node->edges[i];
713         node->edges[i]->longline = GARY_SIZE(longlines)-1;
714         bfs(node->edges[i]->longline);
715
716         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Joined %d edges\n", dbg_num_hits); dbg_num_hits = 0;
717         DEBUG(dbg_bfs, VERBOSITY_INDIVIDUAL, "Planned %zu edges\n", GARY_SIZE(bfs_queue));
718       }
719     }
720   }
721   HASH_END_FOR;
722
723   GARY_FREE(bfs_queue);
724 }
725
726 void dump_longlines(void)
727 {
728   printf("*** Longlines dump\n");
729   for (uns i=0; i<GARY_SIZE(longlines); i++)
730   {
731     printf("Longline %u:", i);
732     struct graph_edge *e = longlines[i].first;
733     if ((e->label) && (e->label->type == SYMBOLIZER_TEXT))
734       printf(" labelled %s", osm_val_decode(((struct sym_text *) e->label)->text));
735     printf("\n");
736
737     while (e)
738     {
739       printf("\t#%ju (%d): [%.2f; %.2f] -- [%.2f; %.2f] (dir %d)\n",
740              e->id, e->num, e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->dir);
741
742       e = e->next;
743     }
744   }
745 }
746
747 struct request_line *make_new_line(void)
748 {
749   struct request_line *rl = GARY_PUSH(requests_line);
750   rl->request.ind = num_requests++;
751   rl->request.type = REQUEST_LINE;
752   GARY_INIT(rl->sections, 0);
753   GARY_INIT(rl->request.variants, 0);
754
755   return rl;
756 }
757
758 struct request_section *make_new_section(struct request_line *rl)
759 {
760   struct request_section *rls = GARY_PUSH(rl->sections);
761   rls->request.ind = num_requests++;
762   rls->request.type = REQUEST_SECTION;
763   rls->num_segments = 0;
764   GARY_INIT(rls->segments, 0);
765   GARY_INIT(rls->request.variants, 0);
766
767   return rls;
768 }
769
770 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym)
771 {
772   struct request_segment *rs = GARY_PUSH(rls->segments);
773   rls->num_segments++;
774
775   rs->request.ind = num_requests++;
776   rs->request.type = REQUEST_SEGMENT;
777
778   GARY_INIT(rs->request.variants, 0);
779   if (sym)
780   {
781     struct variant *v = GARY_PUSH(rs->request.variants);
782     make_bitmap(v, sym);
783   }
784
785   return rs;
786 }
787
788 void cut_edge(struct graph_edge *e, double dist)
789 {
790   DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Cutting [%.2f; %.2f] -- [%.2f; %.2f] to dist %.2f\n", e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, dist);
791
792   struct graph_edge *new = xmalloc(sizeof(struct graph_edge));
793   *new = *e;
794   e->next = new;
795
796   switch (e->label->type)
797   {
798     case SYMBOLIZER_TEXT:
799       new->label = xmalloc(sizeof(struct sym_text));
800       *((struct sym_text *) new->label) = *((struct sym_text *) e->label);
801       break;
802     default:
803       ;
804   }
805
806   struct osm_node *n1 = e->n1->o;
807   struct osm_node *n2 = e->n2->o;
808
809   if ((n1->x == n2->x) && (n1->y == n2->y))
810   {
811     printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", n1->x, n1->y, n2->x, n2->y);
812     DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Won't cut point\n");
813     return;
814   }
815
816   struct osm_node *n11 = xmalloc(sizeof(struct osm_node));
817   struct graph_node *gn = xmalloc(sizeof(struct graph_node));
818   gn->o = n11;
819   double vsize = hypot(n1->x - n2->x, n1->y - n2->y);
820   n11->x = n1->x + (n2->x - n1->x) / vsize * dist;
821   n11->y = n1->y + (n2->y - n1->y) / vsize * dist;
822
823   e->n2 = new->n1 = gn;
824
825   e->length = hypot(abs(n1->x - n11->x), abs(n1->y - n11->y));
826   new->length = hypot(abs(n11->x - n2->x), abs(n11->y - n2->y));
827   new->visited = 0;
828 }
829
830 void make_segments(void)
831 {
832   for (uns i=0; i<GARY_SIZE(longlines); i++)
833   {
834     // Skip lines which are not labelled
835     if (! (longlines[i].first && longlines[i].first->label))
836       continue;
837
838     struct request_line *request = make_new_line();
839     struct request_section *rls = make_new_section(request);
840     struct request_segment *rs = NULL;
841
842     struct graph_edge *e = longlines[i].first;
843     double cur_length = 0;
844
845     struct sym_text *st = NULL;
846     if (e->label->type == SYMBOLIZER_TEXT)
847     {
848       st = (struct sym_text *) e->label;
849     }
850     else
851     {
852       // FIXME: Should other label types be supported in future?
853       DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Warning: Skipping line\n");
854       continue;
855     }
856
857     DEBUG(dbg_segments, VERBOSITY_INDIVIDUAL, "New longline\n");
858
859     while (e)
860     {
861       if (e->visited < 0)
862       {
863         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "BEWARE: Edge cycle\n");
864         break;
865       }
866       e->visited = -1;
867
868       DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Taking edge from [%.2f; %.2f] to [%.2f; %.2f] of length %.2f\n", e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->length);
869
870       if (st && (e->length < st->tw))
871       {
872         e = e->next;
873         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Warning: Skipping segment\n");
874         continue;
875       }
876
877       if (cur_length + e->length > conf_max_section_length + conf_max_section_overlay)
878       {
879         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Edge too long, length is %.2f; %.2f - %.2f = %.2f\n", e->length, conf_max_section_length, cur_length, conf_max_section_length - cur_length);
880         // HACK to prevent cutting to 0 lenght
881         cut_edge(e, max2(conf_max_section_length - cur_length, 2));
882       }
883
884       rs = make_new_segment(rls, NULL);
885       rs->label = xmalloc(sizeof(struct sym_text));
886       *((struct sym_text *) rs->label) = *((struct sym_text *) e->label);
887
888       rs->x1 = e->n1->o->x;
889       rs->y1 = e->n1->o->y;
890       rs->x2 = e->n2->o->x;
891       rs->y2 = e->n2->o->y;
892
893       rs->slope = (rs->y2 - rs->y1) / (rs->x2 - rs->x1);
894       ((struct sym_text *) rs->label)->rotate = convert_to_deg(atan(rs->slope));
895       struct variant *v = GARY_PUSH(rs->request.variants);
896       make_bitmap(v, rs->label);
897
898       rs->zindex = e->zindex;
899
900       cur_length += e->length;
901       if (cur_length > conf_max_section_length)
902       {
903         DEBUG(dbg_segments, VERBOSITY_PLACEMENT, "Making new section, new length would be %f, allowed is %.2f / %.2f\n", cur_length + e->length, conf_max_section_length, conf_max_section_overlay);
904
905         rls = make_new_section(request);
906         cur_length = 0;
907       }
908
909       e = e->next;
910     }
911
912     if (request->sections[0].num_segments == 0)
913     {
914       DEBUG(dbg_segments, VERBOSITY_INDIVIDUAL, "WARNING: Longline without any segment, skipped\n");
915
916       struct request_section *rls = &request->sections[0];
917       GARY_FREE(rls->segments);
918       GARY_FREE(rls->request.variants);
919
920       struct request_line *rl = &requests_line[GARY_SIZE(requests_line)-1];
921       GARY_FREE(rl->sections);
922       GARY_FREE(rl->request.variants);
923
924       GARY_POP(requests_line);
925       num_requests -= 2;
926     }
927   }
928 }
929
930 void dump_linelabel_requests(void)
931 {
932   for (uns i=0; i<GARY_SIZE(requests_line); i++)
933   {
934     if (requests_line[i].sections[0].num_segments == 0)
935     {
936       DEBUG(dbg_segments, VERBOSITY_INDIVIDUAL, "Beware: Longline without any segment\n");
937       continue;
938     }
939
940     printf("Request for linelabel, %zu sections\n", GARY_SIZE(requests_line[i].sections));
941     dump_label(requests_line[i].sections[0].segments[0].label);
942     for (uns j=0; j<GARY_SIZE(requests_line[i].sections); j++)
943     {
944       printf("%u section, %zu segments [%d]\n", j, GARY_SIZE(requests_line[i].sections[j].segments), requests_line[i].sections[j].request.ind);
945       for (uns k=0; k<GARY_SIZE(requests_line[i].sections[j].segments); k++)
946       {
947         struct request_segment *rs = &requests_line[i].sections[j].segments[k];
948         printf("[%.2f; %.2f] -- [%.2f; %.2f]\t\t[%d]\n", rs->x1, rs->y1, rs->x2, rs->y2, rs->request.ind);
949       }
950     }
951     printf("\n");
952   }
953 }
954
955 void dump_bitmaps(struct individual *individual)
956 {
957   bool *bitmap = xmalloc(page_width_int * page_height_int * sizeof(bool));
958   printf("Bitmap size is %d\n", page_width_int * page_height_int);
959   for (int i=0; i<page_height_int; i++)
960     for (int j=0; j<page_width_int; j++)
961       bitmap[i*page_width_int + j] = 0;
962
963   int total = 0;
964   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
965   {
966     if (individual->placements[i].variant_used == -1) continue;
967
968     struct placement *p = &(individual->placements[i]);
969     struct variant *v = NULL;
970
971     switch (p->request->type)
972     {
973       case REQUEST_SEGMENT: ;
974       case REQUEST_POINT: ;
975       case REQUEST_AREA: ;
976         v = &(p->request->variants[p->variant_used]);
977         break;
978       default:
979         ASSERT(p->request->type != REQUEST_INVALID);
980         continue;
981     }
982
983     int base_x = p->x; int base_y = p->y;
984     for (int dr = max2(0, 0-p->y); dr < v->height; dr++)
985     {
986       for (int dc = max2(0, 0-p->x); dc < v->width; dc++)
987       {
988         if (v->bitmap[dr * v->width + dc])
989         {
990           if (bitmap[(base_y + dr) * page_width_int + (base_x + dc)]) total += 1;
991           bitmap[(base_y + dr) * page_width_int + (base_x + dc)] = 1;
992         }
993       }
994     }
995   }
996   DEBUG(dbg_overlaps, VERBOSITY_GENERAL, "There were %d collisions during bitmap dump\n", total);
997
998   FILE *fd_dump = fopen("dump.pbm", "w");
999   fprintf(fd_dump, "P1\n");
1000   fprintf(fd_dump, "%d %d\n", page_width_int, page_height_int);
1001   for (int i=0; i<page_height_int; i++)
1002   {
1003     for (int j=0; j<page_width_int; j++)
1004     {
1005       fprintf(fd_dump, "%d", bitmap[(int) (i*page_width_int + j)] ? 1 : 0);
1006     }
1007     fprintf(fd_dump, "\n");
1008   }
1009   fclose(fd_dump);
1010
1011   free(bitmap);
1012 }
1013
1014 void dump_individual(struct individual *individual)
1015 {
1016   printf("*** Individual dump\n");
1017   printf("(There are %d requests)\n", num_requests);
1018
1019   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1020   {
1021     struct placement *p = &(individual->placements[i]);
1022
1023     switch (p->request->type)
1024     {
1025       case REQUEST_POINT:
1026         printf("Point at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_point *) p->request)->zindex);
1027         break;
1028       case REQUEST_LINE: ;
1029         struct request_line *rl = (struct request_line *) p->request;
1030         printf("Line: ");
1031         dump_label(rl->sections[0].segments[0].label);
1032         break;
1033       case REQUEST_SECTION: ;
1034         printf("*");
1035         break;
1036       case REQUEST_SEGMENT: ;
1037         if (p->variant_used >= 0)
1038           printf("Segment placed at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_segment *) p->request)->zindex);
1039         else
1040           printf("Segment not placed\n");
1041         break;
1042       case REQUEST_AREA: ;
1043         struct request_area *ra = (struct request_area *) p->request;
1044         printf("Area label ");
1045         dump_label(ra->label);
1046         printf(" at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_area *) p->request)->zindex);
1047         break;
1048       default:
1049         ASSERT(p->request->type != 0);
1050     }
1051   }
1052   printf("\nTotal penalty: %d\n", individual->penalty);
1053 }
1054
1055 void dump_placements(struct individual *individual)
1056 {
1057   printf("*** Individual placements dump\n");
1058
1059   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1060   {
1061     struct placement *p = &individual->placements[i];
1062     printf("Placement %d:\tPlacet at [%.2f; %.2f] using variant %d\n", p->ind, p->x, p->y, p->variant_used);
1063   }
1064 }
1065
1066 void plan_individual(struct individual *individual)
1067 {
1068   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1069   {
1070     struct symbol *s = NULL;
1071     z_index_t zindex = 0;
1072     /**
1073     if (individual->placements[i].variant_used < 0)
1074     {
1075       printf("Skipping placement of request %d\n", individual->placements[i].request->ind);
1076     }
1077     **/
1078     if (individual->placements[i].variant_used < 0) continue;
1079     switch (individual->placements[i].request->type)
1080     {
1081       case REQUEST_POINT: ;
1082         struct request_point *rp = (struct request_point *) individual->placements[i].request;
1083         s = rp->sym;
1084         zindex = rp->zindex;
1085         break;
1086       case REQUEST_SEGMENT: ;
1087         struct request_segment *rs = (struct request_segment *) individual->placements[i].request;
1088         s = rs->label;
1089         zindex = rs->zindex;
1090         break;
1091       case REQUEST_LINE: ;
1092         break;
1093       case REQUEST_AREA: ;
1094         struct request_area *ra = (struct request_area *) individual->placements[i].request;
1095         s = ra->label;
1096         zindex = ra->zindex;
1097         break;
1098       default:
1099         ASSERT(individual->placements[i].request != REQUEST_INVALID);
1100         continue;
1101     }
1102
1103   DEBUG(dbg_plan, VERBOSITY_PLACEMENT, "Will plan symbol of request %d at [%.2f; %.2f] on %u\n", individual->placements[i].request->ind, individual->placements[i].x, individual->placements[i].y, zindex);
1104
1105     if (s) switch (s->type)
1106     {
1107       case SYMBOLIZER_POINT: ;
1108         struct sym_point *sp = (struct sym_point *) s;
1109         sp->x = individual->placements[i].x;
1110         sp->y = individual->placements[i].y;
1111         sym_plan((struct symbol *) sp, zindex);
1112         break;
1113       case SYMBOLIZER_ICON: ;
1114         struct sym_icon *si = (struct sym_icon *) s;
1115         si->sir.x = individual->placements[i].x;
1116         si->sir.y = individual->placements[i].y;
1117         sym_plan((struct symbol *) si, zindex);
1118         break;
1119       case SYMBOLIZER_TEXT: ;
1120         struct sym_text *st = (struct sym_text *) s;
1121         st->x = individual->placements[i].x;
1122         st->y = individual->placements[i].y;
1123         st->next_duplicate = NULL;
1124         DEBUG(dbg_plan, VERBOSITY_PLACEMENT, "Planning text %s at [%.2f; %.2f] on %u, with rotation %.2f\n", osm_val_decode(st->text), st->x, st->y, zindex, st->rotate);
1125         sym_plan((struct symbol *) st, zindex);
1126         break;
1127       default:
1128         ASSERT(s->type != SYMBOLIZER_INVALID);
1129     }
1130   }
1131 }
1132
1133 void dump_penalties(struct individual **population)
1134 {
1135   for (int i=0; i<conf_pop_size; i++)
1136   {
1137     printf("Individual %d has penalty %d\n", i, population[i]->penalty);
1138   }
1139 }
1140
1141 void dump_placement_links(struct placement *p)
1142 {
1143   struct map_placement *mp = p->map_links;
1144
1145   while (mp)
1146   {
1147     printf(" %d", mp->part->ind);
1148     mp = mp->next_in_placement;
1149   }
1150
1151   printf("\n");
1152 }
1153
1154 void dump_part_links(struct map_part *part)
1155 {
1156   struct map_placement *mp = part->placement->next_in_map;
1157
1158   while (mp)
1159   {
1160     printf(" %d", mp->placement->ind);
1161     mp = mp->next_in_map;
1162   }
1163
1164   printf("\n");
1165 }
1166
1167 void dump_links(struct individual *individual)
1168 {
1169   printf("Dumping links in individual\n");
1170   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1171   {
1172     dump_placement_links(&individual->placements[i]);
1173   }
1174 }
1175
1176 void compute_sizes(void)
1177 {
1178   page_width_int = floor(page_width);
1179   page_height_int = floor(page_height);
1180
1181   num_map_parts_row = (page_width_int + conf_map_part_width) / conf_map_part_width;
1182   num_map_parts_col = (page_height_int + conf_map_part_height) / conf_map_part_height;
1183   num_map_parts = num_map_parts_row * num_map_parts_col;
1184
1185   breed_pop_size = conf_breed_pop_size * conf_pop_size;
1186   breed_rbest_size = conf_breed_rbest * conf_pop_size;
1187   if (dbg_evolution >= VERBOSITY_GENERAL)
1188   {
1189     printf("Breeding parameters:\n");
1190     printf(" %d individuals are created\n", breed_pop_size);
1191     printf(" %d best individuals in old population are considered\n", breed_rbest_size);
1192   }
1193
1194   mutate_pop_size = conf_mutate_pop_size * conf_pop_size;
1195   mutate_rbest_size = conf_mutate_rbest * conf_pop_size;
1196   if (dbg_evolution >= VERBOSITY_GENERAL)
1197   {
1198     printf("Mutation parameters:\n");
1199     printf(" %d individuals are created\n", mutate_pop_size);
1200     printf(" %d best individuals in old population are considered\n", mutate_rbest_size);
1201   }
1202
1203   elite_pop_size = conf_elite_pop_size * conf_pop_size;
1204   if (dbg_evolution >= VERBOSITY_GENERAL)
1205   {
1206     printf("Elitism parameters:\n");
1207     printf(" %d best individuals are copied\n", elite_pop_size);
1208   }
1209
1210   if (breed_pop_size + mutate_pop_size + elite_pop_size != conf_pop_size)
1211   {
1212     if (conf_fit_size)
1213     {
1214       elite_pop_size += conf_pop_size - (breed_pop_size + mutate_pop_size + elite_pop_size);
1215     }
1216     else
1217     {
1218       fprintf(stderr, "Breeding + mutation + elitism won't create correct number of individuals\n");
1219       fprintf(stderr, "Please fix conf_breed_pop_size, conf_mutate_pop_size and conf_elite_pop_size parameters\n");
1220       exit(2);
1221     }
1222   }
1223 }
1224
1225 void labeller_label(void)
1226 {
1227 //srandom(29011992);
1228   make_graph();
1229   label_graph();
1230   bfs_wrapper();
1231   make_segments();
1232
1233   printf("Will deal with %d requests\n", num_requests);
1234
1235   GARY_INIT(population1, conf_pop_size);
1236   GARY_INIT(population2, conf_pop_size);
1237   make_population();
1238   rank_population();
1239   qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1240
1241   if (dbg_evolution >= VERBOSITY_GENERAL)
1242   {
1243     printf("Penalties after initialization\n");
1244     dump_penalties(population1);
1245   }
1246
1247   while (! shall_terminate())
1248   {
1249     iteration++;
1250     if (dbg_evolution)
1251       printf("\n*** Iteration %d ***\n", iteration);
1252
1253     breed();
1254     mutate();
1255     elite();
1256
1257     struct individual **swp = population1;
1258     population1 = population2;
1259     population2 = swp;
1260     pop2_ind = 0;
1261     clear_population(population2);
1262
1263     rank_population();
1264
1265     if (dbg_evolution >= VERBOSITY_INDIVIDUAL)
1266     {
1267       printf("Penalties before sort\n");
1268       dump_penalties(population1);
1269     }
1270
1271     DEBUG(dbg_evolution, VERBOSITY_GENERAL, "Sorting population\n");
1272     qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1273
1274     if (dbg_evolution >= VERBOSITY_GENERAL)
1275     {
1276       printf("Penalties after sort\n");
1277       dump_penalties(population1);
1278     }
1279
1280     old_best = population1[0]->penalty;
1281   }
1282
1283   if (dbg_overlaps >= VERBOSITY_GENERAL)
1284     dump_bitmaps(population1[0]);
1285
1286   plan_individual(population1[0]);
1287
1288   labeller_cleanup();
1289 }
1290
1291 void labeller_cleanup(void)
1292 {
1293   hash_cleanup();
1294   GARY_FREE(longlines);
1295
1296   GARY_FREE(requests_point);
1297   GARY_FREE(requests_area);
1298
1299   for (uns i=0; i<GARY_SIZE(requests_line); i++)
1300   {
1301     for (uns j=0; j<GARY_SIZE(requests_line[i].sections); j++)
1302     {
1303       GARY_FREE(requests_line[i].sections[j].segments);
1304     }
1305     GARY_FREE(requests_line[i].sections);
1306   }
1307   GARY_FREE(requests_line);
1308 }
1309
1310 void make_population(void)
1311 {
1312   for (int i=0; i<conf_pop_size; i++)
1313   {
1314     num_placements = 0; // FIXME: This IS a terrible HACK
1315     struct individual *i2 = ep_alloc(ep_individuals);
1316     init_individual(i2);
1317     population2[i] = i2;
1318
1319     DEBUG(dbg_init, VERBOSITY_INDIVIDUAL, "Making individual %d\n", i);
1320     struct individual *individual = ep_alloc(ep_individuals); init_individual(individual);
1321     population1[i] = individual;
1322
1323     int p = 0;
1324     for (uns j=0; j<GARY_SIZE(requests_point); j++)
1325     {
1326       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_point[j]);
1327     }
1328
1329     for (uns j=0; j<GARY_SIZE(requests_line); j++)
1330     {
1331       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j]);
1332
1333       for (uns k=0; k<GARY_SIZE(requests_line[j].sections); k++)
1334       {
1335         init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k]);
1336
1337         for (uns l=0; l<GARY_SIZE(requests_line[j].sections[k].segments); l++)
1338         {
1339           init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k].segments[l]);
1340         }
1341       }
1342     }
1343
1344     for (uns j=0; j<GARY_SIZE(requests_area); j++)
1345     {
1346       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_area[j]);
1347     }
1348
1349     hide_segment_labels(individual);
1350
1351     ASSERT(p == num_requests);
1352   }
1353 }
1354
1355 bool shall_terminate(void)
1356 {
1357   switch (conf_term_cond)
1358   {
1359     case TERM_COND_PENALTY:
1360       return (population1[0]->penalty < conf_penalty_bound);
1361     case TERM_COND_STAGNATION:
1362       return (abs(old_best - population1[0]->penalty) < conf_stagnation_bound);
1363     case TERM_COND_ITERATIONS:
1364       return (iteration >= conf_iteration_limit);
1365     default:
1366       fprintf(stderr, "Warning: No termination condition is set, terminating\n");
1367       return 1;
1368   }
1369 }
1370
1371 void breed(void)
1372 {
1373   int i=0;
1374
1375   struct individual **breed_buffer;
1376   while (i < breed_pop_size)
1377   {
1378     int parent1 = randint(0, breed_rbest_size);
1379     int parent2 = randint(0, breed_rbest_size);
1380     DEBUG(dbg_breeding, VERBOSITY_INDIVIDUAL, "Will breed %d and %d\n", parent1, parent2);
1381
1382     breed_buffer = perform_crossover(population1[parent1], population1[parent2]);
1383     population2[pop2_ind++] = breed_buffer[0];
1384     population2[pop2_ind++] = breed_buffer[1];
1385     free(breed_buffer);
1386     i += 2;
1387   }
1388 }
1389
1390 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2)
1391 {
1392   struct individual **buffer = xmalloc(2*sizeof(struct individual));
1393   struct individual *child1 = ep_alloc(ep_individuals); init_individual(child1);
1394   struct individual *child2 = ep_alloc(ep_individuals); init_individual(child2);
1395
1396   bool *processed;
1397   GARY_INIT_ZERO(processed, GARY_SIZE(parent1->placements));
1398
1399   for (uns i=0; i<GARY_SIZE(parent1->placements); i++)
1400   {
1401     if (! processed[parent1->placements[i].ind])
1402     {
1403       DEBUG(dbg_breeding, VERBOSITY_PLACEMENT, "Creating symbol closure for placement %u\n", i);
1404
1405       struct placement **clos_symbols = get_closure(&(parent1->placements[i]));
1406       int x = randint(0, 2);
1407
1408       if (x == 0)
1409       {
1410         DEBUG(dbg_breeding, VERBOSITY_PLACEMENT, "Copying parent->child 1->1 and 2->2\n");
1411         copy_symbols(clos_symbols, parent1, child1, &processed);
1412         copy_symbols(clos_symbols, parent2, child2, &processed);
1413       }
1414       else
1415       {
1416         DEBUG(dbg_breeding, VERBOSITY_PLACEMENT, "Copying parent->child 2->1 and 1->2\n");
1417         copy_symbols(clos_symbols, parent2, child1, &processed);
1418         copy_symbols(clos_symbols, parent1, child2, &processed);
1419       }
1420
1421       GARY_FREE(clos_symbols);
1422     }
1423   }
1424
1425   GARY_FREE(processed);
1426
1427   if (conf_mutate_children)
1428   {
1429     if (randdouble() < conf_mutate_children_prob) perform_mutation(child1);
1430     else hide_segment_labels(child1);
1431
1432     if (randdouble() < conf_mutate_children_prob) perform_mutation(child2);
1433     else hide_segment_labels(child2);
1434   }
1435
1436   buffer[0] = child1;
1437   buffer[1] = child2;
1438   return buffer;
1439 }
1440
1441 void mutate(void)
1442 {
1443   for (int i=0; i < mutate_pop_size; i++)
1444   {
1445     DEBUG(dbg_mutation, VERBOSITY_INDIVIDUAL, "Creating %d-th individual by mutation\n", i);
1446     int ind = randint(0, mutate_rbest_size);
1447     DEBUG(dbg_mutation, VERBOSITY_INDIVIDUAL, "Mutating %d-th individual of original population\n", ind);
1448     population2[pop2_ind] = ep_alloc(ep_individuals);
1449     copy_individual(population1[ind], population2[pop2_ind]);
1450     DEBUG(dbg_mutation, VERBOSITY_INDIVIDUAL, "Individual %d in pop2 inited from individual %d in pop1\n", pop2_ind, ind);
1451     perform_mutation(population2[pop2_ind]);
1452     pop2_ind++;
1453   }
1454 }
1455
1456 void perform_mutation(struct individual *individual)
1457 {
1458   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1459   {
1460     double x = randdouble();
1461     double acc = 0;
1462
1463     if (x <= acc + conf_mutate_move_bound)
1464     {
1465       DEBUG(dbg_mutation, VERBOSITY_PLACEMENT, "Mutation: Moving symbol in placement %u\n", i);
1466       move_symbol(&(individual->placements[i]));
1467       continue;
1468     }
1469     acc += conf_mutate_move_bound;
1470
1471     if (x <= acc + conf_mutate_regen_bound)
1472     {
1473       gen_coords(&(individual->placements[i]));
1474       continue;
1475     }
1476     acc += conf_mutate_regen_bound;
1477
1478     if (x <= acc + conf_mutate_chvar_bound)
1479     {
1480       struct placement *p = &(individual->placements[i]);
1481       switch (p->request->type)
1482       {
1483         case REQUEST_POINT:
1484         case REQUEST_AREA:
1485           // Does nothing when there are 0 variants... does it mind?
1486           p->variant_used = randint(-1, GARY_SIZE(p->request->variants));
1487           break;
1488         case REQUEST_SEGMENT:
1489           p->variant_used = randint(0, GARY_SIZE(p->request->variants));
1490           break;
1491         case REQUEST_SECTION:
1492           p->variant_used = randint(0, GARY_SIZE(((struct request_section *) p->request)->segments));
1493           break;
1494         default:
1495           ;
1496       }
1497     }
1498   }
1499
1500   hide_segment_labels(individual);
1501 }
1502
1503 void elite(void)
1504 {
1505   for (int i=0; i<elite_pop_size; i++)
1506   {
1507     DEBUG(dbg_evolution, VERBOSITY_INDIVIDUAL, "Iteration %d: Copying individual #%d from pop 1 to #%d in pop 2\n", iteration, i, pop2_ind);
1508     population2[pop2_ind] = ep_alloc(ep_individuals);
1509     copy_individual(population1[i], population2[pop2_ind++]);
1510   }
1511 }
1512
1513 int overlaps(struct placement *p1, struct placement *p2)
1514 {
1515   if (p1->request->type != REQUEST_POINT &&
1516       p1->request->type != REQUEST_SEGMENT &&
1517       p1->request->type != REQUEST_AREA)
1518     return 0;
1519
1520   if (p2->request->type != REQUEST_POINT &&
1521       p2->request->type != REQUEST_SEGMENT &&
1522       p2->request->type != REQUEST_AREA)
1523     return 0;
1524
1525   if (p1->variant_used == -1 || p2->variant_used == -1)
1526     return 0;
1527
1528   struct variant *v1, *v2;
1529
1530   v1 = &(p1->request->variants[p1->variant_used]);
1531   v2 = &(p2->request->variants[p2->variant_used]);
1532
1533   // FIXME: This doesn't fully respect offset which it probably should
1534   int p1x = p1->x; int p1y = p1->y;
1535   int p2x = p2->x; int p2y = p2->y;
1536
1537   int overlap = 0;
1538   for (int y=max2(0, max2(p1y, p2y)); y<min2(page_height_int, min2(p1y+v1->height, p2y+v2->height)); y++)
1539     for (int x=max2(0, max2(p1x, p2x)); x<min2(page_width_int, min2(p1x+v1->width, p2x+v2->width)); x++)
1540     {
1541       if (v1->bitmap[(y-p1y)*v1->width + (x-p1x)] &&
1542           v2->bitmap[(y-p2y)*v2->width + (x-p2x)])
1543         overlap++;
1544     }
1545
1546   return overlap;
1547 }
1548
1549 int get_overlap(struct placement *p, int **planned_ptr, int iteration)
1550 {
1551   int *planned = *planned_ptr;
1552
1553   if (p->variant_used == -1) return 0;
1554
1555   struct map_part **parts = get_map_parts(p);
1556   if (! parts)
1557   {
1558     DEBUG(dbg_overlaps, VERBOSITY_PLACEMENT, "Placement of request %d seems not to be placed\n", p->request->ind);
1559     return 0;
1560   }
1561
1562   struct placement **others;
1563
1564   planned[p->request->ind] = iteration;
1565   GARY_INIT(others, 0);
1566
1567 //printf("Iterating over parts of placement %d (at [%.2f; %.2f] / %d)\n", p->ind, p->x, p->y, p->variant_used);
1568   for (uns i=0; i<GARY_SIZE(parts); i++)
1569   {
1570   //printf("%d:\t", parts[i]->ind);
1571   //dump_part_links(parts[i]);
1572     struct map_placement *mp = parts[i]->placement->next_in_map;
1573     while (mp)
1574     {
1575       if (planned[mp->placement->request->ind] != iteration)
1576       {
1577         struct placement **p = GARY_PUSH(others);
1578         *p = mp->placement;
1579         planned[mp->placement->request->ind] = iteration;
1580       }
1581       mp = mp->next_in_map;
1582     }
1583   }
1584
1585   int overlap = 0;
1586   for (uns i=0; i<GARY_SIZE(others); i++)
1587   {
1588     overlap += overlaps(p, others[i]);
1589   }
1590
1591   GARY_FREE(parts);
1592   GARY_FREE(others);
1593
1594   if (dbg_overlaps >= VERBOSITY_PLACEMENT)
1595   {
1596     printf("Placement %d (of request %d) add %d to overlaps", p->ind, p->request->ind, overlap);
1597     dump_placement_links(p);
1598   }
1599
1600   if (p->x < 0) overlap += 0 - p->x;
1601   if (p->x + p->request->variants[p->variant_used].width > page_width_int)
1602     overlap += p->x + p->request->variants[p->variant_used].width - page_width_int;
1603
1604   if (p->y < 0) overlap += 0 - p->y;
1605   if (p->y + p->request->variants[p->variant_used].height > page_height_int)
1606     overlap += p->y + p->request->variants[p->variant_used].height - page_height_int;
1607
1608   return overlap;
1609 }
1610
1611 int individual_overlap(struct individual *individual)
1612 {
1613   int overlap = 0;
1614
1615   int *planned;
1616   GARY_INIT_ZERO(planned, GARY_SIZE(individual->placements));
1617
1618   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1619   {
1620     overlap += get_overlap(&individual->placements[i], &planned, i+1);
1621   }
1622
1623   GARY_FREE(planned);
1624
1625 //  printf("Total overlap is %d\n", overlap);
1626
1627   return overlap;
1628 }
1629
1630 double get_distance(struct placement *p)
1631 {
1632   if (p->variant_used < 0) return 0;
1633   struct variant *v = &p->request->variants[p->variant_used];
1634
1635   double dx, dy, distance;
1636   switch (p->request->type)
1637   {
1638     case REQUEST_POINT: ;
1639       struct request_point *rp = (struct request_point *) p->request;
1640       dx = rp->x + v->offset_x - p->x;
1641       dy = rp->y + v->offset_y - p->y;
1642       distance = hypot(dx, dy);
1643       DEBUG(dbg_rank, VERBOSITY_PLACEMENT, "Point placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, rp->x, rp->y);
1644       break;
1645     case REQUEST_SEGMENT: ;
1646       struct request_segment *rs = (struct request_segment *) p->request;
1647       struct sym_text *st = (struct sym_text *) rs->label;
1648
1649       double width = p->request->variants[p->variant_used].width;
1650       double rotated_x = p->x + width * sin(convert_to_rad(st->rotate));
1651       double rotated_y = p->y + width * cos(convert_to_rad(st->rotate));
1652
1653       if (rs->x1 < rs->x2)
1654       {
1655         if (p->x < rs->x1)
1656         {
1657           dx = rs->x1 - p->x;
1658           dy = rs->y1 - p->y;
1659         }
1660         else if (rotated_x > rs->x2)
1661         {
1662           dx = rotated_x - rs->x2;
1663           dy = rotated_y - rs->y2;
1664         }
1665         else
1666         {
1667           dx = dy = 0;
1668         }
1669       }
1670       else
1671       {
1672         if (p->x < rs->x2)
1673         {
1674           dx = rs->x2 - p->x;
1675           dy = rs->y2 - p->y;
1676         }
1677         else if (rotated_x > rs->x1)
1678         {
1679           dx = rotated_x - rs->x1;
1680           dy = rotated_y - rs->y1;
1681         }
1682         else
1683         {
1684           dx = dy = 0;
1685         }
1686       }
1687
1688       distance = hypot(dx, dy);
1689       break;
1690     case REQUEST_AREA: ;
1691       struct request_area *ra = (struct request_area *) p->request;
1692       dx = ra->cx + v->offset_x - p->x;
1693       dy = ra->cy + v->offset_y - p->y;
1694       distance = hypot(dx, dy);
1695       DEBUG(dbg_rank, VERBOSITY_PLACEMENT, "Area placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1696       break;
1697     default:
1698       return 0;
1699   }
1700
1701   DEBUG(dbg_rank, VERBOSITY_PLACEMENT, "Placement %d has distance %.2f\n", p->ind, distance);
1702   return distance;
1703 }
1704
1705 double individual_distances(struct individual *individual)
1706 {
1707   int distances = 0;
1708
1709   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1710   {
1711     distances += get_distance(&individual->placements[i]);
1712   }
1713
1714   return distances;
1715 }
1716
1717 double get_omittment(struct placement *p)
1718 {
1719   if (p->variant_used >= 0) return 0;
1720
1721   // FIX ME :)
1722   switch (p->request->type)
1723   {
1724     case REQUEST_POINT:
1725     case REQUEST_AREA:
1726       return 10;
1727       break;
1728     default:
1729       return 0;
1730   }
1731 }
1732
1733 double individual_omittment(struct individual *individual)
1734 {
1735   int omittment = 0;
1736
1737   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1738   {
1739     omittment += get_omittment(&individual->placements[i]);
1740   }
1741
1742   return omittment;
1743 }
1744
1745 int cmp_individual(const void *a, const void *b)
1746 {
1747   struct individual **ia = (struct individual **) a;
1748   struct individual **ib = (struct individual **) b;
1749
1750   return (*ia)->penalty - (*ib)->penalty;
1751 }
1752
1753 void rank_population(void)
1754 {
1755   int penalty;
1756
1757   for (int i=0; i<conf_pop_size; i++)
1758   {
1759     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Individual %d\n", i);
1760     population1[i]->penalty = 0;
1761
1762     penalty = individual_omittment(population1[i]);
1763     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Increasing penalty by %d for omittment\n", penalty);
1764     population1[i]->penalty += penalty;
1765
1766     penalty = individual_overlap(population1[i]);
1767     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Increasing penalty by %d for overlap\n", penalty);
1768     population1[i]->penalty += penalty;
1769
1770     penalty = individual_distances(population1[i]);
1771     DEBUG(dbg_rank, VERBOSITY_INDIVIDUAL, "Increasing penalty by %d for distances\n", penalty);
1772     population1[i]->penalty += penalty;
1773   }
1774 }
1775
1776 struct map_part **get_map_parts(struct placement *p)
1777 {
1778   if (p->variant_used < 0) return NULL;
1779
1780   struct map_part **buffer;
1781   GARY_INIT(buffer, 0);
1782
1783   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Looking for map parts containing placement of request %d, placed at [%.2f; %.2f]\n", p->request->ind, p->x, p->y);
1784
1785   struct variant v;
1786   switch (p->request->type)
1787   {
1788     case REQUEST_POINT:
1789     case REQUEST_SEGMENT:
1790     case REQUEST_AREA:
1791       v = p->request->variants[p->variant_used];
1792       break;
1793     default:
1794       DEBUG(dbg_map_parts, VERBOSITY_ALL, "Skipping unsupported request type (%d)\n", p->request->type);
1795       return NULL;
1796   }
1797
1798   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Bitmap is %d x %d\n", v.width, v.height);
1799
1800   int x_min = max2(0, p->x) / conf_map_part_width;
1801   // CHECK ME: Is rounding needed?
1802   int x_max = min2(page_width_int, (p->x + v.width)) / conf_map_part_width;
1803   int y_min = max2(0, p->y) / conf_map_part_height;
1804   // CHECK ME: Is rounding needed?
1805   int y_max = min2(page_height_int, (p->y + v.height)) / conf_map_part_height;
1806
1807   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Cells between [%d; %d] and [%d; %d] generated\n", x_min, y_min, x_max, y_max);
1808
1809   for (int y=y_min; y<=y_max; y++)
1810     for (int x=x_min; x<=x_max; x++)
1811     {
1812       struct map_part **m = GARY_PUSH(buffer);
1813       DEBUG(dbg_map_parts, VERBOSITY_ALL, "Asking for %d of %zu\n", y * num_map_parts_row + x, GARY_SIZE(p->individual->map));
1814       *m = p->individual->map[y * num_map_parts_row + x];
1815     }
1816
1817   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Returning %zu map parts potentially containing the symbol\n", GARY_SIZE(buffer));
1818
1819   return buffer;
1820 }
1821
1822 void update_map_parts_delete(struct placement *p)
1823 {
1824   struct map_placement *mp = p->map_links;
1825   while (mp)
1826   {
1827     mp->prev_in_map->next_in_map = mp->next_in_map;
1828     if (mp->next_in_map)
1829       mp->next_in_map->prev_in_map = mp->prev_in_map;
1830
1831     struct map_placement *tmp = mp;
1832     mp = mp->next_in_placement;
1833     free(tmp);
1834   }
1835   p->map_links = NULL;
1836 }
1837
1838 void update_map_parts_create(struct placement *p)
1839 {
1840   struct map_part **parts = get_map_parts(p);
1841   if (parts == NULL) return;
1842
1843   for (uns i=0; i<GARY_SIZE(parts); i++)
1844   {
1845     struct map_placement *mp = xmalloc(sizeof(struct map_placement));
1846     mp->placement = p;
1847     mp->part = parts[i];
1848
1849     mp->next_in_map = parts[i]->placement->next_in_map;
1850     mp->prev_in_map = parts[i]->placement;
1851     parts[i]->placement->next_in_map = mp;
1852     if (mp->next_in_map) mp->next_in_map->prev_in_map = mp;
1853
1854     mp->next_in_placement = p->map_links;
1855     mp->prev_in_placement = NULL;
1856     p->map_links = mp;
1857   }
1858
1859   GARY_FREE(parts);
1860 }
1861
1862 void update_map_parts(struct placement *p)
1863 {
1864   update_map_parts_delete(p);
1865   update_map_parts_create(p);
1866 }
1867
1868 void gen_coords(struct placement *p)
1869 {
1870   switch(p->request->type)
1871   {
1872     case REQUEST_POINT:
1873       gen_coords_point(p);
1874       break;
1875     case REQUEST_AREA:
1876       gen_coords_area(p);
1877       break;
1878     case REQUEST_SEGMENT:
1879       gen_coords_segment(p);
1880       break;
1881     case REQUEST_LINE:
1882       if (dbg_movement)
1883         printf("Not yet implemented\n");
1884       break;
1885     default:
1886       DEBUG(dbg_movement, VERBOSITY_ALL, "Testing request type\n");
1887       ASSERT(p->request->type != REQUEST_INVALID);
1888   }
1889
1890   update_map_parts(p);
1891 }
1892
1893 double gen_movement(void)
1894 {
1895   double m = (random() % 100000) / 10000;
1896   m = pow(m, 1.0/3) * flip(1, -1);
1897   DEBUG(dbg_movement, VERBOSITY_ALL, "Movement %.2f\n", m);
1898   return m;
1899 }
1900
1901 double gen_movement_uniform(void)
1902 {
1903   return (move_max - move_min) * randdouble() * flip(1, -1);
1904 }
1905
1906 void gen_coords_point(struct placement *p)
1907 {
1908   p->x = p->x + gen_movement();
1909 }
1910
1911 void gen_coords_segment(struct placement *p)
1912 {
1913   struct request_segment *rs = (struct request_segment *) p->request;
1914   p->x = (rs->x1 + rs->x2) / 2;
1915   p->y = (rs->y1 + rs->y2) / 2;
1916 }
1917
1918 void gen_coords_area(struct placement *p)
1919 {
1920   struct request_area *ra = (struct request_area *) p->request;
1921
1922   p->x = p->x + gen_movement();
1923   p->y = p->y + gen_movement();
1924
1925   DEBUG(dbg_movement, VERBOSITY_PLACEMENT, "Moved label to [%.2f; %.2f] from [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1926 }
1927
1928 int randint(int min, int max)
1929 {
1930   if (min == max) return min;
1931   int r = random();
1932   return min + (r % (max - min));
1933 }
1934
1935 struct placement **get_closure(struct placement *placement)
1936 {
1937   struct placement **closure;
1938   GARY_INIT(closure, 0);
1939   bool *chosen = xmalloc(GARY_SIZE(placement->individual->placements) * sizeof(bool));
1940   for (uns i=0; i<GARY_SIZE(placement->individual->placements); i++) { chosen[i] = 0; }
1941   chosen[placement->request->ind] = 1;
1942
1943   struct placement **p = GARY_PUSH(closure); *p = placement;
1944
1945   uns first = 0;
1946   while (first < GARY_SIZE(closure))
1947   {
1948     DEBUG(dbg_breeding, VERBOSITY_ALL, "Iterating, first is %u of current %zu\n", first, GARY_SIZE(closure));
1949     struct placement **overlapping = get_overlapping(placement);
1950     if (! overlapping) { first++; continue; }
1951
1952     struct placement **filtered = filter(overlapping, &chosen);
1953     DEBUG(dbg_breeding, VERBOSITY_ALL, "There are %zu new overlapping symbols\n", GARY_SIZE(filtered));
1954     GARY_FREE(overlapping);
1955     overlapping = filtered;
1956     for (uns j=0; j<GARY_SIZE(overlapping); j++)
1957     {
1958       if (! chosen[overlapping[j]->request->ind])
1959       {
1960         if (overlaps(*p, overlapping[j]))
1961         {
1962           p = GARY_PUSH(closure); *p = overlapping[j];
1963           DEBUG(dbg_breeding, VERBOSITY_ALL, "Adding placement of request %d (in fact at [%.2f; %.2f] of size %d x %d)\n", overlapping[j]->request->ind, overlapping[j]->x, overlapping[j]->y, overlapping[j]->request->variants[overlapping[j]->variant_used].width, overlapping[j]->request->variants[overlapping[j]->variant_used].height);
1964           chosen[overlapping[j]->request->ind] = 1;
1965         }
1966       }
1967     }
1968     GARY_FREE(overlapping);
1969     first++;
1970   }
1971
1972   free(chosen);
1973
1974   return closure;
1975 }
1976
1977 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child, bool **processed_ptr)
1978 {
1979   bool *processed = *processed_ptr;
1980   DEBUG(dbg_breeding, VERBOSITY_ALL, "Will copy %zu symbols\n", GARY_SIZE(closure));
1981
1982   for (uns i=0; i<GARY_SIZE(closure); i++)
1983   {
1984     processed[closure[i]->ind] = 1;
1985     int ind = closure[i]->ind;
1986     child->placements[ind] = parent->placements[ind];
1987     child->placements[ind].individual = child;
1988     child->placements[ind].processed = 0;
1989     child->placements[ind].map_links = NULL;
1990     update_map_parts(&child->placements[ind]);
1991   }
1992 }
1993
1994 void move_symbol(struct placement *p)
1995 {
1996   switch (p->request->type)
1997   {
1998     case REQUEST_POINT:
1999     case REQUEST_AREA:
2000       move_symbol_point(p);
2001       break;
2002     case REQUEST_SEGMENT:
2003       move_symbol_segment(p);
2004       break;
2005     default:
2006       ASSERT(p->request->type != REQUEST_INVALID);
2007   }
2008 }
2009
2010 void move_symbol_point(struct placement *p)
2011 {
2012   p->x += gen_movement_uniform();
2013   p->y += gen_movement_uniform();
2014 }
2015
2016 void move_symbol_segment(struct placement *p)
2017 {
2018   double m = gen_movement_uniform();
2019   // CHECK ME
2020   p->x += m;
2021   p->y += m * ((struct request_segment *) p->request)->slope;
2022 }
2023
2024 void hide_segment_labels(struct individual *individual)
2025 {
2026   // BEWARE: This fully depends on current genetic encoding
2027
2028   int used = -1, num = -1;
2029   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
2030   {
2031     switch (individual->placements[i].request->type)
2032     {
2033       case REQUEST_SECTION:
2034         used = individual->placements[i].variant_used;
2035         num = 0;
2036         break;
2037       case REQUEST_SEGMENT:
2038         if (num == used)
2039           individual->placements[i].variant_used = 0;
2040         else
2041           individual->placements[i].variant_used = -1;
2042         num++;
2043         break;
2044       default:
2045         ;
2046     }
2047   }
2048 }
2049
2050 void init_placement(struct placement *p, struct individual *individual, struct request *r)
2051 {
2052   p->ind = num_placements++;
2053   p->request = r;
2054   p->processed = 0;
2055   p->x = p->y = 0; // To prevent valgrind from complaining
2056   p->variant_used = 0;
2057   p->map_links = NULL;
2058   p->individual = individual;
2059   switch (r->type)
2060   {
2061     case REQUEST_POINT: ;
2062       struct request_point *rp = (struct request_point *) r;
2063       p->x = rp->x;
2064       p->y = rp->y;
2065       break;
2066     case REQUEST_LINE: ;
2067       break;
2068     case REQUEST_SECTION: ;
2069       struct request_section *rls = (struct request_section *) r;
2070       p->variant_used = randint(0, rls->num_segments);
2071       break;
2072     case REQUEST_SEGMENT: ;
2073       struct request_segment *rs = (struct request_segment *) r;
2074       p->x = rs->x2;
2075       p->y = rs->y2;
2076       break;
2077     case REQUEST_AREA: ;
2078       struct request_area *ra = (struct request_area *) r;
2079       p->x = ra->cx;
2080       p->y = ra->cy;
2081       p->variant_used = 0;
2082       break;
2083     default:
2084       ASSERT(p->request->type != REQUEST_INVALID);
2085   }
2086
2087   gen_coords(p);
2088   DEBUG(dbg_init, VERBOSITY_PLACEMENT, "Inited placement to [%.2f; %.2f]\n", p->x, p->y);
2089 }
2090
2091 /**
2092 void reset_individual_map(struct individual *i)
2093 {
2094   for (uns j=0; j<num_map_parts; j++)
2095   {
2096     struct map_placement *mp = i->map[j]->placement;
2097     while (mp)
2098     {
2099       struct map_placement *tmp = mp;
2100       mp = mp->next_in_map;
2101       free(tmp);
2102     }
2103
2104     free(i->map[j]);
2105     struct map_part *part = xmalloc(sizeof(struct map_part));
2106     part->ind = j;
2107
2108     mp = xmalloc(sizeof(struct map_placement));
2109     part->placement = mp;
2110     mp->placement = &dummy_placement;
2111     mp->next_in_map = mp->prev_in_map = NULL;
2112     mp->next_in_placement = mp->prev_in_placement = NULL;
2113     i->map[j] = part;
2114   }
2115 }
2116 **/
2117
2118 /**
2119 void update_individual(struct individual *individual)
2120 {
2121   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
2122   {
2123     update_map_parts_delete(&individual->placements[i]);
2124   }
2125 }
2126 **/
2127
2128 void clear_individual(struct individual *individual)
2129 {
2130   for (uns j=0; j<num_map_parts; j++)
2131   {
2132     struct map_placement *mp = individual->map[j]->placement;
2133     while (mp)
2134     {
2135       struct map_placement *tmp = mp;
2136       mp = mp->next_in_map;
2137       free(tmp);
2138     }
2139
2140     free(individual->map[j]);
2141   }
2142
2143   GARY_FREE(individual->map);
2144   GARY_FREE(individual->placements);
2145   ep_free(ep_individuals, individual);
2146 }
2147
2148 void clear_population(struct individual **pop)
2149 {
2150   for (uns i=0; i<GARY_SIZE(pop); i++)
2151   {
2152     clear_individual(pop[i]);
2153   }
2154 }
2155
2156 struct placement **get_overlapping(struct placement *p)
2157 {
2158   struct placement **buffer;
2159   GARY_INIT(buffer, 0);
2160
2161   struct map_part **parts = get_map_parts(p);
2162   if (! parts) return NULL;
2163
2164   for (uns i=0; i<GARY_SIZE(parts); i++)
2165   {
2166     struct map_placement *mp = parts[i]->placement->next_in_map;
2167     while (mp)
2168     {
2169       if (p->variant_used >= 0)
2170       {
2171         struct placement **p = GARY_PUSH(buffer);
2172         *p = mp->placement;
2173       }
2174       mp = mp->next_in_map;
2175     }
2176   }
2177   GARY_FREE(parts);
2178
2179   DEBUG(dbg_map_parts, VERBOSITY_PLACEMENT, "Returning %zu potentially overlapping placements\n", GARY_SIZE(buffer));
2180
2181   return buffer;
2182 }
2183
2184 struct placement **filter(struct placement **list, bool **pred_ptr)
2185 {
2186   bool *pred = *pred_ptr; // As GARY can't be passed directly
2187   struct placement **filtered;
2188   GARY_INIT(filtered, 0);
2189
2190   for (uns i=0; i<GARY_SIZE(list); i++)
2191   {
2192     if (pred[list[i]->request->ind])
2193       continue;
2194
2195     struct placement **p = GARY_PUSH(filtered);
2196     *p = list[i];
2197   }
2198
2199   return filtered;
2200 }
2201
2202 int flip(int a, int b)
2203 {
2204   return (random() % 2 ? a : b);
2205 }
2206
2207 double randdouble(void)
2208 {
2209   return ((double) rand() / (double) RAND_MAX);
2210 }
2211
2212 void init_individual(struct individual *individual)
2213 {
2214   GARY_INIT(individual->placements, num_requests);
2215   GARY_INIT(individual->map, 0);
2216   for (uns j=0; j<num_map_parts; j++)
2217   {
2218     GARY_PUSH(individual->map);
2219     struct map_part *part = xmalloc(sizeof(struct map_part));
2220     struct map_placement *mp = xmalloc(sizeof(struct map_placement));
2221     part->placement = mp;
2222     part->ind = j;
2223     mp->placement = &dummy_placement;
2224     mp->next_in_map = mp->prev_in_map = NULL;
2225     mp->next_in_placement = mp->prev_in_placement = NULL;
2226     individual->map[j] = part;
2227   }
2228   individual->penalty = 0;
2229 }
2230
2231 void copy_individual(struct individual *src, struct individual *dest)
2232 {
2233   init_individual(dest);
2234   dest->penalty = src->penalty;
2235
2236   for (uns i=0; i<GARY_SIZE(src->placements); i++)
2237   {
2238     dest->placements[i] = src->placements[i];
2239     dest->placements[i].map_links = NULL;
2240     dest->placements[i].individual = dest;
2241
2242     update_map_parts_create(&dest->placements[i]);
2243   }
2244 }