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