]> mj.ucw.cz Git - leo.git/blob - labeller.c
Labelling: Placements have indices
[leo.git] / labeller.c
1 #include <errno.h>
2
3 #include <ucw/lib.h>
4 #include <ucw/gary.h>
5 #include <ucw/mempool.h>
6 #include <ucw/eltpool.h>
7
8 #include "leo.h"
9 #include "sym.h"
10 #include "map.h"
11 #include "labeller.h"
12
13 #define HASH_NODE struct graph_node
14 #define HASH_PREFIX(x) hash_##x
15 #define HASH_KEY_ATOMIC id
16 #define HASH_WANT_FIND
17 #define HASH_WANT_NEW
18 #define HASH_WANT_CLEANUP
19 #include <ucw/hashtable.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <math.h>
24 #include <fcntl.h>
25
26 #define BLOCK_SIZE 4096
27
28 //struct mempool *mpool_requests;
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; int num_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 = 0;
45 int dbg_plan = 0;
46 int dbg_requests = 0;
47 int dbg_graph = 0;
48 int dbg_bfs = 0;
49 int dbg_map_parts = 0;
50 int dbg_movement = 0;
51 int dbg_init = 0;
52 int dbg_overlaps = 0;
53 int dbg_rank = 0;
54 int dbg_evolution = 0;
55 int dbg_mutation = 0;
56
57 int page_width_int;
58 int page_height_int;
59
60 int num_edges_dbg;
61 int num_nodes;
62 int num_edges = 0;
63 int dbg_num_hits = 0;
64
65 int conf_pop_size = 50;
66
67 int conf_penalty_bound = 0;
68 int conf_stagnation_bound = 0;
69 int conf_iteration_limit = 4;
70
71 int conf_term_cond = TERM_COND_ITERATIONS;
72
73 int conf_breed_rbest_perc = 80;
74 int conf_breed_pop_size_perc = 20;
75 int conf_breed_perc = 50;                       // Percentage of new pop created by breeding
76
77 bool conf_mutate_children = 1;
78 double conf_mutate_children_prob = 0.3;
79
80 double conf_mutate_rbest = 1;
81 double conf_mutate_pop_size = 0.9;
82
83 double conf_mutate_move_bound = 1.0;
84 double conf_mutate_regen_bound = 0.0;
85 double conf_mutate_chvar_bound = 0.0;
86
87 int mutate_pop_size;
88 int mutate_rbest_size;
89
90 double conf_elite_pop_size = 0.1;
91 int elite_pop_size;
92
93 double conf_max_section_length = 100;
94 double conf_max_section_overlay = 10;
95
96 int old_best = 0; // FIXME: Shall be int max
97 int iteration = 0;
98 int pop2_ind;
99
100 int conf_part_size = 50;
101
102 int move_min = 0;
103 int move_max = 1;
104
105 int num_requests = 0;
106 int num_placements = 0;
107
108 int conf_map_part_width = 5;
109 int conf_map_part_height = 5;
110 int num_map_parts_row;
111 int num_map_parts_col;
112 int num_map_parts;
113
114 void make_graph(void);
115 void label_graph(void);
116 void join_edge(struct graph_edge *e, int dir);
117 void bfs(uns longline);
118 void make_segments(void);
119
120 int overlaps(struct placement *p1, struct placement *p2);
121 int get_overlap(struct placement *p);
122 int individual_overlap(struct individual *individual);
123
124 void make_population(void);
125 bool shall_terminate(void);
126 void breed(void);
127 void mutate(void);
128 void elite(void);
129 void rank_population(void);
130 void plan_individual(struct individual *individual);
131
132 int cmp_individual(const void *a, const void *b);
133
134 void make_bitmap(struct variant *v, struct symbol *sym);
135 void make_bitmap_icon(struct variant *v, struct sym_icon *si);
136 void make_bitmap_point(struct variant *v, struct sym_point *sp);
137 void make_bitmap_label(struct variant *v, struct sym_text *text);
138
139 void cut_edge(struct graph_edge *e, double dist);
140 struct request_line *make_new_line(void);
141 struct request_section *make_new_section(struct request_line *rl);
142 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym);
143
144 void dump_bitmaps(struct individual *individual);
145 void dump_graph(void);
146 void bfs2(void);
147 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir);
148 void bfs_wrapper(void);
149 void oldbfs(void);
150 void dump_longlines(void);
151 void dump_linelabel_requests(void);
152 void dump_individual(struct individual *individual);
153 void print_label(struct symbol *sym);
154 void dump_penalties(struct individual **population);
155
156 double gen_movement(void);
157 double gen_movement_uniform(void);
158 void gen_coords(struct placement *p);
159 void gen_coords_point(struct placement *p);
160 void gen_coords_segment(struct placement *p);
161 void gen_coords_area(struct placement *p);
162
163 struct map_part **get_map_parts(struct placement *p);
164 void update_map_parts(struct placement *p);
165
166 void make_segments_old(void);
167
168 void labeller_cleanup(void);
169
170 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2);
171 void perform_mutation(struct individual *individual);
172
173 void hide_segment_labels(struct individual *individual);
174 void init_placement(struct placement *p, struct individual *individual, struct request *r);
175 void init_individual(struct individual *i);
176 struct map_part **get_parts(struct placement *symbol, struct individual *individual);
177
178 int randint(int min, int max);
179
180 struct placement **get_closure(struct placement *placement, struct individual *parent1, struct individual *parent2);
181 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child);
182 void move_symbol(struct placement *p);
183 void move_symbol_point(struct placement *p);
184 void move_symbol_segment(struct placement *p);
185
186 struct placement **get_overlapping(struct placement *p);
187 void filter(struct placement **list, bool *pred);
188
189 int flip(int a, int b);
190 double randdouble(void);
191
192 void cleanup(void);
193
194 void copy_individual(struct individual *src, struct individual *dest);
195
196 int max2(int a, int b);
197 int min2(int a, int b);
198 int max4(int a, int b, int c, int d);
199 int min4(int a, int b, int c, int d);
200
201 struct placement dummy_placement;
202
203 int max2(int a, int b)
204 {
205   return (a > b ? a : b);
206 }
207
208 int min2(int a, int b)
209 {
210   return (a < b ? a : b);
211 }
212
213 int max4(int a, int b, int c, int d)
214 {
215   return max2(max2(a, b), max2(c, d));
216 }
217
218 int min4(int a, int b, int c, int d)
219 {
220   return min2(min2(a, b), min2(c, d));
221 }
222
223 void print_label(struct symbol *sym)
224 {
225   switch (sym->type)
226   {
227     case SYMBOLIZER_TEXT: ;
228       struct sym_text *st = (struct sym_text *) sym;
229       printf("%s\n", osm_val_decode(st->text));
230     default:
231       // FIXME
232       ;
233   }
234 }
235
236 void labeller_init(void)
237 {
238   GARY_INIT(requests_point, 0);
239   GARY_INIT(requests_line, 0);
240   GARY_INIT(requests_area, 0);
241   GARY_INIT(buffer_line, 0);
242   GARY_INIT(buffer_linelabel, 0);
243   ep_individuals = ep_new(sizeof(struct individual), 1);
244
245   page_width_int = floor(page_width);
246   page_height_int = floor(page_height);
247
248   num_map_parts_row = (page_width_int + conf_map_part_width) / conf_map_part_width;
249   num_map_parts_col = (page_height_int + conf_map_part_height) / conf_map_part_height;
250   num_map_parts = num_map_parts_row * num_map_parts_col;
251 }
252
253 void make_bitmap(struct variant *v, struct symbol *sym)
254 {
255   switch (sym->type)
256   {
257     case SYMBOLIZER_POINT:
258       make_bitmap_point(v, (struct sym_point *) sym);
259       break;
260     case SYMBOLIZER_ICON:
261       make_bitmap_icon(v, (struct sym_icon *) sym);
262       break;
263     case SYMBOLIZER_TEXT:
264       make_bitmap_label(v, (struct sym_text *) sym);
265       break;
266     default:
267       ASSERT(sym->type != SYMBOLIZER_INVALID);
268   }
269 }
270
271 void make_bitmap_icon(struct variant *v, struct sym_icon *si)
272 {
273   v->width = si->sir.width + 1;
274   v->height = si->sir.height + 1;
275   v->bitmap = malloc(v->width * v->height * sizeof(bool));
276   for (int i=0; i<v->width*v->height; i++) v->bitmap[i] = 1;
277 }
278
279 void make_bitmap_point(struct variant *v, struct sym_point *sp)
280 {
281   v->width = v->height = sp->size + 1;
282   v->bitmap = malloc(v->width * v->height * sizeof(bool));
283   // FIXME: Okay, memset would be much nicer here
284   for (int i=0; i<sp->size*sp->size; i++) v->bitmap[i] = 1;
285 }
286
287 void make_bitmap_label(struct variant *v, struct sym_text *text)
288 {
289   v->width = ceil(text->tw);
290   v->height = ceil(text->th);
291   v->bitmap = malloc(v->width * v->height * sizeof(bool));
292   for (int i=0; i<v->height; i++)
293     for (int j=0; j<v->width; j++)
294     {
295       v->bitmap[i*v->width + j] = 1;
296     }
297 }
298
299 void labeller_add_point(struct symbol *sym, struct osm_object *object, z_index_t zindex)
300 {
301   if (dbg_requests)
302     printf("Adding point\n");
303   if (object->type != OSM_TYPE_NODE)
304   {
305     printf("Warning: Point label requested on non-point object\n");
306     return;
307   }
308
309   struct request_point *r = GARY_PUSH(requests_point);
310
311   r->request.type = REQUEST_POINT;
312   r->request.ind = num_requests++;
313
314   r->sym = sym;
315   r->zindex = zindex;
316
317   r->offset_x = 0;
318   r->offset_y = 0;
319
320   r->num_variants = 1;
321   GARY_INIT(r->request.variants, 0);
322
323   struct variant *v = GARY_PUSH(r->request.variants);
324
325   struct osm_node *n = (struct osm_node *) object; // FIXME: Compiler warning
326   r->x = n->x;
327   r->y = n->y;
328   switch (sym->type)
329   {
330     case SYMBOLIZER_ICON:
331       make_bitmap_icon(v, (struct sym_icon *) sym);
332       r->x = ((struct sym_icon *)sym)->sir.x;
333       r->y = ((struct sym_icon *)sym)->sir.y;
334       break;
335     case SYMBOLIZER_POINT:
336       make_bitmap_point(v, (struct sym_point *) sym);
337       break;
338     case SYMBOLIZER_TEXT: ;
339       struct sym_text *st = (struct sym_text *) sym;
340       struct osm_node *n = (struct osm_node *) object;
341       make_bitmap_label(v, st);
342     default:
343       // FIXME
344       return;
345   }
346
347 //  printf("Inited point to [%.2f; %.2f] on %u\n", r->x, r->y, r->zindex);
348 }
349
350 void labeller_add_line(struct symbol *sym, z_index_t zindex)
351 {
352   if (dbg_requests)
353     printf("Adding line on %u\n", zindex);
354   struct buffer_line *b = GARY_PUSH(buffer_line);
355   b->line = (struct sym_line *) sym;
356   b->zindex = zindex;
357   sym_plan(sym, zindex);
358 }
359
360 void labeller_add_linelabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
361 {
362   if (o->type != OSM_TYPE_WAY)
363   {
364     // FIXME
365     return;
366   }
367
368   if (dbg_requests)
369     printf("[LAB] Labelling way %ju on %u\n", o->id, zindex);
370   struct buffer_linelabel *ll = GARY_PUSH(buffer_linelabel);
371   ll->way = (struct osm_way *) o;
372   ll->label = sym;
373   ll->zindex = zindex;
374 }
375
376 void labeller_add_arealabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
377 {
378   if (dbg_requests)
379     printf("Adding area on %u\n", zindex);
380   struct request_area *r = GARY_PUSH(requests_area);
381
382   r->request.type = REQUEST_AREA;
383   r->request.ind = num_requests++;
384
385   r->o = (struct osm_multipolygon *) o;
386   r->zindex = zindex;
387   r->label = sym;
388
389   osm_obj_center(o, &(r->cx), &(r->cy));
390
391   GARY_INIT(r->request.variants, 0);
392   struct variant *v = GARY_PUSH(r->request.variants);
393   switch (sym->type)
394   {
395     case SYMBOLIZER_ICON:
396       if (dbg_requests)
397         printf("DEBUG: Icon label\n");
398       make_bitmap_icon(v, (struct sym_icon *) sym);
399       break;
400     case SYMBOLIZER_TEXT:
401       if (dbg_requests)
402         printf("DEBUG: Text label\n");
403       make_bitmap_label(v, (struct sym_text *) sym);
404     default:
405       // FIXME
406       ;
407   }
408 }
409
410 void make_graph(void)
411 {
412   hash_init();
413   struct mempool *mp_edges = mp_new(BLOCK_SIZE);
414
415   printf("Extracting nodes, will iterate over %lld ways\n", GARY_SIZE(buffer_line));
416   for (uns i=0; i<GARY_SIZE(buffer_line); i++)
417   {
418     struct osm_way *way = (struct osm_way *) buffer_line[i].line->s.o;
419     struct graph_node *g_prev = NULL;
420     struct osm_node *o_prev = NULL;
421
422     CLIST_FOR_EACH(struct osm_ref *, ref, way->nodes)
423     {
424       // FIXME: Shall osm_object's type be checked here?
425       struct osm_node *o_node = (struct osm_node *) ref->o;
426
427       struct graph_node *g_node = hash_find(ref->o->id);
428       if (!g_node)
429       {
430         g_node = hash_new(ref->o->id);
431         GARY_INIT(g_node->edges, 0);
432         g_node->o = o_node;
433         g_node->id = ref->o->id;
434         g_node->num = num_nodes++;
435       }
436
437       if (! g_prev)
438       {
439         g_prev = g_node;
440         o_prev = o_node;
441         continue;
442       }
443
444       struct graph_edge *e = mp_alloc(mp_edges, sizeof(struct graph_edge)); num_edges_dbg++;
445       e->num = num_edges++;
446       e->id = buffer_line[i].line->s.o->id;
447       e->color = buffer_line[i].line->color;
448       e->length = hypot(abs(o_prev->x - o_node->x), abs(o_prev->y - o_node->y));
449       e->visited = -1;
450       e->prev = NULL;
451       e->next = NULL;
452       e->n1 = g_prev;
453       e->n2 = g_node;
454       e->longline = (uns) -1;
455       e->line = buffer_line[i].line;
456       e->dir = DIR_UNSET;
457       e->label = NULL;
458
459       struct graph_edge **edge = GARY_PUSH(g_prev->edges);
460       *edge = e;
461       edge = GARY_PUSH(g_node->edges);
462       *edge = e;
463
464       g_prev = g_node;
465       o_prev = o_node;
466     }
467   }
468
469   printf("Made graph with %d edges\n", num_edges_dbg);
470 }
471
472 void dump_graph(void)
473 {
474   HASH_FOR_ALL(hash, node)
475   {
476     printf("* Node: (%d) #%ju [%.2f; %.2f]\n", node->num, node->id, node->o->x, node->o->y);
477     for (uns i=0; i<GARY_SIZE(node->edges); i++)
478     {
479       struct graph_edge *e = node->edges[i];
480       printf("\t edge (%d) #%ju to ", e->num, e->id);
481       if (node->edges[i]->n1->id == node->id)
482         printf("(%d) #%ju [%.2f; %.2f]\n", e->n2->num, e->n2->id, e->n2->o->x, e->n2->o->y);
483       else if (node->edges[i]->n2->id == node->id)
484         printf("(%d) #%ju [%.2f; %.2f]\n", e->n1->num, e->n1->id, e->n1->o->x, e->n1->o->y);
485       else
486         printf("BEWARE! BEWARE! BEWARE!\n");
487
488       printf("\t\t");
489       if ((node->edges[i]->label)) printf("Labelled\n");
490       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));
491       printf(" colored %d;", node->edges[i]->color);
492       printf("   length %.2f", node->edges[i]->length);
493       printf("\n");
494     }
495   }
496   HASH_END_FOR;
497 }
498
499 void label_graph(void)
500 {
501   if (dbg_graph)
502     printf("There are %u line labels requested\n", GARY_SIZE(buffer_linelabel));
503   for (uns i=0; i<GARY_SIZE(buffer_linelabel); i++)
504   {
505     if (buffer_linelabel[i].label->type == SYMBOLIZER_TEXT)
506     if (dbg_graph)
507       printf("Labelling nodes of way %s\n", osm_val_decode(((struct sym_text *) buffer_linelabel[i].label)->text));
508     CLIST_FOR_EACH(struct osm_ref *, ref, buffer_linelabel[i].way->nodes)
509     {
510       if (dbg_graph)
511         printf("Looking for node %ju\n", ref->o->id);
512       struct graph_node *n = hash_find(ref->o->id);
513       if (n == NULL)
514       {
515         // FIXME: What shall be done?
516       }
517       else
518       {
519         if (dbg_graph)
520           printf("Searching among %u edges\n", GARY_SIZE(n->edges));
521         for (uns j=0; j<GARY_SIZE(n->edges); j++)
522         {
523           if (n->edges[j]->id == buffer_linelabel[i].way->o.id)
524           {
525             if (dbg_graph)
526               printf("Labelling node %ju\n", n->id);
527             n->edges[j]->label = buffer_linelabel[i].label;
528             n->edges[j]->zindex = buffer_linelabel[i].zindex;
529           }
530         }
531       }
532     }
533   }
534 }
535
536 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir)
537 {
538   if (dbg_bfs)
539     printf("BFS edge called for edge %d (going %d) in direction %d\n", e->num, e->dir, dir);
540   struct graph_edge *candidate = NULL;
541
542   for (uns i=0; i<GARY_SIZE(node->edges); i++)
543   {
544     struct graph_edge *other = node->edges[i];
545     if ((other->longline != (uns) -1) && (other->longline != e->longline)) continue;
546
547     if ((uns) other->visited != e->longline) {
548     if (dbg_bfs)
549       printf("Pushing new edge %d / %ju\n", other->num, other->id);
550     struct graph_edge **e_ptr = GARY_PUSH(bfs_queue);
551     *e_ptr = other;
552     other->visited = e->longline;
553     }
554
555     if (((other->n1->id == node->id) && (other->n2->id == anode->id)) ||
556         ((other->n2->id == node->id) && (other->n1->id == anode->id)))
557         continue;
558
559     if (((other->n1->id == node->id) || (other->n2->id == node->id)) &&
560         (e->label) && (other->label) &&
561         (e->label->type == SYMBOLIZER_TEXT) && (other->label->type == SYMBOLIZER_TEXT) &&
562         (((struct sym_text *) e->label)->text == ((struct sym_text *) other->label)->text))
563     {
564       if (! candidate || (other->length > candidate->length))
565       candidate = other;
566     }
567   }
568
569   if (candidate)
570   {
571     if (dbg_bfs)
572       printf("New line in longline %u\n", e->longline);
573     struct graph_edge *other = candidate;
574       other->longline = e->longline;
575       other->dir = dir;
576       if (((dir == DIR_BWD) && (other->n1->id == node->id)) ||
577           ((dir == DIR_FWD) && (other->n2->id == node->id)))
578       {
579         struct graph_node *swp = other->n2;
580         other->n2 = other->n1;
581         other->n1 = swp;
582       }
583
584       switch (dir)
585       {
586         case DIR_BWD:
587           e->prev = other;
588           other->next = e;
589           longlines[other->longline].first = other;
590           break;
591         case DIR_FWD:
592           e->next = other;
593           other->prev = e;
594           break;
595         default:
596           printf("Oops\n");
597           ASSERT(0);
598       }
599   }
600 }
601
602 void bfs(uns longline)
603 {
604 if (dbg_bfs)
605   printf("BFS called for longline %u\n", longline);
606 if (dbg_bfs)
607   printf("%d longlines are believed to exist, %d exist\n", num_longlines, GARY_SIZE(longlines));
608   for (uns i=0; i<GARY_SIZE(bfs_queue); i++)
609   {
610     struct graph_edge *cur = bfs_queue[i];
611     if (dbg_bfs)
612       printf("Exploring new edge %d; %d remaining\n", cur->num, GARY_SIZE(bfs_queue));
613     //ASSERT(! cur->visited);
614
615     cur->visited = longline;
616
617     if (cur->longline == (uns) -1)
618       continue;
619
620     if (cur->dir == DIR_UNSET)
621     {
622       cur->dir = DIR_CENTER;
623       bfs_edge(cur, cur->n1, cur->n2, DIR_BWD);
624       bfs_edge(cur, cur->n2, cur->n1, DIR_FWD);
625     }
626     else
627     {
628       switch (cur->dir)
629       {
630         case DIR_BWD:
631           bfs_edge(cur, cur->n1, cur->n2, cur->dir);
632           break;
633         case DIR_FWD:
634           bfs_edge(cur, cur->n2, cur->n1, cur->dir);
635           break;
636         default:
637           // FIXME
638           ;
639       }
640     }
641   }
642 }
643
644 void bfs_wrapper(void)
645 {
646   GARY_INIT(bfs_queue, 0);
647   GARY_INIT(longlines, 0);
648
649   HASH_FOR_ALL(hash, node)
650   {
651     for (uns i=0; i<GARY_SIZE(node->edges); i++)
652     {
653       if ((node->edges[i]->label) && (node->edges[i]->longline == (uns) -1))
654       {
655         GARY_PUSH(longlines);
656         longlines[num_longlines].first = node->edges[i];
657         if (dbg_bfs)
658           printf("Running new BFS\n");
659         if (dbg_bfs)
660           printf("Creating longline %u\n", num_longlines);
661         GARY_RESIZE(bfs_queue, 0);
662         struct graph_edge **e = GARY_PUSH(bfs_queue);
663         *e = node->edges[i];
664         node->edges[i]->longline = num_longlines;
665         bfs(node->edges[i]->longline);
666         //dump_longlines();
667         if (dbg_bfs)
668           printf("Joined %d edges\n", dbg_num_hits); dbg_num_hits = 0;
669         if (dbg_bfs)
670           printf("Planned %u edges\n", GARY_SIZE(bfs_queue));
671         num_longlines++;
672       }
673     }
674   }
675   HASH_END_FOR;
676
677   GARY_FREE(bfs_queue);
678 }
679
680 void dump_longlines(void)
681 {
682 printf("*** Longlines dump\n");
683   for (uns i=0; i<GARY_SIZE(longlines); i++)
684   {
685 printf("Longline %u:", i);
686     struct graph_edge *e = longlines[i].first;
687 if ((e->label) && (e->label->type == SYMBOLIZER_TEXT))
688   printf(" labelled %s", osm_val_decode(((struct sym_text *) e->label)->text));
689 printf("\n");
690
691     while (e)
692     {
693       printf("\t#%ju (%d): [%.2f; %.2f] -- [%.2f; %.2f] (dir %d)\n",
694              e->id, e->num, e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->dir);
695
696       e = e->next;
697     }
698   }
699 }
700
701 struct request_line *make_new_line(void)
702 {
703   struct request_line *rl = GARY_PUSH(requests_line);
704   rl->request.ind = num_requests++;
705   rl->request.type = REQUEST_LINE;
706   GARY_INIT(rl->sections, 0);
707   GARY_INIT(rl->request.variants, 0);
708
709   return rl;
710 }
711
712 struct request_section *make_new_section(struct request_line *rl)
713 {
714   struct request_section *rls = GARY_PUSH(rl->sections);
715   rls->request.ind = num_requests++;
716   rls->request.type = REQUEST_SECTION;
717   rls->num_segments = 0;
718   GARY_INIT(rls->segments, 0);
719   GARY_INIT(rls->request.variants, 0);
720
721   return rls;
722 }
723
724 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym)
725 {
726   struct request_segment *rs = GARY_PUSH(rls->segments);
727   rls->num_segments++;
728
729   rs->request.ind = num_requests++;
730   rs->request.type = REQUEST_SEGMENT;
731
732   GARY_INIT(rs->request.variants, 0);
733   struct variant *v = GARY_PUSH(rs->request.variants);
734   make_bitmap(v, sym);
735
736   return rs;
737 }
738
739 void cut_edge(struct graph_edge *e, double dist)
740 {
741   if (dbg_segments)
742     printf("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);
743
744   struct graph_edge *new = malloc(sizeof(struct graph_edge));
745   *new = *e;
746   e->next = new;
747
748   // FIXME? Create new label for new edge, don't only copy pointer?
749
750   struct osm_node *n1 = e->n1->o;
751   struct osm_node *n2 = e->n2->o;
752
753   // FIXME
754   if ((n1->x == n2->x) && (n1->y == n2->y))
755   {
756     printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", n1->x, n1->y, n2->x, n2->y);
757     printf("Won't cut point\n");
758     return;
759   }
760
761   struct osm_node *n11 = malloc(sizeof(struct osm_node));
762   struct graph_node *gn = malloc(sizeof(struct graph_node));
763   gn->o = n11;
764   double vsize = sqrt(pow(n1->x - n2->x, 2) + pow(n1->y - n2->y, 2));
765   n11->x = n1->x + (n2->x - n1->x) / vsize * dist;
766   n11->y = n1->y + (n2->y - n1->y) / vsize * dist;
767
768   e->n2 = new->n1 = gn;
769
770   e->length = hypot(abs(n1->x - n11->x), abs(n1->y - n11->y));
771   new->length = hypot(abs(n11->x - n2->x), abs(n11->y - n2->y));
772   new->visited = 0;
773 }
774
775 void make_segments(void)
776 {
777   for (uns i=0; i<GARY_SIZE(longlines); i++)
778   {
779     // Skip lines which are not labelled
780     if (! (longlines[i].first && longlines[i].first->label))
781       continue;
782
783     struct request_line *request = make_new_line();
784     struct request_section *rls = make_new_section(request);
785     struct request_segment *rs = NULL;
786
787     struct graph_edge *e = longlines[i].first;
788     double cur_length = 0;
789
790     struct sym_text *st = NULL;
791     if (e->label->type == SYMBOLIZER_TEXT)
792     {
793       st = (struct sym_text *) e->label;
794     }
795     else
796     {
797       if (dbg_segments)
798         printf("Warning: Skipping line\n");
799       continue;
800       // FIXME;
801     }
802
803     if (dbg_segments)
804       printf("New longline\n");
805     while (e)
806     {
807       if (e->visited < 0)
808       {
809         printf("BEWARE: Edge cycle\n");
810         break;
811       }
812       e->visited = -1; // FIXME
813
814       if (dbg_segments)
815         printf("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);
816
817       if (st && (e->length < st->tw))
818       {
819         e = e->next;
820         //printf("Warning: Skipping segment\n");
821         continue;
822       }
823
824       if (cur_length + e->length > conf_max_section_length + conf_max_section_overlay)
825       {
826         if (dbg_segments)
827           printf("Edge too long, length is %.2f; %.2f - %.2f = %.2f\n", e->length, conf_max_section_length, cur_length, conf_max_section_length - cur_length);
828         // HACK to prevent cutting to 0 lenght
829         cut_edge(e, max2(conf_max_section_length - cur_length, 2));
830       }
831
832       rs = make_new_segment(rls, e->label);
833       rs->label = malloc(sizeof(struct sym_text));
834       *((struct sym_text *) rs->label) = *((struct sym_text *) e->label);
835
836       rs->x1 = e->n1->o->x;
837       rs->y1 = e->n1->o->y;
838       rs->x2 = e->n2->o->x;
839       rs->y2 = e->n2->o->y;
840
841       rs->slope = (rs->y2 - rs->y1) / (rs->x2 - rs->x1);
842       rs->zindex = e->zindex;
843
844       cur_length += e->length;
845       if (cur_length > conf_max_section_length)
846       {
847         if (dbg_segments)
848           printf("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);
849
850         rls = make_new_section(request);
851         cur_length = 0;
852       }
853
854       e = e->next;
855     }
856
857     if (request->sections[0].num_segments == 0)
858     {
859       // FIXME
860       printf("WARNING: 0 segment section\n");
861       GARY_POP(requests_line);
862       num_requests -= 2;
863     }
864   }
865 }
866
867 void dump_linelabel_requests(void)
868 {
869   for (uns i=0; i<GARY_SIZE(requests_line); i++)
870   {
871     if (requests_line[i].sections[0].num_segments == 0)
872     {
873       printf("HEY!\n");
874       continue;
875     }
876     printf("Request for linelabel, %d sections\n", GARY_SIZE(requests_line[i].sections));
877     print_label(requests_line[i].sections[0].segments[0].label);
878     for (uns j=0; j<GARY_SIZE(requests_line[i].sections); j++)
879     {
880       printf("%d section, %d segments\n", j, GARY_SIZE(requests_line[i].sections[j].segments));
881       for (uns k=0; k<GARY_SIZE(requests_line[i].sections[j].segments); k++)
882       {
883         struct request_segment *rs = &requests_line[i].sections[j].segments[k];
884         printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", rs->x1, rs->y1, rs->x2, rs->y2);
885       }
886     }
887     printf("\n");
888   }
889 }
890
891 void dump_bitmaps(struct individual *individual)
892 {
893   bool *bitmap = malloc(page_width_int * page_height_int * sizeof(bool));
894   printf("Bitmap size is %d\n", page_width_int * page_height_int);
895   for (int i=0; i<page_height_int; i++)
896     for (int j=0; j<page_width_int; j++)
897       bitmap[i*page_width_int + j] = 0;
898
899   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
900   {
901     if (individual->placements[i].variant_used == -1) continue;
902
903     struct placement *p = &(individual->placements[i]);
904     struct variant *v = NULL;
905
906     switch (p->request->type)
907     {
908       case REQUEST_SEGMENT: ;
909       case REQUEST_POINT: ;
910       case REQUEST_AREA: ;
911         v = &(p->request->variants[p->variant_used]);
912         break;
913       default:
914         ASSERT(p->request->type != REQUEST_INVALID);
915         continue;
916     }
917
918     for (int row = max2(p->y, 0); row < min2(p->y + v->height, page_height_int); row++)
919     {
920       for (int col = max2(p->x, 0); col < min2(p->x + v->width, page_width_int); col++)
921       {
922         bitmap[row * page_width_int + col] = 1;
923       }
924     }
925   }
926
927   errno = 0;
928   FILE *fd_dump = fopen("dump.pbm", "w");
929   fprintf(fd_dump, "P1\n");
930   fprintf(fd_dump, "%d %d\n", page_width_int, page_height_int);
931   for (int i=0; i<page_height_int; i++)
932   {
933     for (int j=0; j<page_width_int; j++)
934     {
935       fprintf(fd_dump, "%d", bitmap[(int) (i*page_width_int + j)] ? 1 : 0);
936     }
937     fprintf(fd_dump, "\n");
938   }
939   fclose(fd_dump);
940 }
941
942 void dump_individual(struct individual *individual)
943 {
944 printf("*** Dumping INDIVIDUAL ***\n");
945 printf("(There are %d requests)\n", num_requests);
946   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
947   {
948     struct placement *p = &(individual->placements[i]);
949
950     switch (p->request->type)
951     {
952       case REQUEST_POINT:
953         printf("Point at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_point *) p->request)->zindex);
954         break;
955       case REQUEST_LINE: ;
956         struct request_line *rl = (struct request_line *) p->request;
957         printf("Line: ");
958         print_label(rl->sections[0].segments[0].label);
959         break;
960       case REQUEST_SECTION: ;
961         printf("*");
962         break;
963       case REQUEST_SEGMENT: ;
964         if (p->variant_used >= 0)
965           printf("Segment placed at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_segment *) p->request)->zindex);
966         else
967           printf("Segment not placed\n");
968         break;
969       case REQUEST_AREA: ;
970         struct request_area *ra = (struct request_area *) p->request;
971         printf("Area label ");
972         print_label(ra->label);
973         printf(" at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_area *) p->request)->zindex);
974         break;
975       default:
976         printf("Testing request type (dump_individual)\n");
977         ASSERT(p->request->type != 0);
978     }
979   }
980   printf("\nTotal penalty: %d\n", individual->penalty);
981 }
982
983 void plan_individual(struct individual *individual)
984 {
985   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
986   {
987     struct symbol *s = NULL;
988     z_index_t zindex = 0;
989     if (individual->placements[i].variant_used < 0) continue;
990     switch (individual->placements[i].request->type)
991     {
992       case REQUEST_POINT: ;
993         struct request_point *rp = (struct request_point *) individual->placements[i].request;
994         s = rp->sym;
995         zindex = rp->zindex;
996         break;
997       case REQUEST_SEGMENT: ;
998         struct request_segment *rs = (struct request_segment *) individual->placements[i].request;
999         s = rs->label;
1000         zindex = rs->zindex;
1001         break;
1002       case REQUEST_LINE: ;
1003         break;
1004       case REQUEST_AREA: ;
1005         struct request_area *ra = (struct request_area *) individual->placements[i].request;
1006         s = ra->label;
1007         zindex = ra->zindex;
1008         break;
1009       default:
1010         ASSERT(individual->placements[i].request != REQUEST_INVALID);
1011         continue;
1012     }
1013
1014 if (dbg_plan)
1015   printf("Will plan symbol at [%.2f; %.2f] on %u\n", individual->placements[i].x, individual->placements[i].y, zindex);
1016
1017     if (s) switch (s->type)
1018     {
1019       case SYMBOLIZER_POINT: ;
1020         struct sym_point *sp = (struct sym_point *) s;
1021         sp->x = individual->placements[i].x;
1022         sp->y = individual->placements[i].y;
1023         sym_plan((struct symbol *) sp, zindex);
1024         break;
1025       case SYMBOLIZER_ICON: ;
1026         struct sym_icon *si = (struct sym_icon *) s;
1027         si->sir.x = individual->placements[i].x;
1028         si->sir.y = individual->placements[i].y;
1029         sym_plan((struct symbol *) si, zindex);
1030         break;
1031       case SYMBOLIZER_TEXT: ;
1032         struct sym_text *st = (struct sym_text *) s;
1033         st->x = individual->placements[i].x;
1034         st->y = individual->placements[i].y;
1035         st->next_duplicate = NULL;
1036         if (dbg_plan) printf("Planning text %s at [%.2f; %.2f] on %u, with rotation %.2f\n", osm_val_decode(st->text), st->x, st->y, zindex, st->rotate);
1037         sym_plan((struct symbol *) st, zindex);
1038         break;
1039       default:
1040         ASSERT(s->type != SYMBOLIZER_INVALID);
1041     }
1042   }
1043 }
1044
1045 void dump_penalties(struct individual **population)
1046 {
1047   for (int i=0; i<conf_pop_size; i++)
1048   {
1049     printf("Individual %d has penalty %d\n", i, population[i]->penalty);
1050   }
1051 }
1052
1053 void labeller_label(void)
1054 {
1055   make_graph();
1056   label_graph();
1057   bfs_wrapper();
1058   make_segments();
1059
1060 printf("Having %u point requests, %u line requests and %u area requests\n", GARY_SIZE(requests_point), GARY_SIZE(requests_line), GARY_SIZE(requests_area));
1061
1062   GARY_INIT(population1, conf_pop_size);
1063   GARY_INIT(population2, conf_pop_size);
1064   make_population();
1065   rank_population();
1066   qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1067
1068   if (dbg_evolution)
1069     dump_penalties(population1);
1070
1071   printf("Dealing with %d requests\n", num_requests);
1072
1073   mutate_pop_size = conf_mutate_pop_size * conf_pop_size;
1074   mutate_rbest_size = conf_mutate_rbest * conf_pop_size;
1075   if (dbg_evolution)
1076   {
1077     printf("Mutation parameters:\n");
1078     printf(" %d individuals are created\n", mutate_pop_size);
1079     printf(" %d best individuals in old population are considered\n", mutate_rbest_size);
1080   }
1081
1082   elite_pop_size = conf_elite_pop_size * conf_pop_size;
1083   if (dbg_evolution)
1084   {
1085     printf("Elitism parameters:\n");
1086     printf(" %d best individuals are copied\n", elite_pop_size);
1087   }
1088
1089   while (! shall_terminate())
1090   {
1091     iteration++;
1092     if (dbg_evolution)
1093       printf("*** Iteration %d ***\n", iteration);
1094
1095     mutate();
1096     elite();
1097
1098     struct individual **swp = population1;
1099     population1 = population2;
1100     population2 = swp;
1101     pop2_ind = 0;
1102
1103     if (dbg_evolution)
1104       dump_penalties(population1);
1105
1106     rank_population();
1107     qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1108
1109     if (dbg_evolution)
1110       dump_penalties(population1);
1111   }
1112
1113   plan_individual(population1[0]);
1114
1115   labeller_cleanup();
1116
1117   return;
1118 }
1119
1120 void labeller_cleanup(void)
1121 {
1122 }
1123
1124 void make_population(void)
1125 {
1126   for (int i=0; i<conf_pop_size; i++)
1127   {
1128     num_placements = 0; // FIXME: This IS a terrible HACK
1129     struct individual *i2 = ep_alloc(ep_individuals);
1130     init_individual(i2);
1131     population2[i] = i2;
1132
1133     if (dbg_init)
1134       printf("Making individual %d\n", i);
1135     struct individual *individual = ep_alloc(ep_individuals); init_individual(individual);
1136     population1[i] = individual;
1137
1138     int p = 0;
1139     for (uns j=0; j<GARY_SIZE(requests_point); j++)
1140     {
1141       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_point[j]);
1142     }
1143
1144     for (uns j=0; j<GARY_SIZE(requests_line); j++)
1145     {
1146       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j]);
1147
1148       for (uns k=0; k<GARY_SIZE(requests_line[j].sections); k++)
1149       {
1150         init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k]);
1151
1152         for (uns l=0; l<GARY_SIZE(requests_line[j].sections[k].segments); l++)
1153         {
1154           init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k].segments[l]);
1155         }
1156       }
1157     }
1158
1159     for (uns j=0; j<GARY_SIZE(requests_area); j++)
1160     {
1161       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_area[j]);
1162     }
1163
1164     hide_segment_labels(individual);
1165
1166     ASSERT(p == num_requests);
1167   }
1168 }
1169
1170 bool shall_terminate(void)
1171 {
1172   switch (conf_term_cond)
1173   {
1174     case TERM_COND_PENALTY:
1175       return (population1[0]->penalty < conf_penalty_bound);
1176     case TERM_COND_STAGNATION:
1177       return (abs(old_best - population1[0]->penalty) < conf_stagnation_bound);
1178     case TERM_COND_ITERATIONS:
1179       return (iteration >= conf_iteration_limit);
1180     default:
1181       // FIXME: Warn the user that no condition is set
1182       return 1;
1183   }
1184 }
1185
1186 void breed(void)
1187 {
1188   int acc = 0;
1189   int i=0;
1190   printf("%.2f\n", ((double) conf_breed_pop_size_perc/100));
1191   int conf_breed_pop_size = ((double) conf_breed_pop_size_perc/100) * conf_pop_size;
1192   struct individual **breed_buffer;
1193   while (i < conf_breed_pop_size)
1194   {
1195   printf("%d < %d, breeding\n", i, conf_breed_pop_size);
1196     int parent1 = randint(1, conf_breed_pop_size);
1197     int parent2 = randint(1, conf_breed_pop_size);
1198     printf("Will breed %d and %d, chosen of %d best of %d population (intended to be %d)\n", parent1, parent2, conf_breed_pop_size, GARY_SIZE(population1), conf_pop_size);
1199     breed_buffer = perform_crossover(population1[parent1], population1[parent2]);
1200     population2[pop2_ind++] = breed_buffer[0];
1201     population2[pop2_ind++] = breed_buffer[1];
1202     free(breed_buffer);
1203     i++;
1204   }
1205
1206   acc += conf_breed_rbest_perc;
1207
1208   return; // FIXME: DEBUG HACK
1209
1210   int remaining = (1 - acc) * (conf_pop_size * conf_breed_perc);
1211   int step = remaining / conf_pop_size;
1212   for (; i<conf_pop_size; i += 2)
1213   {
1214     printf("Asking for %d and %d of %d\n", i*step, i*(step+1), conf_pop_size);
1215     breed_buffer = perform_crossover(population1[i*step], population1[i*step+1]);
1216     population2[pop2_ind++] = breed_buffer[0];
1217     population2[pop2_ind++] = breed_buffer[1];
1218   }
1219
1220   // FIXME: Could there be one missing individual?
1221 }
1222
1223 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2)
1224 {
1225   struct individual **buffer = malloc(2*sizeof(struct individual));
1226   struct individual *child1 = ep_alloc(ep_individuals); init_individual(child1);
1227   struct individual *child2 = ep_alloc(ep_individuals); init_individual(child2);
1228
1229   printf("Performing crossover\n");
1230
1231   for (uns i=0; i<GARY_SIZE(parent1->placements); i++)
1232   {
1233     printf("%dth placement out of %d\n", i, num_requests);
1234     if (! parent1->placements[i].processed)
1235     {
1236       struct placement **clos_symbols = get_closure(&(parent1->placements[i]), parent1, parent2);
1237       int x = randint(1, 2);
1238
1239       if (x == 1)
1240       {
1241         copy_symbols(clos_symbols, parent1, child1);
1242         copy_symbols(clos_symbols, parent2, child2);
1243       }
1244       else
1245       {
1246         copy_symbols(clos_symbols, parent2, child1);
1247         copy_symbols(clos_symbols, parent1, child2);
1248       }
1249       printf("Symbols copied; %lld\n", GARY_SIZE(clos_symbols));
1250       GARY_FREE(clos_symbols);
1251     }
1252
1253     if (conf_mutate_children)
1254     {
1255       if (randint(1, 1000) < conf_mutate_children_prob * 1000) perform_mutation(child1);
1256       if (randint(1, 1000) < conf_mutate_children_prob * 1000) perform_mutation(child2);
1257     }
1258   }
1259
1260   buffer[0] = child1;
1261   buffer[1] = child2;
1262   return buffer;
1263 }
1264
1265 void mutate(void)
1266 {
1267   for (int i=0; i < mutate_pop_size; i++)
1268   {
1269     if (dbg_mutation)
1270       printf("%d\n", i);
1271     int ind = randint(1, mutate_rbest_size);
1272     if (dbg_mutation)
1273       printf("Mutating %d-th individual of original population\n", ind);
1274     copy_individual(population1[ind], population2[pop2_ind]);
1275     if (dbg_mutation)
1276       printf("Individual %d in pop2 inited from individual %d in pop1\n", pop2_ind, ind);
1277     perform_mutation(population2[pop2_ind]);
1278     pop2_ind++;
1279   }
1280 }
1281
1282 void perform_mutation(struct individual *individual)
1283 {
1284   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1285   {
1286     double x = randdouble();
1287     double acc = 0;
1288
1289     if (x <= acc + conf_mutate_move_bound)
1290     {
1291       if (dbg_mutation)
1292         printf("Mutation: Moving symbol in placement %u\n", i);
1293       move_symbol(&(individual->placements[i]));
1294       continue;
1295     }
1296     acc += conf_mutate_move_bound;
1297
1298     if (x <= acc + conf_mutate_regen_bound)
1299     {
1300       gen_coords(&(individual->placements[i]));
1301       continue;
1302     }
1303     acc += conf_mutate_regen_bound;
1304
1305     if (x <= acc + conf_mutate_chvar_bound)
1306     {
1307       struct placement *p = &(individual->placements[i]);
1308       switch (p->request->type)
1309       {
1310         case REQUEST_POINT:
1311         case REQUEST_SEGMENT:
1312         case REQUEST_AREA:
1313           // Does nothing when there are 0 variants... does it mind?
1314           p->variant_used = randint(0, GARY_SIZE(p->request->variants) - 1);
1315           break;
1316         case REQUEST_SECTION:
1317           p->variant_used = randint(0, GARY_SIZE(((struct request_section *) p->request)->segments)-1);
1318           break;
1319         default:
1320           ;
1321       }
1322     }
1323   }
1324 }
1325
1326 void elite(void)
1327 {
1328   for (int i=0; i<elite_pop_size; i++)
1329   {
1330     copy_individual(population1[i], population2[pop2_ind++]);
1331   }
1332 }
1333
1334 int overlaps(struct placement *p1, struct placement *p2)
1335 {
1336   if (p1->request->type != REQUEST_POINT &&
1337       p1->request->type != REQUEST_SEGMENT &&
1338       p1->request->type != REQUEST_AREA)
1339     return 0;
1340
1341   if (p2->request->type != REQUEST_POINT &&
1342       p2->request->type != REQUEST_SEGMENT &&
1343       p2->request->type != REQUEST_AREA)
1344     return 0;
1345
1346   if (p1->variant_used == -1 || p2->variant_used == -1)
1347     return 0;
1348
1349   struct variant *v1, *v2;
1350
1351   v1 = &(p1->request->variants[p1->variant_used]);
1352   v2 = &(p2->request->variants[p2->variant_used]);
1353
1354   int p1x = p1->x; int p1y = p1->y;
1355   int p2x = p2->x; int p2y = p2->y;
1356
1357   int overlap = 0;
1358   for (int y=max2(0, max2(p1y, p2y)); y<min2(page_height_int, min2(p1y+v1->height, p2y+v2->height)); y++)
1359     for (int x=max2(0, max2(p1x, p2x)); x<min2(page_width_int, min2(p1x+v1->width, p2x+v2->width)); x++)
1360     {
1361       if (v1->bitmap[(y-p1y)*v1->width + (x-p1x)] &&
1362           v2->bitmap[(y-p2y)*v2->width + (x-p2x)])
1363         overlap++;
1364     }
1365
1366   return overlap;
1367 }
1368
1369 int get_overlap(struct placement *p)
1370 {
1371   struct map_part **parts = get_map_parts(p);
1372   if (! parts)
1373   {
1374     if (dbg_overlaps)
1375       printf("Placement of request %d seems not to be placed\n", p->request->ind);
1376     return 0;
1377   }
1378
1379   struct placement **others;
1380   bool *planned;
1381
1382   GARY_INIT_ZERO(planned, num_requests);
1383   planned[p->request->ind] = 1;
1384   GARY_INIT(others, 0);
1385
1386   for (uns i=0; i<GARY_SIZE(parts); i++)
1387   {
1388     struct map_placement *mp = parts[i]->placement->next;
1389     while (mp)
1390     {
1391       if (! planned[mp->placement->request->ind])
1392       {
1393         struct placement **p = GARY_PUSH(others);
1394         *p = mp->placement;
1395         planned[mp->placement->request->ind] = true;
1396       }
1397       mp = mp->next;
1398     }
1399   }
1400
1401   int overlap = 0;
1402   for (uns i=0; i<GARY_SIZE(others); i++)
1403   {
1404     overlap += overlaps(p, others[i]);
1405   }
1406
1407   GARY_FREE(planned);
1408   GARY_FREE(parts);
1409   GARY_FREE(others);
1410
1411   return overlap;
1412 }
1413
1414 int individual_overlap(struct individual *individual)
1415 {
1416   int overlap = 0;
1417
1418   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1419   {
1420     overlap += get_overlap(&individual->placements[i]);
1421   }
1422
1423   return overlap;
1424 }
1425
1426 int cmp_individual(const void *a, const void *b)
1427 {
1428   struct individual **ia = (struct individual **) a;
1429   struct individual **ib = (struct individual **) b;
1430
1431   return (*ia)->penalty - (*ib)->penalty;
1432 }
1433
1434 void rank_population(void)
1435 {
1436   int penalty;
1437
1438   for (int i=0; i<conf_pop_size; i++)
1439   {
1440     if (dbg_rank)
1441       printf("Individual %d\n", i);
1442     population1[i]->penalty = 0;
1443
1444     penalty = individual_overlap(population1[i]);
1445     if (dbg_rank)
1446       printf("Increasing penalty by %d for overlap\n", penalty);
1447     population1[i]->penalty += penalty;
1448   }
1449 }
1450
1451 struct map_part **get_map_parts(struct placement *p)
1452 {
1453   if (p->variant_used < 0) return NULL;
1454
1455   struct map_part **buffer;
1456   GARY_INIT(buffer, 0);
1457
1458   if (dbg_map_parts)
1459     printf("Looking for map parts containing placement of request %d, placed at [%.2f; %.2f]\n", p->request->ind, p->x, p->y);
1460
1461   struct variant v;
1462   switch (p->request->type)
1463   {
1464     case REQUEST_POINT:
1465     case REQUEST_SEGMENT:
1466     case REQUEST_AREA:
1467       v = p->request->variants[p->variant_used];
1468       break;
1469     default:
1470       return NULL;
1471   }
1472
1473   int x_min = max2(0, p->x) / conf_map_part_width;
1474   int x_max = min2(page_width_int, (p->x + v.width + conf_map_part_width - 1)) / conf_map_part_width;
1475   int y_min = max2(0, p->y) / conf_map_part_height;
1476   int y_max = min2(page_height_int, (p->y + v.height + conf_map_part_height - 1)) / conf_map_part_height;
1477
1478   if (dbg_map_parts)
1479     printf("Cells between [%d; %d] and [%d; %d] generated\n", x_min, y_min, x_max, y_max);
1480
1481   for (int y=y_min; y<=y_max; y++)
1482     for (int x=x_min; x<=x_max; x++)
1483     {
1484       struct map_part **m = GARY_PUSH(buffer);
1485       if (dbg_map_parts)
1486         printf("Asking for %d of %u\n", y * num_map_parts_row + x, GARY_SIZE(p->individual->map));
1487       *m = p->individual->map[y * num_map_parts_row + x];
1488     }
1489
1490   return buffer;
1491 }
1492
1493 void update_map_parts(struct placement *p)
1494 {
1495   struct placement_link *ml = p->map_links;
1496   while (ml)
1497   {
1498     struct map_placement *mp = ml->mp;
1499
1500     mp->prev->next = mp->next;
1501     if (mp->next)
1502       mp->next->prev = mp->prev;
1503     free(mp);
1504
1505     struct placement_link *tmp = ml;
1506     ml = ml->next;
1507     free(tmp);
1508   }
1509   p->map_links = NULL;
1510
1511   struct map_part **parts = get_map_parts(p);
1512   if (parts == NULL) return;
1513
1514   for (uns i=0; i<GARY_SIZE(parts); i++)
1515   {
1516     struct map_placement *mp = malloc(sizeof(struct map_placement));
1517     mp->placement = p;
1518
1519     mp->next = parts[i]->placement->next;
1520     mp->prev = parts[i]->placement;
1521     parts[i]->placement->next = mp;
1522     if (mp->next) mp->next->prev = mp;
1523
1524     struct placement_link *ml = malloc(sizeof(struct placement_link));
1525     ml->mp = mp;
1526     ml->next = p->map_links;
1527     p->map_links = ml;
1528   }
1529
1530   GARY_FREE(parts);
1531 }
1532
1533 void gen_coords(struct placement *p)
1534 {
1535   switch(p->request->type)
1536   {
1537     case REQUEST_POINT:
1538       gen_coords_point(p);
1539       break;
1540     case REQUEST_AREA:
1541       gen_coords_area(p);
1542       break;
1543     case REQUEST_SEGMENT:
1544       gen_coords_segment(p);
1545       break;
1546     case REQUEST_LINE:
1547       if (dbg_movement)
1548         printf("Not yet implemented\n");
1549       break;
1550     default:
1551       if (dbg_movement)
1552         printf("Testing request type\n");
1553       ASSERT(p->request->type != REQUEST_INVALID);
1554   }
1555
1556   update_map_parts(p);
1557 }
1558
1559 double gen_movement(void)
1560 {
1561   double m = (random() % 1000000) / 10000;
1562   m = pow(m, 1.0/3) * flip(1, -1);
1563   if (dbg_movement)
1564     printf("Movement %.2f\n", m);
1565   return m;
1566 }
1567
1568 double gen_movement_uniform(void)
1569 {
1570   return (move_max - move_min) * randdouble() * flip(1, -1);
1571 }
1572
1573 void gen_coords_point(struct placement *p)
1574 {
1575   p->x = p->x + gen_movement();
1576 }
1577
1578 void gen_coords_segment(struct placement *p)
1579 {
1580   struct request_segment *rs = (struct request_segment *) p->request;
1581   int a = flip(1, 2);
1582   p->x = (a == 1 ? rs->x1 : rs->x2);
1583   p->y = (a == 1 ? rs->y1 : rs->y2);
1584 }
1585
1586 void gen_coords_area(struct placement *p)
1587 {
1588   struct request_area *ra = (struct request_area *) p->request;
1589
1590   p->x = p->x + gen_movement();
1591   p->y = p->y + gen_movement();
1592
1593   if (dbg_movement)
1594     printf("Moved label to [%.2f; %.2f] from [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1595 }
1596
1597 struct map_part **get_parts(struct placement *symbol, struct individual *individual)
1598 {
1599   struct map_part **buffer;
1600   GARY_INIT(buffer, 0);
1601   int x_min = symbol->x / conf_part_size;
1602   int x_max = (symbol->x /*+ symbol->bitmap->width*/ + conf_part_size - 1) / conf_part_size;
1603   int y_min = symbol->y / conf_part_size;
1604   int y_max = (symbol->y /*+ symbol->bitmap->height*/ + conf_part_size - 1) / conf_part_size;
1605
1606   for (int x=x_min; x < x_max; x++)
1607     for (int y=y_min; y < y_max; y++)
1608     {
1609       struct map_part *m = GARY_PUSH(buffer);
1610       *m = individual->map[x][y];
1611     }
1612
1613   return buffer;
1614 }
1615
1616 int randint(int min, int max)
1617 {
1618   if (min == max) return min;
1619   int r = random();
1620   //printf("Returning %d + (%d %% (%d - %d)) = %d + %d %% %d = %d + %d = %d\n", min, r, max, min, min, r, max-min, min, r%(max-min), min+(r%(max-min)));
1621   return min + (r % (max - min));
1622   return (r * (max - min));
1623 }
1624
1625 struct placement **get_closure(struct placement *placement, struct individual *parent1, struct individual *parent2 UNUSED)
1626 {
1627   printf("Getting closure\n");
1628   struct placement **closure;
1629   GARY_INIT(closure, 0);
1630   bool *chosen = malloc(GARY_SIZE(parent1->placements) * sizeof(bool));
1631   chosen[placement->request->ind] = 1;
1632
1633   struct placement **p = GARY_PUSH(closure); *p = placement;
1634
1635   uns first = 0;
1636   while (first < GARY_SIZE(closure))
1637   {
1638     printf("Iterating, first is %d\n", first);
1639     struct placement **overlapping = get_overlapping(placement);
1640     filter(overlapping, chosen);
1641     for (uns j=0; j<GARY_SIZE(overlapping); j++)
1642     {
1643       p = GARY_PUSH(closure); *p = overlapping[j];
1644       chosen[overlapping[j]->request->ind] = 1;
1645     }
1646     GARY_FREE(overlapping);
1647     first++;
1648   }
1649
1650   return closure;
1651 }
1652
1653 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child)
1654 {
1655   //printf("%d\n", child->penalty);
1656   //printf("Closure size: %lld\n", GARY_SIZE(closure));
1657   for (uns i=0; i<GARY_SIZE(closure); i++)
1658   {
1659     int ind = closure[i]->request->ind;
1660     child->placements[ind] = parent->placements[ind];
1661     child->placements[ind].processed = 0;
1662   }
1663 }
1664
1665 void move_symbol(struct placement *p)
1666 {
1667   switch (p->request->type)
1668   {
1669     case REQUEST_POINT:
1670     case REQUEST_AREA:
1671       move_symbol_point(p);
1672       break;
1673     case REQUEST_SEGMENT:
1674       move_symbol_segment(p);
1675       break;
1676     default:
1677       ASSERT(p->request->type != REQUEST_INVALID);
1678   }
1679 }
1680
1681 void move_symbol_point(struct placement *p)
1682 {
1683   p->x += gen_movement_uniform();
1684   p->y += gen_movement_uniform();
1685 }
1686
1687 void move_symbol_segment(struct placement *p)
1688 {
1689   double m = gen_movement_uniform();
1690   // CHECK ME
1691   p->x += m;
1692   p->y += m * ((struct request_segment *) p->request)->slope;
1693 }
1694
1695 void hide_segment_labels(struct individual *individual)
1696 {
1697   // BEWARE: This fully depends on current genetic encoding
1698
1699   int used = -1, num = -1;
1700   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1701   {
1702     switch (individual->placements[i].request->type)
1703     {
1704       case REQUEST_SECTION:
1705         used = individual->placements[i].variant_used;
1706         num = 0;
1707         break;
1708       case REQUEST_SEGMENT:
1709         if (num == used)
1710           individual->placements[i].variant_used = 0;
1711         else
1712           individual->placements[i].variant_used = -1;
1713         num++;
1714         break;
1715       default:
1716         ;
1717     }
1718   }
1719 }
1720
1721 void init_placement(struct placement *p, struct individual *individual, struct request *r)
1722 {
1723   // FIXME
1724   p->ind = num_placements++;
1725   p->request = r;
1726   p->processed = 0;
1727   p->x = p->y = 0; // To prevent valgrind from complaining
1728   p->variant_used = 0;
1729   p->map_links = NULL;
1730   p->individual = individual;
1731   switch (r->type)
1732   {
1733     case REQUEST_POINT: ;
1734       struct request_point *rp = (struct request_point *) r;
1735       p->x = rp->x;
1736       p->y = rp->y;
1737       break;
1738     case REQUEST_LINE: ;
1739       break;
1740     case REQUEST_SECTION: ;
1741       struct request_section *rls = (struct request_section *) r;
1742       p->variant_used = randint(0, rls->num_segments);
1743       break;
1744     case REQUEST_SEGMENT: ;
1745       struct request_segment *rs = (struct request_segment *) r;
1746       p->x = rs->x2;
1747       p->y = rs->y2;
1748       break;
1749     case REQUEST_AREA: ;
1750       struct request_area *ra = (struct request_area *) r;
1751       p->x = ra->cx;
1752       p->y = ra->cy;
1753       p->variant_used = 0;
1754       break;
1755     default:
1756       ASSERT(p->request->type != REQUEST_INVALID);
1757       printf("Valid request: %d\n", p->request->type);
1758   }
1759
1760   gen_coords(p);
1761   if (dbg_init)
1762     printf("Inited placement to [%.2f; %.2f]\n", p->x, p->y);
1763 }
1764
1765 void init_individual(struct individual *i)
1766 {
1767 //printf("Initing individual\n");
1768   GARY_INIT(i->placements, num_requests);
1769   GARY_INIT(i->map, 0);
1770   for (uns j=0; j<num_map_parts; j++)
1771   {
1772     struct map_part *part = GARY_PUSH(i->map);
1773     GARY_INIT(part->placement, 0);
1774     struct map_placement *mp = GARY_PUSH(part->placement);
1775     mp->placement = &dummy_placement;
1776     mp->next = mp->prev = NULL;
1777   }
1778   i->penalty = 0; // FIXME
1779
1780   if (dbg_init)
1781     printf("Individual inited, has %u map parts\n", GARY_SIZE(i->map));
1782 }
1783
1784 struct placement **get_overlapping(struct placement *p UNUSED)
1785 {
1786   struct placement **buffer;
1787   GARY_INIT(buffer, 0);
1788   return buffer;
1789 }
1790
1791 void filter(struct placement **list UNUSED, bool *pred UNUSED)
1792 {
1793   // FIXME
1794 }
1795
1796 int flip(int a, int b)
1797 {
1798   return (random() % 2 ? a : b);
1799 }
1800
1801 double randdouble(void)
1802 {
1803   return ((double) rand() / (double) RAND_MAX);
1804 }
1805
1806 void cleanup(void)
1807 {
1808   hash_cleanup();
1809   GARY_FREE(requests_point);
1810   GARY_FREE(requests_line);
1811   GARY_FREE(requests_area);
1812 }
1813
1814 void copy_individual(struct individual *src, struct individual *dest)
1815 {
1816   dest->penalty = src->penalty;
1817   GARY_INIT(dest->placements, GARY_SIZE(src->placements));
1818   for (uns i=0; i<GARY_SIZE(src->placements); i++)
1819   {
1820     dest->placements[i] = src->placements[i];
1821     dest->placements[i].map_links = NULL;
1822   }
1823   for (uns j=0; j<num_map_parts; j++)
1824   {
1825     struct map_part *part = GARY_PUSH(dest->map);
1826     GARY_INIT(part->placement, 0);
1827     struct map_placement *mp = GARY_PUSH(part->placement);
1828     mp->placement = &dummy_placement;
1829     mp->next = mp->prev = NULL;
1830   }
1831 }